content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
namespace EasyXML
{
partial class Ribbon1 : Microsoft.Office.Tools.Ribbon.RibbonBase
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
public Ribbon1()
: base(Globals.Factory.GetRibbonFactory())
{
InitializeComponent();
}
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region 组件设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Ribbon1));
this.tab1 = this.Factory.CreateRibbonTab();
this.group1 = this.Factory.CreateRibbonGroup();
this.button1 = this.Factory.CreateRibbonButton();
this.button2 = this.Factory.CreateRibbonButton();
this.checkBox1 = this.Factory.CreateRibbonCheckBox();
this.checkBox2 = this.Factory.CreateRibbonCheckBox();
this.checkBox3 = this.Factory.CreateRibbonCheckBox();
this.tab1.SuspendLayout();
this.group1.SuspendLayout();
this.SuspendLayout();
//
// tab1
//
this.tab1.Groups.Add(this.group1);
this.tab1.Label = "EasyXML";
this.tab1.Name = "tab1";
//
// group1
//
this.group1.Items.Add(this.button1);
this.group1.Items.Add(this.button2);
this.group1.Items.Add(this.checkBox1);
this.group1.Items.Add(this.checkBox2);
this.group1.Items.Add(this.checkBox3);
this.group1.Name = "group1";
//
// button1
//
this.button1.Image = ((System.Drawing.Image)(resources.GetObject("button1.Image")));
this.button1.Label = "导入XML";
this.button1.Name = "button1";
this.button1.ShowImage = true;
this.button1.Click += new Microsoft.Office.Tools.Ribbon.RibbonControlEventHandler(this.button1_Click);
//
// button2
//
this.button2.Image = ((System.Drawing.Image)(resources.GetObject("button2.Image")));
this.button2.Label = "导出XML";
this.button2.Name = "button2";
this.button2.ShowImage = true;
this.button2.Click += new Microsoft.Office.Tools.Ribbon.RibbonControlEventHandler(this.button2_Click);
//
// checkBox1
//
this.checkBox1.Label = "禁止多开";
this.checkBox1.Name = "checkBox1";
this.checkBox1.Click += new Microsoft.Office.Tools.Ribbon.RibbonControlEventHandler(this.checkBox1_Click);
//
// checkBox2
//
this.checkBox2.Label = "检测外部更改";
this.checkBox2.Name = "checkBox2";
this.checkBox2.Click += new Microsoft.Office.Tools.Ribbon.RibbonControlEventHandler(this.checkBox2_Click);
//
// checkBox3
//
this.checkBox3.Label = "导出自动关闭";
this.checkBox3.Name = "checkBox3";
this.checkBox3.Click += new Microsoft.Office.Tools.Ribbon.RibbonControlEventHandler(this.checkBox3_Click);
//
// Ribbon1
//
this.Name = "Ribbon1";
this.RibbonType = "Microsoft.Excel.Workbook";
this.Tabs.Add(this.tab1);
this.Load += new Microsoft.Office.Tools.Ribbon.RibbonUIEventHandler(this.Ribbon1_Load);
this.tab1.ResumeLayout(false);
this.tab1.PerformLayout();
this.group1.ResumeLayout(false);
this.group1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
internal Microsoft.Office.Tools.Ribbon.RibbonTab tab1;
internal Microsoft.Office.Tools.Ribbon.RibbonGroup group1;
internal Microsoft.Office.Tools.Ribbon.RibbonButton button1;
internal Microsoft.Office.Tools.Ribbon.RibbonButton button2;
internal Microsoft.Office.Tools.Ribbon.RibbonCheckBox checkBox1;
internal Microsoft.Office.Tools.Ribbon.RibbonCheckBox checkBox2;
internal Microsoft.Office.Tools.Ribbon.RibbonCheckBox checkBox3;
}
partial class ThisRibbonCollection
{
internal Ribbon1 Ribbon1
{
get { return this.GetRibbon<Ribbon1>(); }
}
}
}
| 37.496183 | 139 | 0.571254 | [
"MIT"
] | SonicPrince/LemonData | EasyXMLCode/EasyXML/Ribbon1.Designer.cs | 5,108 | C# |
// Copyright (c) 2018 Alachisoft
//
// 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 System.Text;
namespace Alachisoft.NCache.Common.Queries
{
public static class QueryKeyWords
{
public const string KeyColumn = "$KEY$";
public const string ValueColumn = "$VALUE$";
}
}
| 31.428571 | 75 | 0.727273 | [
"Apache-2.0"
] | abayaz61/NCache | Src/NCCommon/Queries/QueryKeyWords.cs | 882 | C# |
#region License
/* Copyright 2019 James F. Bellinger <http://www.zer7.com/software/hidsharp>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License. */
#endregion
using System;
namespace HidSharp.Experimental
{
[Flags]
public enum BleCharacteristicProperties : byte
{
None = 0x00,
Broadcast = 0x01,
Read = 0x02,
WriteWithoutResponse = 0x04,
Write = 0x08,
Notify = 0x10,
Indicate = 0x20,
SignedWrite = 0x40,
ExtendedProperties = 0x80
}
}
| 28.583333 | 76 | 0.683188 | [
"ECL-2.0",
"Apache-2.0"
] | vinogradniy/HidSharp | HidSharp/Experimental/BleCharacteristicProperties.cs | 1,031 | C# |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
/*******************************************************************/
/* WARNING */
/* This file should be identical in the Bartok and Singularity */
/* depots. Master copy resides in Bartok Depot. Changes should be */
/* made to Bartok Depot and propagated to Singularity Depot. */
/*******************************************************************/
namespace System.GCs
{
using Microsoft.Bartok.Runtime;
using System.Runtime.CompilerServices;
using System.Threading;
internal abstract unsafe class RefWriteBarrier: Barrier
{
[NoBarriers]
protected override int AtomicSwapImpl(ref int location,
int value,
int mask)
{
return Interlocked.Exchange(ref location, value);
}
[NoBarriers]
protected override UIntPtr AtomicSwapImpl(ref UIntPtr location,
UIntPtr value,
int mask)
{
return Interlocked.Exchange(ref location, value);
}
[NoBarriers]
protected override int AtomicCompareAndSwapImpl(ref int location,
int newValue,
int comparand,
int mask)
{
return Interlocked.CompareExchange(ref location,
newValue, comparand);
}
[NoBarriers]
protected override long AtomicCompareAndSwapImpl(ref long location,
long newValue,
long comparand,
int mask)
{
return Interlocked.CompareExchange(ref location,
newValue, comparand);
}
[NoBarriers]
protected override
UIntPtr AtomicCompareAndSwapImpl(ref UIntPtr location,
UIntPtr newValue,
UIntPtr comparand,
int mask)
{
return Interlocked.CompareExchange(ref location,
newValue, comparand);
}
[Inline]
[NoBarriers]
protected override Object WeakRefReadImpl(UIntPtr addr, int mask)
{
return Magic.fromAddress(addr);
}
[Inline]
[NoBarriers]
protected override UIntPtr WeakRefWriteImpl(Object obj,
int mask)
{
return Magic.addressOf(obj);
}
[Inline]
[NoBarriers]
protected override bool EqImpl(Object a,Object b, int mask)
{
return a==b;
}
[Inline]
[NoBarriers]
protected override bool AllowFastPathImpl() {
return false;
}
[Inline]
protected override void WriteImpl(float *location,
float value,
int mask)
{
*location = value;
}
[Inline]
protected override void WriteImpl(double *location,
double value,
int mask)
{
*location = value;
}
[Inline]
protected override void WriteImpl(byte *location,
byte value,
int mask)
{
*location = value;
}
[Inline]
protected override void WriteImpl(ushort *location,
ushort value,
int mask)
{
*location = value;
}
[Inline]
protected override void WriteImpl(uint *location,
uint value,
int mask)
{
*location = value;
}
[Inline]
protected override void WriteImpl(ulong *location,
ulong value,
int mask)
{
*location = value;
}
[Inline]
protected override void WriteImpl(UIntPtr *location,
UIntPtr value,
int mask)
{
*location = value;
}
[Inline]
protected override Object ReadObjImpl(UIntPtr *location,
int mask)
{
return Magic.fromAddress(*location);
}
[Inline]
protected override float ReadImpl(float *location,
int mask)
{
return *location;
}
[Inline]
protected override double ReadImpl(double *location,
int mask)
{
return *location;
}
[Inline]
protected override byte ReadImpl(byte *location,
int mask)
{
return *location;
}
[Inline]
protected override ushort ReadImpl(ushort *location,
int mask)
{
return *location;
}
[Inline]
protected override uint ReadImpl(uint *location,
int mask)
{
return *location;
}
[Inline]
protected override ulong ReadImpl(ulong *location,
int mask)
{
return *location;
}
[Inline]
protected override UIntPtr ReadImpl(UIntPtr *location,
int mask)
{
return *location;
}
[NoBarriers]
[Inline]
protected override void WriteImplByRef(ref float location,
float value,
int mask)
{
location = value;
}
[NoBarriers]
[Inline]
protected override void WriteImplByRef(ref double location,
double value,
int mask)
{
location = value;
}
[NoBarriers]
[Inline]
protected override void WriteImplByRef(ref byte location,
byte value,
int mask)
{
location = value;
}
[NoBarriers]
[Inline]
protected override void WriteImplByRef(ref ushort location,
ushort value,
int mask)
{
location = value;
}
[NoBarriers]
[Inline]
protected override void WriteImplByRef(ref uint location,
uint value,
int mask)
{
location = value;
}
[NoBarriers]
[Inline]
protected override void WriteImplByRef(ref ulong location,
ulong value,
int mask)
{
location = value;
}
[NoBarriers]
[Inline]
protected override void WriteImplByRef(ref UIntPtr location,
UIntPtr value,
int mask)
{
location = value;
}
[NoBarriers]
[Inline]
protected override Object ReadImplByRef(ref Object location,
int mask)
{
return location;
}
[NoBarriers]
[Inline]
protected override float ReadImplByRef(ref float location,
int mask)
{
return location;
}
[NoBarriers]
[Inline]
protected override double ReadImplByRef(ref double location,
int mask)
{
return location;
}
[NoBarriers]
[Inline]
protected override byte ReadImplByRef(ref byte location,
int mask)
{
return location;
}
[NoBarriers]
[Inline]
protected override ushort ReadImplByRef(ref ushort location,
int mask)
{
return location;
}
[NoBarriers]
[Inline]
protected override uint ReadImplByRef(ref uint location,
int mask)
{
return location;
}
[NoBarriers]
[Inline]
protected override ulong ReadImplByRef(ref ulong location,
int mask)
{
return location;
}
[NoBarriers]
[Inline]
protected override UIntPtr ReadImplByRef(ref UIntPtr location,
int mask)
{
return location;
}
[Inline]
protected override Object LoadStaticFieldImpl(ref Object staticField,
int mask)
{
return this.ReadImplByRef(ref staticField, mask);
}
}
}
| 30.379009 | 77 | 0.390307 | [
"MIT"
] | pmache/singularityrdk | SOURCE/base/Imported/Bartok/runtime/shared/GCs/RefWriteBarrier.cs | 10,420 | C# |
namespace NGSoftware.Common.Configuration
{
public interface IAppSettings
{
string this[string parameterName] { get; }
}
} | 20.285714 | 50 | 0.683099 | [
"MIT"
] | ngeor/NGSoftware.Common | NGSoftware.Common/Configuration/IAppSettings.cs | 142 | C# |
using VkNet.Enums.SafetyEnums;
using VkNet.Utils;
namespace VkNet.Model.RequestParams
{
/// <summary>
/// Параметры метода friends.getOnline
/// </summary>
public struct FriendsGetOnlineParams
{
/// <summary>
/// Параметры метода friends.getOnline
/// </summary>
/// <param name="gag">Заглушка для конструктора.</param>
public FriendsGetOnlineParams(bool gag = true)
{
UserId = null;
ListId = null;
OnlineMobile = null;
Order = null;
Count = null;
Offset = null;
}
/// <summary>
/// Идентификатор пользователя, для которого необходимо получить список друзей онлайн. Если параметр не задан, то считается, что он равен идентификатору текущего пользователя. положительное число, по умолчанию идентификатор текущего пользователя.
/// </summary>
public long? UserId { get; set; }
/// <summary>
/// Идентификатор списка друзей. Если параметр не задан, возвращается информация обо всех друзьях, находящихся на сайте. положительное число.
/// </summary>
public long? ListId { get; set; }
/// <summary>
/// 1 — будет возвращено дополнительное поле online_mobile.
/// По умолчанию — 0. флаг, может принимать значения 1 или 0.
/// </summary>
public bool? OnlineMobile { get; set; }
/// <summary>
/// Порядок, в котором нужно вернуть список друзей, находящихся на сайте. Допустимые значения: random - возвращает друзей в случайном порядке, hints - сортировать по рейтингу, аналогично тому, как друзья сортируются в разделе Мои друзья (данный параметр доступен только для Desktop-приложений). строка.
/// </summary>
public FriendsOrder Order { get; set; }
/// <summary>
/// Количество друзей онлайн, которое нужно вернуть. (по умолчанию – все друзья онлайн) положительное число.
/// </summary>
public long? Count { get; set; }
/// <summary>
/// Смещение, необходимое для выборки определенного подмножества друзей онлайн. положительное число.
/// </summary>
public long? Offset { get; set; }
/// <summary>
/// Привести к типу VkParameters.
/// </summary>
/// <param name="p">Параметры.</param>
/// <returns></returns>
public static VkParameters ToVkParameters(FriendsGetOnlineParams p)
{
var parameters = new VkParameters
{
{ "user_id", p.UserId },
{ "list_id", p.ListId },
{ "online_mobile", p.OnlineMobile },
{ "order", p.Order },
{ "count", p.Count },
{ "offset", p.Offset }
};
return parameters;
}
}
} | 32.131579 | 304 | 0.682637 | [
"MIT"
] | uid17/VK | VkNet/Model/RequestParams/Friends/FriendsGetOnlineParams.cs | 3,318 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace CustomerService.SPA.Pages
{
public class ErrorModel : PageModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}
| 26.166667 | 92 | 0.699045 | [
"MIT"
] | QuinntyneBrown/CustomerService | src/CustomerService.SPA/Pages/Error.cshtml.cs | 628 | C# |
using CellWar.Utils;
using SharpCompress.Archives;
using SharpCompress.Common;
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
namespace ppUpdator.Core
{
public class Updator
{
UpdateInfoModel info;
public Updator()
{
info = JsonHelper.Json2Object_NT<UpdateInfoModel>(InfoFilePath);
}
public string InfoFilePath = Path.Combine(Directory.GetCurrentDirectory(), "ppu_update_info.json");
public void Do()
{
if (!Directory.Exists("ppu_tmp"))
{
Directory.CreateDirectory("ppu_tmp");
}
string tmpFileName = "ppu_tmp\\tmp" + info.DownloadZipType;
Download(info.DownloadUrl, tmpFileName);
var archive = ArchiveFactory.Open(tmpFileName);
foreach (var entry in archive.Entries)
{
if (!entry.IsDirectory)
{
Console.WriteLine(entry.Key);
entry.WriteToDirectory("ppu_tmp\\tmp_new", new ExtractionOptions() { ExtractFullPath = true, Overwrite = true });
}
}
archive.Dispose();
foreach (var deleteFile in info.IgnoreCopyFileNames)
{
File.Delete( Path.Combine( "ppu_tmp\\tmp_new", info.BaseFolderName, deleteFile ) );
}
CopyDir(Path.Combine("ppu_tmp\\tmp_new", info.BaseFolderName), Directory.GetCurrentDirectory() );
DeleteDir("ppu_tmp");
}
public void StartApp()
{
Process.Start( info.RunAfterUpdate );
}
private void DeleteDir(string file)
{
try
{
//去除文件夹和子文件的只读属性
//去除文件夹的只读属性
System.IO.DirectoryInfo fileInfo = new DirectoryInfo(file);
fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
//去除文件的只读属性
System.IO.File.SetAttributes(file, System.IO.FileAttributes.Normal);
//判断文件夹是否还存在
if (Directory.Exists(file))
{
foreach (string f in Directory.GetFileSystemEntries(file))
{
if (File.Exists(f))
{
//如果有子文件删除文件
File.Delete(f);
Console.WriteLine(f);
}
else
{
//循环递归删除子文件夹
DeleteDir(f);
}
}
//删除空文件夹
Directory.Delete(file);
}
}
catch (Exception ex) // 异常处理
{
Console.WriteLine(ex.Message.ToString());// 异常信息
}
}
private void CopyDir(string srcPath, string tarPath)
{
try
{
// 检查目标目录是否以目录分割字符结束如果不是则添加
if (tarPath[tarPath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
{
tarPath += System.IO.Path.DirectorySeparatorChar;
}
// 判断目标目录是否存在如果不存在则新建
if (!System.IO.Directory.Exists(tarPath))
{
System.IO.Directory.CreateDirectory(tarPath);
}
// 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
// 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
// string[] fileList = Directory.GetFiles(srcPath);
string[] fileList = System.IO.Directory.GetFileSystemEntries(srcPath);
// 遍历所有的文件和目录
foreach (string file in fileList)
{
// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
if (System.IO.Directory.Exists(file))
{
CopyDir(file, tarPath + System.IO.Path.GetFileName(file));
}
// 否则直接Copy文件
else
{
System.IO.File.Copy(file, tarPath + System.IO.Path.GetFileName(file), true);
}
}
}
catch (Exception e)
{
throw;
}
}
private bool Download(string url, string localfile)
{
bool flag = false;
long startPosition = 0; // 上次下载的文件起始位置
FileStream writeStream; // 写入本地文件流对象
// 判断要下载的文件夹是否存在
if (File.Exists(localfile))
{
writeStream = File.OpenWrite(localfile); // 存在则打开要下载的文件
startPosition = writeStream.Length; // 获取已经下载的长度
writeStream.Seek(startPosition, SeekOrigin.Current); // 本地文件写入位置定位
}
else
{
writeStream = new FileStream(localfile, FileMode.Create);// 文件不保存创建一个文件
startPosition = 0;
}
try
{
HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);// 打开网络连接
if (startPosition > 0)
{
myRequest.AddRange((int)startPosition);// 设置Range值,与上面的writeStream.Seek用意相同,是为了定义远程文件读取位置
}
Stream readStream = myRequest.GetResponse().GetResponseStream();// 向服务器请求,获得服务器的回应数据流
byte[] btArray = new byte[512];// 定义一个字节数据,用来向readStream读取内容和向writeStream写入内容
int contentSize = readStream.Read(btArray, 0, btArray.Length);// 向远程文件读第一次
while (contentSize > 0)// 如果读取长度大于零则继续读
{
writeStream.Write(btArray, 0, contentSize);// 写入本地文件
contentSize = readStream.Read(btArray, 0, btArray.Length);// 继续向远程文件读取
}
//关闭流
writeStream.Close();
readStream.Close();
flag = true; //返回true下载成功
}
catch (Exception)
{
writeStream.Close();
flag = false; //返回false下载失败
}
return flag;
}
}
}
| 32.597938 | 133 | 0.47723 | [
"MIT"
] | cyf-gh/ppUpdator | ppUpdator/ppUpdator.Core/Updator.cs | 7,158 | C# |
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using WebApplication11.Models;
namespace WebApplication11.Controllers
{
[Authorize]
public class HomeController : Controller
{
[AllowAnonymous]
public IActionResult Index()
{
// Convert.ToInt32("a");
return View();
}
[TestFilter("002")]
public IActionResult Privacy()
{
int a = 1;
a += 1;
var b = a;
return View();
}
public IActionResult OnGet()
{
if (HttpContext.User.Identity.IsAuthenticated)
{
return Content(HttpContext.User.Claims.SingleOrDefault(t => t.Type == ClaimTypes.Name).Value);
}
return Content("未登录");
}
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Content("退出");
}
/// <summary>
/// 登录
/// </summary>
/// <returns></returns>
[AllowAnonymous]
public async Task<IActionResult> OnPost()
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, "user.Email"),
new Claim("FullName", "user.FullName"),
new Claim(ClaimTypes.Role, "Administrator"),
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTime.UtcNow.AddMinutes(20)
};
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
return Content("登录完成");
}
[AllowAnonymous]
public IActionResult login()
{
return Content("需要登录");
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
} | 29.659341 | 112 | 0.564283 | [
"Apache-2.0"
] | 18965824402/dotnet-core-Example | DotNetCore/mvc.filter/Controllers/HomeController.cs | 2,731 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using NativeLibrary = NativeLibraryLoader.NativeLibrary;
using Veldrid.MetalBindings;
namespace Veldrid.MTL
{
internal unsafe class MTLGraphicsDevice : GraphicsDevice
{
private static readonly Lazy<bool> s_isSupported = new Lazy<bool>(GetIsSupported);
private static readonly Dictionary<IntPtr, MTLGraphicsDevice> s_aotRegisteredBlocks
= new Dictionary<IntPtr, MTLGraphicsDevice>();
private readonly MTLDevice _device;
private readonly string _deviceName;
private readonly GraphicsApiVersion _apiVersion;
private readonly MTLCommandQueue _commandQueue;
private readonly MTLSwapchain _mainSwapchain;
private readonly bool[] _supportedSampleCounts;
private BackendInfoMetal _metalInfo;
private readonly object _submittedCommandsLock = new object();
private readonly Dictionary<MTLCommandBuffer, MTLFence> _submittedCBs = new Dictionary<MTLCommandBuffer, MTLFence>();
private MTLCommandBuffer _latestSubmittedCB;
private readonly object _resetEventsLock = new object();
private readonly List<ManualResetEvent[]> _resetEvents = new List<ManualResetEvent[]>();
private const string UnalignedBufferCopyPipelineMacOSName = "MTL_UnalignedBufferCopy_macOS";
private const string UnalignedBufferCopyPipelineiOSName = "MTL_UnalignedBufferCopy_iOS";
private readonly object _unalignedBufferCopyPipelineLock = new object();
private readonly NativeLibrary _libSystem;
private readonly IntPtr _concreteGlobalBlock;
private MTLShader _unalignedBufferCopyShader;
private MTLComputePipelineState _unalignedBufferCopyPipeline;
private MTLCommandBufferHandler _completionHandler;
private readonly IntPtr _completionHandlerFuncPtr;
private readonly IntPtr _completionBlockDescriptor;
private readonly IntPtr _completionBlockLiteral;
public MTLDevice Device => _device;
public MTLCommandQueue CommandQueue => _commandQueue;
public MTLFeatureSupport MetalFeatures { get; }
public ResourceBindingModel ResourceBindingModel { get; }
public MTLGraphicsDevice(
GraphicsDeviceOptions options,
SwapchainDescription? swapchainDesc)
{
_device = MTLDevice.MTLCreateSystemDefaultDevice();
_deviceName = _device.name;
MetalFeatures = new MTLFeatureSupport(_device);
int major = (int)MetalFeatures.MaxFeatureSet / 10000;
int minor = (int)MetalFeatures.MaxFeatureSet % 10000;
_apiVersion = new GraphicsApiVersion(major, minor, 0, 0);
Features = new GraphicsDeviceFeatures(
computeShader: true,
geometryShader: false,
tessellationShaders: false,
multipleViewports: MetalFeatures.IsSupported(MTLFeatureSet.macOS_GPUFamily1_v3),
samplerLodBias: false,
drawBaseVertex: MetalFeatures.IsDrawBaseVertexInstanceSupported(),
drawBaseInstance: MetalFeatures.IsDrawBaseVertexInstanceSupported(),
drawIndirect: true,
drawIndirectBaseInstance: true,
fillModeWireframe: true,
samplerAnisotropy: true,
depthClipDisable: true,
texture1D: true, // TODO: Should be macOS 10.11+ and iOS 11.0+.
independentBlend: true,
structuredBuffer: true,
subsetTextureView: true,
commandListDebugMarkers: true,
bufferRangeBinding: true,
shaderFloat64: false);
ResourceBindingModel = options.ResourceBindingModel;
_libSystem = new NativeLibrary("libSystem.dylib");
_concreteGlobalBlock = _libSystem.LoadFunction("_NSConcreteGlobalBlock");
if (MetalFeatures.IsMacOS)
{
_completionHandler = OnCommandBufferCompleted;
}
else
{
_completionHandler = OnCommandBufferCompleted_Static;
}
_completionHandlerFuncPtr = Marshal.GetFunctionPointerForDelegate<MTLCommandBufferHandler>(_completionHandler);
_completionBlockDescriptor = Marshal.AllocHGlobal(Unsafe.SizeOf<BlockDescriptor>());
BlockDescriptor* descriptorPtr = (BlockDescriptor*)_completionBlockDescriptor;
descriptorPtr->reserved = 0;
descriptorPtr->Block_size = (ulong)Unsafe.SizeOf<BlockDescriptor>();
_completionBlockLiteral = Marshal.AllocHGlobal(Unsafe.SizeOf<BlockLiteral>());
BlockLiteral* blockPtr = (BlockLiteral*)_completionBlockLiteral;
blockPtr->isa = _concreteGlobalBlock;
blockPtr->flags = 1 << 28 | 1 << 29;
blockPtr->invoke = _completionHandlerFuncPtr;
blockPtr->descriptor = descriptorPtr;
if (!MetalFeatures.IsMacOS)
{
lock (s_aotRegisteredBlocks)
{
s_aotRegisteredBlocks.Add(_completionBlockLiteral, this);
}
}
ResourceFactory = new MTLResourceFactory(this);
_commandQueue = _device.newCommandQueue();
TextureSampleCount[] allSampleCounts = (TextureSampleCount[])Enum.GetValues(typeof(TextureSampleCount));
_supportedSampleCounts = new bool[allSampleCounts.Length];
for (int i = 0; i < allSampleCounts.Length; i++)
{
TextureSampleCount count = allSampleCounts[i];
uint uintValue = FormatHelpers.GetSampleCountUInt32(count);
if (_device.supportsTextureSampleCount((UIntPtr)uintValue))
{
_supportedSampleCounts[i] = true;
}
}
if (swapchainDesc != null)
{
SwapchainDescription desc = swapchainDesc.Value;
_mainSwapchain = new MTLSwapchain(this, ref desc);
}
_metalInfo = new BackendInfoMetal(this);
PostDeviceCreated();
}
public override string DeviceName => _deviceName;
public override string VendorName => "Apple";
public override GraphicsApiVersion ApiVersion => _apiVersion;
public override GraphicsBackend BackendType => GraphicsBackend.Metal;
public override bool IsUvOriginTopLeft => true;
public override bool IsDepthRangeZeroToOne => true;
public override bool IsClipSpaceYInverted => false;
public override ResourceFactory ResourceFactory { get; }
public override Swapchain MainSwapchain => _mainSwapchain;
public override GraphicsDeviceFeatures Features { get; }
private void OnCommandBufferCompleted(IntPtr block, MTLCommandBuffer cb)
{
lock (_submittedCommandsLock)
{
if (_submittedCBs.TryGetValue(cb, out MTLFence fence))
{
fence.Set();
_submittedCBs.Remove(cb);
}
if (_latestSubmittedCB.NativePtr == cb.NativePtr)
{
_latestSubmittedCB = default(MTLCommandBuffer);
}
}
ObjectiveCRuntime.release(cb.NativePtr);
}
// Xamarin AOT requires native callbacks be static.
[MonoPInvokeCallback(typeof(MTLCommandBufferHandler))]
private static void OnCommandBufferCompleted_Static(IntPtr block, MTLCommandBuffer cb)
{
lock (s_aotRegisteredBlocks)
{
if (s_aotRegisteredBlocks.TryGetValue(block, out MTLGraphicsDevice gd))
{
gd.OnCommandBufferCompleted(block, cb);
}
}
}
private protected override void SubmitCommandsCore(CommandList commandList, Fence fence)
{
MTLCommandList mtlCL = Util.AssertSubtype<CommandList, MTLCommandList>(commandList);
mtlCL.CommandBuffer.addCompletedHandler(_completionBlockLiteral);
lock (_submittedCommandsLock)
{
if (fence != null)
{
MTLFence mtlFence = Util.AssertSubtype<Fence, MTLFence>(fence);
_submittedCBs.Add(mtlCL.CommandBuffer, mtlFence);
}
_latestSubmittedCB = mtlCL.Commit();
}
}
public override TextureSampleCount GetSampleCountLimit(PixelFormat format, bool depthFormat)
{
for (int i = _supportedSampleCounts.Length - 1; i >= 0; i--)
{
if (_supportedSampleCounts[i])
{
return (TextureSampleCount)i;
}
}
return TextureSampleCount.Count1;
}
private protected override bool GetPixelFormatSupportCore(
PixelFormat format,
TextureType type,
TextureUsage usage,
out PixelFormatProperties properties)
{
if (!MTLFormats.IsFormatSupported(format, usage, MetalFeatures))
{
properties = default(PixelFormatProperties);
return false;
}
uint sampleCounts = 0;
for (int i = 0; i < _supportedSampleCounts.Length; i++)
{
if (_supportedSampleCounts[i])
{
sampleCounts |= (uint)(1 << i);
}
}
MTLFeatureSet maxFeatureSet = MetalFeatures.MaxFeatureSet;
uint maxArrayLayer = MTLFormats.GetMaxTextureVolume(maxFeatureSet);
uint maxWidth;
uint maxHeight;
uint maxDepth;
if (type == TextureType.Texture1D)
{
maxWidth = MTLFormats.GetMaxTexture1DWidth(maxFeatureSet);
maxHeight = 1;
maxDepth = 1;
}
else if (type == TextureType.Texture2D)
{
uint maxDimensions;
if ((usage & TextureUsage.Cubemap) != 0)
{
maxDimensions = MTLFormats.GetMaxTextureCubeDimensions(maxFeatureSet);
}
else
{
maxDimensions = MTLFormats.GetMaxTexture2DDimensions(maxFeatureSet);
}
maxWidth = maxDimensions;
maxHeight = maxDimensions;
maxDepth = 1;
}
else if (type == TextureType.Texture3D)
{
maxWidth = maxArrayLayer;
maxHeight = maxArrayLayer;
maxDepth = maxArrayLayer;
maxArrayLayer = 1;
}
else
{
throw Illegal.Value<TextureType>();
}
properties = new PixelFormatProperties(
maxWidth,
maxHeight,
maxDepth,
uint.MaxValue,
maxArrayLayer,
sampleCounts);
return true;
}
private protected override void SwapBuffersCore(Swapchain swapchain)
{
MTLSwapchain mtlSC = Util.AssertSubtype<Swapchain, MTLSwapchain>(swapchain);
IntPtr currentDrawablePtr = mtlSC.CurrentDrawable.NativePtr;
if (currentDrawablePtr != IntPtr.Zero)
{
using (NSAutoreleasePool.Begin())
{
MTLCommandBuffer submitCB = _commandQueue.commandBuffer();
submitCB.presentDrawable(currentDrawablePtr);
submitCB.commit();
}
}
mtlSC.GetNextDrawable();
}
private protected override void UpdateBufferCore(DeviceBuffer buffer, uint bufferOffsetInBytes, IntPtr source, uint sizeInBytes)
{
var mtlBuffer = Util.AssertSubtype<DeviceBuffer, MTLBuffer>(buffer);
void* destPtr = mtlBuffer.DeviceBuffer.contents();
byte* destOffsetPtr = (byte*)destPtr + bufferOffsetInBytes;
Unsafe.CopyBlock(destOffsetPtr, source.ToPointer(), sizeInBytes);
}
private protected override void UpdateTextureCore(
Texture texture,
IntPtr source,
uint sizeInBytes,
uint x,
uint y,
uint z,
uint width,
uint height,
uint depth,
uint mipLevel,
uint arrayLayer)
{
MTLTexture mtlTex = Util.AssertSubtype<Texture, MTLTexture>(texture);
if (mtlTex.StagingBuffer.IsNull)
{
Texture stagingTex = ResourceFactory.CreateTexture(new TextureDescription(
width, height, depth, 1, 1, texture.Format, TextureUsage.Staging, texture.Type));
UpdateTexture(stagingTex, source, sizeInBytes, 0, 0, 0, width, height, depth, 0, 0);
CommandList cl = ResourceFactory.CreateCommandList();
cl.Begin();
cl.CopyTexture(
stagingTex, 0, 0, 0, 0, 0,
texture, x, y, z, mipLevel, arrayLayer,
width, height, depth, 1);
cl.End();
SubmitCommands(cl);
cl.Dispose();
stagingTex.Dispose();
}
else
{
mtlTex.GetSubresourceLayout(mipLevel, arrayLayer, out uint dstRowPitch, out uint dstDepthPitch);
ulong dstOffset = Util.ComputeSubresourceOffset(mtlTex, mipLevel, arrayLayer);
uint srcRowPitch = FormatHelpers.GetRowPitch(width, texture.Format);
uint srcDepthPitch = FormatHelpers.GetDepthPitch(srcRowPitch, height, texture.Format);
Util.CopyTextureRegion(
source.ToPointer(),
0, 0, 0,
srcRowPitch, srcDepthPitch,
(byte*)mtlTex.StagingBuffer.contents() + dstOffset,
x, y, z,
dstRowPitch, dstDepthPitch,
width, height, depth,
texture.Format);
}
}
private protected override void WaitForIdleCore()
{
MTLCommandBuffer lastCB = default(MTLCommandBuffer);
lock (_submittedCommandsLock)
{
lastCB = _latestSubmittedCB;
ObjectiveCRuntime.retain(lastCB.NativePtr);
}
if (lastCB.NativePtr != IntPtr.Zero && lastCB.status != MTLCommandBufferStatus.Completed)
{
lastCB.waitUntilCompleted();
}
ObjectiveCRuntime.release(lastCB.NativePtr);
}
protected override MappedResource MapCore(MappableResource resource, MapMode mode, uint subresource)
{
if (resource is MTLBuffer buffer)
{
return MapBuffer(buffer, mode);
}
else
{
MTLTexture texture = Util.AssertSubtype<MappableResource, MTLTexture>(resource);
return MapTexture(texture, mode, subresource);
}
}
private MappedResource MapBuffer(MTLBuffer buffer, MapMode mode)
{
void* data = buffer.DeviceBuffer.contents();
return new MappedResource(
buffer,
mode,
(IntPtr)data,
buffer.SizeInBytes,
0,
buffer.SizeInBytes,
buffer.SizeInBytes);
}
private MappedResource MapTexture(MTLTexture texture, MapMode mode, uint subresource)
{
Debug.Assert(!texture.StagingBuffer.IsNull);
void* data = texture.StagingBuffer.contents();
Util.GetMipLevelAndArrayLayer(texture, subresource, out uint mipLevel, out uint arrayLayer);
Util.GetMipDimensions(texture, mipLevel, out uint width, out uint height, out uint depth);
uint subresourceSize = texture.GetSubresourceSize(mipLevel, arrayLayer);
texture.GetSubresourceLayout(mipLevel, arrayLayer, out uint rowPitch, out uint depthPitch);
ulong offset = Util.ComputeSubresourceOffset(texture, mipLevel, arrayLayer);
byte* offsetPtr = (byte*)data + offset;
return new MappedResource(texture, mode, (IntPtr)offsetPtr, subresourceSize, subresource, rowPitch, depthPitch);
}
protected override void PlatformDispose()
{
WaitForIdle();
if (!_unalignedBufferCopyPipeline.IsNull)
{
_unalignedBufferCopyShader.Dispose();
ObjectiveCRuntime.release(_unalignedBufferCopyPipeline.NativePtr);
}
_mainSwapchain?.Dispose();
ObjectiveCRuntime.release(_commandQueue.NativePtr);
ObjectiveCRuntime.release(_device.NativePtr);
lock (s_aotRegisteredBlocks)
{
s_aotRegisteredBlocks.Remove(_completionBlockLiteral);
}
_libSystem.Dispose();
Marshal.FreeHGlobal(_completionBlockDescriptor);
Marshal.FreeHGlobal(_completionBlockLiteral);
}
public override bool GetMetalInfo(out BackendInfoMetal info)
{
info = _metalInfo;
return true;
}
protected override void UnmapCore(MappableResource resource, uint subresource)
{
}
public override bool WaitForFence(Fence fence, ulong nanosecondTimeout)
{
return Util.AssertSubtype<Fence, MTLFence>(fence).Wait(nanosecondTimeout);
}
public override bool WaitForFences(Fence[] fences, bool waitAll, ulong nanosecondTimeout)
{
int msTimeout;
if (nanosecondTimeout == ulong.MaxValue)
{
msTimeout = -1;
}
else
{
msTimeout = (int)Math.Min(nanosecondTimeout / 1_000_000, int.MaxValue);
}
ManualResetEvent[] events = GetResetEventArray(fences.Length);
for (int i = 0; i < fences.Length; i++)
{
events[i] = Util.AssertSubtype<Fence, MTLFence>(fences[i]).ResetEvent;
}
bool result;
if (waitAll)
{
result = WaitHandle.WaitAll(events, msTimeout);
}
else
{
int index = WaitHandle.WaitAny(events, msTimeout);
result = index != WaitHandle.WaitTimeout;
}
ReturnResetEventArray(events);
return result;
}
private ManualResetEvent[] GetResetEventArray(int length)
{
lock (_resetEventsLock)
{
for (int i = _resetEvents.Count - 1; i > 0; i--)
{
ManualResetEvent[] array = _resetEvents[i];
if (array.Length == length)
{
_resetEvents.RemoveAt(i);
return array;
}
}
}
ManualResetEvent[] newArray = new ManualResetEvent[length];
return newArray;
}
private void ReturnResetEventArray(ManualResetEvent[] array)
{
lock (_resetEventsLock)
{
_resetEvents.Add(array);
}
}
public override void ResetFence(Fence fence)
{
Util.AssertSubtype<Fence, MTLFence>(fence).Reset();
}
internal static bool IsSupported() => s_isSupported.Value;
private static bool GetIsSupported()
{
bool result = false;
try
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
if (RuntimeInformation.OSDescription.Contains("Darwin"))
{
NSArray allDevices = MTLDevice.MTLCopyAllDevices();
result |= (ulong)allDevices.count > 0;
ObjectiveCRuntime.release(allDevices.NativePtr);
}
else
{
MTLDevice defaultDevice = MTLDevice.MTLCreateSystemDefaultDevice();
if (defaultDevice.NativePtr != IntPtr.Zero)
{
result = true;
ObjectiveCRuntime.release(defaultDevice.NativePtr);
}
}
}
}
catch
{
result = false;
}
return result;
}
internal MTLComputePipelineState GetUnalignedBufferCopyPipeline()
{
lock (_unalignedBufferCopyPipelineLock)
{
if (_unalignedBufferCopyPipeline.IsNull)
{
MTLComputePipelineDescriptor descriptor = MTLUtil.AllocInit<MTLComputePipelineDescriptor>(
nameof(MTLComputePipelineDescriptor));
MTLPipelineBufferDescriptor buffer0 = descriptor.buffers[0];
buffer0.mutability = MTLMutability.Mutable;
MTLPipelineBufferDescriptor buffer1 = descriptor.buffers[1];
buffer0.mutability = MTLMutability.Mutable;
Debug.Assert(_unalignedBufferCopyShader == null);
string name = MetalFeatures.IsMacOS ? UnalignedBufferCopyPipelineMacOSName : UnalignedBufferCopyPipelineiOSName;
using (Stream resourceStream = typeof(MTLGraphicsDevice).Assembly.GetManifestResourceStream(name))
{
byte[] data = new byte[resourceStream.Length];
using (MemoryStream ms = new MemoryStream(data))
{
resourceStream.CopyTo(ms);
ShaderDescription shaderDesc = new ShaderDescription(ShaderStages.Compute, data, "copy_bytes");
_unalignedBufferCopyShader = new MTLShader(ref shaderDesc, this);
}
}
descriptor.computeFunction = _unalignedBufferCopyShader.Function;
_unalignedBufferCopyPipeline = _device.newComputePipelineStateWithDescriptor(descriptor);
ObjectiveCRuntime.release(descriptor.NativePtr);
}
return _unalignedBufferCopyPipeline;
}
}
internal override uint GetUniformBufferMinOffsetAlignmentCore() => MetalFeatures.IsMacOS ? 16u : 256u;
internal override uint GetStructuredBufferMinOffsetAlignmentCore() => 16u;
}
internal sealed class MonoPInvokeCallbackAttribute : Attribute
{
public MonoPInvokeCallbackAttribute(Type t) { }
}
}
| 38.702479 | 136 | 0.572667 | [
"MIT"
] | Bxil/veldrid | src/Veldrid/MTL/MTLGraphicsDevice.cs | 23,415 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Elektronik.Containers.SpecialInterfaces;
using Elektronik.Data;
using Elektronik.PluginsSystem;
namespace Elektronik.Containers
{
public class VirtualContainer : ISourceTree, IVisible, ISnapshotable
{
public VirtualContainer(string displayName, List<ISourceTree> children = null)
{
DisplayName = displayName;
ChildrenList = children ?? new List<ISourceTree>();
}
public void AddChild(ISourceTree child)
{
ChildrenList.Add(child);
}
#region ISourceTree
public virtual void Clear()
{
foreach (var child in Children)
{
child.Clear();
}
}
public virtual void SetRenderer(ISourceRenderer renderer)
{
foreach (var child in Children)
{
child.SetRenderer(renderer);
}
}
public string DisplayName { get; set; }
public IEnumerable<ISourceTree> Children => ChildrenList;
#endregion
#region IVisible
public bool IsVisible
{
get => _isVisible;
set
{
if (_isVisible == value) return;
_isVisible = value;
OnVisibleChanged?.Invoke(_isVisible);
foreach (var child in Children.OfType<IVisible>())
{
child.IsVisible = IsVisible;
}
}
}
public bool ShowButton { get; private set; } = true;
public event Action<bool> OnVisibleChanged;
#endregion
#region Protected
protected void Squeeze()
{
for (int i = 0; i < ChildrenList.Count(); i++)
{
if (!(ChildrenList[i] is VirtualContainer @virtual)) continue;
@virtual.Squeeze();
if (@virtual.ChildrenList.Count != 1) continue;
ChildrenList[i] = @virtual.ChildrenList[0];
ChildrenList[i].DisplayName = $"{@virtual.DisplayName}/{ChildrenList[i].DisplayName}";
}
ShowButton = CheckShowButton();
}
#endregion
#region ISnapshotable
public ISnapshotable TakeSnapshot()
{
return new VirtualContainer(DisplayName, ChildrenList.OfType<ISnapshotable>()
.Select(ch => ch.TakeSnapshot())
.Select(ch => ch as ISourceTree)
.ToList());
}
public void WriteSnapshot(IDataRecorderPlugin recorder)
{
foreach (var snapshotable in Children.OfType<ISnapshotable>())
{
snapshotable.WriteSnapshot(recorder);
}
}
#endregion
#region Private
private bool _isVisible = true;
protected readonly List<ISourceTree> ChildrenList;
private bool CheckShowButton()
{
foreach (var child in ChildrenList)
{
switch (child)
{
case IVisible {ShowButton: true}:
ShowButton = true;
return true;
case VirtualContainer v when v.CheckShowButton():
ShowButton = true;
return true;
}
}
ShowButton = false;
return false;
}
#endregion
}
} | 26.866667 | 102 | 0.506479 | [
"MIT"
] | dioram/Elektronik | Assets/Scripts/Containers/VirtualContainer.cs | 3,629 | C# |
using Project1.WebUi.Controllers.Exceptions;
using Project1.WebUi.Models;
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace Project1.Tests.WebUi.Models
{
public class OrderTest
{
[Fact]
public void CanAdd12Pizzas()
{
Order o = new Order();
for (int i=0; i<12; i++)
{
Pizza p = new Pizza();
p.Id = 1;
p.Name = "Pizza";
p.Price = 10;
o.AddPizza(p);
}
Assert.Equal(12, o.OrderPizzas.Count);
}
[Fact]
public void CannotAdd13Pizzas()
{
Order o = new Order();
for (int i=0; i<12; i++)
{
Pizza p = new Pizza();
p.Id = 1;
p.Name = "Pizza";
p.Price = 10;
o.AddPizza(p);
}
//Pizza 13
Pizza p13 = new Pizza();
p13.Id = 1;
p13.Name = "Pizza";
p13.Price = 10;
Assert.Throws<MaximumQuantityException>(() => o.AddPizza(p13));
Assert.Equal(12, o.OrderPizzas.Count);
}
[Fact]
public void ValueCannotBeMoreThan500()
{
Order o = new Order();
for (int i = 0; i < 10; i++)
{
Pizza p = new Pizza();
p.Id = 1;
p.Name = "Pizza";
p.Price = 50;
o.AddPizza(p);
}
//Pizza 11
Pizza p11 = new Pizza();
p11.Id = 1;
p11.Name = "Pizza";
p11.Price = 10;
Assert.Throws<MaximumAmountException>(() => o.AddPizza(p11));
Assert.Equal(10, o.OrderPizzas.Count);
Assert.Equal(500, o.Value);
}
[Theory]
[InlineData(0, 1, false)]
[InlineData(0, 15, false)]
[InlineData(0, 30, false)]
[InlineData(0, 45, false)]
[InlineData(1, 0, false)]
[InlineData(1, 15, false)]
[InlineData(1, 30, false)]
[InlineData(1, 45, false)]
[InlineData(2, 0, true)]
[InlineData(2, 1, true)]
[InlineData(3, 0, true)]
public void checkTimeBeforeTwoHours(int hours, int minutes, bool pass)
{
DateTime time = DateTime.Now;
time = time.AddHours(-hours).AddMinutes(-minutes);
Order o = new Order();
if (pass == true)
{
bool canOrder = o.canOrderFromSameAddress(time);
Assert.Equal(pass, canOrder);
}
else
Assert.Throws<SamePlaceException>(() => o.canOrderFromSameAddress(time));
}
}
}
| 25.071429 | 89 | 0.450499 | [
"MIT"
] | 1811-nov27-net/rogerio-pereira-Project1 | Project1/Project1.Tests/WebUi/Models/OrderTest.cs | 2,810 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TrackHoverManager : MonoBehaviour
{
public TrackHover[] tracks;
public void Start() {
Hover(1);
}
public void Hover(float number) {
if (tracks.Length > number - 1) {
for (int i = 0; i < tracks.Length; i++) {
if (i == number - 1) {
tracks[i].Hover();
} else {
tracks[i].Unhover();
}
}
}
}
}
| 21.846154 | 54 | 0.457746 | [
"MIT"
] | codebaard/synthesia | Unity_Synthesia/Assets/TrackHoverManager.cs | 570 | C# |
namespace CarDiaryX.Application.Common
{
public class ApplicationSettings
{
public string Secret { get; private set; }
}
}
| 18 | 50 | 0.666667 | [
"MIT"
] | stefanMinch3v/CarDiaryX | src/CarDiaryX.Api/CarDiaryX.Application/Common/ApplicationSettings.cs | 146 | C# |
using System;
using System.Linq;
namespace ngCoreSmartApp.ViewModels
{
public class OrderViewModel
{
public int Id { get; set; }
public decimal Discount { get; set; }
public string Comments { get; set; }
}
}
| 16.533333 | 45 | 0.620968 | [
"MIT"
] | girishgodage/SmartApp | ngCoreSmartApp/ViewModels/OrderViewModel.cs | 250 | C# |
#if ! (UNITY_DASHBOARD_WIDGET || UNITY_WEBPLAYER || UNITY_WII || UNITY_WIIU || UNITY_NACL || UNITY_FLASH || UNITY_BLACKBERRY) // Disable under unsupported platforms.
//------------------------------------------------------------------------------
// <auto-generated />
//
// This file was automatically generated by SWIG (http://www.swig.org).
// Version 3.0.12
//
// Do not make changes to this file unless you know what you are doing--modify
// the SWIG interface file instead.
//------------------------------------------------------------------------------
public enum AkCallbackType {
AK_EndOfEvent = 0x0001,
AK_EndOfDynamicSequenceItem = 0x0002,
AK_Marker = 0x0004,
AK_Duration = 0x0008,
AK_SpeakerVolumeMatrix = 0x0010,
AK_Starvation = 0x0020,
AK_MusicPlaylistSelect = 0x0040,
AK_MusicPlayStarted = 0x0080,
AK_MusicSyncBeat = 0x0100,
AK_MusicSyncBar = 0x0200,
AK_MusicSyncEntry = 0x0400,
AK_MusicSyncExit = 0x0800,
AK_MusicSyncGrid = 0x1000,
AK_MusicSyncUserCue = 0x2000,
AK_MusicSyncPoint = 0x4000,
AK_MusicSyncAll = 0x7f00,
AK_MIDIEvent = 0x10000,
AK_CallbackBits = 0xfffff,
AK_EnableGetSourcePlayPosition = 0x100000,
AK_EnableGetMusicPlayPosition = 0x200000,
AK_EnableGetSourceStreamBuffering = 0x400000,
AK_Monitoring = 0x20000000,
AK_Bank = 0x40000000,
AK_AudioInterruption = 0x22000000,
AK_AudioSourceChange = 0x23000000
}
#endif // #if ! (UNITY_DASHBOARD_WIDGET || UNITY_WEBPLAYER || UNITY_WII || UNITY_WIIU || UNITY_NACL || UNITY_FLASH || UNITY_BLACKBERRY) // Disable under unsupported platforms. | 39.075 | 175 | 0.682662 | [
"MIT"
] | Anreol/ReleasedFromTheVoid | Assets/Wwise/Deployment/API/Generated/Common/AkCallbackType.cs | 1,563 | C# |
namespace NupkgWrench
{
internal class Constants
{
internal const string HelpOption = "-h|--help";
internal const string ExcludeSymbolsTemplate = "--exclude-symbols";
internal const string ExcludeSymbolsDesc = "Filter out symbol packages.";
internal const string VersionFilterTemplate = "-v|--version";
internal const string VersionFilterDesc = "Filter to only packages matching the version or wildcard.";
internal const string IdFilterTemplate = "-i|--id";
internal const string IdFilterDesc = "Filter to only packages matching the id or wildcard.";
internal const string HighestVersionFilterTemplate = "--highest-version";
internal const string HighestVersionFilterDesc = "Filter to only the highest version for a package id.";
internal const string SinglePackageRootDesc = "Path to a package, directory containing, or a file globbing pattern that resolves to a single package (ex: path/**/*.nupkg).";
internal const string MultiplePackagesRootDesc = "Paths to individual packages, directories containing packages, or file globbing patterns (ex: path/**/*.nupkg). Multiple values may be passed in.";
internal const string FrameworkOptionTemplate = "-f|--framework";
internal const string FrameworkOptionDesc = "Group target frameworks. Use 'any' for the default group. If not specified all dependencies are processed.";
internal const string DependencyVersionRangeTemplate = "--dependency-version";
internal const string DependencyVersionRangeDesc = "Dependency version range.";
internal const string DependencyIdTemplate = "--dependency-id";
internal const string DependencyIdDesc = "Dependency id.";
internal const string DependencyExcludeAttributeTemplate = "--dependency-exclude";
internal const string DependencyExcludeAttributeDesc = "Dependency exclude attribute, example: Build,Analyzers.";
internal const string DependencyIncludeAttributeTemplate = "--dependency-include";
internal const string DependencyIncludeAttributeDesc = "Dependency include attribute, example: Build,Analyzers.";
}
} | 59.216216 | 205 | 0.735281 | [
"MIT"
] | AChubatova/NupkgWrench | src/NupkgWrench/Constants.cs | 2,191 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
using Microsoft.PowerFx.Core.Functions;
namespace Microsoft.PowerFx.Intellisense.IntellisenseData
{
/// <summary>
/// This class represents the default intellisense result.
/// </summary>
internal class DefaultIntellisenseData : IIntellisenseData
{
public int ReplacementStartIndex => 0;
public int ReplacementLength => 0;
public TexlFunction CurFunc => null;
public int ArgCount => 0;
public int ArgIndex => 0;
public string Script => string.Empty;
/// <summary>
/// No-op, default Intellisense does not augment signatures at this stage.
/// </summary>
/// <param name="func"></param>
/// <param name="argIndex"></param>
/// <param name="paramName"></param>
/// <param name="highlightStart"></param>
/// <param name="newHighlightStart">
/// 0 when this method returns.
/// </param>
/// <param name="newHighlightEnd">
/// 0 when this method returns.
/// </param>
/// <param name="newParamName">
/// <see cref="string.Empty"/> when this method returns.
/// </param>
/// <param name="newInvariantParamName">
/// <see cref="string.Empty"/> when this method returns.
/// </param>
/// <returns>
/// False.
/// </returns>
public static bool DefaultTryAugmentSignature(TexlFunction func, int argIndex, string paramName, int highlightStart, out int newHighlightStart, out int newHighlightEnd, out string newParamName, out string newInvariantParamName)
{
newHighlightStart = 0;
newHighlightEnd = 0;
newParamName = string.Empty;
newInvariantParamName = string.Empty;
return false;
}
public bool TryAugmentSignature(TexlFunction func, int argIndex, string paramName, int highlightStart, out int newHighlightStart, out int newHighlightEnd, out string newParamName, out string newInvariantParamName) =>
DefaultTryAugmentSignature(func, argIndex, paramName, highlightStart, out newHighlightStart, out newHighlightEnd, out newParamName, out newInvariantParamName);
/// <summary>
/// Returns nothing, default Intellisense does not suffix parameters by default.
/// </summary>
/// <param name="function">
/// The function that will not be suffixed.
/// </param>
/// <param name="paramName">
/// The parameter that will not be suffixed.
/// </param>
/// <returns><see cref="string.Empty"/>.</returns>
public static string GenerateDefaultParameterDescriptionSuffix(TexlFunction function, string paramName) => string.Empty;
public string GenerateParameterDescriptionSuffix(TexlFunction function, string paramName) => GenerateDefaultParameterDescriptionSuffix(function, paramName);
}
}
| 40.540541 | 235 | 0.638667 | [
"MIT"
] | CarlosFigueiraMSFT/Power-Fx | src/libraries/Microsoft.PowerFx.Core/Texl/Intellisense/IntellisenseData/DefaultIntellisenseData.cs | 3,002 | C# |
// 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.
#nullable disable
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace RunTests
{
internal sealed partial class Program
{
private static readonly ImmutableHashSet<string> PrimaryProcessNames = ImmutableHashSet.Create(
StringComparer.OrdinalIgnoreCase,
"devenv",
"xunit.console",
"xunit.console.x86",
"ServiceHub.RoslynCodeAnalysisService",
"ServiceHub.RoslynCodeAnalysisService32");
internal const int ExitSuccess = 0;
internal const int ExitFailure = 1;
private const long MaxTotalDumpSizeInMegabytes = 8196;
internal static async Task<int> Main(string[] args)
{
Logger.Log("RunTest command line");
Logger.Log(string.Join(" ", args));
var options = Options.Parse(args);
if (options == null)
{
return ExitFailure;
}
ConsoleUtil.WriteLine($"Running '{options.DotnetFilePath} --version'..");
var dotnetResult = await ProcessRunner.CreateProcess(options.DotnetFilePath, arguments: "--version", captureOutput: true).Result;
ConsoleUtil.WriteLine(string.Join(Environment.NewLine, dotnetResult.OutputLines));
ConsoleUtil.WriteLine(ConsoleColor.Red, string.Join(Environment.NewLine, dotnetResult.ErrorLines));
if (options.CollectDumps)
{
if (!DumpUtil.IsAdministrator())
{
ConsoleUtil.WriteLine(ConsoleColor.Yellow, "Dump collection specified but user is not administrator so cannot modify registry");
}
else
{
DumpUtil.EnableRegistryDumpCollection(options.LogFilesDirectory);
}
}
try
{
// Setup cancellation for ctrl-c key presses
using var cts = new CancellationTokenSource();
Console.CancelKeyPress += delegate
{
cts.Cancel();
DisableRegistryDumpCollection();
};
int result;
if (options.Timeout is { } timeout)
{
result = await RunAsync(options, timeout, cts.Token);
}
else
{
result = await RunAsync(options, cts.Token);
}
CheckTotalDumpFilesSize();
return result;
}
finally
{
DisableRegistryDumpCollection();
}
void DisableRegistryDumpCollection()
{
if (options.CollectDumps && DumpUtil.IsAdministrator())
{
DumpUtil.DisableRegistryDumpCollection();
}
}
}
private static async Task<int> RunAsync(Options options, TimeSpan timeout, CancellationToken cancellationToken)
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
var runTask = RunAsync(options, cts.Token);
var timeoutTask = Task.Delay(options.Timeout.Value, cancellationToken);
var finishedTask = await Task.WhenAny(timeoutTask, runTask);
if (finishedTask == timeoutTask)
{
await HandleTimeout(options, cancellationToken);
cts.Cancel();
try
{
// Need to await here to ensure that all of the child processes are properly
// killed before we exit.
await runTask;
}
catch
{
// Cancellation exceptions expected here.
}
return ExitFailure;
}
return await runTask;
}
private static async Task<int> RunAsync(Options options, CancellationToken cancellationToken)
{
var testExecutor = CreateTestExecutor(options);
var testRunner = new TestRunner(options, testExecutor);
var start = DateTime.Now;
var assemblyInfoList = GetAssemblyList(options);
if (assemblyInfoList.Count == 0)
{
ConsoleUtil.WriteLine(ConsoleColor.Red, "No assemblies to test");
return ExitFailure;
}
var assemblyCount = assemblyInfoList.GroupBy(x => x.AssemblyPath).Count();
ConsoleUtil.WriteLine($"Proc dump location: {options.ProcDumpFilePath}");
ConsoleUtil.WriteLine($"Running {assemblyCount} test assemblies in {assemblyInfoList.Count} partitions");
var result = options.UseHelix
? await testRunner.RunAllOnHelixAsync(assemblyInfoList, cancellationToken).ConfigureAwait(true)
: await testRunner.RunAllAsync(assemblyInfoList, cancellationToken).ConfigureAwait(true);
var elapsed = DateTime.Now - start;
ConsoleUtil.WriteLine($"Test execution time: {elapsed}");
LogProcessResultDetails(result.ProcessResults);
WriteLogFile(options);
DisplayResults(options.Display, result.TestResults);
if (!result.Succeeded)
{
ConsoleUtil.WriteLine(ConsoleColor.Red, $"Test failures encountered");
return ExitFailure;
}
ConsoleUtil.WriteLine($"All tests passed");
return ExitSuccess;
}
private static void LogProcessResultDetails(ImmutableArray<ProcessResult> processResults)
{
Logger.Log("### Begin logging executed process details");
foreach (var processResult in processResults)
{
var process = processResult.Process;
var startInfo = process.StartInfo;
Logger.Log($"### Begin {process.Id}");
Logger.Log($"### {startInfo.FileName} {startInfo.Arguments}");
Logger.Log($"### Exit code {process.ExitCode}");
Logger.Log("### Standard Output");
foreach (var line in processResult.OutputLines)
{
Logger.Log(line);
}
Logger.Log("### Standard Error");
foreach (var line in processResult.ErrorLines)
{
Logger.Log(line);
}
Logger.Log($"### End {process.Id}");
}
Logger.Log("End logging executed process details");
}
private static void WriteLogFile(Options options)
{
var logFilePath = Path.Combine(options.LogFilesDirectory, "runtests.log");
try
{
Directory.CreateDirectory(options.LogFilesDirectory);
using (var writer = new StreamWriter(logFilePath, append: false))
{
Logger.WriteTo(writer);
}
}
catch (Exception ex)
{
ConsoleUtil.WriteLine($"Error writing log file {logFilePath}");
ConsoleUtil.WriteLine(ex.ToString());
}
Logger.Clear();
}
/// <summary>
/// Invoked when a timeout occurs and we need to dump all of the test processes and shut down
/// the runnner.
/// </summary>
private static async Task HandleTimeout(Options options, CancellationToken cancellationToken)
{
async Task DumpProcess(Process targetProcess, string procDumpExeFilePath, string dumpFilePath)
{
var name = targetProcess.ProcessName;
// Our space for saving dump files is limited. Skip dumping for processes that won't contribute
// to bug investigations.
if (name is "procdump" or "conhost")
{
return;
}
ConsoleUtil.Write($"Dumping {name} {targetProcess.Id} to {dumpFilePath} ... ");
try
{
var args = $"-accepteula -ma {targetProcess.Id} {dumpFilePath}";
var processInfo = ProcessRunner.CreateProcess(procDumpExeFilePath, args, cancellationToken: cancellationToken);
var processOutput = await processInfo.Result;
// The exit code for procdump doesn't obey standard windows rules. It will return non-zero
// for successful cases (possibly returning the count of dumps that were written). Best
// backup is to test for the dump file being present.
if (File.Exists(dumpFilePath))
{
ConsoleUtil.WriteLine($"succeeded ({new FileInfo(dumpFilePath).Length} bytes)");
}
else
{
ConsoleUtil.WriteLine($"FAILED with {processOutput.ExitCode}");
ConsoleUtil.WriteLine($"{procDumpExeFilePath} {args}");
ConsoleUtil.WriteLine(string.Join(Environment.NewLine, processOutput.OutputLines));
}
}
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
{
ConsoleUtil.WriteLine("FAILED");
ConsoleUtil.WriteLine(ex.Message);
Logger.Log("Failed to dump process", ex);
}
}
if (options.CollectDumps && GetProcDumpInfo(options) is { } procDumpInfo)
{
ConsoleUtil.WriteLine("Roslyn Error: test timeout exceeded, dumping remaining processes");
var counter = 0;
foreach (var proc in ProcessUtil.GetProcessTree(Process.GetCurrentProcess()).OrderBy(x => x.ProcessName))
{
var dumpDir = procDumpInfo.DumpDirectory;
var dumpFilePath = Path.Combine(dumpDir, $"{proc.ProcessName}-{counter}.dmp");
await DumpProcess(proc, procDumpInfo.ProcDumpFilePath, dumpFilePath);
counter++;
}
}
WriteLogFile(options);
}
private static ProcDumpInfo? GetProcDumpInfo(Options options)
{
if (!string.IsNullOrEmpty(options.ProcDumpFilePath))
{
return new ProcDumpInfo(options.ProcDumpFilePath, options.LogFilesDirectory);
}
return null;
}
private static List<AssemblyInfo> GetAssemblyList(Options options)
{
var scheduler = new AssemblyScheduler(options);
var list = new List<AssemblyInfo>();
var assemblyPaths = GetAssemblyFilePaths(options);
foreach (var assemblyPath in assemblyPaths.OrderByDescending(x => new FileInfo(x.FilePath).Length))
{
list.AddRange(scheduler.Schedule(assemblyPath.FilePath).Select(x => new AssemblyInfo(x, assemblyPath.TargetFramework, options.Architecture)));
}
return list;
}
private static List<(string FilePath, string TargetFramework)> GetAssemblyFilePaths(Options options)
{
var list = new List<(string, string)>();
var binDirectory = Path.Combine(options.ArtifactsDirectory, "bin");
foreach (var project in Directory.EnumerateDirectories(binDirectory, "*", SearchOption.TopDirectoryOnly))
{
var name = Path.GetFileName(project);
var include = false;
foreach (var pattern in options.IncludeFilter)
{
if (Regex.IsMatch(name, pattern.Trim('\'', '"')))
{
include = true;
}
}
if (!include)
{
continue;
}
foreach (var pattern in options.ExcludeFilter)
{
if (Regex.IsMatch(name, pattern.Trim('\'', '"')))
{
continue;
}
}
var fileName = $"{name}.dll";
foreach (var targetFramework in options.TargetFrameworks)
{
var fileContainingDirectory = Path.Combine(project, options.Configuration, targetFramework);
var filePath = Path.Combine(fileContainingDirectory, fileName);
if (File.Exists(filePath))
{
list.Add((filePath, targetFramework));
}
else if (Directory.Exists(fileContainingDirectory) && Directory.GetFiles(fileContainingDirectory, searchPattern: "*.UnitTests.dll") is { Length: > 0 } matches)
{
// If the unit test assembly name doesn't match the project folder name, but still matches our "unit test" name pattern, we want to run it.
// If more than one such assembly is present in a project output folder, we assume something is wrong with the build configuration.
// For example, one unit test project might be referencing another unit test project.
if (matches.Length > 1)
{
var message = $"Multiple unit test assemblies found in '{fileContainingDirectory}'. Please adjust the build to prevent this. Matches:{Environment.NewLine}{string.Join(Environment.NewLine, matches)}";
throw new Exception(message);
}
list.Add((matches[0], targetFramework));
}
}
}
return list;
}
private static void DisplayResults(Display display, ImmutableArray<TestResult> testResults)
{
foreach (var cur in testResults)
{
var open = false;
switch (display)
{
case Display.All:
open = true;
break;
case Display.None:
open = false;
break;
case Display.Succeeded:
open = cur.Succeeded;
break;
case Display.Failed:
open = !cur.Succeeded;
break;
}
if (open)
{
ProcessRunner.OpenFile(cur.ResultsDisplayFilePath);
}
}
}
private static ProcessTestExecutor CreateTestExecutor(Options options)
{
var testExecutionOptions = new TestExecutionOptions(
dotnetFilePath: options.DotnetFilePath,
procDumpInfo: options.CollectDumps ? GetProcDumpInfo(options) : null,
testResultsDirectory: options.TestResultsDirectory,
testFilter: options.TestFilter,
includeHtml: options.IncludeHtml,
retry: options.Retry);
return new ProcessTestExecutor(testExecutionOptions);
}
/// <summary>
/// Checks the total size of dump file and removes files exceeding a limit.
/// </summary>
private static void CheckTotalDumpFilesSize()
{
var directory = Directory.GetCurrentDirectory();
var dumpFiles = Directory.EnumerateFiles(directory, "*.dmp", SearchOption.AllDirectories).ToArray();
long currentTotalSize = 0;
foreach (var dumpFile in dumpFiles)
{
long fileSizeInMegabytes = (new FileInfo(dumpFile).Length / 1024) / 1024;
currentTotalSize += fileSizeInMegabytes;
if (currentTotalSize > MaxTotalDumpSizeInMegabytes)
{
ConsoleUtil.WriteLine($"Deleting '{dumpFile}' because we have exceeded our total dump size of {MaxTotalDumpSizeInMegabytes} megabytes.");
File.Delete(dumpFile);
}
}
}
}
}
| 40.609639 | 227 | 0.540379 | [
"Apache-2.0"
] | CyberSys/roslyn | src/Tools/Source/RunTests/Program.cs | 16,855 | C# |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;
namespace System.Security.Policy
{
public static class __UnionCodeGroup
{
public static IObservable<System.Security.Policy.PolicyStatement> Resolve(
this IObservable<System.Security.Policy.UnionCodeGroup> UnionCodeGroupValue,
IObservable<System.Security.Policy.Evidence> evidence)
{
return Observable.Zip(UnionCodeGroupValue, evidence,
(UnionCodeGroupValueLambda, evidenceLambda) => UnionCodeGroupValueLambda.Resolve(evidenceLambda));
}
public static IObservable<System.Security.Policy.CodeGroup> ResolveMatchingCodeGroups(
this IObservable<System.Security.Policy.UnionCodeGroup> UnionCodeGroupValue,
IObservable<System.Security.Policy.Evidence> evidence)
{
return Observable.Zip(UnionCodeGroupValue, evidence,
(UnionCodeGroupValueLambda, evidenceLambda) =>
UnionCodeGroupValueLambda.ResolveMatchingCodeGroups(evidenceLambda));
}
public static IObservable<System.Security.Policy.CodeGroup> Copy(
this IObservable<System.Security.Policy.UnionCodeGroup> UnionCodeGroupValue)
{
return Observable.Select(UnionCodeGroupValue,
(UnionCodeGroupValueLambda) => UnionCodeGroupValueLambda.Copy());
}
public static IObservable<System.String> get_MergeLogic(
this IObservable<System.Security.Policy.UnionCodeGroup> UnionCodeGroupValue)
{
return Observable.Select(UnionCodeGroupValue,
(UnionCodeGroupValueLambda) => UnionCodeGroupValueLambda.MergeLogic);
}
}
} | 39.888889 | 114 | 0.700836 | [
"MIT"
] | RixianOpenTech/RxWrappers | Source/Wrappers/mscorlib/System.Security.Policy.UnionCodeGroup.cs | 1,795 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using Elastic.Elasticsearch.Xunit.XunitPlumbing;
using Nest;
using System.ComponentModel;
namespace Examples.XPack.Docs.En.RestApi.Security
{
public class GetTokensPage : ExampleBase
{
[U(Skip = "Example not implemented")]
[Description("../../x-pack/docs/en/rest-api/security/get-tokens.asciidoc:111")]
public void Line111()
{
// tag::cee591c1fc70d4f180c623a3a6d07755[]
var response0 = new SearchResponse<object>();
// end::cee591c1fc70d4f180c623a3a6d07755[]
response0.MatchesExample(@"POST /_security/oauth2/token
{
""grant_type"" : ""client_credentials""
}");
}
[U(Skip = "Example not implemented")]
[Description("../../x-pack/docs/en/rest-api/security/get-tokens.asciidoc:146")]
public void Line146()
{
// tag::e1337c6b76defd5a46d05220f9d9c9fc[]
var response0 = new SearchResponse<object>();
// end::e1337c6b76defd5a46d05220f9d9c9fc[]
response0.MatchesExample(@"POST /_security/oauth2/token
{
""grant_type"" : ""password"",
""username"" : ""test_admin"",
""password"" : ""x-pack-test-password""
}");
}
[U(Skip = "Example not implemented")]
[Description("../../x-pack/docs/en/rest-api/security/get-tokens.asciidoc:176")]
public void Line176()
{
// tag::1873f8a8a291e6fcd6c1c83ea6928759[]
var response0 = new SearchResponse<object>();
// end::1873f8a8a291e6fcd6c1c83ea6928759[]
response0.MatchesExample(@"POST /_security/oauth2/token
{
""grant_type"": ""refresh_token"",
""refresh_token"": ""vLBPvmAB6KvwvJZr27cS""
}");
}
}
}
| 29.830508 | 81 | 0.690341 | [
"Apache-2.0"
] | Atharvpatel21/elasticsearch-net | tests/Examples/XPack/Docs/En/RestApi/Security/GetTokensPage.cs | 1,760 | C# |
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
namespace FastDFSCore.Client
{
/// <summary>FastDFSCore配置信息帮助类
/// </summary>
public static class FDFSOptionHelper
{
/// <summary>从文件中读取配置信息
/// </summary>
public static FDFSOption GetFDFSOption(string file)
{
if (!File.Exists(file))
{
throw new ArgumentException("配置文件不存在");
}
var option = new FDFSOption();
var doc = new XmlDocument();
XmlReaderSettings settings = new XmlReaderSettings
{
IgnoreComments = true //忽略文档里面的注释
};
XmlReader reader = XmlReader.Create(file, settings);
doc.Load(reader);
XmlNode root = doc.SelectSingleNode("FDFSClient");
var allTrackers = root.SelectSingleNode("Trackers");
//全部的Tracker节点
var trackerNodes = allTrackers.SelectNodes("Tracker");
foreach (XmlNode trackerNode in trackerNodes)
{
var ipAddress = IPAddress.Parse(trackerNode.SelectSingleNode("IPAddress").InnerText);
var port = int.Parse(trackerNode.SelectSingleNode("Port").InnerText);
option.Trackers.Add(new IPEndPoint(ipAddress, port));
}
//charset
option.Charset = Encoding.GetEncoding(root.SelectSingleNode("Charset").InnerText);
//ConnectionTimeout
option.ConnectionTimeout = int.Parse(root.SelectSingleNode("ConnectionTimeout").InnerText);
//ConnectionLifeTime
option.ConnectionLifeTime = int.Parse(root.SelectSingleNode("ConnectionLifeTime").InnerText);
//ScanTimeoutConnectionInterval
option.ScanTimeoutConnectionInterval= int.Parse(root.SelectSingleNode("ScanTimeoutConnectionInterval").InnerText);
//TrackerMaxConnection
option.TrackerMaxConnection = int.Parse(root.SelectSingleNode("TrackerMaxConnection").InnerText);
//StorageMaxConnection
option.StorageMaxConnection = int.Parse(root.SelectSingleNode("StorageMaxConnection").InnerText);
//LoggerName
option.LoggerName = root.SelectSingleNode("LoggerName").InnerText;
//tcp相关配置
option.TcpSetting = new TcpSetting();
//Tcp节点
var tcpNode = root.SelectSingleNode("TcpSetting");
//退出后指定时间内关闭(ms)
option.TcpSetting.QuietPeriodMilliSeconds = int.Parse(tcpNode.SelectSingleNode("QuietPeriodMilliSeconds").InnerText);
//关闭超时时间(s)
option.TcpSetting.CloseTimeoutSeconds = int.Parse(tcpNode.SelectSingleNode("CloseTimeoutSeconds").InnerText);
//高水位
option.TcpSetting.WriteBufferHighWaterMark = int.Parse(tcpNode.SelectSingleNode("WriteBufferHighWaterMark").InnerText);
//低水位
option.TcpSetting.WriteBufferLowWaterMark = int.Parse(tcpNode.SelectSingleNode("WriteBufferLowWaterMark").InnerText);
//接收socket缓存大小
option.TcpSetting.SoRcvbuf = int.Parse(tcpNode.SelectSingleNode("SoRcvbuf").InnerText);
//发送socket缓存大小
option.TcpSetting.SoSndbuf = int.Parse(tcpNode.SelectSingleNode("SoSndbuf").InnerText);
//Tcp无延迟发送
option.TcpSetting.TcpNodelay = bool.Parse(tcpNode.SelectSingleNode("TcpNodelay").InnerText);
//重用端口号
option.TcpSetting.SoReuseaddr = bool.Parse(tcpNode.SelectSingleNode("SoReuseaddr").InnerText);
//关闭读取流
reader.Close();
return option;
}
/// <summary>将配置文件转换成xml字符串
/// </summary>
public static string ToXml(FDFSOption option)
{
try
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("<FDFSClient>");
sb.AppendLine(ParseNote("Trackers信息,可以配置多台"));
sb.AppendLine("<Trackers>");
foreach (var tracker in option.Trackers)
{
sb.AppendLine("<Tracker>");
sb.Append("<IPAddress>");
sb.Append(tracker.Address.ToIPv4Address());
sb.AppendLine("</IPAddress>");
sb.Append("<Port>");
sb.Append(tracker.Port);
sb.AppendLine("</Port>");
sb.AppendLine("</Tracker>");
}
sb.AppendLine("</Trackers>");
sb.AppendLine(ParseNote("编码"));
sb.Append("<Charset>");
sb.Append(option.Charset.BodyName);
sb.AppendLine("</Charset>");
sb.AppendLine(ParseNote("连接超时时间(s)"));
sb.Append("<ConnectionTimeout>");
sb.Append(option.ConnectionTimeout);
sb.AppendLine("</ConnectionTimeout>");
sb.AppendLine(ParseNote("连接的有效时间(s)"));
sb.Append("<ConnectionLifeTime>");
sb.Append(option.ConnectionLifeTime);
sb.AppendLine("</ConnectionLifeTime>");
sb.AppendLine(ParseNote("查询超时的连接的时间间隔(s)"));
sb.Append("<ScanTimeoutConnectionInterval>");
sb.Append(option.ScanTimeoutConnectionInterval);
sb.AppendLine("</ScanTimeoutConnectionInterval>");
sb.AppendLine(ParseNote("最大Tracker连接数"));
sb.Append("<TrackerMaxConnection>");
sb.Append(option.TrackerMaxConnection);
sb.AppendLine("</TrackerMaxConnection>");
sb.AppendLine(ParseNote("最大Storage连接数"));
sb.Append("<StorageMaxConnection>");
sb.Append(option.StorageMaxConnection);
sb.AppendLine("</StorageMaxConnection>");
sb.Append("<LoggerName>");
sb.Append(option.LoggerName);
sb.AppendLine("</LoggerName>");
//Tcp参数设置
sb.AppendLine("<TcpSetting>");
sb.AppendLine(ParseNote("退出后在指定时间内关闭(ms)"));
sb.Append("<QuietPeriodMilliSeconds>");
sb.Append(option.TcpSetting.QuietPeriodMilliSeconds);
sb.AppendLine("</QuietPeriodMilliSeconds>");
sb.AppendLine(ParseNote("超时关闭时间(s)"));
sb.Append("<CloseTimeoutSeconds>");
sb.Append(option.TcpSetting.CloseTimeoutSeconds);
sb.AppendLine("</CloseTimeoutSeconds>");
sb.AppendLine(ParseNote("高水位"));
sb.Append("<WriteBufferHighWaterMark>");
sb.Append(option.TcpSetting.WriteBufferHighWaterMark);
sb.AppendLine("</WriteBufferHighWaterMark>");
sb.AppendLine(ParseNote("低水位"));
sb.Append("<WriteBufferLowWaterMark>");
sb.Append(option.TcpSetting.WriteBufferLowWaterMark);
sb.AppendLine("</WriteBufferLowWaterMark>");
sb.AppendLine(ParseNote("接收的Socket缓存大小"));
sb.Append("<SoRcvbuf>");
sb.Append(option.TcpSetting.SoRcvbuf);
sb.AppendLine("</SoRcvbuf>");
sb.AppendLine(ParseNote("发送的Socket缓存大小"));
sb.Append("<SoSndbuf>");
sb.Append(option.TcpSetting.SoSndbuf);
sb.AppendLine("</SoSndbuf>");
sb.AppendLine(ParseNote("Tcp发送无延迟"));
sb.Append("<TcpNodelay>");
sb.Append(option.TcpSetting.TcpNodelay);
sb.AppendLine("</TcpNodelay>");
sb.AppendLine(ParseNote("是否重用端口"));
sb.Append("<SoReuseaddr>");
sb.Append(option.TcpSetting.SoReuseaddr);
sb.AppendLine("</SoReuseaddr>");
sb.AppendLine("</TcpSetting>");
sb.AppendLine("</FDFSClient>");
return sb.ToString();
}
catch (Exception ex)
{
throw new Exception($"生成Xml配置文件出错!{ex.Message}", ex);
}
}
private static string ParseNote(string note)
{
return $"<![CDATA[{note}]]>";
}
}
}
| 40.42439 | 131 | 0.563654 | [
"MIT"
] | SunGram/FastDFSCore | src/FastDFSCore/Client/FDFSOptionHelper.cs | 8,707 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Microsoft.Build.Shared.FileSystem;
using Microsoft.Build.Utilities;
using CodeDomProvider = System.CodeDom.Compiler.CodeDomProvider;
using MSBuildProcessorArchitecture = Microsoft.Build.Utilities.ProcessorArchitecture;
namespace Microsoft.Build.Tasks
{
/// <summary>
/// This class defines the "GenerateResource" MSBuild task, which enables using resource APIs
/// to transform resource files.
/// </summary>
/// <comment>See GenerateResource.cs for the source code to the GenerateResource task; this file
/// just contains the nested internal ResGen task</comment>
public sealed partial class GenerateResource : TaskExtension
{
/// <summary>
/// Defines the "ResGen" MSBuild task, which enables using ResGen.exe
/// to generate strongly-typed resource classes and convert resource
/// files from one format to another.
/// </summary>
internal class ResGen : ToolTaskExtension
{
#region Properties
/*
Microsoft (R) .NET Resource Generator
[Microsoft .Net Framework, Version 4.0.10719.0]
Copyright (c) Microsoft Corporation. All rights reserved.
Usage:
ResGen inputFile.ext [outputFile.ext] [/str:lang[,namespace[,class[,file]]]]
ResGen [options] /compile inputFile1.ext[,outputFile1.resources] [...]
Where .ext is .resX, .restext, .txt, or .resources
Converts files from one resource format to another. If the output
filename is not specified, inputFile.resources will be used.
Options:
/compile Converts a list of resource files from one format to another
in one bulk operation. By default, it converts into .resources
files, using inputFile[i].resources for the output file name.
/str:<language>[,<namespace>[,<class name>[,<file name>]]]]
Creates a strongly-typed resource class in the specified
programming language using CodeDOM. In order for the strongly
typed resource class to work properly, the name of your output
file without the .resources must match the
[namespace.]classname of your strongly typed resource class.
You may need to rename your output file before using it or
embedding it into an assembly.
/useSourcePath Use each source file's directory as the current directory
for resolving relative file paths.
/publicClass Create the strongly typed resource class as a public class.
This option is ignored if the /str: option is not used.
/r:<assembly> Load types from these assemblies. A ResX file with a previous
version of a type will use the one in this assembly, when set.
/define:A[,B] For #ifdef support in .ResText files, pass a comma-separated
list of symbols. ResText files can use "#ifdef A" or "#if !B".
Miscellaneous:
@<file> Read response file for more options. At most one response file
may be specified, and its entries must be line-separated.
.restext & .txt files have this format:
# Use # at the beginning of a line for a comment character.
name=value
more elaborate name=value
Example response file contents:
# Use # at the beginning of a line for a comment character.
/useSourcePath
/compile
file1.resx,file1.resources
file2.resx,file2.resources
Language names valid for the /str:<language> option are:
c#, cs, csharp, vb, vbs, visualbasic, vbscript, js, jscript, javascript, vj#, vjs, vjsharp, c++, mc, cpp
*/
/// <summary>
/// Files being passed to ResGen.exe to be converted to a different resource format.
/// If a strongly typed resource class is being created, only one file may be
/// passed to InputFiles at a time.
/// </summary>
public ITaskItem[] InputFiles
{
get => (ITaskItem[])Bag[nameof(InputFiles)];
set => Bag[nameof(InputFiles)] = value;
}
/// <summary>
/// Should be the same length as InputFiles or null. If null, the files output
/// by ResGen.exe will be named "inputFiles[i].resources". Otherwise, the
/// extensions on the output filesnames indicate which format the corresponding
/// input file will be translated to.
/// </summary>
public ITaskItem[] OutputFiles
{
get => (ITaskItem[])Bag[nameof(OutputFiles)];
set => Bag[nameof(OutputFiles)] = value;
}
/// <summary>
/// Specifies whether the strongly typed class should be created public (with public methods)
/// instead of the default internal. Analogous to resgen.exe's /publicClass switch.
/// </summary>
public bool PublicClass
{
get => GetBoolParameterWithDefault(nameof(PublicClass), false);
set => Bag[nameof(PublicClass)] = value;
}
/// <summary>
/// Resolves types in ResX files (XML resources) for Strongly Typed Resources
/// </summary>
public ITaskItem[] References
{
get => (ITaskItem[])Bag[nameof(References)];
set => Bag[nameof(References)] = value;
}
/// <summary>
/// Path to the SDK directory where ResGen.exe can be found
/// </summary>
public string SdkToolsPath
{
get => (string)Bag[nameof(SdkToolsPath)];
set => Bag[nameof(SdkToolsPath)] = value;
}
/// <summary>
/// The language to use when generating the class source for the strongly typed resource.
/// This parameter must match exactly one of the languages used by the CodeDomProvider.
/// </summary>
public string StronglyTypedLanguage
{
get => (string)Bag[nameof(StronglyTypedLanguage)];
set => Bag[nameof(StronglyTypedLanguage)] = value;
}
/// <summary>
/// Specifies the namespace to use for the generated class source for the
/// strongly typed resource. If left blank, no namespace is used.
/// </summary>
public string StronglyTypedNamespace
{
get => (string)Bag[nameof(StronglyTypedNamespace)];
set => Bag[nameof(StronglyTypedNamespace)] = value;
}
/// <summary>
/// Specifies the class name for the strongly typed resource class. If left blank, the base
/// name of the resource file is used.
/// </summary>
public string StronglyTypedClassName
{
get => (string)Bag[nameof(StronglyTypedClassName)];
set => Bag[nameof(StronglyTypedClassName)] = value;
}
/// <summary>
/// Specifies the filename for the source file. If left blank, the name of the class is
/// used as the base filename, with the extension dependent on the language.
/// </summary>
public string StronglyTypedFileName
{
get => (string)Bag[nameof(StronglyTypedFileName)];
set => Bag[nameof(StronglyTypedFileName)] = value;
}
/// <summary>
/// Indicates whether the resource reader should use the source file's directory to
/// resolve relative file paths.
/// </summary>
public bool UseSourcePath
{
get => GetBoolParameterWithDefault(nameof(UseSourcePath), false);
set => Bag[nameof(UseSourcePath)] = value;
}
#endregion // Properties
#region ToolTask Members
/// <summary>
/// Returns the name of the tool to execute
/// </summary>
protected override string ToolName => "resgen.exe";
/// <summary>
/// Tracker.exe wants Unicode response files, and ResGen.exe doesn't care,
/// so make them Unicode across the board.
/// </summary>
/// <comment>
/// We no longer use Tracker.exe in ResGen, but given that as ResGen doesn't care,
/// there doesn't really seem to be a particular reason to change it back, either...
/// </comment>
protected override Encoding ResponseFileEncoding => Encoding.Unicode;
/// <summary>
/// Invokes the ToolTask with the given parameters
/// </summary>
/// <returns>True if the task succeeded, false otherwise</returns>
public override bool Execute()
{
// If there aren't any input resources, well, we've already succeeded!
if (IsNullOrEmpty(InputFiles))
{
Log.LogMessageFromResources(MessageImportance.Low, "ResGen.NoInputFiles");
return !Log.HasLoggedErrors;
}
if (IsNullOrEmpty(OutputFiles))
{
GenerateOutputFileNames();
}
bool success;
// if command line is too long, fail
string commandLineCommands = GenerateCommandLineCommands();
// when comparing command line length, need to add one for leading space added between command arguments and tool name
if (!string.IsNullOrEmpty(commandLineCommands) && (commandLineCommands.Length + 1) > s_maximumCommandLength)
{
Log.LogErrorWithCodeFromResources("ResGen.CommandTooLong", commandLineCommands.Length);
success = false;
}
else
{
// Use ToolTaskExtension's Execute()
success = base.Execute();
}
if (String.IsNullOrEmpty(StronglyTypedLanguage))
{
if (!success)
{
// One or more of the generated resources was not, in fact generated --
// only keep in OutputFiles the ones that actually exist.
ITaskItem[] outputFiles = OutputFiles;
var successfullyGenerated = new List<ITaskItem>();
for (int i = 0; i < outputFiles.Length; i++)
{
if (FileSystems.Default.FileExists(outputFiles[i].ItemSpec))
{
successfullyGenerated.Add(outputFiles[i]);
}
}
OutputFiles = successfullyGenerated.ToArray();
}
}
else
{
ITaskItem outputFile = OutputFiles[0];
// if the resource generation was unsuccessful, check to see that the resource file
// was in fact generated
if (!success)
{
if (!FileSystems.Default.FileExists(outputFile.ItemSpec))
{
OutputFiles = Array.Empty<ITaskItem>();
}
}
// Default the class name if we need to - regardless of whether the STR was successfully generated
if (StronglyTypedClassName == null)
{
StronglyTypedClassName = Path.GetFileNameWithoutExtension(outputFile.ItemSpec);
}
// Default the filename if we need to - regardless of whether the STR was successfully generated
if (StronglyTypedFileName == null)
{
CodeDomProvider provider;
try
{
provider = CodeDomProvider.CreateProvider(StronglyTypedLanguage);
}
catch (System.Configuration.ConfigurationException)
{
// If the language can't be found, then ResGen.exe will already have
// logged an appropriate error.
return false;
}
catch (System.Security.SecurityException)
{
// If the language can't be found, then ResGen.exe will already have
// logged an appropriate error.
return false;
}
StronglyTypedFileName = ProcessResourceFiles.GenerateDefaultStronglyTypedFilename(provider, outputFile.ItemSpec);
}
}
return success && !Log.HasLoggedErrors;
}
/// <summary>
/// Fills the provided CommandLineBuilderExtension with all the command line options used when
/// executing this tool that can go into a response file.
/// </summary>
/// <comments>
/// ResGen 3.5 and earlier doesn't support response files, but ResGen 4.0 and later does.
/// </comments>
/// <param name="commandLine">Gets filled with command line options</param>
protected internal override void AddResponseFileCommands(CommandLineBuilderExtension commandLine)
{
string pathToResGen = GenerateResGenFullPath();
// Only do anything if we can actually use response files
if (pathToResGen != null
&& NativeMethodsShared.IsWindows
&& !pathToResGen.Equals(
ToolLocationHelper.GetPathToDotNetFrameworkSdkFile(
"resgen.exe",
TargetDotNetFrameworkVersion.Version35),
StringComparison.OrdinalIgnoreCase)
&& String.IsNullOrEmpty(StronglyTypedLanguage))
{
// 4.0 resgen.exe does support response files, so we can return the resgen arguments here!
var resGenArguments = new CommandLineBuilderExtension();
GenerateResGenCommands(resGenArguments, true /* arguments must be line-delimited */);
commandLine.AppendTextUnquoted(resGenArguments.ToString());
}
else
{
// return nothing -- if it's not 4.0, or if we're building strongly typed resources, we assume that,
// as far as ToolTask is concerned at least, response files are not supported.
}
}
/// <summary>
/// Fills the provided CommandLineBuilderExtension with all the command line options used when
/// executing this tool that must go on the command line
/// </summary>
/// <comments>
/// Has to be command line commands because ResGen 3.5 and earlier don't know about
/// response files.
/// </comments>
/// <param name="commandLine">Gets filled with command line options</param>
protected internal override void AddCommandLineCommands(CommandLineBuilderExtension commandLine)
{
ErrorUtilities.VerifyThrow(!IsNullOrEmpty(InputFiles), "If InputFiles is empty, the task should have returned before reaching this point");
var resGenArguments = new CommandLineBuilderExtension();
GenerateResGenCommands(resGenArguments, false /* don't line-delimit arguments; spaces are just fine */);
string pathToResGen = GenerateResGenFullPath();
if (pathToResGen != null &&
NativeMethodsShared.IsWindows &&
!pathToResGen.Equals(NativeMethodsShared.GetLongFilePath(ToolLocationHelper.GetPathToDotNetFrameworkSdkFile("resgen.exe", TargetDotNetFrameworkVersion.Version35)), StringComparison.OrdinalIgnoreCase) &&
String.IsNullOrEmpty(StronglyTypedLanguage))
{
// 4.0 resgen.exe does support response files (at least as long as you're not building an STR), so we can
// make use of them here by returning nothing!
}
else
{
// otherwise, the toolname is ResGen.exe and we just need the resgen arguments in CommandLineCommands.
commandLine.AppendTextUnquoted(resGenArguments.ToString());
}
}
/// <summary>
/// Generates the full path to the tool being executed by this ToolTask
/// </summary>
/// <returns>A string containing the full path of this tool, or null if the tool was not found</returns>
protected override string GenerateFullPathToTool()
{
// Use ToolPath if it exists.
string pathToTool = GenerateResGenFullPath();
return pathToTool;
}
/// <summary>
/// Validates the parameters passed to the task
/// </summary>
/// <returns>True if parameters are valid</returns>
protected override bool ValidateParameters()
{
ErrorUtilities.VerifyThrow(!IsNullOrEmpty(InputFiles), "If InputFiles is empty, the task should have returned before reaching this point");
// make sure that if the output resources were set, they exactly match the number of input sources
if (!IsNullOrEmpty(OutputFiles) && (OutputFiles.Length != InputFiles.Length))
{
Log.LogErrorWithCodeFromResources("General.TwoVectorsMustHaveSameLength", InputFiles.Length, OutputFiles.Length, "InputFiles", "OutputFiles");
return false;
}
// Creating an STR is triggered merely by setting the language
if (!String.IsNullOrEmpty(StronglyTypedLanguage))
{
// Only a single Sources is allowed if you are generating STR.
// Otherwise, each STR class overwrites the previous one. In theory we could generate separate
// STR classes for each input, but then the class name and file name parameters would have to be vectors.
if (InputFiles.Length != 1)
{
Log.LogErrorWithCodeFromResources("ResGen.STRLanguageButNotExactlyOneSourceFile");
return false;
}
}
else
{
if (
!String.IsNullOrEmpty(StronglyTypedClassName) ||
!String.IsNullOrEmpty(StronglyTypedNamespace) ||
!String.IsNullOrEmpty(StronglyTypedFileName)
)
{
// We have no language to generate a STR, but nevertheless the user passed us a class,
// namespace, and/or filename. Let them know that they probably wanted to pass a language too.
Log.LogErrorWithCodeFromResources("ResGen.STRClassNamespaceOrFilenameWithoutLanguage");
return false;
}
}
// Verify that the ToolPath exists -- if the tool doesn't exist in it
// we'll worry about that later
if ((String.IsNullOrEmpty(ToolPath) || !FileSystems.Default.DirectoryExists(ToolPath)) &&
(String.IsNullOrEmpty(SdkToolsPath) || !FileSystems.Default.DirectoryExists(SdkToolsPath)))
{
Log.LogErrorWithCodeFromResources("ResGen.SdkOrToolPathNotSpecifiedOrInvalid", SdkToolsPath ?? "", ToolPath ?? "");
return false;
}
return base.ValidateParameters();
}
#endregion // ToolTask Members
#region Helper methods
/// <summary>
/// Checks a string array for null or length zero. Does not check if
/// individual members are null
/// </summary>
/// <param name="value">The string array to check</param>
/// <returns>True if the array is null or has length zero</returns>
private static bool IsNullOrEmpty(ITaskItem[] value)
{
return value == null || value.Length == 0;
}
/// <summary>
/// If OutputFiles is null, we need to generate default output names
/// to pass to resgen.exe (which would generate the names on its own, but
/// then we wouldn't have access to them)
/// </summary>
private void GenerateOutputFileNames()
{
ErrorUtilities.VerifyThrow(!IsNullOrEmpty(InputFiles), "If InputFiles is empty, the task should have returned before reaching this point");
ITaskItem[] inputFiles = InputFiles;
ITaskItem[] outputFiles = new ITaskItem[inputFiles.Length];
// Set the default OutputFiles values
for (int i = 0; i < inputFiles.Length; i++)
{
if (inputFiles[i] is ITaskItem2 inputFileAsITaskItem2)
{
outputFiles[i] = new TaskItem(Path.ChangeExtension(inputFileAsITaskItem2.EvaluatedIncludeEscaped, ".resources"));
}
else
{
outputFiles[i] = new TaskItem(Path.ChangeExtension(EscapingUtilities.Escape(inputFiles[i].ItemSpec), ".resources"));
}
}
Bag[nameof(OutputFiles)] = outputFiles;
}
/// <summary>
/// Generates the full path to ResGen.exe.
/// </summary>
/// <returns>The path to ResGen.exe, or null.</returns>
private string GenerateResGenFullPath()
{
// Use ToolPath if it exists.
var pathToTool = (string)Bag["ToolPathWithFile"];
if (pathToTool == null)
{
// First see if the user has set ToolPath
if (ToolPath != null)
{
pathToTool = Path.Combine(ToolPath, ToolExe);
if (!FileSystems.Default.FileExists(pathToTool))
{
pathToTool = null;
}
}
// If it still hasn't been found, try to generate the appropriate path.
if (pathToTool == null)
{
pathToTool = SdkToolsPathUtility.GeneratePathToTool
(
SdkToolsPathUtility.FileInfoExists,
MSBuildProcessorArchitecture.CurrentProcessArchitecture,
SdkToolsPath,
ToolExe,
Log,
true /* log errors and warnings */
);
pathToTool = NativeMethodsShared.GetLongFilePath(pathToTool);
}
// And then set it for future reference. If it's still null, there's nothing else
// we can do, and we've already logged an appropriate error.
Bag["ToolPathWithFile"] = pathToTool;
}
return pathToTool;
}
/// <summary>
/// Generate the command line to be passed to resgen.exe, sans the path to the tool.
/// </summary>
private void GenerateResGenCommands(CommandLineBuilderExtension resGenArguments, bool useForResponseFile)
{
resGenArguments ??= new CommandLineBuilderExtension();
if (IsNullOrEmpty(OutputFiles))
{
GenerateOutputFileNames();
}
// Append boolean flags if requested
string useSourcePathSwitch = "/useSourcePath" + (useForResponseFile ? "\n" : String.Empty);
string publicClassSwitch = "/publicClass" + (useForResponseFile ? "\n" : String.Empty);
resGenArguments.AppendWhenTrue(useSourcePathSwitch, Bag, "UseSourcePath");
resGenArguments.AppendWhenTrue(publicClassSwitch, Bag, "PublicClass");
// append the references, if any
if (References != null)
{
foreach (ITaskItem reference in References)
{
// ResGen.exe response files frown on quotes in filenames, even if there are
// spaces in the names of the files.
if (useForResponseFile && reference != null)
{
resGenArguments.AppendTextUnquoted("/r:");
resGenArguments.AppendTextUnquoted(reference.ItemSpec);
resGenArguments.AppendTextUnquoted("\n");
}
else
{
resGenArguments.AppendSwitchIfNotNull("/r:", reference);
}
}
}
if (String.IsNullOrEmpty(StronglyTypedLanguage))
{
// append the compile switch
resGenArguments.AppendSwitch("/compile" + (useForResponseFile ? "\n" : String.Empty));
// append the resources to compile
if (InputFiles?.Length > 0)
{
ITaskItem[] inputFiles = InputFiles;
ITaskItem[] outputFiles = OutputFiles;
for (int i = 0; i < inputFiles.Length; ++i)
{
if (useForResponseFile)
{
// ResGen.exe response files frown on quotes in filenames, even if there are
// spaces in the names of the files.
if (inputFiles[i] != null && outputFiles[i] != null)
{
resGenArguments.AppendTextUnquoted(inputFiles[i].ItemSpec);
resGenArguments.AppendTextUnquoted(",");
resGenArguments.AppendTextUnquoted(outputFiles[i].ItemSpec);
resGenArguments.AppendTextUnquoted("\n");
}
}
else
{
resGenArguments.AppendFileNamesIfNotNull
(
new[] { inputFiles[i], outputFiles[i] },
","
);
}
}
}
}
else
{
// append the resource to compile
resGenArguments.AppendFileNamesIfNotNull(InputFiles, " ");
resGenArguments.AppendFileNamesIfNotNull(OutputFiles, " ");
// append the strongly-typed resource details
resGenArguments.AppendSwitchIfNotNull
(
"/str:",
new[] { StronglyTypedLanguage, StronglyTypedNamespace, StronglyTypedClassName, StronglyTypedFileName },
","
);
}
}
#endregion // Helper methods
}
}
}
| 46.665079 | 222 | 0.51978 | [
"MIT"
] | 0xced/msbuild | src/Tasks/ResGen.cs | 29,401 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using Orleans;
using Squidex.Log;
namespace Squidex.Infrastructure.Orleans
{
public sealed class LoggingFilter : IIncomingGrainCallFilter
{
private readonly ISemanticLog log;
public LoggingFilter(ISemanticLog log)
{
this.log = log;
}
public async Task Invoke(IIncomingGrainCallContext context)
{
var name = $"Grain/{context.Grain?.GetType().Name}/{context.ImplementationMethod?.Name}";
using (Telemetry.Activities.StartActivity(name))
{
try
{
await context.Invoke();
}
catch (DomainException ex)
{
if (ex.InnerException != null)
{
Log(context, ex.InnerException);
}
throw;
}
catch (Exception ex)
{
Log(context, ex);
throw;
}
}
}
private void Log(IIncomingGrainCallContext context, Exception ex)
{
log.LogError(ex, w => w
.WriteProperty("action", "GrainInvoked")
.WriteProperty("status", "Failed")
.WriteProperty("grain", context.Grain.ToString())
.WriteProperty("grainMethod", context.ImplementationMethod.ToString()));
}
}
}
| 31.135593 | 101 | 0.438214 | [
"MIT"
] | Appleseed/squidex | backend/src/Squidex.Infrastructure/Orleans/LoggingFilter.cs | 1,839 | C# |
namespace Zhigly.Code.API
{
public class Recaptcha
{
public const string SiteKey = "Enter Recaptcha Site Key Here";
public const string Secret = "Enter Recaptcha Secret Here";
private const string Url = "https://www.google.com/recaptcha/api/siteverify";
public static string GetURL(string response)
{
string url = Url;
url += "?secret=" + Secret;
url += "&response=" + response;
return url;
}
public string Success { get; set; }
}
} | 26.714286 | 85 | 0.56328 | [
"MIT"
] | AlanMorel/zhigly | Zhigly/Zhigly/Code/API/Recaptcha.cs | 563 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
namespace HillPigeon.MvcAttributes
{
/// <summary>
/// Identifies an action that supports the HTTP GET method.
/// </summary>
public class HttpGetAttribute : HttpMethodAttribute
{
private static readonly IEnumerable<string> _supportedMethods = new [] { "GET" };
/// <summary>
/// Creates a new <see cref="HttpGetAttribute"/>.
/// </summary>
public HttpGetAttribute()
: base(_supportedMethods)
{
}
/// <summary>
/// Creates a new <see cref="HttpGetAttribute"/> with the given route template.
/// </summary>
/// <param name="template">The route template. May not be null.</param>
public HttpGetAttribute(string template)
: base(_supportedMethods, template)
{
if (template == null)
{
throw new ArgumentNullException(nameof(template));
}
}
}
} | 31.621622 | 111 | 0.600855 | [
"MIT"
] | AClumsy/HillPigeon | src/HillPigeon.Orleans/MvcAttributes/HttpGetAttribute.cs | 1,170 | C# |
using System.Collections.Generic;
using ActionGameFramework.Audio;
using Core.Health;
using TowerDefense.Agents;
using UnityEngine;
namespace TowerDefense.Level
{
/// <summary>
/// A class representing the home base that players must defend
/// </summary>
public class PlayerHomeBase : DamageableBehaviour
{
/// <summary>
/// The particle system when an attack is charging
/// </summary>
public ParticleSystem chargePfx;
/// <summary>
/// Sound to play when charge effect starts
/// </summary>
public RandomAudioSource chargeSound;
/// <summary>
/// The particle system for an attack
/// </summary>
public ParticleSystem attackPfx;
/// <summary>
/// Sound to play when attack effect starts
/// </summary>
public RandomAudioSource attackSound;
/// <summary>
/// The current Agents within the home base attack zone
/// </summary>
protected List<Agent> m_CurrentAgentsInside = new List<Agent>();
/// <summary>
/// Subscribes to damaged event
/// </summary>
protected virtual void Start()
{
configuration.damaged += OnDamaged;
}
/// <summary>
/// Unsubscribes to damaged event
/// </summary>
protected virtual void OnDestroy()
{
configuration.damaged -= OnDamaged;
}
/// <summary>
/// Plays <see cref="attackPfx"/> if assigned
/// </summary>
protected virtual void OnDamaged(HealthChangeInfo obj)
{
if (attackPfx != null)
{
attackPfx.Play();
}
if (attackSound != null)
{
attackSound.PlayRandomClip();
}
}
/// <summary>
/// Adds triggered Agent to tracked Agents, subscribes to Agent's
/// removed event and plays pfx
/// </summary>
/// <param name="other">Triggered collider</param>
void OnTriggerEnter(Collider other)
{
var homeBaseAttacker = other.GetComponent<HomeBaseAttacker>();
if (homeBaseAttacker == null)
{
return;
}
m_CurrentAgentsInside.Add(homeBaseAttacker.agent);
homeBaseAttacker.agent.removed += OnAgentRemoved;
if (chargePfx != null)
{
chargePfx.Play();
}
if (chargeSound != null)
{
chargeSound.PlayRandomClip();
}
}
/// <summary>
/// If the entity that has entered the collider
/// has an <see cref="Agent"/> component on it
/// </summary>
void OnTriggerExit(Collider other)
{
var homeBaseAttacker = other.GetComponent<HomeBaseAttacker>();
if (homeBaseAttacker == null)
{
return;
}
RemoveTarget(homeBaseAttacker.agent);
}
/// <summary>
/// Removes Agent from tracked <see cref="m_CurrentAgentsInside"/>
/// </summary>
void OnAgentRemoved(DamageableBehaviour targetable)
{
targetable.removed -= OnAgentRemoved;
Agent attackingAgent = targetable as Agent;
RemoveTarget(attackingAgent);
}
/// <summary>
/// Removes <paramref name="agent"/> from <see cref="m_CurrentAgentsInside"/> and stops pfx
/// if there are no more <see cref="Agent"/>s
/// </summary>
/// <param name="agent">
/// The agent to remove
/// </param>
void RemoveTarget(Agent agent)
{
if (agent == null)
{
return;
}
m_CurrentAgentsInside.Remove(agent);
if (m_CurrentAgentsInside.Count == 0 && chargePfx != null)
{
chargePfx.Stop();
}
}
}
} | 23.333333 | 94 | 0.657453 | [
"MIT"
] | FriendlyUser/BattleTD | Assets/Scripts/TowerDefense/Level/PlayerHomeBase.cs | 3,222 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusinessEngine.Models
{
public class ProduitsBonLivraison
{
virtual public ProduitsBonLivraisonPK PKs { get; set; }
}
[Serializable]
public class ProduitsBonLivraisonPK
{
public int produitId { get; set; }
public int bonLivraisonId { get; set; }
public override bool Equals(object obj)
{
if (obj == null)
return false;
ProduitsBonLivraisonPK pk;
pk = (ProduitsBonLivraisonPK)obj;
if (pk == null)
return false;
if (produitId == pk.produitId && bonLivraisonId == pk.bonLivraisonId)
return true;
return false;
}
// override object.GetHashCode
public override int GetHashCode()
{
return (produitId + "|" + bonLivraisonId).GetHashCode();
}
}
}
| 24.095238 | 81 | 0.579051 | [
"Apache-2.0"
] | InnovLabs/InnovFishShop | BusinessEngine/Models/ProduitsBonLivraison.cs | 1,014 | C# |
using System;
using WindowsInput;
namespace GamepadMapper.Actuators
{
public class SendCharacterActuator : IAction
{
public SendCharacterActuator(char character, IKeyboardSimulator keyboard)
{
Character = character;
Keyboard = keyboard;
}
public char Character { get; }
public IKeyboardSimulator Keyboard { get; }
public void Execute()
{
Keyboard.TextEntry(Character);
}
}
}
| 20.5 | 81 | 0.605691 | [
"MIT"
] | EdonGashi/gamepad-mapper | src/GamepadMapper/Actuators/SendCharacterActuator.cs | 494 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Text.Json.Serialization.Converters
{
internal sealed class Int32Converter : JsonConverter<int>
{
public Int32Converter()
{
IsInternalConverterForNumberType = true;
}
public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return reader.GetInt32();
}
public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options)
{
// For performance, lift up the writer implementation.
writer.WriteNumberValue((long)value);
}
internal override int ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return reader.GetInt32WithQuotes();
}
internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, int value, JsonSerializerOptions options, bool isWritingExtensionDataProperty)
{
writer.WritePropertyName(value);
}
internal override int ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.String &&
(JsonNumberHandling.AllowReadingFromString & handling) != 0)
{
return reader.GetInt32WithQuotes();
}
return reader.GetInt32();
}
internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, int value, JsonNumberHandling handling)
{
if ((JsonNumberHandling.WriteAsString & handling) != 0)
{
writer.WriteNumberValueAsString(value);
}
else
{
// For performance, lift up the writer implementation.
writer.WriteNumberValue((long)value);
}
}
}
}
| 35.491525 | 156 | 0.637536 | [
"MIT"
] | 333fred/runtime | src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/Int32Converter.cs | 2,094 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using FluentAssertions;
using Xunit;
namespace Nett.Tests.Unit
{
[ExcludeFromCodeCoverage]
public sealed partial class TomlObjectFactoryTests
{
[Fact]
public void Update_WhenKeyDoesntExist_ThrowInvalidOperation()
{
// Act
Action a = () => this.updateThis.Update("noexisto", "newvalue");
// Assert
a.ShouldThrow<InvalidOperationException>().WithMessage("*noexisto*");
}
[Fact]
public void Update_WhenXSetToNewBoolValue_ChangesRowToThat()
{
// Act
const bool newValue = true;
this.updateThis.Update("x", newValue);
// Assert
this.updateThis.Get<bool>("x").Should().Be(newValue);
}
[Fact]
public void Update_WhenXSetToNewStringValue_ChangesRowToThat()
{
// Act
const string newValue = "newvalue";
this.updateThis.Update("x", newValue);
// Assert
this.updateThis.Get<string>("x").Should().Be(newValue);
}
[Fact]
public void Update_WhenXSetToNewIntValue_ChangesRowToThat()
{
// Act
this.updateThis.Update("x", 2);
// Assert
this.updateThis.Get<int>("x").Should().Be(2);
}
[Fact]
public void Update_WhenXSetToNewFloatValue_ChangesRowToThat()
{
// Act
const double newValue = 2.0;
this.updateThis.Update("x", newValue);
// Assert
this.updateThis.Get<double>("x").Should().Be(newValue);
}
[Fact]
public void Update_WhenXSetToNewTimespanValue_ChangesRowToThat()
{
// Act
TimeSpan newValue = TimeSpan.FromSeconds(1);
this.updateThis.Update("x", newValue);
// Assert
this.updateThis.Get<TimeSpan>("x").Should().Be(newValue);
}
[Fact]
public void Update_WhenXSetToNewDateTimeValue_ChangesRowToThat()
{
// Act
var newValue = DateTimeOffset.MaxValue;
this.updateThis.Update("x", newValue);
// Assert
this.updateThis.Get<DateTimeOffset>("x").Should().Be(newValue);
}
[Fact]
public void Update_WhenXSetToNewBoolArray_ChangesRowToThat()
{
// Act
var newValue = new List<bool>() { true, false };
this.updateThis.Update("x", newValue);
// Assert
this.updateThis.Get<List<bool>>("x").Should().Equal(newValue);
}
[Fact]
public void Update_WhenXSetToNewStringArray_ChangesRowToThat()
{
// Act
var newValue = new List<string>() { "X", "Y" };
this.updateThis.Update("x", newValue);
// Assert
this.updateThis.Get<List<string>>("x").Should().Equal(newValue);
}
[Fact]
public void Update_WhenXSetToNewLongArray_ChangesRowToThat()
{
// Act
var newValue = new List<long>() { 0, 1 };
this.updateThis.Update("x", newValue);
// Assert
this.updateThis.Get<List<long>>("x").Should().Equal(newValue);
}
[Fact]
public void Update_WhenXSetToNewIntArray_ChangesRowToThat()
{
// Act
var newValue = new List<int>() { 0, 1 };
this.updateThis.Update("x", newValue);
// Assert
this.updateThis.Get<List<int>>("x").Should().Equal(newValue);
}
[Fact]
public void Update_WhenXSetToNewDoubleArray_ChangesRowToThat()
{
// Act
var newValue = new List<double>() { 0, 1 };
this.updateThis.Update("x", newValue);
// Assert
this.updateThis.Get<List<double>>("x").Should().Equal(newValue);
}
[Fact]
public void Update_WhenXSetToNewFloatArray_ChangesRowToThat()
{
// Act
var newValue = new List<float>() { 0, 1 };
this.updateThis.Update("x", newValue);
// Assert
this.updateThis.Get<List<float>>("x").Should().Equal(newValue);
}
[Fact]
public void Update_WhenXSetToNewDateTimeOffsetArray_ChangesRowToThat()
{
// Act
var newValue = new List<DateTimeOffset>() { DateTimeOffset.MinValue, DateTimeOffset.MaxValue };
this.updateThis.Update("x", newValue);
// Assert
this.updateThis.Get<List<DateTimeOffset>>("x").Should().Equal(newValue);
}
[Fact]
public void Update_WhenXSetToNewDateTimeArray_ChangesRowToThat()
{
// Act
long ticks = new DateTime(2000, 1, 1).Ticks;
var newValue = new List<DateTime>() { new DateTime(ticks, DateTimeKind.Utc), new DateTime(ticks + 1, DateTimeKind.Utc) };
this.updateThis.Update("x", newValue);
// Assert
var val = this.updateThis.Get<List<DateTime>>("x");
this.updateThis.Get<List<DateTime>>("x").Should().Equal(newValue);
}
[Fact]
public void Update_WhenXSetToNewTimespanArray_ChangesRowToThat()
{
// Act
var newValue = new List<TimeSpan>() { TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2) };
this.updateThis.Update("x", newValue);
// Assert
this.updateThis.Get<List<TimeSpan>>("x").Should().Equal(newValue);
}
[Fact]
public void Update_WithFooClassListSource_UpdatesToTableArray()
{
// Act
var ta = this.updateThis.Update("x", FooClassList.List1);
// Assert
FooClassList.List1.AssertIs(this.updateThis["x"]);
}
[Fact]
public void Update_WhenXSetToNewValueObject_ChangesRowToThat()
{
// Act
var newValue = new FooStruct() { X = 1 };
this.updateThis.Update("x", newValue);
// Assert
this.updateThis.Get<FooStruct>("x").Should().Be(newValue);
}
[Fact]
public void Update_WithFooClass_UpdatesToTable()
{
// Act
this.updateThis.Update("x", FooClass.Foo1);
// Assert
FooClass.Foo1.AssertIs(this.updateThis["x"]);
}
[Fact]
public void Update_WithFooStruct_UpdatesToTable()
{
// Act
this.updateThis.Update("x", FooStruct.Foo1);
// Assert
FooStruct.Foo1.AssertIs(this.updateThis["x"]);
}
[Fact]
public void Update_WithFooDict_UpdatesToTable()
{
// Act
var u = this.updateThis.Update("x", FooDict.Dict1);
// Assert
FooDict.Dict1.AssertIs(this.updateThis["x"]);
FooDict.Dict1.AssertIs(u.Added);
}
[Fact]
public void Update_WithFooClassList_UpdatesToTableArray()
{
// Act
var ta = this.updateThis.Update("x", FooClassList.List1);
// Assert
FooClassList.List1.AssertIs(this.updateThis["x"]);
}
[Fact]
public void Update_WithFooStructList_UpdatesToTableArray()
{
// Act
var ta = this.updateThis.Update("x", FooStructList.List1);
// Assert
FooStructList.List1.AssertIs(this.updateThis["x"]);
}
[Fact]
public void Update_WithResultObject_ThrowsInvalidArg()
{
// Arrange
var r = this.updateThis.Update("x", false);
// Act
Action a = () => this.updateThis.Update("x", r);
// Assert
a.ShouldThrow<ArgumentException>();
}
}
}
| 29.182482 | 133 | 0.538394 | [
"MIT"
] | NZSmartie/Nett | Test/Nett.Tests/Unit/TomlObjectFactory.Update.Tests.cs | 7,998 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http.Features;
namespace Microsoft.AspNetCore.Mvc.Formatters
{
/// <summary>
/// Always copies the stream to the response, regardless of requested content type.
/// </summary>
public class StreamOutputFormatter : IOutputFormatter
{
/// <inheritdoc />
public bool CanWriteResult(OutputFormatterCanWriteContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
// Ignore the passed in content type, if the object is a Stream.
if (context.Object is Stream)
{
return true;
}
return false;
}
/// <inheritdoc />
public async Task WriteAsync(OutputFormatterWriteContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
using (var valueAsStream = ((Stream)context.Object))
{
var response = context.HttpContext.Response;
if (context.ContentType != null)
{
response.ContentType = context.ContentType.ToString();
}
var bufferingFeature = context.HttpContext.Features.Get<IHttpBufferingFeature>();
bufferingFeature?.DisableResponseBuffering();
await valueAsStream.CopyToAsync(response.Body);
}
}
}
}
| 30.362069 | 111 | 0.579216 | [
"Apache-2.0"
] | Karthik270290/Projects | src/Microsoft.AspNetCore.Mvc.Core/Formatters/StreamOutputFormatter.cs | 1,761 | C# |
using DG.Tweening;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using GameComponentAttributes;
using GameComponentAttributes.Attributes;
using TMPro;
using UnityEngine;
namespace LD48Project.UI {
public class EndgameWindow : GameComponent {
const string DepthDescTemplate = "Your max depth is: \n{0:.0}";
[NotNull] public TMP_Text DepthDescText;
[NotNull] public Button ReturnToMenuButton;
[NotNull] public CanvasGroup GameplayUI;
[NotNull] public Transform CenterPoint;
public void Init(float depth) {
DepthDescText.text = string.Format(DepthDescTemplate, depth);
ReturnToMenuButton.onClick.AddListener(() => SceneManager.LoadScene("StartMenu"));
GameplayUI.DOFade(0f, 0.5f);
transform.DOMove(CenterPoint.position, 1f);
}
void OnDestroy() {
ReturnToMenuButton.onClick.RemoveAllListeners();
}
}
} | 27.548387 | 85 | 0.763466 | [
"MIT"
] | shelhelix/LD48Project | Assets/Scripts/UI/EndgameWindow.cs | 856 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit;
using Microsoft.MixedReality.Toolkit.Input;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Examples.Demos
{
// Simple example script that subscribes to primary pointer changes and applies a cursor highlight to the current one.
[AddComponentMenu("Scripts/MRTK/Examples/PrimaryPointerHandlerExample")]
public class PrimaryPointerHandlerExample : MonoBehaviour
{
public GameObject CursorHighlight;
private void OnEnable()
{
CoreServices.InputSystem?.FocusProvider?.SubscribeToPrimaryPointerChanged(OnPrimaryPointerChanged, true);
}
private void OnPrimaryPointerChanged(IMixedRealityPointer oldPointer, IMixedRealityPointer newPointer)
{
if (CursorHighlight != null)
{
if (newPointer != null)
{
Transform parentTransform = newPointer.BaseCursor.TryGetMonoBehaviour(out MonoBehaviour baseCursor) ? baseCursor.transform : null;
// If there's no cursor try using the controller pointer transform instead
if (parentTransform == null)
{
if (newPointer.TryGetMonoBehaviour(out MonoBehaviour controllerPointer))
{
parentTransform = controllerPointer.transform;
}
}
if (parentTransform != null)
{
CursorHighlight.transform.SetParent(parentTransform, false);
CursorHighlight.SetActive(true);
return;
}
}
CursorHighlight.SetActive(false);
CursorHighlight.transform.SetParent(null, false);
}
}
private void OnDisable()
{
CoreServices.InputSystem?.FocusProvider?.UnsubscribeFromPrimaryPointerChanged(OnPrimaryPointerChanged);
OnPrimaryPointerChanged(null, null);
}
}
}
| 38.413793 | 151 | 0.585278 | [
"MIT"
] | HyperLethalVector/ProjectEsky-UnityIntegration | Assets/MRTK/Examples/Demos/Input/Scenes/PrimaryPointer/PrimaryPointerHandlerExample.cs | 2,228 | C# |
namespace FFXIVClientStructs.FFXIV.Component.GUI;
[StructLayout(LayoutKind.Explicit, Size = 0x24)]
public unsafe struct AtkUldComponentDataRadioButton
{
[FieldOffset(0x00)] public AtkUldComponentDataBase Base;
[FieldOffset(0x0C)] public fixed uint Nodes[4];
[FieldOffset(0x1C)] public uint TextId;
[FieldOffset(0x20)] public uint GroupId;
} | 35.8 | 60 | 0.773743 | [
"MIT"
] | AsgardXIV/FFXIVClientStructs | FFXIVClientStructs/FFXIV/Component/GUI/AtkUldComponentDataRadioButton.cs | 360 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Azos.Log;
using Azos.Conf;
namespace Azos.Apps.Volatile
{
/// <summary>
/// Defines a base provider that stores objects for ObjectStoreService class
/// </summary>
public abstract class ObjectStoreProvider : Service<ObjectStoreService>
{
#region CONSTS
#endregion
#region .ctor
protected ObjectStoreProvider(ObjectStoreService director) : base(director)
{
}
#endregion
#region Private Fields
#endregion
#region Public
public abstract IEnumerable<ObjectStoreEntry> LoadAll();
public abstract void Write(ObjectStoreEntry entry);
public abstract void Delete(ObjectStoreEntry entry);
#endregion
#region Protected
protected override void DoConfigure(IConfigSectionNode node)
{
base.DoConfigure(node);
}
protected void WriteLog(MessageType type, string message, string parameters, string from = null)
{
App.Log.Write(
new Log.Message
{
Text = message ?? string.Empty,
Type = type,
Topic = CoreConsts.OBJSTORESVC_PROVIDER_TOPIC,
From = from,
Parameters = parameters ?? string.Empty
});
}
#endregion
}
}
| 21.630137 | 104 | 0.545915 | [
"MIT"
] | chadfords/azos | src/Azos/Apps/Volatile/ObjectStoreProvider.cs | 1,579 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TextCellListCode.WinPhone")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TextCellListCode.WinPhone")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)] | 36.758621 | 84 | 0.746717 | [
"Apache-2.0"
] | aliozgur/xamarin-forms-book-samples | Chapter19/TextCellListCode/TextCellListCode/TextCellListCode.WinPhone/Properties/AssemblyInfo.cs | 1,067 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.cloudwf.Model.V20170328;
namespace Aliyun.Acs.cloudwf.Transform.V20170328
{
public class ListApRadioStatusResponseUnmarshaller
{
public static ListApRadioStatusResponse Unmarshall(UnmarshallerContext context)
{
ListApRadioStatusResponse listApRadioStatusResponse = new ListApRadioStatusResponse();
listApRadioStatusResponse.HttpResponse = context.HttpResponse;
listApRadioStatusResponse.RequestId = context.StringValue("ListApRadioStatus.RequestId");
listApRadioStatusResponse.Success = context.BooleanValue("ListApRadioStatus.Success");
listApRadioStatusResponse.Message = context.StringValue("ListApRadioStatus.Message");
listApRadioStatusResponse.Data = context.StringValue("ListApRadioStatus.Data");
listApRadioStatusResponse.ErrorCode = context.IntegerValue("ListApRadioStatus.ErrorCode");
listApRadioStatusResponse.ErrorMsg = context.StringValue("ListApRadioStatus.ErrorMsg");
return listApRadioStatusResponse;
}
}
}
| 42.555556 | 94 | 0.777023 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-cloudwf/Cloudwf/Transform/V20170328/ListApRadioStatusResponseUnmarshaller.cs | 1,915 | C# |
// Copyright (C) 2014 dot42
//
// Original filename: Android.Test.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Android.Test
{
/// <summary>
/// <para>This test case class provides a framework for testing a single ContentProvider and for testing your app code with an isolated content provider. Instead of using the system map of providers that is based on the manifests of other applications, the test case creates its own internal map. It then uses this map to resolve providers given an authority. This allows you to inject test providers and to null out providers that you do not want to use. </para><para>This test case also sets up the following mock objects: </para><para><ul><li><para>An android.test.IsolatedContext that stubs out Context methods that might affect the rest of the running system, while allowing tests to do real file and database work. </para></li><li><para>A android.test.mock.MockContentResolver that provides the functionality of a regular content resolver, but uses IsolatedContext. It stubs out ContentResolver#notifyChange(Uri, ContentObserver, boolean) to prevent the test from affecting the running system. </para></li><li><para>An instance of the provider under test, running in an IsolatedContext. </para></li></ul></para><para>This framework is set up automatically by the base class' setUp() method. If you override this method, you must call the super method as the first statement in your override. </para><para>In order for their tests to be run, concrete subclasses must provide their own constructor with no arguments. This constructor must call ProviderTestCase2(Class, String) as its first operation. </para><para>For more information on content provider testing, please see . </para>
/// </summary>
/// <java-name>
/// android/test/ProviderTestCase2
/// </java-name>
[Dot42.DexImport("android/test/ProviderTestCase2", AccessFlags = 1057, Signature = "<T:Landroid/content/ContentProvider;>Landroid/test/AndroidTestCase;")]
public abstract partial class ProviderTestCase2<T> : global::Android.Test.AndroidTestCase
/* scope: __dot42__ */
{
/// <summary>
/// <para>Constructor.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/Class;Ljava/lang/String;)V", AccessFlags = 1, Signature = "(Ljava/lang/Class<TT;>;Ljava/lang/String;)V")]
public ProviderTestCase2(global::System.Type providerClass, string providerAuthority) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the content provider created by this class in the setUp() method. </para>
/// </summary>
/// <returns>
/// <para>T An instance of the provider class given as a parameter to the test case class. </para>
/// </returns>
/// <java-name>
/// getProvider
/// </java-name>
[Dot42.DexImport("getProvider", "()Landroid/content/ContentProvider;", AccessFlags = 1, Signature = "()TT;")]
public virtual T GetProvider() /* MethodBuilder.Create */
{
return default(T);
}
/// <summary>
/// <para>Sets up the environment for the test fixture. </para><para>Creates a new android.test.mock.MockContentResolver, a new IsolatedContext that isolates the provider's file operations, and a new instance of the provider under test within the isolated environment. </para><para></para>
/// </summary>
/// <java-name>
/// setUp
/// </java-name>
[Dot42.DexImport("setUp", "()V", AccessFlags = 4)]
protected internal override void SetUp() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tears down the environment for the test fixture. </para><para>Calls android.content.ContentProvider#shutdown() on the android.content.ContentProvider represented by mProvider. </para>
/// </summary>
/// <java-name>
/// tearDown
/// </java-name>
[Dot42.DexImport("tearDown", "()V", AccessFlags = 4)]
protected internal override void TearDown() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the MockContentResolver created by this class during initialization. You must use the methods of this resolver to access the provider under test.</para><para></para>
/// </summary>
/// <returns>
/// <para>A MockContentResolver instance. </para>
/// </returns>
/// <java-name>
/// getMockContentResolver
/// </java-name>
[Dot42.DexImport("getMockContentResolver", "()Landroid/test/mock/MockContentResolver;", AccessFlags = 1)]
public virtual global::Android.Test.Mock.MockContentResolver GetMockContentResolver() /* MethodBuilder.Create */
{
return default(global::Android.Test.Mock.MockContentResolver);
}
/// <summary>
/// <para>Gets the IsolatedContext created by this class during initialization. </para>
/// </summary>
/// <returns>
/// <para>The IsolatedContext instance </para>
/// </returns>
/// <java-name>
/// getMockContext
/// </java-name>
[Dot42.DexImport("getMockContext", "()Landroid/test/IsolatedContext;", AccessFlags = 1)]
public virtual global::Android.Test.IsolatedContext GetMockContext() /* MethodBuilder.Create */
{
return default(global::Android.Test.IsolatedContext);
}
/// <summary>
/// <para>Creates a new content provider of the same type as that passed to the test case class, with an authority name set to the authority parameter, and using an SQLite database as the underlying data source. The SQL statement parameter is used to create the database. This method also creates a new MockContentResolver and adds the provider to it. </para><para>Both the new provider and the new resolver are put into an IsolatedContext that uses the targetContext parameter for file operations and a MockContext for everything else. The IsolatedContext prepends the filenamePrefix parameter to file, database, and directory names. </para><para>This is a convenience method for creating a "mock" provider that can contain test data. </para><para></para>
/// </summary>
/// <returns>
/// <para>ContentResolver A new MockContentResolver linked to the provider</para>
/// </returns>
/// <java-name>
/// newResolverWithContentProviderFromSql
/// </java-name>
[Dot42.DexImport("newResolverWithContentProviderFromSql", "(Landroid/content/Context;Ljava/lang/String;Ljava/lang/Class;Ljava/lang/String;Lj" +
"ava/lang/String;ILjava/lang/String;)Landroid/content/ContentResolver;", AccessFlags = 9, Signature = "<T:Landroid/content/ContentProvider;>(Landroid/content/Context;Ljava/lang/String;" +
"Ljava/lang/Class<TT;>;Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;)La" +
"ndroid/content/ContentResolver;")]
public static global::Android.Content.ContentResolver NewResolverWithContentProviderFromSql<JavaT>(global::Android.Content.Context targetContext, string filenamePrefix, global::System.Type providerClass, string authority, string databaseName, int databaseVersion, string sql) /* MethodBuilder.Create */
{
return default(global::Android.Content.ContentResolver);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal ProviderTestCase2() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Returns the content provider created by this class in the setUp() method. </para>
/// </summary>
/// <returns>
/// <para>T An instance of the provider class given as a parameter to the test case class. </para>
/// </returns>
/// <java-name>
/// getProvider
/// </java-name>
public T Provider
{
[Dot42.DexImport("getProvider", "()Landroid/content/ContentProvider;", AccessFlags = 1, Signature = "()TT;")]
get{ return GetProvider(); }
}
/// <summary>
/// <para>Gets the MockContentResolver created by this class during initialization. You must use the methods of this resolver to access the provider under test.</para><para></para>
/// </summary>
/// <returns>
/// <para>A MockContentResolver instance. </para>
/// </returns>
/// <java-name>
/// getMockContentResolver
/// </java-name>
public global::Android.Test.Mock.MockContentResolver MockContentResolver
{
[Dot42.DexImport("getMockContentResolver", "()Landroid/test/mock/MockContentResolver;", AccessFlags = 1)]
get{ return GetMockContentResolver(); }
}
/// <summary>
/// <para>Gets the IsolatedContext created by this class during initialization. </para>
/// </summary>
/// <returns>
/// <para>The IsolatedContext instance </para>
/// </returns>
/// <java-name>
/// getMockContext
/// </java-name>
public global::Android.Test.IsolatedContext MockContext
{
[Dot42.DexImport("getMockContext", "()Landroid/test/IsolatedContext;", AccessFlags = 1)]
get{ return GetMockContext(); }
}
}
/// <summary>
/// <para>Thrown when an assert equals for Strings failed.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>use junit.framework.ComparisonFailure </para></xrefdescription></xrefsect></para>
/// </summary>
/// <java-name>
/// android/test/ComparisonFailure
/// </java-name>
[Dot42.DexImport("android/test/ComparisonFailure", AccessFlags = 33)]
public partial class ComparisonFailure : global::Android.Test.AssertionFailedError
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)]
public ComparisonFailure(string message, string expected, string actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getMessage
/// </java-name>
[Dot42.DexImport("getMessage", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMessage() /* MethodBuilder.Create */
{
return default(string);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal ComparisonFailure() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>This is a class which delegates to the given context, but performs database and file operations with a renamed database/file name (prefixes default names with a given prefix). </para>
/// </summary>
/// <java-name>
/// android/test/RenamingDelegatingContext
/// </java-name>
[Dot42.DexImport("android/test/RenamingDelegatingContext", AccessFlags = 33)]
public partial class RenamingDelegatingContext : global::Android.Content.ContextWrapper
/* scope: __dot42__ */
{
/// <summary>
/// <para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Landroid/content/Context;Ljava/lang/String;)V", AccessFlags = 1)]
public RenamingDelegatingContext(global::Android.Content.Context context, string filePrefix) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Landroid/content/Context;Landroid/content/Context;Ljava/lang/String;)V", AccessFlags = 1)]
public RenamingDelegatingContext(global::Android.Content.Context context, global::Android.Content.Context fileContext, string filePrefix) /* MethodBuilder.Create */
{
}
/// <java-name>
/// providerWithRenamedContext
/// </java-name>
[Dot42.DexImport("providerWithRenamedContext", "(Ljava/lang/Class;Landroid/content/Context;Ljava/lang/String;)Landroid/content/Co" +
"ntentProvider;", AccessFlags = 9, Signature = "<T:Landroid/content/ContentProvider;>(Ljava/lang/Class<TT;>;Landroid/content/Cont" +
"ext;Ljava/lang/String;)TT;")]
public static T ProviderWithRenamedContext<T>(global::System.Type contentProvider, global::Android.Content.Context c, string filePrefix) /* MethodBuilder.Create */
{
return default(T);
}
/// <java-name>
/// providerWithRenamedContext
/// </java-name>
[Dot42.DexImport("providerWithRenamedContext", "(Ljava/lang/Class;Landroid/content/Context;Ljava/lang/String;Z)Landroid/content/C" +
"ontentProvider;", AccessFlags = 9, Signature = "<T:Landroid/content/ContentProvider;>(Ljava/lang/Class<TT;>;Landroid/content/Cont" +
"ext;Ljava/lang/String;Z)TT;")]
public static T ProviderWithRenamedContext<T>(global::System.Type contentProvider, global::Android.Content.Context c, string filePrefix, bool allowAccessToExistingFilesAndDbs) /* MethodBuilder.Create */
{
return default(T);
}
/// <summary>
/// <para>Makes accessible all files and databases whose names match the filePrefix that was passed to the constructor. Normally only files and databases that were created through this context are accessible. </para>
/// </summary>
/// <java-name>
/// makeExistingFilesAndDbsAccessible
/// </java-name>
[Dot42.DexImport("makeExistingFilesAndDbsAccessible", "()V", AccessFlags = 1)]
public virtual void MakeExistingFilesAndDbsAccessible() /* MethodBuilder.Create */
{
}
/// <java-name>
/// getDatabasePrefix
/// </java-name>
[Dot42.DexImport("getDatabasePrefix", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetDatabasePrefix() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Open a new private SQLiteDatabase associated with this Context's application package. Create the database file if it doesn't exist.</para><para><para>MODE_PRIVATE </para><simplesectsep></simplesectsep><para>MODE_WORLD_READABLE </para><simplesectsep></simplesectsep><para>MODE_WORLD_WRITEABLE </para><simplesectsep></simplesectsep><para>MODE_ENABLE_WRITE_AHEAD_LOGGING </para><simplesectsep></simplesectsep><para>deleteDatabase </para></para>
/// </summary>
/// <returns>
/// <para>The contents of a newly created database with the given name. </para>
/// </returns>
/// <java-name>
/// openOrCreateDatabase
/// </java-name>
[Dot42.DexImport("openOrCreateDatabase", "(Ljava/lang/String;ILandroid/database/sqlite/SQLiteDatabase$CursorFactory;)Landro" +
"id/database/sqlite/SQLiteDatabase;", AccessFlags = 1)]
public override global::Android.Database.Sqlite.SQLiteDatabase OpenOrCreateDatabase(string name, int mode, global::Android.Database.Sqlite.SQLiteDatabase.ICursorFactory factory) /* MethodBuilder.Create */
{
return default(global::Android.Database.Sqlite.SQLiteDatabase);
}
/// <summary>
/// <para>Open a new private SQLiteDatabase associated with this Context's application package. Creates the database file if it doesn't exist.</para><para>Accepts input param: a concrete instance of DatabaseErrorHandler to be used to handle corruption when sqlite reports database corruption.</para><para><para>MODE_PRIVATE </para><simplesectsep></simplesectsep><para>MODE_WORLD_READABLE </para><simplesectsep></simplesectsep><para>MODE_WORLD_WRITEABLE </para><simplesectsep></simplesectsep><para>MODE_ENABLE_WRITE_AHEAD_LOGGING </para><simplesectsep></simplesectsep><para>deleteDatabase </para></para>
/// </summary>
/// <returns>
/// <para>The contents of a newly created database with the given name. </para>
/// </returns>
/// <java-name>
/// openOrCreateDatabase
/// </java-name>
[Dot42.DexImport("openOrCreateDatabase", "(Ljava/lang/String;ILandroid/database/sqlite/SQLiteDatabase$CursorFactory;Landroi" +
"d/database/DatabaseErrorHandler;)Landroid/database/sqlite/SQLiteDatabase;", AccessFlags = 1)]
public override global::Android.Database.Sqlite.SQLiteDatabase OpenOrCreateDatabase(string name, int mode, global::Android.Database.Sqlite.SQLiteDatabase.ICursorFactory factory, global::Android.Database.IDatabaseErrorHandler errorHandler) /* MethodBuilder.Create */
{
return default(global::Android.Database.Sqlite.SQLiteDatabase);
}
/// <summary>
/// <para>Delete an existing private SQLiteDatabase associated with this Context's application package.</para><para><para>openOrCreateDatabase </para></para>
/// </summary>
/// <returns>
/// <para>True if the database was successfully deleted; else false.</para>
/// </returns>
/// <java-name>
/// deleteDatabase
/// </java-name>
[Dot42.DexImport("deleteDatabase", "(Ljava/lang/String;)Z", AccessFlags = 1)]
public override bool DeleteDatabase(string name) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Returns the absolute path on the filesystem where a database created with openOrCreateDatabase is stored.</para><para><para>openOrCreateDatabase </para></para>
/// </summary>
/// <returns>
/// <para>Returns an absolute path to the given database.</para>
/// </returns>
/// <java-name>
/// getDatabasePath
/// </java-name>
[Dot42.DexImport("getDatabasePath", "(Ljava/lang/String;)Ljava/io/File;", AccessFlags = 1)]
public override global::Java.Io.File GetDatabasePath(string name) /* MethodBuilder.Create */
{
return default(global::Java.Io.File);
}
/// <summary>
/// <para>Returns an array of strings naming the private databases associated with this Context's application package.</para><para><para>openOrCreateDatabase </para><simplesectsep></simplesectsep><para>deleteDatabase </para></para>
/// </summary>
/// <returns>
/// <para>Array of strings naming the private databases.</para>
/// </returns>
/// <java-name>
/// databaseList
/// </java-name>
[Dot42.DexImport("databaseList", "()[Ljava/lang/String;", AccessFlags = 1)]
public override string[] DatabaseList() /* MethodBuilder.Create */
{
return default(string[]);
}
/// <summary>
/// <para>Open a private file associated with this Context's application package for reading.</para><para><para>openFileOutput </para><simplesectsep></simplesectsep><para>fileList </para><simplesectsep></simplesectsep><para>deleteFile </para><simplesectsep></simplesectsep><para>java.io.FileInputStream::FileInputStream(String) </para></para>
/// </summary>
/// <returns>
/// <para>FileInputStream Resulting input stream.</para>
/// </returns>
/// <java-name>
/// openFileInput
/// </java-name>
[Dot42.DexImport("openFileInput", "(Ljava/lang/String;)Ljava/io/FileInputStream;", AccessFlags = 1)]
public override global::Java.Io.FileInputStream OpenFileInput(string name) /* MethodBuilder.Create */
{
return default(global::Java.Io.FileInputStream);
}
/// <summary>
/// <para>Open a private file associated with this Context's application package for writing. Creates the file if it doesn't already exist.</para><para><para>MODE_APPEND </para><simplesectsep></simplesectsep><para>MODE_PRIVATE </para><simplesectsep></simplesectsep><para>MODE_WORLD_READABLE </para><simplesectsep></simplesectsep><para>MODE_WORLD_WRITEABLE </para><simplesectsep></simplesectsep><para>openFileInput </para><simplesectsep></simplesectsep><para>fileList </para><simplesectsep></simplesectsep><para>deleteFile </para><simplesectsep></simplesectsep><para>java.io.FileOutputStream::FileOutputStream(String) </para></para>
/// </summary>
/// <returns>
/// <para>FileOutputStream Resulting output stream.</para>
/// </returns>
/// <java-name>
/// openFileOutput
/// </java-name>
[Dot42.DexImport("openFileOutput", "(Ljava/lang/String;I)Ljava/io/FileOutputStream;", AccessFlags = 1)]
public override global::Java.Io.FileOutputStream OpenFileOutput(string name, int mode) /* MethodBuilder.Create */
{
return default(global::Java.Io.FileOutputStream);
}
/// <summary>
/// <para>Returns the absolute path on the filesystem where a file created with openFileOutput is stored.</para><para><para>openFileOutput </para><simplesectsep></simplesectsep><para>getFilesDir </para><simplesectsep></simplesectsep><para>getDir </para></para>
/// </summary>
/// <returns>
/// <para>Returns an absolute path to the given file.</para>
/// </returns>
/// <java-name>
/// getFileStreamPath
/// </java-name>
[Dot42.DexImport("getFileStreamPath", "(Ljava/lang/String;)Ljava/io/File;", AccessFlags = 1)]
public override global::Java.Io.File GetFileStreamPath(string name) /* MethodBuilder.Create */
{
return default(global::Java.Io.File);
}
/// <summary>
/// <para>Delete the given private file associated with this Context's application package.</para><para><para>openFileInput </para><simplesectsep></simplesectsep><para>openFileOutput </para><simplesectsep></simplesectsep><para>fileList </para><simplesectsep></simplesectsep><para>java.io.File::delete() </para></para>
/// </summary>
/// <returns>
/// <para>True if the file was successfully deleted; else false.</para>
/// </returns>
/// <java-name>
/// deleteFile
/// </java-name>
[Dot42.DexImport("deleteFile", "(Ljava/lang/String;)Z", AccessFlags = 1)]
public override bool DeleteFile(string name) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Returns an array of strings naming the private files associated with this Context's application package.</para><para><para>openFileInput </para><simplesectsep></simplesectsep><para>openFileOutput </para><simplesectsep></simplesectsep><para>deleteFile </para></para>
/// </summary>
/// <returns>
/// <para>Array of strings naming the private files.</para>
/// </returns>
/// <java-name>
/// fileList
/// </java-name>
[Dot42.DexImport("fileList", "()[Ljava/lang/String;", AccessFlags = 1)]
public override string[] FileList() /* MethodBuilder.Create */
{
return default(string[]);
}
/// <summary>
/// <para>In order to support calls to getCacheDir(), we create a temp cache dir (inside the real one) and return it instead. This code is basically getCacheDir(), except it uses the real cache dir as the parent directory and creates a test cache dir inside that. </para>
/// </summary>
/// <java-name>
/// getCacheDir
/// </java-name>
[Dot42.DexImport("getCacheDir", "()Ljava/io/File;", AccessFlags = 1)]
public override global::Java.Io.File GetCacheDir() /* MethodBuilder.Create */
{
return default(global::Java.Io.File);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal RenamingDelegatingContext() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <java-name>
/// getDatabasePrefix
/// </java-name>
public string DatabasePrefix
{
[Dot42.DexImport("getDatabasePrefix", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetDatabasePrefix(); }
}
/// <summary>
/// <para>In order to support calls to getCacheDir(), we create a temp cache dir (inside the real one) and return it instead. This code is basically getCacheDir(), except it uses the real cache dir as the parent directory and creates a test cache dir inside that. </para>
/// </summary>
/// <java-name>
/// getCacheDir
/// </java-name>
public global::Java.Io.File CacheDir
{
[Dot42.DexImport("getCacheDir", "()Ljava/io/File;", AccessFlags = 1)]
get{ return GetCacheDir(); }
}
}
/// <summary>
/// <para>This class provides isolated testing of a single activity. The activity under test will be created with minimal connection to the system infrastructure, and you can inject mocked or wrappered versions of many of Activity's dependencies. Most of the work is handled automatically here by setUp and tearDown.</para><para>If you prefer a functional test, see android.test.ActivityInstrumentationTestCase.</para><para>It must be noted that, as a true unit test, your Activity will not be running in the normal system and will not participate in the normal interactions with other Activities. The following methods should not be called in this configuration - most of them will throw exceptions: <ul><li><para>android.app.Activity#createPendingResult(int, Intent, int) </para></li><li><para>android.app.Activity#startActivityIfNeeded(Intent, int) </para></li><li><para>android.app.Activity#startActivityFromChild(Activity, Intent, int) </para></li><li><para>android.app.Activity#startNextMatchingActivity(Intent) </para></li><li><para>android.app.Activity#getCallingActivity() </para></li><li><para>android.app.Activity#getCallingPackage() </para></li><li><para>android.app.Activity#createPendingResult(int, Intent, int) </para></li><li><para>android.app.Activity#getTaskId() </para></li><li><para>android.app.Activity#isTaskRoot() </para></li><li><para>android.app.Activity#moveTaskToBack(boolean) </para></li></ul></para><para>The following methods may be called but will not do anything. For test purposes, you can use the methods getStartedActivityIntent() and getStartedActivityRequest() to inspect the parameters that they were called with. <ul><li><para>android.app.Activity#startActivity(Intent) </para></li><li><para>android.app.Activity#startActivityForResult(Intent, int) </para></li></ul></para><para>The following methods may be called but will not do anything. For test purposes, you can use the methods isFinishCalled() and getFinishedActivityRequest() to inspect the parameters that they were called with. <ul><li><para>android.app.Activity#finish() </para></li><li><para>android.app.Activity#finishFromChild(Activity child) </para></li><li><para>android.app.Activity#finishActivity(int requestCode) </para></li></ul></para>
/// </summary>
/// <java-name>
/// android/test/ActivityUnitTestCase
/// </java-name>
[Dot42.DexImport("android/test/ActivityUnitTestCase", AccessFlags = 1057, Signature = "<T:Landroid/app/Activity;>Landroid/test/ActivityTestCase;")]
public abstract partial class ActivityUnitTestCase<T> : global::Android.Test.ActivityTestCase
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Ljava/lang/Class;)V", AccessFlags = 1, Signature = "(Ljava/lang/Class<TT;>;)V")]
public ActivityUnitTestCase(global::System.Type activityClass) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>Returns the activity under test. </para>
/// </returns>
/// <java-name>
/// getActivity
/// </java-name>
[Dot42.DexImport("getActivity", "()Landroid/app/Activity;", AccessFlags = 1, Signature = "()TT;")]
public new virtual T GetActivity() /* MethodBuilder.Create */
{
return default(T);
}
/// <summary>
/// <para>Sets up the fixture, for example, open a network connection. This method is called before a test is executed. </para>
/// </summary>
/// <java-name>
/// setUp
/// </java-name>
[Dot42.DexImport("setUp", "()V", AccessFlags = 4)]
protected internal override void SetUp() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Start the activity under test, in the same way as if it was started by Context.startActivity(), providing the arguments it supplied. When you use this method to start the activity, it will automatically be stopped by tearDown.</para><para>This method will call onCreate(), but if you wish to further exercise Activity life cycle methods, you must call them yourself from your test case.</para><para><b>Do not call from your setUp() method. You must call this method from each of your test methods.</b></para><para></para>
/// </summary>
/// <returns>
/// <para>Returns the Activity that was created </para>
/// </returns>
/// <java-name>
/// startActivity
/// </java-name>
[Dot42.DexImport("startActivity", "(Landroid/content/Intent;Landroid/os/Bundle;Ljava/lang/Object;)Landroid/app/Activ" +
"ity;", AccessFlags = 4, Signature = "(Landroid/content/Intent;Landroid/os/Bundle;Ljava/lang/Object;)TT;")]
protected internal virtual T StartActivity(global::Android.Content.Intent intent, global::Android.Os.Bundle savedInstanceState, object lastNonConfigurationInstance) /* MethodBuilder.Create */
{
return default(T);
}
/// <summary>
/// <para>Make sure all resources are cleaned up and garbage collected before moving on to the next test. Subclasses that override this method should make sure they call super.tearDown() at the end of the overriding method.</para><para></para>
/// </summary>
/// <java-name>
/// tearDown
/// </java-name>
[Dot42.DexImport("tearDown", "()V", AccessFlags = 4)]
protected internal override void TearDown() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Set the application for use during the test. You must call this function before calling startActivity. If your test does not call this method, </para>
/// </summary>
/// <java-name>
/// setApplication
/// </java-name>
[Dot42.DexImport("setApplication", "(Landroid/app/Application;)V", AccessFlags = 1)]
public virtual void SetApplication(global::Android.App.Application application) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>If you wish to inject a Mock, Isolated, or otherwise altered context, you can do so here. You must call this function before calling startActivity. If you wish to obtain a real Context, as a building block, use getInstrumentation().getTargetContext(). </para>
/// </summary>
/// <java-name>
/// setActivityContext
/// </java-name>
[Dot42.DexImport("setActivityContext", "(Landroid/content/Context;)V", AccessFlags = 1)]
public virtual void SetActivityContext(global::Android.Content.Context activityContext) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>This method will return the value if your Activity under test calls android.app.Activity#setRequestedOrientation. </para>
/// </summary>
/// <java-name>
/// getRequestedOrientation
/// </java-name>
[Dot42.DexImport("getRequestedOrientation", "()I", AccessFlags = 1)]
public virtual int GetRequestedOrientation() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>This method will return the launch intent if your Activity under test calls android.app.Activity#startActivity(Intent) or android.app.Activity#startActivityForResult(Intent, int). </para>
/// </summary>
/// <returns>
/// <para>The Intent provided in the start call, or null if no start call was made. </para>
/// </returns>
/// <java-name>
/// getStartedActivityIntent
/// </java-name>
[Dot42.DexImport("getStartedActivityIntent", "()Landroid/content/Intent;", AccessFlags = 1)]
public virtual global::Android.Content.Intent GetStartedActivityIntent() /* MethodBuilder.Create */
{
return default(global::Android.Content.Intent);
}
/// <summary>
/// <para>This method will return the launch request code if your Activity under test calls android.app.Activity#startActivityForResult(Intent, int). </para>
/// </summary>
/// <returns>
/// <para>The request code provided in the start call, or -1 if no start call was made. </para>
/// </returns>
/// <java-name>
/// getStartedActivityRequest
/// </java-name>
[Dot42.DexImport("getStartedActivityRequest", "()I", AccessFlags = 1)]
public virtual int GetStartedActivityRequest() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>This method will notify you if the Activity under test called android.app.Activity#finish(), android.app.Activity#finishFromChild(Activity), or android.app.Activity#finishActivity(int). </para>
/// </summary>
/// <returns>
/// <para>Returns true if one of the listed finish methods was called. </para>
/// </returns>
/// <java-name>
/// isFinishCalled
/// </java-name>
[Dot42.DexImport("isFinishCalled", "()Z", AccessFlags = 1)]
public virtual bool IsFinishCalled() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>This method will return the request code if the Activity under test called android.app.Activity#finishActivity(int). </para>
/// </summary>
/// <returns>
/// <para>The request code provided in the start call, or -1 if no finish call was made. </para>
/// </returns>
/// <java-name>
/// getFinishedActivityRequest
/// </java-name>
[Dot42.DexImport("getFinishedActivityRequest", "()I", AccessFlags = 1)]
public virtual int GetFinishedActivityRequest() /* MethodBuilder.Create */
{
return default(int);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal ActivityUnitTestCase() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>Returns the activity under test. </para>
/// </returns>
/// <java-name>
/// getActivity
/// </java-name>
public T Activity
{
[Dot42.DexImport("getActivity", "()Landroid/app/Activity;", AccessFlags = 1, Signature = "()TT;")]
get{ return GetActivity(); }
}
/// <summary>
/// <para>This method will return the value if your Activity under test calls android.app.Activity#setRequestedOrientation. </para>
/// </summary>
/// <java-name>
/// getRequestedOrientation
/// </java-name>
public int RequestedOrientation
{
[Dot42.DexImport("getRequestedOrientation", "()I", AccessFlags = 1)]
get{ return GetRequestedOrientation(); }
}
/// <summary>
/// <para>This method will return the launch intent if your Activity under test calls android.app.Activity#startActivity(Intent) or android.app.Activity#startActivityForResult(Intent, int). </para>
/// </summary>
/// <returns>
/// <para>The Intent provided in the start call, or null if no start call was made. </para>
/// </returns>
/// <java-name>
/// getStartedActivityIntent
/// </java-name>
public global::Android.Content.Intent StartedActivityIntent
{
[Dot42.DexImport("getStartedActivityIntent", "()Landroid/content/Intent;", AccessFlags = 1)]
get{ return GetStartedActivityIntent(); }
}
/// <summary>
/// <para>This method will return the launch request code if your Activity under test calls android.app.Activity#startActivityForResult(Intent, int). </para>
/// </summary>
/// <returns>
/// <para>The request code provided in the start call, or -1 if no start call was made. </para>
/// </returns>
/// <java-name>
/// getStartedActivityRequest
/// </java-name>
public int StartedActivityRequest
{
[Dot42.DexImport("getStartedActivityRequest", "()I", AccessFlags = 1)]
get{ return GetStartedActivityRequest(); }
}
/// <summary>
/// <para>This method will return the request code if the Activity under test called android.app.Activity#finishActivity(int). </para>
/// </summary>
/// <returns>
/// <para>The request code provided in the start call, or -1 if no finish call was made. </para>
/// </returns>
/// <java-name>
/// getFinishedActivityRequest
/// </java-name>
public int FinishedActivityRequest
{
[Dot42.DexImport("getFinishedActivityRequest", "()I", AccessFlags = 1)]
get{ return GetFinishedActivityRequest(); }
}
}
/// <summary>
/// <para>This class provides functional testing of a single activity. The activity under test will be created using the system infrastructure (by calling InstrumentationTestCase.launchActivity()) and you will then be able to manipulate your Activity directly. Most of the work is handled automatically here by setUp and tearDown.</para><para>If you prefer an isolated unit test, see android.test.ActivityUnitTestCase.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>new tests should be written using android.test.ActivityInstrumentationTestCase2, which provides more options for configuring the Activity under test </para></xrefdescription></xrefsect></para>
/// </summary>
/// <java-name>
/// android/test/ActivityInstrumentationTestCase
/// </java-name>
[Dot42.DexImport("android/test/ActivityInstrumentationTestCase", AccessFlags = 1057, Signature = "<T:Landroid/app/Activity;>Landroid/test/ActivityTestCase;")]
public abstract partial class ActivityInstrumentationTestCase<T> : global::Android.Test.ActivityTestCase
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates an ActivityInstrumentationTestCase in non-touch mode.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Class;)V", AccessFlags = 1, Signature = "(Ljava/lang/String;Ljava/lang/Class<TT;>;)V")]
public ActivityInstrumentationTestCase(string pkg, global::System.Type activityClass) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates an ActivityInstrumentationTestCase.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Class;Z)V", AccessFlags = 1, Signature = "(Ljava/lang/String;Ljava/lang/Class<TT;>;Z)V")]
public ActivityInstrumentationTestCase(string pkg, global::System.Type activityClass, bool initialTouchMode) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>Returns the activity under test. </para>
/// </returns>
/// <java-name>
/// getActivity
/// </java-name>
[Dot42.DexImport("getActivity", "()Landroid/app/Activity;", AccessFlags = 1, Signature = "()TT;")]
public new virtual T GetActivity() /* MethodBuilder.Create */
{
return default(T);
}
/// <summary>
/// <para>Sets up the fixture, for example, open a network connection. This method is called before a test is executed. </para>
/// </summary>
/// <java-name>
/// setUp
/// </java-name>
[Dot42.DexImport("setUp", "()V", AccessFlags = 4)]
protected internal override void SetUp() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Make sure all resources are cleaned up and garbage collected before moving on to the next test. Subclasses that override this method should make sure they call super.tearDown() at the end of the overriding method.</para><para></para>
/// </summary>
/// <java-name>
/// tearDown
/// </java-name>
[Dot42.DexImport("tearDown", "()V", AccessFlags = 4)]
protected internal override void TearDown() /* MethodBuilder.Create */
{
}
/// <java-name>
/// testActivityTestCaseSetUpProperly
/// </java-name>
[Dot42.DexImport("testActivityTestCaseSetUpProperly", "()V", AccessFlags = 1)]
public virtual void TestActivityTestCaseSetUpProperly() /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal ActivityInstrumentationTestCase() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>Returns the activity under test. </para>
/// </returns>
/// <java-name>
/// getActivity
/// </java-name>
public T Activity
{
[Dot42.DexImport("getActivity", "()Landroid/app/Activity;", AccessFlags = 1, Signature = "()TT;")]
get{ return GetActivity(); }
}
}
/// <summary>
/// <para>An Instrumentation that runs various types of junit.framework.TestCases against an Android package (application).</para><para> <h3>Developer Guides</h3></para><para> </para><para>For more information about application testing, read the developer guide.</para><para> </para><para><h3>Typical Usage</h3></para><para><ol><li><para>Write junit.framework.TestCases that perform unit, functional, or performance tests against the classes in your package. Typically these are subclassed from: <ul><li><para>android.test.ActivityInstrumentationTestCase2 </para></li><li><para>android.test.ActivityUnitTestCase </para></li><li><para>android.test.AndroidTestCase </para></li><li><para>android.test.ApplicationTestCase </para></li><li><para>android.test.InstrumentationTestCase </para></li><li><para>android.test.ProviderTestCase </para></li><li><para>android.test.ServiceTestCase </para></li><li><para>android.test.SingleLaunchActivityTestCase</para></li></ul></para></li><li><para>In an appropriate AndroidManifest.xml, define the this instrumentation with the appropriate android:targetPackage set. </para></li><li><para>Run the instrumentation using "adb shell am instrument -w", with no optional arguments, to run all tests (except performance tests). </para></li><li><para>Run the instrumentation using "adb shell am instrument -w", with the argument '-e func true' to run all functional tests. These are tests that derive from android.test.InstrumentationTestCase. </para></li><li><para>Run the instrumentation using "adb shell am instrument -w", with the argument '-e unit true' to run all unit tests. These are tests that <b>do not</b>derive from android.test.InstrumentationTestCase (and are not performance tests). </para></li><li><para>Run the instrumentation using "adb shell am instrument -w", with the argument '-e class' set to run an individual junit.framework.TestCase. </para></li></ol></para><para><b>Running all tests:</b> adb shell am instrument -w com.android.foo/android.test.InstrumentationTestRunner </para><para><b>Running all small tests:</b> adb shell am instrument -w -e size small com.android.foo/android.test.InstrumentationTestRunner </para><para><b>Running all medium tests:</b> adb shell am instrument -w -e size medium com.android.foo/android.test.InstrumentationTestRunner </para><para><b>Running all large tests:</b> adb shell am instrument -w -e size large com.android.foo/android.test.InstrumentationTestRunner </para><para><b>Filter test run to tests with given annotation:</b> adb shell am instrument -w -e annotation com.android.foo.MyAnnotation com.android.foo/android.test.InstrumentationTestRunner </para><para>If used with other options, the resulting test run will contain the union of the two options. e.g. "-e size large -e annotation com.android.foo.MyAnnotation" will run only tests with both the LargeTest and "com.android.foo.MyAnnotation" annotations. </para><para><b>Filter test run to tests <b>without</b> given annotation:</b> adb shell am instrument -w -e notAnnotation com.android.foo.MyAnnotation com.android.foo/android.test.InstrumentationTestRunner </para><para><b>Running a single testcase:</b> adb shell am instrument -w -e class com.android.foo.FooTest com.android.foo/android.test.InstrumentationTestRunner </para><para><b>Running a single test:</b> adb shell am instrument -w -e class com.android.foo.FooTest::testFoo com.android.foo/android.test.InstrumentationTestRunner </para><para><b>Running multiple tests:</b> adb shell am instrument -w -e class com.android.foo.FooTest,com.android.foo.TooTest com.android.foo/android.test.InstrumentationTestRunner </para><para><b>Running all tests in a java package:</b> adb shell am instrument -w -e package com.android.foo.subpkg com.android.foo/android.test.InstrumentationTestRunner </para><para><b>Including performance tests:</b> adb shell am instrument -w -e perf true com.android.foo/android.test.InstrumentationTestRunner </para><para><b>To debug your tests, set a break point in your code and pass:</b> -e debug true </para><para><b>To run in 'log only' mode</b> -e log true This option will load and iterate through all test classes and methods, but will bypass actual test execution. Useful for quickly obtaining info on the tests to be executed by an instrumentation command. </para><para><b>To generate EMMA code coverage:</b> -e coverage true Note: this requires an emma instrumented build. By default, the code coverage results file will be saved in a /data/<app>/coverage.ec file, unless overridden by coverageFile flag (see below) </para><para><b> To specify EMMA code coverage results file path:</b> -e coverageFile /sdcard/myFile.ec <br></br> in addition to the other arguments. </para>
/// </summary>
/// <java-name>
/// android/test/InstrumentationTestRunner
/// </java-name>
[Dot42.DexImport("android/test/InstrumentationTestRunner", AccessFlags = 33)]
public partial class InstrumentationTestRunner : global::Android.App.Instrumentation, global::Android.Test.ITestSuiteProvider
/* scope: __dot42__ */
{
/// <summary>
/// <para>The following keys are used in the status bundle to provide structured reports to an IInstrumentationWatcher. This value, if stored with key android.app.Instrumentation#REPORT_KEY_IDENTIFIER, identifies InstrumentationTestRunner as the source of the report. This is sent with all status messages. </para>
/// </summary>
/// <java-name>
/// REPORT_VALUE_ID
/// </java-name>
[Dot42.DexImport("REPORT_VALUE_ID", "Ljava/lang/String;", AccessFlags = 25)]
public const string REPORT_VALUE_ID = "InstrumentationTestRunner";
/// <summary>
/// <para>If included in the status or final bundle sent to an IInstrumentationWatcher, this key identifies the total number of tests that are being run. This is sent with all status messages. </para>
/// </summary>
/// <java-name>
/// REPORT_KEY_NUM_TOTAL
/// </java-name>
[Dot42.DexImport("REPORT_KEY_NUM_TOTAL", "Ljava/lang/String;", AccessFlags = 25)]
public const string REPORT_KEY_NUM_TOTAL = "numtests";
/// <summary>
/// <para>If included in the status or final bundle sent to an IInstrumentationWatcher, this key identifies the sequence number of the current test. This is sent with any status message describing a specific test being started or completed. </para>
/// </summary>
/// <java-name>
/// REPORT_KEY_NUM_CURRENT
/// </java-name>
[Dot42.DexImport("REPORT_KEY_NUM_CURRENT", "Ljava/lang/String;", AccessFlags = 25)]
public const string REPORT_KEY_NUM_CURRENT = "current";
/// <summary>
/// <para>If included in the status or final bundle sent to an IInstrumentationWatcher, this key identifies the name of the current test class. This is sent with any status message describing a specific test being started or completed. </para>
/// </summary>
/// <java-name>
/// REPORT_KEY_NAME_CLASS
/// </java-name>
[Dot42.DexImport("REPORT_KEY_NAME_CLASS", "Ljava/lang/String;", AccessFlags = 25)]
public const string REPORT_KEY_NAME_CLASS = "class";
/// <summary>
/// <para>If included in the status or final bundle sent to an IInstrumentationWatcher, this key identifies the name of the current test. This is sent with any status message describing a specific test being started or completed. </para>
/// </summary>
/// <java-name>
/// REPORT_KEY_NAME_TEST
/// </java-name>
[Dot42.DexImport("REPORT_KEY_NAME_TEST", "Ljava/lang/String;", AccessFlags = 25)]
public const string REPORT_KEY_NAME_TEST = "test";
/// <summary>
/// <para>The test is starting. </para>
/// </summary>
/// <java-name>
/// REPORT_VALUE_RESULT_START
/// </java-name>
[Dot42.DexImport("REPORT_VALUE_RESULT_START", "I", AccessFlags = 25)]
public const int REPORT_VALUE_RESULT_START = 1;
/// <summary>
/// <para>The test completed successfully. </para>
/// </summary>
/// <java-name>
/// REPORT_VALUE_RESULT_OK
/// </java-name>
[Dot42.DexImport("REPORT_VALUE_RESULT_OK", "I", AccessFlags = 25)]
public const int REPORT_VALUE_RESULT_OK = 0;
/// <summary>
/// <para>The test completed with an error. </para>
/// </summary>
/// <java-name>
/// REPORT_VALUE_RESULT_ERROR
/// </java-name>
[Dot42.DexImport("REPORT_VALUE_RESULT_ERROR", "I", AccessFlags = 25)]
public const int REPORT_VALUE_RESULT_ERROR = -1;
/// <summary>
/// <para>The test completed with a failure. </para>
/// </summary>
/// <java-name>
/// REPORT_VALUE_RESULT_FAILURE
/// </java-name>
[Dot42.DexImport("REPORT_VALUE_RESULT_FAILURE", "I", AccessFlags = 25)]
public const int REPORT_VALUE_RESULT_FAILURE = -2;
/// <summary>
/// <para>If included in the status bundle sent to an IInstrumentationWatcher, this key identifies a stack trace describing an error or failure. This is sent with any status message describing a specific test being completed. </para>
/// </summary>
/// <java-name>
/// REPORT_KEY_STACK
/// </java-name>
[Dot42.DexImport("REPORT_KEY_STACK", "Ljava/lang/String;", AccessFlags = 25)]
public const string REPORT_KEY_STACK = "stack";
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public InstrumentationTestRunner() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Called when the instrumentation is starting, before any application code has been loaded. Usually this will be implemented to simply call start to begin the instrumentation thread, which will then continue execution in onStart.</para><para>If you do not need your own thread that is you are writing your instrumentation to be completely asynchronous (returning to the event loop so that the application can run), you can simply begin your instrumentation here, for example call Context#startActivity to begin the appropriate first activity of the application.</para><para></para>
/// </summary>
/// <java-name>
/// onCreate
/// </java-name>
[Dot42.DexImport("onCreate", "(Landroid/os/Bundle;)V", AccessFlags = 1)]
public override void OnCreate(global::Android.Os.Bundle arguments) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getAndroidTestRunner
/// </java-name>
[Dot42.DexImport("getAndroidTestRunner", "()Landroid/test/AndroidTestRunner;", AccessFlags = 4)]
protected internal virtual global::Android.Test.AndroidTestRunner GetAndroidTestRunner() /* MethodBuilder.Create */
{
return default(global::Android.Test.AndroidTestRunner);
}
/// <summary>
/// <para>Method where the instrumentation thread enters execution. This allows you to run your instrumentation code in a separate thread than the application, so that it can perform blocking operation such as sendKeySync or startActivitySync.</para><para>You will typically want to call finish() when this function is done, to end your instrumentation. </para>
/// </summary>
/// <java-name>
/// onStart
/// </java-name>
[Dot42.DexImport("onStart", "()V", AccessFlags = 1)]
public override void OnStart() /* MethodBuilder.Create */
{
}
/// <java-name>
/// getTestSuite
/// </java-name>
[Dot42.DexImport("getTestSuite", "()Ljunit/framework/TestSuite;", AccessFlags = 1)]
public virtual global::Junit.Framework.TestSuite GetTestSuite() /* MethodBuilder.Create */
{
return default(global::Junit.Framework.TestSuite);
}
/// <summary>
/// <para>Override this to define all of the tests to run in your package. </para>
/// </summary>
/// <java-name>
/// getAllTests
/// </java-name>
[Dot42.DexImport("getAllTests", "()Ljunit/framework/TestSuite;", AccessFlags = 1)]
public virtual global::Junit.Framework.TestSuite GetAllTests() /* MethodBuilder.Create */
{
return default(global::Junit.Framework.TestSuite);
}
/// <summary>
/// <para>Override this to provide access to the class loader of your package. </para>
/// </summary>
/// <java-name>
/// getLoader
/// </java-name>
[Dot42.DexImport("getLoader", "()Ljava/lang/ClassLoader;", AccessFlags = 1)]
public virtual global::Java.Lang.ClassLoader GetLoader() /* MethodBuilder.Create */
{
return default(global::Java.Lang.ClassLoader);
}
/// <java-name>
/// getAndroidTestRunner
/// </java-name>
protected internal global::Android.Test.AndroidTestRunner AndroidTestRunner
{
[Dot42.DexImport("getAndroidTestRunner", "()Landroid/test/AndroidTestRunner;", AccessFlags = 4)]
get{ return GetAndroidTestRunner(); }
}
/// <java-name>
/// getTestSuite
/// </java-name>
public global::Junit.Framework.TestSuite TestSuite
{
[Dot42.DexImport("getTestSuite", "()Ljunit/framework/TestSuite;", AccessFlags = 1)]
get{ return GetTestSuite(); }
}
/// <summary>
/// <para>Override this to define all of the tests to run in your package. </para>
/// </summary>
/// <java-name>
/// getAllTests
/// </java-name>
public global::Junit.Framework.TestSuite AllTests
{
[Dot42.DexImport("getAllTests", "()Ljunit/framework/TestSuite;", AccessFlags = 1)]
get{ return GetAllTests(); }
}
/// <summary>
/// <para>Override this to provide access to the class loader of your package. </para>
/// </summary>
/// <java-name>
/// getLoader
/// </java-name>
public global::Java.Lang.ClassLoader Loader
{
[Dot42.DexImport("getLoader", "()Ljava/lang/ClassLoader;", AccessFlags = 1)]
get{ return GetLoader(); }
}
}
/// <summary>
/// <para>A convenience class for testing Loaders. This test case provides a simple way to synchronously get the result from a Loader making it easy to assert that the Loader returns the expected result. </para>
/// </summary>
/// <java-name>
/// android/test/LoaderTestCase
/// </java-name>
[Dot42.DexImport("android/test/LoaderTestCase", AccessFlags = 33)]
public partial class LoaderTestCase : global::Android.Test.AndroidTestCase
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public LoaderTestCase() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Runs a Loader synchronously and returns the result of the load. The loader will be started, stopped, and destroyed by this method so it cannot be reused.</para><para></para>
/// </summary>
/// <returns>
/// <para>The result from the loader </para>
/// </returns>
/// <java-name>
/// getLoaderResultSynchronously
/// </java-name>
[Dot42.DexImport("getLoaderResultSynchronously", "(Landroid/content/Loader;)Ljava/lang/Object;", AccessFlags = 1, Signature = "<T:Ljava/lang/Object;>(Landroid/content/Loader<TT;>;)TT;")]
public virtual T GetLoaderResultSynchronously<T>(global::Android.Content.Loader<T> loader) /* MethodBuilder.Create */
{
return default(T);
}
}
/// <summary>
/// <para>Reusable methods for generating touch events. These methods can be used with InstrumentationTestCase or ActivityInstrumentationTestCase2 to simulate user interaction with the application through a touch screen. </para>
/// </summary>
/// <java-name>
/// android/test/TouchUtils
/// </java-name>
[Dot42.DexImport("android/test/TouchUtils", AccessFlags = 33)]
public partial class TouchUtils
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public TouchUtils() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Simulate touching in the center of the screen and dragging one quarter of the way down <xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>android.test.ActivityInstrumentationTestCase is deprecated in favor of android.test.ActivityInstrumentationTestCase2, which provides more options for configuring the Activity under test </para></xrefdescription></xrefsect></para>
/// </summary>
/// <java-name>
/// dragQuarterScreenDown
/// </java-name>
[Dot42.DexImport("dragQuarterScreenDown", "(Landroid/test/ActivityInstrumentationTestCase;)V", AccessFlags = 9)]
public static void DragQuarterScreenDown(global::Android.Test.ActivityInstrumentationTestCase<object> test) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Simulate touching in the center of the screen and dragging one quarter of the way down </para>
/// </summary>
/// <java-name>
/// dragQuarterScreenDown
/// </java-name>
[Dot42.DexImport("dragQuarterScreenDown", "(Landroid/test/InstrumentationTestCase;Landroid/app/Activity;)V", AccessFlags = 9)]
public static void DragQuarterScreenDown(global::Android.Test.InstrumentationTestCase test, global::Android.App.Activity activity) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Simulate touching in the center of the screen and dragging one quarter of the way up <xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>android.test.ActivityInstrumentationTestCase is deprecated in favor of android.test.ActivityInstrumentationTestCase2, which provides more options for configuring the Activity under test </para></xrefdescription></xrefsect></para>
/// </summary>
/// <java-name>
/// dragQuarterScreenUp
/// </java-name>
[Dot42.DexImport("dragQuarterScreenUp", "(Landroid/test/ActivityInstrumentationTestCase;)V", AccessFlags = 9)]
public static void DragQuarterScreenUp(global::Android.Test.ActivityInstrumentationTestCase<object> test) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Simulate touching in the center of the screen and dragging one quarter of the way up </para>
/// </summary>
/// <java-name>
/// dragQuarterScreenUp
/// </java-name>
[Dot42.DexImport("dragQuarterScreenUp", "(Landroid/test/InstrumentationTestCase;Landroid/app/Activity;)V", AccessFlags = 9)]
public static void DragQuarterScreenUp(global::Android.Test.InstrumentationTestCase test, global::Android.App.Activity activity) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Scroll a ViewGroup to the bottom by repeatedly calling dragQuarterScreenUp(InstrumentationTestCase, Activity)</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>android.test.ActivityInstrumentationTestCase is deprecated in favor of android.test.ActivityInstrumentationTestCase2, which provides more options for configuring the Activity under test </para></xrefdescription></xrefsect></para>
/// </summary>
/// <java-name>
/// scrollToBottom
/// </java-name>
[Dot42.DexImport("scrollToBottom", "(Landroid/test/ActivityInstrumentationTestCase;Landroid/view/ViewGroup;)V", AccessFlags = 9)]
public static void ScrollToBottom(global::Android.Test.ActivityInstrumentationTestCase<object> test, global::Android.View.ViewGroup v) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Scroll a ViewGroup to the bottom by repeatedly calling dragQuarterScreenUp(InstrumentationTestCase, Activity)</para><para></para>
/// </summary>
/// <java-name>
/// scrollToBottom
/// </java-name>
[Dot42.DexImport("scrollToBottom", "(Landroid/test/InstrumentationTestCase;Landroid/app/Activity;Landroid/view/ViewGr" +
"oup;)V", AccessFlags = 9)]
public static void ScrollToBottom(global::Android.Test.InstrumentationTestCase test, global::Android.App.Activity activity, global::Android.View.ViewGroup v) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Scroll a ViewGroup to the top by repeatedly calling dragQuarterScreenDown(InstrumentationTestCase, Activity)</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>android.test.ActivityInstrumentationTestCase is deprecated in favor of android.test.ActivityInstrumentationTestCase2, which provides more options for configuring the Activity under test </para></xrefdescription></xrefsect></para>
/// </summary>
/// <java-name>
/// scrollToTop
/// </java-name>
[Dot42.DexImport("scrollToTop", "(Landroid/test/ActivityInstrumentationTestCase;Landroid/view/ViewGroup;)V", AccessFlags = 9)]
public static void ScrollToTop(global::Android.Test.ActivityInstrumentationTestCase<object> test, global::Android.View.ViewGroup v) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Scroll a ViewGroup to the top by repeatedly calling dragQuarterScreenDown(InstrumentationTestCase, Activity)</para><para></para>
/// </summary>
/// <java-name>
/// scrollToTop
/// </java-name>
[Dot42.DexImport("scrollToTop", "(Landroid/test/InstrumentationTestCase;Landroid/app/Activity;Landroid/view/ViewGr" +
"oup;)V", AccessFlags = 9)]
public static void ScrollToTop(global::Android.Test.InstrumentationTestCase test, global::Android.App.Activity activity, global::Android.View.ViewGroup v) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Simulate touching the center of a view and dragging to the bottom of the screen.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>android.test.ActivityInstrumentationTestCase is deprecated in favor of android.test.ActivityInstrumentationTestCase2, which provides more options for configuring the Activity under test </para></xrefdescription></xrefsect></para>
/// </summary>
/// <java-name>
/// dragViewToBottom
/// </java-name>
[Dot42.DexImport("dragViewToBottom", "(Landroid/test/ActivityInstrumentationTestCase;Landroid/view/View;)V", AccessFlags = 9)]
public static void DragViewToBottom(global::Android.Test.ActivityInstrumentationTestCase<object> test, global::Android.View.View v) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Simulate touching the center of a view and dragging to the bottom of the screen.</para><para></para>
/// </summary>
/// <java-name>
/// dragViewToBottom
/// </java-name>
[Dot42.DexImport("dragViewToBottom", "(Landroid/test/InstrumentationTestCase;Landroid/app/Activity;Landroid/view/View;)" +
"V", AccessFlags = 9)]
public static void DragViewToBottom(global::Android.Test.InstrumentationTestCase test, global::Android.App.Activity activity, global::Android.View.View v) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Simulate touching the center of a view and dragging to the bottom of the screen.</para><para></para>
/// </summary>
/// <java-name>
/// dragViewToBottom
/// </java-name>
[Dot42.DexImport("dragViewToBottom", "(Landroid/test/ActivityInstrumentationTestCase;Landroid/view/View;I)V", AccessFlags = 9)]
public static void DragViewToBottom(global::Android.Test.ActivityInstrumentationTestCase<object> test, global::Android.View.View activity, int v) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Simulate touching the center of a view and dragging to the bottom of the screen.</para><para></para>
/// </summary>
/// <java-name>
/// dragViewToBottom
/// </java-name>
[Dot42.DexImport("dragViewToBottom", "(Landroid/test/InstrumentationTestCase;Landroid/app/Activity;Landroid/view/View;I" +
")V", AccessFlags = 9)]
public static void DragViewToBottom(global::Android.Test.InstrumentationTestCase test, global::Android.App.Activity activity, global::Android.View.View v, int stepCount) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Simulate touching the center of a view and releasing quickly (before the tap timeout).</para><para></para>
/// </summary>
/// <java-name>
/// tapView
/// </java-name>
[Dot42.DexImport("tapView", "(Landroid/test/InstrumentationTestCase;Landroid/view/View;)V", AccessFlags = 9)]
public static void TapView(global::Android.Test.InstrumentationTestCase test, global::Android.View.View v) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Simulate touching the center of a view and cancelling (so no onClick should fire, etc).</para><para></para>
/// </summary>
/// <java-name>
/// touchAndCancelView
/// </java-name>
[Dot42.DexImport("touchAndCancelView", "(Landroid/test/InstrumentationTestCase;Landroid/view/View;)V", AccessFlags = 9)]
public static void TouchAndCancelView(global::Android.Test.InstrumentationTestCase test, global::Android.View.View v) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Simulate touching the center of a view and releasing.</para><para></para>
/// </summary>
/// <java-name>
/// clickView
/// </java-name>
[Dot42.DexImport("clickView", "(Landroid/test/InstrumentationTestCase;Landroid/view/View;)V", AccessFlags = 9)]
public static void ClickView(global::Android.Test.InstrumentationTestCase test, global::Android.View.View v) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Simulate touching the center of a view, holding until it is a long press, and then releasing.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>android.test.ActivityInstrumentationTestCase is deprecated in favor of android.test.ActivityInstrumentationTestCase2, which provides more options for configuring the Activity under test </para></xrefdescription></xrefsect></para>
/// </summary>
/// <java-name>
/// longClickView
/// </java-name>
[Dot42.DexImport("longClickView", "(Landroid/test/ActivityInstrumentationTestCase;Landroid/view/View;)V", AccessFlags = 9)]
public static void LongClickView(global::Android.Test.ActivityInstrumentationTestCase<object> test, global::Android.View.View v) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Simulate touching the center of a view, holding until it is a long press, and then releasing.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>android.test.ActivityInstrumentationTestCase is deprecated in favor of android.test.ActivityInstrumentationTestCase2, which provides more options for configuring the Activity under test </para></xrefdescription></xrefsect></para>
/// </summary>
/// <java-name>
/// longClickView
/// </java-name>
[Dot42.DexImport("longClickView", "(Landroid/test/InstrumentationTestCase;Landroid/view/View;)V", AccessFlags = 9)]
public static void LongClickView(global::Android.Test.InstrumentationTestCase test, global::Android.View.View v) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Simulate touching the center of a view and dragging to the top of the screen.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>android.test.ActivityInstrumentationTestCase is deprecated in favor of android.test.ActivityInstrumentationTestCase2, which provides more options for configuring the Activity under test </para></xrefdescription></xrefsect></para>
/// </summary>
/// <java-name>
/// dragViewToTop
/// </java-name>
[Dot42.DexImport("dragViewToTop", "(Landroid/test/ActivityInstrumentationTestCase;Landroid/view/View;)V", AccessFlags = 9)]
public static void DragViewToTop(global::Android.Test.ActivityInstrumentationTestCase<object> test, global::Android.View.View v) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Simulate touching the center of a view and dragging to the top of the screen.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>android.test.ActivityInstrumentationTestCase is deprecated in favor of android.test.ActivityInstrumentationTestCase2, which provides more options for configuring the Activity under test </para></xrefdescription></xrefsect></para>
/// </summary>
/// <java-name>
/// dragViewToTop
/// </java-name>
[Dot42.DexImport("dragViewToTop", "(Landroid/test/ActivityInstrumentationTestCase;Landroid/view/View;I)V", AccessFlags = 9)]
public static void DragViewToTop(global::Android.Test.ActivityInstrumentationTestCase<object> test, global::Android.View.View v, int stepCount) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Simulate touching the center of a view and dragging to the top of the screen.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>android.test.ActivityInstrumentationTestCase is deprecated in favor of android.test.ActivityInstrumentationTestCase2, which provides more options for configuring the Activity under test </para></xrefdescription></xrefsect></para>
/// </summary>
/// <java-name>
/// dragViewToTop
/// </java-name>
[Dot42.DexImport("dragViewToTop", "(Landroid/test/InstrumentationTestCase;Landroid/view/View;)V", AccessFlags = 9)]
public static void DragViewToTop(global::Android.Test.InstrumentationTestCase test, global::Android.View.View v) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Simulate touching the center of a view and dragging to the top of the screen.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>android.test.ActivityInstrumentationTestCase is deprecated in favor of android.test.ActivityInstrumentationTestCase2, which provides more options for configuring the Activity under test </para></xrefdescription></xrefsect></para>
/// </summary>
/// <java-name>
/// dragViewToTop
/// </java-name>
[Dot42.DexImport("dragViewToTop", "(Landroid/test/InstrumentationTestCase;Landroid/view/View;I)V", AccessFlags = 9)]
public static void DragViewToTop(global::Android.Test.InstrumentationTestCase test, global::Android.View.View v, int stepCount) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Simulate touching a view and dragging it by the specified amount.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>android.test.ActivityInstrumentationTestCase is deprecated in favor of android.test.ActivityInstrumentationTestCase2, which provides more options for configuring the Activity under test </para></xrefdescription></xrefsect></para>
/// </summary>
/// <returns>
/// <para>distance in pixels covered by the drag</para>
/// </returns>
/// <java-name>
/// dragViewBy
/// </java-name>
[Dot42.DexImport("dragViewBy", "(Landroid/test/ActivityInstrumentationTestCase;Landroid/view/View;III)I", AccessFlags = 9)]
public static int DragViewBy(global::Android.Test.ActivityInstrumentationTestCase<object> test, global::Android.View.View v, int gravity, int deltaX, int deltaY) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Simulate touching a view and dragging it by the specified amount.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>android.test.ActivityInstrumentationTestCase is deprecated in favor of android.test.ActivityInstrumentationTestCase2, which provides more options for configuring the Activity under test </para></xrefdescription></xrefsect></para>
/// </summary>
/// <returns>
/// <para>distance in pixels covered by the drag</para>
/// </returns>
/// <java-name>
/// dragViewBy
/// </java-name>
[Dot42.DexImport("dragViewBy", "(Landroid/test/InstrumentationTestCase;Landroid/view/View;III)I", AccessFlags = 9)]
public static int DragViewBy(global::Android.Test.InstrumentationTestCase test, global::Android.View.View v, int gravity, int deltaX, int deltaY) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Simulate touching a view and dragging it to a specified location.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>android.test.ActivityInstrumentationTestCase is deprecated in favor of android.test.ActivityInstrumentationTestCase2, which provides more options for configuring the Activity under test </para></xrefdescription></xrefsect></para>
/// </summary>
/// <returns>
/// <para>distance in pixels covered by the drag</para>
/// </returns>
/// <java-name>
/// dragViewTo
/// </java-name>
[Dot42.DexImport("dragViewTo", "(Landroid/test/ActivityInstrumentationTestCase;Landroid/view/View;III)I", AccessFlags = 9)]
public static int DragViewTo(global::Android.Test.ActivityInstrumentationTestCase<object> test, global::Android.View.View v, int gravity, int toX, int toY) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Simulate touching a view and dragging it to a specified location.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>android.test.ActivityInstrumentationTestCase is deprecated in favor of android.test.ActivityInstrumentationTestCase2, which provides more options for configuring the Activity under test </para></xrefdescription></xrefsect></para>
/// </summary>
/// <returns>
/// <para>distance in pixels covered by the drag</para>
/// </returns>
/// <java-name>
/// dragViewTo
/// </java-name>
[Dot42.DexImport("dragViewTo", "(Landroid/test/InstrumentationTestCase;Landroid/view/View;III)I", AccessFlags = 9)]
public static int DragViewTo(global::Android.Test.InstrumentationTestCase test, global::Android.View.View v, int gravity, int toX, int toY) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Simulate touching a view and dragging it to a specified location. Only moves horizontally.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>android.test.ActivityInstrumentationTestCase is deprecated in favor of android.test.ActivityInstrumentationTestCase2, which provides more options for configuring the Activity under test </para></xrefdescription></xrefsect></para>
/// </summary>
/// <returns>
/// <para>distance in pixels covered by the drag</para>
/// </returns>
/// <java-name>
/// dragViewToX
/// </java-name>
[Dot42.DexImport("dragViewToX", "(Landroid/test/ActivityInstrumentationTestCase;Landroid/view/View;II)I", AccessFlags = 9)]
public static int DragViewToX(global::Android.Test.ActivityInstrumentationTestCase<object> test, global::Android.View.View v, int gravity, int toX) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Simulate touching a view and dragging it to a specified location. Only moves horizontally.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>android.test.ActivityInstrumentationTestCase is deprecated in favor of android.test.ActivityInstrumentationTestCase2, which provides more options for configuring the Activity under test </para></xrefdescription></xrefsect></para>
/// </summary>
/// <returns>
/// <para>distance in pixels covered by the drag</para>
/// </returns>
/// <java-name>
/// dragViewToX
/// </java-name>
[Dot42.DexImport("dragViewToX", "(Landroid/test/InstrumentationTestCase;Landroid/view/View;II)I", AccessFlags = 9)]
public static int DragViewToX(global::Android.Test.InstrumentationTestCase test, global::Android.View.View v, int gravity, int toX) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Simulate touching a view and dragging it to a specified location. Only moves vertically.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>android.test.ActivityInstrumentationTestCase is deprecated in favor of android.test.ActivityInstrumentationTestCase2, which provides more options for configuring the Activity under test </para></xrefdescription></xrefsect></para>
/// </summary>
/// <returns>
/// <para>distance in pixels covered by the drag</para>
/// </returns>
/// <java-name>
/// dragViewToY
/// </java-name>
[Dot42.DexImport("dragViewToY", "(Landroid/test/ActivityInstrumentationTestCase;Landroid/view/View;II)I", AccessFlags = 9)]
public static int DragViewToY(global::Android.Test.ActivityInstrumentationTestCase<object> test, global::Android.View.View v, int gravity, int toY) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Simulate touching a view and dragging it to a specified location. Only moves vertically.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>android.test.ActivityInstrumentationTestCase is deprecated in favor of android.test.ActivityInstrumentationTestCase2, which provides more options for configuring the Activity under test </para></xrefdescription></xrefsect></para>
/// </summary>
/// <returns>
/// <para>distance in pixels covered by the drag</para>
/// </returns>
/// <java-name>
/// dragViewToY
/// </java-name>
[Dot42.DexImport("dragViewToY", "(Landroid/test/InstrumentationTestCase;Landroid/view/View;II)I", AccessFlags = 9)]
public static int DragViewToY(global::Android.Test.InstrumentationTestCase test, global::Android.View.View v, int gravity, int toY) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// drag
/// </java-name>
[Dot42.DexImport("drag", "(Landroid/test/ActivityInstrumentationTestCase;FFFFI)V", AccessFlags = 9)]
public static void Drag(global::Android.Test.ActivityInstrumentationTestCase<object> activityInstrumentationTestCase, float single, float single1, float single2, float single3, int int32) /* MethodBuilder.Create */
{
}
/// <java-name>
/// drag
/// </java-name>
[Dot42.DexImport("drag", "(Landroid/test/InstrumentationTestCase;FFFFI)V", AccessFlags = 9)]
public static void Drag(global::Android.Test.InstrumentationTestCase instrumentationTestCase, float single, float single1, float single2, float single3, int int32) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>This test case provides a framework in which you can test Application classes in a controlled environment. It provides basic support for the lifecycle of a Application, and hooks by which you can inject various dependencies and control the environment in which your Application is tested.</para><para><b>Lifecycle Support.</b> Every Application is designed to be accessed within a specific sequence of method calls (see android.app.Application for more details). In order to support the lifecycle of a Application, this test case will make the following calls at the following times.</para><para><ul><li><para>The test case will not call onCreate() until your test calls createApplication(). This gives you a chance to set up or adjust any additional framework or test logic before onCreate(). </para></li><li><para>After your test completes, the test case tearDown method is automatically called, and it will stop & destroy your application by calling its onDestroy() method. </para></li></ul></para><para><b>Dependency Injection.</b> Every Application has one inherent dependency, the Context in which it runs. This framework allows you to inject a modified, mock, or isolated replacement for this dependencies, and thus perform a true unit test.</para><para>If simply run your tests as-is, your Application will be injected with a fully-functional Context. You can create and inject alternative types of Contexts by calling setContext(). You must do this <b>before</b> calling createApplication(). The test framework provides a number of alternatives for Context, including MockContext, RenamingDelegatingContext, and ContextWrapper. </para>
/// </summary>
/// <java-name>
/// android/test/ApplicationTestCase
/// </java-name>
[Dot42.DexImport("android/test/ApplicationTestCase", AccessFlags = 1057, Signature = "<T:Landroid/app/Application;>Landroid/test/AndroidTestCase;")]
public abstract partial class ApplicationTestCase<T> : global::Android.Test.AndroidTestCase
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Ljava/lang/Class;)V", AccessFlags = 1, Signature = "(Ljava/lang/Class<TT;>;)V")]
public ApplicationTestCase(global::System.Type applicationClass) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>Returns the actual Application under test. </para>
/// </returns>
/// <java-name>
/// getApplication
/// </java-name>
[Dot42.DexImport("getApplication", "()Landroid/app/Application;", AccessFlags = 1, Signature = "()TT;")]
public virtual T GetApplication() /* MethodBuilder.Create */
{
return default(T);
}
/// <summary>
/// <para>This will do the work to instantiate the Application under test. After this, your test code must also start and stop the Application. </para>
/// </summary>
/// <java-name>
/// setUp
/// </java-name>
[Dot42.DexImport("setUp", "()V", AccessFlags = 4)]
protected internal override void SetUp() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Start the Application under test, in the same way as if it was started by the system. If you use this method to start the Application, it will automatically be stopped by tearDown. If you wish to inject a specialized Context for your test, by calling setContext(), you must do so before calling this method. </para>
/// </summary>
/// <java-name>
/// createApplication
/// </java-name>
[Dot42.DexImport("createApplication", "()V", AccessFlags = 20)]
protected internal void CreateApplication() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>This will make the necessary calls to terminate the Application under test (it will call onTerminate(). Ordinarily this will be called automatically (by tearDown, but you can call it directly from your test in order to check for proper shutdown behaviors. </para>
/// </summary>
/// <java-name>
/// terminateApplication
/// </java-name>
[Dot42.DexImport("terminateApplication", "()V", AccessFlags = 20)]
protected internal void TerminateApplication() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Shuts down the Application under test. Also makes sure all resources are cleaned up and garbage collected before moving on to the next test. Subclasses that override this method should make sure they call super.tearDown() at the end of the overriding method.</para><para></para>
/// </summary>
/// <java-name>
/// tearDown
/// </java-name>
[Dot42.DexImport("tearDown", "()V", AccessFlags = 4)]
protected internal override void TearDown() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Return a real (not mocked or instrumented) system Context that can be used when generating Mock or other Context objects for your Application under test.</para><para></para>
/// </summary>
/// <returns>
/// <para>Returns a reference to a normal Context. </para>
/// </returns>
/// <java-name>
/// getSystemContext
/// </java-name>
[Dot42.DexImport("getSystemContext", "()Landroid/content/Context;", AccessFlags = 1)]
public virtual global::Android.Content.Context GetSystemContext() /* MethodBuilder.Create */
{
return default(global::Android.Content.Context);
}
/// <summary>
/// <para>This test simply confirms that the Application class can be instantiated properly.</para><para></para>
/// </summary>
/// <java-name>
/// testApplicationTestCaseSetUpProperly
/// </java-name>
[Dot42.DexImport("testApplicationTestCaseSetUpProperly", "()V", AccessFlags = 17)]
public void TestApplicationTestCaseSetUpProperly() /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal ApplicationTestCase() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>Returns the actual Application under test. </para>
/// </returns>
/// <java-name>
/// getApplication
/// </java-name>
public T Application
{
[Dot42.DexImport("getApplication", "()Landroid/app/Application;", AccessFlags = 1, Signature = "()TT;")]
get{ return GetApplication(); }
}
/// <summary>
/// <para>Return a real (not mocked or instrumented) system Context that can be used when generating Mock or other Context objects for your Application under test.</para><para></para>
/// </summary>
/// <returns>
/// <para>Returns a reference to a normal Context. </para>
/// </returns>
/// <java-name>
/// getSystemContext
/// </java-name>
public global::Android.Content.Context SystemContext
{
[Dot42.DexImport("getSystemContext", "()Landroid/content/Context;", AccessFlags = 1)]
get{ return GetSystemContext(); }
}
}
/// <summary>
/// <para>This annotation can be used on an android.test.InstrumentationTestCase's test methods. When the annotation is present, the test method is re-executed if the test fails. The total number of executions is specified by the tolerance and defaults to 1. </para>
/// </summary>
/// <java-name>
/// android/test/FlakyTest
/// </java-name>
[Dot42.DexImport("android/test/FlakyTest", AccessFlags = 9729)]
public partial interface IFlakyTest : global::Java.Lang.Annotation.IAnnotation
/* scope: __dot42__ */
{
/// <summary>
/// <para>Indicates how many times a test can run and fail before being reported as a failed test. If the tolerance factor is less than 1, the test runs only once.</para><para></para>
/// </summary>
/// <returns>
/// <para>The total number of allowed run, the default is 1. </para>
/// </returns>
/// <java-name>
/// tolerance
/// </java-name>
[Dot42.DexImport("tolerance", "()I", AccessFlags = 1025)]
int Tolerance() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Extend this if you need to access Resources or other things that depend on Activity Context. </para>
/// </summary>
/// <java-name>
/// android/test/AndroidTestCase
/// </java-name>
[Dot42.DexImport("android/test/AndroidTestCase", AccessFlags = 33)]
public partial class AndroidTestCase : global::Junit.Framework.TestCase
/* scope: __dot42__ */
{
/// <java-name>
/// mContext
/// </java-name>
[Dot42.DexImport("mContext", "Landroid/content/Context;", AccessFlags = 4)]
protected internal global::Android.Content.Context MContext;
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public AndroidTestCase() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets up the fixture, for example, open a network connection. This method is called before a test is executed. </para>
/// </summary>
/// <java-name>
/// setUp
/// </java-name>
[Dot42.DexImport("setUp", "()V", AccessFlags = 4)]
protected internal override void SetUp() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tears down the fixture, for example, close a network connection. This method is called after a test is executed. </para>
/// </summary>
/// <java-name>
/// tearDown
/// </java-name>
[Dot42.DexImport("tearDown", "()V", AccessFlags = 4)]
protected internal override void TearDown() /* MethodBuilder.Create */
{
}
/// <java-name>
/// testAndroidTestCaseSetupProperly
/// </java-name>
[Dot42.DexImport("testAndroidTestCaseSetupProperly", "()V", AccessFlags = 1)]
public virtual void TestAndroidTestCaseSetupProperly() /* MethodBuilder.Create */
{
}
/// <java-name>
/// setContext
/// </java-name>
[Dot42.DexImport("setContext", "(Landroid/content/Context;)V", AccessFlags = 1)]
public virtual void SetContext(global::Android.Content.Context context) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getContext
/// </java-name>
[Dot42.DexImport("getContext", "()Landroid/content/Context;", AccessFlags = 1)]
public virtual global::Android.Content.Context GetContext() /* MethodBuilder.Create */
{
return default(global::Android.Content.Context);
}
/// <summary>
/// <para>Asserts that launching a given activity is protected by a particular permission by attempting to start the activity and validating that a SecurityException is thrown that mentions the permission in its error message.</para><para>Note that an instrumentation isn't needed because all we are looking for is a security error and we don't need to wait for the activity to launch and get a handle to the activity.</para><para></para>
/// </summary>
/// <java-name>
/// assertActivityRequiresPermission
/// </java-name>
[Dot42.DexImport("assertActivityRequiresPermission", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void AssertActivityRequiresPermission(string packageName, string className, string permission) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that reading from the content uri requires a particular permission by querying the uri and ensuring a SecurityException is thrown mentioning the particular permission.</para><para></para>
/// </summary>
/// <java-name>
/// assertReadingContentUriRequiresPermission
/// </java-name>
[Dot42.DexImport("assertReadingContentUriRequiresPermission", "(Landroid/net/Uri;Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void AssertReadingContentUriRequiresPermission(global::Android.Net.Uri uri, string permission) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that writing to the content uri requires a particular permission by inserting into the uri and ensuring a SecurityException is thrown mentioning the particular permission.</para><para></para>
/// </summary>
/// <java-name>
/// assertWritingContentUriRequiresPermission
/// </java-name>
[Dot42.DexImport("assertWritingContentUriRequiresPermission", "(Landroid/net/Uri;Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void AssertWritingContentUriRequiresPermission(global::Android.Net.Uri uri, string permission) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>This function is called by various TestCase implementations, at tearDown() time, in order to scrub out any class variables. This protects against memory leaks in the case where a test case creates a non-static inner class (thus referencing the test case) and gives it to someone else to hold onto.</para><para></para>
/// </summary>
/// <java-name>
/// scrubClass
/// </java-name>
[Dot42.DexImport("scrubClass", "(Ljava/lang/Class;)V", AccessFlags = 4, Signature = "(Ljava/lang/Class<*>;)V")]
protected internal virtual void ScrubClass(global::System.Type testCaseClass) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getContext
/// </java-name>
public global::Android.Content.Context Context
{
[Dot42.DexImport("getContext", "()Landroid/content/Context;", AccessFlags = 1)]
get{ return GetContext(); }
[Dot42.DexImport("setContext", "(Landroid/content/Context;)V", AccessFlags = 1)]
set{ SetContext(value); }
}
}
/// <summary>
/// <para><span>A mock context which prevents its users from talking to the rest of the device while</span> stubbing enough methods to satify code that tries to talk to other packages. </para>
/// </summary>
/// <java-name>
/// android/test/IsolatedContext
/// </java-name>
[Dot42.DexImport("android/test/IsolatedContext", AccessFlags = 33)]
public partial class IsolatedContext : global::Android.Content.ContextWrapper
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Landroid/content/ContentResolver;Landroid/content/Context;)V", AccessFlags = 1)]
public IsolatedContext(global::Android.Content.ContentResolver resolver, global::Android.Content.Context targetContext) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the list of intents that were broadcast since the last call to this method. </para>
/// </summary>
/// <java-name>
/// getAndClearBroadcastIntents
/// </java-name>
[Dot42.DexImport("getAndClearBroadcastIntents", "()Ljava/util/List;", AccessFlags = 1, Signature = "()Ljava/util/List<Landroid/content/Intent;>;")]
public virtual global::Java.Util.IList<global::Android.Content.Intent> GetAndClearBroadcastIntents() /* MethodBuilder.Create */
{
return default(global::Java.Util.IList<global::Android.Content.Intent>);
}
/// <summary>
/// <para>Return a ContentResolver instance for your application's package. </para>
/// </summary>
/// <java-name>
/// getContentResolver
/// </java-name>
[Dot42.DexImport("getContentResolver", "()Landroid/content/ContentResolver;", AccessFlags = 1)]
public override global::Android.Content.ContentResolver GetContentResolver() /* MethodBuilder.Create */
{
return default(global::Android.Content.ContentResolver);
}
/// <summary>
/// <para>Connect to an application service, creating it if needed. This defines a dependency between your application and the service. The given <b>conn</b> will receive the service object when it is created and be told if it dies and restarts. The service will be considered required by the system only for as long as the calling context exists. For example, if this Context is an Activity that is stopped, the service will not be required to continue running until the Activity is resumed.</para><para>This function will throw SecurityException if you do not have permission to bind to the given service.</para><para>Note: this method <b>can not be called from a BroadcastReceiver component</b>. A pattern you can use to communicate from a BroadcastReceiver to a Service is to call startService with the arguments containing the command to be sent, with the service calling its android.app.Service#stopSelf(int) method when done executing that command. See the API demo App/Service/Service Start Arguments Controller for an illustration of this. It is okay, however, to use this method from a BroadcastReceiver that has been registered with registerReceiver, since the lifetime of this BroadcastReceiver is tied to another object (the one that registered it).</para><para><para>unbindService </para><simplesectsep></simplesectsep><para>startService </para><simplesectsep></simplesectsep><para>BIND_AUTO_CREATE </para><simplesectsep></simplesectsep><para>BIND_DEBUG_UNBIND </para><simplesectsep></simplesectsep><para>BIND_NOT_FOREGROUND </para></para>
/// </summary>
/// <returns>
/// <para>If you have successfully bound to the service, true is returned; false is returned if the connection is not made so you will not receive the service object.</para>
/// </returns>
/// <java-name>
/// bindService
/// </java-name>
[Dot42.DexImport("bindService", "(Landroid/content/Intent;Landroid/content/ServiceConnection;I)Z", AccessFlags = 1)]
public override bool BindService(global::Android.Content.Intent service, global::Android.Content.IServiceConnection conn, int flags) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Register a BroadcastReceiver to be run in the main activity thread. The <b>receiver</b> will be called with any broadcast Intent that matches <b>filter</b>, in the main application thread.</para><para>The system may broadcast Intents that are "sticky" these stay around after the broadcast as finished, to be sent to any later registrations. If your IntentFilter matches one of these sticky Intents, that Intent will be returned by this function <b>and</b> sent to your <b>receiver</b> as if it had just been broadcast.</para><para>There may be multiple sticky Intents that match <b>filter</b>, in which case each of these will be sent to <b>receiver</b>. In this case, only one of these can be returned directly by the function; which of these that is returned is arbitrarily decided by the system.</para><para>If you know the Intent your are registering for is sticky, you can supply null for your <b>receiver</b>. In this case, no receiver is registered the function simply returns the sticky Intent that matches <b>filter</b>. In the case of multiple matches, the same rules as described above apply.</para><para>See BroadcastReceiver for more information on Intent broadcasts.</para><para>As of android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH, receivers registered with this method will correctly respect the Intent#setPackage(String) specified for an Intent being broadcast. Prior to that, it would be ignored and delivered to all matching registered receivers. Be careful if using this for security.</para><para>Note: this method <b>cannot be called from a BroadcastReceiver component;</b> that is, from a BroadcastReceiver that is declared in an application's manifest. It is okay, however, to call this method from another BroadcastReceiver that has itself been registered at run time with registerReceiver, since the lifetime of such a registered BroadcastReceiver is tied to the object that registered it.</para><para><para>registerReceiver(BroadcastReceiver, IntentFilter, String, Handler) </para><simplesectsep></simplesectsep><para>sendBroadcast </para><simplesectsep></simplesectsep><para>unregisterReceiver </para></para>
/// </summary>
/// <returns>
/// <para>The first sticky intent found that matches <b>filter</b>, or null if there are none.</para>
/// </returns>
/// <java-name>
/// registerReceiver
/// </java-name>
[Dot42.DexImport("registerReceiver", "(Landroid/content/BroadcastReceiver;Landroid/content/IntentFilter;)Landroid/conte" +
"nt/Intent;", AccessFlags = 1)]
public override global::Android.Content.Intent RegisterReceiver(global::Android.Content.BroadcastReceiver receiver, global::Android.Content.IntentFilter filter) /* MethodBuilder.Create */
{
return default(global::Android.Content.Intent);
}
/// <summary>
/// <para>Unregister a previously registered BroadcastReceiver. <b>All</b> filters that have been registered for this BroadcastReceiver will be removed.</para><para><para>registerReceiver </para></para>
/// </summary>
/// <java-name>
/// unregisterReceiver
/// </java-name>
[Dot42.DexImport("unregisterReceiver", "(Landroid/content/BroadcastReceiver;)V", AccessFlags = 1)]
public override void UnregisterReceiver(global::Android.Content.BroadcastReceiver receiver) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Broadcast the given intent to all interested BroadcastReceivers. This call is asynchronous; it returns immediately, and you will continue executing while the receivers are run. No results are propagated from receivers and receivers can not abort the broadcast. If you want to allow receivers to propagate results or abort the broadcast, you must send an ordered broadcast using sendOrderedBroadcast(Intent, String).</para><para>See BroadcastReceiver for more information on Intent broadcasts.</para><para><para>android.content.BroadcastReceiver </para><simplesectsep></simplesectsep><para>registerReceiver </para><simplesectsep></simplesectsep><para>sendBroadcast(Intent, String) </para><simplesectsep></simplesectsep><para>sendOrderedBroadcast(Intent, String) </para><simplesectsep></simplesectsep><para>sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle) </para></para>
/// </summary>
/// <java-name>
/// sendBroadcast
/// </java-name>
[Dot42.DexImport("sendBroadcast", "(Landroid/content/Intent;)V", AccessFlags = 1)]
public override void SendBroadcast(global::Android.Content.Intent intent) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Broadcast the given intent to all interested BroadcastReceivers, delivering them one at a time to allow more preferred receivers to consume the broadcast before it is delivered to less preferred receivers. This call is asynchronous; it returns immediately, and you will continue executing while the receivers are run.</para><para>See BroadcastReceiver for more information on Intent broadcasts.</para><para><para>android.content.BroadcastReceiver </para><simplesectsep></simplesectsep><para>registerReceiver </para><simplesectsep></simplesectsep><para>sendBroadcast(Intent) </para><simplesectsep></simplesectsep><para>sendOrderedBroadcast(Intent, String, BroadcastReceiver, Handler, int, String, Bundle) </para></para>
/// </summary>
/// <java-name>
/// sendOrderedBroadcast
/// </java-name>
[Dot42.DexImport("sendOrderedBroadcast", "(Landroid/content/Intent;Ljava/lang/String;)V", AccessFlags = 1)]
public override void SendOrderedBroadcast(global::Android.Content.Intent intent, string receiverPermission) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Check both a Uri and normal permission. This allows you to perform both checkPermission and checkUriPermission in one call.</para><para></para>
/// </summary>
/// <returns>
/// <para>Returns PackageManager#PERMISSION_GRANTED if the caller is allowed to access that uri or holds one of the given permissions, or PackageManager#PERMISSION_DENIED if it is not. </para>
/// </returns>
/// <java-name>
/// checkUriPermission
/// </java-name>
[Dot42.DexImport("checkUriPermission", "(Landroid/net/Uri;Ljava/lang/String;Ljava/lang/String;III)I", AccessFlags = 1)]
public override int CheckUriPermission(global::Android.Net.Uri uri, string readPermission, string writePermission, int pid, int uid, int modeFlags) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Determine whether a particular process and user ID has been granted permission to access a specific URI. This only checks for permissions that have been explicitly granted if the given process/uid has more general access to the URI's content provider then this check will always fail.</para><para><para>checkCallingUriPermission </para></para>
/// </summary>
/// <returns>
/// <para>Returns PackageManager#PERMISSION_GRANTED if the given pid/uid is allowed to access that uri, or PackageManager#PERMISSION_DENIED if it is not.</para>
/// </returns>
/// <java-name>
/// checkUriPermission
/// </java-name>
[Dot42.DexImport("checkUriPermission", "(Landroid/net/Uri;III)I", AccessFlags = 1)]
public override int CheckUriPermission(global::Android.Net.Uri uri, int pid, int uid, int modeFlags) /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Return the handle to a system-level service by name. The class of the returned object varies by the requested name. Currently available names are:</para><para></para><para>Note: System services obtained via this API may be closely associated with the Context in which they are obtained from. In general, do not share the service objects between various different contexts (Activities, Applications, Services, Providers, etc.)</para><para><para>WINDOW_SERVICE </para><simplesectsep></simplesectsep><para>android.view.WindowManager </para><simplesectsep></simplesectsep><para>LAYOUT_INFLATER_SERVICE </para><simplesectsep></simplesectsep><para>android.view.LayoutInflater </para><simplesectsep></simplesectsep><para>ACTIVITY_SERVICE </para><simplesectsep></simplesectsep><para>android.app.ActivityManager </para><simplesectsep></simplesectsep><para>POWER_SERVICE </para><simplesectsep></simplesectsep><para>android.os.PowerManager </para><simplesectsep></simplesectsep><para>ALARM_SERVICE </para><simplesectsep></simplesectsep><para>android.app.AlarmManager </para><simplesectsep></simplesectsep><para>NOTIFICATION_SERVICE </para><simplesectsep></simplesectsep><para>android.app.NotificationManager </para><simplesectsep></simplesectsep><para>KEYGUARD_SERVICE </para><simplesectsep></simplesectsep><para>android.app.KeyguardManager </para><simplesectsep></simplesectsep><para>LOCATION_SERVICE </para><simplesectsep></simplesectsep><para>android.location.LocationManager </para><simplesectsep></simplesectsep><para>SEARCH_SERVICE </para><simplesectsep></simplesectsep><para>android.app.SearchManager </para><simplesectsep></simplesectsep><para>SENSOR_SERVICE </para><simplesectsep></simplesectsep><para>android.hardware.SensorManager </para><simplesectsep></simplesectsep><para>STORAGE_SERVICE </para><simplesectsep></simplesectsep><para>android.os.storage.StorageManager </para><simplesectsep></simplesectsep><para>VIBRATOR_SERVICE </para><simplesectsep></simplesectsep><para>android.os.Vibrator </para><simplesectsep></simplesectsep><para>CONNECTIVITY_SERVICE </para><simplesectsep></simplesectsep><para>android.net.ConnectivityManager </para><simplesectsep></simplesectsep><para>WIFI_SERVICE </para><simplesectsep></simplesectsep><para>android.net.wifi.WifiManager </para><simplesectsep></simplesectsep><para>AUDIO_SERVICE </para><simplesectsep></simplesectsep><para>android.media.AudioManager </para><simplesectsep></simplesectsep><para>MEDIA_ROUTER_SERVICE </para><simplesectsep></simplesectsep><para>android.media.MediaRouter </para><simplesectsep></simplesectsep><para>TELEPHONY_SERVICE </para><simplesectsep></simplesectsep><para>android.telephony.TelephonyManager </para><simplesectsep></simplesectsep><para>INPUT_METHOD_SERVICE </para><simplesectsep></simplesectsep><para>android.view.inputmethod.InputMethodManager </para><simplesectsep></simplesectsep><para>UI_MODE_SERVICE </para><simplesectsep></simplesectsep><para>android.app.UiModeManager </para><simplesectsep></simplesectsep><para>DOWNLOAD_SERVICE </para><simplesectsep></simplesectsep><para>android.app.DownloadManager </para></para>
/// </summary>
/// <returns>
/// <para>The service or null if the name does not exist.</para>
/// </returns>
/// <java-name>
/// getSystemService
/// </java-name>
[Dot42.DexImport("getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;", AccessFlags = 1)]
public override object GetSystemService(string name) /* MethodBuilder.Create */
{
return default(object);
}
/// <summary>
/// <para>Returns the absolute path to the directory on the filesystem where files created with openFileOutput are stored.</para><para><para>openFileOutput </para><simplesectsep></simplesectsep><para>getFileStreamPath </para><simplesectsep></simplesectsep><para>getDir </para></para>
/// </summary>
/// <returns>
/// <para>Returns the path of the directory holding application files.</para>
/// </returns>
/// <java-name>
/// getFilesDir
/// </java-name>
[Dot42.DexImport("getFilesDir", "()Ljava/io/File;", AccessFlags = 1)]
public override global::Java.Io.File GetFilesDir() /* MethodBuilder.Create */
{
return default(global::Java.Io.File);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal IsolatedContext() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Returns the list of intents that were broadcast since the last call to this method. </para>
/// </summary>
/// <java-name>
/// getAndClearBroadcastIntents
/// </java-name>
public global::Java.Util.IList<global::Android.Content.Intent> AndClearBroadcastIntents
{
[Dot42.DexImport("getAndClearBroadcastIntents", "()Ljava/util/List;", AccessFlags = 1, Signature = "()Ljava/util/List<Landroid/content/Intent;>;")]
get{ return GetAndClearBroadcastIntents(); }
}
/// <summary>
/// <para>Return a ContentResolver instance for your application's package. </para>
/// </summary>
/// <java-name>
/// getContentResolver
/// </java-name>
public global::Android.Content.ContentResolver ContentResolver
{
[Dot42.DexImport("getContentResolver", "()Landroid/content/ContentResolver;", AccessFlags = 1)]
get{ return GetContentResolver(); }
}
/// <summary>
/// <para>Returns the absolute path to the directory on the filesystem where files created with openFileOutput are stored.</para><para><para>openFileOutput </para><simplesectsep></simplesectsep><para>getFileStreamPath </para><simplesectsep></simplesectsep><para>getDir </para></para>
/// </summary>
/// <returns>
/// <para>Returns the path of the directory holding application files.</para>
/// </returns>
/// <java-name>
/// getFilesDir
/// </java-name>
public global::Java.Io.File FilesDir
{
[Dot42.DexImport("getFilesDir", "()Ljava/io/File;", AccessFlags = 1)]
get{ return GetFilesDir(); }
}
}
/// <java-name>
/// android/test/AndroidTestRunner
/// </java-name>
[Dot42.DexImport("android/test/AndroidTestRunner", AccessFlags = 33)]
public partial class AndroidTestRunner : global::Junit.Runner.BaseTestRunner
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public AndroidTestRunner() /* MethodBuilder.Create */
{
}
/// <java-name>
/// setTestClassName
/// </java-name>
[Dot42.DexImport("setTestClassName", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetTestClassName(string testClassName, string testMethodName) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setTest
/// </java-name>
[Dot42.DexImport("setTest", "(Ljunit/framework/Test;)V", AccessFlags = 1)]
public virtual void SetTest(global::Junit.Framework.ITest test) /* MethodBuilder.Create */
{
}
/// <java-name>
/// clearTestListeners
/// </java-name>
[Dot42.DexImport("clearTestListeners", "()V", AccessFlags = 1)]
public virtual void ClearTestListeners() /* MethodBuilder.Create */
{
}
/// <java-name>
/// addTestListener
/// </java-name>
[Dot42.DexImport("addTestListener", "(Ljunit/framework/TestListener;)V", AccessFlags = 1)]
public virtual void AddTestListener(global::Junit.Framework.ITestListener testListener) /* MethodBuilder.Create */
{
}
/// <java-name>
/// createTestResult
/// </java-name>
[Dot42.DexImport("createTestResult", "()Ljunit/framework/TestResult;", AccessFlags = 4)]
protected internal virtual global::Junit.Framework.TestResult CreateTestResult() /* MethodBuilder.Create */
{
return default(global::Junit.Framework.TestResult);
}
/// <java-name>
/// getTestCases
/// </java-name>
[Dot42.DexImport("getTestCases", "()Ljava/util/List;", AccessFlags = 1, Signature = "()Ljava/util/List<Ljunit/framework/TestCase;>;")]
public virtual global::Java.Util.IList<global::Junit.Framework.TestCase> GetTestCases() /* MethodBuilder.Create */
{
return default(global::Java.Util.IList<global::Junit.Framework.TestCase>);
}
/// <java-name>
/// getTestClassName
/// </java-name>
[Dot42.DexImport("getTestClassName", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetTestClassName() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getTestResult
/// </java-name>
[Dot42.DexImport("getTestResult", "()Ljunit/framework/TestResult;", AccessFlags = 1)]
public virtual global::Junit.Framework.TestResult GetTestResult() /* MethodBuilder.Create */
{
return default(global::Junit.Framework.TestResult);
}
/// <java-name>
/// runTest
/// </java-name>
[Dot42.DexImport("runTest", "()V", AccessFlags = 1)]
public virtual void RunTest() /* MethodBuilder.Create */
{
}
/// <java-name>
/// runTest
/// </java-name>
[Dot42.DexImport("runTest", "(Ljunit/framework/TestResult;)V", AccessFlags = 1)]
public virtual void RunTest(global::Junit.Framework.TestResult testResult) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setContext
/// </java-name>
[Dot42.DexImport("setContext", "(Landroid/content/Context;)V", AccessFlags = 1)]
public virtual void SetContext(global::Android.Content.Context context) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setInstrumentation
/// </java-name>
[Dot42.DexImport("setInstrumentation", "(Landroid/app/Instrumentation;)V", AccessFlags = 1)]
public virtual void SetInstrumentation(global::Android.App.Instrumentation instrumentation) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Incorrect spelling, use setInstrumentation(android.app.Instrumentation) instead. </para></xrefdescription></xrefsect></para>
/// </summary>
/// <java-name>
/// setInstrumentaiton
/// </java-name>
[Dot42.DexImport("setInstrumentaiton", "(Landroid/app/Instrumentation;)V", AccessFlags = 1)]
public virtual void SetInstrumentaiton(global::Android.App.Instrumentation instrumentation) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the loaded Class for a suite name. </para>
/// </summary>
/// <java-name>
/// loadSuiteClass
/// </java-name>
[Dot42.DexImport("loadSuiteClass", "(Ljava/lang/String;)Ljava/lang/Class;", AccessFlags = 4)]
protected internal override global::System.Type LoadSuiteClass(string suiteClassName) /* MethodBuilder.Create */
{
return default(global::System.Type);
}
/// <java-name>
/// testStarted
/// </java-name>
[Dot42.DexImport("testStarted", "(Ljava/lang/String;)V", AccessFlags = 1)]
public override void TestStarted(string testName) /* MethodBuilder.Create */
{
}
/// <java-name>
/// testEnded
/// </java-name>
[Dot42.DexImport("testEnded", "(Ljava/lang/String;)V", AccessFlags = 1)]
public override void TestEnded(string testName) /* MethodBuilder.Create */
{
}
/// <java-name>
/// testFailed
/// </java-name>
[Dot42.DexImport("testFailed", "(ILjunit/framework/Test;Ljava/lang/Throwable;)V", AccessFlags = 1)]
public override void TestFailed(int status, global::Junit.Framework.ITest test, global::System.Exception t) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Override to define how to handle a failed loading of a test suite. </para>
/// </summary>
/// <java-name>
/// runFailed
/// </java-name>
[Dot42.DexImport("runFailed", "(Ljava/lang/String;)V", AccessFlags = 4)]
protected internal override void RunFailed(string message) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getTestCases
/// </java-name>
public global::Java.Util.IList<global::Junit.Framework.TestCase> TestCases
{
[Dot42.DexImport("getTestCases", "()Ljava/util/List;", AccessFlags = 1, Signature = "()Ljava/util/List<Ljunit/framework/TestCase;>;")]
get{ return GetTestCases(); }
}
/// <java-name>
/// getTestClassName
/// </java-name>
public string TestClassName
{
[Dot42.DexImport("getTestClassName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetTestClassName(); }
}
/// <java-name>
/// getTestResult
/// </java-name>
public global::Junit.Framework.TestResult TestResult
{
[Dot42.DexImport("getTestResult", "()Ljunit/framework/TestResult;", AccessFlags = 1)]
get{ return GetTestResult(); }
}
}
/// <summary>
/// <para>Contains additional assertion methods not found in JUnit. </para>
/// </summary>
/// <java-name>
/// android/test/MoreAsserts
/// </java-name>
[Dot42.DexImport("android/test/MoreAsserts", AccessFlags = 49)]
public sealed partial class MoreAsserts
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal MoreAsserts() /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertAssignableFrom
/// </java-name>
[Dot42.DexImport("assertAssignableFrom", "(Ljava/lang/Class;Ljava/lang/Object;)V", AccessFlags = 9, Signature = "(Ljava/lang/Class<*>;Ljava/lang/Object;)V")]
public static void AssertAssignableFrom(global::System.Type type, object @object) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertAssignableFrom
/// </java-name>
[Dot42.DexImport("assertAssignableFrom", "(Ljava/lang/Class;Ljava/lang/Class;)V", AccessFlags = 9, Signature = "(Ljava/lang/Class<*>;Ljava/lang/Class<*>;)V")]
public static void AssertAssignableFrom(global::System.Type type, global::System.Type type1) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that <c> actual </c> is not equal <c> unexpected </c> , according to both <c> == </c> and Object#equals. </para>
/// </summary>
/// <java-name>
/// assertNotEqual
/// </java-name>
[Dot42.DexImport("assertNotEqual", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertNotEqual(string message, object unexpected, object actual) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Variant of assertNotEqual(String,Object,Object) using a generic message. </para>
/// </summary>
/// <java-name>
/// assertNotEqual
/// </java-name>
[Dot42.DexImport("assertNotEqual", "(Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertNotEqual(object unexpected, object actual) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;[B[B)V", AccessFlags = 9)]
public static void AssertEquals(string @string, sbyte[] sByte, sbyte[] sByte1) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;[B[B)V", AccessFlags = 9, IgnoreFromJava = true)]
public static void AssertEquals(string @string, byte[] @byte, byte[] byte1) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "([B[B)V", AccessFlags = 9)]
public static void AssertEquals(sbyte[] sByte, sbyte[] sByte1) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "([B[B)V", AccessFlags = 9, IgnoreFromJava = true)]
public static void AssertEquals(byte[] @byte, byte[] byte1) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;[I[I)V", AccessFlags = 9)]
public static void AssertEquals(string @string, int[] int32, int[] int321) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "([I[I)V", AccessFlags = 9)]
public static void AssertEquals(int[] int32, int[] int321) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;[D[D)V", AccessFlags = 9)]
public static void AssertEquals(string @string, double[] @double, double[] double1) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "([D[D)V", AccessFlags = 9)]
public static void AssertEquals(double[] @double, double[] double1) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;[Ljava/lang/Object;[Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertEquals(string @string, object[] @object, object[] object1) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "([Ljava/lang/Object;[Ljava/lang/Object;)V", AccessFlags = 9)]
public static void AssertEquals(object[] @object, object[] object1) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/lang/String;Ljava/util/Set;Ljava/util/Set;)V", AccessFlags = 9, Signature = "(Ljava/lang/String;Ljava/util/Set<+Ljava/lang/Object;>;Ljava/util/Set<+Ljava/lang" +
"/Object;>;)V")]
public static void AssertEquals(string @string, global::Java.Util.ISet<object> set, global::Java.Util.ISet<object> set1) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEquals
/// </java-name>
[Dot42.DexImport("assertEquals", "(Ljava/util/Set;Ljava/util/Set;)V", AccessFlags = 9, Signature = "(Ljava/util/Set<+Ljava/lang/Object;>;Ljava/util/Set<+Ljava/lang/Object;>;)V")]
public static void AssertEquals(global::Java.Util.ISet<object> set, global::Java.Util.ISet<object> set1) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that <c> expectedRegex </c> exactly matches <c> actual </c> and fails with <c> message </c> if it does not. The MatchResult is returned in case the test needs access to any captured groups. Note that you can also use this for a literal string, by wrapping your expected string in Pattern#quote. </para>
/// </summary>
/// <java-name>
/// assertMatchesRegex
/// </java-name>
[Dot42.DexImport("assertMatchesRegex", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/util/regex/MatchRes" +
"ult;", AccessFlags = 9)]
public static global::Java.Util.Regex.IMatchResult AssertMatchesRegex(string message, string expectedRegex, string actual) /* MethodBuilder.Create */
{
return default(global::Java.Util.Regex.IMatchResult);
}
/// <summary>
/// <para>Variant of assertMatchesRegex(String,String,String) using a generic message. </para>
/// </summary>
/// <java-name>
/// assertMatchesRegex
/// </java-name>
[Dot42.DexImport("assertMatchesRegex", "(Ljava/lang/String;Ljava/lang/String;)Ljava/util/regex/MatchResult;", AccessFlags = 9)]
public static global::Java.Util.Regex.IMatchResult AssertMatchesRegex(string expectedRegex, string actual) /* MethodBuilder.Create */
{
return default(global::Java.Util.Regex.IMatchResult);
}
/// <summary>
/// <para>Asserts that <c> expectedRegex </c> matches any substring of <c> actual </c> and fails with <c> message </c> if it does not. The Matcher is returned in case the test needs access to any captured groups. Note that you can also use this for a literal string, by wrapping your expected string in Pattern#quote. </para>
/// </summary>
/// <java-name>
/// assertContainsRegex
/// </java-name>
[Dot42.DexImport("assertContainsRegex", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/util/regex/MatchRes" +
"ult;", AccessFlags = 9)]
public static global::Java.Util.Regex.IMatchResult AssertContainsRegex(string message, string expectedRegex, string actual) /* MethodBuilder.Create */
{
return default(global::Java.Util.Regex.IMatchResult);
}
/// <summary>
/// <para>Variant of assertContainsRegex(String,String,String) using a generic message. </para>
/// </summary>
/// <java-name>
/// assertContainsRegex
/// </java-name>
[Dot42.DexImport("assertContainsRegex", "(Ljava/lang/String;Ljava/lang/String;)Ljava/util/regex/MatchResult;", AccessFlags = 9)]
public static global::Java.Util.Regex.IMatchResult AssertContainsRegex(string expectedRegex, string actual) /* MethodBuilder.Create */
{
return default(global::Java.Util.Regex.IMatchResult);
}
/// <summary>
/// <para>Asserts that <c> expectedRegex </c> does not exactly match <c> actual </c> , and fails with <c> message </c> if it does. Note that you can also use this for a literal string, by wrapping your expected string in Pattern#quote. </para>
/// </summary>
/// <java-name>
/// assertNotMatchesRegex
/// </java-name>
[Dot42.DexImport("assertNotMatchesRegex", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 9)]
public static void AssertNotMatchesRegex(string message, string expectedRegex, string actual) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Variant of assertNotMatchesRegex(String,String,String) using a generic message. </para>
/// </summary>
/// <java-name>
/// assertNotMatchesRegex
/// </java-name>
[Dot42.DexImport("assertNotMatchesRegex", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 9)]
public static void AssertNotMatchesRegex(string expectedRegex, string actual) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that <c> expectedRegex </c> does not match any substring of <c> actual </c> , and fails with <c> message </c> if it does. Note that you can also use this for a literal string, by wrapping your expected string in Pattern#quote. </para>
/// </summary>
/// <java-name>
/// assertNotContainsRegex
/// </java-name>
[Dot42.DexImport("assertNotContainsRegex", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 9)]
public static void AssertNotContainsRegex(string message, string expectedRegex, string actual) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Variant of assertNotContainsRegex(String,String,String) using a generic message. </para>
/// </summary>
/// <java-name>
/// assertNotContainsRegex
/// </java-name>
[Dot42.DexImport("assertNotContainsRegex", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 9)]
public static void AssertNotContainsRegex(string expectedRegex, string actual) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that <c> actual </c> contains precisely the elements <c> expected </c> , and in the same order. </para>
/// </summary>
/// <java-name>
/// assertContentsInOrder
/// </java-name>
[Dot42.DexImport("assertContentsInOrder", "(Ljava/lang/String;Ljava/lang/Iterable;[Ljava/lang/Object;)V", AccessFlags = 137, Signature = "(Ljava/lang/String;Ljava/lang/Iterable<*>;[Ljava/lang/Object;)V")]
public static void AssertContentsInOrder(string message, global::Java.Lang.IIterable<object> actual, params object[] expected) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Variant of assertContentsInOrder(String, Iterable<?>, Object...) using a generic message. </para>
/// </summary>
/// <java-name>
/// assertContentsInOrder
/// </java-name>
[Dot42.DexImport("assertContentsInOrder", "(Ljava/lang/Iterable;[Ljava/lang/Object;)V", AccessFlags = 137, Signature = "(Ljava/lang/Iterable<*>;[Ljava/lang/Object;)V")]
public static void AssertContentsInOrder(global::Java.Lang.IIterable<object> actual, params object[] expected) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Asserts that <c> actual </c> contains precisely the elements <c> expected </c> , but in any order. </para>
/// </summary>
/// <java-name>
/// assertContentsInAnyOrder
/// </java-name>
[Dot42.DexImport("assertContentsInAnyOrder", "(Ljava/lang/String;Ljava/lang/Iterable;[Ljava/lang/Object;)V", AccessFlags = 137, Signature = "(Ljava/lang/String;Ljava/lang/Iterable<*>;[Ljava/lang/Object;)V")]
public static void AssertContentsInAnyOrder(string message, global::Java.Lang.IIterable<object> actual, params object[] expected) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Variant of assertContentsInAnyOrder(String, Iterable<?>, Object...) using a generic message. </para>
/// </summary>
/// <java-name>
/// assertContentsInAnyOrder
/// </java-name>
[Dot42.DexImport("assertContentsInAnyOrder", "(Ljava/lang/Iterable;[Ljava/lang/Object;)V", AccessFlags = 137, Signature = "(Ljava/lang/Iterable<*>;[Ljava/lang/Object;)V")]
public static void AssertContentsInAnyOrder(global::Java.Lang.IIterable<object> actual, params object[] expected) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEmpty
/// </java-name>
[Dot42.DexImport("assertEmpty", "(Ljava/lang/String;Ljava/lang/Iterable;)V", AccessFlags = 9, Signature = "(Ljava/lang/String;Ljava/lang/Iterable<*>;)V")]
public static void AssertEmpty(string @string, global::Java.Lang.IIterable<object> iterable) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEmpty
/// </java-name>
[Dot42.DexImport("assertEmpty", "(Ljava/lang/Iterable;)V", AccessFlags = 9, Signature = "(Ljava/lang/Iterable<*>;)V")]
public static void AssertEmpty(global::Java.Lang.IIterable<object> iterable) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEmpty
/// </java-name>
[Dot42.DexImport("assertEmpty", "(Ljava/lang/String;Ljava/util/Map;)V", AccessFlags = 9, Signature = "(Ljava/lang/String;Ljava/util/Map<**>;)V")]
public static void AssertEmpty(string @string, global::Java.Util.IMap<object, object> map) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertEmpty
/// </java-name>
[Dot42.DexImport("assertEmpty", "(Ljava/util/Map;)V", AccessFlags = 9, Signature = "(Ljava/util/Map<**>;)V")]
public static void AssertEmpty(global::Java.Util.IMap<object, object> map) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertNotEmpty
/// </java-name>
[Dot42.DexImport("assertNotEmpty", "(Ljava/lang/String;Ljava/lang/Iterable;)V", AccessFlags = 9, Signature = "(Ljava/lang/String;Ljava/lang/Iterable<*>;)V")]
public static void AssertNotEmpty(string @string, global::Java.Lang.IIterable<object> iterable) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertNotEmpty
/// </java-name>
[Dot42.DexImport("assertNotEmpty", "(Ljava/lang/Iterable;)V", AccessFlags = 9, Signature = "(Ljava/lang/Iterable<*>;)V")]
public static void AssertNotEmpty(global::Java.Lang.IIterable<object> iterable) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertNotEmpty
/// </java-name>
[Dot42.DexImport("assertNotEmpty", "(Ljava/lang/String;Ljava/util/Map;)V", AccessFlags = 9, Signature = "(Ljava/lang/String;Ljava/util/Map<**>;)V")]
public static void AssertNotEmpty(string @string, global::Java.Util.IMap<object, object> map) /* MethodBuilder.Create */
{
}
/// <java-name>
/// assertNotEmpty
/// </java-name>
[Dot42.DexImport("assertNotEmpty", "(Ljava/util/Map;)V", AccessFlags = 9, Signature = "(Ljava/util/Map<**>;)V")]
public static void AssertNotEmpty(global::Java.Util.IMap<object, object> map) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Utility for testing equals() and hashCode() results at once. Tests that lhs.equals(rhs) matches expectedResult, as well as rhs.equals(lhs). Also tests that hashCode() return values are equal if expectedResult is true. (hashCode() is not tested if expectedResult is false, as unequal objects can have equal hashCodes.)</para><para></para>
/// </summary>
/// <java-name>
/// checkEqualsAndHashCodeMethods
/// </java-name>
[Dot42.DexImport("checkEqualsAndHashCodeMethods", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;Z)V", AccessFlags = 9)]
public static void CheckEqualsAndHashCodeMethods(string message, object lhs, object rhs, bool expectedResult) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Variant of checkEqualsAndHashCodeMethods(String,Object,Object,boolean...)} using a generic message. </para>
/// </summary>
/// <java-name>
/// checkEqualsAndHashCodeMethods
/// </java-name>
[Dot42.DexImport("checkEqualsAndHashCodeMethods", "(Ljava/lang/Object;Ljava/lang/Object;Z)V", AccessFlags = 9)]
public static void CheckEqualsAndHashCodeMethods(object lhs, object rhs, bool expectedResult) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>If you would like to test sync a single provider with an InstrumentationTestCase, this provides some of the boiler plate in setUp and tearDown. </para>
/// </summary>
/// <java-name>
/// android/test/SyncBaseInstrumentation
/// </java-name>
[Dot42.DexImport("android/test/SyncBaseInstrumentation", AccessFlags = 33)]
public partial class SyncBaseInstrumentation : global::Android.Test.InstrumentationTestCase
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public SyncBaseInstrumentation() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets up the fixture, for example, open a network connection. This method is called before a test is executed. </para>
/// </summary>
/// <java-name>
/// setUp
/// </java-name>
[Dot42.DexImport("setUp", "()V", AccessFlags = 4)]
protected internal override void SetUp() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Syncs the specified provider. </para>
/// </summary>
/// <java-name>
/// syncProvider
/// </java-name>
[Dot42.DexImport("syncProvider", "(Landroid/net/Uri;Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 4)]
protected internal virtual void SyncProvider(global::Android.Net.Uri uri, string accountName, string authority) /* MethodBuilder.Create */
{
}
/// <java-name>
/// cancelSyncsandDisableAutoSync
/// </java-name>
[Dot42.DexImport("cancelSyncsandDisableAutoSync", "()V", AccessFlags = 4)]
protected internal virtual void CancelSyncsandDisableAutoSync() /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>This test case provides a framework in which you can test Service classes in a controlled environment. It provides basic support for the lifecycle of a Service, and hooks with which you can inject various dependencies and control the environment in which your Service is tested.</para><para> <h3>Developer Guides</h3></para><para> </para><para>For more information about application testing, read the developer guide.</para><para> </para><para><b>Lifecycle Support.</b> A Service is accessed with a specific sequence of calls, as described in the document. In order to support the lifecycle of a Service, <code>ServiceTestCase</code> enforces this protocol:</para><para><ul><li><para>The setUp() method is called before each test method. The base implementation gets the system context. If you override <code>setUp()</code>, you must call <code>super.setUp()</code> as the first statement in your override. </para></li><li><para>The test case waits to call android.app.Service#onCreate() until one of your test methods calls startService or bindService. This gives you an opportunity to set up or adjust any additional framework or test logic before you test the running service. </para></li><li><para>When one of your test methods calls ServiceTestCase.startService() or ServiceTestCase.bindService(), the test case calls Service.onCreate() and then calls either Service.startService(Intent) or Service.bindService(Intent, ServiceConnection, int), as appropriate. It also stores values needed to track and support the lifecycle. </para></li><li><para>After each test method finishes, the test case calls the tearDown method. This method stops and destroys the service with the appropriate calls, depending on how the service was started. If you override <code>tearDown()</code>, your must call the <code>super.tearDown()</code> as the last statement in your override. </para></li></ul></para><para><b>Dependency Injection.</b> A service has two inherent dependencies, its Context and its associated Application. The ServiceTestCase framework allows you to inject modified, mock, or isolated replacements for these dependencies, and thus perform unit tests with controlled dependencies in an isolated environment. </para><para>By default, the test case is injected with a full system context and a generic MockApplication object. You can inject alternatives to either of these by invoking setContext() or setApplication(). You must do this <b>before</b> calling startService() or bindService(). The test framework provides a number of alternatives for Context, including MockContext, RenamingDelegatingContext, ContextWrapper, and android.test.IsolatedContext. </para>
/// </summary>
/// <java-name>
/// android/test/ServiceTestCase
/// </java-name>
[Dot42.DexImport("android/test/ServiceTestCase", AccessFlags = 1057, Signature = "<T:Landroid/app/Service;>Landroid/test/AndroidTestCase;")]
public abstract partial class ServiceTestCase<T> : global::Android.Test.AndroidTestCase
/* scope: __dot42__ */
{
/// <summary>
/// <para>Constructor </para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/Class;)V", AccessFlags = 1, Signature = "(Ljava/lang/Class<TT;>;)V")]
public ServiceTestCase(global::System.Type serviceClass) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>An instance of the service under test. This instance is created automatically when a test calls startService or bindService. </para>
/// </returns>
/// <java-name>
/// getService
/// </java-name>
[Dot42.DexImport("getService", "()Landroid/app/Service;", AccessFlags = 1, Signature = "()TT;")]
public virtual T GetService() /* MethodBuilder.Create */
{
return default(T);
}
/// <summary>
/// <para>Gets the current system context and stores it.</para><para>Extend this method to do your own test initialization. If you do so, you must call <code>super.setUp()</code> as the first statement in your override. The method is called before each test method is executed. </para>
/// </summary>
/// <java-name>
/// setUp
/// </java-name>
[Dot42.DexImport("setUp", "()V", AccessFlags = 4)]
protected internal override void SetUp() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates the service under test and attaches all injected dependencies (Context, Application) to it. This is called automatically by startService or by bindService. If you need to call setContext() or setApplication(), do so before calling this method. </para>
/// </summary>
/// <java-name>
/// setupService
/// </java-name>
[Dot42.DexImport("setupService", "()V", AccessFlags = 4)]
protected internal virtual void SetupService() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Starts the service under test, in the same way as if it were started by Context.startService(Intent) with an android.content.Intent that identifies a service. If you use this method to start the service, it is automatically stopped by tearDown.</para><para></para>
/// </summary>
/// <java-name>
/// startService
/// </java-name>
[Dot42.DexImport("startService", "(Landroid/content/Intent;)V", AccessFlags = 4)]
protected internal virtual void StartService(global::Android.Content.Intent intent) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Starts the service under test, in the same way as if it were started by Context.bindService(Intent, ServiceConnection, flags) with an android.content.Intent that identifies a service. </para><para>Notice that the parameters are different. You do not provide a android.content.ServiceConnection object or the flags parameter. Instead, you only provide the Intent. The method returns an object whose type is a subclass of android.os.IBinder, or null if the method fails. An IBinder object refers to a communication channel between the application and the service. The flag is assumed to be android.content.Context#BIND_AUTO_CREATE. </para><para>See for more information about the communication channel object returned by this method. </para><para>Note: To be able to use bindService in a test, the service must implement getService() method. An example of this is in the ApiDemos sample application, in the LocalService demo.</para><para></para>
/// </summary>
/// <returns>
/// <para>An object whose type is a subclass of IBinder, for making further calls into the service. </para>
/// </returns>
/// <java-name>
/// bindService
/// </java-name>
[Dot42.DexImport("bindService", "(Landroid/content/Intent;)Landroid/os/IBinder;", AccessFlags = 4)]
protected internal virtual global::Android.Os.IBinder BindService(global::Android.Content.Intent intent) /* MethodBuilder.Create */
{
return default(global::Android.Os.IBinder);
}
/// <summary>
/// <para>Makes the necessary calls to stop (or unbind) the service under test, and calls onDestroy(). Ordinarily this is called automatically (by tearDown, but you can call it directly from your test in order to check for proper shutdown behavior. </para>
/// </summary>
/// <java-name>
/// shutdownService
/// </java-name>
[Dot42.DexImport("shutdownService", "()V", AccessFlags = 4)]
protected internal virtual void ShutdownService() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Shuts down the service under test. Ensures all resources are cleaned up and garbage collected before moving on to the next test. This method is called after each test method. </para><para>Subclasses that override this method must call <code>super.tearDown()</code> as their last statement. </para><para></para>
/// </summary>
/// <java-name>
/// tearDown
/// </java-name>
[Dot42.DexImport("tearDown", "()V", AccessFlags = 4)]
protected internal override void TearDown() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets the application that is used during the test. If you do not call this method, a new MockApplication object is used.</para><para><para>getApplication() </para></para>
/// </summary>
/// <java-name>
/// setApplication
/// </java-name>
[Dot42.DexImport("setApplication", "(Landroid/app/Application;)V", AccessFlags = 1)]
public virtual void SetApplication(global::Android.App.Application application) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the Application object in use by the service under test.</para><para><para>setApplication </para></para>
/// </summary>
/// <returns>
/// <para>The application object.</para>
/// </returns>
/// <java-name>
/// getApplication
/// </java-name>
[Dot42.DexImport("getApplication", "()Landroid/app/Application;", AccessFlags = 1)]
public virtual global::Android.App.Application GetApplication() /* MethodBuilder.Create */
{
return default(global::Android.App.Application);
}
/// <summary>
/// <para>Returns the real system context that is saved by setUp(). Use it to create mock or other types of context objects for the service under test.</para><para></para>
/// </summary>
/// <returns>
/// <para>A normal system context. </para>
/// </returns>
/// <java-name>
/// getSystemContext
/// </java-name>
[Dot42.DexImport("getSystemContext", "()Landroid/content/Context;", AccessFlags = 1)]
public virtual global::Android.Content.Context GetSystemContext() /* MethodBuilder.Create */
{
return default(global::Android.Content.Context);
}
/// <summary>
/// <para>Tests that setupService() runs correctly and issues an junit.framework.Assert#assertNotNull(String, Object) if it does. You can override this test method if you wish.</para><para></para>
/// </summary>
/// <java-name>
/// testServiceTestCaseSetUpProperly
/// </java-name>
[Dot42.DexImport("testServiceTestCaseSetUpProperly", "()V", AccessFlags = 1)]
public virtual void TestServiceTestCaseSetUpProperly() /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal ServiceTestCase() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>An instance of the service under test. This instance is created automatically when a test calls startService or bindService. </para>
/// </returns>
/// <java-name>
/// getService
/// </java-name>
public T Service
{
[Dot42.DexImport("getService", "()Landroid/app/Service;", AccessFlags = 1, Signature = "()TT;")]
get{ return GetService(); }
}
/// <summary>
/// <para>Returns the Application object in use by the service under test.</para><para><para>setApplication </para></para>
/// </summary>
/// <returns>
/// <para>The application object.</para>
/// </returns>
/// <java-name>
/// getApplication
/// </java-name>
public global::Android.App.Application Application
{
[Dot42.DexImport("getApplication", "()Landroid/app/Application;", AccessFlags = 1)]
get{ return GetApplication(); }
[Dot42.DexImport("setApplication", "(Landroid/app/Application;)V", AccessFlags = 1)]
set{ SetApplication(value); }
}
/// <summary>
/// <para>Returns the real system context that is saved by setUp(). Use it to create mock or other types of context objects for the service under test.</para><para></para>
/// </summary>
/// <returns>
/// <para>A normal system context. </para>
/// </returns>
/// <java-name>
/// getSystemContext
/// </java-name>
public global::Android.Content.Context SystemContext
{
[Dot42.DexImport("getSystemContext", "()Landroid/content/Context;", AccessFlags = 1)]
get{ return GetSystemContext(); }
}
}
/// <summary>
/// <para>More complex interface performance for test cases.</para><para>If you want your test to be used as a performance test, you must implement this interface. </para>
/// </summary>
/// <java-name>
/// android/test/PerformanceTestCase
/// </java-name>
[Dot42.DexImport("android/test/PerformanceTestCase", AccessFlags = 1537)]
public partial interface IPerformanceTestCase
/* scope: __dot42__ */
{
/// <summary>
/// <para>Set up to begin performance tests. The 'intermediates' is a communication channel to send back intermediate performance numbers if you use it, you will probably want to ensure your test is only executed once by returning 1. Otherwise, return 0 to allow the test harness to decide the number of iterations.</para><para>If you return a non-zero iteration count, you should call intermediates.startTiming and intermediates.endTiming to report the duration of the test whose performance should actually be measured.</para><para></para>
/// </summary>
/// <returns>
/// <para>int Maximum number of iterations to run, or 0 to let the caller decide. </para>
/// </returns>
/// <java-name>
/// startPerformance
/// </java-name>
[Dot42.DexImport("startPerformance", "(Landroid/test/PerformanceTestCase$Intermediates;)I", AccessFlags = 1025)]
int StartPerformance(global::Android.Test.IPerformanceTestCase_IIntermediates intermediates) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>This method is used to determine what modes this test case can run in.</para><para></para>
/// </summary>
/// <returns>
/// <para>true if this test case can only be run in performance mode. </para>
/// </returns>
/// <java-name>
/// isPerformanceOnly
/// </java-name>
[Dot42.DexImport("isPerformanceOnly", "()Z", AccessFlags = 1025)]
bool IsPerformanceOnly() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Callbacks for PerformanceTestCase. </para>
/// </summary>
/// <java-name>
/// android/test/PerformanceTestCase$Intermediates
/// </java-name>
[Dot42.DexImport("android/test/PerformanceTestCase$Intermediates", AccessFlags = 1545)]
public partial interface IPerformanceTestCase_IIntermediates
/* scope: __dot42__ */
{
/// <java-name>
/// setInternalIterations
/// </java-name>
[Dot42.DexImport("setInternalIterations", "(I)V", AccessFlags = 1025)]
void SetInternalIterations(int count) /* MethodBuilder.Create */ ;
/// <java-name>
/// startTiming
/// </java-name>
[Dot42.DexImport("startTiming", "(Z)V", AccessFlags = 1025)]
void StartTiming(bool realTime) /* MethodBuilder.Create */ ;
/// <java-name>
/// addIntermediate
/// </java-name>
[Dot42.DexImport("addIntermediate", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void AddIntermediate(string name) /* MethodBuilder.Create */ ;
/// <java-name>
/// addIntermediate
/// </java-name>
[Dot42.DexImport("addIntermediate", "(Ljava/lang/String;J)V", AccessFlags = 1025)]
void AddIntermediate(string name, long timeInNS) /* MethodBuilder.Create */ ;
/// <java-name>
/// finishTiming
/// </java-name>
[Dot42.DexImport("finishTiming", "(Z)V", AccessFlags = 1025)]
void FinishTiming(bool realTime) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Implementors will know how to get a test suite. </para>
/// </summary>
/// <java-name>
/// android/test/TestSuiteProvider
/// </java-name>
[Dot42.DexImport("android/test/TestSuiteProvider", AccessFlags = 1537)]
public partial interface ITestSuiteProvider
/* scope: __dot42__ */
{
/// <java-name>
/// getTestSuite
/// </java-name>
[Dot42.DexImport("getTestSuite", "()Ljunit/framework/TestSuite;", AccessFlags = 1025)]
global::Junit.Framework.TestSuite GetTestSuite() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>This is common code used to support Activity test cases. For more useful classes, please see android.test.ActivityUnitTestCase and android.test.ActivityInstrumentationTestCase. </para>
/// </summary>
/// <java-name>
/// android/test/ActivityTestCase
/// </java-name>
[Dot42.DexImport("android/test/ActivityTestCase", AccessFlags = 1057)]
public abstract partial class ActivityTestCase : global::Android.Test.InstrumentationTestCase
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public ActivityTestCase() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>Returns the activity under test. </para>
/// </returns>
/// <java-name>
/// getActivity
/// </java-name>
[Dot42.DexImport("getActivity", "()Landroid/app/Activity;", AccessFlags = 4)]
protected internal virtual global::Android.App.Activity GetActivity() /* MethodBuilder.Create */
{
return default(global::Android.App.Activity);
}
/// <summary>
/// <para>Set the activity under test. </para>
/// </summary>
/// <java-name>
/// setActivity
/// </java-name>
[Dot42.DexImport("setActivity", "(Landroid/app/Activity;)V", AccessFlags = 4)]
protected internal virtual void SetActivity(global::Android.App.Activity testActivity) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>This function is called by various TestCase implementations, at tearDown() time, in order to scrub out any class variables. This protects against memory leaks in the case where a test case creates a non-static inner class (thus referencing the test case) and gives it to someone else to hold onto.</para><para></para>
/// </summary>
/// <java-name>
/// scrubClass
/// </java-name>
[Dot42.DexImport("scrubClass", "(Ljava/lang/Class;)V", AccessFlags = 4, Signature = "(Ljava/lang/Class<*>;)V")]
protected internal virtual void ScrubClass(global::System.Type testCaseClass) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>Returns the activity under test. </para>
/// </returns>
/// <java-name>
/// getActivity
/// </java-name>
protected internal global::Android.App.Activity Activity
{
[Dot42.DexImport("getActivity", "()Landroid/app/Activity;", AccessFlags = 4)]
get{ return GetActivity(); }
[Dot42.DexImport("setActivity", "(Landroid/app/Activity;)V", AccessFlags = 4)]
set{ SetActivity(value); }
}
}
/// <summary>
/// <para>If you would like to test a single activity with an android.test.InstrumentationTestCase, this provides some of the boiler plate to launch and finish the activity in setUp and tearDown.</para><para>This launches the activity only once for the entire class instead of doing it in every setup / teardown call. </para>
/// </summary>
/// <java-name>
/// android/test/SingleLaunchActivityTestCase
/// </java-name>
[Dot42.DexImport("android/test/SingleLaunchActivityTestCase", AccessFlags = 1057, Signature = "<T:Landroid/app/Activity;>Landroid/test/InstrumentationTestCase;")]
public abstract partial class SingleLaunchActivityTestCase<T> : global::Android.Test.InstrumentationTestCase
/* scope: __dot42__ */
{
/// <summary>
/// <para><b>NOTE:</b> The parameter <b>pkg</b> must refer to the package identifier of the package hosting the activity to be launched, which is specified in the AndroidManifest.xml file. This is not necessarily the same as the java package name.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Class;)V", AccessFlags = 1, Signature = "(Ljava/lang/String;Ljava/lang/Class<TT;>;)V")]
public SingleLaunchActivityTestCase(string pkg, global::System.Type activityClass) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getActivity
/// </java-name>
[Dot42.DexImport("getActivity", "()Landroid/app/Activity;", AccessFlags = 1, Signature = "()TT;")]
public virtual T GetActivity() /* MethodBuilder.Create */
{
return default(T);
}
/// <summary>
/// <para>Sets up the fixture, for example, open a network connection. This method is called before a test is executed. </para>
/// </summary>
/// <java-name>
/// setUp
/// </java-name>
[Dot42.DexImport("setUp", "()V", AccessFlags = 4)]
protected internal override void SetUp() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Make sure all resources are cleaned up and garbage collected before moving on to the next test. Subclasses that override this method should make sure they call super.tearDown() at the end of the overriding method.</para><para></para>
/// </summary>
/// <java-name>
/// tearDown
/// </java-name>
[Dot42.DexImport("tearDown", "()V", AccessFlags = 4)]
protected internal override void TearDown() /* MethodBuilder.Create */
{
}
/// <java-name>
/// testActivityTestCaseSetUpProperly
/// </java-name>
[Dot42.DexImport("testActivityTestCaseSetUpProperly", "()V", AccessFlags = 1)]
public virtual void TestActivityTestCaseSetUpProperly() /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal SingleLaunchActivityTestCase() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <java-name>
/// getActivity
/// </java-name>
public T Activity
{
[Dot42.DexImport("getActivity", "()Landroid/app/Activity;", AccessFlags = 1, Signature = "()TT;")]
get{ return GetActivity(); }
}
}
/// <summary>
/// <para>A junit.framework.TestSuite that injects android.app.Instrumentation into InstrumentationTestCase before running them. </para>
/// </summary>
/// <java-name>
/// android/test/InstrumentationTestSuite
/// </java-name>
[Dot42.DexImport("android/test/InstrumentationTestSuite", AccessFlags = 33)]
public partial class InstrumentationTestSuite : global::Junit.Framework.TestSuite
/* scope: __dot42__ */
{
/// <summary>
/// <para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Landroid/app/Instrumentation;)V", AccessFlags = 1)]
public InstrumentationTestSuite(global::Android.App.Instrumentation instr) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;Landroid/app/Instrumentation;)V", AccessFlags = 1)]
public InstrumentationTestSuite(string @string, global::Android.App.Instrumentation instrumentation) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/Class;Landroid/app/Instrumentation;)V", AccessFlags = 1)]
public InstrumentationTestSuite(global::System.Type type, global::Android.App.Instrumentation instrumentation) /* MethodBuilder.Create */
{
}
/// <java-name>
/// addTestSuite
/// </java-name>
[Dot42.DexImport("addTestSuite", "(Ljava/lang/Class;)V", AccessFlags = 1)]
public override void AddTestSuite(global::System.Type testClass) /* MethodBuilder.Create */
{
}
/// <java-name>
/// runTest
/// </java-name>
[Dot42.DexImport("runTest", "(Ljunit/framework/Test;Ljunit/framework/TestResult;)V", AccessFlags = 1)]
public override void RunTest(global::Junit.Framework.ITest test, global::Junit.Framework.TestResult result) /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal InstrumentationTestSuite() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para>If you would like to test a single content provider with an InstrumentationTestCase, this provides some of the boiler plate in setUp and tearDown.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>this class extends InstrumentationTestCase but should extend AndroidTestCase. Use ProviderTestCase2, which corrects this problem, instead. </para></xrefdescription></xrefsect></para>
/// </summary>
/// <java-name>
/// android/test/ProviderTestCase
/// </java-name>
[Dot42.DexImport("android/test/ProviderTestCase", AccessFlags = 1057, Signature = "<T:Landroid/content/ContentProvider;>Landroid/test/InstrumentationTestCase;")]
public abstract partial class ProviderTestCase<T> : global::Android.Test.InstrumentationTestCase
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Ljava/lang/Class;Ljava/lang/String;)V", AccessFlags = 1, Signature = "(Ljava/lang/Class<TT;>;Ljava/lang/String;)V")]
public ProviderTestCase(global::System.Type providerClass, string providerAuthority) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getProvider
/// </java-name>
[Dot42.DexImport("getProvider", "()Landroid/content/ContentProvider;", AccessFlags = 1, Signature = "()TT;")]
public virtual T GetProvider() /* MethodBuilder.Create */
{
return default(T);
}
/// <summary>
/// <para>Sets up the fixture, for example, open a network connection. This method is called before a test is executed. </para>
/// </summary>
/// <java-name>
/// setUp
/// </java-name>
[Dot42.DexImport("setUp", "()V", AccessFlags = 4)]
protected internal override void SetUp() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tears down the environment for the test fixture. </para><para>Calls android.content.ContentProvider#shutdown() on the android.content.ContentProvider represented by mProvider. </para>
/// </summary>
/// <java-name>
/// tearDown
/// </java-name>
[Dot42.DexImport("tearDown", "()V", AccessFlags = 4)]
protected internal override void TearDown() /* MethodBuilder.Create */
{
}
/// <java-name>
/// getMockContentResolver
/// </java-name>
[Dot42.DexImport("getMockContentResolver", "()Landroid/test/mock/MockContentResolver;", AccessFlags = 1)]
public virtual global::Android.Test.Mock.MockContentResolver GetMockContentResolver() /* MethodBuilder.Create */
{
return default(global::Android.Test.Mock.MockContentResolver);
}
/// <java-name>
/// getMockContext
/// </java-name>
[Dot42.DexImport("getMockContext", "()Landroid/test/IsolatedContext;", AccessFlags = 1)]
public virtual global::Android.Test.IsolatedContext GetMockContext() /* MethodBuilder.Create */
{
return default(global::Android.Test.IsolatedContext);
}
/// <java-name>
/// newResolverWithContentProviderFromSql
/// </java-name>
[Dot42.DexImport("newResolverWithContentProviderFromSql", "(Landroid/content/Context;Ljava/lang/Class;Ljava/lang/String;Ljava/lang/String;IL" +
"java/lang/String;)Landroid/content/ContentResolver;", AccessFlags = 9, Signature = "<T:Landroid/content/ContentProvider;>(Landroid/content/Context;Ljava/lang/Class<T" +
"T;>;Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;)Landroid/content/Con" +
"tentResolver;")]
public static global::Android.Content.ContentResolver NewResolverWithContentProviderFromSql<JavaT>(global::Android.Content.Context targetContext, global::System.Type providerClass, string authority, string databaseName, int databaseVersion, string sql) /* MethodBuilder.Create */
{
return default(global::Android.Content.ContentResolver);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal ProviderTestCase() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <java-name>
/// getProvider
/// </java-name>
public T Provider
{
[Dot42.DexImport("getProvider", "()Landroid/content/ContentProvider;", AccessFlags = 1, Signature = "()TT;")]
get{ return GetProvider(); }
}
/// <java-name>
/// getMockContentResolver
/// </java-name>
public global::Android.Test.Mock.MockContentResolver MockContentResolver
{
[Dot42.DexImport("getMockContentResolver", "()Landroid/test/mock/MockContentResolver;", AccessFlags = 1)]
get{ return GetMockContentResolver(); }
}
/// <java-name>
/// getMockContext
/// </java-name>
public global::Android.Test.IsolatedContext MockContext
{
[Dot42.DexImport("getMockContext", "()Landroid/test/IsolatedContext;", AccessFlags = 1)]
get{ return GetMockContext(); }
}
}
/// <summary>
/// <para>Some useful assertions about views. </para>
/// </summary>
/// <java-name>
/// android/test/ViewAsserts
/// </java-name>
[Dot42.DexImport("android/test/ViewAsserts", AccessFlags = 33)]
public partial class ViewAsserts
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal ViewAsserts() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Assert that view is on the screen. </para>
/// </summary>
/// <java-name>
/// assertOnScreen
/// </java-name>
[Dot42.DexImport("assertOnScreen", "(Landroid/view/View;Landroid/view/View;)V", AccessFlags = 9)]
public static void AssertOnScreen(global::Android.View.View origin, global::Android.View.View view) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Assert that view is below the visible screen. </para>
/// </summary>
/// <java-name>
/// assertOffScreenBelow
/// </java-name>
[Dot42.DexImport("assertOffScreenBelow", "(Landroid/view/View;Landroid/view/View;)V", AccessFlags = 9)]
public static void AssertOffScreenBelow(global::Android.View.View origin, global::Android.View.View view) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Assert that view is above the visible screen. </para>
/// </summary>
/// <java-name>
/// assertOffScreenAbove
/// </java-name>
[Dot42.DexImport("assertOffScreenAbove", "(Landroid/view/View;Landroid/view/View;)V", AccessFlags = 9)]
public static void AssertOffScreenAbove(global::Android.View.View origin, global::Android.View.View view) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Assert that a view has a particular x and y position on the visible screen. </para>
/// </summary>
/// <java-name>
/// assertHasScreenCoordinates
/// </java-name>
[Dot42.DexImport("assertHasScreenCoordinates", "(Landroid/view/View;Landroid/view/View;II)V", AccessFlags = 9)]
public static void AssertHasScreenCoordinates(global::Android.View.View origin, global::Android.View.View view, int x, int y) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Assert that two views are aligned on their baseline, that is that their baselines are on the same y location.</para><para></para>
/// </summary>
/// <java-name>
/// assertBaselineAligned
/// </java-name>
[Dot42.DexImport("assertBaselineAligned", "(Landroid/view/View;Landroid/view/View;)V", AccessFlags = 9)]
public static void AssertBaselineAligned(global::Android.View.View first, global::Android.View.View second) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Assert that two views are right aligned, that is that their right edges are on the same x location.</para><para></para>
/// </summary>
/// <java-name>
/// assertRightAligned
/// </java-name>
[Dot42.DexImport("assertRightAligned", "(Landroid/view/View;Landroid/view/View;)V", AccessFlags = 9)]
public static void AssertRightAligned(global::Android.View.View first, global::Android.View.View second) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Assert that two views are right aligned, that is that their right edges are on the same x location, with respect to the specified margin.</para><para></para>
/// </summary>
/// <java-name>
/// assertRightAligned
/// </java-name>
[Dot42.DexImport("assertRightAligned", "(Landroid/view/View;Landroid/view/View;I)V", AccessFlags = 9)]
public static void AssertRightAligned(global::Android.View.View first, global::Android.View.View second, int margin) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Assert that two views are left aligned, that is that their left edges are on the same x location.</para><para></para>
/// </summary>
/// <java-name>
/// assertLeftAligned
/// </java-name>
[Dot42.DexImport("assertLeftAligned", "(Landroid/view/View;Landroid/view/View;)V", AccessFlags = 9)]
public static void AssertLeftAligned(global::Android.View.View first, global::Android.View.View second) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Assert that two views are left aligned, that is that their left edges are on the same x location, with respect to the specified margin.</para><para></para>
/// </summary>
/// <java-name>
/// assertLeftAligned
/// </java-name>
[Dot42.DexImport("assertLeftAligned", "(Landroid/view/View;Landroid/view/View;I)V", AccessFlags = 9)]
public static void AssertLeftAligned(global::Android.View.View first, global::Android.View.View second, int margin) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Assert that two views are bottom aligned, that is that their bottom edges are on the same y location.</para><para></para>
/// </summary>
/// <java-name>
/// assertBottomAligned
/// </java-name>
[Dot42.DexImport("assertBottomAligned", "(Landroid/view/View;Landroid/view/View;)V", AccessFlags = 9)]
public static void AssertBottomAligned(global::Android.View.View first, global::Android.View.View second) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Assert that two views are bottom aligned, that is that their bottom edges are on the same y location, with respect to the specified margin.</para><para></para>
/// </summary>
/// <java-name>
/// assertBottomAligned
/// </java-name>
[Dot42.DexImport("assertBottomAligned", "(Landroid/view/View;Landroid/view/View;I)V", AccessFlags = 9)]
public static void AssertBottomAligned(global::Android.View.View first, global::Android.View.View second, int margin) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Assert that two views are top aligned, that is that their top edges are on the same y location.</para><para></para>
/// </summary>
/// <java-name>
/// assertTopAligned
/// </java-name>
[Dot42.DexImport("assertTopAligned", "(Landroid/view/View;Landroid/view/View;)V", AccessFlags = 9)]
public static void AssertTopAligned(global::Android.View.View first, global::Android.View.View second) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Assert that two views are top aligned, that is that their top edges are on the same y location, with respect to the specified margin.</para><para></para>
/// </summary>
/// <java-name>
/// assertTopAligned
/// </java-name>
[Dot42.DexImport("assertTopAligned", "(Landroid/view/View;Landroid/view/View;I)V", AccessFlags = 9)]
public static void AssertTopAligned(global::Android.View.View first, global::Android.View.View second, int margin) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Assert that the <code>test</code> view is horizontally center aligned with respect to the <code>reference</code> view.</para><para></para>
/// </summary>
/// <java-name>
/// assertHorizontalCenterAligned
/// </java-name>
[Dot42.DexImport("assertHorizontalCenterAligned", "(Landroid/view/View;Landroid/view/View;)V", AccessFlags = 9)]
public static void AssertHorizontalCenterAligned(global::Android.View.View reference, global::Android.View.View test) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Assert that the <code>test</code> view is vertically center aligned with respect to the <code>reference</code> view.</para><para></para>
/// </summary>
/// <java-name>
/// assertVerticalCenterAligned
/// </java-name>
[Dot42.DexImport("assertVerticalCenterAligned", "(Landroid/view/View;Landroid/view/View;)V", AccessFlags = 9)]
public static void AssertVerticalCenterAligned(global::Android.View.View reference, global::Android.View.View test) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Assert the specified group's integrity. The children count should be >= 0 and each child should be non-null.</para><para></para>
/// </summary>
/// <java-name>
/// assertGroupIntegrity
/// </java-name>
[Dot42.DexImport("assertGroupIntegrity", "(Landroid/view/ViewGroup;)V", AccessFlags = 9)]
public static void AssertGroupIntegrity(global::Android.View.ViewGroup parent) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Assert that the specified group contains a specific child once and only once.</para><para></para>
/// </summary>
/// <java-name>
/// assertGroupContains
/// </java-name>
[Dot42.DexImport("assertGroupContains", "(Landroid/view/ViewGroup;Landroid/view/View;)V", AccessFlags = 9)]
public static void AssertGroupContains(global::Android.View.ViewGroup parent, global::Android.View.View child) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Assert that the specified group does not contain a specific child.</para><para></para>
/// </summary>
/// <java-name>
/// assertGroupNotContains
/// </java-name>
[Dot42.DexImport("assertGroupNotContains", "(Landroid/view/ViewGroup;Landroid/view/View;)V", AccessFlags = 9)]
public static void AssertGroupNotContains(global::Android.View.ViewGroup parent, global::Android.View.View child) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>This annotation can be used on an InstrumentationTestCase's test methods. When the annotation is present, the test method is executed on the application's main thread (or UI thread.) Note that instrumentation methods may not be used when this annotation is present. </para>
/// </summary>
/// <java-name>
/// android/test/UiThreadTest
/// </java-name>
[Dot42.DexImport("android/test/UiThreadTest", AccessFlags = 9729)]
public partial interface IUiThreadTest : global::Java.Lang.Annotation.IAnnotation
/* scope: __dot42__ */
{
}
/// <summary>
/// <para>Thrown when an assertion failed.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>use junit.framework.AssertionFailedError </para></xrefdescription></xrefsect></para>
/// </summary>
/// <java-name>
/// android/test/AssertionFailedError
/// </java-name>
[Dot42.DexImport("android/test/AssertionFailedError", AccessFlags = 33)]
public partial class AssertionFailedError : global::Java.Lang.Error
/* scope: __dot42__ */
{
/// <summary>
/// <para>It is more typical to call AssertionFailedError(String). </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public AssertionFailedError() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public AssertionFailedError(string errorMessage) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>This class provides functional testing of a single activity. The activity under test will be created using the system infrastructure (by calling InstrumentationTestCase.launchActivity()) and you will then be able to manipulate your Activity directly.</para><para>Other options supported by this test case include: <ul><li><para>You can run any test method on the UI thread (see android.test.UiThreadTest). </para></li><li><para>You can inject custom Intents into your Activity (see setActivityIntent(Intent)). </para></li></ul></para><para>This class replaces android.test.ActivityInstrumentationTestCase, which is deprecated. New tests should be written using this base class.</para><para>If you prefer an isolated unit test, see android.test.ActivityUnitTestCase.</para><para> <h3>Developer Guides</h3></para><para> </para><para>For more information about application testing, read the developer guide.</para><para> </para>
/// </summary>
/// <java-name>
/// android/test/ActivityInstrumentationTestCase2
/// </java-name>
[Dot42.DexImport("android/test/ActivityInstrumentationTestCase2", AccessFlags = 1057, Signature = "<T:Landroid/app/Activity;>Landroid/test/ActivityTestCase;")]
public abstract partial class ActivityInstrumentationTestCase2<T> : global::Android.Test.ActivityTestCase
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates an ActivityInstrumentationTestCase2.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>use ActivityInstrumentationTestCase2(Class) instead </para></xrefdescription></xrefsect></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Class;)V", AccessFlags = 1, Signature = "(Ljava/lang/String;Ljava/lang/Class<TT;>;)V")]
public ActivityInstrumentationTestCase2(string pkg, global::System.Type activityClass) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates an ActivityInstrumentationTestCase2.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/Class;)V", AccessFlags = 1, Signature = "(Ljava/lang/Class<TT;>;)V")]
public ActivityInstrumentationTestCase2(global::System.Type activityClass) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Get the Activity under test, starting it if necessary.</para><para>For each test method invocation, the Activity will not actually be created until the first time this method is called.</para><para>If you wish to provide custom setup values to your Activity, you may call setActivityIntent(Intent) and/or setActivityInitialTouchMode(boolean) before your first call to getActivity(). Calling them after your Activity has started will have no effect.</para><para><b>NOTE:</b> Activities under test may not be started from within the UI thread. If your test method is annotated with android.test.UiThreadTest, then your Activity will be started automatically just before your test method is run. You still call this method in order to get the Activity under test.</para><para></para>
/// </summary>
/// <returns>
/// <para>the Activity under test </para>
/// </returns>
/// <java-name>
/// getActivity
/// </java-name>
[Dot42.DexImport("getActivity", "()Landroid/app/Activity;", AccessFlags = 1, Signature = "()TT;")]
public new virtual T GetActivity() /* MethodBuilder.Create */
{
return default(T);
}
/// <summary>
/// <para>Call this method before the first call to getActivity to inject a customized Intent into the Activity under test.</para><para>If you do not call this, the default intent will be provided. If you call this after your Activity has been started, it will have no effect.</para><para><b>NOTE:</b> Activities under test may not be started from within the UI thread. If your test method is annotated with android.test.UiThreadTest, then you must call setActivityIntent(Intent) from setUp().</para><para>The default Intent (if this method is not called) is: action = Intent#ACTION_MAIN flags = Intent#FLAG_ACTIVITY_NEW_TASK All other fields are null or empty.</para><para></para>
/// </summary>
/// <java-name>
/// setActivityIntent
/// </java-name>
[Dot42.DexImport("setActivityIntent", "(Landroid/content/Intent;)V", AccessFlags = 1)]
public virtual void SetActivityIntent(global::Android.Content.Intent i) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Call this method before the first call to getActivity to set the initial touch mode for the Activity under test.</para><para>If you do not call this, the touch mode will be false. If you call this after your Activity has been started, it will have no effect.</para><para><b>NOTE:</b> Activities under test may not be started from within the UI thread. If your test method is annotated with android.test.UiThreadTest, then you must call setActivityInitialTouchMode(boolean) from setUp().</para><para></para>
/// </summary>
/// <java-name>
/// setActivityInitialTouchMode
/// </java-name>
[Dot42.DexImport("setActivityInitialTouchMode", "(Z)V", AccessFlags = 1)]
public virtual void SetActivityInitialTouchMode(bool initialTouchMode) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sets up the fixture, for example, open a network connection. This method is called before a test is executed. </para>
/// </summary>
/// <java-name>
/// setUp
/// </java-name>
[Dot42.DexImport("setUp", "()V", AccessFlags = 4)]
protected internal override void SetUp() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Make sure all resources are cleaned up and garbage collected before moving on to the next test. Subclasses that override this method should make sure they call super.tearDown() at the end of the overriding method.</para><para></para>
/// </summary>
/// <java-name>
/// tearDown
/// </java-name>
[Dot42.DexImport("tearDown", "()V", AccessFlags = 4)]
protected internal override void TearDown() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Runs the current unit test. If the unit test is annotated with android.test.UiThreadTest, force the Activity to be created before switching to the UI thread. </para>
/// </summary>
/// <java-name>
/// runTest
/// </java-name>
[Dot42.DexImport("runTest", "()V", AccessFlags = 4)]
protected internal override void RunTest() /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal ActivityInstrumentationTestCase2() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Get the Activity under test, starting it if necessary.</para><para>For each test method invocation, the Activity will not actually be created until the first time this method is called.</para><para>If you wish to provide custom setup values to your Activity, you may call setActivityIntent(Intent) and/or setActivityInitialTouchMode(boolean) before your first call to getActivity(). Calling them after your Activity has started will have no effect.</para><para><b>NOTE:</b> Activities under test may not be started from within the UI thread. If your test method is annotated with android.test.UiThreadTest, then your Activity will be started automatically just before your test method is run. You still call this method in order to get the Activity under test.</para><para></para>
/// </summary>
/// <returns>
/// <para>the Activity under test </para>
/// </returns>
/// <java-name>
/// getActivity
/// </java-name>
public T Activity
{
[Dot42.DexImport("getActivity", "()Landroid/app/Activity;", AccessFlags = 1, Signature = "()TT;")]
get{ return GetActivity(); }
}
}
/// <summary>
/// <para>A test case that has access to Instrumentation. </para>
/// </summary>
/// <java-name>
/// android/test/InstrumentationTestCase
/// </java-name>
[Dot42.DexImport("android/test/InstrumentationTestCase", AccessFlags = 33)]
public partial class InstrumentationTestCase : global::Junit.Framework.TestCase
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public InstrumentationTestCase() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Injects instrumentation into this test case. This method is called by the test runner during test setup.</para><para></para>
/// </summary>
/// <java-name>
/// injectInstrumentation
/// </java-name>
[Dot42.DexImport("injectInstrumentation", "(Landroid/app/Instrumentation;)V", AccessFlags = 1)]
public virtual void InjectInstrumentation(global::Android.App.Instrumentation instrumentation) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Injects instrumentation into this test case. This method is called by the test runner during test setup.</para><para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Incorrect spelling, use injectInstrumentation(android.app.Instrumentation) instead. </para></xrefdescription></xrefsect></para>
/// </summary>
/// <java-name>
/// injectInsrumentation
/// </java-name>
[Dot42.DexImport("injectInsrumentation", "(Landroid/app/Instrumentation;)V", AccessFlags = 1)]
public virtual void InjectInsrumentation(global::Android.App.Instrumentation instrumentation) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Inheritors can access the instrumentation using this. </para>
/// </summary>
/// <returns>
/// <para>instrumentation </para>
/// </returns>
/// <java-name>
/// getInstrumentation
/// </java-name>
[Dot42.DexImport("getInstrumentation", "()Landroid/app/Instrumentation;", AccessFlags = 1)]
public virtual global::Android.App.Instrumentation GetInstrumentation() /* MethodBuilder.Create */
{
return default(global::Android.App.Instrumentation);
}
/// <summary>
/// <para>Utility method for launching an activity.</para><para>The Intent used to launch the Activity is: action = Intent#ACTION_MAIN extras = null, unless a custom bundle is provided here All other fields are null or empty.</para><para><b>NOTE:</b> The parameter <b>pkg</b> must refer to the package identifier of the package hosting the activity to be launched, which is specified in the AndroidManifest.xml file. This is not necessarily the same as the java package name.</para><para></para>
/// </summary>
/// <returns>
/// <para>The activity, or null if non launched. </para>
/// </returns>
/// <java-name>
/// launchActivity
/// </java-name>
[Dot42.DexImport("launchActivity", "(Ljava/lang/String;Ljava/lang/Class;Landroid/os/Bundle;)Landroid/app/Activity;", AccessFlags = 17, Signature = "<T:Landroid/app/Activity;>(Ljava/lang/String;Ljava/lang/Class<TT;>;Landroid/os/Bu" +
"ndle;)TT;")]
public T LaunchActivity<T>(string pkg, global::System.Type activityCls, global::Android.Os.Bundle extras) /* MethodBuilder.Create */
{
return default(T);
}
/// <summary>
/// <para>Utility method for launching an activity with a specific Intent.</para><para><b>NOTE:</b> The parameter <b>pkg</b> must refer to the package identifier of the package hosting the activity to be launched, which is specified in the AndroidManifest.xml file. This is not necessarily the same as the java package name.</para><para></para>
/// </summary>
/// <returns>
/// <para>The activity, or null if non launched. </para>
/// </returns>
/// <java-name>
/// launchActivityWithIntent
/// </java-name>
[Dot42.DexImport("launchActivityWithIntent", "(Ljava/lang/String;Ljava/lang/Class;Landroid/content/Intent;)Landroid/app/Activit" +
"y;", AccessFlags = 17, Signature = "<T:Landroid/app/Activity;>(Ljava/lang/String;Ljava/lang/Class<TT;>;Landroid/conte" +
"nt/Intent;)TT;")]
public T LaunchActivityWithIntent<T>(string pkg, global::System.Type activityCls, global::Android.Content.Intent intent) /* MethodBuilder.Create */
{
return default(T);
}
/// <summary>
/// <para>Helper for running portions of a test on the UI thread.</para><para>Note, in most cases it is simpler to annotate the test method with android.test.UiThreadTest, which will run the entire test method on the UI thread. Use this method if you need to switch in and out of the UI thread to perform your test.</para><para></para>
/// </summary>
/// <java-name>
/// runTestOnUiThread
/// </java-name>
[Dot42.DexImport("runTestOnUiThread", "(Ljava/lang/Runnable;)V", AccessFlags = 1)]
public virtual void RunTestOnUiThread(global::Java.Lang.IRunnable r) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Runs the current unit test. If the unit test is annotated with android.test.UiThreadTest, the test is run on the UI thread. </para>
/// </summary>
/// <java-name>
/// runTest
/// </java-name>
[Dot42.DexImport("runTest", "()V", AccessFlags = 4)]
protected internal override void RunTest() /* MethodBuilder.Create */
{
}
/// <java-name>
/// sendKeys
/// </java-name>
[Dot42.DexImport("sendKeys", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SendKeys(string @string) /* MethodBuilder.Create */
{
}
/// <java-name>
/// sendKeys
/// </java-name>
[Dot42.DexImport("sendKeys", "([I)V", AccessFlags = 129)]
public virtual void SendKeys(params int[] int32) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Sends a series of key events through instrumentation and waits for idle. Each key code must be preceded by the number of times the key code must be sent. For instance: sendRepeatedKeys(1, KEYCODE_DPAD_CENTER, 2, KEYCODE_DPAD_LEFT).</para><para></para>
/// </summary>
/// <java-name>
/// sendRepeatedKeys
/// </java-name>
[Dot42.DexImport("sendRepeatedKeys", "([I)V", AccessFlags = 129)]
public virtual void SendRepeatedKeys(params int[] keys) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Make sure all resources are cleaned up and garbage collected before moving on to the next test. Subclasses that override this method should make sure they call super.tearDown() at the end of the overriding method.</para><para></para>
/// </summary>
/// <java-name>
/// tearDown
/// </java-name>
[Dot42.DexImport("tearDown", "()V", AccessFlags = 4)]
protected internal override void TearDown() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Inheritors can access the instrumentation using this. </para>
/// </summary>
/// <returns>
/// <para>instrumentation </para>
/// </returns>
/// <java-name>
/// getInstrumentation
/// </java-name>
public global::Android.App.Instrumentation Instrumentation
{
[Dot42.DexImport("getInstrumentation", "()Landroid/app/Instrumentation;", AccessFlags = 1)]
get{ return GetInstrumentation(); }
}
}
}
| 51.898181 | 4,729 | 0.681889 | [
"Apache-2.0"
] | Dot42Xna/master | Generated/v4.2/Android.Test.cs | 191,141 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/wingdi.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop.Windows;
/// <include file='EMREXTCREATEFONTINDIRECTW.xml' path='doc/member[@name="EMREXTCREATEFONTINDIRECTW"]/*' />
public partial struct EMREXTCREATEFONTINDIRECTW
{
/// <include file='EMREXTCREATEFONTINDIRECTW.xml' path='doc/member[@name="EMREXTCREATEFONTINDIRECTW.emr"]/*' />
public EMR emr;
/// <include file='EMREXTCREATEFONTINDIRECTW.xml' path='doc/member[@name="EMREXTCREATEFONTINDIRECTW.ihFont"]/*' />
[NativeTypeName("DWORD")]
public uint ihFont;
/// <include file='EMREXTCREATEFONTINDIRECTW.xml' path='doc/member[@name="EMREXTCREATEFONTINDIRECTW.elfw"]/*' />
public EXTLOGFONTW elfw;
}
| 44.666667 | 145 | 0.744136 | [
"MIT"
] | reflectronic/terrafx.interop.windows | sources/Interop/Windows/Windows/um/wingdi/EMREXTCREATEFONTINDIRECTW.cs | 940 | C# |
// 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.Globalization;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Diagnostics
{
public sealed partial class FileVersionInfo
{
private unsafe FileVersionInfo(string fileName)
{
_fileName = fileName;
uint handle; // This variable is not used, but we need an out variable.
uint infoSize = Interop.Version.GetFileVersionInfoSizeEx(
(uint)Interop.Version.FileVersionInfoType.FILE_VER_GET_LOCALISED, _fileName, out handle);
if (infoSize != 0)
{
byte[] mem = new byte[infoSize];
fixed (byte* memPtr = &mem[0])
{
IntPtr memIntPtr = new IntPtr((void*)memPtr);
if (Interop.Version.GetFileVersionInfoEx(
(uint)Interop.Version.FileVersionInfoType.FILE_VER_GET_LOCALISED | (uint)Interop.Version.FileVersionInfoType.FILE_VER_GET_NEUTRAL,
_fileName,
0U,
infoSize,
memIntPtr))
{
uint langid = GetVarEntry(memIntPtr);
if (!GetVersionInfoForCodePage(memIntPtr, ConvertTo8DigitHex(langid)))
{
// Some DLLs might not contain correct codepage information. In these cases we will fail during lookup.
// Explorer will take a few shots in dark by trying several specific lang-codepages
// (Explorer also randomly guesses 041D04B0=Swedish+CP_UNICODE and 040704B0=German+CP_UNICODE sometimes).
// We will try to simulate similar behavior here.
foreach (uint id in s_fallbackLanguageCodePages)
{
if (id != langid)
{
if (GetVersionInfoForCodePage(memIntPtr, ConvertTo8DigitHex(id)))
{
break;
}
}
}
}
}
}
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
// Some dlls might not contain correct codepage information,
// in which case the lookup will fail. Explorer will take
// a few shots in dark. We'll simulate similar behavior by
// falling back to the following lang-codepages:
private static readonly uint[] s_fallbackLanguageCodePages = new uint[]
{
0x040904B0, // US English + CP_UNICODE
0x040904E4, // US English + CP_USASCII
0x04090000 // US English + unknown codepage
};
private static string ConvertTo8DigitHex(uint value)
{
return value.ToString("X8", CultureInfo.InvariantCulture);
}
private static Interop.Version.VS_FIXEDFILEINFO GetFixedFileInfo(IntPtr memPtr)
{
IntPtr memRef = IntPtr.Zero;
uint memLen;
if (Interop.Version.VerQueryValue(memPtr, "\\", out memRef, out memLen))
{
return (Interop.Version.VS_FIXEDFILEINFO)Marshal.PtrToStructure<Interop.Version.VS_FIXEDFILEINFO>(memRef);
}
return new Interop.Version.VS_FIXEDFILEINFO();
}
private static string GetFileVersionLanguage(IntPtr memPtr)
{
uint langid = GetVarEntry(memPtr) >> 16;
var lang = new StringBuilder(256);
Interop.Kernel32.VerLanguageName(langid, lang, (uint)lang.Capacity);
return lang.ToString();
}
private static string GetFileVersionString(IntPtr memPtr, string name)
{
IntPtr memRef = IntPtr.Zero;
uint memLen;
if (Interop.Version.VerQueryValue(memPtr, name, out memRef, out memLen))
{
if (memRef != IntPtr.Zero)
{
return Marshal.PtrToStringUni(memRef);
}
}
return string.Empty;
}
private static uint GetVarEntry(IntPtr memPtr)
{
IntPtr memRef = IntPtr.Zero;
uint memLen;
if (Interop.Version.VerQueryValue(memPtr, "\\VarFileInfo\\Translation", out memRef, out memLen))
{
return (uint)((Marshal.ReadInt16(memRef) << 16) + Marshal.ReadInt16((IntPtr)((long)memRef + 2)));
}
return 0x040904E4;
}
//
// This function tries to find version information for a specific codepage.
// Returns true when version information is found.
//
private bool GetVersionInfoForCodePage(IntPtr memIntPtr, string codepage)
{
string template = "\\\\StringFileInfo\\\\{0}\\\\{1}";
_companyName = GetFileVersionString(memIntPtr, string.Format(CultureInfo.InvariantCulture, template, codepage, "CompanyName"));
_fileDescription = GetFileVersionString(memIntPtr, string.Format(CultureInfo.InvariantCulture, template, codepage, "FileDescription"));
_fileVersion = GetFileVersionString(memIntPtr, string.Format(CultureInfo.InvariantCulture, template, codepage, "FileVersion"));
_internalName = GetFileVersionString(memIntPtr, string.Format(CultureInfo.InvariantCulture, template, codepage, "InternalName"));
_legalCopyright = GetFileVersionString(memIntPtr, string.Format(CultureInfo.InvariantCulture, template, codepage, "LegalCopyright"));
_originalFilename = GetFileVersionString(memIntPtr, string.Format(CultureInfo.InvariantCulture, template, codepage, "OriginalFilename"));
_productName = GetFileVersionString(memIntPtr, string.Format(CultureInfo.InvariantCulture, template, codepage, "ProductName"));
_productVersion = GetFileVersionString(memIntPtr, string.Format(CultureInfo.InvariantCulture, template, codepage, "ProductVersion"));
_comments = GetFileVersionString(memIntPtr, string.Format(CultureInfo.InvariantCulture, template, codepage, "Comments"));
_legalTrademarks = GetFileVersionString(memIntPtr, string.Format(CultureInfo.InvariantCulture, template, codepage, "LegalTrademarks"));
_privateBuild = GetFileVersionString(memIntPtr, string.Format(CultureInfo.InvariantCulture, template, codepage, "PrivateBuild"));
_specialBuild = GetFileVersionString(memIntPtr, string.Format(CultureInfo.InvariantCulture, template, codepage, "SpecialBuild"));
_language = GetFileVersionLanguage(memIntPtr);
Interop.Version.VS_FIXEDFILEINFO ffi = GetFixedFileInfo(memIntPtr);
_fileMajor = (int)HIWORD(ffi.dwFileVersionMS);
_fileMinor = (int)LOWORD(ffi.dwFileVersionMS);
_fileBuild = (int)HIWORD(ffi.dwFileVersionLS);
_filePrivate = (int)LOWORD(ffi.dwFileVersionLS);
_productMajor = (int)HIWORD(ffi.dwProductVersionMS);
_productMinor = (int)LOWORD(ffi.dwProductVersionMS);
_productBuild = (int)HIWORD(ffi.dwProductVersionLS);
_productPrivate = (int)LOWORD(ffi.dwProductVersionLS);
_isDebug = (ffi.dwFileFlags & (uint)Interop.Version.FileVersionInfo.VS_FF_DEBUG) != 0;
_isPatched = (ffi.dwFileFlags & (uint)Interop.Version.FileVersionInfo.VS_FF_PATCHED) != 0;
_isPrivateBuild = (ffi.dwFileFlags & (uint)Interop.Version.FileVersionInfo.VS_FF_PRIVATEBUILD) != 0;
_isPreRelease = (ffi.dwFileFlags & (uint)Interop.Version.FileVersionInfo.VS_FF_PRERELEASE) != 0;
_isSpecialBuild = (ffi.dwFileFlags & (uint)Interop.Version.FileVersionInfo.VS_FF_SPECIALBUILD) != 0;
// fileVersion is chosen based on best guess. Other fields can be used if appropriate.
return (_fileVersion != string.Empty);
}
private static uint HIWORD(uint dword)
{
return (dword >> 16) & 0xffff;
}
private static uint LOWORD(uint dword)
{
return dword & 0xffff;
}
}
}
| 47.379121 | 158 | 0.59666 | [
"MIT"
] | Acidburn0zzz/corefx | src/System.Diagnostics.FileVersionInfo/src/System/Diagnostics/FileVersionInfo.Windows.cs | 8,623 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WinFormsMVC.Request;
using WinFormsMVC.View;
namespace WinFormsMVCUnitTest.Test.Services.Base.GivenFormsManagementTest
{
interface IRedoTest
{
bool IsUndoLock
{
get;
set;
}
Action<IEnumerable<Command>, IEnumerable<BaseForm>> ParentAssertion
{
get;
set;
}
}
}
| 19.884615 | 76 | 0.595745 | [
"MIT"
] | belre/WinFormsMVC | WinFormsMVCUnitTest/Test/Services/Base/GivenFormsManagementTest/IRedoTest.cs | 519 | C# |
using System;
using System.Threading.Tasks;
using Couchbase;
using Couchbase.KeyValue;
namespace try_cb_dotnet.Services
{
public interface ICouchbaseService
{
ICluster Cluster { get; }
IBucket TravelSampleBucket { get; }
ICouchbaseCollection HotelCollection { get; }
public Task<ICouchbaseCollection> TenantCollection(string tenant, string collection);
}
public static class StringExtension
{
public static string DefaultIfEmpty(this string str, string defaultValue)
=> string.IsNullOrWhiteSpace(str) ? defaultValue : str;
}
public class CouchbaseService : ICouchbaseService
{
public ICluster Cluster { get; private set; }
public IBucket TravelSampleBucket { get; private set; }
public ICouchbaseCollection HotelCollection { get; private set; }
public CouchbaseService()
{
// TODO: get these variables via DI, possibly overriding config in appsettings.json
var CB_HOST = Environment.GetEnvironmentVariable("CB_HOST").DefaultIfEmpty("localhost");
var CB_USER = Environment.GetEnvironmentVariable("CB_USER").DefaultIfEmpty("Administrator");
var CB_PSWD = Environment.GetEnvironmentVariable("CB_PSWD").DefaultIfEmpty("password");
Console.WriteLine(
$"Connecting to couchbase://{CB_HOST} with {CB_USER} / {CB_PSWD}");
try {
var task = Task.Run(async () => {
var cluster = await Couchbase.Cluster.ConnectAsync(
$"couchbase://{CB_HOST}",
CB_USER,
CB_PSWD);
Cluster = cluster;
TravelSampleBucket = await Cluster.BucketAsync("travel-sample");
var inventoryScope = await TravelSampleBucket.ScopeAsync("inventory");
HotelCollection = await inventoryScope.CollectionAsync("hotel");
});
task.Wait();
}
catch (AggregateException ae) {
ae.Handle((x) => throw x);
}
}
public async Task<ICouchbaseCollection> TenantCollection(string tenant, string collection)
{
var tenantScope = await TravelSampleBucket.ScopeAsync(tenant);
var tenantCollection = await tenantScope.CollectionAsync(collection);
return tenantCollection;
}
}
}
| 37.5 | 104 | 0.612121 | [
"MIT"
] | couchbaselabs/try-cb-dotnet | try-cb-dotnet/Services/CouchbaseService.cs | 2,475 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
using System.Management.Automation.Internal;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// The implementation of the "get-alias" cmdlet.
/// </summary>
[Cmdlet(VerbsCommon.Get, "Alias", DefaultParameterSetName = "Default", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096702")]
[OutputType(typeof(AliasInfo))]
public class GetAliasCommand : PSCmdlet
{
#region Parameters
/// <summary>
/// The Name parameter for the command.
/// </summary>
[Parameter(ParameterSetName = "Default", Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty()]
public string[] Name
{
get { return _names; }
set { _names = value ?? new string[] { "*" }; }
}
private string[] _names = new string[] { "*" };
/// <summary>
/// The Exclude parameter for the command.
/// </summary>
[Parameter]
public string[] Exclude
{
get { return _excludes; }
set { _excludes = value ?? Array.Empty<string>(); }
}
private string[] _excludes = Array.Empty<string>();
/// <summary>
/// The scope parameter for the command determines
/// which scope the aliases are retrieved from.
/// </summary>
[Parameter]
public string Scope { get; set; }
/// <summary>
/// Parameter definition to retrieve aliases based on their definitions.
/// </summary>
[Parameter(ParameterSetName = "Definition")]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Definition { get; set; }
#endregion Parameters
#region Command code
/// <summary>
/// The main processing loop of the command.
/// </summary>
protected override void ProcessRecord()
{
if (ParameterSetName.Equals("Definition"))
{
foreach (string defn in Definition)
{
WriteMatches(defn, "Definition");
}
}
else
{
foreach (string aliasName in _names)
{
WriteMatches(aliasName, "Default");
}
}
}
#endregion Command code
private void WriteMatches(string value, string parametersetname)
{
// First get the alias table (from the proper scope if necessary)
IDictionary<string, AliasInfo> aliasTable = null;
// get the command origin
CommandOrigin origin = MyInvocation.CommandOrigin;
string displayString = "name";
if (!string.IsNullOrEmpty(Scope))
{
// This can throw PSArgumentException and PSArgumentOutOfRangeException
// but just let them go as this is terminal for the pipeline and the
// exceptions are already properly adorned with an ErrorRecord.
aliasTable = SessionState.Internal.GetAliasTableAtScope(Scope);
}
else
{
aliasTable = SessionState.Internal.GetAliasTable();
}
bool matchfound = false;
bool ContainsWildcard = WildcardPattern.ContainsWildcardCharacters(value);
WildcardPattern wcPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase);
// excluding patter for Default paramset.
Collection<WildcardPattern> excludePatterns =
SessionStateUtilities.CreateWildcardsFromStrings(
_excludes,
WildcardOptions.IgnoreCase);
List<AliasInfo> results = new List<AliasInfo>();
foreach (KeyValuePair<string, AliasInfo> tableEntry in aliasTable)
{
if (parametersetname.Equals("Definition", StringComparison.OrdinalIgnoreCase))
{
displayString = "definition";
if (!wcPattern.IsMatch(tableEntry.Value.Definition))
{
continue;
}
if (SessionStateUtilities.MatchesAnyWildcardPattern(tableEntry.Value.Definition, excludePatterns, false))
{
continue;
}
}
else
{
if (!wcPattern.IsMatch(tableEntry.Key))
{
continue;
}
// excludes pattern
if (SessionStateUtilities.MatchesAnyWildcardPattern(tableEntry.Key, excludePatterns, false))
{
continue;
}
}
if (ContainsWildcard)
{
// Only write the command if it is visible to the requestor
if (SessionState.IsVisible(origin, tableEntry.Value))
{
matchfound = true;
results.Add(tableEntry.Value);
}
}
else
{
// For specifically named elements, generate an error for elements that aren't visible...
try
{
SessionState.ThrowIfNotVisible(origin, tableEntry.Value);
results.Add(tableEntry.Value);
matchfound = true;
}
catch (SessionStateException sessionStateException)
{
WriteError(
new ErrorRecord(
sessionStateException.ErrorRecord,
sessionStateException));
// Even though it resulted in an error, a result was found
// so we don't want to generate the nothing found error
// at the end...
matchfound = true;
continue;
}
}
}
results.Sort(
delegate (AliasInfo left, AliasInfo right)
{
return StringComparer.CurrentCultureIgnoreCase.Compare(left.Name, right.Name);
});
foreach (AliasInfo alias in results)
{
this.WriteObject(alias);
}
if (!matchfound && !ContainsWildcard && (excludePatterns == null || excludePatterns.Count == 0))
{
// Need to write an error if the user tries to get an alias
// tat doesn't exist and they are not globbing.
ItemNotFoundException itemNotFound = new ItemNotFoundException(StringUtil.Format(AliasCommandStrings.NoAliasFound, displayString, value));
ErrorRecord er = new ErrorRecord(itemNotFound, "ItemNotFoundException", ErrorCategory.ObjectNotFound, value);
WriteError(er);
}
}
}
}
| 36.936585 | 154 | 0.521659 | [
"MIT"
] | 202006233011/PowerShell | src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs | 7,572 | C# |
//******************************************************************************************************
// AssemblyInfo.cs - Gbtc
//
// Copyright © 2017, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this
// file except in compliance with the License. You may obtain a copy of the License at:
//
// http://opensource.org/licenses/MIT
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 03/09/2017 - J. Ritchie Carroll
// Generated original version of source code.
//
//******************************************************************************************************
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("eDNAAdapters")]
[assembly: AssemblyDescription("Instep eDNA Adapters for the Grid Solutions Framework")]
[assembly: AssemblyDefaultAlias("eDNAAdapters")]
[assembly: AssemblyProduct("Grid Solutions Framework")]
[assembly: AssemblyCopyright("Copyright © GPA, 2017. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Assembly manifest attributes.
#if DEBUG
[assembly: AssemblyConfiguration("Debug Build")]
#else
[assembly: AssemblyConfiguration("Release Build")]
#endif
// Other configuration attributes.
[assembly: CLSCompliant(false)]
[assembly: ComVisible(false)]
[assembly: Guid("1c165fad-7d51-4d8e-9311-4a3be266d877")]
// Assembly identity attributes.
[assembly: AssemblyVersion("2.3.73.0")]
[assembly: AssemblyFileVersion("2.3.73.0")]
[assembly: AssemblyInformationalVersion("2.3.73-beta")] | 43.647059 | 105 | 0.651842 | [
"MIT"
] | QuarkSoftware/gsf | Source/Libraries/Adapters/eDNAAdapters/Properties/AssemblyInfo.cs | 2,230 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.PubSub.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedSubscriberServiceApiClientTest
{
[xunit::FactAttribute]
public void CreateSubscriptionRequestObject()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
Subscription request = new Subscription
{
SubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
PushConfig = new PushConfig(),
AckDeadlineSeconds = -1594362342,
RetainAckedMessages = false,
MessageRetentionDuration = new wkt::Duration(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EnableMessageOrdering = true,
ExpirationPolicy = new ExpirationPolicy(),
Filter = "filtere47ac9b2",
DeadLetterPolicy = new DeadLetterPolicy(),
RetryPolicy = new RetryPolicy(),
Detached = false,
};
Subscription expectedResponse = new Subscription
{
SubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
PushConfig = new PushConfig(),
AckDeadlineSeconds = -1594362342,
RetainAckedMessages = false,
MessageRetentionDuration = new wkt::Duration(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EnableMessageOrdering = true,
ExpirationPolicy = new ExpirationPolicy(),
Filter = "filtere47ac9b2",
DeadLetterPolicy = new DeadLetterPolicy(),
RetryPolicy = new RetryPolicy(),
Detached = false,
};
mockGrpcClient.Setup(x => x.CreateSubscription(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Subscription response = client.CreateSubscription(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateSubscriptionRequestObjectAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
Subscription request = new Subscription
{
SubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
PushConfig = new PushConfig(),
AckDeadlineSeconds = -1594362342,
RetainAckedMessages = false,
MessageRetentionDuration = new wkt::Duration(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EnableMessageOrdering = true,
ExpirationPolicy = new ExpirationPolicy(),
Filter = "filtere47ac9b2",
DeadLetterPolicy = new DeadLetterPolicy(),
RetryPolicy = new RetryPolicy(),
Detached = false,
};
Subscription expectedResponse = new Subscription
{
SubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
PushConfig = new PushConfig(),
AckDeadlineSeconds = -1594362342,
RetainAckedMessages = false,
MessageRetentionDuration = new wkt::Duration(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EnableMessageOrdering = true,
ExpirationPolicy = new ExpirationPolicy(),
Filter = "filtere47ac9b2",
DeadLetterPolicy = new DeadLetterPolicy(),
RetryPolicy = new RetryPolicy(),
Detached = false,
};
mockGrpcClient.Setup(x => x.CreateSubscriptionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Subscription>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Subscription responseCallSettings = await client.CreateSubscriptionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Subscription responseCancellationToken = await client.CreateSubscriptionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateSubscription()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
Subscription request = new Subscription
{
SubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
PushConfig = new PushConfig(),
AckDeadlineSeconds = -1594362342,
};
Subscription expectedResponse = new Subscription
{
SubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
PushConfig = new PushConfig(),
AckDeadlineSeconds = -1594362342,
RetainAckedMessages = false,
MessageRetentionDuration = new wkt::Duration(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EnableMessageOrdering = true,
ExpirationPolicy = new ExpirationPolicy(),
Filter = "filtere47ac9b2",
DeadLetterPolicy = new DeadLetterPolicy(),
RetryPolicy = new RetryPolicy(),
Detached = false,
};
mockGrpcClient.Setup(x => x.CreateSubscription(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Subscription response = client.CreateSubscription(request.Name, request.Topic, request.PushConfig, request.AckDeadlineSeconds);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateSubscriptionAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
Subscription request = new Subscription
{
SubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
PushConfig = new PushConfig(),
AckDeadlineSeconds = -1594362342,
};
Subscription expectedResponse = new Subscription
{
SubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
PushConfig = new PushConfig(),
AckDeadlineSeconds = -1594362342,
RetainAckedMessages = false,
MessageRetentionDuration = new wkt::Duration(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EnableMessageOrdering = true,
ExpirationPolicy = new ExpirationPolicy(),
Filter = "filtere47ac9b2",
DeadLetterPolicy = new DeadLetterPolicy(),
RetryPolicy = new RetryPolicy(),
Detached = false,
};
mockGrpcClient.Setup(x => x.CreateSubscriptionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Subscription>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Subscription responseCallSettings = await client.CreateSubscriptionAsync(request.Name, request.Topic, request.PushConfig, request.AckDeadlineSeconds, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Subscription responseCancellationToken = await client.CreateSubscriptionAsync(request.Name, request.Topic, request.PushConfig, request.AckDeadlineSeconds, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateSubscriptionResourceNames()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
Subscription request = new Subscription
{
SubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
PushConfig = new PushConfig(),
AckDeadlineSeconds = -1594362342,
};
Subscription expectedResponse = new Subscription
{
SubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
PushConfig = new PushConfig(),
AckDeadlineSeconds = -1594362342,
RetainAckedMessages = false,
MessageRetentionDuration = new wkt::Duration(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EnableMessageOrdering = true,
ExpirationPolicy = new ExpirationPolicy(),
Filter = "filtere47ac9b2",
DeadLetterPolicy = new DeadLetterPolicy(),
RetryPolicy = new RetryPolicy(),
Detached = false,
};
mockGrpcClient.Setup(x => x.CreateSubscription(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Subscription response = client.CreateSubscription(request.SubscriptionName, request.TopicAsTopicName, request.PushConfig, request.AckDeadlineSeconds);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateSubscriptionResourceNamesAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
Subscription request = new Subscription
{
SubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
PushConfig = new PushConfig(),
AckDeadlineSeconds = -1594362342,
};
Subscription expectedResponse = new Subscription
{
SubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
PushConfig = new PushConfig(),
AckDeadlineSeconds = -1594362342,
RetainAckedMessages = false,
MessageRetentionDuration = new wkt::Duration(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EnableMessageOrdering = true,
ExpirationPolicy = new ExpirationPolicy(),
Filter = "filtere47ac9b2",
DeadLetterPolicy = new DeadLetterPolicy(),
RetryPolicy = new RetryPolicy(),
Detached = false,
};
mockGrpcClient.Setup(x => x.CreateSubscriptionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Subscription>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Subscription responseCallSettings = await client.CreateSubscriptionAsync(request.SubscriptionName, request.TopicAsTopicName, request.PushConfig, request.AckDeadlineSeconds, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Subscription responseCancellationToken = await client.CreateSubscriptionAsync(request.SubscriptionName, request.TopicAsTopicName, request.PushConfig, request.AckDeadlineSeconds, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSubscriptionRequestObject()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
GetSubscriptionRequest request = new GetSubscriptionRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
};
Subscription expectedResponse = new Subscription
{
SubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
PushConfig = new PushConfig(),
AckDeadlineSeconds = -1594362342,
RetainAckedMessages = false,
MessageRetentionDuration = new wkt::Duration(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EnableMessageOrdering = true,
ExpirationPolicy = new ExpirationPolicy(),
Filter = "filtere47ac9b2",
DeadLetterPolicy = new DeadLetterPolicy(),
RetryPolicy = new RetryPolicy(),
Detached = false,
};
mockGrpcClient.Setup(x => x.GetSubscription(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Subscription response = client.GetSubscription(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSubscriptionRequestObjectAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
GetSubscriptionRequest request = new GetSubscriptionRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
};
Subscription expectedResponse = new Subscription
{
SubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
PushConfig = new PushConfig(),
AckDeadlineSeconds = -1594362342,
RetainAckedMessages = false,
MessageRetentionDuration = new wkt::Duration(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EnableMessageOrdering = true,
ExpirationPolicy = new ExpirationPolicy(),
Filter = "filtere47ac9b2",
DeadLetterPolicy = new DeadLetterPolicy(),
RetryPolicy = new RetryPolicy(),
Detached = false,
};
mockGrpcClient.Setup(x => x.GetSubscriptionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Subscription>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Subscription responseCallSettings = await client.GetSubscriptionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Subscription responseCancellationToken = await client.GetSubscriptionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSubscription()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
GetSubscriptionRequest request = new GetSubscriptionRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
};
Subscription expectedResponse = new Subscription
{
SubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
PushConfig = new PushConfig(),
AckDeadlineSeconds = -1594362342,
RetainAckedMessages = false,
MessageRetentionDuration = new wkt::Duration(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EnableMessageOrdering = true,
ExpirationPolicy = new ExpirationPolicy(),
Filter = "filtere47ac9b2",
DeadLetterPolicy = new DeadLetterPolicy(),
RetryPolicy = new RetryPolicy(),
Detached = false,
};
mockGrpcClient.Setup(x => x.GetSubscription(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Subscription response = client.GetSubscription(request.Subscription);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSubscriptionAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
GetSubscriptionRequest request = new GetSubscriptionRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
};
Subscription expectedResponse = new Subscription
{
SubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
PushConfig = new PushConfig(),
AckDeadlineSeconds = -1594362342,
RetainAckedMessages = false,
MessageRetentionDuration = new wkt::Duration(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EnableMessageOrdering = true,
ExpirationPolicy = new ExpirationPolicy(),
Filter = "filtere47ac9b2",
DeadLetterPolicy = new DeadLetterPolicy(),
RetryPolicy = new RetryPolicy(),
Detached = false,
};
mockGrpcClient.Setup(x => x.GetSubscriptionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Subscription>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Subscription responseCallSettings = await client.GetSubscriptionAsync(request.Subscription, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Subscription responseCancellationToken = await client.GetSubscriptionAsync(request.Subscription, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSubscriptionResourceNames()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
GetSubscriptionRequest request = new GetSubscriptionRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
};
Subscription expectedResponse = new Subscription
{
SubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
PushConfig = new PushConfig(),
AckDeadlineSeconds = -1594362342,
RetainAckedMessages = false,
MessageRetentionDuration = new wkt::Duration(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EnableMessageOrdering = true,
ExpirationPolicy = new ExpirationPolicy(),
Filter = "filtere47ac9b2",
DeadLetterPolicy = new DeadLetterPolicy(),
RetryPolicy = new RetryPolicy(),
Detached = false,
};
mockGrpcClient.Setup(x => x.GetSubscription(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Subscription response = client.GetSubscription(request.SubscriptionAsSubscriptionName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSubscriptionResourceNamesAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
GetSubscriptionRequest request = new GetSubscriptionRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
};
Subscription expectedResponse = new Subscription
{
SubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
PushConfig = new PushConfig(),
AckDeadlineSeconds = -1594362342,
RetainAckedMessages = false,
MessageRetentionDuration = new wkt::Duration(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EnableMessageOrdering = true,
ExpirationPolicy = new ExpirationPolicy(),
Filter = "filtere47ac9b2",
DeadLetterPolicy = new DeadLetterPolicy(),
RetryPolicy = new RetryPolicy(),
Detached = false,
};
mockGrpcClient.Setup(x => x.GetSubscriptionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Subscription>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Subscription responseCallSettings = await client.GetSubscriptionAsync(request.SubscriptionAsSubscriptionName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Subscription responseCancellationToken = await client.GetSubscriptionAsync(request.SubscriptionAsSubscriptionName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateSubscriptionRequestObject()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
UpdateSubscriptionRequest request = new UpdateSubscriptionRequest
{
Subscription = new Subscription(),
UpdateMask = new wkt::FieldMask(),
};
Subscription expectedResponse = new Subscription
{
SubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
PushConfig = new PushConfig(),
AckDeadlineSeconds = -1594362342,
RetainAckedMessages = false,
MessageRetentionDuration = new wkt::Duration(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EnableMessageOrdering = true,
ExpirationPolicy = new ExpirationPolicy(),
Filter = "filtere47ac9b2",
DeadLetterPolicy = new DeadLetterPolicy(),
RetryPolicy = new RetryPolicy(),
Detached = false,
};
mockGrpcClient.Setup(x => x.UpdateSubscription(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Subscription response = client.UpdateSubscription(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateSubscriptionRequestObjectAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
UpdateSubscriptionRequest request = new UpdateSubscriptionRequest
{
Subscription = new Subscription(),
UpdateMask = new wkt::FieldMask(),
};
Subscription expectedResponse = new Subscription
{
SubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
PushConfig = new PushConfig(),
AckDeadlineSeconds = -1594362342,
RetainAckedMessages = false,
MessageRetentionDuration = new wkt::Duration(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
EnableMessageOrdering = true,
ExpirationPolicy = new ExpirationPolicy(),
Filter = "filtere47ac9b2",
DeadLetterPolicy = new DeadLetterPolicy(),
RetryPolicy = new RetryPolicy(),
Detached = false,
};
mockGrpcClient.Setup(x => x.UpdateSubscriptionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Subscription>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Subscription responseCallSettings = await client.UpdateSubscriptionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Subscription responseCancellationToken = await client.UpdateSubscriptionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteSubscriptionRequestObject()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
DeleteSubscriptionRequest request = new DeleteSubscriptionRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSubscription(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
client.DeleteSubscription(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteSubscriptionRequestObjectAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
DeleteSubscriptionRequest request = new DeleteSubscriptionRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSubscriptionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
await client.DeleteSubscriptionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteSubscriptionAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteSubscription()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
DeleteSubscriptionRequest request = new DeleteSubscriptionRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSubscription(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
client.DeleteSubscription(request.Subscription);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteSubscriptionAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
DeleteSubscriptionRequest request = new DeleteSubscriptionRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSubscriptionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
await client.DeleteSubscriptionAsync(request.Subscription, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteSubscriptionAsync(request.Subscription, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteSubscriptionResourceNames()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
DeleteSubscriptionRequest request = new DeleteSubscriptionRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSubscription(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
client.DeleteSubscription(request.SubscriptionAsSubscriptionName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteSubscriptionResourceNamesAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
DeleteSubscriptionRequest request = new DeleteSubscriptionRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSubscriptionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
await client.DeleteSubscriptionAsync(request.SubscriptionAsSubscriptionName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteSubscriptionAsync(request.SubscriptionAsSubscriptionName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ModifyAckDeadlineRequestObject()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
ModifyAckDeadlineRequest request = new ModifyAckDeadlineRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
AckDeadlineSeconds = -1594362342,
AckIds = { "ack_ids67b2de9b", },
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.ModifyAckDeadline(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
client.ModifyAckDeadline(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ModifyAckDeadlineRequestObjectAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
ModifyAckDeadlineRequest request = new ModifyAckDeadlineRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
AckDeadlineSeconds = -1594362342,
AckIds = { "ack_ids67b2de9b", },
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.ModifyAckDeadlineAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
await client.ModifyAckDeadlineAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.ModifyAckDeadlineAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ModifyAckDeadline()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
ModifyAckDeadlineRequest request = new ModifyAckDeadlineRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
AckDeadlineSeconds = -1594362342,
AckIds = { "ack_ids67b2de9b", },
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.ModifyAckDeadline(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
client.ModifyAckDeadline(request.Subscription, request.AckIds, request.AckDeadlineSeconds);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ModifyAckDeadlineAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
ModifyAckDeadlineRequest request = new ModifyAckDeadlineRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
AckDeadlineSeconds = -1594362342,
AckIds = { "ack_ids67b2de9b", },
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.ModifyAckDeadlineAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
await client.ModifyAckDeadlineAsync(request.Subscription, request.AckIds, request.AckDeadlineSeconds, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.ModifyAckDeadlineAsync(request.Subscription, request.AckIds, request.AckDeadlineSeconds, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ModifyAckDeadlineResourceNames()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
ModifyAckDeadlineRequest request = new ModifyAckDeadlineRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
AckDeadlineSeconds = -1594362342,
AckIds = { "ack_ids67b2de9b", },
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.ModifyAckDeadline(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
client.ModifyAckDeadline(request.SubscriptionAsSubscriptionName, request.AckIds, request.AckDeadlineSeconds);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ModifyAckDeadlineResourceNamesAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
ModifyAckDeadlineRequest request = new ModifyAckDeadlineRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
AckDeadlineSeconds = -1594362342,
AckIds = { "ack_ids67b2de9b", },
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.ModifyAckDeadlineAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
await client.ModifyAckDeadlineAsync(request.SubscriptionAsSubscriptionName, request.AckIds, request.AckDeadlineSeconds, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.ModifyAckDeadlineAsync(request.SubscriptionAsSubscriptionName, request.AckIds, request.AckDeadlineSeconds, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void AcknowledgeRequestObject()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
AcknowledgeRequest request = new AcknowledgeRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
AckIds = { "ack_ids67b2de9b", },
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.Acknowledge(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
client.Acknowledge(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task AcknowledgeRequestObjectAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
AcknowledgeRequest request = new AcknowledgeRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
AckIds = { "ack_ids67b2de9b", },
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.AcknowledgeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
await client.AcknowledgeAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.AcknowledgeAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Acknowledge()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
AcknowledgeRequest request = new AcknowledgeRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
AckIds = { "ack_ids67b2de9b", },
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.Acknowledge(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
client.Acknowledge(request.Subscription, request.AckIds);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task AcknowledgeAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
AcknowledgeRequest request = new AcknowledgeRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
AckIds = { "ack_ids67b2de9b", },
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.AcknowledgeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
await client.AcknowledgeAsync(request.Subscription, request.AckIds, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.AcknowledgeAsync(request.Subscription, request.AckIds, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void AcknowledgeResourceNames()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
AcknowledgeRequest request = new AcknowledgeRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
AckIds = { "ack_ids67b2de9b", },
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.Acknowledge(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
client.Acknowledge(request.SubscriptionAsSubscriptionName, request.AckIds);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task AcknowledgeResourceNamesAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
AcknowledgeRequest request = new AcknowledgeRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
AckIds = { "ack_ids67b2de9b", },
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.AcknowledgeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
await client.AcknowledgeAsync(request.SubscriptionAsSubscriptionName, request.AckIds, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.AcknowledgeAsync(request.SubscriptionAsSubscriptionName, request.AckIds, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void PullRequestObject()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
PullRequest request = new PullRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
#pragma warning disable CS0612
ReturnImmediately = false,
#pragma warning restore CS0612
MaxMessages = 453182879,
};
PullResponse expectedResponse = new PullResponse
{
ReceivedMessages =
{
new ReceivedMessage(),
},
};
mockGrpcClient.Setup(x => x.Pull(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
PullResponse response = client.Pull(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task PullRequestObjectAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
PullRequest request = new PullRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
#pragma warning disable CS0612
ReturnImmediately = false,
#pragma warning restore CS0612
MaxMessages = 453182879,
};
PullResponse expectedResponse = new PullResponse
{
ReceivedMessages =
{
new ReceivedMessage(),
},
};
mockGrpcClient.Setup(x => x.PullAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PullResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
PullResponse responseCallSettings = await client.PullAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PullResponse responseCancellationToken = await client.PullAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Pull()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
PullRequest request = new PullRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
#pragma warning disable CS0612
ReturnImmediately = false,
#pragma warning restore CS0612
MaxMessages = 453182879,
};
PullResponse expectedResponse = new PullResponse
{
ReceivedMessages =
{
new ReceivedMessage(),
},
};
mockGrpcClient.Setup(x => x.Pull(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
#pragma warning disable CS0612
PullResponse response = client.Pull(request.Subscription, request.ReturnImmediately, request.MaxMessages);
#pragma warning restore CS0612
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task PullAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
PullRequest request = new PullRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
#pragma warning disable CS0612
ReturnImmediately = false,
#pragma warning restore CS0612
MaxMessages = 453182879,
};
PullResponse expectedResponse = new PullResponse
{
ReceivedMessages =
{
new ReceivedMessage(),
},
};
mockGrpcClient.Setup(x => x.PullAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PullResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
#pragma warning disable CS0612
PullResponse responseCallSettings = await client.PullAsync(request.Subscription, request.ReturnImmediately, request.MaxMessages, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
#pragma warning restore CS0612
xunit::Assert.Same(expectedResponse, responseCallSettings);
#pragma warning disable CS0612
PullResponse responseCancellationToken = await client.PullAsync(request.Subscription, request.ReturnImmediately, request.MaxMessages, st::CancellationToken.None);
#pragma warning restore CS0612
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void PullResourceNames()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
PullRequest request = new PullRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
#pragma warning disable CS0612
ReturnImmediately = false,
#pragma warning restore CS0612
MaxMessages = 453182879,
};
PullResponse expectedResponse = new PullResponse
{
ReceivedMessages =
{
new ReceivedMessage(),
},
};
mockGrpcClient.Setup(x => x.Pull(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
#pragma warning disable CS0612
PullResponse response = client.Pull(request.SubscriptionAsSubscriptionName, request.ReturnImmediately, request.MaxMessages);
#pragma warning restore CS0612
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task PullResourceNamesAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
PullRequest request = new PullRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
#pragma warning disable CS0612
ReturnImmediately = false,
#pragma warning restore CS0612
MaxMessages = 453182879,
};
PullResponse expectedResponse = new PullResponse
{
ReceivedMessages =
{
new ReceivedMessage(),
},
};
mockGrpcClient.Setup(x => x.PullAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PullResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
#pragma warning disable CS0612
PullResponse responseCallSettings = await client.PullAsync(request.SubscriptionAsSubscriptionName, request.ReturnImmediately, request.MaxMessages, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
#pragma warning restore CS0612
xunit::Assert.Same(expectedResponse, responseCallSettings);
#pragma warning disable CS0612
PullResponse responseCancellationToken = await client.PullAsync(request.SubscriptionAsSubscriptionName, request.ReturnImmediately, request.MaxMessages, st::CancellationToken.None);
#pragma warning restore CS0612
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ModifyPushConfigRequestObject()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
ModifyPushConfigRequest request = new ModifyPushConfigRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
PushConfig = new PushConfig(),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.ModifyPushConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
client.ModifyPushConfig(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ModifyPushConfigRequestObjectAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
ModifyPushConfigRequest request = new ModifyPushConfigRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
PushConfig = new PushConfig(),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.ModifyPushConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
await client.ModifyPushConfigAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.ModifyPushConfigAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ModifyPushConfig()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
ModifyPushConfigRequest request = new ModifyPushConfigRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
PushConfig = new PushConfig(),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.ModifyPushConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
client.ModifyPushConfig(request.Subscription, request.PushConfig);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ModifyPushConfigAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
ModifyPushConfigRequest request = new ModifyPushConfigRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
PushConfig = new PushConfig(),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.ModifyPushConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
await client.ModifyPushConfigAsync(request.Subscription, request.PushConfig, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.ModifyPushConfigAsync(request.Subscription, request.PushConfig, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ModifyPushConfigResourceNames()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
ModifyPushConfigRequest request = new ModifyPushConfigRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
PushConfig = new PushConfig(),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.ModifyPushConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
client.ModifyPushConfig(request.SubscriptionAsSubscriptionName, request.PushConfig);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ModifyPushConfigResourceNamesAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
ModifyPushConfigRequest request = new ModifyPushConfigRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
PushConfig = new PushConfig(),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.ModifyPushConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
await client.ModifyPushConfigAsync(request.SubscriptionAsSubscriptionName, request.PushConfig, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.ModifyPushConfigAsync(request.SubscriptionAsSubscriptionName, request.PushConfig, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSnapshotRequestObject()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
GetSnapshotRequest request = new GetSnapshotRequest
{
SnapshotAsSnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
};
Snapshot expectedResponse = new Snapshot
{
SnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
ExpireTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetSnapshot(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Snapshot response = client.GetSnapshot(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSnapshotRequestObjectAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
GetSnapshotRequest request = new GetSnapshotRequest
{
SnapshotAsSnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
};
Snapshot expectedResponse = new Snapshot
{
SnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
ExpireTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetSnapshotAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Snapshot>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Snapshot responseCallSettings = await client.GetSnapshotAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Snapshot responseCancellationToken = await client.GetSnapshotAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSnapshot()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
GetSnapshotRequest request = new GetSnapshotRequest
{
SnapshotAsSnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
};
Snapshot expectedResponse = new Snapshot
{
SnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
ExpireTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetSnapshot(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Snapshot response = client.GetSnapshot(request.Snapshot);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSnapshotAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
GetSnapshotRequest request = new GetSnapshotRequest
{
SnapshotAsSnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
};
Snapshot expectedResponse = new Snapshot
{
SnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
ExpireTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetSnapshotAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Snapshot>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Snapshot responseCallSettings = await client.GetSnapshotAsync(request.Snapshot, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Snapshot responseCancellationToken = await client.GetSnapshotAsync(request.Snapshot, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSnapshotResourceNames()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
GetSnapshotRequest request = new GetSnapshotRequest
{
SnapshotAsSnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
};
Snapshot expectedResponse = new Snapshot
{
SnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
ExpireTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetSnapshot(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Snapshot response = client.GetSnapshot(request.SnapshotAsSnapshotName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSnapshotResourceNamesAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
GetSnapshotRequest request = new GetSnapshotRequest
{
SnapshotAsSnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
};
Snapshot expectedResponse = new Snapshot
{
SnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
ExpireTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.GetSnapshotAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Snapshot>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Snapshot responseCallSettings = await client.GetSnapshotAsync(request.SnapshotAsSnapshotName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Snapshot responseCancellationToken = await client.GetSnapshotAsync(request.SnapshotAsSnapshotName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateSnapshotRequestObject()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
CreateSnapshotRequest request = new CreateSnapshotRequest
{
SnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
Snapshot expectedResponse = new Snapshot
{
SnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
ExpireTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.CreateSnapshot(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Snapshot response = client.CreateSnapshot(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateSnapshotRequestObjectAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
CreateSnapshotRequest request = new CreateSnapshotRequest
{
SnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
Snapshot expectedResponse = new Snapshot
{
SnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
ExpireTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.CreateSnapshotAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Snapshot>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Snapshot responseCallSettings = await client.CreateSnapshotAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Snapshot responseCancellationToken = await client.CreateSnapshotAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateSnapshot()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
CreateSnapshotRequest request = new CreateSnapshotRequest
{
SnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
};
Snapshot expectedResponse = new Snapshot
{
SnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
ExpireTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.CreateSnapshot(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Snapshot response = client.CreateSnapshot(request.Name, request.Subscription);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateSnapshotAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
CreateSnapshotRequest request = new CreateSnapshotRequest
{
SnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
};
Snapshot expectedResponse = new Snapshot
{
SnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
ExpireTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.CreateSnapshotAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Snapshot>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Snapshot responseCallSettings = await client.CreateSnapshotAsync(request.Name, request.Subscription, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Snapshot responseCancellationToken = await client.CreateSnapshotAsync(request.Name, request.Subscription, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateSnapshotResourceNames()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
CreateSnapshotRequest request = new CreateSnapshotRequest
{
SnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
};
Snapshot expectedResponse = new Snapshot
{
SnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
ExpireTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.CreateSnapshot(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Snapshot response = client.CreateSnapshot(request.SnapshotName, request.SubscriptionAsSubscriptionName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateSnapshotResourceNamesAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
CreateSnapshotRequest request = new CreateSnapshotRequest
{
SnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
};
Snapshot expectedResponse = new Snapshot
{
SnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
ExpireTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.CreateSnapshotAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Snapshot>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Snapshot responseCallSettings = await client.CreateSnapshotAsync(request.SnapshotName, request.SubscriptionAsSubscriptionName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Snapshot responseCancellationToken = await client.CreateSnapshotAsync(request.SnapshotName, request.SubscriptionAsSubscriptionName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateSnapshotRequestObject()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
UpdateSnapshotRequest request = new UpdateSnapshotRequest
{
Snapshot = new Snapshot(),
UpdateMask = new wkt::FieldMask(),
};
Snapshot expectedResponse = new Snapshot
{
SnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
ExpireTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.UpdateSnapshot(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Snapshot response = client.UpdateSnapshot(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateSnapshotRequestObjectAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
UpdateSnapshotRequest request = new UpdateSnapshotRequest
{
Snapshot = new Snapshot(),
UpdateMask = new wkt::FieldMask(),
};
Snapshot expectedResponse = new Snapshot
{
SnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
ExpireTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
mockGrpcClient.Setup(x => x.UpdateSnapshotAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Snapshot>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
Snapshot responseCallSettings = await client.UpdateSnapshotAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Snapshot responseCancellationToken = await client.UpdateSnapshotAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteSnapshotRequestObject()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
DeleteSnapshotRequest request = new DeleteSnapshotRequest
{
SnapshotAsSnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSnapshot(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
client.DeleteSnapshot(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteSnapshotRequestObjectAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
DeleteSnapshotRequest request = new DeleteSnapshotRequest
{
SnapshotAsSnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSnapshotAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
await client.DeleteSnapshotAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteSnapshotAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteSnapshot()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
DeleteSnapshotRequest request = new DeleteSnapshotRequest
{
SnapshotAsSnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSnapshot(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
client.DeleteSnapshot(request.Snapshot);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteSnapshotAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
DeleteSnapshotRequest request = new DeleteSnapshotRequest
{
SnapshotAsSnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSnapshotAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
await client.DeleteSnapshotAsync(request.Snapshot, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteSnapshotAsync(request.Snapshot, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteSnapshotResourceNames()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
DeleteSnapshotRequest request = new DeleteSnapshotRequest
{
SnapshotAsSnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSnapshot(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
client.DeleteSnapshot(request.SnapshotAsSnapshotName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteSnapshotResourceNamesAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
DeleteSnapshotRequest request = new DeleteSnapshotRequest
{
SnapshotAsSnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSnapshotAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
await client.DeleteSnapshotAsync(request.SnapshotAsSnapshotName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteSnapshotAsync(request.SnapshotAsSnapshotName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SeekRequestObject()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
SeekRequest request = new SeekRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
Time = new wkt::Timestamp(),
SnapshotAsSnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
};
SeekResponse expectedResponse = new SeekResponse { };
mockGrpcClient.Setup(x => x.Seek(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
SeekResponse response = client.Seek(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SeekRequestObjectAsync()
{
moq::Mock<Subscriber.SubscriberClient> mockGrpcClient = new moq::Mock<Subscriber.SubscriberClient>(moq::MockBehavior.Strict);
SeekRequest request = new SeekRequest
{
SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
Time = new wkt::Timestamp(),
SnapshotAsSnapshotName = SnapshotName.FromProjectSnapshot("[PROJECT]", "[SNAPSHOT]"),
};
SeekResponse expectedResponse = new SeekResponse { };
mockGrpcClient.Setup(x => x.SeekAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SeekResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SubscriberServiceApiClient client = new SubscriberServiceApiClientImpl(mockGrpcClient.Object, null);
SeekResponse responseCallSettings = await client.SeekAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SeekResponse responseCancellationToken = await client.SeekAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| 56.772101 | 258 | 0.631657 | [
"Apache-2.0"
] | garrettwong/google-cloud-dotnet | apis/Google.Cloud.PubSub.V1/Google.Cloud.PubSub.V1.Tests/SubscriberServiceApiClientTest.g.cs | 98,897 | C# |
// <auto-generated />
namespace Microsoft.Extensions.ApiDescription.Tool
{
using System.Globalization;
using System.Reflection;
using System.Resources;
internal static class Resources
{
private static readonly ResourceManager _resourceManager
= new ResourceManager("Microsoft.Extensions.ApiDescription.Tool.Resources", typeof(Resources).GetTypeInfo().Assembly);
/// <summary>
/// dotnet-getdocument
/// </summary>
internal static string CommandFullName
{
get => GetString("CommandFullName");
}
/// <summary>
/// dotnet-getdocument
/// </summary>
internal static string FormatCommandFullName()
=> GetString("CommandFullName");
/// <summary>
/// The target framework to use. Required.
/// </summary>
internal static string TargetFrameworkDescription
{
get => GetString("TargetFrameworkDescription");
}
/// <summary>
/// The target framework to use. Required.
/// </summary>
internal static string FormatTargetFrameworkDescription()
=> GetString("TargetFrameworkDescription");
/// <summary>
/// Project '{0}' targets framework '.NETCoreApp' version '{1}'. This version of the dotnet-getdocument tool only supports version 2.1 or higher.
/// </summary>
internal static string OldNETCoreAppProject
{
get => GetString("OldNETCoreAppProject");
}
/// <summary>
/// Project '{0}' targets framework '.NETCoreApp' version '{1}'. This version of the dotnet-getdocument tool only supports version 2.1 or higher.
/// </summary>
internal static string FormatOldNETCoreAppProject(object p0, object p1)
=> string.Format(CultureInfo.CurrentCulture, GetString("OldNETCoreAppProject"), p0, p1);
/// <summary>
/// Project '{0}' targets framework '.NETStandard'. There is no runtime associated with this framework and projects targeting it cannot be executed directly. To use the dotnet-getdocument tool with this project, update this project to target .NET Core and / or .NET Framework.
/// </summary>
internal static string NETStandardProject
{
get => GetString("NETStandardProject");
}
/// <summary>
/// Project '{0}' targets framework '.NETStandard'. There is no runtime associated with this framework and projects targeting it cannot be executed directly. To use the dotnet-getdocument tool with this project, update this project to target .NET Core and / or .NET Framework.
/// </summary>
internal static string FormatNETStandardProject(object p0)
=> string.Format(CultureInfo.CurrentCulture, GetString("NETStandardProject"), p0);
/// <summary>
/// Do not colorize console output.
/// </summary>
internal static string NoColorDescription
{
get => GetString("NoColorDescription");
}
/// <summary>
/// Do not colorize console output.
/// </summary>
internal static string FormatNoColorDescription()
=> GetString("NoColorDescription");
/// <summary>
/// Prefix console output with logging level.
/// </summary>
internal static string PrefixDescription
{
get => GetString("PrefixDescription");
}
/// <summary>
/// Prefix console output with logging level.
/// </summary>
internal static string FormatPrefixDescription()
=> GetString("PrefixDescription");
/// <summary>
/// The project name. Required.
/// </summary>
internal static string ProjectDescription
{
get => GetString("ProjectDescription");
}
/// <summary>
/// The project name. Required.
/// </summary>
internal static string FormatProjectDescription()
=> GetString("ProjectDescription");
/// <summary>
/// The runtime identifier to use.
/// </summary>
internal static string RuntimeDescription
{
get => GetString("RuntimeDescription");
}
/// <summary>
/// The runtime identifier to use.
/// </summary>
internal static string FormatRuntimeDescription()
=> GetString("RuntimeDescription");
/// <summary>
/// Project '{0}' targets framework '{1}'. The dotnet-getdocument tool does not support this framework.
/// </summary>
internal static string UnsupportedFramework
{
get => GetString("UnsupportedFramework");
}
/// <summary>
/// Project '{0}' targets framework '{1}'. The dotnet-getdocument tool does not support this framework.
/// </summary>
internal static string FormatUnsupportedFramework(object p0, object p1)
=> string.Format(CultureInfo.CurrentCulture, GetString("UnsupportedFramework"), p0, p1);
/// <summary>
/// Show verbose output.
/// </summary>
internal static string VerboseDescription
{
get => GetString("VerboseDescription");
}
/// <summary>
/// Show verbose output.
/// </summary>
internal static string FormatVerboseDescription()
=> GetString("VerboseDescription");
/// <summary>
/// The project assets file to use.
/// </summary>
internal static string AssetsFileDescription
{
get => GetString("AssetsFileDescription");
}
/// <summary>
/// The project assets file to use.
/// </summary>
internal static string FormatAssetsFileDescription()
=> GetString("AssetsFileDescription");
/// <summary>
/// Missing required option '--{0}'.
/// </summary>
internal static string MissingOption
{
get => GetString("MissingOption");
}
/// <summary>
/// Missing required option '--{0}'.
/// </summary>
internal static string FormatMissingOption(object p0)
=> string.Format(CultureInfo.CurrentCulture, GetString("MissingOption"), p0);
/// <summary>
/// The platform to use.
/// </summary>
internal static string PlatformDescription
{
get => GetString("PlatformDescription");
}
/// <summary>
/// The platform to use.
/// </summary>
internal static string FormatPlatformDescription()
=> GetString("PlatformDescription");
/// <summary>
/// The assembly path to use. Required.
/// </summary>
internal static string AssemblyDescription
{
get => GetString("AssemblyDescription");
}
/// <summary>
/// The assembly path to use. Required.
/// </summary>
internal static string FormatAssemblyDescription()
=> GetString("AssemblyDescription");
private static string GetString(string name, params string[] formatterNames)
{
var value = _resourceManager.GetString(name);
System.Diagnostics.Debug.Assert(value != null);
if (formatterNames != null)
{
for (var i = 0; i < formatterNames.Length; i++)
{
value = value.Replace("{" + formatterNames[i] + "}", "{" + i + "}");
}
}
return value;
}
}
}
| 34.013216 | 284 | 0.575314 | [
"Apache-2.0"
] | FluentGuru/AspNetCore | src/Mvc/dotnet-getdocument/src/Properties/Resources.Designer.cs | 7,721 | C# |
namespace NServiceKit.DataAccess.Criteria
{
/// <summary>Interface for order descending criteria.</summary>
public interface IOrderDescendingCriteria : ICriteria
{
/// <summary>Gets who ordered descending this object.</summary>
///
/// <value>Describes who ordered descending this object.</value>
string OrderedDescendingBy { get; }
}
} | 34.454545 | 73 | 0.686016 | [
"BSD-3-Clause"
] | NServiceKit/NServiceKit | src/NServiceKit.Interfaces/DataAccess/Criteria/IOrderDescendingCriteria.cs | 369 | C# |
using EntityFX.NetBenchmark.Core.Generic;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace EntityFX.NetBenchmark.Core.Whetstone
{
public class WhetstoneBenchmark : BenchmarkBase<WhetstoneResult>, IBenchamrk
{
private readonly WhetstoneDouble whetstone;
public WhetstoneBenchmark(IWriter writer)
:base(writer)
{
whetstone = new WhetstoneDouble(true);
}
public override WhetstoneResult BenchImplementation()
{
return whetstone.Bench(true);
}
public override BenchResult PopulateResult(BenchResult benchResult, WhetstoneResult whetstoneResult)
{
benchResult.Result = whetstoneResult.MWIPS;
benchResult.Points = whetstoneResult.MWIPS * Ratio;
benchResult.Units = "MWIPS";
benchResult.Output = whetstoneResult.Output;
return benchResult;
}
public override void Warmup(double aspect)
{
}
}
}
| 26.95 | 108 | 0.656772 | [
"MIT"
] | Civil/EntityFX-Bench | src/dotnet/EntityFX.NetBenchamarks.Core/Whetstone/WhetstoneBenchmark.cs | 1,080 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace dotIRC.Ctcp
{
// Defines all message senders for the client.
partial class CtcpClient
{
/// <summary>
/// Sends an action message to the specified target.
/// </summary>
/// <param name="targets">A list of the targets of the message.</param>
/// <param name="text">The message text.</param>
protected void SendMessageAction(IList<IIrcMessageTarget> targets, string text)
{
WriteMessage(targets, "action", text);
OnActionSent(new CtcpMessageEventArgs(this.ircClient.LocalUser, targets, text));
}
/// <summary>
/// Sends a request for the local date/time to the specified target.
/// </summary>
/// <param name="targets">A list of the targets of the message.</param>
/// <param name="info">The information to send.</param>
/// <param name="isResponse"><see langword="true"/> if the message is a response; <see langword="false"/>,
/// otherwise.</param>
protected void SendMessageTime(IList<IIrcMessageTarget> targets, string info, bool isResponse)
{
WriteMessage(targets, "time", info, isResponse);
}
/// <summary>
/// Sends a request or response for information about the version of the client.
/// </summary>
/// <param name="targets">A list of the targets of the message.</param>
/// <param name="info">The information to send.</param>
/// <param name="isResponse"><see langword="true"/> if the message is a response; <see langword="false"/>,
/// otherwise.</param>
protected void SendMessageVersion(IList<IIrcMessageTarget> targets, string info, bool isResponse)
{
WriteMessage(targets, "version", info, isResponse);
}
/// <summary>
/// Sends a request for confirming that no error has occurred.
/// </summary>
/// <param name="targets">A list of the targets of the message.</param>
/// <param name="tag">A tag that can be used for tracking the response.</param>
/// <param name="isResponse"><see langword="true"/> if the message is a response; <see langword="false"/>,
/// otherwise.</param>
protected void SendMessageErrMsg(IList<IIrcMessageTarget> targets, string tag, bool isResponse)
{
WriteMessage(targets, "errmsg", tag, isResponse);
}
/// <summary>
/// Sends a ping request or response to the specified target.
/// </summary>
/// <param name="targets">A list of the targets of the message.</param>
/// <param name="info">The information to send.</param>
/// <param name="isResponse"><see langword="true"/> if the message is a response; <see langword="false"/>,
/// otherwise.</param>
protected void SendMessagePing(IList<IIrcMessageTarget> targets, string info, bool isResponse)
{
WriteMessage(targets, "ping", info, isResponse);
}
}
}
| 43.109589 | 114 | 0.614871 | [
"MIT"
] | JustOxlamon/TwoRatChat | dotIRC/Ctcp/CtcpClientMessageSending.cs | 3,149 | C# |
using LinkedList.Classes;
using System;
namespace LL_merge
{
public class Program
{
public static void Main(string[] args)
{
Node LL1Node1 = new Node("LL1Node1");
Node LL1Node2 = new Node("LL1Node2");
Node LL1Node3 = new Node("LL1Node3");
Node LL1Node4 = new Node("LL1Node4");
Node LL1Node5 = new Node("LL1Node5");
Node LL1Node6 = new Node("LL1Node6");
LL LL1 = new LL(LL1Node1);
LL1.Append(LL1Node2);
LL1.Append(LL1Node3);
LL1.Append(LL1Node4);
LL1.Append(LL1Node5);
LL1.Append(LL1Node6);
Node LL2Node1 = new Node("LL2Node1");
Node LL2Node2 = new Node("LL2Node2");
Node LL2Node3 = new Node("LL2Node3");
Node LL2Node4 = new Node("LL2Node4");
Node LL2Node5 = new Node("LL2Node5");
LL LL2 = new LL(LL2Node1);
LL2.Append(LL2Node2);
LL2.Append(LL2Node3);
LL2.Append(LL2Node4);
LL2.Append(LL2Node5);
LL1.Print();
Console.WriteLine("");
LL2.Print();
LLMerge(LL1, LL2);
Console.WriteLine("");
LL1.Print();
}
/// <summary>
/// Merges two linked lists
/// </summary>
/// <param name="LL1">A linked list</param>
/// <param name="LL2">A linked list</param>
/// <returns>Returns a merged linked list</returns>
public static LL LLMerge(LL LL1, LL LL2)
{
LL1.Current = LL1.Head;
LL2.Current = LL2.Head;
Node temp = LL2.Current.Next;
while (LL1.Current.Next.Next != null)
{
LL1.AddAfter(LL2.Head, LL1.Current);
LL2.Head = temp;
LL2.Current = LL2.Head;
temp = LL2.Current.Next;
LL1.Current = LL1.Current.Next.Next;
}
LL1.AddAfter(LL2.Head, LL1.Current);
LL2.Head = temp;
LL1.Append(LL2.Head);
LL2.Head = null;
return LL1;
}
}
}
| 28.088608 | 59 | 0.4831 | [
"MIT"
] | riedmank/Data-Structures-and-Algorithms | Challenges/LL_merge/LL_merge/Program.cs | 2,221 | C# |
// Copyright 2020 zmjack
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// See the LICENSE file in the project root for more information.
using Microsoft.Extensions.Caching.Memory;
using NStandard;
using System;
using System.Reflection;
namespace LinqSharp
{
public static class MethodUnit
{
private static readonly MemoryCache Cache = new(new MemoryCacheOptions());
public static MethodInfo StringConcat => Cache.GetOrCreate(nameof(StringConcat), entry => typeof(string).GetMethodViaQualifiedName("System.String Concat(System.String, System.String)"));
public static MethodInfo StringEquals => Cache.GetOrCreate(nameof(StringEquals), entry => typeof(string).GetMethodViaQualifiedName("Boolean Equals(System.String)"));
public static MethodInfo StringContains => Cache.GetOrCreate(nameof(StringContains), entry => typeof(string).GetMethodViaQualifiedName("Boolean Contains(System.String)"));
public static MethodInfo Int16Equals => Cache.GetOrCreate(nameof(Int16Equals), entry => typeof(short).GetMethodViaQualifiedName("Boolean Equals(System.Int16)"));
public static MethodInfo UInt16Equals => Cache.GetOrCreate(nameof(UInt16Equals), entry => typeof(ushort).GetMethodViaQualifiedName("Boolean Equals(System.UInt16)"));
public static MethodInfo Int32Equals => Cache.GetOrCreate(nameof(Int32Equals), entry => typeof(int).GetMethodViaQualifiedName("Boolean Equals(System.Int32)"));
public static MethodInfo UInt32Equals => Cache.GetOrCreate(nameof(UInt32Equals), entry => typeof(uint).GetMethodViaQualifiedName("Boolean Equals(System.UInt32)"));
public static MethodInfo Int64Equals => Cache.GetOrCreate(nameof(Int64Equals), entry => typeof(long).GetMethodViaQualifiedName("Boolean Equals(System.Int64)"));
public static MethodInfo UInt64Equals => Cache.GetOrCreate(nameof(UInt64Equals), entry => typeof(ulong).GetMethodViaQualifiedName("Boolean Equals(System.UInt64)"));
public static MethodInfo SingleEquals => Cache.GetOrCreate(nameof(SingleEquals), entry => typeof(float).GetMethodViaQualifiedName("Boolean Equals(System.Single)"));
public static MethodInfo DoubleEquals => Cache.GetOrCreate(nameof(DoubleEquals), entry => typeof(double).GetMethodViaQualifiedName("Boolean Equals(System.Double)"));
public static MethodInfo DateTimeEquals => Cache.GetOrCreate(nameof(DateTimeEquals), entry => typeof(DateTime).GetMethodViaQualifiedName("Boolean Equals(System.DateTime)"));
public static MethodInfo GuidEquals => Cache.GetOrCreate(nameof(GuidEquals), entry => typeof(DateTime).GetMethodViaQualifiedName("Boolean Equals(System.Guid)"));
public static MethodInfo NullableInt16Equals => Cache.GetOrCreate(nameof(NullableInt16Equals), entry => typeof(short?).GetMethodViaQualifiedName("Boolean Equals(System.Object)"));
public static MethodInfo NullableUInt16Equals => Cache.GetOrCreate(nameof(NullableUInt16Equals), entry => typeof(ushort?).GetMethodViaQualifiedName("Boolean Equals(System.Object)"));
public static MethodInfo NullableInt32Equals => Cache.GetOrCreate(nameof(NullableInt32Equals), entry => typeof(int?).GetMethodViaQualifiedName("Boolean Equals(System.Object)"));
public static MethodInfo NullableUInt32Equals => Cache.GetOrCreate(nameof(NullableUInt32Equals), entry => typeof(uint?).GetMethodViaQualifiedName("Boolean Equals(System.Object)"));
public static MethodInfo NullableInt64Equals => Cache.GetOrCreate(nameof(NullableInt64Equals), entry => typeof(long?).GetMethodViaQualifiedName("Boolean Equals(System.Object)"));
public static MethodInfo NullableUInt64Equals => Cache.GetOrCreate(nameof(NullableUInt64Equals), entry => typeof(ulong?).GetMethodViaQualifiedName("Boolean Equals(System.Object)"));
public static MethodInfo NullableSingleEquals => Cache.GetOrCreate(nameof(NullableSingleEquals), entry => typeof(float?).GetMethodViaQualifiedName("Boolean Equals(System.Object)"));
public static MethodInfo NullableDoubleEquals => Cache.GetOrCreate(nameof(NullableDoubleEquals), entry => typeof(double?).GetMethodViaQualifiedName("Boolean Equals(System.Object)"));
public static MethodInfo NullableDateTimeEquals => Cache.GetOrCreate(nameof(NullableDateTimeEquals), entry => typeof(DateTime?).GetMethodViaQualifiedName("Boolean Equals(System.Object)"));
public static MethodInfo NullableGuidEquals => Cache.GetOrCreate(nameof(NullableGuidEquals), entry => typeof(DateTime?).GetMethodViaQualifiedName("Boolean Equals(System.Object)"));
}
}
| 103.511111 | 196 | 0.777158 | [
"Apache-2.0"
] | zmjack/NLinq | LinqSharp/~WhereHelper/MethodUnit.cs | 4,660 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DlibDotNet.Tests
{
public abstract class TestBase
{
#region Fields
private readonly Random _Random;
#endregion
#region Constructors
protected TestBase()
{
this._Random = new Random();
}
#endregion
#region Properties
public bool CanGuiDebug
{
get
{
#if DEBUG
return true;
#else
return false;
#endif
}
}
#endregion
#region Methods
public void DisposeAndCheckDisposedState(DlibObject obj)
{
obj.Dispose();
Assert.IsTrue(obj.IsDisposed);
Assert.IsTrue(obj.NativePtr == IntPtr.Zero);
}
public void DisposeAndCheckDisposedStates(IEnumerable<DlibObject> objs)
{
foreach (var obj in objs)
this.DisposeAndCheckDisposedState(obj);
}
public static void DoTest<T>(Func<bool, T> outputImageFunc, bool expect, Action<T> successAction, Action finallyAction, Action failAction, Action exceptionAction)
where T : class
{
try
{
try
{
var outputImage = outputImageFunc(expect);
if (!expect)
{
failAction();
}
else
{
successAction(outputImage);
}
}
catch (ArgumentException)
{
if (!expect)
Console.WriteLine("OK");
else
throw;
}
catch (NotSupportedException)
{
if (!expect)
Console.WriteLine("OK");
else
throw;
}
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
exceptionAction();
throw;
}
finally
{
finallyAction();
}
}
public FileInfo GetDataFile(string filename)
{
return new FileInfo(Path.Combine("data", filename));
}
public IEnumerable<FileInfo> GetDataFiles(string directoryName)
{
var dir = new DirectoryInfo(Path.Combine("data", directoryName));
return dir.GetFiles();
}
public string GetOutDir(string function)
{
var path = Path.Combine("out", function);
Directory.CreateDirectory(path);
return path;
}
public string GetOutDir(params string[] function)
{
var path = Path.Combine("out", Path.Combine(function));
Directory.CreateDirectory(path);
return path;
}
#region Random
public byte NextByteRandom()
{
return (byte)this._Random.Next(0, 255);
}
public sbyte NextSByteRandom()
{
return (sbyte)this._Random.Next(sbyte.MinValue, sbyte.MaxValue);
}
public ushort NextUInt16Random()
{
return (ushort)this._Random.Next(ushort.MinValue, ushort.MaxValue);
}
public short NextInt16Random()
{
return (short)this._Random.Next(short.MinValue, short.MaxValue);
}
public int NextInt32Random()
{
return this._Random.Next(int.MinValue, int.MaxValue);
}
public uint NextUInt32Random()
{
return (uint)this._Random.Next(0, int.MaxValue);
}
public int NextRandom()
{
return this._Random.Next();
}
public int NextRandom(int maxValue)
{
return this._Random.Next(maxValue);
}
public int NextRandom(int minValue, int maxValue)
{
return this._Random.Next(minValue, maxValue);
}
public double NextDoubleRandom()
{
return this._Random.NextDouble();
}
public float NextFloatRandom()
{
return (float)this._Random.NextDouble();
}
public RgbAlphaPixel NextRgbAlphaPixelRandom()
{
return this.NextRgbAlphaPixelRandom(0, 255);
}
public RgbAlphaPixel NextRgbAlphaPixelRandom(int minValue, int maxValue)
{
return new RgbAlphaPixel
{
Blue = (byte)this._Random.Next(minValue, maxValue),
Green = (byte)this._Random.Next(minValue, maxValue),
Red = (byte)this._Random.Next(minValue, maxValue),
Alpha = (byte)this._Random.Next(minValue, maxValue)
};
}
public RgbPixel NextRgbPixelRandom()
{
return this.NextRgbPixelRandom(0, 255);
}
public RgbPixel NextRgbPixelRandom(int minValue, int maxValue)
{
return new RgbPixel
{
Blue = (byte)this._Random.Next(minValue, maxValue),
Green = (byte)this._Random.Next(minValue, maxValue),
Red = (byte)this._Random.Next(minValue, maxValue)
};
}
public HsiPixel NextHsiPixelRandom()
{
return this.NextHsiPixelRandom(0, 255);
}
public HsiPixel NextHsiPixelRandom(int minValue, int maxValue)
{
return new HsiPixel()
{
H = (byte)this._Random.Next(minValue, maxValue),
S = (byte)this._Random.Next(minValue, maxValue),
I = (byte)this._Random.Next(minValue, maxValue)
};
}
#region Array2D
public Array2D<Byte> CreateRandomArray2DByte(int rows, int columns)
{
var array = new Array2D<byte>(rows, columns);
for (var r = 0; r < rows; r++)
for (var c = 0; c < columns; c++)
array[r][c] = this.NextByteRandom();
return array;
}
public Array2D<UInt16> CreateRandomArray2DUInt16(int rows, int columns)
{
var array = new Array2D<ushort>(rows, columns);
for (var r = 0; r < rows; r++)
for (var c = 0; c < columns; c++)
array[r][c] = this.NextUInt16Random();
return array;
}
public Array2D<UInt32> CreateRandomArray2DUInt32(int rows, int columns)
{
var array = new Array2D<uint>(rows, columns);
for (var r = 0; r < rows; r++)
for (var c = 0; c < columns; c++)
array[r][c] = this.NextUInt32Random();
return array;
}
public Array2D<SByte> CreateRandomArray2DSByte(int rows, int columns)
{
var array = new Array2D<sbyte>(rows, columns);
for (var r = 0; r < rows; r++)
for (var c = 0; c < columns; c++)
array[r][c] = this.NextSByteRandom();
return array;
}
public Array2D<Int16> CreateRandomArray2DInt16(int rows, int columns)
{
var array = new Array2D<short>(rows, columns);
for (var r = 0; r < rows; r++)
for (var c = 0; c < columns; c++)
array[r][c] = this.NextInt16Random();
return array;
}
public Array2D<Int32> CreateRandomArray2DInt32(int rows, int columns)
{
var array = new Array2D<int>(rows, columns);
for (var r = 0; r < rows; r++)
for (var c = 0; c < columns; c++)
array[r][c] = this.NextInt32Random();
return array;
}
public Array2D<float> CreateRandomArray2DFloat(int rows, int columns)
{
var array = new Array2D<float>(rows, columns);
for (var r = 0; r < rows; r++)
for (var c = 0; c < columns; c++)
array[r][c] = this.NextFloatRandom();
return array;
}
public Array2D<Double> CreateRandomArray2DDouble(int rows, int columns)
{
var array = new Array2D<double>(rows, columns);
for (var r = 0; r < rows; r++)
for (var c = 0; c < columns; c++)
array[r][c] = this.NextDoubleRandom();
return array;
}
public Array2D<RgbPixel> CreateRandomArray2DRgbPixel(int rows, int columns)
{
var array = new Array2D<RgbPixel>(rows, columns);
for (var r = 0; r < rows; r++)
for (var c = 0; c < columns; c++)
array[r][c] = this.NextRgbPixelRandom();
return array;
}
public Array2D<RgbAlphaPixel> CreateRandomArray2DRgbAlphaPixel(int rows, int columns)
{
var array = new Array2D<RgbAlphaPixel>(rows, columns);
for (var r = 0; r < rows; r++)
for (var c = 0; c < columns; c++)
array[r][c] = this.NextRgbAlphaPixelRandom();
return array;
}
public Array2D<HsiPixel> CreateRandomArray2DHsiPixel(int rows, int columns)
{
var array = new Array2D<HsiPixel>(rows, columns);
for (var r = 0; r < rows; r++)
for (var c = 0; c < columns; c++)
array[r][c] = this.NextHsiPixelRandom();
return array;
}
#endregion
#region Matrix
public Matrix<Byte> CreateRandomMatrixByte(int rows, int columns)
{
var array = new Matrix<byte>(rows, columns);
for (var r = 0; r < rows; r++)
for (var c = 0; c < columns; c++)
array[r, c] = this.NextByteRandom();
return array;
}
public Matrix<UInt16> CreateRandomMatrixUInt16(int rows, int columns)
{
var array = new Matrix<ushort>(rows, columns);
for (var r = 0; r < rows; r++)
for (var c = 0; c < columns; c++)
array[r, c] = this.NextUInt16Random();
return array;
}
public Matrix<UInt32> CreateRandomMatrixUInt32(int rows, int columns)
{
var array = new Matrix<uint>(rows, columns);
for (var r = 0; r < rows; r++)
for (var c = 0; c < columns; c++)
array[r, c] = this.NextUInt32Random();
return array;
}
public Matrix<SByte> CreateRandomMatrixSByte(int rows, int columns)
{
var array = new Matrix<sbyte>(rows, columns);
for (var r = 0; r < rows; r++)
for (var c = 0; c < columns; c++)
array[r, c] = this.NextSByteRandom();
return array;
}
public Matrix<Int16> CreateRandomMatrixInt16(int rows, int columns)
{
var array = new Matrix<short>(rows, columns);
for (var r = 0; r < rows; r++)
for (var c = 0; c < columns; c++)
array[r, c] = this.NextInt16Random();
return array;
}
public Matrix<Int32> CreateRandomMatrixInt32(int rows, int columns)
{
var array = new Matrix<int>(rows, columns);
for (var r = 0; r < rows; r++)
for (var c = 0; c < columns; c++)
array[r, c] = this.NextInt32Random();
return array;
}
public Matrix<float> CreateRandomMatrixFloat(int rows, int columns)
{
var array = new Matrix<float>(rows, columns);
for (var r = 0; r < rows; r++)
for (var c = 0; c < columns; c++)
array[r, c] = this.NextFloatRandom();
return array;
}
public Matrix<Double> CreateRandomMatrixDouble(int rows, int columns)
{
var array = new Matrix<double>(rows, columns);
for (var r = 0; r < rows; r++)
for (var c = 0; c < columns; c++)
array[r, c] = this.NextDoubleRandom();
return array;
}
public Matrix<RgbPixel> CreateRandomMatrixRgbPixel(int rows, int columns)
{
var array = new Matrix<RgbPixel>(rows, columns);
for (var r = 0; r < rows; r++)
for (var c = 0; c < columns; c++)
array[r, c] = this.NextRgbPixelRandom();
return array;
}
public Matrix<RgbAlphaPixel> CreateRandomMatrixRgbAlphaPixel(int rows, int columns)
{
var array = new Matrix<RgbAlphaPixel>(rows, columns);
for (var r = 0; r < rows; r++)
for (var c = 0; c < columns; c++)
array[r, c] = this.NextRgbAlphaPixelRandom();
return array;
}
public Matrix<HsiPixel> CreateRandomMatrixHsiPixel(int rows, int columns)
{
var array = new Matrix<HsiPixel>(rows, columns);
for (var r = 0; r < rows; r++)
for (var c = 0; c < columns; c++)
array[r, c] = this.NextHsiPixelRandom();
return array;
}
#endregion
#endregion
#endregion
}
}
| 29.628755 | 170 | 0.484175 | [
"MIT"
] | dongshengfengniaowu/DlibDotNet | test/DlibDotNet.Tests/TestBase.cs | 13,809 | C# |
namespace HareDu.Model
{
using System.Collections.Generic;
public interface PolicyInfo
{
string VirtualHost { get; }
string Name { get; }
string Pattern { get; }
string AppliedTo { get; }
IDictionary<string, string> Definition { get; }
int Priority { get; }
}
} | 18.736842 | 55 | 0.536517 | [
"Apache-2.0"
] | ahives/HareDu2 | src/HareDu/Model/PolicyInfo.cs | 358 | C# |
namespace Stump.DofusProtocol.Messages
{
using System;
using System.Linq;
using System.Text;
using Stump.DofusProtocol.Types;
using Stump.Core.IO;
[Serializable]
public class NpcDialogCreationMessage : Message
{
public const uint Id = 5618;
public override uint MessageId
{
get { return Id; }
}
public double MapId { get; set; }
public int NpcId { get; set; }
public NpcDialogCreationMessage(double mapId, int npcId)
{
this.MapId = mapId;
this.NpcId = npcId;
}
public NpcDialogCreationMessage() { }
public override void Serialize(IDataWriter writer)
{
writer.WriteDouble(MapId);
writer.WriteInt(NpcId);
}
public override void Deserialize(IDataReader reader)
{
MapId = reader.ReadDouble();
NpcId = reader.ReadInt();
}
}
}
| 23.238095 | 64 | 0.566598 | [
"Apache-2.0"
] | Daymortel/Stump | src/Stump.DofusProtocol/Messages/Messages/Game/Context/Roleplay/Npc/NpcDialogCreationMessage.cs | 978 | C# |
using osu.Framework.Graphics.Textures;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Input.Events;
using osu.Framework.Localisation;
using osu.Framework.Platform;
using osu.Game.Graphics.Sprites;
using osu.Game.Overlays;
using osu.Game.Rulesets.RurusettoAddon.UI.Users;
using osuTK.Input;
#nullable disable
namespace osu.Game.Rulesets.RurusettoAddon.UI.Wiki;
[Cached]
public class WikiTab : OverlayTab {
FillFlowContainer content;
APIRuleset ruleset;
Sprite cover;
FillFlowContainer info;
Container subpageContent;
MarkdownPage mainPage;
protected FillFlowContainer Tags;
protected FillFlowContainer Status;
SubpageSectionTabControl subpageTabControl;
FillFlowContainer buttons;
public WikiTab ( APIRuleset ruleset ) {
this.ruleset = ruleset;
AddInternal( content = new FillFlowContainer {
Direction = FillDirection.Full,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Padding = new MarginPadding { Horizontal = 32, Top = 8 }
} );
}
OverlayColourProvider colourProvider;
Texture defaultCover;
[BackgroundDependencyLoader]
private void load ( OverlayColourProvider colourProvider, GameHost host, TextureStore textures, RurusettoAddonRuleset ruleset ) {
this.colourProvider = colourProvider;
defaultCover = ruleset.GetTexture( host, textures, TextureNames.DefaultCover );
}
SubpageListingEntry main;
SubpageListingEntry changelog;
SubpageListingEntry recommended;
Dictionary<SubpageListingEntry, WikiPage> subpageDrawables = new();
[Resolved]
private LocalisationManager localisation { get; set; }
ILocalisedBindableString contentBindable;
protected override void LoadContent () {
AddInternal( new Container {
RelativeSizeAxes = Axes.X,
Height = 220,
Children = new Drawable[] {
cover = new Sprite {
RelativeSizeAxes = Axes.Both,
FillMode = FillMode.Fill,
Origin = Anchor.Centre,
Anchor = Anchor.Centre
},
new Box {
Colour = new ColourInfo {
HasSingleColour = false,
BottomLeft = colourProvider.Background5,
BottomRight = colourProvider.Background5,
TopLeft = colourProvider.Background5.Opacity( 0.5f ),
TopRight = colourProvider.Background5.Opacity( 0.5f )
},
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.BottomCentre,
Origin = Anchor.BottomCentre
}
},
Masking = true,
Depth = 1,
MaskingSmoothness = 0
} );
content.Add( new Container {
Name = "Padding",
RelativeSizeAxes = Axes.X,
Height = 160,
Children = new Drawable[] {
Tags = new FillFlowContainer {
Direction = FillDirection.Horizontal,
AutoSizeAxes = Axes.Both,
Spacing = new Vector2( 6, 0 ),
Margin = new MarginPadding { Top = 16 }
},
Status = new FillFlowContainer {
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Direction = FillDirection.Vertical,
AutoSizeAxes = Axes.Both,
Spacing = new Vector2( 0, 6 ),
Margin = new MarginPadding { Top = 16 }
}
}
} );
content.Add( new Container {
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Children = new Drawable[] {
new FillFlowContainer {
Direction = FillDirection.Horizontal,
RelativeSizeAxes = Axes.X,
Height = 170f * 14 / 20,
Children = new Drawable[] {
new RulesetLogo( ruleset ) {
Height = 170f * 14 / 20,
Width = 170f * 14 / 20,
Margin = new MarginPadding { Right = 16 },
UseDarkerBackground = true
},
new DrawableRurusettoUser( Users.GetUser( ruleset.Owner ), ruleset.IsVerified ) {
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
Height = 64f * 14 / 20,
Margin = new MarginPadding { Bottom = 4 },
UseDarkerBackground = true
}
},
Margin = new MarginPadding { Bottom = 20 }
},
buttons = new FillFlowContainer {
Y = -28,
Spacing = new Vector2( 8, 0 ),
AutoSizeAxes = Axes.Both,
Origin = Anchor.BottomRight,
Anchor = Anchor.BottomRight,
Children = new Drawable[] {
new RulesetDownloadButton( ruleset ) {
Height = 40f * 14 / 20,
Width = 200f * 14 / 20,
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreRight,
UseDarkerBackground = true
}
}
}
}
} );
content.Add( new Container {
Height = 28,
RelativeSizeAxes = Axes.X,
Child = new Container {
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Horizontal = 6 },
Y = -6,
Child = subpageTabControl = new() {
RelativeSizeAxes = Axes.X
}
},
Margin = new MarginPadding { Bottom = 12 }
} );
content.Add( info = new FillFlowContainer {
Padding = new MarginPadding { Horizontal = -32 },
Direction = FillDirection.Vertical,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y
} );
content.Add( subpageContent = new Container {
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Margin = new MarginPadding { Top = 16 }
} );
subpageTabControl.Current.BindValueChanged( _ => {
loadCurrentPage();
} );
main = new() { Title = Localisation.Strings.MainPage };
mainPage = new MarkdownPage( ruleset );
loadSubpages();
bool isCoverLoaded = false;
cover.Texture = defaultCover;
API.RequestImage( StaticAPIResource.DefaultCover, texture => {
if ( !isCoverLoaded ) {
cover.Texture = texture;
}
} );
ruleset.RequestDarkCover( texture => {
isCoverLoaded = true;
cover.Texture = texture;
} );
loadHeader();
}
void loadSubpages () {
Overlay.StartLoading( this );
subpageTabControl.Current.Value = null;
subpageTabControl.Clear();
subpageDrawables.Clear();
subpageDrawables.Add( main, mainPage );
changelog = null;
void addDefaultSubpages () {
subpageTabControl.AddItem( main );
subpageTabControl.PinItem( main );
if ( ruleset.ListingEntry?.Status?.Changelog is string log && !string.IsNullOrWhiteSpace( log ) ) {
changelog = new() { Title = Localisation.Strings.ChangelogPage };
subpageTabControl.AddItem( changelog );
subpageTabControl.PinItem( changelog );
subpageDrawables.Add( changelog, new MarkdownPage( ruleset ) { Text = log } );
}
ruleset.RequestRecommendations( RurusettoAPI.RecommendationSource.All, r => {
if ( r.Count == 0 )
return;
recommended = new() { Title = Localisation.Strings.RecommendedBeatmapsPage };
subpageTabControl.AddItem( recommended );
subpageTabControl.PinItem( recommended );
} );
}
ruleset.RequestSubpages( subpages => {
addDefaultSubpages();
foreach ( var i in subpages ) {
subpageTabControl.AddItem( i );
}
subpageTabControl.Current.Value = main;
Overlay.FinishLoadiong( this );
}, failure: e => {
addDefaultSubpages();
info.Add( new RequestFailedDrawable {
ContentText = Localisation.Strings.SubpagesFetchError,
ButtonClicked = RefreshSubpages
} );
subpageTabControl.Current.Value = main;
Overlay.FinishLoadiong( this );
} );
}
public void RefreshSubpages () {
info.Clear();
ruleset.FlushSubpageListing();
loadSubpages();
}
void loadCurrentPage () {
var page = subpageTabControl.Current.Value;
subpageContent.Clear( disposeChildren: false );
if ( page is null )
return;
if ( page == main ) {
loadMainPage();
}
if ( !subpageDrawables.TryGetValue( page, out var subpage ) ) {
if ( page == recommended ) {
subpageDrawables.Add( recommended, subpage = new RecommendedBeatmapsPage( ruleset ) );
}
else {
subpageDrawables.Add( page, subpage = new WikiSubpage( ruleset, page.Slug ) );
}
}
subpageContent.Add( subpage );
}
public void RefreshCurrentPage () {
var page = subpageTabControl.Current.Value;
if ( page is null )
return;
if ( !subpageDrawables[page].Refresh() ) {
subpageDrawables.Remove( page );
loadCurrentPage();
}
}
void loadMainPage () {
Overlay.StartLoading( this );
ruleset.RequestDetail( detail => {
contentBindable?.UnbindAll();
contentBindable = localisation.GetLocalisedBindableString( detail.Content );
contentBindable.BindValueChanged( v => {
mainPage.Text = v.NewValue;
}, true );
Overlay.FinishLoadiong( this );
}, failure: e => {
// TODO RequestFailedDrawable
API.LogFailure( $"Could not retrieve detail for {ruleset}", e );
Overlay.FinishLoadiong( this );
} );
}
void loadHeader () {
Overlay.StartLoading( this );
ruleset.RequestDetail( detail => {
Tags.Clear();
Status.Clear();
Tags.AddRange( ruleset.GenerateTags( detail, large: true, includePlayability: false ) );
if ( ruleset.ListingEntry?.Status?.IsPlayable == true ) {
Status.Add( DrawableTag.CreatePlayable( large: true ).With( d => {
d.Anchor = Anchor.TopRight;
d.Origin = Anchor.TopRight;
} ) );
}
else if ( ruleset.ListingEntry?.Status?.IsBorked == true ) {
Status.Add( DrawableTag.CreateBorked( large: true ).With( d => {
d.Anchor = Anchor.TopRight;
d.Origin = Anchor.TopRight;
} ) );
}
Status.Add( new OsuSpriteText {
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Font = OsuFont.GetFont( Typeface.Inter, size: 14 ),
Text = string.IsNullOrWhiteSpace( ruleset.ListingEntry?.Status?.LatestVersion ) ? Localisation.Strings.UnknownVersion : ruleset.ListingEntry.Status.LatestVersion
} );
buttons.Add( new HomeButton( detail ) {
Height = 40f * 14 / 20,
Width = 120f * 14 / 20,
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreRight
} );
buttons.Add( new IssueButton( detail ) {
Height = 40f * 14 / 20,
Width = 40f * 14 / 20,
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreRight
} );
Overlay.FinishLoadiong( this );
}, failure: e => {
API.LogFailure( $"Could not retrieve detail for {ruleset}", e );
Overlay.FinishLoadiong( this );
} );
}
protected override bool OnKeyDown ( KeyDownEvent e ) {
if ( e.Key is Key.F5 ) { // NOTE o!f doenst seem to have a 'refresh' action
if ( e.ShiftPressed )
return Refresh();
else {
RefreshCurrentPage();
return true;
}
}
return false;
}
public override bool Refresh () {
RefreshSubpages();
return true;
}
// https://github.com/ppy/osu/blob/2fd4647e6eeb7c08861d8e526af97aff5c0e39f6/osu.Game/Overlays/UserProfileOverlay.cs#L153
private class SubpageSectionTabControl : OverlayTabControl<SubpageListingEntry> {
private const float bar_height = 2;
public SubpageSectionTabControl () {
TabContainer.RelativeSizeAxes &= ~Axes.X;
TabContainer.AutoSizeAxes |= Axes.X;
TabContainer.Anchor |= Anchor.x1;
TabContainer.Origin |= Anchor.x1;
Height = 36 + bar_height;
BarHeight = bar_height;
}
protected override TabItem<SubpageListingEntry> CreateTabItem ( SubpageListingEntry value ) => new SubpageSectionTabItem( value ) {
AccentColour = AccentColour,
};
[BackgroundDependencyLoader]
private void load ( OverlayColourProvider colourProvider ) {
AccentColour = colourProvider.Highlight1;
}
protected override bool OnClick ( ClickEvent e ) => true;
protected override bool OnHover ( HoverEvent e ) => true;
private class SubpageSectionTabItem : OverlayTabItem {
public SubpageSectionTabItem ( SubpageListingEntry value ) : base( value ) {
Text.Text = value.Title;
Text.Font = Text.Font.With( size: 16 );
Text.Margin = new MarginPadding { Bottom = 10 + bar_height };
Bar.ExpandedSize = 10;
Bar.Margin = new MarginPadding { Bottom = bar_height };
}
}
}
} | 27.73494 | 165 | 0.677585 | [
"MIT"
] | Flutterish/rurusetto-addon | osu.Game.Rulesets.RurusettoAddon/UI/Wiki/WikiTab.cs | 11,512 | C# |
using k8s;
using k8s.Models;
namespace KubeOps.Operator.Entities;
/// <summary>
/// Defines a custom kubernetes entity which can be used in finalizers and controllers.
/// </summary>
public abstract class CustomKubernetesEntity : KubernetesObject, IKubernetesObject<V1ObjectMeta>
{
/// <summary>
/// The metadata of the kubernetes object.
/// </summary>
public V1ObjectMeta Metadata { get; set; } = new();
}
| 26.6875 | 96 | 0.714286 | [
"Apache-2.0"
] | hypnopotamus/dotnet-operator-sdk | src/KubeOps/Operator/Entities/CustomKubernetesEntity.cs | 429 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.Azure.IIoT.OpcUa.Registry.Models {
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Endpoint model extensions
/// </summary>
public static class EndpointModelEx {
/// <summary>
/// Equality comparison
/// </summary>
/// <param name="model"></param>
/// <param name="that"></param>
/// <returns></returns>
public static bool IsSameAs(this EndpointModel model, EndpointModel that) {
if (model == that) {
return true;
}
if (model == null || that == null) {
return false;
}
if (!that.HasSameSecurityProperties(model)) {
return false;
}
if (!that.GetAllUrls().SequenceEqualsSafe(model.GetAllUrls())) {
return false;
}
return true;
}
/// <summary>
/// Equality comparison
/// </summary>
/// <param name="model"></param>
/// <param name="that"></param>
/// <returns></returns>
public static bool HasSameSecurityProperties(this EndpointModel model, EndpointModel that) {
if (model == that) {
return true;
}
if (model == null || that == null) {
return false;
}
if (!that.User.IsSameAs(model.User)) {
return false;
}
if (!that.Certificate.SequenceEqualsSafe(model.Certificate)) {
return false;
}
if (that.SecurityPolicy!= model.SecurityPolicy) {
return false;
}
if ((that.SecurityMode ?? SecurityMode.Best) !=
(model.SecurityMode ?? SecurityMode.Best)) {
return false;
}
return true;
}
/// <summary>
/// Create unique hash
/// </summary>
/// <param name="endpoint"></param>
/// <returns></returns>
public static int CreateConsistentHash(this EndpointModel endpoint) {
var hashCode = -1971667340;
hashCode = (hashCode * -1521134295) +
endpoint.GetAllUrls().SequenceGetHashSafe();
hashCode = (hashCode * -1521134295) +
endpoint.Certificate.SequenceGetHashSafe();
hashCode = (hashCode * -1521134295) +
EqualityComparer<string>.Default.GetHashCode(endpoint.SecurityPolicy);
hashCode = (hashCode * -1521134295) +
EqualityComparer<SecurityMode?>.Default.GetHashCode(
endpoint.SecurityMode ?? SecurityMode.Best);
hashCode = (hashCode * -1521134295) +
EqualityComparer<CredentialType?>.Default.GetHashCode(
endpoint.User?.Type ?? CredentialType.None);
hashCode = (hashCode * -1521134295) +
JToken.EqualityComparer.GetHashCode(endpoint.User?.Value);
return hashCode;
}
/// <summary>
/// Get all urls
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static IEnumerable<string> GetAllUrls(this EndpointModel model) {
if (model == null) {
return null;
}
var all = model.Url.YieldReturn();
if (model.AlternativeUrls != null) {
all = all.Concat(model.AlternativeUrls);
}
return all;
}
/// <summary>
/// Create Union with endpoint
/// </summary>
/// <param name="endpoint"></param>
/// <param name="model"></param>
public static void UnionWith(this EndpointModel model,
EndpointModel endpoint) {
if (endpoint == null) {
return;
}
if (model.AlternativeUrls == null) {
model.AlternativeUrls = endpoint.AlternativeUrls;
}
else {
model.AlternativeUrls = model.AlternativeUrls.MergeWith(
endpoint.AlternativeUrls);
}
if (model.Url == null) {
model.Url = endpoint.Url;
}
else {
model.AlternativeUrls.Add(endpoint.Url);
}
model.AlternativeUrls.Remove(model.Url);
}
/// <summary>
/// Deep clone
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static EndpointModel Clone(this EndpointModel model) {
if (model == null) {
return null;
}
return new EndpointModel {
Certificate = model.Certificate?.ToArray(),
AlternativeUrls = model.AlternativeUrls.ToHashSetSafe(),
SecurityMode = model.SecurityMode,
SecurityPolicy = model.SecurityPolicy,
User = model.User.Clone(),
Url = model.Url
};
}
}
}
| 35.415584 | 100 | 0.496883 | [
"MIT"
] | TheWaywardHayward/Industrial-IoT | components/opc-ua/src/Microsoft.Azure.IIoT.OpcUa/src/Registry/Extensions/EndpointModelEx.cs | 5,454 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using EStore.Services;
using EStore.Models.Admin.ManageCategoriesViewModels;
using EStore.Models;
namespace EStore.Controllers.Admin
{
public class ManageCategoriesController : AdminBaseController
{
private readonly ICategoryService _categoryService;
public ManageCategoriesController(ICategoryService categoryService)
{
this._categoryService = categoryService;
}
public IActionResult Index()
{
var categories = this._categoryService.GetAll();
var model = new ListCategoriesViewModel()
{
Categories = categories.Data
};
return View(model);
}
[HttpGet]
public IActionResult Edit(int id)
{
var categoryResult = this._categoryService.Find(id);
if(categoryResult.Status == Models.ServiceModels.ServiceResultStatus.Error)
{
return NotFound();
}
var category = categoryResult.Data;
var model = new EditCategoryViewModel()
{
Id = category.Id,
Name = category.Name
};
return this.View(model);
}
[HttpPost]
public IActionResult Edit(EditCategoryViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var categoryResult = this._categoryService.Find(model.Id);
if (categoryResult.Status == Models.ServiceModels.ServiceResultStatus.Error)
{
ModelState.AddModelError("Error", "You tried editing a category that does not exist");
return View(model);
}
var category = categoryResult.Data;
category.Name = model.Name;
var result = this._categoryService.Update(category);
if(result.Status == Models.ServiceModels.ServiceResultStatus.Error)
{
ModelState.AddModelError("Error", "Could not edit category");
}
return View(model);
}
[HttpGet]
public IActionResult Create()
{
var model = new EditCategoryViewModel();
return View(model);
}
[HttpPost]
public IActionResult Create(EditCategoryViewModel model)
{
if (!ModelState.IsValid)
{
return View();
}
var category = new Category()
{
Name = model.Name
};
var result = this._categoryService.Create(category);
if (!result.Succeeded)
{
ModelState.AddModelError("Error", result.Message);
return View();
}
return RedirectToAction("Index", "ManageCategories");
}
[HttpGet]
public IActionResult Delete(int id)
{
var result = this._categoryService.Remove(id);
if (result.Succeeded)
{
}
return RedirectToAction("Index", "ManageCategories");
}
}
} | 25.860465 | 102 | 0.543765 | [
"MIT"
] | thehink/E-Store | EStore/Controllers/Admin/ManageCategoriesController.cs | 3,336 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Agencija.Models;
namespace Agencija.Controllers
{
[ApiController]
[Route("[controller]")]
public class LukaController : ControllerBase
{
public AgencijaContext Context { get; set; }
public LukaController(AgencijaContext context)
{
Context = context;
}
[Route("Dodaj")]
[HttpPost]
public async Task<ActionResult> DodajLuku([FromBody] Luka luka)
{
try
{
var uBazi = Context.Luke.Where(p => p.Oznaka == luka.Oznaka);
if (uBazi.Count() > 0)
return BadRequest("Luka koju pokušavate da kreirate je već postoji!");
Context.Luke.Add(luka);
await Context.SaveChangesAsync();
return Ok($"Luka {luka.Oznaka} je uspešno dodata!");
}
catch (Exception e)
{
return BadRequest("Došlo je do greške: " + e.Message);
}
}
[Route("Izmeni")]
[HttpPut]
public async Task<ActionResult> IzmeniLuku([FromBody] Luka luka)
{
try
{
var lukaUBazi = await Context.Luke.Where(p => p.Oznaka == luka.Oznaka)
.FirstOrDefaultAsync();
if (lukaUBazi == null)
return BadRequest("Luka koju pokušavate da izmenite ne postoji!");
lukaUBazi.Naziv = luka.Naziv;
lukaUBazi.VisinaTakse = luka.VisinaTakse;
lukaUBazi.Grad = luka.Grad;
lukaUBazi.Drzava = luka.Drzava;
await Context.SaveChangesAsync();
return Ok($"Luka {lukaUBazi.Oznaka} je uspešno izmenjena!");
}
catch (Exception e)
{
return BadRequest("Došlo je do greške: " + e.Message);
}
}
[Route("Preuzmi/{id}")]
[HttpGet]
public async Task<ActionResult> PreuzmiKrstarenje(int id)
{
try
{
Luka l = await Context.Luke.FindAsync(id);
if (l == null)
return BadRequest("Tražena luka ne postoji!");
return Ok(l);
}
catch (Exception e)
{
return BadRequest("Došlo je do greške: " + e.Message);
}
}
[Route("PreuzmiListu")]
[HttpGet]
public async Task<ActionResult> PreuzmiListu()
{
try
{
return Ok
(
await Context.Luke.Select(p =>
new
{
ID = p.ID,
Naziv = $"[ {p.Oznaka} ] {p.Naziv} - {p.Grad}"
}).ToListAsync()
);
}
catch (Exception e)
{
return BadRequest("Došlo je do greške: " + e.Message);
}
}
[Route("Obrisi/{oznaka}")]
[HttpDelete]
public async Task<ActionResult> ObrisiLuku(string oznaka)
{
try
{
var luka = await Context.Luke.Where(p => p.Oznaka == oznaka).FirstOrDefaultAsync();
if (luka == null)
return BadRequest("Luka koju želite da obrišete ne postoji!");
Context.Luke.Remove(luka);
await Context.SaveChangesAsync();
return Ok($"Luka {oznaka} je uspešno obrisana!");
}
catch (Exception e)
{
return BadRequest("Došlo je do greške: " + e.Message);
}
}
}
}
| 31.117188 | 99 | 0.456942 | [
"MIT"
] | bazlooka/elfak-web-projekat | backend/Controllers/LukaController.cs | 4,002 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Entities;
using Services;
namespace App
{
public partial class AddExpenseForm : Form
{
public AddExpenseForm()
{
InitializeComponent();
}
private void AddExpenseForm_Load(object sender, EventArgs e)
{
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "dd-MMM-yyyy";
}
private void button1_Click(object sender, EventArgs e)
{
if (t_ExpName.Text == string.Empty)
{
MessageBox.Show("Please Enter Expense name");
}
else if (t_ExpAmount.Text == string.Empty)
{
MessageBox.Show("Please Enter Expense amount");
}
else
{
AddExpenseService expService = new AddExpenseService();
int result = expService.Insert(new Expense() { ExpenseName = t_ExpName.Text, ExpenseAmount = float.Parse(t_ExpAmount.Text), ExpenseDate = dateTimePicker1.Value });
if (result > 0)
{
MessageBox.Show("Expense added.");
}
else
{
MessageBox.Show("Error");
}
}
}
private void t_ExpAmount_ONLY_NUMBER_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
private void t_ExpName_ONLY_CHAR_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsLetter(e.KeyChar) && !char.IsWhiteSpace(e.KeyChar))
{
e.Handled = true;
}
}
}
}
| 29.114286 | 179 | 0.546614 | [
"MIT"
] | sahaavi/Restaurant-Managemnet-System | App/AddExpenseForm.cs | 2,040 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TestController.cs" company="Marcin Smółka zNET Computer Solutions">
// Copyright (c) Marcin Smółka zNET Computer Solutions. All rights reserved.
// </copyright>
// <summary>
// The test controller.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace ZNetCS.AspNetCore.ResumingFileResults.TestWebSite.Controllers
{
#region Usings
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using ZNetCS.AspNetCore.ResumingFileResults.Extensions;
#endregion
/// <summary>
/// The test controller.
/// </summary>
[Route("test/file")]
public class TestController : Controller
{
#region Constants
/// <summary>
/// The entity tag.
/// </summary>
private const string EntityTag = "\"TestFile\"";
#endregion
#region Fields
/// <summary>
/// The hosting environment.
/// </summary>
#if NETCOREAPP3_0
private readonly IWebHostEnvironment hostingEnvironment;
#else
private readonly IHostingEnvironment hostingEnvironment;
#endif
/// <summary>
/// The last modified.
/// </summary>
private readonly DateTimeOffset lastModified = new DateTimeOffset(2016, 1, 1, 0, 0, 0, TimeSpan.Zero);
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="TestController"/> class.
/// </summary>
/// <param name="hostingEnvironment">
/// The hosting environment.
/// </param>
#if NETCOREAPP3_0
public TestController(IWebHostEnvironment hostingEnvironment)
#else
public TestController(IHostingEnvironment hostingEnvironment)
#endif
{
this.hostingEnvironment = hostingEnvironment;
}
#endregion
#region Public Methods
/// <summary>
/// The file contents.
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1611:ElementParametersMustBeDocumented", Justification = "OK")]
[HttpGet("contents/{fileName}/{etag}")]
public IActionResult FileContents(bool fileName, bool etag)
{
string webRoot = this.hostingEnvironment.WebRootPath;
var contents = System.IO.File.ReadAllBytes(Path.Combine(webRoot, "TestFile.txt"));
ResumingFileContentResult result = this.ResumingFile(contents, "text/plain", fileName ? "TestFile.txt" : null, etag ? EntityTag : null);
result.LastModified = this.lastModified;
return result;
}
/// <summary>
/// The file contents.
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1611:ElementParametersMustBeDocumented", Justification = "OK")]
[HttpGet("contents/{fileName}")]
public IActionResult FileContents(bool fileName)
{
string webRoot = this.hostingEnvironment.WebRootPath;
var contents = System.IO.File.ReadAllBytes(Path.Combine(webRoot, "TestFile.txt"));
var result = new ResumingFileContentResult(contents, "text/plain")
{
FileInlineName = "TestFile.txt",
LastModified = this.lastModified
};
return result;
}
/// <summary>
/// The file head.
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1611:ElementParametersMustBeDocumented", Justification = "OK")]
[HttpHead("file")]
public IActionResult FileHead()
{
ResumingVirtualFileResult result = this.ResumingFile("TestFile.txt", "text/plain", "TestFile.txt", EntityTag);
result.LastModified = this.lastModified;
return result;
}
/// <summary>
/// The file put.
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1611:ElementParametersMustBeDocumented", Justification = "OK")]
[HttpPut("file")]
public IActionResult FilePut()
{
ResumingVirtualFileResult result = this.ResumingFile("TestFile.txt", "text/plain", "TestFile.txt", EntityTag);
result.LastModified = this.lastModified;
return result;
}
/// <summary>
/// The file stream.
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1611:ElementParametersMustBeDocumented", Justification = "OK")]
[HttpGet("stream/{fileName}/{etag}")]
public IActionResult FileStream(bool fileName, bool etag)
{
string webRoot = this.hostingEnvironment.WebRootPath;
FileStream stream = System.IO.File.OpenRead(Path.Combine(webRoot, "TestFile.txt"));
ResumingFileStreamResult result = this.ResumingFile(stream, "text/plain", fileName ? "TestFile.txt" : null, etag ? EntityTag : null);
result.LastModified = this.lastModified;
return result;
}
/// <summary>
/// The file stream.
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1611:ElementParametersMustBeDocumented", Justification = "OK")]
[HttpGet("stream/{fileName}")]
public IActionResult FileStream(bool fileName)
{
string webRoot = this.hostingEnvironment.WebRootPath;
FileStream stream = System.IO.File.OpenRead(Path.Combine(webRoot, "TestFile.txt"));
var result = new ResumingFileStreamResult(stream, "text/plain")
{
FileInlineName = "TestFile.txt",
LastModified = this.lastModified
};
return result;
}
/// <summary>
/// The hello action.
/// </summary>
[HttpGet("hello")]
public IActionResult Hello() => this.Content("Hello");
/// <summary>
/// The physical file.
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1611:ElementParametersMustBeDocumented", Justification = "OK")]
[HttpGet("physical/{fileName}/{etag}")]
public IActionResult PhysicalFile(bool fileName, bool etag)
{
string webRoot = this.hostingEnvironment.WebRootPath;
ResumingPhysicalFileResult result = this.ResumingPhysicalFile(
Path.Combine(webRoot, "TestFile.txt"),
"text/plain",
fileName ? "TestFile.txt" : null,
etag ? EntityTag : null);
result.LastModified = this.lastModified;
return result;
}
/// <summary>
/// The physical file.
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1611:ElementParametersMustBeDocumented", Justification = "OK")]
[HttpGet("physical/{fileName}")]
public IActionResult PhysicalFile(bool fileName)
{
string webRoot = this.hostingEnvironment.WebRootPath;
var result = new ResumingPhysicalFileResult(Path.Combine(webRoot, "TestFile.txt"), "text/plain")
{
FileInlineName = "TestFile.txt",
LastModified = this.lastModified
};
return result;
}
/// <summary>
/// The virtual file.
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1611:ElementParametersMustBeDocumented", Justification = "OK")]
[HttpGet("virtual/{fileName}/{etag}")]
public IActionResult VirtualFile(bool fileName, bool etag)
{
ResumingVirtualFileResult result = this.ResumingFile("TestFile.txt", "text/plain", fileName ? "TestFile.txt" : null, etag ? EntityTag : null);
result.LastModified = this.lastModified;
return result;
}
/// <summary>
/// The virtual file.
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1611:ElementParametersMustBeDocumented", Justification = "OK")]
[HttpGet("virtual/{fileName}")]
public IActionResult VirtualFile(bool fileName)
{
var result = new ResumingVirtualFileResult("TestFile.txt", "text/plain")
{
FileInlineName = "TestFile.txt",
LastModified = this.lastModified
};
return result;
}
#endregion
}
} | 36.456432 | 154 | 0.589461 | [
"MIT"
] | msmolka/ZNetCS.AspNetCore.ResumingFileResults | test/ZNetCS.AspNetCore.ResumingFileResults.TestWebSite/Controllers/TestController.cs | 8,792 | C# |
using System;
using Domain.Interfaces;
namespace Domain.Entities
{
public class UserMessage : IEntity
{
public Guid Id { get; set; }
public Guid MessageId { get; set; }
public Message Message { get; set; }
public Guid UserToId { get; set; }
public User To { get; set; }
public Guid UserFromId { get; set; }
public User From { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
} | 28.166667 | 47 | 0.589744 | [
"MIT"
] | M4urici0GM/messenger | v1/Backend/Domain/Entities/UserMessage.cs | 509 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
/// <summary>
/// https://sqlscriptmove.codeplex.com/
/// </summary>
namespace sqlScriptMoveCS
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmMain());
}
}
}
| 22.5 | 65 | 0.617094 | [
"MIT"
] | jlion001/sqlscriptmover | SQLScriptMover/Program.cs | 587 | C# |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Azure.Cosmos
{
using System.Net;
using Microsoft.Azure.Documents;
/// <summary>
/// The cosmos user response
/// </summary>
public class UserResponse : Response<UserProperties>
{
/// <summary>
/// Create a <see cref="UserResponse"/> as a no-op for mock testing
/// </summary>
protected UserResponse()
: base()
{
}
/// <summary>
/// A private constructor to ensure the factory is used to create the object.
/// This will prevent memory leaks when handling the HttpResponseMessage
/// </summary>
internal UserResponse(
HttpStatusCode httpStatusCode,
Headers headers,
UserProperties userProperties,
User user,
CosmosDiagnostics diagnostics)
{
this.StatusCode = httpStatusCode;
this.Headers = headers;
this.Resource = userProperties;
this.User = user;
this.Diagnostics = diagnostics;
}
/// <summary>
/// The reference to the cosmos user. This allows additional operations on the user
/// or for easy access permissions
/// </summary>
public virtual User User { get; private set; }
/// <inheritdoc/>
public override Headers Headers { get; }
/// <inheritdoc/>
public override UserProperties Resource { get; }
/// <inheritdoc/>
public override HttpStatusCode StatusCode { get; }
/// <inheritdoc/>
public override CosmosDiagnostics Diagnostics { get; }
/// <inheritdoc/>
public override double RequestCharge => this.Headers?.RequestCharge ?? 0;
/// <inheritdoc/>
public override string ActivityId => this.Headers?.ActivityId;
/// <inheritdoc/>
public override string ETag => this.Headers?.ETag;
/// <inheritdoc/>
internal override string MaxResourceQuota => this.Headers?.GetHeaderValue<string>(HttpConstants.HttpHeaders.MaxResourceQuota);
/// <inheritdoc/>
internal override string CurrentResourceQuotaUsage => this.Headers?.GetHeaderValue<string>(HttpConstants.HttpHeaders.CurrentResourceQuotaUsage);
/// <summary>
/// Get <see cref="Cosmos.User"/> implicitly from <see cref="UserResponse"/>
/// </summary>
/// <param name="response">UserResponse</param>
public static implicit operator User(UserResponse response)
{
return response.User;
}
}
}
| 33.119048 | 152 | 0.573329 | [
"MIT"
] | SnehaGunda/azure-cosmos-dotnet-v3 | Microsoft.Azure.Cosmos/src/Resource/User/UserResponse.cs | 2,784 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the cloudformation-2010-05-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.CloudFormation.Model
{
/// <summary>
/// The output for <a>GetTemplate</a> action.
/// </summary>
public partial class GetTemplateResponse : AmazonWebServiceResponse
{
private string _templateBody;
/// <summary>
/// Gets and sets the property TemplateBody.
/// <para>
/// Structure containing the template body. (For more information, go to <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-anatomy.html">Template
/// Anatomy</a> in the AWS CloudFormation User Guide.)
/// </para>
/// </summary>
public string TemplateBody
{
get { return this._templateBody; }
set { this._templateBody = value; }
}
// Check to see if TemplateBody property is set
internal bool IsSetTemplateBody()
{
return this._templateBody != null;
}
}
} | 32.157895 | 183 | 0.668849 | [
"Apache-2.0"
] | SaschaHaertel/AmazonAWS | sdk/src/Services/CloudFormation/Generated/Model/GetTemplateResponse.cs | 1,833 | C# |
namespace Microsoft.Bing.ImageSearch.Samples
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
class ExampleAbstraction
{
public IList<Example> Examples { get; private set; }
private TypeInfo backingType;
public ExampleAbstraction(TypeInfo backingType)
{
this.backingType = backingType;
}
public void Load()
{
this.Examples = new List<Example>();
var exampleMethods = backingType.GetMethods().Where(method => method.GetCustomAttribute<ExampleAttribute>() != null).ToArray();
for (var i = 0; i < exampleMethods.Length; i++)
{
var methodInfo = exampleMethods[i];
var exampleMethod = methodInfo.GetCustomAttribute<ExampleAttribute>();
this.Examples.Add(new Example(i, exampleMethod.ExampleDescription, methodInfo));
// assert our assumptions about the method so that this throws if someone adds an improper signature
if (!methodInfo.IsStatic)
{
throw new TypeAccessException(string.Format("Method with description \"{0}\" needs to be static", exampleMethod.ExampleDescription));
}
var methodParams = methodInfo.GetParameters();
if ((methodParams == null || methodParams.Length != 1 || methodParams[0].ParameterType != typeof(string)))
{
throw new TypeAccessException(string.Format("Method with description \"{0}\" needs to have one string parameter for the subscription key", exampleMethod.ExampleDescription));
}
}
}
internal class Example
{
public int Number { get; private set; }
public string Description { get; private set; }
private MethodInfo method;
public Example(int number, string description, MethodInfo method)
{
this.Number = number;
this.Description = description;
this.method = method;
}
public void Invoke(string subscriptionKey)
{
this.method.Invoke(null, new object[] { subscriptionKey });
}
}
}
}
| 35.044776 | 194 | 0.580494 | [
"MIT"
] | josmperez1/bing-search-sdk-for-net-1 | samples/BingSearchSamples/BingImageSearch/multifeatured/ExampleAbstraction.cs | 2,350 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Binary
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Binary.Structure;
using Apache.Ignite.Core.Impl.Common;
/// <summary>
/// Binary reader implementation.
/// </summary>
internal class BinaryReader : IBinaryReader, IBinaryRawReader
{
/** Marshaller. */
private readonly Marshaller _marsh;
/** Parent builder. */
private readonly BinaryObjectBuilder _builder;
/** Handles. */
private BinaryReaderHandleDictionary _hnds;
/** Detach flag. */
private bool _detach;
/** Binary read mode. */
private BinaryMode _mode;
/** Current frame. */
private Frame _frame;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="marsh">Marshaller.</param>
/// <param name="stream">Input stream.</param>
/// <param name="mode">The mode.</param>
/// <param name="builder">Builder.</param>
public BinaryReader
(Marshaller marsh,
IBinaryStream stream,
BinaryMode mode,
BinaryObjectBuilder builder)
{
_marsh = marsh;
_mode = mode;
_builder = builder;
_frame.Pos = stream.Position;
Stream = stream;
}
/// <summary>
/// Gets the marshaller.
/// </summary>
public Marshaller Marshaller
{
get { return _marsh; }
}
/// <summary>
/// Gets the mode.
/// </summary>
public BinaryMode Mode
{
get { return _mode; }
}
/** <inheritdoc /> */
public IBinaryRawReader GetRawReader()
{
MarkRaw();
return this;
}
/** <inheritdoc /> */
public bool ReadBoolean(string fieldName)
{
return ReadField(fieldName, r => r.ReadBoolean(), BinaryUtils.TypeBool);
}
/** <inheritdoc /> */
public bool ReadBoolean()
{
return Stream.ReadBool();
}
/** <inheritdoc /> */
public bool[] ReadBooleanArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadBooleanArray, BinaryUtils.TypeArrayBool);
}
/** <inheritdoc /> */
public bool[] ReadBooleanArray()
{
return Read(BinaryUtils.ReadBooleanArray, BinaryUtils.TypeArrayBool);
}
/** <inheritdoc /> */
public byte ReadByte(string fieldName)
{
return ReadField(fieldName, ReadByte, BinaryUtils.TypeByte);
}
/** <inheritdoc /> */
public byte ReadByte()
{
return Stream.ReadByte();
}
/** <inheritdoc /> */
public byte[] ReadByteArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadByteArray, BinaryUtils.TypeArrayByte);
}
/** <inheritdoc /> */
public byte[] ReadByteArray()
{
return Read(BinaryUtils.ReadByteArray, BinaryUtils.TypeArrayByte);
}
/** <inheritdoc /> */
public short ReadShort(string fieldName)
{
return ReadField(fieldName, ReadShort, BinaryUtils.TypeShort);
}
/** <inheritdoc /> */
public short ReadShort()
{
return Stream.ReadShort();
}
/** <inheritdoc /> */
public short[] ReadShortArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadShortArray, BinaryUtils.TypeArrayShort);
}
/** <inheritdoc /> */
public short[] ReadShortArray()
{
return Read(BinaryUtils.ReadShortArray, BinaryUtils.TypeArrayShort);
}
/** <inheritdoc /> */
public char ReadChar(string fieldName)
{
return ReadField(fieldName, ReadChar, BinaryUtils.TypeChar);
}
/** <inheritdoc /> */
public char ReadChar()
{
return Stream.ReadChar();
}
/** <inheritdoc /> */
public char[] ReadCharArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadCharArray, BinaryUtils.TypeArrayChar);
}
/** <inheritdoc /> */
public char[] ReadCharArray()
{
return Read(BinaryUtils.ReadCharArray, BinaryUtils.TypeArrayChar);
}
/** <inheritdoc /> */
public int ReadInt(string fieldName)
{
return ReadField(fieldName, ReadInt, BinaryUtils.TypeInt);
}
/** <inheritdoc /> */
public int ReadInt()
{
return Stream.ReadInt();
}
/** <inheritdoc /> */
public int[] ReadIntArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadIntArray, BinaryUtils.TypeArrayInt);
}
/** <inheritdoc /> */
public int[] ReadIntArray()
{
return Read(BinaryUtils.ReadIntArray, BinaryUtils.TypeArrayInt);
}
/** <inheritdoc /> */
public long ReadLong(string fieldName)
{
return ReadField(fieldName, ReadLong, BinaryUtils.TypeLong);
}
/** <inheritdoc /> */
public long ReadLong()
{
return Stream.ReadLong();
}
/** <inheritdoc /> */
public long[] ReadLongArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadLongArray, BinaryUtils.TypeArrayLong);
}
/** <inheritdoc /> */
public long[] ReadLongArray()
{
return Read(BinaryUtils.ReadLongArray, BinaryUtils.TypeArrayLong);
}
/** <inheritdoc /> */
public float ReadFloat(string fieldName)
{
return ReadField(fieldName, ReadFloat, BinaryUtils.TypeFloat);
}
/** <inheritdoc /> */
public float ReadFloat()
{
return Stream.ReadFloat();
}
/** <inheritdoc /> */
public float[] ReadFloatArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadFloatArray, BinaryUtils.TypeArrayFloat);
}
/** <inheritdoc /> */
public float[] ReadFloatArray()
{
return Read(BinaryUtils.ReadFloatArray, BinaryUtils.TypeArrayFloat);
}
/** <inheritdoc /> */
public double ReadDouble(string fieldName)
{
return ReadField(fieldName, ReadDouble, BinaryUtils.TypeDouble);
}
/** <inheritdoc /> */
public double ReadDouble()
{
return Stream.ReadDouble();
}
/** <inheritdoc /> */
public double[] ReadDoubleArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadDoubleArray, BinaryUtils.TypeArrayDouble);
}
/** <inheritdoc /> */
public double[] ReadDoubleArray()
{
return Read(BinaryUtils.ReadDoubleArray, BinaryUtils.TypeArrayDouble);
}
/** <inheritdoc /> */
public decimal? ReadDecimal(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadDecimal, BinaryUtils.TypeDecimal);
}
/** <inheritdoc /> */
public decimal? ReadDecimal()
{
return Read(BinaryUtils.ReadDecimal, BinaryUtils.TypeDecimal);
}
/** <inheritdoc /> */
public decimal?[] ReadDecimalArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadDecimalArray, BinaryUtils.TypeArrayDecimal);
}
/** <inheritdoc /> */
public decimal?[] ReadDecimalArray()
{
return Read(BinaryUtils.ReadDecimalArray, BinaryUtils.TypeArrayDecimal);
}
/** <inheritdoc /> */
public DateTime? ReadTimestamp(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadTimestamp, BinaryUtils.TypeTimestamp);
}
/** <inheritdoc /> */
public DateTime? ReadTimestamp()
{
return Read(BinaryUtils.ReadTimestamp, BinaryUtils.TypeTimestamp);
}
/** <inheritdoc /> */
public DateTime?[] ReadTimestampArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadTimestampArray, BinaryUtils.TypeArrayTimestamp);
}
/** <inheritdoc /> */
public DateTime?[] ReadTimestampArray()
{
return Read(BinaryUtils.ReadTimestampArray, BinaryUtils.TypeArrayTimestamp);
}
/** <inheritdoc /> */
public string ReadString(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadString, BinaryUtils.TypeString);
}
/** <inheritdoc /> */
public string ReadString()
{
return Read(BinaryUtils.ReadString, BinaryUtils.TypeString);
}
/** <inheritdoc /> */
public string[] ReadStringArray(string fieldName)
{
return ReadField(fieldName, r => BinaryUtils.ReadArray<string>(r, false), BinaryUtils.TypeArrayString);
}
/** <inheritdoc /> */
public string[] ReadStringArray()
{
return Read(r => BinaryUtils.ReadArray<string>(r, false), BinaryUtils.TypeArrayString);
}
/** <inheritdoc /> */
public Guid? ReadGuid(string fieldName)
{
return ReadField<Guid?>(fieldName, r => BinaryUtils.ReadGuid(r), BinaryUtils.TypeGuid);
}
/** <inheritdoc /> */
public Guid? ReadGuid()
{
return Read<Guid?>(r => BinaryUtils.ReadGuid(r), BinaryUtils.TypeGuid);
}
/** <inheritdoc /> */
public Guid?[] ReadGuidArray(string fieldName)
{
return ReadField(fieldName, r => BinaryUtils.ReadArray<Guid?>(r, false), BinaryUtils.TypeArrayGuid);
}
/** <inheritdoc /> */
public Guid?[] ReadGuidArray()
{
return Read(r => BinaryUtils.ReadArray<Guid?>(r, false), BinaryUtils.TypeArrayGuid);
}
/** <inheritdoc /> */
public T ReadEnum<T>(string fieldName)
{
return SeekField(fieldName) ? ReadEnum<T>() : default(T);
}
/** <inheritdoc /> */
public T ReadEnum<T>()
{
var hdr = ReadByte();
switch (hdr)
{
case BinaryUtils.HdrNull:
return default(T);
case BinaryUtils.TypeEnum:
// Never read enums in binary mode when reading a field (we do not support half-binary objects)
return ReadEnum0<T>(this, false);
case BinaryUtils.HdrFull:
// Unregistered enum written as serializable
Stream.Seek(-1, SeekOrigin.Current);
return ReadObject<T>();
default:
throw new BinaryObjectException(
string.Format("Invalid header on enum deserialization. Expected: {0} or {1} but was: {2}",
BinaryUtils.TypeEnum, BinaryUtils.HdrFull, hdr));
}
}
/** <inheritdoc /> */
public T[] ReadEnumArray<T>(string fieldName)
{
return ReadField(fieldName, r => BinaryUtils.ReadArray<T>(r, true), BinaryUtils.TypeArrayEnum);
}
/** <inheritdoc /> */
public T[] ReadEnumArray<T>()
{
return Read(r => BinaryUtils.ReadArray<T>(r, true), BinaryUtils.TypeArrayEnum);
}
/** <inheritdoc /> */
public T ReadObject<T>(string fieldName)
{
if (_frame.Raw)
throw new BinaryObjectException("Cannot read named fields after raw data is read.");
if (SeekField(fieldName))
return Deserialize<T>();
return default(T);
}
/** <inheritdoc /> */
public T ReadObject<T>()
{
return Deserialize<T>();
}
/** <inheritdoc /> */
public T[] ReadArray<T>(string fieldName)
{
return ReadField(fieldName, r => BinaryUtils.ReadArray<T>(r, true), BinaryUtils.TypeArray);
}
/** <inheritdoc /> */
public T[] ReadArray<T>()
{
return Read(r => BinaryUtils.ReadArray<T>(r, true), BinaryUtils.TypeArray);
}
/** <inheritdoc /> */
public ICollection ReadCollection(string fieldName)
{
return ReadCollection(fieldName, null, null);
}
/** <inheritdoc /> */
public ICollection ReadCollection()
{
return ReadCollection(null, null);
}
/** <inheritdoc /> */
public ICollection ReadCollection(string fieldName, Func<int, ICollection> factory,
Action<ICollection, object> adder)
{
return ReadField(fieldName, r => BinaryUtils.ReadCollection(r, factory, adder), BinaryUtils.TypeCollection);
}
/** <inheritdoc /> */
public ICollection ReadCollection(Func<int, ICollection> factory, Action<ICollection, object> adder)
{
return Read(r => BinaryUtils.ReadCollection(r, factory, adder), BinaryUtils.TypeCollection);
}
/** <inheritdoc /> */
public IDictionary ReadDictionary(string fieldName)
{
return ReadDictionary(fieldName, null);
}
/** <inheritdoc /> */
public IDictionary ReadDictionary()
{
return ReadDictionary((Func<int, IDictionary>) null);
}
/** <inheritdoc /> */
public IDictionary ReadDictionary(string fieldName, Func<int, IDictionary> factory)
{
return ReadField(fieldName, r => BinaryUtils.ReadDictionary(r, factory), BinaryUtils.TypeDictionary);
}
/** <inheritdoc /> */
public IDictionary ReadDictionary(Func<int, IDictionary> factory)
{
return Read(r => BinaryUtils.ReadDictionary(r, factory), BinaryUtils.TypeDictionary);
}
/// <summary>
/// Enable detach mode for the next object read.
/// </summary>
public BinaryReader DetachNext()
{
_detach = true;
return this;
}
/// <summary>
/// Deserialize object.
/// </summary>
/// <returns>Deserialized object.</returns>
public T Deserialize<T>()
{
T res;
// ReSharper disable once CompareNonConstrainedGenericWithNull
if (!TryDeserialize(out res) && default(T) != null)
throw new BinaryObjectException(string.Format("Invalid data on deserialization. " +
"Expected: '{0}' But was: null", typeof (T)));
return res;
}
/// <summary>
/// Deserialize object.
/// </summary>
/// <returns>Deserialized object.</returns>
public bool TryDeserialize<T>(out T res)
{
int pos = Stream.Position;
byte hdr = Stream.ReadByte();
var doDetach = _detach; // save detach flag into a var and reset so it does not go deeper
_detach = false;
switch (hdr)
{
case BinaryUtils.HdrNull:
res = default(T);
return false;
case BinaryUtils.HdrHnd:
res = ReadHandleObject<T>(pos);
return true;
case BinaryUtils.HdrFull:
res = ReadFullObject<T>(pos);
return true;
case BinaryUtils.TypeBinary:
res = ReadBinaryObject<T>(doDetach);
return true;
case BinaryUtils.TypeEnum:
res = ReadEnum0<T>(this, _mode != BinaryMode.Deserialize);
return true;
}
if (BinarySystemHandlers.TryReadSystemType(hdr, this, out res))
return true;
throw new BinaryObjectException("Invalid header on deserialization [pos=" + pos + ", hdr=" + hdr + ']');
}
/// <summary>
/// Gets the flag indicating that there is custom type information in raw region.
/// </summary>
public bool GetCustomTypeDataFlag()
{
return _frame.Hdr.IsCustomDotNetType;
}
/// <summary>
/// Reads the binary object.
/// </summary>
private T ReadBinaryObject<T>(bool doDetach)
{
var len = Stream.ReadInt();
var binaryBytesPos = Stream.Position;
if (_mode != BinaryMode.Deserialize)
return TypeCaster<T>.Cast(ReadAsBinary(binaryBytesPos, len, doDetach));
Stream.Seek(len, SeekOrigin.Current);
var offset = Stream.ReadInt();
var retPos = Stream.Position;
Stream.Seek(binaryBytesPos + offset, SeekOrigin.Begin);
_mode = BinaryMode.KeepBinary;
try
{
return Deserialize<T>();
}
finally
{
_mode = BinaryMode.Deserialize;
Stream.Seek(retPos, SeekOrigin.Begin);
}
}
/// <summary>
/// Reads the binary object in binary form.
/// </summary>
private BinaryObject ReadAsBinary(int binaryBytesPos, int dataLen, bool doDetach)
{
try
{
Stream.Seek(dataLen + binaryBytesPos, SeekOrigin.Begin);
var offs = Stream.ReadInt(); // offset inside data
var pos = binaryBytesPos + offs;
var hdr = BinaryObjectHeader.Read(Stream, pos);
if (!doDetach)
return new BinaryObject(_marsh, Stream.GetArray(), pos, hdr);
Stream.Seek(pos, SeekOrigin.Begin);
return new BinaryObject(_marsh, Stream.ReadByteArray(hdr.Length), 0, hdr);
}
finally
{
Stream.Seek(binaryBytesPos + dataLen + 4, SeekOrigin.Begin);
}
}
/// <summary>
/// Reads the full object.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "hashCode")]
private T ReadFullObject<T>(int pos)
{
var hdr = BinaryObjectHeader.Read(Stream, pos);
// Validate protocol version.
BinaryUtils.ValidateProtocolVersion(hdr.Version);
try
{
// Already read this object?
object hndObj;
if (_hnds != null && _hnds.TryGetValue(pos, out hndObj))
return (T) hndObj;
if (hdr.IsUserType && _mode == BinaryMode.ForceBinary)
{
BinaryObject portObj;
if (_detach)
{
Stream.Seek(pos, SeekOrigin.Begin);
portObj = new BinaryObject(_marsh, Stream.ReadByteArray(hdr.Length), 0, hdr);
}
else
portObj = new BinaryObject(_marsh, Stream.GetArray(), pos, hdr);
T obj = _builder == null ? TypeCaster<T>.Cast(portObj) : TypeCaster<T>.Cast(_builder.Child(portObj));
AddHandle(pos, obj);
return obj;
}
else
{
// Find descriptor.
var desc = hdr.TypeId == BinaryUtils.TypeUnregistered
? _marsh.GetDescriptor(Type.GetType(ReadString(), true))
: _marsh.GetDescriptor(hdr.IsUserType, hdr.TypeId, true);
// Instantiate object.
if (desc.Type == null)
{
if (desc is BinarySurrogateTypeDescriptor)
{
throw new BinaryObjectException(string.Format(
"Unknown type ID: {0}. " +
"This usually indicates missing BinaryConfiguration." +
"Make sure that all nodes have the same BinaryConfiguration.", hdr.TypeId));
}
throw new BinaryObjectException(string.Format(
"No matching type found for object [typeId={0}, typeName={1}]." +
"This usually indicates that assembly with specified type is not loaded on a node." +
"When using Apache.Ignite.exe, make sure to load assemblies with -assembly parameter.",
desc.TypeId, desc.TypeName));
}
// Preserve old frame.
var oldFrame = _frame;
// Set new frame.
_frame.Hdr = hdr;
_frame.Pos = pos;
SetCurSchema(desc);
_frame.Struct = new BinaryStructureTracker(desc, desc.ReaderTypeStructure);
_frame.Raw = false;
// Read object.
var obj = desc.Serializer.ReadBinary<T>(this, desc, pos);
_frame.Struct.UpdateReaderStructure();
// Restore old frame.
_frame = oldFrame;
return obj;
}
}
finally
{
// Advance stream pointer.
Stream.Seek(pos + hdr.Length, SeekOrigin.Begin);
}
}
/// <summary>
/// Sets the current schema.
/// </summary>
private void SetCurSchema(IBinaryTypeDescriptor desc)
{
_frame.SchemaMap = null;
if (_frame.Hdr.HasSchema)
{
_frame.Schema = desc.Schema.Get(_frame.Hdr.SchemaId);
if (_frame.Schema == null)
{
_frame.Schema = ReadSchema(desc.TypeId);
desc.Schema.Add(_frame.Hdr.SchemaId, _frame.Schema);
}
}
else
{
_frame.Schema = null;
}
}
/// <summary>
/// Reads the schema.
/// </summary>
private int[] ReadSchema(int typeId)
{
if (_frame.Hdr.IsCompactFooter)
{
// Get schema from Java
var ignite = Marshaller.Ignite;
Debug.Assert(typeId != BinaryUtils.TypeUnregistered);
var schema = ignite == null
? null
: ignite.BinaryProcessor.GetSchema(_frame.Hdr.TypeId, _frame.Hdr.SchemaId);
if (schema == null)
throw new BinaryObjectException("Cannot find schema for object with compact footer [" +
"typeId=" + typeId + ", schemaId=" + _frame.Hdr.SchemaId + ']');
return schema;
}
var pos = Stream.Position;
Stream.Seek(_frame.Pos + _frame.Hdr.SchemaOffset, SeekOrigin.Begin);
var count = _frame.Hdr.SchemaFieldCount;
var offsetSize = _frame.Hdr.SchemaFieldOffsetSize;
var res = new int[count];
for (int i = 0; i < count; i++)
{
res[i] = Stream.ReadInt();
Stream.Seek(offsetSize, SeekOrigin.Current);
}
Stream.Seek(pos, SeekOrigin.Begin);
return res;
}
/// <summary>
/// Reads the handle object.
/// </summary>
private T ReadHandleObject<T>(int pos)
{
// Get handle position.
int hndPos = pos - Stream.ReadInt();
int retPos = Stream.Position;
try
{
object hndObj;
if (_builder == null || !_builder.TryGetCachedField(hndPos, out hndObj))
{
if (_hnds == null || !_hnds.TryGetValue(hndPos, out hndObj))
{
// No such handler, i.e. we trying to deserialize inner object before deserializing outer.
Stream.Seek(hndPos, SeekOrigin.Begin);
hndObj = Deserialize<T>();
}
// Notify builder that we deserialized object on other location.
if (_builder != null)
_builder.CacheField(hndPos, hndObj);
}
return (T) hndObj;
}
finally
{
// Position stream to correct place.
Stream.Seek(retPos, SeekOrigin.Begin);
}
}
/// <summary>
/// Adds a handle to the dictionary.
/// </summary>
/// <param name="pos">Position.</param>
/// <param name="obj">Object.</param>
internal void AddHandle(int pos, object obj)
{
if (_hnds == null)
_hnds = new BinaryReaderHandleDictionary(pos, obj);
else
_hnds.Add(pos, obj);
}
/// <summary>
/// Underlying stream.
/// </summary>
public IBinaryStream Stream
{
get;
private set;
}
/// <summary>
/// Seeks to raw data.
/// </summary>
internal void SeekToRaw()
{
Stream.Seek(_frame.Pos + _frame.Hdr.GetRawOffset(Stream, _frame.Pos), SeekOrigin.Begin);
}
/// <summary>
/// Mark current output as raw.
/// </summary>
private void MarkRaw()
{
if (!_frame.Raw)
{
_frame.Raw = true;
SeekToRaw();
}
}
/// <summary>
/// Seeks the field by name.
/// </summary>
private bool SeekField(string fieldName)
{
if (_frame.Raw)
throw new BinaryObjectException("Cannot read named fields after raw data is read.");
if (!_frame.Hdr.HasSchema)
return false;
var actionId = _frame.Struct.CurStructAction;
var fieldId = _frame.Struct.GetFieldId(fieldName);
if (_frame.Schema == null || actionId >= _frame.Schema.Length || fieldId != _frame.Schema[actionId])
{
_frame.SchemaMap = _frame.SchemaMap ?? BinaryObjectSchemaSerializer.ReadSchema(Stream, _frame.Pos,
_frame.Hdr, () => _frame.Schema).ToDictionary();
_frame.Schema = null; // read order is different, ignore schema for future reads
int pos;
if (!_frame.SchemaMap.TryGetValue(fieldId, out pos))
return false;
Stream.Seek(pos + _frame.Pos, SeekOrigin.Begin);
}
return true;
}
/// <summary>
/// Seeks specified field and invokes provided func.
/// </summary>
private T ReadField<T>(string fieldName, Func<IBinaryStream, T> readFunc, byte expHdr)
{
return SeekField(fieldName) ? Read(readFunc, expHdr) : default(T);
}
/// <summary>
/// Seeks specified field and invokes provided func.
/// </summary>
private T ReadField<T>(string fieldName, Func<BinaryReader, T> readFunc, byte expHdr)
{
return SeekField(fieldName) ? Read(readFunc, expHdr) : default(T);
}
/// <summary>
/// Seeks specified field and invokes provided func.
/// </summary>
private T ReadField<T>(string fieldName, Func<T> readFunc, byte expHdr)
{
return SeekField(fieldName) ? Read(readFunc, expHdr) : default(T);
}
/// <summary>
/// Reads header and invokes specified func if the header is not null.
/// </summary>
private T Read<T>(Func<BinaryReader, T> readFunc, byte expHdr)
{
return Read(() => readFunc(this), expHdr);
}
/// <summary>
/// Reads header and invokes specified func if the header is not null.
/// </summary>
private T Read<T>(Func<IBinaryStream, T> readFunc, byte expHdr)
{
return Read(() => readFunc(Stream), expHdr);
}
/// <summary>
/// Reads header and invokes specified func if the header is not null.
/// </summary>
private T Read<T>(Func<T> readFunc, byte expHdr)
{
var hdr = ReadByte();
if (hdr == BinaryUtils.HdrNull)
return default(T);
if (hdr == BinaryUtils.HdrHnd)
return ReadHandleObject<T>(Stream.Position - 1);
if (expHdr != hdr)
throw new BinaryObjectException(string.Format("Invalid header on deserialization. " +
"Expected: {0} but was: {1}", expHdr, hdr));
return readFunc();
}
/// <summary>
/// Reads the enum.
/// </summary>
private static T ReadEnum0<T>(BinaryReader reader, bool keepBinary)
{
var enumType = reader.ReadInt();
var enumValue = reader.ReadInt();
if (!keepBinary)
return BinaryUtils.GetEnumValue<T>(enumValue, enumType, reader.Marshaller);
return TypeCaster<T>.Cast(new BinaryEnum(enumType, enumValue, reader.Marshaller));
}
/// <summary>
/// Stores current reader stack frame.
/// </summary>
private struct Frame
{
/** Current position. */
public int Pos;
/** Current raw flag. */
public bool Raw;
/** Current type structure tracker. */
public BinaryStructureTracker Struct;
/** Current schema. */
public int[] Schema;
/** Current schema with positions. */
public Dictionary<int, int> SchemaMap;
/** Current header. */
public BinaryObjectHeader Hdr;
}
}
}
| 30.844206 | 121 | 0.520093 | [
"CC0-1.0"
] | dropoutlabs/ignite | modules/platforms/dotnet/Apache.Ignite.Core/Impl/Binary/BinaryReader.cs | 31,677 | C# |
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using AspNetCoreSpa.Server.Entities;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using AspNetCoreSpa.Server.Services;
using Microsoft.AspNetCore.Localization;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Http;
using System;
using Microsoft.Extensions.Localization;
using AspNetCoreSpa.Server.ViewModels;
using System.Globalization;
using Microsoft.Extensions.Caching.Memory;
namespace AspNetCoreSpa.Server.Controllers
{
public class HomeController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly IStringLocalizer<HomeController> _stringLocalizer;
private readonly IHostingEnvironment _env;
private readonly IMemoryCache _cache;
public HomeController(
UserManager<ApplicationUser> userManager,
IHostingEnvironment env,
IStringLocalizer<HomeController> stringLocalizer,
IMemoryCache memoryCache
)
{
_userManager = userManager;
_stringLocalizer = stringLocalizer;
_env = env;
_cache = memoryCache;
}
public async Task<IActionResult> Index()
{
if (ConfirmEmailRequest())
{
await ConfirmEmail();
}
var content = GetContentByCulture();
ViewBag.content = content;
return View();
}
[HttpPost]
public IActionResult SetLanguage(string culture)
{
Response.Cookies.Append(CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)), new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
);
return LocalRedirect("~/");
}
private bool ConfirmEmailRequest()
{
return Request.Query.ContainsKey("emailConfirmCode") && Request.Query.ContainsKey("userId");
}
private async Task ConfirmEmail()
{
var userId = Request.Query["userId"].ToString();
var code = Request.Query["emailConfirmCode"].ToString();
code = code.Replace(" ", "+");
var user = await _userManager.FindByIdAsync(userId);
if (user != null && !user.EmailConfirmed)
{
var valid = await _userManager.ConfirmEmailAsync(user, code);
if (valid.Succeeded)
{
ViewBag.emailConfirmed = true;
}
}
}
private string GetContentByCulture()
{
var requestCulture = HttpContext.Features.Get<IRequestCultureFeature>();
// Culture contains the information of the requested culture
var culture = requestCulture.RequestCulture.Culture;
var CACHE_KEY = $"Content-{culture.Name}";
string cacheEntry;
// Look for cache key.
if (!_cache.TryGetValue(CACHE_KEY, out cacheEntry))
{
// Key not in cache, so get & set data.
var culturalContent = _stringLocalizer.WithCulture(culture)
.GetAllStrings()
.Select(c => new ContentVm
{
Key = c.Name,
Value = c.Value
})
.ToDictionary(x => x.Key, x => x.Value);
cacheEntry = Helpers.JsonSerialize(culturalContent);
// Set cache options.
var cacheEntryOptions = new MemoryCacheEntryOptions()
// Keep in cache for this time, reset time if accessed.
.SetSlidingExpiration(TimeSpan.FromMinutes(30));
// Save data in cache.
_cache.Set(CACHE_KEY, cacheEntry, cacheEntryOptions);
}
return cacheEntry;
}
}
}
| 34.283465 | 156 | 0.576481 | [
"MIT"
] | Delashok/AspNetCoreSpa | Server/Controllers/HomeController.cs | 4,356 | C# |
// -----------------------------------------------------------------------
// <copyright file="RoundRobinRouterState.cs" company="Asynkron AB">
// Copyright (C) 2015-2022 Asynkron AB All rights reserved
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Threading;
namespace Proto.Router.Routers;
class RoundRobinRouterState : RouterState
{
private readonly ISenderContext _senderContext;
private int _currentIndex;
internal RoundRobinRouterState(ISenderContext senderContext) => _senderContext = senderContext;
public override void RouteMessage(object message)
{
var values = GetValues();
var i = Math.Abs(Interlocked.Increment(ref _currentIndex) - 1) % values.Count;
var pid = values[i];
_senderContext.Send(pid, message);
}
} | 34.44 | 99 | 0.594657 | [
"Apache-2.0"
] | BearerPipelineTest/protoactor-dotnet | src/Proto.Actor/Router/Routers/RoundRobinRouterState.cs | 863 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public enum BattleState { START, PLAYERTURN, DEFENDINGTURN, WON, LOST }
public class GameManager : MonoBehaviour
{
private MusicController theMusicController;
public GameObject playerCamera;
public GameObject battleCamera;
public BattleHud playerHUD;
public BattleHud defendingHUD;
public GameObject yourPokemon;
public GameObject emptyPokemon;
BasePokemon playerPokemon;
BasePokemon defendingPokemon;
private Player player;
public GameObject playerObject;
private GameObject dPokemon;
public List<BasePokemon> allPokemon = new List<BasePokemon>();
public List<PokemonMoves> allMoves = new List<PokemonMoves>();
public Transform defensePodium;
public Transform attackPodium;
public Text dialogueText;
private int expToReceive;
private static bool gmExists;
public BattleState state;
// Start is called before the first frame update
void Start()
{
/* if (!gmExists)
{
gmExists = true;
DontDestroyOnLoad(transform.gameObject);
}
else
{
Destroy(gameObject);
} */
playerCamera = GameObject.Find("Main Camera");
battleCamera = GameObject.Find("BattleCamera");
playerObject = GameObject.Find("Player");
playerCamera.SetActive(true);
battleCamera.SetActive(false);
theMusicController = FindObjectOfType<MusicController>();
}
public IEnumerator EnterBattle(Rarity rarity)
{
theMusicController.SwitchTrack(2);
state = BattleState.START;
playerObject.GetComponent<Movement>().isAllowedToMove = false;
playerCamera.SetActive(false);
battleCamera.SetActive(true);
GameObject playerGo = Instantiate(yourPokemon, attackPodium);
playerPokemon = playerGo.GetComponent<BasePokemon>();
defendingPokemon = GetRandomPokemonFromList(GetPokemonByRarity(rarity));
Debug.Log(defendingPokemon.name);
dPokemon = Instantiate(emptyPokemon, defensePodium.transform.position, Quaternion.identity) as GameObject;
Vector3 pokemonLocalPosition = new Vector3(0, 1, 0);
dPokemon.transform.parent = defensePodium;
dPokemon.transform.localPosition = pokemonLocalPosition;
BasePokemon tempPokemon = dPokemon.AddComponent<BasePokemon>() as BasePokemon;
tempPokemon.AddMember(defendingPokemon);
dPokemon.GetComponent<SpriteRenderer>().sprite = defendingPokemon.image;
dialogueText.text = "A wild " + defendingPokemon.PName + " approaches";
playerHUD.SetHUD(playerPokemon);
defendingHUD.SetHUD(tempPokemon);
yield return new WaitForSeconds(2f);
state = BattleState.PLAYERTURN;
PlayerTurn();
//bm.ChangeMenu(BattleMenu.Selection);
}
void PlayerTurn()
{
dialogueText.text = "Choose an action: ";
}
IEnumerator PlayerAttack()
{
// Damage the enemy
dialogueText.text = playerPokemon.PName + " used Thunderbolt!";
theMusicController.PlayTrack(4);
yield return new WaitForSeconds(3f);
bool isDead = defendingPokemon.TakeDamage(playerPokemon.damage);
defendingHUD.SetHP(defendingPokemon.HP);
yield return new WaitForSeconds(2f);
// Check if the defending pokemon fainted
// Change the state
if (isDead)
{
state = BattleState.WON;
StartCoroutine(EndBattle());
} else
{
state = BattleState.DEFENDINGTURN;
StartCoroutine(DefendingTurn());
}
}
IEnumerator DefendingTurn()
{
dialogueText.text = defendingPokemon.PName + " used an attack!";
theMusicController.PlayTrack(5);
yield return new WaitForSeconds(2f);
bool isDead = playerPokemon.TakeDamage(defendingPokemon.damage);
playerHUD.SetHP(playerPokemon.HP);
yield return new WaitForSeconds(2f);
if (isDead)
{
state = BattleState.LOST;
StartCoroutine(EndBattle());
} else
{
state = BattleState.PLAYERTURN;
PlayerTurn();
}
}
IEnumerator Flee()
{
dialogueText.text = "You got away safely!";
theMusicController.PlayTrack(6);
yield return new WaitForSeconds(1f);
SwitchBackToWorld();
//playerCamera.SetActive(true);
//battleCamera.SetActive(false);
//playerObject.GetComponent<Movement>().isAllowedToMove = true;
//Destroy(dPokemon);
//theMusicController.SwitchTrack(1);
}
IEnumerator EndBattle()
{
if (state == BattleState.WON)
{
dialogueText.text = "Wild " + defendingPokemon.PName + " has fainted!";
} else if (state == BattleState.LOST)
{
dialogueText.text = "Your " + playerPokemon.PName + "has fainted!";
}
theMusicController.SwitchTrack(3);
yield return new WaitForSeconds(6f);
expToReceive = defendingPokemon.expToReceive;
Debug.Log("Total EXP: " + expToReceive);
dialogueText.text = "Your Ash's Pikachu got " + expToReceive + " Exp. points!";
//player.ResolveCombat(expToReceive);
yield return new WaitForSeconds(3f);
SwitchBackToWorld();
//playerCamera.SetActive(true);
//battleCamera.SetActive(false);
//playerObject.GetComponent<Movement>().isAllowedToMove = true;
//Destroy(dPokemon);
//theMusicController.SwitchTrack(1);
}
public void onFight()
{
if (state != BattleState.PLAYERTURN)
return;
StartCoroutine(PlayerAttack());
}
public void onBag()
{
}
public void onPokemon()
{
}
public void onRun()
{
if (state != BattleState.PLAYERTURN)
return;
StartCoroutine(Flee());
}
private void SwitchBackToWorld()
{
playerCamera.SetActive(true);
battleCamera.SetActive(false);
playerObject.GetComponent<Movement>().isAllowedToMove = true;
Destroy(dPokemon);
theMusicController.SwitchTrack(1);
}
public List<BasePokemon> GetPokemonByRarity(Rarity rarity)
{
List<BasePokemon> returnPokemon = new List<BasePokemon>();
foreach (BasePokemon Pokemon in allPokemon)
{
if (Pokemon.rarity == rarity)
returnPokemon.Add(Pokemon);
}
return returnPokemon;
}
public BasePokemon GetRandomPokemonFromList(List<BasePokemon> pokeList)
{
BasePokemon poke = new BasePokemon();
int pokeIndex = Random.Range(0, pokeList.Count - 1);
poke = pokeList[pokeIndex];
return poke;
}
}
[System.Serializable]
public class PokemonMoves
{
string Name;
public MoveType category;
public Stat moveStat;
public PokemonType moveType;
public int PP;
public float power;
public float accuracy;
}
[System.Serializable]
public class Stat
{
public float minimum;
public float maximum;
}
public enum MoveType
{
Physical,
Special,
Status
}
| 26.831502 | 114 | 0.637679 | [
"MIT"
] | charte88/Pokemon-Unity-Clone | Pokemon/Assets/Scripts/GameManager.cs | 7,327 | C# |
using System;
using NUnit.Framework;
namespace EventStore.Projections.Core.Tests.Services.event_filter
{
[TestFixture]
public class empty_event_filter : TestFixtureWithEventFilter
{
[Test]
public void cannot_be_built()
{
Assert.IsAssignableFrom(typeof (InvalidOperationException), _exception);
}
}
}
| 22.625 | 84 | 0.68232 | [
"Apache-2.0",
"CC0-1.0"
] | cuteant/EventStore-DotNetty-Fork | src/EventStore.Projections.Core.Tests/Services/event_filter/empty_event_filter.cs | 364 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Persona5Rus.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.387097 | 151 | 0.581614 | [
"MIT"
] | Meloman19/Persona5Rus | Persona5Rus/Properties/Settings.Designer.cs | 1,068 | C# |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace EmpleadosMVC.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("00000000000000_CreateIdentitySchema")]
partial class CreateIdentitySchema
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.2");
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("EmpleadosMVC.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasMaxLength(256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole")
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("EmpleadosMVC.Models.ApplicationUser")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("EmpleadosMVC.Models.ApplicationUser")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole")
.WithMany("Users")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("EmpleadosMVC.Models.ApplicationUser")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| 33.633803 | 96 | 0.456449 | [
"MIT"
] | dobleub/dotnetcore-course | EmpleadosMVC/Data/Migrations/00000000000000_CreateIdentitySchema.Designer.cs | 7,166 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.IO;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Text;
using System.Threading.Tasks;
namespace System.Xml
{
public abstract class XmlDictionaryWriter : XmlWriter
{
public static XmlDictionaryWriter CreateBinaryWriter(Stream stream)
{
return CreateBinaryWriter(stream, null);
}
public static XmlDictionaryWriter CreateBinaryWriter(Stream stream, IXmlDictionary? dictionary)
{
return CreateBinaryWriter(stream, dictionary, null);
}
public static XmlDictionaryWriter CreateBinaryWriter(Stream stream, IXmlDictionary? dictionary, XmlBinaryWriterSession? session)
{
return CreateBinaryWriter(stream, dictionary, session, true);
}
public static XmlDictionaryWriter CreateBinaryWriter(Stream stream, IXmlDictionary? dictionary, XmlBinaryWriterSession? session, bool ownsStream)
{
XmlBinaryWriter writer = new XmlBinaryWriter();
writer.SetOutput(stream, dictionary, session, ownsStream);
return writer;
}
private static readonly Encoding s_UTF8Encoding = new UTF8Encoding(false);
public static XmlDictionaryWriter CreateTextWriter(Stream stream)
{
return CreateTextWriter(stream, s_UTF8Encoding, true);
}
public static XmlDictionaryWriter CreateTextWriter(Stream stream, Encoding encoding)
{
return CreateTextWriter(stream, encoding, true);
}
public static XmlDictionaryWriter CreateTextWriter(Stream stream, Encoding encoding, bool ownsStream)
{
XmlUTF8TextWriter writer = new XmlUTF8TextWriter();
writer.SetOutput(stream, encoding, ownsStream);
var asyncWriter = new XmlDictionaryAsyncCheckWriter(writer);
return asyncWriter;
}
public static XmlDictionaryWriter CreateMtomWriter(Stream stream, Encoding encoding, int maxSizeInBytes, string startInfo)
{
return CreateMtomWriter(stream, encoding, maxSizeInBytes, startInfo, null, null, true, true);
}
public static XmlDictionaryWriter CreateMtomWriter(Stream stream, Encoding encoding, int maxSizeInBytes, string startInfo, string? boundary, string? startUri, bool writeMessageHeaders, bool ownsStream)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_MtomEncoding);
}
public static XmlDictionaryWriter CreateDictionaryWriter(XmlWriter writer)
{
ArgumentNullException.ThrowIfNull(writer);
XmlDictionaryWriter? dictionaryWriter = writer as XmlDictionaryWriter;
if (dictionaryWriter == null)
{
dictionaryWriter = new XmlWrappedWriter(writer);
}
return dictionaryWriter;
}
public override Task WriteBase64Async(byte[] buffer, int index, int count)
{
WriteBase64(buffer, index, count);
return Task.CompletedTask;
}
public void WriteStartElement(XmlDictionaryString localName, XmlDictionaryString? namespaceUri)
{
WriteStartElement((string?)null, localName, namespaceUri);
}
public virtual void WriteStartElement(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri)
{
WriteStartElement(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri));
}
public void WriteStartAttribute(XmlDictionaryString localName, XmlDictionaryString? namespaceUri)
{
WriteStartAttribute((string?)null, localName, namespaceUri);
}
public virtual void WriteStartAttribute(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri)
{
WriteStartAttribute(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri));
}
public void WriteAttributeString(XmlDictionaryString localName, XmlDictionaryString? namespaceUri, string? value)
{
WriteAttributeString((string?)null, localName, namespaceUri, value);
}
public virtual void WriteXmlnsAttribute(string? prefix, string namespaceUri)
{
ArgumentNullException.ThrowIfNull(namespaceUri);
if (prefix == null)
{
if (LookupPrefix(namespaceUri) != null)
return;
prefix = namespaceUri.Length == 0 ? string.Empty : $"d{namespaceUri.Length}";
}
WriteAttributeString("xmlns", prefix, null, namespaceUri);
}
public virtual void WriteXmlnsAttribute(string? prefix, XmlDictionaryString namespaceUri)
{
WriteXmlnsAttribute(prefix, XmlDictionaryString.GetString(namespaceUri));
}
public virtual void WriteXmlAttribute(string localName, string? value)
{
WriteAttributeString("xml", localName, null, value);
}
public virtual void WriteXmlAttribute(XmlDictionaryString localName, XmlDictionaryString? value)
{
WriteXmlAttribute(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(value));
}
public void WriteAttributeString(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, string? value)
{
WriteStartAttribute(prefix, localName, namespaceUri);
WriteString(value);
WriteEndAttribute();
}
public void WriteElementString(XmlDictionaryString localName, XmlDictionaryString? namespaceUri, string? value)
{
WriteElementString((string?)null, localName, namespaceUri, value);
}
public void WriteElementString(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, string? value)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteString(value);
WriteEndElement();
}
public virtual void WriteString(XmlDictionaryString? value)
{
WriteString(XmlDictionaryString.GetString(value));
}
public virtual void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString? namespaceUri)
{
ArgumentNullException.ThrowIfNull(localName);
if (namespaceUri == null)
namespaceUri = XmlDictionaryString.Empty;
#pragma warning suppress 56506 // Microsoft, XmlDictionaryString.Empty is never null
WriteQualifiedName(localName.Value, namespaceUri.Value);
}
public virtual void WriteValue(XmlDictionaryString? value)
{
WriteValue(XmlDictionaryString.GetString(value));
}
public virtual void WriteValue(UniqueId value)
{
ArgumentNullException.ThrowIfNull(value);
WriteString(value.ToString());
}
public virtual void WriteValue(Guid value)
{
WriteString(value.ToString());
}
public virtual void WriteValue(TimeSpan value)
{
WriteString(XmlConvert.ToString(value));
}
public virtual void WriteValue(IStreamProvider value)
{
ArgumentNullException.ThrowIfNull(value);
Stream stream = value.GetStream();
if (stream == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.XmlInvalidStream));
int blockSize = 256;
int bytesRead;
byte[] block = new byte[blockSize];
while (true)
{
bytesRead = stream.Read(block, 0, blockSize);
if (bytesRead > 0)
WriteBase64(block, 0, bytesRead);
else
break;
if (blockSize < 65536 && bytesRead == blockSize)
{
blockSize = blockSize * 16;
block = new byte[blockSize];
}
}
value.ReleaseStream(stream);
}
public virtual Task WriteValueAsync(IStreamProvider value)
{
WriteValue(value);
return Task.CompletedTask;
}
public virtual bool CanCanonicalize
{
get
{
return false;
}
}
public virtual void StartCanonicalization(Stream stream, bool includeComments, string[]? inclusivePrefixes)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
public virtual void EndCanonicalization()
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
private void WriteElementNode(XmlDictionaryReader reader, bool defattr)
{
XmlDictionaryString? localName;
XmlDictionaryString? namespaceUri;
if (reader.TryGetLocalNameAsDictionaryString(out localName) && reader.TryGetNamespaceUriAsDictionaryString(out namespaceUri))
{
WriteStartElement(reader.Prefix, localName, namespaceUri);
}
else
{
WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
}
if (defattr || !reader.IsDefault)
{
if (reader.MoveToFirstAttribute())
{
do
{
if (reader.TryGetLocalNameAsDictionaryString(out localName) && reader.TryGetNamespaceUriAsDictionaryString(out namespaceUri))
{
WriteStartAttribute(reader.Prefix, localName, namespaceUri);
}
else
{
WriteStartAttribute(reader.Prefix, reader.LocalName, reader.NamespaceURI);
}
while (reader.ReadAttributeValue())
{
if (reader.NodeType == XmlNodeType.EntityReference)
{
WriteEntityRef(reader.Name);
}
else
{
WriteTextNode(reader, true);
}
}
WriteEndAttribute();
}
while (reader.MoveToNextAttribute());
reader.MoveToElement();
}
}
if (reader.IsEmptyElement)
{
WriteEndElement();
}
}
private void WriteArrayNode(XmlDictionaryReader reader, string prefix, string localName, string namespaceUri, Type type)
{
if (type == typeof(bool))
BooleanArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(short))
Int16ArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(int))
Int32ArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(long))
Int64ArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(float))
SingleArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(double))
DoubleArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(decimal))
DecimalArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(DateTime))
DateTimeArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(Guid))
GuidArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(TimeSpan))
TimeSpanArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else
{
WriteElementNode(reader, false);
reader.Read();
}
}
private void WriteArrayNode(XmlDictionaryReader reader, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Type type)
{
if (type == typeof(bool))
BooleanArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(short))
Int16ArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(int))
Int32ArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(long))
Int64ArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(float))
SingleArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(double))
DoubleArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(decimal))
DecimalArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(DateTime))
DateTimeArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(Guid))
GuidArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(TimeSpan))
TimeSpanArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else
{
WriteElementNode(reader, false);
reader.Read();
}
}
private void WriteArrayNode(XmlDictionaryReader reader, Type type)
{
XmlDictionaryString? localName;
XmlDictionaryString? namespaceUri;
if (reader.TryGetLocalNameAsDictionaryString(out localName) && reader.TryGetNamespaceUriAsDictionaryString(out namespaceUri))
WriteArrayNode(reader, reader.Prefix, localName, namespaceUri, type);
else
WriteArrayNode(reader, reader.Prefix, reader.LocalName, reader.NamespaceURI, type);
}
protected virtual void WriteTextNode(XmlDictionaryReader reader, bool isAttribute)
{
XmlDictionaryString? value;
if (reader.TryGetValueAsDictionaryString(out value))
{
WriteString(value);
}
else
{
WriteString(reader.Value);
}
if (!isAttribute)
{
reader.Read();
}
}
public override void WriteNode(XmlReader reader, bool defattr)
{
XmlDictionaryReader? dictionaryReader = reader as XmlDictionaryReader;
if (dictionaryReader != null)
WriteNode(dictionaryReader, defattr);
else
base.WriteNode(reader, defattr);
}
public virtual void WriteNode(XmlDictionaryReader reader, bool defattr)
{
ArgumentNullException.ThrowIfNull(reader);
int d = (reader.NodeType == XmlNodeType.None ? -1 : reader.Depth);
do
{
XmlNodeType nodeType = reader.NodeType;
Type? type;
if (nodeType == XmlNodeType.Text || nodeType == XmlNodeType.Whitespace || nodeType == XmlNodeType.SignificantWhitespace)
{
// This will advance if necessary, so we don't need to call Read() explicitly
WriteTextNode(reader, false);
}
else if (reader.Depth > d && reader.IsStartArray(out type))
{
WriteArrayNode(reader, type);
}
else
{
// These will not advance, so we must call Read() explicitly
switch (nodeType)
{
case XmlNodeType.Element:
WriteElementNode(reader, defattr);
break;
case XmlNodeType.CDATA:
WriteCData(reader.Value);
break;
case XmlNodeType.EntityReference:
WriteEntityRef(reader.Name);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
WriteProcessingInstruction(reader.Name, reader.Value);
break;
case XmlNodeType.DocumentType:
WriteDocType(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value);
break;
case XmlNodeType.Comment:
WriteComment(reader.Value);
break;
case XmlNodeType.EndElement:
WriteFullEndElement();
break;
}
if (!reader.Read())
break;
}
}
while (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement));
}
private static void CheckArray(Array array, int offset, int count)
{
ArgumentNullException.ThrowIfNull(array);
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > array.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, array.Length)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > array.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, array.Length - offset)));
}
// bool
public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, bool[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, bool[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Int16
public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, short[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, short[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Int32
public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, int[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, int[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Int64
public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, long[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, long[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// float
public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, float[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, float[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// double
public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, double[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, double[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// decimal
public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, decimal[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, decimal[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// DateTime
public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, DateTime[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, DateTime[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Guid
public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, Guid[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, Guid[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// TimeSpan
public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, TimeSpan[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, TimeSpan[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
protected override void Dispose(bool disposing)
{
if (disposing && WriteState != WriteState.Closed)
{
Close();
}
}
public override void Close() { }
private sealed class XmlWrappedWriter : XmlDictionaryWriter
{
private readonly XmlWriter _writer;
private int _depth;
private int _prefix;
public XmlWrappedWriter(XmlWriter writer)
{
_writer = writer;
_depth = 0;
}
public override void Close()
{
_writer.Dispose();
}
public override void Flush()
{
_writer.Flush();
}
public override string? LookupPrefix(string namespaceUri)
{
return _writer.LookupPrefix(namespaceUri);
}
public override void WriteAttributes(XmlReader reader, bool defattr)
{
_writer.WriteAttributes(reader, defattr);
}
public override void WriteBase64(byte[] buffer, int index, int count)
{
_writer.WriteBase64(buffer, index, count);
}
public override void WriteBinHex(byte[] buffer, int index, int count)
{
_writer.WriteBinHex(buffer, index, count);
}
public override void WriteCData(string? text)
{
_writer.WriteCData(text);
}
public override void WriteCharEntity(char ch)
{
_writer.WriteCharEntity(ch);
}
public override void WriteChars(char[] buffer, int index, int count)
{
_writer.WriteChars(buffer, index, count);
}
public override void WriteComment(string? text)
{
_writer.WriteComment(text);
}
public override void WriteDocType(string name, string? pubid, string? sysid, string? subset)
{
_writer.WriteDocType(name, pubid, sysid, subset);
}
public override void WriteEndAttribute()
{
_writer.WriteEndAttribute();
}
public override void WriteEndDocument()
{
_writer.WriteEndDocument();
}
public override void WriteEndElement()
{
_writer.WriteEndElement();
_depth--;
}
public override void WriteEntityRef(string name)
{
_writer.WriteEntityRef(name);
}
public override void WriteFullEndElement()
{
_writer.WriteFullEndElement();
}
public override void WriteName(string name)
{
_writer.WriteName(name);
}
public override void WriteNmToken(string name)
{
_writer.WriteNmToken(name);
}
public override void WriteNode(XmlReader reader, bool defattr)
{
_writer.WriteNode(reader, defattr);
}
public override void WriteProcessingInstruction(string name, string? text)
{
_writer.WriteProcessingInstruction(name, text);
}
public override void WriteQualifiedName(string localName, string? namespaceUri)
{
_writer.WriteQualifiedName(localName, namespaceUri);
}
public override void WriteRaw(char[] buffer, int index, int count)
{
_writer.WriteRaw(buffer, index, count);
}
public override void WriteRaw(string data)
{
_writer.WriteRaw(data);
}
public override void WriteStartAttribute(string? prefix, string localName, string? namespaceUri)
{
_writer.WriteStartAttribute(prefix, localName, namespaceUri);
_prefix++;
}
public override void WriteStartDocument()
{
_writer.WriteStartDocument();
}
public override void WriteStartDocument(bool standalone)
{
_writer.WriteStartDocument(standalone);
}
public override void WriteStartElement(string? prefix, string localName, string? namespaceUri)
{
_writer.WriteStartElement(prefix, localName, namespaceUri);
_depth++;
_prefix = 1;
}
public override WriteState WriteState
{
get
{
return _writer.WriteState;
}
}
public override void WriteString(string? text)
{
_writer.WriteString(text);
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
_writer.WriteSurrogateCharEntity(lowChar, highChar);
}
public override void WriteWhitespace(string? whitespace)
{
_writer.WriteWhitespace(whitespace);
}
public override void WriteValue(object value)
{
_writer.WriteValue(value);
}
public override void WriteValue(string? value)
{
_writer.WriteValue(value);
}
public override void WriteValue(bool value)
{
_writer.WriteValue(value);
}
public override void WriteValue(DateTimeOffset value)
{
_writer.WriteValue(value);
}
public override void WriteValue(double value)
{
_writer.WriteValue(value);
}
public override void WriteValue(int value)
{
_writer.WriteValue(value);
}
public override void WriteValue(long value)
{
_writer.WriteValue(value);
}
public override void WriteXmlnsAttribute(string? prefix, string namespaceUri)
{
ArgumentNullException.ThrowIfNull(namespaceUri);
if (prefix == null)
{
if (LookupPrefix(namespaceUri) != null)
return;
if (namespaceUri.Length == 0)
{
prefix = string.Empty;
}
else
{
string depthStr = _depth.ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
string prefixStr = _prefix.ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
prefix = string.Concat("d", depthStr, "p", prefixStr);
}
}
WriteAttributeString("xmlns", prefix, null, namespaceUri);
}
public override string? XmlLang
{
get
{
return _writer.XmlLang;
}
}
public override XmlSpace XmlSpace
{
get
{
return _writer.XmlSpace;
}
}
}
}
}
| 39.37486 | 221 | 0.57726 | [
"MIT"
] | Ali-YousefiTelori/runtime | src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs | 35,083 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace TestApi
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseIISPlatformHandler();
app.UseStaticFiles();
app.UseMvc();
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
}
| 31.18 | 109 | 0.657473 | [
"MIT"
] | adamstephensen/test-api-publish-1221 | TestApi/Startup.cs | 1,561 | C# |
using System.Net.Mime;
using System.Threading.Tasks;
using Amazon.DynamoDBv2.DataModel;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NUlid;
using Portfolio.Api.Infrastructure.Database.DataModel.Posts;
using Portfolio.Api.Models.Posts;
using System.Linq;
using Portfolio.Api.Infrastructure.Serialization.Posts;
using Portfolio.Api.Features.Posts;
using Portfolio.Api.Infrastructure.Serialization.Users;
using Portfolio.Api.Features.Users;
using Portfolio.Api.Infrastructure.Database.DataModel.Categories;
using System.Collections.Generic;
using Portfolio.Api.Infrastructure.Serialization.Categories;
using Microsoft.AspNetCore.Authorization;
namespace Portfolio.Api.Controllers
{
[Route("Posts")]
public class PostsController : Controller
{
private readonly IDynamoDBContext _dbContext;
public PostsController(IDynamoDBContext dbContext)
{
_dbContext = dbContext;
}
const string UserId = "01FPSM8KW4ZPRS2K7JJHM3WSJZ";
const string UserEmail = "paulo.prsdesouza@gmail.com";
/// <summary>
/// Get posts from Anonymous Request.
/// </summary>
/// <remarks>
/// Get registered posts.
/// </remarks>
[HttpGet, Route("published"), AllowAnonymous]
[Produces(MediaTypeNames.Application.Json)]
[ProducesResponseType(typeof(GetPostResponse), StatusCodes.Status200OK)]
public async Task<ActionResult> ListPublished([FromQuery] GetPostsQuery queryString)
{
var query = new PostQuery();
query.BeforePost = queryString.Before ?? Ulid.NewUlid();
query.Status = "P";
query.Title = queryString.Title;
query.Length = queryString.Length ?? 30;
query.CategoryId = queryString.CategoryId;
var userSearch = new UserSearch(_dbContext);
var user = await userSearch.Find(UserEmail);
var posts = await _dbContext
.FromQueryAsync<Post>(query.ToDynamoDBQuery())
.GetRemainingAsync();
IEnumerable<PostResponse> postsResponse = posts.Select(post => post.MapToResponse()).ToList();
foreach (var post in postsResponse)
{
post.PostedBy = user.MapToResponse();
};
return Ok(new GetPostResponse
{
Posts = postsResponse
});
}
/// <summary>
/// Get posts.
/// </summary>
/// <remarks>
/// Get registered posts.
/// </remarks>
[HttpGet]
[Produces(MediaTypeNames.Application.Json)]
[ProducesResponseType(typeof(GetPostResponse), StatusCodes.Status200OK)]
public async Task<ActionResult> List([FromQuery] GetPostsQuery queryString)
{
var query = new PostQuery();
query.BeforePost = queryString.Before ?? Ulid.NewUlid();
query.Status = queryString.Status;
query.Length = queryString.Length ?? 30;
query.CategoryId = queryString.CategoryId;
var userSearch = new UserSearch(_dbContext);
var user = await userSearch.Find(UserEmail);
var posts = await _dbContext
.FromQueryAsync<Post>(query.ToDynamoDBQuery())
.GetRemainingAsync();
IEnumerable<PostResponse> postsResponse = posts.Select(post => post.MapToResponse()).ToList();
foreach (var post in postsResponse)
{
post.PostedBy = user.MapToResponse();
};
return Ok(new GetPostResponse
{
Posts = postsResponse
});
}
/// <summary>
/// Create a post.
/// </summary>
/// <remarks>
/// Save a post.
/// </remarks>
[HttpPost]
[Produces(MediaTypeNames.Application.Json)]
[ProducesResponseType(typeof(PostResponse), StatusCodes.Status200OK)]
public async Task<ActionResult> Create([FromBody] PostRequest postRequest)
{
var createPost = new CreatePost(_dbContext);
var post = postRequest.ToPost();
await createPost.Register(UserId, UserEmail, post);
return Ok(post.MapToResponse());
}
/// <summary>
/// Update a post.
/// </summary>
/// <remarks>
/// Update a post already registered.
/// </remarks>
/// <param name="postId" example="01FME0F949HAVJ91A9100N16ZS">Posts's ID</param>
/// <param name="putPostRequest">Posts's content</param>
[HttpPut, Route("{postId}")]
[Produces(MediaTypeNames.Application.Json)]
[ProducesResponseType(typeof(PostResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(PostNotFoundError), StatusCodes.Status404NotFound)]
public async Task<ActionResult> Update([FromRoute] Ulid postId, [FromBody] PutPostRequest putPostRequest)
{
var postSearch = new PostSearch(_dbContext);
var post = await postSearch.Find(postId);
if (postSearch.PostNotFound)
{
return NotFound(new PostNotFoundError(postId.ToString()));
}
putPostRequest.MapTo(post);
var postUpdate = new PostUpdate(_dbContext);
await postUpdate.Update(post);
return Ok(post.MapToResponse());
}
/// <summary>
/// Update views of a post.
/// </summary>
/// <remarks>
/// Update a post already registered.
/// </remarks>
/// <param name="postId" example="01FME0F949HAVJ91A9100N16ZS">Post's ID</param>
[HttpPut, Route("views/{postId}"), AllowAnonymous]
[Produces(MediaTypeNames.Application.Json)]
[ProducesResponseType(typeof(PostResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(PostNotFoundError), StatusCodes.Status404NotFound)]
public async Task<ActionResult> UpdateViews([FromRoute] Ulid postId)
{
var postSearch = new PostSearch(_dbContext);
var post = await postSearch.Find(postId);
if (postSearch.PostNotFound)
{
return NotFound(new PostNotFoundError(postId.ToString()));
}
var views = int.Parse(post.Views) + 1;
post.Views = views.ToString();
var postUpdate = new PostUpdate(_dbContext);
await postUpdate.Update(post);
return Ok(post.MapToResponse());
}
/// <summary>
/// Find a post.
/// </summary>
/// <remarks>
/// Find a post already registerd.
/// </remarks>
/// <param name="postId" example="01FME0F949HAVJ91A9100N16ZS">Posts's ID</param>
[HttpGet, Route("{postId}"), AllowAnonymous]
[Produces(MediaTypeNames.Application.Json)]
[ProducesResponseType(typeof(PostResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(PostNotFoundError), StatusCodes.Status404NotFound)]
public async Task<ActionResult> Find([FromRoute] Ulid postId)
{
var postSearch = new PostSearch(_dbContext);
var post = await postSearch.Find(postId);
if (postSearch.PostNotFound)
{
return NotFound(new PostNotFoundError(postId.ToString()));
}
var userSearch = new UserSearch(_dbContext);
var user = await userSearch.Find(UserEmail);
var query = new CategoryQuery();
var categories = await _dbContext
.FromQueryAsync<Category>(query.ToDynamoDBQuery())
.GetRemainingAsync();
PostResponse postResponse = post.MapToResponse();
postResponse.PostedBy = user.MapToResponse();
postResponse.Category = categories
.Where(category => category.Id.ToString() == post.CategoryId)
.FirstOrDefault()
.MapToResponse();
return Ok(postResponse);
}
/// <summary>
/// Delete a post.
/// </summary>
/// <remarks>
/// Delete a post already registered.
/// </remarks>
/// <param name="postId" example="01FME0F949HAVJ91A9100N16ZS">Posts's ID</param>
[HttpDelete, Route("{postId}")]
[Produces(MediaTypeNames.Application.Json)]
[ProducesResponseType(typeof(PostResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(PostNotFoundError), StatusCodes.Status404NotFound)]
public async Task<ActionResult> Delete([FromRoute] Ulid postId)
{
var postSearch = new PostSearch(_dbContext);
var post = await postSearch.Find(postId);
if (postSearch.PostNotFound)
{
return NotFound(new PostNotFoundError(postId.ToString()));
}
var postDelete = new DeletePost(_dbContext);
await postDelete.Delete(post);
return Ok(post.MapToResponse());
}
}
}
| 36.082031 | 113 | 0.597164 | [
"MIT"
] | pauloprsdesouza/personal-portfolio-api | src/Portfolio.Api/Controllers/PostsController.cs | 9,237 | C# |
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Threading.Tasks;
using Docker.DotNet.Models;
namespace DockerTestHelpers
{
public class SqlServerContainer : DockerServer
{
private readonly int _port;
private string _password;
public SqlServerContainer(string containerName, int port = 1434, string password = "P@55w0rd") : base("microsoft/mssql-server-linux:latest", containerName)
{
_port = port;
ConnectionString = $"Server=localhost,{port};User Id=sa;Password={password};Timeout=5";
_password = password;
}
public string ConnectionString { get; }
protected override async Task<bool> isReady()
{
try
{
using (var conn = new SqlConnection(ConnectionString))
{
await conn.OpenAsync();
return true;
}
}
catch (Exception)
{
return false;
}
}
public override HostConfig ToHostConfig()
{
return new HostConfig
{
PortBindings = new Dictionary<string, IList<PortBinding>>
{
{
"1433/tcp",
new List<PortBinding>
{
new PortBinding
{
HostPort = _port.ToString(),
HostIP = "127.0.0.1"
}
}
},
},
};
}
public override Config ToConfig()
{
return new Config
{
Env = new List<string> { "ACCEPT_EULA=Y", $"SA_PASSWORD={_password}", "MSSQL_PID=Developer" }
};
}
}
}
| 28.253521 | 163 | 0.459621 | [
"MIT"
] | JasperFx/DockerTestHelpers | src/DockerTestHelpers/SqlServerContainer.cs | 2,008 | C# |
using System;
using System.Windows;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI.Events;
using System.Windows.Forms;
using RvtDialogs;
namespace RvtElectrical
{
[TransactionAttribute(TransactionMode.Manual)]
public class CmdFPParamAssoc : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
//Get UIDocument
UIDocument uidoc = commandData.Application.ActiveUIDocument;
Document doc = uidoc.Document;
bool isValidPlate = true;
if (!doc.IsFamilyDocument)
{
TaskDialog.Show("Document Error", "Command only availabLe in Family Editor");
return Result.Failed;
}
try
{
//Get FamilyManager
FamilyManager fm = doc.FamilyManager;
//Store Local Variables
string famDeviceBox = "Device Box";
string concatDeviceCode = "";
string concatPlateCode = "";
//GET SYSTEM CODE and TEMPLATE CLASSIFICATION INFORMATION
//Get System Code
DeviceId templateDeviceId = FamilyUtils.GetTemplateSystemCode(fm);
if (templateDeviceId.System == 0)
{
TaskDialog.Show("Template Family Error", "The family document is not compatible with this routine. " +
"Ensure you are using the correct template");
return Result.Failed;
}
string SystemCode = templateDeviceId.SystemCode.ToString();
//Get Box Classifcation Code
string boxClassCode = FamilyUtils.GetTemplateBoxClassificationCode(fm);
if (boxClassCode == null)
isValidPlate = false;
//Determine if template should apply distinct numbers to connectors
bool isConnectSetPosition = FamilyUtils.IsSetConnectorPosition(boxClassCode);
//GET ELEMENTS IN FAMILY BUILDER
//Create Filtered Element Collector & Filter for Electrical Fixtures
FilteredElementCollector collector = new FilteredElementCollector(doc);
ElementQuickFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_ElectricalFixtures);
//Apply Filter
IList<Element> devices = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements();
//Locate Device Box(es) Family
//List<Element> deviceBoxes = new List<Element>();
IList<Element> deviceBoxes = devices
.Where(d => d.get_Parameter(TCCElecSettings.BackboxCodeGuid) != null)
.ToList();
//Locate the visible Connector Families
//Visibility filters out CS connectors
IList<Element> deviceConnectorElements = devices
.Where(d => d.get_Parameter(TCCElecSettings.BoxIdGuid) != null)
.Where(d => d.get_Parameter(TCCElecSettings.DeviceIdGuid) != null)
.Where(d => d.get_Parameter(BuiltInParameter.IS_VISIBLE_PARAM).AsInteger() != 0)
.ToList();
//Filter out only connectors that can be associated using the BoxID parameter
//(Eliminates embedded family connectors)
List<Element> filteredDeviceConnectorElements = new List<Element>();
foreach (Element deviceConnectorElement in deviceConnectorElements)
{
Parameter boxIdParam = deviceConnectorElement.get_Parameter(TCCElecSettings.BoxIdGuid);
if (doc.FamilyManager.CanElementParameterBeAssociated(boxIdParam))
filteredDeviceConnectorElements.Add(deviceConnectorElement);
}
//Create a list of Conector Devices from Elements
deviceConnectorElements = filteredDeviceConnectorElements;
List<DeviceConnector> deviceConnectors = new List<DeviceConnector>();
foreach(Element filteredDeviceConnectorElement in filteredDeviceConnectorElements)
{
deviceConnectors.Add(new DeviceConnector(filteredDeviceConnectorElement, "", doc));
}
//Get all Family Parameters in Family
List<FamilyParameter> famParams = (from FamilyParameter fp in doc.FamilyManager.Parameters select fp).ToList();
using (Transaction trans = new Transaction(doc, "Map Parameters"))
{
trans.Start();
//DEVICE BOX PARAMETER MAPPING
foreach (Element db in deviceBoxes)
{
//Get all Parameters in Devicebox
List<Parameter> deviceBoxParams = (from Parameter p in db.Parameters select p).ToList();
//Associate Device Box Parameters
FamilyUtils.AssociateParameters(deviceBoxParams, famParams, doc);
}
//DEVICE CONNECTOR PARAMETER MAPPING
int i = 1;
int j = 1;
foreach (Element deviceConnectorElement in deviceConnectorElements)
{
//Get all Parameters in Devicebox
List<Parameter> deviceConnectorParams = (from Parameter p in deviceConnectorElement.Parameters select p).ToList();
//Associate Connector Parameters
FamilyUtils.AssociateParameters(deviceConnectorParams, famParams, doc);
//Set the connector position
if (isConnectSetPosition)
{
//Associate Connector Positions
Parameter connectPosParam = deviceConnectorElement.get_Parameter(TCCElecSettings.ConnectorPositionGuid);
if (!connectPosParam.IsReadOnly)
{
if (doc.FamilyManager.GetAssociatedFamilyParameter(connectPosParam) != null)
doc.FamilyManager.AssociateElementParameterToFamilyParameter(connectPosParam, null);
connectPosParam.Set(i);
i++;
}
//Associate Sub Connector Positions
Parameter subconnectPosParam = deviceConnectorElement.get_Parameter(TCCElecSettings.ConnectorSubPositionGuid);
if (!subconnectPosParam.IsReadOnly)
{
if (doc.FamilyManager.GetAssociatedFamilyParameter(subconnectPosParam) != null)
doc.FamilyManager.AssociateElementParameterToFamilyParameter(subconnectPosParam, null);
subconnectPosParam.Set(j);
j++;
}
}
}
trans.Commit();
}
//Set Required Parameters from underlying connectors
using (Transaction trans = new Transaction(doc, "Update Plate Parameters"))
{
trans.Start();
// If a power connector exists, set the Has Power = true
bool hasPower = false;
bool isIG = false;
foreach(DeviceConnector connector in deviceConnectors)
{
if ((connector.DeviceId.Voltage != Voltage.LowVoltage) && (connector.DeviceId.Voltage != Voltage.MixedVoltage))
hasPower = true;
ElementId eid = connector.Connector.GetTypeId();
var ConnectorType = doc.GetElement(connector.Connector.GetTypeId());
if(ConnectorType.get_Parameter(TCCElecSettings.IsIGGuid) != null)
{
var param = ConnectorType.get_Parameter(TCCElecSettings.IsIGGuid);
if (param.AsInteger() == 1)
{
isIG = true;
}
}
}
foreach(FamilyParameter param in famParams)
{
if ((param.IsShared) && (param.GUID == TCCElecSettings.HasPowerGuid))
if (hasPower)
doc.FamilyManager.SetFormula(param, "1=1");
else
{
doc.FamilyManager.SetFormula(param, "1=0");
doc.FamilyManager.SetFormula(param, null);
}
if ((param.IsShared) && (param.GUID == TCCElecSettings.IsIGGuid))
if (isIG)
doc.FamilyManager.SetFormula(param, "1=1");
else
{
doc.FamilyManager.SetFormula(param, "1=0");
doc.FamilyManager.SetFormula(param, null);
}
}
trans.Commit();
}
if (isValidPlate)
{
//FAMILY CODE CREATION
using (Transaction trans = new Transaction(doc, "Map Parameters"))
{
trans.Start();
try
{
//Get connector group series codes
// Get distinct group connectors and sort
List<DeviceConnector> distinctDeviceConnectors = deviceConnectors
.GroupBy(dc => dc.ConnectorGroupCode)
.Select(d => d.First())
.OrderBy(o => o.ConnectorGroupCode)
.ToList();
// Set Has Power and Has Low Voltage equal to false
bool hasPower = false;
//bool hasLowVoltage = false;
//Sort connectors with power connectors first
List<DeviceConnector> sortedDeviceConnectors = new List<DeviceConnector>();
List<DeviceConnector> noPowerDeviceConnectors = new List<DeviceConnector>();
foreach (DeviceConnector ddc in distinctDeviceConnectors)
{
if (ddc.DeviceId.Voltage != Voltage.LowVoltage)
sortedDeviceConnectors.Add(ddc);
else
noPowerDeviceConnectors.Add(ddc);
}
//Check if any have power or low voltage to determine box classification
if (sortedDeviceConnectors.Count() > 0)
hasPower = true;
//if (noPowerDeviceConnectors.Count() > 0)
// hasLowVoltage = true;
sortedDeviceConnectors.AddRange(noPowerDeviceConnectors);
//Create Group Series Code String
string groupSeriesCodes = "";
foreach (DeviceConnector sortedDeviceConnector in sortedDeviceConnectors)
{
int count = deviceConnectors.Where(c => c.ConnectorGroupCode.Equals(sortedDeviceConnector.ConnectorGroupCode))
.Select(c => c)
.Count();
groupSeriesCodes = groupSeriesCodes + sortedDeviceConnector.ConnectorGroupCode + count.ToString();
}
//Box Type Classification Code
//If this is a type of DEvice Box, then
//Determine if this is a Power, Control, or Universal Box
string plateClassCode = "";
if (FamilyUtils.IsDeviceBox(boxClassCode))
{
FamilyParameter BoxClassificationCodeParam = doc.FamilyManager.get_Parameter(TCCElecSettings.BoxClassificationCode);
//Get Box and Plate Classification Codes
if (sortedDeviceConnectors.Count() > 1)
{
boxClassCode = "UB";
plateClassCode = "U";
}
else if (hasPower)
{
boxClassCode = "PB";
plateClassCode = sortedDeviceConnectors[0].ConnectorGroupCode;
plateClassCode = plateClassCode[0].ToString();
}
else
{
boxClassCode = "CB";
plateClassCode = sortedDeviceConnectors[0].ConnectorGroupCode;
plateClassCode = plateClassCode[0].ToString();
}
//Assign Box Classification Code
doc.FamilyManager.SetFormula(BoxClassificationCodeParam, "\"" + boxClassCode + "\"");
}
else
{
plateClassCode = FamilyUtils.getPlateClassCode(boxClassCode);
}
//Get Backbox Code
//First check if Connector strip, and if so, apply C and length
string boxCode = "";
if (boxClassCode == "CS")
{
double? csLength = FamilyUtils.GetTemplateCSLength(fm);
boxCode = Math.Floor(Convert.ToDouble(csLength)).ToString() + "C";
//TRANSFER BOX SIZE TO FAMILY
FamilyParameter famBoxSizeParam = doc.FamilyManager.get_Parameter(TCCElecSettings.BackboxSizeGuid);
string boxSize = "\"" + csLength.ToString() + "' Long" + "\"";
doc.FamilyManager.SetFormula(famBoxSizeParam, boxSize);
}
else
{
if (deviceBoxes.Count == 0)
{
TaskDialog.Show("Device Box Error", "There are no compatible device boxes in the family. Family name cannot be created. Exiting.");
trans.Commit();
return Result.Succeeded;
}
if (deviceBoxes.Count > 1)
{
TaskDialog.Show("Device Box Warning", "WARNING - Multiple device boxes are in the family. " +
"Association may not work correctly. Verify family.");
}
ElementId boxTypeId = deviceBoxes[0].GetTypeId();
ElementType boxType = doc.GetElement(boxTypeId) as ElementType;
boxCode = boxType.get_Parameter(TCCElecSettings.BackboxCodeGuid).AsString();
//TRANSFER BOX SIZE TO FAMILY
FamilyParameter famBoxSizeParam = doc.FamilyManager.get_Parameter(TCCElecSettings.BackboxSizeGuid);
string boxSize = boxType.get_Parameter(TCCElecSettings.BackboxSizeGuid).AsString();
boxSize = "\"" + boxSize + "\"";
doc.FamilyManager.SetFormula(famBoxSizeParam, boxSize);
}
//Create the concatenated device code
concatDeviceCode = SystemCode + "-" + boxClassCode + "-" +
groupSeriesCodes + "-" + boxCode;
string concatParamDeviceCode = "\"" + concatDeviceCode + "\"";
//Assign to family parameter
FamilyParameter famNameCodeParam = doc.FamilyManager.get_Parameter(TCCElecSettings.PlateFamilyCodeGuid);
doc.FamilyManager.SetFormula(famNameCodeParam, concatParamDeviceCode);
//CREATE BOX CODE
string plateThirdDigit = "";
if (plateClassCode == "U")
{
for (int j = 0; j < 2; j++)
{
if (boxCode[j].ToString() != "G")
plateThirdDigit += boxCode[j];
}
}
else if (plateClassCode == "C")
{
int count = deviceConnectors.Where(c => c.DeviceId.Voltage != Voltage.LowVoltage)
.Select(c => c)
.Count();
plateThirdDigit = count.ToString();
}
else
{
plateThirdDigit = deviceConnectors.Count().ToString();
}
string plateFourthDigit = "";
if (plateClassCode == "U" || plateClassCode == "S")
{
PlateNumDialog win = new PlateNumDialog();
win.SizeToContent = SizeToContent.WidthAndHeight;
win.ShowDialog();
plateFourthDigit = win.returnValue;
}
concatPlateCode = concatPlateCode + SystemCode +
plateClassCode +
plateThirdDigit +
plateFourthDigit;
string concatParamPlateCode = "\"" + concatPlateCode + "\"";
//Add Plate code to front of device code
concatDeviceCode = "(" + concatPlateCode + ") " + concatDeviceCode;
//Assign to family parameter
FamilyParameter famPlateCodeParam = doc.FamilyManager.get_Parameter(TCCElecSettings.PlateCodeGuid);
doc.FamilyManager.SetFormula(famPlateCodeParam, concatParamPlateCode);
//Copy Family Name Code to Clipboard
System.Windows.Forms.Clipboard.SetText(concatDeviceCode);
trans.Commit();
if (TaskDialog.Show("Command Succeeded", "Parameters Association Complete" + Environment.NewLine +
"Family Device Code: " + concatDeviceCode + Environment.NewLine +
"Plate Code: " + concatPlateCode + Environment.NewLine +
"Family Device Code has been copied to clipboard." + Environment.NewLine +
"Press <ctl>V to paste in the file name" + Environment.NewLine + Environment.NewLine +
"Save File? ", TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No) == TaskDialogResult.Yes)
uidoc.SaveAs();
}
catch
{
TaskDialog.Show("Plate Code Creation Error", "Error Creating Plate Code. \n Please manually enter");
trans.Commit();
}
}
}
return Result.Succeeded;
}
catch (Exception ex)
{
UIUtils.EBSGenException(ex);
return Result.Failed;
}
}
}
}
| 48.351351 | 169 | 0.463946 | [
"MIT"
] | jtprichard/RvtTCC2020 | RvtElectrical/CmdFPParamAssoc.cs | 21,470 | C# |
using DL.Entities.Base;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace DL.Entities
{
public class Degree : BaseEntity
{
[Required]
public string Name { get; set; }
public ICollection<Scientist> Scientists { get; set; } = new List<Scientist>();
}
}
| 22 | 87 | 0.672727 | [
"MIT"
] | OlehTymoshenko/Diploma-API | Diploma/DL.Entities/Degree.cs | 332 | C# |
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using Microsoft.Xaml.Interactivity;
using Windows.UI.Xaml.Controls;
using AppContainerUITestMethod = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.AppContainer.UITestMethodAttribute;
namespace ManagedUnitTests
{
[TestClass]
public class InteractionTest
{
[AppContainerUITestMethod]
public void SetBehaviors_MultipleBehaviors_AllAttached()
{
BehaviorCollection behaviorCollection = new BehaviorCollection();
behaviorCollection.Add(new StubBehavior());
behaviorCollection.Add(new StubBehavior());
behaviorCollection.Add(new StubBehavior());
Button button = new Button();
Interaction.SetBehaviors(button, behaviorCollection);
foreach (StubBehavior behavior in behaviorCollection)
{
Assert.AreEqual(1, behavior.AttachCount, "Should only have called Attach once.");
Assert.AreEqual(0, behavior.DetachCount, "Should not have called Detach.");
Assert.AreEqual(button, behavior.AssociatedObject, "Should be attached to the host of the BehaviorCollection.");
}
}
[AppContainerUITestMethod]
public void SetBehaviors_MultipleSets_DoesNotReattach()
{
BehaviorCollection behaviorCollection = new BehaviorCollection() { new StubBehavior() };
Button button = new Button();
Interaction.SetBehaviors(button, behaviorCollection);
Interaction.SetBehaviors(button, behaviorCollection);
foreach (StubBehavior behavior in behaviorCollection)
{
Assert.AreEqual(1, behavior.AttachCount, "Should only have called Attach once.");
}
}
[AppContainerUITestMethod]
public void SetBehaviors_CollectionThenNull_DeatchCollection()
{
BehaviorCollection behaviorCollection = new BehaviorCollection() { new StubBehavior() };
Button button = new Button();
Interaction.SetBehaviors(button, behaviorCollection);
Interaction.SetBehaviors(button, null);
foreach (StubBehavior behavior in behaviorCollection)
{
Assert.AreEqual(1, behavior.DetachCount, "Should only have called Detach once.");
Assert.IsNull(behavior.AssociatedObject, "AssociatedObject should be null after Detach.");
}
}
[AppContainerUITestMethod]
public void SetBehaviors_NullThenNull_NoOp()
{
// As long as this doesn't crash/assert, we're good.
Button button = new Button();
Interaction.SetBehaviors(button, null);
Interaction.SetBehaviors(button, null);
Interaction.SetBehaviors(button, null);
}
[AppContainerUITestMethod]
public void SetBehaviors_ManualDetachThenNull_DoesNotDoubleDetach()
{
BehaviorCollection behaviorCollection = new BehaviorCollection();
behaviorCollection.Add(new StubBehavior());
behaviorCollection.Add(new StubBehavior());
behaviorCollection.Add(new StubBehavior());
Button button = new Button();
Interaction.SetBehaviors(button, behaviorCollection);
foreach (StubBehavior behavior in behaviorCollection)
{
behavior.Detach();
}
Interaction.SetBehaviors(button, null);
foreach (StubBehavior behavior in behaviorCollection)
{
Assert.AreEqual(1, behavior.DetachCount, "Setting BehaviorCollection to null should not call Detach on already Detached Behaviors.");
Assert.IsNull(behavior.AssociatedObject, "AssociatedObject should be null after Detach.");
}
}
[AppContainerUITestMethod]
public void ExecuteActions_NullParameters_ReturnsEmptyEnumerable()
{
// Mostly just want to test that this doesn't throw any exceptions.
IEnumerable<object> result = Interaction.ExecuteActions(null, null, null);
Assert.IsNotNull(result);
Assert.AreEqual(0, result.Count(), "Calling ExecuteActions with a null ActionCollection should return an empty enumerable.");
}
[AppContainerUITestMethod]
public void ExecuteActions_MultipleActions_AllActionsExecuted()
{
ActionCollection actions = new ActionCollection();
actions.Add(new StubAction());
actions.Add(new StubAction());
actions.Add(new StubAction());
Button sender = new Button();
string parameterString = "TestString";
Interaction.ExecuteActions(sender, actions, parameterString);
foreach (StubAction action in actions)
{
Assert.AreEqual(1, action.ExecuteCount, "Each IAction should be executed once.");
Assert.AreEqual(sender, action.Sender, "Sender is passed to the actions.");
Assert.AreEqual(parameterString, action.Parameter, "Parameter is passed to the actions.");
}
}
[AppContainerUITestMethod]
public void ExecuteActions_ActionsWithResults_ResultsInActionOrder()
{
string[] expectedReturnValues = { "A", "B", "C" };
ActionCollection actions = new ActionCollection();
foreach (string returnValue in expectedReturnValues)
{
actions.Add(new StubAction(returnValue));
}
List<object> results = Interaction.ExecuteActions(null, actions, null).ToList();
Assert.AreEqual(expectedReturnValues.Length, results.Count, "Should have the same number of results as IActions.");
for (int resultIndex = 0; resultIndex < results.Count; resultIndex++)
{
Assert.AreEqual(expectedReturnValues[resultIndex], results[resultIndex], "Results should be returned in the order of the actions in the ActionCollection.");
}
}
}
}
| 40.402597 | 172 | 0.643362 | [
"MIT"
] | ajpinedam/Uno.XamlBehaviors | src/BehaviorsSDKManaged/ManagedUnitTests/InteractionTest.cs | 6,224 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Satrabel.OpenBlocks.Token {
public partial class WidgetConfigurator {
/// <summary>
/// lTemplate control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lTemplate;
/// <summary>
/// ddlTemplate control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ddlTemplate;
/// <summary>
/// lFile control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lFile;
/// <summary>
/// ddlFile control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ddlFile;
/// <summary>
/// plField control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label plField;
/// <summary>
/// ddlDataSource control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ddlDataSource;
/// <summary>
/// phConfigurator control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder phConfigurator;
}
}
| 34.443038 | 84 | 0.529952 | [
"MIT"
] | sachatrauwaen/OpenBlocks | Providers/TokenProvider/Widget/WidgetConfigurator.ascx.designer.cs | 2,723 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.ComponentModel.DataAnnotations.Schema;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
namespace Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public class RelationalColumnAttributeConvention : PropertyAttributeConvention<ColumnAttribute>
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public RelationalColumnAttributeConvention([NotNull] IDiagnosticsLogger<DbLoggerCategory.Model> logger)
: base(logger)
{
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override InternalPropertyBuilder Apply(
InternalPropertyBuilder propertyBuilder, ColumnAttribute attribute, MemberInfo clrMember)
{
if (!string.IsNullOrWhiteSpace(attribute.Name))
{
propertyBuilder.Relational(ConfigurationSource.DataAnnotation).HasColumnName(attribute.Name);
}
if (!string.IsNullOrWhiteSpace(attribute.TypeName))
{
propertyBuilder.Relational(ConfigurationSource.DataAnnotation).HasColumnType(attribute.TypeName);
}
return propertyBuilder;
}
}
}
| 49.384615 | 113 | 0.695483 | [
"Apache-2.0"
] | BionStt/EntityFrameworkCore | src/EFCore.Relational/Metadata/Conventions/Internal/RelationalColumnAttributeConvention.cs | 2,568 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("03. Temperature Converter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("03. Temperature Converter")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c75bcc33-4ee6-4a3f-aab1-86c1569496dc")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.459459 | 84 | 0.745608 | [
"MIT"
] | MikeHitrov/SoftUni | C# Basics OOP/3. Static Members Exercises/03. Temperature Converter/Properties/AssemblyInfo.cs | 1,426 | C# |
using JetBrains.Annotations;
using JetBrains.ReSharper.Plugins.FSharp.Psi.Impl.Tree;
using JetBrains.ReSharper.Plugins.FSharp.Psi.Tree;
using JetBrains.ReSharper.Psi.Tree;
using Microsoft.FSharp.Compiler.SourceCodeServices;
namespace JetBrains.ReSharper.Plugins.FSharp.Psi.Impl.DeclaredElement
{
internal class FSharpProperty<TDeclaration> : FSharpPropertyBase<TDeclaration>
where TDeclaration : FSharpDeclarationBase, IFSharpDeclaration, IAccessRightsOwnerDeclaration,
IModifiersOwnerDeclaration
{
public FSharpProperty([NotNull] ITypeMemberDeclaration declaration,
[NotNull] FSharpMemberOrFunctionOrValue mfv) : base(declaration, mfv)
{
}
}
} | 37.666667 | 98 | 0.811209 | [
"Apache-2.0"
] | gitter-badger/fsharp-support | ReSharper.FSharp/src/FSharp.Psi/src/Impl/DeclaredElement/FSharpProperty.cs | 680 | C# |
// -----------------------------------------------------------------------
// <copyright file="GenerationState.cs" company="Steven Kirk">
// Copyright 2013 MIT Licence. See licence.md for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace Avalonia.Controls
{
using System;
using Avalonia.Controls.Primitives;
internal class GenerationState : IDisposable
{
public bool AllowStartAtRealizedItem { get; set; }
public GeneratorDirection Direction { get; set; }
public ItemContainerGenerator Generator { get; set; }
public GeneratorPosition Position { get; set; }
public int Step
{
get { return this.Direction == GeneratorDirection.Forward ? 1 : -1; }
}
public void Dispose()
{
this.Generator.GenerationState = null;
}
}
}
| 27.818182 | 81 | 0.528322 | [
"MIT"
] | RustamGulamov/Avalonia | Avalonia/Controls/GenerationState.cs | 920 | C# |
using System;
using System.Threading;
namespace p2e03
{
class Person
{
public string CI { get; set; }
public string Nombre { get; set; }
public string Email { get; set; }
public string Tel { get; set; }
}
}
| 18 | 42 | 0.571429 | [
"MIT"
] | pollingerMaxi/ingenieria-en-sistemas | programacion-de-redes/practicos/practico-2/src/p2e03/Person.cs | 252 | C# |
namespace AngleSharp.Css.Dom
{
using AngleSharp.Css.Parser;
using System;
using System.IO;
/// <summary>
/// Represents a CSS @keyframe rule.
/// </summary>
sealed class CssKeyframeRule : CssRule, ICssKeyframeRule
{
#region Fields
private readonly CssStyleDeclaration _style;
private IKeyframeSelector _selector;
#endregion
#region ctor
internal CssKeyframeRule(ICssStyleSheet owner)
: base(owner, CssRuleType.Keyframe)
{
_style = new CssStyleDeclaration(this);
}
#endregion
#region Properties
public String KeyText
{
get => _selector?.ToCss();
set => _selector = KeyframeParser.Parse(value);
}
public IKeyframeSelector Key => _selector;
ICssStyleDeclaration ICssKeyframeRule.Style => _style;
public CssStyleDeclaration Style => _style;
#endregion
#region Methods
protected override void ReplaceWith(ICssRule rule)
{
var newRule = (ICssKeyframeRule)rule;
_style.SetDeclarations(newRule.Style);
_selector = newRule.Key;
}
public override void ToCss(TextWriter writer, IStyleFormatter formatter)
{
var block = _style.ToCssBlock(formatter);
writer.Write(formatter.Rule(KeyText, null, block));
}
#endregion
}
}
| 23.285714 | 80 | 0.597137 | [
"MIT"
] | Fraaankes/AngleSharp.Css | src/AngleSharp.Css/Dom/Internal/Rules/CssKeyframeRule.cs | 1,467 | C# |
using UnityEngine;
using System.Collections;
namespace TinyFrameWork
{
public class UILevelItem : MonoBehaviour
{
private UILabel lbLevelName;
private GameObject btnLevelItem;
private int starCount = 0;
void Awake()
{
lbLevelName = GameUtility.FindDeepChild<UILabel>(this.gameObject, "Label");
btnLevelItem = GameUtility.FindDeepChild(this.gameObject, "Icon").gameObject;
UIEventListener.Get(btnLevelItem).onClick = delegate
{
ShowWindowData showData = new ShowWindowData();
ContextDataLevelDetail context = new ContextDataLevelDetail();
context.levelDescription = "Hi Man cool things will be happen.Be busy living or be busy dying. - Fighting for the game world";
context.levelId = 10001;
context.levelName = lbLevelName.text;
context.starCount = starCount;
showData.contextData = context;
UICenterMasterManager.Instance.ShowWindow(WindowID.WindowID_LevelDetail, showData);
};
}
public void SetData(string levelName, int count)
{
lbLevelName.text = levelName;
starCount = count;
}
}
}
| 33.894737 | 142 | 0.615683 | [
"MIT"
] | tinyantstudio/UIFrameWork | Assets/Scripts/DemoExample/Example/UILevel/UILevelItem.cs | 1,290 | C# |
using CoinGram.Common;
using CoinGram.Common.Coinigy;
using InfluxDB.LineProtocol.Client;
using MediatR;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Telegram.Bot;
namespace CoinGram
{
class Program
{
private readonly ILogger<Program> _logger;
private readonly Application _application;
private readonly AppSettings _appSettings;
public Program(ILogger<Program> logger, IOptions<AppSettings> appSettings, Application application)
{
_logger = logger;
_application = application;
_appSettings = appSettings.Value;
}
private async Task RunAsync()
{
_logger.LogInformation($"coingram is starting with version {_appSettings.Version}");
await _application.InitializeAsync();
await _application.RunAsync(CancellationToken.None);
}
static async Task Main(string[] args)
{
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
var serviceProvider = serviceCollection.BuildServiceProvider();
await serviceProvider.GetService<Program>().RunAsync();
Console.ReadLine();
}
private static void ConfigureServices(IServiceCollection serviceCollection)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
.AddJsonFile("appsettings.private.json", optional: true, reloadOnChange: false)
.Build();
var appSettings = configuration.GetSection("Configuration").Get<AppSettings>();
serviceCollection
.AddLogging(builder => builder.SetMinimumLevel(LogLevel.Trace).AddConsole().AddDebug())
.AddOptions()
.Configure<AppSettings>(configuration.GetSection("Configuration"))
.AddSingleton<Program, Program>()
.AddTransient<Application, Application>()
.AddSingleton(new CoinigyApiClient(appSettings.CoinigyApiKey, appSettings.CoinigyApiSecret))
.AddSingleton<ITelegramBotClient>(new TelegramBotClient(appSettings.TelegramApiKey))
.AddSingleton(new LineProtocolClient(new Uri(appSettings.InfluxDbHost), appSettings.InfluxDbDatabase, appSettings.InfluxDbUser, appSettings.InfluxDbPassword))
.AddMediatR(Assembly.GetExecutingAssembly());
}
}
}
| 38.310811 | 174 | 0.670194 | [
"MIT"
] | dennisbappert/coingram | src/Program.cs | 2,837 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Extensions.Hosting;
namespace Microsoft.AspNetCore.TestHost;
internal class NoopHostLifetime : IHostLifetime
{
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
public Task WaitForStartAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
| 24.9 | 71 | 0.751004 | [
"MIT"
] | 3ejki/aspnetcore | src/Hosting/TestHost/src/NoopHostLifetime.cs | 498 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using NBitcoin;
using NBitcoin.BuilderExtensions;
using Stratis.Bitcoin.Configuration;
using Stratis.Bitcoin.Features.Wallet.Interfaces;
using Stratis.Bitcoin.Features.Wallet.Models;
using Stratis.Bitcoin.Utilities;
using Stratis.Bitcoin.Utilities.Extensions;
using TracerAttributes;
[assembly: InternalsVisibleTo("Stratis.Bitcoin.Features.Wallet.Tests")]
[assembly: InternalsVisibleTo("Stratis.Bitcoin.IntegrationTests")]
[assembly: InternalsVisibleTo("Stratis.Bitcoin.IntegrationTests.Common")]
namespace Stratis.Bitcoin.Features.Wallet
{
public class WalletCollection : ICollection<Wallet>
{
public IWalletManager WalletManager { get; set; }
private IWalletRepository repository => this.WalletManager?.WalletRepository;
public int Count => this.GetWallets().Count();
public bool IsReadOnly => true;
private IEnumerable<Wallet> GetWallets()
{
foreach (string walletName in this.repository.GetWalletNames())
{
var wallet = this.repository.GetWallet(walletName);
wallet.WalletManager = this.WalletManager;
yield return wallet;
}
}
public WalletCollection(WalletManager walletManager)
{
this.WalletManager = walletManager;
}
public void Add(Wallet wallet)
{
wallet.WalletManager = this.WalletManager;
}
public void Clear()
{
throw new NotImplementedException();
}
public bool Contains(Wallet wallet)
{
throw new NotImplementedException();
}
public void CopyTo(Wallet[] arr, int index)
{
foreach (Wallet wallet in this.GetWallets())
arr[index++] = wallet;
}
public bool Remove(Wallet wallet)
{
throw new NotImplementedException();
}
public IEnumerator<Wallet> GetEnumerator()
{
return GetWallets().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetWallets().GetEnumerator();
}
}
/// <summary>
/// A manager providing operations on wallets.
/// </summary>
public class WalletManager : IWalletManager
{
/// <summary>Used to get the first account.</summary>
public const string DefaultAccount = "account 0";
// <summary>As per RPC method definition this should be the max allowable expiry duration.</summary>
private const int MaxWalletUnlockDurationInSeconds = 1073741824;
/// <summary>Quantity of accounts created in a wallet file when a wallet is created.</summary>
private const int WalletCreationAccountsCount = 1;
/// <summary>File extension for wallet files.</summary>
private const string WalletFileExtension = "wallet.json";
/// <summary>
/// A lock object that protects access to the <see cref="Wallet"/>.
/// Any of the collections inside Wallet must be synchronized using this lock.
/// </summary>
protected readonly object lockObject;
protected readonly object lockProcess;
public WalletCollection Wallets;
/// <summary>The type of coin used in this manager.</summary>
protected readonly CoinType coinType;
/// <summary>Specification of the network the node runs on - regtest/testnet/mainnet.</summary>
protected readonly Network network;
/// <summary>The chain of headers.</summary>
protected readonly ChainIndexer ChainIndexer;
/// <summary>Instance logger.</summary>
private readonly ILogger logger;
/// <summary>An object capable of storing <see cref="Wallet"/>s to the file system.</summary>
private readonly FileStorage<Wallet> fileStorage;
/// <summary>Provider of time functions.</summary>
private readonly IDateTimeProvider dateTimeProvider;
/// <summary>The settings for the wallet feature.</summary>
private readonly WalletSettings walletSettings;
/// <summary>The private key cache for unlocked wallets.</summary>
private readonly MemoryCache privateKeyCache;
internal bool ExcludeTransactionsFromWalletImports { get; set; }
public IWalletRepository WalletRepository { get; private set; }
public uint256 WalletTipHash => this.WalletCommonTip(this.ChainIndexer.Tip)?.HashBlock ?? 0;
public int WalletTipHeight => this.WalletCommonTip(this.ChainIndexer.Tip)?.Height ?? -1;
public bool IsStarted { get; private set; }
public WalletManager(
ILoggerFactory loggerFactory,
Network network,
ChainIndexer chainIndexer,
WalletSettings walletSettings,
DataFolder dataFolder,
IWalletFeePolicy walletFeePolicy,
IDateTimeProvider dateTimeProvider,
IWalletRepository walletRepository)
{
Guard.NotNull(loggerFactory, nameof(loggerFactory));
Guard.NotNull(network, nameof(network));
Guard.NotNull(chainIndexer, nameof(chainIndexer));
Guard.NotNull(walletSettings, nameof(walletSettings));
Guard.NotNull(dataFolder, nameof(dataFolder));
Guard.NotNull(walletFeePolicy, nameof(walletFeePolicy));
Guard.NotNull(walletRepository, nameof(walletRepository));
this.Wallets = new WalletCollection(this);
this.walletSettings = walletSettings;
this.lockObject = new object();
this.lockProcess = new object();
this.logger = loggerFactory.CreateLogger(this.GetType().FullName);
this.network = network;
this.coinType = (CoinType)network.Consensus.CoinType;
this.ChainIndexer = chainIndexer;
this.fileStorage = new FileStorage<Wallet>(dataFolder.WalletPath);
this.dateTimeProvider = dateTimeProvider;
this.WalletRepository = walletRepository;
this.ExcludeTransactionsFromWalletImports = true;
this.privateKeyCache = new MemoryCache(new MemoryCacheOptions() { ExpirationScanFrequency = new TimeSpan(0, 1, 0) });
}
/// <summary>
/// Creates the <see cref="ScriptToAddressLookup"/> object to use.
/// </summary>
/// <remarks>
/// Override this method and the <see cref="ScriptToAddressLookup"/> object to provide a custom keys lookup.
/// </remarks>
/// <returns>A new <see cref="ScriptToAddressLookup"/> object for use by this class.</returns>
protected virtual ScriptToAddressLookup CreateAddressFromScriptLookup()
{
return new ScriptToAddressLookup();
}
/// <inheritdoc />
public virtual Dictionary<string, ScriptTemplate> GetValidStakingTemplates()
{
return new Dictionary<string, ScriptTemplate> {
{ "P2PK", PayToPubkeyTemplate.Instance },
{ "P2PKH", PayToPubkeyHashTemplate.Instance },
{ "P2WPKH", PayToWitPubKeyHashTemplate.Instance }
};
}
// <inheritdoc />
public virtual IEnumerable<BuilderExtension> GetTransactionBuilderExtensionsForStaking()
{
return new List<BuilderExtension>();
}
public void Start()
{
this.logger.LogInformation("Wallet Manager starting...");
this.WalletRepository.Bech32AddressFunc = scriptPubKey =>
{
if (string.IsNullOrEmpty(scriptPubKey))
return string.Empty;
var pubKey = PayToPubkeyTemplate.Instance.ExtractScriptPubKeyParameters(Script.FromHex(scriptPubKey));
Script witScriptPubKey = PayToWitPubKeyHashTemplate.Instance.GenerateScriptPubKey(pubKey);
return witScriptPubKey.GetDestinationAddress(this.network).ToString();
};
this.WalletRepository.Initialize(false);
// Ensure that any legacy JSON wallets are loaded to active storage.
foreach (string walletName in this.fileStorage.GetFilesNames(WalletFileExtension))
{
this.LoadWallet(walletName.Substring(0, walletName.Length - WalletFileExtension.Length - 1));
}
// Performs early rewinding of wallets that exceed the consensus tip instead of waiting for
// the next WalletSyncManager.OrchestrateWalletSync invocation.
foreach (string walletName in this.WalletRepository.GetWalletNames())
{
// A wallet ahead of consensus should be truncated.
ChainedHeader fork = this.WalletRepository.FindFork(walletName, this.ChainIndexer.Tip);
if (this.WalletRepository.RewindWallet(walletName, fork).RewindExecuted)
this.logger.LogDebug("Rewound wallet, {0}='{1}', {2}='{3}'", nameof(fork), fork, nameof(this.ChainIndexer.Tip), this.ChainIndexer.Tip?.HashBlock);
}
if (this.walletSettings.IsDefaultWalletEnabled())
{
// Check if it already exists, if not, create one.
if (!this.WalletRepository.GetWalletNames().Any(name => name == this.walletSettings.DefaultWalletName))
{
this.logger.LogInformation("Default wallet is enabled, creating wallet...");
var mnemonic = new Mnemonic(Wordlist.English, WordCount.Twelve);
this.CreateWallet(this.walletSettings.DefaultWalletPassword, this.walletSettings.DefaultWalletName, string.Empty, mnemonic);
}
// Make sure both unlock is specified, and that we actually have a default wallet name specified.
if (this.walletSettings.UnlockDefaultWallet)
{
this.UnlockWallet(this.walletSettings.DefaultWalletPassword, this.walletSettings.DefaultWalletName, MaxWalletUnlockDurationInSeconds);
}
}
this.IsStarted = true;
}
/// <inheritdoc />
public void Stop()
{
this.IsStarted = false;
this.WalletRepository.Shutdown();
this.logger.LogInformation("WalletManager stopped.");
}
/// <inheritdoc />
public int GetAddressBufferSize()
{
return this.walletSettings.UnusedAddressesBuffer;
}
/// <inheritdoc />
public (Wallet, Mnemonic) CreateWallet(string password, string name, string passphrase, Mnemonic mnemonic = null)
{
Guard.NotEmpty(password, nameof(password));
Guard.NotEmpty(name, nameof(name));
Guard.NotNull(passphrase, nameof(passphrase));
// Generate the root seed used to generate keys from a mnemonic picked at random
// and a passphrase optionally provided by the user.
mnemonic = mnemonic ?? new Mnemonic(Wordlist.English, WordCount.Twelve);
ExtKey extendedKey = HdOperations.GetExtendedKey(mnemonic, passphrase);
// Create a wallet file.
string encryptedSeed = extendedKey.PrivateKey.GetEncryptedBitcoinSecret(password, this.network).ToWif();
Wallet wallet = this.WalletRepository.CreateWallet(name, encryptedSeed, extendedKey.ChainCode,
(this.ChainIndexer.Tip == null) ? null : new HashHeightPair(this.ChainIndexer.Tip),
this.ChainIndexer.Tip?.GetLocator(), this.ChainIndexer.Tip.Header.Time + 1);
wallet.WalletManager = this;
// Generate multiple accounts and addresses from the get-go.
for (int i = 0; i < WalletCreationAccountsCount; i++)
{
wallet.AddNewAccount(password, i, $"account {i}");
}
return (wallet, mnemonic);
}
public ChainedHeader FindFork(string walletName, ChainedHeader chainedHeader)
{
return this.WalletRepository.FindFork(walletName, chainedHeader);
}
public ChainedHeader WalletCommonTip(ChainedHeader consensusTip)
{
ChainedHeader walletTip = consensusTip;
foreach (string walletName in this.WalletRepository.GetWalletNames())
{
if (walletTip == null)
break;
ChainedHeader fork = this.WalletRepository.FindFork(walletName, this.ChainIndexer.Tip);
walletTip = (fork == null) ? null : walletTip.FindFork(fork);
}
return walletTip;
}
public void UpdateLastBlockSyncedHeight(ChainedHeader tip, string walletName = null)
{
if (walletName != null)
this.RewindWallet(walletName, tip);
else
foreach (string wallet in this.GetWalletsNames())
this.RewindWallet(wallet, tip);
}
public void RewindWallet(string walletName, ChainedHeader chainedHeader)
{
this.WalletRepository.RewindWallet(walletName, chainedHeader);
}
public int GetTransactionCount(string walletName, string accountName = null)
{
return this.WalletRepository.GetTransactionCount(walletName, accountName);
}
/// <inheritdoc />
public string RetrievePrivateKey(string password, string walletName, string address)
{
Guard.NotEmpty(password, nameof(password));
Guard.NotEmpty(walletName, nameof(walletName));
Guard.NotEmpty(address, nameof(address));
Wallet wallet = this.GetWallet(walletName);
// Locate the address based on its base58 string representation.
// Check external addresses first.
HdAddress hdAddress = this.WalletRepository.GetAccounts(wallet).SelectMany(a => this.WalletRepository.GetAccountAddresses(
new WalletAccountReference(walletName, a.Name), 0, int.MaxValue)).Select(a => a).FirstOrDefault(addr => addr.Address.ToString() == address);
// Then check change addresses if needed.
if (hdAddress == null)
{
hdAddress = this.WalletRepository.GetAccounts(wallet).SelectMany(a => this.WalletRepository.GetAccountAddresses(
new WalletAccountReference(walletName, a.Name), 1, int.MaxValue)).Select(a => a).FirstOrDefault(addr => addr.Address.ToString() == address);
}
ISecret privateKey = wallet.GetExtendedPrivateKeyForAddress(password, hdAddress).PrivateKey.GetWif(this.network);
return privateKey.ToString();
}
/// <inheritdoc />
public string GetPubKey(string walletName, string externalAddress)
{
Guard.NotEmpty(walletName, nameof(walletName));
Guard.NotEmpty(externalAddress, nameof(externalAddress));
Script scriptPubKey = BitcoinAddress.Create(externalAddress, this.network).ScriptPubKey;
if (!this.WalletRepository.GetWalletAddressLookup(walletName).Contains(scriptPubKey, out AddressIdentifier addressIdentifier))
throw new SecurityException("The address does not exist in the wallet.");
var script = Script.FromHex(addressIdentifier.PubKeyScript);
PubKey pubKey = PayToPubkeyTemplate.Instance.ExtractScriptPubKeyParameters(script);
return pubKey.ToHex();
}
/// <inheritdoc />
public string SignMessage(string password, string walletName, string externalAddress, string message)
{
Guard.NotEmpty(password, nameof(password));
Guard.NotEmpty(walletName, nameof(walletName));
Guard.NotEmpty(message, nameof(message));
Guard.NotEmpty(externalAddress, nameof(externalAddress));
// Get wallet.
Wallet wallet = this.GetWallet(walletName);
Script scriptPubKey = BitcoinAddress.Create(externalAddress, this.network).ScriptPubKey;
if (!this.WalletRepository.GetWalletAddressLookup(walletName).Contains(scriptPubKey, out AddressIdentifier addressIdentifier))
throw new SecurityException("The address does not exist in the wallet.");
// Get HD Path.
string hdPath = $"{HdOperations.GetAccountHdPath(this.network.Consensus.CoinType, (int)addressIdentifier.AccountIndex)}/{addressIdentifier.AddressType}/{addressIdentifier.AddressIndex}";
// Get extended private key.
Key privateKey = HdOperations.DecryptSeed(wallet.EncryptedSeed, password, wallet.Network);
Key extendedPrivateKey = HdOperations.GetExtendedPrivateKey(privateKey, wallet.ChainCode, hdPath, wallet.Network).PrivateKey;
return extendedPrivateKey.SignMessage(message);
}
/// <inheritdoc />
public bool VerifySignedMessage(string externalAddress, string message, string signature)
{
Guard.NotEmpty(message, nameof(message));
Guard.NotEmpty(externalAddress, nameof(externalAddress));
Guard.NotEmpty(signature, nameof(signature));
bool result = false;
try
{
BitcoinPubKeyAddress bitcoinPubKeyAddress = new BitcoinPubKeyAddress(externalAddress, this.network);
result = bitcoinPubKeyAddress.VerifyMessage(message, signature);
}
catch (Exception ex)
{
this.logger.LogDebug("Failed to verify message: {0}", ex.ToString());
this.logger.LogTrace("(-)[EXCEPTION]");
}
return result;
}
/// <inheritdoc />
public Wallet LoadWallet(string password, string name)
{
Guard.NotEmpty(password, nameof(password));
Guard.NotEmpty(name, nameof(name));
void CheckThePassword(Wallet walletToCheck)
{
// Check the password.
try
{
if (!string.IsNullOrEmpty(walletToCheck.EncryptedSeed))
Key.Parse(walletToCheck.EncryptedSeed, password, this.network);
}
catch (Exception ex)
{
this.logger.LogDebug("Exception occurred: {0}", ex.ToString());
this.logger.LogTrace("(-)[EXCEPTION]");
throw new SecurityException(ex.Message);
}
}
return LoadWallet(name, (wallet) => CheckThePassword(wallet));
}
internal Wallet LoadWallet(string walletName, Action<Wallet> check = null)
{
Wallet wallet = null;
try
{
// Check if the json wallet isn't already in the repository.
wallet = this.GetWallet(walletName);
this.logger.LogInformation("Legacy JSON wallet '{0}' has already been imported.", walletName);
check?.Invoke(wallet);
}
catch (WalletException)
{
this.logger.LogInformation("Legacy JSON wallet '{0}' has not yet been imported.", walletName);
// If its not found then see if we have a JSON file for it.
string fileName = $"{walletName}.{WalletFileExtension}";
if (!this.fileStorage.Exists(fileName))
throw;
Wallet jsonWallet = this.fileStorage.LoadByFileName(fileName);
check?.Invoke(jsonWallet);
this.logger.LogInformation("Legacy JSON wallet '{0}' found, importing...", walletName);
if (this.ExcludeTransactionsFromWalletImports)
{
// Import the wallet to the database.
int lastBlock = 0;
var lastBlockSynced = new HashHeightPair(this.network.GenesisHash, lastBlock);
var blockLocator = this.ChainIndexer.GetHeader(lastBlock).GetLocator();
ITransactionContext transactionContext = this.WalletRepository.BeginTransaction(jsonWallet.Name);
try
{
lock (this.lockProcess)
{
this.logger.LogDebug("Creating wallet from json file called '{0}'.", jsonWallet.Name);
wallet = this.WalletRepository.CreateWallet(jsonWallet.Name, jsonWallet.EncryptedSeed, jsonWallet.ChainCode, lastBlockSynced, blockLocator, jsonWallet.CreationTime.ToUnixTimeSeconds());
this.logger.LogDebug("Wallet '{0}' created.", jsonWallet.Name);
foreach (HdAccount account in jsonWallet.AccountsRoot.First().Accounts)
{
int lastUsedExternalAddress = account.ExternalAddresses.LastOrDefault(p => p.Transactions.Any())?.Index ?? -1;
int lastUsedInternalAddress = account.InternalAddresses.LastOrDefault(p => p.Transactions.Any())?.Index ?? -1;
int buffer = this.walletSettings?.UnusedAddressesBuffer ?? 20;
this.WalletRepository.CreateAccount(jsonWallet.Name, account.Index, account.Name, ExtPubKey.Parse(account.ExtendedPubKey), account.CreationTime,
(lastUsedExternalAddress + 1 + buffer, lastUsedInternalAddress + 1 + buffer));
}
transactionContext.Commit();
}
}
catch (Exception ex)
{
this.logger.LogError("[EXCLUDE_TX_FROM_IMPORT]:Failed to import wallet '{0}'. Move the wallet to a backup location and use wallet recovery.", jsonWallet.Name);
this.logger.LogError(ex.ToString());
transactionContext.Rollback();
throw;
}
}
else
{
var walletTip = this.GetFork(jsonWallet, this.ChainIndexer.Tip);
var accountRoot = jsonWallet.AccountsRoot.First();
var lastBlockSynced = new HashHeightPair(accountRoot.LastBlockSyncedHash, (int)accountRoot.LastBlockSyncedHeight);
var blockLocator = new BlockLocator() { Blocks = jsonWallet.BlockLocator.ToList() };
ITransactionContext transactionContext = this.WalletRepository.BeginTransaction(jsonWallet.Name);
try
{
lock (this.lockProcess)
{
this.logger.LogDebug("Creating wallet from json file called '{0}'.", jsonWallet.Name);
wallet = this.WalletRepository.CreateWallet(jsonWallet.Name, jsonWallet.EncryptedSeed, jsonWallet.ChainCode, lastBlockSynced, blockLocator, jsonWallet.CreationTime.ToUnixTimeSeconds());
this.logger.LogDebug("Wallet '{0}' created.", jsonWallet.Name);
foreach (HdAccount account in jsonWallet.AccountsRoot.First().Accounts)
{
int lastUsedExternalAddress = account.ExternalAddresses.LastOrDefault(p => p.Transactions.Any())?.Index ?? -1;
int lastUsedInternalAddress = account.InternalAddresses.LastOrDefault(p => p.Transactions.Any())?.Index ?? -1;
int buffer = this.walletSettings?.UnusedAddressesBuffer ?? 20;
this.WalletRepository.CreateAccount(jsonWallet.Name, account.Index, account.Name, ExtPubKey.Parse(account.ExtendedPubKey), account.CreationTime,
(lastUsedExternalAddress + 1 + buffer, lastUsedInternalAddress + 1 + buffer));
foreach (HdAddress address in account.ExternalAddresses)
{
this.WalletRepository.AddWatchOnlyTransactions(jsonWallet.Name, account.Name, address, address.Transactions, true);
}
foreach (HdAddress address in account.InternalAddresses)
{
this.WalletRepository.AddWatchOnlyTransactions(jsonWallet.Name, account.Name, address, address.Transactions, true);
}
}
transactionContext.Commit();
}
}
catch (Exception ex)
{
this.logger.LogError("Failed to import wallet '{0}'. Move the wallet to a backup location and use wallet recovery.", jsonWallet.Name);
this.logger.LogError(ex.ToString());
transactionContext.Rollback();
throw;
}
}
this.logger.LogInformation("Legacy JSON wallet '{0}' imported successfully.", walletName);
}
return wallet;
}
internal ChainedHeader GetFork(Wallet wallet, ChainedHeader chainTip)
{
if (chainTip == null)
return null;
AccountRoot accountRoot = wallet.AccountsRoot.First();
if (chainTip.Height > accountRoot.LastBlockSyncedHeight)
{
if (accountRoot.LastBlockSyncedHeight < 0)
return null;
chainTip = chainTip.GetAncestor((int)accountRoot.LastBlockSyncedHeight);
}
if (chainTip.Height == accountRoot.LastBlockSyncedHeight)
{
if (chainTip.HashBlock == accountRoot.LastBlockSyncedHash)
return chainTip;
else
return null;
}
var blockLocator = new BlockLocator()
{
Blocks = wallet.BlockLocator.ToList()
};
List<int> locatorHeights = GetLocatorHeights(accountRoot.LastBlockSyncedHeight);
for (int i = 0; i < locatorHeights.Count; i++)
{
if (chainTip.Height > locatorHeights[i])
chainTip = chainTip.GetAncestor(locatorHeights[i]);
if (chainTip.HashBlock == blockLocator.Blocks[i])
return chainTip;
}
return null;
}
public static List<int> GetLocatorHeights(int? tipHeight)
{
int nStep = 1;
var blockHeights = new List<int>();
while (tipHeight != null)
{
blockHeights.Add((int)tipHeight);
// Stop when we have added the genesis block.
if (tipHeight == 0)
break;
// Exponentially larger steps back, plus the genesis block.
tipHeight = Math.Max((int)tipHeight - nStep, 0);
if (blockHeights.Count > 10)
nStep *= 2;
}
return blockHeights;
}
/// <inheritdoc />
public void UnlockWallet(string password, string name, int timeout)
{
Guard.NotEmpty(password, nameof(password));
Guard.NotEmpty(name, nameof(name));
// Length of expiry of the unlocking, restricted to max duration.
TimeSpan duration = new TimeSpan(0, 0, Math.Min(timeout, MaxWalletUnlockDurationInSeconds));
this.CacheSecret(name, password, duration);
}
/// <inheritdoc />
public void LockWallet(string name)
{
Guard.NotNull(name, nameof(name));
Wallet wallet = this.GetWallet(name);
string cacheKey = wallet.EncryptedSeed;
this.privateKeyCache.Remove(cacheKey);
}
[NoTrace]
private SecureString CacheSecret(string name, string walletPassword, TimeSpan duration)
{
Wallet wallet = this.GetWallet(name);
string cacheKey = wallet.EncryptedSeed;
if (!this.privateKeyCache.TryGetValue(cacheKey, out SecureString secretValue))
{
Key privateKey = Key.Parse(wallet.EncryptedSeed, walletPassword, wallet.Network);
secretValue = privateKey.ToString(wallet.Network).ToSecureString();
}
this.privateKeyCache.Set(cacheKey, secretValue, duration);
return secretValue;
}
/// <inheritdoc />
public Wallet RecoverWallet(string password, string name, string mnemonic, DateTime creationTime, string passphrase, ChainedHeader lastBlockSynced = null)
{
Guard.NotEmpty(password, nameof(password));
Guard.NotEmpty(name, nameof(name));
Guard.NotEmpty(mnemonic, nameof(mnemonic));
Guard.NotNull(passphrase, nameof(passphrase));
ExtKey extendedKey = HdOperations.GetExtendedKey(mnemonic, passphrase);
string encryptedSeed = extendedKey.PrivateKey.GetEncryptedBitcoinSecret(password, this.network).ToWif();
// Create the wallet with the lastBlockSynced set to null to sync from the beginning.
var wallet = new Wallet(name, encryptedSeed, extendedKey.ChainCode, creationTime, lastBlockSynced, this.WalletRepository);
wallet.AddNewAccount(password, 0, $"account {0}");
return wallet;
}
/// <inheritdoc />
public Wallet RecoverWallet(string name, ExtPubKey extPubKey, int accountIndex, DateTime creationTime, ChainedHeader lastBlockSynced = null)
{
Guard.NotEmpty(name, nameof(name));
Guard.NotNull(extPubKey, nameof(extPubKey));
this.logger.LogDebug("({0}:'{1}',{2}:'{3}',{4}:'{5}')", nameof(name), name, nameof(extPubKey), extPubKey, nameof(accountIndex), accountIndex);
// Create the wallet with the lastBlockSynced set to null to sync from the beginning.
var wallet = new Wallet(name, null, null, creationTime, lastBlockSynced, this.WalletRepository);
wallet.AddNewAccount(extPubKey, accountIndex, $"account {accountIndex}");
return wallet;
}
/// <inheritdoc />
public HdAccount GetUnusedAccount(string walletName, string password)
{
Guard.NotEmpty(walletName, nameof(walletName));
Guard.NotEmpty(password, nameof(password));
Wallet wallet = this.GetWallet(walletName);
if (wallet.IsExtPubKeyWallet)
{
this.logger.LogTrace("(-)[CANNOT_ADD_ACCOUNT_TO_EXTPUBKEY_WALLET]");
throw new CannotAddAccountToXpubKeyWalletException("Use recover-via-extpubkey instead.");
}
HdAccount res = this.GetUnusedAccount(wallet, password);
return res;
}
/// <inheritdoc />
public HdAccount GetUnusedAccount(Wallet wallet, string password)
{
Guard.NotNull(wallet, nameof(wallet));
Guard.NotEmpty(password, nameof(password));
HdAccount account;
lock (this.lockObject)
{
account = wallet.GetFirstUnusedAccount();
if (account != null)
{
this.logger.LogTrace("(-)[ACCOUNT_FOUND]");
return account;
}
// No unused account was found, create a new one.
account = wallet.AddNewAccount(password, accountCreationTime: this.dateTimeProvider.GetTimeOffset());
}
return account;
}
public string GetExtPubKey(WalletAccountReference accountReference)
{
Guard.NotNull(accountReference, nameof(accountReference));
Wallet wallet = this.GetWallet(accountReference.WalletName);
string extPubKey;
lock (this.lockObject)
{
// Get the account.
HdAccount account = wallet.GetAccount(accountReference.AccountName);
if (account == null)
throw new WalletException($"No account with the name '{accountReference.AccountName}' could be found.");
extPubKey = account.ExtendedPubKey;
}
return extPubKey;
}
/// <inheritdoc />
public HdAddress GetUnusedAddress(WalletAccountReference accountReference)
{
HdAddress res = this.GetUnusedAddresses(accountReference, 1).Single();
return res;
}
/// <inheritdoc />
public HdAddress GetUnusedChangeAddress(WalletAccountReference accountReference)
{
HdAddress res = this.GetUnusedAddresses(accountReference, 1, true).Single();
return res;
}
/// <inheritdoc />
public IEnumerable<HdAddress> GetUnusedAddresses(WalletAccountReference accountReference, int count, bool isChange = false)
{
Guard.NotNull(accountReference, nameof(accountReference));
Guard.Assert(count > 0);
return this.WalletRepository.GetUnusedAddresses(accountReference, count, isChange);
}
/// <inheritdoc />
public IEnumerable<HdAddress> GetUnusedAddresses(WalletAccountReference accountReference, bool isChange = false)
{
Guard.NotNull(accountReference, nameof(accountReference));
return this.WalletRepository.GetUnusedAddresses(accountReference, isChange);
}
/// <inheritdoc />
public IEnumerable<HdAddress> GetNewAddresses(WalletAccountReference accountReference, int count, bool isChange = false)
{
Guard.NotNull(accountReference, nameof(accountReference));
Guard.Assert(count > 0);
return this.WalletRepository.GetNewAddresses(accountReference, count, isChange);
}
/// <inheritdoc />
public IEnumerable<(HdAddress address, Money confirmed, Money total)> GetUsedAddresses(WalletAccountReference accountReference, bool isChange = false)
{
Guard.NotNull(accountReference, nameof(accountReference));
return this.WalletRepository.GetUsedAddresses(accountReference, isChange);
}
/// <inheritdoc />
public IEnumerable<AccountHistory> GetHistory(string walletName, string accountName = null, string searchQuery = null, int limit = int.MaxValue, int offset = 0)
{
Guard.NotEmpty(walletName, nameof(walletName));
Wallet wallet = this.GetWallet(walletName);
var accountsHistory = new List<AccountHistory>();
lock (this.lockObject)
{
var accounts = new List<HdAccount>();
if (!string.IsNullOrEmpty(accountName))
{
HdAccount account = wallet.GetAccount(accountName);
if (account == null)
throw new WalletException($"No account with the name '{accountName}' could be found.");
accounts.Add(account);
}
else
{
accounts.AddRange(wallet.GetAccounts());
}
foreach (HdAccount account in accounts)
{
accountsHistory.Add(this.GetHistoryForAccount(account, limit, offset, searchQuery));
}
}
return accountsHistory;
}
protected AccountHistory GetHistoryForAccount(HdAccount account, int limit, int offset, string searchQuery = null)
{
Guard.NotNull(account, nameof(account));
var accountHistory = new AccountHistory();
lock (this.lockObject)
{
return this.WalletRepository.GetHistory(account, limit, offset, searchQuery);
}
}
/// <inheritdoc />
public IEnumerable<AccountBalance> GetBalances(string walletName, string accountName = null, int confirmations = 0)
{
lock (this.lockObject)
{
int tipHeight = this.ChainIndexer.Height;
Wallet hdWallet = this.WalletRepository.GetWallet(walletName);
foreach (HdAccount hdAccount in this.WalletRepository.GetAccounts(hdWallet, accountName))
{
(Money totalAmount, Money confirmedAmount, Money spendableAmount) = this.WalletRepository.GetAccountBalance(new WalletAccountReference(walletName, hdAccount.Name), tipHeight, confirmations: confirmations);
yield return new AccountBalance()
{
Account = hdAccount,
AmountConfirmed = confirmedAmount,
AmountUnconfirmed = totalAmount - confirmedAmount,
SpendableAmount = spendableAmount
};
}
}
}
/// <inheritdoc />
public AddressBalance GetAddressBalance(string address)
{
Guard.NotEmpty(address, nameof(address));
var balance = new AddressBalance
{
Address = address,
CoinType = this.coinType
};
lock (this.lockObject)
{
Script scriptPubKey = BitcoinAddress.Create(address, this.network).ScriptPubKey;
foreach (string walletName in this.WalletRepository.GetWalletNames())
{
int walletId = this.WalletRepository.GetWalletId(walletName);
if (!this.WalletRepository.GetWalletAddressLookup(walletName).Contains(scriptPubKey, out AddressIdentifier addressIdentifier))
continue;
if (addressIdentifier.WalletId != walletId)
continue;
Wallet wallet = this.WalletRepository.GetWallet(walletName);
string accountName = wallet.AccountsRoot.First().Accounts.FirstOrDefault(a => a.Index == addressIdentifier.AccountIndex)?.Name;
(Money amountTotal, Money amountConfirmed, Money amountSpendable) result =
this.WalletRepository.GetAccountBalance(new WalletAccountReference(walletName, accountName),
this.ChainIndexer.Height,
address: ((int)addressIdentifier.AddressType, (int)addressIdentifier.AddressIndex));
balance.AmountConfirmed = result.amountConfirmed;
balance.AmountUnconfirmed = result.amountTotal - result.amountConfirmed;
balance.SpendableAmount = result.amountSpendable;
return balance;
}
this.logger.LogTrace("(-)[ADDRESS_NOT_FOUND]");
throw new WalletException($"Address '{address}' not found in wallets.");
}
}
/// <inheritdoc />
public IEnumerable<HdAccount> GetAccounts(string walletName)
{
Guard.NotEmpty(walletName, nameof(walletName));
Wallet wallet = this.GetWallet(walletName);
HdAccount[] res = null;
lock (this.lockObject)
{
res = wallet.GetAccounts().ToArray();
}
return res;
}
public HdAccount GetAccount(string walletName, string accountName)
{
Guard.NotEmpty(walletName, nameof(walletName));
Wallet wallet = this.GetWallet(walletName);
HdAccount res = null;
lock (this.lockObject)
{
res = wallet.GetAccounts().FirstOrDefault(a => a.Name == accountName);
}
return res;
}
public HdAccount GetAccount(WalletAccountReference accountReference)
{
return GetAccount(accountReference.WalletName, accountReference.AccountName);
}
public HdAccount GetOrCreateWatchOnlyAccount(string walletName)
{
Guard.NotEmpty(walletName, nameof(walletName));
Wallet wallet = this.GetWallet(walletName);
HdAccount[] res = null;
lock (this.lockObject)
{
res = wallet.GetAccounts(Wallet.WatchOnlyAccount).ToArray();
}
HdAccount watchOnlyAccount = res.FirstOrDefault(a => a.Index == Wallet.WatchOnlyAccountIndex);
if (watchOnlyAccount == null)
{
watchOnlyAccount = this.WalletRepository.CreateAccount(walletName, Wallet.WatchOnlyAccountIndex, Wallet.WatchOnlyAccountName, null);
}
return watchOnlyAccount;
}
// TODO: Perhaps this shouldn't be in the WalletManager itself, although it doesn't fit well with HdAccount either
public void AddWatchOnlyAddress(string walletName, string accountName, PubKey[] pubKeys)
{
this.WalletRepository.AddWatchOnlyAddresses(walletName, accountName, 0, pubKeys.Select(pubKey => new HdAddress() { Pubkey = pubKey.ScriptPubKey }).ToList());
}
public IEnumerable<HdAccount> GetAllAccounts()
{
HdAccount[] res = null;
lock (this.lockObject)
{
res = this.Wallets.SelectMany(w => w.GetAccounts()).ToArray();
}
return res;
}
/// <inheritdoc />
public int LastBlockHeight()
{
return this.WalletTipHeight;
}
/// <inheritdoc />
public bool ContainsWallets => this.WalletRepository.GetWalletNames().Any();
/// WALLET TODO: We can remove this walletManager.LastReceivedBlockInfo()
/// <summary>
/// Gets the hash of the last block received by the wallets.
/// </summary>
/// <returns>Hash of the last block received by the wallets.</returns>
public HashHeightPair LastReceivedBlockInfo()
{
if (this.Wallets.Count == 0)
return new HashHeightPair(this.ChainIndexer.Tip);
return new HashHeightPair(this.WalletTipHash, this.WalletTipHeight);
}
/// <inheritdoc />
public IEnumerable<UnspentOutputReference> GetSpendableTransactionsInWallet(string walletName, int confirmations = 0)
{
return this.GetSpendableTransactionsInWallet(walletName, confirmations, Wallet.NormalAccounts);
}
public virtual IEnumerable<UnspentOutputReference> GetSpendableTransactionsInWalletForStaking(string walletName, int confirmations = 0)
{
return this.GetUnspentTransactionsInWallet(walletName, confirmations, Wallet.NormalAccounts);
}
/// <inheritdoc />
public IEnumerable<UnspentOutputReference> GetUnspentTransactionsInWallet(string walletName, int confirmations, Func<HdAccount, bool> accountFilter)
{
Guard.NotEmpty(walletName, nameof(walletName));
Wallet wallet = this.GetWallet(walletName);
UnspentOutputReference[] res = null;
lock (this.lockObject)
{
res = wallet.GetAllUnspentTransactions(this.ChainIndexer.Tip.Height, confirmations, accountFilter).ToArray();
}
return res;
}
public IEnumerable<UnspentOutputReference> GetSpendableTransactionsInWallet(string walletName, int confirmations, Func<HdAccount, bool> accountFilter)
{
Guard.NotEmpty(walletName, nameof(walletName));
Wallet wallet = this.GetWallet(walletName);
UnspentOutputReference[] res = null;
lock (this.lockObject)
{
res = wallet.GetAllSpendableTransactions(this.ChainIndexer.Tip.Height, confirmations, accountFilter).ToArray();
}
return res;
}
/// <inheritdoc />
public IEnumerable<UnspentOutputReference> GetSpendableTransactionsInAccount(WalletAccountReference walletAccountReference, int confirmations = 0)
{
Guard.NotNull(walletAccountReference, nameof(walletAccountReference));
Wallet wallet = this.GetWallet(walletAccountReference.WalletName);
UnspentOutputReference[] res = null;
lock (this.lockObject)
{
HdAccount account = wallet.GetAccount(walletAccountReference.AccountName);
if (account == null)
{
this.logger.LogTrace("(-)[ACT_NOT_FOUND]");
throw new WalletException(
$"Account '{walletAccountReference.AccountName}' in wallet '{walletAccountReference.WalletName}' not found.");
}
res = account.GetSpendableTransactions(this.ChainIndexer.Tip.Height, this.network.Consensus.CoinbaseMaturity, confirmations).ToArray();
}
return res;
}
/// <inheritdoc />
public void RemoveBlocks(ChainedHeader fork)
{
lock (this.lockObject)
{
foreach (string walletName in this.WalletRepository.GetWalletNames())
this.WalletRepository.RewindWallet(walletName, fork);
}
}
/// <inheritdoc />
public void ProcessBlocks(Func<ChainedHeader, IEnumerable<(ChainedHeader, Block)>> blockProvider)
{
lock (this.lockProcess)
{
try
{
var walletNames = this.WalletRepository.GetWalletNames().ToList();
// Nothing to do?
if (walletNames.Count == 0)
{
this.logger.LogDebug("(-)[NO_WALLETS_TO_PROCESS]");
return;
}
ChainedHeader walletTip = this.ChainIndexer.Tip;
foreach (string walletName in walletNames)
{
// A wallet ahead of consensus should be truncated.
ChainedHeader fork = this.WalletRepository.FindFork(walletName, this.ChainIndexer.Tip);
if (this.WalletRepository.RewindWallet(walletName, fork).RewindExecuted)
this.logger.LogDebug("Rewound wallet, {0}='{1}', {2}='{3}'", nameof(fork), fork, nameof(this.ChainIndexer.Tip), this.ChainIndexer.Tip?.HashBlock);
// Update the lowest common tip.
walletTip = (fork == null) ? null : walletTip?.FindFork(fork);
}
// First process genesis.
if (walletTip == null)
{
var genesisBlock = this.network.GetGenesis();
var genesisHeader = new ChainedHeader(genesisBlock.Header, this.network.GenesisHash, 0);
this.WalletRepository.ProcessBlock(genesisBlock, genesisHeader);
walletTip = genesisHeader;
}
this.WalletRepository.ProcessBlocks(blockProvider(walletTip));
}
catch (Exception err)
{
// TODO: Resolve SQLite "Locked" issue.
throw err;
}
}
}
/// <inheritdoc />
public void ProcessBlock(Block block, ChainedHeader chainedHeader = null)
{
Guard.NotNull(block, nameof(block));
if (!this.ContainsWallets)
{
this.logger.LogTrace("(-)[NO_WALLET]");
return;
}
chainedHeader = chainedHeader ?? this.ChainIndexer.GetHeader(block.GetHash());
this.ProcessBlocks((previousBlock) => (previousBlock.HashBlock == chainedHeader.Previous.HashBlock) ? new[] { (chainedHeader, block) } : new (ChainedHeader, Block)[] { });
}
/// <inheritdoc />
public bool ProcessTransaction(Transaction transaction)
{
lock (this.lockProcess)
{
foreach (string walletName in this.WalletRepository.GetWalletNames())
{
this.WalletRepository.ProcessTransaction(walletName, transaction);
}
}
return true;
}
/// <inheritdoc />
public void DeleteWallet(string walletName)
{
lock (this.lockObject)
{
// Back-up to JSON ".wallet.json.bak" first.
this.SaveWallet(walletName, true);
// Delete any JSON wallet file that may otherwise be re-imported.
string fileName = $"{walletName}.{WalletFileExtension}";
this.fileStorage.DeleteFile(fileName);
// Delete from the repository.
this.WalletRepository.DeleteWallet(walletName);
}
}
private void SaveWallet(string walletName, bool toBackup)
{
Guard.NotNull(walletName, nameof(walletName));
lock (this.lockObject)
{
var wallet = this.GetWallet(walletName);
string fileName = $"{wallet.Name}.{WalletFileExtension}";
if (toBackup)
fileName += ".bak";
this.fileStorage.SaveToFile(wallet, fileName, new FileStorageOption { SerializeNullValues = false });
}
}
/// <inheritdoc />
public void SaveWallet(string walletName)
{
this.SaveWallet(walletName, false);
}
/// <inheritdoc />
public string GetWalletFileExtension()
{
return WalletFileExtension;
}
/// <inheritdoc />
public IEnumerable<string> GetWalletsNames()
{
return this.WalletRepository.GetWalletNames();
}
/// <inheritdoc />
public IEnumerable<string> GetWatchOnlyWalletsNames()
{
var watchOnlyWallets = new List<string>();
foreach (string walletName in this.WalletRepository.GetWalletNames())
{
Wallet wallet = this.WalletRepository.GetWallet(walletName);
if (wallet.IsExtPubKeyWallet)
watchOnlyWallets.Add(walletName);
}
return watchOnlyWallets;
}
/// <inheritdoc />
public Wallet GetWallet(string walletName)
{
var wallet = this.WalletRepository.GetWallet(walletName);
wallet.WalletManager = this;
return wallet;
}
public IEnumerable<Wallet> GetWallets()
{
return this.Wallets.ToArray();
}
/// <inheritdoc />
public HashSet<(uint256, DateTimeOffset)> RemoveTransactionsByIds(string walletName, IEnumerable<uint256> transactionsIds)
{
Guard.NotNull(transactionsIds, nameof(transactionsIds));
Guard.NotEmpty(walletName, nameof(walletName));
var result = new HashSet<(uint256, DateTimeOffset)>();
foreach (uint256 transactionId in transactionsIds)
{
this.logger.LogDebug("Removing transaction '{0}' from wallet '{1}'.", transactionId, walletName);
DateTimeOffset? dateTimeOffset = this.WalletRepository.RemoveUnconfirmedTransaction(walletName, transactionId);
if (dateTimeOffset != null)
result.Add((transactionId, (DateTimeOffset)dateTimeOffset));
}
return result;
}
/// <inheritdoc />
public void RemoveUnconfirmedTransaction(Transaction transaction)
{
Guard.NotNull(transaction, nameof(transaction));
foreach (Wallet wallet in this.Wallets)
{
this.logger.LogDebug("Removing unconfirmed transaction '{0}' from wallet '{1}'.", transaction.GetHash(), wallet.Name);
this.WalletRepository.RemoveUnconfirmedTransaction(wallet.Name, transaction.GetHash());
}
}
/// <inheritdoc />
public HashSet<(uint256, DateTimeOffset)> RemoveAllTransactions(string walletName)
{
Guard.NotEmpty(walletName, nameof(walletName));
(_, IEnumerable<(uint256 txId, DateTimeOffset creationTime)> result) = this.WalletRepository.RewindWallet(walletName, null);
result = result.Concat(this.WalletRepository.RemoveAllUnconfirmedTransactions(walletName));
return new HashSet<(uint256, DateTimeOffset)>(result.Select(kv => (kv.txId, kv.creationTime)));
}
/// <inheritdoc />
public HashSet<(uint256, DateTimeOffset)> RemoveTransactionsFromDate(string walletName, DateTimeOffset fromDate)
{
Guard.NotEmpty(walletName, nameof(walletName));
Wallet wallet = this.GetWallet(walletName);
var removedTransactions = new HashSet<(uint256, DateTimeOffset)>();
lock (this.lockObject)
{
IEnumerable<HdAccount> accounts = wallet.GetAccounts();
foreach (HdAccount account in accounts)
{
foreach (HdAddress address in account.GetCombinedAddresses())
{
var toRemove = address.Transactions.Where(t => t.CreationTime > fromDate).ToList();
foreach (var trx in toRemove)
{
removedTransactions.Add((trx.Id, trx.CreationTime));
address.Transactions.Remove(trx);
}
}
}
}
return removedTransactions;
}
/// <inheritdoc />
[NoTrace]
public ExtKey GetExtKey(WalletAccountReference accountReference, string password = "")
{
Wallet wallet = this.GetWallet(accountReference.WalletName);
string cacheKey = wallet.EncryptedSeed;
Key privateKey;
if (this.privateKeyCache.TryGetValue(cacheKey, out SecureString secretValue))
{
privateKey = wallet.Network.CreateBitcoinSecret(secretValue.FromSecureString()).PrivateKey;
}
else
{
privateKey = Key.Parse(wallet.EncryptedSeed, password, wallet.Network);
}
return new ExtKey(privateKey, wallet.ChainCode);
}
/// <inheritdoc />
public IEnumerable<IEnumerable<string>> GetAddressGroupings(string walletName)
{
return this.WalletRepository.GetAddressGroupings(walletName);
}
}
}
| 39.964672 | 225 | 0.589472 | [
"MIT"
] | fr0stnk/StratisFullNode | src/Stratis.Bitcoin.Features.Wallet/WalletManager.cs | 55,433 | C# |
// Copyright 2017 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
namespace NodaTime.Text
{
/// <summary>
/// Centralized location for error messages around text handling.
/// </summary>
internal static class TextErrorMessages
{
internal const string AmbiguousLocalTime = "The local date/time is ambiguous in the target time zone.";
internal const string CalendarAndEra = "The era specifier cannot be specified in the same pattern as the calendar specifier.";
internal const string DateFieldAndEmbeddedDate = "Custom date specifiers cannot be specified in the same pattern as an embedded date specifier";
internal const string DateSeparatorMismatch = "The value string does not match a date separator in the format string.";
internal const string DayOfMonthOutOfRange = "The day {0} is out of range in month {1} of year {2}.";
internal const string DayOfMonthOutOfRangeNoYear = "The day {0} is out of range in month {1}.";
internal const string EmptyPeriod = "The specified period was empty.";
internal const string EmptyZPrefixedOffsetPattern = "The Z prefix for an Offset pattern must be followed by a custom pattern.";
internal const string EndOfString = "Input string ended unexpectedly early.";
internal const string EraWithoutYearOfEra = "The era specifier cannot be used without the \"year of era\" specifier.";
internal const string EscapeAtEndOfString = "The format string has an escape character (backslash '\') at the end of the string.";
internal const string EscapedCharacterMismatch = "The value string does not match an escaped character in the format string: \"{0}\"";
internal const string ExpectedEndOfString = "Expected end of input, but more data remains.";
internal const string ExtraValueCharacters = "The format matches a prefix of the value string but not the entire string. Part not matching: \"{0}\".";
internal const string FieldValueOutOfRange = "The value {0} is out of range for the field '{1}' in the {2} type.";
internal const string FormatOnlyPattern = "This pattern is only capable of formatting, not parsing.";
internal const string FormatStringEmpty = "The format string is empty.";
internal const string Hour12PatternNotSupported = "The 'h' pattern flag (12 hour format) is not supported by the {0} type.";
internal const string InconsistentDayOfWeekTextValue = "The specified day of the week does not matched the computed value.";
internal const string InconsistentMonthTextValue = "The month values specified as text and numbers are inconsistent.";
internal const string InconsistentValues2 = "The individual values for the fields '{0}' and '{1}' created an inconsistency in the {2} type.";
internal const string InvalidEmbeddedPatternType = "The type of embedded pattern is not supported for this type.";
internal const string InvalidHour24 = "24 is only valid as an hour number when the units smaller than hours are all 0.";
internal const string InvalidOffset = "The specified offset is invalid for the given date/time.";
internal const string InvalidRepeatCount = "The number of consecutive copies of the pattern character \"{0}\" in the format string ({1}) is invalid.";
internal const string InvalidUnitSpecifier = "The period unit specifier '{0}' is invalid.";
internal const string IsoMonthOutOfRange = "The month {0} is out of range in the ISO calendar.";
internal const string MismatchedCharacter = "The value string does not match a simple character in the format string \"{0}\".";
internal const string MismatchedNumber = "The value string does not match the required number from the format string \"{0}\".";
internal const string MismatchedText = "The value string does not match the text-based field '{0}'.";
internal const string MisplacedUnitSpecifier = "The period unit specifier '{0}' appears at the wrong place in the input string.";
internal const string MissingAmPmDesignator = "The value string does not match the AM or PM designator for the culture at the required place.";
internal const string MissingEmbeddedPatternEnd = "The pattern has an embedded pattern which is missing its closing character ('{0}').";
internal const string MissingEmbeddedPatternStart = "The pattern has an embedded pattern which is missing its opening character ('{0}').";
internal const string MissingEndQuote = "The format string is missing the end quote character \"{0}\".";
internal const string MissingNumber = "The value string does not include a number in the expected position.";
internal const string MissingSign = "The required value sign is missing.";
internal const string MonthOutOfRange = "The month {0} is out of range in year {1}.";
internal const string MultipleCapitalDurationFields = "Only one of \"D\", \"H\", \"M\" or \"S\" can occur in a duration format string.";
internal const string NoMatchingCalendarSystem = "The specified calendar id is not recognized.";
internal const string NoMatchingFormat = "None of the specified formats matches the given value string.";
internal const string NoMatchingZoneId = "The specified time zone identifier is not recognized.";
internal const string OverallValueOutOfRange = "Value is out of the legal range for the {0} type.";
internal const string PercentAtEndOfString = "A percent sign (%) appears at the end of the format string.";
internal const string PercentDoubled = "A percent sign (%) is followed by another percent sign in the format string.";
internal const string PositiveSignInvalid = "A positive value sign is not valid at this point.";
internal const string QuotedStringMismatch = "The value string does not match a quoted string in the pattern.";
internal const string RepeatCountExceeded = "There were more consecutive copies of the pattern character \"{0}\" than the maximum allowed ({1}) in the format string.";
internal const string RepeatedFieldInPattern = "The field \"{0}\" is specified multiple times in the pattern.";
internal const string RepeatedUnitSpecifier = "The period unit specifier '{0}' appears multiple times in the input string.";
internal const string SkippedLocalTime = "The local date/time is skipped in the target time zone.";
internal const string TimeFieldAndEmbeddedTime = "Custom time specifiers cannot be specified in the same pattern as an embedded time specifier";
internal const string TimeSeparatorMismatch = "The value string does not match a time separator in the format string.";
internal const string UnexpectedNegative = "The value string includes a negative value where only a non-negative one is allowed.";
internal const string UnknownStandardFormat = "The standard format \"{0}\" is not valid for the {1} type. If the pattern was intended to be a custom format, escape it with a percent sign: \"%{0}\".";
internal const string UnparsableValue = "{0} Value being parsed: '{1}'. (^ indicates error position.)";
internal const string UnparsableValuePostParse = "{0} Value being parsed: '{1}'.";
internal const string UnquotedLiteral = "The character {0} is not a format specifier for this pattern type, and should be quoted to act as a literal. Note that each type of pattern has its own set of valid format specifiers.";
internal const string ValueOutOfRange = "The value {0} is out of the legal range for the {1} type.";
internal const string ValueStringEmpty = "The value string is empty.";
internal const string YearOfEraOutOfRange = "The year {0} is out of range for the {1} era in the {2} calendar.";
internal const string ZPrefixNotAtStartOfPattern = "The Z prefix for an Offset pattern must occur at the beginning of the pattern.";
}
}
| 106.842105 | 234 | 0.727463 | [
"Apache-2.0"
] | BearerPipelineTest/nodatime | src/NodaTime/Text/TextErrorMessages.cs | 8,122 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PayohService")]
[assembly: AssemblyTrademark("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1859a86c-cd3d-4dc1-a051-9ca64944df1f")]
| 41.1 | 84 | 0.782238 | [
"MIT"
] | payoh/aspdotnet-client-directkit-json2 | src/PayohService/Properties/AssemblyInfo.cs | 824 | C# |
using Microsoft.Win32;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Documents;
using TSP;
using TSP.Solution_Stratergies;
using TSP.Solution_Stratergies.LocalSearch;
using TSP_WPF.ViewModels;
namespace TSP_WPF.Views
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
private readonly RunViewModel runViewModel;
private readonly GraphViewModel graphViewModel;
public Window1()
{
InitializeComponent();
runViewModel = new RunViewModel();
DataContext = runViewModel;
List<ISearchStrategy> strategies = MyLocalSearches.GenerateSearchesTimeOut();
cboOptions.ItemsSource = strategies;
cboOptions.SelectedIndex = strategies.Count - 1;
graphViewModel = new GraphViewModel()
{
BoundX = 100,
BoundY = 100,
NodeCount = 25,
Seed = 255
};
runViewModel.Graph = graphViewModel.ToGraph();
ReadyToComputeCheck();
}
private void Compute()
{
if (runViewModel.SearchStrategy != null && runViewModel.Graph != null)
{
runViewModel.NewSeries();
Task.Run(() => runViewModel.SearchStrategy.Compute(runViewModel.Graph));
}
}
private void btnCompute_Click(object sender, RoutedEventArgs e)
{
Compute();
}
private void btnNewGraph_Click(object sender, RoutedEventArgs e)
{
var graphDialog = new NewGraphDialogue(graphViewModel);
bool? r = graphDialog.ShowDialog();
if (r != null && (bool)r)
{
runViewModel.Graph = graphDialog.graphViewModel.ToGraph();
ReadyToComputeCheck();
}
}
private void ReadyToComputeCheck()
{
btnCompute.IsEnabled = runViewModel.IsReady;
}
private void ChangeSearchStrategy(ISearchStrategy searchStrategy)
{
runViewModel.SearchStrategy = searchStrategy;
searchStrategy.OnItterationComplete += ItterationCompleteHandler;
if (searchStrategy != null)
searchStrategy.OnItterationComplete += ItterationCompleteHandler;
ReadyToComputeCheck();
void ItterationCompleteHandler(ISearchStrategy sender, Log log)
{
//TODO console
runViewModel.Add(log.timeToCompute, log.bestRouteCost); ;
pltPlot.InvalidatePlot(true);
}
}
private void btnLoadGraphFromFile(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
{
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "comma separated values (*.csv)|*.csv|All files (*.*)|*.*";
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == true)
{
runViewModel.Graph = Graph.ParseGraphFromFile(openFileDialog.FileName);
}
}
}
private void cboOptions_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
ChangeSearchStrategy((ISearchStrategy)cboOptions.SelectedItem);
}
}
}
| 31.025862 | 116 | 0.584051 | [
"MIT"
] | JR-Morgan/Genetic-Algorithm-Framework | TSP_WPF/Views/Window1.xaml.cs | 3,601 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Acme.ProjectName.Roles.Dto
{
public class UpdateRolePermissionsInput
{
[Range(1, int.MaxValue)]
public int RoleId { get; set; }
[Required]
public List<string> GrantedPermissionNames { get; set; }
}
} | 23.928571 | 64 | 0.680597 | [
"MIT"
] | OzBob/aspnetboilerplate-samples | ModuleZeroCoreWebFarm/aspnet-core/src/Acme.ProjectName.Application/Roles/Dto/UpdateRolePermissionsInput.cs | 337 | C# |
/*
* Activiti REST API
*
* # activiti - Activiti is battle-tested Business Process Management. Organizations across the world depend on the open source platform in a huge range of demanding situations. It supports open standards with BPMN and DMN so you can create processes that suit you.
*
* OpenAPI spec version: v1
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = Activiti.Rest.Client.SwaggerDateConverter;
namespace Activiti.Rest.Model
{
/// <summary>
/// FieldExtension
/// </summary>
[DataContract]
public partial class FieldExtension : IEquatable<FieldExtension>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="FieldExtension" /> class.
/// </summary>
/// <param name="Id">Id.</param>
/// <param name="XmlRowNumber">XmlRowNumber.</param>
/// <param name="XmlColumnNumber">XmlColumnNumber.</param>
/// <param name="ExtensionElements">ExtensionElements.</param>
/// <param name="Attributes">Attributes.</param>
/// <param name="FieldName">FieldName.</param>
/// <param name="StringValue">StringValue.</param>
/// <param name="Expression">Expression.</param>
public FieldExtension(string Id = default(string), int? XmlRowNumber = default(int?), int? XmlColumnNumber = default(int?), Dictionary<string, List<ExtensionElement>> ExtensionElements = default(Dictionary<string, List<ExtensionElement>>), Dictionary<string, List<ExtensionAttribute>> Attributes = default(Dictionary<string, List<ExtensionAttribute>>), string FieldName = default(string), string StringValue = default(string), string Expression = default(string))
{
this.Id = Id;
this.XmlRowNumber = XmlRowNumber;
this.XmlColumnNumber = XmlColumnNumber;
this.ExtensionElements = ExtensionElements;
this.Attributes = Attributes;
this.FieldName = FieldName;
this.StringValue = StringValue;
this.Expression = Expression;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public string Id { get; set; }
/// <summary>
/// Gets or Sets XmlRowNumber
/// </summary>
[DataMember(Name="xmlRowNumber", EmitDefaultValue=false)]
public int? XmlRowNumber { get; set; }
/// <summary>
/// Gets or Sets XmlColumnNumber
/// </summary>
[DataMember(Name="xmlColumnNumber", EmitDefaultValue=false)]
public int? XmlColumnNumber { get; set; }
/// <summary>
/// Gets or Sets ExtensionElements
/// </summary>
[DataMember(Name="extensionElements", EmitDefaultValue=false)]
public Dictionary<string, List<ExtensionElement>> ExtensionElements { get; set; }
/// <summary>
/// Gets or Sets Attributes
/// </summary>
[DataMember(Name="attributes", EmitDefaultValue=false)]
public Dictionary<string, List<ExtensionAttribute>> Attributes { get; set; }
/// <summary>
/// Gets or Sets FieldName
/// </summary>
[DataMember(Name="fieldName", EmitDefaultValue=false)]
public string FieldName { get; set; }
/// <summary>
/// Gets or Sets StringValue
/// </summary>
[DataMember(Name="stringValue", EmitDefaultValue=false)]
public string StringValue { get; set; }
/// <summary>
/// Gets or Sets Expression
/// </summary>
[DataMember(Name="expression", EmitDefaultValue=false)]
public string Expression { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class FieldExtension {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" XmlRowNumber: ").Append(XmlRowNumber).Append("\n");
sb.Append(" XmlColumnNumber: ").Append(XmlColumnNumber).Append("\n");
sb.Append(" ExtensionElements: ").Append(ExtensionElements).Append("\n");
sb.Append(" Attributes: ").Append(Attributes).Append("\n");
sb.Append(" FieldName: ").Append(FieldName).Append("\n");
sb.Append(" StringValue: ").Append(StringValue).Append("\n");
sb.Append(" Expression: ").Append(Expression).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as FieldExtension);
}
/// <summary>
/// Returns true if FieldExtension instances are equal
/// </summary>
/// <param name="input">Instance of FieldExtension to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(FieldExtension input)
{
if (input == null)
return false;
return
(
this.Id == input.Id ||
(this.Id != null &&
this.Id.Equals(input.Id))
) &&
(
this.XmlRowNumber == input.XmlRowNumber ||
(this.XmlRowNumber != null &&
this.XmlRowNumber.Equals(input.XmlRowNumber))
) &&
(
this.XmlColumnNumber == input.XmlColumnNumber ||
(this.XmlColumnNumber != null &&
this.XmlColumnNumber.Equals(input.XmlColumnNumber))
) &&
(
this.ExtensionElements == input.ExtensionElements ||
this.ExtensionElements != null &&
this.ExtensionElements.SequenceEqual(input.ExtensionElements)
) &&
(
this.Attributes == input.Attributes ||
this.Attributes != null &&
this.Attributes.SequenceEqual(input.Attributes)
) &&
(
this.FieldName == input.FieldName ||
(this.FieldName != null &&
this.FieldName.Equals(input.FieldName))
) &&
(
this.StringValue == input.StringValue ||
(this.StringValue != null &&
this.StringValue.Equals(input.StringValue))
) &&
(
this.Expression == input.Expression ||
(this.Expression != null &&
this.Expression.Equals(input.Expression))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Id != null)
hashCode = hashCode * 59 + this.Id.GetHashCode();
if (this.XmlRowNumber != null)
hashCode = hashCode * 59 + this.XmlRowNumber.GetHashCode();
if (this.XmlColumnNumber != null)
hashCode = hashCode * 59 + this.XmlColumnNumber.GetHashCode();
if (this.ExtensionElements != null)
hashCode = hashCode * 59 + this.ExtensionElements.GetHashCode();
if (this.Attributes != null)
hashCode = hashCode * 59 + this.Attributes.GetHashCode();
if (this.FieldName != null)
hashCode = hashCode * 59 + this.FieldName.GetHashCode();
if (this.StringValue != null)
hashCode = hashCode * 59 + this.StringValue.GetHashCode();
if (this.Expression != null)
hashCode = hashCode * 59 + this.Expression.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 40.2827 | 471 | 0.560071 | [
"MIT"
] | freetalent/Activiti.Rest | src/IO.Swagger/Model/FieldExtension.cs | 9,547 | C# |
using System;
namespace NuGet.Server.Infrastructure.Lucene
{
public enum IndexingState
{
Idle,
Scanning,
Building,
Commit,
Optimizing
}
public class IndexingStatus
{
public IndexingState State { get; set; }
public string CurrentPackagePath { get; set; }
public int CompletedPackages { get; set; }
public int PackagesToIndex { get; set; }
public int TotalPackages { get; set; }
public int PendingDeletes { get; set; }
public bool IsOptimized { get; set; }
public DateTime LastModification { get; set; }
}
} | 26.36 | 55 | 0.581184 | [
"ECL-2.0",
"Apache-2.0"
] | themotleyfool/NuGet | src/Server/Infrastructure/Lucene/IndexingStatus.cs | 659 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("07.ReplaceSubString")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("07.ReplaceSubString")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e9e0ef4b-3ac0-4dc2-be93-bce519b2efb0")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.135135 | 84 | 0.746279 | [
"MIT"
] | Andro0/TelerikAcademy | C#2/08.Homework_Text_Files/07.ReplaceSubString/Properties/AssemblyInfo.cs | 1,414 | C# |
using System.Collections;
using NUnit.Framework;
namespace Selenium3.Nunit.Framework
{
public class CrossBrowserData
{
public static IEnumerable LatestConfigurations
{
get
{
//chrome on Mac
yield return new TestFixtureData("Chrome", "latest", "macOS 10.13");
yield return new TestFixtureData("Chrome", "latest-1", "macOS 10.13");
yield return new TestFixtureData("Chrome", "latest-2", "macOS 10.13");
//chrome on Windows(#1 platform as of 2019)
yield return new TestFixtureData("Chrome", "latest", "Windows 10");
yield return new TestFixtureData("Chrome", "latest-1", "Windows 10");
yield return new TestFixtureData("Chrome", "latest-2", "Windows 10");
//chrome on Windows 7(#3 platform as of 2019)
yield return new TestFixtureData("Chrome", "latest", "Windows 7");
yield return new TestFixtureData("Chrome", "latest-1", "Windows 7");
yield return new TestFixtureData("Chrome", "latest-2", "Windows 7");
//safari
//doesn't work
//yield return new TestFixtureData("Safari", "latest", "macOS 10.15");
//click on Safari with macOS 10.13 doesn't work
//yield return new TestFixtureData("Safari", "latest", "macOS 10.13");
yield return new TestFixtureData("Safari", "latest", "macOS 10.14");
yield return new TestFixtureData("Safari", "latest", "macOS 10.12");
//firefox
yield return new TestFixtureData("Firefox", "latest", "macOS 10.13");
yield return new TestFixtureData("Firefox", "latest-1", "macOS 10.13");
yield return new TestFixtureData("Firefox", "latest-2", "macOS 10.13");
//edge
yield return new TestFixtureData("MicrosoftEdge", "latest", "Windows 10");
yield return new TestFixtureData("MicrosoftEdge", "latest-1", "Windows 10");
yield return new TestFixtureData("MicrosoftEdge", "latest-2", "Windows 10");
//IE
yield return new TestFixtureData("Internet Explorer", "latest", "Windows 10");
yield return new TestFixtureData("Internet Explorer", "latest", "Windows 7");
//Doesn't work
//yield return new TestFixtureData("Internet Explorer", "latest", "Windows 8");
//yield return new TestFixtureData("Internet Explorer", "10.0", "Windows 7");
}
}
public static IEnumerable SimpleConfiguration
{
get
{
yield return new TestFixtureData("Chrome", "latest", "Windows 10");
yield return new TestFixtureData("Chrome", "latest", "Windows 10");
yield return new TestFixtureData("Chrome", "latest", "Windows 10");
yield return new TestFixtureData("Chrome", "latest", "Windows 10");
yield return new TestFixtureData("Chrome", "latest", "Windows 10");
yield return new TestFixtureData("Chrome", "latest", "Windows 10");
yield return new TestFixtureData("Chrome", "latest", "Windows 10");
yield return new TestFixtureData("Chrome", "latest", "Windows 10");
yield return new TestFixtureData("Chrome", "latest", "Windows 10");
yield return new TestFixtureData("Chrome", "latest", "Windows 10");
yield return new TestFixtureData("Chrome", "latest", "Windows 10");
yield return new TestFixtureData("Chrome", "latest", "Windows 10");
yield return new TestFixtureData("Chrome", "latest", "Windows 10");
yield return new TestFixtureData("Chrome", "latest", "Windows 10");
yield return new TestFixtureData("Chrome", "latest", "Windows 10");
}
}
}
} | 50.8875 | 102 | 0.566691 | [
"MIT"
] | etiennesillon/demo-csharp | SauceExamples/Web.Tests/CrossBrowserData.cs | 4,071 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.