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
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using SmsBlissAPI.Model; using Newtonsoft.Json; using System.Collections.Generic; using System.Threading.Tasks; using System.Linq; namespace SmsBlissAPI { public sealed class SmsBlissClient { private const string baseAddress = "http://api.smsbliss.net/messages/v2"; private const string contentType = "application/json"; private readonly string login; private readonly string password; public SmsBlissClient(string login, string password) { this.login = login; this.password = password; } public async Task<MessagesResponse> SendMessagesAsync(IEnumerable<Message> messages, string queueName = null, bool showBillingDetails = false) { if(messages == null) { throw new ArgumentNullException(nameof(messages)); } MessagesRequest request = new MessagesRequest(login, password, messages); request.StatusQueueName = queueName; request.ShowBillingDetails = showBillingDetails; string content = JsonConvert.SerializeObject(request); using(HttpClient httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType)); HttpContent httpContent = new StringContent(content, Encoding.UTF8, contentType); string url = baseAddress + "/send.json"; var httpResponse = await httpClient.PostAsync(url, httpContent); var responseContent = await httpResponse.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<MessagesResponse>(responseContent); } } public MessagesResponse SendMessages(IEnumerable<Message> messages, string queueName = null, bool showBillingDetails = false) { var sendMessageTask = SendMessagesAsync(messages, queueName, showBillingDetails); sendMessageTask.Wait(); return sendMessageTask.Result; } public async Task<MessageStatusesResponse> GetMessageStatusesAsync(IEnumerable<MessageStatusRequestInfo> messages) { if(messages == null) { throw new ArgumentNullException(nameof(messages)); } if(!messages.Any()) { throw new ArgumentException("Должны быть указаны сообщения для которых необходимо получить статусы"); } MessageStatusesRequest request = new MessageStatusesRequest(login, password, messages); string content = JsonConvert.SerializeObject(request); using(HttpClient httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType)); HttpContent httpContent = new StringContent(content, Encoding.UTF8, contentType); string url = baseAddress + "/status.json"; var httpResponse = await httpClient.PostAsync(url, httpContent); var responseContent = await httpResponse.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<MessageStatusesResponse>(responseContent); } } public MessageStatusesResponse GetMessageStatuses(IEnumerable<MessageStatusRequestInfo> messages) { var messageStatusesTask = GetMessageStatusesAsync(messages); messageStatusesTask.Wait(); return messageStatusesTask.Result; } public async Task<StatusQueueResponse> GetQueueStatusAsync(string statusQueueName, int statusQueueLimit = 1) { if(statusQueueLimit <= 0) { throw new ArgumentException("Количество запрашиваемых статусов в очереди должно быть больше 1"); } if(statusQueueLimit > 1000) { throw new ArgumentException("Максимальное количество запрашиваемых сообщений ограничено 1000 сообщений"); } StatusQueueRequest request = new StatusQueueRequest(login, password, statusQueueLimit.ToString(), statusQueueName); string content = JsonConvert.SerializeObject(request); using(HttpClient httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType)); HttpContent httpContent = new StringContent(content, Encoding.UTF8, contentType); string url = baseAddress + "/statusQueue.json"; var httpResponse = await httpClient.PostAsync(url, httpContent); var responseContent = await httpResponse.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<StatusQueueResponse>(responseContent); } } public StatusQueueResponse GetQueueStatus(string statusQueueName, int statusQueueLimit = 1) { var queueStatusTask = GetQueueStatusAsync(statusQueueName, statusQueueLimit); queueStatusTask.Wait(); return queueStatusTask.Result; } public async Task<BalanceResponse> GetBalanceAsync() { BalanceRequest request = new BalanceRequest(login, password); string content = JsonConvert.SerializeObject(request); using(HttpClient httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType)); HttpContent httpContent = new StringContent(content, Encoding.UTF8, contentType); string url = baseAddress + "/balance.json"; var httpResponse = await httpClient.PostAsync(url, httpContent); var responseContent = await httpResponse.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<BalanceResponse>(responseContent); } } public BalanceResponse GetBalance() { var balanceTask = GetBalanceAsync(); balanceTask.Wait(); return balanceTask.Result; } public async Task<SenderNamesResponse> GetSenderNamesAsync() { SenderNamesRequest request = new SenderNamesRequest(login, password); string content = JsonConvert.SerializeObject(request); using(HttpClient httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType)); HttpContent httpContent = new StringContent(content, Encoding.UTF8, contentType); string url = baseAddress + "/senders.json"; var httpResponse = await httpClient.PostAsync(url, httpContent); var responseContent = await httpResponse.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<SenderNamesResponse>(responseContent); } } public SenderNamesResponse GetSenderNames() { var senderNamesTask = GetSenderNamesAsync(); senderNamesTask.Wait(); return senderNamesTask.Result; } public async Task<ApiVersionResponse> GetApiVersionAsync() { ApiVersionRequest request = new ApiVersionRequest(login, password); string content = JsonConvert.SerializeObject(request); using(HttpClient httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType)); HttpContent httpContent = new StringContent(content, Encoding.UTF8, contentType); string url = baseAddress + "/version.json"; var httpResponse = await httpClient.PostAsync(url, httpContent); var responseContent = await httpResponse.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<ApiVersionResponse>(responseContent); } } public ApiVersionResponse GetApiVersion() { var apiVersionTask = GetApiVersionAsync(); apiVersionTask.Wait(); return apiVersionTask.Result; } } }
38.479167
144
0.773958
[ "MIT" ]
Enzogord/SmsBlissApi
SmsBlissAPI/SmsBlissClient.cs
7,569
C#
//====================================================================== // Copyright (C) 2015-2020 Winddy He. All rights reserved // Email: [email protected] //====================================================================== using System; using UnityEngine; using Object = UnityEngine.Object; using Knight.Framework; namespace Knight.Hotfix.Core { [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class HotfixBindingAttribute : Attribute { public string Name; public int Index; public HotfixBindingAttribute(string rName = "") { this.Name = rName; } public HotfixBindingAttribute(int nIndex = -1) { this.Index = nIndex; } } [AttributeUsage(AttributeTargets.Method)] public class HotfixBindingEventAttribute : Attribute { public string Name; public HEventTriggerType EventType; public bool NeedUnbind; public HotfixBindingEventAttribute(string rName, HEventTriggerType rEventType, bool bNeedUnbind = true) { this.Name = rName; this.EventType = rEventType; this.NeedUnbind = bNeedUnbind; } } public class HotfixEventObject { public Object TargetObject; public Action<Object> EventHandler; public HEventTriggerType EventType; public bool NeedUnbind; } [AttributeUsage(AttributeTargets.Method)] public class HotfixEventAttribute : Attribute { public int MsgCode; public HotfixEventAttribute(int nMsgCode) { this.MsgCode = nMsgCode; } } }
29.301587
111
0.530878
[ "MIT" ]
JansonC/knight
knight-client/Assets/Game.Hotfix/Core/Assist/HotfixBinding.cs
1,848
C#
using System; using System.Collections.Generic; namespace SKIT.FlurlHttpClient.Wechat.Api.Models { /// <summary> /// <para>表示 [GET] /union/promoter/promotion/list 接口的响应。</para> /// </summary> public class UnionPromoterPromotionListResponse : WechatApiResponse { public static class Types { public class Promotion { /// <summary> /// 获取或设置推广位 ID。 /// </summary> [Newtonsoft.Json.JsonProperty("promotionSourcePid")] [System.Text.Json.Serialization.JsonPropertyName("promotionSourcePid")] public string PromotionId { get; set; } = default!; /// <summary> /// 获取或设置推广位名称。 /// </summary> [Newtonsoft.Json.JsonProperty("promotionSourceName")] [System.Text.Json.Serialization.JsonPropertyName("promotionSourceName")] public string SourceName { get; set; } = default!; } } /// <summary> /// 获取或设置推广位列表。 /// </summary> [Newtonsoft.Json.JsonProperty("promotionSourceList")] [System.Text.Json.Serialization.JsonPropertyName("promotionSourceList")] public Types.Promotion[] PromotionList { get; set; } = default!; /// <summary> /// 获取或设置推广位总数量。 /// </summary> [Newtonsoft.Json.JsonProperty("total")] [System.Text.Json.Serialization.JsonPropertyName("total")] public int Total { get; set; } /// <summary> /// 获取或设置允许创建的推广位最大数量。 /// </summary> [Newtonsoft.Json.JsonProperty("promotionMaxCnt")] [System.Text.Json.Serialization.JsonPropertyName("promotionMaxCnt")] public int MaxPromotionCount { get; set; } } }
33.759259
88
0.56994
[ "MIT" ]
KimMeng2015/DotNetCore.SKIT.FlurlHttpClient.Wechat
src/SKIT.FlurlHttpClient.Wechat.Api/Models/UnionPromoter/Promotion/UnionPromoterPromotionListResponse.cs
1,963
C#
using System; using System.IO; namespace Studio.AssemblyResolver.PathResolver.Implementation { internal class DefaultStudio2011PathResolver: IPathResolver { public string Resolve() { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), @"SDL\SDL Trados Studio\Studio2\"); } } }
24.4
137
0.710383
[ "Apache-2.0" ]
cromica/Studio-AssemblyResolver
Studio.AssemblyResolver/PathResolver/Implementation/DefaultStudio2011PathResolver.cs
368
C#
using System.Linq; using System.Text.Encodings.Web; using System.Threading.Tasks; using GraphQL.Types; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Localization; using OrchardCore.Apis.GraphQL; using OrchardCore.ContentManagement.Metadata; using OrchardCore.ShortCodes.Services; using OrchardCore.Infrastructure.Html; using OrchardCore.Liquid; using OrchardCore.Markdown.Models; using OrchardCore.Markdown.Services; using OrchardCore.Markdown.Settings; using OrchardCore.Markdown.ViewModels; namespace OrchardCore.Markdown.GraphQL { public class MarkdownBodyQueryObjectType : ObjectGraphType<MarkdownBodyPart> { public MarkdownBodyQueryObjectType(IStringLocalizer<MarkdownBodyQueryObjectType> S) { Name = nameof(MarkdownBodyPart); Description = S["Content stored as Markdown. You can also query the HTML interpreted version of Markdown."]; Field("markdown", x => x.Markdown, nullable: true) .Description(S["the markdown value"]); Field<StringGraphType>() .Name("html") .Description(S["the HTML representation of the markdown content"]) .ResolveLockedAsync(ToHtml); } private static async Task<object> ToHtml(ResolveFieldContext<MarkdownBodyPart> ctx) { if (string.IsNullOrEmpty(ctx.Source.Markdown)) { return ctx.Source.Markdown; } var serviceProvider = ctx.ResolveServiceProvider(); var markdownService = serviceProvider.GetRequiredService<IMarkdownService>(); var shortCodeService = serviceProvider.GetRequiredService<IShortCodeService>(); var contentDefinitionManager = serviceProvider.GetRequiredService<IContentDefinitionManager>(); var contentTypeDefinition = contentDefinitionManager.GetTypeDefinition(ctx.Source.ContentItem.ContentType); var contentTypePartDefinition = contentTypeDefinition.Parts.FirstOrDefault(x => string.Equals(x.PartDefinition.Name, "MarkdownBodyPart")); var settings = contentTypePartDefinition.GetSettings<MarkdownBodyPartSettings>(); // The default Markdown option is to entity escape html // so filters must be run after the markdown has been processed. var html = markdownService.ToHtml(ctx.Source.Markdown); // The liquid rendering is for backwards compatability and can be removed in a future version. if (!settings.SanitizeHtml) { var liquidTemplateManager = serviceProvider.GetService<ILiquidTemplateManager>(); var htmlEncoder = serviceProvider.GetService<HtmlEncoder>(); var model = new MarkdownBodyPartViewModel() { Markdown = ctx.Source.Markdown, Html = html, MarkdownBodyPart = ctx.Source, ContentItem = ctx.Source.ContentItem }; html = await liquidTemplateManager.RenderAsync(html, htmlEncoder, model, scope => scope.SetValue("ContentItem", model.ContentItem)); } html = await shortCodeService.ProcessAsync(html); if (settings.SanitizeHtml) { var htmlSanitizerService = serviceProvider.GetRequiredService<IHtmlSanitizerService>(); html = htmlSanitizerService.Sanitize(html); } return html; } } }
41.929412
150
0.6633
[ "BSD-3-Clause" ]
Frunck82/Orchard2
src/OrchardCore.Modules/OrchardCore.Markdown/GraphQL/MarkdownBodyQueryObjectType.cs
3,564
C#
using Infrastructure; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Wutnu.Common; using Wutnu.Common.ErrorMgr; using Wutnu.Data; using Wutnu.Repo; using Wutnu.Models; using Newtonsoft.Json; using System.IdentityModel.Claims; using Wutnu.Infrastructure; namespace Wutnu.Controllers { public class HomeController : BaseController { public HomeController(WutCache cache, WutNuContext models) :base(cache, models) { } public ActionResult Index() { if (Request.Cookies["Error"] != null) { ViewBag.Error = Request.Cookies["Error"].Value; } return CheckForReturn(); } private ActionResult CheckForReturn() { if (Request.UrlReferrer == null) return View(); var profile = HttpUtility.ParseQueryString(Request.UrlReferrer.Query)["p"]; if (profile != null && Request.UrlReferrer.AbsolutePath.Split('/').Last()!="logout") { profile = profile.ToLower(); if (profile==Startup.ResetPolicyId.ToLower() || profile == Startup.ProfilePolicyId.ToLower()) { return RedirectToAction("Index", "Profile", new { area = "Manage" }); } } return View(); } /// <summary> ///Grab the short URL and look it up for redirection ///see MVC routes for definition ///(if we wanted to authenticate the user that is trying to expand a link, here's where we'd do it) /// </summary> /// <param name="shortUrl"></param> /// <returns></returns> public ActionResult Redir(string id) { if (id == null) return View("Index"); var res = ShortUrlUtils.RetrieveUrlFromDatabase(id, Wutcontext); if (res == null || (res!=null && res.RealUrl == null)) { ViewBag.Error="Sorry, that URL wasn't found. Please check your source and try again."; return View("Index"); } if (res.IsProtected) { //redirect to the authorized entry point return Redirect("/a/" + id); } if (res.IsAzureBlob) { res = GenToken(res); } return LogAndRedir(res); } /// <summary> ///Grab the short URL and look it up for redirection ///see MVC routes for definition ///(if we wanted to authenticate the user that is trying to expand a link, here's where we'd do it) /// </summary> /// <param name="shortUrl"></param> /// <returns></returns> public ActionResult RedirAuth(string id) { if (!User.Identity.IsAuthenticated) { return RedirectToAction("Signin", "Account", new { redir = "/a/" + id }); } if (id == null) return View("Index"); var userId = User.Identity.GetClaim<int>(CustomClaimTypes.UserId); var email = User.Identity.GetClaim(ClaimTypes.Email); var res = ShortUrlUtils.RetrieveUrlFromDatabase(id, Wutcontext, userId, email); if (res == null || (res != null && res.RealUrl == null)) { ViewBag.Error = "Sorry, that URL wasn't found or access is denied. Please check your source and try again."; return View("Index"); } //checking to see if this user was granted access to this file var isAuth = res.UserEmailColl.Any(u => u == email); if (!isAuth) { Logging.WriteMessageToErrorLog(String.Format("User \"{0}\" attempted unauthorized retrieval of url \"{1}\" resolving to \"{2}\".", email, res.ShortUrl, res.RealUrl), Wutcontext); ViewBag.Error = "Sorry, you are not authorized to view this resource. This attempt has been logged. Please check with the issuer."; return View("Index"); } if (res.IsAzureBlob) { res = GenToken(res); } return LogAndRedir(res, userId); } private WutLinkPoco GenToken(WutLinkPoco res) { var containerName = GetContainerFromUri(res.RealUrl); var container = WutStorage.GetContainer(containerName); res.RealUrl = WutStorage.GetBlobReadTokenUri(container, System.IO.Path.GetFileName(res.RealUrl)); return res; } private string GetContainerFromUri(string realUrl) { var uri = new Uri(realUrl); int segment = (realUrl.IndexOf("devstoreaccount")>-1) ? 2 : 1; var containerName = uri.Segments[segment]; containerName = containerName.Substring(0, containerName.Length - 1); return containerName; } private ActionResult LogAndRedir(WutLinkPoco res, int? userId=null) { var cli = WutQueue.GetQueueClient(); var queue = WutQueue.GetQueue(cli, Settings.AuditQueueName); var msg = new AuditDataModel { UserId = userId, CallDate = DateTime.UtcNow, HostIp = Request.UserHostAddress, ShortUrl = res.ShortUrl }; var message = JsonConvert.SerializeObject(msg); WutQueue.AddMessage(queue, message); if (res.UseDelay) { ViewBag.RealUrl = res.RealUrl; return View("redir"); } else { return Redirect(res.RealUrl); } } public ActionResult Missing() { return View(); } public ActionResult About() { ViewBag.Message = "Mother of All Azure Demos (MOAAD)"; return View(); } public ActionResult Error(string message) { if (message == null) message = "N/A"; ViewBag.ErrorMessage = message.Replace("\r\n","<br>"); return View(); } public ActionResult Tos() { return View(); } public ActionResult Privacy() { return View(); } public ActionResult Contact() { ViewBag.Message = "These are not the droids you're looking for."; return View(); } public ActionResult IssueInfo() { return View(); } [HttpPost] public ActionResult IssueInfo(string comments) { if (HttpContext.Session == null) return View(); var eid = (HttpContext.Session != null && HttpContext.Session["ErrorID"] != null) ? HttpContext.Session["ErrorID"].ToString() : Request.Form["et"]; //var emgr = new ErrorMgr(HttpContext.GetOwinContext().Get<WutNuContext>("WutNuContext"), HttpContext); var emgr = new ErrorMgr(Wutcontext, HttpContext); try { var eo = emgr.ReadError(eid); if (eo != null) { eo.UserComment = comments; emgr.SaveError(eo); } else { //Writing to node WEL emgr.WriteToAppLog("Unable to save user comments to. Comment: " + comments, System.Diagnostics.EventLogEntryType.Error); } } catch (Exception ex) { //Writing to node WEL emgr.WriteToAppLog("Unable to save user comments. \r\nError: " + ex.Message + ". \r\nComment: " + comments, System.Diagnostics.EventLogEntryType.Error); } return View(); } } }
32.582996
194
0.525596
[ "Apache-2.0" ]
bretthacker/Wutnu
Wutnu3/Controllers/HomeController.cs
8,050
C#
#region Using directives using System; using System.Reflection; using System.Runtime.InteropServices; #endregion // 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("PowerShell.support")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PowerShell.support")] [assembly: AssemblyCopyright("Copyright 2009")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // This sets the default COM visibility of types in the assembly to invisible. // If you need to expose a type to COM, use [ComVisible(true)] on that type. [assembly: ComVisible(false)] // The assembly version has following format : // // Major.Minor.Build.Revision // // You can specify all the values or you can use the default the Revision and // Build Numbers by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")]
34.09375
79
0.738772
[ "MIT" ]
d3x0r/xperdex
PowerShell/PowerShell.support/Properties/AssemblyInfo.cs
1,093
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Models.Api20200515 { using static Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.Extensions; /// <summary>Key-value pairs of additional properties for the reference data set.</summary> public partial class ReferenceDataSetUpdateParametersTags { /// <summary> /// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.Json.JsonObject json); /// <summary> /// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.Json.JsonObject" /// /> before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.Json.JsonObject container); /// <summary> /// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of /// the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> /// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return /// instantly.</param> partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.Json.JsonObject json, ref bool returnNow); /// <summary> /// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the /// object before it is serialized. /// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.Json.JsonObject container, ref bool returnNow); /// <summary> /// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Models.Api20200515.IReferenceDataSetUpdateParametersTags. /// </summary> /// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.Json.JsonNode" /> to deserialize from.</param> /// <returns> /// an instance of Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Models.Api20200515.IReferenceDataSetUpdateParametersTags. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Models.Api20200515.IReferenceDataSetUpdateParametersTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.Json.JsonNode node) { return node is Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.Json.JsonObject json ? new ReferenceDataSetUpdateParametersTags(json) : null; } /// <summary> /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.Json.JsonObject into a new instance of <see cref="ReferenceDataSetUpdateParametersTags" />. /// </summary> /// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.Json.JsonObject instance to deserialize from.</param> /// <param name="exclusions"></param> internal ReferenceDataSetUpdateParametersTags(Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.Json.JsonObject json, global::System.Collections.Generic.HashSet<string> exclusions = null) { bool returnNow = false; BeforeFromJson(json, ref returnNow); if (returnNow) { return; } Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.IAssociativeArray<string>)this).AdditionalProperties, null ,exclusions ); AfterFromJson(json); } /// <summary> /// Serializes this instance of <see cref="ReferenceDataSetUpdateParametersTags" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.Json.JsonNode" /// />. /// </summary> /// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller /// passes in <c>null</c>, a new instance will be created and returned to the caller.</param> /// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.SerializationMode"/>.</param> /// <returns> /// a serialized instance of <see cref="ReferenceDataSetUpdateParametersTags" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.Json.JsonNode" />. /// </returns> public Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.SerializationMode serializationMode) { container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.Json.JsonObject(); bool returnNow = false; BeforeToJson(ref container, ref returnNow); if (returnNow) { return container; } Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.TimeSeriesInsights.Runtime.IAssociativeArray<string>)this).AdditionalProperties, container); AfterToJson(ref container); return container; } } }
70.592233
286
0.704305
[ "MIT" ]
3quanfeng/azure-powershell
src/TimeSeriesInsights/generated/api/Models/Api20200515/ReferenceDataSetUpdateParametersTags.json.cs
7,169
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class brickBrokenPartController : MonoBehaviour { //类型 //1 - left //2 - right public short part_type; //效果持续时间 public float liveTime; //透明度差值(每次) private float deltaAlpha; //Sprite Render private SpriteRenderer render; private void Start() { //调整重心 Rigidbody2D rigidbody = this.GetComponent<Rigidbody2D>(); Transform centerofMass = transform.Find("centerofMass"); rigidbody.centerOfMass = centerofMass.position; //deltaAlpha初始化 if (Time.deltaTime>0) { deltaAlpha = 1f / (liveTime / Time.deltaTime); } else { deltaAlpha = 1f / (liveTime / 0.167f); } //render初始化 render = GetComponent<SpriteRenderer>(); } private void Update() { //透明度渐变 processAlpha(); //清理 if (transform.position.y <= -5.6f) { Destroy(gameObject); } } //处理Alpha的变化 void processAlpha() { Color t = render.color; //当物体因为透明度改变不可见时删除该物体 if (t.a-deltaAlpha <= 0) { Destroy(gameObject); } t = new Color(t.r, t.g, t.b, t.a - deltaAlpha); render.color = t; } public void throwout(Vector3 ballPosition) { //定义刚体和力 Rigidbody2D rigidbody = this.GetComponent<Rigidbody2D>(); Vector2 force = new Vector2(); //球从下面打 if (ballPosition.y <= transform.position.y) { //分情况向部件施加力 switch (part_type) { case 1: force = new Vector2(Random.Range(-175f,-65f),Random.Range(35f, 95f)); rigidbody.AddForceAtPosition(force, ballPosition); break; case 2: force = new Vector2(Random.Range(65f, 175f), Random.Range(35f, 95f)); rigidbody.AddForceAtPosition(force, ballPosition); break; } } else { //球从上面打 switch (part_type) { case 1: force = new Vector2(Random.Range(-125f, -55f), Random.Range(-95f, -35f)); rigidbody.AddForceAtPosition(force, ballPosition); break; case 2: force = new Vector2(Random.Range(55f, 125f), Random.Range(-95f, -35f)); rigidbody.AddForceAtPosition(force, ballPosition); break; } } } }
26.405941
93
0.506562
[ "MIT" ]
backrunner/Hit-Brick
Assets/Scripts/Bricks/brickBrokenPartController.cs
2,835
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("FlashExcel")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FlashExcel")] [assembly: AssemblyCopyright("Copyright © 2018-2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 会使此程序集中的类型 //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("3a4ece18-cb97-4126-82b2-d60087473309")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号 // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
25.567568
56
0.714588
[ "MIT" ]
MidiSmallYue/FlashExcel
Properties/AssemblyInfo.cs
1,287
C#
using DataAccess.Abstract; using Entities.Concrete; using Entities.DTOs; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace DataAccess.Concrete.InMemory { public class InMemoryCarDal : ICarDal { List<Car> _cars; List<Brand> _brands; List<Color> _colors; public InMemoryCarDal() { _brands = new List<Brand> { new Brand{BrandId=1, BrandName="Alfa Romeo"}, new Brand{BrandId=2, BrandName="Audi"}, new Brand{BrandId=3, BrandName="Ferrari"}, new Brand{BrandId=4, BrandName="BMW"}, new Brand{BrandId=5, BrandName="Porsche"} }; _colors = new List<Color> { new Color{ColorId=1, ColorName="Black"}, new Color{ColorId=2, ColorName="White"}, new Color{ColorId=3, ColorName="Red"}, new Color{ColorId=4, ColorName="Grey"}, new Color{ColorId=5, ColorName="Blue"} }; _cars = new List<Car> { new Car{Id=1, BrandId=1, ColorId=2, ModelYear=2014, DailyPrice=300, Description="Fena değil"}, new Car{Id=2, BrandId=1, ColorId=2, ModelYear=2015, DailyPrice=320, Description="Fena değil"}, new Car{Id=3, BrandId=2, ColorId=2, ModelYear=2019, DailyPrice=390, Description="Bebek gibi"}, new Car{Id=4, BrandId=3, ColorId=2, ModelYear=2021, DailyPrice=850, Description="Adrenalin dolu bi yaşam"}, new Car{Id=5, BrandId=4, ColorId=2, ModelYear=2018, DailyPrice=470, Description="Havalı bir araba"}, new Car{Id=6, BrandId=5, ColorId=2, ModelYear=2017, DailyPrice=600, Description="Zorluklara karşı diren"}, new Car{Id=7, BrandId=4, ColorId=2, ModelYear=2016, DailyPrice=430, Description="Havalı bir araba"}, new Car{Id=8, BrandId=5, ColorId=2, ModelYear=2020, DailyPrice=680, Description="Zorluklara karşı diren"} }; } public void Add(Car car) { _cars.Add(car); Console.WriteLine("Yeni araba eklendi : " + car.Description); } public void Delete(Car car) { Car carToDelete = _cars.SingleOrDefault(c => c.Id == car.Id); _cars.Remove(carToDelete); Console.WriteLine("Araba silme işlemi tamamlandı"); } public Car Get(Expression<Func<Car, bool>> filter) { throw new NotImplementedException(); } public List<Car> GetAll() { return _cars; } public List<Car> GetAll(Expression<Func<Car, bool>> filter = null) { throw new NotImplementedException(); } public List<CarDetailDto> GetCarDetails(Expression<Func<Car, bool>> filter = null) { throw new NotImplementedException(); } public void Update(Car car) { Car carToUpdate = _cars.SingleOrDefault(c => c.Id == car.Id); carToUpdate.Id = car.Id; carToUpdate.BrandId = car.BrandId; carToUpdate.ColorId = car.ColorId; carToUpdate.ModelYear = car.ModelYear; carToUpdate.DailyPrice = car.DailyPrice; carToUpdate.Description = car.Description; Console.WriteLine("Araba bilgileri güncellendi :" + carToUpdate.Description); } } }
36.56701
123
0.575134
[ "MIT" ]
mecazadam/ReCapProject
DataAccess/Concrete/InMemory/InMemoryCarDal.cs
3,561
C#
// Copyright (C) 2015-2022 The Neo Project. // // The Neo.Plugins.StateService is free software distributed under the MIT software license, // see the accompanying file LICENSE in the main directory of the // project or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without // modifications are permitted. using Neo.Cryptography.MPTTrie; using Neo.IO; using Neo.Persistence; using Neo.Plugins.StateService.Network; using System; namespace Neo.Plugins.StateService.Storage { class StateSnapshot : IDisposable { private readonly ISnapshot snapshot; public Trie Trie; public StateSnapshot(IStore store) { snapshot = store.GetSnapshot(); Trie = new Trie(snapshot, CurrentLocalRootHash(), Settings.Default.FullState); } public StateRoot GetStateRoot(uint index) { return snapshot.TryGet(Keys.StateRoot(index))?.AsSerializable<StateRoot>(); } public void AddLocalStateRoot(StateRoot state_root) { snapshot.Put(Keys.StateRoot(state_root.Index), state_root.ToArray()); snapshot.Put(Keys.CurrentLocalRootIndex, BitConverter.GetBytes(state_root.Index)); } public uint? CurrentLocalRootIndex() { var bytes = snapshot.TryGet(Keys.CurrentLocalRootIndex); if (bytes is null) return null; return BitConverter.ToUInt32(bytes); } public UInt256 CurrentLocalRootHash() { var index = CurrentLocalRootIndex(); if (index is null) return null; return GetStateRoot((uint)index)?.RootHash; } public void AddValidatedStateRoot(StateRoot state_root) { if (state_root?.Witness is null) throw new ArgumentException(nameof(state_root) + " missing witness in invalidated state root"); snapshot.Put(Keys.StateRoot(state_root.Index), state_root.ToArray()); snapshot.Put(Keys.CurrentValidatedRootIndex, BitConverter.GetBytes(state_root.Index)); } public uint? CurrentValidatedRootIndex() { var bytes = snapshot.TryGet(Keys.CurrentValidatedRootIndex); if (bytes is null) return null; return BitConverter.ToUInt32(bytes); } public UInt256 CurrentValidatedRootHash() { var index = CurrentLocalRootIndex(); if (index is null) return null; var state_root = GetStateRoot((uint)index); if (state_root is null || state_root.Witness is null) throw new InvalidOperationException(nameof(CurrentValidatedRootHash) + " could not get validated state root"); return state_root.RootHash; } public void Commit() { Trie.Commit(); snapshot.Commit(); } public void Dispose() { snapshot.Dispose(); } } }
33.173913
126
0.6327
[ "MIT" ]
KickSeason/neo-modules
src/StateService/Storage/StateSnapshot.cs
3,052
C#
using System; using System.Threading.Tasks; using Abp.Application.Services; using TakTikan.Tailor.Authorization.Users.Dto; using TakTikan.Tailor.Authorization.Users.Profile.Dto; using TakTikan.Tailor.Dto; namespace TakTikan.Tailor.Authorization.Users.Profile { public interface IProfileAppService : IApplicationService { Task<CurrentUserProfileEditDto> GetCurrentUserProfileForEdit(); Task UpdateCurrentUserProfile(CurrentUserProfileEditDto input); Task ChangePassword(ChangePasswordInput input); Task UpdateProfilePicture(UpdateProfilePictureInput input); Task<GetPasswordComplexitySettingOutput> GetPasswordComplexitySetting(); Task<GetProfilePictureOutput> GetProfilePicture(); Task<GetProfilePictureOutput> GetProfilePictureByUser(long userId); Task<GetProfilePictureOutput> GetProfilePictureByUserName(string username); Task<GetProfilePictureOutput> GetFriendProfilePicture(GetFriendProfilePictureInput input); Task ChangeLanguage(ChangeUserLanguageDto input); Task<UpdateGoogleAuthenticatorKeyOutput> UpdateGoogleAuthenticatorKey(); Task SendVerificationSms(SendVerificationSmsInputDto input); Task VerifySmsCode(VerifySmsCodeInputDto input); Task PrepareCollectedData(); } }
32.414634
98
0.779533
[ "MIT" ]
vahidsaberi/TakTikan-Tailor
aspnet-core/src/TakTikan.Tailor.Application.Shared/Authorization/Users/Profile/IProfileAppService.cs
1,331
C#
using System; using Newtonsoft.Json; namespace TdLib { /// <summary> /// AUTOGENERATED: DO NOT EDIT! /// </summary> public partial class TdApi { public class Invoice : Object { [JsonProperty("@type")] public override string DataType { get; set; } = "invoice"; [JsonProperty("@extra")] public override string Extra { get; set; } [JsonConverter(typeof(Converter))] [JsonProperty("currency")] public string Currency { get; set; } [JsonConverter(typeof(Converter))] [JsonProperty("price_parts")] public LabeledPricePart[] PriceParts { get; set; } [JsonConverter(typeof(Converter))] [JsonProperty("is_test")] public bool IsTest { get; set; } [JsonConverter(typeof(Converter))] [JsonProperty("need_name")] public bool NeedName { get; set; } [JsonConverter(typeof(Converter))] [JsonProperty("need_phone_number")] public bool NeedPhoneNumber { get; set; } [JsonConverter(typeof(Converter))] [JsonProperty("need_email_address")] public bool NeedEmailAddress { get; set; } [JsonConverter(typeof(Converter))] [JsonProperty("need_shipping_address")] public bool NeedShippingAddress { get; set; } [JsonConverter(typeof(Converter))] [JsonProperty("send_phone_number_to_provider")] public bool SendPhoneNumberToProvider { get; set; } [JsonConverter(typeof(Converter))] [JsonProperty("send_email_address_to_provider")] public bool SendEmailAddressToProvider { get; set; } [JsonConverter(typeof(Converter))] [JsonProperty("is_flexible")] public bool IsFlexible { get; set; } } } }
32.87931
94
0.582066
[ "MIT" ]
Behnam-Emamian/tdsharp
TDLib.Api/Objects/Invoice.cs
1,907
C#
namespace PinBot2 { partial class ScrapeUsersExportForm { private System.ComponentModel.IContainer components = null; /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ScrapeUsersExportForm)); this.lblStatus = new System.Windows.Forms.ToolStripStatusLabel(); this.label4 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.txtTimeoutMax = new System.Windows.Forms.NumericUpDown(); this.txtTimeoutMin = new System.Windows.Forms.NumericUpDown(); this.grpTimeout = new System.Windows.Forms.GroupBox(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.grpQueries = new System.Windows.Forms.GroupBox(); this.txtQry = new System.Windows.Forms.TextBox(); this.chkLimitScrape = new System.Windows.Forms.CheckBox(); this.grpLimitScrape = new System.Windows.Forms.GroupBox(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.txtFollowsMax = new System.Windows.Forms.NumericUpDown(); this.txtFollowsMin = new System.Windows.Forms.NumericUpDown(); this.panel = new System.Windows.Forms.Panel(); this.chkCriteria = new System.Windows.Forms.CheckBox(); this.grpCriteria = new System.Windows.Forms.GroupBox(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.chkHasWebsite = new System.Windows.Forms.CheckBox(); this.chkHasTw = new System.Windows.Forms.CheckBox(); this.chkHasFb = new System.Windows.Forms.CheckBox(); this.chkHasCustomPic = new System.Windows.Forms.CheckBox(); this.chkHasLocation = new System.Windows.Forms.CheckBox(); this.chkHasAbout = new System.Windows.Forms.CheckBox(); this.label18 = new System.Windows.Forms.Label(); this.label19 = new System.Windows.Forms.Label(); this.label20 = new System.Windows.Forms.Label(); this.txtPinsMax = new System.Windows.Forms.NumericUpDown(); this.txtPinsMin = new System.Windows.Forms.NumericUpDown(); this.label15 = new System.Windows.Forms.Label(); this.label16 = new System.Windows.Forms.Label(); this.label17 = new System.Windows.Forms.Label(); this.txtBoardsMax = new System.Windows.Forms.NumericUpDown(); this.txtBoardsMin = new System.Windows.Forms.NumericUpDown(); this.label12 = new System.Windows.Forms.Label(); this.label13 = new System.Windows.Forms.Label(); this.label14 = new System.Windows.Forms.Label(); this.txtFollowingMax = new System.Windows.Forms.NumericUpDown(); this.txtFollowingMin = new System.Windows.Forms.NumericUpDown(); this.label1 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label(); this.txtFollowersMax = new System.Windows.Forms.NumericUpDown(); this.txtFollowersMin = new System.Windows.Forms.NumericUpDown(); this.btnScrape = new System.Windows.Forms.Button(); this.btnSelectFile = new System.Windows.Forms.Button(); this.chkAppendToFile = new System.Windows.Forms.CheckBox(); this.flowLayoutPanel2 = new System.Windows.Forms.FlowLayoutPanel(); this.btnStop = new System.Windows.Forms.Button(); this.sfdFile = new System.Windows.Forms.SaveFileDialog(); ((System.ComponentModel.ISupportInitialize)(this.txtTimeoutMax)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtTimeoutMin)).BeginInit(); this.grpTimeout.SuspendLayout(); this.statusStrip1.SuspendLayout(); this.grpQueries.SuspendLayout(); this.grpLimitScrape.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.txtFollowsMax)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtFollowsMin)).BeginInit(); this.panel.SuspendLayout(); this.grpCriteria.SuspendLayout(); this.flowLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.txtPinsMax)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtPinsMin)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtBoardsMax)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtBoardsMin)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtFollowingMax)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtFollowingMin)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtFollowersMax)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtFollowersMin)).BeginInit(); this.flowLayoutPanel2.SuspendLayout(); this.SuspendLayout(); // // lblStatus // this.lblStatus.Name = "lblStatus"; this.lblStatus.Size = new System.Drawing.Size(0, 17); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(248, 36); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(61, 17); this.label4.TabIndex = 8; this.label4.Text = "seconds"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(145, 36); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(32, 17); this.label3.TabIndex = 7; this.label3.Text = "and"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(12, 36); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(62, 17); this.label2.TabIndex = 6; this.label2.Text = "Between"; this.txtTimeoutMax.Location = new System.Drawing.Point(183, 34); this.txtTimeoutMax.Maximum = new decimal(new int[] { 1000, 0, 0, 0}); this.txtTimeoutMax.Minimum = new decimal(new int[] { 2, 0, 0, 0}); this.txtTimeoutMax.Name = "txtTimeoutMax"; this.txtTimeoutMax.Size = new System.Drawing.Size(59, 22); this.txtTimeoutMax.TabIndex = 4; this.txtTimeoutMax.Value = new decimal(new int[] { 5, 0, 0, 0}); this.txtTimeoutMax.ValueChanged += new System.EventHandler(this.txtTimeoutMax_ValueChanged); this.txtTimeoutMin.Location = new System.Drawing.Point(80, 34); this.txtTimeoutMin.Maximum = new decimal(new int[] { 1000, 0, 0, 0}); this.txtTimeoutMin.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.txtTimeoutMin.Name = "txtTimeoutMin"; this.txtTimeoutMin.Size = new System.Drawing.Size(59, 22); this.txtTimeoutMin.TabIndex = 3; this.txtTimeoutMin.Value = new decimal(new int[] { 1, 0, 0, 0}); this.txtTimeoutMin.ValueChanged += new System.EventHandler(this.txtTimeoutMin_ValueChanged); // // grpTimeout // this.grpTimeout.Controls.Add(this.label4); this.grpTimeout.Controls.Add(this.label3); this.grpTimeout.Controls.Add(this.label2); this.grpTimeout.Controls.Add(this.txtTimeoutMax); this.grpTimeout.Controls.Add(this.txtTimeoutMin); this.grpTimeout.Location = new System.Drawing.Point(10, 12); this.grpTimeout.Name = "grpTimeout"; this.grpTimeout.Size = new System.Drawing.Size(318, 71); this.grpTimeout.TabIndex = 5; this.grpTimeout.TabStop = false; this.grpTimeout.Text = "Timeout per page"; // // statusStrip1 // this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.lblStatus}); this.statusStrip1.Location = new System.Drawing.Point(0, 378); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Size = new System.Drawing.Size(665, 22); this.statusStrip1.SizingGrip = false; this.statusStrip1.TabIndex = 11; this.statusStrip1.Text = "statusStrip1"; // // grpQueries // this.grpQueries.Controls.Add(this.txtQry); this.grpQueries.Location = new System.Drawing.Point(334, 12); this.grpQueries.Name = "grpQueries"; this.grpQueries.Size = new System.Drawing.Size(318, 148); this.grpQueries.TabIndex = 10; this.grpQueries.TabStop = false; this.grpQueries.Text = "Queries (one per line)"; this.txtQry.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.txtQry.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F); this.txtQry.Location = new System.Drawing.Point(6, 21); this.txtQry.Margin = new System.Windows.Forms.Padding(6); this.txtQry.Multiline = true; this.txtQry.Name = "txtQry"; this.txtQry.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtQry.Size = new System.Drawing.Size(305, 121); this.txtQry.TabIndex = 24; // // chkLimitScrape // this.chkLimitScrape.AutoSize = true; this.chkLimitScrape.Location = new System.Drawing.Point(19, 88); this.chkLimitScrape.Name = "chkLimitScrape"; this.chkLimitScrape.Size = new System.Drawing.Size(103, 21); this.chkLimitScrape.TabIndex = 7; this.chkLimitScrape.Text = "Scrape limit"; this.chkLimitScrape.UseVisualStyleBackColor = true; this.chkLimitScrape.CheckedChanged += new System.EventHandler(this.chkLimitScrape_CheckedChanged); // // grpLimitScrape // this.grpLimitScrape.Controls.Add(this.label6); this.grpLimitScrape.Controls.Add(this.label7); this.grpLimitScrape.Controls.Add(this.txtFollowsMax); this.grpLimitScrape.Controls.Add(this.txtFollowsMin); this.grpLimitScrape.Enabled = false; this.grpLimitScrape.Location = new System.Drawing.Point(10, 89); this.grpLimitScrape.Name = "grpLimitScrape"; this.grpLimitScrape.Size = new System.Drawing.Size(318, 71); this.grpLimitScrape.TabIndex = 10; this.grpLimitScrape.TabStop = false; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(145, 36); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(32, 17); this.label6.TabIndex = 11; this.label6.Text = "and"; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(12, 36); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(62, 17); this.label7.TabIndex = 9; this.label7.Text = "Between"; this.txtFollowsMax.Location = new System.Drawing.Point(183, 34); this.txtFollowsMax.Maximum = new decimal(new int[] { 100000, 0, 0, 0}); this.txtFollowsMax.Minimum = new decimal(new int[] { 2, 0, 0, 0}); this.txtFollowsMax.Name = "txtFollowsMax"; this.txtFollowsMax.Size = new System.Drawing.Size(59, 22); this.txtFollowsMax.TabIndex = 10; this.txtFollowsMax.Value = new decimal(new int[] { 20, 0, 0, 0}); this.txtFollowsMin.Location = new System.Drawing.Point(80, 34); this.txtFollowsMin.Maximum = new decimal(new int[] { 100000, 0, 0, 0}); this.txtFollowsMin.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.txtFollowsMin.Name = "txtFollowsMin"; this.txtFollowsMin.Size = new System.Drawing.Size(59, 22); this.txtFollowsMin.TabIndex = 8; this.txtFollowsMin.Value = new decimal(new int[] { 10, 0, 0, 0}); this.panel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.panel.Controls.Add(this.chkCriteria); this.panel.Controls.Add(this.grpCriteria); this.panel.Controls.Add(this.chkLimitScrape); this.panel.Controls.Add(this.grpLimitScrape); this.panel.Controls.Add(this.grpQueries); this.panel.Controls.Add(this.grpTimeout); this.panel.Location = new System.Drawing.Point(2, 39); this.panel.Name = "panel"; this.panel.Size = new System.Drawing.Size(660, 336); this.panel.TabIndex = 10; // // chkCriteria // this.chkCriteria.AutoSize = true; this.chkCriteria.Checked = true; this.chkCriteria.CheckState = System.Windows.Forms.CheckState.Checked; this.chkCriteria.Location = new System.Drawing.Point(19, 164); this.chkCriteria.Name = "chkCriteria"; this.chkCriteria.Size = new System.Drawing.Size(111, 21); this.chkCriteria.TabIndex = 10; this.chkCriteria.Text = "User criteria:"; this.chkCriteria.UseVisualStyleBackColor = true; this.chkCriteria.CheckedChanged += new System.EventHandler(this.chkCriteria_CheckedChanged); // // grpCriteria // this.grpCriteria.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.grpCriteria.Controls.Add(this.flowLayoutPanel1); this.grpCriteria.Controls.Add(this.label18); this.grpCriteria.Controls.Add(this.label19); this.grpCriteria.Controls.Add(this.label20); this.grpCriteria.Controls.Add(this.txtPinsMax); this.grpCriteria.Controls.Add(this.txtPinsMin); this.grpCriteria.Controls.Add(this.label15); this.grpCriteria.Controls.Add(this.label16); this.grpCriteria.Controls.Add(this.label17); this.grpCriteria.Controls.Add(this.txtBoardsMax); this.grpCriteria.Controls.Add(this.txtBoardsMin); this.grpCriteria.Controls.Add(this.label12); this.grpCriteria.Controls.Add(this.label13); this.grpCriteria.Controls.Add(this.label14); this.grpCriteria.Controls.Add(this.txtFollowingMax); this.grpCriteria.Controls.Add(this.txtFollowingMin); this.grpCriteria.Controls.Add(this.label1); this.grpCriteria.Controls.Add(this.label10); this.grpCriteria.Controls.Add(this.label11); this.grpCriteria.Controls.Add(this.txtFollowersMax); this.grpCriteria.Controls.Add(this.txtFollowersMin); this.grpCriteria.Location = new System.Drawing.Point(10, 166); this.grpCriteria.Name = "grpCriteria"; this.grpCriteria.Size = new System.Drawing.Size(642, 167); this.grpCriteria.TabIndex = 12; this.grpCriteria.TabStop = false; this.flowLayoutPanel1.Controls.Add(this.chkHasWebsite); this.flowLayoutPanel1.Controls.Add(this.chkHasTw); this.flowLayoutPanel1.Controls.Add(this.chkHasFb); this.flowLayoutPanel1.Controls.Add(this.chkHasCustomPic); this.flowLayoutPanel1.Controls.Add(this.chkHasLocation); this.flowLayoutPanel1.Controls.Add(this.chkHasAbout); this.flowLayoutPanel1.FlowDirection = System.Windows.Forms.FlowDirection.BottomUp; this.flowLayoutPanel1.Location = new System.Drawing.Point(350, 37); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; this.flowLayoutPanel1.Size = new System.Drawing.Size(285, 112); this.flowLayoutPanel1.TabIndex = 35; // // chkHasWebsite // this.chkHasWebsite.AutoSize = true; this.chkHasWebsite.Location = new System.Drawing.Point(3, 88); this.chkHasWebsite.Name = "chkHasWebsite"; this.chkHasWebsite.Size = new System.Drawing.Size(106, 21); this.chkHasWebsite.TabIndex = 29; this.chkHasWebsite.Text = "Has website"; this.chkHasWebsite.UseVisualStyleBackColor = true; // // chkHasTw // this.chkHasTw.AutoSize = true; this.chkHasTw.Location = new System.Drawing.Point(3, 61); this.chkHasTw.Name = "chkHasTw"; this.chkHasTw.Size = new System.Drawing.Size(101, 21); this.chkHasTw.TabIndex = 30; this.chkHasTw.Text = "Has Twitter"; this.chkHasTw.UseVisualStyleBackColor = true; // // chkHasFb // this.chkHasFb.AutoSize = true; this.chkHasFb.Location = new System.Drawing.Point(3, 34); this.chkHasFb.Name = "chkHasFb"; this.chkHasFb.Size = new System.Drawing.Size(121, 21); this.chkHasFb.TabIndex = 31; this.chkHasFb.Text = "Has Facebook"; this.chkHasFb.UseVisualStyleBackColor = true; // // chkHasCustomPic // this.chkHasCustomPic.AutoSize = true; this.chkHasCustomPic.Location = new System.Drawing.Point(3, 7); this.chkHasCustomPic.Name = "chkHasCustomPic"; this.chkHasCustomPic.Size = new System.Drawing.Size(151, 21); this.chkHasCustomPic.TabIndex = 32; this.chkHasCustomPic.Text = "Has custom picture"; this.chkHasCustomPic.UseVisualStyleBackColor = true; // // chkHasLocation // this.chkHasLocation.AutoSize = true; this.chkHasLocation.Location = new System.Drawing.Point(160, 88); this.chkHasLocation.Name = "chkHasLocation"; this.chkHasLocation.Size = new System.Drawing.Size(108, 21); this.chkHasLocation.TabIndex = 33; this.chkHasLocation.Text = "Has location"; this.chkHasLocation.UseVisualStyleBackColor = true; // // chkHasAbout // this.chkHasAbout.AutoSize = true; this.chkHasAbout.Location = new System.Drawing.Point(160, 61); this.chkHasAbout.Name = "chkHasAbout"; this.chkHasAbout.Size = new System.Drawing.Size(121, 21); this.chkHasAbout.TabIndex = 34; this.chkHasAbout.Text = "Has about text"; this.chkHasAbout.UseVisualStyleBackColor = true; // // label18 // this.label18.AutoSize = true; this.label18.Location = new System.Drawing.Point(248, 132); this.label18.Name = "label18"; this.label18.Size = new System.Drawing.Size(34, 17); this.label18.TabIndex = 28; this.label18.Text = "pins"; // // label19 // this.label19.AutoSize = true; this.label19.Location = new System.Drawing.Point(145, 132); this.label19.Name = "label19"; this.label19.Size = new System.Drawing.Size(32, 17); this.label19.TabIndex = 27; this.label19.Text = "and"; // // label20 // this.label20.AutoSize = true; this.label20.Location = new System.Drawing.Point(12, 132); this.label20.Name = "label20"; this.label20.Size = new System.Drawing.Size(62, 17); this.label20.TabIndex = 26; this.label20.Text = "Between"; // // this.txtPinsMax.Location = new System.Drawing.Point(183, 130); this.txtPinsMax.Maximum = new decimal(new int[] { 100000000, 0, 0, 0}); this.txtPinsMax.Minimum = new decimal(new int[] { 2, 0, 0, 0}); this.txtPinsMax.Name = "txtPinsMax"; this.txtPinsMax.Size = new System.Drawing.Size(59, 22); this.txtPinsMax.TabIndex = 18; this.txtPinsMax.Value = new decimal(new int[] { 10000, 0, 0, 0}); this.txtPinsMax.ValueChanged += new System.EventHandler(this.txtPinsMax_ValueChanged); // // this.txtPinsMin.Location = new System.Drawing.Point(80, 130); this.txtPinsMin.Maximum = new decimal(new int[] { 100000000, 0, 0, 0}); this.txtPinsMin.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.txtPinsMin.Name = "txtPinsMin"; this.txtPinsMin.Size = new System.Drawing.Size(59, 22); this.txtPinsMin.TabIndex = 17; this.txtPinsMin.Value = new decimal(new int[] { 100, 0, 0, 0}); this.txtPinsMin.ValueChanged += new System.EventHandler(this.txtPinsMin_ValueChanged); // // label15 // this.label15.AutoSize = true; this.label15.Location = new System.Drawing.Point(248, 102); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(52, 17); this.label15.TabIndex = 23; this.label15.Text = "boards"; // // label16 // this.label16.AutoSize = true; this.label16.Location = new System.Drawing.Point(145, 102); this.label16.Name = "label16"; this.label16.Size = new System.Drawing.Size(32, 17); this.label16.TabIndex = 22; this.label16.Text = "and"; // // label17 // this.label17.AutoSize = true; this.label17.Location = new System.Drawing.Point(12, 102); this.label17.Name = "label17"; this.label17.Size = new System.Drawing.Size(62, 17); this.label17.TabIndex = 21; this.label17.Text = "Between"; // // this.txtBoardsMax.Location = new System.Drawing.Point(183, 100); this.txtBoardsMax.Maximum = new decimal(new int[] { 5000000, 0, 0, 0}); this.txtBoardsMax.Minimum = new decimal(new int[] { 2, 0, 0, 0}); this.txtBoardsMax.Name = "txtBoardsMax"; this.txtBoardsMax.Size = new System.Drawing.Size(59, 22); this.txtBoardsMax.TabIndex = 16; this.txtBoardsMax.Value = new decimal(new int[] { 100, 0, 0, 0}); this.txtBoardsMax.ValueChanged += new System.EventHandler(this.txtBoardsMax_ValueChanged); // // this.txtBoardsMin.Location = new System.Drawing.Point(80, 100); this.txtBoardsMin.Maximum = new decimal(new int[] { 5000, 0, 0, 0}); this.txtBoardsMin.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.txtBoardsMin.Name = "txtBoardsMin"; this.txtBoardsMin.Size = new System.Drawing.Size(59, 22); this.txtBoardsMin.TabIndex = 15; this.txtBoardsMin.Value = new decimal(new int[] { 30, 0, 0, 0}); this.txtBoardsMin.ValueChanged += new System.EventHandler(this.txtBoardsMin_ValueChanged); // // label12 // this.label12.AutoSize = true; this.label12.Location = new System.Drawing.Point(248, 72); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(62, 17); this.label12.TabIndex = 18; this.label12.Text = "following"; // // label13 // this.label13.AutoSize = true; this.label13.Location = new System.Drawing.Point(145, 72); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(32, 17); this.label13.TabIndex = 17; this.label13.Text = "and"; // // label14 // this.label14.AutoSize = true; this.label14.Location = new System.Drawing.Point(12, 72); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(62, 17); this.label14.TabIndex = 16; this.label14.Text = "Between"; // // this.txtFollowingMax.Location = new System.Drawing.Point(183, 70); this.txtFollowingMax.Maximum = new decimal(new int[] { 100000000, 0, 0, 0}); this.txtFollowingMax.Minimum = new decimal(new int[] { 2, 0, 0, 0}); this.txtFollowingMax.Name = "txtFollowingMax"; this.txtFollowingMax.Size = new System.Drawing.Size(59, 22); this.txtFollowingMax.TabIndex = 14; this.txtFollowingMax.Value = new decimal(new int[] { 2000, 0, 0, 0}); this.txtFollowingMax.ValueChanged += new System.EventHandler(this.txtFollowingMax_ValueChanged); // // this.txtFollowingMin.Location = new System.Drawing.Point(80, 70); this.txtFollowingMin.Maximum = new decimal(new int[] { 100000000, 0, 0, 0}); this.txtFollowingMin.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.txtFollowingMin.Name = "txtFollowingMin"; this.txtFollowingMin.Size = new System.Drawing.Size(59, 22); this.txtFollowingMin.TabIndex = 13; this.txtFollowingMin.Value = new decimal(new int[] { 500, 0, 0, 0}); this.txtFollowingMin.ValueChanged += new System.EventHandler(this.txtFollowingMin_ValueChanged); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(248, 42); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(63, 17); this.label1.TabIndex = 13; this.label1.Text = "followers"; // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(145, 42); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(32, 17); this.label10.TabIndex = 12; this.label10.Text = "and"; // // label11 // this.label11.AutoSize = true; this.label11.Location = new System.Drawing.Point(12, 42); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(62, 17); this.label11.TabIndex = 11; this.label11.Text = "Between"; // // this.txtFollowersMax.Location = new System.Drawing.Point(183, 40); this.txtFollowersMax.Maximum = new decimal(new int[] { 100000000, 0, 0, 0}); this.txtFollowersMax.Minimum = new decimal(new int[] { 2, 0, 0, 0}); this.txtFollowersMax.Name = "txtFollowersMax"; this.txtFollowersMax.Size = new System.Drawing.Size(59, 22); this.txtFollowersMax.TabIndex = 12; this.txtFollowersMax.Value = new decimal(new int[] { 5000, 0, 0, 0}); this.txtFollowersMax.ValueChanged += new System.EventHandler(this.txtFollowersMax_ValueChanged); // // this.txtFollowersMin.Location = new System.Drawing.Point(80, 40); this.txtFollowersMin.Maximum = new decimal(new int[] { 100000000, 0, 0, 0}); this.txtFollowersMin.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.txtFollowersMin.Name = "txtFollowersMin"; this.txtFollowersMin.Size = new System.Drawing.Size(59, 22); this.txtFollowersMin.TabIndex = 11; this.txtFollowersMin.Value = new decimal(new int[] { 100, 0, 0, 0}); this.txtFollowersMin.ValueChanged += new System.EventHandler(this.txtFollowersMin_ValueChanged); // // this.btnScrape.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnScrape.Enabled = false; this.btnScrape.Location = new System.Drawing.Point(495, 3); this.btnScrape.Name = "btnScrape"; this.btnScrape.Size = new System.Drawing.Size(75, 28); this.btnScrape.TabIndex = 2; this.btnScrape.Text = "Start"; this.btnScrape.UseVisualStyleBackColor = true; this.btnScrape.Click += new System.EventHandler(this.btnScrape_Click); // // this.btnSelectFile.Location = new System.Drawing.Point(390, 3); this.btnSelectFile.Name = "btnSelectFile"; this.btnSelectFile.Size = new System.Drawing.Size(99, 28); this.btnSelectFile.TabIndex = 12; this.btnSelectFile.Text = "Select file..."; this.btnSelectFile.UseVisualStyleBackColor = true; this.btnSelectFile.Click += new System.EventHandler(this.btnSelectFile_Click); // // chkAppendToFile // this.chkAppendToFile.AutoSize = true; this.chkAppendToFile.Location = new System.Drawing.Point(267, 3); this.chkAppendToFile.Name = "chkAppendToFile"; this.chkAppendToFile.Size = new System.Drawing.Size(117, 21); this.chkAppendToFile.TabIndex = 13; this.chkAppendToFile.Text = "Append to file"; this.chkAppendToFile.UseVisualStyleBackColor = true; // // this.flowLayoutPanel2.Controls.Add(this.btnStop); this.flowLayoutPanel2.Controls.Add(this.btnScrape); this.flowLayoutPanel2.Controls.Add(this.btnSelectFile); this.flowLayoutPanel2.Controls.Add(this.chkAppendToFile); this.flowLayoutPanel2.FlowDirection = System.Windows.Forms.FlowDirection.RightToLeft; this.flowLayoutPanel2.Location = new System.Drawing.Point(5, 4); this.flowLayoutPanel2.Name = "flowLayoutPanel2"; this.flowLayoutPanel2.Size = new System.Drawing.Size(654, 35); this.flowLayoutPanel2.TabIndex = 25; // // this.btnStop.Enabled = false; this.btnStop.Location = new System.Drawing.Point(576, 3); this.btnStop.Name = "btnStop"; this.btnStop.Size = new System.Drawing.Size(75, 28); this.btnStop.TabIndex = 14; this.btnStop.Text = "Stop"; this.btnStop.UseVisualStyleBackColor = true; this.btnStop.Click += new System.EventHandler(this.btnStop_Click); // // sfdFile // this.sfdFile.OverwritePrompt = false; this.sfdFile.FileOk += new System.ComponentModel.CancelEventHandler(this.sfdFile_FileOk); // // ScrapeUsersExportForm // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(665, 400); this.Controls.Add(this.flowLayoutPanel2); this.Controls.Add(this.statusStrip1); this.Controls.Add(this.panel); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "ScrapeUsersExportForm"; this.Text = "Scrape usernames and Export"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.ScrapeUsersExportForm_FormClosing); ((System.ComponentModel.ISupportInitialize)(this.txtTimeoutMax)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtTimeoutMin)).EndInit(); this.grpTimeout.ResumeLayout(false); this.grpTimeout.PerformLayout(); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); this.grpQueries.ResumeLayout(false); this.grpQueries.PerformLayout(); this.grpLimitScrape.ResumeLayout(false); this.grpLimitScrape.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.txtFollowsMax)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtFollowsMin)).EndInit(); this.panel.ResumeLayout(false); this.panel.PerformLayout(); this.grpCriteria.ResumeLayout(false); this.grpCriteria.PerformLayout(); this.flowLayoutPanel1.ResumeLayout(false); this.flowLayoutPanel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.txtPinsMax)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtPinsMin)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtBoardsMax)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtBoardsMin)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtFollowingMax)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtFollowingMin)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtFollowersMax)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtFollowersMin)).EndInit(); this.flowLayoutPanel2.ResumeLayout(false); this.flowLayoutPanel2.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ToolStripStatusLabel lblStatus; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.NumericUpDown txtTimeoutMax; private System.Windows.Forms.NumericUpDown txtTimeoutMin; private System.Windows.Forms.GroupBox grpTimeout; private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.GroupBox grpQueries; private System.Windows.Forms.TextBox txtQry; private System.Windows.Forms.CheckBox chkLimitScrape; private System.Windows.Forms.GroupBox grpLimitScrape; private System.Windows.Forms.Panel panel; private System.Windows.Forms.Button btnScrape; private System.Windows.Forms.GroupBox grpCriteria; private System.Windows.Forms.Label label18; private System.Windows.Forms.Label label19; private System.Windows.Forms.Label label20; private System.Windows.Forms.NumericUpDown txtPinsMax; private System.Windows.Forms.NumericUpDown txtPinsMin; private System.Windows.Forms.Label label15; private System.Windows.Forms.Label label16; private System.Windows.Forms.Label label17; private System.Windows.Forms.NumericUpDown txtBoardsMax; private System.Windows.Forms.NumericUpDown txtBoardsMin; private System.Windows.Forms.Label label12; private System.Windows.Forms.Label label13; private System.Windows.Forms.Label label14; private System.Windows.Forms.NumericUpDown txtFollowingMax; private System.Windows.Forms.NumericUpDown txtFollowingMin; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label11; private System.Windows.Forms.NumericUpDown txtFollowersMax; private System.Windows.Forms.NumericUpDown txtFollowersMin; private System.Windows.Forms.CheckBox chkCriteria; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label7; private System.Windows.Forms.NumericUpDown txtFollowsMax; private System.Windows.Forms.NumericUpDown txtFollowsMin; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private System.Windows.Forms.CheckBox chkHasWebsite; private System.Windows.Forms.CheckBox chkHasTw; private System.Windows.Forms.CheckBox chkHasFb; private System.Windows.Forms.CheckBox chkHasCustomPic; private System.Windows.Forms.CheckBox chkHasLocation; private System.Windows.Forms.CheckBox chkHasAbout; private System.Windows.Forms.Button btnSelectFile; private System.Windows.Forms.CheckBox chkAppendToFile; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel2; private System.Windows.Forms.Button btnStop; private System.Windows.Forms.SaveFileDialog sfdFile; } }
45.667045
159
0.582104
[ "MIT" ]
inevolin/PinBot-2
PinBot2/SpecialFeatures/ScrapeUsersExportForm.Designer.cs
40,189
C#
namespace TestStack.BDDfy { public interface IScenarioScanner { Scenario Scan(object testObject); } }
17.285714
41
0.677686
[ "MIT" ]
MehdiK/TestStack.BDDfy
TestStack.BDDfy/Scanners/ScenarioScanners/IScenarioScanner.cs
121
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeQuality.Analyzers.QualityGuidelines { /// <summary> /// CA2119: Seal methods that satisfy private interfaces /// </summary> [ExportCodeFixProvider(LanguageNames.CSharp /*, LanguageNames.VisualBasic*/), Shared] // note: disabled VB until SyntaxGenerator.WithStatements works public sealed class SealMethodsThatSatisfyPrivateInterfacesFixer : CodeFixProvider { public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(SealMethodsThatSatisfyPrivateInterfacesAnalyzer.RuleId); public sealed override FixAllProvider GetFixAllProvider() { return WellKnownFixAllProviders.BatchFixer; } public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var model = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); var gen = SyntaxGenerator.GetGenerator(context.Document); foreach (var dx in context.Diagnostics) { if (dx.Location.IsInSource) { var root = dx.Location.SourceTree.GetRoot(context.CancellationToken); var declarationNode = gen.GetDeclaration(root.FindToken(dx.Location.SourceSpan.Start).Parent); if (declarationNode != null) { var solution = context.Document.Project.Solution; var symbol = model.GetDeclaredSymbol(declarationNode, context.CancellationToken); if (symbol != null) { if (!(symbol is INamedTypeSymbol)) { if (symbol.IsOverride) { context.RegisterCodeFix(new ChangeModifierAction(MicrosoftQualityGuidelinesAnalyzersResources.MakeMemberNotOverridable, "MakeMemberNotOverridable", solution, symbol, DeclarationModifiers.From(symbol) + DeclarationModifiers.Sealed), dx); } else if (symbol.IsVirtual) { context.RegisterCodeFix(new ChangeModifierAction(MicrosoftQualityGuidelinesAnalyzersResources.MakeMemberNotOverridable, "MakeMemberNotOverridable", solution, symbol, DeclarationModifiers.From(symbol) - DeclarationModifiers.Virtual), dx); } else if (symbol.IsAbstract) { context.RegisterCodeFix(new ChangeModifierAction(MicrosoftQualityGuidelinesAnalyzersResources.MakeMemberNotOverridable, "MakeMemberNotOverridable", solution, symbol, DeclarationModifiers.From(symbol) - DeclarationModifiers.Abstract), dx); } // trigger containing type code fixes below symbol = symbol.ContainingType; } // if the diagnostic identified a type then it is the containing type of the member if (symbol is INamedTypeSymbol type) { // cannot make abstract type sealed because they cannot be constructed if (!type.IsAbstract) { context.RegisterCodeFix(new ChangeModifierAction(MicrosoftQualityGuidelinesAnalyzersResources.MakeDeclaringTypeSealed, "MakeDeclaringTypeSealed", solution, type, DeclarationModifiers.From(type) + DeclarationModifiers.Sealed), dx); } context.RegisterCodeFix(new ChangeAccessibilityAction(MicrosoftQualityGuidelinesAnalyzersResources.MakeDeclaringTypeInternal, "MakeDeclaringTypeInternal", solution, type, Accessibility.Internal), dx); } } } } } } private abstract class ChangeSymbolAction : CodeAction { public ChangeSymbolAction(string title, string equivalenceKey, Solution solution, ISymbol symbol) { Title = title; EquivalenceKey = equivalenceKey; Solution = solution; Symbol = symbol; } public override string Title { get; } public override string EquivalenceKey { get; } public Solution Solution { get; } public ISymbol Symbol { get; } } private class ChangeModifierAction : ChangeSymbolAction { private readonly DeclarationModifiers _newModifiers; public ChangeModifierAction(string title, string equivalenceKey, Solution solution, ISymbol symbol, DeclarationModifiers newModifiers) : base(title, equivalenceKey, solution, symbol) { _newModifiers = newModifiers; } protected async override Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken) { var editor = SymbolEditor.Create(this.Solution); await editor.EditAllDeclarationsAsync(this.Symbol, (e, d) => { e.SetModifiers(d, _newModifiers); if (this.Symbol.IsAbstract && !_newModifiers.IsAbstract && this.Symbol.Kind == SymbolKind.Method) { e.ReplaceNode(d, (_d, g) => g.WithStatements(_d, Array.Empty<SyntaxNode>())); } } , cancellationToken).ConfigureAwait(false); return editor.ChangedSolution; } } private class ChangeAccessibilityAction : ChangeSymbolAction { private readonly Accessibility _newAccessibility; public ChangeAccessibilityAction(string title, string equivalenceKey, Solution solution, ISymbol symbol, Accessibility newAccessibilty) : base(title, equivalenceKey, solution, symbol) { _newAccessibility = newAccessibilty; } protected async override Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken) { var editor = SymbolEditor.Create(this.Solution); await editor.EditAllDeclarationsAsync(this.Symbol, (e, d) => e.SetAccessibility(d, _newAccessibility), cancellationToken).ConfigureAwait(false); return editor.ChangedSolution; } } } }
50.622378
274
0.59732
[ "Apache-2.0" ]
LingxiaChen/roslyn-analyzers
src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/SealMethodsThatSatisfyPrivateInterfaces.Fixer.cs
7,239
C#
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Reflection; using System.Windows.Forms; using Microsoft.SPOT.Emulator; using Microsoft.SPOT.Hardware; namespace Microsoft.SPOT.Emulator.Temperature { /// <summary> /// Connects a button to a GPIO pin. This class is a WinForm control. /// </summary> public class Button : Control { // Contains the GPIO pin that this button controls. Gpio.GpioPort _port; // Stores whether the button is pressed. bool _pressed; Image _image; Image _imagePressed; // A key that enables input via the keyboard. Keys _key; delegate void PortWriteDelegate(bool fState); /// <summary> /// The default constructor. /// </summary> public Button() { _image = Properties.Resources.DefaultButtonUp; _imagePressed = Properties.Resources.DefaultButtonDown; this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); this.SetStyle(ControlStyles.Opaque, true); } /// <summary> /// Gets or sets the GPIO pin that this button is responsible for /// toggling. /// </summary> public Gpio.GpioPort Port { get { return _port; } set { _port = value; } } /// <summary> /// Gets or sets the key that this button should respond to. This is /// mainly for use if this control is a child of a ButtonCollection /// control with keyboard focus. /// </summary> public Keys Key { get { return _key; } set { _key = value; } } /// <summary> /// Sets the state of the button. /// </summary> /// <param name="pressed">Whether the button is depressed.</param> internal void OnButtonStateChanged(bool pressed) { if (_port != null) { if (_pressed != pressed) { _pressed = pressed; bool val = false; switch (_port.Resistor) { case Microsoft.SPOT.Emulator.Gpio.GpioResistorMode.Disabled: case Microsoft.SPOT.Emulator.Gpio.GpioResistorMode.PullUp: val = pressed; break; case Microsoft.SPOT.Emulator.Gpio.GpioResistorMode.PullDown: val = !pressed; break; } // Marshal to the MicroFramework thread. There's no need to // wait for a response; just post the message. _port.BeginInvoke( new PortWriteDelegate(_port.Write), !val ); this.Invalidate(); } } } /// <summary> /// Returns whether the specified key is the input key. /// </summary> /// <param name="keyData"></param> /// <returns>true if the specified key is the input key; otherwise, /// false.</returns> protected override bool IsInputKey(Keys keyData) { return _key == keyData; } /// <summary> /// Paints the control. Either Image or ImagePressed is drawn, /// depending on the state of the button. /// </summary> protected override void OnPaint(PaintEventArgs e) { Image image = _pressed ? _imagePressed : _image; e.Graphics.DrawImage(image, 0, 0, new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel); base.OnPaint(e); } /// <summary> /// If this control has focus, any keypress triggers the GPIO port. /// Normally, this control does not have focus. Instead, it is a child /// of a ButtonCollection. /// </summary> protected override void OnKeyDown(KeyEventArgs e) { OnButtonStateChanged(true); base.OnKeyDown(e); } /// <summary> /// If this control has focus, any keypress triggers the GPIO port. /// Normally, this control does not have focus. Instead, it is a child /// of a ButtonCollection. /// </summary> protected override void OnKeyUp(KeyEventArgs e) { OnButtonStateChanged(false); base.OnKeyUp(e); } /// <summary> /// Responds to mouse down events by depressing the button. /// </summary> protected override void OnMouseDown(MouseEventArgs e) { OnButtonStateChanged(true); base.OnMouseDown(e); } /// <summary> /// Responds to mouse up events by releasing the button. /// </summary> protected override void OnMouseUp(MouseEventArgs e) { OnButtonStateChanged(false); base.OnMouseUp(e); } } }
32.582857
200
0.494563
[ "Apache-2.0" ]
Sirokujira/MicroFrameworkPK_v4_3
Product/Samples/TemperatureSample/TemperatureEmulator/Button.cs
5,702
C#
/* ========================================================================================== */ /* */ /* FMOD Ex - C# Wrapper . Copyright (c), Firelight Technologies Pty, Ltd. 2004-2014. */ /* */ /* ========================================================================================== */ using System; using System.Text; using System.Runtime.InteropServices; namespace FMOD { /* FMOD version number. Check this against FMOD::System::getVersion / System_GetVersion 0xaaaabbcc -> aaaa = major version number. bb = minor version number. cc = development version number. */ public class VERSION { public const int number = 0x00010503; #if WIN64 public const string dll = "fmod64"; #else public const string dll = "fmod"; #endif } /* FMOD types */ /* [ENUM] [ [DESCRIPTION] error codes. Returned from every function. [REMARKS] [SEE_ALSO] ] */ public enum RESULT : int { OK, /* No errors. */ ERR_BADCOMMAND, /* Tried to call a function on a data type that does not allow this type of functionality (ie calling Sound::lock on a streaming sound). */ ERR_CHANNEL_ALLOC, /* Error trying to allocate a channel. */ ERR_CHANNEL_STOLEN, /* The specified channel has been reused to play another sound. */ ERR_DMA, /* DMA Failure. See debug output for more information. */ ERR_DSP_CONNECTION, /* DSP connection error. Connection possibly caused a cyclic dependency or connected dsps with incompatible buffer counts. */ ERR_DSP_DONTPROCESS, /* DSP return code from a DSP process query callback. Tells mixer not to call the process callback and therefore not consume CPU. Use this to optimize the DSP graph. */ ERR_DSP_FORMAT, /* DSP Format error. A DSP unit may have attempted to connect to this network with the wrong format, or a matrix may have been set with the wrong size if the target unit has a specified channel map. */ ERR_DSP_INUSE, /* DSP is already in the mixer's DSP network. It must be removed before being reinserted or released. */ ERR_DSP_NOTFOUND, /* DSP connection error. Couldn't find the DSP unit specified. */ ERR_DSP_RESERVED, /* DSP operation error. Cannot perform operation on this DSP as it is reserved by the system. */ ERR_DSP_SILENCE, /* DSP return code from a DSP process query callback. Tells mixer silence would be produced from read, so go idle and not consume CPU. Use this to optimize the DSP graph. */ ERR_DSP_TYPE, /* DSP operation cannot be performed on a DSP of this type. */ ERR_FILE_BAD, /* Error loading file. */ ERR_FILE_COULDNOTSEEK, /* Couldn't perform seek operation. This is a limitation of the medium (ie netstreams) or the file format. */ ERR_FILE_DISKEJECTED, /* Media was ejected while reading. */ ERR_FILE_EOF, /* End of file unexpectedly reached while trying to read essential data (truncated?). */ ERR_FILE_ENDOFDATA, /* End of current chunk reached while trying to read data. */ ERR_FILE_NOTFOUND, /* File not found. */ ERR_FORMAT, /* Unsupported file or audio format. */ ERR_HEADER_MISMATCH, /* There is a version mismatch between the FMOD header and either the FMOD Studio library or the FMOD Low Level library. */ ERR_HTTP, /* A HTTP error occurred. This is a catch-all for HTTP errors not listed elsewhere. */ ERR_HTTP_ACCESS, /* The specified resource requires authentication or is forbidden. */ ERR_HTTP_PROXY_AUTH, /* Proxy authentication is required to access the specified resource. */ ERR_HTTP_SERVER_ERROR, /* A HTTP server error occurred. */ ERR_HTTP_TIMEOUT, /* The HTTP request timed out. */ ERR_INITIALIZATION, /* FMOD was not initialized correctly to support this function. */ ERR_INITIALIZED, /* Cannot call this command after System::init. */ ERR_INTERNAL, /* An error occurred that wasn't supposed to. Contact support. */ ERR_INVALID_FLOAT, /* Value passed in was a NaN, Inf or denormalized float. */ ERR_INVALID_HANDLE, /* An invalid object handle was used. */ ERR_INVALID_PARAM, /* An invalid parameter was passed to this function. */ ERR_INVALID_POSITION, /* An invalid seek position was passed to this function. */ ERR_INVALID_SPEAKER, /* An invalid speaker was passed to this function based on the current speaker mode. */ ERR_INVALID_SYNCPOINT, /* The syncpoint did not come from this sound handle. */ ERR_INVALID_THREAD, /* Tried to call a function on a thread that is not supported. */ ERR_INVALID_VECTOR, /* The vectors passed in are not unit length, or perpendicular. */ ERR_MAXAUDIBLE, /* Reached maximum audible playback count for this sound's soundgroup. */ ERR_MEMORY, /* Not enough memory or resources. */ ERR_MEMORY_CANTPOINT, /* Can't use FMOD_OPENMEMORY_POINT on non PCM source data, or non mp3/xma/adpcm data if FMOD_CREATECOMPRESSEDSAMPLE was used. */ ERR_NEEDS3D, /* Tried to call a command on a 2d sound when the command was meant for 3d sound. */ ERR_NEEDSHARDWARE, /* Tried to use a feature that requires hardware support. */ ERR_NET_CONNECT, /* Couldn't connect to the specified host. */ ERR_NET_SOCKET_ERROR, /* A socket error occurred. This is a catch-all for socket-related errors not listed elsewhere. */ ERR_NET_URL, /* The specified URL couldn't be resolved. */ ERR_NET_WOULD_BLOCK, /* Operation on a non-blocking socket could not complete immediately. */ ERR_NOTREADY, /* Operation could not be performed because specified sound/DSP connection is not ready. */ ERR_OUTPUT_ALLOCATED, /* Error initializing output device, but more specifically, the output device is already in use and cannot be reused. */ ERR_OUTPUT_CREATEBUFFER, /* Error creating hardware sound buffer. */ ERR_OUTPUT_DRIVERCALL, /* A call to a standard soundcard driver failed, which could possibly mean a bug in the driver or resources were missing or exhausted. */ ERR_OUTPUT_FORMAT, /* Soundcard does not support the specified format. */ ERR_OUTPUT_INIT, /* Error initializing output device. */ ERR_OUTPUT_NODRIVERS, /* The output device has no drivers installed. If pre-init, FMOD_OUTPUT_NOSOUND is selected as the output mode. If post-init, the function just fails. */ ERR_PLUGIN, /* An unspecified error has been returned from a plugin. */ ERR_PLUGIN_MISSING, /* A requested output, dsp unit type or codec was not available. */ ERR_PLUGIN_RESOURCE, /* A resource that the plugin requires cannot be found. (ie the DLS file for MIDI playback) */ ERR_PLUGIN_VERSION, /* A plugin was built with an unsupported SDK version. */ ERR_RECORD, /* An error occurred trying to initialize the recording device. */ ERR_REVERB_CHANNELGROUP, /* Reverb properties cannot be set on this channel because a parent channelgroup owns the reverb connection. */ ERR_REVERB_INSTANCE, /* Specified instance in FMOD_REVERB_PROPERTIES couldn't be set. Most likely because it is an invalid instance number or the reverb doesn't exist. */ ERR_SUBSOUNDS, /* The error occurred because the sound referenced contains subsounds when it shouldn't have, or it doesn't contain subsounds when it should have. The operation may also not be able to be performed on a parent sound. */ ERR_SUBSOUND_ALLOCATED, /* This subsound is already being used by another sound, you cannot have more than one parent to a sound. Null out the other parent's entry first. */ ERR_SUBSOUND_CANTMOVE, /* Shared subsounds cannot be replaced or moved from their parent stream, such as when the parent stream is an FSB file. */ ERR_TAGNOTFOUND, /* The specified tag could not be found or there are no tags. */ ERR_TOOMANYCHANNELS, /* The sound created exceeds the allowable input channel count. This can be increased using the 'maxinputchannels' parameter in System::setSoftwareFormat. */ ERR_TRUNCATED, /* The retrieved string is too long to fit in the supplied buffer and has been truncated. */ ERR_UNIMPLEMENTED, /* Something in FMOD hasn't been implemented when it should be! contact support! */ ERR_UNINITIALIZED, /* This command failed because System::init or System::setDriver was not called. */ ERR_UNSUPPORTED, /* A command issued was not supported by this object. Possibly a plugin without certain callbacks specified. */ ERR_VERSION, /* The version number of this file format is not supported. */ ERR_EVENT_ALREADY_LOADED, /* The specified bank has already been loaded. */ ERR_EVENT_LIVEUPDATE_BUSY, /* The live update connection failed due to the game already being connected. */ ERR_EVENT_LIVEUPDATE_MISMATCH, /* The live update connection failed due to the game data being out of sync with the tool. */ ERR_EVENT_LIVEUPDATE_TIMEOUT, /* The live update connection timed out. */ ERR_EVENT_NOTFOUND, /* The requested event, bus or vca could not be found. */ ERR_STUDIO_UNINITIALIZED, /* The Studio::System object is not yet initialized. */ ERR_STUDIO_NOT_LOADED, /* The specified resource is not loaded, so it can't be unloaded. */ ERR_INVALID_STRING, /* An invalid string was passed to this function. */ ERR_ALREADY_LOCKED, /* The specified resource is already locked. */ ERR_NOT_LOCKED, /* The specified resource is not locked, so it can't be unlocked. */ } /* [ENUM] [ [DESCRIPTION] Used to distinguish if a FMOD_CHANNELCONTROL parameter is actually a channel or a channelgroup. [REMARKS] Cast the FMOD_CHANNELCONTROL to an FMOD_CHANNEL/FMOD::Channel, or FMOD_CHANNELGROUP/FMOD::ChannelGroup if specific functionality is needed for either class. Otherwise use as FMOD_CHANNELCONTROL/FMOD::ChannelControl and use that API. [SEE_ALSO] Channel::setCallback ChannelGroup::setCallback ] */ public enum CHANNELCONTROL_TYPE : int { CHANNEL, CHANNELGROUP } /* [STRUCTURE] [ [DESCRIPTION] Structure describing a point in 3D space. [REMARKS] FMOD uses a left handed co-ordinate system by default. To use a right handed co-ordinate system specify FMOD_INIT_3D_RIGHTHANDED from FMOD_INITFLAGS in System::init. [SEE_ALSO] System::set3DListenerAttributes System::get3DListenerAttributes Channel::set3DAttributes Channel::get3DAttributes Geometry::addPolygon Geometry::setPolygonVertex Geometry::getPolygonVertex Geometry::setRotation Geometry::getRotation Geometry::setPosition Geometry::getPosition Geometry::setScale Geometry::getScale FMOD_INITFLAGS ] */ [StructLayout(LayoutKind.Sequential)] public struct VECTOR { public float x; /* X co-ordinate in 3D space. */ public float y; /* Y co-ordinate in 3D space. */ public float z; /* Z co-ordinate in 3D space. */ } /* [STRUCTURE] [ [DESCRIPTION] Structure describing a position, velocity and orientation. [REMARKS] [SEE_ALSO] FMOD_VECTOR FMOD_DSP_PARAMETER_3DATTRIBUTES ] */ [StructLayout(LayoutKind.Sequential)] public struct _3D_ATTRIBUTES { VECTOR position; VECTOR velocity; VECTOR forward; VECTOR up; } /* [STRUCTURE] [ [DESCRIPTION] Structure describing a globally unique identifier. [REMARKS] [SEE_ALSO] System::getDriverInfo ] */ [StructLayout(LayoutKind.Sequential)] public struct GUID { public uint Data1; /* Specifies the first 8 hexadecimal digits of the GUID */ public ushort Data2; /* Specifies the first group of 4 hexadecimal digits. */ public ushort Data3; /* Specifies the second group of 4 hexadecimal digits. */ [MarshalAs(UnmanagedType.ByValArray,SizeConst=8)] public byte[] Data4; /* Array of 8 bytes. The first 2 bytes contain the third group of 4 hexadecimal digits. The remaining 6 bytes contain the final 12 hexadecimal digits. */ } /* [STRUCTURE] [ [DESCRIPTION] Structure that is passed into FMOD_FILE_ASYNCREAD_CALLBACK. Use the information in this structure to perform [REMARKS] Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value.<br> Members marked with [w] mean the variable can be written to. The user can set the value.<br> <br> Instructions: write to 'buffer', and 'bytesread' <b>BEFORE</b> setting 'result'.<br> As soon as result is set, FMOD will asynchronously continue internally using the data provided in this structure.<br> <br> Set 'result' to the result expected from a normal file read callback.<br> If the read was successful, set it to FMOD_OK.<br> If it read some data but hit the end of the file, set it to FMOD_ERR_FILE_EOF.<br> If a bad error occurred, return FMOD_ERR_FILE_BAD<br> If a disk was ejected, return FMOD_ERR_FILE_DISKEJECTED.<br> [SEE_ALSO] FMOD_FILE_ASYNCREAD_CALLBACK FMOD_FILE_ASYNCCANCEL_CALLBACK ] */ [StructLayout(LayoutKind.Sequential)] public struct ASYNCREADINFO { public IntPtr handle; /* [r] The file handle that was filled out in the open callback. */ public uint offset; /* [r] Seek position, make sure you read from this file offset. */ public uint sizebytes; /* [r] how many bytes requested for read. */ public int priority; /* [r] 0 = low importance. 100 = extremely important (ie 'must read now or stuttering may occur') */ public IntPtr buffer; /* [w] Buffer to read file data into. */ public uint bytesread; /* [w] Fill this in before setting result code to tell FMOD how many bytes were read. */ public RESULT result; /* [r/w] Result code, FMOD_OK tells the system it is ready to consume the data. Set this last! Default value = FMOD_ERR_NOTREADY. */ public IntPtr userdata; /* [r] User data pointer. */ } /* [ENUM] [ [DESCRIPTION] These output types are used with System::setOutput / System::getOutput, to choose which output method to use. [REMARKS] To pass information to the driver when initializing fmod use the *extradriverdata* parameter in System::init for the following reasons. - FMOD_OUTPUTTYPE_WAVWRITER - extradriverdata is a pointer to a char * file name that the wav writer will output to. - FMOD_OUTPUTTYPE_WAVWRITER_NRT - extradriverdata is a pointer to a char * file name that the wav writer will output to. - FMOD_OUTPUTTYPE_DSOUND - extradriverdata is cast to a HWND type, so that FMOD can set the focus on the audio for a particular window. - FMOD_OUTPUTTYPE_PS3 - extradriverdata is a pointer to a FMOD_PS3_EXTRADRIVERDATA struct. This can be found in fmodps3.h. - FMOD_OUTPUTTYPE_XBOX360 - extradriverdata is a pointer to a FMOD_360_EXTRADRIVERDATA struct. This can be found in fmodxbox360.h. Currently these are the only FMOD drivers that take extra information. Other unknown plugins may have different requirements. Note! If FMOD_OUTPUTTYPE_WAVWRITER_NRT or FMOD_OUTPUTTYPE_NOSOUND_NRT are used, and if the System::update function is being called very quickly (ie for a non realtime decode) it may be being called too quickly for the FMOD streamer thread to respond to. The result will be a skipping/stuttering output in the captured audio. To remedy this, disable the FMOD streamer thread, and use FMOD_INIT_STREAM_FROM_UPDATE to avoid skipping in the output stream, as it will lock the mixer and the streamer together in the same thread. [SEE_ALSO] System::setOutput System::getOutput System::setSoftwareFormat System::getSoftwareFormat System::init System::update FMOD_INITFLAGS ] */ public enum OUTPUTTYPE : int { AUTODETECT, /* Picks the best output mode for the platform. This is the default. */ UNKNOWN, /* All - 3rd party plugin, unknown. This is for use with System::getOutput only. */ NOSOUND, /* All - Perform all mixing but discard the final output. */ WAVWRITER, /* All - Writes output to a .wav file. */ NOSOUND_NRT, /* All - Non-realtime version of FMOD_OUTPUTTYPE_NOSOUND. User can drive mixer with System::update at whatever rate they want. */ WAVWRITER_NRT, /* All - Non-realtime version of FMOD_OUTPUTTYPE_WAVWRITER. User can drive mixer with System::update at whatever rate they want. */ DSOUND, /* Win - Direct Sound. (Default on Windows XP and below) */ WINMM, /* Win - Windows Multimedia. */ WASAPI, /* Win/WinStore/XboxOne - Windows Audio Session API. (Default on Windows Vista and above, Xbox One and Windows Store Applications) */ ASIO, /* Win - Low latency ASIO 2.0. */ PULSEAUDIO, /* Linux - Pulse Audio. (Default on Linux if available) */ ALSA, /* Linux - Advanced Linux Sound Architecture. (Default on Linux if PulseAudio isn't available) */ COREAUDIO, /* Mac/iOS - Core Audio. (Default on Mac and iOS) */ XBOX360, /* Xbox 360 - XAudio. (Default on Xbox 360) */ PS3, /* PS3 - Audio Out. (Default on PS3) */ AUDIOTRACK, /* Android - Java Audio Track. (Default on Android 2.2 and below) */ OPENSL, /* Android - OpenSL ES. (Default on Android 2.3 and above) */ WIIU, /* Wii U - AX. (Default on Wii U) */ AUDIOOUT, /* PS4/PSVita - Audio Out. (Default on PS4 and PS Vita) */ MAX, /* Maximum number of output types supported. */ } /* [ENUM] [ [DESCRIPTION] Specify the destination of log output when using the logging version of FMOD. [REMARKS] TTY destination can vary depending on platform, common examples include the Visual Studio / Xcode output window, stderr and LogCat. [SEE_ALSO] FMOD_Debug_Initialize ] */ [Flags] public enum DEBUG_MODE : int { TTY, /* Default log location per platform, i.e. Visual Studio output window, stderr, LogCat, etc */ FILE, /* Write log to specified file path */ CALLBACK, /* Call specified callback with log information */ } /* [DEFINE] [ [NAME] FMOD_DEBUG_FLAGS [DESCRIPTION] Specify the requested information to be output when using the logging version of FMOD. [REMARKS] [SEE_ALSO] FMOD_Debug_Initialize ] */ [Flags] public enum DEBUG_FLAGS : int { NONE = 0x00000000, /* Disable all messages */ ERROR = 0x00000001, /* Enable only error messages. */ WARNING = 0x00000002, /* Enable warning and error messages. */ LOG = 0x00000004, /* Enable informational, warning and error messages (default). */ TYPE_MEMORY = 0x00000100, /* Verbose logging for memory operations, only use this if you are debugging a memory related issue. */ TYPE_FILE = 0x00000200, /* Verbose logging for file access, only use this if you are debugging a file related issue. */ TYPE_CODEC = 0x00000400, /* Verbose logging for codec initialization, only use this if you are debugging a codec related issue. */ TYPE_TRACE = 0x00000800, /* Verbose logging for internal errors, use this for tracking the origin of error codes. */ DISPLAY_TIMESTAMPS = 0x00010000, /* Display the time stamp of the log message in milliseconds. */ DISPLAY_LINENUMBERS = 0x00020000, /* Display the source code file and line number for where the message originated. */ DISPLAY_THREAD = 0x00040000, /* Display the thread ID of the calling function that generated the message. */ } /* [DEFINE] [ [NAME] FMOD_MEMORY_TYPE [DESCRIPTION] Bit fields for memory allocation type being passed into FMOD memory callbacks. [REMARKS] Remember this is a bitfield. You may get more than 1 bit set (ie physical + persistent) so do not simply switch on the types! You must check each bit individually or clear out the bits that you do not want within the callback.<br> Bits can be excluded if you want during Memory_Initialize so that you never get them. [SEE_ALSO] FMOD_MEMORY_ALLOC_CALLBACK FMOD_MEMORY_REALLOC_CALLBACK FMOD_MEMORY_FREE_CALLBACK Memory_Initialize ] */ [Flags] public enum MEMORY_TYPE : uint { NORMAL = 0x00000000, /* Standard memory. */ STREAM_FILE = 0x00000001, /* Stream file buffer, size controllable with System::setStreamBufferSize. */ STREAM_DECODE = 0x00000002, /* Stream decode buffer, size controllable with FMOD_CREATESOUNDEXINFO::decodebuffersize. */ SAMPLEDATA = 0x00000004, /* Sample data buffer. Raw audio data, usually PCM/MPEG/ADPCM/XMA data. */ DSP_BUFFER = 0x00000008, /* DSP memory block allocated when more than 1 output exists on a DSP node. */ PLUGIN = 0x00000010, /* Memory allocated by a third party plugin. */ XBOX360_PHYSICAL = 0x00100000, /* Requires XPhysicalAlloc / XPhysicalFree. */ PERSISTENT = 0x00200000, /* Persistent memory. Memory will be freed when System::release is called. */ SECONDARY = 0x00400000, /* Secondary memory. Allocation should be in secondary memory. For example RSX on the PS3. */ ALL = 0xFFFFFFFF } /* [ENUM] [ [DESCRIPTION] These are speaker types defined for use with the System::setSoftwareFormat command. [REMARKS] Note below the phrase 'sound channels' is used. These are the subchannels inside a sound, they are not related and have nothing to do with the FMOD class "Channel".<br> For example a mono sound has 1 sound channel, a stereo sound has 2 sound channels, and an AC3 or 6 channel wav file have 6 "sound channels".<br> <br> FMOD_SPEAKERMODE_RAW<br> ---------------------<br> This mode is for output devices that are not specifically mono/stereo/quad/surround/5.1 or 7.1, but are multichannel.<br> Use System::setSoftwareFormat to specify the number of speakers you want to address, otherwise it will default to 2 (stereo).<br> Sound channels map to speakers sequentially, so a mono sound maps to output speaker 0, stereo sound maps to output speaker 0 & 1.<br> The user assumes knowledge of the speaker order. FMOD_SPEAKER enumerations may not apply, so raw channel indices should be used.<br> Multichannel sounds map input channels to output channels 1:1. <br> Channel::setPan and Channel::setPanLevels do not work.<br> Speaker levels must be manually set with Channel::setPanMatrix.<br> <br> FMOD_SPEAKERMODE_MONO<br> ---------------------<br> This mode is for a 1 speaker arrangement.<br> Panning does not work in this speaker mode.<br> Mono, stereo and multichannel sounds have each sound channel played on the one speaker unity.<br> Mix behavior for multichannel sounds can be set with Channel::setPanMatrix.<br> Channel::setPanLevels does not work.<br> <br> FMOD_SPEAKERMODE_STEREO<br> -----------------------<br> This mode is for 2 speaker arrangements that have a left and right speaker.<br> <li>Mono sounds default to an even distribution between left and right. They can be panned with Channel::setPan.<br> <li>Stereo sounds default to the middle, or full left in the left speaker and full right in the right speaker. <li>They can be cross faded with Channel::setPan.<br> <li>Multichannel sounds have each sound channel played on each speaker at unity.<br> <li>Mix behavior for multichannel sounds can be set with Channel::setPanMatrix.<br> <li>Channel::setPanLevels works but only front left and right parameters are used, the rest are ignored.<br> <br> FMOD_SPEAKERMODE_QUAD<br> ------------------------<br> This mode is for 4 speaker arrangements that have a front left, front right, surround left and a surround right speaker.<br> <li>Mono sounds default to an even distribution between front left and front right. They can be panned with Channel::setPan.<br> <li>Stereo sounds default to the left sound channel played on the front left, and the right sound channel played on the front right.<br> <li>They can be cross faded with Channel::setPan.<br> <li>Multichannel sounds default to all of their sound channels being played on each speaker in order of input.<br> <li>Mix behavior for multichannel sounds can be set with Channel::setPanMatrix.<br> <li>Channel::setPanLevels works but rear left, rear right, center and lfe are ignored.<br> <br> FMOD_SPEAKERMODE_SURROUND<br> ------------------------<br> This mode is for 5 speaker arrangements that have a left/right/center/surround left/surround right.<br> <li>Mono sounds default to the center speaker. They can be panned with Channel::setPan.<br> <li>Stereo sounds default to the left sound channel played on the front left, and the right sound channel played on the front right. <li>They can be cross faded with Channel::setPan.<br> <li>Multichannel sounds default to all of their sound channels being played on each speaker in order of input. <li>Mix behavior for multichannel sounds can be set with Channel::setPanMatrix.<br> <li>Channel::setPanLevels works but rear left / rear right are ignored.<br> <br> FMOD_SPEAKERMODE_5POINT1<br> ---------------------------------------------------------<br> This mode is for 5.1 speaker arrangements that have a left/right/center/surround left/surround right and a subwoofer speaker.<br> <li>Mono sounds default to the center speaker. They can be panned with Channel::setPan.<br> <li>Stereo sounds default to the left sound channel played on the front left, and the right sound channel played on the front right. <li>They can be cross faded with Channel::setPan.<br> <li>Multichannel sounds default to all of their sound channels being played on each speaker in order of input. <li>Mix behavior for multichannel sounds can be set with Channel::setPanMatrix.<br> <li>Channel::setPanLevels works but rear left / rear right are ignored.<br> <br> FMOD_SPEAKERMODE_7POINT1<br> ------------------------<br> This mode is for 7.1 speaker arrangements that have a left/right/center/surround left/surround right/rear left/rear right and a subwoofer speaker.<br> <li>Mono sounds default to the center speaker. They can be panned with Channel::setPan.<br> <li>Stereo sounds default to the left sound channel played on the front left, and the right sound channel played on the front right. <li>They can be cross faded with Channel::setPan.<br> <li>Multichannel sounds default to all of their sound channels being played on each speaker in order of input. <li>Mix behavior for multichannel sounds can be set with Channel::setPanMatrix.<br> <li>Channel::setPanLevels works and every parameter is used to set the balance of a sound in any speaker.<br> <br> [SEE_ALSO] System::setSoftwareFormat System::getSoftwareFormat DSP::setChannelFormat ] */ public enum SPEAKERMODE : int { DEFAULT, /* Default speaker mode based on operating system/output mode. Windows = control panel setting, Xbox = 5.1, PS3 = 7.1 etc. */ RAW, /* There is no specific speakermode. Sound channels are mapped in order of input to output. Use System::setSoftwareFormat to specify speaker count. See remarks for more information. */ MONO, /* The speakers are monaural. */ STEREO, /* The speakers are stereo. */ QUAD, /* 4 speaker setup. This includes front left, front right, surround left, surround right. */ SURROUND, /* 5 speaker setup. This includes front left, front right, center, surround left, surround right. */ _5POINT1, /* 5.1 speaker setup. This includes front left, front right, center, surround left, surround right and an LFE speaker. */ _7POINT1, /* 7.1 speaker setup. This includes front left, front right, center, surround left, surround right, back left, back right and an LFE speaker. */ MAX, /* Maximum number of speaker modes supported. */ } /* [ENUM] [ [DESCRIPTION] Assigns an enumeration for a speaker index. [REMARKS] [SEE_ALSO] System::setSpeakerPosition System::getSpeakerPosition ] */ public enum SPEAKER : int { FRONT_LEFT, FRONT_RIGHT, FRONT_CENTER, LOW_FREQUENCY, SURROUND_LEFT, SURROUND_RIGHT, BACK_LEFT, BACK_RIGHT, MAX, /* Maximum number of speaker types supported. */ } /* [DEFINE] [ [NAME] FMOD_CHANNELMASK [DESCRIPTION] These are bitfields to describe for a certain number of channels in a signal, which channels are being represented.<br> For example, a signal could be 1 channel, but contain the LFE channel only.<br> [REMARKS] FMOD_CHANNELMASK_BACK_CENTER is not represented as an output speaker in fmod - but it is encountered in input formats and is down or upmixed appropriately to the nearest speakers.<br> [SEE_ALSO] DSP::setChannelFormat DSP::getChannelFormat FMOD_SPEAKERMODE ] */ [Flags] public enum CHANNELMASK : int { FRONT_LEFT = 0x00000001, FRONT_RIGHT = 0x00000002, FRONT_CENTER = 0x00000004, LOW_FREQUENCY = 0x00000008, SURROUND_LEFT = 0x00000010, SURROUND_RIGHT = 0x00000020, BACK_LEFT = 0x00000040, BACK_RIGHT = 0x00000080, BACK_CENTER = 0x00000100, MONO = (FRONT_LEFT), STEREO = (FRONT_LEFT | FRONT_RIGHT), LRC = (FRONT_LEFT | FRONT_RIGHT | FRONT_CENTER), QUAD = (FRONT_LEFT | FRONT_RIGHT | SURROUND_LEFT | SURROUND_RIGHT), SURROUND = (FRONT_LEFT | FRONT_RIGHT | FRONT_CENTER | SURROUND_LEFT | SURROUND_RIGHT), _5POINT1 = (FRONT_LEFT | FRONT_RIGHT | FRONT_CENTER | LOW_FREQUENCY | SURROUND_LEFT | SURROUND_RIGHT), _5POINT1_REARS = (FRONT_LEFT | FRONT_RIGHT | FRONT_CENTER | LOW_FREQUENCY | BACK_LEFT | BACK_RIGHT), _7POINT0 = (FRONT_LEFT | FRONT_RIGHT | FRONT_CENTER | SURROUND_LEFT | SURROUND_RIGHT | BACK_LEFT | BACK_RIGHT), _7POINT1 = (FRONT_LEFT | FRONT_RIGHT | FRONT_CENTER | LOW_FREQUENCY | SURROUND_LEFT | SURROUND_RIGHT | BACK_LEFT | BACK_RIGHT) } /* [ENUM] [ [DESCRIPTION] When creating a multichannel sound, FMOD will pan them to their default speaker locations, for example a 6 channel sound will default to one channel per 5.1 output speaker.<br> Another example is a stereo sound. It will default to left = front left, right = front right.<br> <br> This is for sounds that are not 'default'. For example you might have a sound that is 6 channels but actually made up of 3 stereo pairs, that should all be located in front left, front right only. [REMARKS] [SEE_ALSO] FMOD_CREATESOUNDEXINFO ] */ public enum CHANNELORDER : int { DEFAULT, /* Left, Right, Center, LFE, Surround Left, Surround Right, Back Left, Back Right (see FMOD_SPEAKER enumeration) */ WAVEFORMAT, /* Left, Right, Center, LFE, Back Left, Back Right, Surround Left, Surround Right (as per Microsoft .wav WAVEFORMAT structure master order) */ PROTOOLS, /* Left, Center, Right, Surround Left, Surround Right, LFE */ ALLMONO, /* Mono, Mono, Mono, Mono, Mono, Mono, ... (each channel all the way up to 32 channels are treated as if they were mono) */ ALLSTEREO, /* Left, Right, Left, Right, Left, Right, ... (each pair of channels is treated as stereo all the way up to 32 channels) */ ALSA, /* Left, Right, Surround Left, Surround Right, Center, LFE (as per Linux ALSA channel order) */ MAX, /* Maximum number of channel orderings supported. */ } /* [ENUM] [ [DESCRIPTION] These are plugin types defined for use with the System::getNumPlugins, System::getPluginInfo and System::unloadPlugin functions. [REMARKS] [SEE_ALSO] System::getNumPlugins System::getPluginInfo System::unloadPlugin ] */ public enum PLUGINTYPE : int { OUTPUT, /* The plugin type is an output module. FMOD mixed audio will play through one of these devices */ CODEC, /* The plugin type is a file format codec. FMOD will use these codecs to load file formats for playback. */ DSP, /* The plugin type is a DSP unit. FMOD will use these plugins as part of its DSP network to apply effects to output or generate sound in realtime. */ MAX, /* Maximum number of plugin types supported. */ } /* [STRUCTURE] [ [DESCRIPTION] DSP metering info used for retrieving metering info [REMARKS] Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value.<br> Members marked with [w] mean the variable can be written to. The user can set the value.<br> [SEE_ALSO] FMOD_SPEAKER ] */ [StructLayoutAttribute(LayoutKind.Sequential)] public struct DSP_METERING_INFO { public int numsamples; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 32, ArraySubType = UnmanagedType.R4)] public float[] peaklevel; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 32, ArraySubType = UnmanagedType.R4)] public float[] rmslevel; public short numchannels; } /* [ENUM] [ [DESCRIPTION] Initialization flags. Use them with System::init in the flags parameter to change various behaviour. [REMARKS] [SEE_ALSO] System::init ] */ [Flags] public enum INITFLAGS : int { NORMAL = 0x00000000, /* Initialize normally */ STREAM_FROM_UPDATE = 0x00000001, /* No stream thread is created internally. Streams are driven from System::update. Mainly used with non-realtime outputs. */ MIX_FROM_UPDATE = 0x00000002, /* Win/Wii/PS3/Xbox/Xbox 360 Only - FMOD Mixer thread is woken up to do a mix when System::update is called rather than waking periodically on its own timer. */ _3D_RIGHTHANDED = 0x00000004, /* FMOD will treat +X as right, +Y as up and +Z as backwards (towards you). */ CHANNEL_LOWPASS = 0x00000100, /* All FMOD_3D based voices will add a software lowpass filter effect into the DSP chain which is automatically used when Channel::set3DOcclusion is used or the geometry API. This also causes sounds to sound duller when the sound goes behind the listener, as a fake HRTF style effect. Use System::setAdvancedSettings to disable or adjust cutoff frequency for this feature. */ CHANNEL_DISTANCEFILTER = 0x00000200, /* All FMOD_3D based voices will add a software lowpass and highpass filter effect into the DSP chain which will act as a distance-automated bandpass filter. Use System::setAdvancedSettings to adjust the center frequency. */ PROFILE_ENABLE = 0x00010000, /* Enable TCP/IP based host which allows FMOD Designer or FMOD Profiler to connect to it, and view memory, CPU and the DSP network graph in real-time. */ VOL0_BECOMES_VIRTUAL = 0x00020000, /* Any sounds that are 0 volume will go virtual and not be processed except for having their positions updated virtually. Use System::setAdvancedSettings to adjust what volume besides zero to switch to virtual at. */ GEOMETRY_USECLOSEST = 0x00040000, /* With the geometry engine, only process the closest polygon rather than accumulating all polygons the sound to listener line intersects. */ PREFER_DOLBY_DOWNMIX = 0x00080000, /* When using FMOD_SPEAKERMODE_5POINT1 with a stereo output device, use the Dolby Pro Logic II downmix algorithm instead of the SRS Circle Surround algorithm. */ THREAD_UNSAFE = 0x00100000, /* Disables thread safety for API calls. Only use this if FMOD low level is being called from a single thread, and if Studio API is not being used! */ PROFILE_METER_ALL = 0x00200000 /* Slower, but adds level metering for every single DSP unit in the graph. Use DSP::setMeteringEnabled to turn meters off individually. */ } /* [ENUM] [ [DESCRIPTION] These definitions describe the type of song being played. [REMARKS] [SEE_ALSO] Sound::getFormat ] */ public enum SOUND_TYPE { UNKNOWN, /* 3rd party / unknown plugin format. */ AIFF, /* AIFF. */ ASF, /* Microsoft Advanced Systems Format (ie WMA/ASF/WMV). */ AT3, /* Sony ATRAC 3 format */ DLS, /* Sound font / downloadable sound bank. */ FLAC, /* FLAC lossless codec. */ FSB, /* FMOD Sample Bank. */ GCADPCM, /* GameCube ADPCM */ IT, /* Impulse Tracker. */ MIDI, /* MIDI. */ MOD, /* Protracker / Fasttracker MOD. */ MPEG, /* MP2/MP3 MPEG. */ OGGVORBIS, /* Ogg vorbis. */ PLAYLIST, /* Information only from ASX/PLS/M3U/WAX playlists */ RAW, /* Raw PCM data. */ S3M, /* ScreamTracker 3. */ USER, /* User created sound. */ WAV, /* Microsoft WAV. */ XM, /* FastTracker 2 XM. */ XMA, /* Xbox360 XMA */ VAG, /* PlayStation Portable adpcm VAG format. */ AUDIOQUEUE, /* iPhone hardware decoder, supports AAC, ALAC and MP3. */ XWMA, /* Xbox360 XWMA */ BCWAV, /* 3DS BCWAV container format for DSP ADPCM and PCM */ AT9, /* NGP ATRAC 9 format */ VORBIS, /* Raw vorbis */ MEDIA_FOUNDATION, /* Windows Store Application built in system codecs */ MEDIACODEC, /* Android MediaCodec */ MAX, /* Maximum number of sound types supported. */ } /* [ENUM] [ [DESCRIPTION] These definitions describe the native format of the hardware or software buffer that will be used. [REMARKS] This is the format the native hardware or software buffer will be or is created in. [SEE_ALSO] System::createSoundEx Sound::getFormat ] */ public enum SOUND_FORMAT : int { NONE, /* Unitialized / unknown */ PCM8, /* 8bit integer PCM data */ PCM16, /* 16bit integer PCM data */ PCM24, /* 24bit integer PCM data */ PCM32, /* 32bit integer PCM data */ PCMFLOAT, /* 32bit floating point PCM data */ GCADPCM, /* Compressed GameCube DSP data */ IMAADPCM, /* Compressed XBox ADPCM data */ VAG, /* Compressed PlayStation 2 ADPCM data */ HEVAG, /* Compressed NGP ADPCM data. */ XMA, /* Compressed Xbox360 data. */ MPEG, /* Compressed MPEG layer 2 or 3 data. */ CELT, /* Compressed CELT data. */ AT9, /* Compressed ATRAC9 data. */ XWMA, /* Compressed Xbox360 xWMA data. */ VORBIS, /* Compressed Vorbis data. */ MAX /* Maximum number of sound formats supported. */ } /* [DEFINE] [ [NAME] FMOD_MODE [DESCRIPTION] Sound description bitfields, bitwise OR them together for loading and describing sounds. [REMARKS] By default a sound will open as a static sound that is decompressed fully into memory to PCM. (ie equivalent of FMOD_CREATESAMPLE)<br> To have a sound stream instead, use FMOD_CREATESTREAM, or use the wrapper function System::createStream.<br> Some opening modes (ie FMOD_OPENUSER, FMOD_OPENMEMORY, FMOD_OPENMEMORY_POINT, FMOD_OPENRAW) will need extra information.<br> This can be provided using the FMOD_CREATESOUNDEXINFO structure. <br> Specifying FMOD_OPENMEMORY_POINT will POINT to your memory rather allocating its own sound buffers and duplicating it internally.<br> <b><u>This means you cannot free the memory while FMOD is using it, until after Sound::release is called.</b></u> With FMOD_OPENMEMORY_POINT, for PCM formats, only WAV, FSB, and RAW are supported. For compressed formats, only those formats supported by FMOD_CREATECOMPRESSEDSAMPLE are supported.<br> With FMOD_OPENMEMORY_POINT and FMOD_OPENRAW or PCM, if using them together, note that you must pad the data on each side by 16 bytes. This is so fmod can modify the ends of the data for looping/interpolation/mixing purposes. If a wav file, you will need to insert silence, and then reset loop points to stop the playback from playing that silence.<br> <br> <b>Xbox 360 memory</b> On Xbox 360 Specifying FMOD_OPENMEMORY_POINT to a virtual memory address will cause FMOD_ERR_INVALID_ADDRESS to be returned. Use physical memory only for this functionality.<br> <br> FMOD_LOWMEM is used on a sound if you want to minimize the memory overhead, by having FMOD not allocate memory for certain features that are not likely to be used in a game environment. These are :<br> 1. Sound::getName functionality is removed. 256 bytes per sound is saved.<br> [SEE_ALSO] System::createSound System::createStream Sound::setMode Sound::getMode Channel::setMode Channel::getMode Sound::set3DCustomRolloff Channel::set3DCustomRolloff Sound::getOpenState ] */ public enum MODE :uint { DEFAULT = 0x00000000, /* Default for all modes listed below. FMOD_LOOP_OFF, FMOD_2D, FMOD_3D_WORLDRELATIVE, FMOD_3D_INVERSEROLLOFF */ LOOP_OFF = 0x00000001, /* For non looping sounds. (default). Overrides FMOD_LOOP_NORMAL / FMOD_LOOP_BIDI. */ LOOP_NORMAL = 0x00000002, /* For forward looping sounds. */ LOOP_BIDI = 0x00000004, /* For bidirectional looping sounds. (only works on software mixed static sounds). */ _2D = 0x00000008, /* Ignores any 3d processing. (default). */ _3D = 0x00000010, /* Makes the sound positionable in 3D. Overrides FMOD_2D. */ CREATESTREAM = 0x00000080, /* Decompress at runtime, streaming from the source provided (standard stream). Overrides FMOD_CREATESAMPLE. */ CREATESAMPLE = 0x00000100, /* Decompress at loadtime, decompressing or decoding whole file into memory as the target sample format. (standard sample). */ CREATECOMPRESSEDSAMPLE = 0x00000200, /* Load MP2, MP3, IMAADPCM or XMA into memory and leave it compressed. During playback the FMOD software mixer will decode it in realtime as a 'compressed sample'. Can only be used in combination with FMOD_SOFTWARE. */ OPENUSER = 0x00000400, /* Opens a user created static sample or stream. Use FMOD_CREATESOUNDEXINFO to specify format and/or read callbacks. If a user created 'sample' is created with no read callback, the sample will be empty. Use FMOD_Sound_Lock and FMOD_Sound_Unlock to place sound data into the sound if this is the case. */ OPENMEMORY = 0x00000800, /* "name_or_data" will be interpreted as a pointer to memory instead of filename for creating sounds. */ OPENMEMORY_POINT = 0x10000000, /* "name_or_data" will be interpreted as a pointer to memory instead of filename for creating sounds. Use FMOD_CREATESOUNDEXINFO to specify length. This differs to FMOD_OPENMEMORY in that it uses the memory as is, without duplicating the memory into its own buffers. Cannot be freed after open, only after Sound::release. Will not work if the data is compressed and FMOD_CREATECOMPRESSEDSAMPLE is not used. */ OPENRAW = 0x00001000, /* Will ignore file format and treat as raw pcm. User may need to declare if data is FMOD_SIGNED or FMOD_UNSIGNED */ OPENONLY = 0x00002000, /* Just open the file, dont prebuffer or read. Good for fast opens for info, or when sound::readData is to be used. */ ACCURATETIME = 0x00004000, /* For FMOD_CreateSound - for accurate FMOD_Sound_GetLength / FMOD_Channel_SetPosition on VBR MP3, AAC and MOD/S3M/XM/IT/MIDI files. Scans file first, so takes longer to open. FMOD_OPENONLY does not affect this. */ MPEGSEARCH = 0x00008000, /* For corrupted / bad MP3 files. This will search all the way through the file until it hits a valid MPEG header. Normally only searches for 4k. */ NONBLOCKING = 0x00010000, /* For opening sounds and getting streamed subsounds (seeking) asyncronously. Use Sound::getOpenState to poll the state of the sound as it opens or retrieves the subsound in the background. */ UNIQUE = 0x00020000, /* Unique sound, can only be played one at a time */ _3D_HEADRELATIVE = 0x00040000, /* Make the sound's position, velocity and orientation relative to the listener. */ _3D_WORLDRELATIVE = 0x00080000, /* Make the sound's position, velocity and orientation absolute (relative to the world). (DEFAULT) */ _3D_INVERSEROLLOFF = 0x00100000, /* This sound will follow the inverse rolloff model where mindistance = full volume, maxdistance = where sound stops attenuating, and rolloff is fixed according to the global rolloff factor. (DEFAULT) */ _3D_LINEARROLLOFF = 0x00200000, /* This sound will follow a linear rolloff model where mindistance = full volume, maxdistance = silence. */ _3D_LINEARSQUAREROLLOFF= 0x00400000, /* This sound will follow a linear-square rolloff model where mindistance = full volume, maxdistance = silence. Rolloffscale is ignored. */ _3D_INVERSETAPEREDROLLOFF = 0x00800000, /* This sound will follow the inverse rolloff model at distances close to mindistance and a linear-square rolloff close to maxdistance. */ _3D_CUSTOMROLLOFF = 0x04000000, /* This sound will follow a rolloff model defined by Sound::set3DCustomRolloff / Channel::set3DCustomRolloff. */ _3D_IGNOREGEOMETRY = 0x40000000, /* Is not affect by geometry occlusion. If not specified in Sound::setMode, or Channel::setMode, the flag is cleared and it is affected by geometry again. */ IGNORETAGS = 0x02000000, /* Skips id3v2/asf/etc tag checks when opening a sound, to reduce seek/read overhead when opening files (helps with CD performance). */ LOWMEM = 0x08000000, /* Removes some features from samples to give a lower memory overhead, like Sound::getName. */ LOADSECONDARYRAM = 0x20000000, /* Load sound into the secondary RAM of supported platform. On PS3, sounds will be loaded into RSX/VRAM. */ VIRTUAL_PLAYFROMSTART = 0x80000000 /* For sounds that start virtual (due to being quiet or low importance), instead of swapping back to audible, and playing at the correct offset according to time, this flag makes the sound play from the start. */ } /* [ENUM] [ [DESCRIPTION] These values describe what state a sound is in after FMOD_NONBLOCKING has been used to open it. [REMARKS] With streams, if you are using FMOD_NONBLOCKING, note that if the user calls Sound::getSubSound, a stream will go into FMOD_OPENSTATE_SEEKING state and sound related commands will return FMOD_ERR_NOTREADY.<br> With streams, if you are using FMOD_NONBLOCKING, note that if the user calls Channel::getPosition, a stream will go into FMOD_OPENSTATE_SETPOSITION state and sound related commands will return FMOD_ERR_NOTREADY.<br> [SEE_ALSO] Sound::getOpenState FMOD_MODE ] */ public enum OPENSTATE : int { READY = 0, /* Opened and ready to play */ LOADING, /* Initial load in progress */ ERROR, /* Failed to open - file not found, out of memory etc. See return value of Sound::getOpenState for what happened. */ CONNECTING, /* Connecting to remote host (internet sounds only) */ BUFFERING, /* Buffering data */ SEEKING, /* Seeking to subsound and re-flushing stream buffer. */ PLAYING, /* Ready and playing, but not possible to release at this time without stalling the main thread. */ SETPOSITION, /* Seeking within a stream to a different position. */ MAX, /* Maximum number of open state types. */ } /* [ENUM] [ [DESCRIPTION] These flags are used with SoundGroup::setMaxAudibleBehavior to determine what happens when more sounds are played than are specified with SoundGroup::setMaxAudible. [REMARKS] When using FMOD_SOUNDGROUP_BEHAVIOR_MUTE, SoundGroup::setMuteFadeSpeed can be used to stop a sudden transition. Instead, the time specified will be used to cross fade between the sounds that go silent and the ones that become audible. [SEE_ALSO] SoundGroup::setMaxAudibleBehavior SoundGroup::getMaxAudibleBehavior SoundGroup::setMaxAudible SoundGroup::getMaxAudible SoundGroup::setMuteFadeSpeed SoundGroup::getMuteFadeSpeed ] */ public enum SOUNDGROUP_BEHAVIOR : int { BEHAVIOR_FAIL, /* Any sound played that puts the sound count over the SoundGroup::setMaxAudible setting, will simply fail during System::playSound. */ BEHAVIOR_MUTE, /* Any sound played that puts the sound count over the SoundGroup::setMaxAudible setting, will be silent, then if another sound in the group stops the sound that was silent before becomes audible again. */ BEHAVIOR_STEALLOWEST, /* Any sound played that puts the sound count over the SoundGroup::setMaxAudible setting, will steal the quietest / least important sound playing in the group. */ MAX, /* Maximum number of sound group behaviors. */ } /* [ENUM] [ [DESCRIPTION] These callback types are used with Channel::setCallback. [REMARKS] Each callback has commanddata parameters passed as int unique to the type of callback.<br> See reference to FMOD_CHANNELCONTROL_CALLBACK to determine what they might mean for each type of callback.<br> <br> <b>Note!</b> Currently the user must call System::update for these callbacks to trigger! [SEE_ALSO] Channel::setCallback ChannelGroup::setCallback FMOD_CHANNELCONTROL_CALLBACK System::update ] */ public enum CHANNELCONTROL_CALLBACK_TYPE : int { END, /* Called when a sound ends. */ VIRTUALVOICE, /* Called when a voice is swapped out or swapped in. */ SYNCPOINT, /* Called when a syncpoint is encountered. Can be from wav file markers. */ OCCLUSION, /* Called when the channel has its geometry occlusion value calculated. Can be used to clamp or change the value. */ MAX, /* Maximum number of callback types supported. */ } /* [ENUM] [ [DESCRIPTION] These enums denote special types of node within a DSP chain. [REMARKS] [SEE_ALSO] Channel::getDSP ChannelGroup::getDSP ] */ public struct CHANNELCONTROL_DSP_INDEX { public const int HEAD = -1; /* Head of the DSP chain. */ public const int FADER = -2; /* Built in fader DSP. */ public const int PANNER = -3; /* Built in panner DSP. */ public const int TAIL = -4; /* Tail of the DSP chain. */ } /* [ENUM] [ [DESCRIPTION] Used to distinguish the instance type passed into FMOD_ERROR_CALLBACK. [REMARKS] Cast the instance of FMOD_ERROR_CALLBACK to the appropriate class indicated by this enum. [SEE_ALSO] ] */ public enum ERRORCALLBACK_INSTANCETYPE { NONE, SYSTEM, CHANNEL, CHANNELGROUP, CHANNELCONTROL, SOUND, SOUNDGROUP, DSP, DSPCONNECTION, GEOMETRY, REVERB3D, STUDIO_SYSTEM, STUDIO_EVENTDESCRIPTION, STUDIO_EVENTINSTANCE, STUDIO_PARAMETERINSTANCE, STUDIO_CUEINSTANCE, STUDIO_BUS, STUDIO_VCA, STUDIO_BANK } /* [STRUCTURE] [ [DESCRIPTION] Structure that is passed into FMOD_SYSTEM_CALLBACK for the FMOD_SYSTEM_CALLBACK_ERROR callback type. [REMARKS] The instance pointer will be a type corresponding to the instanceType enum. [SEE_ALSO] FMOD_ERRORCALLBACK_INSTANCETYPE ] */ [StructLayoutAttribute(LayoutKind.Sequential)] public struct ERRORCALLBACK_INFO { public RESULT result; /* Error code result */ public ERRORCALLBACK_INSTANCETYPE instancetype; /* Type of instance the error occurred on */ public IntPtr instance; /* Instance pointer */ private IntPtr functionnamePtr; /* Function that the error occurred on */ private IntPtr functionparamsPtr; /* Function parameters that the error ocurred on */ public string functionname { get { return Marshal.PtrToStringAnsi(functionnamePtr); } } public string functionparams { get { return Marshal.PtrToStringAnsi(functionparamsPtr); } } } /* [ENUM] [ [DESCRIPTION] These callback types are used with System::setCallback. [REMARKS] Each callback has commanddata parameters passed as int unique to the type of callback.<br> See reference to FMOD_SYSTEM_CALLBACK to determine what they might mean for each type of callback.<br> <br> <b>Note!</b> Currently the user must call System::update for these callbacks to trigger! [SEE_ALSO] System::setCallback FMOD_SYSTEM_CALLBACK System::update ] */ [Flags] public enum SYSTEM_CALLBACK_TYPE : int { DEVICELISTCHANGED = 0x00000001, /* Called from System::update when the enumerated list of devices has changed. */ DEVICELOST = 0x00000002, /* Called from System::update when an output device has been lost due to control panel parameter changes and FMOD cannot automatically recover. */ MEMORYALLOCATIONFAILED = 0x00000004, /* Called directly when a memory allocation fails somewhere in FMOD. (NOTE - 'system' will be NULL in this callback type.)*/ THREADCREATED = 0x00000008, /* Called directly when a thread is created. (NOTE - 'system' will be NULL in this callback type.) */ BADDSPCONNECTION = 0x00000010, /* Called when a bad connection was made with DSP::addInput. Usually called from mixer thread because that is where the connections are made. */ PREMIX = 0x00000020, /* Called each tick before a mix update happens. */ POSTMIX = 0x00000040, /* Called each tick after a mix update happens. */ ERROR = 0x00000080, /* Called when each API function returns an error code, including delayed async functions. */ MIDMIX = 0x00000100, /* Called each tick in mix update after clocks have been updated before the main mix occurs. */ THREADDESTROYED = 0x00000200, /* Called directly when a thread is destroyed. */ PREUPDATE = 0x00000400, /* Called at start of System::update function. */ POSTUPDATE = 0x00000800, /* Called at end of System::update function. */ } /* FMOD Callbacks */ public delegate RESULT DEBUG_CALLBACK (DEBUG_FLAGS flags, string file, int line, string func, string message); public delegate RESULT SYSTEM_CALLBACK (IntPtr systemraw, SYSTEM_CALLBACK_TYPE type, IntPtr commanddata1, IntPtr commanddata2, IntPtr userdata); public delegate RESULT CHANNEL_CALLBACK (IntPtr channelraw, CHANNELCONTROL_TYPE controltype, CHANNELCONTROL_CALLBACK_TYPE type, IntPtr commanddata1, IntPtr commanddata2); public delegate RESULT SOUND_NONBLOCKCALLBACK (IntPtr soundraw, RESULT result); public delegate RESULT SOUND_PCMREADCALLBACK (IntPtr soundraw, IntPtr data, uint datalen); public delegate RESULT SOUND_PCMSETPOSCALLBACK (IntPtr soundraw, int subsound, uint position, TIMEUNIT postype); public delegate RESULT FILE_OPENCALLBACK ([MarshalAs(UnmanagedType.LPWStr)]string name, ref uint filesize, ref IntPtr handle, IntPtr userdata); public delegate RESULT FILE_CLOSECALLBACK (IntPtr handle, IntPtr userdata); public delegate RESULT FILE_READCALLBACK (IntPtr handle, IntPtr buffer, uint sizebytes, ref uint bytesread, IntPtr userdata); public delegate RESULT FILE_SEEKCALLBACK (IntPtr handle, int pos, IntPtr userdata); public delegate RESULT FILE_ASYNCREADCALLBACK (IntPtr handle, IntPtr info, IntPtr userdata); public delegate RESULT FILE_ASYNCCANCELCALLBACK (IntPtr handle, IntPtr userdata); public delegate IntPtr MEMORY_ALLOC_CALLBACK (uint size, MEMORY_TYPE type, string sourcestr); public delegate IntPtr MEMORY_REALLOC_CALLBACK (IntPtr ptr, uint size, MEMORY_TYPE type, string sourcestr); public delegate void MEMORY_FREE_CALLBACK (IntPtr ptr, MEMORY_TYPE type, string sourcestr); public delegate float CB_3D_ROLLOFFCALLBACK (IntPtr channelraw, float distance); /* [ENUM] [ [DESCRIPTION] List of interpolation types that the FMOD Ex software mixer supports. [REMARKS] The default resampler type is FMOD_DSP_RESAMPLER_LINEAR.<br> Use System::setSoftwareFormat to tell FMOD the resampling quality you require for FMOD_SOFTWARE based sounds. [SEE_ALSO] System::setSoftwareFormat System::getSoftwareFormat ] */ public enum DSP_RESAMPLER : int { DEFAULT, /* Default interpolation method. Currently equal to FMOD_DSP_RESAMPLER_LINEAR. */ NOINTERP, /* No interpolation. High frequency aliasing hiss will be audible depending on the sample rate of the sound. */ LINEAR, /* Linear interpolation (default method). Fast and good quality, causes very slight lowpass effect on low frequency sounds. */ CUBIC, /* Cubic interpolation. Slower than linear interpolation but better quality. */ SPLINE, /* 5 point spline interpolation. Slowest resampling method but best quality. */ MAX, /* Maximum number of resample methods supported. */ } /* [ENUM] [ [DESCRIPTION] List of connection types between 2 DSP nodes. [REMARKS] FMOD_DSP_CONNECTION_TYPE_STANDARD<br> ----------------------------------<br> Default DSPConnection type. Audio is mixed from the input to the output DSP's audible buffer, meaning it will be part of the audible signal. A standard connection will execute its input DSP if it has not been executed before.<br> <br> FMOD_DSP_CONNECTION_TYPE_SIDECHAIN<br> ----------------------------------<br> Sidechain DSPConnection type. Audio is mixed from the input to the output DSP's sidechain buffer, meaning it will NOT be part of the audible signal. A sidechain connection will execute its input DSP if it has not been executed before.<br> The purpose of the seperate sidechain buffer in a DSP, is so that the DSP effect can privately access for analysis purposes. An example of use in this case, could be a compressor which analyzes the signal, to control its own effect parameters (ie a compression level or gain).<br> <br> For the effect developer, to accept sidechain data, the sidechain data will appear in the FMOD_DSP_STATE struct which is passed into the read callback of a DSP unit.<br> FMOD_DSP_STATE::sidechaindata and FMOD_DSP::sidechainchannels will hold the mixed result of any sidechain data flowing into it.<br> <br> FMOD_DSP_CONNECTION_TYPE_SEND<br> -----------------------------<br> Send DSPConnection type. Audio is mixed from the input to the output DSP's audible buffer, meaning it will be part of the audible signal. A send connection will NOT execute its input DSP if it has not been executed before.<br> A send connection will only read what exists at the input's buffer at the time of executing the output DSP unit (which can be considered the 'return')<br> <br> FMOD_DSP_CONNECTION_TYPE_SEND_SIDECHAIN<br> ---------------------------------------<br> Send sidechain DSPConnection type. Audio is mixed from the input to the output DSP's sidechain buffer, meaning it will NOT be part of the audible signal. A send sidechain connection will NOT execute its input DSP if it has not been executed before.<br> A send sidechain connection will only read what exists at the input's buffer at the time of executing the output DSP unit (which can be considered the 'sidechain return'). <br> For the effect developer, to accept sidechain data, the sidechain data will appear in the FMOD_DSP_STATE struct which is passed into the read callback of a DSP unit.<br> FMOD_DSP_STATE::sidechaindata and FMOD_DSP::sidechainchannels will hold the mixed result of any sidechain data flowing into it. [SEE_ALSO] DSP::addInput DSPConnection::getType ] */ public enum DSPCONNECTION_TYPE : int { STANDARD, /* Default connection type. Audio is mixed from the input to the output DSP's audible buffer. */ SIDECHAIN, /* Sidechain connection type. Audio is mixed from the input to the output DSP's sidechain buffer. */ SEND, /* Send connection type. Audio is mixed from the input to the output DSP's audible buffer, but the input is NOT executed, only copied from. A standard connection or sidechain needs to make an input execute to generate data. */ SEND_SIDECHAIN, /* Send sidechain connection type. Audio is mixed from the input to the output DSP's sidechain buffer, but the input is NOT executed, only copied from. A standard connection or sidechain needs to make an input execute to generate data. */ MAX, /* Maximum number of DSP connection types supported. */ } /* [ENUM] [ [DESCRIPTION] List of tag types that could be stored within a sound. These include id3 tags, metadata from netstreams and vorbis/asf data. [REMARKS] [SEE_ALSO] Sound::getTag ] */ public enum TAGTYPE : int { UNKNOWN = 0, ID3V1, ID3V2, VORBISCOMMENT, SHOUTCAST, ICECAST, ASF, MIDI, PLAYLIST, FMOD, USER, MAX /* Maximum number of tag types supported. */ } /* [ENUM] [ [DESCRIPTION] List of data types that can be returned by Sound::getTag [REMARKS] [SEE_ALSO] Sound::getTag ] */ public enum TAGDATATYPE : int { BINARY = 0, INT, FLOAT, STRING, STRING_UTF16, STRING_UTF16BE, STRING_UTF8, CDTOC, MAX /* Maximum number of tag datatypes supported. */ } /* [STRUCTURE] [ [DESCRIPTION] Structure describing a piece of tag data. [REMARKS] Members marked with [w] mean the user sets the value before passing it to the function. Members marked with [r] mean FMOD sets the value to be used after the function exits. [SEE_ALSO] Sound::getTag TAGTYPE TAGDATATYPE ] */ [StructLayout(LayoutKind.Sequential)] public struct TAG { public TAGTYPE type; /* [r] The type of this tag. */ public TAGDATATYPE datatype; /* [r] The type of data that this tag contains */ private IntPtr namePtr; /* [r] The name of this tag i.e. "TITLE", "ARTIST" etc. */ public IntPtr data; /* [r] Pointer to the tag data - its format is determined by the datatype member */ public uint datalen; /* [r] Length of the data contained in this tag */ public bool updated; /* [r] True if this tag has been updated since last being accessed with Sound::getTag */ public string name { get { return Marshal.PtrToStringAnsi(namePtr); } } } /* [ENUM] [ [DESCRIPTION] List of time types that can be returned by Sound::getLength and used with Channel::setPosition or Channel::getPosition. [REMARKS] [SEE_ALSO] Sound::getLength Channel::setPosition Channel::getPosition ] */ public enum TIMEUNIT { MS = 0x00000001, /* Milliseconds. */ PCM = 0x00000002, /* PCM Samples, related to milliseconds * samplerate / 1000. */ PCMBYTES = 0x00000004, /* Bytes, related to PCM samples * channels * datawidth (ie 16bit = 2 bytes). */ RAWBYTES = 0x00000008, /* Raw file bytes of (compressed) sound data (does not include headers). Only used by Sound::getLength and Channel::getPosition. */ PCMFRACTION = 0x00000010, /* Fractions of 1 PCM sample. Unsigned int range 0 to 0xFFFFFFFF. Used for sub-sample granularity for DSP purposes. */ MODORDER = 0x00000100, /* MOD/S3M/XM/IT. Order in a sequenced module format. Use Sound::getFormat to determine the format. */ MODROW = 0x00000200, /* MOD/S3M/XM/IT. Current row in a sequenced module format. Sound::getLength will return the number if rows in the currently playing or seeked to pattern. */ MODPATTERN = 0x00000400, /* MOD/S3M/XM/IT. Current pattern in a sequenced module format. Sound::getLength will return the number of patterns in the song and Channel::getPosition will return the currently playing pattern. */ BUFFERED = 0x10000000, /* Time value as seen by buffered stream. This is always ahead of audible time, and is only used for processing. */ } /* [DEFINE] [ [NAME] FMOD_PORT_INDEX [DESCRIPTION] [REMARKS] [SEE_ALSO] System::AttachChannelGroupToPort ] */ public struct PORT_INDEX { public const ulong NONE = 0xFFFFFFFFFFFFFFFF; } /* [STRUCTURE] [ [DESCRIPTION] Use this structure with System::createSound when more control is needed over loading. The possible reasons to use this with System::createSound are: - Loading a file from memory. - Loading a file from within another larger (possibly wad/pak) file, by giving the loader an offset and length. - To create a user created / non file based sound. - To specify a starting subsound to seek to within a multi-sample sounds (ie FSB/DLS) when created as a stream. - To specify which subsounds to load for multi-sample sounds (ie FSB/DLS) so that memory is saved and only a subset is actually loaded/read from disk. - To specify 'piggyback' read and seek callbacks for capture of sound data as fmod reads and decodes it. Useful for ripping decoded PCM data from sounds as they are loaded / played. - To specify a MIDI DLS sample set file to load when opening a MIDI file. See below on what members to fill for each of the above types of sound you want to create. [REMARKS] This structure is optional! Specify 0 or NULL in System::createSound if you don't need it! <u>Loading a file from memory.</u> - Create the sound using the FMOD_OPENMEMORY flag. - Mandatory. Specify 'length' for the size of the memory block in bytes. - Other flags are optional. <u>Loading a file from within another larger (possibly wad/pak) file, by giving the loader an offset and length.</u> - Mandatory. Specify 'fileoffset' and 'length'. - Other flags are optional. <u>To create a user created / non file based sound.</u> - Create the sound using the FMOD_OPENUSER flag. - Mandatory. Specify 'defaultfrequency, 'numchannels' and 'format'. - Other flags are optional. <u>To specify a starting subsound to seek to and flush with, within a multi-sample stream (ie FSB/DLS).</u> - Mandatory. Specify 'initialsubsound'. <u>To specify which subsounds to load for multi-sample sounds (ie FSB/DLS) so that memory is saved and only a subset is actually loaded/read from disk.</u> - Mandatory. Specify 'inclusionlist' and 'inclusionlistnum'. <u>To specify 'piggyback' read and seek callbacks for capture of sound data as fmod reads and decodes it. Useful for ripping decoded PCM data from sounds as they are loaded / played.</u> - Mandatory. Specify 'pcmreadcallback' and 'pcmseekcallback'. <u>To specify a MIDI DLS sample set file to load when opening a MIDI file.</u> - Mandatory. Specify 'dlsname'. Setting the 'decodebuffersize' is for cpu intensive codecs that may be causing stuttering, not file intensive codecs (ie those from CD or netstreams) which are normally altered with System::setStreamBufferSize. As an example of cpu intensive codecs, an mp3 file will take more cpu to decode than a PCM wav file. If you have a stuttering effect, then it is using more cpu than the decode buffer playback rate can keep up with. Increasing the decode buffersize will most likely solve this problem. FSB codec. If inclusionlist and numsubsounds are used together, this will trigger a special mode where subsounds are shuffled down to save memory. (useful for large FSB files where you only want to load 1 sound). There will be no gaps, ie no null subsounds. As an example, if there are 10,000 subsounds and there is an inclusionlist with only 1 entry, and numsubsounds = 1, then subsound 0 will be that entry, and there will only be the memory allocated for 1 subsound. Previously there would still be 10,000 subsound pointers and other associated codec entries allocated along with it multiplied by 10,000. Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value.<br> Members marked with [w] mean the variable can be written to. The user can set the value. [SEE_ALSO] System::createSound System::setStreamBufferSize FMOD_MODE FMOD_SOUND_FORMAT FMOD_SOUND_TYPE FMOD_CHANNELMASK FMOD_CHANNELORDER ] */ [StructLayout(LayoutKind.Sequential)] public struct CREATESOUNDEXINFO { public int cbsize; /* [w] Size of this structure. This is used so the structure can be expanded in the future and still work on older versions of FMOD Ex. */ public uint length; /* [w] Optional. Specify 0 to ignore. Size in bytes of file to load, or sound to create (in this case only if FMOD_OPENUSER is used). Required if loading from memory. If 0 is specified, then it will use the size of the file (unless loading from memory then an error will be returned). */ public uint fileoffset; /* [w] Optional. Specify 0 to ignore. Offset from start of the file to start loading from. This is useful for loading files from inside big data files. */ public int numchannels; /* [w] Optional. Specify 0 to ignore. Number of channels in a sound specified only if OPENUSER is used. */ public int defaultfrequency; /* [w] Optional. Specify 0 to ignore. Default frequency of sound in a sound specified only if OPENUSER is used. Other formats use the frequency determined by the file format. */ public SOUND_FORMAT format; /* [w] Optional. Specify 0 or SOUND_FORMAT_NONE to ignore. Format of the sound specified only if OPENUSER is used. Other formats use the format determined by the file format. */ public uint decodebuffersize; /* [w] Optional. Specify 0 to ignore. For streams. This determines the size of the double buffer (in PCM samples) that a stream uses. Use this for user created streams if you want to determine the size of the callback buffer passed to you. Specify 0 to use FMOD's default size which is currently equivalent to 400ms of the sound format created/loaded. */ public int initialsubsound; /* [w] Optional. Specify 0 to ignore. In a multi-sample file format such as .FSB/.DLS/.SF2, specify the initial subsound to seek to, only if CREATESTREAM is used. */ public int numsubsounds; /* [w] Optional. Specify 0 to ignore or have no subsounds. In a user created multi-sample sound, specify the number of subsounds within the sound that are accessable with Sound::getSubSound / SoundGetSubSound. */ public IntPtr inclusionlist; /* [w] Optional. Specify 0 to ignore. In a multi-sample format such as .FSB/.DLS/.SF2 it may be desirable to specify only a subset of sounds to be loaded out of the whole file. This is an array of subsound indicies to load into memory when created. */ public int inclusionlistnum; /* [w] Optional. Specify 0 to ignore. This is the number of integers contained within the */ public SOUND_PCMREADCALLBACK pcmreadcallback; /* [w] Optional. Specify 0 to ignore. Callback to 'piggyback' on FMOD's read functions and accept or even write PCM data while FMOD is opening the sound. Used for user sounds created with OPENUSER or for capturing decoded data as FMOD reads it. */ public SOUND_PCMSETPOSCALLBACK pcmsetposcallback; /* [w] Optional. Specify 0 to ignore. Callback for when the user calls a seeking function such as Channel::setPosition within a multi-sample sound, and for when it is opened.*/ public SOUND_NONBLOCKCALLBACK nonblockcallback; /* [w] Optional. Specify 0 to ignore. Callback for successful completion, or error while loading a sound that used the FMOD_NONBLOCKING flag.*/ public IntPtr dlsname; /* [w] Optional. Specify 0 to ignore. Filename for a DLS or SF2 sample set when loading a MIDI file. If not specified, on windows it will attempt to open /windows/system32/drivers/gm.dls, otherwise the MIDI will fail to open. */ public IntPtr encryptionkey; /* [w] Optional. Specify 0 to ignore. Key for encrypted FSB file. Without this key an encrypted FSB file will not load. */ public int maxpolyphony; /* [w] Optional. Specify 0 to ingore. For sequenced formats with dynamic channel allocation such as .MID and .IT, this specifies the maximum voice count allowed while playing. .IT defaults to 64. .MID defaults to 32. */ public IntPtr userdata; /* [w] Optional. Specify 0 to ignore. This is user data to be attached to the sound during creation. Access via Sound::getUserData. */ public SOUND_TYPE suggestedsoundtype; /* [w] Optional. Specify 0 or FMOD_SOUND_TYPE_UNKNOWN to ignore. Instead of scanning all codec types, use this to speed up loading by making it jump straight to this codec. */ public FILE_OPENCALLBACK useropen; /* [w] Optional. Specify 0 to ignore. Callback for opening this file. */ public FILE_CLOSECALLBACK userclose; /* [w] Optional. Specify 0 to ignore. Callback for closing this file. */ public FILE_READCALLBACK userread; /* [w] Optional. Specify 0 to ignore. Callback for reading from this file. */ public FILE_SEEKCALLBACK userseek; /* [w] Optional. Specify 0 to ignore. Callback for seeking within this file. */ public FILE_ASYNCREADCALLBACK userasyncread; /* [w] Optional. Specify 0 to ignore. Callback for asyncronously reading from this file. */ public FILE_ASYNCCANCELCALLBACK userasynccancel; /* [w] Optional. Specify 0 to ignore. Callback for cancelling an asyncronous read. */ public IntPtr fileuserdata; /* [w] Optional. Specify 0 to ignore. User data to be passed into the file callbacks. */ public CHANNELORDER channelorder; /* [w] Optional. Specify 0 to ignore. Use this to differ the way fmod maps multichannel sounds to speakers. See FMOD_CHANNELORDER for more. */ public CHANNELMASK channelmask; /* [w] Optional. Specify 0 to ignore. Use this to differ the way fmod maps multichannel sounds to speakers. See FMOD_CHANNELMASK for more. */ public IntPtr initialsoundgroup; /* [w] Optional. Specify 0 to ignore. Specify a sound group if required, to put sound in as it is created. */ public uint initialseekposition; /* [w] Optional. Specify 0 to ignore. For streams. Specify an initial position to seek the stream to. */ public TIMEUNIT initialseekpostype; /* [w] Optional. Specify 0 to ignore. For streams. Specify the time unit for the position set in initialseekposition. */ public int ignoresetfilesystem; /* [w] Optional. Specify 0 to ignore. Set to 1 to use fmod's built in file system. Ignores setFileSystem callbacks and also FMOD_CREATESOUNEXINFO file callbacks. Useful for specific cases where you don't want to use your own file system but want to use fmod's file system (ie net streaming). */ public uint audioqueuepolicy; /* [w] Optional. Specify 0 or FMOD_AUDIOQUEUE_CODECPOLICY_DEFAULT to ignore. Policy used to determine whether hardware or software is used for decoding, see FMOD_AUDIOQUEUE_CODECPOLICY for options (iOS >= 3.0 required, otherwise only hardware is available) */ public uint minmidigranularity; /* [w] Optional. Specify 0 to ignore. Allows you to set a minimum desired MIDI mixer granularity. Values smaller than 512 give greater than default accuracy at the cost of more CPU and vise versa. Specify 0 for default (512 samples). */ public int nonblockthreadid; /* [w] Optional. Specify 0 to ignore. Specifies a thread index to execute non blocking load on. Allows for up to 5 threads to be used for loading at once. This is to avoid one load blocking another. Maximum value = 4. */ } /* [STRUCTURE] [ [DESCRIPTION] Structure defining a reverb environment for FMOD_SOFTWARE based sounds only.<br> [REMARKS] Note the default reverb properties are the same as the FMOD_PRESET_GENERIC preset.<br> Note that integer values that typically range from -10,000 to 1000 are represented in decibels, and are of a logarithmic scale, not linear, wheras float values are always linear.<br> <br> The numerical values listed below are the maximum, minimum and default values for each variable respectively.<br> <br> Hardware voice / Platform Specific reverb support.<br> WII See FMODWII.H for hardware specific reverb functionality.<br> 3DS See FMOD3DS.H for hardware specific reverb functionality.<br> PSP See FMODWII.H for hardware specific reverb functionality.<br> <br> Members marked with [r] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value.<br> Members marked with [w] mean the variable can be written to. The user can set the value.<br> Members marked with [r/w] are either read or write depending on if you are using System::setReverbProperties (w) or System::getReverbProperties (r). [SEE_ALSO] System::setReverbProperties System::getReverbProperties FMOD_REVERB_PRESETS ] */ #pragma warning disable 414 [StructLayout(LayoutKind.Sequential)] public struct REVERB_PROPERTIES { /* MIN MAX DEFAULT DESCRIPTION */ float DecayTime; /* [r/w] 0.0 20000.0 1500.0 Reverberation decay time in ms */ float EarlyDelay; /* [r/w] 0.0 300.0 7.0 Initial reflection delay time */ float LateDelay; /* [r/w] 0.0 100 11.0 Late reverberation delay time relative to initial reflection */ float HFReference; /* [r/w] 20.0 20000.0 5000 Reference high frequency (hz) */ float HFDecayRatio; /* [r/w] 10.0 100.0 50.0 High-frequency to mid-frequency decay time ratio */ float Diffusion; /* [r/w] 0.0 100.0 100.0 Value that controls the echo density in the late reverberation decay. */ float Density; /* [r/w] 0.0 100.0 100.0 Value that controls the modal density in the late reverberation decay */ float LowShelfFrequency; /* [r/w] 20.0 1000.0 250.0 Reference low frequency (hz) */ float LowShelfGain; /* [r/w] -36.0 12.0 0.0 Relative room effect level at low frequencies */ float HighCut; /* [r/w] 20.0 20000.0 20000.0 Relative room effect level at high frequencies */ float EarlyLateMix; /* [r/w] 0.0 100.0 50.0 Early reflections level relative to room effect */ float WetLevel; /* [r/w] -80.0 20.0 -6.0 Room effect level (at mid frequencies) * */ #region wrapperinternal public REVERB_PROPERTIES(float decayTime, float earlyDelay, float lateDelay, float hfReference, float hfDecayRatio, float diffusion, float density, float lowShelfFrequency, float lowShelfGain, float highCut, float earlyLateMix, float wetLevel) { DecayTime = decayTime; EarlyDelay = earlyDelay; LateDelay = lateDelay; HFReference = hfReference; HFDecayRatio = hfDecayRatio; Diffusion = diffusion; Density = density; LowShelfFrequency = lowShelfFrequency; LowShelfGain = lowShelfGain; HighCut = highCut; EarlyLateMix = earlyLateMix; WetLevel = wetLevel; } #endregion } #pragma warning restore 414 /* [DEFINE] [ [NAME] FMOD_REVERB_PRESETS [DESCRIPTION] A set of predefined environment PARAMETERS, created by Creative Labs These are used to initialize an FMOD_REVERB_PROPERTIES structure statically. ie FMOD_REVERB_PROPERTIES prop = FMOD_PRESET_GENERIC; [SEE_ALSO] System::setReverbProperties ] */ class PRESET { /* Instance Env Diffus Room RoomHF RmLF DecTm DecHF DecLF Refl RefDel Revb RevDel ModTm ModDp HFRef LFRef Diffus Densty FLAGS */ public REVERB_PROPERTIES OFF() { return new REVERB_PROPERTIES( 1000, 7, 11, 5000, 100, 100, 100, 250, 0, 20, 96, -80.0f );} public REVERB_PROPERTIES GENERIC() { return new REVERB_PROPERTIES( 1500, 7, 11, 5000, 83, 100, 100, 250, 0, 14500, 96, -8.0f );} public REVERB_PROPERTIES PADDEDCELL() { return new REVERB_PROPERTIES( 170, 1, 2, 5000, 10, 100, 100, 250, 0, 160, 84, -7.8f );} public REVERB_PROPERTIES ROOM() { return new REVERB_PROPERTIES( 400, 2, 3, 5000, 83, 100, 100, 250, 0, 6050, 88, -9.4f );} public REVERB_PROPERTIES BATHROOM() { return new REVERB_PROPERTIES( 1500, 7, 11, 5000, 54, 100, 60, 250, 0, 2900, 83, 0.5f );} public REVERB_PROPERTIES LIVINGROOM() { return new REVERB_PROPERTIES( 500, 3, 4, 5000, 10, 100, 100, 250, 0, 160, 58, -19.0f );} public REVERB_PROPERTIES STONEROOM() { return new REVERB_PROPERTIES( 2300, 12, 17, 5000, 64, 100, 100, 250, 0, 7800, 71, -8.5f );} public REVERB_PROPERTIES AUDITORIUM() { return new REVERB_PROPERTIES( 4300, 20, 30, 5000, 59, 100, 100, 250, 0, 5850, 64, -11.7f );} public REVERB_PROPERTIES CONCERTHALL() { return new REVERB_PROPERTIES( 3900, 20, 29, 5000, 70, 100, 100, 250, 0, 5650, 80, -9.8f );} public REVERB_PROPERTIES CAVE() { return new REVERB_PROPERTIES( 2900, 15, 22, 5000, 100, 100, 100, 250, 0, 20000, 59, -11.3f );} public REVERB_PROPERTIES ARENA() { return new REVERB_PROPERTIES( 7200, 20, 30, 5000, 33, 100, 100, 250, 0, 4500, 80, -9.6f );} public REVERB_PROPERTIES HANGAR() { return new REVERB_PROPERTIES( 10000, 20, 30, 5000, 23, 100, 100, 250, 0, 3400, 72, -7.4f );} public REVERB_PROPERTIES CARPETTEDHALLWAY() { return new REVERB_PROPERTIES( 300, 2, 30, 5000, 10, 100, 100, 250, 0, 500, 56, -24.0f );} public REVERB_PROPERTIES HALLWAY() { return new REVERB_PROPERTIES( 1500, 7, 11, 5000, 59, 100, 100, 250, 0, 7800, 87, -5.5f );} public REVERB_PROPERTIES STONECORRIDOR() { return new REVERB_PROPERTIES( 270, 13, 20, 5000, 79, 100, 100, 250, 0, 9000, 86, -6.0f );} public REVERB_PROPERTIES ALLEY() { return new REVERB_PROPERTIES( 1500, 7, 11, 5000, 86, 100, 100, 250, 0, 8300, 80, -9.8f );} public REVERB_PROPERTIES FOREST() { return new REVERB_PROPERTIES( 1500, 162, 88, 5000, 54, 79, 100, 250, 0, 760, 94, -12.3f );} public REVERB_PROPERTIES CITY() { return new REVERB_PROPERTIES( 1500, 7, 11, 5000, 67, 50, 100, 250, 0, 4050, 66, -26.0f );} public REVERB_PROPERTIES MOUNTAINS() { return new REVERB_PROPERTIES( 1500, 300, 100, 5000, 21, 27, 100, 250, 0, 1220, 82, -24.0f );} public REVERB_PROPERTIES QUARRY() { return new REVERB_PROPERTIES( 1500, 61, 25, 5000, 83, 100, 100, 250, 0, 3400, 100, -5.0f );} public REVERB_PROPERTIES PLAIN() { return new REVERB_PROPERTIES( 1500, 179, 100, 5000, 50, 21, 100, 250, 0, 1670, 65, -28.0f );} public REVERB_PROPERTIES PARKINGLOT() { return new REVERB_PROPERTIES( 1700, 8, 12, 5000, 100, 100, 100, 250, 0, 20000, 56, -19.5f );} public REVERB_PROPERTIES SEWERPIPE() { return new REVERB_PROPERTIES( 2800, 14, 21, 5000, 14, 80, 60, 250, 0, 3400, 66, 1.2f );} public REVERB_PROPERTIES UNDERWATER() { return new REVERB_PROPERTIES( 1500, 7, 11, 5000, 10, 100, 100, 250, 0, 500, 92, 7.0f );} } /* [STRUCTURE] [ [DESCRIPTION] Settings for advanced features like configuring memory and cpu usage for the FMOD_CREATECOMPRESSEDSAMPLE feature. [REMARKS] maxMPEGCodecs / maxADPCMCodecs / maxXMACodecs will determine the maximum cpu usage of playing realtime samples. Use this to lower potential excess cpu usage and also control memory usage.<br> [SEE_ALSO] System::setAdvancedSettings System::getAdvancedSettings ] */ [StructLayout(LayoutKind.Sequential)] public struct ADVANCEDSETTINGS { public int cbSize; /* [r] Size of structure. Use sizeof(FMOD_ADVANCEDSETTINGS) */ public int maxMPEGCodecs; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_CREATECOMPRESSEDSAMPLE only. MPEG codecs consume 30,528 bytes per instance and this number will determine how many MPEG channels can be played simultaneously. Default = 32. */ public int maxADPCMCodecs; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_CREATECOMPRESSEDSAMPLE only. ADPCM codecs consume 3,128 bytes per instance and this number will determine how many ADPCM channels can be played simultaneously. Default = 32. */ public int maxXMACodecs; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_CREATECOMPRESSEDSAMPLE only. XMA codecs consume 14,836 bytes per instance and this number will determine how many XMA channels can be played simultaneously. Default = 32. */ public int maxCELTCodecs; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_CREATECOMPRESSEDSAMPLE only. CELT codecs consume 25,408 bytes per instance and this number will determine how many CELT channels can be played simultaneously. Default = 32. */ public int maxVorbisCodecs; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_CREATECOMPRESSEDSAMPLE only. Vorbis codecs consume 23,256 bytes per instance and this number will determine how many Vorbis channels can be played simultaneously. Default = 32. */ public int maxAT9Codecs; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_CREATECOMPRESSEDSAMPLE only. AT9 codecs consume 8,720 bytes per instance and this number will determine how many AT9 channels can be played simultaneously. Default = 32. */ public int maxPCMCodecs; /* [r/w] Optional. Specify 0 to ignore. For use with PS3 only. PCM codecs consume 12,672 bytes per instance and this number will determine how many streams and PCM voices can be played simultaneously. Default = 16. */ public int ASIONumChannels; /* [r/w] Optional. Specify 0 to ignore. Number of channels available on the ASIO device. */ public IntPtr ASIOChannelList; /* [r/w] Optional. Specify 0 to ignore. Pointer to an array of strings (number of entries defined by ASIONumChannels) with ASIO channel names. */ public IntPtr ASIOSpeakerList; /* [r/w] Optional. Specify 0 to ignore. Pointer to a list of speakers that the ASIO channels map to. This can be called after System::init to remap ASIO output. */ public float HRTFMinAngle; /* [r/w] Optional. For use with FMOD_INIT_HRTF_LOWPASS. The angle range (0-360) of a 3D sound in relation to the listener, at which the HRTF function begins to have an effect. 0 = in front of the listener. 180 = from 90 degrees to the left of the listener to 90 degrees to the right. 360 = behind the listener. Default = 180.0. */ public float HRTFMaxAngle; /* [r/w] Optional. For use with FMOD_INIT_HRTF_LOWPASS. The angle range (0-360) of a 3D sound in relation to the listener, at which the HRTF function has maximum effect. 0 = front of the listener. 180 = from 90 degrees to the left of the listener to 90 degrees to the right. 360 = behind the listener. Default = 360.0. */ public float HRTFFreq; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_INIT_HRTF_LOWPASS. The cutoff frequency of the HRTF's lowpass filter function when at maximum effect. (i.e. at HRTFMaxAngle). Default = 4000.0. */ public float vol0virtualvol; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_INIT_VOL0_BECOMES_VIRTUAL. If this flag is used, and the volume is below this, then the sound will become virtual. Use this value to raise the threshold to a different point where a sound goes virtual. */ public uint defaultDecodeBufferSize; /* [r/w] Optional. Specify 0 to ignore. For streams. This determines the default size of the double buffer (in milliseconds) that a stream uses. Default = 400ms */ public ushort profilePort; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_INIT_ENABLE_PROFILE. Specify the port to listen on for connections by the profiler application. */ public uint geometryMaxFadeTime; /* [r/w] Optional. Specify 0 to ignore. The maximum time in miliseconds it takes for a channel to fade to the new level when its occlusion changes. */ public float distanceFilterCenterFreq; /* [r/w] Optional. Specify 0 to ignore. For use with FMOD_INIT_DISTANCE_FILTERING. The default center frequency in Hz for the distance filtering effect. Default = 1500.0. */ public int reverb3Dinstance; /* [r/w] Optional. Specify 0 to ignore. Out of 0 to 3, 3d reverb spheres will create a phyical reverb unit on this instance slot. See FMOD_REVERB_PROPERTIES. */ public int DSPBufferPoolSize; /* [r/w] Optional. Specify 0 to ignore. Number of buffers in DSP buffer pool. Each buffer will be DSPBlockSize * sizeof(float) * SpeakerModeChannelCount. ie 7.1 @ 1024 DSP block size = 8 * 1024 * 4 = 32kb. Default = 8. */ public uint stackSizeStream; /* [r/w] Optional. Specify 0 to ignore. Specify the stack size for the FMOD Stream thread in bytes. Useful for custom codecs that use excess stack. Default 49,152 (48kb) */ public uint stackSizeNonBlocking; /* [r/w] Optional. Specify 0 to ignore. Specify the stack size for the FMOD_NONBLOCKING loading thread. Useful for custom codecs that use excess stack. Default 65,536 (64kb) */ public uint stackSizeMixer; /* [r/w] Optional. Specify 0 to ignore. Specify the stack size for the FMOD mixer thread. Useful for custom dsps that use excess stack. Default 49,152 (48kb) */ public uint resamplerMethod; /* [r/w] Optional. Specify 0 to ignore. Resampling method used with fmod's software mixer. See FMOD_DSP_RESAMPLER for details on methods. */ public uint commandQueueSize; /* [r/w] Optional. Specify 0 to ignore. Specify the command queue size for thread safe processing. Default 2048 (2kb) */ public uint randomSeed; /* [r/w] Optional. Specify 0 to ignore. Seed value that FMOD will use to initialize its internal random number generators. */ } /* FMOD System factory functions. Use this to create an FMOD System Instance. below you will see System init/close to get started. */ public class Factory { public static RESULT System_Create(out System system) { system = null; RESULT result = RESULT.OK; IntPtr rawPtr = new IntPtr(); result = FMOD_System_Create(out rawPtr); if (result != RESULT.OK) { return result; } system = new System(rawPtr); return result; } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_Create (out IntPtr system); #endregion } public class Memory { public static RESULT Initialize(IntPtr poolmem, int poollen, MEMORY_ALLOC_CALLBACK useralloc, MEMORY_REALLOC_CALLBACK userrealloc, MEMORY_FREE_CALLBACK userfree, MEMORY_TYPE memtypeflags) { return FMOD_Memory_Initialize(poolmem, poollen, useralloc, userrealloc, userfree, memtypeflags); } public static RESULT GetStats(out int currentalloced, out int maxalloced) { return GetStats(out currentalloced, out maxalloced, false); } public static RESULT GetStats(out int currentalloced, out int maxalloced, bool blocking) { return FMOD_Memory_GetStats(out currentalloced, out maxalloced, blocking); } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_Memory_Initialize(IntPtr poolmem, int poollen, MEMORY_ALLOC_CALLBACK useralloc, MEMORY_REALLOC_CALLBACK userrealloc, MEMORY_FREE_CALLBACK userfree, MEMORY_TYPE memtypeflags); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Memory_GetStats(out int currentalloced, out int maxalloced, bool blocking); #endregion } public class Debug { public static RESULT Initialize(DEBUG_FLAGS flags, DEBUG_MODE mode, DEBUG_CALLBACK callback, string filename) { return FMOD_Debug_Initialize(flags, mode, callback, filename); } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_Debug_Initialize(DEBUG_FLAGS flags, DEBUG_MODE mode, DEBUG_CALLBACK callback, string filename); #endregion } public class HandleBase { public HandleBase(IntPtr newPtr) { rawPtr = newPtr; } public bool isValid() { return rawPtr != IntPtr.Zero; } public IntPtr getRaw() { return rawPtr; } protected IntPtr rawPtr; #region equality public override bool Equals(Object obj) { return Equals(obj as HandleBase); } public bool Equals(HandleBase p) { // Equals if p not null and handle is the same return ((object)p != null && rawPtr == p.rawPtr); } public override int GetHashCode() { return rawPtr.ToInt32(); } public static bool operator ==(HandleBase a, HandleBase b) { // If both are null, or both are same instance, return true. if (Object.ReferenceEquals(a, b)) { return true; } // If one is null, but not both, return false. if (((object)a == null) || ((object)b == null)) { return false; } // Return true if the handle matches return (a.rawPtr == b.rawPtr); } public static bool operator !=(HandleBase a, HandleBase b) { return !(a == b); } #endregion } /* 'System' API. */ public class System : HandleBase { public RESULT release () { RESULT result = FMOD_System_Release(rawPtr); if (result == RESULT.OK) { rawPtr = IntPtr.Zero; } return result; } // Pre-init functions. public RESULT setOutput (OUTPUTTYPE output) { return FMOD_System_SetOutput(rawPtr, output); } public RESULT getOutput (out OUTPUTTYPE output) { return FMOD_System_GetOutput(rawPtr, out output); } public RESULT getNumDrivers (out int numdrivers) { return FMOD_System_GetNumDrivers(rawPtr, out numdrivers); } public RESULT getDriverInfo (int id, StringBuilder name, int namelen, out GUID guid, out int systemrate, out SPEAKERMODE speakermode, out int speakermodechannels) { IntPtr stringMem = Marshal.AllocHGlobal(name.Capacity); RESULT result = FMOD_System_GetDriverInfo(rawPtr, id, stringMem, namelen, out guid, out systemrate, out speakermode, out speakermodechannels); StringMarshalHelper.NativeToBuilder(name, stringMem); Marshal.FreeHGlobal(stringMem); return result; } public RESULT setDriver (int driver) { return FMOD_System_SetDriver(rawPtr, driver); } public RESULT getDriver (out int driver) { return FMOD_System_GetDriver(rawPtr, out driver); } public RESULT setSoftwareChannels (int numsoftwarechannels) { return FMOD_System_SetSoftwareChannels(rawPtr, numsoftwarechannels); } public RESULT getSoftwareChannels (out int numsoftwarechannels) { return FMOD_System_GetSoftwareChannels(rawPtr, out numsoftwarechannels); } public RESULT setSoftwareFormat (int samplerate, SPEAKERMODE speakermode, int numrawspeakers) { return FMOD_System_SetSoftwareFormat(rawPtr, samplerate, speakermode, numrawspeakers); } public RESULT getSoftwareFormat (out int samplerate, out SPEAKERMODE speakermode, out int numrawspeakers) { return FMOD_System_GetSoftwareFormat(rawPtr, out samplerate, out speakermode, out numrawspeakers); } public RESULT setDSPBufferSize (uint bufferlength, int numbuffers) { return FMOD_System_SetDSPBufferSize(rawPtr, bufferlength, numbuffers); } public RESULT getDSPBufferSize (out uint bufferlength, out int numbuffers) { return FMOD_System_GetDSPBufferSize(rawPtr, out bufferlength, out numbuffers); } public RESULT setFileSystem (FILE_OPENCALLBACK useropen, FILE_CLOSECALLBACK userclose, FILE_READCALLBACK userread, FILE_SEEKCALLBACK userseek, FILE_ASYNCREADCALLBACK userasyncread, FILE_ASYNCCANCELCALLBACK userasynccancel, int blockalign) { return FMOD_System_SetFileSystem(rawPtr, useropen, userclose, userread, userseek, userasyncread, userasynccancel, blockalign); } public RESULT attachFileSystem (FILE_OPENCALLBACK useropen, FILE_CLOSECALLBACK userclose, FILE_READCALLBACK userread, FILE_SEEKCALLBACK userseek) { return FMOD_System_AttachFileSystem(rawPtr, useropen, userclose, userread, userseek); } public RESULT setAdvancedSettings (ref ADVANCEDSETTINGS settings) { settings.cbSize = Marshal.SizeOf(settings); return FMOD_System_SetAdvancedSettings(rawPtr, ref settings); } public RESULT getAdvancedSettings (ref ADVANCEDSETTINGS settings) { settings.cbSize = Marshal.SizeOf(settings); return FMOD_System_GetAdvancedSettings(rawPtr, ref settings); } public RESULT setCallback (SYSTEM_CALLBACK callback, SYSTEM_CALLBACK_TYPE callbackmask) { return FMOD_System_SetCallback(rawPtr, callback, callbackmask); } // Plug-in support. public RESULT setPluginPath (string path) { return FMOD_System_SetPluginPath(rawPtr, Encoding.UTF8.GetBytes(path + Char.MinValue)); } public RESULT loadPlugin (string filename, out uint handle, uint priority) { return FMOD_System_LoadPlugin(rawPtr, Encoding.UTF8.GetBytes(filename + Char.MinValue), out handle, priority); } public RESULT loadPlugin (string filename, out uint handle) { return loadPlugin(filename, out handle, 0); } public RESULT unloadPlugin (uint handle) { return FMOD_System_UnloadPlugin(rawPtr, handle); } public RESULT getNumPlugins (PLUGINTYPE plugintype, out int numplugins) { return FMOD_System_GetNumPlugins(rawPtr, plugintype, out numplugins); } public RESULT getPluginHandle (PLUGINTYPE plugintype, int index, out uint handle) { return FMOD_System_GetPluginHandle(rawPtr, plugintype, index, out handle); } public RESULT getPluginInfo (uint handle, out PLUGINTYPE plugintype, StringBuilder name, int namelen, out uint version) { IntPtr stringMem = Marshal.AllocHGlobal(name.Capacity); RESULT result = FMOD_System_GetPluginInfo(rawPtr, handle, out plugintype, stringMem, namelen, out version); StringMarshalHelper.NativeToBuilder(name, stringMem); Marshal.FreeHGlobal(stringMem); return result; } public RESULT setOutputByPlugin (uint handle) { return FMOD_System_SetOutputByPlugin(rawPtr, handle); } public RESULT getOutputByPlugin (out uint handle) { return FMOD_System_GetOutputByPlugin(rawPtr, out handle); } public RESULT createDSPByPlugin(uint handle, out DSP dsp) { dsp = null; IntPtr dspraw; RESULT result = FMOD_System_CreateDSPByPlugin(rawPtr, handle, out dspraw); dsp = new DSP(dspraw); return result; } public RESULT getDSPInfoByPlugin(uint handle, out IntPtr description) { return FMOD_System_GetDSPInfoByPlugin(rawPtr, handle, out description); } /* public RESULT registerCodec(ref CODEC_DESCRIPTION description, out uint handle, uint priority) { return FMOD_System_RegisterCodec(rawPtr, ref description, out handle, priority); } */ public RESULT registerDSP(ref DSP_DESCRIPTION description, out uint handle) { return FMOD_System_RegisterDSP(rawPtr, ref description, out handle); } // Init/Close. public RESULT init (int maxchannels, INITFLAGS flags, IntPtr extradriverdata) { return FMOD_System_Init(rawPtr, maxchannels, flags, extradriverdata); } public RESULT close () { return FMOD_System_Close(rawPtr); } // General post-init system functions. public RESULT update () { return FMOD_System_Update(rawPtr); } public RESULT setSpeakerPosition(SPEAKER speaker, float x, float y, bool active) { return FMOD_System_SetSpeakerPosition(rawPtr, speaker, x, y, active); } public RESULT getSpeakerPosition(SPEAKER speaker, out float x, out float y, out bool active) { return FMOD_System_GetSpeakerPosition(rawPtr, speaker, out x, out y, out active); } public RESULT setStreamBufferSize(uint filebuffersize, TIMEUNIT filebuffersizetype) { return FMOD_System_SetStreamBufferSize(rawPtr, filebuffersize, filebuffersizetype); } public RESULT getStreamBufferSize(out uint filebuffersize, out TIMEUNIT filebuffersizetype) { return FMOD_System_GetStreamBufferSize(rawPtr, out filebuffersize, out filebuffersizetype); } public RESULT set3DSettings (float dopplerscale, float distancefactor, float rolloffscale) { return FMOD_System_Set3DSettings(rawPtr, dopplerscale, distancefactor, rolloffscale); } public RESULT get3DSettings (out float dopplerscale, out float distancefactor, out float rolloffscale) { return FMOD_System_Get3DSettings(rawPtr, out dopplerscale, out distancefactor, out rolloffscale); } public RESULT set3DNumListeners (int numlisteners) { return FMOD_System_Set3DNumListeners(rawPtr, numlisteners); } public RESULT get3DNumListeners (out int numlisteners) { return FMOD_System_Get3DNumListeners(rawPtr, out numlisteners); } public RESULT set3DListenerAttributes(int listener, ref VECTOR pos, ref VECTOR vel, ref VECTOR forward, ref VECTOR up) { return FMOD_System_Set3DListenerAttributes(rawPtr, listener, ref pos, ref vel, ref forward, ref up); } public RESULT get3DListenerAttributes(int listener, out VECTOR pos, out VECTOR vel, out VECTOR forward, out VECTOR up) { return FMOD_System_Get3DListenerAttributes(rawPtr, listener, out pos, out vel, out forward, out up); } public RESULT set3DRolloffCallback (CB_3D_ROLLOFFCALLBACK callback) { return FMOD_System_Set3DRolloffCallback (rawPtr, callback); } public RESULT mixerSuspend () { return FMOD_System_MixerSuspend(rawPtr); } public RESULT mixerResume () { return FMOD_System_MixerResume(rawPtr); } // System information functions. public RESULT getVersion (out uint version) { return FMOD_System_GetVersion(rawPtr, out version); } public RESULT getOutputHandle (out IntPtr handle) { return FMOD_System_GetOutputHandle(rawPtr, out handle); } public RESULT getChannelsPlaying (out int channels) { return FMOD_System_GetChannelsPlaying(rawPtr, out channels); } public RESULT getCPUUsage (out float dsp, out float stream, out float geometry, out float update, out float total) { return FMOD_System_GetCPUUsage(rawPtr, out dsp, out stream, out geometry, out update, out total); } public RESULT getSoundRAM (out int currentalloced, out int maxalloced, out int total) { return FMOD_System_GetSoundRAM(rawPtr, out currentalloced, out maxalloced, out total); } // Sound/DSP/Channel/FX creation and retrieval. public RESULT createSound (string name, MODE mode, ref CREATESOUNDEXINFO exinfo, out Sound sound) { sound = null; byte[] stringData; stringData = Encoding.UTF8.GetBytes(name + Char.MinValue); exinfo.cbsize = Marshal.SizeOf(exinfo); IntPtr soundraw; RESULT result = FMOD_System_CreateSound(rawPtr, stringData, mode, ref exinfo, out soundraw); sound = new Sound(soundraw); return result; } public RESULT createSound (byte[] data, MODE mode, ref CREATESOUNDEXINFO exinfo, out Sound sound) { sound = null; exinfo.cbsize = Marshal.SizeOf(exinfo); IntPtr soundraw; RESULT result = FMOD_System_CreateSound(rawPtr, data, mode, ref exinfo, out soundraw); sound = new Sound(soundraw); return result; } public RESULT createSound (string name, MODE mode, out Sound sound) { CREATESOUNDEXINFO exinfo = new CREATESOUNDEXINFO(); exinfo.cbsize = Marshal.SizeOf(exinfo); return createSound(name, mode, ref exinfo, out sound); } public RESULT createStream (string name, MODE mode, ref CREATESOUNDEXINFO exinfo, out Sound sound) { sound = null; byte[] stringData; stringData = Encoding.UTF8.GetBytes(name + Char.MinValue); exinfo.cbsize = Marshal.SizeOf(exinfo); IntPtr soundraw; RESULT result = FMOD_System_CreateStream(rawPtr, stringData, mode, ref exinfo, out soundraw); sound = new Sound(soundraw); return result; } public RESULT createStream (byte[] data, MODE mode, ref CREATESOUNDEXINFO exinfo, out Sound sound) { sound = null; exinfo.cbsize = Marshal.SizeOf(exinfo); IntPtr soundraw; RESULT result = FMOD_System_CreateStream(rawPtr, data, mode, ref exinfo, out soundraw); sound = new Sound(soundraw); return result; } public RESULT createStream (string name, MODE mode, out Sound sound) { CREATESOUNDEXINFO exinfo = new CREATESOUNDEXINFO(); exinfo.cbsize = Marshal.SizeOf(exinfo); return createStream(name, mode, ref exinfo, out sound); } public RESULT createDSP (ref DSP_DESCRIPTION description, out DSP dsp) { dsp = null; IntPtr dspraw; RESULT result = FMOD_System_CreateDSP(rawPtr, ref description, out dspraw); dsp = new DSP(dspraw); return result; } public RESULT createDSPByType (DSP_TYPE type, out DSP dsp) { dsp = null; IntPtr dspraw; RESULT result = FMOD_System_CreateDSPByType(rawPtr, type, out dspraw); dsp = new DSP(dspraw); return result; } public RESULT createChannelGroup (string name, out ChannelGroup channelgroup) { channelgroup = null; byte[] stringData = Encoding.UTF8.GetBytes(name + Char.MinValue); IntPtr channelgroupraw; RESULT result = FMOD_System_CreateChannelGroup(rawPtr, stringData, out channelgroupraw); channelgroup = new ChannelGroup(channelgroupraw); return result; } public RESULT createSoundGroup (string name, out SoundGroup soundgroup) { soundgroup = null; byte[] stringData = Encoding.UTF8.GetBytes(name + Char.MinValue); IntPtr soundgroupraw; RESULT result = FMOD_System_CreateSoundGroup(rawPtr, stringData, out soundgroupraw); soundgroup = new SoundGroup(soundgroupraw); return result; } public RESULT createReverb3D (out Reverb3D reverb) { IntPtr reverbraw; RESULT result = FMOD_System_CreateReverb3D(rawPtr, out reverbraw); reverb = new Reverb3D(reverbraw); return result; } public RESULT playSound (Sound sound, ChannelGroup channelGroup, bool paused, out Channel channel) { channel = null; IntPtr channelGroupRaw = (channelGroup != null) ? channelGroup.getRaw() : IntPtr.Zero; IntPtr channelraw; RESULT result = FMOD_System_PlaySound(rawPtr, sound.getRaw(), channelGroupRaw, paused, out channelraw); channel = new Channel(channelraw); return result; } public RESULT playDSP (DSP dsp, ChannelGroup channelGroup, bool paused, out Channel channel) { channel = null; IntPtr channelGroupRaw = (channelGroup != null) ? channelGroup.getRaw() : IntPtr.Zero; IntPtr channelraw; RESULT result = FMOD_System_PlayDSP(rawPtr, dsp.getRaw(), channelGroupRaw, paused, out channelraw); channel = new Channel(channelraw); return result; } public RESULT getChannel (int channelid, out Channel channel) { channel = null; IntPtr channelraw; RESULT result = FMOD_System_GetChannel(rawPtr, channelid, out channelraw); channel = new Channel(channelraw); return result; } public RESULT getMasterChannelGroup (out ChannelGroup channelgroup) { channelgroup = null; IntPtr channelgroupraw; RESULT result = FMOD_System_GetMasterChannelGroup(rawPtr, out channelgroupraw); channelgroup = new ChannelGroup(channelgroupraw); return result; } public RESULT getMasterSoundGroup (out SoundGroup soundgroup) { soundgroup = null; IntPtr soundgroupraw; RESULT result = FMOD_System_GetMasterSoundGroup(rawPtr, out soundgroupraw); soundgroup = new SoundGroup(soundgroupraw); return result; } // Routing to ports. public RESULT attachChannelGroupToPort(uint portType, ulong portIndex, ChannelGroup channelgroup) { return FMOD_System_AttachChannelGroupToPort(rawPtr, portType, portIndex, channelgroup.getRaw()); } public RESULT detachChannelGroupFromPort(ChannelGroup channelgroup) { return FMOD_System_DetachChannelGroupFromPort(rawPtr, channelgroup.getRaw()); } // Reverb api. public RESULT setReverbProperties (int instance, ref REVERB_PROPERTIES prop) { return FMOD_System_SetReverbProperties(rawPtr, instance, ref prop); } public RESULT getReverbProperties (int instance, out REVERB_PROPERTIES prop) { return FMOD_System_GetReverbProperties(rawPtr, instance, out prop); } // System level DSP functionality. public RESULT lockDSP () { return FMOD_System_LockDSP(rawPtr); } public RESULT unlockDSP () { return FMOD_System_UnlockDSP(rawPtr); } // Recording api public RESULT getRecordNumDrivers (out int numdrivers) { return FMOD_System_GetRecordNumDrivers(rawPtr, out numdrivers); } public RESULT getRecordDriverInfo(int id, StringBuilder name, int namelen, out GUID guid, out int systemrate, out SPEAKERMODE speakermode, out int speakermodechannels) { IntPtr stringMem = Marshal.AllocHGlobal(name.Capacity); RESULT result = FMOD_System_GetRecordDriverInfo(rawPtr, id, stringMem, namelen, out guid, out systemrate, out speakermode, out speakermodechannels); StringMarshalHelper.NativeToBuilder(name, stringMem); Marshal.FreeHGlobal(stringMem); return result; } public RESULT getRecordPosition (int id, out uint position) { return FMOD_System_GetRecordPosition(rawPtr, id, out position); } public RESULT recordStart (int id, Sound sound, bool loop) { return FMOD_System_RecordStart(rawPtr, id, sound.getRaw(), loop); } public RESULT recordStop (int id) { return FMOD_System_RecordStop(rawPtr, id); } public RESULT isRecording (int id, out bool recording) { return FMOD_System_IsRecording(rawPtr, id, out recording); } // Geometry api public RESULT createGeometry (int maxpolygons, int maxvertices, out Geometry geometry) { geometry = null; IntPtr geometryraw; RESULT result = FMOD_System_CreateGeometry(rawPtr, maxpolygons, maxvertices, out geometryraw); geometry = new Geometry(geometryraw); return result; } public RESULT setGeometrySettings (float maxworldsize) { return FMOD_System_SetGeometrySettings(rawPtr, maxworldsize); } public RESULT getGeometrySettings (out float maxworldsize) { return FMOD_System_GetGeometrySettings(rawPtr, out maxworldsize); } public RESULT loadGeometry(IntPtr data, int datasize, out Geometry geometry) { geometry = null; IntPtr geometryraw; RESULT result = FMOD_System_LoadGeometry(rawPtr, data, datasize, out geometryraw); geometry = new Geometry(geometryraw); return result; } public RESULT getGeometryOcclusion (ref VECTOR listener, ref VECTOR source, out float direct, out float reverb) { return FMOD_System_GetGeometryOcclusion(rawPtr, ref listener, ref source, out direct, out reverb); } // Network functions public RESULT setNetworkProxy (string proxy) { return FMOD_System_SetNetworkProxy(rawPtr, Encoding.UTF8.GetBytes(proxy + Char.MinValue)); } public RESULT getNetworkProxy (StringBuilder proxy, int proxylen) { IntPtr stringMem = Marshal.AllocHGlobal(proxy.Capacity); RESULT result = FMOD_System_GetNetworkProxy(rawPtr, stringMem, proxylen); StringMarshalHelper.NativeToBuilder(proxy, stringMem); Marshal.FreeHGlobal(stringMem); return result; } public RESULT setNetworkTimeout (int timeout) { return FMOD_System_SetNetworkTimeout(rawPtr, timeout); } public RESULT getNetworkTimeout(out int timeout) { return FMOD_System_GetNetworkTimeout(rawPtr, out timeout); } // Userdata set/get public RESULT setUserData (IntPtr userdata) { return FMOD_System_SetUserData(rawPtr, userdata); } public RESULT getUserData (out IntPtr userdata) { return FMOD_System_GetUserData(rawPtr, out userdata); } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_Release (IntPtr system); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetOutput (IntPtr system, OUTPUTTYPE output); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetOutput (IntPtr system, out OUTPUTTYPE output); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetNumDrivers (IntPtr system, out int numdrivers); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetDriverInfo (IntPtr system, int id, IntPtr name, int namelen, out GUID guid, out int systemrate, out SPEAKERMODE speakermode, out int speakermodechannels); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetDriver (IntPtr system, int driver); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetDriver (IntPtr system, out int driver); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetSoftwareChannels (IntPtr system, int numsoftwarechannels); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetSoftwareChannels (IntPtr system, out int numsoftwarechannels); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetSoftwareFormat (IntPtr system, int samplerate, SPEAKERMODE speakermode, int numrawspeakers); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetSoftwareFormat (IntPtr system, out int samplerate, out SPEAKERMODE speakermode, out int numrawspeakers); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetDSPBufferSize (IntPtr system, uint bufferlength, int numbuffers); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetDSPBufferSize (IntPtr system, out uint bufferlength, out int numbuffers); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetFileSystem (IntPtr system, FILE_OPENCALLBACK useropen, FILE_CLOSECALLBACK userclose, FILE_READCALLBACK userread, FILE_SEEKCALLBACK userseek, FILE_ASYNCREADCALLBACK userasyncread, FILE_ASYNCCANCELCALLBACK userasynccancel, int blockalign); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_AttachFileSystem (IntPtr system, FILE_OPENCALLBACK useropen, FILE_CLOSECALLBACK userclose, FILE_READCALLBACK userread, FILE_SEEKCALLBACK userseek); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetPluginPath (IntPtr system, byte[] path); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_LoadPlugin (IntPtr system, byte[] filename, out uint handle, uint priority); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_UnloadPlugin (IntPtr system, uint handle); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetNumPlugins (IntPtr system, PLUGINTYPE plugintype, out int numplugins); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetPluginHandle (IntPtr system, PLUGINTYPE plugintype, int index, out uint handle); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetPluginInfo (IntPtr system, uint handle, out PLUGINTYPE plugintype, IntPtr name, int namelen, out uint version); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_CreateDSPByPlugin (IntPtr system, uint handle, out IntPtr dsp); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetOutputByPlugin (IntPtr system, uint handle); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetOutputByPlugin (IntPtr system, out uint handle); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetDSPInfoByPlugin (IntPtr system, uint handle, out IntPtr description); [DllImport(VERSION.dll)] //private static extern RESULT FMOD_System_RegisterCodec (IntPtr system, out CODEC_DESCRIPTION description, out uint handle, uint priority); //[DllImport(VERSION.dll)] private static extern RESULT FMOD_System_RegisterDSP (IntPtr system, ref DSP_DESCRIPTION description, out uint handle); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_Init (IntPtr system, int maxchannels, INITFLAGS flags, IntPtr extradriverdata); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_Close (IntPtr system); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_Update (IntPtr system); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetAdvancedSettings (IntPtr system, ref ADVANCEDSETTINGS settings); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetAdvancedSettings (IntPtr system, ref ADVANCEDSETTINGS settings); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_Set3DRolloffCallback (IntPtr system, CB_3D_ROLLOFFCALLBACK callback); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_MixerSuspend (IntPtr system); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_MixerResume (IntPtr system); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetCallback (IntPtr system, SYSTEM_CALLBACK callback, SYSTEM_CALLBACK_TYPE callbackmask); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetSpeakerPosition (IntPtr system, SPEAKER speaker, float x, float y, bool active); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetSpeakerPosition (IntPtr system, SPEAKER speaker, out float x, out float y, out bool active); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_Set3DSettings (IntPtr system, float dopplerscale, float distancefactor, float rolloffscale); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_Get3DSettings (IntPtr system, out float dopplerscale, out float distancefactor, out float rolloffscale); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_Set3DNumListeners (IntPtr system, int numlisteners); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_Get3DNumListeners (IntPtr system, out int numlisteners); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_Set3DListenerAttributes(IntPtr system, int listener, ref VECTOR pos, ref VECTOR vel, ref VECTOR forward, ref VECTOR up); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_Get3DListenerAttributes(IntPtr system, int listener, out VECTOR pos, out VECTOR vel, out VECTOR forward, out VECTOR up); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetStreamBufferSize (IntPtr system, uint filebuffersize, TIMEUNIT filebuffersizetype); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetStreamBufferSize (IntPtr system, out uint filebuffersize, out TIMEUNIT filebuffersizetype); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetVersion (IntPtr system, out uint version); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetOutputHandle (IntPtr system, out IntPtr handle); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetChannelsPlaying (IntPtr system, out int channels); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetCPUUsage (IntPtr system, out float dsp, out float stream, out float geometry, out float update, out float total); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetSoundRAM (IntPtr system, out int currentalloced, out int maxalloced, out int total); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_CreateSound (IntPtr system, byte[] name_or_data, MODE mode, ref CREATESOUNDEXINFO exinfo, out IntPtr sound); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_CreateStream (IntPtr system, byte[] name_or_data, MODE mode, ref CREATESOUNDEXINFO exinfo, out IntPtr sound); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_CreateDSP (IntPtr system, ref DSP_DESCRIPTION description, out IntPtr dsp); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_CreateDSPByType (IntPtr system, DSP_TYPE type, out IntPtr dsp); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_CreateChannelGroup (IntPtr system, byte[] name, out IntPtr channelgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_CreateSoundGroup (IntPtr system, byte[] name, out IntPtr soundgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_CreateReverb3D (IntPtr system, out IntPtr reverb); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_PlaySound (IntPtr system, IntPtr sound, IntPtr channelGroup, bool paused, out IntPtr channel); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_PlayDSP (IntPtr system, IntPtr dsp, IntPtr channelGroup, bool paused, out IntPtr channel); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetChannel (IntPtr system, int channelid, out IntPtr channel); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetMasterChannelGroup (IntPtr system, out IntPtr channelgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetMasterSoundGroup (IntPtr system, out IntPtr soundgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_AttachChannelGroupToPort (IntPtr system, uint portType, ulong portIndex, IntPtr channelgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_DetachChannelGroupFromPort(IntPtr system, IntPtr channelgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetReverbProperties (IntPtr system, int instance, ref REVERB_PROPERTIES prop); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetReverbProperties (IntPtr system, int instance, out REVERB_PROPERTIES prop); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_LockDSP (IntPtr system); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_UnlockDSP (IntPtr system); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetRecordNumDrivers (IntPtr system, out int numdrivers); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetRecordDriverInfo (IntPtr system, int id, IntPtr name, int namelen, out GUID guid, out int systemrate, out SPEAKERMODE speakermode, out int speakermodechannels); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetRecordPosition (IntPtr system, int id, out uint position); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_RecordStart (IntPtr system, int id, IntPtr sound, bool loop); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_RecordStop (IntPtr system, int id); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_IsRecording (IntPtr system, int id, out bool recording); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_CreateGeometry (IntPtr system, int maxpolygons, int maxvertices, out IntPtr geometry); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetGeometrySettings (IntPtr system, float maxworldsize); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetGeometrySettings (IntPtr system, out float maxworldsize); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_LoadGeometry (IntPtr system, IntPtr data, int datasize, out IntPtr geometry); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetGeometryOcclusion (IntPtr system, ref VECTOR listener, ref VECTOR source, out float direct, out float reverb); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetNetworkProxy (IntPtr system, byte[] proxy); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetNetworkProxy (IntPtr system, IntPtr proxy, int proxylen); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetNetworkTimeout (IntPtr system, int timeout); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetNetworkTimeout (IntPtr system, out int timeout); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_SetUserData (IntPtr system, IntPtr userdata); [DllImport(VERSION.dll)] private static extern RESULT FMOD_System_GetUserData (IntPtr system, out IntPtr userdata); #endregion #region wrapperinternal public System(IntPtr raw) : base(raw) { } #endregion } /* 'Sound' API. */ public class Sound : HandleBase { public RESULT release () { RESULT result = FMOD_Sound_Release(rawPtr); if (result == RESULT.OK) { rawPtr = IntPtr.Zero; } return result; } public RESULT getSystemObject (out System system) { system = null; IntPtr systemraw; RESULT result = FMOD_Sound_GetSystemObject(rawPtr, out systemraw); system = new System(systemraw); return result; } // Standard sound manipulation functions. public RESULT @lock (uint offset, uint length, out IntPtr ptr1, out IntPtr ptr2, out uint len1, out uint len2) { return FMOD_Sound_Lock(rawPtr, offset, length, out ptr1, out ptr2, out len1, out len2); } public RESULT unlock (IntPtr ptr1, IntPtr ptr2, uint len1, uint len2) { return FMOD_Sound_Unlock(rawPtr, ptr1, ptr2, len1, len2); } public RESULT setDefaults (float frequency, int priority) { return FMOD_Sound_SetDefaults(rawPtr, frequency, priority); } public RESULT getDefaults (out float frequency, out int priority) { return FMOD_Sound_GetDefaults(rawPtr, out frequency, out priority); } public RESULT set3DMinMaxDistance (float min, float max) { return FMOD_Sound_Set3DMinMaxDistance(rawPtr, min, max); } public RESULT get3DMinMaxDistance (out float min, out float max) { return FMOD_Sound_Get3DMinMaxDistance(rawPtr, out min, out max); } public RESULT set3DConeSettings (float insideconeangle, float outsideconeangle, float outsidevolume) { return FMOD_Sound_Set3DConeSettings(rawPtr, insideconeangle, outsideconeangle, outsidevolume); } public RESULT get3DConeSettings (out float insideconeangle, out float outsideconeangle, out float outsidevolume) { return FMOD_Sound_Get3DConeSettings(rawPtr, out insideconeangle, out outsideconeangle, out outsidevolume); } public RESULT set3DCustomRolloff (ref VECTOR points, int numpoints) { return FMOD_Sound_Set3DCustomRolloff(rawPtr, ref points, numpoints); } public RESULT get3DCustomRolloff (out IntPtr points, out int numpoints) { return FMOD_Sound_Get3DCustomRolloff(rawPtr, out points, out numpoints); } public RESULT setSubSound (int index, Sound subsound) { IntPtr subsoundraw = subsound.getRaw(); return FMOD_Sound_SetSubSound(rawPtr, index, subsoundraw); } public RESULT getSubSound (int index, out Sound subsound) { subsound = null; IntPtr subsoundraw; RESULT result = FMOD_Sound_GetSubSound(rawPtr, index, out subsoundraw); subsound = new Sound(subsoundraw); return result; } public RESULT getSubSoundParent(out Sound parentsound) { parentsound = null; IntPtr subsoundraw; RESULT result = FMOD_Sound_GetSubSoundParent(rawPtr, out subsoundraw); parentsound = new Sound(subsoundraw); return result; } public RESULT getName (StringBuilder name, int namelen) { IntPtr stringMem = Marshal.AllocHGlobal(name.Capacity); RESULT result = FMOD_Sound_GetName(rawPtr, stringMem, namelen); StringMarshalHelper.NativeToBuilder(name, stringMem); Marshal.FreeHGlobal(stringMem); return result; } public RESULT getLength (out uint length, TIMEUNIT lengthtype) { return FMOD_Sound_GetLength(rawPtr, out length, lengthtype); } public RESULT getFormat (out SOUND_TYPE type, out SOUND_FORMAT format, out int channels, out int bits) { return FMOD_Sound_GetFormat(rawPtr, out type, out format, out channels, out bits); } public RESULT getNumSubSounds (out int numsubsounds) { return FMOD_Sound_GetNumSubSounds(rawPtr, out numsubsounds); } public RESULT getNumTags (out int numtags, out int numtagsupdated) { return FMOD_Sound_GetNumTags(rawPtr, out numtags, out numtagsupdated); } public RESULT getTag (string name, int index, out TAG tag) { return FMOD_Sound_GetTag(rawPtr, name, index, out tag); } public RESULT getOpenState (out OPENSTATE openstate, out uint percentbuffered, out bool starving, out bool diskbusy) { return FMOD_Sound_GetOpenState(rawPtr, out openstate, out percentbuffered, out starving, out diskbusy); } public RESULT readData (IntPtr buffer, uint lenbytes, out uint read) { return FMOD_Sound_ReadData(rawPtr, buffer, lenbytes, out read); } public RESULT seekData (uint pcm) { return FMOD_Sound_SeekData(rawPtr, pcm); } public RESULT setSoundGroup (SoundGroup soundgroup) { return FMOD_Sound_SetSoundGroup(rawPtr, soundgroup.getRaw()); } public RESULT getSoundGroup (out SoundGroup soundgroup) { soundgroup = null; IntPtr soundgroupraw; RESULT result = FMOD_Sound_GetSoundGroup(rawPtr, out soundgroupraw); soundgroup = new SoundGroup(soundgroupraw); return result; } // Synchronization point API. These points can come from markers embedded in wav files, and can also generate channel callbacks. public RESULT getNumSyncPoints (out int numsyncpoints) { return FMOD_Sound_GetNumSyncPoints(rawPtr, out numsyncpoints); } public RESULT getSyncPoint (int index, out IntPtr point) { return FMOD_Sound_GetSyncPoint(rawPtr, index, out point); } public RESULT getSyncPointInfo (IntPtr point, StringBuilder name, int namelen, out uint offset, TIMEUNIT offsettype) { IntPtr stringMem = Marshal.AllocHGlobal(name.Capacity); RESULT result = FMOD_Sound_GetSyncPointInfo(rawPtr, point, stringMem, namelen, out offset, offsettype); StringMarshalHelper.NativeToBuilder(name, stringMem); Marshal.FreeHGlobal(stringMem); return result; } public RESULT addSyncPoint (uint offset, TIMEUNIT offsettype, string name, out IntPtr point) { return FMOD_Sound_AddSyncPoint(rawPtr, offset, offsettype, name, out point); } public RESULT deleteSyncPoint (IntPtr point) { return FMOD_Sound_DeleteSyncPoint(rawPtr, point); } // Functions also in Channel class but here they are the 'default' to save having to change it in Channel all the time. public RESULT setMode (MODE mode) { return FMOD_Sound_SetMode(rawPtr, mode); } public RESULT getMode (out MODE mode) { return FMOD_Sound_GetMode(rawPtr, out mode); } public RESULT setLoopCount (int loopcount) { return FMOD_Sound_SetLoopCount(rawPtr, loopcount); } public RESULT getLoopCount (out int loopcount) { return FMOD_Sound_GetLoopCount(rawPtr, out loopcount); } public RESULT setLoopPoints (uint loopstart, TIMEUNIT loopstarttype, uint loopend, TIMEUNIT loopendtype) { return FMOD_Sound_SetLoopPoints(rawPtr, loopstart, loopstarttype, loopend, loopendtype); } public RESULT getLoopPoints (out uint loopstart, TIMEUNIT loopstarttype, out uint loopend, TIMEUNIT loopendtype) { return FMOD_Sound_GetLoopPoints(rawPtr, out loopstart, loopstarttype, out loopend, loopendtype); } // For MOD/S3M/XM/IT/MID sequenced formats only. public RESULT getMusicNumChannels (out int numchannels) { return FMOD_Sound_GetMusicNumChannels(rawPtr, out numchannels); } public RESULT setMusicChannelVolume (int channel, float volume) { return FMOD_Sound_SetMusicChannelVolume(rawPtr, channel, volume); } public RESULT getMusicChannelVolume (int channel, out float volume) { return FMOD_Sound_GetMusicChannelVolume(rawPtr, channel, out volume); } public RESULT setMusicSpeed(float speed) { return FMOD_Sound_SetMusicSpeed(rawPtr, speed); } public RESULT getMusicSpeed(out float speed) { return FMOD_Sound_GetMusicSpeed(rawPtr, out speed); } // Userdata set/get. public RESULT setUserData (IntPtr userdata) { return FMOD_Sound_SetUserData(rawPtr, userdata); } public RESULT getUserData (out IntPtr userdata) { return FMOD_Sound_GetUserData(rawPtr, out userdata); } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_Release (IntPtr sound); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetSystemObject (IntPtr sound, out IntPtr system); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_Lock (IntPtr sound, uint offset, uint length, out IntPtr ptr1, out IntPtr ptr2, out uint len1, out uint len2); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_Unlock (IntPtr sound, IntPtr ptr1, IntPtr ptr2, uint len1, uint len2); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_SetDefaults (IntPtr sound, float frequency, int priority); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetDefaults (IntPtr sound, out float frequency, out int priority); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_Set3DMinMaxDistance (IntPtr sound, float min, float max); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_Get3DMinMaxDistance (IntPtr sound, out float min, out float max); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_Set3DConeSettings (IntPtr sound, float insideconeangle, float outsideconeangle, float outsidevolume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_Get3DConeSettings (IntPtr sound, out float insideconeangle, out float outsideconeangle, out float outsidevolume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_Set3DCustomRolloff (IntPtr sound, ref VECTOR points, int numpoints); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_Get3DCustomRolloff (IntPtr sound, out IntPtr points, out int numpoints); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_SetSubSound (IntPtr sound, int index, IntPtr subsound); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetSubSound (IntPtr sound, int index, out IntPtr subsound); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetSubSoundParent (IntPtr sound, out IntPtr parentsound); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetName (IntPtr sound, IntPtr name, int namelen); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetLength (IntPtr sound, out uint length, TIMEUNIT lengthtype); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetFormat (IntPtr sound, out SOUND_TYPE type, out SOUND_FORMAT format, out int channels, out int bits); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetNumSubSounds (IntPtr sound, out int numsubsounds); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetNumTags (IntPtr sound, out int numtags, out int numtagsupdated); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetTag (IntPtr sound, string name, int index, out TAG tag); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetOpenState (IntPtr sound, out OPENSTATE openstate, out uint percentbuffered, out bool starving, out bool diskbusy); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_ReadData (IntPtr sound, IntPtr buffer, uint lenbytes, out uint read); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_SeekData (IntPtr sound, uint pcm); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_SetSoundGroup (IntPtr sound, IntPtr soundgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetSoundGroup (IntPtr sound, out IntPtr soundgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetNumSyncPoints (IntPtr sound, out int numsyncpoints); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetSyncPoint (IntPtr sound, int index, out IntPtr point); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetSyncPointInfo (IntPtr sound, IntPtr point, IntPtr name, int namelen, out uint offset, TIMEUNIT offsettype); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_AddSyncPoint (IntPtr sound, uint offset, TIMEUNIT offsettype, string name, out IntPtr point); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_DeleteSyncPoint (IntPtr sound, IntPtr point); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_SetMode (IntPtr sound, MODE mode); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetMode (IntPtr sound, out MODE mode); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_SetLoopCount (IntPtr sound, int loopcount); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetLoopCount (IntPtr sound, out int loopcount); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_SetLoopPoints (IntPtr sound, uint loopstart, TIMEUNIT loopstarttype, uint loopend, TIMEUNIT loopendtype); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetLoopPoints (IntPtr sound, out uint loopstart, TIMEUNIT loopstarttype, out uint loopend, TIMEUNIT loopendtype); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetMusicNumChannels (IntPtr sound, out int numchannels); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_SetMusicChannelVolume (IntPtr sound, int channel, float volume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetMusicChannelVolume (IntPtr sound, int channel, out float volume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_SetMusicSpeed (IntPtr sound, float speed); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetMusicSpeed (IntPtr sound, out float speed); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_SetUserData (IntPtr sound, IntPtr userdata); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Sound_GetUserData (IntPtr sound, out IntPtr userdata); #endregion #region wrapperinternal public Sound(IntPtr raw) : base(raw) { } #endregion } /* 'ChannelControl' API */ public class ChannelControl : HandleBase { public RESULT getSystemObject(out System system) { system = null; IntPtr systemraw; RESULT result = FMOD_ChannelGroup_GetSystemObject(rawPtr, out systemraw); system = new System(systemraw); return result; } // General control functionality for Channels and ChannelGroups. public RESULT stop() { return FMOD_ChannelGroup_Stop(rawPtr); } public RESULT setPaused(bool paused) { return FMOD_ChannelGroup_SetPaused(rawPtr, paused); } public RESULT getPaused(out bool paused) { return FMOD_ChannelGroup_GetPaused(rawPtr, out paused); } public RESULT setVolume(float volume) { return FMOD_ChannelGroup_SetVolume(rawPtr, volume); } public RESULT getVolume(out float volume) { return FMOD_ChannelGroup_GetVolume(rawPtr, out volume); } public RESULT setVolumeRamp(bool ramp) { return FMOD_ChannelGroup_SetVolumeRamp(rawPtr, ramp); } public RESULT getVolumeRamp(out bool ramp) { return FMOD_ChannelGroup_GetVolumeRamp(rawPtr, out ramp); } public RESULT getAudibility(out float audibility) { return FMOD_ChannelGroup_GetAudibility(rawPtr, out audibility); } public RESULT setPitch(float pitch) { return FMOD_ChannelGroup_SetPitch(rawPtr, pitch); } public RESULT getPitch(out float pitch) { return FMOD_ChannelGroup_GetPitch(rawPtr, out pitch); } public RESULT setMute(bool mute) { return FMOD_ChannelGroup_SetMute(rawPtr, mute); } public RESULT getMute(out bool mute) { return FMOD_ChannelGroup_GetMute(rawPtr, out mute); } public RESULT setReverbProperties(int instance, float wet) { return FMOD_ChannelGroup_SetReverbProperties(rawPtr, instance, wet); } public RESULT getReverbProperties(int instance, out float wet) { return FMOD_ChannelGroup_GetReverbProperties(rawPtr, instance, out wet); } public RESULT setLowPassGain(float gain) { return FMOD_ChannelGroup_SetLowPassGain(rawPtr, gain); } public RESULT getLowPassGain(out float gain) { return FMOD_ChannelGroup_GetLowPassGain(rawPtr, out gain); } public RESULT setMode(MODE mode) { return FMOD_ChannelGroup_SetMode(rawPtr, mode); } public RESULT getMode(out MODE mode) { return FMOD_ChannelGroup_GetMode(rawPtr, out mode); } public RESULT setCallback(CHANNEL_CALLBACK callback) { return FMOD_ChannelGroup_SetCallback(rawPtr, callback); } public RESULT isPlaying(out bool isplaying) { return FMOD_ChannelGroup_IsPlaying(rawPtr, out isplaying); } // Panning and level adjustment. public RESULT setPan(float pan) { return FMOD_ChannelGroup_SetPan(rawPtr, pan); } public RESULT setMixLevelsOutput(float frontleft, float frontright, float center, float lfe, float surroundleft, float surroundright, float backleft, float backright) { return FMOD_ChannelGroup_SetMixLevelsOutput(rawPtr, frontleft, frontright, center, lfe, surroundleft, surroundright, backleft, backright); } public RESULT setMixLevelsInput(float[] levels, int numlevels) { return FMOD_ChannelGroup_SetMixLevelsInput(rawPtr, levels, numlevels); } public RESULT setMixMatrix(float[] matrix, int outchannels, int inchannels, int inchannel_hop) { return FMOD_ChannelGroup_SetMixMatrix(rawPtr, matrix, outchannels, inchannels, inchannel_hop); } public RESULT getMixMatrix(float[] matrix, out int outchannels, out int inchannels, int inchannel_hop) { return FMOD_ChannelGroup_GetMixMatrix(rawPtr, matrix, out outchannels, out inchannels, inchannel_hop); } // Clock based functionality. public RESULT getDSPClock(out ulong dspclock, out ulong parentclock) { return FMOD_ChannelGroup_GetDSPClock(rawPtr, out dspclock, out parentclock); } public RESULT setDelay(ulong dspclock_start, ulong dspclock_end, bool stopchannels) { return FMOD_ChannelGroup_SetDelay(rawPtr, dspclock_start, dspclock_end, stopchannels); } public RESULT getDelay(out ulong dspclock_start, out ulong dspclock_end, out bool stopchannels) { return FMOD_ChannelGroup_GetDelay(rawPtr, out dspclock_start, out dspclock_end, out stopchannels); } public RESULT addFadePoint(ulong dspclock, float volume) { return FMOD_ChannelGroup_AddFadePoint(rawPtr, dspclock, volume); } public RESULT removeFadePoints(ulong dspclock_start, ulong dspclock_end) { return FMOD_ChannelGroup_RemoveFadePoints(rawPtr, dspclock_start, dspclock_end); } public RESULT getFadePoints(ref uint numpoints, ulong[] point_dspclock, float[] point_volume) { return FMOD_ChannelGroup_GetFadePoints(rawPtr, ref numpoints, point_dspclock, point_volume); } // DSP effects. public RESULT getDSP(int index, out DSP dsp) { dsp = null; IntPtr dspraw; RESULT result = FMOD_ChannelGroup_GetDSP(rawPtr, index, out dspraw); dsp = new DSP(dspraw); return result; } public RESULT addDSP(int index, DSP dsp) { return FMOD_ChannelGroup_AddDSP(rawPtr, index, dsp.getRaw()); } public RESULT removeDSP(DSP dsp) { return FMOD_ChannelGroup_RemoveDSP(rawPtr, dsp.getRaw()); } public RESULT getNumDSPs(out int numdsps) { return FMOD_ChannelGroup_GetNumDSPs(rawPtr, out numdsps); } public RESULT setDSPIndex(DSP dsp, int index) { return FMOD_ChannelGroup_SetDSPIndex(rawPtr, dsp.getRaw(), index); } public RESULT getDSPIndex(DSP dsp, out int index) { return FMOD_ChannelGroup_GetDSPIndex(rawPtr, dsp.getRaw(), out index); } public RESULT overridePanDSP(DSP pan) { return FMOD_ChannelGroup_OverridePanDSP(rawPtr, pan.getRaw()); } // 3D functionality. public RESULT set3DAttributes(ref VECTOR pos, ref VECTOR vel, ref VECTOR alt_pan_pos) { return FMOD_ChannelGroup_Set3DAttributes(rawPtr, ref pos, ref vel, ref alt_pan_pos); } public RESULT get3DAttributes(out VECTOR pos, out VECTOR vel, out VECTOR alt_pan_pos) { return FMOD_ChannelGroup_Get3DAttributes(rawPtr, out pos, out vel, out alt_pan_pos); } public RESULT set3DMinMaxDistance(float mindistance, float maxdistance) { return FMOD_ChannelGroup_Set3DMinMaxDistance(rawPtr, mindistance, maxdistance); } public RESULT get3DMinMaxDistance(out float mindistance, out float maxdistance) { return FMOD_ChannelGroup_Get3DMinMaxDistance(rawPtr, out mindistance, out maxdistance); } public RESULT set3DConeSettings(float insideconeangle, float outsideconeangle, float outsidevolume) { return FMOD_ChannelGroup_Set3DConeSettings(rawPtr, insideconeangle, outsideconeangle, outsidevolume); } public RESULT get3DConeSettings(out float insideconeangle, out float outsideconeangle, out float outsidevolume) { return FMOD_ChannelGroup_Get3DConeSettings(rawPtr, out insideconeangle, out outsideconeangle, out outsidevolume); } public RESULT set3DConeOrientation(ref VECTOR orientation) { return FMOD_ChannelGroup_Set3DConeOrientation(rawPtr, ref orientation); } public RESULT get3DConeOrientation(out VECTOR orientation) { return FMOD_ChannelGroup_Get3DConeOrientation(rawPtr, out orientation); } public RESULT set3DCustomRolloff(ref VECTOR points, int numpoints) { return FMOD_ChannelGroup_Set3DCustomRolloff(rawPtr, ref points, numpoints); } public RESULT get3DCustomRolloff(out IntPtr points, out int numpoints) { return FMOD_ChannelGroup_Get3DCustomRolloff(rawPtr, out points, out numpoints); } public RESULT set3DOcclusion(float directocclusion, float reverbocclusion) { return FMOD_ChannelGroup_Set3DOcclusion(rawPtr, directocclusion, reverbocclusion); } public RESULT get3DOcclusion(out float directocclusion, out float reverbocclusion) { return FMOD_ChannelGroup_Get3DOcclusion(rawPtr, out directocclusion, out reverbocclusion); } public RESULT set3DSpread(float angle) { return FMOD_ChannelGroup_Set3DSpread(rawPtr, angle); } public RESULT get3DSpread(out float angle) { return FMOD_ChannelGroup_Get3DSpread(rawPtr, out angle); } public RESULT set3DLevel(float level) { return FMOD_ChannelGroup_Set3DLevel(rawPtr, level); } public RESULT get3DLevel(out float level) { return FMOD_ChannelGroup_Get3DLevel(rawPtr, out level); } public RESULT set3DDopplerLevel(float level) { return FMOD_ChannelGroup_Set3DDopplerLevel(rawPtr, level); } public RESULT get3DDopplerLevel(out float level) { return FMOD_ChannelGroup_Get3DDopplerLevel(rawPtr, out level); } public RESULT set3DDistanceFilter(bool custom, float customLevel, float centerFreq) { return FMOD_ChannelGroup_Set3DDistanceFilter(rawPtr, custom, customLevel, centerFreq); } public RESULT get3DDistanceFilter(out bool custom, out float customLevel, out float centerFreq) { return FMOD_ChannelGroup_Get3DDistanceFilter(rawPtr, out custom, out customLevel, out centerFreq); } // Userdata set/get. public RESULT setUserData(IntPtr userdata) { return FMOD_ChannelGroup_SetUserData(rawPtr, userdata); } public RESULT getUserData(out IntPtr userdata) { return FMOD_ChannelGroup_GetUserData(rawPtr, out userdata); } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Stop(IntPtr channelgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetPaused(IntPtr channelgroup, bool paused); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetPaused(IntPtr channelgroup, out bool paused); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetVolume(IntPtr channelgroup, out float volume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetVolumeRamp(IntPtr channelgroup, bool ramp); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetVolumeRamp(IntPtr channelgroup, out bool ramp); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetAudibility(IntPtr channelgroup, out float audibility); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetPitch(IntPtr channelgroup, float pitch); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetPitch(IntPtr channelgroup, out float pitch); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetMute(IntPtr channelgroup, bool mute); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetMute(IntPtr channelgroup, out bool mute); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetReverbProperties(IntPtr channelgroup, int instance, float wet); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetReverbProperties(IntPtr channelgroup, int instance, out float wet); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetLowPassGain(IntPtr channelgroup, float gain); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetLowPassGain(IntPtr channelgroup, out float gain); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetMode(IntPtr channelgroup, MODE mode); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetMode(IntPtr channelgroup, out MODE mode); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetCallback(IntPtr channelgroup, CHANNEL_CALLBACK callback); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_IsPlaying(IntPtr channelgroup, out bool isplaying); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetPan(IntPtr channelgroup, float pan); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetMixLevelsOutput(IntPtr channelgroup, float frontleft, float frontright, float center, float lfe, float surroundleft, float surroundright, float backleft, float backright); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetMixLevelsInput(IntPtr channelgroup, float[] levels, int numlevels); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetMixMatrix(IntPtr channelgroup, float[] matrix, int outchannels, int inchannels, int inchannel_hop); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetMixMatrix(IntPtr channelgroup, float[] matrix, out int outchannels, out int inchannels, int inchannel_hop); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetDSPClock(IntPtr channelgroup, out ulong dspclock, out ulong parentclock); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetDelay(IntPtr channelgroup, ulong dspclock_start, ulong dspclock_end, bool stopchannels); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetDelay(IntPtr channelgroup, out ulong dspclock_start, out ulong dspclock_end, out bool stopchannels); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_AddFadePoint(IntPtr channelgroup, ulong dspclock, float volume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_RemoveFadePoints(IntPtr channelgroup, ulong dspclock_start, ulong dspclock_end); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetFadePoints(IntPtr channelgroup, ref uint numpoints, ulong[] point_dspclock, float[] point_volume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Set3DAttributes(IntPtr channelgroup, ref VECTOR pos, ref VECTOR vel, ref VECTOR alt_pan_pos); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Get3DAttributes(IntPtr channelgroup, out VECTOR pos, out VECTOR vel, out VECTOR alt_pan_pos); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Set3DMinMaxDistance(IntPtr channelgroup, float mindistance, float maxdistance); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Get3DMinMaxDistance(IntPtr channelgroup, out float mindistance, out float maxdistance); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Set3DConeSettings(IntPtr channelgroup, float insideconeangle, float outsideconeangle, float outsidevolume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Get3DConeSettings(IntPtr channelgroup, out float insideconeangle, out float outsideconeangle, out float outsidevolume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Set3DConeOrientation(IntPtr channelgroup, ref VECTOR orientation); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Get3DConeOrientation(IntPtr channelgroup, out VECTOR orientation); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Set3DCustomRolloff(IntPtr channelgroup, ref VECTOR points, int numpoints); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Get3DCustomRolloff(IntPtr channelgroup, out IntPtr points, out int numpoints); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Set3DOcclusion(IntPtr channelgroup, float directocclusion, float reverbocclusion); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Get3DOcclusion(IntPtr channelgroup, out float directocclusion, out float reverbocclusion); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Set3DSpread(IntPtr channelgroup, float angle); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Get3DSpread(IntPtr channelgroup, out float angle); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Set3DLevel(IntPtr channelgroup, float level); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Get3DLevel(IntPtr channelgroup, out float level); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Set3DDopplerLevel(IntPtr channelgroup, float level); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Get3DDopplerLevel(IntPtr channelgroup, out float level); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Set3DDistanceFilter(IntPtr channelgroup, bool custom, float customLevel, float centerFreq); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Get3DDistanceFilter(IntPtr channelgroup, out bool custom, out float customLevel, out float centerFreq); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetSystemObject(IntPtr channelgroup, out IntPtr system); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetVolume(IntPtr channelgroup, float volume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetDSP(IntPtr channelgroup, int index, out IntPtr dsp); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_AddDSP(IntPtr channelgroup, int index, IntPtr dsp); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_RemoveDSP(IntPtr channelgroup, IntPtr dsp); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetNumDSPs(IntPtr channelgroup, out int numdsps); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetDSPIndex(IntPtr channelgroup, IntPtr dsp, int index); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetDSPIndex(IntPtr channelgroup, IntPtr dsp, out int index); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_OverridePanDSP(IntPtr channelgroup, IntPtr pan); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_SetUserData(IntPtr channelgroup, IntPtr userdata); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetUserData(IntPtr channelgroup, out IntPtr userdata); #endregion #region wrapperinternal protected ChannelControl(IntPtr raw) : base(raw) { } #endregion } /* 'Channel' API */ public class Channel : ChannelControl { // Channel specific control functionality. public RESULT setFrequency (float frequency) { return FMOD_Channel_SetFrequency(getRaw(), frequency); } public RESULT getFrequency (out float frequency) { return FMOD_Channel_GetFrequency(getRaw(), out frequency); } public RESULT setPriority (int priority) { return FMOD_Channel_SetPriority(getRaw(), priority); } public RESULT getPriority (out int priority) { return FMOD_Channel_GetPriority(getRaw(), out priority); } public RESULT setPosition (uint position, TIMEUNIT postype) { return FMOD_Channel_SetPosition(getRaw(), position, postype); } public RESULT getPosition (out uint position, TIMEUNIT postype) { return FMOD_Channel_GetPosition(getRaw(), out position, postype); } public RESULT setChannelGroup (ChannelGroup channelgroup) { return FMOD_Channel_SetChannelGroup(getRaw(), channelgroup.getRaw()); } public RESULT getChannelGroup (out ChannelGroup channelgroup) { channelgroup = null; IntPtr channelgroupraw; RESULT result = FMOD_Channel_GetChannelGroup(getRaw(), out channelgroupraw); channelgroup = new ChannelGroup(channelgroupraw); return result; } public RESULT setLoopCount(int loopcount) { return FMOD_Channel_SetLoopCount(getRaw(), loopcount); } public RESULT getLoopCount(out int loopcount) { return FMOD_Channel_GetLoopCount(getRaw(), out loopcount); } public RESULT setLoopPoints(uint loopstart, TIMEUNIT loopstarttype, uint loopend, TIMEUNIT loopendtype) { return FMOD_Channel_SetLoopPoints(getRaw(), loopstart, loopstarttype, loopend, loopendtype); } public RESULT getLoopPoints(out uint loopstart, TIMEUNIT loopstarttype, out uint loopend, TIMEUNIT loopendtype) { return FMOD_Channel_GetLoopPoints(getRaw(), out loopstart, loopstarttype, out loopend, loopendtype); } // Information only functions. public RESULT isVirtual (out bool isvirtual) { return FMOD_Channel_IsVirtual(getRaw(), out isvirtual); } public RESULT getCurrentSound (out Sound sound) { sound = null; IntPtr soundraw; RESULT result = FMOD_Channel_GetCurrentSound(getRaw(), out soundraw); sound = new Sound(soundraw); return result; } public RESULT getIndex (out int index) { return FMOD_Channel_GetIndex(getRaw(), out index); } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_SetFrequency (IntPtr channel, float frequency); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_GetFrequency (IntPtr channel, out float frequency); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_SetPriority (IntPtr channel, int priority); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_GetPriority (IntPtr channel, out int priority); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_SetChannelGroup (IntPtr channel, IntPtr channelgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_GetChannelGroup (IntPtr channel, out IntPtr channelgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_IsVirtual (IntPtr channel, out bool isvirtual); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_GetCurrentSound (IntPtr channel, out IntPtr sound); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_GetIndex (IntPtr channel, out int index); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_SetPosition (IntPtr channel, uint position, TIMEUNIT postype); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_GetPosition (IntPtr channel, out uint position, TIMEUNIT postype); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_SetMode (IntPtr channel, MODE mode); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_GetMode (IntPtr channel, out MODE mode); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_SetLoopCount (IntPtr channel, int loopcount); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_GetLoopCount (IntPtr channel, out int loopcount); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_SetLoopPoints (IntPtr channel, uint loopstart, TIMEUNIT loopstarttype, uint loopend, TIMEUNIT loopendtype); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_GetLoopPoints (IntPtr channel, out uint loopstart, TIMEUNIT loopstarttype, out uint loopend, TIMEUNIT loopendtype); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_SetUserData (IntPtr channel, IntPtr userdata); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Channel_GetUserData (IntPtr channel, out IntPtr userdata); #endregion #region wrapperinternal public Channel(IntPtr raw) : base(raw) { } #endregion } /* 'ChannelGroup' API */ public class ChannelGroup : ChannelControl { public RESULT release () { RESULT result = FMOD_ChannelGroup_Release(getRaw()); if (result == RESULT.OK) { rawPtr = IntPtr.Zero; } return result; } // Nested channel groups. public RESULT addGroup (ChannelGroup group) { return FMOD_ChannelGroup_AddGroup(getRaw(), group.getRaw()); } public RESULT getNumGroups (out int numgroups) { return FMOD_ChannelGroup_GetNumGroups(getRaw(), out numgroups); } public RESULT getGroup (int index, out ChannelGroup group) { group = null; IntPtr groupraw; RESULT result = FMOD_ChannelGroup_GetGroup(getRaw(), index, out groupraw); group = new ChannelGroup(groupraw); return result; } public RESULT getParentGroup (out ChannelGroup group) { group = null; IntPtr groupraw; RESULT result = FMOD_ChannelGroup_GetParentGroup(getRaw(), out groupraw); group = new ChannelGroup(groupraw); return result; } // Information only functions. public RESULT getName (StringBuilder name, int namelen) { IntPtr stringMem = Marshal.AllocHGlobal(name.Capacity); RESULT result = FMOD_ChannelGroup_GetName(getRaw(), stringMem, namelen); StringMarshalHelper.NativeToBuilder(name, stringMem); Marshal.FreeHGlobal(stringMem); return result; } public RESULT getNumChannels (out int numchannels) { return FMOD_ChannelGroup_GetNumChannels(getRaw(), out numchannels); } public RESULT getChannel (int index, out Channel channel) { channel = null; IntPtr channelraw; RESULT result = FMOD_ChannelGroup_GetChannel(getRaw(), index, out channelraw); channel = new Channel(channelraw); return result; } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_Release (IntPtr channelgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_AddGroup (IntPtr channelgroup, IntPtr group); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetNumGroups (IntPtr channelgroup, out int numgroups); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetGroup (IntPtr channelgroup, int index, out IntPtr group); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetParentGroup (IntPtr channelgroup, out IntPtr group); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetName (IntPtr channelgroup, IntPtr name, int namelen); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetNumChannels (IntPtr channelgroup, out int numchannels); [DllImport(VERSION.dll)] private static extern RESULT FMOD_ChannelGroup_GetChannel (IntPtr channelgroup, int index, out IntPtr channel); #endregion #region wrapperinternal public ChannelGroup(IntPtr raw) : base(raw) { } #endregion } /* 'SoundGroup' API */ public class SoundGroup : HandleBase { public RESULT release () { RESULT result = FMOD_SoundGroup_Release(getRaw()); if (result == RESULT.OK) { rawPtr = IntPtr.Zero; } return result; } public RESULT getSystemObject (out System system) { system = null; IntPtr systemraw; RESULT result = FMOD_SoundGroup_GetSystemObject(rawPtr, out systemraw); system = new System(systemraw); return result; } // SoundGroup control functions. public RESULT setMaxAudible (int maxaudible) { return FMOD_SoundGroup_SetMaxAudible(rawPtr, maxaudible); } public RESULT getMaxAudible (out int maxaudible) { return FMOD_SoundGroup_GetMaxAudible(rawPtr, out maxaudible); } public RESULT setMaxAudibleBehavior (SOUNDGROUP_BEHAVIOR behavior) { return FMOD_SoundGroup_SetMaxAudibleBehavior(rawPtr, behavior); } public RESULT getMaxAudibleBehavior (out SOUNDGROUP_BEHAVIOR behavior) { return FMOD_SoundGroup_GetMaxAudibleBehavior(rawPtr, out behavior); } public RESULT setMuteFadeSpeed (float speed) { return FMOD_SoundGroup_SetMuteFadeSpeed(rawPtr, speed); } public RESULT getMuteFadeSpeed (out float speed) { return FMOD_SoundGroup_GetMuteFadeSpeed(rawPtr, out speed); } public RESULT setVolume (float volume) { return FMOD_SoundGroup_SetVolume(rawPtr, volume); } public RESULT getVolume (out float volume) { return FMOD_SoundGroup_GetVolume(rawPtr, out volume); } public RESULT stop () { return FMOD_SoundGroup_Stop(rawPtr); } // Information only functions. public RESULT getName (StringBuilder name, int namelen) { IntPtr stringMem = Marshal.AllocHGlobal(name.Capacity); RESULT result = FMOD_SoundGroup_GetName(rawPtr, stringMem, namelen); StringMarshalHelper.NativeToBuilder(name, stringMem); Marshal.FreeHGlobal(stringMem); return result; } public RESULT getNumSounds (out int numsounds) { return FMOD_SoundGroup_GetNumSounds(rawPtr, out numsounds); } public RESULT getSound (int index, out Sound sound) { sound = null; IntPtr soundraw; RESULT result = FMOD_SoundGroup_GetSound(rawPtr, index, out soundraw); sound = new Sound(soundraw); return result; } public RESULT getNumPlaying (out int numplaying) { return FMOD_SoundGroup_GetNumPlaying(rawPtr, out numplaying); } // Userdata set/get. public RESULT setUserData (IntPtr userdata) { return FMOD_SoundGroup_SetUserData(rawPtr, userdata); } public RESULT getUserData (out IntPtr userdata) { return FMOD_SoundGroup_GetUserData(rawPtr, out userdata); } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_Release (IntPtr soundgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_GetSystemObject (IntPtr soundgroup, out IntPtr system); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_SetMaxAudible (IntPtr soundgroup, int maxaudible); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_GetMaxAudible (IntPtr soundgroup, out int maxaudible); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_SetMaxAudibleBehavior(IntPtr soundgroup, SOUNDGROUP_BEHAVIOR behavior); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_GetMaxAudibleBehavior(IntPtr soundgroup, out SOUNDGROUP_BEHAVIOR behavior); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_SetMuteFadeSpeed (IntPtr soundgroup, float speed); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_GetMuteFadeSpeed (IntPtr soundgroup, out float speed); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_SetVolume (IntPtr soundgroup, float volume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_GetVolume (IntPtr soundgroup, out float volume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_Stop (IntPtr soundgroup); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_GetName (IntPtr soundgroup, IntPtr name, int namelen); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_GetNumSounds (IntPtr soundgroup, out int numsounds); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_GetSound (IntPtr soundgroup, int index, out IntPtr sound); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_GetNumPlaying (IntPtr soundgroup, out int numplaying); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_SetUserData (IntPtr soundgroup, IntPtr userdata); [DllImport(VERSION.dll)] private static extern RESULT FMOD_SoundGroup_GetUserData (IntPtr soundgroup, out IntPtr userdata); #endregion #region wrapperinternal public SoundGroup(IntPtr raw) : base(raw) { } #endregion } /* 'DSP' API */ public class DSP : HandleBase { public RESULT release () { RESULT result = FMOD_DSP_Release(getRaw()); if (result == RESULT.OK) { rawPtr = IntPtr.Zero; } return result; } public RESULT getSystemObject (out System system) { system = null; IntPtr systemraw; RESULT result = FMOD_DSP_GetSystemObject(rawPtr, out systemraw); system = new System(systemraw); return result; } // Connection / disconnection / input and output enumeration. public RESULT addInput(DSP target, out DSPConnection connection) { connection = null; IntPtr dspconnectionraw; RESULT result = FMOD_DSP_AddInput(rawPtr, target.getRaw(), out dspconnectionraw); connection = new DSPConnection(dspconnectionraw); return result; } public RESULT disconnectFrom (DSP target) { return FMOD_DSP_DisconnectFrom(rawPtr, target.getRaw()); } public RESULT disconnectAll (bool inputs, bool outputs) { return FMOD_DSP_DisconnectAll(rawPtr, inputs, outputs); } public RESULT getNumInputs (out int numinputs) { return FMOD_DSP_GetNumInputs(rawPtr, out numinputs); } public RESULT getNumOutputs (out int numoutputs) { return FMOD_DSP_GetNumOutputs(rawPtr, out numoutputs); } public RESULT getInput (int index, out DSP input, out DSPConnection inputconnection) { input = null; inputconnection = null; IntPtr dspinputraw; IntPtr dspconnectionraw; RESULT result = FMOD_DSP_GetInput(rawPtr, index, out dspinputraw, out dspconnectionraw); input = new DSP(dspinputraw); inputconnection = new DSPConnection(dspconnectionraw); return result; } public RESULT getOutput (int index, out DSP output, out DSPConnection outputconnection) { output = null; outputconnection = null; IntPtr dspoutputraw; IntPtr dspconnectionraw; RESULT result = FMOD_DSP_GetOutput(rawPtr, index, out dspoutputraw, out dspconnectionraw); output = new DSP(dspoutputraw); outputconnection = new DSPConnection(dspconnectionraw); return result; } // DSP unit control. public RESULT setActive (bool active) { return FMOD_DSP_SetActive(rawPtr, active); } public RESULT getActive (out bool active) { return FMOD_DSP_GetActive(rawPtr, out active); } public RESULT setBypass(bool bypass) { return FMOD_DSP_SetBypass(rawPtr, bypass); } public RESULT getBypass(out bool bypass) { return FMOD_DSP_GetBypass(rawPtr, out bypass); } public RESULT setWetDryMix(float wet, float dry) { return FMOD_DSP_SetWetDryMix(rawPtr, wet, dry); } public RESULT getWetDryMix(out float wet, out float dry) { return FMOD_DSP_GetWetDryMix(rawPtr, out wet, out dry); } public RESULT setChannelFormat(CHANNELMASK channelmask, int numchannels, SPEAKERMODE source_speakermode) { return FMOD_DSP_SetChannelFormat(rawPtr, channelmask, numchannels, source_speakermode); } public RESULT getChannelFormat(out CHANNELMASK channelmask, out int numchannels, out SPEAKERMODE source_speakermode) { return FMOD_DSP_GetChannelFormat(rawPtr, out channelmask, out numchannels, out source_speakermode); } public RESULT getOutputChannelFormat(CHANNELMASK inmask, int inchannels, SPEAKERMODE inspeakermode, out CHANNELMASK outmask, out int outchannels, out SPEAKERMODE outspeakermode) { return FMOD_DSP_GetOutputChannelFormat(rawPtr, inmask, inchannels, inspeakermode, out outmask, out outchannels, out outspeakermode); } public RESULT reset () { return FMOD_DSP_Reset(rawPtr); } // DSP parameter control. public RESULT setParameterFloat(int index, float value) { return FMOD_DSP_SetParameterFloat(rawPtr, index, value); } public RESULT setParameterInt(int index, int value) { return FMOD_DSP_SetParameterInt(rawPtr, index, value); } public RESULT setParameterBool(int index, bool value) { return FMOD_DSP_SetParameterBool(rawPtr, index, value); } public RESULT setParameterData(int index, byte[] data) { return FMOD_DSP_SetParameterData(rawPtr, index, Marshal.UnsafeAddrOfPinnedArrayElement(data, 0), (uint)data.Length); } public RESULT getParameterFloat(int index, out float value) { IntPtr valuestr = IntPtr.Zero; return FMOD_DSP_GetParameterFloat(rawPtr, index, out value, valuestr, 0); } public RESULT getParameterInt(int index, out int value) { IntPtr valuestr = IntPtr.Zero; return FMOD_DSP_GetParameterInt(rawPtr, index, out value, valuestr, 0); } public RESULT getParameterBool(int index, out bool value) { return FMOD_DSP_GetParameterBool(rawPtr, index, out value, IntPtr.Zero, 0); } public RESULT getParameterData(int index, out IntPtr data, out uint length) { return FMOD_DSP_GetParameterData(rawPtr, index, out data, out length, IntPtr.Zero, 0); } public RESULT getNumParameters (out int numparams) { return FMOD_DSP_GetNumParameters(rawPtr, out numparams); } public RESULT getParameterInfo (int index, out DSP_PARAMETER_DESC desc) { IntPtr descPtr; RESULT result = FMOD_DSP_GetParameterInfo(rawPtr, index, out descPtr); if (result == RESULT.OK) { desc = (DSP_PARAMETER_DESC)Marshal.PtrToStructure(descPtr, typeof(DSP_PARAMETER_DESC)); } else { desc = new DSP_PARAMETER_DESC(); } return result; } public RESULT getDataParameterIndex(int datatype, out int index) { return FMOD_DSP_GetDataParameterIndex (rawPtr, datatype, out index); } public RESULT showConfigDialog (IntPtr hwnd, bool show) { return FMOD_DSP_ShowConfigDialog (rawPtr, hwnd, show); } // DSP attributes. public RESULT getInfo (StringBuilder name, out uint version, out int channels, out int configwidth, out int configheight) { IntPtr nameMem = Marshal.AllocHGlobal(32); RESULT result = FMOD_DSP_GetInfo(rawPtr, nameMem, out version, out channels, out configwidth, out configheight); StringMarshalHelper.NativeToBuilder(name, nameMem); Marshal.FreeHGlobal(nameMem); return result; } public RESULT getType (out DSP_TYPE type) { return FMOD_DSP_GetType(rawPtr, out type); } public RESULT getIdle (out bool idle) { return FMOD_DSP_GetIdle(rawPtr, out idle); } // Userdata set/get. public RESULT setUserData (IntPtr userdata) { return FMOD_DSP_SetUserData(rawPtr, userdata); } public RESULT getUserData (out IntPtr userdata) { return FMOD_DSP_GetUserData(rawPtr, out userdata); } // Metering. public RESULT setMeteringEnabled(bool inputEnabled, bool outputEnabled) { return FMOD_DSP_SetMeteringEnabled(rawPtr, inputEnabled, outputEnabled); } public RESULT getMeteringEnabled(out bool inputEnabled, out bool outputEnabled) { return FMOD_DSP_GetMeteringEnabled(rawPtr, out inputEnabled, out outputEnabled); } public RESULT getMeteringInfo(out DSP_METERING_INFO info) { return FMOD_DSP_GetMeteringInfo(rawPtr, out info); } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_Release (IntPtr dsp); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetSystemObject (IntPtr dsp, out IntPtr system); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_AddInput (IntPtr dsp, IntPtr target, out IntPtr connection); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_DisconnectFrom (IntPtr dsp, IntPtr target); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_DisconnectAll (IntPtr dsp, bool inputs, bool outputs); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetNumInputs (IntPtr dsp, out int numinputs); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetNumOutputs (IntPtr dsp, out int numoutputs); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetInput (IntPtr dsp, int index, out IntPtr input, out IntPtr inputconnection); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetOutput (IntPtr dsp, int index, out IntPtr output, out IntPtr outputconnection); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_SetActive (IntPtr dsp, bool active); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetActive (IntPtr dsp, out bool active); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_SetBypass (IntPtr dsp, bool bypass); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetBypass (IntPtr dsp, out bool bypass); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_SetWetDryMix (IntPtr dsp, float wet, float dry); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetWetDryMix (IntPtr dsp, out float wet, out float dry); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_SetChannelFormat (IntPtr dsp, CHANNELMASK channelmask, int numchannels, SPEAKERMODE source_speakermode); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetChannelFormat (IntPtr dsp, out CHANNELMASK channelmask, out int numchannels, out SPEAKERMODE source_speakermode); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetOutputChannelFormat (IntPtr dsp, CHANNELMASK inmask, int inchannels, SPEAKERMODE inspeakermode, out CHANNELMASK outmask, out int outchannels, out SPEAKERMODE outspeakermode); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_Reset (IntPtr dsp); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_SetParameterFloat (IntPtr dsp, int index, float value); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_SetParameterInt (IntPtr dsp, int index, int value); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_SetParameterBool (IntPtr dsp, int index, bool value); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_SetParameterData (IntPtr dsp, int index, IntPtr data, uint length); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetParameterFloat (IntPtr dsp, int index, out float value, IntPtr valuestr, int valuestrlen); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetParameterInt (IntPtr dsp, int index, out int value, IntPtr valuestr, int valuestrlen); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetParameterBool (IntPtr dsp, int index, out bool value, IntPtr valuestr, int valuestrlen); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetParameterData (IntPtr dsp, int index, out IntPtr data, out uint length, IntPtr valuestr, int valuestrlen); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetNumParameters (IntPtr dsp, out int numparams); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetParameterInfo (IntPtr dsp, int index, out IntPtr desc); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetDataParameterIndex (IntPtr dsp, int datatype, out int index); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_ShowConfigDialog (IntPtr dsp, IntPtr hwnd, bool show); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetInfo (IntPtr dsp, IntPtr name, out uint version, out int channels, out int configwidth, out int configheight); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetType (IntPtr dsp, out DSP_TYPE type); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetIdle (IntPtr dsp, out bool idle); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_SetUserData (IntPtr dsp, IntPtr userdata); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSP_GetUserData (IntPtr dsp, out IntPtr userdata); [DllImport(VERSION.dll)] public static extern RESULT FMOD_DSP_SetMeteringEnabled (IntPtr dsp, bool inputEnabled, bool outputEnabled); [DllImport(VERSION.dll)] public static extern RESULT FMOD_DSP_GetMeteringEnabled (IntPtr dsp, out bool inputEnabled, out bool outputEnabled); [DllImport(VERSION.dll)] public static extern RESULT FMOD_DSP_GetMeteringInfo (IntPtr dsp, out DSP_METERING_INFO dspInfo); #endregion #region wrapperinternal public DSP(IntPtr raw) : base(raw) { } #endregion } /* 'DSPConnection' API */ public class DSPConnection : HandleBase { public RESULT getInput (out DSP input) { input = null; IntPtr dspraw; RESULT result = FMOD_DSPConnection_GetInput(rawPtr, out dspraw); input = new DSP(dspraw); return result; } public RESULT getOutput (out DSP output) { output = null; IntPtr dspraw; RESULT result = FMOD_DSPConnection_GetOutput(rawPtr, out dspraw); output = new DSP(dspraw); return result; } public RESULT setMix (float volume) { return FMOD_DSPConnection_SetMix(rawPtr, volume); } public RESULT getMix (out float volume) { return FMOD_DSPConnection_GetMix(rawPtr, out volume); } public RESULT setMixMatrix(float[] matrix, int outchannels, int inchannels, int inchannel_hop) { return FMOD_DSPConnection_SetMixMatrix(rawPtr, matrix, outchannels, inchannels, inchannel_hop); } public RESULT getMixMatrix(float[] matrix, out int outchannels, out int inchannels, int inchannel_hop) { return FMOD_DSPConnection_GetMixMatrix(rawPtr, matrix, out outchannels, out inchannels, inchannel_hop); } public RESULT getType(out DSPCONNECTION_TYPE type) { return FMOD_DSPConnection_GetType(rawPtr, out type); } // Userdata set/get. public RESULT setUserData(IntPtr userdata) { return FMOD_DSPConnection_SetUserData(rawPtr, userdata); } public RESULT getUserData(out IntPtr userdata) { return FMOD_DSPConnection_GetUserData(rawPtr, out userdata); } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSPConnection_GetInput (IntPtr dspconnection, out IntPtr input); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSPConnection_GetOutput (IntPtr dspconnection, out IntPtr output); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSPConnection_SetMix (IntPtr dspconnection, float volume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSPConnection_GetMix (IntPtr dspconnection, out float volume); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSPConnection_SetMixMatrix (IntPtr dspconnection, float[] matrix, int outchannels, int inchannels, int inchannel_hop); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSPConnection_GetMixMatrix (IntPtr dspconnection, float[] matrix, out int outchannels, out int inchannels, int inchannel_hop); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSPConnection_GetType (IntPtr dspconnection, out DSPCONNECTION_TYPE type); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSPConnection_SetUserData (IntPtr dspconnection, IntPtr userdata); [DllImport(VERSION.dll)] private static extern RESULT FMOD_DSPConnection_GetUserData (IntPtr dspconnection, out IntPtr userdata); #endregion #region wrapperinternal public DSPConnection(IntPtr raw) : base(raw) { } #endregion } /* 'Geometry' API */ public class Geometry : HandleBase { public RESULT release () { RESULT result = FMOD_Geometry_Release(getRaw()); if (result == RESULT.OK) { rawPtr = IntPtr.Zero; } return result; } // Polygon manipulation. public RESULT addPolygon (float directocclusion, float reverbocclusion, bool doublesided, int numvertices, VECTOR[] vertices, out int polygonindex) { return FMOD_Geometry_AddPolygon(rawPtr, directocclusion, reverbocclusion, doublesided, numvertices, vertices, out polygonindex); } public RESULT getNumPolygons (out int numpolygons) { return FMOD_Geometry_GetNumPolygons(rawPtr, out numpolygons); } public RESULT getMaxPolygons (out int maxpolygons, out int maxvertices) { return FMOD_Geometry_GetMaxPolygons(rawPtr, out maxpolygons, out maxvertices); } public RESULT getPolygonNumVertices (int index, out int numvertices) { return FMOD_Geometry_GetPolygonNumVertices(rawPtr, index, out numvertices); } public RESULT setPolygonVertex (int index, int vertexindex, ref VECTOR vertex) { return FMOD_Geometry_SetPolygonVertex(rawPtr, index, vertexindex, ref vertex); } public RESULT getPolygonVertex (int index, int vertexindex, out VECTOR vertex) { return FMOD_Geometry_GetPolygonVertex(rawPtr, index, vertexindex, out vertex); } public RESULT setPolygonAttributes (int index, float directocclusion, float reverbocclusion, bool doublesided) { return FMOD_Geometry_SetPolygonAttributes(rawPtr, index, directocclusion, reverbocclusion, doublesided); } public RESULT getPolygonAttributes (int index, out float directocclusion, out float reverbocclusion, out bool doublesided) { return FMOD_Geometry_GetPolygonAttributes(rawPtr, index, out directocclusion, out reverbocclusion, out doublesided); } // Object manipulation. public RESULT setActive (bool active) { return FMOD_Geometry_SetActive(rawPtr, active); } public RESULT getActive (out bool active) { return FMOD_Geometry_GetActive(rawPtr, out active); } public RESULT setRotation (ref VECTOR forward, ref VECTOR up) { return FMOD_Geometry_SetRotation(rawPtr, ref forward, ref up); } public RESULT getRotation (out VECTOR forward, out VECTOR up) { return FMOD_Geometry_GetRotation(rawPtr, out forward, out up); } public RESULT setPosition (ref VECTOR position) { return FMOD_Geometry_SetPosition(rawPtr, ref position); } public RESULT getPosition (out VECTOR position) { return FMOD_Geometry_GetPosition(rawPtr, out position); } public RESULT setScale (ref VECTOR scale) { return FMOD_Geometry_SetScale(rawPtr, ref scale); } public RESULT getScale (out VECTOR scale) { return FMOD_Geometry_GetScale(rawPtr, out scale); } public RESULT save (IntPtr data, out int datasize) { return FMOD_Geometry_Save(rawPtr, data, out datasize); } // Userdata set/get. public RESULT setUserData (IntPtr userdata) { return FMOD_Geometry_SetUserData(rawPtr, userdata); } public RESULT getUserData (out IntPtr userdata) { return FMOD_Geometry_GetUserData(rawPtr, out userdata); } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_Release (IntPtr geometry); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_AddPolygon (IntPtr geometry, float directocclusion, float reverbocclusion, bool doublesided, int numvertices, VECTOR[] vertices, out int polygonindex); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_GetNumPolygons (IntPtr geometry, out int numpolygons); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_GetMaxPolygons (IntPtr geometry, out int maxpolygons, out int maxvertices); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_GetPolygonNumVertices(IntPtr geometry, int index, out int numvertices); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_SetPolygonVertex (IntPtr geometry, int index, int vertexindex, ref VECTOR vertex); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_GetPolygonVertex (IntPtr geometry, int index, int vertexindex, out VECTOR vertex); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_SetPolygonAttributes (IntPtr geometry, int index, float directocclusion, float reverbocclusion, bool doublesided); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_GetPolygonAttributes (IntPtr geometry, int index, out float directocclusion, out float reverbocclusion, out bool doublesided); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_SetActive (IntPtr geometry, bool active); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_GetActive (IntPtr geometry, out bool active); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_SetRotation (IntPtr geometry, ref VECTOR forward, ref VECTOR up); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_GetRotation (IntPtr geometry, out VECTOR forward, out VECTOR up); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_SetPosition (IntPtr geometry, ref VECTOR position); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_GetPosition (IntPtr geometry, out VECTOR position); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_SetScale (IntPtr geometry, ref VECTOR scale); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_GetScale (IntPtr geometry, out VECTOR scale); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_Save (IntPtr geometry, IntPtr data, out int datasize); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_SetUserData (IntPtr geometry, IntPtr userdata); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Geometry_GetUserData (IntPtr geometry, out IntPtr userdata); #endregion #region wrapperinternal public Geometry(IntPtr raw) : base(raw) { } #endregion } /* 'Reverb3D' API */ public class Reverb3D : HandleBase { public RESULT release() { RESULT result = FMOD_Reverb3D_Release(getRaw()); if (result == RESULT.OK) { rawPtr = IntPtr.Zero; } return result; } // Reverb manipulation. public RESULT set3DAttributes(ref VECTOR position, float mindistance, float maxdistance) { return FMOD_Reverb3D_Set3DAttributes(rawPtr, ref position, mindistance, maxdistance); } public RESULT get3DAttributes(ref VECTOR position, ref float mindistance, ref float maxdistance) { return FMOD_Reverb3D_Get3DAttributes(rawPtr, ref position, ref mindistance, ref maxdistance); } public RESULT setProperties(ref REVERB_PROPERTIES properties) { return FMOD_Reverb3D_SetProperties(rawPtr, ref properties); } public RESULT getProperties(ref REVERB_PROPERTIES properties) { return FMOD_Reverb3D_GetProperties(rawPtr, ref properties); } public RESULT setActive(bool active) { return FMOD_Reverb3D_SetActive(rawPtr, active); } public RESULT getActive(out bool active) { return FMOD_Reverb3D_GetActive(rawPtr, out active); } // Userdata set/get. public RESULT setUserData(IntPtr userdata) { return FMOD_Reverb3D_SetUserData(rawPtr, userdata); } public RESULT getUserData(out IntPtr userdata) { return FMOD_Reverb3D_GetUserData(rawPtr, out userdata); } #region importfunctions [DllImport(VERSION.dll)] private static extern RESULT FMOD_Reverb3D_Release(IntPtr reverb); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Reverb3D_Set3DAttributes(IntPtr reverb, ref VECTOR position, float mindistance, float maxdistance); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Reverb3D_Get3DAttributes(IntPtr reverb, ref VECTOR position, ref float mindistance, ref float maxdistance); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Reverb3D_SetProperties(IntPtr reverb, ref REVERB_PROPERTIES properties); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Reverb3D_GetProperties(IntPtr reverb, ref REVERB_PROPERTIES properties); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Reverb3D_SetActive(IntPtr reverb, bool active); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Reverb3D_GetActive(IntPtr reverb, out bool active); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Reverb3D_SetUserData(IntPtr reverb, IntPtr userdata); [DllImport(VERSION.dll)] private static extern RESULT FMOD_Reverb3D_GetUserData(IntPtr reverb, out IntPtr userdata); #endregion #region wrapperinternal public Reverb3D(IntPtr raw) : base(raw) { } #endregion } class StringMarshalHelper { static internal void NativeToBuilder(StringBuilder builder, IntPtr nativeMem) { byte[] bytes = new byte[builder.Capacity]; Marshal.Copy(nativeMem, bytes, 0, builder.Capacity); String str = Encoding.UTF8.GetString(bytes, 0, Array.IndexOf(bytes, (byte)0)); builder.Append(str); } } }
53.480878
461
0.629645
[ "MIT" ]
ashleygwinnell/foh-ld40
src/util/fmod_windows/fmod.cs
226,545
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace DataAccessLayer { /// <summary> /// UserService is a cache of the user objects. /// All operations and query on users should go through the userservice. /// </summary> public class UserService { /********************IMPORTANT******************************* * Make sure that all the queries that query the users have the * same columns in the same order. Because the users are cached * in memory, accidentally missing a few properties could be * catastrophic. ********************IMPORTANT*******************************/ private static string UserPhoneNumberQueryString = "SELECT ID, PhoneNumber, Name, Secret, UserType, LastSyncTime, PublicKey, GroupOwner, RegisteredDevice, RegistrationDate from dbo.UserTable WHERE PhoneNumber = @phoneNumber AND UserType = @userType ORDER BY ID ASC;"; private static string UserIdQueryString = "SELECT ID, PhoneNumber, Name, Secret, UserType, LastSyncTime, PublicKey, GroupOwner, RegisteredDevice, RegistrationDate from dbo.UserTable WHERE ID = @id ORDER BY ID ASC;"; private static string InsertUserCommandString = "INSERT into dbo.UserTable (PhoneNumber, Name, Secret, UserType) VALUES (@phoneNumber, @name, @secret, @userType); SELECT scope_identity();"; private static string UpdateUserNameCommandString = "UPDATE dbo.UserTable SET Name = @name WHERE ID = @userId AND UserType = @userType"; private static string UpdateDeviceIdCommandString = "UPDATE dbo.UserTable SET RegisteredDevice = @device, RegistrationDate = @registrationdate WHERE ID = @userId AND UserType = @userType"; private static string UpdateLastSyncTimeCommand = "UPDATE dbo.UserTable SET LastSyncTime = @lastSyncTime WHERE ID = @userId"; private static string UpdateUserPublicKeyCommand = "UPDATE dbo.UserTable SET PublicKey = @publicKey WHERE ID = @userId"; private static string UsersQueryString = "SELECT ID, PhoneNumber, Name, Secret, UserType, LastSyncTime, PublicKey, GroupOwner, RegisteredDevice, RegistrationDate from dbo.UserTable {0} ORDER BY Name ASC;"; private static string WhereClause = "WHERE"; private static string IdClause = " ID = {0} "; private static string PhoneNumberClause = " PhoneNumber = '{0}' "; private ReaderWriterLockSlim readerWriterLock = new ReaderWriterLockSlim(); private Dictionary<int, User> userCache = new Dictionary<int, User>(); private Dictionary<string, User> phoneUserCache = new Dictionary<string, User>(); private Dictionary<object, object> userLockObjects = new Dictionary<object, object>(); public static UserService Instance = new UserService(); public User GetUserFromId(int id) { try { this.readerWriterLock.EnterReadLock(); if (this.userCache.ContainsKey(id)) { return this.userCache[id]; } } finally { this.readerWriterLock.ExitReadLock(); } // We don't use a global lock while reading the user from the table // We lock only the 'id' that we are trying to retrieve. For each id, // we use a dummy lock object. This lock object is used to synchronize // the threads attempting to read the same user object. // The list of lock objects are stored in a dictionary. // We first lock the dictionary and get/create a lock object for this id. // Then we lock the lock object and check if another thread added the user to // the cache already. If so, we return. // Else we read it from the database, add the user to the user cache and exit. object lockObject = null; try { lock (this.userLockObjects) { if (!this.userLockObjects.ContainsKey(id)) { this.userLockObjects.Add(id, new object()); } lockObject = this.userLockObjects[id]; } Monitor.Enter(lockObject); if (this.userCache.ContainsKey(id)) { return this.userCache[id]; } User user = UserService.InternalGetUserFromId(id); if (user == null) { return null; } this.userCache.Add(id, user); if (user.UserType != UserType.Group) { this.phoneUserCache.Add(user.PhoneNumber, user); } return user; } finally { Monitor.Exit(lockObject); lock (this.userLockObjects) { if (this.userLockObjects.ContainsKey(id)) { this.userLockObjects.Remove(id); } } } } public User GetUserFromPhone(string phoneNumber) { try { this.readerWriterLock.EnterReadLock(); if (this.phoneUserCache.ContainsKey(phoneNumber)) { return this.phoneUserCache[phoneNumber]; } } finally { this.readerWriterLock.ExitReadLock(); } // We don't use a global lock while reading the user from the table // We lock only the 'id' that we are trying to retrieve. For each id, // we use a dummy lock object. This lock object is used to synchronize // the threads attempting to read the same user object. // The list of lock objects are stored in a dictionary. // We first lock the dictionary and get/create a lock object for this id. // Then we lock the lock object and check if another thread added the user to // the cache already. If so, we return. // Else we read it from the database, add the user to the user cache and exit. object lockObject = null; try { lock (this.userLockObjects) { if (!this.userLockObjects.ContainsKey(phoneNumber)) { this.userLockObjects.Add(phoneNumber, new object()); } lockObject = this.userLockObjects[phoneNumber]; } Monitor.Enter(lockObject); if (this.phoneUserCache.ContainsKey(phoneNumber)) { return this.phoneUserCache[phoneNumber]; } User user = UserService.InternalGetUserFromPhone(phoneNumber); if (user != null) { this.userCache.Add(user.Id, user); if (user.UserType != UserType.Group) { this.phoneUserCache.Add(user.PhoneNumber, user); } } return user; } finally { Monitor.Exit(lockObject); lock (this.userLockObjects) { if (this.userLockObjects.ContainsKey(phoneNumber)) { this.userLockObjects.Remove(phoneNumber); } } } } public void RemoveUserFromCache(User user) { this.RemoveUserFromCache(user.Id); } public void RemoveUserFromCache(int userId) { this.readerWriterLock.EnterReadLock(); if (!this.userCache.ContainsKey(userId)) { return; } object lockObject = null; try { lock (this.userLockObjects) { if (!this.userLockObjects.ContainsKey(userId)) { this.userLockObjects.Add(userId, new object()); } lockObject = this.userLockObjects[userId]; Monitor.Enter(lockObject); } if (!this.userCache.ContainsKey(userId)) { return; } User user = this.userCache[userId]; this.userCache.Remove(userId); this.phoneUserCache.Remove(user.PhoneNumber); } finally { Monitor.Exit(lockObject); lock (this.userLockObjects) { if (this.userLockObjects.ContainsKey(userId)) { this.userLockObjects.Remove(userId); } } this.readerWriterLock.ExitReadLock(); } } public void ReloadUserSubscriptions(int userId) { this.readerWriterLock.EnterReadLock(); if (!this.userCache.ContainsKey(userId)) { return; } object lockObject = null; try { lock (this.userLockObjects) { if (!this.userLockObjects.ContainsKey(userId)) { this.userLockObjects.Add(userId, new object()); } lockObject = this.userLockObjects[userId]; Monitor.Enter(lockObject); } if (!this.userCache.ContainsKey(userId)) { return; } User user = this.userCache[userId]; user.SubscriptionUrls = Subscription.GetSubscriptionsForUser(userId, user.RegisteredDevice); } finally { Monitor.Exit(lockObject); lock (this.userLockObjects) { if (this.userLockObjects.ContainsKey(userId)) { this.userLockObjects.Remove(userId); } } this.readerWriterLock.ExitReadLock(); } } public List<User> GetUsersFromPhones(List<string> phoneNumbers) { List<User> users = new List<User>(); List<string> notFoundPhoneNumbers = new List<string>(); Dictionary<int, User> addedUsers = new Dictionary<int, User>(); foreach (string phoneNumber in phoneNumbers) { try { this.readerWriterLock.EnterReadLock(); if (this.phoneUserCache.ContainsKey(phoneNumber)) { User user = this.phoneUserCache[phoneNumber]; if (!addedUsers.ContainsKey(user.Id)) { users.Add(this.phoneUserCache[phoneNumber]); addedUsers.Add(user.Id, user); } } else { notFoundPhoneNumbers.Add(phoneNumber); } } finally { this.readerWriterLock.ExitReadLock(); } } List<User> notFoundUsers = UserService.InternalGetUsersFromPhones(notFoundPhoneNumbers); foreach (User u in notFoundUsers) { if (!addedUsers.ContainsKey(u.Id)) { users.Add(u); addedUsers.Add(u.Id, u); } } foreach (User user in notFoundUsers) { object lockObject = null; try { lock (this.userLockObjects) { if (!this.userLockObjects.ContainsKey(user.Id)) { this.userLockObjects.Add(user.Id, new object()); } lockObject = this.userLockObjects[user.Id]; } Monitor.Enter(lockObject); if (this.userCache.ContainsKey(user.Id)) { continue; } this.userCache.Add(user.Id, user); this.phoneUserCache.Add(user.PhoneNumber, user); } finally { Monitor.Exit(lockObject); lock (this.userLockObjects) { if (this.userLockObjects.ContainsKey(user.Id)) { this.userLockObjects.Remove(user.Id); } } } } return users; } /// <summary> /// Search for the phone based on the phone number /// </summary> /// <param name="phoneNumber"></param> /// <returns></returns> private static User InternalGetUserFromPhone(string phoneNumber) { // Create and open the connection in a using block. This // ensures that all resources will be closed and disposed // when the code exits. using (SqlConnection connection = new SqlConnection(Globals.SqlConnectionString)) { connection.Open(); using (SqlTransaction sqlTransaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)) { // Open the connection in a try/catch block. // Create and execute the DataReader, writing the result // set to the console window. try { // Create the Command and Parameter objects. using (SqlCommand command = new SqlCommand(UserService.UserPhoneNumberQueryString, connection, sqlTransaction)) { command.Parameters.AddWithValue("@phoneNumber", phoneNumber); command.Parameters.AddWithValue("@userType", UserType.User); var adapter = new SqlDataAdapter(command); var dataset = new DataSet(); adapter.Fill(dataset); if (dataset.Tables[0].Rows.Count != 1) { return null; } return UserService.CreateUserFromRow(dataset.Tables[0].Rows[0]); } } finally { connection.Close(); } } } } /// <summary> /// Search for the phone based on the phone number /// </summary> /// <param name="phoneNumber"></param> /// <returns></returns> private static User InternalGetUserFromId(int id) { // Create and open the connection in a using block. This // ensures that all resources will be closed and disposed // when the code exits. using (SqlConnection connection = new SqlConnection(Globals.SqlConnectionString)) { connection.Open(); using (SqlTransaction sqlTransaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)) { // Open the connection in a try/catch block. // Create and execute the DataReader, writing the result // set to the console window. try { // Create the Command and Parameter objects. using (SqlCommand command = new SqlCommand(UserService.UserIdQueryString, connection, sqlTransaction)) { command.Parameters.AddWithValue("@id", id); var adapter = new SqlDataAdapter(command); var dataset = new DataSet(); adapter.Fill(dataset); if (dataset.Tables[0].Rows.Count != 1) { return null; } return UserService.CreateUserFromRow(dataset.Tables[0].Rows[0]); } } finally { connection.Close(); } } } } /// <summary> /// Search for the phone based on the phone number /// </summary> /// <param name="phoneNumber"></param> /// <returns></returns> private static List<User> InternalGetUsersFromPhones(List<string> phoneNumbers) { if (phoneNumbers == null || phoneNumbers.Count == 0) { return new List<User>(); } StringBuilder whereClauses = new StringBuilder(); whereClauses.Append(UserService.WhereClause); for (int i = 0; i < phoneNumbers.Count; i++) { if (i != 0) { whereClauses.Append("OR"); } whereClauses.AppendFormat(UserService.PhoneNumberClause, phoneNumbers[i]); } // Create and open the connection in a using block. This // ensures that all resources will be closed and disposed // when the code exits. using (SqlConnection connection = new SqlConnection(Globals.SqlConnectionString)) { connection.Open(); using (SqlTransaction sqlTransaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)) { // Open the connection in a try/catch block. // Create and execute the DataReader, writing the result // set to the console window. try { // Create the Command and Parameter objects. string commandString = string.Format(UserService.UsersQueryString, whereClauses); using (SqlCommand command = new SqlCommand(commandString, connection, sqlTransaction)) { var adapter = new SqlDataAdapter(command); var dataset = new DataSet(); adapter.Fill(dataset); List<User> users = new List<User>(); for (int i = 0; i < dataset.Tables[0].Rows.Count; i++) { User u = UserService.CreateUserFromRow(dataset.Tables[0].Rows[i]); users.Add(u); } return users; } } finally { connection.Close(); } } } } private static User CreateUserFromRow(DataRow dataRow) { if ((UserType)dataRow[4] == UserType.User) { DateTime LastSyncTime = DateTime.MinValue; if (!DBNull.Value.Equals(dataRow[5])) { LastSyncTime = (DateTime)dataRow[5]; } byte[] publicKey = null; if (!DBNull.Value.Equals(dataRow[6])) { publicKey = (byte[])dataRow[6]; } return new User( (int)dataRow[0], (string)dataRow[1], (string)dataRow[2], (string)dataRow[3], LastSyncTime, publicKey, dataRow[8] == DBNull.Value ? string.Empty : (string)dataRow[8], dataRow[8] == DBNull.Value ? 0 : (long)dataRow[9]); } else { int groupOwnerId = (int)dataRow[7]; User groupOwner = UserService.Instance.GetUserFromId(groupOwnerId); Group group = new Group((int)dataRow[0], (string)dataRow[2], groupOwner); return group; } } /// <summary> /// Registers a new user /// </summary> /// <param name="phoneNumber"></param> /// <param name="name"></param> /// <remarks> /// Note that because the table is not locked and phonenumber is not the primary key, /// another instance of the webapp could register with the same phone number. /// </remarks> /// <returns>the registered user</returns> internal static User Register(string phoneNumber, string name) { // Create and open the connection in a using block. This // ensures that all resources will be closed and disposed // when the code exits. using (SqlConnection connection = new SqlConnection(Globals.SqlConnectionString)) { connection.Open(); using (SqlTransaction sqlTransaction = connection.BeginTransaction()) { // Open the connection in a try/catch block. // Create and execute the DataReader, writing the result // set to the console window. try { // Create the Command and Parameter objects. using (SqlCommand command = new SqlCommand(UserService.InsertUserCommandString, connection, sqlTransaction)) { string secret = Guid.NewGuid().ToString(); command.Parameters.AddWithValue("@phoneNumber", phoneNumber); command.Parameters.AddWithValue("@name", name); command.Parameters.AddWithValue("@secret", secret); command.Parameters.AddWithValue("@userType", UserType.User); SqlParameter outParameter = new SqlParameter("@UserId", SqlDbType.BigInt); outParameter.Direction = ParameterDirection.Output; command.Parameters.Add(outParameter); int identity = (int)(decimal)command.ExecuteScalar(); sqlTransaction.Commit(); return new User(identity, phoneNumber, name, secret); } } catch (Exception) { sqlTransaction.Rollback(); } finally { connection.Close(); } return null; } } } public void UpdateName(User user, string name) { Stopwatch watch = new Stopwatch(); long connectionTime = 0; long transctionTime = 0; long executionTime = 0; long commitTime = 0; watch.Start(); using (SqlConnection connection = new SqlConnection(Globals.SqlConnectionString)) { connection.Open(); connectionTime = watch.ElapsedMilliseconds; watch.Restart(); using (SqlTransaction sqlTransaction = connection.BeginTransaction()) { transctionTime = watch.ElapsedMilliseconds; watch.Restart(); // Open the connection in a try/catch block. // Create and execute the DataReader, writing the result // set to the console window. try { // Create the Command and Parameter objects. using (SqlCommand command = new SqlCommand(UserService.UpdateUserNameCommandString, connection, sqlTransaction)) { command.Parameters.AddWithValue("@name", name); command.Parameters.AddWithValue("@userId", user.Id); command.Parameters.AddWithValue("@userType", UserType.User); int result = command.ExecuteNonQuery(); executionTime = watch.ElapsedMilliseconds; watch.Restart(); if (result > 0) { user.Name = name; sqlTransaction.Commit(); } else { sqlTransaction.Rollback(); } commitTime = watch.ElapsedMilliseconds; watch.Restart(); } } catch (Exception) { sqlTransaction.Rollback(); } finally { connection.Close(); } } } } public void UpdateDeviceId(User user, string deviceId) { Stopwatch watch = new Stopwatch(); long connectionTime = 0; long transctionTime = 0; long executionTime = 0; long commitTime = 0; watch.Start(); using (SqlConnection connection = new SqlConnection(Globals.SqlConnectionString)) { connection.Open(); connectionTime = watch.ElapsedMilliseconds; watch.Restart(); using (SqlTransaction sqlTransaction = connection.BeginTransaction()) { transctionTime = watch.ElapsedMilliseconds; watch.Restart(); // Open the connection in a try/catch block. // Create and execute the DataReader, writing the result // set to the console window. try { long registrationdate = DateTime.UtcNow.Ticks; // Create the Command and Parameter objects. using (SqlCommand command = new SqlCommand(UserService.UpdateDeviceIdCommandString, connection, sqlTransaction)) { command.Parameters.AddWithValue("@device", deviceId); command.Parameters.AddWithValue("@registrationdate", registrationdate); command.Parameters.AddWithValue("@userId", user.Id); command.Parameters.AddWithValue("@userType", UserType.User); int result = command.ExecuteNonQuery(); executionTime = watch.ElapsedMilliseconds; watch.Restart(); if (result > 0) { user.RegisteredDevice = deviceId; user.RegistrationDate = registrationdate; sqlTransaction.Commit(); } else { sqlTransaction.Rollback(); } commitTime = watch.ElapsedMilliseconds; watch.Restart(); } } catch (Exception) { sqlTransaction.Rollback(); } finally { connection.Close(); } } } } internal static List<User> GetUsers(List<int> participants) { StringBuilder whereClauses = new StringBuilder(); whereClauses.Append(UserService.WhereClause); for (int i = 0; i < participants.Count; i++) { if (i != 0) { whereClauses.Append("OR"); } whereClauses.AppendFormat(UserService.IdClause, participants[i]); } // Create and open the connection in a using block. This // ensures that all resources will be closed and disposed // when the code exits. using (SqlConnection connection = new SqlConnection(Globals.SqlConnectionString)) { connection.Open(); using (SqlTransaction sqlTransaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)) { // Open the connection in a try/catch block. // Create and execute the DataReader, writing the result // set to the console window. try { // Create the Command and Parameter objects. string commandString = string.Format(UserService.UsersQueryString, whereClauses); using (SqlCommand command = new SqlCommand(commandString, connection, sqlTransaction)) { var adapter = new SqlDataAdapter(command); var dataset = new DataSet(); adapter.Fill(dataset); List<User> users = new List<User>(); for (int i = 0; i < dataset.Tables[0].Rows.Count; i++) { users.Add(UserService.CreateUserFromRow(dataset.Tables[0].Rows[i])); } return users; } } catch (Exception) { return null; } finally { connection.Close(); } } } } internal static void UpdateUserLastSyncTime(int UserId, DateTime lastSyncTime) { using (SqlConnection connection = new SqlConnection(Globals.SqlConnectionString)) { connection.Open(); using (SqlTransaction sqlTransaction = connection.BeginTransaction()) { // Open the connection in a try/catch block. // Create and execute the DataReader, writing the result // set to the console window. try { // Create the Command and Parameter objects. using (SqlCommand command = new SqlCommand(UserService.UpdateLastSyncTimeCommand, connection, sqlTransaction)) { command.Parameters.AddWithValue("@userId", UserId); command.Parameters.AddWithValue("@lastSyncTime", lastSyncTime); int result = command.ExecuteNonQuery(); if (result > 0) { sqlTransaction.Commit(); } else { sqlTransaction.Rollback(); } } User user = UserService.Instance.GetUserFromId(UserId); user.LastSyncTime = lastSyncTime; } catch (Exception) { sqlTransaction.Rollback(); } finally { connection.Close(); } } } } internal static void UpdateUserPublicKey(User user, byte[] publicKey) { using (SqlConnection connection = new SqlConnection(Globals.SqlConnectionString)) { connection.Open(); using (SqlTransaction sqlTransaction = connection.BeginTransaction()) { // Open the connection in a try/catch block. // Create and execute the DataReader, writing the result // set to the console window. try { // Create the Command and Parameter objects. using (SqlCommand command = new SqlCommand(UserService.UpdateUserPublicKeyCommand, connection, sqlTransaction)) { command.Parameters.AddWithValue("@userId", user.Id); command.Parameters.AddWithValue("@publicKey", publicKey); int result = command.ExecuteNonQuery(); if (result > 0) { sqlTransaction.Commit(); } else { sqlTransaction.Rollback(); } } user.PublicKey = publicKey; } catch (Exception) { sqlTransaction.Rollback(); } finally { connection.Close(); } } } } } }
38.736842
276
0.447371
[ "MIT" ]
nrag/yapper
Server/YapperServer/DataAccessLayer/UserService.cs
36,066
C#
using System; using System.Globalization; using System.Linq; using System.Reflection; namespace TraceMe.Areas.HelpPage.ModelDescriptions { internal static class ModelNameHelper { // Modify this to provide custom model name mapping. public static string GetModelName(Type type) { ModelNameAttribute modelNameAttribute = type.GetCustomAttribute<ModelNameAttribute>(); if (modelNameAttribute != null && !String.IsNullOrEmpty(modelNameAttribute.Name)) { return modelNameAttribute.Name; } string modelName = type.Name; if (type.IsGenericType) { // Format the generic type name to something like: GenericOfAgurment1AndArgument2 Type genericType = type.GetGenericTypeDefinition(); Type[] genericArguments = type.GetGenericArguments(); string genericTypeName = genericType.Name; // Trim the generic parameter counts from the name genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`')); string[] argumentTypeNames = genericArguments.Select(t => GetModelName(t)).ToArray(); modelName = String.Format(CultureInfo.InvariantCulture, "{0}Of{1}", genericTypeName, String.Join("And", argumentTypeNames)); } return modelName; } } }
39.888889
140
0.635097
[ "MIT" ]
bjornhol/traceme
source/Areas/HelpPage/ModelDescriptions/ModelNameHelper.cs
1,436
C#
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace DalRis { /// <summary> /// Strongly-typed collection for the SysRelPacienteObraSocial class. /// </summary> [Serializable] public partial class SysRelPacienteObraSocialCollection : ActiveList<SysRelPacienteObraSocial, SysRelPacienteObraSocialCollection> { public SysRelPacienteObraSocialCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>SysRelPacienteObraSocialCollection</returns> public SysRelPacienteObraSocialCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { SysRelPacienteObraSocial o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Sys_RelPacienteObraSocial table. /// </summary> [Serializable] public partial class SysRelPacienteObraSocial : ActiveRecord<SysRelPacienteObraSocial>, IActiveRecord { #region .ctors and Default Settings public SysRelPacienteObraSocial() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public SysRelPacienteObraSocial(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public SysRelPacienteObraSocial(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public SysRelPacienteObraSocial(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Sys_RelPacienteObraSocial", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdRelPacienteObraSocial = new TableSchema.TableColumn(schema); colvarIdRelPacienteObraSocial.ColumnName = "idRelPacienteObraSocial"; colvarIdRelPacienteObraSocial.DataType = DbType.Int32; colvarIdRelPacienteObraSocial.MaxLength = 0; colvarIdRelPacienteObraSocial.AutoIncrement = true; colvarIdRelPacienteObraSocial.IsNullable = false; colvarIdRelPacienteObraSocial.IsPrimaryKey = true; colvarIdRelPacienteObraSocial.IsForeignKey = false; colvarIdRelPacienteObraSocial.IsReadOnly = false; colvarIdRelPacienteObraSocial.DefaultSetting = @""; colvarIdRelPacienteObraSocial.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdRelPacienteObraSocial); TableSchema.TableColumn colvarIdPaciente = new TableSchema.TableColumn(schema); colvarIdPaciente.ColumnName = "idPaciente"; colvarIdPaciente.DataType = DbType.Int32; colvarIdPaciente.MaxLength = 0; colvarIdPaciente.AutoIncrement = false; colvarIdPaciente.IsNullable = false; colvarIdPaciente.IsPrimaryKey = false; colvarIdPaciente.IsForeignKey = true; colvarIdPaciente.IsReadOnly = false; colvarIdPaciente.DefaultSetting = @""; colvarIdPaciente.ForeignKeyTableName = "Sys_Paciente"; schema.Columns.Add(colvarIdPaciente); TableSchema.TableColumn colvarIdObraSocial = new TableSchema.TableColumn(schema); colvarIdObraSocial.ColumnName = "idObraSocial"; colvarIdObraSocial.DataType = DbType.Int32; colvarIdObraSocial.MaxLength = 0; colvarIdObraSocial.AutoIncrement = false; colvarIdObraSocial.IsNullable = false; colvarIdObraSocial.IsPrimaryKey = false; colvarIdObraSocial.IsForeignKey = true; colvarIdObraSocial.IsReadOnly = false; colvarIdObraSocial.DefaultSetting = @""; colvarIdObraSocial.ForeignKeyTableName = "Sys_ObraSocial"; schema.Columns.Add(colvarIdObraSocial); TableSchema.TableColumn colvarNumeroAfiliado = new TableSchema.TableColumn(schema); colvarNumeroAfiliado.ColumnName = "numeroAfiliado"; colvarNumeroAfiliado.DataType = DbType.AnsiString; colvarNumeroAfiliado.MaxLength = 50; colvarNumeroAfiliado.AutoIncrement = false; colvarNumeroAfiliado.IsNullable = false; colvarNumeroAfiliado.IsPrimaryKey = false; colvarNumeroAfiliado.IsForeignKey = false; colvarNumeroAfiliado.IsReadOnly = false; colvarNumeroAfiliado.DefaultSetting = @""; colvarNumeroAfiliado.ForeignKeyTableName = ""; schema.Columns.Add(colvarNumeroAfiliado); TableSchema.TableColumn colvarFechaAlta = new TableSchema.TableColumn(schema); colvarFechaAlta.ColumnName = "fechaAlta"; colvarFechaAlta.DataType = DbType.DateTime; colvarFechaAlta.MaxLength = 0; colvarFechaAlta.AutoIncrement = false; colvarFechaAlta.IsNullable = false; colvarFechaAlta.IsPrimaryKey = false; colvarFechaAlta.IsForeignKey = false; colvarFechaAlta.IsReadOnly = false; colvarFechaAlta.DefaultSetting = @""; colvarFechaAlta.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaAlta); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("Sys_RelPacienteObraSocial",schema); } } #endregion #region Props [XmlAttribute("IdRelPacienteObraSocial")] [Bindable(true)] public int IdRelPacienteObraSocial { get { return GetColumnValue<int>(Columns.IdRelPacienteObraSocial); } set { SetColumnValue(Columns.IdRelPacienteObraSocial, value); } } [XmlAttribute("IdPaciente")] [Bindable(true)] public int IdPaciente { get { return GetColumnValue<int>(Columns.IdPaciente); } set { SetColumnValue(Columns.IdPaciente, value); } } [XmlAttribute("IdObraSocial")] [Bindable(true)] public int IdObraSocial { get { return GetColumnValue<int>(Columns.IdObraSocial); } set { SetColumnValue(Columns.IdObraSocial, value); } } [XmlAttribute("NumeroAfiliado")] [Bindable(true)] public string NumeroAfiliado { get { return GetColumnValue<string>(Columns.NumeroAfiliado); } set { SetColumnValue(Columns.NumeroAfiliado, value); } } [XmlAttribute("FechaAlta")] [Bindable(true)] public DateTime FechaAlta { get { return GetColumnValue<DateTime>(Columns.FechaAlta); } set { SetColumnValue(Columns.FechaAlta, value); } } #endregion #region ForeignKey Properties /// <summary> /// Returns a SysObraSocial ActiveRecord object related to this SysRelPacienteObraSocial /// /// </summary> public DalRis.SysObraSocial SysObraSocial { get { return DalRis.SysObraSocial.FetchByID(this.IdObraSocial); } set { SetColumnValue("idObraSocial", value.IdObraSocial); } } /// <summary> /// Returns a SysPaciente ActiveRecord object related to this SysRelPacienteObraSocial /// /// </summary> public DalRis.SysPaciente SysPaciente { get { return DalRis.SysPaciente.FetchByID(this.IdPaciente); } set { SetColumnValue("idPaciente", value.IdPaciente); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdPaciente,int varIdObraSocial,string varNumeroAfiliado,DateTime varFechaAlta) { SysRelPacienteObraSocial item = new SysRelPacienteObraSocial(); item.IdPaciente = varIdPaciente; item.IdObraSocial = varIdObraSocial; item.NumeroAfiliado = varNumeroAfiliado; item.FechaAlta = varFechaAlta; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdRelPacienteObraSocial,int varIdPaciente,int varIdObraSocial,string varNumeroAfiliado,DateTime varFechaAlta) { SysRelPacienteObraSocial item = new SysRelPacienteObraSocial(); item.IdRelPacienteObraSocial = varIdRelPacienteObraSocial; item.IdPaciente = varIdPaciente; item.IdObraSocial = varIdObraSocial; item.NumeroAfiliado = varNumeroAfiliado; item.FechaAlta = varFechaAlta; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdRelPacienteObraSocialColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdPacienteColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdObraSocialColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn NumeroAfiliadoColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn FechaAltaColumn { get { return Schema.Columns[4]; } } #endregion #region Columns Struct public struct Columns { public static string IdRelPacienteObraSocial = @"idRelPacienteObraSocial"; public static string IdPaciente = @"idPaciente"; public static string IdObraSocial = @"idObraSocial"; public static string NumeroAfiliado = @"numeroAfiliado"; public static string FechaAlta = @"fechaAlta"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
30.562025
145
0.644798
[ "MIT" ]
saludnqn/ris
DalRis/generated/SysRelPacienteObraSocial.cs
12,072
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CondenseArrayToNumber { class CondenseArrayToNumber { static void Main(string[] args) { int[] numbers = Console.ReadLine().Split().Select(int.Parse).ToArray(); if (numbers.Length == 1) { Console.WriteLine(numbers[0]); } else { while (numbers.Length > 1) { int[] condensed = new int[numbers.Length - 1]; for (int i = 0; i < condensed.Length; i++) { condensed[i] = numbers[i] + numbers[i + 1]; } numbers = condensed; } Console.WriteLine(numbers[0]); } } } }
25.594595
84
0.436114
[ "MIT" ]
BorislavD/Arrays-and-Lists-CSharp
CondenseArrayToNumber.cs
949
C#
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using System.Web; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin; using Microsoft.Owin.Security; using BikeTracker.Models; namespace BikeTracker { public class EmailService : IIdentityMessageService { public Task SendAsync(IdentityMessage message) { // Plug in your email service here to send an email. return Task.FromResult(0); } } public class SmsService : IIdentityMessageService { public Task SendAsync(IdentityMessage message) { // Plug in your SMS service here to send a text message. return Task.FromResult(0); } } // Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application. public class ApplicationUserManager : UserManager<ApplicationUser> { public ApplicationUserManager(IUserStore<ApplicationUser> store) : base(store) { } public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) { var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>())); // Configure validation logic for usernames manager.UserValidator = new UserValidator<ApplicationUser>(manager) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; // Configure validation logic for passwords manager.PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = true, RequireDigit = true, RequireLowercase = true, RequireUppercase = true, }; // Configure user lockout defaults manager.UserLockoutEnabledByDefault = true; manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); manager.MaxFailedAccessAttemptsBeforeLockout = 5; // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user // You can write your own provider and plug it in here. manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser> { MessageFormat = "Your security code is {0}" }); manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser> { Subject = "Security Code", BodyFormat = "Your security code is {0}" }); manager.EmailService = new EmailService(); manager.SmsService = new SmsService(); var dataProtectionProvider = options.DataProtectionProvider; if (dataProtectionProvider != null) { manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity")); } return manager; } } // Configure the application sign-in manager which is used in this application. public class ApplicationSignInManager : SignInManager<ApplicationUser, string> { public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager) : base(userManager, authenticationManager) { } public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user) { return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager); } public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context) { return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication); } } }
39.345455
152
0.659889
[ "MIT" ]
SiiHackathon/BikeTracking
BikeTracker/App_Start/IdentityConfig.cs
4,330
C#
using NUnit.Framework; using umbraco.cms.presentation.Trees; namespace Umbraco.Tests.TreesAndSections { [TestFixture] public class BaseMediaTreeTests { [TearDown] public void TestTearDown() { BaseTree.AfterTreeRender -= EventHandler; BaseTree.BeforeTreeRender -= EventHandler; } [Test] public void Run_Optimized() { var tree = new MyOptimizedMediaTree("media"); Assert.IsTrue(tree.UseOptimizedRendering); } [Test] public void Not_Optimized_Events_AfterRender() { var tree = new MyOptimizedMediaTree("media"); BaseTree.AfterTreeRender += EventHandler; Assert.IsFalse(tree.UseOptimizedRendering); } [Test] public void Not_Optimized_Events_BeforeRender() { var tree = new MyOptimizedMediaTree("media"); BaseTree.BeforeTreeRender += EventHandler; Assert.IsFalse(tree.UseOptimizedRendering); } private void EventHandler(object sender, TreeEventArgs treeEventArgs) { } public class MyOptimizedMediaTree : BaseMediaTree { public MyOptimizedMediaTree(string application) : base(application) { } protected override void CreateRootNode(ref XmlTreeNode rootNode) { } } } }
22.876923
77
0.577001
[ "MIT" ]
Abhith/Umbraco-CMS
src/Umbraco.Tests/TreesAndSections/BaseMediaTreeTests.cs
1,489
C#
using System; namespace NPrng { public interface IPseudoRandomGenerator { /// <summary>Generates a pseudo random 64-bit integer.</summary> Int64 Generate(); /// <summary>Generates a pseudo random non-negative 64-bit integer up to range.</summary> Int64 GenerateLessOrEqualTo(Int64 range); /// <summary>Generates a pseudo random 64-bit integer in [lower, upper] range.</summary> Int64 GenerateInRange(Int64 lower, Int64 upper); /// <summary>Generates a pseudo random 64-bit double in [0, 1) range.</summary> double GenerateDouble(); } }
30.8
97
0.662338
[ "MIT" ]
RafalSzefler/NPrng
Sources/NPrng/IPseudoRandomGenerator.cs
616
C#
using Azure.Storage.Blobs; using Google.Apis.Auth.OAuth2; using Google.Cloud.Storage.V1; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System.IO; using System.Text; using TCC.Lib.AsyncStreams; using TCC.Lib.Blocks; using TCC.Lib.Command; using TCC.Lib.Database; using TCC.Lib.Dependencies; using TCC.Lib.Helpers; using TCC.Lib.Options; using TCC.Lib.PrepareBlocks; using TCC.Lib.Storage; namespace TCC.Lib { public class TarCompressCrypt { private readonly CancellationTokenSource _cancellationTokenSource; private readonly ILogger<TarCompressCrypt> _logger; private readonly EncryptionCommands _encryptionCommands; private readonly CompressionCommands _compressionCommands; private readonly IServiceProvider _serviceProvider; private readonly DatabaseHelper _databaseHelper; private int _compressCounter; private int _uploadCounter; private int _totalCounter; public TarCompressCrypt(CancellationTokenSource cancellationTokenSource, ILogger<TarCompressCrypt> logger, EncryptionCommands encryptionCommands, CompressionCommands compressionCommands, IServiceProvider serviceProvider, DatabaseHelper databaseHelper) { _cancellationTokenSource = cancellationTokenSource; _logger = logger; _encryptionCommands = encryptionCommands; _compressionCommands = compressionCommands; _serviceProvider = serviceProvider; _databaseHelper = databaseHelper; } public async Task<OperationSummary> Compress(CompressOption option) { var sw = Stopwatch.StartNew(); var compFolder = new CompressionFolderProvider(new DirectoryInfo(option.DestinationDir), option.FolderPerDay); IEnumerable<CompressionBlock> blocks = option.GenerateCompressBlocks(compFolder); IPrepareCompressBlocks prepare = new FileSystemPrepareCompressBlocks(compFolder, option.BackupMode, option.CleanupTime); var buffer = prepare.PrepareCompressionBlocksAsync(blocks); _totalCounter = buffer.Count; PrepareBoostRatio(option, buffer); _logger.LogInformation("job prepared in " + sw.Elapsed.HumanizedTimeSpan()); _logger.LogInformation("Starting compression job"); var po = ParallelizeOption(option); IRemoteStorage uploader = await option.GetRemoteStorageAsync(_logger, _cancellationTokenSource.Token); var operationBlocks = await buffer .AsAsyncStream(_cancellationTokenSource.Token) .CountAsync(out var counter) // Prepare encryption .ParallelizeStreamAsync(async (b, token) => { b.StartTime = DateTime.UtcNow; await _encryptionCommands.PrepareEncryptionKey(b, option, token); return b; }, po) // Core loop .ParallelizeStreamAsync((block, token) => { return CompressionBlockInternal(option, block, token); }, po) // Cleanup loop .ParallelizeStreamAsync(async (opb, token) => { await CleanupOldFiles(opb); await _encryptionCommands.CleanupKey(opb.BlockResult.Block, option, Mode.Compress); return opb; }, po) // Upload loop .ParallelizeStreamAsync((block, token) => UploadBlockInternal(uploader, option, block, token), new ParallelizeOption { FailMode = Fail.Smart, MaxDegreeOfParallelism = option.AzThread ?? 1 }) .AsReadOnlyCollectionAsync(); sw.Stop(); var ops = new OperationSummary(operationBlocks, option.Threads, sw); return ops; } private async Task<OperationCompressionBlock> UploadBlockInternal(IRemoteStorage uploader, CompressOption option, OperationCompressionBlock block, CancellationToken token) { if (uploader is NoneRemoteStorage) { return block; } int count = Interlocked.Increment(ref _uploadCounter); string progress = $"{count}/{_totalCounter}"; var file = block.CompressionBlock.DestinationArchiveFileInfo; var name = file.Name; RetryContext ctx = null; while (true) { bool hasError; try { var sw = Stopwatch.StartNew(); var result = await uploader.UploadAsync(file, block.CompressionBlock.FolderProvider.RootFolder, token); hasError = !result.IsSuccess; block.BlockResult.StepResults.Add(new StepResult() { Type = StepType.Upload, Errors = result.IsSuccess ? null : result.ErrorMessage, Infos = result.IsSuccess ? result.ErrorMessage : null }); sw.Stop(); if (!hasError) { double speed = file.Length / sw.Elapsed.TotalSeconds; _logger.LogInformation($"{progress} Uploaded \"{file.Name}\" in {sw.Elapsed.HumanizedTimeSpan()} at {speed.HumanizedBandwidth()} "); } else { if (ctx == null && option.RetryPeriodInSeconds.HasValue) { ctx = new RetryContext(option.RetryPeriodInSeconds.Value); } _logger.LogError($"{progress} Uploaded {file.Name} with errors. {result.ErrorMessage}"); } } catch (Exception e) { hasError = true; if (ctx == null && option.RetryPeriodInSeconds.HasValue) { ctx = new RetryContext(option.RetryPeriodInSeconds.Value); } _logger.LogCritical(e, $"{progress} Error uploading {name}"); } if (hasError) { if (ctx != null && await ctx.WaitForNextRetry()) { _logger.LogWarning($"{progress} Retrying uploading {name}, attempt #{ctx.Retries}"); } else { break; } } else { break; } } return block; } private async Task CleanupOldFiles(OperationCompressionBlock opb) { if (opb.CompressionBlock.FullsToDelete != null) { foreach (var full in opb.CompressionBlock.FullsToDelete) { try { await full.TryDeleteFileWithRetryAsync(); } catch (Exception e) { _logger.LogError(e, "Error while deleting FULL file "); } } } if (opb.CompressionBlock.DiffsToDelete != null) { foreach (var diff in opb.CompressionBlock.DiffsToDelete) { try { await diff.TryDeleteFileWithRetryAsync(); } catch (Exception e) { _logger.LogError(e, "Error while deleting DIFF file "); } } } } private void PrepareBoostRatio(CompressOption option, IEnumerable<CompressionBlock> buffer) { _logger.LogInformation("Requested order : "); int countFull = 0; int countDiff = 0; foreach (CompressionBlock block in buffer) { if (block.BackupMode == BackupMode.Full) { countFull++; } else { countDiff++; } } if (option.Threads > 1 && option.BoostRatio.HasValue) { if (countFull == 0 && countDiff > 0) { _logger.LogInformation($"100% diff ({countDiff}), running with X{option.BoostRatio.Value} more threads"); // boost mode when 100% of diff, we want to saturate iops : X mode option.Threads = Math.Min(option.Threads * option.BoostRatio.Value, countDiff); if (option.AzThread.HasValue) { option.AzThread = Math.Min(option.AzThread.Value * option.BoostRatio.Value, countDiff); } } else if (countFull != 0 && (countDiff / (double)(countFull + countDiff) >= 0.9)) { _logger.LogInformation($"{countFull} full, {countDiff} diffs, running with X{option.BoostRatio.Value} more threads"); // boost mode when 95% of diff, we want to saturate iops option.Threads = Math.Min(option.Threads * option.BoostRatio.Value, countDiff); if (option.AzThread.HasValue) { option.AzThread = Math.Min(option.AzThread.Value * option.BoostRatio.Value, countDiff); } } else { _logger.LogInformation($"No boost mode : {countFull} full, {countDiff} diffs"); } } } private async Task<OperationCompressionBlock> CompressionBlockInternal(CompressOption option, CompressionBlock block, CancellationToken token) { int count = Interlocked.Increment(ref _compressCounter); string progress = $"{count}/{_totalCounter}"; RetryContext ctx = null; CommandResult result = null; while (true) { bool hasError = false; try { string cmd = _compressionCommands.CompressCommand(block, option); result = await cmd.Run(block.OperationFolder, token); LogCompressionReport(block, result); if (result.HasError) { hasError = true; if (ctx == null && option.RetryPeriodInSeconds.HasValue) { ctx = new RetryContext(option.RetryPeriodInSeconds.Value); } } var report = $"{progress} [{block.BackupMode}] : {block.BlockName}"; if (block.BackupMode == BackupMode.Diff) { report += $" (from {block.DiffDate})"; } _logger.LogInformation(report); } catch (Exception e) { hasError = true; if (ctx == null && option.RetryPeriodInSeconds.HasValue) { ctx = new RetryContext(option.RetryPeriodInSeconds.Value); } _logger.LogCritical(e, $"{progress} Error compressing {block.Source}"); } if (hasError) { if (ctx != null && await ctx.WaitForNextRetry()) { _logger.LogWarning($"{progress} Retrying compressing {block.Source}, attempt #{ctx.Retries}"); await block.DestinationArchiveFileInfo.TryDeleteFileWithRetryAsync(); } else { await block.DestinationArchiveFileInfo.TryDeleteFileWithRetryAsync(); break; } } else { break; } } return new OperationCompressionBlock(block, result); } public async Task<OperationSummary> Decompress(DecompressOption option) { var sw = Stopwatch.StartNew(); var po = ParallelizeOption(option); var job = await _databaseHelper.InitializeRestoreJobAsync(); IEnumerable<DecompressionBatch> blocks = option.GenerateDecompressBlocks().ToList(); var prepare = new DatabasePreparedDecompressionBlocks(_serviceProvider.GetRequiredService<TccRestoreDbContext>(), _logger); IAsyncEnumerable<DecompressionBatch> ordered = prepare.PrepareDecompressionBlocksAsync(blocks); IReadOnlyCollection<OperationDecompressionsBlock> operationBlocks = await ordered .AsAsyncStream(_cancellationTokenSource.Token) .CountAsync(out var counter) // Prepare decryption .ParallelizeStreamAsync(async (b, token) => { b.StartTime = DateTime.UtcNow; await _encryptionCommands.PrepareDecryptionKey(b.BackupFull ?? b.BackupsDiff.FirstOrDefault(), option, token); return b; }, po) // Core loop .ParallelizeStreamAsync(async (batch, token) => { int count = Interlocked.Increment(ref _compressCounter); string progress = $"{count}/{_totalCounter}"; var blockResults = new List<BlockResult>(); if (batch.BackupFull != null) { batch.BackupFullCommandResult = await DecompressBlock(option, batch.BackupFull, token); blockResults.Add(new BlockResult(batch.BackupFull, batch.BackupFullCommandResult)); } if (batch.BackupsDiff != null) { batch.BackupDiffCommandResult = new CommandResult[batch.BackupsDiff.Length]; for (int i = 0; i < batch.BackupsDiff.Length; i++) { batch.BackupDiffCommandResult[i] = await DecompressBlock(option, batch.BackupsDiff[i], token); blockResults.Add(new BlockResult(batch.BackupsDiff[i], batch.BackupDiffCommandResult[i])); } } if (batch.BackupFull != null) { var report = $"{progress} [{BackupMode.Full}] : {batch.BackupFull.BlockName} (from {batch.BackupFull.BlockDate})"; _logger.LogInformation(report); } if (batch.BackupsDiff != null) { foreach (var dec in batch.BackupsDiff) { var report = $"{progress} [{BackupMode.Diff}] : {dec.BlockName} (from {dec.BlockDate})"; _logger.LogInformation(report); } } return new OperationDecompressionsBlock(blockResults, batch); }, po) // Cleanup loop .ParallelizeStreamAsync(async (odb, token) => { foreach (var b in odb.BlockResults) { await _encryptionCommands.CleanupKey(b.Block, option, Mode.Compress); } return odb; }, po) .AsReadOnlyCollectionAsync(); sw.Stop(); await _databaseHelper.AddRestoreBlockJobAsync(job, operationBlocks); await _databaseHelper.UpdateRestoreJobStatsAsync(sw, job); return new OperationSummary(operationBlocks, option.Threads, sw); } private async Task<CommandResult> DecompressBlock(DecompressOption option, DecompressionBlock block, CancellationToken token) { CommandResult result = null; try { string cmd = _compressionCommands.DecompressCommand(block, option); result = await cmd.Run(block.OperationFolder, token); LogReport(block, result); } catch (Exception e) { _logger.LogError(e, $"Error decompressing {block.Source}"); } return result; } private TccRestoreDbContext RestoreDb() { return _serviceProvider.GetRequiredService<TccRestoreDbContext>(); } private static ParallelizeOption ParallelizeOption(TccOption option) { var po = new ParallelizeOption { FailMode = option.FailFast ? Fail.Fast : Fail.Smart, MaxDegreeOfParallelism = option.Threads }; return po; } private void LogCompressionReport(CompressionBlock block, CommandResult result) { _logger.LogInformation($"Compressed {block.Source} in {result?.Elapsed.HumanizedTimeSpan()}, {block.DestinationArchiveFileInfo.Length.HumanizeSize()}, {block.DestinationArchiveFileInfo.FullName}"); if (result?.Infos.Any() ?? false) { _logger.LogWarning($"Compressed {block.Source} with warning : {string.Join(Environment.NewLine, result.Infos)}"); } if (result?.HasError ?? false) { _logger.LogError($"Compressed {block.Source} with errors : {result.Errors}"); } } private void LogReport(DecompressionBlock block, CommandResult result) { _logger.LogInformation($"Decompressed {block.Source} in {result?.Elapsed.HumanizedTimeSpan()}, {block.SourceArchiveFileInfo.Length.HumanizeSize()}, {block.SourceArchiveFileInfo.FullName}"); if (result?.Infos.Any() ?? false) { _logger.LogWarning($"Decompressed {block.Source} with warning : {string.Join(Environment.NewLine, result.Infos)}"); } if (result?.HasError ?? false) { _logger.LogError($"Decompressed {block.Source} with errors : {result.Errors}"); } } } }
41.799117
259
0.526116
[ "MIT" ]
LuccaSA/TarCompressCrypt
TCC.Lib/TarCompressCrypt.cs
18,937
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; //Reference - //https://docs.unity3d.com/ScriptReference/Physics.Raycast.html [RequireComponent(typeof(NavMeshAgent))] public class MobMoving : MonoBehaviour { NavMeshAgent _agent; public GameObject Player; public float Range = 10; public float AttackRange = 5; public float AttackCoolDown = 3f; public float Damage = 5f; float _coolDownTimer = 0; // Use this for initialization void Start () { _agent = GetComponent<NavMeshAgent>(); } // Update is called once per frame void Update () { if (Vector3.Distance(transform.position, Player.transform.position ) < Range) { MoveTo (Player.transform.position); AttackPlayer(); } AttackTimer(); } public void MoveTo(Vector3 point) { _agent.SetDestination(point); } public void OnDrawGizmos() { if (_agent != null) { Gizmos.color = new Color (255, 0, 0, 0.5f); Gizmos.DrawSphere (transform.position, Range); Gizmos.DrawLine (transform.position, _agent.destination); } } public void AttackPlayer() { RaycastHit _hit; if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out _hit, AttackRange) && _coolDownTimer == 0) { Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * _hit.distance, Color.yellow); //Debug.Log("Did Hit"); if (_hit.transform.CompareTag ("Player")) { _hit.transform.GetComponent<Health> ().TakeDamage (Damage); } } else { Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.white); //Debug.Log("Did not Hit"); } } public void AttackTimer() { if (_coolDownTimer == 0) { _coolDownTimer = AttackCoolDown; } if (_coolDownTimer > 0) { _coolDownTimer -= Time.deltaTime; } if (_coolDownTimer < 0) { _coolDownTimer = 0; } } }
25.918605
142
0.604755
[ "MIT" ]
CapNick/G54SPM
Assets/Scripts/AI/MobMoving.cs
2,231
C#
namespace Egnyte.Api.Files { public class FileOrFolderMetadata { internal FileOrFolderMetadata( bool isFolder, FolderExtendedMetadata foldesExtendedMetadata = null, FileMetadata fileMetadataResponse = null) { IsFolder = isFolder; AsFolder = foldesExtendedMetadata; AsFile = fileMetadataResponse; } public bool IsFolder { get; private set; } public FolderExtendedMetadata AsFolder { get; private set; } public FileMetadata AsFile { get; private set; } } }
26.909091
68
0.619932
[ "MIT" ]
BryanEllis/egnyte-dotnetcore
Egnyte.Core.Api/Files/FileOrFolderMetadata.cs
594
C#
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.IO; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenExprLambdaTests : CSharpTestBase { #region A string containing expression-tree dumping utilities const string ExpressionTestLibrary = @" using System; using System.Globalization; using System.Linq.Expressions; using System.Text; public class TestBase { protected static void DCheck<T>(Expression<T> e, string expected) { Check(e.Dump(), expected); } protected static void Check<T>(Expression<Func<T>> e, string expected) { Check(e.Dump(), expected); } protected static void Check<T1, T2>(Expression<Func<T1, T2>> e, string expected) { Check(e.Dump(), expected); } protected static void Check<T1, T2, T3>(Expression<Func<T1, T2, T3>> e, string expected) { Check(e.Dump(), expected); } protected static void Check<T1, T2, T3, T4>(Expression<Func<T1, T2, T3, T4>> e, string expected) { Check(e.Dump(), expected); } protected static string ToString<T>(Expression<Func<T>> e) { return e.Dump(); } protected static string ToString<T1, T2>(Expression<Func<T1, T2>> e) { return e.Dump(); } protected static string ToString<T1, T2, T3>(Expression<Func<T1, T2, T3>> e) { return e.Dump(); } private static void Check(string actual, string expected) { if (expected != actual) { Console.WriteLine(""FAIL""); Console.WriteLine(""expected: "" + expected); Console.WriteLine(""actual: "" + actual); // throw new Exception(""expected='"" + expected + ""'; actual='"" + actual + ""'""); } } } public static class ExpressionExtensions { public static string Dump<T>(this Expression<T> self) { return ExpressionPrinter.Print(self.Body); } } class ExpressionPrinter : System.Linq.Expressions.ExpressionVisitor { private StringBuilder s = new StringBuilder(); public static string Print(Expression e) { var p = new ExpressionPrinter(); p.Visit(e); return p.s.ToString(); } public override Expression Visit(Expression node) { if (node == null) { s.Append(""null""); return null; } s.Append(node.NodeType.ToString()); s.Append(""(""); base.Visit(node); s.Append("" Type:"" + node.Type); s.Append("")""); return null; } protected override MemberBinding VisitMemberBinding(MemberBinding node) { if (node == null) { s.Append(""null""); return null; } return base.VisitMemberBinding(node); } protected override MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding node) { s.Append(""MemberMemberBinding(Member=""); s.Append(node.Member.ToString()); foreach (var b in node.Bindings) { s.Append("" ""); VisitMemberBinding(b); } s.Append("")""); return null; } protected override MemberListBinding VisitMemberListBinding(MemberListBinding node) { s.Append(""MemberListBinding(Member=""); s.Append(node.Member.ToString()); foreach (var i in node.Initializers) { s.Append("" ""); VisitElementInit(i); } s.Append("")""); return null; } protected override MemberAssignment VisitMemberAssignment(MemberAssignment node) { s.Append(""MemberAssignment(Member=""); s.Append(node.Member.ToString()); s.Append("" Expression=""); Visit(node.Expression); s.Append("")""); return null; } protected override Expression VisitMemberInit(MemberInitExpression node) { s.Append(""NewExpression: ""); Visit(node.NewExpression); s.Append("" Bindings:[""); bool first = true; foreach (var b in node.Bindings) { if (!first) s.Append("" ""); VisitMemberBinding(b); first = false; } s.Append(""]""); return null; } protected override Expression VisitBinary(BinaryExpression node) { Visit(node.Left); s.Append("" ""); Visit(node.Right); if (node.Conversion != null) { s.Append("" Conversion:""); Visit(node.Conversion); } if (node.IsLifted) s.Append("" Lifted""); if (node.IsLiftedToNull) s.Append("" LiftedToNull""); if (node.Method != null) s.Append("" Method:["" + node.Method + ""]""); return null; } protected override Expression VisitConditional(ConditionalExpression node) { Visit(node.Test); s.Append("" ? ""); Visit(node.IfTrue); s.Append("" : ""); Visit(node.IfFalse); return null; } protected override Expression VisitConstant(ConstantExpression node) { // s.Append(node.Value == null ? ""null"" : node.Value.ToString()); s.Append(node.Value == null ? ""null"" : GetCultureInvariantString(node.Value)); return null; } protected override Expression VisitDefault(DefaultExpression node) { return null; } protected override Expression VisitIndex(IndexExpression node) { Visit(node.Object); s.Append(""[""); int n = node.Arguments.Count; for (int i = 0; i < n; i++) { if (i != 0) s.Append("" ""); Visit(node.Arguments[i]); } s.Append(""]""); if (node.Indexer != null) s.Append("" Indexer:"" + node.Indexer); return null; } protected override Expression VisitInvocation(InvocationExpression node) { Visit(node.Expression); s.Append(""(""); int n = node.Arguments.Count; for (int i = 0; i < n; i++) { if (i != 0) s.Append("" ""); Visit(node.Arguments[i]); } s.Append("")""); return null; } protected override Expression VisitLambda<T>(Expression<T> node) { s.Append(""(""); int n = node.Parameters.Count; for (int i = 0; i < n; i++) { if (i != 0) s.Append("" ""); Visit(node.Parameters[i]); } s.Append("") => ""); if (node.Name != null) s.Append(node.Name); Visit(node.Body); if (node.ReturnType != null) s.Append("" ReturnType:"" + node.ReturnType); if (node.TailCall) s.Append("" TailCall""); return null; } protected override Expression VisitListInit(ListInitExpression node) { Visit(node.NewExpression); s.Append(""{""); int n = node.Initializers.Count; for (int i = 0; i < n; i++) { if (i != 0) s.Append("" ""); Visit(node.Initializers[i]); } s.Append(""}""); return null; } protected override ElementInit VisitElementInit(ElementInit node) { Visit(node); return null; } private void Visit(ElementInit node) { s.Append(""ElementInit(""); s.Append(node.AddMethod); int n = node.Arguments.Count; for (int i = 0; i < n; i++) { s.Append("" ""); Visit(node.Arguments[i]); } s.Append("")""); } protected override Expression VisitMember(MemberExpression node) { Visit(node.Expression); s.Append("".""); s.Append(node.Member.Name); return null; } protected override Expression VisitMethodCall(MethodCallExpression node) { Visit(node.Object); s.Append("".["" + node.Method + ""]""); s.Append(""(""); int n = node.Arguments.Count; for (int i = 0; i < n; i++) { if (i != 0) s.Append("", ""); Visit(node.Arguments[i]); } s.Append("")""); return null; } protected override Expression VisitNew(NewExpression node) { s.Append((node.Constructor != null) ? ""["" + node.Constructor + ""]"" : ""<.ctor>""); s.Append(""(""); int n = node.Arguments.Count; for (int i = 0; i < n; i++) { if (i != 0) s.Append("", ""); Visit(node.Arguments[i]); } s.Append("")""); if (node.Members != null) { n = node.Members.Count; if (n != 0) { s.Append(""{""); for (int i = 0; i < n; i++) { var info = node.Members[i]; if (i != 0) s.Append("" ""); s.Append(info); } s.Append(""}""); } } return null; } protected override Expression VisitNewArray(NewArrayExpression node) { s.Append(""[""); int n = node.Expressions.Count; for (int i = 0; i < n; i++) { if (i != 0) s.Append("" ""); Visit(node.Expressions[i]); } s.Append(""]""); return null; } protected override Expression VisitParameter(ParameterExpression node) { s.Append(node.Name); if (node.IsByRef) s.Append("" ByRef""); return null; } protected override Expression VisitTypeBinary(TypeBinaryExpression node) { Visit(node.Expression); s.Append("" TypeOperand:"" + node.TypeOperand); return null; } protected override Expression VisitUnary(UnaryExpression node) { Visit(node.Operand); if (node.IsLifted) s.Append("" Lifted""); if (node.IsLiftedToNull) s.Append("" LiftedToNull""); if (node.Method != null) s.Append("" Method:["" + node.Method + ""]""); return null; } public static string GetCultureInvariantString(object value) { var valueType = value.GetType(); if (valueType == typeof(string)) { return value as string; } if (valueType == typeof(DateTime)) { return ((DateTime)value).ToString(""M/d/yyyy h:mm:ss tt"", CultureInfo.InvariantCulture); } if (valueType == typeof(float)) { return ((float)value).ToString(CultureInfo.InvariantCulture); } if (valueType == typeof(double)) { return ((double)value).ToString(CultureInfo.InvariantCulture); } if (valueType == typeof(decimal)) { return ((decimal)value).ToString(CultureInfo.InvariantCulture); } return value.ToString(); } } "; #endregion A string containing expression-tree dumping utilities [WorkItem(544283, "DevDiv")] [Fact] public void MissingLibrary() { string program = @" using System; using System.Linq.Expressions; class Program { static void Main() { Expression<Func<int>> e = () => 1; } } namespace System.Linq.Expressions { class Expression<T> { } }"; CreateCompilationWithMscorlibAndSystemCore(program).Emit(new System.IO.MemoryStream()).Diagnostics .Verify( // (9,9): warning CS0436: The type 'System.Linq.Expressions.Expression<T>' in '' conflicts with the imported type 'System.Linq.Expressions.Expression<TDelegate>' in 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''. // Expression<Func<int>> e = () => 1; Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Expression<Func<int>>").WithArguments("", "System.Linq.Expressions.Expression<T>", "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Linq.Expressions.Expression<TDelegate>"), // (9,35): error CS0656: Missing compiler required member 'System.Linq.Expressions.Expression.Lambda' // Expression<Func<int>> e = () => 1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "() => 1").WithArguments("System.Linq.Expressions.Expression", "Lambda") ); } [WorkItem(543322, "DevDiv")] [Fact] public void CaptureParameterCallAddition() { string program = @"using System; delegate D D(int x); class Program : TestBase { public static D F(int n) { Console.WriteLine(n); return null; } public static void Main(string[] args) { int z = 1; DCheck<D>( x => y => F(x+y+z), ""Lambda((Parameter(y Type:System.Int32)) => Call(null.[D F(Int32)](Add(Add(Parameter(x Type:System.Int32) Parameter(y Type:System.Int32) Type:System.Int32) MemberAccess(Constant(Program+<>c__DisplayClass0 Type:Program+<>c__DisplayClass0).z Type:System.Int32) Type:System.Int32)) Type:D) ReturnType:D Type:D)""); Console.Write('k'); } }"; CompileAndVerify( sources: new string[] { program, ExpressionTestLibrary }, additionalRefs: new[] { SystemCoreRef }, expectedOutput: @"k") .VerifyDiagnostics(); } [WorkItem(543322, "DevDiv")] [Fact] public void ExpressionConversionInExpression() { string program = @"using System; using System.Linq.Expressions; delegate Expression<D> D(int x); class Program : TestBase { public static Expression<D> F(int n) { Console.WriteLine(n); return null; } public static void Main(string[] args) { int z = 1; DCheck<D>( x => y => F(x + y + z), ""Quote(Lambda((Parameter(y Type:System.Int32)) => Call(null.[System.Linq.Expressions.Expression`1[D] F(Int32)](Add(Add(Parameter(x Type:System.Int32) Parameter(y Type:System.Int32) Type:System.Int32) MemberAccess(Constant(Program+<>c__DisplayClass0 Type:Program+<>c__DisplayClass0).z Type:System.Int32) Type:System.Int32)) Type:System.Linq.Expressions.Expression`1[D]) ReturnType:System.Linq.Expressions.Expression`1[D] Type:D) Type:System.Linq.Expressions.Expression`1[D])""); Console.Write('k'); } }"; CompileAndVerify( sources: new string[] { program, ExpressionTestLibrary }, additionalRefs: new[] { SystemCoreRef }, expectedOutput: @"k") .VerifyDiagnostics(); } [Fact] public void Addition() { var source = @"using System; class UD { public static UD operator +(UD l, UD r) { return null; } } struct UDS { public static UDS operator +(UDS l, UDS r) { return default(UDS); } } class Program : TestBase { public static void Main(string[] args) { Check<int, int, int>( (l, r) => l + r, ""Add(Parameter(l Type:System.Int32) Parameter(r Type:System.Int32) Type:System.Int32)""); Check<UD, UD, UD>( (l, r) => l + r, ""Add(Parameter(l Type:UD) Parameter(r Type:UD) Method:[UD op_Addition(UD, UD)] Type:UD)""); checked { Check<int, int, int>( (l, r) => l + r, ""AddChecked(Parameter(l Type:System.Int32) Parameter(r Type:System.Int32) Type:System.Int32)""); Check<int?, int?, int?>( (l, r) => l + r, ""AddChecked(Parameter(l Type:System.Nullable`1[System.Int32]) Parameter(r Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32])""); Check<UD, UD, UD>( (l, r) => l + r, ""Add(Parameter(l Type:UD) Parameter(r Type:UD) Method:[UD op_Addition(UD, UD)] Type:UD)""); } Check<int?, int?, int?>( (l, r) => l + r, ""Add(Parameter(l Type:System.Nullable`1[System.Int32]) Parameter(r Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32])""); Check<UDS, UDS, UDS>( (l, r) => l + r, ""Add(Parameter(l Type:UDS) Parameter(r Type:UDS) Method:[UDS op_Addition(UDS, UDS)] Type:UDS)""); Check<decimal, decimal, decimal>( (x, y) => x + y, ""Add(Parameter(x Type:System.Decimal) Parameter(y Type:System.Decimal) Method:[System.Decimal op_Addition(System.Decimal, System.Decimal)] Type:System.Decimal)""); Check<string, string, string>( (x, y) => x + y, ""Add(Parameter(x Type:System.String) Parameter(y Type:System.String) Method:[System.String Concat(System.String, System.String)] Type:System.String)""); Check<string, int, string>( (x, y) => x + y, ""Add(Parameter(x Type:System.String) Convert(Parameter(y Type:System.Int32) Type:System.Object) Method:[System.String Concat(System.Object, System.Object)] Type:System.String)""); Check<int, string, string>( (x, y) => x + y, ""Add(Convert(Parameter(x Type:System.Int32) Type:System.Object) Parameter(y Type:System.String) Method:[System.String Concat(System.Object, System.Object)] Type:System.String)""); Check<Action, Action, Action>( (x, y) => x + y, ""Convert(Add(Parameter(x Type:System.Action) Parameter(y Type:System.Action) Method:[System.Delegate Combine(System.Delegate, System.Delegate)] Type:System.Delegate) Type:System.Action)""); Check<int?, int?>( x => x + null, ""Add(Parameter(x Type:System.Nullable`1[System.Int32]) Constant(null Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32])""); Console.Write('k'); } }"; var compilation = CompileAndVerify( new string[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: @"k"); } [WorkItem(544027, "DevDiv")] [Fact] void AnonymousCreation() { var source = @"using System; class Program : TestBase { public static void Main(string[] args) { Check<int, string, object>( (i, s) => new { A = i, B = s }, ""New([Void .ctor(Int32, System.String)](Parameter(i Type:System.Int32), Parameter(s Type:System.String)){Int32 A System.String B} Type:<>f__AnonymousType0`2[System.Int32,System.String])""); Console.Write('k'); } }"; var compilation = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: @"k"); } [WorkItem(544028, "DevDiv")] [Fact] void ArrayIndex() { var source = @"using System; class Program : TestBase { public static void Main(string[] args) { Check<int, string>( i => args[i], ""ArrayIndex(MemberAccess(Constant(Program+<>c__DisplayClass0 Type:Program+<>c__DisplayClass0).args Type:System.String[]) Parameter(i Type:System.Int32) Type:System.String)""); string[,] s2 = new string[2, 2]; Check<int, string>( i => s2[i,i], ""Call(MemberAccess(Constant(Program+<>c__DisplayClass0 Type:Program+<>c__DisplayClass0).s2 Type:System.String[,]).[System.String Get(Int32, Int32)](Parameter(i Type:System.Int32), Parameter(i Type:System.Int32)) Type:System.String)""); Console.Write('k'); } }"; var compilation = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: @"k"); } [WorkItem(544029, "DevDiv")] [Fact] void ArrayCreation() { var source = @"using System; class Program : TestBase { public static void Main(string[] args) { Check<int, int[]>( i => new int[i], ""NewArrayBounds([Parameter(i Type:System.Int32)] Type:System.Int32[])""); Check<int, int[,]>( i => new int[i,i], ""NewArrayBounds([Parameter(i Type:System.Int32) Parameter(i Type:System.Int32)] Type:System.Int32[,])""); Console.Write('k'); } }"; var compilation = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: @"k"); } [WorkItem(544030, "DevDiv")] [Fact] void ArrayInitialization() { var source = @"using System; class Program : TestBase { public static void Main(string[] args) { Check<int, int[]>( i => new[] { i, i }, ""NewArrayInit([Parameter(i Type:System.Int32) Parameter(i Type:System.Int32)] Type:System.Int32[])""); Console.Write('k'); } }"; var compilation = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: @"k"); } [WorkItem(544112, "DevDiv")] [Fact] void CS0838ERR_ExpressionTreeContainsMultiDimensionalArrayInitializer() { var source = @"using System; using System.Linq.Expressions; class Program { public static void Main(string[] args) { Expression<Func<int, int[,]>> x = i => new[,] {{ i }}; } }"; CreateCompilationWithMscorlibAndSystemCore(source).VerifyDiagnostics( // (7,48): error CS0838: An expression tree may not contain a multidimensional array initializer // Expression<Func<int, int[,]>> x = i => new[,] {{ i }}; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsMultiDimensionalArrayInitializer, "new[,] {{ i }}") ); } [WorkItem(544031, "DevDiv")] [Fact] void ArrayLength() { var source = @"using System; class Program : TestBase { public static void Main(string[] args) { Check<int[], int>( s => s.Length, ""ArrayLength(Parameter(s Type:System.Int32[]) Type:System.Int32)""); Check<int[,], int>( a => a.Length, ""MemberAccess(Parameter(a Type:System.Int32[,]).Length Type:System.Int32)""); Console.Write('k'); } }"; var compilation = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: @"k"); } [WorkItem(544032, "DevDiv")] [Fact] void AsOperator() { var source = @"using System; class Program : TestBase { public static void Main(string[] args) { Check<object, string>( o => (o as string), ""TypeAs(Parameter(o Type:System.Object) Type:System.String)""); Console.Write('k'); } }"; var compilation = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: "k"); } [WorkItem(544034, "DevDiv")] [Fact] void BaseReference() { var source = @"using System; class Program0 : TestBase { protected virtual string M() { return ""base""; } } class Program : Program0 { protected override string M() { return ""derived""; } public static void Main(string[] args) { new Program().Main(); } void Main() { Check<string>( () => base.M(), """"); Console.Write('k'); } }"; CreateCompilationWithMscorlibAndSystemCore(new[] { Parse(source), Parse(ExpressionTestLibrary) }).VerifyDiagnostics( // (265,19): error CS0831: An expression tree may not contain a base access // () => base.M(), ""); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsBaseAccess, "base") ); } [Fact(Skip = "BadTestCode")] void AsyncLambda() { var source = @"using System; class Program : TestBase { public static void Main(string[] args) { Check<Task<int>, Task<int>>( async x => (await x), ""); Console.Write('k'); } }"; var compilation = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }).VerifyDiagnostics( // error CS1989: Async lambda expressions cannot be converted to expression trees Diagnostic((ErrorCode)1989) ); } [WorkItem(544035, "DevDiv")] [Fact] void Multiply() { var source = @"using System; class UD { public static UD operator *(UD l, UD r) { return null; } } struct UDS { public static UDS operator *(UDS l, UDS r) { return default(UDS); } } class Program : TestBase { public static void Main(string[] args) { Check<int, int, int>( (l, r) => l * r, ""Multiply(Parameter(l Type:System.Int32) Parameter(r Type:System.Int32) Type:System.Int32)""); Check<UD, UD, UD>( (l, r) => l * r, ""Multiply(Parameter(l Type:UD) Parameter(r Type:UD) Method:[UD op_Multiply(UD, UD)] Type:UD)""); checked { Check<int, int, int>( (l, r) => l * r, ""MultiplyChecked(Parameter(l Type:System.Int32) Parameter(r Type:System.Int32) Type:System.Int32)""); Check<int?, int?, int?>( (l, r) => l * r, ""MultiplyChecked(Parameter(l Type:System.Nullable`1[System.Int32]) Parameter(r Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32])""); Check<UD, UD, UD>( (l, r) => l * r, ""Multiply(Parameter(l Type:UD) Parameter(r Type:UD) Method:[UD op_Multiply(UD, UD)] Type:UD)""); } Check<int?, int?, int?>( (l, r) => l * r, ""Multiply(Parameter(l Type:System.Nullable`1[System.Int32]) Parameter(r Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32])""); Check<UDS, UDS, UDS>( (l, r) => l * r, ""Multiply(Parameter(l Type:UDS) Parameter(r Type:UDS) Method:[UDS op_Multiply(UDS, UDS)] Type:UDS)""); Console.Write('k'); } }"; var compilation = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: "k"); } [WorkItem(544036, "DevDiv")] [Fact] void Subtract() { var source = @"using System; class UD { public static UD operator -(UD l, UD r) { return null; } } struct UDS { public static UDS operator -(UDS l, UDS r) { return default(UDS); } } class Program : TestBase { public static void Main(string[] args) { Check<int, int, int>( (l, r) => l - r, ""Subtract(Parameter(l Type:System.Int32) Parameter(r Type:System.Int32) Type:System.Int32)""); Check<UD, UD, UD>( (l, r) => l - r, ""Subtract(Parameter(l Type:UD) Parameter(r Type:UD) Method:[UD op_Subtraction(UD, UD)] Type:UD)""); checked { Check<int, int, int>( (l, r) => l - r, ""SubtractChecked(Parameter(l Type:System.Int32) Parameter(r Type:System.Int32) Type:System.Int32)""); Check<int?, int?, int?>( (l, r) => l - r, ""SubtractChecked(Parameter(l Type:System.Nullable`1[System.Int32]) Parameter(r Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32])""); Check<UD, UD, UD>( (l, r) => l - r, ""Subtract(Parameter(l Type:UD) Parameter(r Type:UD) Method:[UD op_Subtraction(UD, UD)] Type:UD)""); } Check<int?, int?, int?>( (l, r) => l - r, ""Subtract(Parameter(l Type:System.Nullable`1[System.Int32]) Parameter(r Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32])""); Check<UDS, UDS, UDS>( (l, r) => l - r, ""Subtract(Parameter(l Type:UDS) Parameter(r Type:UDS) Method:[UDS op_Subtraction(UDS, UDS)] Type:UDS)""); Check<Action, Action, Action>( (x, y) => x - y, ""Convert(Subtract(Parameter(x Type:System.Action) Parameter(y Type:System.Action) Method:[System.Delegate Remove(System.Delegate, System.Delegate)] Type:System.Delegate) Type:System.Action)""); Console.Write('k'); } }"; var compilation = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: "k"); } [WorkItem(544037, "DevDiv")] [Fact] void Divide() { var source = @"using System; class UD { public static UD operator /(UD l, UD r) { return null; } } struct UDS { public static UDS operator /(UDS l, UDS r) { return default(UDS); } } class Program : TestBase { public static void Main(string[] args) { Check<int, int, int>( (l, r) => l / r, ""Divide(Parameter(l Type:System.Int32) Parameter(r Type:System.Int32) Type:System.Int32)""); Check<UD, UD, UD>( (l, r) => l / r, ""Divide(Parameter(l Type:UD) Parameter(r Type:UD) Method:[UD op_Division(UD, UD)] Type:UD)""); checked { Check<int, int, int>( (l, r) => l / r, ""Divide(Parameter(l Type:System.Int32) Parameter(r Type:System.Int32) Type:System.Int32)""); Check<int?, int?, int?>( (l, r) => l / r, ""Divide(Parameter(l Type:System.Nullable`1[System.Int32]) Parameter(r Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32])""); Check<UD, UD, UD>( (l, r) => l / r, ""Divide(Parameter(l Type:UD) Parameter(r Type:UD) Method:[UD op_Division(UD, UD)] Type:UD)""); } Check<int?, int?, int?>( (l, r) => l / r, ""Divide(Parameter(l Type:System.Nullable`1[System.Int32]) Parameter(r Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32])""); Check<UDS, UDS, UDS>( (l, r) => l / r, ""Divide(Parameter(l Type:UDS) Parameter(r Type:UDS) Method:[UDS op_Division(UDS, UDS)] Type:UDS)""); Console.Write('k'); } }"; var compilation = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: "k"); } [WorkItem(544038, "DevDiv")] [Fact] void Remainder() { var source = @"using System; class UD { public static UD operator %(UD l, UD r) { return null; } } struct UDS { public static UDS operator %(UDS l, UDS r) { return default(UDS); } } class Program : TestBase { public static void Main(string[] args) { Check<int, int, int>( (l, r) => l % r, ""Modulo(Parameter(l Type:System.Int32) Parameter(r Type:System.Int32) Type:System.Int32)""); Check<UD, UD, UD>( (l, r) => l % r, ""Modulo(Parameter(l Type:UD) Parameter(r Type:UD) Method:[UD op_Modulus(UD, UD)] Type:UD)""); checked { Check<int, int, int>( (l, r) => l % r, ""Modulo(Parameter(l Type:System.Int32) Parameter(r Type:System.Int32) Type:System.Int32)""); Check<int?, int?, int?>( (l, r) => l % r, ""Modulo(Parameter(l Type:System.Nullable`1[System.Int32]) Parameter(r Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32])""); Check<UD, UD, UD>( (l, r) => l % r, ""Modulo(Parameter(l Type:UD) Parameter(r Type:UD) Method:[UD op_Modulus(UD, UD)] Type:UD)""); } Check<int?, int?, int?>( (l, r) => l % r, ""Modulo(Parameter(l Type:System.Nullable`1[System.Int32]) Parameter(r Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32])""); Check<UDS, UDS, UDS>( (l, r) => l % r, ""Modulo(Parameter(l Type:UDS) Parameter(r Type:UDS) Method:[UDS op_Modulus(UDS, UDS)] Type:UDS)""); Console.Write('k'); } }"; var compilation = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: "k"); } [WorkItem(544041, "DevDiv")] [Fact] void And() { var source = @"using System; class UD { public static UD operator &(UD l, UD r) { return null; } } struct UDS { public static UDS operator &(UDS l, UDS r) { return default(UDS); } } class Program : TestBase { public static void Main(string[] args) { Check<int, int, int>( (l, r) => l & r, ""And(Parameter(l Type:System.Int32) Parameter(r Type:System.Int32) Type:System.Int32)""); Check<UD, UD, UD>( (l, r) => l & r, ""And(Parameter(l Type:UD) Parameter(r Type:UD) Method:[UD op_BitwiseAnd(UD, UD)] Type:UD)""); checked { Check<int, int, int>( (l, r) => l & r, ""And(Parameter(l Type:System.Int32) Parameter(r Type:System.Int32) Type:System.Int32)""); Check<int?, int?, int?>( (l, r) => l & r, ""And(Parameter(l Type:System.Nullable`1[System.Int32]) Parameter(r Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32])""); Check<UD, UD, UD>( (l, r) => l & r, ""And(Parameter(l Type:UD) Parameter(r Type:UD) Method:[UD op_BitwiseAnd(UD, UD)] Type:UD)""); } Check<int?, int?, int?>( (l, r) => l & r, ""And(Parameter(l Type:System.Nullable`1[System.Int32]) Parameter(r Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32])""); Check<UDS, UDS, UDS>( (l, r) => l & r, ""And(Parameter(l Type:UDS) Parameter(r Type:UDS) Method:[UDS op_BitwiseAnd(UDS, UDS)] Type:UDS)""); Console.Write('k'); } }"; var compilation = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: "k"); } [WorkItem(544042, "DevDiv")] [Fact] void ExclusiveOr() { var source = @"using System; class UD { public static UD operator ^(UD l, UD r) { return null; } } struct UDS { public static UDS operator ^(UDS l, UDS r) { return default(UDS); } } class Program : TestBase { public static void Main(string[] args) { Check<int, int, int>( (l, r) => l ^ r, ""ExclusiveOr(Parameter(l Type:System.Int32) Parameter(r Type:System.Int32) Type:System.Int32)""); Check<UD, UD, UD>( (l, r) => l ^ r, ""ExclusiveOr(Parameter(l Type:UD) Parameter(r Type:UD) Method:[UD op_ExclusiveOr(UD, UD)] Type:UD)""); checked { Check<int, int, int>( (l, r) => l ^ r, ""ExclusiveOr(Parameter(l Type:System.Int32) Parameter(r Type:System.Int32) Type:System.Int32)""); Check<int?, int?, int?>( (l, r) => l ^ r, ""ExclusiveOr(Parameter(l Type:System.Nullable`1[System.Int32]) Parameter(r Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32])""); Check<UD, UD, UD>( (l, r) => l ^ r, ""ExclusiveOr(Parameter(l Type:UD) Parameter(r Type:UD) Method:[UD op_ExclusiveOr(UD, UD)] Type:UD)""); } Check<int?, int?, int?>( (l, r) => l ^ r, ""ExclusiveOr(Parameter(l Type:System.Nullable`1[System.Int32]) Parameter(r Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32])""); Check<UDS, UDS, UDS>( (l, r) => l ^ r, ""ExclusiveOr(Parameter(l Type:UDS) Parameter(r Type:UDS) Method:[UDS op_ExclusiveOr(UDS, UDS)] Type:UDS)""); Console.Write('k'); } }"; var compilation = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: "k"); } [WorkItem(544043, "DevDiv")] [Fact] void BitwiseOr() { var source = @"using System; class UD { public static UD operator |(UD l, UD r) { return null; } } struct UDS { public static UDS operator |(UDS l, UDS r) { return default(UDS); } } class Program : TestBase { public static void Main(string[] args) { Check<int, int, int>( (l, r) => l | r, ""Or(Parameter(l Type:System.Int32) Parameter(r Type:System.Int32) Type:System.Int32)""); Check<UD, UD, UD>( (l, r) => l | r, ""Or(Parameter(l Type:UD) Parameter(r Type:UD) Method:[UD op_BitwiseOr(UD, UD)] Type:UD)""); checked { Check<int, int, int>( (l, r) => l | r, ""Or(Parameter(l Type:System.Int32) Parameter(r Type:System.Int32) Type:System.Int32)""); Check<int?, int?, int?>( (l, r) => l | r, ""Or(Parameter(l Type:System.Nullable`1[System.Int32]) Parameter(r Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32])""); Check<UD, UD, UD>( (l, r) => l | r, ""Or(Parameter(l Type:UD) Parameter(r Type:UD) Method:[UD op_BitwiseOr(UD, UD)] Type:UD)""); } Check<int?, int?, int?>( (l, r) => l | r, ""Or(Parameter(l Type:System.Nullable`1[System.Int32]) Parameter(r Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32])""); Check<UDS, UDS, UDS>( (l, r) => l | r, ""Or(Parameter(l Type:UDS) Parameter(r Type:UDS) Method:[UDS op_BitwiseOr(UDS, UDS)] Type:UDS)""); Console.Write('k'); } }"; var compilation = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: "k"); } [WorkItem(544039, "DevDiv"), WorkItem(544040, "DevDiv")] [Fact] void MoreBinaryOperators() { var source = @"using System; struct S { } class Program : TestBase { public static void Main(string[] args) { Check<int, int, int>( (l, r) => (l<<r) + (l>>r), ""Add(LeftShift(Parameter(l Type:System.Int32) Parameter(r Type:System.Int32) Type:System.Int32) RightShift(Parameter(l Type:System.Int32) Parameter(r Type:System.Int32) Type:System.Int32) Type:System.Int32)""); Check<int, int, bool>( (l, r) => (l == r), ""Equal(Parameter(l Type:System.Int32) Parameter(r Type:System.Int32) Type:System.Boolean)""); Check<int, int, bool>( (l, r) => (l != r), ""NotEqual(Parameter(l Type:System.Int32) Parameter(r Type:System.Int32) Type:System.Boolean)""); Check<int, int, bool>( (l, r) => (l < r), ""LessThan(Parameter(l Type:System.Int32) Parameter(r Type:System.Int32) Type:System.Boolean)""); Check<int, int, bool>( (l, r) => (l <= r), ""LessThanOrEqual(Parameter(l Type:System.Int32) Parameter(r Type:System.Int32) Type:System.Boolean)""); Check<int, int, bool>( (l, r) => (l > r), ""GreaterThan(Parameter(l Type:System.Int32) Parameter(r Type:System.Int32) Type:System.Boolean)""); Check<int, int, bool>( (l, r) => (l >= r), ""GreaterThanOrEqual(Parameter(l Type:System.Int32) Parameter(r Type:System.Int32) Type:System.Boolean)""); Check<int?, bool>( x => x == null, ""Equal(Parameter(x Type:System.Nullable`1[System.Int32]) Constant(null Type:System.Nullable`1[System.Int32]) Lifted Type:System.Boolean)""); Check<S?, bool>( x => x == null, ""Equal(Parameter(x Type:System.Nullable`1[S]) Constant(null Type:System.Nullable`1[S]) Lifted Type:System.Boolean)""); Console.Write('k'); } }"; var compilation = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: "k"); } [WorkItem(544059, "DevDiv")] [Fact] void UnaryOperators() { var source = @"using System; class UD { public static UD operator +(UD l) { return null; } } struct UDS { public static UDS operator +(UDS l) { return default(UDS); } } class Program : TestBase { public static void Main(string[] args) { Check<int, int>( x => +x, ""Parameter(x Type:System.Int32)""); Check<UD, UD>( x => +x, ""UnaryPlus(Parameter(x Type:UD) Method:[UD op_UnaryPlus(UD)] Type:UD)""); Check<UDS, UDS>( x => +x, ""UnaryPlus(Parameter(x Type:UDS) Method:[UDS op_UnaryPlus(UDS)] Type:UDS)""); Check<int, int>( x => -x, ""Negate(Parameter(x Type:System.Int32) Type:System.Int32)""); Check<int, int>( x => checked (-x), ""NegateChecked(Parameter(x Type:System.Int32) Type:System.Int32)""); Check<int, int>( x => ~x, ""Not(Parameter(x Type:System.Int32) Type:System.Int32)""); Check<bool, bool>( x => !x, ""Not(Parameter(x Type:System.Boolean) Type:System.Boolean)""); Console.Write('k'); } }"; var compilation = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: "k"); } [Fact] void GrabBag01() { var source = @"using System; using System.Linq.Expressions; struct S { } class C { } delegate int D(int x); class Program : TestBase { static int M(int x) { Console.Write(x); return x+1; } public static void Main(string[] args) { Check<bool, int, int, int>( (x, y, z) => x ? y : z, ""Conditional(Parameter(x Type:System.Boolean) ? Parameter(y Type:System.Int32) : Parameter(z Type:System.Int32) Type:System.Int32)""); Check<int>( () => default(int), ""Constant(0 Type:System.Int32)""); Main2<int>(""Constant(0 Type:System.Int32)""); Check<C>( () => default(C), ""Constant(null Type:C)""); Main2<C>(""Constant(null Type:C)""); Check<S>( () => default(S), ""Constant(S Type:S)""); Main2<S>(""Constant(S Type:S)""); Check<Func<int>, int>( x => x(), ""Invoke(Parameter(x Type:System.Func`1[System.Int32])() Type:System.Int32)""); // // The precise form of a delegate creation depends on your platform version! // Check<Func<int, int>>( // () => M, // ""Convert(Call(null.CreateDelegate(Constant(System.Func`2[System.Int32,System.Int32] Type:System.Type), Constant(null Type:System.Object), Constant(Int32 M(Int32) Type:MethodInfo)) Type:Delegate) Type:Func`2)""); Expression<Func<Func<int, int>>> f = () => M; f.Compile()()(1); // Check<Func<int, int>>( // () => new Func<int, int>(M), // ""Convert(Call(null.CreateDelegate(Constant(System.Func`2[System.Int32,System.Int32] Type:System.Type), Constant(null Type:System.Object), Constant(Int32 M(Int32) Type:MethodInfo)) Type:Delegate) Type:Func`2)""); f = () => new Func<int, int>(M); f.Compile()()(2); // Check<D, Func<int, int>>( // d => new Func<int, int>(d), // ""Convert(Call(null.CreateDelegate(Constant(System.Func`2[System.Int32,System.Int32] Type:System.Type), Convert(Parameter(d Type:D) Type:System.Object), Constant(Int32 Invoke(Int32) Type:MethodInfo)) Type:Delegate) Type:Func`2)""); D q = M; f = () => new Func<int, int>(q); f.Compile()()(3); Console.Write('k'); } public static void Main2<T>(string expected) { Check<T>(() => default(T), expected); } }"; var compilation = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: "123k"); } [WorkItem(546147, "DevDiv")] [Fact] void DelegateInvoke() { var source = @"using System; using System.Linq.Expressions; class P { static void Main() { Func<int, int> f = c => c + 1; Expression<Func<int>> expr = () => f(12); Console.WriteLine(expr.Dump()); Console.WriteLine(expr); } }"; var compilation = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: @"Invoke(MemberAccess(Constant(P+<>c__DisplayClass0 Type:P+<>c__DisplayClass0).f Type:System.Func`2[System.Int32,System.Int32])(Constant(12 Type:System.Int32)) Type:System.Int32) () => Invoke(value(P+<>c__DisplayClass0).f, 12)"); } [Fact] void GrabBag02() { var source = @"using System; class Array { public int this[int x] { get { return 0; } } } struct S { } class C { public static C operator &(C c1, C c2) { return c1; } public static C operator |(C c1, C c2) { return c1; } public static bool operator true(C c) { return false; } public static bool operator false(C c) { return false; } } class Program : TestBase { public event Action InstanceEvent; public static event Action StaticEvent; public static void Main2<T>(string expected) where T : new() { Check<T>( () => new T(), expected); } public static void Main(string[] args) { Check<Array, int, int>( (a, i) => a[i], ""Call(Parameter(a Type:Array).[Int32 get_Item(Int32)](Parameter(i Type:System.Int32)) Type:System.Int32)""); Check<object, bool>( o => o is string, ""TypeIs(Parameter(o Type:System.Object) TypeOperand:System.String Type:System.Boolean)""); Main2<int>(""New(<.ctor>() Type:System.Int32)""); Main2<object>(""New([Void .ctor()]() Type:System.Object)""); Check<string, object, object>( (a, b) => a ?? b, ""Coalesce(Parameter(a Type:System.String) Parameter(b Type:System.Object) Type:System.Object)""); Check<string, Exception>( (s) => new Exception(s), ""New([Void .ctor(System.String)](Parameter(s Type:System.String)) Type:System.Exception)""); Check<int>( () => new int(), ""Constant(0 Type:System.Int32)""); Check<S>( () => new S(), ""New(<.ctor>() Type:S)""); Check<Type>( () => typeof(string), ""Constant(System.String Type:System.Type)""); Check<C, C, C>( (l, r) => l && r, ""AndAlso(Parameter(l Type:C) Parameter(r Type:C) Method:[C op_BitwiseAnd(C, C)] Type:C)""); Check<C, C, C>( (l, r) => l || r, ""OrElse(Parameter(l Type:C) Parameter(r Type:C) Method:[C op_BitwiseOr(C, C)] Type:C)""); Check<int[]>( () => new int[] { 1, 2, 3 }, ""NewArrayInit([Constant(1 Type:System.Int32) Constant(2 Type:System.Int32) Constant(3 Type:System.Int32)] Type:System.Int32[])""); Check<Program, Action>( p => p.InstanceEvent, ""MemberAccess(Parameter(p Type:Program).InstanceEvent Type:System.Action)""); Check<Action>( () => Program.StaticEvent, ""MemberAccess(null.StaticEvent Type:System.Action)""); Check<string, string, bool>( (x, y) => x == y, ""Equal(Parameter(x Type:System.String) Parameter(y Type:System.String) Method:[Boolean op_Equality(System.String, System.String)] Type:System.Boolean)""); DCheck<Action>( () => Console.WriteLine((object)null), ""Call(null.[Void WriteLine(System.Object)](Constant(null Type:System.Object)) Type:System.Void)""); Console.Write('k'); } }"; var compilation = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: "k"); } [Fact] void UnsafeExprTree() { var source = @"using System; using System.Linq.Expressions; struct S {} class Program { public unsafe static void Main(string[] args) { int* p = null; Expression<Func<int>> efi = () => *p; Expression<Func<int>> efi2 = () => sizeof(S); } }"; var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.UnsafeReleaseDll); c.VerifyDiagnostics( // (9,43): error CS1944: An expression tree may not contain an unsafe pointer operation // Expression<Func<int>> efi = () => *p; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, "*p"), // (10,44): error CS1944: An expression tree may not contain an unsafe pointer operation // Expression<Func<int>> efi2 = () => sizeof(S); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, "sizeof(S)") ); } [WorkItem(544044, "DevDiv")] [Fact] void CollectionInitialization() { var source = @"using System; class Program : TestBase { public static void Main(string[] args) { Check<System.Collections.Generic.List<int>>( () => new System.Collections.Generic.List<int> { 1, 2, 3 }, ""ListInit(New([Void .ctor()]() Type:System.Collections.Generic.List`1[System.Int32]){ElementInit(Void Add(Int32) Constant(1 Type:System.Int32)) ElementInit(Void Add(Int32) Constant(2 Type:System.Int32)) ElementInit(Void Add(Int32) Constant(3 Type:System.Int32))} Type:System.Collections.Generic.List`1[System.Int32])""); Console.Write('k'); } }"; var compilation = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: "k"); } [WorkItem(544390, "DevDiv")] [Fact] void ObjectInitialization() { var source = @"using System; using System.Collections.Generic; using System.Linq.Expressions; public class Node { public Node A; public Node B { set; get; } public List<Node> C = new List<Node>(); public List<Node> D { set; get; } } class Program : TestBase { public static void N(Expression<Func<Node, Node>> e) { Console.WriteLine(e.Dump()); } public static void Main(string[] args) { N(x => new Node { A = x }); N(x => new Node { B = x }); N(x => new Node { A = { A = { A = x } } }); N(x => new Node { B = { B = { B = x } } }); N(x => new Node { B = { B = { C = { x, x } } } }); N(x => new Node { C = { x, x } }); N(x => new Node { D = { x, x } }); } }"; var expectedOutput = @"MemberInit(NewExpression: New([Void .ctor()]() Type:Node) Bindings:[MemberAssignment(Member=Node A Expression=Parameter(x Type:Node))] Type:Node) MemberInit(NewExpression: New([Void .ctor()]() Type:Node) Bindings:[MemberAssignment(Member=Node B Expression=Parameter(x Type:Node))] Type:Node) MemberInit(NewExpression: New([Void .ctor()]() Type:Node) Bindings:[MemberMemberBinding(Member=Node A MemberMemberBinding(Member=Node A MemberAssignment(Member=Node A Expression=Parameter(x Type:Node))))] Type:Node) MemberInit(NewExpression: New([Void .ctor()]() Type:Node) Bindings:[MemberMemberBinding(Member=Node B MemberMemberBinding(Member=Node B MemberAssignment(Member=Node B Expression=Parameter(x Type:Node))))] Type:Node) MemberInit(NewExpression: New([Void .ctor()]() Type:Node) Bindings:[MemberMemberBinding(Member=Node B MemberMemberBinding(Member=Node B MemberListBinding(Member=System.Collections.Generic.List`1[Node] C ElementInit(Void Add(Node) Parameter(x Type:Node)) ElementInit(Void Add(Node) Parameter(x Type:Node)))))] Type:Node) MemberInit(NewExpression: New([Void .ctor()]() Type:Node) Bindings:[MemberListBinding(Member=System.Collections.Generic.List`1[Node] C ElementInit(Void Add(Node) Parameter(x Type:Node)) ElementInit(Void Add(Node) Parameter(x Type:Node)))] Type:Node) MemberInit(NewExpression: New([Void .ctor()]() Type:Node) Bindings:[MemberListBinding(Member=System.Collections.Generic.List`1[Node] D ElementInit(Void Add(Node) Parameter(x Type:Node)) ElementInit(Void Add(Node) Parameter(x Type:Node)))] Type:Node)"; var compilation = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: expectedOutput); } [Fact] void Lambda() { var source = @"using System; using System.Linq.Expressions; class L : TestBase { public L Select(Expression<Func<int, int>> f) { Check(f, ""Parameter(y Type:System.Int32)""); return this; } } partial class Program { public static void Main(string[] args) { L el = new L(); var x = from y in el select y; Console.Write('k'); } }"; var compilation = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: "k"); } [WorkItem(544218, "DevDiv")] [Fact] void Linq() { var source = @"using System; using System.Linq; using System.Linq.Expressions; class A { static void Main() { Expression<Func<string[], object>> e = s => from x in s from y in s orderby x descending select x; Console.WriteLine(e.ToString()); } }"; var compilation = CompileAndVerify( new[] { source }, new[] { ExpressionAssemblyRef }, expectedOutput: "s => s.SelectMany(x => s, (x, y) => new <>f__AnonymousType0`2(x = x, y = y)).OrderByDescending(<>h__TransparentIdentifier0 => <>h__TransparentIdentifier0.x).Select(<>h__TransparentIdentifier0 => <>h__TransparentIdentifier0.x)"); } [Fact] void Enum() { var source = @"using System; enum Color { Red } partial class Program : TestBase { public static void Main(string[] args) { Check<Color, int, Color>( (x, y) => x + y, ""Convert(Add(Convert(Parameter(x Type:Color) Type:System.Int32) Parameter(y Type:System.Int32) Type:System.Int32) Type:Color)""); Check<int, Color, Color>( (x, y) => x + y, ""Convert(Add(Parameter(x Type:System.Int32) Convert(Parameter(y Type:Color) Type:System.Int32) Type:System.Int32) Type:Color)""); Check<Color?, int?, Color?>( (x, y) => x + y, ""Convert(Add(Convert(Parameter(x Type:System.Nullable`1[Color]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Parameter(y Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[Color])""); Check<int?, Color?, Color?>( (x, y) => x + y, ""Convert(Add(Parameter(x Type:System.Nullable`1[System.Int32]) Convert(Parameter(y Type:System.Nullable`1[Color]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[Color])""); Check<Color, Color, bool>( (x, y) => x < y, ""LessThan(Convert(Parameter(x Type:Color) Type:System.Int32) Convert(Parameter(y Type:Color) Type:System.Int32) Type:System.Boolean)""); Check<Color?, Color?, bool>( (x, y) => x < y, ""LessThan(Convert(Parameter(x Type:System.Nullable`1[Color]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Convert(Parameter(y Type:System.Nullable`1[Color]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted Type:System.Boolean)""); Console.Write('k'); } }"; var compilation = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: "k"); } [Fact] public void CoalesceAndConversions() { var text = @"using System; class D { public static implicit operator int(D d) { return 0; } public static implicit operator D(int i) { return null; } } public struct S { public static implicit operator S(decimal d) { return new S(); } } partial class Program : TestBase { public static void Main(string[] args) { Check<D, D, D>( (x, y) => x ?? y, ""Coalesce(Parameter(x Type:D) Parameter(y Type:D) Type:D)""); Check<int?, int, int>( (x, y) => x ?? y, ""Coalesce(Parameter(x Type:System.Nullable`1[System.Int32]) Parameter(y Type:System.Int32) Type:System.Int32)""); Check<int?, int?, int?>( (x, y) => x ?? y, ""Coalesce(Parameter(x Type:System.Nullable`1[System.Int32]) Parameter(y Type:System.Nullable`1[System.Int32]) Type:System.Nullable`1[System.Int32])""); Check<D, int, int>( (x, y) => x ?? y, ""Convert(Coalesce(Parameter(x Type:D) Convert(Parameter(y Type:System.Int32) Method:[D op_Implicit(Int32)] Type:D) Type:D) Method:[Int32 op_Implicit(D)] Type:System.Int32)""); Check<D, int?, int?>( (x, y) => x ?? y, ""Convert(Convert(Coalesce(Parameter(x Type:D) Convert(Parameter(y Type:System.Nullable`1[System.Int32]) Lifted Method:[D op_Implicit(Int32)] Type:D) Type:D) Method:[Int32 op_Implicit(D)] Type:System.Int32) Lifted LiftedToNull Type:System.Nullable`1[System.Int32])""); Check<int?, D, long?>( (x, y) => x ?? y, ""Convert(Convert(Coalesce(Parameter(x Type:System.Nullable`1[System.Int32]) Convert(Parameter(y Type:D) Method:[Int32 op_Implicit(D)] Type:System.Int32) Type:System.Int32) Type:System.Int64) Lifted LiftedToNull Type:System.Nullable`1[System.Int64])""); Check<short?, int, long?>( (x, y) => x ?? y, ""Convert(Convert(Coalesce(Parameter(x Type:System.Nullable`1[System.Int16]) Parameter(y Type:System.Int32) Type:System.Int32) Type:System.Int64) Lifted LiftedToNull Type:System.Nullable`1[System.Int64])""); Check<IntPtr, DayOfWeek>( // 12549 x => (DayOfWeek)x, ""Convert(Convert(Parameter(x Type:System.IntPtr) Method:[Int32 op_Explicit(IntPtr)] Type:System.Int32) Type:System.DayOfWeek)""); Check<int, S?>( x => x, ""Convert(Convert(Convert(Parameter(x Type:System.Int32) Method:[System.Decimal op_Implicit(Int32)] Type:System.Decimal) Method:[S op_Implicit(System.Decimal)] Type:S) Lifted LiftedToNull Type:System.Nullable`1[S])""); // the native compiler gets the following wrong (thereby generating bad code!) We therefore handle the expression tree differently Func<int?, S?> f = x => x; Console.WriteLine(P(f(null))); Console.WriteLine(P(f(1))); } static string P(S? s) { return (s == null) ? ""null"" : ""S""; } }"; var compilation = CompileAndVerify( new[] { text, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: @"null S"); } #region Regression Tests [WorkItem(544159, "DevDiv")] [Fact] public void BinaryAddOperandTypesEnumAndInt() { var text = @" using System; using System.Linq.Expressions; public enum color { Red, Green, Blue }; class Test { static void Main() { Expression<Func<color, int, color>> testExpr = (x, y) => x + y; var result = testExpr.Compile()(color.Red, 1); Console.WriteLine(result); } }"; CompileAndVerify(text, new[] { ExpressionAssemblyRef }, expectedOutput: "Green"); } [WorkItem(544207, "DevDiv")] [Fact] public void BinaryAddOperandTypesStringAndString() { var text = @" using System; using System.Linq; using System.Linq.Expressions; class Test { public static void Main() { Expression<Func<string, string, string>> testExpr = (x, y) => x + y; var result = testExpr.Compile()(""Hello "", ""World!""); Console.WriteLine(result); } } "; CompileAndVerify(text, new[] { ExpressionAssemblyRef }, expectedOutput: "Hello World!"); } [WorkItem(544226, "DevDiv")] [Fact] public void BinaryAddOperandTypesDelegate() { var text = @" using System; using System.Linq; using System.Linq.Expressions; public delegate string Del(int i); class Test { public static void Main() { Expression<Func<Del, Del, Del>> testExpr = (x, y) => x + y; Console.WriteLine(testExpr); } }"; CompileAndVerify(text, new[] { ExpressionAssemblyRef }, expectedOutput: "(x, y) => Convert((x + y))"); } [WorkItem(544187, "DevDiv")] [Fact] public void EnumLogicalOperators() { var text = @" using System; using System.Linq; using System.Linq.Expressions; public enum color { Red, Green, Blue }; class Test { public static void Main() { Expression<Func<color, color, color>> testExpr1 = (x, y) => x & y; var result1 = testExpr1.Compile()(color.Red, color.Green); Expression<Func<color, color, color>> testExpr2 = (x, y) => x | y; var result2 = testExpr2.Compile()(color.Red, color.Green); Expression<Func<color, color, color>> testExpr3 = (x, y) => x ^ y; var result3 = testExpr3.Compile()(color.Red, color.Green); Console.WriteLine(""{0}, {1}, {2}"", result1, result2, result3); } }"; CompileAndVerify(text, new[] { ExpressionAssemblyRef }, expectedOutput: "Red, Green, Green"); } [WorkItem(544171, "DevDiv")] [Fact] public void GenericInterfacePropertyAccess() { var text = @" using System.Linq.Expressions; using System; using System.Linq; class Test { public interface ITest<T> { T Key { get; } } public static void Main() { Expression<Func<ITest<int>, int>> e = (var1) => var1.Key; } }"; CompileAndVerify(text, new[] { ExpressionAssemblyRef }, expectedOutput: ""); } [WorkItem(544171, "DevDiv")] [Fact] public void GenericFieldAccess() { var text = @" using System.Linq.Expressions; using System; using System.Linq; class Test { public class ITest<T> { public T Key; } public static void Main() { Expression<Func<ITest<int>, int>> e = (var1) => var1.Key; } }"; CompileAndVerify(text, new[] { ExpressionAssemblyRef }, expectedOutput: ""); } [WorkItem(544185, "DevDiv")] [Fact] public void UnaryPlusOperandNullableInt() { var text = @"using System; using System.Linq.Expressions; class Test { public static void Main() { Expression<Func<int?, int?>> e = (x) => +x; ExpressionVisitor ev = new ExpressionVisitor(); ev.Visit(e); Console.Write(ev.toStr); } }"; string expectedOutput = @" Lambda: Type->System.Func`2[System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] Parameters-> Parameter: Type->System.Nullable`1[System.Int32] Name->x Body-> Parameter: Type->System.Nullable`1[System.Int32] Name->x "; CompileAndVerify( new[] { text, TreeWalkerLib }, new[] { ExpressionAssemblyRef }, expectedOutput: TrimExpectedOutput(expectedOutput)); } [WorkItem(544213, "DevDiv")] [Fact] public void DelegateInvocation() { var text = @"using System; using System.Linq.Expressions; class Test { delegate int MultFunc(int a, int b); public static void Main() { Expression<Func<MultFunc, int>> testExpr = (mf) => mf(3, 4); ExpressionVisitor ev = new ExpressionVisitor(); ev.Visit(testExpr); Console.Write(ev.toStr); } }"; string expectedOutput = @" Lambda: Type->System.Func`2[Test+MultFunc,System.Int32] Parameters-> Parameter: Type->Test+MultFunc Name->mf Body-> Invoke: Type->System.Int32 Arguments-> Constant: Type->System.Int32 Value->3 Constant: Type->System.Int32 Value->4 Lambda-> Parameter: Type->Test+MultFunc Name->mf "; CompileAndVerify( new[] { text, TreeWalkerLib }, new[] { ExpressionAssemblyRef }, expectedOutput: TrimExpectedOutput(expectedOutput)); } [WorkItem(544220, "DevDiv")] [Fact] public void CoalesceWithLiftedImplicitUDC() { var text = @"using System; using System.Linq.Expressions; public class SampClass1 { public static implicit operator SampClass1(decimal d) { return new SampClass1(); } } class Test { public static void Main() { Expression<Func<SampClass1>> testExpr = () => new decimal?(5) ?? new SampClass1(); } }"; CompileAndVerify( new[] { text, TreeWalkerLib }, new[] { ExpressionAssemblyRef }, expectedOutput: ""); } [WorkItem(544222, "DevDiv")] [Fact] public void CoalesceWithImplicitUDC() { var text = @"using System; using System.Linq.Expressions; public class SampClass1 { } public class SampClass2 { public static implicit operator SampClass1(SampClass2 sc1) { return new SampClass1(); } } class A { static void Main() { Expression<Func<SampClass1, SampClass2, SampClass1>> testExpr = (x, y) => x ?? y; Console.WriteLine(testExpr); } }"; CompileAndVerify( new[] { text, TreeWalkerLib }, new[] { ExpressionAssemblyRef }, expectedOutput: "(x, y) => (x ?? Convert(y))"); } [WorkItem(546156, "DevDiv"), WorkItem(546157, "DevDiv")] [Fact] public void CoalesceWithImplicitUDCFromNullable01() { var text = @"using System; using System.Linq.Expressions; public struct CT0 { } public struct CT2 { public static implicit operator CT0(CT2? c) { throw new Exception(""this conversion is not needed during execution of this test""); } } public struct CT3 { public static implicit operator CT0?(CT3? c) { return null; } } public class Program { static void Main() { Func<CT2?, CT0, CT0> lambda1 = (c1, c2) => c1 ?? c2; Expression<Func<CT2?, CT0, CT0>> e104 = (c1, c2) => c1 ?? c2; Console.WriteLine(e104.Dump()); Func<CT2?, CT0, CT0> lambda2 = e104.Compile(); Console.WriteLine(lambda1(null, new CT0())); Console.WriteLine(lambda2(null, new CT0())); Expression<Func<CT3?, CT0?, CT0?>> e105 = (c1, c2) => c1 ?? c2; Console.WriteLine(e105.Dump()); } }"; CompileAndVerify( new[] { text, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: @"Coalesce(Parameter(c1 Type:System.Nullable`1[CT2]) Parameter(c2 Type:CT0) Conversion:Lambda((Parameter(p Type:CT2)) => Convert(Convert(Parameter(p Type:CT2) Lifted LiftedToNull Type:System.Nullable`1[CT2]) Method:[CT0 op_Implicit(System.Nullable`1[CT2])] Type:CT0) ReturnType:CT0 Type:System.Func`2[CT2,CT0]) Type:CT0) CT0 CT0 Coalesce(Parameter(c1 Type:System.Nullable`1[CT3]) Parameter(c2 Type:System.Nullable`1[CT0]) Conversion:Lambda((Parameter(p Type:CT3)) => Convert(Convert(Parameter(p Type:CT3) Lifted LiftedToNull Type:System.Nullable`1[CT3]) Method:[System.Nullable`1[CT0] op_Implicit(System.Nullable`1[CT3])] Type:System.Nullable`1[CT0]) ReturnType:System.Nullable`1[CT0] Type:System.Func`2[CT3,System.Nullable`1[CT0]]) Type:System.Nullable`1[CT0])"); } [WorkItem(544248, "DevDiv")] [Fact] public void CoalesceWithImplicitUDC2() { var text = @"using System; using System.Linq.Expressions; public struct SampStruct { public static implicit operator int(SampStruct ss1) { return 1; } } public class Test { static void Main() { Expression<Func<SampStruct?, decimal, decimal>> testExpr = (x, y) => x ?? y; Console.WriteLine(testExpr.Compile()(new SampStruct(), 5)); Console.WriteLine(testExpr.Dump()); } }"; CompileAndVerify( new[] { text, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: @"1 Coalesce(Parameter(x Type:System.Nullable`1[SampStruct]) Parameter(y Type:System.Decimal) Conversion:Lambda((Parameter(p Type:SampStruct)) => Convert(Convert(Parameter(p Type:SampStruct) Method:[Int32 op_Implicit(SampStruct)] Type:System.Int32) Method:[System.Decimal op_Implicit(Int32)] Type:System.Decimal) ReturnType:System.Decimal Type:System.Func`2[SampStruct,System.Decimal]) Type:System.Decimal)" ); } [Fact, WorkItem(544223, "DevDiv"), WorkItem(546146, "DevDiv")] public void CoalesceWithLiftedImplicitPDC() { var text = @"using System; class Test : TestBase { public static void Main() { Console.WriteLine(ToString<short?, int, long?>((x, y) => x ?? y)); Console.WriteLine(ToString<long?, int?>(x => (int?)x)); Console.WriteLine(ToString<long, int?>(x => (int?)x)); Console.WriteLine(ToString<long?, int>(x => (int)x)); Console.WriteLine(ToString<int, long?>(x => x)); checked { Console.WriteLine(ToString<short?, int, long?>((x, y) => x ?? y)); Console.WriteLine(ToString<long?, int?>(x => (int?)x)); Console.WriteLine(ToString<long, int?>(x => (int?)x)); Console.WriteLine(ToString<long?, int>(x => (int)x)); Console.WriteLine(ToString<int, long?>(x => x)); } } }"; var expectedOutput = @"Convert(Convert(Coalesce(Parameter(x Type:System.Nullable`1[System.Int16]) Parameter(y Type:System.Int32) Type:System.Int32) Type:System.Int64) Lifted LiftedToNull Type:System.Nullable`1[System.Int64]) Convert(Parameter(x Type:System.Nullable`1[System.Int64]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Convert(Parameter(x Type:System.Int64) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Convert(Parameter(x Type:System.Nullable`1[System.Int64]) Lifted Type:System.Int32) Convert(Convert(Parameter(x Type:System.Int32) Type:System.Int64) Lifted LiftedToNull Type:System.Nullable`1[System.Int64]) ConvertChecked(ConvertChecked(Coalesce(Parameter(x Type:System.Nullable`1[System.Int16]) Parameter(y Type:System.Int32) Type:System.Int32) Type:System.Int64) Lifted LiftedToNull Type:System.Nullable`1[System.Int64]) ConvertChecked(Parameter(x Type:System.Nullable`1[System.Int64]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) ConvertChecked(Parameter(x Type:System.Int64) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) ConvertChecked(Parameter(x Type:System.Nullable`1[System.Int64]) Lifted Type:System.Int32) ConvertChecked(ConvertChecked(Parameter(x Type:System.Int32) Type:System.Int64) Lifted LiftedToNull Type:System.Nullable`1[System.Int64])"; CompileAndVerify( new[] { text, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: expectedOutput); } [WorkItem(544228, "DevDiv")] [Fact] public void NewOfDecimal() { var text = @"using System; using System.Linq.Expressions; class Test { public static void Main() { Expression<Func<decimal>> testExpr = () => new decimal(); ExpressionVisitor ev = new ExpressionVisitor(); ev.Visit(testExpr); Console.Write(ev.toStr); } }"; string expectedOutput = @" Lambda: Type->System.Func`1[System.Decimal] Parameters-> Body-> Constant: Type->System.Decimal Value->0 "; CompileAndVerify( new[] { text, TreeWalkerLib }, new[] { ExpressionAssemblyRef }, expectedOutput: TrimExpectedOutput(expectedOutput)); } [WorkItem(544241, "DevDiv")] [Fact] public void ArrayIndexTypeLong() { var text = @"using System; using System.Linq.Expressions; public class Test { static void Main() { Expression<Func<string[], long, string>> testExpr = (str, i) => str[i]; Console.WriteLine(testExpr); } }"; string expectedOutput = @"(str, i) => str[ConvertChecked(i)]"; CompileAndVerify( new[] { text, TreeWalkerLib }, new[] { ExpressionAssemblyRef }, expectedOutput: TrimExpectedOutput(expectedOutput)); } [WorkItem(544240, "DevDiv")] [Fact] public void EventAssignment() { var source = @"using System.Linq.Expressions; public delegate void A(D d); public delegate void B(); public class C { public event B B1;} public class D : C { public event B B2; static void Main() { Expression<A> e = x => x.B2 += (B)null; } }"; CreateCompilationWithMscorlibAndSystemCore(source) .VerifyDiagnostics( // (11,32): error CS0832: An expression tree may not contain an assignment operator // Expression<A> e = x => x.B2 += (B)null; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "x.B2 += (B)null"), // (5,33): warning CS0067: The event 'C.B1' is never used // public class C { public event B B1;} Diagnostic(ErrorCode.WRN_UnreferencedEvent, "B1").WithArguments("C.B1"), // (8,20): warning CS0067: The event 'D.B2' is never used // public event B B2; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "B2").WithArguments("D.B2") ); } [WorkItem(544233, "DevDiv")] [Fact] public void UnsafePointerAddition() { var source = @"using System.Linq.Expressions; class Program { unsafe delegate int* D1(int* i); static void Main(string[] args) { unsafe { Expression<D1> testExpr = (x) => x + 1; } } }"; var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.UnsafeReleaseDll); c.VerifyDiagnostics( // (10,46): error CS1944: An expression tree may not contain an unsafe pointer operation // Expression<D1> testExpr = (x) => x + 1; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, "x")); } [WorkItem(544276, "DevDiv")] [Fact] public void UnsafeParamTypeInDelegate() { var text = @" using System; using System.Linq; using System.Linq.Expressions; unsafe public class Test { delegate int* UnsafeFunc(int* x); static int* G(int* x) { return x; } static void Main() { Expression<UnsafeFunc> testExpr = (x) => G(x); Console.WriteLine(testExpr); } }"; string expectedOutput = @"x => G(x)"; CompileAndVerify(text, new[] { ExpressionAssemblyRef }, options: TestOptions.UnsafeReleaseExe, expectedOutput: TrimExpectedOutput(expectedOutput)); } [WorkItem(544246, "DevDiv")] [Fact] public void MethodCallWithParams() { var text = @"using System; using System.Linq.Expressions; public class Test { public static int ModAdd2(params int[] b) { return 0; } static void Main() { Expression<Func<int>> testExpr = () => ModAdd2(); Console.WriteLine(testExpr); } }"; string expectedOutput = @"() => ModAdd2(new [] {})"; CompileAndVerify( text, new[] { ExpressionAssemblyRef }, expectedOutput: TrimExpectedOutput(expectedOutput)); } [WorkItem(544270, "DevDiv")] [Fact] public void MethodCallWithParams2() { var text = @"using System; using System.Linq.Expressions; public class Test { public static int ModAdd2(params int[] b) { return 0; } static void Main() { Expression<Func<int>> testExpr = () => ModAdd2(0, 1); Console.WriteLine(testExpr); } }"; string expectedOutput = @"() => ModAdd2(new [] {0, 1})"; CompileAndVerify(text, new[] { ExpressionAssemblyRef }, expectedOutput: TrimExpectedOutput(expectedOutput)); } [Fact] public void MethodCallWithParams3() { var text = @"using System; using System.Linq.Expressions; public class Test { public static int ModAdd2(int x = 3, int y = 4, params int[] b) { return 0; } static void Main() { Expression<Func<int>> testExpr = () => ModAdd2(); Console.WriteLine(testExpr); } }"; CreateCompilationWithMscorlibAndSystemCore(text) .VerifyDiagnostics( // (10,48): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments // Expression<Func<int>> testExpr = () => ModAdd2(); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, "ModAdd2()") ); } [WorkItem(544419, "DevDiv")] [Fact] public void ExplicitUDC2() { var text = @"using System; using System.Linq.Expressions; public class Test { public static explicit operator int(Test x) { return 1; } static void Main() { Expression<Func<Test, long?>> testExpr = x => (long?)x; ExpressionVisitor ev = new ExpressionVisitor(); ev.Visit(testExpr); Console.Write(ev.toStr); } }"; var expectedOutput = @" Lambda: Type->System.Func`2[Test,System.Nullable`1[System.Int64]] Parameters-> Parameter: Type->Test Name->x Body-> Convert: Type->System.Nullable`1[System.Int64] Method-> IsLifted->True IsLiftedToNull->True Operand-> Convert: Type->System.Int64 Method-> IsLifted->False IsLiftedToNull->False Operand-> Convert: Type->System.Int32 Method->Int32 op_Explicit(Test) IsLifted->False IsLiftedToNull->False Operand-> Parameter: Type->Test Name->x "; CompileAndVerify( new[] { text, TreeWalkerLib }, new[] { ExpressionAssemblyRef }, expectedOutput: TrimExpectedOutput(expectedOutput)); } [WorkItem(544027, "DevDiv")] [Fact] public void AnonTypes1() { var text = @"using System; using System.Linq.Expressions; public class Test { static void Main() { Expression<Func<int>> testExpr = () => new { Name = ""Bill"", Salary = 6950.85m, Age = 45 }.Age; Console.WriteLine(testExpr.Compile()()); } }"; CompileAndVerify(text, new[] { ExpressionAssemblyRef }, expectedOutput: "45"); } [Fact] public void AnonTypes2() { var text = @"using System; using System.Linq.Expressions; public class Test { static void Main() { Expression<Func<object>> testExpr = () => new { Name = ""Bill"", Salary = 6950.85m, Age = 45 }; Console.WriteLine(testExpr.Dump()); } }"; CompileAndVerify( new[] { text, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: "New([Void .ctor(System.String, System.Decimal, Int32)](Constant(Bill Type:System.String), Constant(6950.85 Type:System.Decimal), Constant(45 Type:System.Int32)){System.String Name System.Decimal Salary Int32 Age} Type:<>f__AnonymousType0`3[System.String,System.Decimal,System.Int32])"); } [WorkItem(544252, "DevDiv")] [Fact] public void EqualsWithOperandsNullableStructAndNull() { var text = @" using System; using System.Linq.Expressions; public struct StructType { } public class Test { static void Main() { Expression<Func<StructType?, bool>> testExpr = (x) => x == null; Console.WriteLine(testExpr.Compile()(new StructType())); } }"; CompileAndVerify(text, new[] { ExpressionAssemblyRef }, expectedOutput: "False"); } [WorkItem(544254, "DevDiv")] [Fact] public void GreaterThanUD1() { var text = @" using System; using System.Linq.Expressions; struct JoinRec { public static bool operator >(JoinRec a, JoinRec b) { return true; } public static bool operator <(JoinRec a, JoinRec b) { return false; } } public class Test { static void Main() { Expression<Func<JoinRec, JoinRec, bool>> testExpr = (x, y) => x > y; Console.WriteLine(testExpr.Compile()(new JoinRec(), new JoinRec())); } }"; CompileAndVerify(text, new[] { ExpressionAssemblyRef }, expectedOutput: "True"); } [WorkItem(544255, "DevDiv")] [Fact] public void ExpressionTreeAndOperatorOverloading() { var text = @" using System; using System.Linq; using System.Linq.Expressions; public class R { public static int value = 0; static public R operator +(R r, Expression<Func<R, R>> e) { Func<R, R> fun = e.Compile(); return r; } static public R operator +(R r1, R r2) { return r1; } public static int Test2() { R.value = 0; R r = new R(); r = r + ((R c) => (c + ((R d) => (d + d)))); return R.value; } } public class Test { static void Main() { Console.WriteLine(R.Test2()); } }"; CompileAndVerify(text, new[] { ExpressionAssemblyRef }, expectedOutput: "0"); } [WorkItem(544269, "DevDiv")] [Fact] public void CheckedImplicitConversion() { var text = @"using System; using System.Linq.Expressions; class Test { public static void Main() { Expression<Func<int, long, long>> testExpr = (x, y) => checked(x + y); ExpressionVisitor ev = new ExpressionVisitor(); ev.Visit(testExpr); Console.Write(ev.toStr); } }"; string expectedOutput = @" Lambda: Type->System.Func`3[System.Int32,System.Int64,System.Int64] Parameters-> Parameter: Type->System.Int32 Name->x Parameter: Type->System.Int64 Name->y Body-> AddChecked: Type->System.Int64 Method-> IsLifted->False IsLiftedToNull->False Left-> ConvertChecked: Type->System.Int64 Method-> IsLifted->False IsLiftedToNull->False Operand-> Parameter: Type->System.Int32 Name->x Right-> Parameter: Type->System.Int64 Name->y "; CompileAndVerify( new[] { text, TreeWalkerLib }, new[] { ExpressionAssemblyRef }, expectedOutput: TrimExpectedOutput(expectedOutput)); } [WorkItem(544304, "DevDiv")] [Fact] public void CheckedEnumAddition() { var text = @"using System; class Test : TestBase { public enum color { Red, Blue, Green }; public static void Main() { Check<color, int, color>( (x, y) => checked(x + y), ""ConvertChecked(AddChecked(ConvertChecked(Parameter(x Type:Test+color) Type:System.Int32) Parameter(y Type:System.Int32) Type:System.Int32) Type:Test+color)""); } }"; CompileAndVerify( new[] { text, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: ""); } [WorkItem(544275, "DevDiv")] [Fact] public void SizeOf() { var text = @" using System; using System.Linq.Expressions; public class Test { static void Main() { Expression<Func<int>> testExpr = () => sizeof(int); Console.WriteLine(testExpr); } }"; CompileAndVerify(text, new[] { ExpressionAssemblyRef }, expectedOutput: "() => 4"); } [WorkItem(544285, "DevDiv")] [Fact] public void ImplicitReferenceConversion() { var text = @"using System; using System.Linq.Expressions; public class Test { static void Main() { Expression<Func<string, object>> testExpr = x => x; ExpressionVisitor ev = new ExpressionVisitor(); ev.Visit(testExpr); Console.Write(ev.toStr); } }"; string expectedOutput = @" Lambda: Type->System.Func`2[System.String,System.Object] Parameters-> Parameter: Type->System.String Name->x Body-> Parameter: Type->System.String Name->x "; CompileAndVerify( new[] { text, TreeWalkerLib }, new[] { ExpressionAssemblyRef }, expectedOutput: TrimExpectedOutput(expectedOutput)); } [WorkItem(544287, "DevDiv")] [Fact] public void ExplicitIdentityConversion() { var text = @"using System; using System.Linq.Expressions; public class Test { static void Main() { Expression<Func<int, int>> testExpr = (num1) => (int)num1; ExpressionVisitor ev = new ExpressionVisitor(); ev.Visit(testExpr); Console.Write(ev.toStr); } }"; string expectedOutput = @" Lambda: Type->System.Func`2[System.Int32,System.Int32] Parameters-> Parameter: Type->System.Int32 Name->num1 Body-> Convert: Type->System.Int32 Method-> IsLifted->False IsLiftedToNull->False Operand-> Parameter: Type->System.Int32 Name->num1 "; CompileAndVerify( new[] { text, TreeWalkerLib }, new[] { ExpressionAssemblyRef }, expectedOutput: TrimExpectedOutput(expectedOutput)); } [WorkItem(544411, "DevDiv")] [Fact] public void ExplicitConvIntToNullableInt() { var text = @"using System; using System.Linq.Expressions; public class Test { static void Main() { Expression<Func<int, int?>> testExpr = (num1) => (int?)num1; ExpressionVisitor ev = new ExpressionVisitor(); ev.Visit(testExpr); Console.Write(ev.toStr); } }"; string expectedOutput = @" Lambda: Type->System.Func`2[System.Int32,System.Nullable`1[System.Int32]] Parameters-> Parameter: Type->System.Int32 Name->num1 Body-> Convert: Type->System.Nullable`1[System.Int32] Method-> IsLifted->True IsLiftedToNull->True Operand-> Parameter: Type->System.Int32 Name->num1 "; CompileAndVerify( new[] { text, TreeWalkerLib }, new[] { ExpressionAssemblyRef }, expectedOutput: TrimExpectedOutput(expectedOutput)); } [WorkItem(544277, "DevDiv")] [Fact] public void ConvertExtensionMethodToDelegate() { var text = @"using System; using System.Linq; using System.Linq.Expressions; class A { static void Main() { Expression<Func<Func<bool>>> x = () => ""ABC"".Any; Console.WriteLine(x.Compile()()()); } }"; string expectedOutput = @"True"; CompileAndVerify(text, new[] { ExpressionAssemblyRef }, expectedOutput: expectedOutput); } [WorkItem(544306, "DevDiv")] [Fact] public void ExplicitConversionNullToNullableType() { var text = @"using System; using System.Linq.Expressions; public class Test { static void Main() { Expression<Func<short?>> testExpr = () => (short?)null; ExpressionVisitor ev = new ExpressionVisitor(); ev.Visit(testExpr); Console.Write(ev.toStr); } }"; string expectedOutput = @" Lambda: Type->System.Func`1[System.Nullable`1[System.Int16]] Parameters-> Body-> Convert: Type->System.Nullable`1[System.Int16] Method-> IsLifted->True IsLiftedToNull->True Operand-> Constant: Type->System.Object Value-> "; CompileAndVerify( new[] { text, TreeWalkerLib }, new[] { ExpressionAssemblyRef }, expectedOutput: TrimExpectedOutput(expectedOutput)); } [WorkItem(544295, "DevDiv")] [Fact] public void LiftedEquality() { var text = @"using System; using System.Linq.Expressions; class Program { static void Main() { Expression<Action> e = () => Console.WriteLine(default(DateTime) == null); e.Compile()(); } }"; string expectedOutput = @"False"; CompileAndVerify(text, new[] { ExpressionAssemblyRef }, expectedOutput: expectedOutput); } [WorkItem(544396, "DevDiv")] [Fact] public void UserDefinedOperatorWithPointerType() { var text = @"using System; using System.Linq.Expressions; unsafe class Test { struct PtrRec { public static int operator +(PtrRec a, int* b) { return 10; } } public static void Main() { int* ptr = null; Expression<Func<PtrRec, int>> testExpr = (x) => x + ptr; } }"; var c = CompileAndVerify(text, additionalRefs: new[] { SystemCoreRef }, options: TestOptions.UnsafeReleaseDll, emitOptions: EmitOptions.RefEmitBug, verify: false); c.VerifyDiagnostics(); } [WorkItem(544398, "DevDiv")] [Fact] public void BitwiseComplementOnNullableShort() { var text = @"using System; using System.Linq.Expressions; public class Test { static void Main() { Expression<Func<short?, int?>> testExpr = (x) => ~x; ExpressionVisitor ev = new ExpressionVisitor(); ev.Visit(testExpr); Console.Write(ev.toStr); } }"; string expectedOutput = @" Lambda: Type->System.Func`2[System.Nullable`1[System.Int16],System.Nullable`1[System.Int32]] Parameters-> Parameter: Type->System.Nullable`1[System.Int16] Name->x Body-> Not: Type->System.Nullable`1[System.Int32] Method-> IsLifted->True IsLiftedToNull->True Operand-> Convert: Type->System.Nullable`1[System.Int32] Method-> IsLifted->True IsLiftedToNull->True Operand-> Parameter: Type->System.Nullable`1[System.Int16] Name->x "; CompileAndVerify( new[] { text, TreeWalkerLib }, new[] { ExpressionAssemblyRef }, expectedOutput: TrimExpectedOutput(expectedOutput)); } [WorkItem(544400, "DevDiv")] [Fact] public void ExpressionTreeWithIterators() { var text = @"using System; using System.Collections.Generic; using System.Linq.Expressions; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { IEnumerable<int> enumerable = Generate<object>(5); IEnumerator<int> enumerator = enumerable.GetEnumerator(); enumerator.MoveNext(); } public static IEnumerable<int> Generate<T>(int count) { Expression<Func<int>> f = () => count; for (var i = 1; i <= count; i++) yield return i; } } }"; string expectedOutput = @""; CompileAndVerify(text, new[] { ExpressionAssemblyRef }, expectedOutput: TrimExpectedOutput(expectedOutput)); } [WorkItem(544401, "DevDiv")] [Fact] public void AnonMethodInsideExprTree() { var text = @"using System; using System.Linq.Expressions; public delegate void D(); public class A { static void Main() { Expression<Func<D>> f = () => delegate() { }; } }"; CreateCompilationWithMscorlibAndSystemCore(text) .VerifyDiagnostics( // (9,39): error CS1945: An expression tree may not contain an anonymous method expressio // Expression<Func<D>> f = () => delegate() { }; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAnonymousMethod, "delegate() { }") ); } [WorkItem(544403, "DevDiv")] [Fact] public void ConditionalWithOperandTypesObjectArrAndStringArr() { var text = @"using System; using System.Linq.Expressions; public class Test { static void Main() { Expression<Func<bool, object[]>> testExpr = (x) => x ? new object[] { ""Test"" } : new string[] { ""Test"" }; Console.WriteLine(testExpr); } }"; string expectedOutput = @"x => IIF(x, new [] {""Test""}, Convert(new [] {""Test""}))"; CompileAndVerify( new[] { text, TreeWalkerLib }, new[] { ExpressionAssemblyRef }, expectedOutput: TrimExpectedOutput(expectedOutput)); } [WorkItem(544413, "DevDiv")] [Fact] public void ExplicitConversionLambdaToExprTree() { var text = @"using System; using System.Linq.Expressions; public class Test { static void Main() { Expression<Func<int, Expression<Func<int, int>>>> testExpr = (y => (Expression<Func<int, int>>)(x => 2 * x)); ExpressionVisitor ev = new ExpressionVisitor(); ev.Visit(testExpr); Console.Write(ev.toStr); } }"; string expectedOutput = @" Lambda: Type->System.Func`2[System.Int32,System.Linq.Expressions.Expression`1[System.Func`2[System.Int32,System.Int32]]] Parameters-> Parameter: Type->System.Int32 Name->y Body-> Convert: Type->System.Linq.Expressions.Expression`1[System.Func`2[System.Int32,System.Int32]] Method-> IsLifted->False IsLiftedToNull->False Operand-> Quote: Type->System.Linq.Expressions.Expression`1[System.Func`2[System.Int32,System.Int32]] Method-> IsLifted->False IsLiftedToNull->False Operand-> Lambda: Type->System.Func`2[System.Int32,System.Int32] Parameters-> Parameter: Type->System.Int32 Name->x Body-> Multiply: Type->System.Int32 Method-> IsLifted->False IsLiftedToNull->False Left-> Constant: Type->System.Int32 Value->2 Right-> Parameter: Type->System.Int32 Name->x "; CompileAndVerify( new[] { text, TreeWalkerLib }, new[] { ExpressionAssemblyRef }, expectedOutput: TrimExpectedOutput(expectedOutput)); } [WorkItem(544442, "DevDiv")] [Fact] public void ExprTreeFieldInitCoalesceWithNullOnLHS() { var text = @"using System; using System.Linq.Expressions; class Program { Expression<Func<object>> testExpr = () => null ?? new object(); }"; CreateCompilationWithMscorlibAndSystemCore(text) .VerifyDiagnostics( // (6,47): error CS0845: An expression tree lambda may not contain a coalescing operator with a null literal left-hand side // Expression<Func<object>> testExpr = () => null ?? new object(); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsBadCoalesce, "null") ); } [WorkItem(544429, "DevDiv")] [Fact] public void ExtraConversionInDelegateCreation() { string source = @"using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Collections.Generic; public class TestClass1 { public int Func1(string a) { return 2; } public int Func1(int b) { return 9; } } public delegate int Del(string a); class Program { static void Main(string[] args) { Expression<Func<TestClass1, Del>> test2 = (tc1) => tc1.Func1; Console.WriteLine(test2.Dump()); } }"; string expectedOutput = @"Convert(Call(null.[System.Delegate CreateDelegate(System.Type, System.Object, System.Reflection.MethodInfo)](Constant(Del Type:System.Type), Parameter(tc1 Type:TestClass1), Constant(Int32 Func1(System.String) Type:System.Reflection.MethodInfo)) Type:System.Delegate) Type:Del)"; CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: expectedOutput); } [WorkItem(544430, "DevDiv")] [Fact] public void ExtraConversionInLiftedUserDefined() { string source = @"using System; using System.Linq.Expressions; struct RomanNumeral { static public implicit operator RomanNumeral(BinaryNumeral binary) { return new RomanNumeral(); } } struct BinaryNumeral { } class Program { static void Main(string[] args) { Expression<Func<BinaryNumeral?, RomanNumeral?>> test4 = (expr1) => expr1; Console.WriteLine(test4.Dump()); } }"; string expectedOutput = @"Convert(Parameter(expr1 Type:System.Nullable`1[BinaryNumeral]) Lifted LiftedToNull Method:[RomanNumeral op_Implicit(BinaryNumeral)] Type:System.Nullable`1[RomanNumeral])"; CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: expectedOutput); } [WorkItem(529420, "DevDiv")] [Fact] public void HalfLiftedLeftShift() { string source = @"using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; class Program { public static void Main(string[] args) { Expression<Func<long?, short, long?>> e = (x, y) => x << y; Console.WriteLine(e.Dump()); } }"; string expectedOutput = @"LeftShift(Parameter(x Type:System.Nullable`1[System.Int64]) Convert(Convert(Parameter(y Type:System.Int16) Type:System.Int32) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int64])"; CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: expectedOutput); } [WorkItem(544451, "DevDiv")] [Fact] public void BinaryOnLiftedByteEnum() { string source = @"using System; using System.Linq.Expressions; enum Color : byte { Red, Blue, Green } class Program : TestBase { public static void Main(string[] args) { // See comments in 12781 regarding these two cases // Check<Color?, byte, Color?>((a, b) => a + b, // ""Convert(Add(Convert(Parameter(a Type:System.Nullable`1[Color]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Convert(Parameter(b Type:System.Byte) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[Color])""); // Check<Color, byte?, Color?>((a, b) => a + b, // ""Convert(Add(Convert(Parameter(a Type:Color) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Convert(Parameter(b Type:System.Nullable`1[System.Byte]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[Color])""); Check<Color, byte, Color>((a, b) => a + b, ""Convert(Add(Convert(Parameter(a Type:Color) Type:System.Int32) Convert(Parameter(b Type:System.Byte) Type:System.Int32) Type:System.Int32) Type:Color)""); Check<Color?, byte?, Color?>((a, b) => a + b, ""Convert(Add(Convert(Parameter(a Type:System.Nullable`1[Color]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Convert(Parameter(b Type:System.Nullable`1[System.Byte]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[Color])""); Check<byte, Color, Color>((a, b) => a + b, ""Convert(Add(Convert(Parameter(a Type:System.Byte) Type:System.Int32) Convert(Parameter(b Type:Color) Type:System.Int32) Type:System.Int32) Type:Color)""); Check<byte?, Color?, Color?>((a, b) => a + b, ""Convert(Add(Convert(Parameter(a Type:System.Nullable`1[System.Byte]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Convert(Parameter(b Type:System.Nullable`1[Color]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[Color])""); Check<Color, Color, byte>((a, b) => a - b, ""Convert(Subtract(Convert(Parameter(a Type:Color) Type:System.Int32) Convert(Parameter(b Type:Color) Type:System.Int32) Type:System.Int32) Type:System.Byte)""); Check<Color?, Color?, byte?>((a, b) => a - b, ""Convert(Subtract(Convert(Parameter(a Type:System.Nullable`1[Color]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Convert(Parameter(b Type:System.Nullable`1[Color]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Byte])""); Check<Color, byte, Color>((a, b) => a - b, ""Convert(Subtract(Convert(Parameter(a Type:Color) Type:System.Int32) Convert(Parameter(b Type:System.Byte) Type:System.Int32) Type:System.Int32) Type:Color)""); Check<Color?, byte?, Color?>((a, b) => a - b, ""Convert(Subtract(Convert(Parameter(a Type:System.Nullable`1[Color]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Convert(Parameter(b Type:System.Nullable`1[System.Byte]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[Color])""); Check<Color, Color, bool>((a, b) => a == b, ""Equal(Convert(Parameter(a Type:Color) Type:System.Int32) Convert(Parameter(b Type:Color) Type:System.Int32) Type:System.Boolean)""); Check<Color?, Color?, bool>((a, b) => a == b, ""Equal(Convert(Parameter(a Type:System.Nullable`1[Color]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Convert(Parameter(b Type:System.Nullable`1[Color]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted Type:System.Boolean)""); Check<Color, Color, bool>((a, b) => a < b, ""LessThan(Convert(Parameter(a Type:Color) Type:System.Int32) Convert(Parameter(b Type:Color) Type:System.Int32) Type:System.Boolean)""); Check<Color?, Color?, bool>((a, b) => a < b, ""LessThan(Convert(Parameter(a Type:System.Nullable`1[Color]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Convert(Parameter(b Type:System.Nullable`1[Color]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted Type:System.Boolean)""); } }"; string expectedOutput = ""; CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: expectedOutput); } [WorkItem(544458, "DevDiv")] [Fact] public void EmptyCollectionInit() { var text = @"using System; using System.Collections.Generic; using System.Linq.Expressions; public class Parent { static void Main() { Expression<Func<List<int>>> testExpr = () => new List<int> { }; Console.WriteLine(testExpr.Dump()); } }"; string expectedOutput = @"MemberInit(NewExpression: New([Void .ctor()]() Type:System.Collections.Generic.List`1[System.Int32]) Bindings:[] Type:System.Collections.Generic.List`1[System.Int32])"; CompileAndVerify( new[] { text, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: TrimExpectedOutput(expectedOutput)); } [WorkItem(544485, "DevDiv")] [Fact] public void EmptyObjectInitForPredefinedType() { var text = @"using System; using System.Collections.Generic; using System.Linq.Expressions; public class Parent { static void Main() { Expression<Func<int>> testExpr = () => new int { }; ExpressionVisitor ev = new ExpressionVisitor(); ev.Visit(testExpr); Console.Write(ev.toStr); } }"; string expectedOutput = @" Lambda: Type->System.Func`1[System.Int32] Parameters-> Body-> MemberInit: Type->System.Int32 NewExpression-> New: Type->System.Int32 Constructor-> Arguments-> Bindings-> "; CompileAndVerify( new[] { text, TreeWalkerLib }, new[] { ExpressionAssemblyRef }, expectedOutput: TrimExpectedOutput(expectedOutput)); } [WorkItem(544546, "DevDiv")] [Fact] public void BadExprTreeLambdaInNSDecl() { string source = @" namespace global::((System.Linq.Expressions.Expression<System.Func<B>>)(() => B )).Compile()(){} "; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (2,11): error CS7000: Unexpected use of an aliased name // namespace global::((System.Linq.Expressions.Expression<System.Func<B>>)(() => B )).Compile()(){} Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "global::"), // (2,19): error CS1001: Identifier expected // namespace global::((System.Linq.Expressions.Expression<System.Func<B>>)(() => B )).Compile()(){} Diagnostic(ErrorCode.ERR_IdentifierExpected, "("), // (2,70): error CS0116: A namespace does not directly contain members such as fields or methods // namespace global::((System.Linq.Expressions.Expression<System.Func<B>>)(() => B )).Compile()(){} Diagnostic(ErrorCode.ERR_NamespaceUnexpected, ">"), // (2,79): error CS0116: A namespace does not directly contain members such as fields or methods // namespace global::((System.Linq.Expressions.Expression<System.Func<B>>)(() => B )).Compile()(){} Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "B"), // (2,19): error CS1514: { expected // namespace global::((System.Linq.Expressions.Expression<System.Func<B>>)(() => B )).Compile()(){} Diagnostic(ErrorCode.ERR_LbraceExpected, "("), // (2,20): error CS1022: Type or namespace definition, or end-of-file expected // namespace global::((System.Linq.Expressions.Expression<System.Func<B>>)(() => B )).Compile()(){} Diagnostic(ErrorCode.ERR_EOFExpected, "("), // (2,71): error CS1022: Type or namespace definition, or end-of-file expected // namespace global::((System.Linq.Expressions.Expression<System.Func<B>>)(() => B )).Compile()(){} Diagnostic(ErrorCode.ERR_EOFExpected, ")"), // (2,81): error CS1022: Type or namespace definition, or end-of-file expected // namespace global::((System.Linq.Expressions.Expression<System.Func<B>>)(() => B )).Compile()(){} Diagnostic(ErrorCode.ERR_EOFExpected, ")"), // (2,84): error CS1520: Method must have a return type // namespace global::((System.Linq.Expressions.Expression<System.Func<B>>)(() => B )).Compile()(){} Diagnostic(ErrorCode.ERR_MemberNeedsType, "Compile"), // (2,93): error CS1002: ; expected // namespace global::((System.Linq.Expressions.Expression<System.Func<B>>)(() => B )).Compile()(){} Diagnostic(ErrorCode.ERR_SemicolonExpected, "("), // (2,93): error CS1022: Type or namespace definition, or end-of-file expected // namespace global::((System.Linq.Expressions.Expression<System.Func<B>>)(() => B )).Compile()(){} Diagnostic(ErrorCode.ERR_EOFExpected, "("), // (2,84): error CS0501: '.<invalid-global-code>.Compile()' must declare a body because it is not marked abstract, extern, or partial // namespace global::((System.Linq.Expressions.Expression<System.Func<B>>)(() => B )).Compile()(){} Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "Compile").WithArguments(".<invalid-global-code>.Compile()")); } [WorkItem(544548, "DevDiv")] [Fact] public void NSaliasSystemIsGlobal() { string source = @" using System = global; class Test { static void Main() { ((System.Linq.Expressions.Expression<System.Func<void>>)(() => global::System.Console.WriteLine(""))).Compile()(); } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (8,58): error CS1547: Keyword 'void' cannot be used in this context // ((System.Linq.Expressions.Expression<System.Func<void>>)(() => global::System.Console.WriteLine("))).Compile()(); Diagnostic(ErrorCode.ERR_NoVoidHere, "void"), // (8,105): error CS1010: Newline in constant // ((System.Linq.Expressions.Expression<System.Func<void>>)(() => global::System.Console.WriteLine("))).Compile()(); Diagnostic(ErrorCode.ERR_NewlineInConst, ""), // (8,122): error CS1026: ) expected // ((System.Linq.Expressions.Expression<System.Func<void>>)(() => global::System.Console.WriteLine("))).Compile()(); Diagnostic(ErrorCode.ERR_CloseParenExpected, ""), // (8,122): error CS1026: ) expected // ((System.Linq.Expressions.Expression<System.Func<void>>)(() => global::System.Console.WriteLine("))).Compile()(); Diagnostic(ErrorCode.ERR_CloseParenExpected, ""), // (8,122): error CS1026: ) expected // ((System.Linq.Expressions.Expression<System.Func<void>>)(() => global::System.Console.WriteLine("))).Compile()(); Diagnostic(ErrorCode.ERR_CloseParenExpected, ""), // (8,122): error CS1002: ; expected // ((System.Linq.Expressions.Expression<System.Func<void>>)(() => global::System.Console.WriteLine("))).Compile()(); Diagnostic(ErrorCode.ERR_SemicolonExpected, ""), // (2,16): error CS0246: The type or namespace name 'global' could not be found (are you missing a using directive or an assembly reference?) // using System = global; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "global").WithArguments("global"), // (8,11): error CS0576: Namespace '<global namespace>' contains a definition conflicting with alias 'System' // ((System.Linq.Expressions.Expression<System.Func<void>>)(() => global::System.Console.WriteLine("))).Compile()(); Diagnostic(ErrorCode.ERR_ConflictAliasAndMember, "System").WithArguments("System", "<global namespace>"), // (8,46): error CS0576: Namespace '<global namespace>' contains a definition conflicting with alias 'System' // ((System.Linq.Expressions.Expression<System.Func<void>>)(() => global::System.Console.WriteLine("))).Compile()(); Diagnostic(ErrorCode.ERR_ConflictAliasAndMember, "System").WithArguments("System", "<global namespace>")); } [WorkItem(544586, "DevDiv")] [Fact] public void ExprTreeInsideAnonymousMethod() { string source = @" using System; using System.Collections.Generic; class Test { delegate void D<T>(T t); static void M<T>(IEnumerable<T> items) { T val = default(T); IEnumerator<T> ie = items.GetEnumerator(); ie.MoveNext(); D<T> d = delegate(T tt) { val = ((System.Linq.Expressions.Expression<System.Func<T>>)(() => ie.Current)).Compile()(); Console.WriteLine(tt); }; d(ie.Current); } static void Main() { List<int> items = new List<int>(); items.Add(3); items.Add(6); M(items); } }"; string expectedOutput = @"3"; CompileAndVerify( new[] { source }, new[] { ExpressionAssemblyRef }, expectedOutput: TrimExpectedOutput(expectedOutput)); } [WorkItem(544598, "DevDiv")] [Fact] public void ConstructorWithParamsParameter() { string source = @" class MyClass { int intTest; public MyClass(params int[] values) { intTest = values[0] + values[1] + values[2]; } public static void Main() { MyClass mc = ((System.Linq.Expressions.Expression<System.Func<MyClass>>)(() => new MyClass(1, 2, 3))).Compile()(); System.Console.WriteLine(mc.intTest); } }"; string expectedOutput = @"6"; CompileAndVerify( new[] { source }, new[] { ExpressionAssemblyRef }, expectedOutput: TrimExpectedOutput(expectedOutput)); } [WorkItem(544599, "DevDiv")] [Fact] public void ExplicitEnumToDecimal() { string source = @" using System; using System.Linq.Expressions; enum EnumType { ValOne = 1 } public class Test { public static void Main() { Expression<Func<EnumType, decimal>> e = x => (decimal)x; Console.WriteLine(e.Dump()); Console.WriteLine(e.Compile()(EnumType.ValOne)); } }"; string expectedOutput = @"Convert(Convert(Parameter(x Type:EnumType) Type:System.Int32) Method:[System.Decimal op_Implicit(Int32)] Type:System.Decimal) 1"; CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: expectedOutput); } [Fact] public void ExplicitEnumToDecimal_Nullable1() { string source = @" using System; using System.Linq.Expressions; enum E { A } class C { static void Main() { Expression<Func<E, decimal>> ed = (x) => (decimal)x; Expression<Func<E?, decimal>> nd = (x) => (decimal)x; Expression<Func<E, decimal?>> end = (x) => (decimal)x; Expression<Func<E?, decimal?>> nend = (x) => (decimal)x; Console.WriteLine(ed.Dump()); Console.WriteLine(nd.Dump()); Console.WriteLine(end.Dump()); Console.WriteLine(nend.Dump()); } }"; string expectedOutput = @" Convert(Convert(Parameter(x Type:E) Type:System.Int32) Method:[System.Decimal op_Implicit(Int32)] Type:System.Decimal) Convert(Convert(Parameter(x Type:System.Nullable`1[E]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted Method:[System.Decimal op_Implicit(Int32)] Type:System.Decimal) Convert(Convert(Convert(Parameter(x Type:E) Type:System.Int32) Method:[System.Decimal op_Implicit(Int32)] Type:System.Decimal) Lifted LiftedToNull Type:System.Nullable`1[System.Decimal]) Convert(Convert(Convert(Parameter(x Type:System.Nullable`1[E]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted Method:[System.Decimal op_Implicit(Int32)] Type:System.Decimal) Lifted LiftedToNull Type:System.Nullable`1[System.Decimal]) ".Trim(); var verifier = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: expectedOutput); verifier.VerifyIL("C.Main", @" { // Code size 405 (0x195) .maxstack 5 .locals init (System.Linq.Expressions.Expression<System.Func<E, decimal>> V_0, //ed System.Linq.Expressions.Expression<System.Func<E?, decimal>> V_1, //nd System.Linq.Expressions.Expression<System.Func<E, decimal?>> V_2, //end System.Linq.Expressions.ParameterExpression V_3) IL_0000: ldtoken ""E"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""x"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.3 IL_0015: ldloc.3 IL_0016: ldtoken ""int"" IL_001b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0020: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0025: ldtoken ""decimal"" IL_002a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_002f: ldtoken ""decimal decimal.op_Implicit(int)"" IL_0034: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0039: castclass ""System.Reflection.MethodInfo"" IL_003e: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type, System.Reflection.MethodInfo)"" IL_0043: ldc.i4.1 IL_0044: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0049: dup IL_004a: ldc.i4.0 IL_004b: ldloc.3 IL_004c: stelem.ref IL_004d: call ""System.Linq.Expressions.Expression<System.Func<E, decimal>> System.Linq.Expressions.Expression.Lambda<System.Func<E, decimal>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0052: stloc.0 IL_0053: ldtoken ""E?"" IL_0058: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005d: ldstr ""x"" IL_0062: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0067: stloc.3 IL_0068: ldloc.3 IL_0069: ldtoken ""int?"" IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0073: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0078: ldtoken ""decimal"" IL_007d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0082: ldtoken ""decimal decimal.op_Implicit(int)"" IL_0087: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_008c: castclass ""System.Reflection.MethodInfo"" IL_0091: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type, System.Reflection.MethodInfo)"" IL_0096: ldc.i4.1 IL_0097: newarr ""System.Linq.Expressions.ParameterExpression"" IL_009c: dup IL_009d: ldc.i4.0 IL_009e: ldloc.3 IL_009f: stelem.ref IL_00a0: call ""System.Linq.Expressions.Expression<System.Func<E?, decimal>> System.Linq.Expressions.Expression.Lambda<System.Func<E?, decimal>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_00a5: stloc.1 IL_00a6: ldtoken ""E"" IL_00ab: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00b0: ldstr ""x"" IL_00b5: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_00ba: stloc.3 IL_00bb: ldloc.3 IL_00bc: ldtoken ""int"" IL_00c1: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00c6: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_00cb: ldtoken ""decimal"" IL_00d0: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00d5: ldtoken ""decimal decimal.op_Implicit(int)"" IL_00da: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_00df: castclass ""System.Reflection.MethodInfo"" IL_00e4: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type, System.Reflection.MethodInfo)"" IL_00e9: ldtoken ""decimal?"" IL_00ee: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00f3: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_00f8: ldc.i4.1 IL_00f9: newarr ""System.Linq.Expressions.ParameterExpression"" IL_00fe: dup IL_00ff: ldc.i4.0 IL_0100: ldloc.3 IL_0101: stelem.ref IL_0102: call ""System.Linq.Expressions.Expression<System.Func<E, decimal?>> System.Linq.Expressions.Expression.Lambda<System.Func<E, decimal?>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0107: stloc.2 IL_0108: ldtoken ""E?"" IL_010d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0112: ldstr ""x"" IL_0117: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_011c: stloc.3 IL_011d: ldloc.3 IL_011e: ldtoken ""int?"" IL_0123: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0128: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_012d: ldtoken ""decimal"" IL_0132: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0137: ldtoken ""decimal decimal.op_Implicit(int)"" IL_013c: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0141: castclass ""System.Reflection.MethodInfo"" IL_0146: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type, System.Reflection.MethodInfo)"" IL_014b: ldtoken ""decimal?"" IL_0150: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0155: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_015a: ldc.i4.1 IL_015b: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0160: dup IL_0161: ldc.i4.0 IL_0162: ldloc.3 IL_0163: stelem.ref IL_0164: call ""System.Linq.Expressions.Expression<System.Func<E?, decimal?>> System.Linq.Expressions.Expression.Lambda<System.Func<E?, decimal?>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0169: ldloc.0 IL_016a: call ""string ExpressionExtensions.Dump<System.Func<E, decimal>>(System.Linq.Expressions.Expression<System.Func<E, decimal>>)"" IL_016f: call ""void System.Console.WriteLine(string)"" IL_0174: ldloc.1 IL_0175: call ""string ExpressionExtensions.Dump<System.Func<E?, decimal>>(System.Linq.Expressions.Expression<System.Func<E?, decimal>>)"" IL_017a: call ""void System.Console.WriteLine(string)"" IL_017f: ldloc.2 IL_0180: call ""string ExpressionExtensions.Dump<System.Func<E, decimal?>>(System.Linq.Expressions.Expression<System.Func<E, decimal?>>)"" IL_0185: call ""void System.Console.WriteLine(string)"" IL_018a: call ""string ExpressionExtensions.Dump<System.Func<E?, decimal?>>(System.Linq.Expressions.Expression<System.Func<E?, decimal?>>)"" IL_018f: call ""void System.Console.WriteLine(string)"" IL_0194: ret }"); } [Fact] public void ExplicitEnumToDecimal_Nullable2() { string source = @" using System; using System.Linq.Expressions; enum E { A } class C { static void Main() { Expression<Func<E, decimal?>> end = (x) => (decimal?)x; Expression<Func<E?, decimal?>> nend = (x) => (decimal?)x; Console.WriteLine(end.Dump()); Console.WriteLine(nend.Dump()); } }"; string expectedOutput = @" Convert(Convert(Convert(Parameter(x Type:E) Type:System.Int32) Method:[System.Decimal op_Implicit(Int32)] Type:System.Decimal) Lifted LiftedToNull Type:System.Nullable`1[System.Decimal]) Convert(Convert(Parameter(x Type:System.Nullable`1[E]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Method:[System.Decimal op_Implicit(Int32)] Type:System.Nullable`1[System.Decimal]) ".Trim(); var verifier = CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: expectedOutput); verifier.VerifyIL("C.Main", @" { // Code size 202 (0xca) .maxstack 5 .locals init (System.Linq.Expressions.Expression<System.Func<E, decimal?>> V_0, //end System.Linq.Expressions.ParameterExpression V_1) IL_0000: ldtoken ""E"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""x"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.1 IL_0015: ldloc.1 IL_0016: ldtoken ""int"" IL_001b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0020: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0025: ldtoken ""decimal"" IL_002a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_002f: ldtoken ""decimal decimal.op_Implicit(int)"" IL_0034: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0039: castclass ""System.Reflection.MethodInfo"" IL_003e: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type, System.Reflection.MethodInfo)"" IL_0043: ldtoken ""decimal?"" IL_0048: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_004d: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0052: ldc.i4.1 IL_0053: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0058: dup IL_0059: ldc.i4.0 IL_005a: ldloc.1 IL_005b: stelem.ref IL_005c: call ""System.Linq.Expressions.Expression<System.Func<E, decimal?>> System.Linq.Expressions.Expression.Lambda<System.Func<E, decimal?>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0061: stloc.0 IL_0062: ldtoken ""E?"" IL_0067: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_006c: ldstr ""x"" IL_0071: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0076: stloc.1 IL_0077: ldloc.1 IL_0078: ldtoken ""int?"" IL_007d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0082: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0087: ldtoken ""decimal?"" IL_008c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0091: ldtoken ""decimal decimal.op_Implicit(int)"" IL_0096: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_009b: castclass ""System.Reflection.MethodInfo"" IL_00a0: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type, System.Reflection.MethodInfo)"" IL_00a5: ldc.i4.1 IL_00a6: newarr ""System.Linq.Expressions.ParameterExpression"" IL_00ab: dup IL_00ac: ldc.i4.0 IL_00ad: ldloc.1 IL_00ae: stelem.ref IL_00af: call ""System.Linq.Expressions.Expression<System.Func<E?, decimal?>> System.Linq.Expressions.Expression.Lambda<System.Func<E?, decimal?>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_00b4: ldloc.0 IL_00b5: call ""string ExpressionExtensions.Dump<System.Func<E, decimal?>>(System.Linq.Expressions.Expression<System.Func<E, decimal?>>)"" IL_00ba: call ""void System.Console.WriteLine(string)"" IL_00bf: call ""string ExpressionExtensions.Dump<System.Func<E?, decimal?>>(System.Linq.Expressions.Expression<System.Func<E?, decimal?>>)"" IL_00c4: call ""void System.Console.WriteLine(string)"" IL_00c9: ret }"); } [WorkItem(544955, "DevDiv")] [Fact] public void FirstOperandOfConditionalOperatorImplementsOperatorTrue() { string source = @"using System; using System.Linq.Expressions; class MyTest { public static bool operator true(MyTest t) { return true; } public static bool operator false(MyTest t) { return false; } } class MyClass { public static void Main() { Expression<Func<MyTest, int>> e = t => t ? 2 : 3; Console.WriteLine(e.Dump()); int intI = e.Compile()(new MyTest()); Console.WriteLine(intI); } }"; string expectedOutput = @"Conditional(Call(null.[Boolean op_True(MyTest)](Parameter(t Type:MyTest)) Type:System.Boolean) ? Constant(2 Type:System.Int32) : Constant(3 Type:System.Int32) Type:System.Int32) 2"; CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: expectedOutput); } [WorkItem(545042, "DevDiv")] [Fact] public void AnonMethodInExprTree() { var source = @"using System; using System.Linq.Expressions; public class Program { static void Main() { EventHandler eventHandler = delegate { }; Expression<Func<EventHandler>> testExpr = () => new EventHandler(delegate { }); } }"; CreateCompilationWithMscorlibAndSystemCore(source) .VerifyDiagnostics( // (9,74): error CS1945: An expression tree may not contain an anonymous method expression // Expression<Func<EventHandler>> testExpr = () => new EventHandler(delegate { }); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAnonymousMethod, "delegate { }") ); } [WorkItem(545122, "DevDiv")] [Fact] public void CollInitAddMethodWithParams() { string source = @" using System; using System.Collections.Generic; using System.Collections; using System.Linq.Expressions; class C { public static void Main() { Expression<Func<B>> e1 = () => new B { { 5, 8, 10, 15L } }; Console.WriteLine(e1); } } public class B : IEnumerable { List<object> list = new List<object>(); public int Add(params long[] l1) { for (int i = 0; i < l1.Length; i++) { list.Add(l1[i]); } return 10; } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } }"; string expectedOutput = @"() => new B() {Int32 Add(Int64[])(new [] {5, 8, 10, 15})}"; CompileAndVerify( new[] { source }, new[] { ExpressionAssemblyRef }, expectedOutput: TrimExpectedOutput(expectedOutput)); } [WorkItem(545189, "DevDiv")] [Fact] public void ExprTreeInTypeArgument() { string source = @" public class MemberInitializerTest { delegate void D<T>(); public static void GenericMethod<T>() { } public static void Run() { Foo f = new Foo { genD = (D<int>) GenericMethod<((System.Linq.Expressions.Expression<System.Func<int>>)(() => int)).Compile()()> }; } }"; CreateCompilationWithMscorlibAndSystemCore(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.Experimental)).VerifyDiagnostics( // (9,108): error CS1001: Identifier expected // genD = (D<int>) GenericMethod<((System.Linq.Expressions.Expression<System.Func<int>>)(() => int)).Compile()()> Diagnostic(ErrorCode.ERR_IdentifierExpected, ")"), // (9,123): error CS1525: Invalid expression term '}' // genD = (D<int>) GenericMethod<((System.Linq.Expressions.Expression<System.Func<int>>)(() => int)).Compile()()> Diagnostic(ErrorCode.ERR_InvalidExprTerm, "").WithArguments("}"), // (8,9): error CS0246: The type or namespace name 'Foo' could not be found (are you missing a using directive or an assembly reference?) // Foo f = new Foo { Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Foo").WithArguments("Foo"), // (8,21): error CS0246: The type or namespace name 'Foo' could not be found (are you missing a using directive or an assembly reference?) // Foo f = new Foo { Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Foo").WithArguments("Foo"), // (9,20): error CS0030: Cannot convert type 'method' to 'MemberInitializerTest.D<int>' // genD = (D<int>) GenericMethod<((System.Linq.Expressions.Expression<System.Func<int>>)(() => int)).Compile()()> Diagnostic(ErrorCode.ERR_NoExplicitConv, "(D<int>) GenericMethod").WithArguments("method", "MemberInitializerTest.D<int>"), // (9,105): error CS0165: Use of unassigned local variable '' // genD = (D<int>) GenericMethod<((System.Linq.Expressions.Expression<System.Func<int>>)(() => int)).Compile()()> Diagnostic(ErrorCode.ERR_UseDefViolation, "int").WithArguments("").WithLocation(9, 105)); } [WorkItem(545189, "DevDiv")] [Fact] public void ExprTreeInTypeArgument_NoDeclExpr() { string source = @" public class MemberInitializerTest { delegate void D<T>(); public static void GenericMethod<T>() { } public static void Run() { Foo f = new Foo { genD = (D<int>) GenericMethod<((System.Linq.Expressions.Expression<System.Func<int>>)(() => int)).Compile()()> }; } }"; CreateCompilationWithMscorlibAndSystemCore(source).VerifyDiagnostics( // (9,105): error CS1525: Invalid expression term 'int' // genD = (D<int>) GenericMethod<((System.Linq.Expressions.Expression<System.Func<int>>)(() => int)).Compile()()> Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int"), // (9,123): error CS1525: Invalid expression term '}' // genD = (D<int>) GenericMethod<((System.Linq.Expressions.Expression<System.Func<int>>)(() => int)).Compile()()> Diagnostic(ErrorCode.ERR_InvalidExprTerm, "").WithArguments("}"), // (8,9): error CS0246: The type or namespace name 'Foo' could not be found (are you missing a using directive or an assembly reference?) // Foo f = new Foo { Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Foo").WithArguments("Foo"), // (8,21): error CS0246: The type or namespace name 'Foo' could not be found (are you missing a using directive or an assembly reference?) // Foo f = new Foo { Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Foo").WithArguments("Foo"), // (9,20): error CS0030: Cannot convert type 'method' to 'MemberInitializerTest.D<int>' // genD = (D<int>) GenericMethod<((System.Linq.Expressions.Expression<System.Func<int>>)(() => int)).Compile()()> Diagnostic(ErrorCode.ERR_NoExplicitConv, "(D<int>) GenericMethod").WithArguments("method", "MemberInitializerTest.D<int>")); } [WorkItem(545191, "DevDiv")] [Fact] public void ObjectInitializersValueType() { string source = @" using System; using System.Linq; using System.Linq.Expressions; interface I { int X { get; set; } } struct S : I { public int X { get; set; } } class Program { static void Main() { int result = Foo<S>(); Console.WriteLine(result); } static int Foo<T>() where T : I, new() { Expression<Func<T>> f1 = () => new T { X = 1 }; var b = f1.Compile()(); return b.X; } }"; string expectedOutput = @"1"; CompileAndVerify( new[] { source }, new[] { ExpressionAssemblyRef }, expectedOutput: expectedOutput); } [WorkItem(545396, "DevDiv")] [Fact] public void LongLengthArrayProperty() { string source = @" using System; using System.Linq.Expressions; public class Test { public static void Main() { Expression<Func<long>> e1 = () => new int[100].LongLength; Func<long> f1 = e1.Compile(); Console.WriteLine(f1()); } }"; string expectedOutput = @"100"; CompileAndVerify( new[] { source }, new[] { ExpressionAssemblyRef }, expectedOutput: expectedOutput); } [WorkItem(545457, "DevDiv")] [Fact] public void NullableDecimalToNullableEnumExplicitConv() { string source = @" using System; using System.Linq.Expressions; public class Derived { public enum Enum1 { zero, one, two, three } public static void Main() { Expression<Func<decimal?, Enum1?>> f1e = decimalq => (Enum1?)decimalq; Func<decimal?, Enum1?> f1 = f1e.Compile(); Console.WriteLine(f1(1)); Expression<Func<decimal, Enum1?>> f2e = decimalq => (Enum1?)decimalq; Func<decimal, Enum1?> f2 = f2e.Compile(); Console.WriteLine(f2(2)); Expression<Func<decimal?, Enum1>> f3e = decimalq => (Enum1)decimalq; Func<decimal?, Enum1> f3 = f3e.Compile(); Console.WriteLine(f3(3)); } } "; string expectedOutput = @"one two three"; CompileAndVerify( new[] { source }, new[] { ExpressionAssemblyRef }, expectedOutput: expectedOutput); } [WorkItem(545461, "DevDiv")] [Fact] public void LiftedUserDefinedConversionWithNullArg() { string source = @" using System; using System.Linq.Expressions; public struct C { public static implicit operator C(int num) { return new C(); } public static void Main() { Expression<Func<int?, C?>> e1 = (x) => (C?)x; Console.WriteLine(e1.Dump()); e1.Compile()(null); } } "; string expectedOutput = @"Convert(Parameter(x Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Method:[C op_Implicit(Int32)] Type:System.Nullable`1[C])"; CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: expectedOutput); } [WorkItem(546731, "DevDiv")] [Fact] public void CallLeastDerivedOverride() { string source = @" using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Collections.Generic; public class TestClass1 { public virtual int VirtMeth1() { return 5; } } public class TestClass2 : TestClass1 { public override int VirtMeth1() { return 10; } } class Test { // Invoking a instance virtual method, ""override"" public static void Main() { Expression<Func<TestClass2, int>> testExpr = (tc2) => tc2.VirtMeth1(); Console.WriteLine(testExpr.Dump()); Console.WriteLine(((MethodCallExpression)testExpr.Body).Method.DeclaringType); Console.WriteLine(testExpr.Compile()(new TestClass2())); } } "; string expectedOutput = @"Call(Parameter(tc2 Type:TestClass2).[Int32 VirtMeth1()]() Type:System.Int32) TestClass1 10"; CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: expectedOutput); } [WorkItem(530529, "DevDiv")] [Fact] public void BoxTypeParameter() { string source = @"using System; using System.Linq; using System.Linq.Expressions; using System.Collections.Generic; interface I { int P { get; set; } int M(); } struct S : I { int _p; public int P { get { return _p++; } set { _p = value; } } public int M() { P = 7; return 1; } } class Test { public static void Test1<T>() where T : I { Func<T, int> f = x => x.M() + x.P + x.P; var r1 = f(default(T)); Expression<Func<T, int>> e = x => x.M() + x.P + x.P; var r2 = e.Compile()(default(T)); Console.WriteLine(r1==r2 ? ""pass"" : ""fail""); } static void Main() { Test1<S>(); } }"; string expectedOutput = @"pass"; CompileAndVerify( new[] { source }, new[] { ExpressionAssemblyRef }, expectedOutput: expectedOutput); } [WorkItem(546601, "DevDiv")] [Fact] public void NewArrayInitInAsAndIs() { string source = @"using System; using System.Linq.Expressions; class Test { public static void Main() { // Func<bool> func1 = () => new[] { DayOfWeek.Friday } is int[]; Expression<Func<bool>> expr1 = () => new[] { DayOfWeek.Friday } is int[]; Console.WriteLine(expr1.Dump()); Expression<Func<Test>> expr2 = () => (object)null as Test; Console.WriteLine(expr2.Dump()); Expression<Func<Test, object>> e = t => t as object; Console.WriteLine(e.Dump()); } }"; string expectedOutput = @"TypeIs(NewArrayInit([Constant(Friday Type:System.DayOfWeek)] Type:System.DayOfWeek[]) TypeOperand:System.Int32[] Type:System.Boolean) TypeAs(Constant(null Type:System.Object) Type:Test) TypeAs(Parameter(t Type:Test) Type:System.Object)"; CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: expectedOutput); } [WorkItem(531047, "DevDiv")] [Fact, WorkItem(531047, "DevDiv")] public void NullIsRegression() { string source = @"using System; using System.Linq.Expressions; class Test { public static void Main() { Expression<Func<bool>> expr = () => null is Test; Console.WriteLine(expr.Dump()); } }"; string expectedOutput = "TypeIs(Constant(null Type:System.Object) TypeOperand:Test Type:System.Boolean)"; CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: expectedOutput); } [WorkItem(546618, "DevDiv")] [Fact] public void TildeNullableEnum() { string source = @"using System; using System.Linq; using System.Linq.Expressions; class Test { public enum Color { Red, Green, Blue }; static void Main() { Expression<Func<Color?, Color?>> e1 = x => x ^ x; Console.WriteLine(e1.Dump()); Expression<Func<Color?, Color?>> e2 = x => ~x; Console.WriteLine(e2.Dump()); Expression<Func<Color, Color>> e3 = x => ~x; Console.WriteLine(e3.Dump()); } }"; string expectedOutput = @"Convert(ExclusiveOr(Convert(Parameter(x Type:System.Nullable`1[Test+Color]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Convert(Parameter(x Type:System.Nullable`1[Test+Color]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[Test+Color]) Convert(Not(Convert(Parameter(x Type:System.Nullable`1[Test+Color]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[System.Int32]) Lifted LiftedToNull Type:System.Nullable`1[Test+Color]) Convert(Not(Convert(Parameter(x Type:Test+Color) Type:System.Int32) Type:System.Int32) Type:Test+Color)"; CompileAndVerify( new[] { source, ExpressionTestLibrary }, new[] { ExpressionAssemblyRef }, expectedOutput: expectedOutput); } [WorkItem(531382, "DevDiv")] [Fact] public void IndexerIsIndexedPropoperty() { var source1 = @"<System.Runtime.InteropServices.ComImport> Public Class Cells Default Public ReadOnly Property Cell(index As Integer) As Integer Get Return 0 End Get End Property End Class"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1, verify: false); var source2 = @"class A { public Cells Cells { get { return null; } } } class Program { static void Main(string[] args) { System.Linq.Expressions.Expression<System.Func<A, int>> z2 = a => a.Cells[2]; System.Console.WriteLine(z2.ToString()); } }"; var expectedOutput = @"a => a.Cells.get_Cell(2)"; CompileAndVerify( new[] { source2 }, new[] { ExpressionAssemblyRef, reference1 }, expectedOutput: expectedOutput); } [WorkItem(579711, "DevDiv")] [Fact] public void CheckedEnumConversion() { var text = @"using System; using System.Linq; using System.Linq.Expressions; public enum color { Red, Blue, Green }; public enum cars { Toyota, Honda, Scion, Ford }; class C { static void Main() { Expression<Func<color, int>> expr1 = (x) => checked((int)x); Console.WriteLine(expr1); Expression<Func<int, color>> expr2 = (x) => checked((color)x); Console.WriteLine(expr2); Expression<Func<cars, color>> expr3 = (x) => checked((color)x); Console.WriteLine(expr3); } }"; var expected = @"x => ConvertChecked(x) x => ConvertChecked(x) x => ConvertChecked(x)"; CompileAndVerify( new[] { text }, new[] { ExpressionAssemblyRef }, expectedOutput: expected); } [WorkItem(717364, "DevDiv")] [Fact] public void NullAs() { var text = @" using System; using System.Linq; using System.Linq.Expressions; public delegate object Del(); class Test { public static void Main() { Expression<Del> testExpr = () => null as string; Console.WriteLine(testExpr); } }"; CompileAndVerify(text, new[] { ExpressionAssemblyRef }, expectedOutput: "() => (null As String)"); } [WorkItem(797996, "DevDiv")] [Fact] public void MissingMember_System_Type__GetTypeFromHandle() { var text = @"using System.Linq.Expressions; namespace System { public class Object { } public struct Void { } public class ValueType { } public class MulticastDelegate { } public struct IntPtr { } public struct Int32 { } public struct Nullable<T> { } public class Type { } } namespace System.Collections.Generic { public interface IEnumerable<T> { } } namespace System.Linq.Expressions { public class Expression { public static Expression New(Type t) { return null; } public static Expression<T> Lambda<T>(Expression e, Expression[] args) { return null; } } public class Expression<T> { } public class ParameterExpression : Expression { } } delegate C D(); class C { static Expression<D> E = () => new C(); }"; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics(); using (var stream = new MemoryStream()) { var result = compilation.Emit(stream); result.Diagnostics.Verify( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion), // (30,36): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle' // static Expression<D> E = () => new C(); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "new C()").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(30, 36)); } } [WorkItem(797996, "DevDiv")] [Fact] public void MissingMember_System_Reflection_FieldInfo__GetFieldFromHandle() { var text = @"using System.Linq.Expressions; using System.Reflection; namespace System { public class Object { } public struct Void { } public class ValueType { } public class MulticastDelegate { } public struct IntPtr { } public struct Int32 { } public struct Nullable<T> { } public class Type { } public class Array { } } namespace System.Collections.Generic { public interface IEnumerable<T> { } } namespace System.Linq.Expressions { public class Expression { public static Expression Field(Expression e, FieldInfo f) { return null; } public static Expression<T> Lambda<T>(Expression e, ParameterExpression[] args) { return null; } } public class Expression<T> { } public class ParameterExpression : Expression { } } namespace System.Reflection { public class FieldInfo { } } delegate object D(); class A { static object F = null; static Expression<D> G = () => F; } class B<T> { static object F = null; static Expression<D> G = () => F; }"; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics(); using (var stream = new MemoryStream()) { var result = compilation.Emit(stream); result.Diagnostics.Verify( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1), // (37,36): error CS0656: Missing compiler required member 'System.Reflection.FieldInfo.GetFieldFromHandle' // static Expression<D> G = () => F; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F").WithArguments("System.Reflection.FieldInfo", "GetFieldFromHandle").WithLocation(37, 36), // (42,36): error CS0656: Missing compiler required member 'System.Reflection.FieldInfo.GetFieldFromHandle' // static Expression<D> G = () => F; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F").WithArguments("System.Reflection.FieldInfo", "GetFieldFromHandle").WithLocation(42, 36) ); } } [WorkItem(797996, "DevDiv")] [Fact] public void MissingMember_System_Reflection_MethodBase__GetMethodFromHandle() { var text = @"using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; namespace System { public class Object { } public struct Void { } public class ValueType { } public class MulticastDelegate { } public struct IntPtr { } public struct Int32 { } public struct Nullable<T> { } public class Type { } } namespace System.Collections.Generic { public interface IEnumerable<T> { } } namespace System.Linq.Expressions { public class Expression { public static Expression Constant(object o, Type t) { return null; } public static Expression Call(Expression e, MethodInfo m, Expression[] args) { return null; } public static Expression<T> Lambda<T>(Expression e, Expression[] args) { return null; } public static Expression New(ConstructorInfo c, IEnumerable<Expression> args) { return null; } } public class Expression<T> { } public class ParameterExpression : Expression { } } namespace System.Reflection { public class ConstructorInfo { } public class MethodInfo { } } delegate void D(); class A { static Expression<D> F = () => new A(null); static Expression<D> G = () => M(); static void M() { } A(object o) { } } class B<T> { static Expression<D> F = () => new B<object>(null); static Expression<D> G = () => M(); static void M() { } B(object o) { } }"; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics(); using (var stream = new MemoryStream()) { var result = compilation.Emit(stream); result.Diagnostics.Verify( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1), // (39,36): error CS0656: Missing compiler required member 'System.Reflection.MethodBase.GetMethodFromHandle' // static Expression<D> F = () => new A(null); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "new A(null)").WithArguments("System.Reflection.MethodBase", "GetMethodFromHandle").WithLocation(39, 36), // (40,36): error CS0656: Missing compiler required member 'System.Reflection.MethodBase.GetMethodFromHandle' // static Expression<D> G = () => M(); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "M()").WithArguments("System.Reflection.MethodBase", "GetMethodFromHandle").WithLocation(40, 36), // (46,36): error CS0656: Missing compiler required member 'System.Reflection.MethodBase.GetMethodFromHandle' // static Expression<D> F = () => new B<object>(null); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "new B<object>(null)").WithArguments("System.Reflection.MethodBase", "GetMethodFromHandle").WithLocation(46, 36), // (47,36): error CS0656: Missing compiler required member 'System.Reflection.MethodBase.GetMethodFromHandle' // static Expression<D> G = () => M(); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "M()").WithArguments("System.Reflection.MethodBase", "GetMethodFromHandle").WithLocation(47, 36) ); } } [WorkItem(957927, "DevDiv")] [Fact] public void Bug957927() { string source = @" using System; using System.Linq.Expressions; class Test { static void Main() { System.Console.WriteLine(GetFunc<int>()().ToString()); } static Func<Expression<Func<T,T>>> GetFunc<T>() { int x = 10; return ()=> { int y = x; return (T m)=> m;}; } }"; string expectedOutput = @"m => m"; CompileAndVerify( new[] { source }, new[] { ExpressionAssemblyRef }, expectedOutput: expectedOutput); } #endregion Regression Tests #region helpers public string TrimExpectedOutput(string expectedOutput) { char[] delimit = { '\n' }; string trimmedOutput = null; string[] expected_strs = expectedOutput.Trim().Split(delimit); foreach (string expected_string in expected_strs) { trimmedOutput = trimmedOutput + expected_string.Trim() + '\n'; } return trimmedOutput; } const string TreeWalkerLib = @" using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using System.Linq; using System.Linq.Expressions; using System.Reflection; public class ExpressionVisitor { public string toStr; public ExpressionVisitor() { toStr = null; } internal virtual Expression Visit(Expression exp) { if (exp == null) return exp; toStr = toStr + exp.NodeType + "":\n""; toStr = toStr + ""Type->"" + exp.Type + ""\n""; switch (exp.NodeType) { case ExpressionType.Negate: case ExpressionType.UnaryPlus: case ExpressionType.NegateChecked: case ExpressionType.Not: case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.ArrayLength: case ExpressionType.Quote: case ExpressionType.TypeAs: return this.VisitUnary((UnaryExpression)exp); case ExpressionType.Add: case ExpressionType.AddChecked: case ExpressionType.Subtract: case ExpressionType.SubtractChecked: case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: case ExpressionType.Divide: case ExpressionType.Modulo: case ExpressionType.And: case ExpressionType.AndAlso: case ExpressionType.Or: case ExpressionType.OrElse: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.Equal: case ExpressionType.NotEqual: case ExpressionType.Coalesce: case ExpressionType.ArrayIndex: case ExpressionType.RightShift: case ExpressionType.LeftShift: case ExpressionType.ExclusiveOr: return this.VisitBinary((BinaryExpression)exp); case ExpressionType.TypeIs: return this.VisitTypeIs((TypeBinaryExpression)exp); case ExpressionType.Conditional: return this.VisitConditional((ConditionalExpression)exp); case ExpressionType.Constant: return this.VisitConstant((ConstantExpression)exp); case ExpressionType.Parameter: return this.VisitParameter((ParameterExpression)exp); case ExpressionType.MemberAccess: return this.VisitMemberAccess((MemberExpression)exp); case ExpressionType.Call: return this.VisitMethodCall((MethodCallExpression)exp); case ExpressionType.Lambda: return this.VisitLambda((LambdaExpression)exp); case ExpressionType.New: return this.VisitNew((NewExpression)exp); case ExpressionType.NewArrayInit: case ExpressionType.NewArrayBounds: return this.VisitNewArray((NewArrayExpression)exp); case ExpressionType.Invoke: return this.VisitInvocation((InvocationExpression)exp); case ExpressionType.MemberInit: return this.VisitMemberInit((MemberInitExpression)exp); case ExpressionType.ListInit: return this.VisitListInit((ListInitExpression)exp); default: return null; } } internal virtual MemberBinding VisitBinding(MemberBinding binding) { toStr = toStr + ""MemberBindingType->"" + binding.BindingType + ""\n""; toStr = toStr + ""Member->"" + binding.Member + ""\n""; switch (binding.BindingType) { case MemberBindingType.Assignment: return this.VisitMemberAssignment((MemberAssignment)binding); case MemberBindingType.MemberBinding: return this.VisitMemberMemberBinding((MemberMemberBinding)binding); case MemberBindingType.ListBinding: return this.VisitMemberListBinding((MemberListBinding)binding); default: return null; } } internal virtual ElementInit VisitElementInitializer(ElementInit initializer) { toStr = toStr + ""AddMethod->"" + initializer.AddMethod + ""\n""; toStr = toStr + ""Arguments->"" + ""\n""; ReadOnlyCollection<Expression> arguments = this.VisitExpressionList(initializer.Arguments); if (arguments != initializer.Arguments) { return Expression.ElementInit(initializer.AddMethod, arguments); } return initializer; } internal virtual Expression VisitUnary(UnaryExpression u) { toStr = toStr + ""Method->"" + u.Method + ""\n""; toStr = toStr + ""IsLifted->"" + u.IsLifted + ""\n""; toStr = toStr + ""IsLiftedToNull->"" + u.IsLiftedToNull + ""\n""; toStr = toStr + ""Operand->"" + ""\n""; Expression operand = this.Visit(u.Operand); if (operand != u.Operand) { return Expression.MakeUnary(u.NodeType, operand, u.Type); } return u; } internal virtual Expression VisitBinary(BinaryExpression b) { toStr = toStr + ""Method->"" + b.Method + ""\n""; toStr = toStr + ""IsLifted->"" + b.IsLifted + ""\n""; toStr = toStr + ""IsLiftedToNull->"" + b.IsLiftedToNull + ""\n""; toStr = toStr + ""Left->"" + ""\n""; Expression left = this.Visit(b.Left); toStr = toStr + ""Right->"" + ""\n""; Expression right = this.Visit(b.Right); if (b.NodeType == ExpressionType.Coalesce) { toStr = toStr + ""Conversion->"" + ""\n""; Expression conversion = this.Visit(b.Conversion); } if (left != b.Left || right != b.Right) { return Expression.MakeBinary(b.NodeType, left, right); } return b; } internal virtual Expression VisitTypeIs(TypeBinaryExpression b) { toStr = toStr + ""Expression->"" + ""\n""; Expression expr = this.Visit(b.Expression); toStr = toStr + ""TypeOperand->"" + b.TypeOperand + ""\n""; if (expr != b.Expression) { return Expression.TypeIs(expr, b.TypeOperand); } return b; } internal virtual Expression VisitConstant(ConstantExpression c) { toStr = toStr + ""Value->"" + c.Value + ""\n""; return c; } internal virtual Expression VisitConditional(ConditionalExpression c) { toStr = toStr + ""Test->"" + ""\n""; Expression test = this.Visit(c.Test); toStr = toStr + ""IfTrue->"" + ""\n""; Expression ifTrue = this.Visit(c.IfTrue); toStr = toStr + ""IfFalse->"" + ""\n""; Expression ifFalse = this.Visit(c.IfFalse); if (test != c.Test || ifTrue != c.IfTrue || ifFalse != c.IfFalse) { return Expression.Condition(test, ifTrue, ifFalse); } return c; } internal virtual Expression VisitParameter(ParameterExpression p) { toStr = toStr + ""Name->"" + p.Name + ""\n""; return p; } internal virtual Expression VisitMemberAccess(MemberExpression m) { toStr = toStr + ""Expression->"" + ""\n""; Expression exp = this.Visit(m.Expression); toStr = toStr + ""Member->"" + m.Member + ""\n""; if (exp != m.Expression) { return Expression.MakeMemberAccess(exp, m.Member); } return m; } internal virtual Expression VisitMethodCall(MethodCallExpression m) { toStr = toStr + ""MethodInfo->"" + m.Method + ""\n""; toStr = toStr + ""Object->"" + ""\n""; Expression obj = this.Visit(m.Object); toStr = toStr + ""Arguments->"" + ""\n""; IEnumerable<Expression> args = this.VisitExpressionList(m.Arguments); if (obj != m.Object || args != m.Arguments) { return Expression.Call(obj, m.Method, args); } return m; } internal virtual ReadOnlyCollection<Expression> VisitExpressionList(ReadOnlyCollection<Expression> original) { List<Expression> list = null; for (int i = 0, n = original.Count; i < n; i++) { Expression p = this.Visit(original[i]); if (list != null) { list.Add(p); } else if (p != original[i]) { list = new List<Expression>(n); for (int j = 0; j < i; j++) { list.Add(original[j]); } list.Add(p); } } if (list != null) return list.ToReadOnlyCollection(); return original; } internal virtual ReadOnlyCollection<ParameterExpression> VisitParamExpressionList(ReadOnlyCollection<ParameterExpression> original) { List<ParameterExpression> list = null; for (int i = 0, n = original.Count; i < n; i++) { ParameterExpression p = (ParameterExpression)this.Visit(original[i]); if (list != null) { list.Add(p); } else if (p != original[i]) { list = new List<ParameterExpression>(n); for (int j = 0; j < i; j++) { list.Add(original[j]); } list.Add(p); } } if (list != null) return list.ToReadOnlyCollection(); return original; } internal virtual MemberAssignment VisitMemberAssignment(MemberAssignment assignment) { toStr = toStr + ""Expression->"" + ""\n""; Expression e = this.Visit(assignment.Expression); if (e != assignment.Expression) { return Expression.Bind(assignment.Member, e); } return assignment; } internal virtual MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding) { toStr = toStr + ""Bindings->"" + ""\n""; IEnumerable<MemberBinding> bindings = this.VisitBindingList(binding.Bindings); if (bindings != binding.Bindings) { return Expression.MemberBind(binding.Member, bindings); } return binding; } internal virtual MemberListBinding VisitMemberListBinding(MemberListBinding binding) { toStr = toStr + ""Initiailizers->"" + ""\n""; IEnumerable<ElementInit> initializers = this.VisitElementInitializerList(binding.Initializers); if (initializers != binding.Initializers) { return Expression.ListBind(binding.Member, initializers); } return binding; } internal virtual IEnumerable<MemberBinding> VisitBindingList(ReadOnlyCollection<MemberBinding> original) { List<MemberBinding> list = null; for (int i = 0, n = original.Count; i < n; i++) { MemberBinding b = this.VisitBinding(original[i]); if (list != null) { list.Add(b); } else if (b != original[i]) { list = new List<MemberBinding>(n); for (int j = 0; j < i; j++) { list.Add(original[j]); } list.Add(b); } } if (list != null) return list; return original; } internal virtual IEnumerable<ElementInit> VisitElementInitializerList(ReadOnlyCollection<ElementInit> original) { List<ElementInit> list = null; for (int i = 0, n = original.Count; i < n; i++) { ElementInit init = this.VisitElementInitializer(original[i]); if (list != null) { list.Add(init); } else if (init != original[i]) { list = new List<ElementInit>(n); for (int j = 0; j < i; j++) { list.Add(original[j]); } list.Add(init); } } if (list != null) return list; return original; } internal virtual Expression VisitLambda(LambdaExpression lambda) { toStr = toStr + ""Parameters->"" + ""\n""; IEnumerable<ParameterExpression> parms = this.VisitParamExpressionList(lambda.Parameters); toStr = toStr + ""Body->"" + ""\n""; Expression body = this.Visit(lambda.Body); if (body != lambda.Body) { return Expression.Lambda(lambda.Type, body, lambda.Parameters); } return lambda; } internal virtual NewExpression VisitNew(NewExpression nex) { toStr = toStr + ""Constructor->"" + nex.Constructor + ""\n""; toStr = toStr + ""Arguments->"" + ""\n""; IEnumerable<Expression> args = this.VisitExpressionList(nex.Arguments); if (args != nex.Arguments) { return Expression.New(nex.Constructor, args); } return nex; } internal virtual Expression VisitMemberInit(MemberInitExpression init) { toStr = toStr + ""NewExpression->"" + ""\n""; NewExpression n = (NewExpression)this.Visit(init.NewExpression); toStr = toStr + ""Bindings->"" + ""\n""; IEnumerable<MemberBinding> bindings = this.VisitBindingList(init.Bindings); if (n != init.NewExpression || bindings != init.Bindings) { return Expression.MemberInit(n, bindings); } return init; } internal virtual Expression VisitListInit(ListInitExpression init) { toStr = toStr + ""NewExpression->"" + ""\n""; NewExpression n = (NewExpression)this.Visit(init.NewExpression); toStr = toStr + ""Initializers->"" + ""\n""; IEnumerable<ElementInit> initializers = this.VisitElementInitializerList(init.Initializers); if (n != init.NewExpression || initializers != init.Initializers) { return Expression.ListInit(n, initializers); } return init; } internal virtual Expression VisitNewArray(NewArrayExpression na) { toStr = toStr + ""Expressions->"" + ""\n""; IEnumerable<Expression> exprs = this.VisitExpressionList(na.Expressions); if (exprs != na.Expressions) { if (na.NodeType == ExpressionType.NewArrayInit) { return Expression.NewArrayInit(na.Type.GetElementType(), exprs); } else { return Expression.NewArrayBounds(na.Type.GetElementType(), exprs); } } return na; } internal virtual Expression VisitInvocation(InvocationExpression iv) { toStr = toStr + ""Arguments->"" + ""\n""; IEnumerable<Expression> args = this.VisitExpressionList(iv.Arguments); toStr = toStr + ""Lambda->"" + ""\n""; Expression expr = this.Visit(iv.Expression); if (args != iv.Arguments || expr != iv.Expression) { return Expression.Invoke(expr, args); } return iv; } } internal static class ReadOnlyCollectionExtensions { internal static ReadOnlyCollection<T> ToReadOnlyCollection<T>(this IEnumerable<T> sequence) { if (sequence == null) return DefaultReadOnlyCollection<T>.Empty; ReadOnlyCollection<T> col = sequence as ReadOnlyCollection<T>; if (col != null) return col; IList<T> list = sequence as IList<T>; if (list != null) return new ReadOnlyCollection<T>(list); return new ReadOnlyCollection<T>(new List<T>(sequence)); } private static class DefaultReadOnlyCollection<T> { private static ReadOnlyCollection<T> _defaultCollection; internal static ReadOnlyCollection<T> Empty { get { if (_defaultCollection == null) _defaultCollection = new ReadOnlyCollection<T>(new T[] { }); return _defaultCollection; } } } }"; #endregion helpers } }
35.4987
490
0.587942
[ "Apache-2.0" ]
semihokur/pattern-matching-csharp
Src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenExprLambdaTests.cs
177,458
C#
using System; namespace Customizer.Utility { /// <summary> /// Serialize member /// </summary> [AttributeUsageAttribute(AttributeTargets.Field | AttributeTargets.Property)] public sealed class CzSerializeAttribute : Attribute { /// <summary> /// Serialize member /// </summary> /// <param name="tag">Identifier tag</param> public CzSerializeAttribute(int tag) { Tag = tag; } /// <summary> /// Identifier tag /// </summary> public int Tag { get; } } }
25.818182
81
0.56162
[ "MIT" ]
fossabot/Customizer
Customizer/Utility/CzSerializeAttribute.cs
568
C#
using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; namespace System { [Serializable] public readonly struct EnumShortRange<T> : IRange<T, EnumShortRange<T>.Enumerator>, IEquatableReadOnlyStruct<EnumShortRange<T>>, ISerializable where T : unmanaged, Enum { public T Start { get; } public T End { get; } public bool IsFromEnd { get; } public EnumShortRange(T start, T end) { this.Start = start; this.End = end; this.IsFromEnd = false; } public EnumShortRange(T start, T end, bool fromEnd) { this.Start = start; this.End = end; this.IsFromEnd = fromEnd; } private EnumShortRange(SerializationInfo info, StreamingContext context) { if (!Enum<T>.TryParse(info.GetStringOrDefault(nameof(this.Start)), out var start)) start = default; if (!Enum<T>.TryParse(info.GetStringOrDefault(nameof(this.End)), out var end)) end = default; this.Start = start; this.End = end; this.IsFromEnd = info.GetBooleanOrDefault(nameof(this.IsFromEnd)); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue(nameof(this.Start), this.Start.ToString()); info.AddValue(nameof(this.End), this.End.ToString()); info.AddValue(nameof(this.IsFromEnd), this.IsFromEnd); } public void Deconstruct(out T start, out T end) { start = this.Start; end = this.End; } public void Deconstruct(out T start, out T end, out bool fromEnd) { start = this.Start; end = this.End; fromEnd = this.IsFromEnd; } public EnumShortRange<T> With(in T? Start = null, in T? End = null, bool? IsFromEnd = null) => new EnumShortRange<T>( Start ?? this.Start, End ?? this.End, IsFromEnd ?? this.IsFromEnd ); public EnumShortRange<T> FromStart() => new EnumShortRange<T>(this.Start, this.End, false); public EnumShortRange<T> FromEnd() => new EnumShortRange<T>(this.Start, this.End, true); IRange<T> IRange<T>.FromStart() => FromStart(); IRange<T> IRange<T>.FromEnd() => FromEnd(); public short Count() { var startVal = Enum<T>.ToShort(this.Start); var endVal = Enum<T>.ToShort(this.End); if (endVal > startVal) return (short)(endVal - startVal + 1); return (short)(startVal - endVal + 1); } public bool Contains(T value) { var startVal = Enum<T>.ToShort(value); var endVal = Enum<T>.ToShort(value); var val = Enum<T>.ToShort(value); return startVal < endVal ? val >= startVal && val <= endVal : val >= endVal && val <= startVal; } public override bool Equals(object obj) => obj is EnumShortRange<T> other && this.Start.Equals(other.Start) && this.End.Equals(other.End) && this.IsFromEnd == other.IsFromEnd; public bool Equals(in EnumShortRange<T> other) => this.Start.Equals(other.Start) && this.End.Equals(other.End) && this.IsFromEnd == other.IsFromEnd; public bool Equals(EnumShortRange<T> other) => this.Start.Equals(other.Start) && this.End.Equals(other.End) && this.IsFromEnd == other.IsFromEnd; public override int GetHashCode() { #if USE_SYSTEM_HASHCODE return HashCode.Combine(this.Start, this.End, this.IsFromEnd); #endif #pragma warning disable CS0162 // Unreachable code detected var hashCode = -1418356749; hashCode = hashCode * -1521134295 + this.Start.GetHashCode(); hashCode = hashCode * -1521134295 + this.End.GetHashCode(); hashCode = hashCode * -1521134295 + this.IsFromEnd.GetHashCode(); return hashCode; #pragma warning restore CS0162 // Unreachable code detected } public override string ToString() => $"{{ {nameof(this.Start)}={this.Start}, {nameof(this.End)}={this.End}, {nameof(this.IsFromEnd)}={this.IsFromEnd} }}"; public Enumerator GetEnumerator() => new Enumerator(this); public Enumerator Range() => GetEnumerator(); IEnumerator<T> IRange<T>.Range() => GetEnumerator(); public EnumShortRange<T> Normalize() => Normal(this.Start, this.End); /// <summary> /// Create a normal range from (a, b) where <see cref="Start"/> is lesser than <see cref="End"/>. /// </summary> public static EnumShortRange<T> Normal(T a, T b) { var aVal = Enum<T>.ToShort(a); var bVal = Enum<T>.ToShort(b); return aVal > bVal ? new EnumShortRange<T>(b, a) : new EnumShortRange<T>(a, b); } /// <summary> /// Create a range from a size which is greater than 0 /// </summary> /// <exception cref="InvalidOperationException">Size must be greater than 0</exception> public static EnumShortRange<T> FromSize(short value, bool fromEnd = false) { var values = Enum<T>.Values; var size = Math.Min(value, values.LongLength); if (size <= 0) throw new InvalidOperationException("Size must be greater than 0"); var start = default(T); var end = default(T); var last = size - 1; for (var i = 0u; i < size; i++) { if (i == 0u) start = values[i]; else if (i == last) end = values[i]; } return new EnumShortRange<T>(start, end, fromEnd); } public static EnumShortRange<T> FromStart(T start, T end) => new EnumShortRange<T>(start, end, false); public static EnumShortRange<T> FromEnd(T start, T end) => new EnumShortRange<T>(start, end, true); public static implicit operator EnumShortRange<T>(in (T start, T end) value) => new EnumShortRange<T>(value.start, value.end); public static implicit operator EnumShortRange<T>(in (T start, T end, bool fromEnd) value) => new EnumShortRange<T>(value.start, value.end, value.fromEnd); public static implicit operator ReadRange<T, Enumerator.Default>(in EnumShortRange<T> value) => new ReadRange<T, Enumerator.Default>(value.Start, value.End, value.IsFromEnd); public static implicit operator ReadRange<T>(in EnumShortRange<T> value) => new ReadRange<T>(value.Start, value.End, value.IsFromEnd, new Enumerator.Default()); public static implicit operator EnumShortRange<T>(in ReadRange<T> value) => new EnumShortRange<T>(value.Start, value.End, value.IsFromEnd); public static implicit operator EnumShortRange<T>(in ReadRange<T, Enumerator.Default> value) => new EnumShortRange<T>(value.Start, value.End, value.IsFromEnd); public static bool operator ==(in EnumShortRange<T> lhs, in EnumShortRange<T> rhs) => lhs.Start.Equals(rhs.Start) && lhs.End.Equals(rhs.End) && lhs.IsFromEnd == rhs.IsFromEnd; public static bool operator !=(in EnumShortRange<T> lhs, in EnumShortRange<T> rhs) => !lhs.Start.Equals(rhs.Start) || !lhs.End.Equals(rhs.End) || lhs.IsFromEnd != rhs.IsFromEnd; public struct Enumerator : IEnumerator<T> { private readonly short start; private readonly short end; private readonly sbyte sign; private short current; private sbyte flag; public Enumerator(in EnumShortRange<T> range) : this(range.Start, range.End, range.IsFromEnd) { } public Enumerator(T start, T end, bool fromEnd) { var startVal = Enum<T>.ToShort(start); var endVal = Enum<T>.ToShort(end); var increasing = startVal <= endVal; if (fromEnd) { this.start = endVal; this.end = startVal; } else { this.start = startVal; this.end = endVal; } this.sign = (sbyte)(increasing ? (fromEnd ? -1 : 1) : (fromEnd ? 1 : -1)); this.current = this.start; this.flag = -1; } public bool MoveNext() { if (this.flag == 0) { if (this.current == this.end) { this.flag = 1; return false; } this.current += this.sign; return true; } if (this.flag < 0) { this.flag = 0; return true; } return false; } public T Current { get { if (this.flag < 0) throw ThrowHelper.GetInvalidOperationException_InvalidOperation_EnumNotStarted(); if (this.flag > 0) throw ThrowHelper.GetInvalidOperationException_InvalidOperation_EnumEnded(); return Enum<T>.From(this.current); } } public void Dispose() { } object IEnumerator.Current => this.Current; void IEnumerator.Reset() { this.current = this.start; this.flag = -1; } public readonly struct Default : IRangeEnumerator<T> { public IEnumerator<T> Enumerate(T start, T end, bool fromEnd) => new Enumerator(start, end, fromEnd); } } } }
33.530159
146
0.523954
[ "MIT" ]
laicasaane/unity-supplements
System/Range/EnumShortRange{T}.cs
10,564
C#
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Cluster.Codecs { public class ClusterSessionEncoder { public const ushort BLOCK_LENGTH = 40; public const ushort TEMPLATE_ID = 103; public const ushort SCHEMA_ID = 111; public const ushort SCHEMA_VERSION = 6; private ClusterSessionEncoder _parentMessage; private IMutableDirectBuffer _buffer; protected int _offset; protected int _limit; public ClusterSessionEncoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IMutableDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public ClusterSessionEncoder Wrap(IMutableDirectBuffer buffer, int offset) { this._buffer = buffer; this._offset = offset; Limit(offset + BLOCK_LENGTH); return this; } public ClusterSessionEncoder WrapAndApplyHeader( IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder) { headerEncoder .Wrap(buffer, offset) .BlockLength(BLOCK_LENGTH) .TemplateId(TEMPLATE_ID) .SchemaId(SCHEMA_ID) .Version(SCHEMA_VERSION); return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH); } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int ClusterSessionIdEncodingOffset() { return 0; } public static int ClusterSessionIdEncodingLength() { return 8; } public static long ClusterSessionIdNullValue() { return -9223372036854775808L; } public static long ClusterSessionIdMinValue() { return -9223372036854775807L; } public static long ClusterSessionIdMaxValue() { return 9223372036854775807L; } public ClusterSessionEncoder ClusterSessionId(long value) { _buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian); return this; } public static int CorrelationIdEncodingOffset() { return 8; } public static int CorrelationIdEncodingLength() { return 8; } public static long CorrelationIdNullValue() { return -9223372036854775808L; } public static long CorrelationIdMinValue() { return -9223372036854775807L; } public static long CorrelationIdMaxValue() { return 9223372036854775807L; } public ClusterSessionEncoder CorrelationId(long value) { _buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian); return this; } public static int OpenedLogPositionEncodingOffset() { return 16; } public static int OpenedLogPositionEncodingLength() { return 8; } public static long OpenedLogPositionNullValue() { return -9223372036854775808L; } public static long OpenedLogPositionMinValue() { return -9223372036854775807L; } public static long OpenedLogPositionMaxValue() { return 9223372036854775807L; } public ClusterSessionEncoder OpenedLogPosition(long value) { _buffer.PutLong(_offset + 16, value, ByteOrder.LittleEndian); return this; } public static int TimeOfLastActivityEncodingOffset() { return 24; } public static int TimeOfLastActivityEncodingLength() { return 8; } public static long TimeOfLastActivityNullValue() { return -9223372036854775808L; } public static long TimeOfLastActivityMinValue() { return -9223372036854775807L; } public static long TimeOfLastActivityMaxValue() { return 9223372036854775807L; } public ClusterSessionEncoder TimeOfLastActivity(long value) { _buffer.PutLong(_offset + 24, value, ByteOrder.LittleEndian); return this; } public static int CloseReasonEncodingOffset() { return 32; } public static int CloseReasonEncodingLength() { return 4; } public ClusterSessionEncoder CloseReason(CloseReason value) { _buffer.PutInt(_offset + 32, (int)value, ByteOrder.LittleEndian); return this; } public static int ResponseStreamIdEncodingOffset() { return 36; } public static int ResponseStreamIdEncodingLength() { return 4; } public static int ResponseStreamIdNullValue() { return -2147483648; } public static int ResponseStreamIdMinValue() { return -2147483647; } public static int ResponseStreamIdMaxValue() { return 2147483647; } public ClusterSessionEncoder ResponseStreamId(int value) { _buffer.PutInt(_offset + 36, value, ByteOrder.LittleEndian); return this; } public static int ResponseChannelId() { return 7; } public static string ResponseChannelCharacterEncoding() { return "US-ASCII"; } public static string ResponseChannelMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int ResponseChannelHeaderLength() { return 4; } public ClusterSessionEncoder PutResponseChannel(IDirectBuffer src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public ClusterSessionEncoder PutResponseChannel(byte[] src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public ClusterSessionEncoder ResponseChannel(string value) { int length = value.Length; if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutStringWithoutLengthAscii(limit + headerLength, value); return this; } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { ClusterSessionDecoder writer = new ClusterSessionDecoder(); writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION); return writer.AppendTo(builder); } } }
22.351499
97
0.636109
[ "Apache-2.0" ]
23dproject/Aeron.NET
src/Adaptive.Cluster/Codecs/ClusterSessionEncoder.cs
8,203
C#
using System; using Eto.Parse.Parsers; namespace Eto.Parse { partial class Parser { public static Parser operator !(Parser parser) { var inverse = parser as IInverseParser; if (inverse != null) { if (!parser.Reusable) { parser = parser.Clone(); inverse = parser as IInverseParser; } inverse.Inverse = !inverse.Inverse; return parser; } return new LookAheadParser(parser) { Reusable = true }; } public static RepeatParser operator +(Parser parser) { return new RepeatParser(parser, 1) { Reusable = true }; } public static RepeatParser operator -(Parser parser) { return new RepeatParser(parser, 0) { Reusable = true }; } public static AlternativeParser operator |(Parser left, Parser right) { var alternative = left as AlternativeParser; if (alternative != null && alternative.Reusable) { alternative.Items.Add(right); return alternative; } /*alternative = right as AlternativeParser; if (alternative != null && alternative.Reusable) { alternative.Items.Insert(0, left); return alternative; }*/ return new AlternativeParser(left, right) { Reusable = true }; } public static OptionalParser operator ~(Parser parser) { return new OptionalParser(parser) { Reusable = true }; } public static implicit operator Parser(char ch) { var parser = Terminals.Set(ch); parser.Reusable = true; return parser; } public static implicit operator Parser(char[] chars) { var parser = Terminals.Set(chars); parser.Reusable = true; return parser; } public static implicit operator Parser(string literalString) { return new LiteralTerminal(literalString) { Reusable = true }; } public static SequenceParser operator &(Parser left, Parser right) { var sequence = left as SequenceParser; if (sequence != null && sequence.Reusable) { sequence.Items.Add(right); return sequence; } /*sequence = right as SequenceParser; if (sequence != null && sequence.Reusable) { sequence.Items.Insert(0, left); return sequence; }*/ return new SequenceParser(left, right) { Reusable = true }; } public static ExceptParser operator -(Parser include, Parser exclude) { return new ExceptParser(include, exclude); } public static RepeatParser operator *(Parser parser, int repetitions) { return new RepeatParser(parser, repetitions, repetitions); } } }
23.380952
71
0.67943
[ "MIT" ]
ArsenShnurkov/Eto.Parse
Eto.Parse/Parser.operators.cs
2,455
C#
namespace _12D_Nechetni { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.firstNumberTextBox = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.allNumbersTextBox = new System.Windows.Forms.TextBox(); this.getUnevenNumbersButton = new System.Windows.Forms.Button(); this.unevenNumbersTextBox = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(13, 9); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(85, 17); this.label1.TabIndex = 0; this.label1.Text = "firstNumber:"; // // firstNumberTextBox // this.firstNumberTextBox.Location = new System.Drawing.Point(15, 30); this.firstNumberTextBox.Name = "firstNumberTextBox"; this.firstNumberTextBox.Size = new System.Drawing.Size(96, 22); this.firstNumberTextBox.TabIndex = 1; this.firstNumberTextBox.TextChanged += new System.EventHandler(this.firstNumberTextBox_TextChanged); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(173, 9); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(69, 17); this.label2.TabIndex = 2; this.label2.Text = "Numbers:"; // // allNumbersTextBox // this.allNumbersTextBox.BackColor = System.Drawing.SystemColors.Info; this.allNumbersTextBox.Location = new System.Drawing.Point(176, 29); this.allNumbersTextBox.Name = "allNumbersTextBox"; this.allNumbersTextBox.ReadOnly = true; this.allNumbersTextBox.Size = new System.Drawing.Size(612, 22); this.allNumbersTextBox.TabIndex = 3; // // getUnevenNumbersButton // this.getUnevenNumbersButton.Location = new System.Drawing.Point(16, 112); this.getUnevenNumbersButton.Name = "getUnevenNumbersButton"; this.getUnevenNumbersButton.Size = new System.Drawing.Size(772, 39); this.getUnevenNumbersButton.TabIndex = 4; this.getUnevenNumbersButton.Text = "Get Uneven"; this.getUnevenNumbersButton.UseVisualStyleBackColor = true; this.getUnevenNumbersButton.Click += new System.EventHandler(this.getUnevenNumbersButton_Click); // // unevenNumbersTextBox // this.unevenNumbersTextBox.BackColor = System.Drawing.SystemColors.Info; this.unevenNumbersTextBox.Location = new System.Drawing.Point(15, 157); this.unevenNumbersTextBox.Name = "unevenNumbersTextBox"; this.unevenNumbersTextBox.ReadOnly = true; this.unevenNumbersTextBox.Size = new System.Drawing.Size(773, 22); this.unevenNumbersTextBox.TabIndex = 5; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 450); this.Controls.Add(this.unevenNumbersTextBox); this.Controls.Add(this.getUnevenNumbersButton); this.Controls.Add(this.allNumbersTextBox); this.Controls.Add(this.label2); this.Controls.Add(this.firstNumberTextBox); this.Controls.Add(this.label1); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox firstNumberTextBox; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox allNumbersTextBox; private System.Windows.Forms.Button getUnevenNumbersButton; private System.Windows.Forms.TextBox unevenNumbersTextBox; } }
42.795082
112
0.598927
[ "MIT" ]
FullscreenSauna/School-12th-grade
First Semester/12D_Nechetni/12D_Nechetni/Form1.Designer.cs
5,223
C#
using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace Weixin.Next.Utilities { // Modified version of http://stackoverflow.com/questions/2196767/c-implementing-networkstream-peek/7281113#7281113 /// <summary> /// PeekableStream wraps a Stream and can be used to peek ahead in the underlying stream, /// without consuming the bytes. In other words, doing Peek() will allow you to look ahead in the stream, /// but it won't affect the result of subsequent Read() calls. /// /// This is sometimes necessary, e.g. for peeking at the magic number of a stream of bytes and decide which /// stream processor to hand over the stream. /// </summary> internal class PeekableStream : Stream { private readonly Stream _underlyingStream; private readonly byte[] _lookAheadBuffer; private int _lookAheadIndex; public PeekableStream(Stream underlyingStream, int maxPeekBytes) { this._underlyingStream = underlyingStream; _lookAheadBuffer = new byte[maxPeekBytes]; } protected override void Dispose(bool disposing) { if (disposing) _underlyingStream.Dispose(); base.Dispose(disposing); } /// <summary> /// Peeks at a maximum of count bytes, or less if the stream ends before that number of bytes can be read. /// /// Calls to this method do not influence subsequent calls to Read() and Peek(). /// /// Please note that this method will always peek count bytes unless the end of the stream is reached before that - in contrast to the Read() /// method, which might read less than count bytes, even though the end of the stream has not been reached. /// </summary> /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and /// (offset + number-of-peeked-bytes - 1) replaced by the bytes peeked from the current source.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data peeked from the current stream.</param> /// <param name="count">The maximum number of bytes to be peeked from the current stream.</param> /// <returns>The total number of bytes peeked into the buffer. If it is less than the number of bytes requested then the end of the stream has been reached.</returns> public virtual int Peek(byte[] buffer, int offset, int count) { if (count > _lookAheadBuffer.Length) throw new ArgumentOutOfRangeException(nameof(count), "must be smaller than peekable size, which is " + _lookAheadBuffer.Length); while (_lookAheadIndex < count) { int bytesRead = _underlyingStream.Read(_lookAheadBuffer, _lookAheadIndex, count - _lookAheadIndex); if (bytesRead == 0) // end of stream reached break; _lookAheadIndex += bytesRead; } int peeked = Math.Min(count, _lookAheadIndex); Array.Copy(_lookAheadBuffer, 0, buffer, offset, peeked); return peeked; } /// <summary> /// Peeks at a maximum of count bytes, or less if the stream ends before that number of bytes can be read. /// /// Calls to this method do not influence subsequent calls to Read() and Peek(). /// /// Please note that this method will always peek count bytes unless the end of the stream is reached before that - in contrast to the Read() /// method, which might read less than count bytes, even though the end of the stream has not been reached. /// </summary> /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and /// (offset + number-of-peeked-bytes - 1) replaced by the bytes peeked from the current source.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data peeked from the current stream.</param> /// <param name="count">The maximum number of bytes to be peeked from the current stream.</param> /// <returns>The total number of bytes peeked into the buffer. If it is less than the number of bytes requested then the end of the stream has been reached.</returns> public virtual async Task<int> PeekAsync(byte[] buffer, int offset, int count) { if (count > _lookAheadBuffer.Length) throw new ArgumentOutOfRangeException(nameof(count), "must be smaller than peekable size, which is " + _lookAheadBuffer.Length); while (_lookAheadIndex < count) { int bytesRead = await _underlyingStream.ReadAsync(_lookAheadBuffer, _lookAheadIndex, count - _lookAheadIndex).ConfigureAwait(false); if (bytesRead == 0) // end of stream reached break; _lookAheadIndex += bytesRead; } int peeked = Math.Min(count, _lookAheadIndex); Array.Copy(_lookAheadBuffer, 0, buffer, offset, peeked); return peeked; } public override bool CanRead { get { return true; } } public override long Position { get { return _underlyingStream.Position - _lookAheadIndex; } set { _underlyingStream.Position = value; _lookAheadIndex = 0; // this needs to be done AFTER the call to underlyingStream.Position, as that might throw NotSupportedException, // in which case we don't want to change the lookAhead status } } public override int Read(byte[] buffer, int offset, int count) { int bytesTakenFromLookAheadBuffer = 0; if (count > 0 && _lookAheadIndex > 0) { bytesTakenFromLookAheadBuffer = Math.Min(count, _lookAheadIndex); Array.Copy(_lookAheadBuffer, 0, buffer, offset, bytesTakenFromLookAheadBuffer); count -= bytesTakenFromLookAheadBuffer; offset += bytesTakenFromLookAheadBuffer; _lookAheadIndex -= bytesTakenFromLookAheadBuffer; if (_lookAheadIndex > 0) // move remaining bytes in lookAheadBuffer to front // copying into same array should be fine, according to http://msdn.microsoft.com/en-us/library/z50k9bft(v=VS.90).aspx : // "If sourceArray and destinationArray overlap, this method behaves as if the original values of sourceArray were preserved // in a temporary location before destinationArray is overwritten." Array.Copy(_lookAheadBuffer, _lookAheadBuffer.Length - bytesTakenFromLookAheadBuffer + 1, _lookAheadBuffer, 0, _lookAheadIndex); } return count > 0 ? bytesTakenFromLookAheadBuffer + _underlyingStream.Read(buffer, offset, count) : bytesTakenFromLookAheadBuffer; } public override int ReadByte() { if (_lookAheadIndex > 0) { _lookAheadIndex--; byte firstByte = _lookAheadBuffer[0]; if (_lookAheadIndex > 0) // move remaining bytes in lookAheadBuffer to front Array.Copy(_lookAheadBuffer, 1, _lookAheadBuffer, 0, _lookAheadIndex); return firstByte; } else { return _underlyingStream.ReadByte(); } } public override long Seek(long offset, SeekOrigin origin) { long ret = _underlyingStream.Seek(offset, origin); _lookAheadIndex = 0; // this needs to be done AFTER the call to underlyingStream.Seek(), as that might throw NotSupportedException, // in which case we don't want to change the lookAhead status return ret; } public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { int bytesTakenFromLookAheadBuffer = 0; if (count > 0 && _lookAheadIndex > 0) { bytesTakenFromLookAheadBuffer = Math.Min(count, _lookAheadIndex); Array.Copy(_lookAheadBuffer, 0, buffer, offset, bytesTakenFromLookAheadBuffer); count -= bytesTakenFromLookAheadBuffer; offset += bytesTakenFromLookAheadBuffer; _lookAheadIndex -= bytesTakenFromLookAheadBuffer; if (_lookAheadIndex > 0) // move remaining bytes in lookAheadBuffer to front // copying into same array should be fine, according to http://msdn.microsoft.com/en-us/library/z50k9bft(v=VS.90).aspx : // "If sourceArray and destinationArray overlap, this method behaves as if the original values of sourceArray were preserved // in a temporary location before destinationArray is overwritten." Array.Copy(_lookAheadBuffer, _lookAheadBuffer.Length - bytesTakenFromLookAheadBuffer + 1, _lookAheadBuffer, 0, _lookAheadIndex); } return count > 0 ? bytesTakenFromLookAheadBuffer + await _underlyingStream.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false) : bytesTakenFromLookAheadBuffer; } // from here on, only simple delegations to underlyingStream public override bool CanSeek { get { return _underlyingStream.CanSeek; } } public override bool CanWrite { get { return _underlyingStream.CanWrite; } } public override bool CanTimeout { get { return _underlyingStream.CanTimeout; } } public override int ReadTimeout { get { return _underlyingStream.ReadTimeout; } set { _underlyingStream.ReadTimeout = value; } } public override int WriteTimeout { get { return _underlyingStream.WriteTimeout; } set { _underlyingStream.WriteTimeout = value; } } public override void Flush() { _underlyingStream.Flush(); } public override Task FlushAsync(CancellationToken cancellationToken) { return _underlyingStream.FlushAsync(cancellationToken); } public override long Length { get { return _underlyingStream.Length; } } public override void SetLength(long value) { _underlyingStream.SetLength(value); } public override void Write(byte[] buffer, int offset, int count) { _underlyingStream.Write(buffer, offset, count); } public override void WriteByte(byte value) { _underlyingStream.WriteByte(value); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return _underlyingStream.WriteAsync(buffer, offset, count, cancellationToken); } } }
53.601896
174
0.631123
[ "MIT" ]
deerchao/weixin.next
src/Weixin.Next/Utilities/PeekableStream.cs
11,312
C#
namespace Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.Implementation { using System; using System.Collections.Generic; using System.IO; using System.Linq; internal class PlatformFolder : IPlatformFolder { private readonly DirectoryInfo folder; public PlatformFolder(DirectoryInfo folder) { if (folder == null) { throw new ArgumentNullException("folder"); } this.folder = folder; } public string Name { get { return this.folder.Name; } } internal DirectoryInfo Folder { get { return this.folder; } } public bool Exists() { return Directory.Exists(this.folder.FullName); } public void Delete() { this.folder.Delete(); } public IEnumerable<IPlatformFile> GetFiles() { try { return this.folder.GetFiles().Select(fileInfo => new PlatformFile(fileInfo)); } catch (DirectoryNotFoundException) { // Return empty list for compatibility with Windows runtime. return Enumerable.Empty<IPlatformFile>(); } } public IPlatformFile CreateFile(string fileName) { // Check argument manually for consistent behavior on both Silverlight and Windows runtimes if (fileName == null) { throw new ArgumentNullException("fileName"); } if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentException("fileName"); } this.folder.Create(); var fileInfo = new FileInfo(Path.Combine(this.folder.FullName, fileName)); if (fileInfo.Exists) { throw new IOException("Cannot create file '" + fileName + "' because it already exists."); } using (fileInfo.Create()) { } return new PlatformFile(fileInfo); } } }
26.658537
106
0.52882
[ "MIT" ]
pakrym/ApplicationInsights-dotnet
src/TelemetryChannels/ServerTelemetryChannel/Shared/Implementation/PlatformFolder.cs
2,188
C#
using BlueSheep.Interface; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; namespace BlueSheep.Engine.Constants { public class Translate { #region Fields private static Dictionary<string, string> Dic = new Dictionary<string, string>(); private static int ENInitialized = 0; private static int PTInitialized = 0; private static int ESInitialized = 0; #endregion #region Public Methods public static void TranslateUC(UserControl uc) { foreach (Control c in uc.Controls) { c.Text = GetTranslation(c.Text, MainForm.ActualMainForm.Lang); } } public static string GetTranslation(string content, string langue) { switch (langue) { case "FR": return content; case "EN": if (ENInitialized == 0) InitEN(); break; case "PT": if (PTInitialized == 0) InitPT(); break; case "ES": if (ESInitialized == 0) InitES(); break; } foreach (KeyValuePair<string, string> pair in Dic) { if (content.Contains(pair.Key)) content = content.Replace(pair.Key, pair.Value); } return content; } #endregion #region Private Methods private static void InitEN() { Dic.Clear(); Dic.Add("Connecté", "Connected"); Dic.Add("Déconnecté", "Disconnected"); Dic.Add("Dialogue", "Speaking"); Dic.Add("Régénération", "Regenerating"); Dic.Add("Récolte", "Gathering"); Dic.Add("Déplacement", "Moving"); Dic.Add("Combat", "Fighting"); Dic.Add("Téléportation", "Teleportating"); Dic.Add("est mort", "is dead"); Dic.Add("Fin du tour", "Turn ended"); Dic.Add("Equipement rapide numero", "Stuff preset number"); Dic.Add("Trajet arrêté", "Path Stopped"); Dic.Add("Reconnexion automatique dans minutes", "Reconnection in X minutes"); Dic.Add("Prochain repas dans", "Next meal in"); Dic.Add("Aucune nourriture disponible, pas de prochaine connexion", "No food available, stay disconnected."); Dic.Add("Connexion", "Connecting"); Dic.Add("Je suis le chef de groupe biatch", "I'm the group leader biatch !"); Dic.Add("Trajet chargé", "Path loaded "); Dic.Add("Erreur lors de la sélection du personnage", "Error during the selection of the character"); Dic.Add("Serveur complet", "The server is full, try again later"); Dic.Add("Echec de connexion : Dofus a été mis à jour", "Connection failure, Dofus has been updated. Try again later"); Dic.Add("Echec de connexion : Vous êtes bannis", "Connection failure, your account has been banned"); Dic.Add("Identification en cours", "Identification in process"); Dic.Add("Identification réussie", "Identification successful"); Dic.Add("Echec de l'identification", "Identification failure"); Dic.Add("J'ai rejoint le groupe", "I joined the group"); Dic.Add("Ancienne cellid of", "Last cellid of"); Dic.Add("Nouvelle cellid of", "New cellid of "); Dic.Add("Début du combat", "Fight started"); Dic.Add("Combat fini !", "Fight is over !"); Dic.Add("Echec de l'ouverture du coffre", "Failed to open the chest"); Dic.Add("File d'attente", "Position in queue"); Dic.Add("Déconnecté du serveur", "Disconnected from the server"); Dic.Add("Inactivité prolongée", "Prolonged inactivity"); Dic.Add("Connexion établie au serveur", "Connected to server"); Dic.Add("Connexion échouée", " Connection failed"); Dic.Add("Lancement du trajet", "Path launched"); Dic.Add("Echec de connexion : compte banni temporairement", "Connection failure, your account is temporarily banned"); Dic.Add("Echec de connexion : compte banni", "Connection failure, your account is banned"); Dic.Add("Echec de connexion : serveur en maintenance", "Connection failure, server's is down for maintenance"); Dic.Add("Echec de connexion : erreur inconnue", "Connection failure : Uknown error"); Dic.Add("Echec de connnexion : serveur déconnecté", "connection failure, servor disconnected"); Dic.Add("Echec de connexion : serveur en sauvegarde", "Connection failure, the server is down for backup"); Dic.Add("Echec de connexion : serveur complet", "connection failure, servor is full"); Dic.Add("Echec de connexion : raison inconnue", "Connection failure : Unknown cause"); Dic.Add("Récupération d'un objet du coffre", "Taking an item from the chest"); Dic.Add("Fermeture du coffre", "Closing the chest"); Dic.Add("Ouverture du coffre", "Opening the chest"); Dic.Add("Dépôt d'un objet dans le coffre", "Putting an item in the chest"); Dic.Add("est connecté", "is connected"); Dic.Add("Fight Turn", "Fight Turn"); Dic.Add("Sort validé", "Spell agreed-upon"); Dic.Add("Cible en vue à la cellule", "Traget is on the cell n°"); Dic.Add("It's Time to capture ! POKEBALL GOOOOOOOO", "It's Time to capture ! POKEBALL GOOOOOOOO"); Dic.Add("Lancement d'un combat contre monstres de niveau", "Starting a fight against monsters of level "); Dic.Add("Lancement d'un sort en", "Launching a spell at"); Dic.Add("Placement du personnage", "Character's in-fight position"); Dic.Add("Impossible d'enclencher le déplacement", "Unable to move"); Dic.Add("Le bot n'a pas encore reçu les informations de la map, veuillez patienter. Si le problème persiste, rapportez le beug sur forum : http://forum.bluesheepbot.com ", "The bot didn't receive the map's informations yet, please check out later, if the poblem persists, report it on the forum : http://forum.bluesheep.com"); Dic.Add("Up de caractéristique", "Enhance characteristics"); Dic.Add("Envoi de la réponse", "Sending the answer"); Dic.Add("Aucune réponse disponible dans le trajet", "No answer available in the path for this ask"); Dic.Add("au serveur de jeu", "to the game's server"); Dic.Add("au serveur d'identification", "to the authentication's server"); Dic.Add("La récolte n'est pas encore implémentée, veuillez attendre la mise à jour. Tenez vous au courant sur", "Gathering isn't already implemented, please wait a release. Stay updated on"); ENInitialized = 1; } private static void InitES() { Dic.Clear(); Dic.Add("Connecté", "Conectado"); Dic.Add("Déconnecté", "Desconectado"); Dic.Add("Dialogue", "Diálogo"); Dic.Add("Régénération", "Regeneración"); Dic.Add("Récolte", "Cosecha"); Dic.Add("Déplacement", "Desplazamiento"); Dic.Add("Combat", "Combate"); Dic.Add("Téléportation", "Teleportación"); Dic.Add("Trajet arrêté", "Camino detuvo"); Dic.Add("Reconnexion automatique dans minutes", "Reconexión en X minutos"); Dic.Add("Prochain repas dans heures", "Alimentación Siguiente X horas"); Dic.Add("Aucune nourriture disponible, pas de prochaine connexion", "No hay comida disponible, mantenerse desconectado"); Dic.Add("Connexion", "Conectando"); Dic.Add("Je suis le chef de groupe biatch", "Yo soy el líder del grupo, perra"); Dic.Add("Trajet chargé", "Camino cargado"); Dic.Add("Erreur lors de la sélection du personnage", "Error durante la selección de personaje"); Dic.Add("Serveur complet", "Servidor está llena, inténtalo más tarde"); Dic.Add("Echec de connexion : Dofus a été mis à jour", "Error de conexión, Dofus se ha actualizado, intentarlo más tarde"); Dic.Add("Echec de connexion : Vous êtes bannis", "Error de conexión, tu cuenta ha sido prohibido"); Dic.Add("Identification en cours", "Identificación en curso"); Dic.Add("Identification réussie", "Identificado con éxito"); Dic.Add("Echec de l'identification", "Fracaso de identificación"); Dic.Add("Bienvenue sur DOFUS, dans le Monde des Douze !", "Bienvenido a DOFUS, el Mundo de los Doce"); Dic.Add("Il est interdit de transmettre votre identifiant ou votre mot de passe", "Se prohíbe transmitir su nombre de usuario o contraseña."); Dic.Add("Votre adresse IP actuelle est", "Su dirección de IP es"); Dic.Add("Impossible de lancer ce sort, vous avez une portée de", "Incapaz de lanzar el hechizo, tiene un rango de, y está apuntando a 2"); Dic.Add("J'ai rejoint le groupe", "Me uní a un grupo"); Dic.Add("Ancienn cellid of", "Última ID de celda"); Dic.Add("Nouvelle cellid of", "Nuevo ID de celda"); Dic.Add("Début du combat", "Lucha comenzado"); Dic.Add("GameMap Ancienne cellid of", "Última ID de celda del Mapa de Juego"); Dic.Add("GameMap Nouvelle cellid of", "Nuevo ID de celda del Mapa de Juego"); Dic.Add("Send ready !", "Envía listo"); Dic.Add("Combat fini !", "Lucha ha terminado"); Dic.Add("Echec de l'ouverture du coffre", "Error al abrir el baul"); Dic.Add("File d'attente", "Posición en la cola"); Dic.Add("Déconnecté du serveur", "desconectado del servidor"); Dic.Add("Inactivité prolongée", "inactividad prolongada"); Dic.Add("Connexion établie au serveur", "Conectado al servidor"); Dic.Add("Connexion échouée", "Error de conexión"); Dic.Add("Lancement du trajet", "Lanzamiento de camino"); Dic.Add("Echec de connexion : compte banni temporairement", "Error de conexión, Su cuenta se temporalmente prohibido"); Dic.Add("Echec de connexion : compte banni", "Error en la conexión, su cuenta está prohibida"); Dic.Add("Echec de connexion : serveur en maintenance", "Error de conexión, el servidor es cerrado por mantenimiento"); Dic.Add("Echec de connexion : erreur inconnue", "Error de conexión: Error desconocido"); Dic.Add("Echec de connnexion : serveur déconnecté", "Error de conexión, servidor está desconectado"); Dic.Add("Echec de connexion : serveur en sauvegarde", "Error de conexión: el servidor no funciona para copia de seguridad"); Dic.Add("Echec de connexion : serveur complet", "Error de conexión, servidor está lleno"); Dic.Add("Echec de connexion : raison inconnue", "Error de conexión: Causa desconocida"); Dic.Add("Récupération d'un objet du coffre", "Recogiendo un elemento del baul"); Dic.Add("Fermeture du coffre", "Cerrando el baul"); Dic.Add("Ouverture du coffre", "Abriendo el baul"); Dic.Add("Dépôt d'un objet dans le coffre", "Abriendo el baul"); Dic.Add("est connecté", "se encuentra conectado"); Dic.Add("Fight Turn", "Su vez"); Dic.Add("Sort validé", "Hechizo validado"); Dic.Add("Cible en vue à la cellule", "Del objetivo es el número de células."); Dic.Add("It's Time to capture ! POKEBALL GOOOOOOOO", "Es hora de capturar! Pokeball GOOOOOO"); Dic.Add("Lancement d'un combat contre monstres de niveau", "Inicio de una lucha contra monstruos de nivel"); Dic.Add("Lancement d'un sort en", "Al lanzar un hechizo sobre"); Dic.Add("Placement du personnage", "Carácter en posición de luchar"); Dic.Add("Impossible d'enclencher le déplacement", "No se puede mover"); Dic.Add("Le bot n'a pas encore reçu les informations de la map, veuillez patienter. Si le problème persiste, rapportez le beug sur forum : http://forum.bluesheepbot.com", "El Bot no ha recibido información, Por favor, vuelva más tarde, si el problema persiste, notifique foro: http://forum.bluesheep.com"); Dic.Add("Up de caractéristique", "Mejorar características"); ESInitialized = 1; } private static void InitPT() { Dic.Clear(); Dic.Add("Connecté", "Conectado"); Dic.Add("Déconnecté", "Desconectado"); Dic.Add("Dialogue", "Diálogo"); Dic.Add("Régénération", "Regeneração"); Dic.Add("Récolte", "Colheita"); Dic.Add("Déplacement", "Deslocação"); Dic.Add("Combat", "Briga"); Dic.Add("Téléportation", "Teletransporte"); Dic.Add("Trajet arrêté", "Trajeto Parou"); Dic.Add("Reconnexion automatique dans minutes", "Reconexão em X minutos"); Dic.Add("Prochain repas dans heures", "Próxima alimentação em X horas"); Dic.Add("Aucune nourriture disponible, pas de prochaine connexion", "Sem comida disponível, permaneça desconectado"); Dic.Add("Connexion", "Conectando"); Dic.Add("Je suis le chef de groupe biatch", "Eu sou o líder do grupo, cadela"); Dic.Add("Trajet chargé", "Caminho carregado"); Dic.Add("Erreur lors de la sélection du personnage", "Erro durante seleção do personagem"); Dic.Add("Serveur complet", "Servidor está cheio, tente novamente mais tarde"); Dic.Add("Echec de connexion : Dofus a été mis à jour", "Erro de conexão, Dofus foi atualizado, tente novamente mais tarde"); Dic.Add("Echec de connexion : Vous êtes bannis", "Erro de conexão, sua conta foi banida"); Dic.Add("Identification en cours", "Identificação em processo"); Dic.Add("Identification réussie", "Identificado com sucesso"); Dic.Add("Echec de l'identification", "Falha de identificação"); Dic.Add("Bienvenue sur DOFUS, dans le Monde des Douze !", "Bem vindo ao Dofus, "); Dic.Add("Il est interdit de transmettre votre identifiant ou votre mot de passe", "É proibido transferir);transmitir seu nome de usuário e senha"); Dic.Add("Votre adresse IP actuelle est", "Seu endereço IP é"); Dic.Add("Impossible de lancer ce sort, vous avez une portée de 0 à 1, et vous visez à 2 !", ""); Dic.Add("J'ai rejoint le groupe", "Impossível lançar o feitiço, você tem um alcance de 0 a 1, e está mirando a 2"); Dic.Add("Ancienn cellid of", "Eu ingressei em um grupo"); Dic.Add("Nouvelle cellid of", "ùltima id de célula de"); Dic.Add("Début du combat", "Combate começou"); Dic.Add("GameMap Ancienne cellid of", "Última id de célula do Mapa do Jogo"); Dic.Add("GameMap Nouvelle cellid of", "Nova id de célula do Mapa do Jogo"); Dic.Add("Send ready !", "Enviar pronto"); Dic.Add("Combat fini !", "Fim de combate "); Dic.Add("Echec de l'ouverture du coffre", "Falhou ao abrir o baú"); Dic.Add("File d'attente", "Posição na fila"); Dic.Add("Déconnecté du serveur", "Disconectado do servidor"); Dic.Add("Inactivité prolongée", "Inatividade prolongada"); Dic.Add("Connexion établie au serveur", "Conectado ao servidor"); Dic.Add("Connexion échouée", "Conexão falhou"); Dic.Add("Lancement du trajet", "Lançamento do caminho"); Dic.Add("Echec de connexion : compte banni temporairement", "Falha de conexão, sua conta está temporariamente banida"); Dic.Add("Echec de connexion : compte banni", "Falha de conexão, sua conta está banida"); Dic.Add("Echec de connexion : serveur en maintenance", "Falha de conexão, servidor está inativo para manutenção"); Dic.Add("Echec de connexion : erreur inconnue", "Falha de conexão: Erro desconhecido"); Dic.Add("Echec de connnexion : serveur déconnecté", "Falha de conexão, servidor está disconectado"); Dic.Add("Echec de connexion : serveur en sauvegarde", "Falha de conexão: o servidor está inativo para cópia de segurança"); Dic.Add("Echec de connexion : serveur complet", "Falha de conexão, servidor está cheio"); Dic.Add("Echec de connexion : raison inconnue", "Falha de conexão: Causa desconhecida"); Dic.Add("Récupération d'un objet du coffre", "Pegando um item do baú"); Dic.Add("Fermeture du coffre", "Fechando o baú"); Dic.Add("Ouverture du coffre", "Abrindo o baú"); Dic.Add("Dépôt d'un objet dans le coffre", "Colocando um item no baú"); Dic.Add("est connecté", "está conectado"); Dic.Add("Fight Turn", "Turno da luta"); Dic.Add("Sort validé", "Feitiço validado"); Dic.Add("Cible en vue à la cellule", "O alvo está na célula número..."); Dic.Add("It's Time to capture ! POKEBALL GOOOOOOOO", "É hora de capturar! Pokebola vaaaaaaaaiii"); Dic.Add("Lancement d'un combat contre monstres de niveau", "Iniciando a luta contra monstros de nível"); Dic.Add("Lancement d'un sort en", "Lançando um feitiço em"); Dic.Add("Placement du personnage", "Personagem em posição de luta"); Dic.Add("Impossible d'enclencher le déplacement", "Incapaz de se mover"); Dic.Add("Le bot n'a pas encore reçu les informations de la map, veuillez patienter. Si le problème persiste, rapportez le beug sur forum : http://forum.bluesheepbot.com ", "O Bot não recebeu informações ainda, por favor, cheque novamente mais tarde, se o problema persistir, avise no fórum: http://forum.bluesheep.com"); Dic.Add("Up de caractéristique", "Melhorar Características"); PTInitialized = 1; } #endregion } }
67.962963
338
0.615695
[ "MIT" ]
Sadikk/BlueSheep
BlueSheep/Engine/Constants/Translate.cs
18,606
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using SPNewsData.Data.Context; namespace SPNewsData.Data.Migrations { [DbContext(typeof(SPNewsDataContext))] [Migration("20211107134836_content")] partial class content { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Relational:MaxIdentifierLength", 64) .HasAnnotation("ProductVersion", "5.0.11"); modelBuilder.Entity("SPNewsData.Domain.Entities.GovNews", b => { b.Property<int?>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<DateTime?>("CaptureDate") .ValueGeneratedOnAdd() .HasColumnType("datetime(6)") .HasDefaultValueSql("(CURRENT_TIMESTAMP)"); b.Property<string>("Content") .HasColumnType("text"); b.Property<DateTime?>("PublicationDate") .HasColumnType("datetime(6)"); b.Property<string>("Source") .HasColumnType("longtext"); b.Property<string>("Subtitle") .HasColumnType("longtext"); b.Property<string>("Title") .HasColumnType("longtext"); b.HasKey("Id"); b.ToTable("GovNews"); }); modelBuilder.Entity("SPNewsData.Domain.Entities.Subject", b => { b.Property<int?>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<int?>("GovNewsId") .HasColumnType("int"); b.Property<string>("Name") .HasColumnType("longtext"); b.HasKey("Id"); b.HasIndex("GovNewsId"); b.ToTable("Subjects"); }); modelBuilder.Entity("SPNewsData.Domain.Entities.UrlExtracted", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("Search") .HasColumnType("longtext"); b.Property<string>("Title") .HasColumnType("longtext"); b.Property<string>("Url") .HasColumnType("longtext"); b.HasKey("Id"); b.ToTable("UrlExtracteds"); }); modelBuilder.Entity("SPNewsData.Domain.Entities.Subject", b => { b.HasOne("SPNewsData.Domain.Entities.GovNews", "GovNews") .WithMany("Subjects") .HasForeignKey("GovNewsId"); b.Navigation("GovNews"); }); modelBuilder.Entity("SPNewsData.Domain.Entities.GovNews", b => { b.Navigation("Subjects"); }); #pragma warning restore 612, 618 } } }
32.513761
79
0.475451
[ "MIT" ]
Marcus-V-Freitas/CrawlerBrazilGovData
Contexts/SPNewsData/SPNewsData.Data/Migrations/20211107134836_content.Designer.cs
3,546
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.ObjectModel; using System.Collections.Generic; using Microsoft.VisualStudio.TestPlatform.ObjectModel; /// <summary> /// The discovery complete payload. /// </summary> public class DiscoveryCompletePayload { /// <summary> /// Gets or sets the total number of tests discovered. /// </summary> public long TotalTests { get; set; } /// <summary> /// Gets or sets the last chunk of discovered tests. /// </summary> public IEnumerable<TestCase> LastDiscoveredTests { get; set; } /// <summary> /// Gets or sets a value indicating whether discovery was aborted. /// </summary> public bool IsAborted { get; set; } /// <summary> /// Gets or sets the Metrics /// </summary> public IDictionary<string, object> Metrics { get; set; } }
30.117647
101
0.691406
[ "MIT" ]
lbussell/vstest
src/Microsoft.TestPlatform.CommunicationUtilities/Messages/DiscoveryCompletePayload.cs
1,024
C#
using System; using System.ComponentModel; using EfsTools.Attributes; using EfsTools.Utils; using Newtonsoft.Json; using EfsTools.Items.Data; namespace EfsTools.Items.Nv { [Serializable] [NvItemId(5367)] [Attributes(9)] public class Gsm900PaPredistSwpt1 { [ElementsCount(1)] [ElementType("uint16")] [Description("")] public ushort Value { get; set; } } }
20.090909
42
0.617647
[ "MIT" ]
HomerSp/EfsTools
EfsTools/Items/Nv/Gsm900PaPredistSwpt1I.cs
442
C#
using MvvmCross.Plugin.Messenger; namespace CardboardKnight.Core.Messages { public class RatingResultMessage : MvxMessage { public string Review; public bool Success; public double Value; public RatingResultMessage(object sender, bool success, double value, string review) : base(sender) { Success = success; Value = value; Review = review; } } }
24.666667
107
0.617117
[ "MIT" ]
TheCardboardKnight/App
CardboardKnight.Core/Messages/RatingResultMessage.cs
444
C#
using EPiServer; using EPiServer.Commerce.Catalog; using EPiServer.Commerce.Catalog.ContentTypes; using EPiServer.Core; using EPiServer.ServiceLocation; using EPiServer.Web; using EPiServer.Web.Routing; using System; using System.Collections.Generic; using System.Linq; namespace Foundation.Commerce.Extensions { public static class AssetContainerExtensions { private static readonly Injected<AssetUrlResolver> AssetUrlResolver; public static string GetDefaultAsset<T>(this IAssetContainer assetContainer) where T : IContentMedia { var url = AssetUrlResolver.Service.GetAssetUrl<T>(assetContainer); if (Uri.TryCreate(url, UriKind.Absolute, out var uri)) { return uri.PathAndQuery; } return url; } public static IList<string> GetAssets<T>(this IAssetContainer assetContainer, IContentLoader contentLoader, UrlResolver urlResolver) where T : IContentMedia { var assets = new List<string>(); if (assetContainer.CommerceMediaCollection != null) { assets.AddRange(assetContainer.CommerceMediaCollection .Where(x => ValidateCorrectType<T>(x.AssetLink, contentLoader)) .Select(media => urlResolver.GetUrl(media.AssetLink, null, new VirtualPathArguments() { ContextMode = ContextMode.Default }))); } if (!assets.Any()) { assets.Add(string.Empty); } return assets; } public static IList<KeyValuePair<string,string>> GetAssetsWithType(this IAssetContainer assetContainer, IContentLoader contentLoader, UrlResolver urlResolver) { var assets = new List<KeyValuePair<string, string>>(); if (assetContainer.CommerceMediaCollection != null) { assets.AddRange( assetContainer.CommerceMediaCollection .Select(media => { if (contentLoader.TryGet<IContentMedia>(media.AssetLink, out var contentMedia)) { var type = "Image"; var url = urlResolver.GetUrl(media.AssetLink, null, new VirtualPathArguments() { ContextMode = ContextMode.Default }); if (contentMedia is IContentVideo) { type = "Video"; } return new KeyValuePair<string, string>(type, url); } return new KeyValuePair<string, string>(string.Empty, string.Empty); }) .Where(x => x.Key != string.Empty) ); } return assets; } public static IList<MediaData> GetAssetsMediaData(this IAssetContainer assetContainer, IContentLoader contentLoader, string groupName = "") { if (assetContainer.CommerceMediaCollection != null) { var assets = assetContainer.CommerceMediaCollection .Where(x => string.IsNullOrEmpty(groupName) || x.GroupName == groupName) .Select(x => contentLoader.Get<IContent>(x.AssetLink) as MediaData) .Where(x => x != null) .ToList(); return assets; } return new List<MediaData>(); } private static bool ValidateCorrectType<T>(ContentReference contentLink, IContentLoader contentLoader) where T : IContentMedia { if (typeof(T) == typeof(IContentMedia)) { return true; } if (ContentReference.IsNullOrEmpty(contentLink)) { return false; } return contentLoader.TryGet(contentLink, out T _); } } }
35.789474
147
0.55049
[ "Apache-2.0" ]
himadric/sitecore-structured-logging
src/Foundation.Commerce/Extensions/AssetContainerExtensions.cs
4,082
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 namespace Dnn.ExportImport.Components.Scheduler { using System; using System.Text; using System.Threading; using Dnn.ExportImport.Components.Common; using Dnn.ExportImport.Components.Controllers; using Dnn.ExportImport.Components.Engines; using Dnn.ExportImport.Components.Models; using DotNetNuke.Common.Utilities; using DotNetNuke.Instrumentation; using DotNetNuke.Services.Localization; using DotNetNuke.Services.Scheduling; /// <summary> /// Implements a SchedulerClient for the Exporting/Importing of site items. /// </summary> public class ExportImportScheduler : SchedulerClient { private const int EmergencyScheduleFrequency = 120; private const int DefaultScheduleFrequency = 1; private const string EmergencyScheduleFrequencyUnit = "m"; private const string DefaultScheduleFrequencyUnit = "d"; private const int EmergencyScheduleRetry = 90; private const int DefaultScheduleRetry = 1; private const string EmergencyScheduleRetryUnit = "s"; private const string DefaultScheduleRetryUnit = "h"; private const int EmergencyHistoryNumber = 1; private const int DefaultHistoryNumber = 60; private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ExportImportScheduler)); public ExportImportScheduler(ScheduleHistoryItem objScheduleHistoryItem) { this.ScheduleHistoryItem = objScheduleHistoryItem; } public override void DoWork() { try { // TODO: do some clean-up for very old import/export jobs/logs var job = EntitiesController.Instance.GetFirstActiveJob(); if (job == null) { this.ScheduleHistoryItem.Succeeded = true; this.ScheduleHistoryItem.AddLogNote("<br/>No Site Export/Import jobs queued for processing."); } else if (job.IsCancelled) { job.JobStatus = JobStatus.Cancelled; EntitiesController.Instance.UpdateJobStatus(job); this.ScheduleHistoryItem.Succeeded = true; this.ScheduleHistoryItem.AddLogNote("<br/>Site Export/Import jobs was previously cancelled."); } else { job.JobStatus = JobStatus.InProgress; EntitiesController.Instance.UpdateJobStatus(job); var result = new ExportImportResult { JobId = job.JobId, }; var engine = new ExportImportEngine(); var succeeded = true; switch (job.JobType) { case JobType.Export: try { engine.Export(job, result, this.ScheduleHistoryItem); } catch (Exception ex) { result.AddLogEntry("EXCEPTION exporting job #" + job.JobId, ex.Message, ReportLevel.Error); engine.AddLogsToDatabase(job.JobId, result.CompleteLog); throw; } EntitiesController.Instance.UpdateJobStatus(job); break; case JobType.Import: try { engine.Import(job, result, this.ScheduleHistoryItem); } catch (ThreadAbortException) { this.ScheduleHistoryItem.TimeLapse = EmergencyScheduleFrequency; this.ScheduleHistoryItem.TimeLapseMeasurement = EmergencyScheduleFrequencyUnit; this.ScheduleHistoryItem.RetryTimeLapse = EmergencyScheduleRetry; this.ScheduleHistoryItem.RetryTimeLapseMeasurement = EmergencyScheduleRetryUnit; this.ScheduleHistoryItem.RetainHistoryNum = EmergencyHistoryNumber; SchedulingController.UpdateSchedule(this.ScheduleHistoryItem); SchedulingController.PurgeScheduleHistory(); Logger.Error("The Schduler item stopped because main thread stopped, set schedule into emergency mode so it will start after app restart."); succeeded = false; } catch (Exception ex) { result.AddLogEntry("EXCEPTION importing job #" + job.JobId, ex.Message, ReportLevel.Error); engine.AddLogsToDatabase(job.JobId, result.CompleteLog); throw; } EntitiesController.Instance.UpdateJobStatus(job); if (job.JobStatus == JobStatus.Successful || job.JobStatus == JobStatus.Cancelled) { // clear everything to be sure imported items take effect DataCache.ClearCache(); } break; default: throw new Exception("Unknown job type: " + job.JobType); } this.ScheduleHistoryItem.Succeeded = true; // restore schedule item running timelapse to default. if (succeeded && this.ScheduleHistoryItem.TimeLapse == EmergencyScheduleFrequency && this.ScheduleHistoryItem.TimeLapseMeasurement == EmergencyScheduleFrequencyUnit) { this.ScheduleHistoryItem.TimeLapse = DefaultScheduleFrequency; this.ScheduleHistoryItem.TimeLapseMeasurement = DefaultScheduleFrequencyUnit; this.ScheduleHistoryItem.RetryTimeLapse = DefaultScheduleRetry; this.ScheduleHistoryItem.RetryTimeLapseMeasurement = DefaultScheduleRetryUnit; this.ScheduleHistoryItem.RetainHistoryNum = DefaultHistoryNumber; SchedulingController.UpdateSchedule(this.ScheduleHistoryItem); } var sb = new StringBuilder(); var jobType = Localization.GetString("JobType_" + job.JobType, Constants.SharedResources); var jobStatus = Localization.GetString("JobStatus_" + job.JobStatus, Constants.SharedResources); sb.AppendFormat("<br/><b>{0} {1}</b>", jobType, jobStatus); var summary = result.Summary; if (summary.Count > 0) { sb.Append("<br/><b>Summary:</b><ul>"); foreach (var entry in summary) { sb.Append($"<li>{entry.Name}: {entry.Value}</li>"); } sb.Append("</ul>"); } this.ScheduleHistoryItem.AddLogNote(sb.ToString()); engine.AddLogsToDatabase(job.JobId, result.CompleteLog); Logger.Trace("Site Export/Import: Job Finished"); } // SetLastSuccessfulIndexingDateTime(ScheduleHistoryItem.ScheduleID, ScheduleHistoryItem.StartDate); } catch (Exception ex) { this.ScheduleHistoryItem.Succeeded = false; this.ScheduleHistoryItem.AddLogNote("<br/>Export/Import EXCEPTION: " + ex.Message); this.Errored(ref ex); // this duplicates the logging // if (ScheduleHistoryItem.ScheduleSource != ScheduleSource.STARTED_FROM_BEGIN_REQUEST) // { // Exceptions.LogException(ex); // } } } } }
46.798913
172
0.529207
[ "MIT" ]
Mariusz11711/DNN
DNN Platform/Modules/DnnExportImport/Components/Scheduler/ExportImportScheduler.cs
8,613
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/codecapi.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="CODECAPI_AVEncH264PPSID" /> struct.</summary> public static unsafe class CODECAPI_AVEncH264PPSIDTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="CODECAPI_AVEncH264PPSID" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(CODECAPI_AVEncH264PPSID).GUID, Is.EqualTo(STATIC_CODECAPI_AVEncH264PPSID)); } /// <summary>Validates that the <see cref="CODECAPI_AVEncH264PPSID" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<CODECAPI_AVEncH264PPSID>(), Is.EqualTo(sizeof(CODECAPI_AVEncH264PPSID))); } /// <summary>Validates that the <see cref="CODECAPI_AVEncH264PPSID" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(CODECAPI_AVEncH264PPSID).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="CODECAPI_AVEncH264PPSID" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(CODECAPI_AVEncH264PPSID), Is.EqualTo(1)); } } }
40.288889
145
0.679537
[ "MIT" ]
phizch/terrafx.interop.windows
tests/Interop/Windows/um/codecapi/CODECAPI_AVEncH264PPSIDTests.cs
1,815
C#
// *********************************************************************** // Copyright (c) 2012-2020 Charlie Poole, Terje Sandstrom // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter; using NUnit.Framework; using NUnit.Tests; using NUnit.Tests.Assemblies; using NUnit.Tests.Singletons; using NUnit.VisualStudio.TestAdapter.Tests.Fakes; namespace NUnit.VisualStudio.TestAdapter.Tests { /// <summary> /// ResultSummary Helper Class. /// </summary> public class ResultSummary { private readonly Dictionary<TestOutcome, int> summary; public ResultSummary(IEnumerable<TestResult> results) { summary = new Dictionary<TestOutcome, int>(); foreach (TestResult result in results) { var outcome = result.Outcome; summary[outcome] = GetCount(outcome) + 1; } } private int GetCount(TestOutcome outcome) { return summary.ContainsKey(outcome) ? summary[outcome] : 0; } } [Category("TestExecution")] public class TestFilteringTests { private string mockAssemblyPath; [OneTimeSetUp] public void LoadMockassembly() { mockAssemblyPath = Path.Combine(TestContext.CurrentContext.TestDirectory, "mock-assembly.dll"); // Sanity check to be sure we have the correct version of mock-assembly.dll Assert.That(MockAssembly.TestsAtRuntime, Is.EqualTo(MockAssembly.Tests), "The reference to mock-assembly.dll appears to be the wrong version"); } [TestCase("", 35)] [TestCase(null, 35)] [TestCase("cat == Special", 1)] [TestCase("cat == MockCategory", 2)] [TestCase("method =~ MockTest?", 5)] [TestCase("method =~ MockTest? and cat != MockCategory", 3)] [TestCase("namespace == ThisNamespaceDoesNotExist", 0)] [TestCase("test==NUnit.Tests.Assemblies.MockTestFixture", MockTestFixture.Tests, TestName = "{m}_MockTestFixture")] [TestCase("test==NUnit.Tests.IgnoredFixture and method == Test2", 1, TestName = "{m}_IgnoredFixture")] [TestCase("class==NUnit.Tests.Assemblies.MockTestFixture", MockTestFixture.Tests)] [TestCase("name==MockTestFixture", MockTestFixture.Tests + NUnit.Tests.TestAssembly.MockTestFixture.Tests)] [TestCase("cat==FixtureCategory", MockTestFixture.Tests)] public void TestsWhereShouldFilter(string filter, int expectedCount) { // Create a fake environment. var context = new FakeRunContext(new FakeRunSettingsForWhere(filter)); var fakeFramework = new FakeFrameworkHandle(); var executor = TestAdapterUtils.CreateExecutor(); executor.RunTests(new[] { mockAssemblyPath }, context, fakeFramework); var completedRuns = fakeFramework.Events.Where(e => e.EventType == FakeFrameworkHandle.EventType.RecordEnd); Assert.That(completedRuns, Has.Exactly(expectedCount).Items); } } [Category("TestExecution")] public class TestExecutionTests { private string mockAssemblyPath; static readonly IRunContext Context = new FakeRunContext(); private FakeFrameworkHandle testLog; ResultSummary Summary { get; set; } [OneTimeSetUp] public void LoadMockassembly() { mockAssemblyPath = Path.Combine(TestContext.CurrentContext.TestDirectory, "mock-assembly.dll"); // Sanity check to be sure we have the correct version of mock-assembly.dll Assert.That(MockAssembly.TestsAtRuntime, Is.EqualTo(MockAssembly.Tests), "The reference to mock-assembly.dll appears to be the wrong version"); testLog = new FakeFrameworkHandle(); // Load the NUnit mock-assembly.dll once for this test, saving // the list of test cases sent to the discovery sink TestAdapterUtils.CreateExecutor().RunTests(new[] { mockAssemblyPath }, Context, testLog); var testResults = testLog.Events .Where(e => e.EventType == FakeFrameworkHandle.EventType.RecordResult) .Select(e => e.TestResult) .ToList(); this.Summary = new ResultSummary(testResults); } [Test] public void DumpEvents() { foreach (var ev in testLog.Events) { TestContext.Write(ev.EventType + ": "); if (ev.TestResult != null) TestContext.WriteLine("{0} {1}", ev.TestResult.TestCase.FullyQualifiedName, ev.TestResult.Outcome); else if (ev.TestCase != null) TestContext.WriteLine(ev.TestCase.FullyQualifiedName); else if (ev.Message.Text != null) TestContext.WriteLine(ev.Message.Text); else TestContext.WriteLine(); } } [Test] public void CorrectNumberOfTestCasesWereStarted() { const FakeFrameworkHandle.EventType eventType = FakeFrameworkHandle.EventType.RecordStart; foreach (var ev in testLog.Events.FindAll(e => e.EventType == eventType)) Console.WriteLine(ev.TestCase.DisplayName); Assert.That( testLog.Events.FindAll(e => e.EventType == eventType).Count, Is.EqualTo(MockAssembly.ResultCount - BadFixture.Tests - IgnoredFixture.Tests - ExplicitFixture.Tests)); } [Test] public void CorrectNumberOfTestCasesWereEnded() { const FakeFrameworkHandle.EventType eventType = FakeFrameworkHandle.EventType.RecordEnd; Assert.That( testLog.Events.FindAll(e => e.EventType == eventType).Count, Is.EqualTo(MockAssembly.ResultCount)); } [Test] public void CorrectNumberOfResultsWereReceived() { const FakeFrameworkHandle.EventType eventType = FakeFrameworkHandle.EventType.RecordResult; Assert.That( testLog.Events.FindAll(e => e.EventType == eventType).Count, Is.EqualTo(MockAssembly.ResultCount)); } static readonly TestCaseData[] Outcomes = { // NOTE: One inconclusive test is reported as None new TestCaseData(TestOutcome.Passed).Returns(MockAssembly.Success), new TestCaseData(TestOutcome.Failed).Returns(MockAssembly.ErrorsAndFailures), new TestCaseData(TestOutcome.Skipped).Returns(MockAssembly.Ignored), new TestCaseData(TestOutcome.None).Returns(MockAssembly.Explicit + 1), new TestCaseData(TestOutcome.NotFound).Returns(0) }; [TestCaseSource(nameof(Outcomes))] public int TestOutcomeTotalsAreCorrect(TestOutcome outcome) { return testLog.Events .Count(e => e.EventType == FakeFrameworkHandle.EventType.RecordResult && e.TestResult.Outcome == outcome); } [TestCase("MockTest3", TestOutcome.Passed, null, false)] [TestCase("FailingTest", TestOutcome.Failed, "Intentional failure", true)] [TestCase("TestWithException", TestOutcome.Failed, "System.Exception : Intentional Exception", true)] // NOTE: Should Inconclusive be reported as TestOutcome.None? [TestCase("ExplicitlyRunTest", TestOutcome.None, null, false)] [TestCase("InconclusiveTest", TestOutcome.None, "No valid data", false)] [TestCase("MockTest4", TestOutcome.Skipped, "ignoring this test method for now", false)] // NOTE: Should this be failed? [TestCase("NotRunnableTest", TestOutcome.Failed, "No arguments were provided", false)] public void TestResultIsReportedCorrectly(string name, TestOutcome outcome, string message, bool hasStackTrace) { var testResult = GetTestResult(name); Assert.NotNull(testResult, "Unable to find result for method: " + name); Assert.That(testResult.Outcome, Is.EqualTo(outcome)); Assert.That(testResult.ErrorMessage, Is.EqualTo(message)); if (hasStackTrace) Assert.NotNull(testResult.ErrorStackTrace, "Unable to find error stacktrace"); } [Test] public void AttachmentsShowSupportMultipleFiles() { var test = GetTestResult(nameof(FixtureWithAttachment.AttachmentTest)); Assert.That(test, Is.Not.Null, "Could not find test result"); Assert.That(test.Attachments.Count, Is.EqualTo(1)); var attachmentSet = test.Attachments[0]; Assert.That(attachmentSet.Uri.OriginalString, Is.EqualTo(NUnitTestAdapter.ExecutorUri)); Assert.That(attachmentSet.Attachments.Count, Is.EqualTo(2)); VerifyAttachment(attachmentSet.Attachments[0], FixtureWithAttachment.Attachment1Name, FixtureWithAttachment.Attachment1Description); VerifyAttachment(attachmentSet.Attachments[1], FixtureWithAttachment.Attachment2Name, FixtureWithAttachment.Attachment2Description); } #if NET46 [Test] public void NativeAssemblyProducesWarning() { // Create a fake environment. var context = new FakeRunContext(); var fakeFramework = new FakeFrameworkHandle(); // Find the native exaple dll. var path = Path.Combine(TestContext.CurrentContext.TestDirectory, "NativeTests.dll"); Assert.That(File.Exists(path)); // Try to execute tests from the dll. TestAdapterUtils.CreateExecutor().RunTests( new[] { path }, context, fakeFramework); // Gather results. var testResults = fakeFramework.Events .Where(e => e.EventType == FakeFrameworkHandle.EventType.RecordResult) .Select(e => e.TestResult) .ToList(); // No tests found. Assert.That(testResults.Count, Is.EqualTo(0)); // A warning about unsupported assebly format provided. var messages = fakeFramework.Events .Where(e => e.EventType == FakeFrameworkHandle.EventType.SendMessage && e.Message.Level == Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging.TestMessageLevel.Warning) .Select(o => o.Message.Text); Assert.That(messages, Has.Some.Contains("Assembly not supported")); } #endif private static void VerifyAttachment(UriDataAttachment attachment, string expectedName, string expectedDescription) { Assert.Multiple(() => { Assert.That(attachment.Uri.OriginalString, Does.EndWith(expectedName)); Assert.That(attachment.Description, Is.EqualTo(expectedDescription)); }); } /// <summary> /// Tries to get the <see cref="TestResult"/> with the specified DisplayName. /// </summary> /// <param name="displayName">DisplayName to search for.</param> /// <returns>The first testresult with the specified DisplayName, or <c>null</c> if none where found.</returns> private TestResult GetTestResult(string displayName) { return testLog.Events .Where(e => e.EventType == FakeFrameworkHandle.EventType.RecordResult && e.TestResult.TestCase.DisplayName == displayName) .Select(e => e.TestResult) .FirstOrDefault(); } } [Category("TestExecution")] public class TestExecutionTestsForTestOutput { private string _mockAssemblyPath; private string _mockAssemblyFolder; private FakeFrameworkHandle testLog; ResultSummary Summary { get; set; } [OneTimeSetUp] public void LoadMockAssembly() { _mockAssemblyPath = Path.Combine(TestContext.CurrentContext.TestDirectory, "mock-assembly.dll"); _mockAssemblyFolder = Path.GetDirectoryName(_mockAssemblyPath); // Sanity check to be sure we have the correct version of mock-assembly.dll Assert.That(MockAssembly.TestsAtRuntime, Is.EqualTo(MockAssembly.Tests), "The reference to mock-assembly.dll appears to be the wrong version"); testLog = new FakeFrameworkHandle(); // Load the NUnit mock-assembly.dll once for this test, saving // the list of test cases sent to the discovery sink var testResults = testLog.Events .Where(e => e.EventType == FakeFrameworkHandle.EventType.RecordResult) .Select(e => e.TestResult) .ToList(); Summary = new ResultSummary(testResults); } #if NET35 [Test] public void ThatTestOutputXmlHasBeenCreatedBelowAssemblyFolder() { var context = new FakeRunContext(new FakeRunSettingsForTestOutput()); TestAdapterUtils.CreateExecutor().RunTests(new[] { _mockAssemblyPath }, context, testLog); var expectedFolder = Path.Combine(_mockAssemblyFolder, "TestResults"); Assert.That(Directory.Exists(expectedFolder), $"Folder {expectedFolder} not created"); var expectedFile = Path.Combine(expectedFolder, "mock-assembly.xml"); Assert.That(File.Exists(expectedFile), $"File {expectedFile} not found"); } [Test] public void ThatTestOutputXmlHasBeenAtWorkDirLocation() { var temp = Path.GetTempPath(); var context = new FakeRunContext(new FakeRunSettingsForTestOutputAndWorkDir("TestResult", Path.Combine(temp, "NUnit"))); var executor = TestAdapterUtils.CreateExecutor(); executor.RunTests(new[] { _mockAssemblyPath }, context, testLog); var expectedFolder = Path.Combine(Path.GetTempPath(), "NUnit", "TestResult"); Assert.That(Directory.Exists(expectedFolder), $"Folder {expectedFolder} not created"); var expectedFile = Path.Combine(expectedFolder, "mock-assembly.xml"); Assert.That(File.Exists(expectedFile), $"File {expectedFile} not found"); } #endif } }
43.611111
150
0.636369
[ "MIT" ]
larsajakobsen/nunit3-vs-adapter
src/NUnitTestAdapterTests/TestExecutionTests.cs
15,702
C#
using System; using JetBrains.Annotations; [UsedImplicitly] public class Entry : RoomApp { protected override bool IndoorRoom => true; protected override TimeSpan OccupancyTimeout => TimeSpan.FromMinutes(2); protected override bool PresenceLightingEnabled => !this.IsAnyoneInBed() && base.PresenceLightingEnabled; }
27.5
109
0.778788
[ "MIT" ]
danpowell88/home
apps/Rooms/Entry/Entry.cs
330
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager.Monitor.Models; namespace Azure.ResourceManager.Monitor { internal partial class DataCollectionRuleAssociationsRestOperations { private readonly TelemetryDetails _userAgent; private readonly HttpPipeline _pipeline; private readonly Uri _endpoint; private readonly string _apiVersion; /// <summary> Initializes a new instance of DataCollectionRuleAssociationsRestOperations. </summary> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> /// <param name="applicationId"> The application id to use for user agent. </param> /// <param name="endpoint"> server parameter. </param> /// <param name="apiVersion"> Api Version. </param> /// <exception cref="ArgumentNullException"> <paramref name="pipeline"/> or <paramref name="apiVersion"/> is null. </exception> public DataCollectionRuleAssociationsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) { _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); _endpoint = endpoint ?? new Uri("https://management.azure.com"); _apiVersion = apiVersion ?? "2021-04-01"; _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); } internal HttpMessage CreateListByResourceRequest(string resourceUri) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/", false); uri.AppendPath(resourceUri, false); uri.AppendPath("/providers/Microsoft.Insights/dataCollectionRuleAssociations", false); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); _userAgent.Apply(message); return message; } /// <summary> Lists associations for the specified resource. </summary> /// <param name="resourceUri"> The identifier of the resource. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceUri"/> is null. </exception> public async Task<Response<DataCollectionRuleAssociationProxyOnlyResourceListResult>> ListByResourceAsync(string resourceUri, CancellationToken cancellationToken = default) { Argument.AssertNotNull(resourceUri, nameof(resourceUri)); using var message = CreateListByResourceRequest(resourceUri); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { DataCollectionRuleAssociationProxyOnlyResourceListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = DataCollectionRuleAssociationProxyOnlyResourceListResult.DeserializeDataCollectionRuleAssociationProxyOnlyResourceListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> Lists associations for the specified resource. </summary> /// <param name="resourceUri"> The identifier of the resource. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceUri"/> is null. </exception> public Response<DataCollectionRuleAssociationProxyOnlyResourceListResult> ListByResource(string resourceUri, CancellationToken cancellationToken = default) { Argument.AssertNotNull(resourceUri, nameof(resourceUri)); using var message = CreateListByResourceRequest(resourceUri); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { DataCollectionRuleAssociationProxyOnlyResourceListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = DataCollectionRuleAssociationProxyOnlyResourceListResult.DeserializeDataCollectionRuleAssociationProxyOnlyResourceListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateListByRuleRequest(string subscriptionId, string resourceGroupName, string dataCollectionRuleName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Insights/dataCollectionRules/", false); uri.AppendPath(dataCollectionRuleName, true); uri.AppendPath("/associations", false); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); _userAgent.Apply(message); return message; } /// <summary> Lists associations for the specified data collection rule. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param> /// <param name="dataCollectionRuleName"> The name of the data collection rule. The name is case insensitive. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="dataCollectionRuleName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="dataCollectionRuleName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<DataCollectionRuleAssociationProxyOnlyResourceListResult>> ListByRuleAsync(string subscriptionId, string resourceGroupName, string dataCollectionRuleName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(dataCollectionRuleName, nameof(dataCollectionRuleName)); using var message = CreateListByRuleRequest(subscriptionId, resourceGroupName, dataCollectionRuleName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { DataCollectionRuleAssociationProxyOnlyResourceListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = DataCollectionRuleAssociationProxyOnlyResourceListResult.DeserializeDataCollectionRuleAssociationProxyOnlyResourceListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> Lists associations for the specified data collection rule. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param> /// <param name="dataCollectionRuleName"> The name of the data collection rule. The name is case insensitive. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="dataCollectionRuleName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="dataCollectionRuleName"/> is an empty string, and was expected to be non-empty. </exception> public Response<DataCollectionRuleAssociationProxyOnlyResourceListResult> ListByRule(string subscriptionId, string resourceGroupName, string dataCollectionRuleName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(dataCollectionRuleName, nameof(dataCollectionRuleName)); using var message = CreateListByRuleRequest(subscriptionId, resourceGroupName, dataCollectionRuleName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { DataCollectionRuleAssociationProxyOnlyResourceListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = DataCollectionRuleAssociationProxyOnlyResourceListResult.DeserializeDataCollectionRuleAssociationProxyOnlyResourceListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateGetRequest(string resourceUri, string associationName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/", false); uri.AppendPath(resourceUri, false); uri.AppendPath("/providers/Microsoft.Insights/dataCollectionRuleAssociations/", false); uri.AppendPath(associationName, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); _userAgent.Apply(message); return message; } /// <summary> Returns the specified association. </summary> /// <param name="resourceUri"> The identifier of the resource. </param> /// <param name="associationName"> The name of the association. The name is case insensitive. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceUri"/> or <paramref name="associationName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="associationName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<DataCollectionRuleAssociationData>> GetAsync(string resourceUri, string associationName, CancellationToken cancellationToken = default) { Argument.AssertNotNull(resourceUri, nameof(resourceUri)); Argument.AssertNotNullOrEmpty(associationName, nameof(associationName)); using var message = CreateGetRequest(resourceUri, associationName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { DataCollectionRuleAssociationData value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = DataCollectionRuleAssociationData.DeserializeDataCollectionRuleAssociationData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((DataCollectionRuleAssociationData)null, message.Response); default: throw new RequestFailedException(message.Response); } } /// <summary> Returns the specified association. </summary> /// <param name="resourceUri"> The identifier of the resource. </param> /// <param name="associationName"> The name of the association. The name is case insensitive. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceUri"/> or <paramref name="associationName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="associationName"/> is an empty string, and was expected to be non-empty. </exception> public Response<DataCollectionRuleAssociationData> Get(string resourceUri, string associationName, CancellationToken cancellationToken = default) { Argument.AssertNotNull(resourceUri, nameof(resourceUri)); Argument.AssertNotNullOrEmpty(associationName, nameof(associationName)); using var message = CreateGetRequest(resourceUri, associationName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { DataCollectionRuleAssociationData value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = DataCollectionRuleAssociationData.DeserializeDataCollectionRuleAssociationData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((DataCollectionRuleAssociationData)null, message.Response); default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateCreateRequest(string resourceUri, string associationName, DataCollectionRuleAssociationData data) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Put; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/", false); uri.AppendPath(resourceUri, false); uri.AppendPath("/providers/Microsoft.Insights/dataCollectionRuleAssociations/", false); uri.AppendPath(associationName, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); if (data != null) { request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(data); request.Content = content; } _userAgent.Apply(message); return message; } /// <summary> Creates or updates an association. </summary> /// <param name="resourceUri"> The identifier of the resource. </param> /// <param name="associationName"> The name of the association. The name is case insensitive. </param> /// <param name="data"> The payload. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceUri"/> or <paramref name="associationName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="associationName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<DataCollectionRuleAssociationData>> CreateAsync(string resourceUri, string associationName, DataCollectionRuleAssociationData data = null, CancellationToken cancellationToken = default) { Argument.AssertNotNull(resourceUri, nameof(resourceUri)); Argument.AssertNotNullOrEmpty(associationName, nameof(associationName)); using var message = CreateCreateRequest(resourceUri, associationName, data); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 201: { DataCollectionRuleAssociationData value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = DataCollectionRuleAssociationData.DeserializeDataCollectionRuleAssociationData(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> Creates or updates an association. </summary> /// <param name="resourceUri"> The identifier of the resource. </param> /// <param name="associationName"> The name of the association. The name is case insensitive. </param> /// <param name="data"> The payload. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceUri"/> or <paramref name="associationName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="associationName"/> is an empty string, and was expected to be non-empty. </exception> public Response<DataCollectionRuleAssociationData> Create(string resourceUri, string associationName, DataCollectionRuleAssociationData data = null, CancellationToken cancellationToken = default) { Argument.AssertNotNull(resourceUri, nameof(resourceUri)); Argument.AssertNotNullOrEmpty(associationName, nameof(associationName)); using var message = CreateCreateRequest(resourceUri, associationName, data); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 201: { DataCollectionRuleAssociationData value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = DataCollectionRuleAssociationData.DeserializeDataCollectionRuleAssociationData(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateDeleteRequest(string resourceUri, string associationName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Delete; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/", false); uri.AppendPath(resourceUri, false); uri.AppendPath("/providers/Microsoft.Insights/dataCollectionRuleAssociations/", false); uri.AppendPath(associationName, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); _userAgent.Apply(message); return message; } /// <summary> Deletes an association. </summary> /// <param name="resourceUri"> The identifier of the resource. </param> /// <param name="associationName"> The name of the association. The name is case insensitive. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceUri"/> or <paramref name="associationName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="associationName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response> DeleteAsync(string resourceUri, string associationName, CancellationToken cancellationToken = default) { Argument.AssertNotNull(resourceUri, nameof(resourceUri)); Argument.AssertNotNullOrEmpty(associationName, nameof(associationName)); using var message = CreateDeleteRequest(resourceUri, associationName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 204: return message.Response; default: throw new RequestFailedException(message.Response); } } /// <summary> Deletes an association. </summary> /// <param name="resourceUri"> The identifier of the resource. </param> /// <param name="associationName"> The name of the association. The name is case insensitive. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceUri"/> or <paramref name="associationName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="associationName"/> is an empty string, and was expected to be non-empty. </exception> public Response Delete(string resourceUri, string associationName, CancellationToken cancellationToken = default) { Argument.AssertNotNull(resourceUri, nameof(resourceUri)); Argument.AssertNotNullOrEmpty(associationName, nameof(associationName)); using var message = CreateDeleteRequest(resourceUri, associationName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 204: return message.Response; default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateListByResourceNextPageRequest(string nextLink, string resourceUri) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendRawNextLink(nextLink, false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); _userAgent.Apply(message); return message; } /// <summary> Lists associations for the specified resource. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="resourceUri"> The identifier of the resource. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> or <paramref name="resourceUri"/> is null. </exception> public async Task<Response<DataCollectionRuleAssociationProxyOnlyResourceListResult>> ListByResourceNextPageAsync(string nextLink, string resourceUri, CancellationToken cancellationToken = default) { Argument.AssertNotNull(nextLink, nameof(nextLink)); Argument.AssertNotNull(resourceUri, nameof(resourceUri)); using var message = CreateListByResourceNextPageRequest(nextLink, resourceUri); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { DataCollectionRuleAssociationProxyOnlyResourceListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = DataCollectionRuleAssociationProxyOnlyResourceListResult.DeserializeDataCollectionRuleAssociationProxyOnlyResourceListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> Lists associations for the specified resource. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="resourceUri"> The identifier of the resource. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> or <paramref name="resourceUri"/> is null. </exception> public Response<DataCollectionRuleAssociationProxyOnlyResourceListResult> ListByResourceNextPage(string nextLink, string resourceUri, CancellationToken cancellationToken = default) { Argument.AssertNotNull(nextLink, nameof(nextLink)); Argument.AssertNotNull(resourceUri, nameof(resourceUri)); using var message = CreateListByResourceNextPageRequest(nextLink, resourceUri); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { DataCollectionRuleAssociationProxyOnlyResourceListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = DataCollectionRuleAssociationProxyOnlyResourceListResult.DeserializeDataCollectionRuleAssociationProxyOnlyResourceListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateListByRuleNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string dataCollectionRuleName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendRawNextLink(nextLink, false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); _userAgent.Apply(message); return message; } /// <summary> Lists associations for the specified data collection rule. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param> /// <param name="dataCollectionRuleName"> The name of the data collection rule. The name is case insensitive. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="dataCollectionRuleName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="dataCollectionRuleName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<DataCollectionRuleAssociationProxyOnlyResourceListResult>> ListByRuleNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string dataCollectionRuleName, CancellationToken cancellationToken = default) { Argument.AssertNotNull(nextLink, nameof(nextLink)); Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(dataCollectionRuleName, nameof(dataCollectionRuleName)); using var message = CreateListByRuleNextPageRequest(nextLink, subscriptionId, resourceGroupName, dataCollectionRuleName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { DataCollectionRuleAssociationProxyOnlyResourceListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = DataCollectionRuleAssociationProxyOnlyResourceListResult.DeserializeDataCollectionRuleAssociationProxyOnlyResourceListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> Lists associations for the specified data collection rule. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param> /// <param name="dataCollectionRuleName"> The name of the data collection rule. The name is case insensitive. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="dataCollectionRuleName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="dataCollectionRuleName"/> is an empty string, and was expected to be non-empty. </exception> public Response<DataCollectionRuleAssociationProxyOnlyResourceListResult> ListByRuleNextPage(string nextLink, string subscriptionId, string resourceGroupName, string dataCollectionRuleName, CancellationToken cancellationToken = default) { Argument.AssertNotNull(nextLink, nameof(nextLink)); Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(dataCollectionRuleName, nameof(dataCollectionRuleName)); using var message = CreateListByRuleNextPageRequest(nextLink, subscriptionId, resourceGroupName, dataCollectionRuleName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { DataCollectionRuleAssociationProxyOnlyResourceListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = DataCollectionRuleAssociationProxyOnlyResourceListResult.DeserializeDataCollectionRuleAssociationProxyOnlyResourceListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } } }
61.892727
261
0.656649
[ "MIT" ]
ChenTanyi/azure-sdk-for-net
sdk/monitor/Azure.ResourceManager.Monitor/src/Generated/RestOperations/DataCollectionRuleAssociationsRestOperations.cs
34,041
C#
using FluentAssertions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Options; using System.Linq; using Xunit; namespace HealthChecks.Gcp.CloudFirestore.Tests.DependencyInjection { public class cloud_firestore_registration_should { [Fact] public void add_health_check_when_properly_configured() { var services = new ServiceCollection(); services.AddHealthChecks() .AddCloudFirestore(setup => setup.RequiredCollections = new string[] { }); var serviceProvider = services.BuildServiceProvider(); var options = serviceProvider.GetService<IOptions<HealthCheckServiceOptions>>(); var registration = options.Value.Registrations.First(); var check = registration.Factory(serviceProvider); registration.Name.Should().Be("cloud firestore"); check.GetType().Should().Be(typeof(CloudFirestoreHealthCheck)); } [Fact] public void add_named_health_check_when_properly_configured() { var services = new ServiceCollection(); services.AddHealthChecks() .AddCloudFirestore(setup => setup.RequiredCollections = new string[] { }, name: "my-cloud-firestore-group"); var serviceProvider = services.BuildServiceProvider(); var options = serviceProvider.GetService<IOptions<HealthCheckServiceOptions>>(); var registration = options.Value.Registrations.First(); var check = registration.Factory(serviceProvider); registration.Name.Should().Be("my-cloud-firestore-group"); check.GetType().Should().Be(typeof(CloudFirestoreHealthCheck)); } } }
39.282609
124
0.675706
[ "Apache-2.0" ]
ExRam/AspNetCore.Diagnostics.HealthChecks
test/HealthChecks.Gcp.CloudFirestore.Tests/DependencyInjection/RegistrationTests.cs
1,809
C#
using System; using System.Collections.Generic; using System.Linq; namespace Unity.MLAgents.Actuators { /// <summary> /// Implementation of IDiscreteActionMask that allows writing to the action mask from an <see cref="IActuator"/>. /// </summary> internal class ActuatorDiscreteActionMask : IDiscreteActionMask { /// When using discrete control, is the starting indices of the actions /// when all the branches are concatenated with each other. int[] m_StartingActionIndices; int[] m_BranchSizes; bool[] m_CurrentMask; IList<IActuator> m_Actuators; readonly int m_SumOfDiscreteBranchSizes; readonly int m_NumBranches; /// <summary> /// The offset into the branches array that is used when actuators are writing to the action mask. /// </summary> public int CurrentBranchOffset { get; set; } internal ActuatorDiscreteActionMask(IList<IActuator> actuators, int sumOfDiscreteBranchSizes, int numBranches) { m_Actuators = actuators; m_SumOfDiscreteBranchSizes = sumOfDiscreteBranchSizes; m_NumBranches = numBranches; } /// <inheritdoc cref="IDiscreteActionMask.WriteMask"/> public void WriteMask(int branch, IEnumerable<int> actionIndices) { LazyInitialize(); // Perform the masking foreach (var actionIndex in actionIndices) { #if DEBUG if (branch >= m_NumBranches || actionIndex >= m_BranchSizes[CurrentBranchOffset + branch]) { throw new UnityAgentsException( "Invalid Action Masking: Action Mask is too large for specified branch."); } #endif m_CurrentMask[actionIndex + m_StartingActionIndices[CurrentBranchOffset + branch]] = true; } } void LazyInitialize() { if (m_BranchSizes == null) { m_BranchSizes = new int[m_NumBranches]; var start = 0; for (var i = 0; i < m_Actuators.Count; i++) { var actuator = m_Actuators[i]; var branchSizes = actuator.ActionSpec.BranchSizes; Array.Copy(branchSizes, 0, m_BranchSizes, start, branchSizes.Length); start += branchSizes.Length; } } // By default, the masks are null. If we want to specify a new mask, we initialize // the actionMasks with trues. if (m_CurrentMask == null) { m_CurrentMask = new bool[m_SumOfDiscreteBranchSizes]; } // If this is the first time the masked actions are used, we generate the starting // indices for each branch. if (m_StartingActionIndices == null) { m_StartingActionIndices = Utilities.CumSum(m_BranchSizes); } } /// <inheritdoc cref="IDiscreteActionMask.GetMask"/> public bool[] GetMask() { #if DEBUG if (m_CurrentMask != null) { AssertMask(); } #endif return m_CurrentMask; } /// <summary> /// Makes sure that the current mask is usable. /// </summary> void AssertMask() { #if DEBUG for (var branchIndex = 0; branchIndex < m_NumBranches; branchIndex++) { if (AreAllActionsMasked(branchIndex)) { throw new UnityAgentsException( "Invalid Action Masking : All the actions of branch " + branchIndex + " are masked."); } } #endif } /// <summary> /// Resets the current mask for an agent. /// </summary> public void ResetMask() { if (m_CurrentMask != null) { Array.Clear(m_CurrentMask, 0, m_CurrentMask.Length); } } /// <summary> /// Checks if all the actions in the input branch are masked. /// </summary> /// <param name="branch"> The index of the branch to check.</param> /// <returns> True if all the actions of the branch are masked.</returns> bool AreAllActionsMasked(int branch) { if (m_CurrentMask == null) { return false; } var start = m_StartingActionIndices[branch]; var end = m_StartingActionIndices[branch + 1]; for (var i = start; i < end; i++) { if (!m_CurrentMask[i]) { return false; } } return true; } } }
32.549669
118
0.532859
[ "Apache-2.0" ]
oereo/ML_Agents_App
com.unity.ml-agents/Runtime/Actuators/ActuatorDiscreteActionMask.cs
4,915
C#
namespace IVolt.Kinguin.API.API.Orders.V2 { using IVolt.Kinguin.API.Configuration; using Newtonsoft.Json; using System.Collections.Generic; /// <summary> /// Defines the <see cref="PlaceOrder_Input_Class" />. /// </summary> public class PlaceOrder_Input_Class { /// <summary> /// Gets or sets the Products. /// </summary> [JsonProperty("products", NullValueHandling = NullValueHandling.Ignore)] public List<PlaceOrder_Input_Product> Products { get; set; } /// <summary> /// Gets or sets the OrderExternalId. /// </summary> [JsonProperty("orderExternalId", NullValueHandling = NullValueHandling.Ignore)] public string OrderExternalId { get; set; } /// <summary> /// Gets or sets the CouponCode. /// </summary> [JsonProperty("couponCode", NullValueHandling = NullValueHandling.Ignore)] public string CouponCode { get; set; } /// <summary> /// The FromJson. /// </summary> /// <param name="json">The json<see cref="string"/>.</param> /// <returns>The <see cref="PlaceOrder_Input_Class"/>.</returns> public static PlaceOrder_Input_Class FromJson(string json) => JsonConvert.DeserializeObject<PlaceOrder_Input_Class>(json, SimpleDB_Converter.Settings); /// <summary> /// The ToJson. /// </summary> /// <returns>The <see cref="string"/>.</returns> public string ToJson() => JsonConvert.SerializeObject(this, SimpleDB_Converter.Settings); } }
36.045455
159
0.619168
[ "BSD-3-Clause" ]
InspiredVoltage-IVolt/Kinguin_API_Importer
Kinguin_API_Importer_Solution/Kinguin_API_Library/API/Orders/V2/PlaceOrder_Input_Class.cs
1,588
C#
using System; using System.Collections.Generic; namespace OSS.Common.Resp { /// <summary> /// 列表通行token接口 /// </summary> public interface ITokenList<TType> { /// <summary> /// 列表 /// </summary> IList<TType> data { get; } /// <summary> /// 列表关联外部字段token字典 /// </summary> public Dictionary<string, Dictionary<string,string>> pass_tokens { get; set; } } /// <summary> /// 通行token列表扩展 /// </summary> public static class IListPassTokensMap { /// <summary> /// 处理列表token处理 /// </summary> /// <typeparam name="TResult"></typeparam> /// <typeparam name="TTokenList"></typeparam> /// <param name="listRes"></param> /// <param name="tokenColumnName">关联的key列名称</param> /// <param name="tokenKeySelector">对应 tokenKeyColumnName 列的 token key 选择器</param> /// <param name="tokenValueTokenSelector">对应 tokenKeyColumnName 列的 token 值处理</param> /// <returns></returns> public static TTokenList AddColumnToken<TTokenList, TResult>(this TTokenList listRes, string tokenColumnName, Func<TResult, string> tokenKeySelector, Func<TResult, string> tokenValueTokenSelector) where TTokenList : ITokenList<TResult> { if (string.IsNullOrEmpty(tokenColumnName) || tokenKeySelector == null || tokenValueTokenSelector == null) throw new ArgumentNullException( $"{nameof(tokenColumnName)},{nameof(tokenKeySelector)},{nameof(tokenValueTokenSelector)}", " 参数不能为空!"); if (listRes.data != null) { if (listRes.pass_tokens == null) { listRes.pass_tokens = new Dictionary<string, Dictionary<string, string>>(); } listRes.pass_tokens[tokenColumnName] = GenerateColumnToken(listRes.data, tokenKeySelector, tokenValueTokenSelector); } return listRes; } /// <summary> /// 生成列表对应的token /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="items"></param> /// <param name="keyValueSelector"></param> /// <param name="keyValueTokenSelector"></param> /// <returns></returns> public static Dictionary<string, string> GenerateColumnToken<TResult>(this IList<TResult> items, Func<TResult, string> keyValueSelector, Func<TResult, string> keyValueTokenSelector) { var dics = new Dictionary<string, string>(items.Count); foreach (var dataItem in items) { var key = keyValueSelector(dataItem); if (!string.IsNullOrEmpty(key)) { dics[key] = keyValueTokenSelector(dataItem); } } return dics; } } }
35.452381
117
0.559436
[ "Apache-2.0" ]
KevinWG/OS.Common
OSS.Common/Resp/ITokenList.cs
3,106
C#
namespace Masa.Framework.Admin.Service.User.Application.Organizations.Queries; public record TreeQuery(Guid ParentId) : Query<List<DepartmentItemResponse>> { public override List<DepartmentItemResponse> Result { get; set; } = new(); }
30.125
78
0.780083
[ "Apache-2.0" ]
masalabs/MASA.Framework.Admin
src/Services/Masa.Framework.Admin.Service.User/Application/Organizations/Queries/TreeQuery.cs
241
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 rds-2014-10-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.RDS.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.RDS.Model.Internal.MarshallTransformations { /// <summary> /// DescribeDBParameters Request Marshaller /// </summary> public class DescribeDBParametersRequestMarshaller : IMarshaller<IRequest, DescribeDBParametersRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((DescribeDBParametersRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DescribeDBParametersRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.RDS"); request.Parameters.Add("Action", "DescribeDBParameters"); request.Parameters.Add("Version", "2014-10-31"); if(publicRequest != null) { if(publicRequest.IsSetDBParameterGroupName()) { request.Parameters.Add("DBParameterGroupName", StringUtils.FromString(publicRequest.DBParameterGroupName)); } if(publicRequest.IsSetFilters()) { int publicRequestlistValueIndex = 1; foreach(var publicRequestlistValue in publicRequest.Filters) { if(publicRequestlistValue.IsSetName()) { request.Parameters.Add("Filters" + "." + "member" + "." + publicRequestlistValueIndex + "." + "Name", StringUtils.FromString(publicRequestlistValue.Name)); } if(publicRequestlistValue.IsSetValues()) { int publicRequestlistValuelistValueIndex = 1; foreach(var publicRequestlistValuelistValue in publicRequestlistValue.Values) { request.Parameters.Add("Filters" + "." + "member" + "." + publicRequestlistValueIndex + "." + "Values" + "." + "member" + "." + publicRequestlistValuelistValueIndex, StringUtils.FromString(publicRequestlistValuelistValue)); publicRequestlistValuelistValueIndex++; } } publicRequestlistValueIndex++; } } if(publicRequest.IsSetMarker()) { request.Parameters.Add("Marker", StringUtils.FromString(publicRequest.Marker)); } if(publicRequest.IsSetMaxRecords()) { request.Parameters.Add("MaxRecords", StringUtils.FromInt(publicRequest.MaxRecords)); } if(publicRequest.IsSetSource()) { request.Parameters.Add("Source", StringUtils.FromString(publicRequest.Source)); } } return request; } private static DescribeDBParametersRequestMarshaller _instance = new DescribeDBParametersRequestMarshaller(); internal static DescribeDBParametersRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DescribeDBParametersRequestMarshaller Instance { get { return _instance; } } } }
40.508333
255
0.583213
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/RDS/Generated/Model/Internal/MarshallTransformations/DescribeDBParametersRequestMarshaller.cs
4,861
C#
// Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.0.6365, generator: {generator}) // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Commvault.Powershell.Models { using static Commvault.Powershell.Runtime.Extensions; /// <summary>CCL Vault v2</summary> public partial class CclVaultV2 { /// <summary> /// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> partial void AfterFromJson(Commvault.Powershell.Runtime.Json.JsonObject json); /// <summary> /// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Commvault.Powershell.Runtime.Json.JsonObject" /// /> before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> partial void AfterToJson(ref Commvault.Powershell.Runtime.Json.JsonObject container); /// <summary> /// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of /// the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> /// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return /// instantly.</param> partial void BeforeFromJson(Commvault.Powershell.Runtime.Json.JsonObject json, ref bool returnNow); /// <summary> /// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the /// object before it is serialized. /// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeToJson(ref Commvault.Powershell.Runtime.Json.JsonObject container, ref bool returnNow); /// <summary> /// Deserializes a Commvault.Powershell.Runtime.Json.JsonObject into a new instance of <see cref="CclVaultV2" />. /// </summary> /// <param name="json">A Commvault.Powershell.Runtime.Json.JsonObject instance to deserialize from.</param> internal CclVaultV2(Commvault.Powershell.Runtime.Json.JsonObject json) { bool returnNow = false; BeforeFromJson(json, ref returnNow); if (returnNow) { return; } __cloudStorage = new Commvault.Powershell.Models.CloudStorage(json); __dedupeStorageList = new Commvault.Powershell.Models.DedupeStorageList(json); {_credentials = If( json?.PropertyT<Commvault.Powershell.Runtime.Json.JsonObject>("credentials"), out var __jsonCredentials) ? Commvault.Powershell.Models.IdName.FromJson(__jsonCredentials) : Credentials;} {_cloudType = If( json?.PropertyT<Commvault.Powershell.Runtime.Json.JsonString>("cloudType"), out var __jsonCloudType) ? (string)__jsonCloudType : (string)CloudType;} {_serviceHost = If( json?.PropertyT<Commvault.Powershell.Runtime.Json.JsonString>("serviceHost"), out var __jsonServiceHost) ? (string)__jsonServiceHost : (string)ServiceHost;} {_bucket = If( json?.PropertyT<Commvault.Powershell.Runtime.Json.JsonString>("bucket"), out var __jsonBucket) ? (string)__jsonBucket : (string)Bucket;} AfterFromJson(json); } /// <summary> /// Deserializes a <see cref="Commvault.Powershell.Runtime.Json.JsonNode"/> into an instance of Commvault.Powershell.Models.ICclVaultV2. /// </summary> /// <param name="node">a <see cref="Commvault.Powershell.Runtime.Json.JsonNode" /> to deserialize from.</param> /// <returns>an instance of Commvault.Powershell.Models.ICclVaultV2.</returns> public static Commvault.Powershell.Models.ICclVaultV2 FromJson(Commvault.Powershell.Runtime.Json.JsonNode node) { return node is Commvault.Powershell.Runtime.Json.JsonObject json ? new CclVaultV2(json) : null; } /// <summary> /// Serializes this instance of <see cref="CclVaultV2" /> into a <see cref="Commvault.Powershell.Runtime.Json.JsonNode" />. /// </summary> /// <param name="container">The <see cref="Commvault.Powershell.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller /// passes in <c>null</c>, a new instance will be created and returned to the caller.</param> /// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Commvault.Powershell.Runtime.SerializationMode"/>.</param> /// <returns> /// a serialized instance of <see cref="CclVaultV2" /> as a <see cref="Commvault.Powershell.Runtime.Json.JsonNode" />. /// </returns> public Commvault.Powershell.Runtime.Json.JsonNode ToJson(Commvault.Powershell.Runtime.Json.JsonObject container, Commvault.Powershell.Runtime.SerializationMode serializationMode) { container = container ?? new Commvault.Powershell.Runtime.Json.JsonObject(); bool returnNow = false; BeforeToJson(ref container, ref returnNow); if (returnNow) { return container; } __cloudStorage?.ToJson(container, serializationMode); __dedupeStorageList?.ToJson(container, serializationMode); AddIf( null != this._credentials ? (Commvault.Powershell.Runtime.Json.JsonNode) this._credentials.ToJson(null,serializationMode) : null, "credentials" ,container.Add ); AddIf( null != (((object)this._cloudType)?.ToString()) ? (Commvault.Powershell.Runtime.Json.JsonNode) new Commvault.Powershell.Runtime.Json.JsonString(this._cloudType.ToString()) : null, "cloudType" ,container.Add ); AddIf( null != (((object)this._serviceHost)?.ToString()) ? (Commvault.Powershell.Runtime.Json.JsonNode) new Commvault.Powershell.Runtime.Json.JsonString(this._serviceHost.ToString()) : null, "serviceHost" ,container.Add ); AddIf( null != (((object)this._bucket)?.ToString()) ? (Commvault.Powershell.Runtime.Json.JsonNode) new Commvault.Powershell.Runtime.Json.JsonString(this._bucket.ToString()) : null, "bucket" ,container.Add ); AfterToJson(ref container); return container; } } }
66.892857
234
0.683796
[ "MIT" ]
Commvault/CVPowershellSDKV2
generated/api/Models/CclVaultV2.json.cs
7,492
C#
// ------------------------------------------------------------ // Copyright (c) Bartels Online. All rights reserved. // ------------------------------------------------------------ using BartelsOnline.Office.IO.Excel; using BartelsOnline.Office.IO.Excel.Models; using GISBlox.Services.SDK.Models; using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; namespace GISBlox.Services.CLI.Utils { internal class IO { #region Load /// <summary> /// Loads coordinates from a file. /// </summary> /// <param name="fileName">The fully-qualified file name.</param> /// <param name="separator">The character that was used to separate the coordinates in the file.</param> /// <param name="firstLineContainsHeaders">Determines whether to skip the first line in the file. Ignored if the input file is an Excel workbook.</param> /// <param name="coordinateOrder">Specifies whether the coordinates in the file are stored in lat/lon or lon/lat order.</param> /// <param name="inputRange">The Excel range that contains the coordinates to project (if applicable).</param> /// <returns>A List with Coordinate types.</returns> public static async Task<List<Coordinate>> LoadCoordinatesFromFile(string fileName, string separator, bool firstLineContainsHeaders, CoordinateOrderEnum coordinateOrder, string inputRange) { FileFormatEnum format = ParseFileFormat(fileName); switch (format) { case FileFormatEnum.CSV: return await LoadCoordinatesFromCSVFile(fileName, separator, firstLineContainsHeaders, coordinateOrder); case FileFormatEnum.XLS: return await LoadCoordinatesFromXLSFile(fileName, inputRange, coordinateOrder); default: return null; } } /// <summary> /// Loads coordinates from a file. /// </summary> /// <param name="fileName">The fully-qualified file name.</param> /// <param name="separator">The character that was used to separate the coordinates in the file.</param> /// <param name="firstLineContainsHeaders">Determines whether to skip the first line in the file.</param> /// <param name="coordinateOrder">Specifies whether the coordinates in the file are stored in lat/lon or lon/lat order.</param> /// <returns>A List with Coordinate types.</returns> private static async Task<List<Coordinate>> LoadCoordinatesFromCSVFile(string fileName, string separator, bool firstLineContainsHeaders, CoordinateOrderEnum coordinateOrder) { if (string.IsNullOrEmpty(separator)) { throw new ArgumentNullException(nameof(separator)); } List<Coordinate> coordinates = new(); using (StreamReader sr = new(fileName)) { if (firstLineContainsHeaders && !sr.EndOfStream) { await sr.ReadLineAsync(); } while (!sr.EndOfStream) { string rowData = await sr.ReadLineAsync(); if (!string.IsNullOrEmpty(rowData)) { coordinates.Add(PositionParser.CoordinateFromString(rowData, separator, coordinateOrder)); } } } return coordinates; } /// <summary> /// Loads coordinates from an Excel file. /// </summary> /// <param name="fileName">The fully-qualified file name.</param> /// <param name="inputRange">The Excel range that contains the coordinates to project.</param> /// <param name="coordinateOrder">Specifies whether the coordinates in the file are stored in lat/lon or lon/lat order.</param> /// <returns>A List with Coordinate types.</returns> private static async Task<List<Coordinate>> LoadCoordinatesFromXLSFile(string fileName, string inputRange, CoordinateOrderEnum coordinateOrder) { List<Coordinate> coordinates = new(); using (ExcelReader xlsReader = new(fileName)) { var rows = Task.Run(() => xlsReader.ReadRange(1, inputRange)); foreach (var row in await rows) { coordinates.Add(PositionParser.CoordinateFromPoints(row[0].Value, row[1].Value, coordinateOrder)); } } return coordinates; } /// <summary> /// Loads RDNew locations from a file. /// </summary> /// <param name="fileName">The fully-qualified file name.</param> /// <param name="separator">The character that was used to separate the coordinates in the file.</param> /// <param name="firstLineContainsHeaders">Determines whether to skip the first line in the file.</param> /// <param name="rdPointOrder">Specifies whether the locations in the file are stored in X-Y or Y-X order.</param> /// <param name="inputRange">The Excel range that contains the coordinates to project (if applicable).</param> /// <returns>A List with RDPoint types.</returns> public static async Task<List<RDPoint>> LoadRDPointsFromFile(string fileName, string separator, bool firstLineContainsHeaders, RDPointOrderEnum rdPointOrder, string inputRange) { FileFormatEnum format = ParseFileFormat(fileName); switch (format) { case FileFormatEnum.CSV: return await LoadRDPointsFromCSVFile(fileName, separator, firstLineContainsHeaders, rdPointOrder); case FileFormatEnum.XLS: return await LoadRDPointsFromXLSFile(fileName, inputRange, rdPointOrder); default: return null; } } /// <summary> /// Loads RDNew locations from a file. /// </summary> /// <param name="fileName">The fully-qualified file name.</param> /// <param name="separator">The character that was used to separate the coordinates in the file.</param> /// <param name="firstLineContainsHeaders">Determines whether to skip the first line in the file.</param> /// <param name="rdPointOrder">Specifies whether the locations in the file are stored in X-Y or Y-X order.</param> /// <returns>A List with RDPoint types.</returns> private static async Task<List<RDPoint>> LoadRDPointsFromCSVFile(string fileName, string separator, bool firstLineContainsHeaders, RDPointOrderEnum rdPointOrder) { if (string.IsNullOrEmpty(separator)) { throw new ArgumentNullException(nameof(separator)); } List<RDPoint> points = new(); using (StreamReader sr = new(fileName)) { if (firstLineContainsHeaders && !sr.EndOfStream) { await sr.ReadLineAsync(); } while (!sr.EndOfStream) { string rowData = await sr.ReadLineAsync(); if (!string.IsNullOrEmpty(rowData)) { points.Add(PositionParser.RDPointFromString(rowData, separator, rdPointOrder)); } } } return points; } /// <summary> /// Loads RDNew locations from an Excel file. /// </summary> /// <param name="fileName">The fully-qualified file name.</param> /// <param name="inputRange">The Excel range that contains the locations to project.</param> /// <param name="rdPointOrder">Specifies whether the locations in the file are stored in X-Y or Y-X order.</param> /// <returns>A List with RDPoint types.</returns> private static async Task<List<RDPoint>> LoadRDPointsFromXLSFile(string fileName, string inputRange, RDPointOrderEnum rdPointOrder) { List<RDPoint> points = new(); using (ExcelReader xlsReader = new(fileName)) { var rows = Task.Run(() => xlsReader.ReadRange(1, inputRange)); foreach (var row in await rows) { points.Add(PositionParser.RDPointFromPoints(row[0].Value, row[1].Value, rdPointOrder)); } } return points; } #endregion #region Save /// <summary> /// Saves coordinates to a file. /// </summary> /// <param name="fileName">The fully-qualified file name.</param> /// <param name="separator">The character that separates the coordinates in the file.</param> /// <param name="coordinates">A List with Coordinate types.</param> /// <param name="coordinateOrder">The order in which to save the coordinate pairs.</param> /// <param name="formatProvider">Culture-specific formatting options</param> /// <returns></returns> public static async Task SaveToCSVFile(string fileName, string separator, List<Coordinate> coordinates, CoordinateOrderEnum coordinateOrder, IFormatProvider formatProvider) { if (string.IsNullOrEmpty(separator)) separator = ";"; using (StreamWriter sw = new(CorrectOutputFileType(fileName))) { foreach (var coordinate in coordinates) { await sw.WriteLineAsync(PositionParser.CoordinateToString(coordinate, separator, coordinateOrder, formatProvider)); } } } /// <summary> /// Saves RDNew locations to a file. /// </summary> /// <param name="fileName">The fully-qualified file name.</param> /// <param name="separator">The character that separates the locations in the file.</param> /// <param name="points">A List with RDPoint types.</param> /// <returns></returns> public static async Task SaveToCSVFile(string fileName, string separator, List<RDPoint> points, RDPointOrderEnum rdPointOrder, IFormatProvider formatProvider) { if (string.IsNullOrEmpty(separator)) separator = ";"; using (StreamWriter sw = new(CorrectOutputFileType(fileName))) { foreach (var point in points) { await sw.WriteLineAsync(PositionParser.RDPointToString(point, separator, rdPointOrder, formatProvider)); } } } /// <summary> /// Save Location types to a file. /// </summary> /// <param name="fileName">The fully-qualified file name.</param> /// <param name="separator">The character that separates the coordinates in the file.</param> /// <param name="locations">A List with Location types.</param> /// <param name="coordinateFirst">True to output the coordinate of the location first, False to output the RDPoint first.</param> /// <param name="coordinateOrder">The order in which to save the coordinate pairs.</param> /// <param name="formatProvider">Culture-specific formatting options</param> /// <returns></returns> public static async Task SaveToCSVFile(string fileName, string separator, List<Location> locations, bool coordinateFirst, CoordinateOrderEnum coordinateOrder, IFormatProvider formatProvider) { if (string.IsNullOrEmpty(separator)) separator = ";"; using (StreamWriter sw = new(CorrectOutputFileType(fileName))) { foreach (var location in locations) { await sw.WriteLineAsync(PositionParser.LocationToString(location, separator, coordinateFirst, coordinateOrder, formatProvider)); } } } #endregion #region File utils protected static FileFormatEnum ParseFileFormat(string fileName) { FileInfo fi = new (fileName); switch (fi.Extension) { case ".csv": case ".txt": return FileFormatEnum.CSV; case ".xls": case ".xlsx": return FileFormatEnum.XLS; default: throw new ArgumentException($"Unsupported file format '{ fi.Extension }'."); } } protected static string CorrectOutputFileType(string fileName) { FileFormatEnum format = ParseFileFormat(fileName); if (format == FileFormatEnum.XLS) { // Currently, saving to Excel is not supported, so save as CSV which opens with Excel return Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName) + ".csv"); } else { return fileName; } } #endregion } }
44.768683
196
0.619952
[ "MIT" ]
GISBlox/gisblox-services-cli
GISBlox.Services.CLI/GISBlox.Services.CLI/Utils/IO.cs
12,582
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Runtime.InteropServices; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class RealParserTests { /// <summary> /// Test some specific floating-point literals that have been shown to be problematic /// in some implementation. /// </summary> [Fact] public static void TestTroublesomeDoubles() { //// https://msdn.microsoft.com/en-us/library/kfsatb94(v=vs.110).aspx CheckOneDouble("0.6822871999174", 0x3FE5D54BF743FD1Bul); //// Common problem numbers CheckOneDouble("2.2250738585072011e-308", 0x000FFFFFFFFFFFFFul); CheckOneDouble("2.2250738585072012e-308", 0x0010000000000000ul); //// http://www.exploringbinary.com/bigcomp-deciding-truncated-near-halfway-conversions/ CheckOneDouble("1.3694713649464322631e-11", 0x3DAE1D703BB5749Dul); CheckOneDouble("9.3170532238714134438e+16", 0x4374B021AFD9F651ul); //// https://connect.microsoft.com/VisualStudio/feedback/details/914964/double-round-trip-conversion-via-a-string-is-not-safe CheckOneDouble("0.84551240822557006", 0x3FEB0E7009B61CE0ul); // This value has a non-terminating binary fraction. It has a 0 at bit 54 // followed by 120 ones. //// http://www.exploringbinary.com/a-bug-in-the-bigcomp-function-of-david-gays-strtod/ CheckOneDouble("1.8254370818746402660437411213933955878019332885742187", 0x3FFD34FD8378EA83ul); //// http://www.exploringbinary.com/decimal-to-floating-point-needs-arbitrary-precision CheckOneDouble("7.8459735791271921e+65", 0x4D9DCD0089C1314Eul); CheckOneDouble("3.08984926168550152811e-32", 0x39640DE48676653Bul); //// other values from https://github.com/dotnet/roslyn/issues/4221 CheckOneDouble("0.6822871999174000000", 0x3FE5D54BF743FD1Bul); CheckOneDouble("0.6822871999174000001", 0x3FE5D54BF743FD1Bul); // A handful of selected values for which double.Parse has been observed to produce an incorrect result CheckOneDouble("88.7448699245e+188", 0x675fde6aee647ed2ul); CheckOneDouble("02.0500496671303857e-88", 0x2dba19a3cf32cd7ful); CheckOneDouble("1.15362842193e193", 0x68043a6fcda86331ul); CheckOneDouble("65.9925719e-190", 0x18dd672e04e96a79ul); CheckOneDouble("0.4619024460e-158", 0x1f103c1e5abd7c87ul); CheckOneDouble("61.8391820096448e147", 0x5ed35849885ad12bul); CheckOneDouble("0.2e+127", 0x5a27a2ecc414a03ful); CheckOneDouble("0.8e+127", 0x5a47a2ecc414a03ful); CheckOneDouble("35.27614496323756e-307", 0x0083d141335ce6c7ul); CheckOneDouble("3.400034617466e190", 0x677e863a216ab367ul); CheckOneDouble("0.78393577148319e-254", 0x0b2d6d5379bc932dul); CheckOneDouble("0.947231e+100", 0x54b152a10483a38ful); CheckOneDouble("4.e126", 0x5a37a2ecc414a03ful); CheckOneDouble("6.235271922748e-165", 0x1dd6faeba4fc9f91ul); CheckOneDouble("3.497444198362024e-82", 0x2f053b8036dd4203ul); CheckOneDouble("8.e+126", 0x5a47a2ecc414a03ful); CheckOneDouble("10.027247729e+91", 0x53089cc2d930ed3ful); CheckOneDouble("4.6544819e-192", 0x18353c5d35ceaaadul); CheckOneDouble("5.e+125", 0x5a07a2ecc414a03ful); CheckOneDouble("6.96768e68", 0x4e39d8352ee997f9ul); CheckOneDouble("0.73433e-145", 0x21cd57b723dc17bful); CheckOneDouble("31.076044256878e259", 0x76043627aa7248dful); CheckOneDouble("0.8089124675e-201", 0x162fb3bf98f037f7ul); CheckOneDouble("88.7453407049700914e-144", 0x227150a674c218e3ul); CheckOneDouble("32.401089401e-65", 0x32c10fa88084d643ul); CheckOneDouble("0.734277884753e-209", 0x14834fdfb6248755ul); CheckOneDouble("8.3435e+153", 0x5fe3e9c5b617dc39ul); CheckOneDouble("30.379e-129", 0x25750ec799af9efful); CheckOneDouble("78.638509299e141", 0x5d99cb8c0a72cd05ul); CheckOneDouble("30.096884930e-42", 0x3784f976b4d47d63ul); //// values from http://www.icir.org/vern/papers/testbase-report.pdf table 1 (less than half ULP - round down) CheckOneDouble("69e+267", 0x77C0B7CB60C994DAul); CheckOneDouble("999e-026", 0x3B282782AFE1869Eul); CheckOneDouble("7861e-034", 0x39AFE3544145E9D8ul); CheckOneDouble("75569e-254", 0x0C35A462D91C6AB3ul); CheckOneDouble("928609e-261", 0x0AFBE2DD66200BEFul); CheckOneDouble("9210917e+080", 0x51FDA232347E6032ul); CheckOneDouble("84863171e+114", 0x59406E98F5EC8F37ul); CheckOneDouble("653777767e+273", 0x7A720223F2B3A881ul); CheckOneDouble("5232604057e-298", 0x041465B896C24520ul); CheckOneDouble("27235667517e-109", 0x2B77D41824D64FB2ul); CheckOneDouble("653532977297e-123", 0x28D925A0AABCDC68ul); CheckOneDouble("3142213164987e-294", 0x057D3409DFBCA26Ful); CheckOneDouble("46202199371337e-072", 0x33D28F9EDFBD341Ful); CheckOneDouble("231010996856685e-073", 0x33C28F9EDFBD341Ful); CheckOneDouble("9324754620109615e+212", 0x6F43AE60753AF6CAul); CheckOneDouble("78459735791271921e+049", 0x4D9DCD0089C1314Eul); CheckOneDouble("272104041512242479e+200", 0x6D13BBB4BF05F087ul); CheckOneDouble("6802601037806061975e+198", 0x6CF3BBB4BF05F087ul); CheckOneDouble("20505426358836677347e-221", 0x161012954B6AABBAul); CheckOneDouble("836168422905420598437e-234", 0x13B20403A628A9CAul); CheckOneDouble("4891559871276714924261e+222", 0x7286ECAF7694A3C7ul); //// values from http://www.icir.org/vern/papers/testbase-report.pdf table 2 (greater than half ULP - round up) CheckOneDouble("85e-037", 0x38A698CCDC60015Aul); CheckOneDouble("623e+100", 0x554640A62F3A83DFul); CheckOneDouble("3571e+263", 0x77462644C61D41AAul); CheckOneDouble("81661e+153", 0x60B7CA8E3D68578Eul); CheckOneDouble("920657e-023", 0x3C653A9985DBDE6Cul); CheckOneDouble("4603285e-024", 0x3C553A9985DBDE6Cul); CheckOneDouble("87575437e-309", 0x016E07320602056Cul); CheckOneDouble("245540327e+122", 0x5B01B6231E18C5CBul); CheckOneDouble("6138508175e+120", 0x5AE1B6231E18C5CBul); CheckOneDouble("83356057653e+193", 0x6A4544E6DAEE2A18ul); CheckOneDouble("619534293513e+124", 0x5C210C20303FE0F1ul); CheckOneDouble("2335141086879e+218", 0x6FC340A1C932C1EEul); CheckOneDouble("36167929443327e-159", 0x21BCE77C2B3328FCul); CheckOneDouble("609610927149051e-255", 0x0E104273B18918B1ul); CheckOneDouble("3743626360493413e-165", 0x20E8823A57ADBEF9ul); CheckOneDouble("94080055902682397e-242", 0x11364981E39E66CAul); CheckOneDouble("899810892172646163e+283", 0x7E6ADF51FA055E03ul); CheckOneDouble("7120190517612959703e+120", 0x5CC3220DCD5899FDul); CheckOneDouble("25188282901709339043e-252", 0x0FA4059AF3DB2A84ul); CheckOneDouble("308984926168550152811e-052", 0x39640DE48676653Bul); CheckOneDouble("6372891218502368041059e+064", 0x51C067047DBB38FEul); // http://www.exploringbinary.com/incorrect-decimal-to-floating-point-conversion-in-sqlite/ CheckOneDouble("1e-23", 0x3B282DB34012B251ul); CheckOneDouble("8.533e+68", 0x4E3FA69165A8EEA2ul); CheckOneDouble("4.1006e-184", 0x19DBE0D1C7EA60C9ul); CheckOneDouble("9.998e+307", 0x7FE1CC0A350CA87Bul); CheckOneDouble("9.9538452227e-280", 0x0602117AE45CDE43ul); CheckOneDouble("6.47660115e-260", 0x0A1FDD9E333BADADul); CheckOneDouble("7.4e+47", 0x49E033D7ECA0ADEFul); CheckOneDouble("5.92e+48", 0x4A1033D7ECA0ADEFul); CheckOneDouble("7.35e+66", 0x4DD172B70EABABA9ul); CheckOneDouble("8.32116e+55", 0x4B8B2628393E02CDul); } /// <summary> /// Test round tripping for some specific floating-point values constructed to test the edge cases of conversion implementations. /// </summary> [Fact] public static void TestSpecificDoubles() { CheckOneDouble("0.0", 0x0000000000000000ul); // Verify the smallest denormals: for (ulong i = 0x0000000000000001ul; i != 0x0000000000000100ul; ++i) { TestRoundTripDouble(i); } // Verify the largest denormals and the smallest normals: for (ulong i = 0x000fffffffffff00ul; i != 0x0010000000000100ul; ++i) { TestRoundTripDouble(i); } // Verify the largest normals: for (ulong i = 0x7fefffffffffff00ul; i != 0x7ff0000000000000ul; ++i) { TestRoundTripDouble(i); } // Verify all representable powers of two and nearby values: for (int pow = -1022; pow <= 1023; pow++) { ulong twoToThePow = ((ulong)(pow + 1023)) << 52; TestRoundTripDouble(twoToThePow); TestRoundTripDouble(twoToThePow + 1); TestRoundTripDouble(twoToThePow - 1); } // Verify all representable powers of ten and nearby values: for (int pow = -323; pow <= 308; pow++) { var s = $"1.0e{pow}"; double value; RealParser.TryParseDouble(s, out value); var tenToThePow = (ulong)BitConverter.DoubleToInt64Bits(value); CheckOneDouble(s, value); TestRoundTripDouble(tenToThePow + 1); TestRoundTripDouble(tenToThePow - 1); } // Verify a few large integer values: TestRoundTripDouble((double)long.MaxValue); TestRoundTripDouble((double)ulong.MaxValue); // Verify small and large exactly representable integers: CheckOneDouble("1", 0x3ff0000000000000); CheckOneDouble("2", 0x4000000000000000); CheckOneDouble("3", 0x4008000000000000); CheckOneDouble("4", 0x4010000000000000); CheckOneDouble("5", 0x4014000000000000); CheckOneDouble("6", 0x4018000000000000); CheckOneDouble("7", 0x401C000000000000); CheckOneDouble("8", 0x4020000000000000); CheckOneDouble("9007199254740984", 0x433ffffffffffff8); CheckOneDouble("9007199254740985", 0x433ffffffffffff9); CheckOneDouble("9007199254740986", 0x433ffffffffffffa); CheckOneDouble("9007199254740987", 0x433ffffffffffffb); CheckOneDouble("9007199254740988", 0x433ffffffffffffc); CheckOneDouble("9007199254740989", 0x433ffffffffffffd); CheckOneDouble("9007199254740990", 0x433ffffffffffffe); CheckOneDouble("9007199254740991", 0x433fffffffffffff); // 2^53 - 1 // Verify the smallest and largest denormal values: CheckOneDouble("5.0e-324", 0x0000000000000001); CheckOneDouble("1.0e-323", 0x0000000000000002); CheckOneDouble("1.5e-323", 0x0000000000000003); CheckOneDouble("2.0e-323", 0x0000000000000004); CheckOneDouble("2.5e-323", 0x0000000000000005); CheckOneDouble("3.0e-323", 0x0000000000000006); CheckOneDouble("3.5e-323", 0x0000000000000007); CheckOneDouble("4.0e-323", 0x0000000000000008); CheckOneDouble("4.5e-323", 0x0000000000000009); CheckOneDouble("5.0e-323", 0x000000000000000a); CheckOneDouble("5.5e-323", 0x000000000000000b); CheckOneDouble("6.0e-323", 0x000000000000000c); CheckOneDouble("6.5e-323", 0x000000000000000d); CheckOneDouble("7.0e-323", 0x000000000000000e); CheckOneDouble("7.5e-323", 0x000000000000000f); CheckOneDouble("2.2250738585071935e-308", 0x000ffffffffffff0); CheckOneDouble("2.2250738585071940e-308", 0x000ffffffffffff1); CheckOneDouble("2.2250738585071945e-308", 0x000ffffffffffff2); CheckOneDouble("2.2250738585071950e-308", 0x000ffffffffffff3); CheckOneDouble("2.2250738585071955e-308", 0x000ffffffffffff4); CheckOneDouble("2.2250738585071960e-308", 0x000ffffffffffff5); CheckOneDouble("2.2250738585071964e-308", 0x000ffffffffffff6); CheckOneDouble("2.2250738585071970e-308", 0x000ffffffffffff7); CheckOneDouble("2.2250738585071974e-308", 0x000ffffffffffff8); CheckOneDouble("2.2250738585071980e-308", 0x000ffffffffffff9); CheckOneDouble("2.2250738585071984e-308", 0x000ffffffffffffa); CheckOneDouble("2.2250738585071990e-308", 0x000ffffffffffffb); CheckOneDouble("2.2250738585071994e-308", 0x000ffffffffffffc); CheckOneDouble("2.2250738585072000e-308", 0x000ffffffffffffd); CheckOneDouble("2.2250738585072004e-308", 0x000ffffffffffffe); CheckOneDouble("2.2250738585072010e-308", 0x000fffffffffffff); // Test cases from Rick Regan's article, "Incorrectly Rounded Conversions in Visual C++": // // http://www.exploringbinary.com/incorrectly-rounded-conversions-in-visual-c-plus-plus/ // // Example 1: CheckOneDouble( "9214843084008499", 0x43405e6cec57761a); // Example 2: CheckOneDouble( "0.500000000000000166533453693773481063544750213623046875", 0x3fe0000000000002); // Example 3 (2^-1 + 2^-53 + 2^-54): CheckOneDouble( "30078505129381147446200", 0x44997a3c7271b021); // Example 4: CheckOneDouble( "1777820000000000000001", 0x4458180d5bad2e3e); // Example 5 (2^-1 + 2^-53 + 2^-54 + 2^-66): CheckOneDouble( "0.500000000000000166547006220929549868969843373633921146392822265625", 0x3fe0000000000002); // Example 6 (2^-1 + 2^-53 + 2^-54 + 2^-65): CheckOneDouble( "0.50000000000000016656055874808561867439493653364479541778564453125", 0x3fe0000000000002); // Example 7: CheckOneDouble( "0.3932922657273", 0x3fd92bb352c4623a ); // The following test cases are taken from other articles on Rick Regan's // Exploring Binary blog. These are conversions that other implementations // were found to perform incorrectly. // http://www.exploringbinary.com/nondeterministic-floating-point-conversions-in-java/ // http://www.exploringbinary.com/incorrectly-rounded-subnormal-conversions-in-java/ // Example 1 (2^-1047 + 2^-1075, half-ulp above a power of two): CheckOneDouble( "6.6312368714697582767853966302759672433990999473553031442499717587" + "362866301392654396180682007880487441059604205526018528897150063763" + "256665955396033303618005191075917832333584923372080578494993608994" + "251286407188566165030934449228547591599881603044399098682919739314" + "266256986631577498362522745234853124423586512070512924530832781161" + "439325697279187097860044978723221938561502254152119972830784963194" + "121246401117772161481107528151017752957198119743384519360959074196" + "224175384736794951486324803914359317679811223967034438033355297560" + "033532098300718322306892013830155987921841729099279241763393155074" + "022348361207309147831684007154624400538175927027662135590421159867" + "638194826541287705957668068727833491469671712939495988506756821156" + "96218943412532098591327667236328125E-316", 0x0000000008000000); // Example 2 (2^-1058 - 2^-1075, half-ulp below a power of two): CheckOneDouble( "3.2378839133029012895883524125015321748630376694231080599012970495" + "523019706706765657868357425877995578606157765598382834355143910841" + "531692526891905643964595773946180389283653051434639551003566966656" + "292020173313440317300443693602052583458034314716600326995807313009" + "548483639755486900107515300188817581841745696521731104736960227499" + "346384253806233697747365600089974040609674980283891918789639685754" + "392222064169814626901133425240027243859416510512935526014211553334" + "302252372915238433223313261384314778235911424088000307751706259156" + "707286570031519536642607698224949379518458015308952384398197084033" + "899378732414634842056080000272705311068273879077914449185347715987" + "501628125488627684932015189916680282517302999531439241685457086639" + "13273994694463908672332763671875E-319", 0x0000000000010000); // Example 3 (2^-1027 + 2^-1066 + 2^-1075, half-ulp above a non-power of two): CheckOneDouble( "6.9533558078476771059728052155218916902221198171459507544162056079" + "800301315496366888061157263994418800653863998640286912755395394146" + "528315847956685600829998895513577849614468960421131982842131079351" + "102171626549398024160346762138294097205837595404767869364138165416" + "212878432484332023692099166122496760055730227032447997146221165421" + "888377703760223711720795591258533828013962195524188394697705149041" + "926576270603193728475623010741404426602378441141744972109554498963" + "891803958271916028866544881824524095839813894427833770015054620157" + "450178487545746683421617594966617660200287528887833870748507731929" + "971029979366198762266880963149896457660004790090837317365857503352" + "620998601508967187744019647968271662832256419920407478943826987518" + "09812609536720628966577351093292236328125E-310", 0x0000800000000100 ); // Example 4 (2^-1058 + 2^-1063 + 2^-1075, half-ulp below a non-power of two): CheckOneDouble( "3.3390685575711885818357137012809439119234019169985217716556569973" + "284403145596153181688491490746626090999981130094655664268081703784" + "340657229916596426194677060348844249897410807907667784563321682004" + "646515939958173717821250106683466529959122339932545844611258684816" + "333436749050742710644097630907080178565840197768788124253120088123" + "262603630354748115322368533599053346255754042160606228586332807443" + "018924703005556787346899784768703698535494132771566221702458461669" + "916553215355296238706468887866375289955928004361779017462862722733" + "744717014529914330472578638646014242520247915673681950560773208853" + "293843223323915646452641434007986196650406080775491621739636492640" + "497383622906068758834568265867109610417379088720358034812416003767" + "05491726170293986797332763671875E-319", 0x0000000000010800 ); // http://www.exploringbinary.com/gays-strtod-returns-zero-for-inputs-just-above-2-1075/ // A number between 2^-2074 and 2^-1075, just slightly larger than 2^-1075. // It has bit 1075 set (the denormal rounding bit), followed by 2506 zeroes, // followed by one bits. It should round up to 2^-1074. CheckOneDouble( "2.470328229206232720882843964341106861825299013071623822127928412503" + "37753635104375932649918180817996189898282347722858865463328355177969" + "89819938739800539093906315035659515570226392290858392449105184435931" + "80284993653615250031937045767824921936562366986365848075700158576926" + "99037063119282795585513329278343384093519780155312465972635795746227" + "66465272827220056374006485499977096599470454020828166226237857393450" + "73633900796776193057750674017632467360096895134053553745851666113422" + "37666786041621596804619144672918403005300575308490487653917113865916" + "46239524912623653881879636239373280423891018672348497668235089863388" + "58792562830275599565752445550725518931369083625477918694866799496832" + "40497058210285131854513962138377228261454376934125320985913276672363" + "28125001e-324", 0x0000000000000001); } static void TestRoundTripDouble(ulong bits) { double d = BitConverter.Int64BitsToDouble((long)bits); if (double.IsInfinity(d) || double.IsNaN(d)) return; string s = $"{d:G17}"; CheckOneDouble(s, bits); } static void TestRoundTripDouble(double d) { string s = $"{d:G17}"; CheckOneDouble(s, d); } static void CheckOneDouble(string s, ulong expectedBits) { CheckOneDouble(s, BitConverter.Int64BitsToDouble((long)expectedBits)); } static void CheckOneDouble(string s, double expected) { double actual; if (!RealParser.TryParseDouble(s, out actual)) actual = 1.0 / 0.0; if (!actual.Equals(expected)) { #if DEBUG throw new AssertFailureException($@" Error for double input ""{s}"" expected {expected:G17} actual {actual:G17}"); #else throw new Exception($@" Error for double input ""{s}"" expected {expected:G17} actual {actual:G17}"); #endif } } // ============ test some floats ============ [Fact] public static void TestSpecificFloats() { CheckOneFloat(" 0.0", 0x00000000); // Verify the smallest denormals: for (uint i = 0x00000001; i != 0x00000100; ++i) { TestRoundTripFloat(i); } // Verify the largest denormals and the smallest normals: for (uint i = 0x007fff00; i != 0x00800100; ++i) { TestRoundTripFloat(i); } // Verify the largest normals: for (uint i = 0x7f7fff00; i != 0x7f800000; ++i) { TestRoundTripFloat(i); } // Verify all representable powers of two and nearby values: for (int i = -1022; i != 1023; ++i) { float f; try { f = (float)Math.Pow(2.0, i); } catch (OverflowException) { continue; } if (f == 0) continue; uint bits = FloatToInt32Bits(f); TestRoundTripFloat(bits - 1); TestRoundTripFloat(bits); TestRoundTripFloat(bits + 1); } // Verify all representable powers of ten and nearby values: for (int i = -50; i <= 40; ++i) { float f; try { f = (float)Math.Pow(10.0, i); } catch (OverflowException) { continue; } if (f == 0) continue; uint bits = FloatToInt32Bits(f); TestRoundTripFloat(bits - 1); TestRoundTripFloat(bits); TestRoundTripFloat(bits + 1); } TestRoundTripFloat((float)int.MaxValue); TestRoundTripFloat((float)uint.MaxValue); // Verify small and large exactly representable integers: CheckOneFloat("1", 0x3f800000); CheckOneFloat("2", 0x40000000); CheckOneFloat("3", 0x40400000); CheckOneFloat("4", 0x40800000); CheckOneFloat("5", 0x40A00000); CheckOneFloat("6", 0x40C00000); CheckOneFloat("7", 0x40E00000); CheckOneFloat("8", 0x41000000); CheckOneFloat("16777208", 0x4b7ffff8); CheckOneFloat("16777209", 0x4b7ffff9); CheckOneFloat("16777210", 0x4b7ffffa); CheckOneFloat("16777211", 0x4b7ffffb); CheckOneFloat("16777212", 0x4b7ffffc); CheckOneFloat("16777213", 0x4b7ffffd); CheckOneFloat("16777214", 0x4b7ffffe); CheckOneFloat("16777215", 0x4b7fffff); // 2^24 - 1 // Verify the smallest and largest denormal values: CheckOneFloat("1.4012984643248170e-45", 0x00000001); CheckOneFloat("2.8025969286496340e-45", 0x00000002); CheckOneFloat("4.2038953929744510e-45", 0x00000003); CheckOneFloat("5.6051938572992680e-45", 0x00000004); CheckOneFloat("7.0064923216240850e-45", 0x00000005); CheckOneFloat("8.4077907859489020e-45", 0x00000006); CheckOneFloat("9.8090892502737200e-45", 0x00000007); CheckOneFloat("1.1210387714598537e-44", 0x00000008); CheckOneFloat("1.2611686178923354e-44", 0x00000009); CheckOneFloat("1.4012984643248170e-44", 0x0000000a); CheckOneFloat("1.5414283107572988e-44", 0x0000000b); CheckOneFloat("1.6815581571897805e-44", 0x0000000c); CheckOneFloat("1.8216880036222622e-44", 0x0000000d); CheckOneFloat("1.9618178500547440e-44", 0x0000000e); CheckOneFloat("2.1019476964872256e-44", 0x0000000f); CheckOneFloat("1.1754921087447446e-38", 0x007ffff0); CheckOneFloat("1.1754922488745910e-38", 0x007ffff1); CheckOneFloat("1.1754923890044375e-38", 0x007ffff2); CheckOneFloat("1.1754925291342839e-38", 0x007ffff3); CheckOneFloat("1.1754926692641303e-38", 0x007ffff4); CheckOneFloat("1.1754928093939768e-38", 0x007ffff5); CheckOneFloat("1.1754929495238232e-38", 0x007ffff6); CheckOneFloat("1.1754930896536696e-38", 0x007ffff7); CheckOneFloat("1.1754932297835160e-38", 0x007ffff8); CheckOneFloat("1.1754933699133625e-38", 0x007ffff9); CheckOneFloat("1.1754935100432089e-38", 0x007ffffa); CheckOneFloat("1.1754936501730553e-38", 0x007ffffb); CheckOneFloat("1.1754937903029018e-38", 0x007ffffc); CheckOneFloat("1.1754939304327482e-38", 0x007ffffd); CheckOneFloat("1.1754940705625946e-38", 0x007ffffe); CheckOneFloat("1.1754942106924411e-38", 0x007fffff); // This number is exactly representable and should not be rounded in any // mode: // 0.1111111111111111111111100 // ^ CheckOneFloat("0.99999988079071044921875", 0x3f7ffffe); // This number is below the halfway point between two representable values // so it should round down in nearest mode: // 0.11111111111111111111111001 // ^ CheckOneFloat("0.99999989569187164306640625", 0x3f7ffffe); // This number is exactly halfway between two representable values, so it // should round to even in nearest mode: // 0.1111111111111111111111101 // ^ CheckOneFloat("0.9999999105930328369140625", 0x3f7ffffe); // This number is above the halfway point between two representable values // so it should round up in nearest mode: // 0.11111111111111111111111011 // ^ CheckOneFloat("0.99999992549419403076171875", 0x3f7fffff); } static void TestRoundTripFloat(uint bits) { float d = Int32BitsToFloat(bits); if (float.IsInfinity(d) || float.IsNaN(d)) return; string s = $"{d:G17}"; CheckOneFloat(s, bits); } static void TestRoundTripFloat(float d) { string s = $"{d:G17}"; if (s != "NaN" && s != "Infinity") CheckOneFloat(s, d); } static void CheckOneFloat(string s, uint expectedBits) { CheckOneFloat(s, Int32BitsToFloat(expectedBits)); } static void CheckOneFloat(string s, float expected) { float actual; if (!RealParser.TryParseFloat(s, out actual)) actual = 1.0f / 0.0f; if (!actual.Equals(expected)) { #if DEBUG throw new AssertFailureException($@"Error for float input ""{s}"" expected {expected:G17} actual {actual:G17}"); #else throw new Exception($@"Error for float input ""{s}"" expected {expected:G17} actual {actual:G17}"); #endif } } static uint FloatToInt32Bits(float f) { var bits = default(FloatUnion); bits.FloatData = f; return bits.IntData; } static float Int32BitsToFloat(uint i) { var bits = default(FloatUnion); bits.IntData = i; return bits.FloatData; } [StructLayout(LayoutKind.Explicit)] struct FloatUnion { [FieldOffset(0)] public uint IntData; [FieldOffset(0)] public float FloatData; } } }
49.541463
161
0.630071
[ "Apache-2.0" ]
AlessandroDelSole/Roslyn
src/Compilers/Core/CodeAnalysisTest/RealParserTests.cs
30,470
C#
/* ** SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008) ** Copyright (C) 2011 Silicon Graphics, Inc. ** All Rights Reserved. ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** of this software and associated documentation files (the "Software"), to deal ** in the Software without restriction, including without limitation the rights ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies ** of the Software, and to permit persons to whom the Software is furnished to do so, ** subject to the following conditions: ** ** The above copyright notice including the dates of first publication and either this ** permission notice or a reference to http://oss.sgi.com/projects/FreeB/ shall be ** included in all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, ** INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A ** PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL SILICON GRAPHICS, INC. ** BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE ** OR OTHER DEALINGS IN THE SOFTWARE. ** ** Except as contained in this notice, the name of Silicon Graphics, Inc. shall not ** be used in advertising or otherwise to promote the sale, use or other dealings in ** this Software without prior written authorization from Silicon Graphics, Inc. */ /* ** Original Author: Eric Veach, July 1994. ** libtess2: Mikko Mononen, http://code.google.com/p/libtess2/. ** LibTessDotNet: Remi Gillig, https://github.com/speps/LibTessDotNet */ // Seanba edit: Put LibTessDotNet in unique namespace so avoid name collisions // Seanba edit: Namespace modifications not supported by Unity using System; using System.Diagnostics; //#if DOUBLE //using Real = System.Double; //namespace LibTessDotNet.Double //#else using Real = System.Single; namespace SuperTiled2Unity.Editor.LibTessDotNet //#endif { internal static class Geom { public static bool IsWindingInside(WindingRule rule, int n) { switch (rule) { case WindingRule.EvenOdd: return (n & 1) == 1; case WindingRule.NonZero: return n != 0; case WindingRule.Positive: return n > 0; case WindingRule.Negative: return n < 0; case WindingRule.AbsGeqTwo: return n >= 2 || n <= -2; } throw new Exception("Wrong winding rule"); } public static bool VertCCW(MeshUtils.Vertex u, MeshUtils.Vertex v, MeshUtils.Vertex w) { return (u._s * (v._t - w._t) + v._s * (w._t - u._t) + w._s * (u._t - v._t)) >= 0.0f; } public static bool VertEq(MeshUtils.Vertex lhs, MeshUtils.Vertex rhs) { return lhs._s == rhs._s && lhs._t == rhs._t; } public static bool VertLeq(MeshUtils.Vertex lhs, MeshUtils.Vertex rhs) { return (lhs._s < rhs._s) || (lhs._s == rhs._s && lhs._t <= rhs._t); } /// <summary> /// Given three vertices u,v,w such that VertLeq(u,v) && VertLeq(v,w), /// evaluates the t-coord of the edge uw at the s-coord of the vertex v. /// Returns v->t - (uw)(v->s), ie. the signed distance from uw to v. /// If uw is vertical (and thus passes thru v), the result is zero. /// /// The calculation is extremely accurate and stable, even when v /// is very close to u or w. In particular if we set v->t = 0 and /// let r be the negated result (this evaluates (uw)(v->s)), then /// r is guaranteed to satisfy MIN(u->t,w->t) <= r <= MAX(u->t,w->t). /// </summary> public static Real EdgeEval(MeshUtils.Vertex u, MeshUtils.Vertex v, MeshUtils.Vertex w) { Debug.Assert(VertLeq(u, v) && VertLeq(v, w)); var gapL = v._s - u._s; var gapR = w._s - v._s; if (gapL + gapR > 0.0f) { if (gapL < gapR) { return (v._t - u._t) + (u._t - w._t) * (gapL / (gapL + gapR)); } else { return (v._t - w._t) + (w._t - u._t) * (gapR / (gapL + gapR)); } } /* vertical line */ return 0; } /// <summary> /// Returns a number whose sign matches EdgeEval(u,v,w) but which /// is cheaper to evaluate. Returns > 0, == 0 , or < 0 /// as v is above, on, or below the edge uw. /// </summary> public static Real EdgeSign(MeshUtils.Vertex u, MeshUtils.Vertex v, MeshUtils.Vertex w) { Debug.Assert(VertLeq(u, v) && VertLeq(v, w)); var gapL = v._s - u._s; var gapR = w._s - v._s; if (gapL + gapR > 0.0f) { return (v._t - w._t) * gapL + (v._t - u._t) * gapR; } /* vertical line */ return 0; } public static bool TransLeq(MeshUtils.Vertex lhs, MeshUtils.Vertex rhs) { return (lhs._t < rhs._t) || (lhs._t == rhs._t && lhs._s <= rhs._s); } public static Real TransEval(MeshUtils.Vertex u, MeshUtils.Vertex v, MeshUtils.Vertex w) { Debug.Assert(TransLeq(u, v) && TransLeq(v, w)); var gapL = v._t - u._t; var gapR = w._t - v._t; if (gapL + gapR > 0.0f) { if (gapL < gapR) { return (v._s - u._s) + (u._s - w._s) * (gapL / (gapL + gapR)); } else { return (v._s - w._s) + (w._s - u._s) * (gapR / (gapL + gapR)); } } /* vertical line */ return 0; } public static Real TransSign(MeshUtils.Vertex u, MeshUtils.Vertex v, MeshUtils.Vertex w) { Debug.Assert(TransLeq(u, v) && TransLeq(v, w)); var gapL = v._t - u._t; var gapR = w._t - v._t; if (gapL + gapR > 0.0f) { return (v._s - w._s) * gapL + (v._s - u._s) * gapR; } /* vertical line */ return 0; } public static bool EdgeGoesLeft(MeshUtils.Edge e) { return VertLeq(e._Dst, e._Org); } public static bool EdgeGoesRight(MeshUtils.Edge e) { return VertLeq(e._Org, e._Dst); } public static Real VertL1dist(MeshUtils.Vertex u, MeshUtils.Vertex v) { return Math.Abs(u._s - v._s) + Math.Abs(u._t - v._t); } public static void AddWinding(MeshUtils.Edge eDst, MeshUtils.Edge eSrc) { eDst._winding += eSrc._winding; eDst._Sym._winding += eSrc._Sym._winding; } public static Real Interpolate(Real a, Real x, Real b, Real y) { if (a < 0.0f) { a = 0.0f; } if (b < 0.0f) { b = 0.0f; } return ((a <= b) ? ((b == 0.0f) ? ((x+y) / 2.0f) : (x + (y-x) * (a/(a+b)))) : (y + (x-y) * (b/(a+b)))); } static void Swap(ref MeshUtils.Vertex a, ref MeshUtils.Vertex b) { var tmp = a; a = b; b = tmp; } /// <summary> /// Given edges (o1,d1) and (o2,d2), compute their point of intersection. /// The computed point is guaranteed to lie in the intersection of the /// bounding rectangles defined by each edge. /// </summary> public static void EdgeIntersect(MeshUtils.Vertex o1, MeshUtils.Vertex d1, MeshUtils.Vertex o2, MeshUtils.Vertex d2, MeshUtils.Vertex v) { // This is certainly not the most efficient way to find the intersection // of two line segments, but it is very numerically stable. // // Strategy: find the two middle vertices in the VertLeq ordering, // and interpolate the intersection s-value from these. Then repeat // using the TransLeq ordering to find the intersection t-value. if (!VertLeq(o1, d1)) { Swap(ref o1, ref d1); } if (!VertLeq(o2, d2)) { Swap(ref o2, ref d2); } if (!VertLeq(o1, o2)) { Swap(ref o1, ref o2); Swap(ref d1, ref d2); } if (!VertLeq(o2, d1)) { // Technically, no intersection -- do our best v._s = (o2._s + d1._s) / 2.0f; } else if (VertLeq(d1, d2)) { // Interpolate between o2 and d1 var z1 = EdgeEval(o1, o2, d1); var z2 = EdgeEval(o2, d1, d2); if (z1 + z2 < 0.0f) { z1 = -z1; z2 = -z2; } v._s = Interpolate(z1, o2._s, z2, d1._s); } else { // Interpolate between o2 and d2 var z1 = EdgeSign(o1, o2, d1); var z2 = -EdgeSign(o1, d2, d1); if (z1 + z2 < 0.0f) { z1 = -z1; z2 = -z2; } v._s = Interpolate(z1, o2._s, z2, d2._s); } // Now repeat the process for t if (!TransLeq(o1, d1)) { Swap(ref o1, ref d1); } if (!TransLeq(o2, d2)) { Swap(ref o2, ref d2); } if (!TransLeq(o1, o2)) { Swap(ref o1, ref o2); Swap(ref d1, ref d2); } if (!TransLeq(o2, d1)) { // Technically, no intersection -- do our best v._t = (o2._t + d1._t) / 2.0f; } else if (TransLeq(d1, d2)) { // Interpolate between o2 and d1 var z1 = TransEval(o1, o2, d1); var z2 = TransEval(o2, d1, d2); if (z1 + z2 < 0.0f) { z1 = -z1; z2 = -z2; } v._t = Interpolate(z1, o2._t, z2, d1._t); } else { // Interpolate between o2 and d2 var z1 = TransSign(o1, o2, d1); var z2 = -TransSign(o1, d2, d1); if (z1 + z2 < 0.0f) { z1 = -z1; z2 = -z2; } v._t = Interpolate(z1, o2._t, z2, d2._t); } } } }
36.898361
145
0.482051
[ "MIT" ]
Debelzak/PlatformerProject
Assets/SuperTiled2Unity/Scripts/Editor/ThirdParty/LibTessDotNet/Geom.cs
11,256
C#
namespace CursoEntityFrameworkCore.ConsoleApp { public class Compra { public int Id { get; set; } public decimal Preco { get; set; } public int ProdutoId { get; set; } public Produto Produto { get; set; } public int Quantidade { get; set; } public override string ToString() => $"Compra[Id={Id}, Preco={Preco}, Produto={Produto.Nome}, Quantidade={Quantidade}]"; } }
32.769231
128
0.615023
[ "MIT" ]
flaviogf/Cursos
alura/curso_entity_framework_core/CursoEntityFrameworkCore.ConsoleApp/Compra.cs
426
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Cr.V20180321.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class CreateBotTaskResponse : AbstractModel { /// <summary> /// 机器人任务Id /// </summary> [JsonProperty("BotId")] public string BotId{ get; set; } /// <summary> /// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 /// </summary> [JsonProperty("RequestId")] public string RequestId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "BotId", this.BotId); this.SetParamSimple(map, prefix + "RequestId", this.RequestId); } } }
30.098039
81
0.640391
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Cr/V20180321/Models/CreateBotTaskResponse.cs
1,603
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace NumSharp.UnitTest.Logic { [TestClass] public class np_all_Test { [TestMethod] public void np_all_1D() { var np1 = new NDArray(new[] {true, true, false, false}, new Shape(4)); var np2 = new NDArray(typeof(bool), new Shape(150)); var np3 = new NDArray(new[] {true, true, true, true, true, true, true, true}, new Shape(8)); Assert.IsFalse(np.all(np1)); Assert.IsFalse(np.all(np2)); Assert.IsTrue(np.all(np3)); } [TestMethod] public void np_all_2D() { var np1 = new NDArray(new bool[] {true, true, false, false, true, false}, new Shape(2, 3)); var np2 = new NDArray(typeof(bool), new Shape(39, 17)); var np3 = new NDArray(new[] {true, true, true, true, true, true, true, true}, new Shape(2, 4)); Assert.IsFalse(np.all(np1)); Assert.IsFalse(np.all(np2)); Assert.IsTrue(np.all(np3)); } } }
32.222222
107
0.569828
[ "Apache-2.0" ]
SciSharp/NumSharp.Lite
UnitTest/Logic/np.all.Test.cs
1,162
C#
using MouseAccelAutoOffMonitor.ViewModels; using MouseAccelAutoOffMonitor.Views; using Prism.Ioc; using Prism.Services.Dialogs; using Prism.Unity; using System.Windows; using Unity; namespace MouseAccelAutoOffMonitor { /// <summary> /// App.xaml の相互作用ロジック /// </summary> public partial class App : PrismApplication { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); ShutdownMode = ShutdownMode.OnExplicitShutdown; MainWindowViewModel.ViewModel.StartProcessesMonitoringCommand.Execute(); } protected override void OnExit(ExitEventArgs e) { MainWindowViewModel.ViewModel.ExitProcessesMonitoringCommand.Execute(); base.OnExit(e); } protected override void RegisterTypes(IContainerRegistry containerRegistry) { containerRegistry.RegisterDialog<Views.ProcessNameListDialog, ViewModels.ProcessNameListDialogViewModel>(); containerRegistry.RegisterDialog<Views.RunningAppListDialog, ViewModels.RunningAppListDialogViewModel>(); containerRegistry.Register<NotifyIcon>(); } protected override Window CreateShell() { return new MainWindow(); } } }
30.186047
119
0.6849
[ "MIT" ]
kiwamaru/MouseAccelAutoOff
MouseAccelAutoOffMonitor/App.xaml.cs
1,318
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20200601 { public static class GetWebApplicationFirewallPolicy { /// <summary> /// Defines web application firewall policy. /// </summary> public static Task<GetWebApplicationFirewallPolicyResult> InvokeAsync(GetWebApplicationFirewallPolicyArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetWebApplicationFirewallPolicyResult>("azure-native:network/v20200601:getWebApplicationFirewallPolicy", args ?? new GetWebApplicationFirewallPolicyArgs(), options.WithVersion()); } public sealed class GetWebApplicationFirewallPolicyArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the policy. /// </summary> [Input("policyName", required: true)] public string PolicyName { get; set; } = null!; /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; public GetWebApplicationFirewallPolicyArgs() { } } [OutputType] public sealed class GetWebApplicationFirewallPolicyResult { /// <summary> /// A collection of references to application gateways. /// </summary> public readonly ImmutableArray<Outputs.ApplicationGatewayResponse> ApplicationGateways; /// <summary> /// The custom rules inside the policy. /// </summary> public readonly ImmutableArray<Outputs.WebApplicationFirewallCustomRuleResponse> CustomRules; /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> public readonly string Etag; /// <summary> /// A collection of references to application gateway http listeners. /// </summary> public readonly ImmutableArray<Outputs.SubResourceResponse> HttpListeners; /// <summary> /// Resource ID. /// </summary> public readonly string? Id; /// <summary> /// Resource location. /// </summary> public readonly string? Location; /// <summary> /// Describes the managedRules structure. /// </summary> public readonly Outputs.ManagedRulesDefinitionResponse ManagedRules; /// <summary> /// Resource name. /// </summary> public readonly string Name; /// <summary> /// A collection of references to application gateway path rules. /// </summary> public readonly ImmutableArray<Outputs.SubResourceResponse> PathBasedRules; /// <summary> /// The PolicySettings for policy. /// </summary> public readonly Outputs.PolicySettingsResponse? PolicySettings; /// <summary> /// The provisioning state of the web application firewall policy resource. /// </summary> public readonly string ProvisioningState; /// <summary> /// Resource status of the policy. /// </summary> public readonly string ResourceState; /// <summary> /// Resource tags. /// </summary> public readonly ImmutableDictionary<string, string>? Tags; /// <summary> /// Resource type. /// </summary> public readonly string Type; [OutputConstructor] private GetWebApplicationFirewallPolicyResult( ImmutableArray<Outputs.ApplicationGatewayResponse> applicationGateways, ImmutableArray<Outputs.WebApplicationFirewallCustomRuleResponse> customRules, string etag, ImmutableArray<Outputs.SubResourceResponse> httpListeners, string? id, string? location, Outputs.ManagedRulesDefinitionResponse managedRules, string name, ImmutableArray<Outputs.SubResourceResponse> pathBasedRules, Outputs.PolicySettingsResponse? policySettings, string provisioningState, string resourceState, ImmutableDictionary<string, string>? tags, string type) { ApplicationGateways = applicationGateways; CustomRules = customRules; Etag = etag; HttpListeners = httpListeners; Id = id; Location = location; ManagedRules = managedRules; Name = name; PathBasedRules = pathBasedRules; PolicySettings = policySettings; ProvisioningState = provisioningState; ResourceState = resourceState; Tags = tags; Type = type; } } }
34.120805
233
0.623131
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Network/V20200601/GetWebApplicationFirewallPolicy.cs
5,084
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; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Internal; namespace Microsoft.EntityFrameworkCore.Query.SqlExpressions { public class SelectExpression : TableExpressionBase { private IDictionary<ProjectionMember, Expression> _projectionMapping = new Dictionary<ProjectionMember, Expression>(); private readonly List<ProjectionExpression> _projection = new List<ProjectionExpression>(); private readonly IDictionary<EntityProjectionExpression, IDictionary<IProperty, int>> _entityProjectionCache = new Dictionary<EntityProjectionExpression, IDictionary<IProperty, int>>(); private readonly List<TableExpressionBase> _tables = new List<TableExpressionBase>(); private readonly List<SqlExpression> _groupBy = new List<SqlExpression>(); private readonly List<OrderingExpression> _orderings = new List<OrderingExpression>(); private readonly List<SqlExpression> _identifier = new List<SqlExpression>(); private readonly List<SqlExpression> _childIdentifiers = new List<SqlExpression>(); private readonly List<SelectExpression> _pendingCollections = new List<SelectExpression>(); public IReadOnlyList<ProjectionExpression> Projection => _projection; public IReadOnlyList<TableExpressionBase> Tables => _tables; public IReadOnlyList<SqlExpression> GroupBy => _groupBy; public IReadOnlyList<OrderingExpression> Orderings => _orderings; public ISet<string> Tags { get; private set; } = new HashSet<string>(); public SqlExpression Predicate { get; private set; } public SqlExpression Having { get; private set; } public SqlExpression Limit { get; private set; } public SqlExpression Offset { get; private set; } public bool IsDistinct { get; private set; } public void ApplyTags(ISet<string> tags) { Tags = tags; } /// <summary> /// Marks this <see cref="SelectExpression"/> as representing an SQL set operation, such as a UNION. /// For regular SQL SELECT expressions, contains <c>None</c>. /// </summary> public SetOperationType SetOperationType { get; private set; } /// <summary> /// Returns whether this <see cref="SelectExpression"/> represents an SQL set operation, such as a UNION. /// </summary> public bool IsSetOperation => SetOperationType != SetOperationType.None; internal SelectExpression( string alias, List<ProjectionExpression> projections, List<TableExpressionBase> tables, List<SqlExpression> groupBy, List<OrderingExpression> orderings) : base(alias) { _projection = projections; _tables = tables; _groupBy = groupBy; _orderings = orderings; } internal SelectExpression(IEntityType entityType) : base(null) { var tableExpression = new TableExpression( entityType.GetTableName(), entityType.GetSchema(), entityType.GetTableName().ToLower().Substring(0, 1)); _tables.Add(tableExpression); var entityProjection = new EntityProjectionExpression(entityType, tableExpression, false); _projectionMapping[new ProjectionMember()] = entityProjection; if (entityType.FindPrimaryKey() != null) { foreach (var property in entityType.FindPrimaryKey().Properties) { _identifier.Add(entityProjection.BindProperty(property)); } } } internal SelectExpression(IEntityType entityType, string sql, Expression arguments) : base(null) { var fromSqlExpression = new FromSqlExpression( sql, arguments, entityType.GetTableName().ToLower().Substring(0, 1)); _tables.Add(fromSqlExpression); var entityProjection = new EntityProjectionExpression(entityType, fromSqlExpression, false); _projectionMapping[new ProjectionMember()] = entityProjection; if (entityType.FindPrimaryKey() != null) { foreach (var property in entityType.FindPrimaryKey().Properties) { _identifier.Add(entityProjection.BindProperty(property)); } } } public bool IsNonComposedFromSql() { return Limit == null && Offset == null && !IsDistinct && Predicate == null && GroupBy.Count == 0 && Having == null && Orderings.Count == 0 && Tables.Count == 1 && Tables[0] is FromSqlExpression fromSql && Projection.All(pe => pe.Expression is ColumnExpression column ? ReferenceEquals(column.Table, fromSql) : false); } public void ApplyProjection() { if (Projection.Any()) { return; } var result = new Dictionary<ProjectionMember, Expression>(); foreach (var keyValuePair in _projectionMapping) { if (keyValuePair.Value is EntityProjectionExpression entityProjection) { var map = new Dictionary<IProperty, int>(); foreach (var property in GetAllPropertiesInHierarchy(entityProjection.EntityType)) { map[property] = AddToProjection(entityProjection.BindProperty(property)); } result[keyValuePair.Key] = Constant(map); } else { result[keyValuePair.Key] = Constant(AddToProjection( (SqlExpression)keyValuePair.Value, keyValuePair.Key.Last?.Name)); } } _projectionMapping = result; } private IEnumerable<IProperty> GetAllPropertiesInHierarchy(IEntityType entityType) => entityType.GetTypesInHierarchy().SelectMany(EntityTypeExtensions.GetDeclaredProperties); public void ReplaceProjectionMapping(IDictionary<ProjectionMember, Expression> projectionMapping) { _projectionMapping.Clear(); foreach (var kvp in projectionMapping) { _projectionMapping[kvp.Key] = kvp.Value; } } public Expression GetMappedProjection(ProjectionMember projectionMember) => _projectionMapping[projectionMember]; public int AddToProjection(SqlExpression sqlExpression) { return AddToProjection(sqlExpression, null); } private int AddToProjection(SqlExpression sqlExpression, string alias) { var existingIndex = _projection.FindIndex(pe => pe.Expression.Equals(sqlExpression)); if (existingIndex != -1) { return existingIndex; } var baseAlias = alias ?? (sqlExpression as ColumnExpression)?.Name ?? (Alias != null ? "c" : null); var currentAlias = baseAlias ?? ""; if (Alias != null && baseAlias != null) { var counter = 0; while (_projection.Any(pe => string.Equals(pe.Alias, currentAlias, StringComparison.OrdinalIgnoreCase))) { currentAlias = $"{baseAlias}{counter++}"; } } _projection.Add(new ProjectionExpression(sqlExpression, currentAlias)); return _projection.Count - 1; } public IDictionary<IProperty, int> AddToProjection(EntityProjectionExpression entityProjection) { if (!_entityProjectionCache.TryGetValue(entityProjection, out var dictionary)) { dictionary = new Dictionary<IProperty, int>(); foreach (var property in GetAllPropertiesInHierarchy(entityProjection.EntityType)) { dictionary[property] = AddToProjection(entityProjection.BindProperty(property)); } _entityProjectionCache[entityProjection] = dictionary; } return dictionary; } public void PrepareForAggregate() { if (IsDistinct || Limit != null || Offset != null || IsSetOperation || GroupBy.Count > 0) { PushdownIntoSubquery(); } } public void ApplyPredicate(SqlExpression expression) { if (expression is SqlConstantExpression sqlConstant && (bool)sqlConstant.Value) { return; } if (Limit != null || Offset != null || IsSetOperation) { var mappings = PushdownIntoSubquery(); expression = new SqlRemappingVisitor(mappings).Remap(expression); } if (_groupBy.Count > 0) { Having = Having == null ? expression : new SqlBinaryExpression( ExpressionType.AndAlso, Having, expression, typeof(bool), expression.TypeMapping); } else { Predicate = Predicate == null ? expression : new SqlBinaryExpression( ExpressionType.AndAlso, Predicate, expression, typeof(bool), expression.TypeMapping); } } public Expression ApplyGrouping(Expression keySelector) { ClearOrdering(); if (keySelector is SqlConstantExpression || keySelector is SqlParameterExpression) { PushdownIntoSubquery(); var subquery = (SelectExpression)_tables[0]; var projectionIndex = subquery.AddToProjection((SqlExpression)keySelector, nameof(IGrouping<int, int>.Key)); keySelector = new ColumnExpression(subquery.Projection[projectionIndex], subquery); } AppendGroupBy(keySelector); return keySelector; } private void AppendGroupBy(Expression keySelector) { switch (keySelector) { case SqlExpression sqlExpression: _groupBy.Add(sqlExpression); break; case NewExpression newExpression: foreach (var argument in newExpression.Arguments) { AppendGroupBy(argument); } break; case MemberInitExpression memberInitExpression: AppendGroupBy(memberInitExpression.NewExpression); foreach (var argument in memberInitExpression.Bindings) { AppendGroupBy(((MemberAssignment)argument).Expression); } break; default: throw new InvalidOperationException("Invalid keySelector for Group By"); } } public void ApplyOrdering(OrderingExpression orderingExpression) { // TODO: We should not be pushing down set operations, see #16244 if (IsDistinct || Limit != null || Offset != null || IsSetOperation) { orderingExpression = orderingExpression.Update( new SqlRemappingVisitor(PushdownIntoSubquery()) .Remap(orderingExpression.Expression)); } _orderings.Clear(); _orderings.Add(orderingExpression); } public void AppendOrdering(OrderingExpression orderingExpression) { if (_orderings.FirstOrDefault(o => o.Expression.Equals(orderingExpression.Expression)) == null) { _orderings.Add(orderingExpression); } } public void ApplyLimit(SqlExpression sqlExpression) { // TODO: We should not be pushing down set operations, see #16244 if (Limit != null || IsSetOperation) { PushdownIntoSubquery(); } Limit = sqlExpression; } public void ApplyOffset(SqlExpression sqlExpression) { // TODO: We should not be pushing down set operations, see #16244 if (Limit != null || Offset != null || IsSetOperation) { PushdownIntoSubquery(); } Offset = sqlExpression; } public void ReverseOrderings() { if (Limit != null || Offset != null) { PushdownIntoSubquery(); } var existingOrdering = _orderings.ToArray(); _orderings.Clear(); for (var i = 0; i < existingOrdering.Length; i++) { _orderings.Add( new OrderingExpression( existingOrdering[i].Expression, !existingOrdering[i].IsAscending)); } } public void ApplyDistinct() { if (Limit != null || Offset != null || IsSetOperation) { PushdownIntoSubquery(); } IsDistinct = true; ClearOrdering(); } public void ClearOrdering() { _orderings.Clear(); } /// <summary> /// Applies a set operation (e.g. Union, Intersect) on this query, pushing it down and <paramref name="otherSelectExpression"/> /// down to be the set operands. /// </summary> /// <param name="setOperationType"> The type of set operation to be applied. </param> /// <param name="otherSelectExpression"> The other expression to participate as an operate in the operation (along with this one). </param> /// <param name="shaperExpression"> The shaper expression currently in use. </param> /// <returns> /// A shaper expression to be used. This will be the same as <paramref name="shaperExpression"/>, unless the set operation /// modified the return type (i.e. upcast to common ancestor). /// </returns> public Expression ApplySetOperation( SetOperationType setOperationType, SelectExpression otherSelectExpression, Expression shaperExpression) { // TODO: throw if there are pending collection joins // TODO: What happens when applying set operations on 2 queries with one of them being grouping var select1 = new SelectExpression(null, new List<ProjectionExpression>(), _tables.ToList(), _groupBy.ToList(), _orderings.ToList()) { IsDistinct = IsDistinct, Predicate = Predicate, Having = Having, Offset = Offset, Limit = Limit, SetOperationType = SetOperationType }; select1._projectionMapping = new Dictionary<ProjectionMember, Expression>(_projectionMapping); _projectionMapping.Clear(); select1._identifier.AddRange(_identifier); _identifier.Clear(); var select2 = otherSelectExpression; if (_projection.Any()) { throw new InvalidOperationException("Can't process set operations after client evaluation, consider moving the operation before the last Select() call (see issue #16243)"); } else { if (select1._projectionMapping.Count != select2._projectionMapping.Count) { // Should not be possible after compiler checks throw new Exception("Different projection mapping count in set operation"); } foreach (var joinedMapping in select1._projectionMapping.Join( select2._projectionMapping, kv => kv.Key, kv => kv.Key, (kv1, kv2) => (kv1.Key, Value1: kv1.Value, Value2: kv2.Value))) { if (joinedMapping.Value1 is EntityProjectionExpression entityProjection1 && joinedMapping.Value2 is EntityProjectionExpression entityProjection2) { handleEntityMapping(joinedMapping.Key, select1, entityProjection1, select2, entityProjection2); continue; } if (joinedMapping.Value1 is ColumnExpression && joinedMapping.Value2 is ColumnExpression || joinedMapping.Value1 is ScalarSubqueryExpression && joinedMapping.Value2 is ScalarSubqueryExpression) { handleColumnMapping( joinedMapping.Key, select1, (SqlExpression)joinedMapping.Value1, select2, (SqlExpression)joinedMapping.Value2); continue; } throw new InvalidOperationException("Non-matching or unknown projection mapping type in set operation"); } } Offset = null; Limit = null; IsDistinct = false; Predicate = null; Having = null; _orderings.Clear(); _tables.Clear(); _tables.Add(select1); _tables.Add(otherSelectExpression); SetOperationType = setOperationType; return shaperExpression; void handleEntityMapping( ProjectionMember projectionMember, SelectExpression select1, EntityProjectionExpression projection1, SelectExpression select2, EntityProjectionExpression projection2) { var propertyExpressions = new Dictionary<IProperty, ColumnExpression>(); if (projection1.EntityType == projection2.EntityType) { foreach (var property in GetAllPropertiesInHierarchy(projection1.EntityType)) { propertyExpressions[property] = addSetOperationColumnProjections( property, select1, projection1.BindProperty(property), select2, projection2.BindProperty(property)); } _projectionMapping[projectionMember] = new EntityProjectionExpression(projection1.EntityType, propertyExpressions); return; } throw new InvalidOperationException("Set operations over different entity types are currently unsupported (see #16298)"); } ColumnExpression addSetOperationColumnProjections( IProperty property, SelectExpression select1, ColumnExpression column1, SelectExpression select2, ColumnExpression column2) { var columnName = column1.Name; select1._projection.Add(new ProjectionExpression(column1, columnName)); select2._projection.Add(new ProjectionExpression(column2, columnName)); if (select1._identifier.Contains(column1)) { _identifier.Add(column1); } return column1; } void handleColumnMapping( ProjectionMember projectionMember, SelectExpression select1, SqlExpression innerColumn1, SelectExpression select2, SqlExpression innerColumn2) { // The actual columns may actually be different, but we don't care as long as the type and alias // coming out of the two operands are the same var alias = projectionMember.Last?.Name; select1.AddToProjection(innerColumn1, alias); select2.AddToProjection(innerColumn2, alias); _projectionMapping[projectionMember] = innerColumn1; } } public IDictionary<SqlExpression, ColumnExpression> PushdownIntoSubquery() { var subquery = new SelectExpression( "t", new List<ProjectionExpression>(), _tables.ToList(), _groupBy.ToList(), _orderings.ToList()) { IsDistinct = IsDistinct, Predicate = Predicate, Having = Having, Offset = Offset, Limit = Limit, SetOperationType = SetOperationType }; ColumnExpression liftProjectionFromSubquery(SqlExpression projection) { var index = subquery.AddToProjection(projection); var projectionExpression = subquery._projection[index]; return new ColumnExpression(projectionExpression, subquery); } var projectionMap = new Dictionary<SqlExpression, ColumnExpression>(); if (_projection.Any()) { var projections = _projection.Select(pe => pe.Expression).ToList(); _projection.Clear(); foreach (var projection in projections) { var outerColumn = liftProjectionFromSubquery(projection); AddToProjection(outerColumn); projectionMap[projection] = outerColumn; } } else { foreach (var mapping in _projectionMapping.ToList()) { if (mapping.Value is EntityProjectionExpression entityProjection) { var propertyExpressions = new Dictionary<IProperty, ColumnExpression>(); foreach (var property in GetAllPropertiesInHierarchy(entityProjection.EntityType)) { var innerColumn = entityProjection.BindProperty(property); var outerColumn = liftProjectionFromSubquery(innerColumn); projectionMap[innerColumn] = outerColumn; propertyExpressions[property] = outerColumn; } _projectionMapping[mapping.Key] = new EntityProjectionExpression(entityProjection.EntityType, propertyExpressions); } else { var innerColumn = (SqlExpression)mapping.Value; var outerColumn = liftProjectionFromSubquery(innerColumn); projectionMap[innerColumn] = outerColumn; _projectionMapping[mapping.Key] = outerColumn; } } } var identifiers = _identifier.ToList(); _identifier.Clear(); // TODO: See issue#15873 foreach (var identifier in identifiers) { if (projectionMap.TryGetValue(identifier, out var outerColumn)) { _identifier.Add(outerColumn); } else if (!IsDistinct && GroupBy.Count == 0) { outerColumn = liftProjectionFromSubquery(identifier); _identifier.Add(outerColumn); } } var childIdentifiers = _childIdentifiers.ToList(); _childIdentifiers.Clear(); // TODO: See issue#15873 foreach (var identifier in childIdentifiers) { if (projectionMap.TryGetValue(identifier, out var outerColumn)) { _childIdentifiers.Add(outerColumn); } else if (!IsDistinct && GroupBy.Count == 0) { outerColumn = liftProjectionFromSubquery(identifier); _childIdentifiers.Add(outerColumn); } } var pendingCollections = _pendingCollections.ToList(); _pendingCollections.Clear(); _pendingCollections.AddRange(pendingCollections.Select(new SqlRemappingVisitor(projectionMap).Remap)); _orderings.Clear(); // Only lift order by to outer if subquery does not have distinct if (!subquery.IsDistinct) { foreach (var ordering in subquery._orderings) { var orderingExpression = ordering.Expression; if (!projectionMap.TryGetValue(orderingExpression, out var outerColumn)) { outerColumn = liftProjectionFromSubquery(orderingExpression); } _orderings.Add(ordering.Update(outerColumn)); } } if (subquery.Offset == null && subquery.Limit == null) { subquery.ClearOrdering(); } Offset = null; Limit = null; IsDistinct = false; Predicate = null; Having = null; SetOperationType = SetOperationType.None; _tables.Clear(); _tables.Add(subquery); _groupBy.Clear(); return projectionMap; } public CollectionShaperExpression AddCollectionProjection( ShapedQueryExpression shapedQueryExpression, INavigation navigation, Type elementType) { var innerSelectExpression = (SelectExpression)shapedQueryExpression.QueryExpression; _pendingCollections.Add(innerSelectExpression); return new CollectionShaperExpression( new ProjectionBindingExpression(this, _pendingCollections.Count - 1, typeof(object)), shapedQueryExpression.ShaperExpression, navigation, elementType); } public Expression ApplyCollectionJoin( int collectionIndex, int collectionId, Expression innerShaper, INavigation navigation, Type elementType) { var innerSelectExpression = _pendingCollections[collectionIndex]; _pendingCollections[collectionIndex] = null; var parentIdentifier = GetIdentifierAccessor(_identifier); var outerIdentifier = GetIdentifierAccessor(_identifier.Concat(_childIdentifiers)); innerSelectExpression.ApplyProjection(); var selfIdentifier = innerSelectExpression.GetIdentifierAccessor(innerSelectExpression._identifier); if (collectionIndex == 0) { foreach (var column in _identifier) { AppendOrdering(new OrderingExpression(column, ascending: true)); } } var joinPredicate = ExtractJoinKey(innerSelectExpression); if (joinPredicate != null) { if (innerSelectExpression.Offset != null || innerSelectExpression.Limit != null || innerSelectExpression.IsDistinct || innerSelectExpression.Predicate != null || innerSelectExpression.Tables.Count > 1 || innerSelectExpression.GroupBy.Count > 1) { var sqlRemappingVisitor = new SqlRemappingVisitor(innerSelectExpression.PushdownIntoSubquery()); joinPredicate = sqlRemappingVisitor.Remap(joinPredicate); } var leftJoinExpression = new LeftJoinExpression(innerSelectExpression.Tables.Single(), joinPredicate); _tables.Add(leftJoinExpression); foreach (var ordering in innerSelectExpression.Orderings) { AppendOrdering(ordering.Update(MakeNullable(ordering.Expression))); } var indexOffset = _projection.Count; foreach (var projection in innerSelectExpression.Projection) { AddToProjection(MakeNullable(projection.Expression)); } foreach (var identifier in innerSelectExpression._identifier.Concat(innerSelectExpression._childIdentifiers)) { var updatedColumn = MakeNullable(identifier); _childIdentifiers.Add(updatedColumn); AppendOrdering(new OrderingExpression(updatedColumn, ascending: true)); } var shaperRemapper = new ShaperRemappingExpressionVisitor(this, innerSelectExpression, indexOffset); innerShaper = shaperRemapper.Visit(innerShaper); selfIdentifier = shaperRemapper.Visit(selfIdentifier); return new RelationalCollectionShaperExpression( collectionId, parentIdentifier, outerIdentifier, selfIdentifier, innerShaper, navigation, elementType); } throw new InvalidOperationException("CollectionJoin: Unable to identify correlation predicate to convert to Left Join"); } private SqlExpression MakeNullable(SqlExpression sqlExpression) => sqlExpression is ColumnExpression column ? column.MakeNullable() : sqlExpression; private Expression GetIdentifierAccessor(IEnumerable<SqlExpression> identifyingProjection) { var updatedExpressions = new List<Expression>(); foreach (var keyExpression in identifyingProjection) { var index = AddToProjection(keyExpression); var projectionBindingExpression = new ProjectionBindingExpression(this, index, keyExpression.Type.MakeNullable()); updatedExpressions.Add( projectionBindingExpression.Type.IsValueType ? Convert(projectionBindingExpression, typeof(object)) : (Expression)projectionBindingExpression); } return NewArrayInit( typeof(object), updatedExpressions); } private class ShaperRemappingExpressionVisitor : ExpressionVisitor { private readonly SelectExpression _queryExpression; private readonly SelectExpression _innerSelectExpression; private readonly int _offset; public ShaperRemappingExpressionVisitor(SelectExpression queryExpression, SelectExpression innerSelectExpression, int offset) { _queryExpression = queryExpression; _innerSelectExpression = innerSelectExpression; _offset = offset; } protected override Expression VisitExtension(Expression extensionExpression) { if (extensionExpression is ProjectionBindingExpression projectionBindingExpression) { var oldIndex = (int)GetProjectionIndex(projectionBindingExpression); return new ProjectionBindingExpression(_queryExpression, oldIndex + _offset, projectionBindingExpression.Type); } if (extensionExpression is EntityShaperExpression entityShaper) { var oldIndexMap = (IDictionary<IProperty, int>)GetProjectionIndex( (ProjectionBindingExpression)entityShaper.ValueBufferExpression); var indexMap = new Dictionary<IProperty, int>(); foreach (var keyValuePair in oldIndexMap) { indexMap[keyValuePair.Key] = keyValuePair.Value + _offset; } return new EntityShaperExpression( entityShaper.EntityType, new ProjectionBindingExpression(_queryExpression, indexMap), nullable: true); } return base.VisitExtension(extensionExpression); } private object GetProjectionIndex(ProjectionBindingExpression projectionBindingExpression) { return projectionBindingExpression.ProjectionMember != null ? ((ConstantExpression)_innerSelectExpression.GetMappedProjection(projectionBindingExpression.ProjectionMember)).Value : (projectionBindingExpression.Index != null ? (object)projectionBindingExpression.Index : projectionBindingExpression.IndexMap); } } private SqlExpression ExtractJoinKey(SelectExpression selectExpression) { if (selectExpression.Predicate != null) { var joinPredicate = ExtractJoinKey(selectExpression, selectExpression.Predicate, out var predicate); selectExpression.Predicate = predicate; return joinPredicate; } return null; } private SqlExpression ExtractJoinKey(SelectExpression selectExpression, SqlExpression predicate, out SqlExpression updatedPredicate) { if (predicate is SqlBinaryExpression sqlBinaryExpression) { var joinPredicate = ValidateKeyComparison(selectExpression, sqlBinaryExpression); if (joinPredicate != null) { updatedPredicate = null; return joinPredicate; } if (sqlBinaryExpression.OperatorType == ExpressionType.AndAlso) { static SqlExpression combineNonNullExpressions(SqlExpression left, SqlExpression right) { return left != null ? right != null ? new SqlBinaryExpression(ExpressionType.AndAlso, left, right, left.Type, left.TypeMapping) : left : right; } var leftJoinKey = ExtractJoinKey(selectExpression, sqlBinaryExpression.Left, out var leftPredicate); var rightJoinKey = ExtractJoinKey(selectExpression, sqlBinaryExpression.Right, out var rightPredicate); updatedPredicate = combineNonNullExpressions(leftPredicate, rightPredicate); return combineNonNullExpressions(leftJoinKey, rightJoinKey); } } updatedPredicate = predicate; return null; } private SqlBinaryExpression ValidateKeyComparison(SelectExpression inner, SqlBinaryExpression sqlBinaryExpression) { if (sqlBinaryExpression.OperatorType == ExpressionType.Equal) { if (sqlBinaryExpression.Left is ColumnExpression leftColumn && sqlBinaryExpression.Right is ColumnExpression rightColumn) { if (ContainsTableReference(leftColumn.Table) && inner.ContainsTableReference(rightColumn.Table)) { inner.AddToProjection(rightColumn); return sqlBinaryExpression; } if (ContainsTableReference(rightColumn.Table) && inner.ContainsTableReference(leftColumn.Table)) { inner.AddToProjection(leftColumn); return sqlBinaryExpression.Update( sqlBinaryExpression.Right, sqlBinaryExpression.Left); } } } return null; } // We treat a set operation as a transparent wrapper over its left operand (the ColumnExpression projection mappings // found on a set operation SelectExpression are actually those of its left operand). private bool ContainsTableReference(TableExpressionBase table) => IsSetOperation ? ((SelectExpression)Tables[0]).ContainsTableReference(table) : Tables.Any(te => ReferenceEquals(te is JoinExpressionBase jeb ? jeb.Table : te, table)); public void AddInnerJoin(SelectExpression innerSelectExpression, SqlExpression joinPredicate, Type transparentIdentifierType) { if (Limit != null || Offset != null || IsDistinct || IsSetOperation || GroupBy.Count > 1) { joinPredicate = new SqlRemappingVisitor(PushdownIntoSubquery()) .Remap(joinPredicate); } // TODO: write a test which has distinct on outer so that we can verify pushdown if (innerSelectExpression.Orderings.Any() || innerSelectExpression.Limit != null || innerSelectExpression.Offset != null || innerSelectExpression.IsDistinct // TODO: Predicate can be lifted in inner join || innerSelectExpression.Predicate != null || innerSelectExpression.Tables.Count > 1 || innerSelectExpression.GroupBy.Count > 1) { joinPredicate = new SqlRemappingVisitor(innerSelectExpression.PushdownIntoSubquery()) .Remap(joinPredicate); } _identifier.AddRange(innerSelectExpression._identifier); var joinTable = new InnerJoinExpression(innerSelectExpression.Tables.Single(), joinPredicate); _tables.Add(joinTable); var outerMemberInfo = transparentIdentifierType.GetTypeInfo().GetDeclaredField("Outer"); var projectionMapping = new Dictionary<ProjectionMember, Expression>(); foreach (var projection in _projectionMapping) { projectionMapping[projection.Key.Prepend(outerMemberInfo)] = projection.Value; } var innerMemberInfo = transparentIdentifierType.GetTypeInfo().GetDeclaredField("Inner"); foreach (var projection in innerSelectExpression._projectionMapping) { projectionMapping[projection.Key.Prepend(innerMemberInfo)] = projection.Value; } _projectionMapping = projectionMapping; } public void AddLeftJoin(SelectExpression innerSelectExpression, SqlExpression joinPredicate, Type transparentIdentifierType) { if (Limit != null || Offset != null || IsDistinct || IsSetOperation || GroupBy.Count > 1) { joinPredicate = new SqlRemappingVisitor(PushdownIntoSubquery()) .Remap(joinPredicate); } if (innerSelectExpression.Orderings.Any() || innerSelectExpression.Limit != null || innerSelectExpression.Offset != null || innerSelectExpression.IsDistinct || innerSelectExpression.Predicate != null || innerSelectExpression.Tables.Count > 1 || innerSelectExpression.GroupBy.Count > 1) { joinPredicate = new SqlRemappingVisitor(innerSelectExpression.PushdownIntoSubquery()) .Remap(joinPredicate); } var joinTable = new LeftJoinExpression(innerSelectExpression.Tables.Single(), joinPredicate); _tables.Add(joinTable); if (transparentIdentifierType != null) { var outerMemberInfo = transparentIdentifierType.GetTypeInfo().GetDeclaredField("Outer"); var projectionMapping = new Dictionary<ProjectionMember, Expression>(); foreach (var projection in _projectionMapping) { projectionMapping[projection.Key.Prepend(outerMemberInfo)] = projection.Value; } var innerMemberInfo = transparentIdentifierType.GetTypeInfo().GetDeclaredField("Inner"); foreach (var projection in innerSelectExpression._projectionMapping) { var projectionToAdd = projection.Value; if (projectionToAdd is EntityProjectionExpression entityProjection) { projectionToAdd = entityProjection.MakeNullable(); } else if (projectionToAdd is ColumnExpression column) { projectionToAdd = column.MakeNullable(); } projectionMapping[projection.Key.Prepend(innerMemberInfo)] = projectionToAdd; } _projectionMapping = projectionMapping; } } public void AddCrossJoin(SelectExpression innerSelectExpression, Type transparentIdentifierType) { if (Limit != null || Offset != null || IsDistinct || Predicate != null || IsSetOperation || GroupBy.Count > 1) { PushdownIntoSubquery(); } if (innerSelectExpression.Orderings.Any() || innerSelectExpression.Limit != null || innerSelectExpression.Offset != null || innerSelectExpression.IsDistinct || innerSelectExpression.Predicate != null || innerSelectExpression.Tables.Count > 1 || innerSelectExpression.GroupBy.Count > 1) { innerSelectExpression.PushdownIntoSubquery(); } _identifier.AddRange(innerSelectExpression._identifier); var joinTable = new CrossJoinExpression(innerSelectExpression.Tables.Single()); _tables.Add(joinTable); var outerMemberInfo = transparentIdentifierType.GetTypeInfo().GetDeclaredField("Outer"); var projectionMapping = new Dictionary<ProjectionMember, Expression>(); foreach (var projection in _projectionMapping) { projectionMapping[projection.Key.Prepend(outerMemberInfo)] = projection.Value; } var innerMemberInfo = transparentIdentifierType.GetTypeInfo().GetDeclaredField("Inner"); foreach (var projection in innerSelectExpression._projectionMapping) { projectionMapping[projection.Key.Prepend(innerMemberInfo)] = projection.Value; } _projectionMapping = projectionMapping; } private class SqlRemappingVisitor : ExpressionVisitor { private readonly IDictionary<SqlExpression, ColumnExpression> _mappings; public SqlRemappingVisitor(IDictionary<SqlExpression, ColumnExpression> mappings) { _mappings = mappings; } public SqlExpression Remap(SqlExpression sqlExpression) => (SqlExpression)Visit(sqlExpression); public SelectExpression Remap(SelectExpression sqlExpression) => (SelectExpression)Visit(sqlExpression); public override Expression Visit(Expression expression) { if (expression is SqlExpression sqlExpression && _mappings.TryGetValue(sqlExpression, out var outer)) { return outer; } return base.Visit(expression); } } protected override Expression VisitChildren(ExpressionVisitor visitor) { // We have to do in-place mutation till we have applied pending collections because of shaper references // This is pseudo finalization phase for select expression. if (_pendingCollections.Any(e => e != null)) { if (Projection.Any()) { var projections = _projection.ToList(); _projection.Clear(); _projection.AddRange(projections.Select(e => (ProjectionExpression)visitor.Visit(e))); } else { var projectionMapping = new Dictionary<ProjectionMember, Expression>(); foreach (var mapping in _projectionMapping) { var newProjection = visitor.Visit(mapping.Value); projectionMapping[mapping.Key] = newProjection; } _projectionMapping = projectionMapping; } var tables = _tables.ToList(); _tables.Clear(); _tables.AddRange(tables.Select(e => (TableExpressionBase)visitor.Visit(e))); Predicate = (SqlExpression)visitor.Visit(Predicate); var groupBy = _groupBy.ToList(); _groupBy.Clear(); _groupBy.AddRange(GroupBy.Select(e => (SqlExpression)visitor.Visit(e))); Having = (SqlExpression)visitor.Visit(Having); var orderings = _orderings.ToList(); _orderings.Clear(); _orderings.AddRange(orderings.Select(e => e.Update((SqlExpression)visitor.Visit(e.Expression)))); Offset = (SqlExpression)visitor.Visit(Offset); Limit = (SqlExpression)visitor.Visit(Limit); return this; } else { var changed = false; var projections = new List<ProjectionExpression>(); IDictionary<ProjectionMember, Expression> projectionMapping; if (Projection.Any()) { projectionMapping = _projectionMapping; foreach (var item in Projection) { var projection = (ProjectionExpression)visitor.Visit(item); projections.Add(projection); changed |= projection != item; } } else { projectionMapping = new Dictionary<ProjectionMember, Expression>(); foreach (var mapping in _projectionMapping) { var newProjection = visitor.Visit(mapping.Value); changed |= newProjection != mapping.Value; projectionMapping[mapping.Key] = newProjection; } } var tables = new List<TableExpressionBase>(); foreach (var table in _tables) { var newTable = (TableExpressionBase)visitor.Visit(table); changed |= newTable != table; tables.Add(newTable); } var predicate = (SqlExpression)visitor.Visit(Predicate); changed |= predicate != Predicate; var groupBy = new List<SqlExpression>(); foreach (var groupingKey in _groupBy) { var newGroupingKey = (SqlExpression)visitor.Visit(groupingKey); changed |= newGroupingKey != groupingKey; groupBy.Add(newGroupingKey); } var havingExpression = (SqlExpression)visitor.Visit(Having); changed |= havingExpression != Having; var orderings = new List<OrderingExpression>(); foreach (var ordering in _orderings) { var orderingExpression = (SqlExpression)visitor.Visit(ordering.Expression); changed |= orderingExpression != ordering.Expression; orderings.Add(ordering.Update(orderingExpression)); } var offset = (SqlExpression)visitor.Visit(Offset); changed |= offset != Offset; var limit = (SqlExpression)visitor.Visit(Limit); changed |= limit != Limit; if (changed) { var newSelectExpression = new SelectExpression(Alias, projections, tables, groupBy, orderings) { _projectionMapping = projectionMapping, Predicate = predicate, Having = havingExpression, Offset = offset, Limit = limit, IsDistinct = IsDistinct, SetOperationType = SetOperationType }; newSelectExpression._identifier.AddRange(_identifier); newSelectExpression._identifier.AddRange(_childIdentifiers); return newSelectExpression; } return this; } } public override bool Equals(object obj) => obj != null && (ReferenceEquals(this, obj) || obj is SelectExpression selectExpression && Equals(selectExpression)); private bool Equals(SelectExpression selectExpression) { if (!base.Equals(selectExpression)) { return false; } if (SetOperationType != selectExpression.SetOperationType) { return false; } if (_projectionMapping.Count != selectExpression._projectionMapping.Count) { return false; } foreach (var projectionMapping in _projectionMapping) { if (!selectExpression._projectionMapping.TryGetValue(projectionMapping.Key, out var projection)) { return false; } if (!projectionMapping.Value.Equals(projection)) { return false; } } if (!_tables.SequenceEqual(selectExpression._tables)) { return false; } if (!(Predicate == null && selectExpression.Predicate == null || Predicate != null && Predicate.Equals(selectExpression.Predicate))) { return false; } if (!_pendingCollections.SequenceEqual(selectExpression._pendingCollections)) { return false; } if (!_groupBy.SequenceEqual(selectExpression._groupBy)) { return false; } if (!(Having == null && selectExpression.Having == null || Having != null && Predicate.Equals(selectExpression.Having))) { return false; } if (!_orderings.SequenceEqual(selectExpression._orderings)) { return false; } if (!(Offset == null && selectExpression.Offset == null || Offset != null && Offset.Equals(selectExpression.Offset))) { return false; } if (!(Limit == null && selectExpression.Limit == null || Limit != null && Limit.Equals(selectExpression.Limit))) { return false; } return IsDistinct == selectExpression.IsDistinct; } // This does not take internal states since when using this method SelectExpression should be finalized public SelectExpression Update( List<ProjectionExpression> projections, List<TableExpressionBase> tables, SqlExpression predicate, List<SqlExpression> groupBy, SqlExpression havingExpression, List<OrderingExpression> orderings, SqlExpression limit, SqlExpression offset, bool distinct, string alias) { var projectionMapping = new Dictionary<ProjectionMember, Expression>(); foreach (var kvp in _projectionMapping) { projectionMapping[kvp.Key] = kvp.Value; } return new SelectExpression(alias, projections, tables, groupBy, orderings) { _projectionMapping = projectionMapping, Predicate = predicate, Having = havingExpression, Offset = offset, Limit = limit, IsDistinct = distinct, SetOperationType = SetOperationType }; } public override int GetHashCode() { var hash = new HashCode(); hash.Add(base.GetHashCode()); hash.Add(SetOperationType); foreach (var projectionMapping in _projectionMapping) { hash.Add(projectionMapping.Key); hash.Add(projectionMapping.Value); } foreach (var table in _tables) { hash.Add(table); } hash.Add(Predicate); foreach (var groupingKey in _groupBy) { hash.Add(groupingKey); } hash.Add(Having); foreach (var ordering in _orderings) { hash.Add(ordering); } hash.Add(Offset); hash.Add(Limit); hash.Add(IsDistinct); return hash.ToHashCode(); } public override void Print(ExpressionPrinter expressionPrinter) { expressionPrinter.StringBuilder.AppendLine("Projection Mapping:"); using (expressionPrinter.StringBuilder.Indent()) { foreach (var projectionMappingEntry in _projectionMapping) { expressionPrinter.StringBuilder.AppendLine(); expressionPrinter.StringBuilder.Append(projectionMappingEntry.Key + " -> "); expressionPrinter.Visit(projectionMappingEntry.Value); } } expressionPrinter.StringBuilder.AppendLine(); if (IsSetOperation) { expressionPrinter.Visit(Tables[0]); expressionPrinter.StringBuilder .AppendLine() .AppendLine(SetOperationType.ToString().ToUpperInvariant()); expressionPrinter.Visit(Tables[1]); } else { if (Alias != null) { expressionPrinter.StringBuilder.AppendLine("("); expressionPrinter.StringBuilder.IncrementIndent(); } expressionPrinter.StringBuilder.Append("SELECT "); if (IsDistinct) { expressionPrinter.StringBuilder.Append("DISTINCT "); } if (Limit != null && Offset == null) { expressionPrinter.StringBuilder.Append("TOP("); expressionPrinter.Visit(Limit); expressionPrinter.StringBuilder.Append(") "); } if (Projection.Any()) { expressionPrinter.VisitList(Projection); } else { expressionPrinter.StringBuilder.Append("1"); } if (Tables.Any()) { expressionPrinter.StringBuilder.AppendLine().Append("FROM "); expressionPrinter.VisitList(Tables, p => p.StringBuilder.AppendLine()); } if (Predicate != null) { expressionPrinter.StringBuilder.AppendLine().Append("WHERE "); expressionPrinter.Visit(Predicate); } if (GroupBy.Any()) { expressionPrinter.StringBuilder.AppendLine().Append("GROUP BY "); expressionPrinter.VisitList(GroupBy); } if (Having != null) { expressionPrinter.StringBuilder.AppendLine().Append("HAVING "); expressionPrinter.Visit(Having); } } if (Orderings.Any()) { expressionPrinter.StringBuilder.AppendLine().Append("ORDER BY "); expressionPrinter.VisitList(Orderings); } else if (Offset != null) { expressionPrinter.StringBuilder.AppendLine().Append("ORDER BY (SELECT 1)"); } if (Offset != null) { expressionPrinter.StringBuilder.AppendLine().Append("OFFSET "); expressionPrinter.Visit(Offset); expressionPrinter.StringBuilder.Append(" ROWS"); if (Limit != null) { expressionPrinter.StringBuilder.Append(" FETCH NEXT "); expressionPrinter.Visit(Limit); expressionPrinter.StringBuilder.Append(" ROWS ONLY"); } } if (Alias != null) { expressionPrinter.StringBuilder.DecrementIndent(); expressionPrinter.StringBuilder.AppendLine().Append(") AS " + Alias); } } } /// <summary> /// Marks a <see cref="SelectExpression"/> as representing an SQL set operation, such as a UNION. /// </summary> public enum SetOperationType { /// <summary> /// Represents a regular SQL SELECT expression that isn't a set operation. /// </summary> None = 0, /// <summary> /// Represents an SQL UNION set operation. /// </summary> Union = 1, /// <summary> /// Represents an SQL UNION ALL set operation. /// </summary> UnionAll = 2, /// <summary> /// Represents an SQL INTERSECT set operation. /// </summary> Intersect = 3, /// <summary> /// Represents an SQL EXCEPT set operation. /// </summary> Except = 4 } }
39.843519
188
0.553273
[ "Apache-2.0" ]
garfbradaz/EntityFrameworkCore
src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs
59,329
C#
using System.Threading.Tasks; using DataTables.Blazored.Models; using BlazorServer.Interfaces; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace BlazorServer.Controllers { [AllowAnonymous] [Route("api/[controller]")] [ApiController] public class EmployeeController : Controller { private readonly IEmployeeRepository _employeeRepository; public EmployeeController(IEmployeeRepository employeeRepository) { _employeeRepository = employeeRepository; } [HttpPost("Data")] public async Task<IActionResult> Data([FromBody] TableRequestViewModel model) { var data = await _employeeRepository.GetDataAsync<object>(model, s => new { s.Id, s.FirstName, s.LastName, s.Office, s.Position, s.StartDate, s.Salary }); return new JsonResult(data); } } }
27.289474
85
0.603664
[ "MIT" ]
ennerperez/Blazored-Table
samples/BlazorServer/Controllers/EmployeeController.cs
1,039
C#
using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Abp.Authorization; using Abp.Authorization.Users; using Abp.MultiTenancy; using Abp.Runtime.Security; using Abp.UI; using RandomNumbersAngular.Authentication.External; using RandomNumbersAngular.Authentication.JwtBearer; using RandomNumbersAngular.Authorization; using RandomNumbersAngular.Authorization.Users; using RandomNumbersAngular.Models.TokenAuth; using RandomNumbersAngular.MultiTenancy; namespace RandomNumbersAngular.Controllers { [Route("api/[controller]/[action]")] public class TokenAuthController : RandomNumbersAngularControllerBase { private readonly LogInManager _logInManager; private readonly ITenantCache _tenantCache; private readonly AbpLoginResultTypeHelper _abpLoginResultTypeHelper; private readonly TokenAuthConfiguration _configuration; private readonly IExternalAuthConfiguration _externalAuthConfiguration; private readonly IExternalAuthManager _externalAuthManager; private readonly UserRegistrationManager _userRegistrationManager; public TokenAuthController( LogInManager logInManager, ITenantCache tenantCache, AbpLoginResultTypeHelper abpLoginResultTypeHelper, TokenAuthConfiguration configuration, IExternalAuthConfiguration externalAuthConfiguration, IExternalAuthManager externalAuthManager, UserRegistrationManager userRegistrationManager) { _logInManager = logInManager; _tenantCache = tenantCache; _abpLoginResultTypeHelper = abpLoginResultTypeHelper; _configuration = configuration; _externalAuthConfiguration = externalAuthConfiguration; _externalAuthManager = externalAuthManager; _userRegistrationManager = userRegistrationManager; } [HttpPost] public async Task<AuthenticateResultModel> Authenticate([FromBody] AuthenticateModel model) { var loginResult = await GetLoginResultAsync( model.UserNameOrEmailAddress, model.Password, GetTenancyNameOrNull() ); var accessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity)); return new AuthenticateResultModel { AccessToken = accessToken, EncryptedAccessToken = GetEncryptedAccessToken(accessToken), ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds, UserId = loginResult.User.Id }; } [HttpGet] public List<ExternalLoginProviderInfoModel> GetExternalAuthenticationProviders() { return ObjectMapper.Map<List<ExternalLoginProviderInfoModel>>(_externalAuthConfiguration.Providers); } [HttpPost] public async Task<ExternalAuthenticateResultModel> ExternalAuthenticate([FromBody] ExternalAuthenticateModel model) { var externalUser = await GetExternalUserInfo(model); var loginResult = await _logInManager.LoginAsync(new UserLoginInfo(model.AuthProvider, model.ProviderKey, model.AuthProvider), GetTenancyNameOrNull()); switch (loginResult.Result) { case AbpLoginResultType.Success: { var accessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity)); return new ExternalAuthenticateResultModel { AccessToken = accessToken, EncryptedAccessToken = GetEncryptedAccessToken(accessToken), ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds }; } case AbpLoginResultType.UnknownExternalLogin: { var newUser = await RegisterExternalUserAsync(externalUser); if (!newUser.IsActive) { return new ExternalAuthenticateResultModel { WaitingForActivation = true }; } // Try to login again with newly registered user! loginResult = await _logInManager.LoginAsync(new UserLoginInfo(model.AuthProvider, model.ProviderKey, model.AuthProvider), GetTenancyNameOrNull()); if (loginResult.Result != AbpLoginResultType.Success) { throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt( loginResult.Result, model.ProviderKey, GetTenancyNameOrNull() ); } return new ExternalAuthenticateResultModel { AccessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity)), ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds }; } default: { throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt( loginResult.Result, model.ProviderKey, GetTenancyNameOrNull() ); } } } private async Task<User> RegisterExternalUserAsync(ExternalAuthUserInfo externalUser) { var user = await _userRegistrationManager.RegisterAsync( externalUser.Name, externalUser.Surname, externalUser.EmailAddress, externalUser.EmailAddress, Authorization.Users.User.CreateRandomPassword(), true ); user.Logins = new List<UserLogin> { new UserLogin { LoginProvider = externalUser.Provider, ProviderKey = externalUser.ProviderKey, TenantId = user.TenantId } }; await CurrentUnitOfWork.SaveChangesAsync(); return user; } private async Task<ExternalAuthUserInfo> GetExternalUserInfo(ExternalAuthenticateModel model) { var userInfo = await _externalAuthManager.GetUserInfo(model.AuthProvider, model.ProviderAccessCode); if (userInfo.ProviderKey != model.ProviderKey) { throw new UserFriendlyException(L("CouldNotValidateExternalUser")); } return userInfo; } private string GetTenancyNameOrNull() { if (!AbpSession.TenantId.HasValue) { return null; } return _tenantCache.GetOrNull(AbpSession.TenantId.Value)?.TenancyName; } private async Task<AbpLoginResult<Tenant, User>> GetLoginResultAsync(string usernameOrEmailAddress, string password, string tenancyName) { var loginResult = await _logInManager.LoginAsync(usernameOrEmailAddress, password, tenancyName); switch (loginResult.Result) { case AbpLoginResultType.Success: return loginResult; default: throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt(loginResult.Result, usernameOrEmailAddress, tenancyName); } } private string CreateAccessToken(IEnumerable<Claim> claims, TimeSpan? expiration = null) { var now = DateTime.UtcNow; var jwtSecurityToken = new JwtSecurityToken( issuer: _configuration.Issuer, audience: _configuration.Audience, claims: claims, notBefore: now, expires: now.Add(expiration ?? _configuration.Expiration), signingCredentials: _configuration.SigningCredentials ); return new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken); } private static List<Claim> CreateJwtClaims(ClaimsIdentity identity) { var claims = identity.Claims.ToList(); var nameIdClaim = claims.First(c => c.Type == ClaimTypes.NameIdentifier); // Specifically add the jti (random nonce), iat (issued timestamp), and sub (subject/user) claims. claims.AddRange(new[] { new Claim(JwtRegisteredClaimNames.Sub, nameIdClaim.Value), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.Now.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64) }); return claims; } private string GetEncryptedAccessToken(string accessToken) { return SimpleStringCipher.Instance.Encrypt(accessToken, AppConsts.DefaultPassPhrase); } } }
40.752137
171
0.602664
[ "MIT" ]
nesumtoj/RandomNumbersJS
aspnet-core/src/RandomNumbersAngular.Web.Core/Controllers/TokenAuthController.cs
9,538
C#
using System.IO; using System.Xml.Linq; using FluentBuild.BuildFileConverter.Parsing; using FluentBuild.BuildFileConverter.Structure; namespace FluentBuild.BuildFileConverter { public class ConvertFile { private readonly string _pathToNantFile; private readonly string _pathToOutputFile; public ConvertFile(string pathToNantFile, string pathToOutputFile) { _pathToNantFile = pathToNantFile; _pathToOutputFile = pathToOutputFile; } public void Generate() { var parser = new NantBuildFileParser(); var mainDocument = XDocument.Load(_pathToNantFile); var rootDir = Path.GetDirectoryName(_pathToNantFile); foreach(var includes in mainDocument.Root.Elements("include")) { var xdocToInclude = XDocument.Load(rootDir + "\\" + includes.Attribute("buildfile").Value); foreach (var includeElement in xdocToInclude.Root.Elements()) { mainDocument.Root.AddFirst(includeElement); } } BuildProject buildProject = parser.ParseDocument(mainDocument); var outputGenerator = new OutputGenerator(buildProject); string output = outputGenerator.CreateOutput(); using (var fs = new StreamWriter(_pathToOutputFile + "\\default.cs")) { fs.Write(output); } } } }
34.581395
107
0.618695
[ "Apache-2.0" ]
GotWoods/Fluent-Build
src/FluentBuild.BuildFileConverter/ConvertFile.cs
1,489
C#
using UnityEngine; using System.Collections; using VRTK; public class Controller_Menu : MonoBehaviour { public GameObject menuObject; private GameObject clonedMenuObject; private bool menuInit = false; private bool menuActive = false; private void Start() { GetComponent<VRTK_ControllerEvents>().AliasMenuOn += new ControllerInteractionEventHandler(DoMenuOn); GetComponent<VRTK_ControllerEvents>().AliasMenuOff += new ControllerInteractionEventHandler(DoMenuOff); menuInit = false; menuActive = false; } private void InitMenu() { clonedMenuObject = Instantiate(menuObject, this.transform.position, Quaternion.identity) as GameObject; clonedMenuObject.SetActive(true); menuInit = true; } private void DoMenuOn(object sender, ControllerInteractionEventArgs e) { if (!menuInit) { InitMenu(); } clonedMenuObject.SetActive(true); menuActive = true; } private void DoMenuOff(object sender, ControllerInteractionEventArgs e) { clonedMenuObject.SetActive(false); menuActive = false; } private void Update() { if (menuActive) { clonedMenuObject.transform.rotation = this.transform.rotation; clonedMenuObject.transform.position = this.transform.position; } } }
26.54717
111
0.663113
[ "MIT" ]
Liquidream/misc
tachyonVR/Assets/SteamVR_Unity_Toolkit/Examples/Resources/Scripts/Controller_Menu.cs
1,409
C#
// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. // ---------------------------------------------------------------------------- namespace AppOwnsData.Models { using System; public class EmbedReport { // Id of Power BI report to be embedded public Guid ReportId { get; set; } // Name of the report public string ReportName { get; set; } // Embed URL for the Power BI report public string EmbedUrl { get; set; } } }
26.772727
79
0.448217
[ "MIT" ]
AdamRiddick/PowerBI-Developer-Samples
.NET Core/Embed for your customers/AppOwnsData/Models/EmbedReport.cs
589
C#
/* * Copyright (c) 2016 Billy Wolfington * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * https://github.com/Bwolfing/Bootstrap.AspNetCore.Mvc.TagHelpers * */ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.TagHelpers; namespace Bootstrap.AspNetCore.Mvc.TagHelpers { public enum TableRowVariation { Normal, Active, Success, Info, Warning, Danger, } [HtmlTargetElement("tr", Attributes = VARIATION_ATTRIBUTE_NAME, ParentTag = Table.TAG)] [HtmlTargetElement("th", Attributes = VARIATION_ATTRIBUTE_NAME, ParentTag = "tr")] [HtmlTargetElement("td", Attributes = VARIATION_ATTRIBUTE_NAME, ParentTag = "tr")] public class TableChildren : BootstrapTagHelperBase { #region Properties #region Public Properties public const string VARIATION_ATTRIBUTE_NAME = Global.PREFIX + "variation"; [HtmlAttributeNotBound] public override string CssClass { get { switch (RowVariation) { case TableRowVariation.Active: case TableRowVariation.Danger: case TableRowVariation.Info: case TableRowVariation.Success: case TableRowVariation.Warning: return $"{RowVariation.ToString().ToLower()}"; case TableRowVariation.Normal: default: return ""; } } } [HtmlAttributeName(VARIATION_ATTRIBUTE_NAME)] public TableRowVariation RowVariation { get; set; } [HtmlAttributeNotBound] public override string OutputTag { get; set; } #endregion #endregion #region Methods #region Public Methods public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { var content = await output.GetChildContentAsync(); output.Content.SetHtmlContent(content); AppendDefaultCssClass(output); } #endregion #endregion } }
29.794872
97
0.606282
[ "MIT" ]
Bwolfing/Bootstrap.AspNetCore.Mvc.TagHelpers
src/Bootstrap.AspNetCore.Mvc.TagHelpers/TableChildren.cs
2,324
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; using System.Collections.Generic; using System.Diagnostics; using Internal.TypeSystem; using ILCompiler; using ILCompiler.Compiler.CppCodeGen; using ILCompiler.CppCodeGen; using ILCompiler.DependencyAnalysis; namespace Internal.IL { internal partial class ILImporter { /// <summary> /// Stack of values pushed onto the IL stack: locals, arguments, values, function pointer, ... /// </summary> private EvaluationStack<StackEntry> _stack = new EvaluationStack<StackEntry>(0); private Compilation _compilation; private NodeFactory _nodeFactory; private CppWriter _writer; private TypeSystemContext _typeSystemContext; private MethodDesc _method; private MethodSignature _methodSignature; private TypeDesc _thisType; private MethodIL _methodIL; private byte[] _ilBytes; private LocalVariableDefinition[] _locals; private struct SequencePoint { public string Document; public int LineNumber; } private SequencePoint[] _sequencePoints; private Dictionary<int, ILLocalVariable> _localSlotToInfoMap; private Dictionary<int, string> _parameterIndexToNameMap; private class ExceptionRegion { public ILExceptionRegion ILRegion; public int ReturnLabels; }; private ExceptionRegion[] _exceptionRegions; private class SpillSlot { public StackValueKind Kind; public TypeDesc Type; public String Name; }; private List<SpillSlot> _spillSlots; // TODO: Unify with verifier? [Flags] private enum Prefix { ReadOnly = 0x01, Unaligned = 0x02, Volatile = 0x04, Tail = 0x08, Constrained = 0x10, No = 0x20, } private Prefix _pendingPrefix; private TypeDesc _constrained; private CppGenerationBuffer _builder = new CppGenerationBuffer(); private ArrayBuilder<object> _dependencies = new ArrayBuilder<object>(); private class BasicBlock { // Common fields public BasicBlock Next; public int StartOffset; public int EndOffset; public EvaluationStack<StackEntry> EntryStack; public bool TryStart; public bool FilterStart; public bool HandlerStart; // Custom fields public string Code; }; public ILImporter(Compilation compilation, CppWriter writer, MethodDesc method, MethodIL methodIL) { _compilation = compilation; _nodeFactory = _compilation.NodeFactory; _writer = writer; _method = method; _methodSignature = method.Signature; _typeSystemContext = method.Context; if (!_methodSignature.IsStatic) _thisType = method.OwningType; _methodIL = methodIL; _ilBytes = _methodIL.GetILBytes(); _locals = _methodIL.GetLocals(); var ilExceptionRegions = _methodIL.GetExceptionRegions(); _exceptionRegions = new ExceptionRegion[ilExceptionRegions.Length]; for (int i = 0; i < ilExceptionRegions.Length; i++) { _exceptionRegions[i] = new ExceptionRegion() { ILRegion = ilExceptionRegions[i] }; } } public void SetSequencePoints(IEnumerable<ILSequencePoint> ilSequencePoints) { try { SequencePoint[] sequencePoints = new SequencePoint[_ilBytes.Length]; foreach (var point in ilSequencePoints) { sequencePoints[point.Offset] = new SequencePoint() { Document = point.Document, LineNumber = point.LineNumber }; } _sequencePoints = sequencePoints; } catch { } } public void SetLocalVariables(IEnumerable<ILLocalVariable> localVariables) { try { HashSet<string> names = new HashSet<string>(); var localSlotToInfoMap = new Dictionary<int, ILLocalVariable>(); foreach (var v in localVariables) { string sanitizedName = _compilation.NameMangler.SanitizeName(v.Name); if (!names.Add(v.Name)) { sanitizedName = string.Format("{0}_local{1}", v.Name, v.Slot); names.Add(sanitizedName); } localSlotToInfoMap[v.Slot] = new ILLocalVariable(v.Slot, sanitizedName, v.CompilerGenerated); } _localSlotToInfoMap = localSlotToInfoMap; } catch { // oops, couldn't get local variables } } public void SetParameterNames(IEnumerable<string> parameters) { var parameterIndexToNameMap = new Dictionary<int, string>(); int index = 0; foreach (var p in parameters) { parameterIndexToNameMap[index] = p; ++index; } _parameterIndexToNameMap = parameterIndexToNameMap; } private StackValueKind GetStackValueKind(TypeDesc type) { switch (type.Category) { case TypeFlags.Boolean: case TypeFlags.Char: case TypeFlags.SByte: case TypeFlags.Byte: case TypeFlags.Int16: case TypeFlags.UInt16: case TypeFlags.Int32: case TypeFlags.UInt32: return StackValueKind.Int32; case TypeFlags.Int64: case TypeFlags.UInt64: return StackValueKind.Int64; case TypeFlags.Single: case TypeFlags.Double: return StackValueKind.Float; case TypeFlags.IntPtr: case TypeFlags.UIntPtr: return StackValueKind.NativeInt; case TypeFlags.ValueType: case TypeFlags.Nullable: return StackValueKind.ValueType; case TypeFlags.Enum: return GetStackValueKind(type.UnderlyingType); case TypeFlags.Class: case TypeFlags.Interface: case TypeFlags.Array: case TypeFlags.SzArray: return StackValueKind.ObjRef; case TypeFlags.ByRef: return StackValueKind.ByRef; case TypeFlags.Pointer: return StackValueKind.NativeInt; default: return StackValueKind.Unknown; } } private string GetStackValueKindCPPTypeName(StackValueKind kind, TypeDesc type = null) { switch (kind) { case StackValueKind.Int32: return "int32_t"; case StackValueKind.Int64: return "int64_t"; case StackValueKind.NativeInt: return "intptr_t"; case StackValueKind.ObjRef: return "void*"; case StackValueKind.Float: return "double"; case StackValueKind.ByRef: case StackValueKind.ValueType: return _writer.GetCppSignatureTypeName(type); default: throw new NotSupportedException(); } } private int _currentTemp = 1; private string NewTempName() { return "_" + (_currentTemp++).ToStringInvariant(); } /// <summary> /// Push an expression named <paramref name="name"/> of kind <paramref name="kind"/>. /// </summary> /// <param name="kind">Kind of entry in stack</param> /// <param name="name">Variable to be pushed</param> /// <param name="type">Type if any of <paramref name="name"/></param> private void PushExpression(StackValueKind kind, string name, TypeDesc type = null) { Debug.Assert(kind != StackValueKind.Unknown, "Unknown stack kind"); _stack.Push(new ExpressionEntry(kind, name, type)); } /// <summary> /// Push a new temporary local of kind <paramref name="kind"/> and type <paramref name="type"/> and generate its declaration. /// </summary> /// <param name="kind">Kind of entry in stack</param> /// <param name="type">Type if any for new entry in stack</param> private void PushTemp(StackValueKind kind, TypeDesc type = null) { Debug.Assert(kind != StackValueKind.Unknown, "Unknown stack kind"); PushTemp(new ExpressionEntry(kind, NewTempName(), type)); } /// <summary> /// Push a new entry onto evaluation stack and declare a temporary local to hold its representation. /// </summary> /// <param name="entry">Entry to push onto evaluation stack.</param> private void PushTemp(StackEntry entry) { _stack.Push(entry); // Start declaration on a new line AppendLine(); Append(GetStackValueKindCPPTypeName(entry.Kind, entry.Type)); Append(" "); Append(entry); Append(" = "); } /// <summary> /// Generate a cast in case the stack type of source is not identical or compatible with destination type. /// </summary> /// <param name="destType">Type of destination</param> /// <param name="srcEntry">Source entry from stack</param> private void AppendCastIfNecessary(TypeDesc destType, StackEntry srcEntry) { ConstantEntry constant = srcEntry as ConstantEntry; if ((constant != null) && (constant.IsCastNecessary(destType)) || !destType.IsValueType) { Append("("); Append(_writer.GetCppSignatureTypeName(destType)); Append(")"); } } private void AppendCastIfNecessary(StackValueKind dstType, TypeDesc srcType) { if (dstType == StackValueKind.ByRef) { Append("("); Append(_writer.GetCppSignatureTypeName(srcType)); Append(")"); } else if (srcType.IsPointer) { Append("(intptr_t)"); } } private StackEntry NewSpillSlot(StackEntry entry) { if (_spillSlots == null) _spillSlots = new List<SpillSlot>(); SpillSlot spillSlot = new SpillSlot(); spillSlot.Kind = entry.Kind; spillSlot.Type = entry.Type; spillSlot.Name = "_s" + _spillSlots.Count.ToStringInvariant(); _spillSlots.Add(spillSlot); return new ExpressionEntry(entry.Kind, spillSlot.Name, entry.Type); } /// <summary> /// If no sequence points are available, append an empty new line into /// <see cref="_builder"/> and the required number of tabs. Otherwise does nothing. /// </summary> private void AppendLine() { if (_sequencePoints != null) return; _builder.AppendLine(); } /// <summary> /// If no sequence points are available, append an empty new line into /// <see cref="_builder"/> without emitting any indentation. Otherwise does nothing. /// Useful to just skip a line. /// </summary> private void AppendEmptyLine() { if (_sequencePoints != null) return; _builder.AppendEmptyLine(); } /// <summary> /// Append an empty new line into <see cref="_builder"/> without emitting any indentation. /// Useful to just skip a line. /// </summary> private void ForceAppendEmptyLine() { _builder.AppendEmptyLine(); } /// <summary> /// Append string <param name="s"/> to <see cref="_builder"/>. /// </summary> /// <param name="s">String value to print.</param> private void Append(string s) { _builder.Append(s); } /// <summary> /// Append string representation of <paramref name="value"/> to <see cref="_builder"/>. /// </summary> /// <param name="value">Value to print.</param> private void Append(StackEntry value) { value.Append(_builder); } /// <summary> /// Append a semicolon to <see cref="_builder"/>. /// </summary> private void AppendSemicolon() { _builder.Append(";"); } /// <summary> /// Increase level of indentation by one in <see cref="_builder"/>. /// </summary> public void Indent() { _builder.Indent(); } /// <summary> /// Decrease level of indentation by one in <see cref="_builder"/>. /// </summary> private void Exdent() { _builder.Exdent(); } private string GetVarName(int index, bool argument) { if (_localSlotToInfoMap != null && !argument && _localSlotToInfoMap.ContainsKey(index) && !_localSlotToInfoMap[index].CompilerGenerated) { return _localSlotToInfoMap[index].Name; } if (_parameterIndexToNameMap != null && argument && _parameterIndexToNameMap.ContainsKey(index)) { return _writer.SanitizeCppVarName(_parameterIndexToNameMap[index]); } return (argument ? "_a" : "_l") + index.ToStringInvariant(); } private TypeDesc GetVarType(int index, bool argument) { if (argument) { if (_thisType != null) index--; if (index == -1) { if (_thisType.IsValueType) return _thisType.MakeByRefType(); return _thisType; } else return _methodSignature[index]; } else { return _locals[index].Type; } } private TypeDesc GetWellKnownType(WellKnownType wellKnownType) { return _typeSystemContext.GetWellKnownType(wellKnownType); } private TypeDesc ResolveTypeToken(int token) { return (TypeDesc)_methodIL.GetObject(token); } private void MarkInstructionBoundary() { } private void StartImportingInstruction() { if (_sequencePoints == null) return; var sequencePoint = _sequencePoints[_currentOffset]; if (sequencePoint.Document == null) return; ForceAppendEmptyLine(); Append("#line "); Append(sequencePoint.LineNumber.ToStringInvariant()); Append(" \""); Append(sequencePoint.Document.Replace("\\", "\\\\")); Append("\""); ForceAppendEmptyLine(); } private void EndImportingInstruction() { // Nothing to do, formatting is properly done. } public void Compile(CppMethodCodeNode methodCodeNodeNeedingCode) { FindBasicBlocks(); ImportBasicBlocks(); if (_sequencePoints != null && _sequencePoints[0].Document != null) { var sequencePoint = _sequencePoints[0]; ForceAppendEmptyLine(); Append("#line "); Append(sequencePoint.LineNumber.ToStringInvariant()); Append(" \""); Append(sequencePoint.Document.Replace("\\", "\\\\")); Append("\""); } ForceAppendEmptyLine(); Append(_writer.GetCppMethodDeclaration(_method, true)); AppendLine(); Append("{"); Indent(); bool initLocals = _methodIL.IsInitLocals; for (int i = 0; i < _locals.Length; i++) { AppendLine(); Append(_writer.GetCppSignatureTypeName(_locals[i].Type)); Append(" "); Append(GetVarName(i, false)); if (initLocals) { TypeDesc localType = _locals[i].Type; if (localType.IsValueType && !localType.IsPrimitive && !localType.IsEnum) { AppendSemicolon(); AppendLine(); Append("memset(&"); Append(GetVarName(i, false)); Append(",0,sizeof("); Append(_writer.GetCppSignatureTypeName(localType)); Append("))"); } else { Append(" = 0"); } } AppendSemicolon(); } if (_spillSlots != null) { for (int i = 0; i < _spillSlots.Count; i++) { SpillSlot spillSlot = _spillSlots[i]; AppendLine(); Append(GetStackValueKindCPPTypeName(spillSlot.Kind, spillSlot.Type)); Append(" "); Append(spillSlot.Name); AppendSemicolon(); } } for (int i = 0; i < _exceptionRegions.Length; i++) { var r = _exceptionRegions[i]; if (r.ReturnLabels != 0) { AppendLine(); Append("int __finallyReturn"); Append(i.ToStringInvariant()); Append(" = 0"); AppendSemicolon(); } } // Temporary the indentation while printing blocks. // We want block to start on the first character of the line Exdent(); for (int i = 0; i < _basicBlocks.Length; i++) { BasicBlock basicBlock = _basicBlocks[i]; if (basicBlock != null) { AppendEmptyLine(); AppendLine(); Append("_bb"); Append(i.ToStringInvariant()); Append(": {"); ForceAppendEmptyLine(); Append(basicBlock.Code); AppendLine(); Append("}"); } } for (int i = 0; i < _exceptionRegions.Length; i++) { var r = _exceptionRegions[i]; if (r.ReturnLabels != 0) { AppendEmptyLine(); AppendLine(); Append("__endFinally" + i.ToStringInvariant() + ":"); Indent(); AppendLine(); Append("switch(__finallyReturn" + i.ToStringInvariant() + ") {"); Indent(); for (int j = 1; j <= r.ReturnLabels; j++) { AppendLine(); Append("case " + j.ToStringInvariant() + ": goto __returnFromFinally" + i.ToStringInvariant() + "_" + j.ToStringInvariant() + ";"); } AppendLine(); Append("default: CORERT_UNREACHABLE;"); Exdent(); AppendLine(); Append("}"); Exdent(); } } AppendEmptyLine(); Append("}"); methodCodeNodeNeedingCode.SetCode(_builder.ToString(), _dependencies.ToArray()); } private void StartImportingBasicBlock(BasicBlock basicBlock) { _stack.Clear(); EvaluationStack<StackEntry> entryStack = basicBlock.EntryStack; if (entryStack != null) { int n = entryStack.Length; for (int i = 0; i < n; i++) { _stack.Push(entryStack[i].Duplicate()); } } Indent(); } private void EndImportingBasicBlock(BasicBlock basicBlock) { Exdent(); basicBlock.Code = _builder.ToString(); _builder.Clear(); } private void ImportNop() { } private void ImportBreak() { throw new NotImplementedException("Opcode: break"); } private void ImportLoadVar(int index, bool argument) { string name = GetVarName(index, argument); TypeDesc type = GetVarType(index, argument); StackValueKind kind = GetStackValueKind(type); PushTemp(kind, type); AppendCastIfNecessary(kind, type); Append(name); AppendSemicolon(); } private void ImportStoreVar(int index, bool argument) { var value = _stack.Pop(); string name = GetVarName(index, argument); AppendLine(); Append(name); Append(" = "); TypeDesc type = GetVarType(index, argument); AppendCastIfNecessary(type, value); Append(value); AppendSemicolon(); } private void ImportAddressOfVar(int index, bool argument) { string name = GetVarName(index, argument); string temp = NewTempName(); TypeDesc type = GetVarType(index, argument); type = type.MakeByRefType(); PushTemp(StackValueKind.ByRef, type); AppendCastIfNecessary(StackValueKind.ByRef, type); Append("&"); Append(name); AppendSemicolon(); } private void ImportDup() { _stack.Push(_stack.Peek().Duplicate()); } private void ImportPop() { _stack.Pop(); } private void ImportJmp(int token) { throw new NotImplementedException("Opcode: jmp"); } private void ImportCasting(ILOpcode opcode, int token) { TypeDesc type = (TypeDesc)_methodIL.GetObject(token); var value = _stack.Pop(); PushTemp(StackValueKind.ObjRef, type); AddTypeReference(type, false); Append(opcode == ILOpcode.isinst ? "__isinst" : "__castclass"); Append("("); Append(value); Append(", "); Append(_writer.GetCppTypeName(type)); Append("::__getMethodTable())"); AppendSemicolon(); } private static bool IsTypeName(MethodDesc method, string typeNamespace, string typeName) { var metadataType = method.OwningType as MetadataType; if (metadataType == null) return false; return metadataType.Namespace == typeNamespace && metadataType.Name == typeName; } private bool ImportIntrinsicCall(MethodDesc method) { Debug.Assert(method.IsIntrinsic); switch (method.Name) { case "InitializeArray": if (IsTypeName(method, "System.Runtime.CompilerServices", "RuntimeHelpers")) { var fieldSlot = (LdTokenEntry<FieldDesc>) _stack.Pop(); var arraySlot = _stack.Pop(); var fieldDesc = fieldSlot.LdToken; var dataBlob = _compilation.GetFieldRvaData(fieldDesc).GetData(_compilation.NodeFactory, false); Debug.Assert(dataBlob.Relocs.Length == 0); var memBlock = dataBlob.Data; // TODO: Need to do more for arches with different endianness? var preinitDataHolder = NewTempName(); AppendLine(); Append("static const unsigned char "); Append(preinitDataHolder); Append("[] = { "); // Format arrays to have 16 entries per line or less. if (memBlock.Length > 16) { Indent(); AppendLine(); } for (int i = 0; i < memBlock.Length; i++) { if (i != 0) { Append(", "); if ((i % 16) == 0) AppendLine(); } Append("0x"); Append(memBlock[i].ToStringInvariant("x2")); } if (memBlock.Length > 16) { Exdent(); AppendLine(); } Append("}"); AppendSemicolon(); AppendLine(); Append("memcpy((char*)"); Append(arraySlot); Append(" + ARRAY_BASE, "); Append(preinitDataHolder); Append(", "); Append(memBlock.Length.ToStringInvariant()); Append(")"); AppendSemicolon(); return true; } break; case "GetValueInternal": if (IsTypeName(method, "System", "RuntimeTypeHandle")) { var typeHandleSlot = (LdTokenEntry<TypeDesc>) _stack.Pop(); TypeDesc typeOfEEType = typeHandleSlot.LdToken; PushExpression(StackValueKind.NativeInt, string.Concat("((intptr_t)", _writer.GetCppTypeName(typeOfEEType), "::__getMethodTable())")); return true; } break; default: break; } return false; } private void ImportNewObjArray(TypeDesc owningType, MethodDesc method) { AppendLine(); string dimensionsTemp = NewTempName(); Append("int32_t " + dimensionsTemp + "[] = { "); int argumentsCount = method.Signature.Length; for (int i = 0; i < argumentsCount; i++) { Append("(int32_t)("); Append(_stack[_stack.Top - argumentsCount + i]); Append("),"); } _stack.PopN(argumentsCount); Append("};"); PushTemp(StackValueKind.ObjRef, owningType); AddTypeReference(owningType, true); MethodDesc helper = _typeSystemContext.GetHelperEntryPoint("ArrayHelpers", "NewObjArray"); AddMethodReference(helper); Append(_writer.GetCppTypeName(helper.OwningType) + "::" + _writer.GetCppMethodName(helper)); Append("((intptr_t)"); Append(_writer.GetCppTypeName(method.OwningType)); Append("::__getMethodTable(),"); Append(argumentsCount.ToStringInvariant()); Append(","); Append(dimensionsTemp); Append(")"); AppendSemicolon(); } private void ImportCall(ILOpcode opcode, int token) { bool callViaSlot = false; bool delegateInvoke = false; DelegateCreationInfo delegateInfo = null; MethodDesc method = (MethodDesc)_methodIL.GetObject(token); if (method.IsIntrinsic) { if (ImportIntrinsicCall(method)) return; } TypeDesc constrained = null; if (opcode != ILOpcode.newobj) { if ((_pendingPrefix & Prefix.Constrained) != 0 && opcode == ILOpcode.callvirt) { _pendingPrefix &= ~Prefix.Constrained; constrained = _constrained; bool forceUseRuntimeLookup; MethodDesc directMethod = constrained.GetClosestMetadataType().TryResolveConstraintMethodApprox(method.OwningType, method, out forceUseRuntimeLookup); if (directMethod == null || forceUseRuntimeLookup) throw new NotImplementedException(); method = directMethod; opcode = ILOpcode.call; } } TypeDesc owningType = method.OwningType; TypeDesc retType = null; { if (opcode == ILOpcode.newobj) retType = owningType; if (opcode == ILOpcode.newobj) { if (owningType.IsString) { // String constructors actually look like regular method calls method = method.GetStringInitializer(); opcode = ILOpcode.call; // WORKAROUND: the static method expects an extra arg // Annoyingly, it needs to be before all the others _stack.InsertAt(new ExpressionEntry(StackValueKind.ObjRef, "0"), _stack.Top - method.Signature.Length + 1); } else if (owningType.IsArray) { ImportNewObjArray(owningType, method); return; } else if (owningType.IsDelegate) { delegateInfo = _compilation.GetDelegateCtor(owningType, ((LdTokenEntry<MethodDesc>)_stack.Peek()).LdToken); method = delegateInfo.Constructor.Method; } } else if (owningType.IsDelegate) { if (method.Name == "Invoke") { opcode = ILOpcode.call; delegateInvoke = true; } } } if (opcode == ILOpcode.callvirt) { // TODO: Null checks if (method.IsVirtual) { // TODO: Full resolution of virtual methods if (!method.IsNewSlot) throw new NotImplementedException(); // TODO: Interface calls if (method.OwningType.IsInterface) throw new NotImplementedException(); _dependencies.Add(_nodeFactory.VirtualMethodUse(method)); callViaSlot = true; } } if (!callViaSlot && !delegateInvoke) AddMethodReference(method); if (opcode == ILOpcode.newobj) AddTypeReference(retType, true); var methodSignature = method.Signature; if (retType == null) retType = methodSignature.ReturnType; string temp = null; StackValueKind retKind = StackValueKind.Unknown; var needNewLine = false; if (!retType.IsVoid) { retKind = GetStackValueKind(retType); temp = NewTempName(); AppendLine(); Append(GetStackValueKindCPPTypeName(retKind, retType)); Append(" "); Append(temp); if (retType.IsValueType && opcode == ILOpcode.newobj) { Append(";"); needNewLine = true; } else { Append(" = "); if (retType.IsPointer) { Append("(intptr_t)"); } } } else { needNewLine = true; } if (opcode == ILOpcode.newobj) { if (!retType.IsValueType) { // We do not reset needNewLine since we still need for the next statement. if (needNewLine) AppendLine(); Append("__allocate_object("); Append(_writer.GetCppTypeName(retType)); Append("::__getMethodTable())"); AppendSemicolon(); needNewLine = true; if (delegateInfo != null && delegateInfo.Thunk != null) { MethodDesc thunkMethod = delegateInfo.Thunk.Method; AddMethodReference(thunkMethod); // Update stack with new name. ((ExpressionEntry) _stack[_stack.Top - 2]).Name = temp; var sb = new CppGenerationBuffer(); AppendLine(); sb.Append("(intptr_t)&"); sb.Append(_writer.GetCppTypeName(thunkMethod.OwningType)); sb.Append("::"); sb.Append(_writer.GetCppMethodName(thunkMethod)); PushExpression(StackValueKind.NativeInt, sb.ToString()); } } } if (needNewLine) AppendLine(); if (callViaSlot || delegateInvoke) { // While waiting for C# return by ref, get this reference and insert it back // if it is a delegate invoke. ExpressionEntry v = (ExpressionEntry) _stack[_stack.Top - (methodSignature.Length + 1)]; Append("(*"); Append(_writer.GetCppTypeName(method.OwningType)); Append("::"); Append(delegateInvoke ? "__invoke__" : "__getslot__"); Append(_writer.GetCppMethodName(method)); Append("("); Append(v); Append("))"); if (delegateInvoke) { v.Name = "((" + _writer.GetCppSignatureTypeName(GetWellKnownType(WellKnownType.MulticastDelegate)) + ")" + v.Name + ")->m_firstParameter"; } } else { Append(_writer.GetCppTypeName(method.OwningType)); Append("::"); Append(_writer.GetCppMethodName(method)); } TypeDesc thisArgument = null; Append("("); if (opcode == ILOpcode.newobj) { Append("("); if (retType.IsValueType) { Append(_writer.GetCppSignatureTypeName(retType.MakeByRefType())); Append(")"); Append("&" + temp); } else { Append(_writer.GetCppSignatureTypeName(retType)); Append(")"); Append(temp); } if (methodSignature.Length > 0) Append(", "); } else { if (!methodSignature.IsStatic) { thisArgument = owningType; if (thisArgument.IsValueType) thisArgument = thisArgument.MakeByRefType(); } } PassCallArguments(methodSignature, thisArgument); Append(")"); if (temp != null) { Debug.Assert(retKind != StackValueKind.Unknown, "Valid return type"); PushExpression(retKind, temp, retType); } AppendSemicolon(); } private void PassCallArguments(MethodSignature methodSignature, TypeDesc thisArgument) { int signatureLength = methodSignature.Length; int argumentsCount = (thisArgument != null) ? (signatureLength + 1) : signatureLength; int startingIndex = _stack.Top - argumentsCount; for (int i = 0; i < argumentsCount; i++) { var op = _stack[startingIndex + i]; int argIndex = signatureLength - (argumentsCount - i); TypeDesc argType; if (argIndex == -1) { argType = thisArgument; } else { argType = methodSignature[argIndex]; } AppendCastIfNecessary(argType, op); Append(op); if (i + 1 != argumentsCount) Append(", "); } _stack.PopN(argumentsCount); } private void ImportCalli(int token) { MethodSignature methodSignature = (MethodSignature)_methodIL.GetObject(token); TypeDesc thisArgument = null; if (!methodSignature.IsStatic) { thisArgument = GetWellKnownType(WellKnownType.Object); if (thisArgument.IsValueType) thisArgument = thisArgument.MakeByRefType(); } string typeDefName = "__calli__" + token.ToStringInvariant("x8"); _writer.AppendSignatureTypeDef(_builder, typeDefName, methodSignature, thisArgument); TypeDesc retType = methodSignature.ReturnType; StackValueKind retKind = StackValueKind.Unknown; string temp = null; if (!retType.IsVoid) { retKind = GetStackValueKind(retType); temp = NewTempName(); AppendLine(); Append(GetStackValueKindCPPTypeName(retKind, retType)); Append(" "); Append(temp); Append(" = "); if (retType.IsPointer) { Append("(intptr_t)"); } } else { AppendLine(); } var fnPtrValue = _stack.Pop(); Append("(("); Append(typeDefName); Append(")"); Append(fnPtrValue); Append(")("); PassCallArguments(methodSignature, thisArgument); Append(")"); if (temp != null) { Debug.Assert(retKind != StackValueKind.Unknown, "Valid return type"); PushExpression(retKind, temp, retType); } AppendSemicolon(); } private void ImportLdFtn(int token, ILOpcode opCode) { MethodDesc method = (MethodDesc)_methodIL.GetObject(token); if (opCode == ILOpcode.ldvirtftn) { if (method.IsVirtual) throw new NotImplementedException(); } AddMethodReference(method); var entry = new LdTokenEntry<MethodDesc>(StackValueKind.NativeInt, NewTempName(), method); PushTemp(entry); Append("(intptr_t)&"); Append(_writer.GetCppTypeName(method.OwningType)); Append("::"); Append(_writer.GetCppMethodName(method)); AppendSemicolon(); } private void ImportLoadInt(long value, StackValueKind kind) { if (kind == StackValueKind.Int64) { _stack.Push(new Int64ConstantEntry(value)); } else { Debug.Assert(value >= Int32.MinValue && value <= Int32.MaxValue, "Value too large for an Int32."); _stack.Push(new Int32ConstantEntry(checked((int) value))); } } private void ImportLoadFloat(double value) { _stack.Push(new FloatConstantEntry(value)); } private void ImportLoadNull() { PushExpression(StackValueKind.ObjRef, "0"); } private void ImportReturn() { var returnType = _methodSignature.ReturnType; AppendLine(); if (returnType.IsVoid) { Append("return"); } else { var value = _stack.Pop(); Append("return "); AppendCastIfNecessary(returnType, value); Append(value); } AppendSemicolon(); } private void ImportFallthrough(BasicBlock next) { EvaluationStack<StackEntry> entryStack = next.EntryStack; if (entryStack != null) { if (entryStack.Length != _stack.Length) throw new InvalidProgramException(); for (int i = 0; i < entryStack.Length; i++) { // TODO: Do we need to allow conversions? if (entryStack[i].Kind != _stack[i].Kind) throw new InvalidProgramException(); if (entryStack[i].Kind == StackValueKind.ValueType) { if (entryStack[i].Type != _stack[i].Type) throw new InvalidProgramException(); } } } else { if (_stack.Length > 0) { entryStack = new EvaluationStack<StackEntry>(_stack.Length); for (int i = 0; i < _stack.Length; i++) { entryStack.Push(NewSpillSlot(_stack[i])); } } next.EntryStack = entryStack; } if (entryStack != null) { for (int i = 0; i < entryStack.Length; i++) { AppendLine(); Append(entryStack[i]); Append(" = "); Append(_stack[i]); AppendSemicolon(); } } MarkBasicBlock(next); } private void ImportSwitchJump(int jmpBase, int[] jmpDelta, BasicBlock fallthrough) { var op = _stack.Pop(); AppendLine(); Append("switch ("); Append(op); Append(") {"); Indent(); for (int i = 0; i < jmpDelta.Length; i++) { BasicBlock target = _basicBlocks[jmpBase + jmpDelta[i]]; AppendLine(); Append("case " + i + ": "); Indent(); ImportFallthrough(target); AppendLine(); Append("goto _bb"); Append(target.StartOffset.ToStringInvariant()); AppendSemicolon(); AppendLine(); Append("break; "); Exdent(); } Exdent(); AppendLine(); Append("}"); if (fallthrough != null) ImportFallthrough(fallthrough); } private void ImportBranch(ILOpcode opcode, BasicBlock target, BasicBlock fallthrough) { AppendLine(); if (opcode != ILOpcode.br) { Append("if ("); if (opcode == ILOpcode.brfalse || opcode == ILOpcode.brtrue) { var op = _stack.Pop(); Append(op); Append((opcode == ILOpcode.brtrue) ? " != 0" : " == 0"); } else { var op1 = _stack.Pop(); var op2 = _stack.Pop(); // StackValueKind is carefully ordered to make this work (assuming the IL is valid) StackValueKind kind; if (op1.Kind > op2.Kind) { kind = op1.Kind; } else { kind = op2.Kind; } string op = null; bool unsigned = false; bool inverted = false; switch (opcode) { case ILOpcode.beq: op = "=="; break; case ILOpcode.bge: op = ">="; break; case ILOpcode.bgt: op = ">"; break; case ILOpcode.ble: op = "<="; break; case ILOpcode.blt: op = "<"; break; case ILOpcode.bne_un: op = "!="; break; case ILOpcode.bge_un: if (kind == StackValueKind.Float) { op = "<"; inverted = true; } else { op = ">="; } if (kind == StackValueKind.Int32 || kind == StackValueKind.Int64) unsigned = true; break; case ILOpcode.bgt_un: if (kind == StackValueKind.Float) { op = "<="; inverted = true; } else { op = ">"; } if (kind == StackValueKind.Int32 || kind == StackValueKind.Int64) unsigned = true; break; case ILOpcode.ble_un: if (kind == StackValueKind.Float) { op = ">"; inverted = true; } else { op = "<="; } if (kind == StackValueKind.Int32 || kind == StackValueKind.Int64) unsigned = true; break; case ILOpcode.blt_un: if (kind == StackValueKind.Float) { op = ">="; inverted = true; } else { op = "<"; } if (kind == StackValueKind.Int32 || kind == StackValueKind.Int64) unsigned = true; break; } if (kind == StackValueKind.ByRef) unsigned = false; if (inverted) { Append("!("); } if (unsigned) { Append("(u"); Append(GetStackValueKindCPPTypeName(kind)); Append(")"); } Append(op2); Append(" "); Append(op); Append(" "); if (unsigned) { Append("(u"); Append(GetStackValueKindCPPTypeName(kind)); Append(")"); } Append(op1); if (inverted) { Append(")"); } } Append(") "); } Append("{"); Indent(); ImportFallthrough(target); AppendLine(); Append("goto _bb"); Append(target.StartOffset.ToStringInvariant()); AppendSemicolon(); Exdent(); AppendLine(); Append("}"); if (fallthrough != null) ImportFallthrough(fallthrough); } private void ImportBinaryOperation(ILOpcode opcode) { var op1 = _stack.Pop(); var op2 = _stack.Pop(); // StackValueKind is carefully ordered to make this work (assuming the IL is valid) StackValueKind kind; TypeDesc type; if (op1.Kind > op2.Kind) { kind = op1.Kind; type = op1.Type; } else { kind = op2.Kind; type = op2.Type; } // The one exception from the above rule if ((kind == StackValueKind.ByRef) && (opcode == ILOpcode.sub || opcode == ILOpcode.sub_ovf || opcode == ILOpcode.sub_ovf_un)) { kind = StackValueKind.NativeInt; type = null; } PushTemp(kind, type); string op = null; bool unsigned = false; switch (opcode) { case ILOpcode.add: op = "+"; break; case ILOpcode.sub: op = "-"; break; case ILOpcode.mul: op = "*"; break; case ILOpcode.div: op = "/"; break; case ILOpcode.div_un: op = "/"; unsigned = true; break; case ILOpcode.rem: op = "%"; break; case ILOpcode.rem_un: op = "%"; unsigned = true; break; case ILOpcode.and: op = "&"; break; case ILOpcode.or: op = "|"; break; case ILOpcode.xor: op = "^"; break; // TODO: Overflow checks case ILOpcode.add_ovf: op = "+"; break; case ILOpcode.add_ovf_un: op = "+"; unsigned = true; break; case ILOpcode.sub_ovf: op = "-"; break; case ILOpcode.sub_ovf_un: op = "-"; unsigned = true; break; case ILOpcode.mul_ovf: op = "*"; break; case ILOpcode.mul_ovf_un: op = "*"; unsigned = true; break; default: Debug.Assert(false, "Unexpected opcode"); break; } if (unsigned) { Append("(u"); Append(GetStackValueKindCPPTypeName(kind)); Append(")"); } Append(op2); Append(" "); Append(op); Append(" "); if (unsigned) { Append("(u"); Append(GetStackValueKindCPPTypeName(kind)); Append(")"); } Append(op1); AppendSemicolon(); } private void ImportShiftOperation(ILOpcode opcode) { var shiftAmount = _stack.Pop(); var op = _stack.Pop(); PushTemp(op.Kind, op.Type); if (opcode == ILOpcode.shr_un) { Append("(u"); Append(GetStackValueKindCPPTypeName(op.Kind)); Append(")"); } Append(op); Append((opcode == ILOpcode.shl) ? " << " : " >> "); Append(shiftAmount); AppendSemicolon(); } private void ImportCompareOperation(ILOpcode opcode) { var op1 = _stack.Pop(); var op2 = _stack.Pop(); // StackValueKind is carefully ordered to make this work (assuming the IL is valid) StackValueKind kind; if (op1.Kind > op2.Kind) { kind = op1.Kind; } else { kind = op2.Kind; } PushTemp(StackValueKind.Int32); string op = null; bool unsigned = false; bool inverted = false; switch (opcode) { case ILOpcode.ceq: op = "=="; break; case ILOpcode.cgt: op = ">"; break; case ILOpcode.clt: op = "<"; break; case ILOpcode.cgt_un: if (kind == StackValueKind.Float) { op = "<="; inverted = true; } else { op = ">"; if (kind == StackValueKind.Int32 || kind == StackValueKind.Int64) unsigned = true; } break; case ILOpcode.clt_un: if (kind == StackValueKind.Float) { op = ">="; inverted = true; } else { op = "<"; if (kind == StackValueKind.Int32 || kind == StackValueKind.Int64) unsigned = true; } break; } if (kind == StackValueKind.ByRef) unsigned = false; if (inverted) { Append("!("); } if (unsigned) { Append("(u"); Append(GetStackValueKindCPPTypeName(kind)); Append(")"); } Append(op2); Append(" "); Append(op); Append(" "); if (unsigned) { Append("(u"); Append(GetStackValueKindCPPTypeName(kind)); Append(")"); } Append(op1); if (inverted) { Append(")"); } AppendSemicolon(); } private void ImportConvert(WellKnownType wellKnownType, bool checkOverflow, bool unsigned) { var op = _stack.Pop(); TypeDesc type = GetWellKnownType(wellKnownType); PushTemp(GetStackValueKind(type)); Append("("); Append(_writer.GetCppSignatureTypeName(type)); Append(")"); Append(op); AppendSemicolon(); } private void ImportLoadField(int token, bool isStatic) { FieldDesc field = (FieldDesc)_methodIL.GetObject(token); AddFieldReference(field); var thisPtr = isStatic ? InvalidEntry.Entry : _stack.Pop(); TypeDesc owningType = field.OwningType; TypeDesc fieldType = field.FieldType; // TODO: Is this valid combination? if (!isStatic && !owningType.IsValueType && thisPtr.Kind != StackValueKind.ObjRef) throw new InvalidProgramException(); if (field.IsStatic) TriggerCctor(field.OwningType); StackValueKind kind = GetStackValueKind(fieldType); PushTemp(kind, fieldType); AppendCastIfNecessary(kind, fieldType); if (field.IsStatic) { if (!fieldType.IsValueType) Append("__gcStatics."); else Append("__statics."); Append(_writer.GetCppStaticFieldName(field)); } else if (thisPtr.Kind == StackValueKind.ValueType) { Append(thisPtr); Append("."); Append(_writer.GetCppFieldName(field)); } else { Append("(("); Append(_writer.GetCppTypeName(owningType)); Append("*)"); Append(thisPtr); Append(")->"); Append(_writer.GetCppFieldName(field)); // TODO: Remove _writer.GetCppSignatureTypeName(owningType); } AppendSemicolon(); } private void ImportAddressOfField(int token, bool isStatic) { FieldDesc field = (FieldDesc)_methodIL.GetObject(token); AddFieldReference(field); var thisPtr = isStatic ? InvalidEntry.Entry: _stack.Pop(); TypeDesc owningType = field.OwningType; TypeDesc fieldType = field.FieldType; // TODO: Is this valid combination? if (!isStatic && !owningType.IsValueType && thisPtr.Kind != StackValueKind.ObjRef) throw new InvalidProgramException(); if (field.IsStatic) TriggerCctor(field.OwningType); TypeDesc addressType = fieldType.MakeByRefType(); StackValueKind kind = GetStackValueKind(addressType); PushTemp(kind, addressType); AppendCastIfNecessary(kind, addressType); Append("&"); if (field.IsStatic) { if (!fieldType.IsValueType) Append("__gcStatics."); else Append("__statics."); Append(_writer.GetCppStaticFieldName(field)); } else if (thisPtr.Kind == StackValueKind.ValueType) { throw new NotImplementedException(); } else { Append("(("); Append(_writer.GetCppTypeName(owningType)); Append("*)"); Append(thisPtr); Append(")->"); Append(_writer.GetCppFieldName(field)); // TODO: Remove _writer.GetCppSignatureTypeName(owningType); } AppendSemicolon(); } private void ImportStoreField(int token, bool isStatic) { FieldDesc field = (FieldDesc)_methodIL.GetObject(token); AddFieldReference(field); var value = _stack.Pop(); var thisPtr = isStatic ? InvalidEntry.Entry : _stack.Pop(); TypeDesc owningType = field.OwningType; TypeDesc fieldType = field.FieldType; // TODO: Is this valid combination? if (!isStatic && !owningType.IsValueType && thisPtr.Kind != StackValueKind.ObjRef) throw new InvalidProgramException(); if (field.IsStatic) TriggerCctor(field.OwningType); // TODO: Write barrier as necessary!!! AppendLine(); if (field.IsStatic) { if (!fieldType.IsValueType) Append("__gcStatics."); else Append("__statics."); Append(_writer.GetCppStaticFieldName(field)); } else if (thisPtr.Kind == StackValueKind.ValueType) { throw new NotImplementedException(); } else { Append("(("); Append(_writer.GetCppTypeName(owningType)); Append("*)"); Append(thisPtr); Append(")->"); Append(_writer.GetCppFieldName(field)); // TODO: Remove _writer.GetCppSignatureTypeName(owningType); } Append(" = "); if (!fieldType.IsValueType) { Append("("); Append(_writer.GetCppSignatureTypeName(fieldType)); Append(")"); } Append(value); AppendSemicolon(); } private void ImportLoadIndirect(int token) { ImportLoadIndirect(ResolveTypeToken(token)); } private void ImportLoadIndirect(TypeDesc type) { if (type == null) type = GetWellKnownType(WellKnownType.Object); var addr = _stack.Pop(); PushTemp(GetStackValueKind(type), type); Append("*("); Append(_writer.GetCppSignatureTypeName(type)); Append("*)"); Append(addr); AppendSemicolon(); } private void ImportStoreIndirect(int token) { ImportStoreIndirect(ResolveTypeToken(token)); } private void ImportStoreIndirect(TypeDesc type) { if (type == null) type = GetWellKnownType(WellKnownType.Object); var value = _stack.Pop(); var addr = _stack.Pop(); // TODO: Write barrier as necessary!!! AppendLine(); Append("*("); Append(_writer.GetCppSignatureTypeName(type)); Append("*)"); Append(addr); Append(" = "); AppendCastIfNecessary(type, value); Append(value); AppendSemicolon(); } private void ImportThrow() { var obj = _stack.Pop(); AppendLine(); Append("__throw_exception("); Append(obj); Append(")"); AppendSemicolon(); } private void ImportLoadString(int token) { string str = (string)_methodIL.GetObject(token); PushTemp(StackValueKind.ObjRef, GetWellKnownType(WellKnownType.String)); var escaped = new CppGenerationBuffer(); foreach (char c in str) { switch (c) { case '\\': escaped.Append("\\\\"); break; case '\r': escaped.Append("\\r"); break; case '\n': escaped.Append("\\n"); break; case '\t': escaped.Append("\\t"); break; default: // TODO: handle all characters < 32 escaped.Append(c); break; } } Append("__load_string_literal(\""); Append(escaped.ToString()); Append("\")"); AppendSemicolon(); } private void ImportInitObj(int token) { TypeDesc type = (TypeDesc)_methodIL.GetObject(token); var addr = _stack.Pop(); AppendLine(); Append("memset((void*)"); Append(addr); Append(",0,sizeof("); Append(_writer.GetCppSignatureTypeName(type)); Append("))"); AppendSemicolon(); } private void ImportBox(int token) { TypeDesc type = (TypeDesc)_methodIL.GetObject(token); if (type.IsValueType) { if (type.IsNullable) throw new NotImplementedException(); var value = _stack.Pop(); PushTemp(StackValueKind.ObjRef, type); AddTypeReference(type, true); Append("__allocate_object("); Append(_writer.GetCppTypeName(type)); Append("::__getMethodTable())"); AppendSemicolon(); string typeName = GetStackValueKindCPPTypeName(GetStackValueKind(type), type); // TODO: Write barrier as necessary AppendLine(); Append("*(" + typeName + " *)((void **)"); Append(_stack.Peek()); Append(" + 1) = "); Append(value); AppendSemicolon(); } } private static bool IsOffsetContained(int offset, int start, int length) { return start <= offset && offset < start + length; } private static string AddReturnLabel(ExceptionRegion r) { r.ReturnLabels++; return r.ReturnLabels.ToStringInvariant(); } private void ImportLeave(BasicBlock target) { // Empty the stack _stack.Clear(); // Close the scope and open a new one so that we don't put a goto label in the middle // of a scope. Exdent(); AppendLine(); Append("}"); AppendLine(); Append("{"); Indent(); for (int i = 0; i < _exceptionRegions.Length; i++) { var r = _exceptionRegions[i]; if (r.ILRegion.Kind == ILExceptionRegionKind.Finally && IsOffsetContained(_currentOffset - 1, r.ILRegion.TryOffset, r.ILRegion.TryLength) && !IsOffsetContained(target.StartOffset, r.ILRegion.TryOffset, r.ILRegion.TryLength)) { string returnLabel = AddReturnLabel(r); AppendLine(); Append("__finallyReturn"); Append(i.ToStringInvariant()); Append(" = "); Append(returnLabel); AppendSemicolon(); AppendLine(); Append("goto _bb"); Append(r.ILRegion.HandlerOffset.ToStringInvariant()); AppendSemicolon(); AppendEmptyLine(); Append("__returnFromFinally"); Append(i.ToStringInvariant()); Append("_"); Append(returnLabel); Append(":"); AppendSemicolon(); MarkBasicBlock(_basicBlocks[r.ILRegion.HandlerOffset]); } } AppendLine(); Append("goto _bb"); Append(target.StartOffset.ToStringInvariant()); AppendSemicolon(); MarkBasicBlock(target); } private int FindNearestFinally(int offset) { int candidate = -1; for (int i = 0; i < _exceptionRegions.Length; i++) { var r = _exceptionRegions[i]; if (r.ILRegion.Kind == ILExceptionRegionKind.Finally && IsOffsetContained(offset - 1, r.ILRegion.HandlerOffset, r.ILRegion.HandlerLength)) { if (candidate == -1 || _exceptionRegions[candidate].ILRegion.HandlerOffset < _exceptionRegions[i].ILRegion.HandlerOffset) { candidate = i; } } } return candidate; } private void ImportEndFinally() { int finallyIndex = FindNearestFinally(_currentOffset - 1); AppendLine(); Append("goto __endFinally"); Append(finallyIndex.ToStringInvariant()); AppendSemicolon(); } private void ImportNewArray(int token) { TypeDesc type = (TypeDesc)_methodIL.GetObject(token); TypeDesc arrayType = type.Context.GetArrayType(type); var numElements = _stack.Pop(); PushTemp(StackValueKind.ObjRef, arrayType); AddTypeReference(arrayType, true); Append("__allocate_array("); Append(numElements); Append(", "); Append(_writer.GetCppTypeName(arrayType)); Append("::__getMethodTable()"); Append(")"); AppendSemicolon(); } private void ImportLoadElement(int token) { ImportLoadElement(ResolveTypeToken(token)); } private void ImportLoadElement(TypeDesc elementType) { // ldelem_ref if (elementType == null) elementType = GetWellKnownType(WellKnownType.Object); var index = _stack.Pop(); var arrayPtr = _stack.Pop(); // Range check AppendLine(); Append("__range_check("); Append(arrayPtr); Append(","); Append(index); Append(");"); PushTemp(GetStackValueKind(elementType), elementType); Append("*("); Append(_writer.GetCppSignatureTypeName(elementType)); Append("*)((char *)"); Append(arrayPtr); Append(" + ARRAY_BASE + sizeof("); Append(_writer.GetCppSignatureTypeName(elementType)); Append(") * "); Append(index); Append(")"); AppendSemicolon(); } private void ImportStoreElement(int token) { ImportStoreElement(ResolveTypeToken(token)); } private void ImportStoreElement(TypeDesc elementType) { // stelem_ref if (elementType == null) elementType = GetWellKnownType(WellKnownType.Object); var value = _stack.Pop(); var index = _stack.Pop(); var arrayPtr = _stack.Pop(); // Range check AppendLine(); Append("__range_check("); Append(arrayPtr); Append(","); Append(index); Append(");"); // TODO: Array covariance // TODO: Write barrier as necessary!!! AppendLine(); Append("*("); Append(_writer.GetCppSignatureTypeName(elementType)); Append("*)((char *)"); Append(arrayPtr); Append(" + ARRAY_BASE + sizeof("); Append(_writer.GetCppSignatureTypeName(elementType)); Append(") * "); Append(index); Append(") = "); AppendCastIfNecessary(elementType, value); Append(value); AppendSemicolon(); } private void ImportAddressOfElement(int token) { TypeDesc elementType = (TypeDesc)_methodIL.GetObject(token); var index = _stack.Pop(); var arrayPtr = _stack.Pop(); // Range check AppendLine(); Append("__range_check("); Append(arrayPtr); Append(","); Append(index); Append(");"); TypeDesc byRef = elementType.MakeByRefType(); PushTemp(StackValueKind.ByRef, byRef); AppendCastIfNecessary(StackValueKind.ByRef, byRef); Append("("); Append(_writer.GetCppSignatureTypeName(elementType)); Append("*)((char *)"); Append(arrayPtr); Append(" + ARRAY_BASE + sizeof("); Append(_writer.GetCppSignatureTypeName(elementType)); Append(") * "); Append(index); Append(")"); AppendSemicolon(); } private void ImportLoadLength() { var arrayPtr = _stack.Pop(); PushTemp(StackValueKind.NativeInt); Append("*((intptr_t *)"); Append(arrayPtr); Append("+ 1)"); AppendSemicolon(); } private void ImportUnaryOperation(ILOpcode opCode) { var argument = _stack.Pop(); if (argument.Kind == StackValueKind.Float) throw new NotImplementedException(); PushTemp(argument.Kind, argument.Type); Append((opCode == ILOpcode.neg) ? "~" : "!"); Append(argument); AppendSemicolon(); } private void ImportCpOpj(int token) { throw new NotImplementedException(); } private void ImportUnbox(int token, ILOpcode opCode) { var type = ResolveTypeToken(token); var obj = _stack.Pop(); if (opCode == ILOpcode.unbox) { PushTemp(StackValueKind.ByRef, type.MakeByRefType()); } else { PushTemp(GetStackValueKind(type), type); } if (type.IsValueType) { // TODO: Unbox of nullable types if (type.IsNullable) throw new NotImplementedException(); if (opCode == ILOpcode.unbox_any) { string typeName = GetStackValueKindCPPTypeName(GetStackValueKind(type), type); Append("*("); Append(typeName); Append("*)"); } Append("("); Append(_writer.GetCppSignatureTypeName(type)); Append("*)"); Append("((void **)"); Append(obj); Append("+1)"); } else { // TODO: Cast Append(obj); } AppendSemicolon(); } private void ImportRefAnyVal(int token) { throw new NotImplementedException(); } private void ImportCkFinite() { throw new NotImplementedException(); } private void ImportMkRefAny(int token) { throw new NotImplementedException(); } private void ImportLdToken(int token) { var ldtokenValue = _methodIL.GetObject(token); WellKnownType ldtokenKind; string name; StackEntry value; if (ldtokenValue is TypeDesc) { ldtokenKind = WellKnownType.RuntimeTypeHandle; AddTypeReference((TypeDesc)ldtokenValue, false); MethodDesc helper = _typeSystemContext.GetHelperEntryPoint("LdTokenHelpers", "GetRuntimeTypeHandle"); AddMethodReference(helper); name = String.Concat( _writer.GetCppTypeName(helper.OwningType), "::", _writer.GetCppMethodName(helper), "((intptr_t)", _writer.GetCppTypeName((TypeDesc)ldtokenValue), "::__getMethodTable())"); value = new LdTokenEntry<TypeDesc>(StackValueKind.ValueType, name, (TypeDesc)ldtokenValue, GetWellKnownType(ldtokenKind)); } else if (ldtokenValue is FieldDesc) { ldtokenKind = WellKnownType.RuntimeFieldHandle; value = new LdTokenEntry<FieldDesc>(StackValueKind.ValueType, null, (FieldDesc) ldtokenValue, GetWellKnownType(ldtokenKind)); } else if (ldtokenValue is MethodDesc) { throw new NotImplementedException(); } else throw new InvalidOperationException(); _stack.Push(value); } private void ImportLocalAlloc() { StackEntry count = _stack.Pop(); // TODO: this is machine dependent and might not result in a HW stack overflow exception // TODO: might not have enough alignment guarantees for the allocated buffer var bufferName = NewTempName(); AppendLine(); Append("void* "); Append(bufferName); Append(" = alloca("); Append(count); Append(")"); AppendSemicolon(); if (_methodIL.IsInitLocals) { AppendLine(); Append("memset("); Append(bufferName); Append(", 0, "); Append(count); Append(")"); AppendSemicolon(); } PushExpression(StackValueKind.NativeInt, bufferName); } private void ImportEndFilter() { throw new NotImplementedException(); } private void ImportCpBlk() { throw new NotImplementedException(); } private void ImportInitBlk() { throw new NotImplementedException(); } private void ImportRethrow() { throw new NotImplementedException(); } private void ImportSizeOf(int token) { var type = ResolveTypeToken(token); // TODO: Remove _writer.GetCppSignatureTypeName(type); PushExpression(StackValueKind.Int32, "sizeof(" + _writer.GetCppTypeName(type) + ")"); } private void ImportRefAnyType() { throw new NotImplementedException(); } private void ImportArgList() { throw new NotImplementedException(); } private void ImportUnalignedPrefix(byte alignment) { throw new NotImplementedException(); } private void ImportVolatilePrefix() { // TODO: // throw new NotImplementedException(); } private void ImportTailPrefix() { throw new NotImplementedException(); } private void ImportConstrainedPrefix(int token) { _pendingPrefix |= Prefix.Constrained; _constrained = ResolveTypeToken(token); } private void ImportNoPrefix(byte mask) { throw new NotImplementedException(); } private void ImportReadOnlyPrefix() { throw new NotImplementedException(); } private void TriggerCctor(TypeDesc type) { // TODO: Before field init MethodDesc cctor = type.GetStaticConstructor(); if (cctor == null) return; // TODO: Thread safety string ctorHasRun = "__statics.__cctor_" + _writer.GetCppTypeName(type).Replace("::", "__"); AppendLine(); Append("if (!" + ctorHasRun + ") {"); Indent(); AppendLine(); Append(ctorHasRun + " = true;"); AppendLine(); Append(_writer.GetCppTypeName(cctor.OwningType)); Append("::"); Append(_writer.GetCppMethodName(cctor)); Append("();"); Exdent(); AppendLine(); Append("}"); AddMethodReference(cctor); } private void AddTypeReference(TypeDesc type, bool constructed) { Object node; if (constructed) node = _nodeFactory.ConstructedTypeSymbol(type); else node = _nodeFactory.NecessaryTypeSymbol(type); _dependencies.Add(node); } private void AddMethodReference(MethodDesc method) { _dependencies.Add(_nodeFactory.MethodEntrypoint(method)); } private void AddFieldReference(FieldDesc field) { if (field.IsStatic) { var owningType = (MetadataType)field.OwningType; Object node; if (field.IsThreadStatic) { node = _nodeFactory.TypeThreadStaticsSymbol(owningType); } else { if (field.HasGCStaticBase) node = _nodeFactory.TypeGCStaticsSymbol(owningType); else node = _nodeFactory.TypeNonGCStaticsSymbol(owningType); } // TODO: Remove once the depedencies for static fields are tracked properly _writer.GetCppSignatureTypeName(owningType); _dependencies.Add(node); } } } }
32.597345
170
0.466737
[ "MIT" ]
OceanYan/corert
src/ILCompiler.Compiler/src/CppCodeGen/ILToCppImporter.cs
81,037
C#
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Concurrent; using System.Collections.ObjectModel; //#if NET40 //using System.Dynamic; //#endif using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using System.Doors; using System.Dynamic; namespace System.Doors.Data { public enum JsonToken { Unknown, LeftBrace, RightBrace, Colon, Comma, LeftBracket, RightBracket, String, Number, True, False, Null } /// Possible JSON tokens in parsed input. public class InvalidJsonException : Exception { public InvalidJsonException(string message) : base(message) { } } public interface IJson { } public class DataJson { private static readonly IDictionary<string, IDictionary<Type, PropertyInfo[]>> _cache; private static readonly char[] _base16 = new[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; private static readonly string[][] _unichar = new string[][] { new string[] { new string('"', 1), @"\""", }, new string[] { new string('/', 1), @"\/", }, new string[] { new string('\\', 1), @"\\", }, new string[] { new string('\b', 1), @"\b", }, new string[] { new string('\f', 1), @"\f", }, new string[] { new string('\n', 1), @"\n", }, new string[] { new string('\r', 1), @"\r", }, new string[] { new string('\t', 1), @"\t", } }; private static NumberStyles _numbers = NumberStyles.Float; static DataJson() { _cache = new Dictionary<string, IDictionary<Type, PropertyInfo[]>>(); foreach (string cmplx in Enum.GetNames(typeof(DepotComplexity))) _cache.Add(cmplx, new Dictionary<Type, PropertyInfo[]>()); } public static object Serialize(object instance) { Type type = instance.GetType(); IDictionary <string, object> bag = GetBagForObject(type, instance); return ToJson(bag); } public static string Serialize<T>(T instance) { IDictionary<string, object> bag = GetBagForObject(instance); return ToJson(bag); } public static object Deserialize(string json, Type type) { object instance; var map = PrepareInstance(out instance, type); var bag = FromJson(json); DeserializeImpl(map, bag, instance); return instance; } public static T Deserialize<T>(string json) { T instance; var map = PrepareInstance(out instance); var bag = FromJson(json); DeserializeImpl(map, bag, instance); return instance; } private static void DeserializeImpl(IEnumerable<PropertyInfo> map, IDictionary<string, object> bag, object instance) { DeserializeType(map, bag, instance); } private static void DeserializeImpl<T>(IEnumerable<PropertyInfo> map, IDictionary<string, object> bag, T instance) { DeserializeType(map, bag, instance); } public static void DeserializeType(IEnumerable<PropertyInfo> map, IDictionary<string, object> bag, object instance) { System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo(); nfi.NumberDecimalSeparator = "."; foreach (PropertyInfo info in map) { bool mutated = false; string key = info.Name; if (!bag.ContainsKey(key)) { key = info.Name.Replace("_", ""); if (!bag.ContainsKey(key)) { key = info.Name.Replace("-", ""); if (!bag.ContainsKey(key)) continue; } } object value = bag[key]; if (value != null && value.GetType() == typeof(String)) if (value.Equals("null")) value = null; if (value != null) { if (info.PropertyType == typeof(byte[])) if (value.GetType() == typeof(List<object>)) value = ((List<object>)value).Select(symbol => Convert.ToByte(symbol)).ToArray(); else value = ((object[])value).Select(symbol => Convert.ToByte(symbol)).ToArray(); else if (info.PropertyType == typeof(Quid)) value = new Quid(value.ToString()); else if (info.PropertyType == typeof(Single)) value = Convert.ToSingle(value, nfi); else if (info.PropertyType == typeof(DateTime)) value = Convert.ToDateTime(value); else if (info.PropertyType == typeof(double)) value = Convert.ToDouble(value, nfi); else if (info.PropertyType == typeof(decimal)) value = Convert.ToDecimal(value, nfi); else if (info.PropertyType == typeof(int)) value = Convert.ToInt32(value); else if (info.PropertyType == typeof(long)) value = Convert.ToInt64(value); else if (info.PropertyType == typeof(short)) value = Convert.ToInt16(value); else if (info.PropertyType == typeof(bool)) value = Convert.ToBoolean(value); else if (info.PropertyType == typeof(IDataNative)) { object n = info.GetValue(instance, null); DeserializeType(n.GetType().GetProperties(), (Dictionary<string, object>)value, n); mutated = true; } else if (info.PropertyType == typeof(SortedDictionary<string, DataSpheres>)) { JsonSpheres.GetJsonByInfo(ref instance, ref value, info); mutated = true; } else if (info.PropertyType == typeof(SortedDictionary<string, DataSphere>)) { JsonSphere.GetJsonByInfo(ref instance, ref value, info); mutated = true; } else if (info.PropertyType == typeof(Dictionary<string, DataTrellis>)) { JsonTrellis.GetJsonByInfo(ref instance, ref value, info); mutated = true; } else if (info.PropertyType == typeof(DataSpheres)) { JsonSpheres.GetJsonByInfo(ref instance, ref value, info, false); mutated = true; } else if (info.PropertyType == typeof(DataTrellises)) { JsonTrellises.GetJsonByInfo(ref instance, ref value, info); mutated = true; } else if (info.PropertyType == typeof(DataTiers)) { JsonTiers.GetJsonByInfo(ref instance, ref value, info); mutated = true; } else if (info.PropertyType == typeof(DataPageDetails)) { object inst = new object(); Dictionary<string, object> subbag = (Dictionary<string, object>)value; IEnumerable<PropertyInfo> submap = PrepareInstance(out inst, typeof(DataPageDetails)); DeserializeType(submap, subbag, inst); DataPageDetails pyls = (DataPageDetails)info.GetValue(instance, null); pyls.Impact((DataPageDetails)inst); mutated = true; } else if (info.PropertyType == typeof(DataRelaying)) { value = (DataRelaying)info.GetValue(instance, null); mutated = true; } else if (info.PropertyType == typeof(DataRelays)) { if (((ICollection)value).Count > 0) { List<object> listobjects = (List<object>)value; List<DataRelay> list = new List<DataRelay>(); foreach (object obj in listobjects) { object inst = new object(); Dictionary<string, object> subbag = (Dictionary<string, object>)obj; IEnumerable<PropertyInfo> submap = PrepareInstance(out inst, typeof(DataRelay)); DeserializeType(submap, subbag, inst); list.Add((DataRelay)inst); } DataRelays pyls = (DataRelays)info.GetValue(instance, null); pyls.AddRange(list); } mutated = true; } else if (info.PropertyType == typeof(DataRelayMember)) { object inst = new object(); Dictionary<string, object> subbag = (Dictionary<string, object>)value; IEnumerable<PropertyInfo> submap = PrepareInstance(out inst, typeof(DataRelayMember)); DeserializeType(submap, subbag, inst); value = inst; } else if (info.PropertyType == typeof(DataRelay)) { value = (DataRelay)info.GetValue(instance, null); mutated = true; } else if (info.PropertyType == typeof(DataPylons)) { if (((ICollection)value).Count > 0) { List<object> listobjects = (List<object>)value; List<DataPylon> list = new List<DataPylon>(); foreach (object obj in listobjects) { object inst = new object(); Dictionary<string, object> subbag = (Dictionary<string, object>)obj; IEnumerable<PropertyInfo> submap = PrepareInstance(out inst, typeof(DataPylon)); DeserializeType(submap, subbag, inst); list.Add((DataPylon)inst); } DataPylons pyls = (DataPylons)info.GetValue(instance, null); pyls.AddRange(list); } mutated = true; } else if (info.PropertyType == typeof(DataFavorites)) { if (((ICollection)value).Count > 0) { List<object> listobjects = (List<object>)value; List<DataFavorite> list = new List<DataFavorite>(); foreach (object obj in listobjects) { object inst = new object(); Dictionary<string, object> subbag = (Dictionary<string, object>)obj; IEnumerable<PropertyInfo> submap = PrepareInstance(out inst, typeof(DataFavorite)); DeserializeType(submap, subbag, inst); list.Add((DataFavorite)inst); } DataFavorites terms = (DataFavorites)info.GetValue(instance, null); terms.AddRange(list); } mutated = true; } else if (info.PropertyType == typeof(FilterTerms)) { if (((ICollection)value).Count > 0) { List<object> listobjects = (List<object>)value; List<FilterTerm> list = new List<FilterTerm>(); foreach (object obj in listobjects) { object inst = new object(); Dictionary<string, object> subbag = (Dictionary<string, object>)obj; IEnumerable<PropertyInfo> submap = PrepareInstance(out inst, typeof(FilterTerm)); DeserializeType(submap, subbag, inst); list.Add((FilterTerm)inst); } FilterTerms terms = (FilterTerms)info.GetValue(instance, null); terms.AddRange(list); } mutated = true; } else if (info.PropertyType == typeof(SortTerms)) { if (((ICollection)value).Count > 0) { List<object> listobjects = (List<object>)value; List<SortTerm> list = new List<SortTerm>(); foreach (object obj in listobjects) { object inst = new object(); Dictionary<string, object> subbag = (Dictionary<string, object>)obj; IEnumerable<PropertyInfo> submap = PrepareInstance(out inst, typeof(SortTerm)); DeserializeType(submap, subbag, inst); list.Add((SortTerm)inst); } SortTerms terms = (SortTerms)info.GetValue(instance, null); terms.AddRange(list); } mutated = true; } else if (info.PropertyType == typeof(DataPylon[])) { if (((ICollection)value).Count > 0) { List<object> listobjects = (List<object>)value; List<DataPylon> list = new List<DataPylon>(); foreach (object obj in listobjects) { object inst = new object(); Dictionary<string, object> subbag = (Dictionary<string, object>)obj; IEnumerable<PropertyInfo> submap = PrepareInstance(out inst, typeof(DataPylon)); DeserializeType(submap, subbag, inst); list.Add((DataPylon)inst); } DataPylon[] pyls = (DataPylon[])info.GetValue(instance, null); pyls = list.ToArray(); } mutated = true; } else if (info.PropertyType == typeof(DataState)) { object inst = new object(); Dictionary<string, object> subbag = (Dictionary<string, object>)value; IEnumerable<PropertyInfo> submap = PrepareInstance(out inst, typeof(DataState)); DeserializeType(submap, subbag, inst); DataState state = (DataState)info.GetValue(instance, null); state.Impact((DataState)inst); mutated = true; } else if (info.PropertyType == typeof(TransactionContext)) { object inst = new object(); Dictionary<string, object> subbag = (Dictionary<string, object>)value; IEnumerable<PropertyInfo> submap = PrepareInstance(out inst, typeof(TransactionContext)); DeserializeType(submap, subbag, inst); info.SetValue(instance, inst, null); mutated = true; } else if (info.PropertyType == typeof(DepotIdentity)) { object inst = new object(); Dictionary<string, object> subbag = (Dictionary<string, object>)value; IEnumerable<PropertyInfo> submap = PrepareInstance(out inst, typeof(DepotIdentity)); DeserializeType(submap, subbag, inst); info.SetValue(instance, inst, null); mutated = true; } else if (info.PropertyType == typeof(DataConfig)) { object inst = new object(); Dictionary<string, object> subbag = (Dictionary<string, object>)value; IEnumerable<PropertyInfo> submap = PrepareInstance(out inst, typeof(DataConfig)); DeserializeType(submap, subbag, inst); DataConfig config = (DataConfig)info.GetValue(instance, null); config.Impact((DataConfig)inst); mutated = true; } else if (info.PropertyType == typeof(DataParams)) { object inst = new object(); Dictionary<string, object> subbags = (Dictionary<string, object>)value; DataParams parameters = (DataParams)info.GetValue(instance, null); foreach (KeyValuePair<string, object> subbag in subbags) parameters.Add(subbag); mutated = true; } else if (info.PropertyType == typeof(Type)) { object typevalue = info.GetValue(instance, null); if (value != null) typevalue = Type.GetType(value.ToString()); value = typevalue; } else if (info.PropertyType.IsEnum) { object enumvalue = info.GetValue(instance, null); enumvalue = Enum.Parse(info.PropertyType, value.ToString()); value = enumvalue; } } if (!mutated) info.SetValue(instance, value, null); } } public static IDictionary<string, object> FromJson(string json) { JsonToken type; var result = FromJson(json, out type); switch (type) { case JsonToken.LeftBrace: var @object = (IDictionary<string, object>)result.Single().Value; return @object; } return result; } public static IDictionary<string, object> FromJson(string json, out JsonToken type) { var data = json.ToCharArray(); var index = 0; // Rewind index for first token var token = NextToken(data, ref index); switch (token) { case JsonToken.LeftBrace: // Start Object case JsonToken.LeftBracket: // Start Array index--; type = token; break; default: throw new InvalidJsonException("JSON must begin with an object or array"); } return ParseObject(data, ref index); } public static string ToJson(IDictionary<string, object> bag, DepotComplexity complexity = DepotComplexity.Standard) { var sb = new StringBuilder(4096); SerializeItem(sb, bag, null, complexity); return sb.ToString(); } public static string ToJson(IDictionary<int, object> bag, DepotComplexity complexity = DepotComplexity.Standard) { var sb = new StringBuilder(0); SerializeItem(sb, bag, null, complexity); return sb.ToString(); } internal static IDictionary<string, object> GetBagForObject(Type type, object instance, DepotComplexity complexity = DepotComplexity.Standard) { CacheReflection(type, complexity); if (type.FullName == null) { return null; } bool anonymous = type.FullName.Contains("__AnonymousType"); PropertyInfo[] map = _cache[complexity.ToString()][type]; IDictionary<string, object> bag = InitializeBag(); foreach (PropertyInfo info in map) { if (info != null) { var readWrite = (info.CanWrite && info.CanRead); if (!readWrite && !anonymous) { continue; } object value = null; try { value = info.GetValue(instance, null); } catch (Exception ex) { ex.ToDataLog(); } bag.Add(info.Name, value); } } return bag; } internal static IDictionary<string, object> GetBagForObject<T>(T instance, DepotComplexity complexity = DepotComplexity.Standard) { return GetBagForObject(typeof(T), instance, complexity); } internal static Dictionary<string, object> InitializeBag() { return new Dictionary<string, object>( 0, StringComparer.OrdinalIgnoreCase ); } public static IEnumerable<PropertyInfo> PrepareInstance(out object instance, Type type) { instance = Activator.CreateInstance(type); CacheReflection(type); return _cache["Standard"][type]; } public static IEnumerable<PropertyInfo> PrepareInstance<T>(out T instance) { instance = Activator.CreateInstance<T>(); Type item = typeof(T); CacheReflection(item); return _cache["Standard"][item]; } internal static void CacheReflection(Type item, DepotComplexity complexity = DepotComplexity.Standard) { if (_cache[complexity.ToString()].ContainsKey(item)) return; PropertyInfo[] verified = new PropertyInfo[0]; PropertyInfo[] prepare = item.GetJsonProperties(complexity); if (prepare != null) verified = prepare; _cache[complexity.ToString()].Add(item, verified); } internal static void SerializeItem(StringBuilder sb, object item, string key = null, DepotComplexity complexity = DepotComplexity.Standard) { if (item == null) { sb.Append("null"); return; } if (item is IDictionary) { SerializeObject(item, sb, false, complexity); return; } if (item is ICollection && !(item is string)) { SerializeArray(item, sb, complexity); return; } if (item is Quid) { sb.Append("\"" + ((Quid)item).ToString() + "\""); return; } if (item is Noid) { sb.Append("\"" + ((Noid)item).ToString() + "\""); return; } if (item is DateTime) { sb.Append("\""+((DateTime)item).ToString("yyyy-MM-dd HH:mm:dd")+"\""); return; } if (item is Enum) { sb.Append("\"" + item.ToString() + "\""); return; } if (item is Type) { sb.Append("\"" + ((Type)item).FullName + "\""); return; } if (item is bool) { sb.Append(((bool)item).ToString().ToLower()); return; } if(item is ValueType) { sb.Append(item.ToString().Replace(',','.')); return; } IDictionary<string, object> bag = GetBagForObject(item.GetType(), item, complexity); SerializeItem(sb, bag, key, complexity); } internal static void SerializeDateTime(StringBuilder sb, object item = null) { sb.Append("\"" + ((DateTime)item).ToString("yyyy-MM-dd HH:mm:dd") + "\""); //var elapsed = DateTime.UtcNow - new DateTime(1970, 1, 1).ToUniversalTime(); //var epoch = (long)elapsed.TotalSeconds; //SerializeString(sb, epoch); } internal static void SerializeArray(object item, StringBuilder sb, DepotComplexity complexity = DepotComplexity.Standard) { Type type = item.GetType(); if (type.IsDefined(typeof(JsonObjectAttribute), false)) { var bag = GetBagForObject(item.GetType(), item, complexity); SerializeItem(sb, bag, null, complexity); } else { ICollection array = (ICollection)item; sb.Append("["); var count = 0; var total = array.Cast<object>().Count(); foreach (object element in array) { SerializeItem(sb, element, null, complexity); count++; if (count < total) sb.Append(","); } sb.Append("]"); } } internal static void SerializeObject(object item, StringBuilder sb, bool intAsKey = false, DepotComplexity complexity = DepotComplexity.Standard) { sb.Append("{"); IDictionary nested = (IDictionary)item; int i = 0; int count = nested.Count; foreach (DictionaryEntry entry in nested) { sb.Append("\"" + entry.Key + "\""); sb.Append(":"); object value = entry.Value; if (value is string) { SerializeString(sb, value); } else { SerializeItem(sb, entry.Value, entry.Key.ToString(), complexity); } if (i < count - 1) { sb.Append(","); } i++; } sb.Append("}"); } internal static void SerializeString(StringBuilder sb, object item) { char[] symbols = ((string)item).ToCharArray(); SerializeUnicode(sb, symbols); } internal static void SerializeUnicode(StringBuilder sb, char[] symbols) { sb.Append("\""); string[] unicodes = symbols.Select(symbol => GetUnicode(symbol)).ToArray(); foreach (var unicode in unicodes) sb.Append(unicode); sb.Append("\""); } internal static string GetUnicode(char character) { switch (character) { case '"': return @"\"""; case '/': return @"\/"; case '\\': return @"\\"; case '\b': return @"\b"; case '\f': return @"\f"; case '\n': return @"\n"; case '\r': return @"\r"; case '\t': return @"\t"; } return new string(character, 1); //var code = (int)character; //var basicLatin = code >= 32 && code <= 243; //if (basicLatin) //{ // return new string(character, 1); //} //var unicode = BaseConvert(code, _base16, 4); //return string.Concat("\\u", unicode); } internal static string BaseConvert(int input, char[] charSet, int minLength) { var sb = new StringBuilder(); var @base = charSet.Length; while (input > 0) { var index = input % @base; sb.Insert(0, new[] { charSet[index] }); input = input / @base; } while (sb.Length < minLength) { sb.Insert(0, "0"); } return sb.ToString(); } internal static IDictionary<string, object> ParseObject(IList<char> data, ref int index) { var result = InitializeBag(); index++; // Skip first token while (index < data.Count - 1) { var token = NextToken(data, ref index); switch (token) { // End Tokens case JsonToken.Unknown: // Bad Data case JsonToken.True: case JsonToken.False: case JsonToken.Null: case JsonToken.Colon: case JsonToken.RightBracket: case JsonToken.Number: throw new InvalidJsonException(string.Format( "Invalid JSON found while parsing an object at index {0}.", index )); case JsonToken.RightBrace: // End Object index++; return result; // Skip Tokens case JsonToken.Comma: index++; break; // Start Tokens case JsonToken.LeftBrace: // Start Object var @object = ParseObject(data, ref index); if (@object != null) { result.Add(string.Concat("object", result.Count), @object); } index++; break; case JsonToken.LeftBracket: // Start Array var @array = ParseArray(data, ref index); if (@array != null) { result.Add(string.Concat("array", result.Count), @array); } index++; break; case JsonToken.String: var pair = ParsePair(data, ref index); result.Add(pair.Key, pair.Value); break; default: throw new NotSupportedException("Invalid token expected."); } } return result; } internal static IEnumerable<object> ParseArray(IList<char> data, ref int index) { var result = new List<object>(); index++; // Skip first bracket while (index < data.Count - 1) { var token = NextToken(data, ref index); switch (token) { // End Tokens case JsonToken.Unknown: // Bad Data throw new InvalidJsonException(string.Format( "Invalid JSON found while parsing an array at index {0}.", index )); case JsonToken.RightBracket: // End Array index++; return result; // Skip Tokens case JsonToken.Comma: // Separator case JsonToken.RightBrace: // End Object case JsonToken.Colon: // Separator index++; break; // Value Tokens case JsonToken.LeftBrace: // Start Object var nested = ParseObject(data, ref index); result.Add(nested); break; case JsonToken.LeftBracket: // Start Array case JsonToken.String: case JsonToken.Number: case JsonToken.True: case JsonToken.False: case JsonToken.Null: var value = ParseValue(data, ref index); result.Add(value); break; default: throw new ArgumentOutOfRangeException(); } } return result; } internal static KeyValuePair<string, object> ParsePair(IList<char> data, ref int index) { var valid = true; var name = ParseString(data, ref index); if (name == null) { valid = false; } if (!ParseToken(JsonToken.Colon, data, ref index)) { valid = false; } if (!valid) { throw new InvalidJsonException(string.Format( "Invalid JSON found while parsing a value pair at index {0}.", index )); } index++; var value = ParseValue(data, ref index); return new KeyValuePair<string, object>(name, value); } internal static bool ParseToken(JsonToken token, IList<char> data, ref int index) { var nextToken = NextToken(data, ref index); return token == nextToken; } internal static string ParseString(IList<char> data, ref int index) { var symbol = data[index]; IgnoreWhitespace(data, ref index, symbol); symbol = data[++index]; // Skip first quotation var sb = new StringBuilder(); while (true) { if (index >= data.Count - 1) { return null; } switch (symbol) { case '"': // End String index++; return sb.ToString(); case '\\': // Control Character symbol = data[++index]; switch (symbol) { case '/': case '\\': case '"': sb.Append(symbol); break; case 'b': sb.Append('\b'); break; case 'f': sb.Append('\f'); break; case 'n': sb.Append('\n'); break; case 'r': sb.Append('\r'); break; case 't': sb.Append('\t'); break; case 'u': // Unicode literals if (index < data.Count - 5) { var array = data.ToArray(); var buffer = new char[4]; Array.Copy(array, index + 1, buffer, 0, 4); // http://msdn.microsoft.com/en-us/library/aa664669%28VS.71%29.aspx // http://www.yoda.arachsys.com/csharp/unicode.html // http://en.wikipedia.org/wiki/UTF-32/UCS-4 var hex = new string(buffer); var unicode = (char)Convert.ToInt32(hex, 16); sb.Append(unicode); index += 4; } else { break; } break; } break; default: sb.Append(symbol); break; } symbol = data[++index]; } } internal static object ParseValue(IList<char> data, ref int index) { var token = NextToken(data, ref index); switch (token) { // End Tokens case JsonToken.RightBracket: // Bad Data case JsonToken.RightBrace: case JsonToken.Unknown: case JsonToken.Colon: case JsonToken.Comma: throw new InvalidJsonException(string.Format( "Invalid JSON found while parsing a value at index {0}.", index )); // Value Tokens case JsonToken.LeftBrace: return ParseObject(data, ref index); case JsonToken.LeftBracket: return ParseArray(data, ref index); case JsonToken.String: return ParseString(data, ref index); case JsonToken.Number: return ParseNumber(data, ref index); case JsonToken.True: return true; case JsonToken.False: return false; case JsonToken.Null: return null; default: throw new ArgumentOutOfRangeException(); } } internal static object ParseNumber(IList<char> data, ref int index) { var symbol = data[index]; IgnoreWhitespace(data, ref index, symbol); var start = index; var length = 0; while (ParseToken(JsonToken.Number, data, ref index)) { length++; index++; } double result; var buffer = new string(data.Skip(start).Take(length).ToArray()); if (!double.TryParse(buffer, _numbers, CultureInfo.InvariantCulture, out result)) { throw new InvalidJsonException( string.Format("Value '{0}' was not a valid JSON number", buffer) ); } return result; } internal static JsonToken NextToken(IList<char> data, ref int index) { var symbol = data[index]; var token = GetTokenFromSymbol(symbol); token = IgnoreWhitespace(data, ref index, ref token, symbol); GetKeyword("true", JsonToken.True, data, ref index, ref token); GetKeyword("false", JsonToken.False, data, ref index, ref token); GetKeyword("null", JsonToken.Null, data, ref index, ref token); return token; } internal static JsonToken GetTokenFromSymbol(char symbol) { return GetTokenFromSymbol(symbol, JsonToken.Unknown); } internal static JsonToken GetTokenFromSymbol(char symbol, JsonToken token) { switch (symbol) { case '{': token = JsonToken.LeftBrace; break; case '}': token = JsonToken.RightBrace; break; case ':': token = JsonToken.Colon; break; case ',': token = JsonToken.Comma; break; case '[': token = JsonToken.LeftBracket; break; case ']': token = JsonToken.RightBracket; break; case '"': token = JsonToken.String; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': case 'e': case 'E': case '+': case '-': token = JsonToken.Number; break; } return token; } internal static void IgnoreWhitespace(IList<char> data, ref int index, char symbol) { var token = JsonToken.Unknown; IgnoreWhitespace(data, ref index, ref token, symbol); return; } internal static JsonToken IgnoreWhitespace(IList<char> data, ref int index, ref JsonToken token, char symbol) { switch (symbol) { case ' ': case '\\': case '/': case '\b': case '\f': case '\n': case '\r': case '\t': index++; token = NextToken(data, ref index); break; } return token; } internal static void GetKeyword(string word, JsonToken target, IList<char> data,ref int index, ref JsonToken result) { int buffer = data.Count - index; if (buffer < word.Length) { return; } for (var i = 0; i < word.Length; i++) { if (data[index + i] != word[i]) { return; } } result = target; index += word.Length; } } public static class DataJsonProperties { public static Dictionary<string, string[]> Registry = new Dictionary<string, string[]>() { { "System.Doors.Data.Depot.TransactionHeader", new string[] { "Context", "Content" } }, { "System.Doors.Data.Depot.TransactionMessage", new string[] { "Notice", "Content" } }, { "System.Doors.TransactionContext", new string[] { "Identity", "ContentType", "Complexity", "Echo" } }, { "System.Doors.DepotIdentity_Advanced", new string[] { "Id", "Name", "Key", "Token", "UserId", "DeptId", "Ip", "DataPlace" } }, { "System.Doors.DepotIdentity_Basic", new string[] { "UserId", "DeptId", "Token", "DataPlace", } }, { "System.Doors.DepotIdentity", new string[] { "Name", "Key", "Token", "UserId", "DeptId", "DataPlace", } }, { "System.Doors.DepotIdentity_Guide", new string[] { "Token", "UserId", "DeptId", "DataPlace" } }, { "System.Doors.Data.DataArea", new string[] { "SpaceName", "DisplayName", "Config", "State", "Areas" } }, { "System.Doors.Data.DataArea_Guide", new string[] { "SpaceName", "Areas", "Config" } }, { "System.Doors.Data.DataSpheres", new string[] { "SpheresId", "DisplayName", "Config", "State", "Spheres", "SpheresIn" } }, { "System.Doors.Data.DataSpheres_Guide", new string[] { "SpheresId", "Spheres", "SpheresIn", "Config" } }, { "System.Doors.Data.DataSphere", new string[] { "SphereId", "DisplayName", "Config", "State", "Relays", "Trellises", "SpheresIn" } }, { "System.Doors.Data.DataSphere_Guide", new string[] { "SphereId", "Trellises", "SpheresIn", "Config" } }, { "System.Doors.Data.DataTrellis", new string[] { "TrellName", "DisplayName", "Mode", "Config", "State", "Checked", "Edited", "Synced", "Saved", "Quered", "CountView", "Count", "PagingDetails", "Pylons", "PrimeKey", "EditLevel", "SimLevel", "Filter", "Sort", "Favorites", "Relaying", "TiersTotal", "SimsTotal" } }, { "System.Doors.Data.DataTrellis_Advanced", new string[] { "TrellName", "DisplayName", "Visible", "Mode", "Checked", "Edited", "Synced", "Saved", "Quered", "CountView", "Count", "Config", "IsPrime", "State", "Pylons", "PrimeKey", "EditLevel", "SimLevel", "Filter", "Sort", "PagingDetails", "Favorites", "Relaying", "TiersTotal", "SimsTotal", "EditLength", "SimLength", "MappingName", "Relays" } }, { "System.Doors.Data.DataTrellis_Basic", new string[] { "TrellName", "DisplayName", "CountView", "Config", "State", "Checked", "Edited", "Synced", "Saved", "Quered", "EditLevel", "SimLevel", "Mode", "Filter", "Sort", "PagingDetails", "Favorites", "TiersTotal", "SimsTotal" } }, { "System.Doors.Data.DataTrellis_Guide", new string[] { "TrellName", "Config" } }, { "System.Doors.Data.DataTier", new string[] { "Checked", "Index", "Page", "PageIndex", "ViewIndex", "NoId", "Edited", "Deleted", "Added", "Synced", "Saved", "Fields", "ChildJoins", "ParentJoins" } }, { "System.Doors.Data.DataField", new string[] { "Value" } }, { "System.Doors.Data.DataPylon", new string[] { "PylonId", "Ordinal", "Visible", "PylonName", "DisplayName", "DataType", "Default", "isKey", "Editable", "Revalue", "RevalOperand", "RevalType", "TotalOperand" } }, { "System.Doors.Data.FilterTerm", new string[] { "Index", "PylonName", "Operand", "Value", "Logic", "Stage", } }, { "System.Doors.Data.SortTerm", new string[] { "Index", "PylonName", "Direction" } }, { "System.Doors.DataConfig", new string[] { "Place", "DataIdx", "Path", "DepotIdx", "DataType" } }, { "System.Doors.DataConfig_Guide", new string[] { "Place", "DataIdx", "DataType" } }, { "System.Doors.DataConfig_Basic", new string[] { "Place", "DataIdx", "DepotIdx", "DataType" } }, { "System.Doors.DataConfig_Advanced", new string[] { "Place", "DataIdx", "Path", "Disk", "File", "DepotIdx", "DataType" } }, { "System.Doors.DataState", new string[] { "Edited", "Deleted", "Added", "Synced", "Canceled", "Saved", "Quered", } }, { "System.Doors.Data.DataPageDetails", new string[] { "Page", "PageActive", "CachedPages", "PageCount", "PageSize", } }, { "System.Doors.Data.DataRelaying", new string[] { "ChildRelays", "ParentRelays" } }, { "System.Doors.Data.DataRelay", new string[] { "RelayName", "Parent", "Child", } }, { "System.Doors.Data.DataRelayMember", new string[] { "TrellName", "RelayKeys" } } }; public static NumberFormatInfo JsonNumberInfo() { System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo(); nfi.NumberDecimalSeparator = "."; return nfi; } public static PropertyInfo[] GetJsonProperties(this Type type, DepotComplexity complexity = DepotComplexity.Standard) { string name = type.FullName; string cname = ""; if (complexity != DepotComplexity.Standard) cname = name + "_" + complexity.ToString(); else cname = name; if (Registry.ContainsKey(cname)) return Registry[cname].Select(t => type.GetProperty(t)).ToArray(); else if (Registry.ContainsKey(name)) return Registry[name].Select(t => type.GetProperty(t)).ToArray(); else return null; } public static PropertyInfo[] GetJsonProperties<T>(DepotComplexity complexity = DepotComplexity.Standard) { Type type = typeof(T); string name = type.FullName; string cname = ""; if (complexity != DepotComplexity.Standard) cname = name + "_" + complexity.ToString(); else cname = name; if (Registry.ContainsKey(cname)) return Registry[cname].Select(t => type.GetProperty(t)).ToArray(); else if (Registry.ContainsKey(name)) return Registry[name].Select(t => type.GetProperty(t)).ToArray(); else return null; } } }
38.729462
153
0.411385
[ "MIT" ]
undersoft-org/NET.Undersoft.Doors.Fwk.Devel
Undersoft.Doors.Fwk/Data/Extensions/DataJson.cs
54,688
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace ClosedXML.Excel { /// <summary> /// Engine for ranges consolidation. Supports IXLRanges including ranges from either one or multiple worksheets. /// </summary> internal class XLRangeConsolidationEngine { #region Public Constructors public XLRangeConsolidationEngine(IXLRanges ranges) { if (ranges == null) throw new ArgumentNullException(nameof(ranges)); _allRanges = ranges; } #endregion Public Constructors #region Public Methods public IXLRanges Consolidate() { if (!_allRanges.Any()) return _allRanges; var worksheets = _allRanges.Select(r => r.Worksheet).Distinct().OrderBy(ws => ws.Position); IXLRanges retVal = new XLRanges(); foreach (var ws in worksheets) { var matrix = new XLRangeConsolidationMatrix(ws, _allRanges.Where(r => r.Worksheet == ws)); var consRanges = matrix.GetConsolidatedRanges(); foreach (var consRange in consRanges) { retVal.Add(consRange); } } return retVal; } #endregion Public Methods #region Private Fields private readonly IXLRanges _allRanges; #endregion Private Fields #region Private Classes /// <summary> /// Class representing the area covering ranges to be consolidated as a set of bit matrices. Does all the dirty job /// of ranges consolidation. /// </summary> private class XLRangeConsolidationMatrix { #region Public Constructors /// <summary> /// Constructor. /// </summary> /// <param name="worksheet">Current worksheet.</param> /// <param name="ranges">Ranges to be consolidated. They are expected to belong to the current worksheet, no check is performed.</param> public XLRangeConsolidationMatrix(IXLWorksheet worksheet, IEnumerable<IXLRange> ranges) { _worksheet = worksheet; PrepareBitMatrix(ranges); FillBitMatrix(ranges); } #endregion Public Constructors #region Public Methods /// <summary> /// Get consolidated ranges equivalent to the input ones. /// </summary> public IEnumerable<IXLRange> GetConsolidatedRanges() { var rowNumbers = _bitMatrix.Keys.OrderBy(k => k).ToArray(); for (int i = 0; i < rowNumbers.Length; i++) { var startRow = rowNumbers[i]; var startings = GetRangesBoundariesStartingByRow(_bitMatrix[startRow]); foreach (var starting in startings) { int j = i + 1; while (j < rowNumbers.Length && RowIncludesRange(_bitMatrix[rowNumbers[j]], starting)) j++; var endRow = rowNumbers[j - 1]; var startColumn = starting.Item1 + _minColumn - 1; var endColumn = starting.Item2 + _minColumn - 1; yield return _worksheet.Range(startRow, startColumn, endRow, endColumn); while (j > i) { ClearRangeInRow(_bitMatrix[rowNumbers[j - 1]], starting); j--; } } } } #endregion Public Methods #region Private Fields private readonly IXLWorksheet _worksheet; private Dictionary<int, BitArray> _bitMatrix; private int _maxColumn = 0; private int _minColumn = XLHelper.MaxColumnNumber + 1; #endregion Private Fields #region Private Methods private void AddToBitMatrix(IXLRangeAddress rangeAddress) { var rows = _bitMatrix.Keys .Where(k => k >= rangeAddress.FirstAddress.RowNumber && k <= rangeAddress.LastAddress.RowNumber); var minIndex = rangeAddress.FirstAddress.ColumnNumber - _minColumn + 1; var maxIndex = rangeAddress.LastAddress.ColumnNumber - _minColumn + 1; foreach (var rowNum in rows) { for (int i = minIndex; i <= maxIndex; i++) { _bitMatrix[rowNum][i] = true; } } } private void ClearRangeInRow(BitArray rowArray, Tuple<int, int> rangeBoundaries) { for (int i = rangeBoundaries.Item1; i <= rangeBoundaries.Item2; i++) { rowArray[i] = false; } } private void FillBitMatrix(IEnumerable<IXLRange> ranges) { foreach (var range in ranges) { AddToBitMatrix(range.RangeAddress); } System.Diagnostics.Debug.Assert( _bitMatrix.Values.All(r => r[0] == false && r[r.Length - 1] == false)); } private IEnumerable<Tuple<int, int>> GetRangesBoundariesStartingByRow(BitArray rowArray) { int startIdx = 0; for (int i = 1; i < rowArray.Length - 1; i++) { if (!rowArray[i - 1] && rowArray[i]) startIdx = i; if (rowArray[i] && !rowArray[i + 1]) yield return new Tuple<int, int>(startIdx, i); } } private void PrepareBitMatrix(IEnumerable<IXLRange> ranges) { _bitMatrix = new Dictionary<int, BitArray>(); foreach (var range in ranges) { var address = range.RangeAddress; _minColumn = (_minColumn <= address.FirstAddress.ColumnNumber) ? _minColumn : address.FirstAddress.ColumnNumber; _maxColumn = (_maxColumn >= address.LastAddress.ColumnNumber) ? _maxColumn : address.LastAddress.ColumnNumber; if (!_bitMatrix.ContainsKey(address.FirstAddress.RowNumber)) _bitMatrix.Add(address.FirstAddress.RowNumber, null); if (!_bitMatrix.ContainsKey(address.LastAddress.RowNumber)) _bitMatrix.Add(address.LastAddress.RowNumber, null); } var keys = _bitMatrix.Keys.ToList(); foreach (var rowNum in keys) { _bitMatrix[rowNum] = new BitArray(_maxColumn - _minColumn + 3, false); } } private bool RowIncludesRange(BitArray rowArray, Tuple<int, int> rangeBoundaries) { for (int i = rangeBoundaries.Item1; i <= rangeBoundaries.Item2; i++) { if (!rowArray[i]) return false; } return true; } #endregion Private Methods } #endregion Private Classes } }
36.296296
149
0.492474
[ "MIT" ]
Gallardo13/ClosedXML
ClosedXML/Excel/Ranges/XLRangeConsolidationEngine.cs
7,625
C#
//------------------------------------------------- // NGUI: Next-Gen UI kit // Copyright © 2011-2020 Tasharen Entertainment Inc //------------------------------------------------- using UnityEngine; using UnityEditor; [CustomEditor(typeof(UIWrapContent), true)] public class UIWrapContentEditor : Editor { public override void OnInspectorGUI () { GUILayout.Space(6f); NGUIEditorTools.SetLabelWidth(90f); string fieldName = "Item Size"; string error = null; UIScrollView sv = null; if (!serializedObject.isEditingMultipleObjects) { UIWrapContent list = target as UIWrapContent; sv = NGUITools.FindInParents<UIScrollView>(list.gameObject); if (sv == null) { error = "UIWrappedList needs a Scroll View on its parent in order to work properly"; } else if (sv.movement == UIScrollView.Movement.Horizontal) fieldName = "Item Width"; else if (sv.movement == UIScrollView.Movement.Vertical) fieldName = "Item Height"; else { error = "Scroll View needs to be using Horizontal or Vertical movement"; } } serializedObject.Update(); GUILayout.BeginHorizontal(); NGUIEditorTools.DrawProperty(fieldName, serializedObject, "itemSize", GUILayout.Width(130f)); GUILayout.Label("pixels"); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); SerializedProperty sp1 = NGUIEditorTools.DrawProperty("Range Limit", serializedObject, "minIndex", GUILayout.Width(130f)); NGUIEditorTools.SetLabelWidth(20f); SerializedProperty sp2 = NGUIEditorTools.DrawProperty("to", serializedObject, "maxIndex", GUILayout.Width(60f)); NGUIEditorTools.SetLabelWidth(90f); if (sp1.intValue == sp2.intValue) GUILayout.Label("unlimited"); GUILayout.EndHorizontal(); serializedObject.DrawProperty("hideInactive"); NGUIEditorTools.DrawProperty("Cull Content", serializedObject, "cullContent"); if (!string.IsNullOrEmpty(error)) { EditorGUILayout.HelpBox(error, MessageType.Error); if (sv != null && GUILayout.Button("Select the Scroll View")) Selection.activeGameObject = sv.gameObject; } serializedObject.ApplyModifiedProperties(); if (sp1.intValue != sp2.intValue) { if ((target as UIWrapContent).GetComponent<UICenterOnChild>() != null) { EditorGUILayout.HelpBox("Limiting indices doesn't play well with UICenterOnChild. You should either not limit the indices, or not use UICenterOnChild.", MessageType.Warning); } } } }
32.824324
178
0.705228
[ "MIT" ]
whilin/crazybox_unity_baseframework
Assets/NGUI/Scripts/Editor/UIWrapContentEditor.cs
2,430
C#
// Copyright (c) 2020, Phoenix Contact GmbH & Co. KG // Licensed under the Apache License, Version 2.0 using System; namespace Moryx.Modules { /// <summary> /// Attribute to decorate a <see cref="IPlugin"/> to receive a certain config type /// </summary> [AttributeUsage(AttributeTargets.Class)] public class ExpectedConfigAttribute : Attribute { /// <summary> /// Config type expected by this <see cref="IPlugin"/> /// </summary> public Type ExcpectedConfigType { get; } // TODO: Rename to ExpectedConfigType in the next major /// <summary> /// State that this <see cref="IPlugin"/> requires config instances of the given type /// </summary> public ExpectedConfigAttribute(Type configType) { ExcpectedConfigType = configType; } } }
30.571429
104
0.627336
[ "Apache-2.0" ]
1nf0rmagician/MORYX-Core
src/Moryx/Modules/ExpectedConfigAttribute.cs
856
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.Collections.Generic; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.TestUtilities; using Microsoft.Extensions.DependencyInjection; using Xunit; namespace Microsoft.EntityFrameworkCore { public abstract class SaveChangesInterceptionInMemoryTestBase : SaveChangesInterceptionTestBase { protected SaveChangesInterceptionInMemoryTestBase(InterceptionInMemoryFixtureBase fixture) : base(fixture) { } protected override bool SupportsOptimisticConcurrency => false; public abstract class InterceptionInMemoryFixtureBase : InterceptionFixtureBase { protected override string StoreName => "SaveChangesInterception"; protected override ITestStoreFactory TestStoreFactory => InMemoryTestStoreFactory.Instance; protected override IServiceCollection InjectInterceptors( IServiceCollection serviceCollection, IEnumerable<IInterceptor> injectedInterceptors) => base.InjectInterceptors(serviceCollection.AddEntityFrameworkInMemoryDatabase(), injectedInterceptors); public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder) => base.AddOptions(builder).ConfigureWarnings(c => c.Ignore(InMemoryEventId.TransactionIgnoredWarning)); } public class SaveChangesInterceptionInMemoryTest : SaveChangesInterceptionInMemoryTestBase, IClassFixture<SaveChangesInterceptionInMemoryTest.InterceptionInMemoryFixture> { public SaveChangesInterceptionInMemoryTest(InterceptionInMemoryFixture fixture) : base(fixture) { } public class InterceptionInMemoryFixture : InterceptionInMemoryFixtureBase { protected override bool ShouldSubscribeToDiagnosticListener => false; } } public class SaveChangesInterceptionWithDiagnosticsInMemoryTest : SaveChangesInterceptionInMemoryTestBase, IClassFixture<SaveChangesInterceptionWithDiagnosticsInMemoryTest.InterceptionInMemoryFixture> { public SaveChangesInterceptionWithDiagnosticsInMemoryTest(InterceptionInMemoryFixture fixture) : base(fixture) { } public class InterceptionInMemoryFixture : InterceptionInMemoryFixtureBase { protected override bool ShouldSubscribeToDiagnosticListener => true; } } } }
39.535211
133
0.693979
[ "MIT" ]
CameronAavik/efcore
test/EFCore.InMemory.FunctionalTests/InterceptionInMemoryTest.cs
2,807
C#
using System; using System.Collections.Generic; using System.Linq; using QuGo.Core; using QuGo.Core.Caching; using QuGo.Core.Data; using QuGo.Core.Domain.Common; using QuGo.Core.Domain.Users; using QuGo.Core.Domain.Logging; using QuGo.Data; namespace QuGo.Services.Logging { /// <summary> /// user activity service /// </summary> public class userActivityService : IUserActivityService { #region Constants /// <summary> /// Key for caching /// </summary> private const string ACTIVITYTYPE_ALL_KEY = "QuGo.activitytype.all"; /// <summary> /// Key pattern to clear cache /// </summary> private const string ACTIVITYTYPE_PATTERN_KEY = "QuGo.activitytype."; #endregion #region Fields /// <summary> /// Cache manager /// </summary> private readonly ICacheManager _cacheManager; private readonly IRepository<ActivityLog> _activityLogRepository; private readonly IRepository<ActivityLogType> _activityLogTypeRepository; private readonly IWorkContext _workContext; private readonly IDbContext _dbContext; private readonly IDataProvider _dataProvider; private readonly CommonSettings _commonSettings; private readonly IWebHelper _webHelper; #endregion #region Ctor /// <summary> /// Ctor /// </summary> /// <param name="cacheManager">Cache manager</param> /// <param name="activityLogRepository">Activity log repository</param> /// <param name="activityLogTypeRepository">Activity log type repository</param> /// <param name="workContext">Work context</param> /// <param name="dbContext">DB context</param>> /// <param name="dataProvider">WeData provider</param> /// <param name="commonSettings">Common settings</param> /// <param name="webHelper">Web helper</param> public userActivityService(ICacheManager cacheManager, IRepository<ActivityLog> activityLogRepository, IRepository<ActivityLogType> activityLogTypeRepository, IWorkContext workContext, IDbContext dbContext, IDataProvider dataProvider, CommonSettings commonSettings, IWebHelper webHelper) { this._cacheManager = cacheManager; this._activityLogRepository = activityLogRepository; this._activityLogTypeRepository = activityLogTypeRepository; this._workContext = workContext; this._dbContext = dbContext; this._dataProvider = dataProvider; this._commonSettings = commonSettings; this._webHelper = webHelper; } #endregion #region Nested classes [Serializable] public class ActivityLogTypeForCaching { public int Id { get; set; } public string SystemKeyword { get; set; } public string Name { get; set; } public bool Enabled { get; set; } } #endregion #region Utitlies /// <summary> /// Gets all activity log types (class for caching) /// </summary> /// <returns>Activity log types</returns> protected virtual IList<ActivityLogTypeForCaching> GetAllActivityTypesCached() { //cache string key = string.Format(ACTIVITYTYPE_ALL_KEY); return _cacheManager.Get(key, () => { var result = new List<ActivityLogTypeForCaching>(); var activityLogTypes = GetAllActivityTypes(); foreach (var alt in activityLogTypes) { var altForCaching = new ActivityLogTypeForCaching { Id = alt.Id, SystemKeyword = alt.SystemKeyword, Name = alt.Name, Enabled = alt.Enabled }; result.Add(altForCaching); } return result; }); } #endregion #region Methods /// <summary> /// Inserts an activity log type item /// </summary> /// <param name="activityLogType">Activity log type item</param> public virtual void InsertActivityType(ActivityLogType activityLogType) { if (activityLogType == null) throw new ArgumentNullException("activityLogType"); _activityLogTypeRepository.Insert(activityLogType); _cacheManager.RemoveByPattern(ACTIVITYTYPE_PATTERN_KEY); } /// <summary> /// Updates an activity log type item /// </summary> /// <param name="activityLogType">Activity log type item</param> public virtual void UpdateActivityType(ActivityLogType activityLogType) { if (activityLogType == null) throw new ArgumentNullException("activityLogType"); _activityLogTypeRepository.Update(activityLogType); _cacheManager.RemoveByPattern(ACTIVITYTYPE_PATTERN_KEY); } /// <summary> /// Deletes an activity log type item /// </summary> /// <param name="activityLogType">Activity log type</param> public virtual void DeleteActivityType(ActivityLogType activityLogType) { if (activityLogType == null) throw new ArgumentNullException("activityLogType"); _activityLogTypeRepository.Delete(activityLogType); _cacheManager.RemoveByPattern(ACTIVITYTYPE_PATTERN_KEY); } /// <summary> /// Gets all activity log type items /// </summary> /// <returns>Activity log type items</returns> public virtual IList<ActivityLogType> GetAllActivityTypes() { var query = from alt in _activityLogTypeRepository.Table orderby alt.Name select alt; var activityLogTypes = query.ToList(); return activityLogTypes; } /// <summary> /// Gets an activity log type item /// </summary> /// <param name="activityLogTypeId">Activity log type identifier</param> /// <returns>Activity log type item</returns> public virtual ActivityLogType GetActivityTypeById(int activityLogTypeId) { if (activityLogTypeId == 0) return null; return _activityLogTypeRepository.GetById(activityLogTypeId); } /// <summary> /// Inserts an activity log item /// </summary> /// <param name="systemKeyword">The system keyword</param> /// <param name="comment">The activity comment</param> /// <param name="commentParams">The activity comment parameters for string.Format() function.</param> /// <returns>Activity log item</returns> public virtual ActivityLog InsertActivity(string systemKeyword, string comment, params object[] commentParams) { return InsertActivity(_workContext.CurrentUser, systemKeyword, comment, commentParams); } /// <summary> /// Inserts an activity log item /// </summary> /// <param name="user">The user</param> /// <param name="systemKeyword">The system keyword</param> /// <param name="comment">The activity comment</param> /// <param name="commentParams">The activity comment parameters for string.Format() function.</param> /// <returns>Activity log item</returns> public virtual ActivityLog InsertActivity(User user, string systemKeyword, string comment, params object[] commentParams) { if (user == null) return null; var activityTypes = GetAllActivityTypesCached(); var activityType = activityTypes.ToList().Find(at => at.SystemKeyword == systemKeyword); if (activityType == null || !activityType.Enabled) return null; comment = CommonHelper.EnsureNotNull(comment); comment = string.Format(comment, commentParams); comment = CommonHelper.EnsureMaximumLength(comment, 4000); var activity = new ActivityLog(); activity.ActivityLogTypeId = activityType.Id; activity.User = user; activity.Comment = comment; activity.CreatedOnUtc = DateTime.UtcNow; activity.IpAddress = _webHelper.GetCurrentIpAddress(); _activityLogRepository.Insert(activity); return activity; } /// <summary> /// Deletes an activity log item /// </summary> /// <param name="activityLog">Activity log type</param> public virtual void DeleteActivity(ActivityLog activityLog) { if (activityLog == null) throw new ArgumentNullException("activityLog"); _activityLogRepository.Delete(activityLog); } /// <summary> /// Gets all activity log items /// </summary> /// <param name="createdOnFrom">Log item creation from; null to load all activities</param> /// <param name="createdOnTo">Log item creation to; null to load all activities</param> /// <param name="userId">User identifier; null to load all activities</param> /// <param name="activityLogTypeId">Activity log type identifier</param> /// <param name="pageIndex">Page index</param> /// <param name="pageSize">Page size</param> /// <param name="ipAddress">IP address; null or empty to load all activities</param> /// <returns>Activity log items</returns> public virtual IPagedList<ActivityLog> GetAllActivities(DateTime? createdOnFrom = null, DateTime? createdOnTo = null, int? userId = null, int activityLogTypeId = 0, int pageIndex = 0, int pageSize = int.MaxValue, string ipAddress = null) { var query = _activityLogRepository.Table; if(!String.IsNullOrEmpty(ipAddress)) query = query.Where(al => al.IpAddress.Contains(ipAddress)); if (createdOnFrom.HasValue) query = query.Where(al => createdOnFrom.Value <= al.CreatedOnUtc); if (createdOnTo.HasValue) query = query.Where(al => createdOnTo.Value >= al.CreatedOnUtc); if (activityLogTypeId > 0) query = query.Where(al => activityLogTypeId == al.ActivityLogTypeId); if (userId.HasValue) query = query.Where(al => userId.Value == al.UserId); query = query.OrderByDescending(al => al.CreatedOnUtc); var activityLog = new PagedList<ActivityLog>(query, pageIndex, pageSize); return activityLog; } /// <summary> /// Gets an activity log item /// </summary> /// <param name="activityLogId">Activity log identifier</param> /// <returns>Activity log item</returns> public virtual ActivityLog GetActivityById(int activityLogId) { if (activityLogId == 0) return null; return _activityLogRepository.GetById(activityLogId); } /// <summary> /// Clears activity log /// </summary> public virtual void ClearAllActivities() { if (_commonSettings.UseStoredProceduresIfSupported && _dataProvider.StoredProceduredSupported) { //although it's not a stored procedure we use it to ensure that a database supports them //we cannot wait until EF team has it implemented - http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/1015357-batch-cud-support //do all databases support "Truncate command"? string activityLogTableName = _dbContext.GetTableName<ActivityLog>(); _dbContext.ExecuteSqlCommand(String.Format("TRUNCATE TABLE [{0}]", activityLogTableName)); } else { var activityLog = _activityLogRepository.Table.ToList(); foreach (var activityLogItem in activityLog) _activityLogRepository.Delete(activityLogItem); } } #endregion } }
38.67284
181
0.60016
[ "MIT" ]
pcurich/QuGo
QubicGo/Libraries/QuGo.Services/Logging/CustomerActivityService.cs
12,532
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using AoE2NetDesktop; namespace LibAoE2net.Tests { [TestClass()] public class PlayerExtTests { [TestMethod()] [DataRow(1, 2, Diplomacy.Enemy)] [DataRow(1, 3, Diplomacy.Ally)] [DataRow(null, 2, Diplomacy.Neutral)] [DataRow(1, null, Diplomacy.Neutral)] [DataRow(null, null, Diplomacy.Neutral)] public void CheckDiplomacyTest(int? p1Color, int? p2Color, Diplomacy expDiplomacy) { // Arrange var player1 = new Player() { Color = p1Color }; var player2 = new Player() { Color = p2Color }; // Act var actVal = player1.CheckDiplomacy(player2); // Assert Assert.AreEqual(expDiplomacy, actVal); } } }
30.296296
90
0.58802
[ "MIT" ]
teshiba/AoE2.netDesktop
AoE2.netDesktopTests/LibAoE2Net/Functions/PlayerExtTests.cs
820
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Bot.Builder.BotFramework; using Microsoft.Bot.Builder.Core.Extensions; using Microsoft.Bot.Builder.Integration.AspNet.Core; using Microsoft.Bot.Builder.TraceExtensions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace AspNetCore_EchoBot_With_State { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Bind appsettings.json values to a class that can be injected into Index.cshtml services.Configure<ApplicationConfiguration>(Configuration); services.AddMvc(); services.AddBot<EchoBot>(options => { options.CredentialProvider = new ConfigurationCredentialProvider(Configuration); // The CatchExceptionMiddleware provides a top-level exception handler for your bot. // Any exceptions thrown by other Middleware, or by your OnTurn method, will be // caught here. To facillitate debugging, the exception is sent out, via Trace, // to the emulator. Trace activities are NOT displayed to users, so in addition // an "Ooops" message is sent. options.Middleware.Add(new CatchExceptionMiddleware<Exception>(async (context, exception) => { await context.TraceActivity("EchoBot Exception", exception); await context.SendActivity("Sorry, it looks like something went wrong!"); })); // The Memory Storage used here is for local bot debugging only. When the bot // is restarted, anything stored in memory will be gone. IStorage dataStore = new MemoryStorage(); // The File data store, shown here, is suitable for bots that run on // a single machine and need durable state across application restarts. // IStorage dataStore = new FileStorage(System.IO.Path.GetTempPath()); // For production bots use the Azure Table Store, Azure Blob, or // Azure CosmosDB storage provides, as seen below. To include any of // the Azure based storage providers, add the Microsoft.Bot.Builder.Azure // Nuget package to your solution. That package is found at: // https://www.nuget.org/packages/Microsoft.Bot.Builder.Azure/ // IStorage dataStore = new Microsoft.Bot.Builder.Azure.AzureTableStorage("AzureTablesConnectionString", "TableName"); // IStorage dataStore = new Microsoft.Bot.Builder.Azure.AzureBlobStorage("AzureBlobConnectionString", "containerName"); options.Middleware.Add(new ConversationState<EchoState>(dataStore)); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); app.UseDefaultFiles() .UseStaticFiles() .UseBotFramework(); } } // This class is used to retrieve strings from appsettings.json on demand public class ApplicationConfiguration { public string MicrosoftAppId { get; set; } public string MicrosoftAppPassword { get; set; } } }
45.63
135
0.641683
[ "MIT" ]
APiZFiBlockChain4/botbuilder-dotnet
samples-final/3.AspNetCore-EchoBot-With-State/Startup.cs
4,565
C#
using Xml; namespace Svg { [Element("animateColor")] public class SvgAnimateColor : SvgAnimationElement, ISvgCommonAttributes, ISvgPresentationAttributes, ISvgTestsAttributes, ISvgResourcesAttributes, ISvgXLinkAttributes, ISvgAnimationEventAttributes, ISvgAnimationAttributeTargetAttributes, ISvgAnimationTimingAttributes, ISvgAnimationValueAttributes, ISvgAnimationAdditionAttributes { } }
24.45
55
0.705521
[ "MIT" ]
punker76/Svg.Skia
src/SvgXml.Svg/Animation/SvgAnimateColor.cs
491
C#
using Microsoft.Identity.Client; using Microsoft.PowerBI.Api; using Microsoft.Rest; using System; using System.Management.Automation; using System.Security; namespace PsPowerBi { [Cmdlet(VerbsCommunications.Connect, "Service", DefaultParameterSetName = PARAMETERSET_PROPERTIES_INTEGRATED)] [OutputType(typeof(PowerBIClient))] public class ConnectServiceCommand : PSCmdlet { #region ParameterSets private const string PARAMETERSET_PROPERTIES_INTEGRATED = "Properties_IntegratedSecurity"; private const string PARAMETERSET_PROPERTIES_INTERACTIVE = "Properties_InteractiveAuthentication"; private const string PARAMETERSET_PROPERTIES_CREDENTIAL = "Properties_Credential"; #endregion internal static PowerBIClient SessionConnection { get; set; } [Parameter(Mandatory = true)] [ValidateNotNullOrEmpty()] public Guid ClientId { get; set; } [Parameter(Mandatory = true)] [ValidateNotNullOrEmpty()] public Guid TenantId { get; set; } [Parameter( ParameterSetName = PARAMETERSET_PROPERTIES_CREDENTIAL, Mandatory = true, ValueFromPipelineByPropertyName = true )] [ValidateNotNullOrEmpty()] public string Username { get; set; } [Parameter( ParameterSetName = PARAMETERSET_PROPERTIES_CREDENTIAL, Mandatory = true, ValueFromPipelineByPropertyName = true )] [ValidateNotNullOrEmpty()] public SecureString Password { get; set; } [Parameter( ParameterSetName = PARAMETERSET_PROPERTIES_INTERACTIVE, Mandatory = true )] public SwitchParameter InteractiveAuthentication { get; set; } protected override void ProcessRecord() { base.ProcessRecord(); var publicClientApp = PublicClientApplicationBuilder .Create(ClientId.ToString()) .WithAuthority(AzureCloudInstance.AzurePublic, TenantId) .WithDefaultRedirectUri() .Build(); AuthenticationResult authenticationResult = null; var scopes = new[] { "https://analysis.windows.net/powerbi/api/.default" }; switch(ParameterSetName) { case PARAMETERSET_PROPERTIES_CREDENTIAL: authenticationResult = publicClientApp .AcquireTokenByUsernamePassword( scopes: scopes, username: Username, password: Password ).ExecuteAsync().Result; break; case PARAMETERSET_PROPERTIES_INTEGRATED: authenticationResult = publicClientApp .AcquireTokenByIntegratedWindowsAuth( scopes: scopes ).ExecuteAsync().Result; break; case PARAMETERSET_PROPERTIES_INTERACTIVE: authenticationResult = publicClientApp .AcquireTokenInteractive( scopes: scopes ).ExecuteAsync().Result; break; default: throw new NotSupportedException($"Parameterset {ParameterSetName} is not supported."); } var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer"); SessionConnection = new PowerBIClient(new Uri("https://api.powerbi.com/"), tokenCredentials); WriteVerbose("Connected to Power BI"); WriteObject(SessionConnection); } } }
37.07767
115
0.590992
[ "MIT" ]
abbgrade/PsPowerBi
src/PsPowerBi/ConnectServiceCommand.cs
3,821
C#
using HarmonyLib; using IPA.Utilities; namespace MappingExtensions.HarmonyPatches { [HarmonyPatch(typeof(ObstacleData), nameof(ObstacleData.Mirror))] internal class ObstacleDataMirror { private static void Prefix(ObstacleData __instance, out int __state) { __state = __instance.lineIndex; } private static void Postfix(ObstacleData __instance, int __state) { bool precisionWidth = __instance.width >= 1000 || __instance.width <= -1000; if (__state is <= 3 and >= 0 && !precisionWidth) return; if (__state is >= 1000 or <= -1000 || precisionWidth) // precision lineIndex { int newIndex = __state; switch (newIndex) { case <= -1000: // normalize index values, we'll fix them later newIndex += 1000; break; case >= 1000: newIndex += -1000; break; default: newIndex *= 1000; // convert lineIndex to precision if not already break; } newIndex = (newIndex - 2000) * -1 + 2000; //flip lineIndex int newWidth = __instance.width; // normalize wall width if (newWidth < 1000 && newWidth > -1000) { newWidth *= 1000; } else { if(newWidth >= 1000) newWidth -= 1000; if (newWidth <= -1000) newWidth += 1000; } newIndex -= newWidth; if (newIndex < 0) // this is where we fix them { newIndex -= 1000; } else { newIndex += 1000; } __instance.SetProperty("lineIndex", newIndex); } else // state > -1000 || state < 1000 assumes no precision width { int mirrorLane = (__state - 2) * -1 + 2; // flip lineIndex __instance.SetProperty("lineIndex", mirrorLane - __instance.width); // adjust for wall width } } } }
35.38806
108
0.449599
[ "MIT" ]
Meivyn/MappingExtensions
MappingExtensions/HarmonyPatches/ObstacleData.cs
2,371
C#
using System; using System.ComponentModel.DataAnnotations; namespace TerribleBankInc.Models.ViewModels { public class ClientViewModel { public int ID { get; set; } [Required] public string FirstName { get; set; } [Required] public string LastName { get; set; } [Required] public string Address { get; set; } [Required] public string PhoneNumber { get; set; } [Required] public string Email { get; set; } [Required] public DateTime DateOfBirth { get; set; } } }
26.272727
49
0.593426
[ "MIT" ]
ecraciun/TerribleBankInc
src/TerribleBankInc/Models/ViewModels/ClientViewModel.cs
580
C#
//------------------------------------------------------------------------------ // <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. //------------------------------------------------------------------------------ namespace EliteQuant { public class Duration : global::System.IDisposable { private global::System.Runtime.InteropServices.HandleRef swigCPtr; protected bool swigCMemOwn; internal Duration(global::System.IntPtr cPtr, bool cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Duration obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } ~Duration() { Dispose(); } public virtual void Dispose() { lock(this) { if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; NQuantLibcPINVOKE.delete_Duration(swigCPtr); } swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } global::System.GC.SuppressFinalize(this); } } public Duration() : this(NQuantLibcPINVOKE.new_Duration(), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } public enum Type { Simple, Macaulay, Modified } } }
30.035714
129
0.63258
[ "Apache-2.0" ]
qg0/EliteQuant_Excel
SwigConversionLayer/csharp/Duration.cs
1,682
C#
/////////////////////////////////////////////////////////////////////////////// // MessageEvents.cs - native Windows message handling for WintabDN // // This code in this file is based on the example given at: // http://msdn.microsoft.com/en-us/magazine/cc163417.aspx // by Steven Toub. // // Copyright (c) 2010, Wacom Technology Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. /////////////////////////////////////////////////////////////////////////////// using System; using System.Threading; using System.Windows.Forms; using System.ComponentModel; using System.Collections.Generic; namespace WintabDN { /// <summary> /// Support for registering a Native Windows message with MessageEvents class. /// </summary> public class MessageReceivedEventArgs : EventArgs { private readonly Message _message; /// <summary> /// MessageReceivedEventArgs constructor. /// </summary> /// <param name="message">Native windows message to be registered.</param> public MessageReceivedEventArgs(Message message) { _message = message; } /// <summary> /// Return native Windows message handled by this object. /// </summary> public Message Message { get { return _message; } } } /// <summary> /// Windows native message handler, to provide support for detecting and /// responding to Wintab messages. /// </summary> public static class MessageEvents { private static object _lock = new object(); private static MessageWindow _window; private static IntPtr _windowHandle; private static SynchronizationContext _context; /// <summary> /// MessageEvents delegate. /// </summary> public static event EventHandler<MessageReceivedEventArgs> MessageReceived; /// <summary> /// Registers to receive the specified native Windows message. /// </summary> /// <param name="message">Native Windows message to watch for.</param> public static void WatchMessage(int message) { EnsureInitialized(); _window.RegisterEventForMessage(message); } /// <summary> /// Returns the MessageEvents native Windows handle. /// </summary> public static IntPtr WindowHandle { get { EnsureInitialized(); return _windowHandle; } } private static void EnsureInitialized() { lock (_lock) { if (_window == null) { _context = AsyncOperationManager.SynchronizationContext; using (ManualResetEvent mre = new ManualResetEvent(false)) { Thread t = new Thread((ThreadStart)delegate { _window = new MessageWindow(); _windowHandle = _window.Handle; mre.Set(); Application.Run(); }); t.Name = "MessageEvents message loop"; t.IsBackground = true; t.Start(); mre.WaitOne(); } } } } private class MessageWindow : Form { private ReaderWriterLock _lock = new ReaderWriterLock(); private Dictionary<int, bool> _messageSet = new Dictionary<int, bool>(); public void RegisterEventForMessage(int messageID) { _lock.AcquireWriterLock(Timeout.Infinite); _messageSet[messageID] = true; _lock.ReleaseWriterLock(); } protected override void WndProc(ref Message m) { _lock.AcquireReaderLock(Timeout.Infinite); bool handleMessage = _messageSet.ContainsKey(m.Msg); _lock.ReleaseReaderLock(); if (handleMessage) { MessageEvents._context.Post(delegate(object state) { EventHandler<MessageReceivedEventArgs> handler = MessageEvents.MessageReceived; if (handler != null) handler(null, new MessageReceivedEventArgs((Message)state)); }, m); } base.WndProc(ref m); } } } }
36.885135
105
0.564939
[ "MIT" ]
Bgoon/GK
GKit/GKit/Base/Input/TabletInput/WintabDN/MessageEvents.cs
5,461
C#
/* * Copyright 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 sagemaker-2017-07-24.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.SageMaker.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.SageMaker.Model.Internal.MarshallTransformations { /// <summary> /// TrialComponentStatus Marshaller /// </summary> public class TrialComponentStatusMarshaller : IRequestMarshaller<TrialComponentStatus, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(TrialComponentStatus requestObject, JsonMarshallerContext context) { if(requestObject.IsSetMessage()) { context.Writer.WritePropertyName("Message"); context.Writer.Write(requestObject.Message); } if(requestObject.IsSetPrimaryStatus()) { context.Writer.WritePropertyName("PrimaryStatus"); context.Writer.Write(requestObject.PrimaryStatus); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static TrialComponentStatusMarshaller Instance = new TrialComponentStatusMarshaller(); } }
34.514706
115
0.657861
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/SageMaker/Generated/Model/Internal/MarshallTransformations/TrialComponentStatusMarshaller.cs
2,347
C#
#if !NETSTANDARD13 /* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloudtrail-2013-11-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Text; using System.Collections; using System.Threading; using System.Threading.Tasks; using Amazon.Runtime; namespace Amazon.CloudTrail.Model { /// <summary> /// Base class for ListTrails paginators. /// </summary> internal sealed partial class ListTrailsPaginator : IPaginator<ListTrailsResponse>, IListTrailsPaginator { private readonly IAmazonCloudTrail _client; private readonly ListTrailsRequest _request; private int _isPaginatorInUse = 0; /// <summary> /// Enumerable containing all full responses for the operation /// </summary> public IPaginatedEnumerable<ListTrailsResponse> Responses => new PaginatedResponse<ListTrailsResponse>(this); /// <summary> /// Enumerable containing all of the Trails /// </summary> public IPaginatedEnumerable<TrailInfo> Trails => new PaginatedResultKeyResponse<ListTrailsResponse, TrailInfo>(this, (i) => i.Trails); internal ListTrailsPaginator(IAmazonCloudTrail client, ListTrailsRequest request) { this._client = client; this._request = request; } #if BCL IEnumerable<ListTrailsResponse> IPaginator<ListTrailsResponse>.Paginate() { if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0) { throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance."); } PaginatorUtils.SetUserAgentAdditionOnRequest(_request); var nextToken = _request.NextToken; ListTrailsResponse response; do { _request.NextToken = nextToken; response = _client.ListTrails(_request); nextToken = response.NextToken; yield return response; } while (!string.IsNullOrEmpty(nextToken)); } #endif #if AWS_ASYNC_ENUMERABLES_API async IAsyncEnumerable<ListTrailsResponse> IPaginator<ListTrailsResponse>.PaginateAsync(CancellationToken cancellationToken = default) { if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0) { throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance."); } PaginatorUtils.SetUserAgentAdditionOnRequest(_request); var nextToken = _request.NextToken; ListTrailsResponse response; do { _request.NextToken = nextToken; response = await _client.ListTrailsAsync(_request, cancellationToken).ConfigureAwait(false); nextToken = response.NextToken; cancellationToken.ThrowIfCancellationRequested(); yield return response; } while (!string.IsNullOrEmpty(nextToken)); } #endif } } #endif
38.232323
150
0.656803
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/CloudTrail/Generated/Model/_bcl45+netstandard/ListTrailsPaginator.cs
3,785
C#
namespace AlchemyAPIClient.Requests { public sealed class AlchemyHtmlSentimentRequest : AlchemyHtmlSentimentBase, IAlchemyAPIHtmlRequest, ICombinableAlchemyAPIRequest { private const string htmlKey = "html"; private const string cqueryKey = "cquery"; protected override string RequestPath { get { return string.IsNullOrEmpty(Target) ? "html/HTMLGetTextSentiment" : "html/HTMLGetTargetedSentiment"; } } public AlchemyHtmlSentimentRequest(string html, AlchemyClient client) : base(client) { AddRequiredParameter(htmlKey); Html = html; } public string Html { get { return GetParameter(htmlKey); } set { AddOrUpdateParameter(htmlKey, value); } } public bool Cquery { get { return GetBooleanParameter(cqueryKey); } set { AddOrUpdateParameter(cqueryKey, value); } } } }
43.095238
132
0.672928
[ "MIT" ]
baywet/AlchemyAPIClient
AlchemyAPIClient/Requests/Sentiment/AlchemyHtmlSentimentRequest.cs
907
C#
using System; using System.Collections.Generic; using System.Text; namespace DynamicDependencyInjectionNoParams { public interface IShape<T> where T : class { } }
19.666667
51
0.740113
[ "MIT" ]
jsanjuan2016/DynamicDI-simple
IShape.cs
179
C#
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* DictionaryCounterDouble.cs -- simple dictionary to count values * Ars Magna project, http://arsmagna.ru * ------------------------------------------------------- * Status: poor */ #region Using directives using System.Collections; using System.Collections.Generic; using JetBrains.Annotations; using Newtonsoft.Json; #endregion namespace UnsafeAM.Collections { /// <summary> /// Simple dictionary to count values. /// </summary> [PublicAPI] public sealed class DictionaryCounterDouble<TKey> : Dictionary<TKey, double> { #region Properties /// <summary> /// Gets the total. /// </summary> [JsonIgnore] public double Total { get { lock (_syncRoot) { double result = 0.0; foreach (double value in Values) { result += value; } return result; } } } #endregion #region Construction /// <summary> /// Initializes a new instance of the /// <see cref="DictionaryCounterDouble{TKey}"/> class. /// </summary> public DictionaryCounterDouble() { } /// <summary> /// Constructor. /// </summary> /// <param name="comparer">The comparer.</param> public DictionaryCounterDouble ( [NotNull] IEqualityComparer<TKey> comparer ) : base(comparer) { } /// <summary> /// Initializes a new instance of the /// <see cref="DictionaryCounterDouble{TKey}"/> class. /// </summary> /// <param name="capacity">The capacity.</param> public DictionaryCounterDouble(int capacity) : base(capacity) { } /// <summary> /// Initializes a new instance of the /// <see cref="DictionaryCounterDouble{TKey}"/> class. /// </summary> /// <param name="dictionary">The dictionary.</param> public DictionaryCounterDouble ( [NotNull] DictionaryCounterDouble<TKey> dictionary ) : base(dictionary) { } #endregion #region Private members private object _syncRoot => ((ICollection)this).SyncRoot; #endregion #region Public methods /// <summary> /// Augments the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="increment">The value.</param> /// <returns>New value for given key.</returns> public double Augment ( [NotNull] TKey key, double increment ) { lock (_syncRoot) { TryGetValue(key, out double value); value += increment; this[key] = value; return value; } } /// <summary> /// Get accumulated value for the specified key. /// </summary> public double GetValue ( [NotNull] TKey key ) { TryGetValue(key, out double result); return result; } /// <summary> /// Increment the specified key. /// </summary> public double Increment ( [NotNull] TKey key ) { return Augment ( key, 1.0 ); } #endregion } }
24.117284
84
0.472741
[ "MIT" ]
amironov73/ManagedClient.45
Source/Classic/Libs/UnsafeIrbis/AM/Collections/DictionaryCounterDouble.cs
3,909
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("Deferred Execution")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Deferred Execution")] [assembly: AssemblyCopyright("Copyright © Microsoft 2014")] [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("6168acae-75fd-48ef-8639-37d39a60a2a2")] // 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.567568
84
0.749124
[ "MIT" ]
PrasadHonrao/Learn.CSharp
Language/LINQ/Deferred Execution/Properties/AssemblyInfo.cs
1,430
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Threading; using Microsoft.Azure.Commands.ResourceManager.Common; using Microsoft.Rest.Azure; using Microsoft.WindowsAzure.Commands.Common; namespace Microsoft.Azure.Commands.MachineLearning { public abstract class MachineLearningCmdletBase : AzureRMCmdlet { /// <summary> /// The cancellation source. /// </summary> private CancellationTokenSource cancellationSource; protected CancellationToken? CancellationToken { get { return this.cancellationSource == null ? null : (CancellationToken?)this.cancellationSource.Token; } } #region Processing life cycle protected override void BeginProcessing() { try { if (this.cancellationSource == null) { this.cancellationSource = new CancellationTokenSource(); } base.BeginProcessing(); } catch (Exception ex) { this.WriteVersionInfoToDebugChannel(); if (this.IsFatalException(ex)) { ThrowTerminatingError( new ErrorRecord( ex, string.Empty, ErrorCategory.InvalidOperation, this)); } var capturedException = ExceptionDispatchInfo.Capture(ex); this.HandleException(capturedException: capturedException); } } protected override void EndProcessing() { try { base.EndProcessing(); } catch (Exception ex) { this.WriteVersionInfoToDebugChannel(); if (this.IsFatalException(ex)) { ThrowTerminatingError( new ErrorRecord( ex, string.Empty, ErrorCategory.InvalidOperation, this)); } var capturedException = ExceptionDispatchInfo.Capture(ex); this.HandleException(capturedException: capturedException); } finally { this.DisposeOfCancellationSource(); } } protected override void StopProcessing() { try { if (this.cancellationSource != null && !this.cancellationSource.IsCancellationRequested) { this.cancellationSource.Cancel(); } base.StopProcessing(); } catch (Exception ex) { this.WriteVersionInfoToDebugChannel(); if (this.IsFatalException(ex)) { throw; } var capturedException = ExceptionDispatchInfo.Capture(ex); this.HandleException(capturedException: capturedException); } finally { this.DisposeOfCancellationSource(); } } /// <summary> /// Actual cmdlet logic goes here in child classes /// </summary> protected virtual void RunCmdlet() { // No op } public override void ExecuteCmdlet() { try { base.ExecuteCmdlet(); this.RunCmdlet(); } catch (Exception ex) { this.WriteVersionInfoToDebugChannel(); if (this.IsFatalException(ex)) { throw; } var capturedException = ExceptionDispatchInfo.Capture(ex); this.HandleException(capturedException: capturedException); } } #endregion private void DisposeOfCancellationSource() { if (this.cancellationSource != null) { if (!this.cancellationSource.IsCancellationRequested) { this.cancellationSource.Cancel(); } this.cancellationSource.Dispose(); this.cancellationSource = null; } } /// <summary> /// Provides specialized exception handling. /// </summary> /// <param name="capturedException">The captured exception</param> private void HandleException(ExceptionDispatchInfo capturedException) { try { ErrorRecord errorRecord; var cloudException = capturedException.SourceException as CloudException; if (cloudException != null) { errorRecord = this.CreateErrorRecordForCloudException(cloudException); } else { var errorResponseException = capturedException.SourceException as ErrorResponseMessageException; if (errorResponseException != null) { errorRecord = errorResponseException.ToErrorRecord(); } else { var aggregateException = capturedException.SourceException as AggregateException; if (aggregateException != null) { errorResponseException = aggregateException.InnerException as ErrorResponseMessageException; if (errorResponseException != null) { errorRecord = errorResponseException.ToErrorRecord(); } else { errorRecord = new ErrorRecord( aggregateException.InnerException, aggregateException.InnerException.Message, ErrorCategory.CloseError, null); } } else { errorRecord = new ErrorRecord( capturedException.SourceException, capturedException.SourceException.Message, ErrorCategory.CloseError, null); } } } this.WriteError(errorRecord); } finally { this.DisposeOfCancellationSource(); } } /// <summary> /// Converts <see cref="CloudException"/> objects into <see cref="ErrorRecord"/> /// </summary> /// <param name="cloudException">The exception</param> private ErrorRecord CreateErrorRecordForCloudException(CloudException cloudException) { var errorReport = new StringBuilder(); string requestId = cloudException.RequestId; if (string.IsNullOrWhiteSpace(requestId) && cloudException.Response != null) { // Try to obtain the request id from the HTTP response associated with the exception IEnumerable<string> headerValues = Enumerable.Empty<string>(); if (cloudException.Response.Headers != null && cloudException.Response.Headers.TryGetValue("x-ms-request-id", out headerValues)) { requestId = headerValues.First(); } } errorReport.AppendLine(); errorReport.AppendLine("Request Id: {0}".FormatInvariant(requestId)); errorReport.AppendLine("Error Code: {0}".FormatInvariant(cloudException.Body.Code)); errorReport.AppendLine("Error Message: {0}".FormatInvariant(cloudException.Body.Message)); errorReport.AppendLine("Error Target: {0}".FormatInvariant(cloudException.Body.Target)); if (cloudException.Body.Details.Any()) { errorReport.AppendLine("Error Details:"); foreach (var errorDetail in cloudException.Body.Details) { errorReport.AppendLine( "\t[Code={0}, Message={1}]".FormatInvariant( errorDetail.Code, errorDetail.Message)); } } var returnedError = new Exception(errorReport.ToString(), cloudException); return new ErrorRecord(returnedError, "Resource Provider Error", ErrorCategory.CloseError, null); } /// <summary> /// Test if an exception is a fatal exception. /// </summary> /// <param name="ex">Exception object.</param> private bool IsFatalException(Exception ex) { if (ex is AggregateException) { return ((AggregateException)ex).Flatten().InnerExceptions.Any(exception => this.IsFatalException(exception)); } if (ex.InnerException != null && this.IsFatalException(ex.InnerException)) { return true; } return ex is TypeInitializationException || ex is AppDomainUnloadedException || ex is ThreadInterruptedException || ex is AccessViolationException || ex is InvalidProgramException || ex is BadImageFormatException || ex is StackOverflowException || ex is ThreadAbortException || ex is OutOfMemoryException || ex is SecurityException || ex is SEHException; } private void WriteVersionInfoToDebugChannel() { var versionInfo = this.MyInvocation.MyCommand.Module.Version; this.WriteDebug(Resources.VersionInfo.FormatInvariant(versionInfo.ToString(3))); } } }
37.76324
126
0.476902
[ "MIT" ]
LaudateCorpus1/azure-powershell
src/ResourceManager/MachineLearning/Commands.MachineLearning/Cmdlets/MachineLearningCmdletBase.cs
11,804
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 route53-2013-04-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Route53.Model { /// <summary> /// A complex type that contains the response information for the request. /// </summary> public partial class ListTrafficPoliciesResponse : AmazonWebServiceResponse { private List<TrafficPolicySummary> _trafficPolicySummaries = new List<TrafficPolicySummary>(); private bool? _isTruncated; private string _trafficPolicyIdMarker; private string _maxItems; /// <summary> /// Gets and sets the property TrafficPolicySummaries. /// <para> /// A list that contains one <code>TrafficPolicySummary</code> element for each traffic /// policy that was created by the current AWS account. /// </para> /// </summary> [AWSProperty(Required=true)] public List<TrafficPolicySummary> TrafficPolicySummaries { get { return this._trafficPolicySummaries; } set { this._trafficPolicySummaries = value; } } // Check to see if TrafficPolicySummaries property is set internal bool IsSetTrafficPolicySummaries() { return this._trafficPolicySummaries != null && this._trafficPolicySummaries.Count > 0; } /// <summary> /// Gets and sets the property IsTruncated. /// <para> /// A flag that indicates whether there are more traffic policies to be listed. If the /// response was truncated, you can get the next group of traffic policies by submitting /// another <code>ListTrafficPolicies</code> request and specifying the value of <code>TrafficPolicyIdMarker</code> /// in the <code>TrafficPolicyIdMarker</code> request parameter. /// </para> /// </summary> [AWSProperty(Required=true)] public bool IsTruncated { get { return this._isTruncated.GetValueOrDefault(); } set { this._isTruncated = value; } } // Check to see if IsTruncated property is set internal bool IsSetIsTruncated() { return this._isTruncated.HasValue; } /// <summary> /// Gets and sets the property TrafficPolicyIdMarker. /// <para> /// If the value of <code>IsTruncated</code> is <code>true</code>, <code>TrafficPolicyIdMarker</code> /// is the ID of the first traffic policy in the next group of <code>MaxItems</code> traffic /// policies. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=36)] public string TrafficPolicyIdMarker { get { return this._trafficPolicyIdMarker; } set { this._trafficPolicyIdMarker = value; } } // Check to see if TrafficPolicyIdMarker property is set internal bool IsSetTrafficPolicyIdMarker() { return this._trafficPolicyIdMarker != null; } /// <summary> /// Gets and sets the property MaxItems. /// <para> /// The value that you specified for the <code>MaxItems</code> parameter in the <code>ListTrafficPolicies</code> /// request that produced the current response. /// </para> /// </summary> [AWSProperty(Required=true)] public string MaxItems { get { return this._maxItems; } set { this._maxItems = value; } } // Check to see if MaxItems property is set internal bool IsSetMaxItems() { return this._maxItems != null; } } }
35.959677
123
0.63041
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/Route53/Generated/Model/ListTrafficPoliciesResponse.cs
4,459
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.MachineLearning.Inputs { /// <summary> /// Holds the available configuration options for an Azure ML web service endpoint. /// </summary> public sealed class RealtimeConfigurationArgs : Pulumi.ResourceArgs { /// <summary> /// Specifies the maximum concurrent calls that can be made to the web service. Minimum value: 4, Maximum value: 200. /// </summary> [Input("maxConcurrentCalls")] public Input<int>? MaxConcurrentCalls { get; set; } public RealtimeConfigurationArgs() { } } }
31
125
0.678532
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/MachineLearning/Inputs/RealtimeConfigurationArgs.cs
899
C#
// <copyright file="Constructor_Should.cs" company="YAGNI"> // All rights reserved. // </copyright> // <summary>Holds unit tests of JsonWriter object constructor.</summary> using System; using LibrarySystem.FileImporters.Utils; using NUnit.Framework; namespace LibrarySystem.FileImporters.UnitTests.Utils.StreamReaderWrapperTests { [TestFixture] public class Constructor_Should { [Test] [Category("FileImporters.StreamReaderWrapper.Constructor")] public void ThrowArgumentNullException_WhenDirectoryArgumentIsNull() { // AAA Assert.Throws<ArgumentNullException>(() => new StreamReaderWrapper(null)); } [Test] [Category("FileImporters.StreamReaderWrapper.Constructor")] public void ThrowArgumentException_WhenDirectoryArgumentIsEmpty() { // AAA Assert.Throws<ArgumentException>(() => new StreamReaderWrapper(string.Empty)); } } }
30.53125
90
0.684749
[ "MIT" ]
TeamYAGNI/LibrarySystem
LibrarySystem/LibrarySystem.FileImporters.UnitTests/Utils/StreamReaderWrapperTests/Constructor_Should.cs
979
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FogchessCore { public class Rook : ChessPiece { public Rook(PieceColor color) { this._type = PieceType.Rook; this._color = color; } /// <summary> /// Rooks look straight ahead and to the left and right /// </summary> public override void RevealVisibleSquares() { int currentRank = this.Square.Rank; int currentFile = this.Square.File; ChessBoard board = this.Square.Board; this.Square.Board.Grid[currentRank][currentFile].Visible = true; //Reveal squares forward int revealedRank = currentRank + 1; while (revealedRank < 8 && board.Grid[revealedRank][currentFile].Piece == null) { board.Grid[revealedRank][currentFile].Visible = true; revealedRank++; } //Reveal squares backwards revealedRank = currentRank - 1; while (revealedRank >= 0 && board.Grid[revealedRank][currentFile].Piece == null) { board.Grid[revealedRank][currentFile].Visible = true; revealedRank--; } //Reveal squares left int revealedFile = currentFile - 1; while (revealedFile >= 0 && board.Grid[currentRank][revealedFile].Piece == null) { board.Grid[currentRank][revealedFile].Visible = true; revealedFile--; } //Reveal squares right revealedFile = currentFile + 1; while (revealedFile < 8 && board.Grid[currentRank][revealedFile].Piece == null) { board.Grid[currentRank][revealedFile].Visible = true; revealedFile++; } } } }
32
92
0.548156
[ "MIT" ]
quanticle/Fogchess
FogchessCore/FogchessCore/Rook.cs
1,954
C#
using Discord; using Discord.Commands; using System.Threading.Tasks; using Bugger.Extensions; using Bugger.Preconditions; namespace Bugger.Modules { public class TymczasowyKanałGłosowy : ModuleBase<MiunieCommandContext> { const int maxTimeInMinutes = 21600000; [Command("TymczasowyKanałGłosowy", RunMode = RunMode.Async)] [Alias("TKG", "TKGłosowy", "TKanałG", "TKanałGłosowy", "TymczasowyKG", "TymczasowyKGłosowy", "TymczasowyKanałG", "Tymczasowy", "TymczasowyGłosowy", "TymczasowyKanalGlosowy", "TymczasowyGlosowy", "TVCH", "TVChannel", "TVoiceCH", "TVoiceChannel", "TemporaryVCH", "TemporaryVChannel", "TemporaryVoiceCH", "Temporary", "TemporaryVoice", "TemporaryVCH", "TVoice", "TemporaryVoiceChannel")] [Summary("Pozwala tworzyć użytkownikom ich własne, tymczasowe kanały głosowe, które po czasie automatycznie znikają. **[VIP FEATURE]**")] [RequireBotPermission(GuildPermission.ManageChannels)] [Cooldown(900, false)] public async Task CreateTemporaryVoiceChannel(int lifetimeInMinutes = 0) { lifetimeInMinutes *= 60000; if (lifetimeInMinutes == 0) { var use = await Context.Channel.SendMessageAsync("**Zapomniałeś o podaniu czasu...**\nSpróbuj tak:```<prefix>tymczasowykanałgłosowy {CzasWMinutach}```\nlub poprostu:```<prefix>tkg {CzasWMinutach}```"); await Task.Delay(10000); await use.DeleteAsync(); } else if (lifetimeInMinutes >= maxTimeInMinutes) { var embed = new EmbedBuilder(); embed.WithTitle("**Tymczasowy Prywatny Kanał Głosowy**"); embed.WithDescription("Maksymalny czas: **360** minut = 6h\n{CzasWMinutach} <= 360"); embed.AddField("Spróbuj tak:\n", "```<prefix>tymczasowykanałgłosowy {CzasWMinutach}```"); embed.AddField("\nlub poprostu:\n", "```<prefix> tkg {CzasWMinutach}```\n"); embed.WithColor(0, 255, 0); await Context.Channel.SendMessageAsync("", embed: embed.Build()); } else if (lifetimeInMinutes == 60000) { await Context.Message.DeleteAsync(); var voiceChannel = await Context.Guild.CreateVoiceChannelAsync(name: $"Tymczasowy Kanał Głosowy użytkownika {Context.User.Username} na ({lifetimeInMinutes / 60000} minut)"); var msg = await Context.Channel.SendMessageAsync($"Stworzyłem Ci tymczasowy kanał głosowy {Context.User.Mention}!"); await msg.ModifyAsync(m => { m.Content = $"Stworzyłem Ci tymczasowy kanał głosowy! {Context.User.Mention}! Masz jeszcze {lifetimeInMinutes / 60000} minut."; }); await Task.Delay(lifetimeInMinutes); await voiceChannel.DeleteAsync(); await msg.DeleteAsync(); } else if (lifetimeInMinutes >= 60001 && lifetimeInMinutes <= maxTimeInMinutes) { await Context.Message.DeleteAsync(); var voiceChannel = await Context.Guild.CreateVoiceChannelAsync(name: $"Tymczasowy Kanał Głosowy użytkownika {Context.User.Username} na ({lifetimeInMinutes / 60000} minut)"); var msg = await Context.Channel.SendMessageAsync($"Stworzyłem Ci tymczasowy kanał głosowy! {Context.User.Mention}! Masz jeszcze {lifetimeInMinutes / 60000} minut."); await Task.Delay(lifetimeInMinutes); await voiceChannel.DeleteAsync(); await msg.ModifyAsync(x => { x.Content = $"{Context.User.Mention}, czas twojego kanału nadszedł... czas upłynął."; }); } } } }
63.62069
392
0.64065
[ "MIT" ]
BuggerDiscordBot/Bugger
Bugger/Modules/Voice.cs
3,740
C#
using System; using System.Collections.Generic; using System.Text; namespace BoletoNet { /// <summary> /// Contém informações que são pertinentes a um boleto, mas para geração da Remessa. Não são necessárias para Impressão do Boleto /// Autor: sidneiklein Data: 09/08/2013 /// </summary> public class Remessa { public enum TipoAmbiemte { Homologacao, Producao } // #region Atributos e Propriedades private TipoAmbiemte _Ambiente; /// <summary> /// Variável que define se a Remessa é para Testes ou Produção /// </summary> public TipoAmbiemte Ambiente { get { return _Ambiente; } set { _Ambiente = value; } } private string _TipoDocumento; /// <summary> /// Tipo Documento Utilizado na geração da remessa. |Identificado no Banrisul by sidneiklein| /// Tipo Cobranca Utilizado na geração da remessa. |Identificado no Sicredi by sidneiklein| /// </summary> public string TipoDocumento { get { return _TipoDocumento; } set { _TipoDocumento = value; } } private string _CodigoOcorrencia; /// <summary> /// Código de Ocorrência Utilizado na geração da Remessa. /// |Identificado no Banrisul como "CODIGO OCORRENCIA" by sidneiklein| /// |Identificado no Banco do Brasil como "COMANDO" by sidneiklein| /// </summary> public string CodigoOcorrencia { get { return _CodigoOcorrencia; } set { _CodigoOcorrencia = value; } } #endregion } }
31.309091
133
0.580139
[ "Apache-2.0" ]
wzambiazzi/BoletoNet
src/Boleto.Net/Boleto/Remessa.cs
1,746
C#
namespace MyTasks.TODO.ViewModels { public class AboutViewModel : FreshMvvm.FreshBasePageModel { public string Title => "About View"; public AboutViewModel() { } } }
19.181818
62
0.606635
[ "MIT" ]
navkar/FreshTodo
MyTasks.TODO/MyTasks.TODO/ViewModels/AboutViewModel.cs
213
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 어셈블리의 일반 정보는 다음 특성 집합을 통해 제어됩니다. // 어셈블리와 관련된 정보를 수정하려면 // 이 특성 값을 변경하십시오. [assembly: AssemblyTitle("FluentFTP.Async Extensions")] [assembly: AssemblyDescription("This component provides async extensions for FluentFTP library.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("ClouDeveloper")] [assembly: AssemblyProduct("FluentFTP.Async")] [assembly: AssemblyCopyright("(c) ClouDeveloper, All rights reserved.")] [assembly: AssemblyTrademark("ClouDeveloper")] [assembly: AssemblyCulture("")] // ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에 // 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면 // 해당 형식에 대해 ComVisible 특성을 true로 설정하십시오. [assembly: ComVisible(false)] // 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다. [assembly: Guid("94b211a9-0c6a-4d46-85f4-67b30b694fdf")] // 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다. // // 주 버전 // 부 버전 // 빌드 번호 // 수정 버전 // // 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 버전이 자동으로 // 지정되도록 할 수 있습니다. // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.3.1")]
31.638889
98
0.720808
[ "MIT" ]
JohnTheGr8/FluentFTP.Async
FluentFTP.Async/FluentFTP.Async/Properties/AssemblyInfo.cs
1,575
C#