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.Collections.Generic; namespace NLog.Extensions.AzureStorage { internal sealed class SortHelpers { /// <summary> /// Key Selector Delegate /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <typeparam name="TKey">The type of the key.</typeparam> /// <param name="value">The value.</param> /// <returns></returns> internal delegate TKey KeySelector<TValue, TKey>(TValue value); /// <summary> /// Buckets sorts returning a dictionary of lists /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <typeparam name="TKey">The type of the key.</typeparam> /// <param name="inputs">The inputs.</param> /// <param name="keySelector">The key selector.</param> /// <returns></returns> internal static Dictionary<TKey, IList<TValue>> BucketSort<TValue, TKey>(IList<TValue> inputs, KeySelector<TValue, TKey> keySelector) { var retVal = new Dictionary<TKey, IList<TValue>>(); for (int i = 0; i < inputs.Count; ++i) { var input = inputs[i]; var keyValue = keySelector(input); if (!retVal.TryGetValue(keyValue, out var eventsInBucket)) { eventsInBucket = new List<TValue>(inputs.Count - i); retVal.Add(keyValue, eventsInBucket); } eventsInBucket.Add(input); } return retVal; } } }
36.454545
141
0.552369
[ "MIT" ]
CptButtercup/NLog.Extensions.AzureStorage
src/NLog.Extensions.AzureStorage/SortHelpers.cs
1,604
C#
using JetBrains.Annotations; using System; namespace ph4n.Common { /// <summary> /// Clever way to handle events using extentions /// http://stackoverflow.com/a/340638/351028 /// </summary> public static class EventHandlerEx { /// <summary> /// Will raise an event handler in a thread safe way with a null check /// </summary> /// <param name="handler">Handler to be raised</param> /// <param name="sender">sender raising the event</param> /// <param name="e">EventArgs event is being raised with</param> public static void Raise([CanBeNull] this EventHandler handler, [CanBeNull] object sender, [CanBeNull] EventArgs e) { if (null != handler) { handler(sender, e); } } /// <summary> /// Will raise an event handler in a thread safe way with a null check /// </summary> /// <typeparam name="TEventArgs">Type of EventArgs event is being raised with</typeparam> /// <param name="handler">Handler to be raised</param> /// <param name="sender">sender raising the event</param> /// <param name="e">EventArgs event is being raised with</param> public static void Raise<TEventArgs>([CanBeNull] this EventHandler<TEventArgs> handler, [CanBeNull] object sender, [CanBeNull] TEventArgs e) where TEventArgs : EventArgs { if (null != handler) { handler(sender, e); } } } }
41.914286
177
0.619632
[ "MIT" ]
buchmoyerm/Lib-ph4n
src/ph4n.Common/EventHandlerEx.cs
1,469
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 codestar-notifications-2019-10-15.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.CodeStarNotifications.Model { /// <summary> /// Container for the parameters to the Unsubscribe operation. /// Removes an association between a notification rule and an Amazon SNS topic so that /// subscribers to that topic stop receiving notifications when the events described in /// the rule are triggered. /// </summary> public partial class UnsubscribeRequest : AmazonCodeStarNotificationsRequest { private string _arn; private string _targetAddress; /// <summary> /// Gets and sets the property Arn. /// <para> /// The Amazon Resource Name (ARN) of the notification rule. /// </para> /// </summary> [AWSProperty(Required=true)] public string Arn { get { return this._arn; } set { this._arn = value; } } // Check to see if Arn property is set internal bool IsSetArn() { return this._arn != null; } /// <summary> /// Gets and sets the property TargetAddress. /// <para> /// The ARN of the SNS topic to unsubscribe from the notification rule. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=320)] public string TargetAddress { get { return this._targetAddress; } set { this._targetAddress = value; } } // Check to see if TargetAddress property is set internal bool IsSetTargetAddress() { return this._targetAddress != null; } } }
31.375
120
0.633865
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/CodeStarNotifications/Generated/Model/UnsubscribeRequest.cs
2,510
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.Mps.V20190612.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class AiAnalysisTaskTagResult : AbstractModel { /// <summary> /// 任务状态,有 PROCESSING,SUCCESS 和 FAIL 三种。 /// </summary> [JsonProperty("Status")] public string Status{ get; set; } /// <summary> /// 错误码,空字符串表示成功,其他值表示失败,取值请参考 [视频处理类错误码](https://cloud.tencent.com/document/product/862/50369#.E8.A7.86.E9.A2.91.E5.A4.84.E7.90.86.E7.B1.BB.E9.94.99.E8.AF.AF.E7.A0.81) 列表。 /// </summary> [JsonProperty("ErrCodeExt")] public string ErrCodeExt{ get; set; } /// <summary> /// 错误码,0 表示成功,其他值表示失败(该字段已不推荐使用,建议使用新的错误码字段 ErrCodeExt)。 /// </summary> [JsonProperty("ErrCode")] public long? ErrCode{ get; set; } /// <summary> /// 错误信息。 /// </summary> [JsonProperty("Message")] public string Message{ get; set; } /// <summary> /// 智能标签任务输入。 /// </summary> [JsonProperty("Input")] public AiAnalysisTaskTagInput Input{ get; set; } /// <summary> /// 智能标签任务输出。 /// 注意:此字段可能返回 null,表示取不到有效值。 /// </summary> [JsonProperty("Output")] public AiAnalysisTaskTagOutput Output{ 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 + "Status", this.Status); this.SetParamSimple(map, prefix + "ErrCodeExt", this.ErrCodeExt); this.SetParamSimple(map, prefix + "ErrCode", this.ErrCode); this.SetParamSimple(map, prefix + "Message", this.Message); this.SetParamObj(map, prefix + "Input.", this.Input); this.SetParamObj(map, prefix + "Output.", this.Output); } } }
33.2875
180
0.606083
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Mps/V20190612/Models/AiAnalysisTaskTagResult.cs
2,925
C#
#pragma checksum "C:\Users\Bruce\Desktop\Finance\Finance\Views\Shared\_CookieConsentPartial.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "d4fdc3d9e6bc2a119e86fb23894c311b8c5abaf6" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Shared__CookieConsentPartial), @"mvc.1.0.view", @"/Views/Shared/_CookieConsentPartial.cshtml")] [assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/Shared/_CookieConsentPartial.cshtml", typeof(AspNetCore.Views_Shared__CookieConsentPartial))] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #line 1 "C:\Users\Bruce\Desktop\Finance\Finance\Views\_ViewImports.cshtml" using Finance; #line default #line hidden #line 2 "C:\Users\Bruce\Desktop\Finance\Finance\Views\_ViewImports.cshtml" using Finance.Models; #line default #line hidden #line 1 "C:\Users\Bruce\Desktop\Finance\Finance\Views\Shared\_CookieConsentPartial.cshtml" using Microsoft.AspNetCore.Http.Features; #line default #line hidden [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"d4fdc3d9e6bc2a119e86fb23894c311b8c5abaf6", @"/Views/Shared/_CookieConsentPartial.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"78d485da229cf3b9644d6f0c651451eded00a1c1", @"/Views/_ViewImports.cshtml")] public class Views_Shared__CookieConsentPartial : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-area", "", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-controller", "Home", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Privacy", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { BeginContext(43, 2, true); WriteLiteral("\r\n"); EndContext(); #line 3 "C:\Users\Bruce\Desktop\Finance\Finance\Views\Shared\_CookieConsentPartial.cshtml" var consentFeature = Context.Features.Get<ITrackingConsentFeature>(); var showBanner = !consentFeature?.CanTrack ?? false; var cookieString = consentFeature?.CreateConsentCookie(); #line default #line hidden BeginContext(248, 2, true); WriteLiteral("\r\n"); EndContext(); #line 9 "C:\Users\Bruce\Desktop\Finance\Finance\Views\Shared\_CookieConsentPartial.cshtml" if (showBanner) { #line default #line hidden BeginContext(271, 168, true); WriteLiteral(" <div id=\"cookieConsent\" class=\"alert alert-info alert-dismissible fade show\" role=\"alert\">\r\n Use this space to summarize your privacy and cookie use policy. "); EndContext(); BeginContext(439, 72, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "d4fdc3d9e6bc2a119e86fb23894c311b8c5abaf65153", async() => { BeginContext(497, 10, true); WriteLiteral("Learn More"); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Area = (string)__tagHelperAttribute_0.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_1.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_2.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(511, 121, true); WriteLiteral(".\r\n <button type=\"button\" class=\"accept-policy close\" data-dismiss=\"alert\" aria-label=\"Close\" data-cookie-string=\""); EndContext(); BeginContext(633, 12, false); #line 13 "C:\Users\Bruce\Desktop\Finance\Finance\Views\Shared\_CookieConsentPartial.cshtml" Write(cookieString); #line default #line hidden EndContext(); BeginContext(645, 403, true); WriteLiteral(@"""> <span aria-hidden=""true"">Accept</span> </button> </div> <script> (function () { var button = document.querySelector(""#cookieConsent button[data-cookie-string]""); button.addEventListener(""click"", function (event) { document.cookie = button.dataset.cookieString; }, false); })(); </script> "); EndContext(); #line 25 "C:\Users\Bruce\Desktop\Finance\Finance\Views\Shared\_CookieConsentPartial.cshtml" } #line default #line hidden } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; } } } #pragma warning restore 1591
58.152318
301
0.7219
[ "MIT" ]
Bruce979527682/Finance
Finance/obj/Debug/netcoreapp2.2/Razor/Views/Shared/_CookieConsentPartial.g.cshtml.cs
8,781
C#
using System; using System.Linq; using System.Web; using System.Web.UI; using System.Collections.Specialized; using PBIWebApp.Properties; using Microsoft.IdentityModel.Clients.ActiveDirectory; using Microsoft.PowerBI.Api.V2; using Microsoft.PowerBI.Api.V2.Models; using Microsoft.Rest; using Newtonsoft.Json; namespace PBIWebApp { /* NOTE: This code is for sample purposes only. In a production application, you could use a MVC design pattern. * In addition, you should provide appropriate exception handling and refactor authentication settings into * a secure configuration. Authentication settings are hard-coded in the sample to make it easier to follow the flow of authentication. * In addition, the sample uses a single web page so that all code is in one location. However, you could refactor the code into * your own production model. */ public partial class EmbedTile : System.Web.UI.Page { string baseUri = Properties.Settings.Default.PowerBiDataset; public AuthenticationResult authResult { get; set; } protected void Page_Load(object sender, EventArgs e) { //Need an Authorization Code from Azure AD before you can get an access token to be able to call Power BI operations //You get the Authorization Code when you click Get Tile (see below). //After you call AcquireAuthorizationCode(), Azure AD redirects back to this page with an Authorization Code. if (Session[Utils.authResultString] != null) { //After you get an AccessToken, you can call Power BI API operations such as Get Tile authResult = (AuthenticationResult)Session[Utils.authResultString]; accessToken.Value = authResult.AccessToken; //Get first dashboard. Sample assumes one dashboard with one tile string dashboardId = GetDashboard(0); //You can get the Dashboard ID with the Get Dashboards operation. Or go to your dashboard, and get it from the url for the dashboard. //The dashboard id is at the end if the url. For example, https://msit.powerbi.com/groups/me/dashboards/00b7e871-cb98-48ed-bddc-0000c000e000 //In this sample, you get the first tile in the first dashbaord. In a production app, you would create a more robost //solution GetTile(dashboardId, 0); } } protected void getTileButton_Click(object sender, EventArgs e) { //You need an Authorization Code from Azure AD so that you can get an Access Token //Values are hard-coded for sample purposes. Utils.EmbedType = "EmbedTile"; var urlToRedirect = Utils.GetAuthorizationCode(); //Redirect to Azure AD to get an authorization code Response.Redirect(urlToRedirect); } //Get a dashbaord id. protected string GetDashboard(int index) { string dashboardId = string.Empty; //Configure tiles request System.Net.WebRequest request = System.Net.WebRequest.Create($"{baseUri}groups/{Settings.Default.WorkspaceId}/Dashboards") as System.Net.HttpWebRequest; request.Method = "GET"; request.ContentLength = 0; request.Headers.Add("Authorization", $"Bearer {accessToken.Value}"); //Get dashboards response from request.GetResponse() using (var response = request.GetResponse() as System.Net.HttpWebResponse) { //Get reader from response stream using (var reader = new System.IO.StreamReader(response.GetResponseStream())) { //Deserialize JSON string PBIDashboards dashboards = JsonConvert.DeserializeObject<PBIDashboards>(reader.ReadToEnd()); //Sample assumes at least one Dashboard with one Tile. //You could write an app that lists all tiles in a dashboard dashboardId = dashboards.value[index].id; } } return dashboardId; } //Get a tile from a dashboard. In this sample, you get the first tile. protected void GetTile(string dashboardId, int index) { //Configure tiles request System.Net.WebRequest request = System.Net.WebRequest.Create($"{baseUri}groups/{Settings.Default.WorkspaceId}/Dashboards/{dashboardId}/Tiles") as System.Net.HttpWebRequest; request.Method = "GET"; request.ContentLength = 0; request.Headers.Add("Authorization", $"Bearer {accessToken.Value}"); //Get tiles response from request.GetResponse() using (var response = request.GetResponse() as System.Net.HttpWebResponse) { //Get reader from response stream using (var reader = new System.IO.StreamReader(response.GetResponseStream())) { //Deserialize JSON string PBITiles tiles = JsonConvert.DeserializeObject<PBITiles>(reader.ReadToEnd()); //Sample assumes at least one Dashboard with one Tile. //You could write an app that lists all tiles in a dashboard if (tiles.value.Length > 0) tileEmbedUrl.Text = tiles.value[index].embedUrl; } } } public string GetAccessToken(string authorizationCode, string clientID, string clientSecret, string redirectUri) { //Redirect uri must match the redirect_uri used when requesting Authorization code. //Note: If you use a redirect back to Default, as in this sample, you need to add a forward slash //such as http://localhost:13526/ // Get auth token from auth code TokenCache TC = new TokenCache(); //Values are hard-coded for sample purposes string authority = Properties.Settings.Default.AADAuthorityUri; AuthenticationContext AC = new AuthenticationContext(authority, TC); ClientCredential cc = new ClientCredential(clientID, clientSecret); //Set token from authentication result return AC.AcquireTokenByAuthorizationCodeAsync( authorizationCode, new Uri(redirectUri), cc).Result.AccessToken; } } }
47.832117
184
0.634671
[ "MIT" ]
agriggs/PowerBI-Developer-Samples
User Owns Data/integrate-web-app/PBIWebApp/EmbedTile.aspx.cs
6,555
C#
using System; using System.Collections.Generic; using System.Linq; using Mono.Cecil; using Mono.Cecil.Cil; using NLog; namespace Papier { public static class StubDetection { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); public static bool FindStubsThatAreCalledFromTheSourceSet(AssemblyDefinition assembly, IEnumerable<string> sourceSet, ref Dictionary<TypeDefinition, HashSet<IMemberDefinition>> stubbedTypes) { var hadStubs = false; var sourceTypes = sourceSet.Select(source => { var ret = assembly.MainModule.GetType(source); if (ret == null) { Logger.Error($"Could not resolve Type {source}!"); Environment.Exit(-1); } return ret; }).ToList(); foreach (var type in sourceTypes) { var methodsToStub = new HashSet<MethodDefinition>(); // TODO: Henn-Egg problem. We only need to stub classes that are referenced _by_ the source set // so limiting it seems like a good idea, but in theory, stubs could also expose new requirements // to be stubbed. This is however very unlikely, and also currently not detectable by FindTypesToStub // (that only checks method bodies, but there are none in stubs). FindTypesToStub(type, ref methodsToStub, stubbedTypes.Keys); if (methodsToStub.Count == 0) { continue; } foreach (var md in methodsToStub) { Console.WriteLine($"STUB {md}, called from {type.Name}"); if (!stubbedTypes.ContainsKey(md.DeclaringType)) { stubbedTypes[md.DeclaringType] = new HashSet<IMemberDefinition>(); // We didn't have md.DT as stub yet, signal that to the caller, because that will require a // complete re-scan for new stubs on the whole sourceSet hadStubs = true; } var stubSet = stubbedTypes[md.DeclaringType]; foreach (var t in sourceTypes) { FindStubContents(md.DeclaringType, t, ref stubSet); } // yield return methods only return an instance of a new compiler-generated inner class // Thus (and potentially other reasons), we're basically adding all innter classes // of type as well. // TODO: Shouldn't that also apply to FindTypesToStub? if (type.HasNestedTypes) { foreach (var nt in type.NestedTypes) { FindStubContents(md.DeclaringType, nt, ref stubSet); } } stubbedTypes[md.DeclaringType] = stubSet; } } return hadStubs; } /// <summary> /// This method searches for all references from type to stubType, in order to find all members that need to /// be stubbed. /// </summary> /// <param name="stubType"></param> /// <param name="type"></param> /// <param name="content"></param> public static void FindStubContents(TypeDefinition stubType, TypeDefinition type, ref HashSet<IMemberDefinition> content) { if (type.HasMethods) { foreach (var m in type.Methods.Where(m => m.HasBody)) { foreach (var ins in m.Body.Instructions) { if (ins.OpCode == OpCodes.Call || ins.OpCode == OpCodes.Calli || ins.OpCode == OpCodes.Callvirt || ins.OpCode == OpCodes.Newobj) { var mr = (MethodReference)ins.Operand; if (stubType.Equals(mr.DeclaringType.Resolve())) { var meth = mr.Resolve(); if (stubType.HasProperties && meth.IsSpecialName && !meth.IsConstructor) { if (meth.Name.StartsWith("get_")) { content.Add(stubType.Properties.First(x => meth.Equals(x.GetMethod))); } else if (meth.Name.StartsWith("set_")) { content.Add(stubType.Properties.First(x => meth.Equals(x.SetMethod))); } else { Console.Error.WriteLine($"Unknown special method {meth.Name}, that is no property"); } } else { content.Add(meth); } } } else if (ins.OpCode == OpCodes.Ldfld || ins.OpCode == OpCodes.Stfld || ins.OpCode == OpCodes.Ldsfld || ins.OpCode == OpCodes.Stsfld) { var fd = (FieldReference)ins.Operand; if (stubType.Equals(fd.DeclaringType.Resolve())) { content.Add(fd.Resolve()); } } } } } } /// <summary> /// This method searches a given type to find where the type/references are leaked (e.g. passing this to a foreign /// class). These references/classes need to be stubbed for the compiler, because the types would otherwise not /// match anymore after "deleting" the type in the assembly.<br /> /// Since this is a complex subject, this method is probably far from perfect and needs a few iterations once /// problems arise. /// </summary> /// <param name="type"></param> /// <param name="methods"></param> /// <param name="stubbedTypes"></param> public static void FindTypesToStub(TypeDefinition type, ref HashSet<MethodDefinition> methods, IEnumerable<TypeDefinition> stubbedTypes) { if (!type.HasMethods) { return; } foreach (var m in type.Methods.Where(x => x.HasBody)) { foreach (var ins in m.Body.Instructions) { if (ins.OpCode == OpCodes.Call || ins.OpCode == OpCodes.Calli || ins.OpCode == OpCodes.Callvirt || ins.OpCode == OpCodes.Newobj) { var mr = (MethodReference)ins.Operand; // TODO: If DT is any of the sourceSet + stubbedTypes, we don't need to report this method // because that means we already have that class in source code form, non-assembly, so we // can't stub it. // TODO: If we skip based on that however, stubs would disappear (a call causes a stub, then it's removed, then it's added again) // TODO: Shouldn't that filtering happen at a later place, so that methods are the true methods? if (!mr.HasParameters || mr.DeclaringType.Equals(type) || mr.DeclaringType.IsNested && mr.DeclaringType.DeclaringType.Equals(type)) { continue; } if (mr.Parameters.Select(p => p.ParameterType.Resolve()) .Where(p => p != null) .Any(pt => type.Equals(pt) || stubbedTypes.Contains(pt))) { // Found a method call that contains a related type (type or any stub) as param. methods.Add(mr.Resolve()); } } } } } } }
47.801105
158
0.465673
[ "MIT" ]
MeFisto94/Papier
Papier/StubDetection.cs
8,654
C#
using UnityEngine; using UnityEditorInternal; using System; using Object = UnityEngine.Object; using System.Collections; using UnityEditor; using System.Text.Ex; using System.Collections.Generic; namespace mulova.comunity { /// <summary> /// Pure C# IList (non SerializableProperty array) cannot be reordered in UnityInternal ReorderableList /// </summary> public class ReorderlessList<T> { public delegate T CreateItemDelegate(); public delegate bool DrawItemDelegate(T item, Rect rect, int index, bool isActive, bool isFocused); public delegate void ChangeDelegate(); public const float HEIGHT = 21; public readonly ReorderableList drawer; public bool changed { get; private set; } public CreateItemDelegate createItem; public DrawItemDelegate drawItem; public ChangeDelegate onChange = () => { }; private string _title; public string title { set { _title = value; drawer.headerHeight = _title.IsEmpty()? 0: HEIGHT; } } public bool displayAdd { get { return drawer.displayAdd; } set { drawer.displayAdd = value; } } public bool displayRemove { get { return drawer.displayRemove; } set { drawer.displayRemove = value; } } public bool draggable { get { return drawer.draggable; } set { drawer.draggable = value; } } public T this[int i] { get { return (T)drawer.list[i]; } set { if (i <= drawer.list.Count) { drawer.list.Insert(i, value); } else { drawer.list[i] = value; } } } public int count { get { return drawer.list.Count; } } public IList list { get { return drawer.list; } set { drawer.list = value; } } public ReorderlessList(IList list) { this.drawer = new ReorderableList(list, typeof(T), true, false, true, true); this.list = (IList)list; Init(); } private void Init() { this.drawer.onAddCallback = _OnAdd; this.drawer.drawHeaderCallback = DrawHeader; this.drawer.drawElementCallback = _DrawItem; this.drawer.onReorderCallback = Reorder; this.drawer.elementHeight = HEIGHT; this.drawer.elementHeightCallback = GetElementHeight; this.drawer.onRemoveCallback = OnRemove; this.createItem = CreateItem; this.drawItem = DrawItem; } private void OnRemove(ReorderableList list) { throw new NotImplementedException(); } private float GetElementHeight(int index) { if (match == null || match(this[index])) { return drawer.elementHeight; } else { return 0; } } private void DrawHeader(Rect rect) { if (_title != null) { EditorGUI.LabelField(rect, new GUIContent(ObjectNames.NicifyVariableName(_title))); } } protected virtual bool DrawItem(T item, Rect rect, int index, bool isActive, bool isFocused) { return false; } private void _DrawItem(Rect rect, int index, bool isActive, bool isFocused) { if (match == null || match(this[index])) { Rect r = rect; r.y += 1; r.height -= 2; if (drawItem(this[index], r, index, isActive, isFocused)) { changed = true; SetDirty(); } } } protected virtual void Reorder(ReorderableList list) { SetDirty(); } public void Refresh() { Filter(match); } protected virtual T CreateItem() { return default(T); } private void _OnAdd(ReorderableList reorderList) { var o = CreateItem(); if (drawer.list.IsFixedSize) { var arr = new T[list.Count + 1]; arr[arr.Length - 1] = o; drawer.list = arr; } else { drawer.index = drawer.list.Add(o); } SetDirty(); onChange(); } public void SetDirty() { changed = true; } public bool Draw() { changed = false; drawer.DoLayoutList(); if (changed) { onChange(); SetDirty(); return true; } else { return false; } } private Predicate<T> match; public void Filter(Predicate<T> match) { this.match = match; } public void Duplicate(int index) { T o = (T)list[index]; list.Insert(index+1, o); this.drawer.index = index+1; SetDirty(); onChange(); this.drawer.onAddCallback?.Invoke(this.drawer); } public void Remove(int i) { T o = (T)list[i]; list.RemoveAt(i); SetDirty(); onChange(); this.drawer.onRemoveCallback?.Invoke(this.drawer); } public void Move(int si, int di) { list.Insert(di, list[si]); int si2 = si > di? si+1: si; list.RemoveAt(si2); SetDirty(); onChange(); this.drawer.onReorderCallback?.Invoke(this.drawer); } public void Clear() { list.Clear(); SetDirty(); onChange(); } } }
24.779468
107
0.454197
[ "MIT" ]
mulova/comunity
Editor/comunity/drawer/ReorderlessList.cs
6,519
C#
// ----------------------------------------------------------------------------- // 让 .NET 开发更简单,更通用,更流行。 // Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd. // // 框架名称:Furion // 框架作者:百小僧 // 框架版本:2.14.1 // 源码地址:Gitee: https://gitee.com/dotnetchina/Furion // Github:https://github.com/monksoul/Furion // 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE) // ----------------------------------------------------------------------------- using Furion.DependencyInjection; using System; namespace Furion.DataValidation { /// <summary> /// 验证消息类型特性 /// </summary> [SuppressSniffer, AttributeUsage(AttributeTargets.Enum)] public sealed class ValidationMessageTypeAttribute : Attribute { } }
30
81
0.542667
[ "Apache-2.0" ]
Cuixq123/Furion
framework/Furion.Pure/DataValidation/Attributes/ValidationMessageTypeAttribute.cs
869
C#
using Nextt_Gestao_Compra.Infre.CrossCutting.Configuracao; using System.Web.Http; namespace Nextt_Gestao_Compra.Apresentacao.API { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.DependencyResolver = AplicacaoConfig.RetornaDIContaimer(); // Rotas da API da Web AplicacaoConfig.RegisgrarMapeamento(); config = AplicacaoConfig.RegistraConfiguracaoGlobal(config); } } }
31.625
77
0.629776
[ "MIT" ]
Philipe1985/NexttWeb
Nextt_Gestao_Compra/Nextt_Gestao_Compra.Apresentacao.API/App_Start/WebApiConfig.cs
761
C#
namespace AnnoSavegameViewer.Structures.Savegame.Generated { using AnnoSavegameViewer.Serialization.Core; public class RegionValue { [BinaryContent(Name = "id", NodeType = BinaryContentTypes.Attribute)] public object Id { get; set; } } }
25.4
73
0.748031
[ "MIT" ]
Veraatversus/AnnoSavegameViewer
src/AnnoSavegameViewer/GeneratedA7s/Structures/Savegame2/Generated/Content/RegionValue.cs
254
C#
/// <summary> /// The icon uv model. /// Contains information neccessary for looking up textures from an atlus. /// </summary> namespace bg3_modders_multitool.Models { public class IconUV { public string MapKey { get; set; } public float U1 { get; set; } public float U2 { get; set; } public float V1 { get; set; } public float V2 { get; set; } } }
25.125
74
0.599502
[ "MIT" ]
ShinyHobo/BG3-Modders-Multitool
bg3-modders-multitool/bg3-modders-multitool/Models/IconUV.cs
404
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.cr.Transform; using Aliyun.Acs.cr.Transform.V20160607; namespace Aliyun.Acs.cr.Model.V20160607 { public class UpdateRepoAuthorizationRequest : RoaAcsRequest<UpdateRepoAuthorizationResponse> { public UpdateRepoAuthorizationRequest() : base("cr", "2016-06-07", "UpdateRepoAuthorization", "cr", "openAPI") { UriPattern = "/repos/[RepoNamespace]/[RepoName]/authorizations/[AuthorizeId]"; Method = MethodType.POST; } private string repoNamespace; private string repoName; private long? authorizeId; public string RepoNamespace { get { return repoNamespace; } set { repoNamespace = value; DictionaryUtil.Add(PathParameters, "RepoNamespace", value); } } public string RepoName { get { return repoName; } set { repoName = value; DictionaryUtil.Add(PathParameters, "RepoName", value); } } public long? AuthorizeId { get { return authorizeId; } set { authorizeId = value; DictionaryUtil.Add(PathParameters, "AuthorizeId", value.ToString()); } } public override UpdateRepoAuthorizationResponse GetResponse(UnmarshallerContext unmarshallerContext) { return UpdateRepoAuthorizationResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
26.277778
108
0.692178
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-cr/Cr/Model/V20160607/UpdateRepoAuthorizationRequest.cs
2,365
C#
// <copyright file="HealthCheckStatusExtensions.cs" company="Allan Hardy"> // Copyright (c) Allan Hardy. All rights reserved. // </copyright> namespace App.Metrics.Health { public static class HealthCheckStatusExtensions { public static bool IsDegraded(this HealthCheckStatus status) { return status == HealthCheckStatus.Degraded; } public static bool IsHealthy(this HealthCheckStatus status) { return status == HealthCheckStatus.Healthy; } public static bool IsIgnored(this HealthCheckStatus status) { return status == HealthCheckStatus.Ignored; } public static bool IsUnhealthy(this HealthCheckStatus status) { return status == HealthCheckStatus.Unhealthy; } } }
41.941176
119
0.746143
[ "Apache-2.0" ]
dkutetsky/Health
src/App.Metrics.Health.Abstractions/HealthCheckStatusExtensions.cs
715
C#
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V8.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Settings for <see cref="AdGroupAssetServiceClient"/> instances.</summary> public sealed partial class AdGroupAssetServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="AdGroupAssetServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="AdGroupAssetServiceSettings"/>.</returns> public static AdGroupAssetServiceSettings GetDefault() => new AdGroupAssetServiceSettings(); /// <summary>Constructs a new <see cref="AdGroupAssetServiceSettings"/> object with default settings.</summary> public AdGroupAssetServiceSettings() { } private AdGroupAssetServiceSettings(AdGroupAssetServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetAdGroupAssetSettings = existing.GetAdGroupAssetSettings; MutateAdGroupAssetsSettings = existing.MutateAdGroupAssetsSettings; OnCopy(existing); } partial void OnCopy(AdGroupAssetServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AdGroupAssetServiceClient.GetAdGroupAsset</c> and <c>AdGroupAssetServiceClient.GetAdGroupAssetAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetAdGroupAssetSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AdGroupAssetServiceClient.MutateAdGroupAssets</c> and /// <c>AdGroupAssetServiceClient.MutateAdGroupAssetsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateAdGroupAssetsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="AdGroupAssetServiceSettings"/> object.</returns> public AdGroupAssetServiceSettings Clone() => new AdGroupAssetServiceSettings(this); } /// <summary> /// Builder class for <see cref="AdGroupAssetServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class AdGroupAssetServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdGroupAssetServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public AdGroupAssetServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public AdGroupAssetServiceClientBuilder() { UseJwtAccessWithScopes = AdGroupAssetServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref AdGroupAssetServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdGroupAssetServiceClient> task); /// <summary>Builds the resulting client.</summary> public override AdGroupAssetServiceClient Build() { AdGroupAssetServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<AdGroupAssetServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<AdGroupAssetServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private AdGroupAssetServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return AdGroupAssetServiceClient.Create(callInvoker, Settings); } private async stt::Task<AdGroupAssetServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return AdGroupAssetServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => AdGroupAssetServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdGroupAssetServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => AdGroupAssetServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>AdGroupAssetService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage ad group assets. /// </remarks> public abstract partial class AdGroupAssetServiceClient { /// <summary> /// The default endpoint for the AdGroupAssetService service, which is a host of "googleads.googleapis.com" and /// a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default AdGroupAssetService scopes.</summary> /// <remarks> /// The default AdGroupAssetService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="AdGroupAssetServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="AdGroupAssetServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="AdGroupAssetServiceClient"/>.</returns> public static stt::Task<AdGroupAssetServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new AdGroupAssetServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="AdGroupAssetServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="AdGroupAssetServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="AdGroupAssetServiceClient"/>.</returns> public static AdGroupAssetServiceClient Create() => new AdGroupAssetServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="AdGroupAssetServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="AdGroupAssetServiceSettings"/>.</param> /// <returns>The created <see cref="AdGroupAssetServiceClient"/>.</returns> internal static AdGroupAssetServiceClient Create(grpccore::CallInvoker callInvoker, AdGroupAssetServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } AdGroupAssetService.AdGroupAssetServiceClient grpcClient = new AdGroupAssetService.AdGroupAssetServiceClient(callInvoker); return new AdGroupAssetServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC AdGroupAssetService client</summary> public virtual AdGroupAssetService.AdGroupAssetServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested ad group asset in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::AdGroupAsset GetAdGroupAsset(GetAdGroupAssetRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested ad group asset in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupAsset> GetAdGroupAssetAsync(GetAdGroupAssetRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested ad group asset in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupAsset> GetAdGroupAssetAsync(GetAdGroupAssetRequest request, st::CancellationToken cancellationToken) => GetAdGroupAssetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested ad group asset in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group asset to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::AdGroupAsset GetAdGroupAsset(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdGroupAsset(new GetAdGroupAssetRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested ad group asset in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group asset to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupAsset> GetAdGroupAssetAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdGroupAssetAsync(new GetAdGroupAssetRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested ad group asset in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group asset to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupAsset> GetAdGroupAssetAsync(string resourceName, st::CancellationToken cancellationToken) => GetAdGroupAssetAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested ad group asset in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group asset to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::AdGroupAsset GetAdGroupAsset(gagvr::AdGroupAssetName resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdGroupAsset(new GetAdGroupAssetRequest { ResourceNameAsAdGroupAssetName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested ad group asset in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group asset to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupAsset> GetAdGroupAssetAsync(gagvr::AdGroupAssetName resourceName, gaxgrpc::CallSettings callSettings = null) => GetAdGroupAssetAsync(new GetAdGroupAssetRequest { ResourceNameAsAdGroupAssetName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested ad group asset in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the ad group asset to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AdGroupAsset> GetAdGroupAssetAsync(gagvr::AdGroupAssetName resourceName, st::CancellationToken cancellationToken) => GetAdGroupAssetAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes ad group assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [NotAllowlistedError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateAdGroupAssetsResponse MutateAdGroupAssets(MutateAdGroupAssetsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes ad group assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [NotAllowlistedError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdGroupAssetsResponse> MutateAdGroupAssetsAsync(MutateAdGroupAssetsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes ad group assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [NotAllowlistedError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdGroupAssetsResponse> MutateAdGroupAssetsAsync(MutateAdGroupAssetsRequest request, st::CancellationToken cancellationToken) => MutateAdGroupAssetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes ad group assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [NotAllowlistedError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose ad group assets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ad group assets. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateAdGroupAssetsResponse MutateAdGroupAssets(string customerId, scg::IEnumerable<AdGroupAssetOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateAdGroupAssets(new MutateAdGroupAssetsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes ad group assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [NotAllowlistedError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose ad group assets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ad group assets. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdGroupAssetsResponse> MutateAdGroupAssetsAsync(string customerId, scg::IEnumerable<AdGroupAssetOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateAdGroupAssetsAsync(new MutateAdGroupAssetsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes ad group assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [NotAllowlistedError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose ad group assets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ad group assets. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdGroupAssetsResponse> MutateAdGroupAssetsAsync(string customerId, scg::IEnumerable<AdGroupAssetOperation> operations, st::CancellationToken cancellationToken) => MutateAdGroupAssetsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>AdGroupAssetService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage ad group assets. /// </remarks> public sealed partial class AdGroupAssetServiceClientImpl : AdGroupAssetServiceClient { private readonly gaxgrpc::ApiCall<GetAdGroupAssetRequest, gagvr::AdGroupAsset> _callGetAdGroupAsset; private readonly gaxgrpc::ApiCall<MutateAdGroupAssetsRequest, MutateAdGroupAssetsResponse> _callMutateAdGroupAssets; /// <summary> /// Constructs a client wrapper for the AdGroupAssetService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="AdGroupAssetServiceSettings"/> used within this client.</param> public AdGroupAssetServiceClientImpl(AdGroupAssetService.AdGroupAssetServiceClient grpcClient, AdGroupAssetServiceSettings settings) { GrpcClient = grpcClient; AdGroupAssetServiceSettings effectiveSettings = settings ?? AdGroupAssetServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetAdGroupAsset = clientHelper.BuildApiCall<GetAdGroupAssetRequest, gagvr::AdGroupAsset>(grpcClient.GetAdGroupAssetAsync, grpcClient.GetAdGroupAsset, effectiveSettings.GetAdGroupAssetSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetAdGroupAsset); Modify_GetAdGroupAssetApiCall(ref _callGetAdGroupAsset); _callMutateAdGroupAssets = clientHelper.BuildApiCall<MutateAdGroupAssetsRequest, MutateAdGroupAssetsResponse>(grpcClient.MutateAdGroupAssetsAsync, grpcClient.MutateAdGroupAssets, effectiveSettings.MutateAdGroupAssetsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateAdGroupAssets); Modify_MutateAdGroupAssetsApiCall(ref _callMutateAdGroupAssets); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetAdGroupAssetApiCall(ref gaxgrpc::ApiCall<GetAdGroupAssetRequest, gagvr::AdGroupAsset> call); partial void Modify_MutateAdGroupAssetsApiCall(ref gaxgrpc::ApiCall<MutateAdGroupAssetsRequest, MutateAdGroupAssetsResponse> call); partial void OnConstruction(AdGroupAssetService.AdGroupAssetServiceClient grpcClient, AdGroupAssetServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC AdGroupAssetService client</summary> public override AdGroupAssetService.AdGroupAssetServiceClient GrpcClient { get; } partial void Modify_GetAdGroupAssetRequest(ref GetAdGroupAssetRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateAdGroupAssetsRequest(ref MutateAdGroupAssetsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested ad group asset in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::AdGroupAsset GetAdGroupAsset(GetAdGroupAssetRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetAdGroupAssetRequest(ref request, ref callSettings); return _callGetAdGroupAsset.Sync(request, callSettings); } /// <summary> /// Returns the requested ad group asset in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::AdGroupAsset> GetAdGroupAssetAsync(GetAdGroupAssetRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetAdGroupAssetRequest(ref request, ref callSettings); return _callGetAdGroupAsset.Async(request, callSettings); } /// <summary> /// Creates, updates, or removes ad group assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [NotAllowlistedError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateAdGroupAssetsResponse MutateAdGroupAssets(MutateAdGroupAssetsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAdGroupAssetsRequest(ref request, ref callSettings); return _callMutateAdGroupAssets.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes ad group assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [NotAllowlistedError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateAdGroupAssetsResponse> MutateAdGroupAssetsAsync(MutateAdGroupAssetsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAdGroupAssetsRequest(ref request, ref callSettings); return _callMutateAdGroupAssets.Async(request, callSettings); } } }
49.889488
563
0.642417
[ "Apache-2.0" ]
friedenberg/google-ads-dotnet
src/V8/Services/AdGroupAssetServiceClient.g.cs
37,018
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Model.Factory { /// <summary> /// 简单工厂的应用 /// </summary> public static class SimpleTicketFactory { /// <summary> /// 将外部参数封装到简单工厂中 /// </summary> /// <param name="ticketType"></param> /// <returns></returns> public static TicketFactory CreateTicketFactory(string ticketType) { TicketFactory factory; switch (ticketType) { case "飞机票": factory = new AirFactory(); break; case "火车票": factory = new RailwayFactory(); break; case "汽车票": factory = new BusFactory(); break; default: return null; } return factory; } public static Type CreateTicketType(string ticketType) { switch (ticketType) { case "飞机票": return typeof(AirTicket); case "火车票": return typeof(RailwayTicket); case "汽车票": return typeof(BusTicket); default: return null; } } public static Tickets CreateTicket(string ticketType, string beginning, string destination) { TicketFactory factory = CreateTicketFactory(ticketType); return factory.CreateTicket(beginning, destination); } } }
27.177419
99
0.478338
[ "Apache-2.0" ]
imwyw/.net
Src/DesignPatternsDemo/DesignComprehensiveTickets/Model/Factory/SimpleTicketFactory.cs
1,763
C#
using System; using System.Collections.Generic; using System.Text; namespace CoreAngular.AdventureWorks { /////////////////////////////////////////////////////////////////////////////// // SAMPLE: Hashing data with salt using MD5 and several SHA algorithms. // // To run this sample, create a new Visual C# project using the Console // Application template and replace the contents of the Class1.cs file with // the code below. // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. // // Copyright (C) 2002 Obviex(TM). All rights reserved. // using System; using System.Text; using System.Security.Cryptography; /// <summary> /// This class generates and compares hashes using MD5, SHA1, SHA256, SHA384, /// and SHA512 hashing algorithms. Before computing a hash, it appends a /// randomly generated salt to the plain text, and stores this salt appended /// to the result. To verify another plain text value against the given hash, /// this class will retrieve the salt value from the hash string and use it /// when computing a new hash of the plain text. Appending a salt value to /// the hash may not be the most efficient approach, so when using hashes in /// a real-life application, you may choose to store them separately. You may /// also opt to keep results as byte arrays instead of converting them into /// base64-encoded strings. /// </summary> public class SimpleHash { /// <summary> /// Generates a hash for the given plain text value and returns a /// base64-encoded result. Before the hash is computed, a random salt /// is generated and appended to the plain text. This salt is stored at /// the end of the hash value, so it can be used later for hash /// verification. /// </summary> /// <param name="plainText"> /// Plaintext value to be hashed. The function does not check whether /// this parameter is null. /// </param> /// <param name="hashAlgorithm"> /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1", /// "SHA256", "SHA384", and "SHA512" (if any other value is specified /// MD5 hashing algorithm will be used). This value is case-insensitive. /// </param> /// <param name="saltBytes"> /// Salt bytes. This parameter can be null, in which case a random salt /// value will be generated. /// </param> /// <returns> /// Hash value formatted as a base64-encoded string. /// </returns> public static string ComputeHash(string plainText, string hashAlgorithm, byte[] saltBytes) { // If salt is not specified, generate it on the fly. if (saltBytes == null) { // Define min and max salt sizes. int minSaltSize = 4; int maxSaltSize = 8; // Generate a random number for the size of the salt. Random random = new Random(); int saltSize = random.Next(minSaltSize, maxSaltSize); // Allocate a byte array, which will hold the salt. saltBytes = new byte[saltSize]; // Initialize a random number generator. RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); // Fill the salt with cryptographically strong byte values. rng.GetNonZeroBytes(saltBytes); } // Convert plain text into a byte array. byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); // Allocate array, which will hold plain text and salt. byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length]; // Copy plain text bytes into resulting array. for (int i = 0; i < plainTextBytes.Length; i++) plainTextWithSaltBytes[i] = plainTextBytes[i]; // Append salt bytes to the resulting array. for (int i = 0; i < saltBytes.Length; i++) plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i]; // Because we support multiple hashing algorithms, we must define // hash object as a common (abstract) base class. We will specify the // actual hashing algorithm class later during object creation. HashAlgorithm hash; // Make sure hashing algorithm name is specified. if (hashAlgorithm == null) hashAlgorithm = ""; // Initialize appropriate hashing algorithm class. switch (hashAlgorithm.ToUpper()) { case "SHA1": hash = new SHA1Managed(); break; case "SHA256": hash = new SHA256Managed(); break; case "SHA384": hash = new SHA384Managed(); break; case "SHA512": hash = new SHA512Managed(); break; default: hash = new MD5CryptoServiceProvider(); break; } // Compute hash value of our plain text with appended salt. byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes); // Create array which will hold hash and original salt bytes. byte[] hashWithSaltBytes = new byte[hashBytes.Length + saltBytes.Length]; // Copy hash bytes into resulting array. for (int i = 0; i < hashBytes.Length; i++) hashWithSaltBytes[i] = hashBytes[i]; // Append salt bytes to the result. for (int i = 0; i < saltBytes.Length; i++) hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i]; // Convert result into a base64-encoded string. string hashValue = Convert.ToBase64String(hashWithSaltBytes); // Return the result. return hashValue; } /// <summary> /// Compares a hash of the specified plain text value to a given hash /// value. Plain text is hashed with the same salt value as the original /// hash. /// </summary> /// <param name="plainText"> /// Plain text to be verified against the specified hash. The function /// does not check whether this parameter is null. /// </param> /// <param name="hashAlgorithm"> /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1", /// "SHA256", "SHA384", and "SHA512" (if any other value is specified, /// MD5 hashing algorithm will be used). This value is case-insensitive. /// </param> /// <param name="hashValue"> /// Base64-encoded hash value produced by ComputeHash function. This value /// includes the original salt appended to it. /// </param> /// <returns> /// If computed hash mathes the specified hash the function the return /// value is true; otherwise, the function returns false. /// </returns> public static bool VerifyHash(string plainText, string hashAlgorithm, string hashValue) { // Convert base64-encoded hash value into a byte array. byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue); // We must know size of hash (without salt). int hashSizeInBits, hashSizeInBytes; // Make sure that hashing algorithm name is specified. if (hashAlgorithm == null) hashAlgorithm = ""; // Size of hash is based on the specified algorithm. switch (hashAlgorithm.ToUpper()) { case "SHA1": hashSizeInBits = 160; break; case "SHA256": hashSizeInBits = 256; break; case "SHA384": hashSizeInBits = 384; break; case "SHA512": hashSizeInBits = 512; break; default: // Must be MD5 hashSizeInBits = 128; break; } // Convert size of hash from bits to bytes. hashSizeInBytes = hashSizeInBits / 8; // Make sure that the specified hash value is long enough. if (hashWithSaltBytes.Length < hashSizeInBytes) return false; // Allocate array to hold original salt bytes retrieved from hash. byte[] saltBytes = new byte[hashWithSaltBytes.Length - hashSizeInBytes]; // Copy salt from the end of the hash to the new array. for (int i = 0; i < saltBytes.Length; i++) saltBytes[i] = hashWithSaltBytes[hashSizeInBytes + i]; // Compute a new hash string. string expectedHashString = ComputeHash(plainText, hashAlgorithm, saltBytes); // If the computed hash matches the specified hash, // the plain text value must be correct. return (hashValue == expectedHashString); } } /// <summary> /// Illustrates the use of the SimpleHash class. /// </summary> public class SimpleHashTest { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { string password = "myP@5sw0rd"; // original password string wrongPassword = "password"; // wrong password string passwordHashMD5 = SimpleHash.ComputeHash(password, "MD5", null); string passwordHashSha1 = SimpleHash.ComputeHash(password, "SHA1", null); string passwordHashSha256 = SimpleHash.ComputeHash(password, "SHA256", null); string passwordHashSha384 = SimpleHash.ComputeHash(password, "SHA384", null); string passwordHashSha512 = SimpleHash.ComputeHash(password, "SHA512", null); Console.WriteLine("COMPUTING HASH VALUES\r\n"); Console.WriteLine("MD5 : {0}", passwordHashMD5); Console.WriteLine("SHA1 : {0}", passwordHashSha1); Console.WriteLine("SHA256: {0}", passwordHashSha256); Console.WriteLine("SHA384: {0}", passwordHashSha384); Console.WriteLine("SHA512: {0}", passwordHashSha512); Console.WriteLine(""); Console.WriteLine("COMPARING PASSWORD HASHES\r\n"); Console.WriteLine("MD5 (good): {0}", SimpleHash.VerifyHash( password, "MD5", passwordHashMD5).ToString()); Console.WriteLine("MD5 (bad) : {0}", SimpleHash.VerifyHash( wrongPassword, "MD5", passwordHashMD5).ToString()); Console.WriteLine("SHA1 (good): {0}", SimpleHash.VerifyHash( password, "SHA1", passwordHashSha1).ToString()); Console.WriteLine("SHA1 (bad) : {0}", SimpleHash.VerifyHash( wrongPassword, "SHA1", passwordHashSha1).ToString()); Console.WriteLine("SHA256 (good): {0}", SimpleHash.VerifyHash( password, "SHA256", passwordHashSha256).ToString()); Console.WriteLine("SHA256 (bad) : {0}", SimpleHash.VerifyHash( wrongPassword, "SHA256", passwordHashSha256).ToString()); Console.WriteLine("SHA384 (good): {0}", SimpleHash.VerifyHash( password, "SHA384", passwordHashSha384).ToString()); Console.WriteLine("SHA384 (bad) : {0}", SimpleHash.VerifyHash( wrongPassword, "SHA384", passwordHashSha384).ToString()); Console.WriteLine("SHA512 (good): {0}", SimpleHash.VerifyHash( password, "SHA512", passwordHashSha512).ToString()); Console.WriteLine("SHA512 (bad) : {0}", SimpleHash.VerifyHash( wrongPassword, "SHA512", passwordHashSha512).ToString()); } } // // END OF FILE }
42.415625
83
0.525308
[ "MIT" ]
chesteryang/CoreAngular
CoreAngular.AdventureWorks/SmpleHash.cs
13,575
C#
using Core.Ids; using Core.Marten.Events; using Core.Marten.Ids; using Core.Marten.Subscriptions; using Marten; using Marten.Events.Daemon.Resiliency; using Marten.Events.Projections; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Weasel.Core; namespace Core.Marten; public class Config { private const string DefaultSchema = "public"; public string ConnectionString { get; set; } = default!; public string WriteModelSchema { get; set; } = DefaultSchema; public string ReadModelSchema { get; set; } = DefaultSchema; public bool ShouldRecreateDatabase { get; set; } = false; public DaemonMode DaemonMode { get; set; } = DaemonMode.Solo; public bool UseMetadata = true; } public static class MartenConfigExtensions { private const string DefaultConfigKey = "EventStore"; public static IServiceCollection AddMarten( this IServiceCollection services, IConfiguration config, Action<StoreOptions>? configureOptions = null, string configKey = DefaultConfigKey ) { var martenConfig = config.GetSection(configKey).Get<Config>(); services .AddScoped<IIdGenerator, MartenIdGenerator>() .AddScoped<IMartenAppendScope, MartenAppendScope>() .AddMartenAppendScope() .AddMarten(sp => SetStoreOptions(sp, martenConfig, configureOptions)) .ApplyAllDatabaseChangesOnStartup() .AddAsyncDaemon(DaemonMode.Solo); return services; } private static StoreOptions SetStoreOptions( IServiceProvider serviceProvider, Config config, Action<StoreOptions>? configureOptions = null ) { var options = new StoreOptions(); options.Connection(config.ConnectionString); options.AutoCreateSchemaObjects = AutoCreate.CreateOrUpdate; var schemaName = Environment.GetEnvironmentVariable("SchemaName"); options.Events.DatabaseSchemaName = schemaName ?? config.WriteModelSchema; options.DatabaseSchemaName = schemaName ?? config.ReadModelSchema; options.UseDefaultSerialization( EnumStorage.AsString, nonPublicMembersStorage: NonPublicMembersStorage.All ); options.Projections.Add( new MartenSubscription( new[] { new MartenEventPublisher(serviceProvider) }, serviceProvider.GetRequiredService<ILogger<MartenSubscription>>() ), ProjectionLifecycle.Async, "MartenSubscription" ); configureOptions?.Invoke(options); if (config.UseMetadata) { options.Events.MetadataConfig.CausationIdEnabled = true; options.Events.MetadataConfig.CorrelationIdEnabled = true; } return options; } }
30.87234
82
0.683666
[ "MIT" ]
mehdihadeli/EventSourcing.NetCore
Core.Marten/Config.cs
2,902
C#
using log4net; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Web.helper { /// <summary> /// 捕获程序出错日志 /// </summary> public class Log4NetExceptionFilter : HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { string message = string.Format("消息类型:{0}<br>消息内容:{1}<br>引发异常的方法:{2}<br>引发异常源:{3}" , filterContext.Exception.GetType().Name , filterContext.Exception.Message , filterContext.Exception.TargetSite , filterContext.Exception.Source + filterContext.Exception.StackTrace ); //记录日志 CZLogger.Logger.Error(message); //抛出异常信息 filterContext.Controller.TempData["ExceptionAttributeMessages"] = message; //转向 filterContext.ExceptionHandled = true; filterContext.Result = new RedirectResult("/Home/Error/"); } } }
29.333333
93
0.604167
[ "Apache-2.0" ]
knifecaojia/CoinsPro
Src/YTWL/WeiXin/CoinNewsMVC/Web/helper/Log4NetExceptionFilter.cs
1,146
C#
using System.Windows.Controls; using Kebler.Models.Interfaces; namespace Kebler.Views { /// <summary> /// Interaction logic for DialogBoxView.xaml /// </summary> public partial class DialogBoxView : IDialogBox { public DialogBoxView() { InitializeComponent(); PWD = DialogPasswordBox; TBX = TBXC; } public PasswordBox PWD { get; } public TextBox TBX { get; } } }
22.333333
52
0.577825
[ "Apache-2.0" ]
69NEO69/Kebler
src/Kebler/Views/DialogBoxView.xaml.cs
471
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace Opc.Ua.Models { using Opc.Ua.Extensions; using Opc.Ua.Nodeset; using System; using System.Linq; using System.Collections.Generic; using System.Collections; /// <summary> /// Represents a node in the form of its attributes /// </summary> public class NodeAttributeSet : INodeAttributes, INode, IEncodeable { /// <summary> /// Constructor /// </summary> public NodeAttributeSet() { _namespaces = new NamespaceTable(); _attributes = new SortedDictionary<uint, DataValue>(); } /// <summary> /// Constructor /// </summary> public NodeAttributeSet(ExpandedNodeId nodeId) : this(nodeId, new NamespaceTable()) { } /// <summary> /// Constructor /// </summary> public NodeAttributeSet(ExpandedNodeId nodeId, NodeClass nodeClass, QualifiedName browseName) : this(nodeId, new NamespaceTable()) { NodeClass = nodeClass; BrowseName = browseName; } /// <summary> /// Constructor /// </summary> public NodeAttributeSet(ExpandedNodeId nodeId, NamespaceTable namespaces) { _namespaces = namespaces ?? throw new ArgumentNullException(nameof(namespaces)); if (Ua.NodeId.IsNull(nodeId)) { throw new ArgumentNullException(nameof(nodeId)); } _attributes = new SortedDictionary<uint, DataValue>(); foreach (var identifier in TypeMaps.Attributes.Value.Identifiers) { _attributes.Add(identifier, null); } _attributes[Attributes.NodeId] = new DataValue(new Variant(nodeId.ToNodeId(namespaces))); } /// <summary> /// Copy constructor /// </summary> /// <param name="nodeId"></param> /// <param name="namespaces"></param> /// <param name="attributes"></param> protected NodeAttributeSet(ExpandedNodeId nodeId, NamespaceTable namespaces, SortedDictionary<uint, DataValue> attributes) : this(nodeId, namespaces) { foreach (var item in attributes) { _attributes[item.Key] = (DataValue)item.Value.MemberwiseClone(); } } /// <inheritdoc/> public object this[uint attribute] { get => GetAttribute<object>(attribute); set => SetAttribute(attribute, value); } /// <inheritdoc/> public IEnumerator<KeyValuePair<uint, DataValue>> GetEnumerator() { return _attributes.GetEnumerator(); } /// <inheritdoc/> IEnumerator IEnumerable.GetEnumerator() { return _attributes.GetEnumerator(); } /// <inheritdoc/> public ExpandedNodeId TypeId => DataTypeIds.Node; /// <inheritdoc/> public ExpandedNodeId BinaryEncodingId => ObjectIds.Node_Encoding_DefaultBinary; /// <inheritdoc/> public ExpandedNodeId XmlEncodingId => ObjectIds.Node_Encoding_DefaultXml; /// <inheritdoc/> public ExpandedNodeId TypeDefinitionId => GetAttribute<ExtensionObject>(Attributes.DataTypeDefinition)?.TypeId; /// <inheritdoc/> public ExpandedNodeId NodeId => LocalId.ToExpandedNodeId(_namespaces); /// <inheritdoc/> public NodeId LocalId => this.GetAttribute(Attributes.NodeId, Ua.NodeId.Null); /// <inheritdoc/> public NodeClass NodeClass { get => this.GetAttribute<NodeClass>( Attributes.NodeClass, null) ?? NodeClass.Unspecified; set => SetAttribute( Attributes.NodeClass, value); } /// <summary> /// Whether this is a historic node /// </summary> public bool IsHistorizedNode => (EventNotifier.HasValue && (EventNotifier.Value & EventNotifiers.HistoryRead) != 0) || (AccessLevel.HasValue && ((AccessLevelType)AccessLevel.Value & AccessLevelType.HistoryRead) != 0); /// <inheritdoc/> public QualifiedName BrowseName { get => this.GetAttribute<QualifiedName>( Attributes.BrowseName, null); set => SetAttribute( Attributes.BrowseName, value); } /// <inheritdoc/> public LocalizedText DisplayName { get => this.GetAttribute<LocalizedText>( Attributes.DisplayName, null); set => SetAttribute( Attributes.DisplayName, value); } /// <inheritdoc/> public LocalizedText Description { get => this.GetAttribute<LocalizedText>( Attributes.Description, null); set => SetAttribute( Attributes.Description, value); } /// <inheritdoc/> public ushort? AccessRestrictions { get => this.GetAttribute<ushort>( Attributes.AccessRestrictions, null); set => SetAttribute( Attributes.AccessRestrictions, value); } /// <inheritdoc/> public uint? WriteMask { get => this.GetAttribute<uint>( Attributes.WriteMask, null); set => SetAttribute( Attributes.WriteMask, value); } /// <inheritdoc/> public uint? UserWriteMask { get => this.GetAttribute<uint>( Attributes.UserWriteMask, null); set => SetAttribute( Attributes.UserWriteMask, value); } /// <inheritdoc/> public bool? IsAbstract { get => this.GetAttribute<bool>( Attributes.IsAbstract, null); set => SetAttribute( Attributes.IsAbstract, value); } /// <inheritdoc/> public bool? ContainsNoLoops { get => this.GetAttribute<bool>( Attributes.ContainsNoLoops, null); set => SetAttribute( Attributes.ContainsNoLoops, value); } /// <inheritdoc/> public byte? EventNotifier { get => this.GetAttribute<byte>( Attributes.EventNotifier, null); set => SetAttribute( Attributes.EventNotifier, value); } /// <inheritdoc/> public bool? Executable { get => this.GetAttribute<bool>( Attributes.Executable, null); set => SetAttribute( Attributes.Executable, value); } /// <inheritdoc/> public bool? UserExecutable { get => this.GetAttribute<bool>( Attributes.UserExecutable, null); set => SetAttribute( Attributes.UserExecutable, value); } /// <inheritdoc/> public ExtensionObject DataTypeDefinition { get => this.GetAttribute<ExtensionObject>( Attributes.DataTypeDefinition, null); set => SetAttribute( Attributes.DataTypeDefinition, value); } /// <inheritdoc/> public byte? AccessLevel { get => this.GetAttribute<byte>( Attributes.AccessLevel, null); set => SetAttribute( Attributes.AccessLevel, value); } /// <inheritdoc/> public uint? AccessLevelEx { get => this.GetAttribute<uint>( Attributes.AccessLevelEx, null); set => SetAttribute( Attributes.AccessLevelEx, value); } /// <inheritdoc/> public byte? UserAccessLevel { get => this.GetAttribute<byte>( Attributes.UserAccessLevel, null); set => SetAttribute( Attributes.UserAccessLevel, value); } /// <inheritdoc/> public NodeId DataType { get => this.GetAttribute<NodeId>( Attributes.DataType, null); set => SetAttribute( Attributes.DataType, value); } /// <inheritdoc/> public int? ValueRank { get => this.GetAttribute<int>( Attributes.ValueRank, null); set => SetAttribute( Attributes.ValueRank, value); } /// <inheritdoc/> public uint[] ArrayDimensions { get => this.GetAttribute<uint[]>( Attributes.ArrayDimensions, null); set => SetAttribute( Attributes.ArrayDimensions, value); } /// <inheritdoc/> public bool? Historizing { get => this.GetAttribute<bool>( Attributes.Historizing, null); set => SetAttribute( Attributes.Historizing, value); } /// <inheritdoc/> public double? MinimumSamplingInterval { get => this.GetAttribute<double>( Attributes.MinimumSamplingInterval, null); set => SetAttribute( Attributes.MinimumSamplingInterval, value); } /// <inheritdoc/> public LocalizedText InverseName { get => this.GetAttribute<LocalizedText>( Attributes.InverseName, null); set => SetAttribute( Attributes.InverseName, value); } /// <inheritdoc/> public bool? Symmetric { get => this.GetAttribute<bool>( Attributes.Symmetric, null); set => SetAttribute( Attributes.Symmetric, value); } /// <inheritdoc/> public IEnumerable<RolePermissionType> RolePermissions { get => this.GetAttribute<ExtensionObject[]>( Attributes.RolePermissions, null)?.Select(ex => ex.Body).OfType<RolePermissionType>(); set => SetAttribute(Attributes.RolePermissions, value?.Select(r => new ExtensionObject(r)).ToArray() ?? new ExtensionObject[0]); } /// <inheritdoc/> public IEnumerable<RolePermissionType> UserRolePermissions { get => this.GetAttribute<ExtensionObject[]>( Attributes.UserRolePermissions, null)?.Select(ex => ex.Body).OfType<RolePermissionType>(); set => SetAttribute(Attributes.UserRolePermissions, value?.Select(r => new ExtensionObject(r)).ToArray() ?? new ExtensionObject[0]); } /// <inheritdoc/> public Variant? Value { get { if (_attributes.TryGetValue(Attributes.Value, out var value) && value != null) { return value.WrappedValue; } return null; } set => _attributes.AddOrUpdate(Attributes.Value, value == null ? null : new DataValue(value.Value)); } /// <summary> /// Get references /// </summary> public List<IReference> References { get; } = new List<IReference>(); /// <inheritdoc/> public virtual void Decode(IDecoder decoder) { decoder.PushNamespace(Namespaces.OpcUa); // now read node class var nodeClass = (NodeClass)_attributeMap.Decode(decoder, Attributes.NodeClass); if (nodeClass == NodeClass.Unspecified) { throw new ServiceResultException(StatusCodes.BadNodeClassInvalid); } SetAttribute(Attributes.NodeClass, nodeClass); foreach (var attributeId in _attributeMap.GetNodeClassAttributes(NodeClass)) { if (attributeId == Attributes.NodeClass) { continue; // Read already first } var value = _attributeMap.Decode(decoder, attributeId); if (value != null) { if (value is DataValue dataValue) { _attributes[attributeId] = dataValue; } else { _attributes[attributeId] = new DataValue(new Variant(value)); } } } References.Clear(); References.AddRange(decoder.ReadEncodeableArray<EncodeableReferenceModel>( nameof(References))?.Select(r => r.Reference)); decoder.PopNamespace(); } /// <inheritdoc/> public virtual void Encode(IEncoder encoder) { encoder.PushNamespace(Namespaces.OpcUa); // Write node class as first element since we need to look it up on decode. _attributeMap.Encode(encoder, Attributes.NodeClass, NodeClass); var optional = false; foreach (var attributeId in _attributeMap.GetNodeClassAttributes(NodeClass)) { if (attributeId == Attributes.NodeClass) { continue; // Read already first } object value = null; if (_attributes.TryGetValue(attributeId, out var result) && result != null) { value = result.WrappedValue.Value; } if (value == null) { value = _attributeMap.GetDefault(NodeClass, attributeId, ref optional); } _attributeMap.Encode(encoder, attributeId, value); } encoder.WriteEncodeableArray(nameof(References), References.Select(r => new EncodeableReferenceModel(r))); encoder.PopNamespace(); } /// <inheritdoc/> public bool IsEqual(IEncodeable encodeable) { if (!(encodeable is NodeAttributeSet node)) { return false; } if (ReferenceEquals(node._attributes, _attributes)) { return true; } if (node.NodeClass != NodeClass) { return false; } if (_attributes.SequenceEqual(node._attributes)) { return true; } var optional = false; var attributes = _attributeMap.GetNodeClassAttributes(NodeClass); foreach (var attributeId in attributes) { var defaultObject = _attributeMap.GetDefault( NodeClass, attributeId, ref optional); object o1 = null; object o2 = null; if (_attributes.TryGetValue(attributeId, out var dataValue)) { o1 = dataValue.Value; } if (node._attributes.TryGetValue(attributeId, out dataValue)) { o2 = dataValue.Value; } if (!Utils.IsEqual(o1 ?? defaultObject, o2 ?? defaultObject)) { return false; } } return true; } /// <inheritdoc/> public T GetAttribute<T>(uint attribute) { if (_attributes.TryGetValue(attribute, out var result) && result != null) { return result.GetValueOrDefault<T>(); } var nodeClass = NodeClass; if (nodeClass == NodeClass.Unspecified) { return default; } var optional = false; var defaultValue = _attributeMap.GetDefault(nodeClass, attribute, ref optional); return (T)defaultValue; } /// <inheritdoc/> public bool TryGetAttribute<T>(uint attribute, out T value) { value = default; try { if (_attributes.TryGetValue(attribute, out var result) && result != null) { value = result.GetValueOrDefault<T>(); return true; } return false; } catch { return false; } } /// <inheritdoc/> public void SetAttribute<T>(uint attribute, T value) { _attributes[attribute] = new DataValue(new Variant(value)); } /// <inheritdoc/> public DataValue GetAttribute(uint attribute) { if (TryGetAttribute(attribute, out var result)) { return result; } return null; } /// <inheritdoc/> public void SetAttribute(uint attribute, DataValue value) { _attributes[attribute] = value; } /// <inheritdoc/> public bool TryGetAttribute(uint attribute, out DataValue value) { return _attributes.TryGetValue(attribute, out value); } /// <inheritdoc/> public override bool Equals(object obj) { if (obj is IEncodeable encodeable) { return IsEqual(encodeable); } return false; } /// <inheritdoc/> public override int GetHashCode() { return NodeId.ToString().GetHashCode(); } /// <inheritdoc/> public override string ToString() { return $"{NodeId} ({BrowseName})"; } /// <summary>Namespaces to use in derived classes</summary> protected readonly NamespaceTable _namespaces; /// <summary>Attributes to use in derived classes</summary> protected SortedDictionary<uint, DataValue> _attributes; private static readonly AttributeMap _attributeMap = new AttributeMap(); } }
35.252941
106
0.532677
[ "MIT" ]
bamajeed/Industrial-IoT
components/opc-ua/src/Microsoft.Azure.IIoT.OpcUa.Protocol/src/Stack/Models/NodeAttributeSet.cs
17,979
C#
using System; using Xamarin.Forms; namespace FormsGallery { class ASAToxicity : ContentPage { public ASAToxicity() { Command<Type> navigateCommand = new Command<Type>(async (Type pageType) => { Page page = (Page)Activator.CreateInstance(pageType); await this.Navigation.PushAsync(page); }); BackgroundColor = Color.White; Label header = new Label { Text = "ASA Toxicity", TextColor = Color.Black, FontSize = 30, FontAttributes = FontAttributes.Bold, HorizontalOptions = LayoutOptions.Center, HorizontalTextAlignment = TextAlignment.Center, }; ScrollView scrollView = new ScrollView { Margin = 0, Padding = 0, Content = new StackLayout { Spacing = 0, Padding = 0, //Orientation = StackOrientation.Vertical, Children = { new StackLayout { Padding = 0, Children = { new Label { FontSize = 20, Text = "Background", TextColor = Color.Black, FontAttributes = FontAttributes.Bold, }, new Label { Text = " ", FontSize = 5, }, } }, new StackLayout { Padding = 0, Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Aspirin is converted to its active metabolite salicylic acid, salicylates at toxic levels are metabolic poisons that: ", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Uncouple oxidative phosphorylation ", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Interfere with the Krebs cycle", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Lead to accumulation of lactic acid & ketoacids\n\n", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = 0, Children = { new Label { FontSize = 20, Text = "Considerations", TextColor = Color.Black, FontAttributes = FontAttributes.Bold, }, new Label { Text = " ", FontSize = 5, }, } }, new StackLayout { Padding = 0, Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Emergency/full stomach", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = 0, Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Consider other toxins ", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = 0, Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Potentially life threatening emergency requiring monitoring: ", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Arterial line for frequent BW", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Consult toxicology/ICU/nephrology", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = 0, Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Severe acidosis:", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Severe AGMA (keto-lactic) with compensatory respiratory alkalosis ", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "↓ pH favours tissue (e.g. brain) passage → toxic effects", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = 0, Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Respiratory:", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Respiratory alkalosis is compensatory mechniasm as alkalinization assists renal elimination ", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Cautious intubation: will not tolerate apnea & ICU ventilator required ", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Non-cardiogenic pulmonary edema can occur", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = 0, Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Central nervous system:", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Uncooperative & co-intoxications", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Profound ↓ LOC", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Cerebral edema", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Neuroglycopenia", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = 0, Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Assess severity & timing:", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Activated charcoal if < 1hour", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Serums ASA levels (note that peak levels can be delayed by 6 hours) \n\n", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = 0, Children = { new Label { FontSize = 20, Text = "Treatment", TextColor = Color.Black, FontAttributes = FontAttributes.Bold, }, new Label { Text = " ", FontSize = 5, }, } }, new StackLayout { Padding = 0, Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Rapid assessment & stabilization of ABCs", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = 0, Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "GI decontamination with activated charcoal: ", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "1st dose: 1g/kg up to 50 grams PO, followed by 25 g PO q2h x 3 ", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = 0, Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Volume resuscitation unless cerebral or pulmonary edema is present", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = 0, Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Empirical glucose if altered LOC even if normal serum glucose", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = 0, Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Urine alkalinization with NaHCO3:", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Bolus: 1 meq/kg IV bolus", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Maintenance: 150 meq NaHCO3 in 1 L of D5W, ", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(40, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Start 2x maintenance ", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(40, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Titrate to urine pH > 7.5. ", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(40, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Continue until serum salicylate < 30 mg/dL", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Monitor & avoid", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(40, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Volume overload", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(40, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Hypokalemia", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = 0, Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Avoid intubation if possible but it may be necessary for:", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Airway protection", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(40, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Lavage/charcoal", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(40, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "GCS < 8", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(40, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Too agitated & delirious for medical procedures such as CVC placement & hemodialysis", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Severe hypoxemia from ASA-induced pulmonary edema", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Maintenance of hyperventilation if respiratory failure occuring (compensation for AGMA)", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = 0, Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Hyperventilate:", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "An abrupt ↓ in salicylate-induced hyperventilation may lead to life-threatening acidosis", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "ICU ventilator available", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = 0, Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Hemodialysis indications:", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Coma or cerebral edema", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Pulmonary edema or fluid overload (limits NaHCO3 administration)", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Renal failure that interferes with salicylate excretion", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Lethal salicylate concentration > 100 mg/dL (7.2 mmol/L)", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, new StackLayout { Padding = new Thickness(20, 0, 0, 0), Orientation = StackOrientation.Horizontal, Children = { new Label { Text = "• ", TextColor = Color.Black, }, new Label { FontSize = 16, Text = "Refractory AGMA despite aggressive management", TextColor = Color.Black, HorizontalOptions = LayoutOptions.Start }, } }, } } }; Button homeButton = new Button { Text = "Home Page", Command = navigateCommand, CommandParameter = typeof(HomePage), Font = Font.SystemFontOfSize(NamedSize.Large), BorderWidth = 1, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.CenterAndExpand }; // Build the page. this.Content = new StackLayout { Children = { header, scrollView, homeButton, } }; } } }
43.232558
161
0.234947
[ "Apache-2.0" ]
EricGrahamMacEachern/anesthesiaconsiderations
anesthesiaconsiderations/anesthesiaconsiderations/ASAToxicity.cs
55,888
C#
using System.Collections; namespace Bumbler { public interface ITable { IColumn[] Columns { get; } string Name { get; } bool HasSingleColumnPrimaryKey { get; } } }
14.384615
42
0.647059
[ "Unlicense" ]
Dreameris/.NET-Common-Library
developers-stuff/common-lib/rhino-tools/SampleApplications/Bumbler/Bumbler/ITable.cs
187
C#
namespace Incoding.MSpecContrib { #region << Using >> using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Incoding.Extensions; #endregion public partial class InventFactory<T> : IInventFactoryDsl<T> { #region IInventFactoryDsl<T> Members public IInventFactoryDsl<T> GenerateTo<TGenerate>(Expression<Func<T, TGenerate>> property) where TGenerate : new() { return GenerateTo(property, null); } public IInventFactoryDsl<T> GenerateTo<TGenerate>(Expression<Func<T, TGenerate>> property, Action<IInventFactoryDsl<TGenerate>> innerDsl) where TGenerate : new() { return Tuning(property, Pleasure.Generator.Invent(innerDsl)); } public IInventFactoryDsl<T> GenerateTo<TGenerate>(Expression<Func<T, IEnumerable<TGenerate>>> property, Action<IInventFactoryDsl<TGenerate>> innerDsl) where TGenerate : new() { var invent = Pleasure.Generator.Invent<List<TGenerate>>(); for (int i = 0; i < invent.Count; i++) invent[i] = Pleasure.Generator.Invent(innerDsl); return Tuning(property, invent); } public IInventFactoryDsl<T> Empty<TGenerate>(Expression<Func<T, TGenerate>> property) { return Empty<TGenerate>(property.GetMemberName()); } public IInventFactoryDsl<T> Empty<TGenerate>(string property) { Guard.NotNull("property", property); VerifyUniqueProperty(property); this.empties.Add(property); return this; } public IInventFactoryDsl<T> Tuning<TValue>(Expression<Func<T, TValue>> property, TValue value) { Guard.NotNull("property", property); var memberName = property.GetMemberName(); Guard.IsConditional("property",typeof(T).GetProperties(bindingFlags) .Where(r=>r.CanWrite) .Select(r => r.Name).Contains(memberName), "Tuning can be use for CanWrite property/field: " + memberName); return Tuning(memberName, value); } public IInventFactoryDsl<T> Tuning(string property, object value) { Guard.NotNull("property", property); VerifyUniqueProperty(property); this.tunings.Set(property, () => value); return this; } public IInventFactoryDsl<T> Ignore(Expression<Func<T, object>> property, string reason) { Guard.NotNull("property", property); return Ignore(property.GetMemberName(), reason); } public IInventFactoryDsl<T> IgnoreBecauseAuto(Expression<Func<T, object>> property) { return Ignore(property, "Auto"); } public IInventFactoryDsl<T> Ignore(string property, string reason) { Guard.NotNull("property", property); VerifyUniqueProperty(property); this.ignoreProperties.Add(property); return this; } public IInventFactoryDsl<T> Callback(Action<T> callback) { Guard.NotNull("callback", callback); this.callbacks.Add(callback); return this; } public IInventFactoryDsl<T> MuteCtor() { this.isMuteCtor = true; return this; } public IInventFactoryDsl<T> Tunings(object propertiesMap) { var dictionary = AnonymousHelper.ToDictionary(propertiesMap); foreach (var valuePair in dictionary) Tuning(valuePair.Key, valuePair.Value); return this; } #endregion } }
33.008772
182
0.601648
[ "Apache-2.0" ]
Incoding-Software/Incoding-Framework
src/Incoding.MSpecContrib/Invent/InventFactory.Dsl.cs
3,763
C#
using System; using System.Collections.Generic; using Task06.BLL.Interfaces; using Task06.DAL.Interfaces; using Task06.Entities; namespace Task06.BLL { public class AwardLogic : IAwardLogic { private readonly IAwardDao awardDao; public AwardLogic(IAwardDao awardDao) { this.awardDao = awardDao; } public Award Add(Award award) { if (award.Title.Length == 0) { throw new ArgumentException(); } return awardDao.Add(award); } public IEnumerable<Award> GetAll() { return awardDao.GetAll(); } public Award GetById(int id) { return awardDao.GetById(id); } public void Remove(int id) { awardDao.Remove(id); } public void Update(int id, Award award) { if (GetById(id) == null || award.Title.Length == 0) { throw new InvalidOperationException(); } awardDao.Update(id, award); } } }
21.960784
63
0.517857
[ "MIT" ]
RayHammer/xt-net-web
xt-net-web/Task06.BLL/AwardLogic.cs
1,122
C#
using System.Diagnostics; using AppCore.Services; using Microsoft.AspNetCore.Mvc; using Web.Models; namespace Web.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } public IActionResult About() { ViewData["Message"] = "About message"; return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
20.714286
112
0.558621
[ "MIT" ]
VKBGroup/core2ntier
Web/Controllers/HomeController.cs
727
C#
// ReSharper disable All namespace OpenTl.Schema { using System; using System.Collections; using OpenTl.Schema; public interface IEncryptedMessage : IObject { long RandomId {get; set;} int ChatId {get; set;} int Date {get; set;} byte[] Bytes {get; set;} } }
14.181818
48
0.608974
[ "MIT" ]
zzz8415/OpenTl.Schema
src/OpenTl.Schema/_generated/_Entities/EncryptedMessage/IEncryptedMessage.cs
314
C#
using System.Collections.Generic; using Essensoft.Paylink.Alipay.Response; namespace Essensoft.Paylink.Alipay.Request { /// <summary> /// alipay.ebpp.community.communityinfo.create /// </summary> public class AlipayEbppCommunityCommunityinfoCreateRequest : IAlipayRequest<AlipayEbppCommunityCommunityinfoCreateResponse> { /// <summary> /// 小区创建 /// </summary> public string BizContent { get; set; } #region IAlipayRequest Members private bool needEncrypt = false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AlipayObject bizModel; public void SetNeedEncrypt(bool needEncrypt) { this.needEncrypt = needEncrypt; } public bool GetNeedEncrypt() { return needEncrypt; } public void SetNotifyUrl(string notifyUrl) { this.notifyUrl = notifyUrl; } public string GetNotifyUrl() { return notifyUrl; } public void SetReturnUrl(string returnUrl) { this.returnUrl = returnUrl; } public string GetReturnUrl() { return returnUrl; } public void SetTerminalType(string terminalType) { this.terminalType = terminalType; } public string GetTerminalType() { return terminalType; } public void SetTerminalInfo(string terminalInfo) { this.terminalInfo = terminalInfo; } public string GetTerminalInfo() { return terminalInfo; } public void SetProdCode(string prodCode) { this.prodCode = prodCode; } public string GetProdCode() { return prodCode; } public string GetApiName() { return "alipay.ebpp.community.communityinfo.create"; } public void SetApiVersion(string apiVersion) { this.apiVersion = apiVersion; } public string GetApiVersion() { return apiVersion; } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary { { "biz_content", BizContent } }; return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
22.806452
127
0.550566
[ "MIT" ]
fory77/paylink
src/Essensoft.Paylink.Alipay/Request/AlipayEbppCommunityCommunityinfoCreateRequest.cs
2,838
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace Listener { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
24.16
76
0.692053
[ "MIT" ]
MorganW09/DesignPatterns
test/Listener/Program.cs
606
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Qpsc.cs" company="Microsoft"> // (c) Microsoft Corporation. All rights reserved. // </copyright> // <summary> // MSAGL class for Gradient Projection implementation in Projection Solver. // </summary> // -------------------------------------------------------------------------------------------------------------------- // Remove this from project build and uncomment here to selectively enable per-class. //#define VERBOSE using System; using System.Collections.Generic; using System.Diagnostics; namespace Microsoft.Msagl.Core.ProjectionSolver { // An instance of Qpsc drives the gradient-projection portion of the Projection Solver. internal class Qpsc { private readonly Parameters solverParameters; // // This class tracks closely to the Ipsep_Cola paper's solve_QPSC function, outside of // the SplitBlocks() and Project() operations. The relevant data are extracted from the // Variables of the solver and placed within the mxA (Hessian A) matrix and vecWiDi (b) // vector on initialization, and then the vecPrevX (x-hat), vecCurX (x-bar), and vecDeltaX // (d) vectors are filled and the normal matrix operations proceed as in the paper. // // From the Ipsep paper: Qpsc solves a system with a goal function that includes minimization of // distance between pairs of neighbors as well as minimization of distances necessary // to satisfy separation constraints. I.e., our goal function is: // f(X) = Sum(i < n) w_i (x_i - a_i)^2 // + Sum(i,j in Edge list) w_ij (x_i - x_j)^2 // Where // X is the vector of CURRENT axis positions (x_i) // a_i is the desired position for each x_i (called d in the paper) // w_ij is the weight of each edge between i and j (possibly multiple edges between // the same i/j pair) // Now we can write f(x) = x'Ax. // The gradient g at X is computed: // g = Ax+b // where b is the negative of the vector (so it becomes Ax-b) // [w_0*d_0 ... w_n-1*d_n-1] // and the optimal stepsize to reduce f in the direction d is: // alpha = d'g / (g'Ag) // In order to compute any of these efficiently we need an expression for the i'th // term of the product of our sparse symmetric square matrix A and a vector v. // Now the i'th term of Av is the inner product of row i of A and the vector v, // i.e. A[i] is the row vector: // Av[i] = A[i] * v = A[i][0]*v[0] + A[i][1]*v[1] + ... +A[i][n-1]*v[n-1] // So what are A[i][0]...A[i][n-1]? // First the diagonal entries: A[i][i] = wi + Sum(wij for every neighbor j of i). // Then the off diagonal entries: A[i][j] = -Sum(wij for each time j is a neighbor of i). // And all A[i][k] where there is no neighbor relation between i and k is 0. // Then, because this is the partial derivative wrt x, each cell is multiplied by 2. // Thus for the small example of 3 variables i, j, and k, with neighbors ij and ik, // the A matrix is (where w is the weight of the variable or neighbor pair): // i j k // +----------------------------------------- // i | 2(wi+wij+wik) -2wij -2wik // j | -2wij 2(wj+wij) 0 // k | -2wik 0 2(wk+wik) // // Because A is sparse, each row is represented as an array of the A[i][0..n] entries // that are nonzero. // The foregoing was updated to the Diagonal scaling paper: // Constrained Stress Majorization Using Diagonally Scaled Gradient Projection.pdf // which is also checked into the project. The implementation here is somewhat modified from it: // // We store the offset o[i] in the variable. // The position for a variable i in a block B is: // y[i] = (S[B] * Y[B] + o[i])/s[i] // // Then the df/dv[i] is: // df/dv[i] = 2 * w[i] * ( y[i] - d[i] ); // // And comp_dfdv(i , AC, ~c) is a bit different too: // Dfdv = df/dv[i] // For each c in AC s.t. i=lv[c] and c!= ~c: // Lambda[c] = comp_dfdv(rv[c], AC, c) // dfdv += Lambda[c] * s[lv[c]] // For each c in AC s.t. i=rv[c] and c!= ~c: // Lambda[c] = comp_dfdv(lv[c], AC, c) // dfdv -= Lambda[c] * s[rv[c]] // // The statistics for the blocks are calculated as follows: // For each variable i we have: // a[i] = S[B] / s[i] // b[i] = o[i] / s[i] // Then: // AD[B] = sum over i=0..n: a[i] * d[i] * w[i] // AB[B] = sum over i=0..n: a[i] * b[i] * w[i] // A2[B] = sum over i=0..n: a[i] * a[i] * w[i] // And the ideal position calculation for the block is then the same as the paper: // Y[B] = (AD[B] - AB[B])/A2[B] // A MatrixCell implements A[i][j] as above. struct MatrixCell { // Initially the summed weights of all variables to which this variable has a relationship // (including self as described above for the diagonal), then modified with scale. internal double Value; // The index of the variable j for this column in the i row (may be same as i). internal readonly uint Column; internal MatrixCell(double w, uint index) { Value = w; Column = index; } } // Store original weight to be restored when done. With the ability to re-Solve() after // updating constraint gaps, we must restore DesiredPos as well. private struct QpscVar { internal readonly Variable Variable; internal readonly double OrigWeight; internal readonly double OrigScale; internal readonly double OrigDesiredPos; internal QpscVar(Variable v) { Variable = v; OrigWeight = v.Weight; OrigScale = v.Scale; OrigDesiredPos = Variable.DesiredPos; } } // // SolveQpsc static data members: These do not change after initialization. // The matrix is sparse in columns for each row, but not in rows, because there is always // at least one entry per row, the diagonal. // private readonly MatrixCell[][] matrixQ; // Sparse matrix A in the Ipsep paper; matrix Q (modified to Q') in the Scaling paper private readonly double[] vectorWiDi; // b (weight * desiredpos) in the Ipsep paper; modified to b' = Sb from the Scaling paper private readonly QpscVar[] vectorQpscVars; // List of variables, for perf (avoid nested block/variable List<> iteration) private readonly List<MatrixCell> newMatrixRow = new List<MatrixCell>(); // current row in AddVariable // // SolveQpsc per-iteration data members: These change with each iteration. // private readonly double[] gradientVector; // g in the paper private readonly double[] vectorQg; // Qg in the paper private readonly double[] vectorPrevY; // y-hat in the paper private readonly double[] vectorCurY; // y-bar in the paper private bool isFirstProjectCall; // If true we're on our first call to Project // Holds the value of f(x) = yQ'y + b'y as computed on the last iteration; used to test for // convergence and updated before HasConverged() returns. private double previousFunctionValue = double.MaxValue; #if VERIFY || VERBOSE // Verify that |d| <= |sg| double normAlphaG; #endif // VERIFY || VERBOSE internal Qpsc(Parameters solverParameters, int cVariables) { this.solverParameters = solverParameters; this.matrixQ = new MatrixCell[cVariables][]; this.vectorWiDi = new double[cVariables]; this.vectorQpscVars = new QpscVar[cVariables]; this.gradientVector = new double[cVariables]; this.vectorQg = new double[cVariables]; this.vectorPrevY = new double[cVariables]; this.vectorCurY = new double[cVariables]; } // // solver.SolveQpsc drives the Qpsc instance as follows: // Initialization: // Qpsc qpsc = new Qpsc(numVariables); // foreach (variable in (foreach block)) // qpsc.AddVariable(variable) // qpsc.VariablesComplete() // Per iteration: // if (!qpsc.PreProject()) break; // solver.SplitBlocks() // solver.Project() // if (!qpsc.PostProject()) break; // Done: // qpsc.ProjectComplete() internal void AddVariable(Variable variable) { Debug.Assert((null == this.matrixQ[variable.Ordinal]) && (null == this.vectorQpscVars[variable.Ordinal].Variable), "variable.Ordinal already exists"); this.isFirstProjectCall = true; // This is the weight times desired position, multiplied by 2.0 per the partial derivative. // We'll use this to keep as close as possible to the desired position on each iteration. this.vectorWiDi[variable.Ordinal] = -2.0 * variable.Weight * variable.DesiredPos; // Temporarily hijack vectorPrevY for use as scratch storage, to handle duplicate // neighbor pairs (take the highest weight). #if VERIFY // Ensure that we've zero'd out all entries after the prior iteration. foreach (double dbl in this.vectorPrevY) { Debug.Assert(0.0 == dbl, "Unexpected nonzero value in vectorPrevY"); } #endif // VERIFY // Sum the weight for cell i,i (the diagonal). this.vectorPrevY[variable.Ordinal] = variable.Weight; if (null != variable.Neighbors) { foreach (var neighborWeightPair in variable.Neighbors) { // We should already have verified this in AddNeighbourPair. Debug.Assert(neighborWeightPair.Neighbor.Ordinal != variable.Ordinal, "self-neighbors are not allowed"); // For the neighbor KeyValuePairs, Key == neighboring variable and Value == relationship // weight. If we've already encountered this pair then we'll sum the relationship weights, under // the assumption the caller will be doing something like creating edges for different reasons, // and multiple edges should be like rubber bands, the sum of the strengths. Mathematica also // sums duplicate weights. // Per above comments: // First the diagonal entries: A[i][i] = wi + Sum(wij for every neighbor j of i). this.vectorPrevY[variable.Ordinal] += neighborWeightPair.Weight; // Then the off diagonal entries: A[i][j] = -Sum(wij for time j is a neighbor of i). this.vectorPrevY[neighborWeightPair.Neighbor.Ordinal] -= neighborWeightPair.Weight; } } // endif null != variable.Neighbors // Add the sparse row to the matrix (all non-zero slots of vectorPrevY are weights to that neighbor). for (uint ii = 0; ii < this.vectorPrevY.Length; ++ii) { if (0.0 != this.vectorPrevY[ii]) { // The diagonal must be > 0 and off-diagonal < 0. Debug.Assert((ii == variable.Ordinal) == (this.vectorPrevY[ii] > 0.0), "Diagonal must be > 0.0"); // All 'A' cells must be 2*(summed weights). this.newMatrixRow.Add(new MatrixCell(this.vectorPrevY[ii] * 2.0, ii)); this.vectorPrevY[ii] = 0.0; } } this.matrixQ[variable.Ordinal] = this.newMatrixRow.ToArray(); this.newMatrixRow.Clear(); this.vectorQpscVars[variable.Ordinal] = new QpscVar(variable); // For the non-Qpsc loop, we consider weights in block reference-position calculation. // Here, we have that in vectorWiDi which we use in calculating gradient and alpha, which // in turn we use to set the gradient-stepped desiredPos. So turn it off for the duration // of Qpsc - we restore it in QpscComplete(). variable.Weight = 1.0; } // end AddVariable() internal void VariablesComplete() { #if VERBOSE System.Diagnostics.Debug.WriteLine("Q and b (before scaling)..."); DumpMatrix(); DumpVector("WiDi", vectorWiDi); #endif // VERBOSE foreach (var qvar in this.vectorQpscVars) { var variable = qvar.Variable; foreach (var cell in this.matrixQ[variable.Ordinal]) { if (cell.Column == variable.Ordinal) { if (solverParameters.Advanced.ScaleInQpsc) { variable.Scale = 1.0 / Math.Sqrt(Math.Abs(cell.Value)); if (double.IsInfinity(variable.Scale)) { variable.Scale = 1.0; } // This is the y = Sx step from the Scaling paper. variable.ActualPos /= variable.Scale; // This is the b' <- Sb step from the Scaling paper this.vectorWiDi[variable.Ordinal] *= variable.Scale; } // This is needed for block re-initialization. this.vectorCurY[variable.Ordinal] = variable.ActualPos; variable.DesiredPos = variable.ActualPos; } } } #if VERBOSE System.Diagnostics.Debug.WriteLine("Qpsc.VariablesComplete Variable scales and values"); System.Diagnostics.Debug.WriteLine(" ordinal origDesired desired scale unscaled actualpos scaled actualpos"); foreach (var qvar in vectorQpscVars) { System.Diagnostics.Debug.WriteLine(" {0} {1} {2} {3} {4} {5}", qvar.Variable.Ordinal, qvar.OrigDesiredPos, qvar.Variable.DesiredPos, qvar.Variable.Scale, qvar.Variable.ActualPos / qvar.Variable.Scale, qvar.Variable.ActualPos); } #endif // VERBOSE if (!solverParameters.Advanced.ScaleInQpsc) { return; } // Now convert mxQ to its scaled form S#QS (noting that the transform of a diagonal matrix S is S // so this is optimized), and we've made the S matrix such that Q[i][i] is 1. The result is in-place // conversion of Q to scaledQ s.t. // for all ii // for all jj // if ii == jj, scaledQ[ii][jj] = 1 // else scaledQ[ii][jj] = Q[ii][jj] * var[ii].scale * var[jj].scale //// for (int rowNum = 0; rowNum < this.matrixQ.Length; ++rowNum) { var row = this.matrixQ[rowNum]; for (int sparseCol = 0; sparseCol < row.Length; ++sparseCol) { if (row[sparseCol].Column == rowNum) { row[sparseCol].Value = 1.0; } else { // Diagonal on left scales rows [SQ], on right scales columns [QS]. row[sparseCol].Value *= this.vectorQpscVars[rowNum].Variable.Scale * this.vectorQpscVars[row[sparseCol].Column].Variable.Scale; } } } #if VERBOSE System.Diagnostics.Debug.WriteLine("Q' and b' (after scaling)..."); DumpMatrix(); DumpVector("WiDi", vectorWiDi); #endif // VERBOSE } // end VariablesComplete() // Called by SolveQpsc before the split/project phase. Returns false if the difference in the // function value on the current vs. previous iteration is sufficiently small that we're done. // @@PERF: Right now this is distinct matrix/vector operations. Profiling shows most time // in Qpsc is taken by MatrixVectorMultiply. We could gain a bit of performance by combining // some things but keep it simple unless that's needed. internal bool PreProject() { if (this.isFirstProjectCall) { #if VERBOSE System.Diagnostics.Debug.WriteLine("Previous and scale-munged ActualPos:"); System.Diagnostics.Debug.WriteLine(" Ordinal origDesired desired unscaledPos scaledPos"); foreach (var qvar in vectorQpscVars) { Debug.Assert(qvar.Variable.ActualPos == vectorCurY[qvar.Variable.Ordinal], "FirstProject: ActualPos != CurY"); System.Diagnostics.Debug.WriteLine(" {0} {1} {2} {3} {4}", qvar.Variable.Ordinal, qvar.OrigDesiredPos, qvar.Variable.DesiredPos, vectorCurY[qvar.Variable.Ordinal] / qvar.Variable.Scale, vectorCurY[qvar.Variable.Ordinal]); } #endif // VERBOSE // Due to MergeEqualityConstraints we may have moved some of the variables. This won't // affect feasibility since QpscMakeFeasible would already have ensured that any unsatisfiable // constraints are so marked. foreach (var qvar in this.vectorQpscVars) { this.vectorCurY[qvar.Variable.Ordinal] = qvar.Variable.ActualPos; } } // // Compute: g = Q'y + b' (in the Scaling paper terminology) // // g(radient) = Q'y... MatrixVectorMultiply(this.vectorCurY, this.gradientVector /*result*/); // If we've minimized the goal function (far enough), we're done. // This uses the Q'y value we've just put into gradientVector and tests the goal-function value // to see if it is sufficiently close to the previous value to be considered converged. if (HasConverged()) { return false; } // ...g = Q'y + b' VectorVectorAdd(this.gradientVector, this.vectorWiDi, this.gradientVector /*result*/); // // Compute: alpha = g#g / g#Q'g (# == transpose) // double alphaNumerator = VectorVectorMultiply(this.gradientVector, this.gradientVector); // Compute numerator of stepsize double alphaDenominator = 0.0; if (0.0 != alphaNumerator) { MatrixVectorMultiply(this.gradientVector, this.vectorQg /*result*/); alphaDenominator = VectorVectorMultiply(this.vectorQg, this.gradientVector); } if (0.0 == alphaDenominator) { #if VERBOSE System.Diagnostics.Debug.WriteLine("Converging due to zero-gradient"); #endif // VERBOSE return false; } double alpha = alphaNumerator / alphaDenominator; #if VERBOSE System.Diagnostics.Debug.WriteLine("Alpha = {0} (num {1}, den {2})", alpha, alphaNumerator, alphaDenominator); #endif // VERBOSE // // Store off the current position as the previous position (the paper's y^ (y-hat)), // then calculate the new current position by subtracting the (gradient * alpha) // from it and update the Variables' desired position. // VectorCopy(this.vectorPrevY /*dest*/, this.vectorCurY /*src*/); #if VERIFY || VERBOSE normAlphaG = 0.0; foreach (var g in this.gradientVector) { var ag = alpha * g; normAlphaG += ag * ag; } normAlphaG = Math.Sqrt(normAlphaG); #if VERBOSE System.Diagnostics.Debug.WriteLine("NormAlphaG = {0}", this.normAlphaG); #endif // VERBOSE #endif // VERIFY || VERBOSE // Update d(esiredpos) = y - alpha*g #if VERBOSE System.Diagnostics.Debug.WriteLine("PreProject gradient-stepped desired positions:"); #endif // VERBOSE // Use vectorCurY as temp as it is not used again here and is updated at start of PostProject. VectorScaledVectorSubtract(this.vectorPrevY, alpha, this.gradientVector, this.vectorCurY /*d*/); for (var ii = 0; ii < this.vectorCurY.Length; ++ii) { this.vectorQpscVars[ii].Variable.DesiredPos = this.vectorCurY[ii]; #if VERBOSE var qvar = vectorQpscVars[ii]; System.Diagnostics.Debug.WriteLine("{0} curY {1} orig desiredpos = {2}, current desiredpos = {3}, gradient = {4}", ii, vectorCurY[ii], qvar.OrigDesiredPos, qvar.Variable.DesiredPos, gradientVector[ii]); #endif // VERBOSE } return true; } // end PreProject() // Called by SolveQpsc after the split/project phase. internal bool PostProject() { // // Update our copy of current positions (y-bar from the paper) and deltaY (p in the Scaling paper; y-bar minus y-hat). // #if VERBOSE System.Diagnostics.Debug.WriteLine("PostProject current scaled and unscaled ActualPos:"); #endif // VERBOSE foreach (var qvar in this.vectorQpscVars) { this.vectorCurY[qvar.Variable.Ordinal] = qvar.Variable.ActualPos; #if VERBOSE System.Diagnostics.Debug.WriteLine(" {0} {1} {2}", qvar.Variable.Ordinal, qvar.Variable.ActualPos, qvar.Variable.ActualPos * qvar.Variable.Scale); #endif // VERBOSE } // vectorCurY temporarily becomes the p-vector from the Scaling paper since we don't use the "current" // position otherwise, until we reset it at the end. VectorVectorSubtract(this.vectorPrevY, this.vectorCurY, this.vectorCurY /*result; p (deltaY)*/); #if VERBOSE System.Diagnostics.Debug.WriteLine("PostProject variable deltas:"); #endif // VERBOSE #if VERIFY || VERBOSE double normDeltaY = 0.0; for (int ii = 0; ii < this.vectorCurY.Length; ++ii) { normDeltaY += this.vectorCurY[ii] * this.vectorCurY[ii]; #if VERBOSE System.Diagnostics.Debug.WriteLine(" {0} {1}", ii, vectorCurY[ii]); #endif // VERBOSE } normDeltaY = Math.Sqrt(normDeltaY); #if VERBOSE System.Diagnostics.Debug.WriteLine("NormAlphaG = {0}; normDeltaY = {1}", this.normAlphaG, normDeltaY); #endif // VERBOSE // dblNormSg must be >= dblNormd; account for rounding errors. Debug.Assert((this.normAlphaG / normDeltaY) > 0.001, "normAlphaG must be >= normDeltaY"); #endif // VERIFY || VERBOSE // // Compute: Beta = min(g#p / p#Qp, 1) // double betaNumerator = VectorVectorMultiply(this.gradientVector, this.vectorCurY /*p*/); // Compute numerator of stepsize double beta = 0.0; #if VERBOSE if (0.0 == betaNumerator) { System.Diagnostics.Debug.WriteLine(" Beta-numerator is zero"); } #endif // VERBOSE if (0.0 != betaNumerator) { // Calculate Qp first (matrix ops are associative so (AB)C == A(BC), so calculate the rhs first // with MatrixVectorMultiply). Temporarily hijack vectorQg for this operation. MatrixVectorMultiply(this.vectorCurY /*p*/, this.vectorQg /*result*/); // Now p#(Qp). double betaDenominator = VectorVectorMultiply(this.vectorQg, this.vectorCurY /*p*/); // Dividing by almost-0 would yield a huge value which we'd cap at 1.0 below. beta = (0.0 == betaDenominator) ? 1.0 : (betaNumerator / betaDenominator); #if VERBOSE System.Diagnostics.Debug.WriteLine("Beta = {0} (num {1}, den {2})", beta, betaNumerator, betaDenominator); #endif // VERBOSE if (beta > 1.0) { // Note: With huge ranges, beta is >>1 here - like 50 or millions. This is expected as // we're dividing by p#Qp where p is potentially quite small. beta = 1.0; } else if (beta < 0.0) { #if VERBOSE System.Diagnostics.Debug.WriteLine(" Resetting negative Beta to zero"); #endif // VERBOSE // Setting it above 0.0 can move us away from convergence, so set it to 0.0 which leaves // vectorCurY unchanged from vectorPrevY and we'll terminate if there are no splits/violations. // If we were close to convergence in preProject, we could have a significantly negative // beta here, which means we're basically done unless split/project still have stuff to do. beta = 0.0; } } // Beta numerator is nonzero // Update the "Qpsc-local" copy of the current positions for use in the next loop's PreProject(). VectorScaledVectorSubtract(this.vectorPrevY, beta, this.vectorCurY /*p*/, this.vectorCurY /*result*/); #if VERBOSE System.Diagnostics.Debug.WriteLine("PostProject variable positions (scaled, unscaled) adjusted for Beta:"); for (int ii = 0; ii < vectorCurY.Length; ++ii) { System.Diagnostics.Debug.WriteLine(" {0} {1} {2}", ii, vectorCurY[ii], vectorCurY[ii] * vectorQpscVars[ii].Variable.Scale); } #endif // VERBOSE this.isFirstProjectCall = false; return beta > 0.0; } // end PostProject() internal double QpscComplete() { // Restore original desired position and unscale the actual position. foreach (QpscVar qvar in this.vectorQpscVars) { qvar.Variable.Weight = qvar.OrigWeight; qvar.Variable.DesiredPos = qvar.OrigDesiredPos; if (solverParameters.Advanced.ScaleInQpsc) { // This multiplication essentially does what Constraint.Violation does, so the "satisfied" state // of constraints won't be changed. qvar.Variable.ActualPos *= qvar.Variable.Scale; qvar.Variable.Scale = qvar.OrigScale; #if VERBOSE System.Diagnostics.Debug.WriteLine("var {0} block {1} blockscale {2} blockrefpos {3} ActualPos {4}", qvar.Variable.Ordinal, qvar.Variable.Block.Id, qvar.Variable.Block.Scale, qvar.Variable.Block.ReferencePos, qvar.Variable.ActualPos); #endif // VERBOSE } } // This was updated to the final function value before HasConverged returned. return this.previousFunctionValue; } #region Internal workers private bool HasConverged() { // // Compute the function value relative to the previous iteration to test convergence: // (x#Ax)/2 + bx + (w d).d Note: final term is from Tim's Mathematica // where the last term (w d).d is constant and, because we only test decreasing value, // can therefore be omitted. // // We don't need to do the Ax operation as this is done as part of PreProject which has // already put this into gradientVector. // double currentFunctionValue = GetFunctionValue(this.vectorCurY); #if VERBOSE // (x'Ax)/2 + bx + (w d).d, to test against the Mathematica output. double dblTestFuncValue = currentFunctionValue; for (int ii = 0; ii < vectorQpscVars.Length; ++ii) { QpscVar qvar = vectorQpscVars[ii]; // Undo what we did to create the vecWiDi entry. double dblOrigDi = (vectorWiDi[ii] / qvar.OrigWeight) / -2.0; // Add the (w d).d final factor for the function value. dblTestFuncValue += qvar.OrigWeight * dblOrigDi * dblOrigDi; } System.Diagnostics.Debug.WriteLine("Iteration function value: {0}", dblTestFuncValue); #endif // VERBOSE // If this is not our first PreProject call, test for convergence. bool fConverged = false; if (!this.isFirstProjectCall) { #if VERBOSE // Let's see what |Xprev - Xcur| is... double dblDeltaNorm = 0.0; for (int ii = 0; ii < vectorCurY.Length; ++ii) { dblDeltaNorm += (vectorPrevY[ii] - vectorCurY[ii]) * (vectorPrevY[ii] - vectorCurY[ii]); } dblDeltaNorm = Math.Sqrt(dblDeltaNorm); System.Diagnostics.Debug.WriteLine("|Xprev - xCur|: {0}", dblDeltaNorm); #endif // VERBOSE // Check for convergence. We are monotonically decreasing so prev should be > cur // with some allowance for rounding error. double diff = (this.previousFunctionValue - currentFunctionValue); double quotient = 0.0; if (diff != 0.0) { double divisor = (0 != this.previousFunctionValue) ? this.previousFunctionValue : currentFunctionValue; quotient = Math.Abs(diff / divisor); #if EX_VERIFY Debug.Assert((previousFunctionValue > currentFunctionValue) || (quotient < 0.001), // account for rounding error "Convergence quotient should not be significantly negative"); #endif // EX_VERIFY } #if VERBOSE System.Diagnostics.Debug.WriteLine(" dblPrevFunctionValue {0:F5}, currentFunctionValue {1:F5}, dblDiff {2}, dblQuotient {3}", previousFunctionValue, currentFunctionValue, diff, quotient); #endif // VERBOSE if ((Math.Abs(diff) < solverParameters.QpscConvergenceEpsilon) || (Math.Abs(quotient) < solverParameters.QpscConvergenceQuotient)) { #if VERBOSE System.Diagnostics.Debug.WriteLine(" Terminating due to function value change within convergence epsilon"); #endif // VERBOSE fConverged = true; } } // endif !isFirstProjectCall this.previousFunctionValue = currentFunctionValue; return fConverged; } private double GetFunctionValue(double[] positions) { // (x#Ax)/2... double value = VectorVectorMultiply(this.gradientVector, positions) / 2.0; // (x'Ax)/2 + bx... return value + VectorVectorMultiply(this.vectorWiDi, positions); } // Returns the dot product of two column vectors (with an "implicit transpose"). private static double VectorVectorMultiply(double[] lhs, double[] rhs) { // Do not use LINQ's Sum, it slows end-to-end by over 10%. double sum = 0.0; for (int ii = 0; ii < lhs.Length; ++ii) { sum += lhs[ii] * rhs[ii]; } return sum; } // Multiplies matrixQ with the column vector rhs leaving the result in column vector in result[]. private void MatrixVectorMultiply(double[] rhs, double[] result) { // The only matrix we have here is (sparse) matrixQ so it's not a parameter. int rowIndex = 0; foreach (var row in this.matrixQ) { // Do not use LINQ's Sum, it slows end-to-end by over 10%. double sum = 0.0; foreach (var cell in row) { sum += cell.Value * rhs[cell.Column]; } result[rowIndex++] = sum; } } #if DEAD_CODE // Currently not needed as matrix multiplication is associative and we only do Vector x Matrix in // a chain with Vector(transpose) x Matrix x Vector, so we do the Matrix x Vector operation first // followed by Vector x Vector. // // Multiplies the column vector lhs (with implicit transpose) with matrixQ leaving the result in column vector in result[]. void VectorMatrixMultiply(double[] lhs, double[] result) { // The only matrix we have here is (sparse) matrixQ so it's not a parameter. for (var col = 0; col < result.Length; ++col) { result[col] = 0.0; } for (var row = 0; row < matrixQ.Length; ++row) { foreach (var cell in matrixQ[row]) { result[cell.Column] += cell.Value * lhs[row]; } } } #endif // DEAD_CODE // Returns the addition result in result[] (which may be lhs or rhs or a different vector). private static void VectorVectorAdd(double[] lhs, double[] rhs, double[] result) { for (int ii = 0; ii < lhs.Length; ++ii) { result[ii] = lhs[ii] + rhs[ii]; } } // Returns the subtraction result in result[] (which may be lhs or rhs or a different vector). private static void VectorVectorSubtract(double[] lhs, double[] rhs, double[] result) { for (int ii = 0; ii < lhs.Length; ++ii) { result[ii] = lhs[ii] - rhs[ii]; } } // Same as VectorVectorSubtract except that rhs is multiplied by the scale value. private static void VectorScaledVectorSubtract(double[] lhs, double scale, double[] rhs, double[] result) { for (int ii = 0; ii < lhs.Length; ++ii) { result[ii] = lhs[ii] - (scale * rhs[ii]); } } #if DEAD_CODE // Same as VectorScaledVectorSubtract except that we're adding and returning the result. double VectorScaledVectorAdd(double[] lhs, double scale, double[] rhs, double[] result) { double dblAbsDiff = 0.0; for (int ii = 0; ii < lhs.Length; ++ii) { result[ii] = lhs[ii] + (scale * rhs[ii]); dblAbsDiff += Math.Abs(result[ii] - lhs[ii]); } return dblAbsDiff; } #endif // DEAD_CODE // Copies src to dest private static void VectorCopy(double[] dest, double[] src) { for (int ii = 0; ii < src.Length; ++ii) { dest[ii] = src[ii]; } } #if VERBOSE void DumpMatrix() { // We only have the one matrix to dump. System.Diagnostics.Debug.WriteLine("A:"); double[] row = new double[vectorQpscVars.Length]; uint activeCells = 0; for (int ii = 0; ii < row.Length; ++ii) { for (int jj = 0; jj < row.Length; ++jj) { row[jj] = 0; // Remove prev row values } activeCells += (uint)matrixQ[ii].Length; foreach (MatrixCell cell in matrixQ[ii]) { row[cell.Column] = cell.Value; } DumpVector(null /*name*/, row); } System.Diagnostics.Debug.WriteLine("A matrix: {0} cells (average {1:F2} per row)", activeCells, (double)activeCells / matrixQ.Length); } void DumpVector(string name, double[] vector) { if (null != (object)name) { System.Diagnostics.Debug.WriteLine(name); } for (int jj = 0; jj < vector.Length; ++jj) { System.Diagnostics.Debug.Write(" {0:F5}", vector[jj]); } System.Diagnostics.Debug.WriteLine(); } #endif // VERBOSE #endregion // Internal workers } }
47.242731
167
0.548289
[ "MIT" ]
AdmiralSnyder/automatic-graph-layout
GraphLayout/MSAGL/Core/ProjectionSolver/QPSC.cs
37,369
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Newtonsoft.Json.Linq; using SharpIrcBot.Collections; using SharpIrcBot.Events.Irc; using SharpIrcBot.Util; namespace SharpIrcBot.Plugins.Punt { public class PuntPlugin : IPlugin, IReloadableConfiguration { private static readonly LoggerWrapper Logger = LoggerWrapper.Create<PuntPlugin>(); protected IConnectionManager ConnectionManager { get; } protected PuntConfig Config { get; set; } protected Random Randomizer { get; } protected RegexCache RegexCache { get; } public PuntPlugin(IConnectionManager connMgr, JObject config) { ConnectionManager = connMgr; Config = new PuntConfig(config); Randomizer = new Random(); RegexCache = new RegexCache(); ConnectionManager.ChannelAction += HandleAnyChannelMessage; ConnectionManager.ChannelMessage += HandleAnyChannelMessage; ConnectionManager.ChannelNotice += HandleAnyChannelMessage; RebuildRegexCache(); } public virtual void ReloadConfiguration(JObject newConfig) { Config = new PuntConfig(newConfig); PostConfigReload(); } protected virtual void PostConfigReload() { RebuildRegexCache(); } protected virtual void RebuildRegexCache() { var newPatterns = new HashSet<string>(); IEnumerable<PuntPattern> allChannelPatterns = Config.ChannelsPatterns.Values .Where(channelPattern => channelPattern != null) .SelectMany(channelPattern => channelPattern); IEnumerable<PuntPattern> allPatterns = Config.CommonPatterns.Concat(allChannelPatterns); foreach (PuntPattern pattern in allPatterns) { IEnumerable<string> allRegexes = pattern.NickPatterns .Concat(pattern.NickExceptPatterns) .Concat(pattern.BodyPatterns) .Concat(pattern.BodyExceptPatterns); foreach (string regex in allRegexes) { newPatterns.Add(regex); } } RegexCache.ReplaceAllWith(newPatterns); } protected virtual void HandleAnyChannelMessage(object sender, IChannelMessageEventArgs e, MessageFlags flags) { if (!Config.ChannelsPatterns.ContainsKey(e.Channel)) { // don't police this channel return; } IEnumerable<PuntPattern> relevantPatterns = Config.CommonPatterns; IEnumerable<PuntPattern> channelPatterns = Config.ChannelsPatterns[e.Channel]; if (channelPatterns != null) { relevantPatterns = relevantPatterns.Concat(channelPatterns); } string normalizedNick = ConnectionManager.RegisteredNameForNick(e.SenderNickname) ?? e.SenderNickname; foreach (PuntPattern pattern in relevantPatterns) { if (!AnyMatch(normalizedNick, pattern.NickPatterns)) { // wrong user continue; } if (AnyMatch(normalizedNick, pattern.NickExceptPatterns)) { // whitelisted user continue; } if (pattern.ChancePercent.HasValue) { int val = Randomizer.Next(100); if (val >= pattern.ChancePercent.Value) { // luck is on their side continue; } } if (!AnyMatch(e.Message, pattern.BodyPatterns)) { // no body match continue; } if (AnyMatch(e.Message, pattern.BodyExceptPatterns)) { // body exception continue; } // match! kick 'em! ConnectionManager.KickChannelUser(e.Channel, e.SenderNickname, pattern.KickMessage); return; } } protected bool AnyMatch(string text, List<string> regexes) { foreach (string regex in regexes) { Regex regexObject = RegexCache[regex]; if (regexObject.IsMatch(text)) { return true; } } return false; } } }
32.875
117
0.545839
[ "MIT" ]
RavuAlHemio/SharpIrcBot
Plugins/Punt/PuntPlugin.cs
4,736
C#
namespace Kopigi.Utils.Class { public enum TimeType { [StringEnum("minutes")] Minutes, [StringEnum("seconds")] Seconds, [StringEnum("milliseconds")] Milliseconds } }
16.285714
36
0.548246
[ "MIT" ]
mplessis/kUtils
Kopigi.Utils/Class/TimeType.cs
230
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Text; using EventStore.Core.Bus; using EventStore.Core.Data; using EventStore.Core.Index; using EventStore.Core.Index.Hashes; using EventStore.Core.Messages; using EventStore.Core.TransactionLog; using EventStore.Core.TransactionLog.Checkpoint; using EventStore.Core.TransactionLog.LogRecords; using ILogger = Serilog.ILogger; namespace EventStore.Core.Services.Storage.ReaderIndex { public interface IIndexCommitter { long LastIndexedPosition { get; } void Init(long buildToPosition); void Dispose(); long Commit(CommitLogRecord commit, bool isTfEof, bool cacheLastEventNumber); long Commit(IList<PrepareLogRecord> commitedPrepares, bool isTfEof, bool cacheLastEventNumber); long GetCommitLastEventNumber(CommitLogRecord commit); } public class IndexCommitter : IIndexCommitter { public static readonly ILogger Log = Serilog.Log.ForContext<IndexCommitter>(); public long LastIndexedPosition => _indexChk.Read(); private readonly IPublisher _bus; private readonly IIndexBackend _backend; private readonly IIndexReader _indexReader; private readonly ITableIndex _tableIndex; private readonly bool _additionalCommitChecks; private long _persistedPreparePos = -1; private long _persistedCommitPos = -1; private bool _indexRebuild = true; private readonly ICheckpoint _indexChk; public IndexCommitter( IPublisher bus, IIndexBackend backend, IIndexReader indexReader, ITableIndex tableIndex, ICheckpoint indexChk, bool additionalCommitChecks) { _bus = bus; _backend = backend; _indexReader = indexReader; _tableIndex = tableIndex; _indexChk = indexChk; _additionalCommitChecks = additionalCommitChecks; } public void Init(long buildToPosition) { Log.Information("TableIndex initialization..."); _tableIndex.Initialize(buildToPosition); _persistedPreparePos = _tableIndex.PrepareCheckpoint; _persistedCommitPos = _tableIndex.CommitCheckpoint; //todo(clc) determin if this needs to move into the TableIndex re:project-io _indexChk.Write(_tableIndex.CommitCheckpoint); _indexChk.Flush(); if (_indexChk.Read() >= buildToPosition) throw new Exception(string.Format("_lastCommitPosition {0} >= buildToPosition {1}", _indexChk.Read(), buildToPosition)); var startTime = DateTime.UtcNow; var lastTime = DateTime.UtcNow; var reportPeriod = TimeSpan.FromSeconds(5); Log.Information("ReadIndex building..."); _indexRebuild = true; using (var reader = _backend.BorrowReader()) { var startPosition = Math.Max(0, _persistedCommitPos); var fullRebuild = startPosition == 0; reader.Reposition(startPosition); var commitedPrepares = new List<PrepareLogRecord>(); long processed = 0; SeqReadResult result; while ((result = reader.TryReadNext()).Success && result.LogRecord.LogPosition < buildToPosition) { switch (result.LogRecord.RecordType) { case LogRecordType.Prepare: { var prepare = (PrepareLogRecord)result.LogRecord; if (prepare.Flags.HasAnyOf(PrepareFlags.IsCommitted)) { if (prepare.Flags.HasAnyOf(PrepareFlags.SingleWrite)) { Commit(commitedPrepares, false, false); commitedPrepares.Clear(); Commit(new[] { prepare }, result.Eof, false); } else { if (prepare.Flags.HasAnyOf(PrepareFlags.Data | PrepareFlags.StreamDelete)) commitedPrepares.Add(prepare); if (prepare.Flags.HasAnyOf(PrepareFlags.TransactionEnd)) { Commit(commitedPrepares, result.Eof, false); commitedPrepares.Clear(); } } } break; } case LogRecordType.Commit: Commit((CommitLogRecord)result.LogRecord, result.Eof, false); break; case LogRecordType.System: break; default: throw new Exception(string.Format("Unknown RecordType: {0}", result.LogRecord.RecordType)); } processed += 1; if (DateTime.UtcNow - lastTime > reportPeriod || processed % 100000 == 0) { Log.Debug("ReadIndex Rebuilding: processed {processed} records ({resultPosition:0.0}%).", processed, (result.RecordPostPosition - startPosition) * 100.0 / (buildToPosition - startPosition)); lastTime = DateTime.UtcNow; } if (fullRebuild && processed % 1000000 == 0) { if (_tableIndex.IsBackgroundTaskRunning) { Log.Debug("Pausing ReadIndex Rebuild due to ongoing index merges."); while (_tableIndex.IsBackgroundTaskRunning) { Thread.Sleep(1000); } Log.Debug("Resuming ReadIndex Rebuild."); } } } Log.Debug("ReadIndex rebuilding done: total processed {processed} records, time elapsed: {elapsed}.", processed, DateTime.UtcNow - startTime); _bus.Publish(new StorageMessage.TfEofAtNonCommitRecord()); _backend.SetSystemSettings(GetSystemSettings()); } _indexRebuild = false; } public void Dispose() { try { _tableIndex.Close(removeFiles: false); } catch (TimeoutException exc) { Log.Error(exc, "Timeout exception when trying to close TableIndex."); throw; } } public long GetCommitLastEventNumber(CommitLogRecord commit) { long eventNumber = EventNumber.Invalid; var lastIndexedPosition = _indexChk.Read(); if (commit.LogPosition < lastIndexedPosition || (commit.LogPosition == lastIndexedPosition && !_indexRebuild)) return eventNumber; foreach (var prepare in GetTransactionPrepares(commit.TransactionPosition, commit.LogPosition)) { if (prepare.Flags.HasNoneOf(PrepareFlags.StreamDelete | PrepareFlags.Data)) continue; eventNumber = prepare.Flags.HasAllOf(PrepareFlags.StreamDelete) ? EventNumber.DeletedStream : commit.FirstEventNumber + prepare.TransactionOffset; } return eventNumber; } public long Commit(CommitLogRecord commit, bool isTfEof, bool cacheLastEventNumber) { long eventNumber = EventNumber.Invalid; var lastIndexedPosition = _indexChk.Read(); if (commit.LogPosition < lastIndexedPosition || (commit.LogPosition == lastIndexedPosition && !_indexRebuild)) return eventNumber; // already committed string streamId = null; var indexEntries = new List<IndexKey>(); var prepares = new List<PrepareLogRecord>(); foreach (var prepare in GetTransactionPrepares(commit.TransactionPosition, commit.LogPosition)) { if (prepare.Flags.HasNoneOf(PrepareFlags.StreamDelete | PrepareFlags.Data)) continue; if (streamId == null) { streamId = prepare.EventStreamId; } else { if (prepare.EventStreamId != streamId) throw new Exception(string.Format("Expected stream: {0}, actual: {1}. LogPosition: {2}", streamId, prepare.EventStreamId, commit.LogPosition)); } eventNumber = prepare.Flags.HasAllOf(PrepareFlags.StreamDelete) ? EventNumber.DeletedStream : commit.FirstEventNumber + prepare.TransactionOffset; if (new TFPos(commit.LogPosition, prepare.LogPosition) > new TFPos(_persistedCommitPos, _persistedPreparePos)) { indexEntries.Add(new IndexKey(streamId, eventNumber, prepare.LogPosition)); prepares.Add(prepare); } } if (indexEntries.Count > 0) { if (_additionalCommitChecks && cacheLastEventNumber) { CheckStreamVersion(streamId, indexEntries[0].Version, commit); CheckDuplicateEvents(streamId, commit, indexEntries, prepares); } _tableIndex.AddEntries(commit.LogPosition, indexEntries); // atomically add a whole bulk of entries } if (eventNumber != EventNumber.Invalid) { if (eventNumber < 0) throw new Exception(string.Format("EventNumber {0} is incorrect.", eventNumber)); if (cacheLastEventNumber) { _backend.SetStreamLastEventNumber(streamId, eventNumber); } if (SystemStreams.IsMetastream(streamId)) _backend.SetStreamMetadata(SystemStreams.OriginalStreamOf(streamId), null); // invalidate cached metadata if (streamId == SystemStreams.SettingsStream) _backend.SetSystemSettings(DeserializeSystemSettings(prepares[prepares.Count - 1].Data)); } var newLastIndexedPosition = Math.Max(commit.LogPosition, lastIndexedPosition); if (_indexChk.Read() != lastIndexedPosition) { throw new Exception( "Concurrency error in ReadIndex.Commit: _lastCommitPosition was modified during Commit execution!"); } _indexChk.Write(newLastIndexedPosition); _indexChk.Flush(); if (!_indexRebuild) for (int i = 0, n = indexEntries.Count; i < n; ++i) { _bus.Publish( new StorageMessage.EventCommitted( commit.LogPosition, new EventRecord(indexEntries[i].Version, prepares[i]), isTfEof && i == n - 1)); } return eventNumber; } public long Commit(IList<PrepareLogRecord> commitedPrepares, bool isTfEof, bool cacheLastEventNumber) { long eventNumber = EventNumber.Invalid; if (commitedPrepares.Count == 0) return eventNumber; var lastIndexedPosition = _indexChk.Read(); var lastPrepare = commitedPrepares[commitedPrepares.Count - 1]; string streamId = lastPrepare.EventStreamId; var indexEntries = new List<IndexKey>(); var prepares = new List<PrepareLogRecord>(); foreach (var prepare in commitedPrepares) { if (prepare.Flags.HasNoneOf(PrepareFlags.StreamDelete | PrepareFlags.Data)) continue; if (prepare.EventStreamId != streamId) { var sb = new StringBuilder(); sb.Append(string.Format("ERROR: Expected stream: {0}, actual: {1}.", streamId, prepare.EventStreamId)); sb.Append(Environment.NewLine); sb.Append(Environment.NewLine); sb.Append("Prepares: (" + commitedPrepares.Count + ")"); sb.Append(Environment.NewLine); for (int i = 0; i < commitedPrepares.Count; i++) { var p = commitedPrepares[i]; sb.Append("Stream ID: " + p.EventStreamId); sb.Append(Environment.NewLine); sb.Append("LogPosition: " + p.LogPosition); sb.Append(Environment.NewLine); sb.Append("Flags: " + p.Flags); sb.Append(Environment.NewLine); sb.Append("Type: " + p.EventType); sb.Append(Environment.NewLine); sb.Append("MetaData: " + Encoding.UTF8.GetString(p.Metadata.Span)); sb.Append(Environment.NewLine); sb.Append("Data: " + Encoding.UTF8.GetString(p.Data.Span)); sb.Append(Environment.NewLine); } throw new Exception(sb.ToString()); } if (prepare.LogPosition < lastIndexedPosition || (prepare.LogPosition == lastIndexedPosition && !_indexRebuild)) continue; // already committed eventNumber = prepare.ExpectedVersion + 1; /* for committed prepare expected version is always explicit */ if (new TFPos(prepare.LogPosition, prepare.LogPosition) > new TFPos(_persistedCommitPos, _persistedPreparePos)) { indexEntries.Add(new IndexKey(streamId, eventNumber, prepare.LogPosition)); prepares.Add(prepare); } } if (indexEntries.Count > 0) { if (_additionalCommitChecks && cacheLastEventNumber) { CheckStreamVersion(streamId, indexEntries[0].Version, null); // TODO AN: bad passing null commit CheckDuplicateEvents(streamId, null, indexEntries, prepares); // TODO AN: bad passing null commit } _tableIndex.AddEntries(lastPrepare.LogPosition, indexEntries); // atomically add a whole bulk of entries } if (eventNumber != EventNumber.Invalid) { if (eventNumber < 0) throw new Exception(string.Format("EventNumber {0} is incorrect.", eventNumber)); if (cacheLastEventNumber) { _backend.SetStreamLastEventNumber(streamId, eventNumber); } if (SystemStreams.IsMetastream(streamId)) _backend.SetStreamMetadata(SystemStreams.OriginalStreamOf(streamId), null); // invalidate cached metadata if (streamId == SystemStreams.SettingsStream) _backend.SetSystemSettings(DeserializeSystemSettings(prepares[prepares.Count - 1].Data)); } var newLastIndexedPosition = Math.Max(lastPrepare.LogPosition, lastIndexedPosition); if (_indexChk.Read() != lastIndexedPosition) { throw new Exception( "Concurrency error in ReadIndex.Commit: _lastCommitPosition was modified during Commit execution!"); } _indexChk.Write(newLastIndexedPosition); _indexChk.Flush(); if (!_indexRebuild) for (int i = 0, n = indexEntries.Count; i < n; ++i) { _bus.Publish( new StorageMessage.EventCommitted( prepares[i].LogPosition, new EventRecord(indexEntries[i].Version, prepares[i]), isTfEof && i == n - 1)); } return eventNumber; } private IEnumerable<PrepareLogRecord> GetTransactionPrepares(long transactionPos, long commitPos) { using (var reader = _backend.BorrowReader()) { reader.Reposition(transactionPos); // in case all prepares were scavenged, we should not read past Commit LogPosition SeqReadResult result; while ((result = reader.TryReadNext()).Success && result.RecordPrePosition <= commitPos) { if (result.LogRecord.RecordType != LogRecordType.Prepare) continue; var prepare = (PrepareLogRecord)result.LogRecord; if (prepare.TransactionPosition == transactionPos) { yield return prepare; if (prepare.Flags.HasAnyOf(PrepareFlags.TransactionEnd)) yield break; } } } } private void CheckStreamVersion(string streamId, long newEventNumber, CommitLogRecord commit) { if (newEventNumber == EventNumber.DeletedStream) return; long lastEventNumber = _indexReader.GetStreamLastEventNumber(streamId); if (newEventNumber != lastEventNumber + 1) { if (Debugger.IsAttached) Debugger.Break(); else throw new Exception( string.Format( "Commit invariant violation: new event number {0} does not correspond to current stream version {1}.\n" + "Stream ID: {2}.\nCommit: {3}.", newEventNumber, lastEventNumber, streamId, commit)); } } private void CheckDuplicateEvents(string streamId, CommitLogRecord commit, IList<IndexKey> indexEntries, IList<PrepareLogRecord> prepares) { using (var reader = _backend.BorrowReader()) { var entries = _tableIndex.GetRange(streamId, indexEntries[0].Version, indexEntries[indexEntries.Count - 1].Version); foreach (var indexEntry in entries) { int prepareIndex = (int)(indexEntry.Version - indexEntries[0].Version); var prepare = prepares[prepareIndex]; PrepareLogRecord indexedPrepare = GetPrepare(reader, indexEntry.Position); if (indexedPrepare != null && indexedPrepare.EventStreamId == prepare.EventStreamId) { if (Debugger.IsAttached) Debugger.Break(); else throw new Exception( string.Format("Trying to add duplicate event #{0} to stream {1} \nCommit: {2}\n" + "Prepare: {3}\nIndexed prepare: {4}.", indexEntry.Version, prepare.EventStreamId, commit, prepare, indexedPrepare)); } } } } private SystemSettings GetSystemSettings() { var res = _indexReader.ReadEvent(SystemStreams.SettingsStream, -1); return res.Result == ReadEventResult.Success ? DeserializeSystemSettings(res.Record.Data) : null; } private static SystemSettings DeserializeSystemSettings(ReadOnlyMemory<byte> settingsData) { try { return SystemSettings.FromJsonBytes(settingsData); } catch (Exception exc) { Log.Error(exc, "Error deserializing SystemSettings record."); } return null; } private static PrepareLogRecord GetPrepare(TFReaderLease reader, long logPosition) { RecordReadResult result = reader.TryReadAt(logPosition); if (!result.Success) return null; if (result.LogRecord.RecordType != LogRecordType.Prepare) throw new Exception(string.Format("Incorrect type of log record {0}, expected Prepare record.", result.LogRecord.RecordType)); return (PrepareLogRecord)result.LogRecord; } } }
36.545872
113
0.711686
[ "Apache-2.0", "CC0-1.0" ]
BrunoZell/EventStore
src/EventStore.Core/Services/Storage/ReaderIndex/IndexCommitter.cs
15,934
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.TestModels.FantasyModel { public class FantasyStoredProceduresContext : FantasyContext { static FantasyStoredProceduresContext() { Database.SetInitializer(new FantasyStoredProceduresInitializer()); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Building>().MapToStoredProcedures(); modelBuilder.Entity<City>().MapToStoredProcedures(); modelBuilder.Entity<Creature>().MapToStoredProcedures(); modelBuilder.Entity<Province>().MapToStoredProcedures(); modelBuilder.Entity<Npc>().MapToStoredProcedures(); modelBuilder.Entity<Perk>().MapToStoredProcedures(); modelBuilder.Entity<Race>().MapToStoredProcedures(); modelBuilder.Entity<Skill>().MapToStoredProcedures(); modelBuilder.Entity<Spell>().MapToStoredProcedures(); modelBuilder.Entity<Landmark>().MapToStoredProcedures(); modelBuilder.Entity<Tower>().MapToStoredProcedures(); modelBuilder.Entity<Carnivore>().HasMany(c => c.Eats).WithMany().MapToStoredProcedures(); modelBuilder.Entity<Omnivore>().HasMany(c => c.Eats).WithMany().MapToStoredProcedures(); modelBuilder.Entity<Perk>().HasMany(p => p.RequiredBy).WithMany(p => p.RequiredPerks).MapToStoredProcedures(); modelBuilder.Entity<Race>().HasMany(r => r.SkillBonuses).WithMany().MapToStoredProcedures(); modelBuilder.Entity<Spell>().HasMany(s => s.SynergyWith).WithMany().MapToStoredProcedures(); } } }
52.342857
133
0.683406
[ "Apache-2.0" ]
CZEMacLeod/EntityFramework6
test/EntityFramework/FunctionalTests/TestModels/FantasyModel/FantasyStoredProceduresContext.cs
1,834
C#
using System; using System.Collections.Generic; using System.Text; namespace Bakery.Models { public class Bread : BakedFood { private const int InitialBreadPortion = 200; public Bread(string name, decimal price) : base(name, InitialBreadPortion, price) { } } }
18.823529
52
0.634375
[ "MIT" ]
DimitarHaralampiev/C-OOP---Exam
Bakery/Bakery/Models/BakedFoods/Bread.cs
322
C#
using System.Collections.Generic; using UnityEngine; namespace FairyGUI { /// <summary> /// /// </summary> public class HitTestContext { //set before hit test public static Vector2 screenPoint; public static Vector3 worldPoint; public static Vector3 direction; public static bool forTouch; public static int layerMask = -1; public static float maxDistance = Mathf.Infinity; public static Camera cachedMainCamera; static Dictionary<Camera, RaycastHit?> raycastHits = new Dictionary<Camera, RaycastHit?>(); /// <summary> /// /// </summary> /// <param name="camera"></param> /// <param name="hit"></param> /// <returns></returns> public static bool GetRaycastHitFromCache(Camera camera, out RaycastHit hit) { RaycastHit? hitRef; if (!HitTestContext.raycastHits.TryGetValue(camera, out hitRef)) { Ray ray = camera.ScreenPointToRay(HitTestContext.screenPoint); if (Physics.Raycast(ray, out hit, maxDistance, layerMask)) { HitTestContext.raycastHits[camera] = hit; return true; } else { HitTestContext.raycastHits[camera] = null; return false; } } else if (hitRef == null) { hit = new RaycastHit(); return false; } else { hit = (RaycastHit)hitRef; return true; } } /// <summary> /// /// </summary> /// <param name="camera"></param> /// <param name="hit"></param> public static void CacheRaycastHit(Camera camera, ref RaycastHit hit) { HitTestContext.raycastHits[camera] = hit; } /// <summary> /// /// </summary> public static void ClearRaycastHitCache() { raycastHits.Clear(); } } }
21.012658
93
0.649398
[ "MIT" ]
21thCenturyBoy/LandlordsProject
Landlords_Client01/Landlords_Client01/Unity/Assets/ThirdParty/FairyGUI/Scripts/Core/HitTest/HitTestContext.cs
1,662
C#
using System; using System.Net; using System.Threading; using System.Threading.Tasks; namespace STUN.Proxy { public interface IUdpProxy : IDisposable { TimeSpan Timeout { get; set; } IPEndPoint LocalEndPoint { get; } Task ConnectAsync(CancellationToken token = default); Task<(byte[], IPEndPoint, IPAddress)> ReceiveAsync(ReadOnlyMemory<byte> bytes, IPEndPoint remote, EndPoint receive, CancellationToken token = default); Task DisconnectAsync(); } }
28.294118
154
0.740125
[ "MIT" ]
CarolineNS/NatTypeTester
STUN/Proxy/IUdpProxy.cs
465
C#
using System; using LuaInterface; using SLua; using System.Collections.Generic; public class Lua_UnityEngine_Camera : LuaObject { [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int constructor(IntPtr l) { try { UnityEngine.Camera o; o=new UnityEngine.Camera(); pushValue(l,true); pushValue(l,o); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int SetTargetBuffers(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); if(matchType(l,argc,2,typeof(UnityEngine.RenderBuffer[]),typeof(UnityEngine.RenderBuffer))){ UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.RenderBuffer[] a1; checkArray(l,2,out a1); UnityEngine.RenderBuffer a2; checkValueType(l,3,out a2); self.SetTargetBuffers(a1,a2); pushValue(l,true); return 1; } else if(matchType(l,argc,2,typeof(UnityEngine.RenderBuffer),typeof(UnityEngine.RenderBuffer))){ UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.RenderBuffer a1; checkValueType(l,2,out a1); UnityEngine.RenderBuffer a2; checkValueType(l,3,out a2); self.SetTargetBuffers(a1,a2); pushValue(l,true); return 1; } pushValue(l,false); LuaDLL.lua_pushstring(l,"No matched override function to call"); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int ResetWorldToCameraMatrix(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); self.ResetWorldToCameraMatrix(); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int ResetProjectionMatrix(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); self.ResetProjectionMatrix(); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int ResetAspect(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); self.ResetAspect(); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int ResetFieldOfView(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); self.ResetFieldOfView(); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int SetStereoViewMatrices(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Matrix4x4 a1; checkValueType(l,2,out a1); UnityEngine.Matrix4x4 a2; checkValueType(l,3,out a2); self.SetStereoViewMatrices(a1,a2); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int GetStereoViewMatrix(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Camera.StereoscopicEye a1; checkEnum(l,2,out a1); var ret=self.GetStereoViewMatrix(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int SetStereoViewMatrix(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Camera.StereoscopicEye a1; checkEnum(l,2,out a1); UnityEngine.Matrix4x4 a2; checkValueType(l,3,out a2); self.SetStereoViewMatrix(a1,a2); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int ResetStereoViewMatrices(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); self.ResetStereoViewMatrices(); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int SetStereoProjectionMatrices(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Matrix4x4 a1; checkValueType(l,2,out a1); UnityEngine.Matrix4x4 a2; checkValueType(l,3,out a2); self.SetStereoProjectionMatrices(a1,a2); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int GetStereoProjectionMatrix(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Camera.StereoscopicEye a1; checkEnum(l,2,out a1); var ret=self.GetStereoProjectionMatrix(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int SetStereoProjectionMatrix(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Camera.StereoscopicEye a1; checkEnum(l,2,out a1); UnityEngine.Matrix4x4 a2; checkValueType(l,3,out a2); self.SetStereoProjectionMatrix(a1,a2); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int ResetStereoProjectionMatrices(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); self.ResetStereoProjectionMatrices(); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int WorldToScreenPoint(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Vector3 a1; checkType(l,2,out a1); var ret=self.WorldToScreenPoint(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int WorldToViewportPoint(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Vector3 a1; checkType(l,2,out a1); var ret=self.WorldToViewportPoint(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int ViewportToWorldPoint(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Vector3 a1; checkType(l,2,out a1); var ret=self.ViewportToWorldPoint(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int ScreenToWorldPoint(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Vector3 a1; checkType(l,2,out a1); var ret=self.ScreenToWorldPoint(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int ScreenToViewportPoint(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Vector3 a1; checkType(l,2,out a1); var ret=self.ScreenToViewportPoint(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int ViewportToScreenPoint(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Vector3 a1; checkType(l,2,out a1); var ret=self.ViewportToScreenPoint(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int ViewportPointToRay(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Vector3 a1; checkType(l,2,out a1); var ret=self.ViewportPointToRay(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int ScreenPointToRay(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Vector3 a1; checkType(l,2,out a1); var ret=self.ScreenPointToRay(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int Render(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); self.Render(); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int RenderWithShader(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Shader a1; checkType(l,2,out a1); System.String a2; checkType(l,3,out a2); self.RenderWithShader(a1,a2); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int SetReplacementShader(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Shader a1; checkType(l,2,out a1); System.String a2; checkType(l,3,out a2); self.SetReplacementShader(a1,a2); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int ResetReplacementShader(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); self.ResetReplacementShader(); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int ResetCullingMatrix(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); self.ResetCullingMatrix(); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int RenderDontRestore(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); self.RenderDontRestore(); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int RenderToCubemap(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); if(matchType(l,argc,2,typeof(UnityEngine.RenderTexture))){ UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.RenderTexture a1; checkType(l,2,out a1); var ret=self.RenderToCubemap(a1); pushValue(l,true); pushValue(l,ret); return 2; } else if(matchType(l,argc,2,typeof(UnityEngine.Cubemap))){ UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Cubemap a1; checkType(l,2,out a1); var ret=self.RenderToCubemap(a1); pushValue(l,true); pushValue(l,ret); return 2; } else if(matchType(l,argc,2,typeof(UnityEngine.RenderTexture),typeof(int))){ UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.RenderTexture a1; checkType(l,2,out a1); System.Int32 a2; checkType(l,3,out a2); var ret=self.RenderToCubemap(a1,a2); pushValue(l,true); pushValue(l,ret); return 2; } else if(matchType(l,argc,2,typeof(UnityEngine.Cubemap),typeof(int))){ UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Cubemap a1; checkType(l,2,out a1); System.Int32 a2; checkType(l,3,out a2); var ret=self.RenderToCubemap(a1,a2); pushValue(l,true); pushValue(l,ret); return 2; } pushValue(l,false); LuaDLL.lua_pushstring(l,"No matched override function to call"); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int CopyFrom(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Camera a1; checkType(l,2,out a1); self.CopyFrom(a1); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int AddCommandBuffer(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Rendering.CameraEvent a1; checkEnum(l,2,out a1); UnityEngine.Rendering.CommandBuffer a2; checkType(l,3,out a2); self.AddCommandBuffer(a1,a2); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int RemoveCommandBuffer(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Rendering.CameraEvent a1; checkEnum(l,2,out a1); UnityEngine.Rendering.CommandBuffer a2; checkType(l,3,out a2); self.RemoveCommandBuffer(a1,a2); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int RemoveCommandBuffers(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Rendering.CameraEvent a1; checkEnum(l,2,out a1); self.RemoveCommandBuffers(a1); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int RemoveAllCommandBuffers(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); self.RemoveAllCommandBuffers(); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int GetCommandBuffers(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Rendering.CameraEvent a1; checkEnum(l,2,out a1); var ret=self.GetCommandBuffers(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int CalculateObliqueMatrix(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Vector4 a1; checkType(l,2,out a1); var ret=self.CalculateObliqueMatrix(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int GetAllCameras_s(IntPtr l) { try { UnityEngine.Camera[] a1; checkArray(l,1,out a1); var ret=UnityEngine.Camera.GetAllCameras(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int SetupCurrent_s(IntPtr l) { try { UnityEngine.Camera a1; checkType(l,1,out a1); UnityEngine.Camera.SetupCurrent(a1); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_onPreCull(IntPtr l) { try { UnityEngine.Camera.CameraCallback v; int op=LuaDelegation.checkDelegate(l,2,out v); if(op==0) UnityEngine.Camera.onPreCull=v; else if(op==1) UnityEngine.Camera.onPreCull+=v; else if(op==2) UnityEngine.Camera.onPreCull-=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_onPreRender(IntPtr l) { try { UnityEngine.Camera.CameraCallback v; int op=LuaDelegation.checkDelegate(l,2,out v); if(op==0) UnityEngine.Camera.onPreRender=v; else if(op==1) UnityEngine.Camera.onPreRender+=v; else if(op==2) UnityEngine.Camera.onPreRender-=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_onPostRender(IntPtr l) { try { UnityEngine.Camera.CameraCallback v; int op=LuaDelegation.checkDelegate(l,2,out v); if(op==0) UnityEngine.Camera.onPostRender=v; else if(op==1) UnityEngine.Camera.onPostRender+=v; else if(op==2) UnityEngine.Camera.onPostRender-=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_fieldOfView(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.fieldOfView); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_fieldOfView(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); float v; checkType(l,2,out v); self.fieldOfView=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_nearClipPlane(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.nearClipPlane); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_nearClipPlane(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); float v; checkType(l,2,out v); self.nearClipPlane=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_farClipPlane(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.farClipPlane); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_farClipPlane(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); float v; checkType(l,2,out v); self.farClipPlane=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_renderingPath(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushEnum(l,(int)self.renderingPath); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_renderingPath(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.RenderingPath v; checkEnum(l,2,out v); self.renderingPath=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_actualRenderingPath(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushEnum(l,(int)self.actualRenderingPath); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_hdr(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.hdr); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_hdr(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); bool v; checkType(l,2,out v); self.hdr=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_orthographicSize(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.orthographicSize); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_orthographicSize(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); float v; checkType(l,2,out v); self.orthographicSize=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_orthographic(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.orthographic); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_orthographic(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); bool v; checkType(l,2,out v); self.orthographic=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_opaqueSortMode(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushEnum(l,(int)self.opaqueSortMode); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_opaqueSortMode(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Rendering.OpaqueSortMode v; checkEnum(l,2,out v); self.opaqueSortMode=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_transparencySortMode(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushEnum(l,(int)self.transparencySortMode); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_transparencySortMode(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.TransparencySortMode v; checkEnum(l,2,out v); self.transparencySortMode=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_depth(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.depth); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_depth(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); float v; checkType(l,2,out v); self.depth=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_aspect(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.aspect); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_aspect(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); float v; checkType(l,2,out v); self.aspect=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_cullingMask(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.cullingMask); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_cullingMask(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); int v; checkType(l,2,out v); self.cullingMask=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_eventMask(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.eventMask); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_eventMask(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); int v; checkType(l,2,out v); self.eventMask=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_backgroundColor(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.backgroundColor); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_backgroundColor(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Color v; checkType(l,2,out v); self.backgroundColor=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_rect(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.rect); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_rect(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Rect v; checkValueType(l,2,out v); self.rect=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_pixelRect(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.pixelRect); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_pixelRect(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Rect v; checkValueType(l,2,out v); self.pixelRect=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_targetTexture(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.targetTexture); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_targetTexture(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.RenderTexture v; checkType(l,2,out v); self.targetTexture=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_pixelWidth(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.pixelWidth); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_pixelHeight(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.pixelHeight); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_cameraToWorldMatrix(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.cameraToWorldMatrix); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_worldToCameraMatrix(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.worldToCameraMatrix); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_worldToCameraMatrix(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Matrix4x4 v; checkValueType(l,2,out v); self.worldToCameraMatrix=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_projectionMatrix(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.projectionMatrix); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_projectionMatrix(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Matrix4x4 v; checkValueType(l,2,out v); self.projectionMatrix=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_nonJitteredProjectionMatrix(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.nonJitteredProjectionMatrix); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_nonJitteredProjectionMatrix(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Matrix4x4 v; checkValueType(l,2,out v); self.nonJitteredProjectionMatrix=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_velocity(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.velocity); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_clearFlags(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushEnum(l,(int)self.clearFlags); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_clearFlags(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.CameraClearFlags v; checkEnum(l,2,out v); self.clearFlags=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_stereoEnabled(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.stereoEnabled); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_stereoSeparation(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.stereoSeparation); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_stereoSeparation(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); float v; checkType(l,2,out v); self.stereoSeparation=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_stereoConvergence(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.stereoConvergence); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_stereoConvergence(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); float v; checkType(l,2,out v); self.stereoConvergence=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_cameraType(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushEnum(l,(int)self.cameraType); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_cameraType(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.CameraType v; checkEnum(l,2,out v); self.cameraType=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_stereoMirrorMode(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.stereoMirrorMode); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_stereoMirrorMode(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); bool v; checkType(l,2,out v); self.stereoMirrorMode=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_stereoTargetEye(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushEnum(l,(int)self.stereoTargetEye); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_stereoTargetEye(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.StereoTargetEyeMask v; checkEnum(l,2,out v); self.stereoTargetEye=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_targetDisplay(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.targetDisplay); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_targetDisplay(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); int v; checkType(l,2,out v); self.targetDisplay=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_main(IntPtr l) { try { pushValue(l,true); pushValue(l,UnityEngine.Camera.main); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_current(IntPtr l) { try { pushValue(l,true); pushValue(l,UnityEngine.Camera.current); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_allCameras(IntPtr l) { try { pushValue(l,true); pushValue(l,UnityEngine.Camera.allCameras); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_allCamerasCount(IntPtr l) { try { pushValue(l,true); pushValue(l,UnityEngine.Camera.allCamerasCount); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_useOcclusionCulling(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.useOcclusionCulling); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_useOcclusionCulling(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); bool v; checkType(l,2,out v); self.useOcclusionCulling=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_cullingMatrix(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.cullingMatrix); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_cullingMatrix(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.Matrix4x4 v; checkValueType(l,2,out v); self.cullingMatrix=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_layerCullDistances(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.layerCullDistances); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_layerCullDistances(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); System.Single[] v; checkArray(l,2,out v); self.layerCullDistances=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_layerCullSpherical(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.layerCullSpherical); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_layerCullSpherical(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); bool v; checkType(l,2,out v); self.layerCullSpherical=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_depthTextureMode(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushEnum(l,(int)self.depthTextureMode); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_depthTextureMode(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); UnityEngine.DepthTextureMode v; checkEnum(l,2,out v); self.depthTextureMode=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_clearStencilAfterLightingPass(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.clearStencilAfterLightingPass); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_clearStencilAfterLightingPass(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); bool v; checkType(l,2,out v); self.clearStencilAfterLightingPass=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_commandBufferCount(IntPtr l) { try { UnityEngine.Camera self=(UnityEngine.Camera)checkSelf(l); pushValue(l,true); pushValue(l,self.commandBufferCount); return 2; } catch(Exception e) { return error(l,e); } } static public void reg(IntPtr l) { getTypeTable(l,"UnityEngine.Camera"); addMember(l,SetTargetBuffers); addMember(l,ResetWorldToCameraMatrix); addMember(l,ResetProjectionMatrix); addMember(l,ResetAspect); addMember(l,ResetFieldOfView); addMember(l,SetStereoViewMatrices); addMember(l,GetStereoViewMatrix); addMember(l,SetStereoViewMatrix); addMember(l,ResetStereoViewMatrices); addMember(l,SetStereoProjectionMatrices); addMember(l,GetStereoProjectionMatrix); addMember(l,SetStereoProjectionMatrix); addMember(l,ResetStereoProjectionMatrices); addMember(l,WorldToScreenPoint); addMember(l,WorldToViewportPoint); addMember(l,ViewportToWorldPoint); addMember(l,ScreenToWorldPoint); addMember(l,ScreenToViewportPoint); addMember(l,ViewportToScreenPoint); addMember(l,ViewportPointToRay); addMember(l,ScreenPointToRay); addMember(l,Render); addMember(l,RenderWithShader); addMember(l,SetReplacementShader); addMember(l,ResetReplacementShader); addMember(l,ResetCullingMatrix); addMember(l,RenderDontRestore); addMember(l,RenderToCubemap); addMember(l,CopyFrom); addMember(l,AddCommandBuffer); addMember(l,RemoveCommandBuffer); addMember(l,RemoveCommandBuffers); addMember(l,RemoveAllCommandBuffers); addMember(l,GetCommandBuffers); addMember(l,CalculateObliqueMatrix); addMember(l,GetAllCameras_s); addMember(l,SetupCurrent_s); addMember(l,"onPreCull",null,set_onPreCull,false); addMember(l,"onPreRender",null,set_onPreRender,false); addMember(l,"onPostRender",null,set_onPostRender,false); addMember(l,"fieldOfView",get_fieldOfView,set_fieldOfView,true); addMember(l,"nearClipPlane",get_nearClipPlane,set_nearClipPlane,true); addMember(l,"farClipPlane",get_farClipPlane,set_farClipPlane,true); addMember(l,"renderingPath",get_renderingPath,set_renderingPath,true); addMember(l,"actualRenderingPath",get_actualRenderingPath,null,true); addMember(l,"hdr",get_hdr,set_hdr,true); addMember(l,"orthographicSize",get_orthographicSize,set_orthographicSize,true); addMember(l,"orthographic",get_orthographic,set_orthographic,true); addMember(l,"opaqueSortMode",get_opaqueSortMode,set_opaqueSortMode,true); addMember(l,"transparencySortMode",get_transparencySortMode,set_transparencySortMode,true); addMember(l,"depth",get_depth,set_depth,true); addMember(l,"aspect",get_aspect,set_aspect,true); addMember(l,"cullingMask",get_cullingMask,set_cullingMask,true); addMember(l,"eventMask",get_eventMask,set_eventMask,true); addMember(l,"backgroundColor",get_backgroundColor,set_backgroundColor,true); addMember(l,"rect",get_rect,set_rect,true); addMember(l,"pixelRect",get_pixelRect,set_pixelRect,true); addMember(l,"targetTexture",get_targetTexture,set_targetTexture,true); addMember(l,"pixelWidth",get_pixelWidth,null,true); addMember(l,"pixelHeight",get_pixelHeight,null,true); addMember(l,"cameraToWorldMatrix",get_cameraToWorldMatrix,null,true); addMember(l,"worldToCameraMatrix",get_worldToCameraMatrix,set_worldToCameraMatrix,true); addMember(l,"projectionMatrix",get_projectionMatrix,set_projectionMatrix,true); addMember(l,"nonJitteredProjectionMatrix",get_nonJitteredProjectionMatrix,set_nonJitteredProjectionMatrix,true); addMember(l,"velocity",get_velocity,null,true); addMember(l,"clearFlags",get_clearFlags,set_clearFlags,true); addMember(l,"stereoEnabled",get_stereoEnabled,null,true); addMember(l,"stereoSeparation",get_stereoSeparation,set_stereoSeparation,true); addMember(l,"stereoConvergence",get_stereoConvergence,set_stereoConvergence,true); addMember(l,"cameraType",get_cameraType,set_cameraType,true); addMember(l,"stereoMirrorMode",get_stereoMirrorMode,set_stereoMirrorMode,true); addMember(l,"stereoTargetEye",get_stereoTargetEye,set_stereoTargetEye,true); addMember(l,"targetDisplay",get_targetDisplay,set_targetDisplay,true); addMember(l,"main",get_main,null,false); addMember(l,"current",get_current,null,false); addMember(l,"allCameras",get_allCameras,null,false); addMember(l,"allCamerasCount",get_allCamerasCount,null,false); addMember(l,"useOcclusionCulling",get_useOcclusionCulling,set_useOcclusionCulling,true); addMember(l,"cullingMatrix",get_cullingMatrix,set_cullingMatrix,true); addMember(l,"layerCullDistances",get_layerCullDistances,set_layerCullDistances,true); addMember(l,"layerCullSpherical",get_layerCullSpherical,set_layerCullSpherical,true); addMember(l,"depthTextureMode",get_depthTextureMode,set_depthTextureMode,true); addMember(l,"clearStencilAfterLightingPass",get_clearStencilAfterLightingPass,set_clearStencilAfterLightingPass,true); addMember(l,"commandBufferCount",get_commandBufferCount,null,true); createTypeMetatable(l,constructor, typeof(UnityEngine.Camera),typeof(UnityEngine.Behaviour)); } }
26.765425
120
0.717461
[ "MIT" ]
zhangjie0072/FairyGUILearn
Assets/Slua/LuaObject/Unity/Lua_UnityEngine_Camera.cs
45,985
C#
using FunctionZero.ExpressionParserZero; using FunctionZero.ExpressionParserZero.BackingStore; using FunctionZero.ExpressionParserZero.Operands; using FunctionZero.ExpressionParserZero.Parser; using FunctionZero.MvvmZero; using FunctionZero.zBind.z; using FunctionZero.zBindTestApp.Mvvm.Pages; using FunctionZero.zBindTestApp.Mvvm.PageViewModels; using System; using System.Collections.Generic; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace FunctionZero.zBindTestApp { public partial class App : Application { public App(IPageServiceZero pageService) { pageService.Init(this); InitializeComponent(); var parser = ExpressionParserZero.Binding.ExpressionParserFactory.GetExpressionParser(); parser.RegisterFunction("GetColor", DoGetColor, 3, 3); MainPage = pageService.MakePage<HomePage, HomePageVm>(async (vm) => await vm.InitAsync()); } private static void DoGetColor(Stack<IOperand> operandStack, IBackingStore backingStore, long paramCount) { // Pop the correct number of parameters from the operands stack, ** in reverse order ** // If an operand is a variable, it is resolved from the backing store provided IOperand fourth = OperatorActions.PopAndResolve(operandStack, backingStore); IOperand third = OperatorActions.PopAndResolve(operandStack, backingStore); IOperand second = OperatorActions.PopAndResolve(operandStack, backingStore); IOperand first = OperatorActions.PopAndResolve(operandStack, backingStore); double r = (double)first.GetValue(); double g = (double)second.GetValue(); double b = (double)third.GetValue(); double a = (double)fourth.GetValue(); // The result is of type Color object result = new Color(r, g, b, 1); // Push the result back onto the operand stack operandStack.Push(new Operand(-1, OperandType.Object, result)); } protected override void OnStart() { } protected override void OnSleep() { } protected override void OnResume() { } } }
35.746032
113
0.672291
[ "MIT" ]
Keflon/FunctionZero.zBindTestApp
FunctionZero.zBindTestApp/FunctionZero.zBindTestApp/App.xaml.cs
2,254
C#
/** * Copyright 2013 Canada Health Infoway, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: $LastChangedBy: tmcgrady $ * Last modified: $LastChangedDate: 2011-05-04 15:47:15 -0400 (Wed, 04 May 2011) $ * Revision: $LastChangedRevision: 2623 $ */ /* This class was auto-generated by the message builder generator tools. */ namespace Ca.Infoway.Messagebuilder.Model.Sk_cerx_v01_r04_2.Interaction { using Ca.Infoway.Messagebuilder.Annotation; using Ca.Infoway.Messagebuilder.Model; using Ca.Infoway.Messagebuilder.Model.Sk_cerx_v01_r04_2.Common.Mcci_mt000100ca; using Ca.Infoway.Messagebuilder.Model.Sk_cerx_v01_r04_2.Common.Quqi_mt020000ca; using Ca.Infoway.Messagebuilder.Model.Sk_cerx_v01_r04_2.Pharmacy.Porx_mt060360ca; /** * <summary>Business Name: PORX_IN060050CA: Device prescription * dispense detail query</summary> * * <remarks>Message: MCCI_MT000100CA.Message Control Act: * QUQI_MT020000CA.ControlActEvent --> Payload: * PORX_MT060360CA.ParameterList</remarks> */ [Hl7PartTypeMappingAttribute(new string[] {"PORX_IN060050CA"})] public class DevicePrescriptionDispenseDetailQuery : HL7Message<Ca.Infoway.Messagebuilder.Model.Sk_cerx_v01_r04_2.Common.Quqi_mt020000ca.TriggerEvent<Ca.Infoway.Messagebuilder.Model.Sk_cerx_v01_r04_2.Pharmacy.Porx_mt060360ca.GenericQueryParameters>>, IInteraction { public DevicePrescriptionDispenseDetailQuery() { } } }
45.422222
270
0.735323
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-sk-v01_r04_3/Main/Ca/Infoway/Messagebuilder/Model/Sk_cerx_v01_r04_2/Interaction/DevicePrescriptionDispenseDetailQuery.cs
2,044
C#
using EFCore.Sharding; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.IO; using System.Text; namespace Coldairarrow.Util { /// <summary> /// 描述:数据库操作抽象帮助类 /// 作者:Coldairarrow /// </summary> public abstract class DbHelper { #region 构造函数 /// <summary> /// 构造函数 /// </summary> /// <param name="dbType">数据库类型</param> /// <param name="conString">完整连接字符串</param> public DbHelper(DatabaseType dbType, string conString) { _dbType = dbType; _conString = conString; } #endregion #region 私有成员 /// <summary> /// 数据库类型 /// </summary> protected DatabaseType _dbType; /// <summary> /// 连接字符串 /// </summary> protected string _conString; /// <summary> /// 实体需要引用的额外命名空间 /// </summary> protected string _extraUsingNamespace { get; set; } = string.Empty; /// <summary> /// 类型映射字典 /// </summary> protected abstract Dictionary<string, Type> DbTypeDic { get; } #endregion #region 外部接口 /// <summary> /// 通过数据库连接字符串和Sql语句查询返回DataTable /// </summary> /// <param name="sql">Sql语句</param> /// <returns></returns> public DataTable GetDataTableWithSql(string sql) { DbProviderFactory dbProviderFactory = DbProviderFactoryHelper.GetDbProviderFactory(_dbType); using (DbConnection conn = dbProviderFactory.CreateConnection()) { conn.ConnectionString = _conString; if (conn.State != ConnectionState.Open) { conn.Open(); } using (DbCommand cmd = conn.CreateCommand()) { cmd.Connection = conn; cmd.CommandText = sql; DbDataAdapter adapter = dbProviderFactory.CreateDataAdapter(); adapter.SelectCommand = cmd; DataSet table = new DataSet(); adapter.Fill(table); return table.Tables[0]; } } } /// <summary> /// 通过数据库连接字符串和Sql语句查询返回DataTable,参数化查询 /// </summary> /// <param name="sql">Sql语句</param> /// <param name="parameters">参数</param> /// <returns></returns> public DataTable GetDataTableWithSql(string sql, List<DbParameter> parameters) { DbProviderFactory dbProviderFactory = DbProviderFactoryHelper.GetDbProviderFactory(_dbType); using (DbConnection conn = dbProviderFactory.CreateConnection()) { conn.ConnectionString = _conString; if (conn.State != ConnectionState.Open) { conn.Open(); } using (DbCommand cmd = conn.CreateCommand()) { cmd.Connection = conn; cmd.CommandText = sql; if (parameters != null && parameters.Count > 0) { foreach (var item in parameters) { cmd.Parameters.Add(item); } } DbDataAdapter adapter = dbProviderFactory.CreateDataAdapter(); adapter.SelectCommand = cmd; DataSet table = new DataSet(); adapter.Fill(table); cmd.Parameters.Clear(); return table.Tables[0]; } } } /// <summary> /// 通过数据库连接字符串和Sql语句查询返回List /// </summary> /// <typeparam name="T">实体类</typeparam> /// <param name="sqlStr">Sql语句</param> /// <returns></returns> public List<T> GetListBySql<T>(string sqlStr) { return GetDataTableWithSql(sqlStr).ToList<T>(); } /// <summary> /// 通过数据库连接字符串和Sql语句查询返回List,参数化查询 /// </summary> /// <typeparam name="T">实体类</typeparam> /// <param name="sqlStr">Sql语句</param> /// <param name="param">查询参数</param> /// <returns></returns> public List<T> GetListBySql<T>(string sqlStr, List<DbParameter> param) { return GetDataTableWithSql(sqlStr, param).ToList<T>(); } /// <summary> /// 执行无返回值的Sql语句 /// </summary> /// <param name="sql">Sql语句</param> public int ExecuteSql(string sql) { int count = 0; DbProviderFactory dbProviderFactory = DbProviderFactoryHelper.GetDbProviderFactory(_dbType); using (DbConnection conn = dbProviderFactory.CreateConnection()) { conn.ConnectionString = _conString; if (conn.State != ConnectionState.Open) { conn.Open(); } using (DbCommand cmd = dbProviderFactory.CreateCommand()) { cmd.Connection = conn; cmd.CommandText = sql; count = cmd.ExecuteNonQuery(); return count; } } } /// <summary> /// 执行无返回值的Sql语句 /// </summary> /// <param name="sql">Sql语句</param> /// <param name="paramters"></param> public int ExecuteSql(string sql, List<DbParameter> paramters) { int count = 0; DbProviderFactory dbProviderFactory = DbProviderFactoryHelper.GetDbProviderFactory(_dbType); using (DbConnection conn = dbProviderFactory.CreateConnection()) { if (conn.State != ConnectionState.Open) { conn.Open(); } using (DbCommand cmd = dbProviderFactory.CreateCommand()) { cmd.Connection = conn; cmd.CommandText = sql; if (paramters != null && paramters.Count > 0) { foreach (var item in paramters) { cmd.Parameters.Add(item); } } count = cmd.ExecuteNonQuery(); return count; } } } /// <summary> /// 获取数据库中的所有表 /// </summary> /// <param name="schemaName">模式(架构)</param> /// <returns></returns> public abstract List<DbTableInfo> GetDbAllTables(string schemaName = null); /// <summary> /// 通过连接字符串和表名获取数据库表的信息 /// </summary> /// <param name="tableName">表名</param> /// <returns></returns> public abstract List<TableInfo> GetDbTableInfo(string tableName); /// <summary> /// 将数据库类型转为对应C#数据类型 /// </summary> /// <param name="dbTypeStr">数据类型</param> /// <returns></returns> public virtual Type DbTypeStr_To_CsharpType(string dbTypeStr) { string _dbTypeStr = dbTypeStr.ToLower(); Type type = null; if (DbTypeDic.ContainsKey(_dbTypeStr)) type = DbTypeDic[_dbTypeStr]; else type = typeof(string); return type; } /// <summary> /// 生成实体文件 /// </summary> /// <param name="infos">表字段信息</param> /// <param name="tableName">表名</param> /// <param name="tableDescription">表描述信息</param> /// <param name="filePath">文件路径(包含文件名)</param> /// <param name="nameSpace">实体命名空间</param> /// <param name="schemaName">架构(模式)名</param> public virtual void SaveEntityToFile(List<TableInfo> infos, string tableName, string tableDescription, string filePath, string nameSpace, string schemaName = null) { string properties = ""; string schema = ""; if (!schemaName.IsNullOrEmpty()) schema = $@", Schema = ""{schemaName}"""; infos.ForEach((item, index) => { string isKey = item.IsKey ? $@" [Key, Column(Order = {index + 1})]" : ""; Type type = DbTypeStr_To_CsharpType(item.Type); string isNullable = item.IsNullable && type.IsValueType ? "?" : ""; string description = item.Description.IsNullOrEmpty() ? item.Name : item.Description; string newPropertyStr = $@" /// <summary> /// {description} /// </summary>{isKey} public {type.Name}{isNullable} {item.Name} {{ get; set; }} "; properties += newPropertyStr; }); string fileStr = $@"using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; {_extraUsingNamespace} namespace {nameSpace} {{ /// <summary> /// {tableDescription} /// </summary> [Table(""{tableName}""{schema})] public class {tableName} {{ {properties} }} }}"; var dir = Path.GetDirectoryName(filePath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } File.WriteAllText(filePath, fileStr, Encoding.UTF8); } #endregion } }
31.526316
171
0.498435
[ "MIT" ]
Coldairarrow/Colder.Admin.AntdVue
src/Coldairarrow.Util/DataAccess/DbHelper.cs
10,166
C#
/*********************************************************************\ *This file is part of My Nes * *A Nintendo Entertainment System Emulator. * * * *Copyright (C) 2009 - 2010 Ala Hadid * *E-mail: mailto:ahdsoftwares@hotmail.com * * * *My Nes is free software: you can redistribute it and/or modify * *it under the terms of the GNU General Public License as published by * *the Free Software Foundation, either version 3 of the License, or * *(at your option) any later version. * * * *My Nes is distributed in the hope that it will be useful, * *but WITHOUT ANY WARRANTY; without even the implied warranty of * *MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * *GNU General Public License for more details. * * * *You should have received a copy of the GNU General Public License * *along with this program. If not, see <http://www.gnu.org/licenses/>.* \*********************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MyNes.Nes { [Serializable ()] class Mapper65 : IMapper { CPUMemory Map; short timer_irq_counter_65 = 0; short timer_irq_Latch_65 = 0; bool timer_irq_enabled; public Mapper65(CPUMemory Maps) { Map = Maps; } public void Write(ushort address, byte data) { if (address == 0x8000) Map.Switch8kPrgRom(data * 2, 0); else if (address == 0xA000) Map.Switch8kPrgRom(data * 2, 1); else if (address == 0xC000) Map.Switch8kPrgRom(data * 2, 2); else if (address == 0x9003) timer_irq_enabled = ((data & 0x80) != 0); else if (address == 0x9004) timer_irq_counter_65 = timer_irq_Latch_65; else if (address == 0x9005) timer_irq_Latch_65 = (short)((timer_irq_Latch_65 & 0x00FF) | (data << 8)); else if (address == 0x9006) timer_irq_Latch_65 = (short)((timer_irq_Latch_65 & 0xFF00) | (data)); else if (address == 0xB000) Map.Switch1kChrRom(data, 0); else if (address == 0xB001) Map.Switch1kChrRom(data, 1); else if (address == 0xB002) Map.Switch1kChrRom(data, 2); else if (address == 0xB003) Map.Switch1kChrRom(data, 3); else if (address == 0xB004) Map.Switch1kChrRom(data, 4); else if (address == 0xB005) Map.Switch1kChrRom(data, 5); else if (address == 0xB006) Map.Switch1kChrRom(data, 6); else if (address == 0xB007) Map.Switch1kChrRom(data, 7); } public void SetUpMapperDefaults() { Map.Switch16kPrgRom(0, 0); Map.Switch16kPrgRom((Map.Cartridge.CHR_PAGES - 1) * 4, 1); if (Map.Cartridge.IsVRAM) Map.FillCHR(16); Map.Switch8kChrRom(0); } public void TickScanlineTimer() { } public void TickCycleTimer(int cycles) { if (timer_irq_enabled) { timer_irq_counter_65 -= (short)cycles; if (timer_irq_counter_65 <= 0) { Map.cpu.IRQRequest = true; timer_irq_enabled = false; } } } public void SoftReset() { } public bool WriteUnder8000 { get { return false; } } public bool WriteUnder6000 { get { return false; } } } }
41.813725
91
0.460961
[ "Apache-2.0" ]
evgenyvinnik/jvsc-windows-apps
Nes7/Nes/Memory/Mappers/Mapper65.cs
4,267
C#
using Game.Core; using Game.Estate.Tes.Records; using Game.Format.Nif; using System; using System.Linq; using UnityEngine; using static Game.Core.CoreDebug; namespace Game.Estate.Tes.Loader { public static class LoadData { static IDataPack DataPack; public static void Awake() { } public static void Start() { var dataUri = new Uri("game://Morrowind/Morrowind.esm"); //var dataUri = new Uri("game://Morrowind/Bloodmoon.esm"); //var dataUri = new Uri("game://Morrowind/Tribunal.esm"); //var dataUri = new Uri("game://Oblivion/Oblivion.esm"); //var dataUri = new Uri("game://SkyrimVR/Skyrim.esm"); //var dataUri = new Uri("game://Fallout4/Fallout4.esm"); //var dataUri = new Uri("game://Fallout4VR/Fallout4.esm"); DataPack = dataUri.GetTesDataPackAsync().Result(); //TestLoadCell(new Vector3(((-2 << 5) + 1) * ConvertUtils.ExteriorCellSideLengthInMeters, 0, ((-1 << 5) + 1) * ConvertUtils.ExteriorCellSideLengthInMeters)); //TestLoadCell(new Vector3((-1 << 3) * ConvertUtils.ExteriorCellSideLengthInMeters, 0, (-1 << 3) * ConvertUtils.ExteriorCellSideLengthInMeters)); TestLoadCell(new Vector3(0 * ConvertUtils.ExteriorCellSideLengthInMeters, 0, 0 * ConvertUtils.ExteriorCellSideLengthInMeters)); //TestLoadCell(new Vector3((1 << 3) * ConvertUtils.ExteriorCellSideLengthInMeters, 0, (1 << 3) * ConvertUtils.ExteriorCellSideLengthInMeters)); //TestLoadCell(new Vector3((1 << 5) * ConvertUtils.ExteriorCellSideLengthInMeters, 0, (1 << 5) * ConvertUtils.ExteriorCellSideLengthInMeters)); //TestAllCells(); } public static Vector3Int GetCellId(Vector3 point, int world) => new Vector3Int(Mathf.FloorToInt(point.x / ConvertUtils.ExteriorCellSideLengthInMeters), Mathf.FloorToInt(point.z / ConvertUtils.ExteriorCellSideLengthInMeters), world); static void TestLoadCell(Vector3 position) { var cellId = GetCellId(position, 60); var cell = DataPack.FindCellRecord(cellId); var land = ((TesDataPack)DataPack).FindLANDRecord(cellId); Log($"LAND #{land?.Id}"); } static void TestAllCells() { var cells = ((TesDataPack)DataPack).GroupByLabel["CELL"].Records; Log($"CELLS: {cells.Count}"); foreach (var record in cells.Cast<CELLRecord>()) Log(record.EDID.Value); } public static void OnDestroy() { DataPack?.Dispose(); DataPack = null; } public static void Update() { } } }
43.285714
241
0.624129
[ "MIT" ]
libcs/game-estates
src/Estates/Tes/src/Game.Estate.Tes.Unity/Loader/LoadData.cs
2,729
C#
using System; using System.ComponentModel; using System.Collections.Generic; using Newtonsoft.Json; using System.Linq; using STEP; namespace IFC { /// <summary> /// <see href="http://www.buildingsmart-tech.org/ifc/IFC4/final/html/link/ifcwallstandardcase.htm"/> /// </summary> public partial class IfcWallStandardCase : IfcWall { /// <summary> /// Construct a IfcWallStandardCase with all required attributes. /// </summary> public IfcWallStandardCase(IfcGloballyUniqueId globalId):base(globalId) { } /// <summary> /// Construct a IfcWallStandardCase with required and optional attributes. /// </summary> [JsonConstructor] public IfcWallStandardCase(IfcGloballyUniqueId globalId,IfcOwnerHistory ownerHistory,IfcLabel name,IfcText description,IfcLabel objectType,IfcObjectPlacement objectPlacement,IfcProductRepresentation representation,IfcIdentifier tag,IfcWallTypeEnum predefinedType):base(globalId,ownerHistory,name,description,objectType,objectPlacement,representation,tag,predefinedType) { } public static new IfcWallStandardCase FromJSON(string json){ return JsonConvert.DeserializeObject<IfcWallStandardCase>(json); } public override string GetStepParameters() { var parameters = new List<string>(); parameters.Add(GlobalId != null ? GlobalId.ToStepValue() : "$"); parameters.Add(OwnerHistory != null ? OwnerHistory.ToStepValue() : "$"); parameters.Add(Name != null ? Name.ToStepValue() : "$"); parameters.Add(Description != null ? Description.ToStepValue() : "$"); parameters.Add(ObjectType != null ? ObjectType.ToStepValue() : "$"); parameters.Add(ObjectPlacement != null ? ObjectPlacement.ToStepValue() : "$"); parameters.Add(Representation != null ? Representation.ToStepValue() : "$"); parameters.Add(Tag != null ? Tag.ToStepValue() : "$"); parameters.Add(PredefinedType.ToStepValue()); return string.Join(", ", parameters.ToArray()); } } }
35.909091
371
0.727089
[ "MIT" ]
Gytaco/IFC-gen
lang/csharp/src/IFC/IfcWallStandardCase.g.cs
1,975
C#
// <auto-generated /> using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using ShoeStore.Products.Infrastructure; namespace ShoeStore.Products.Infrastructure.Migrations { [DbContext(typeof(ProductsDbContext))] partial class ProductsDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasDefaultSchema("ssp") .HasAnnotation("ProductVersion", "2.2.6-servicing-10079") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("ShoeStore.Products.Domain.Catalogue", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name"); b.HasKey("Id"); b.ToTable("Catalogues"); }); modelBuilder.Entity("ShoeStore.Products.Domain.CatalogueProduct", b => { b.Property<int>("CatalogueProductId") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("CatalogueId"); b.Property<int>("ProductId"); b.HasKey("CatalogueProductId"); b.HasIndex("CatalogueId"); b.HasIndex("ProductId"); b.ToTable("CatalogueProduct"); }); modelBuilder.Entity("ShoeStore.Products.Domain.Product", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Code"); b.Property<decimal>("Cost"); b.Property<string>("LongDescription"); b.Property<string>("Name"); b.Property<int>("Rank"); b.Property<string>("ShortDescription"); b.Property<int>("Stock"); b.HasKey("Id"); b.ToTable("Products"); }); modelBuilder.Entity("ShoeStore.Products.Domain.CatalogueProduct", b => { b.HasOne("ShoeStore.Products.Domain.Catalogue", "Catalogue") .WithMany("CatalogueProducts") .HasForeignKey("CatalogueId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("ShoeStore.Products.Domain.Product", "Product") .WithMany("CatalogueProducts") .HasForeignKey("ProductId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
36.084211
125
0.549592
[ "MIT" ]
Shifatullah/shoestore-products-aspnetcore
ShoeStore.Products.Infrastructure/Migrations/ProductsDbContextModelSnapshot.cs
3,430
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 route53domains-2014-05-15.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Route53Domains.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Route53Domains.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ListOperations operation /// </summary> public class ListOperationsResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { ListOperationsResponse response = new ListOperationsResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("NextPageMarker", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.NextPageMarker = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Operations", targetDepth)) { var unmarshaller = new ListUnmarshaller<OperationSummary, OperationSummaryUnmarshaller>(OperationSummaryUnmarshaller.Instance); response.Operations = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidInput")) { return InvalidInputExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonRoute53DomainsException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static ListOperationsResponseUnmarshaller _instance = new ListOperationsResponseUnmarshaller(); internal static ListOperationsResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static ListOperationsResponseUnmarshaller Instance { get { return _instance; } } } }
37.974138
197
0.646765
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Route53Domains/Generated/Model/Internal/MarshallTransformations/ListOperationsResponseUnmarshaller.cs
4,405
C#
#region License & Metadata // The MIT License (MIT) // // 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. // // // Created On: 2019/04/16 13:29 // Modified On: 2019/04/16 13:31 // Modified By: Alexis #endregion using System; namespace SuperMemoAssistant.Interop.SuperMemo.Elements.Models { [Serializable] [Flags] public enum ElemCreationResultCode { Success = 1, WarningConceptNotSet = 4, ErrorTooManyChildren = 64, ErrorUnknown = 128 } }
30.816327
78
0.737748
[ "MIT" ]
KeepOnSurviving/SuperMemoAssistant
src/Core/SuperMemoAssistant.Interop/Interop/SuperMemo/Elements/Models/ElemCreationResultCode.cs
1,512
C#
using System; namespace FontAwesome { /// <summary> /// The unicode values for all FontAwesome icons. /// <para/> /// See https://fontawesome.com/cheatsheet /// <para/> /// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs). /// </summary> public static partial class Unicode { /// <summary> /// fa-alicorn unicode value ("\uf6b0"). /// <para/> /// This icon supports the following styles: Light (Pro), Regular (Pro), Solid (Pro), Duotone (Pro) /// <para/> /// See https://fontawesome.com/icons/alicorn /// </summary> public const string Alicorn = "\uf6b0"; } /// <summary> /// The Css values for all FontAwesome icons. /// <para/> /// See https://fontawesome.com/cheatsheet /// <para/> /// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs). /// </summary> public static partial class Css { /// <summary> /// Alicorn unicode value ("fa-alicorn"). /// <para/> /// This icon supports the following styles: Light (Pro), Regular (Pro), Solid (Pro), Duotone (Pro) /// <para/> /// See https://fontawesome.com/icons/alicorn /// </summary> public const string Alicorn = "fa-alicorn"; } /// <summary> /// The Icon names for all FontAwesome icons. /// <para/> /// See https://fontawesome.com/cheatsheet /// <para/> /// This code was automatically generated by FA2CS (https://github.com/michaelswells/fa2cs a modified fork from https://github.com/matthewrdev/fa2cs). /// </summary> public static partial class Icon { /// <summary> /// fa-alicorn unicode value ("\uf6b0"). /// <para/> /// This icon supports the following styles: Light (Pro), Regular (Pro), Solid (Pro), Duotone (Pro) /// <para/> /// See https://fontawesome.com/icons/alicorn /// </summary> public const string Alicorn = "Alicorn"; } }
36
154
0.588798
[ "MIT" ]
michaelswells/FontAwesomeAttribute
FontAwesome/FontAwesome.Alicorn.cs
2,196
C#
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using Microsoft.EntityFrameworkCore; using Unifiedban.Models; namespace Unifiedban.Data { public class OperationLogService { public OperationLog Add(OperationLog operationLog, int callerId) { using (UBContext ubc = new UBContext()) { try { ubc.Add(operationLog); ubc.SaveChanges(); return operationLog; } catch (Exception ex) { Utils.Logging.AddLog(new SystemLog() { LoggerName = "Unifiedban", Date = DateTime.Now, Function = "Unifiedban.Data.OperationLogService.Add", Level = SystemLog.Levels.Warn, Message = ex.Message, UserId = callerId }); if (ex.InnerException != null) Utils.Logging.AddLog(new SystemLog() { LoggerName = "Unifiedban.Data", Date = DateTime.Now, Function = "Unifiedban.Data.OperationLogService.Add", Level = SystemLog.Levels.Warn, Message = ex.InnerException.Message, UserId = callerId }); } return null; } }public List<OperationLog> Add(List<OperationLog> operationLog, int callerId) { using (UBContext ubc = new UBContext()) { try { ubc.AddRange(operationLog); ubc.SaveChanges(); return operationLog; } catch (Exception ex) { Utils.Logging.AddLog(new SystemLog() { LoggerName = "Unifiedban", Date = DateTime.Now, Function = "Unifiedban.Data.OperationLogService.Add", Level = SystemLog.Levels.Warn, Message = ex.Message, UserId = callerId }); if (ex.InnerException != null) Utils.Logging.AddLog(new SystemLog() { LoggerName = "Unifiedban.Data", Date = DateTime.Now, Function = "Unifiedban.Data.OperationLogService.Add", Level = SystemLog.Levels.Warn, Message = ex.InnerException.Message, UserId = callerId }); } return null; } } public List<OperationLog> Get(Expression<Func<OperationLog, bool>> whereClause) { try { using (UBContext ubc = new UBContext()) { if (whereClause == null) return ubc.OperationLogs .AsNoTracking() .ToList(); return ubc.OperationLogs .AsNoTracking() .Where(whereClause) .ToList(); } } catch { return new List<OperationLog>(); } } } }
35.357143
87
0.419949
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
unified-ban/Data
Unifiedban.Data/OperationLogService.cs
3,962
C#
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; namespace Microsoft.Azure.Commands.Network.Models { public class PSAzureFirewallPolicy : PSTopLevelResource { public PSManagedServiceIdentity Identity { get; set; } public string ThreatIntelMode { get; set; } public PSAzureFirewallPolicyThreatIntelWhitelist ThreatIntelWhitelist { get; set; } public Microsoft.Azure.Management.Network.Models.SubResource BasePolicy { get; set; } public string ProvisioningState { get; set; } [JsonProperty("ruleCollectionGroups")] public List<Microsoft.Azure.Management.Network.Models.SubResource> RuleCollectionGroups { get; set; } public PSAzureFirewallPolicyDnsSettings DnsSettings { get; set; } public PSAzureFirewallPolicyIntrusionDetection IntrusionDetection { get; set; } public PSAzureFirewallPolicyTransportSecurity TransportSecurity { get; set; } public PSAzureFirewallPolicySku Sku { get; set; } } }
36.191489
110
0.717813
[ "MIT" ]
3quanfeng/azure-powershell
src/Network/Network/Models/AzureFirewallPolicy/PSAzureFirewallPolicy.cs
1,657
C#
// Copyright (c) Bynder. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. using System; using System.Threading.Tasks; using Bynder.Api.Queries; namespace Bynder.Api.Impl.Oauth { /// <summary> /// Interface to send oauth <see cref="Request{T}"/> to the API. /// </summary> internal interface IOauthRequestSender : IDisposable { /// <summary> /// Sends the request to Bynder API. It gets all necessary information from <see cref="Request{T}"/> /// and deserializes response if needed to specific object. /// </summary> /// <typeparam name="T">Type we want to deserialize response to</typeparam> /// <param name="request">Request with the information to do the API call</param> /// <returns>Task returning T</returns> Task<T> SendRequestAsync<T>(Request<T> request); } }
38.875
108
0.662379
[ "MIT" ]
Geta/bynder-c-sharp-sdk
Bynder/Api/Impl/Oauth/IOauthRequestSender.cs
935
C#
using System.Collections.ObjectModel; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http.Controllers; using Moq; using Xunit; using Assert = Microsoft.TestCommon.AssertEx; namespace System.Web.Http.Tracing.Tracers { public class HttpActionBindingTracerTest { private Mock<HttpActionDescriptor> _mockActionDescriptor; private Mock<HttpParameterDescriptor> _mockParameterDescriptor; private Mock<HttpParameterBinding> _mockParameterBinding; private HttpActionBinding _actionBinding; private HttpActionContext _actionContext; private HttpControllerContext _controllerContext; private HttpControllerDescriptor _controllerDescriptor; public HttpActionBindingTracerTest() { _mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true }; _mockActionDescriptor.Setup(a => a.ActionName).Returns("test"); _mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0])); _mockParameterDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true }; _mockParameterBinding = new Mock<HttpParameterBinding>(_mockParameterDescriptor.Object) { CallBase = true }; _actionBinding = new HttpActionBinding(_mockActionDescriptor.Object, new HttpParameterBinding[] { _mockParameterBinding.Object }); _controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "controller", typeof(ApiController)); _controllerContext = ContextUtil.CreateControllerContext(request: new HttpRequestMessage()); _controllerContext.ControllerDescriptor = _controllerDescriptor; _actionContext = ContextUtil.CreateActionContext(_controllerContext, actionDescriptor: _mockActionDescriptor.Object); } [Fact] public void BindValuesAsync_Invokes_Inner_And_Traces() { // Arrange bool wasInvoked = false; Mock<HttpActionBinding> mockBinder = new Mock<HttpActionBinding>() { CallBase = true }; mockBinder.Setup(b => b.ExecuteBindingAsync( It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>())). Callback(() => wasInvoked = true).Returns(TaskHelpers.Completed()); TestTraceWriter traceWriter = new TestTraceWriter(); HttpActionBindingTracer tracer = new HttpActionBindingTracer(mockBinder.Object, traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(_actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.Begin }, new TraceRecord(_actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.End } }; // Act tracer.ExecuteBindingAsync(_actionContext, CancellationToken.None).Wait(); // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.True(wasInvoked); } [Fact] public void ExecuteBindingAsync_Faults_And_Traces_When_Inner_Faults() { // Arrange InvalidOperationException exception = new InvalidOperationException(); TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(); tcs.TrySetException(exception); Mock<HttpActionBinding> mockBinder = new Mock<HttpActionBinding>() { CallBase = true }; mockBinder.Setup(b => b.ExecuteBindingAsync( It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>())). Returns(tcs.Task); TestTraceWriter traceWriter = new TestTraceWriter(); HttpActionBindingTracer tracer = new HttpActionBindingTracer(mockBinder.Object, traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(_actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.Begin }, new TraceRecord(_actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Error) { Kind = TraceKind.End } }; // Act Task task = tracer.ExecuteBindingAsync(_actionContext, CancellationToken.None); // Assert Exception thrown = Assert.Throws<InvalidOperationException>(() => task.Wait()); Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.Same(exception, thrown); Assert.Same(exception, traceWriter.Traces[1].Exception); } } }
47.676471
145
0.679827
[ "Apache-2.0" ]
douchedetector/mvc-razor
test/System.Web.Http.Test/Tracing/Tracers/HttpActionBindingTracerTest.cs
4,865
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using DotNetNuke.Entities.Users; using VD.Modules.Framework; using DevExpress.Web; using DataLayer; using DotNetNuke.Services.Localization; using System.Data.SqlClient; using GlobalAPI; namespace VD.Modules.Materials { public partial class Param_Brands : DotNetNuke.Entities.Modules.PortalModuleBase { /// <summary> /// The current user /// </summary> public UserInfo CurrentUser = GlobalAPI.CommunUtility.GetCurrentUserInfo(); /// <summary> /// The ressource file path /// </summary> protected string ressFilePath = "~/DesktopModules/Materials/App_LocalResources/View.ascx.resx"; /// <summary> /// Handles the Load event of the Page control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void Page_Load(object sender, EventArgs e) { Session["Locale"] = System.Threading.Thread.CurrentThread.CurrentCulture.Name; TranslateUtility.localizeGrid(grdParam, ressFilePath); grdParam.Columns["Designation"].Caption = DotNetNuke.Services.Localization.Localization.GetString("hNom", ressFilePath); toolbarMenu.Items[0].Text = DotNetNuke.Services.Localization.Localization.GetString("mnBrands", ressFilePath); toolbarMenu.Items[0].Items[0].Text = popupMenu.Items[0].Text = DotNetNuke.Services.Localization.Localization.GetString("mnAdd", ressFilePath); toolbarMenu.Items[0].Items[1].Text = popupMenu.Items[1].Text = DotNetNuke.Services.Localization.Localization.GetString("mnEdit", ressFilePath); toolbarMenu.Items[0].Items[2].Text = popupMenu.Items[2].Text = DotNetNuke.Services.Localization.Localization.GetString("mnDelete", ressFilePath); } protected void grdParam_CustomCallback(object sender, DevExpress.Web.ASPxGridViewCustomCallbackEventArgs e) { grdParam.DataBind(); grdParam.CancelEdit(); } protected void grdParam_CustomErrorText(object sender, DevExpress.Web.ASPxGridViewCustomErrorTextEventArgs e) { if (e.ErrorTextKind != DevExpress.Web.GridErrorTextKind.RowValidate) { try { SqlException sqlEx = (SqlException)e.Exception; if ((sqlEx.Number == 547)) { e.ErrorText = DotNetNuke.Services.Localization.Localization.GetString("mDeleteBrandError", ressFilePath); } } catch(Exception) {} } } } }
42.820896
160
0.651446
[ "BSD-3-Clause" ]
bssoum12/GFA
site/DesktopModules/Materials/Param_Brands.ascx.cs
2,871
C#
using CatenaX.NetworkServices.Registration.Service.Model; namespace CatenaX.NetworkServices.Registration.Service.RegistrationAccess; public interface IRegistrationDBAccess { Task SetIdp(SetIdp idpToSet); }
23.666667
74
0.840376
[ "Apache-2.0" ]
catenax-ng/product-portal-backend
src/registration/CatenaX.NetworkServices.Registration.Service/RegistrationAccess/IRegistrationDBAccess.cs
215
C#
using System; using System.Collections.ObjectModel; using System.Linq; namespace MicroUpsert { public sealed class UpsertCommand { private readonly ReadOnlyCollection<UpsertVector> _values; public static UpsertCommand On(params UpsertVector[] values) { if (values == null) { throw new ArgumentNullException("values"); } if (values.Length == 0) { throw new ArgumentOutOfRangeException("values", "Zero-length array"); } var upsertValues = (UpsertVector[])values.Clone(); return new UpsertCommand(upsertValues); } private UpsertCommand(UpsertVector[] values) { _values = new ReadOnlyCollection<UpsertVector>(values); } public ReadOnlyCollection<UpsertVector> Values { get { return _values; } } private bool Equals(UpsertCommand other) { return _values.Count == other._values.Count && _values.All(v => other._values.Contains(v)); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } return obj is UpsertCommand && Equals((UpsertCommand) obj); } public override int GetHashCode() { return (_values != null ? _values.GetHashCode() : 0); } } }
26.409836
85
0.532588
[ "MIT" ]
justin-lovell/micro-upsert
MicroUpsert/UpsertCommand.cs
1,613
C#
#region LICENSE /* Sora - A Modular Bancho written in C# Copyright (C) 2019 Robin A. P. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #endregion using Sora.Attributes; using Sora.Enums; using Sora.EventArgs; using Sora.Packets.Server; using Sora.Services; namespace Sora.Events.BanchoEvents.ClientStatus { [EventClass] public class OnSendUserStatusEvent { private readonly PacketStreamService _pss; public OnSendUserStatusEvent(PacketStreamService pss) => _pss = pss; [Event(EventType.BanchoSendUserStatus)] public void OnSendUserStatus(BanchoSendUserStatusArgs args) { args.pr.Status = args.status; args.pr["IS_RELAXING"] = (args.pr.Status.CurrentMods & Mod.Relax) != 0; //Logger.Debug("OnSendUserStatusEvent", "Is Relaxing", args.pr.Relax); var main = _pss.GetStream("main"); //main.Broadcast(new UserPresence(args.pr)); main.Broadcast(new HandleUpdate(args.pr)); } } }
32.45098
83
0.69426
[ "MIT" ]
Tiller431/yes
Sora/Sora/Events/BanchoEvents/ClientStatus/OnSendUserStatusEvent.cs
1,655
C#
namespace Mvc3Host.Filters { using System.Web.Mvc; using Mvc3Host.Services; public class FooAttribute : ActionFilterAttribute { public IFooService FooService { get; set; } public override void OnActionExecuted(ActionExecutedContext filterContext) { var message = (FooService == null) ? "FooService was not injected!" : FooService.GetFoo(); filterContext.Controller.ViewBag.fooMessage = message; } } }
35.461538
94
0.689805
[ "Apache-2.0" ]
bmabdi/mvcturbine
src/Engine/Mvc3Host/Filters/FooAttribute.cs
463
C#
// Copyright (c) 2011-2015 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) #if __MonoCS__ using System; using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; namespace X11 { /// <summary> /// Declarations of unmanaged X11 functions /// </summary> internal static class Unmanaged { /// <summary/> [DllImport("libX11", EntryPoint="XOpenDisplay")] public extern static IntPtr XOpenDisplay(IntPtr display); /// <summary/> [DllImport("libX11", EntryPoint="XCloseDisplay")] public extern static int XCloseDisplay(IntPtr display); /// <summary/> [DllImport ("libX11", EntryPoint="XKeycodeToKeysym")] public extern static int XKeycodeToKeysym(IntPtr display, int keycode, int index); } internal static class X11Helper { /// <summary> /// Gets the X11 display connection that Mono already has open, rather than /// carefully opening and closing it on our own in a way that doesnt crash (FWNX-895). /// </summary> /// <remarks><para>NOTE: The display connection should not be closed!</para> /// <para>NOTE: when running unit tests Mono's DisplayHandle might not be initialized. /// One way to get it intialized is to create a control.</para></remarks> internal static IntPtr GetDisplayConnection() { var swfAssembly = Assembly.GetAssembly(typeof(System.Windows.Forms.Form)); var xplatuix11Type = swfAssembly.GetType("System.Windows.Forms.XplatUIX11"); xplatuix11Type.GetMethod("GetInstance", BindingFlags.Static | BindingFlags.Public).Invoke(null, null); var displayHandleField = xplatuix11Type.GetField("DisplayHandle", BindingFlags.Static | BindingFlags.NonPublic); var displayHandleValue = displayHandleField.GetValue(null); var displayConnection = (IntPtr)displayHandleValue; Debug.Assert(displayConnection != IntPtr.Zero, "Expected to have a handle on X11 display connection."); return displayConnection; } } } #endif
36.722222
115
0.745335
[ "MIT" ]
JohnThomson/libpalaso
PalasoUIWindowsForms/Keyboarding/Linux/X11.cs
1,983
C#
using eBordo.WinUI.Helper; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace eBordo.WinUI.Forms.AdminPanel.RasporedUtakmica { public partial class frmDetaljiUtakmice : Form { frmPrikazRasporedaUtakmicacs _prikazUtakmica; public Model.Models.Utakmica _odabranaUtakmica { get; set; } ByteToImage byteToImage = new ByteToImage(); public frmDetaljiUtakmice(Model.Models.Utakmica odabranaUtakmica) { InitializeComponent(); _odabranaUtakmica = odabranaUtakmica; } private void frmDetaljiUtakmice_Load(object sender, EventArgs e) { if (_odabranaUtakmica.vrstaUtakmice == "Domaća") { grbDomacin.BackgroundImage = Properties.Resources.grbSarajevo; grbDomacin.BackgroundImageLayout = ImageLayout.Zoom; lblDomacin.Text = "FK SARAJEVO"; grbGost.BackgroundImage = byteToImage.ConvertByteToImage(_odabranaUtakmica.protivnik.grb); grbGost.BackgroundImageLayout = ImageLayout.Zoom; lblGost.Text = _odabranaUtakmica.protivnik.nazivKluba.ToUpper(); pictureGostujucaDomaca.BackgroundImage = Properties.Resources.home; } else if (_odabranaUtakmica.vrstaUtakmice == "Gostujuća") { grbDomacin.BackgroundImage = byteToImage.ConvertByteToImage(_odabranaUtakmica.protivnik.grb); grbDomacin.BackgroundImageLayout = ImageLayout.Zoom; lblDomacin.Text = _odabranaUtakmica.protivnik.nazivKluba.ToUpper(); grbGost.BackgroundImage = Properties.Resources.grbSarajevo; grbGost.BackgroundImageLayout = ImageLayout.Zoom; lblGost.Text = "FK SARAJEVO"; pictureGostujucaDomaca.BackgroundImage = Properties.Resources.away; } lblOpisUtakmice.Text = _odabranaUtakmica.opisUtakmice.ToUpper(); txtStadion.Text = "STADION " + _odabranaUtakmica.stadion.nazivStadiona.ToUpper(); txtDatum.Text = _odabranaUtakmica.datumOdigravanja.ToString("dd.MM.yyyy"); txtSatnica.Text = _odabranaUtakmica.satnica + "h"; txtSudija.Text = _odabranaUtakmica.sudija; pictureTakmicenje.BackgroundImage = byteToImage.ConvertByteToImage(_odabranaUtakmica.takmicenje.logo); pictureTakmicenje.BackgroundImageLayout = ImageLayout.Zoom; //pictureKapiten.BackgroundImage = byteToImage.ConvertByteToImage(_odabranaUtakmica.kapiten.korisnik.Slika); //pictureKapiten.BackgroundImageLayout = ImageLayout.Zoom; txtKapiten.Text = (_odabranaUtakmica.kapiten.korisnik.ime[0] + ". " + _odabranaUtakmica.kapiten.korisnik.prezime).ToUpper(); if (_odabranaUtakmica.tipGarniture == "Domaća") { pictureDres.BackgroundImage = Properties.Resources.domaci; txtGarnitura.Text = "DOMAĆA"; } else if (_odabranaUtakmica.tipGarniture == "Gostujuća") { pictureDres.BackgroundImage = Properties.Resources.gostujuci; txtGarnitura.Text = "GOSTUJUĆA"; } else if (_odabranaUtakmica.tipGarniture == "Rezervna") { pictureDres.BackgroundImage = Properties.Resources.rezervni; txtGarnitura.Text = "REZERVNA"; } if (_odabranaUtakmica.datumOdigravanja.Date == DateTime.Now.Date) { txtBrojDana.Text = "DANAS"; } else if (_odabranaUtakmica.datumOdigravanja.Date < DateTime.Now.Date) { txtBrojDana.Text = "ZAVRŠENA PRIJE " + (DateTime.Now.Date - _odabranaUtakmica.datumOdigravanja.Date.Date).TotalDays + " DANA"; } else { txtBrojDana.Text = "ZA " + (_odabranaUtakmica.datumOdigravanja.Date.Date - DateTime.Now.Date).TotalDays + " DANA"; } foreach (var item in _odabranaUtakmica.sastav) { frmUtakmicaSastavKartica_detaljiUtakmice pozvaniIgrac = new frmUtakmicaSastavKartica_detaljiUtakmice(snackbar); pozvaniIgrac.igracSlika = byteToImage.ConvertByteToImage(item.igrac.korisnik.Slika); pozvaniIgrac.igracPozicija = item.pozicija.skracenica; pozvaniIgrac.igracImePrezime = item.igrac.korisnik.ime[0] + ". " + item.igrac.korisnik.prezime; pozvaniIgrac.brojDresa = "#" + item.igrac.brojDresa.ToString(); pozvaniIgrac.igracId = item.igracId; if(item.igrac.igracId == _odabranaUtakmica.kapitenId) { pozvaniIgrac.isKapiten = true; } else { pozvaniIgrac.isKapiten = false; } if (item.uloga == "PRVA_POSTAVA") { flowPanelPrvaPostava.Controls.Add(pozvaniIgrac); } else { flowPanelKlupa.Controls.Add(pozvaniIgrac); } } } } }
47.513274
142
0.618551
[ "MIT" ]
harispandzic/eBordo-desktop-mobile
eBordo.WinUI/Forms/AdminPanel/RasporedUtakmica/frmDetaljiUtakmice.cs
5,378
C#
using System; using System.Data; using System.Data.OleDb; using System.Drawing; using System.IO; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Text.RegularExpressions; using System.Globalization; using System.Threading; using System.Linq; using System.Diagnostics; using System.Collections.Generic; using System.Text.RegularExpressions; using AjaxControlToolkit; using RO.Facade3; using RO.Common3; using RO.Common3.Data; using RO.WebRules; namespace RO.Common3.Data { public class AdmServerRule14 : DataSet { public AdmServerRule14() { this.Tables.Add(MakeColumns(new DataTable("AdmServerRule"))); this.DataSetName = "AdmServerRule14"; this.Namespace = "http://Rintagi.com/DataSet/AdmServerRule14"; } private DataTable MakeColumns(DataTable dt) { DataColumnCollection columns = dt.Columns; columns.Add("ServerRuleId24", typeof(string)); columns.Add("RuleName24", typeof(string)); columns.Add("RuleDescription24", typeof(string)); columns.Add("RuleTypeId24", typeof(string)); columns.Add("ScreenId24", typeof(string)); columns.Add("RuleOrder24", typeof(string)); columns.Add("ProcedureName24", typeof(string)); columns.Add("ParameterNames24", typeof(string)); columns.Add("ParameterTypes24", typeof(string)); columns.Add("CallingParams24", typeof(string)); columns.Add("MasterTable24", typeof(string)); columns.Add("OnAdd24", typeof(string)); columns.Add("OnUpd24", typeof(string)); columns.Add("OnDel24", typeof(string)); columns.Add("BeforeCRUD24", typeof(string)); columns.Add("RuleCode24", typeof(string)); columns.Add("SyncByDb", typeof(string)); columns.Add("SyncToDb", typeof(string)); columns.Add("ModifiedBy24", typeof(string)); columns.Add("LastGenDt24", typeof(string)); return dt; } } } namespace RO.Web { public partial class AdmServerRuleModule : RO.Web.ModuleBase { private const string KEY_dtScreenHlp = "Cache:dtScreenHlp3_14"; private const string KEY_dtClientRule = "Cache:dtClientRule3_14"; private const string KEY_dtAuthCol = "Cache:dtAuthCol3_14"; private const string KEY_dtAuthRow = "Cache:dtAuthRow3_14"; private const string KEY_dtLabel = "Cache:dtLabel3_14"; private const string KEY_dtCriHlp = "Cache:dtCriHlp3_14"; private const string KEY_dtScrCri = "Cache:dtScrCri3_14"; private const string KEY_dsScrCriVal = "Cache:dsScrCriVal3_14"; private const string KEY_dtRuleTypeId24 = "Cache:dtRuleTypeId24"; private const string KEY_dtScreenId24 = "Cache:dtScreenId24"; private const string KEY_dtBeforeCRUD24 = "Cache:dtBeforeCRUD24"; private const string KEY_dtModifiedBy24 = "Cache:dtModifiedBy24"; private const string KEY_dtSystems = "Cache:dtSystems3_14"; private const string KEY_sysConnectionString = "Cache:sysConnectionString3_14"; private const string KEY_dtAdmServerRule14List = "Cache:dtAdmServerRule14List"; private const string KEY_bNewVisible = "Cache:bNewVisible3_14"; private const string KEY_bNewSaveVisible = "Cache:bNewSaveVisible3_14"; private const string KEY_bCopyVisible = "Cache:bCopyVisible3_14"; private const string KEY_bCopySaveVisible = "Cache:bCopySaveVisible3_14"; private const string KEY_bDeleteVisible = "Cache:bDeleteVisible3_14"; private const string KEY_bUndoAllVisible = "Cache:bUndoAllVisible3_14"; private const string KEY_bUpdateVisible = "Cache:bUpdateVisible3_14"; private const string KEY_bClCriVisible = "Cache:bClCriVisible3_14"; private byte LcSystemId; private string LcSysConnString; private string LcAppConnString; private string LcAppDb; private string LcDesDb; private string LcAppPw; protected System.Collections.Generic.Dictionary<string, DataRow> LcAuth; // *** Custom Function/Procedure Web Rule starts here *** // public AdmServerRuleModule() { this.Init += new System.EventHandler(Page_Init); } protected void Page_Load(object sender, System.EventArgs e) { Thread.CurrentThread.CurrentCulture = new CultureInfo(base.LUser.Culture); string lang2 = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName; string lang = "en,zh".IndexOf(lang2) < 0 ? lang2 : Thread.CurrentThread.CurrentCulture.Name; try { ScriptManager.RegisterStartupScript(this, this.GetType(), "datepicker_i18n", File.ReadAllText(Request.MapPath("~/scripts/i18n/jquery.ui.datepicker-" + lang + ".js")), true); } catch { }; if (!IsPostBack) { Session.Remove(KEY_dtScrCri); } int ii = 0; DataView dvCri = GetScrCriteria(); SetCriHolder(ii, dvCri); bConfirm.Value = "Y"; // To get around ajax not displaying ErrMsg and InfoMsg; Set them to Y to show immediately: bErrNow.Value = "N"; bInfoNow.Value = "N"; bExpNow.Value = "N"; CtrlToFocus.Value = string.Empty; EnableValidators(false); if (!IsPostBack) { DataTable dtMenuAccess = (new MenuSystem()).GetMenu(base.LUser.CultureId, 3, base.LImpr, LcSysConnString, LcAppPw,14, null, null); if (dtMenuAccess.Rows.Count == 0 && !IsCronInvoked()) { string message = (new AdminSystem()).GetLabel(base.LUser.CultureId, "cSystem", "AccessDeny", null, null, null); throw new Exception(message); } Session.Remove(KEY_dtAdmServerRule14List); Session.Remove(KEY_dtSystems); Session.Remove(KEY_sysConnectionString); Session.Remove(KEY_dtScreenHlp); Session.Remove(KEY_dtClientRule); Session.Remove(KEY_dtAuthCol); Session.Remove(KEY_dtAuthRow); Session.Remove(KEY_dtLabel); Session.Remove(KEY_dtCriHlp); Session.Remove(KEY_dtRuleTypeId24); Session.Remove(KEY_dtScreenId24); Session.Remove(KEY_dtBeforeCRUD24); Session.Remove(KEY_dtModifiedBy24); SetButtonHlp(); GetSystems(); SetColumnAuthority(); GetGlobalFilter(); GetScreenFilter(); GetCriteria(dvCri); DataTable dtHlp = GetScreenHlp(); cHelpMsg.HelpTitle = dtHlp.Rows[0]["ScreenTitle"].ToString(); cHelpMsg.HelpMsg = dtHlp.Rows[0]["DefaultHlpMsg"].ToString(); cFootLabel.Text = dtHlp.Rows[0]["FootNote"].ToString(); if (cFootLabel.Text == string.Empty) { cFootLabel.Visible = false; } cTitleLabel.Text = dtHlp.Rows[0]["ScreenTitle"].ToString(); DataTable dt = GetScreenTab(); cTab11.InnerText = dt.Rows[0]["TabFolderName"].ToString(); cTab12.InnerText = dt.Rows[1]["TabFolderName"].ToString(); SetClientRule(null,false); IgnoreConfirm(); InitPreserve(); try { (new AdminSystem()).LogUsage(base.LUser.UsrId, string.Empty, dtHlp.Rows[0]["ScreenTitle"].ToString(), 14, 0, 0, string.Empty, LcSysConnString, LcAppPw); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; } // *** Criteria Trigger (before) Web Rule starts here *** // PopAdmServerRule14List(sender, e, true, null); if (cAuditButton.Attributes["OnClick"] == null || cAuditButton.Attributes["OnClick"].IndexOf("AdmScrAudit.aspx") < 0) { cAuditButton.Attributes["OnClick"] += "SearchLink('AdmScrAudit.aspx?cri0=14&typ=N&sys=3','','',''); return false;"; } cScreenId24Search_Script(); cCallingParams24Search_Script(); //WebRule: Prevent production access to stored procedure, also Rintai Paas Analyst if (Config.DeployType == "PRD" || LImpr.UsrGroups == "1") {cRuleCode24.Enabled = false;} else { if (cSyncByDb.Attributes["OnClick"] == null || cSyncByDb.Attributes["OnClick"].IndexOf("return confirm") < 0) {cSyncByDb.Attributes["OnClick"] += "return confirm('Proceed to obtain stored procedure from the physical database for sure?');";} if (cSyncToDb.Attributes["OnClick"] == null || cSyncToDb.Attributes["OnClick"].IndexOf("_bConfirm") < 0) { cSyncToDb.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';"; } if (cSyncToDb.Attributes["OnClick"] == null || cSyncToDb.Attributes["OnClick"].IndexOf("return confirm") < 0) {cSyncToDb.Attributes["OnClick"] += "return confirm('Proceed to synchronize stored procedure to physical database for sure?');";} } // *** WebRule End *** // } if (IsPostBack && !ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack) {SetClientRule(null,false);}; if (!IsPostBack) // Test for Viewstate being lost. { bViewState.Text = "Y"; string xx = Session["Idle:" + Request.Url.PathAndQuery] as string; if (xx == "Y") { Session.Remove("Idle:" + Request.Url.PathAndQuery); bInfoNow.Value = "Y"; PreMsgPopup("Page has been idled past preset limit and no longer valid, please be notified that it has been reloaded."); } } else if (string.IsNullOrEmpty(bViewState.Text)) // Viewstate is lost. { Session["Idle:" + Request.Url.PathAndQuery] = "Y"; Response.Redirect(Request.Url.PathAndQuery); } if (!string.IsNullOrEmpty(cCurrentTab.Value)) { HtmlControl wcTab = this.FindControl(cCurrentTab.Value.Substring(1)) as HtmlControl; wcTab.Style["display"] = "block"; } ScriptManager.RegisterStartupScript(this, this.GetType(), "ScreenLabel", this.ClientID + "={" + string.Join(",", (from dr in GetLabel().AsEnumerable() select string.Format("{0}: {{msg:'{1}',hint:'{2}'}}", "c" + dr.Field<string>("ColumnName") + (dr.Field<int?>("TableId").ToString()), (dr.Field<string>("ErrMessage") ?? string.Empty).Replace("'", "\\'").Replace("\r", "\\r").Replace("\n", "\\n"), (dr.Field<string>("TbHint") ?? string.Empty).Replace("'", "\\'").Replace("\r", "\\r").Replace("\n", "\\n"))).ToArray()) + "};", true); } protected void Page_Init(object sender, EventArgs e) { // *** Page Init (Front of) Web Rule starts here *** // InitializeComponent(); // *** Page Init (End of) Web Rule starts here *** // } #region Web 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() { CheckAuthentication(true); if (LcSysConnString == null) { SetSystem(3); } } #endregion private void SetSystem(byte SystemId) { LcSystemId = SystemId; LcSysConnString = base.SysConnectStr(SystemId); LcAppConnString = base.AppConnectStr(SystemId); LcDesDb = base.DesDb(SystemId); LcAppDb = base.AppDb(SystemId); LcAppPw = base.AppPwd(SystemId); try { base.CPrj = new CurrPrj(((new RobotSystem()).GetEntityList()).Rows[0]); DataRow row = base.SystemsList.Rows.Find(SystemId); base.CSrc = new CurrSrc(true, row); base.CTar = new CurrTar(true, row); if ((Config.DeployType == "DEV" || row["dbAppDatabase"].ToString() == base.CPrj.EntityCode + "View") && !(base.CPrj.EntityCode != "RO" && row["SysProgram"].ToString() == "Y") && (new AdminSystem()).IsRegenNeeded(string.Empty,14,0,0,LcSysConnString,LcAppPw)) { (new GenScreensSystem()).CreateProgram(14, "Server Rule", row["dbAppDatabase"].ToString(), base.CPrj, base.CSrc, base.CTar, LcAppConnString, LcAppPw); Response.Redirect(Request.RawUrl); } } catch (Exception e) { bErrNow.Value = "Y"; PreMsgPopup(e.Message); } } private void EnableValidators(bool bEnable) { foreach (System.Web.UI.WebControls.WebControl va in Page.Validators) { if (bEnable) {va.Enabled = true;} else {va.Enabled = false;} } } private void CheckAuthentication(bool pageLoad) { if (IsCronInvoked()) AnonymousLogin(); else CheckAuthentication(pageLoad, true); } private void SetButtonHlp() { try { DataTable dt; dt = (new AdminSystem()).GetButtonHlp(14,0,0,base.LUser.CultureId,LcSysConnString,LcAppPw); if (dt != null && dt.Rows.Count > 0) { foreach (DataRow dr in dt.Rows) { if (dr["ButtonTypeName"].ToString() == "ClearCri") { cClearCriButton.CssClass = "ButtonImg ClearCriButtonImg"; Session[KEY_bClCriVisible] = base.GetBool(dr["ButtonVisible"].ToString()); cClearCriButton.ToolTip = dr["ButtonToolTip"].ToString(); } else if (dr["ButtonTypeName"].ToString() == "Save") { cSaveButton.CssClass = "ButtonImg SaveButtonImg"; cSaveButton.Text = dr["ButtonName"].ToString(); cSaveButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cSaveButton.ToolTip = dr["ButtonToolTip"].ToString(); Session[KEY_bUpdateVisible] = cSaveButton.Visible; } else if (dr["ButtonTypeName"].ToString() == "ExpTxt") { cExpTxtButton.CssClass = "ButtonImg ExpTxtButtonImg"; cExpTxtButton.Text = dr["ButtonName"].ToString(); cExpTxtButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cExpTxtButton.ToolTip = dr["ButtonToolTip"].ToString(); } else if (dr["ButtonTypeName"].ToString() == "ExpRtf") { cExpRtfButton.CssClass = "ButtonImg ExpRtfButtonImg"; cExpRtfButton.Text = dr["ButtonName"].ToString(); cExpRtfButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cExpRtfButton.ToolTip = dr["ButtonToolTip"].ToString(); } else if (dr["ButtonTypeName"].ToString() == "UndoAll") { cUndoAllButton.CssClass = "ButtonImg UndoAllButtonImg"; cUndoAllButton.Text = dr["ButtonName"].ToString(); cUndoAllButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cUndoAllButton.ToolTip = dr["ButtonToolTip"].ToString(); Session[KEY_bUndoAllVisible] = cUndoAllButton.Visible; } else if (dr["ButtonTypeName"].ToString() == "More") { cMoreButton.CssClass = "ButtonImg MoreButtonImg"; cMoreButton.Text = dr["ButtonName"].ToString(); cMoreButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cMoreButton.ToolTip = dr["ButtonToolTip"].ToString(); } else if (dr["ButtonTypeName"].ToString() == "SaveClose") { cSaveCloseButton.CssClass = "ButtonImg SaveCloseButtonImg"; cSaveCloseButton.Text = dr["ButtonName"].ToString(); cSaveCloseButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cSaveCloseButton.ToolTip = dr["ButtonToolTip"].ToString(); } else if (dr["ButtonTypeName"].ToString() == "Edit") { cEditButton.CssClass = "ButtonImg EditButtonImg"; cEditButton.Text = dr["ButtonName"].ToString(); cEditButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cEditButton.ToolTip = dr["ButtonToolTip"].ToString(); } else if (dr["ButtonTypeName"].ToString() == "Preview") { cPreviewButton.CssClass = "ButtonImg PreviewButtonImg"; cPreviewButton.Text = dr["ButtonName"].ToString(); cPreviewButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cPreviewButton.ToolTip = dr["ButtonToolTip"].ToString(); } if (dr["ButtonTypeName"].ToString() == "Audit") { cAuditButton.CssClass = "ButtonImg AuditButtonImg"; cAuditButton.Text = dr["ButtonName"].ToString(); cAuditButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cAuditButton.ToolTip = dr["ButtonToolTip"].ToString(); } if (dr["ButtonTypeName"].ToString() == "Clear") { cClearButton.CssClass = "ButtonImg ClearButtonImg"; cClearButton.Text = dr["ButtonName"].ToString(); cClearButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cClearButton.ToolTip = dr["ButtonToolTip"].ToString(); } else if (dr["ButtonTypeName"].ToString() == "New") { cNewButton.CssClass = "ButtonImg NewButtonImg"; cNewButton.Text = dr["ButtonName"].ToString(); cNewButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cNewButton.ToolTip = dr["ButtonToolTip"].ToString(); Session[KEY_bNewVisible] = cNewButton.Visible; } else if (dr["ButtonTypeName"].ToString() == "NewSave") { cNewSaveButton.CssClass = "ButtonImg NewSaveButtonImg"; cNewSaveButton.Text = dr["ButtonName"].ToString(); cNewSaveButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cNewSaveButton.ToolTip = dr["ButtonToolTip"].ToString(); Session[KEY_bNewSaveVisible] = cNewSaveButton.Visible; } else if (dr["ButtonTypeName"].ToString() == "Copy") { cCopyButton.CssClass = "ButtonImg CopyButtonImg"; cCopyButton.Text = dr["ButtonName"].ToString(); cCopyButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cCopyButton.ToolTip = dr["ButtonToolTip"].ToString(); Session[KEY_bCopyVisible] = cCopyButton.Visible;} else if (dr["ButtonTypeName"].ToString() == "CopySave") { cCopySaveButton.CssClass = "ButtonImg CopySaveButtonImg"; cCopySaveButton.Text = dr["ButtonName"].ToString(); cCopySaveButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cCopySaveButton.ToolTip = dr["ButtonToolTip"].ToString(); Session[KEY_bCopySaveVisible] = cCopySaveButton.Visible;} else if (dr["ButtonTypeName"].ToString() == "Delete") { cDeleteButton.CssClass = "ButtonImg DeleteButtonImg"; cDeleteButton.Text = dr["ButtonName"].ToString(); cDeleteButton.Visible = base.GetBool(dr["ButtonVisible"].ToString()); cDeleteButton.ToolTip = dr["ButtonToolTip"].ToString(); Session[KEY_bDeleteVisible] = cDeleteButton.Visible;} } } } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); } } private DataTable GetClientRule() { DataTable dtRul = (DataTable)Session[KEY_dtClientRule]; if (dtRul == null) { CheckAuthentication(false); try { dtRul = (new AdminSystem()).GetClientRule(14,0,base.LUser.CultureId,LcSysConnString,LcAppPw); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); } Session[KEY_dtClientRule] = dtRul; } return dtRul; } private void SetClientRule(ListViewDataItem ee, bool isEditItem) { DataView dvRul = new DataView(GetClientRule()); if (dvRul.Count > 0) { WebControl cc = null; string srp = string.Empty; string sn = string.Empty; string st = string.Empty; string sg = string.Empty; int ii = 0; int jj = 0; Regex missing = new Regex("@[0-9]+@"); string lang2 = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName; string lang = "en,zh".IndexOf(lang2) < 0 ? lang2 : Thread.CurrentThread.CurrentCulture.Name; foreach (DataRowView drv in dvRul) { if (ee == null) { srp = drv["ScriptName"].ToString(); srp = srp.Replace("@cLang@", "\'" + lang + "\'"); if (drv["ParamName"].ToString() != string.Empty) { StringBuilder sbName = new StringBuilder(); StringBuilder sbType = new StringBuilder(); StringBuilder sbInGrid = new StringBuilder(); sbName.Append(drv["ParamName"].ToString().Trim()); sbType.Append(drv["ParamType"].ToString().Trim()); sbInGrid.Append(drv["ParamInGrid"].ToString().Trim()); ii = 0; while (sbName.Length > 0) { sn = Utils.PopFirstWord(sbName,(char)44); st = Utils.PopFirstWord(sbType,(char)44);sg = Utils.PopFirstWord(sbInGrid,(char)44); if (ee != null && sg == "Y") { if (st.ToLower() == "combobox" && isEditItem) {srp = srp.Replace("@" + ii.ToString() + "@","'"+((RoboCoder.WebControls.ComboBox)ee.FindControl(sn)).KeyID+"'");} else {srp = srp.Replace("@" + ii.ToString() + "@","'"+((WebControl)ee.FindControl(sn + (!isEditItem ? "l" : ""))).ClientID+"'");} } else { if (st.ToLower() == "combobox") {srp = srp.Replace("@" + ii.ToString() + "@","'"+((RoboCoder.WebControls.ComboBox)this.FindControl(sn)).KeyID+"'");} else {srp = srp.Replace("@" + ii.ToString() + "@","'"+((WebControl)this.FindControl(sn)).ClientID+"'");} } ii = ii + 1; } } if (drv["ScriptEvent"].ToString() == "js") { ScriptManager.RegisterStartupScript(this, this.GetType(), drv["ColName"].ToString() + "_" + drv["ScriptName"].ToString() + jj.ToString(),"<script>"+ drv["ClientRuleProg"].ToString() + srp + "</script>", false); } else if (drv["ScriptEvent"].ToString() == "css") { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), drv["ColName"].ToString() + "_" + drv["ScriptName"].ToString() + jj.ToString(),"<style>"+ drv["ClientRuleProg"].ToString() + "</style>", false); } else if (drv["ScriptEvent"].ToString() == "css_link") { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), drv["ColName"].ToString() + "_" + drv["ScriptName"].ToString() + jj.ToString(),"<link rel='stylesheet' type='text/css' href='"+ drv["ClientRuleProg"].ToString() + "' />", false); } else if (drv["ScriptEvent"].ToString() == "js_link") { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), drv["ColName"].ToString() + "_" + drv["ScriptName"].ToString() + jj.ToString(),"<script type='text/javascript' src='"+ drv["ClientRuleProg"].ToString() + "'></script>", false); } else { srp = missing.Replace(srp, "''"); string scriptEvent = drv["ScriptEvent"].ToString().TrimStart(new char[]{'_'}); if (ee != null) {cc = ee.FindControl(drv["ColName"].ToString()) as WebControl;} else {cc = this.FindControl(drv["ColName"].ToString()) as WebControl;} if (cc != null && (cc.Attributes[scriptEvent] == null || cc.Attributes[scriptEvent].IndexOf(srp) < 0)) {cc.Attributes[scriptEvent] += srp;} if (ee != null && drv["ScriptEvent"].ToString().Substring(0,2).ToLower() != "on") { cc = ee.FindControl(drv["ColName"].ToString() + "l") as WebControl; if (cc != null && (cc.Attributes[scriptEvent] == null || cc.Attributes[scriptEvent].IndexOf(srp) < 0)) {cc.Attributes[scriptEvent] += srp;} } } } jj = jj + 1; } } } private DataTable GetScreenCriHlp() { DataTable dtCriHlp = (DataTable)Session[KEY_dtCriHlp]; if (dtCriHlp == null) { CheckAuthentication(false); try { dtCriHlp = (new AdminSystem()).GetScreenCriHlp(14,base.LUser.CultureId,LcSysConnString,LcAppPw); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); } Session[KEY_dtCriHlp] = dtCriHlp; } return dtCriHlp; } private DataTable GetScreenHlp() { DataTable dtHlp = (DataTable)Session[KEY_dtScreenHlp]; if (dtHlp == null) { CheckAuthentication(false); try { dtHlp = (new AdminSystem()).GetScreenHlp(14,base.LUser.CultureId,LcSysConnString,LcAppPw); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); } Session[KEY_dtScreenHlp] = dtHlp; } return dtHlp; } private void GetGlobalFilter() { try { DataTable dt; dt = (new AdminSystem()).GetGlobalFilter(base.LUser.UsrId,14,base.LUser.CultureId,LcSysConnString,LcAppPw); if (dt != null && dt.Rows.Count > 0) { cGlobalFilter.Text = dt.Rows[0]["FilterDesc"].ToString(); cGlobalFilter.Visible = true; } } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); } } private void GetScreenFilter() { try { DataTable dt = (new AdminSystem()).GetScreenFilter(14,base.LUser.CultureId,LcSysConnString,LcAppPw); if (dt != null) { cFilterId.DataSource = dt; cFilterId.DataBind(); if (cFilterId.Items.Count > 0) { if (Request.QueryString["ftr"] != null) {cFilterId.Items.FindByValue(Request.QueryString["ftr"]).Selected = true;} else {cFilterId.Items[0].Selected = true;} cFilterLabel.Text = (new AdminSystem()).GetLabel(base.LUser.CultureId, "QFilter", "QFilter", null, null, null); cFilter.Visible = true; } } } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); } } private void GetSystems() { Session[KEY_sysConnectionString] = LcSysConnString; DataTable dtSystems = base.SystemsList; if (dtSystems != null) { Session[KEY_dtSystems] = dtSystems; cSystemId.DataSource = dtSystems; cSystemId.DataBind(); if (cSystemId.Items.Count > 1) { if (Request.QueryString["sys"] != null) {cSystemId.Items.FindByValue(Request.QueryString["sys"]).Selected = true;} else { try { cSystemId.Items.FindByValue(base.LCurr.DbId.ToString()).Selected = true; } catch {cSystemId.Items[0].Selected = true;} } base.LCurr.DbId = byte.Parse(cSystemId.SelectedValue); Session[KEY_sysConnectionString] = Config.GetConnStr(dtSystems.Rows[cSystemId.SelectedIndex]["dbAppProvider"].ToString(), dtSystems.Rows[cSystemId.SelectedIndex]["ServerName"].ToString(), dtSystems.Rows[cSystemId.SelectedIndex]["dbDesDatabase"].ToString(), "", dtSystems.Rows[cSystemId.SelectedIndex]["dbAppUserId"].ToString()); cSystemLabel.Text = (new AdminSystem()).GetLabel(base.LUser.CultureId, "cSystem", "Label", null, null, null); cSystem.Visible = true; } } } protected string ColumnWatermark(int idx) { return GetLabel().Rows[idx]["tbHint"].ToString(); } protected string ColumnHeaderText(int idx) { return (GetLabel().Rows[idx]["RequiredValid"].ToString() == "Y" ? Config.MandatoryChar : string.Empty) + GetLabel().Rows[idx]["ColumnHeader"].ToString(); } protected string ColumnToolTip(int idx) { return GetLabel().Rows[idx]["ToolTip"].ToString(); } protected bool GridColumnVisible(int idx) { return GetAuthCol().Rows[idx]["ColVisible"].ToString()=="Y"; } protected bool GridColumnEnable(int idx) { return GetAuthCol().Rows[idx]["ColReadOnly"].ToString()=="N"; } private DataTable GetLabel() { DataTable dt = (DataTable)Session[KEY_dtLabel]; if (dt == null) { try { dt = (new AdminSystem()).GetScreenLabel(14,base.LUser.CultureId,base.LImpr,base.LCurr,LcSysConnString,LcAppPw); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); } Session[KEY_dtLabel] = dt; } return dt; } private DataTable GetAuthCol() { DataTable dt = (DataTable)Session[KEY_dtAuthCol]; if (dt == null) { try { dt = (new AdminSystem()).GetAuthCol(14,base.LImpr,base.LCurr,LcSysConnString,LcAppPw); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); } Session[KEY_dtAuthCol] = dt; } return dt; } protected DataTable GetAuthRow() { DataTable dt = (DataTable)Session[KEY_dtAuthRow]; if (dt == null) { try { dt = (new AdminSystem()).GetAuthRow(14,base.LImpr.RowAuthoritys,LcSysConnString,LcAppPw); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); } Session[KEY_dtAuthRow] = dt; } return dt; } private void getReport(string eExport) { try { StringBuilder sb = new StringBuilder(); CheckAuthentication(false); DataView dv = null; int filterId = 0; if (Utils.IsInt(cFilterId.SelectedValue)) { filterId = int.Parse(cFilterId.SelectedValue); } try { try {dv = new DataView((new AdminSystem()).GetExp(14,"GetExpAdmServerRule14","Y",(string)Session[KEY_sysConnectionString],LcAppPw,filterId,GetScrCriteria(),base.LImpr,base.LCurr,UpdCriteria(false)));} catch {dv = new DataView((new AdminSystem()).GetExp(14,"GetExpAdmServerRule14","N",(string)Session[KEY_sysConnectionString],LcAppPw,filterId,GetScrCriteria(),base.LImpr,base.LCurr,UpdCriteria(false)));} } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; } if (eExport == "TXT") { DataTable dtAu; dtAu = (new AdminSystem()).GetAuthExp(14,base.LUser.CultureId,base.LImpr,base.LCurr,LcSysConnString,LcAppPw); if (dtAu != null) { if (dtAu.Rows[0]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[0]["ColumnHeader"].ToString() + (char)9);} if (dtAu.Rows[1]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[1]["ColumnHeader"].ToString() + (char)9);} if (dtAu.Rows[2]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[2]["ColumnHeader"].ToString() + (char)9);} if (dtAu.Rows[3]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[3]["ColumnHeader"].ToString() + (char)9 + dtAu.Rows[3]["ColumnHeader"].ToString() + " Text" + (char)9);} if (dtAu.Rows[4]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[4]["ColumnHeader"].ToString() + (char)9 + dtAu.Rows[4]["ColumnHeader"].ToString() + " Text" + (char)9);} if (dtAu.Rows[5]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[5]["ColumnHeader"].ToString() + (char)9);} if (dtAu.Rows[6]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[6]["ColumnHeader"].ToString() + (char)9);} if (dtAu.Rows[7]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[7]["ColumnHeader"].ToString() + (char)9);} if (dtAu.Rows[8]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[8]["ColumnHeader"].ToString() + (char)9);} if (dtAu.Rows[9]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[9]["ColumnHeader"].ToString() + (char)9);} if (dtAu.Rows[10]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[10]["ColumnHeader"].ToString() + (char)9);} if (dtAu.Rows[11]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[11]["ColumnHeader"].ToString() + (char)9);} if (dtAu.Rows[12]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[12]["ColumnHeader"].ToString() + (char)9);} if (dtAu.Rows[13]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[13]["ColumnHeader"].ToString() + (char)9);} if (dtAu.Rows[14]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[14]["ColumnHeader"].ToString() + (char)9 + dtAu.Rows[14]["ColumnHeader"].ToString() + " Text" + (char)9);} if (dtAu.Rows[15]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[15]["ColumnHeader"].ToString() + (char)9);} if (dtAu.Rows[16]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[16]["ColumnHeader"].ToString() + (char)9);} if (dtAu.Rows[19]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[19]["ColumnHeader"].ToString() + (char)9 + dtAu.Rows[19]["ColumnHeader"].ToString() + " Text" + (char)9);} if (dtAu.Rows[20]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[20]["ColumnHeader"].ToString() + (char)9);} if (dtAu.Rows[21]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[21]["ColumnHeader"].ToString() + (char)9);} sb.Append(Environment.NewLine); } foreach (DataRowView drv in dv) { if (dtAu.Rows[0]["ColExport"].ToString() == "Y") {sb.Append(RO.Common3.Utils.fmNumeric("0",drv["ServerRuleId24"].ToString(),base.LUser.Culture) + (char)9);} if (dtAu.Rows[1]["ColExport"].ToString() == "Y") {sb.Append("\"" + drv["RuleName24"].ToString().Replace("\"","\"\"") + "\"" + (char)9);} if (dtAu.Rows[2]["ColExport"].ToString() == "Y") {sb.Append("\"" + drv["RuleDescription24"].ToString().Replace("\"","\"\"") + "\"" + (char)9);} if (dtAu.Rows[3]["ColExport"].ToString() == "Y") {sb.Append(drv["RuleTypeId24"].ToString() + (char)9 + drv["RuleTypeId24Text"].ToString() + (char)9);} if (dtAu.Rows[4]["ColExport"].ToString() == "Y") {sb.Append(drv["ScreenId24"].ToString() + (char)9 + drv["ScreenId24Text"].ToString() + (char)9);} if (dtAu.Rows[5]["ColExport"].ToString() == "Y") {sb.Append(RO.Common3.Utils.fmNumeric("0",drv["RuleOrder24"].ToString(),base.LUser.Culture) + (char)9);} if (dtAu.Rows[6]["ColExport"].ToString() == "Y") {sb.Append("\"" + drv["ProcedureName24"].ToString().Replace("\"","\"\"") + "\"" + (char)9);} if (dtAu.Rows[7]["ColExport"].ToString() == "Y") {sb.Append("\"" + drv["ParameterNames24"].ToString().Replace("\"","\"\"") + "\"" + (char)9);} if (dtAu.Rows[8]["ColExport"].ToString() == "Y") {sb.Append("\"" + drv["ParameterTypes24"].ToString().Replace("\"","\"\"") + "\"" + (char)9);} if (dtAu.Rows[9]["ColExport"].ToString() == "Y") {sb.Append("\"" + drv["CallingParams24"].ToString().Replace("\"","\"\"") + "\"" + (char)9);} if (dtAu.Rows[10]["ColExport"].ToString() == "Y") {sb.Append("\"" + drv["MasterTable24"].ToString().Replace("\"","\"\"") + "\"" + (char)9);} if (dtAu.Rows[11]["ColExport"].ToString() == "Y") {sb.Append("\"" + drv["OnAdd24"].ToString().Replace("\"","\"\"") + "\"" + (char)9);} if (dtAu.Rows[12]["ColExport"].ToString() == "Y") {sb.Append("\"" + drv["OnUpd24"].ToString().Replace("\"","\"\"") + "\"" + (char)9);} if (dtAu.Rows[13]["ColExport"].ToString() == "Y") {sb.Append("\"" + drv["OnDel24"].ToString().Replace("\"","\"\"") + "\"" + (char)9);} if (dtAu.Rows[14]["ColExport"].ToString() == "Y") {sb.Append("\"" + drv["BeforeCRUD24"].ToString().Replace("\"","\"\"") + "\"" + (char)9 + "\"" + drv["BeforeCRUD24Text"].ToString().Replace("\"","\"\"") + "\"" + (char)9);} if (dtAu.Rows[15]["ColExport"].ToString() == "Y") {sb.Append("\"" + drv["CrudTypeDesc1289"].ToString().Replace("\"","\"\"") + "\"" + (char)9);} if (dtAu.Rows[16]["ColExport"].ToString() == "Y") {sb.Append("\"" + drv["RuleCode24"].ToString().Replace("\"","\"\"") + "\"" + (char)9);} if (dtAu.Rows[19]["ColExport"].ToString() == "Y") {sb.Append(drv["ModifiedBy24"].ToString() + (char)9 + drv["ModifiedBy24Text"].ToString() + (char)9);} if (dtAu.Rows[20]["ColExport"].ToString() == "Y") {sb.Append(RO.Common3.Utils.fmShortDateTimeUTC(drv["ModifiedOn24"].ToString(),base.LUser.Culture,CurrTimeZoneInfo()) + (char)9);} if (dtAu.Rows[21]["ColExport"].ToString() == "Y") {sb.Append(drv["LastGenDt24"].ToString() + (char)9);} sb.Append(Environment.NewLine); } bExpNow.Value = "Y"; Session["ExportFnm"] = "AdmServerRule.xls"; Session["ExportStr"] = sb.Replace("\r\n","\n"); } else if (eExport == "RTF") { sb.Append(@"{\rtf1\ansi\ansicpg1252\uc1\deff0\stshfdbch0\stshfloch0\stshfhich0\stshfbi0\deflang1033\deflangfe1033{\fonttbl{\f0\froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\f37\fswiss\fcharset0\fprq2{\*\panose 020b0604030504040204}Verdana;} {\f182\froman\fcharset238\fprq2 Times New Roman CE;}{\f183\froman\fcharset204\fprq2 Times New Roman Cyr;}{\f185\froman\fcharset161\fprq2 Times New Roman Greek;}{\f186\froman\fcharset162\fprq2 Times New Roman Tur;} {\f187\froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\f188\froman\fcharset178\fprq2 Times New Roman (Arabic);}{\f189\froman\fcharset186\fprq2 Times New Roman Baltic;}{\f190\froman\fcharset163\fprq2 Times New Roman (Vietnamese);} {\f552\fswiss\fcharset238\fprq2 Verdana CE;}{\f553\fswiss\fcharset204\fprq2 Verdana Cyr;}{\f555\fswiss\fcharset161\fprq2 Verdana Greek;}{\f556\fswiss\fcharset162\fprq2 Verdana Tur;}{\f559\fswiss\fcharset186\fprq2 Verdana Baltic;} {\f560\fswiss\fcharset163\fprq2 Verdana (Vietnamese);}}{\colortbl;\red0\green0\blue0;\red0\green0\blue255;\red0\green255\blue255;\red0\green255\blue0;\red255\green0\blue255;\red255\green0\blue0;\red255\green255\blue0;\red255\green255\blue255; \red0\green0\blue128;\red0\green128\blue128;\red0\green128\blue0;\red128\green0\blue128;\red128\green0\blue0;\red128\green128\blue0;\red128\green128\blue128;\red192\green192\blue192;}{\stylesheet{ \ql \li0\ri0\widctlpar\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \fs24\lang1033\langfe1033\cgrid\langnp1033\langfenp1033 \snext0 Normal;}{\*\cs10 \additive \ssemihidden Default Paragraph Font;}{\* \ts11\tsrowd\trftsWidthB3\trpaddl108\trpaddr108\trpaddfl3\trpaddft3\trpaddfb3\trpaddfr3\tscellwidthfts0\tsvertalt\tsbrdrt\tsbrdrl\tsbrdrb\tsbrdrr\tsbrdrdgl\tsbrdrdgr\tsbrdrh\tsbrdrv \ql \li0\ri0\widctlpar\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \fs20\lang1024\langfe1024\cgrid\langnp1024\langfenp1024 \snext11 \ssemihidden Normal Table;}}{\*\latentstyles\lsdstimax156\lsdlockeddef0}{\*\rsidtbl \rsid1574081\rsid2952683 \rsid4674135\rsid4855636\rsid6620441\rsid6645578\rsid7160396\rsid7497391\rsid8133092\rsid8259185\rsid8528326\rsid8936003\rsid9058410\rsid10305085\rsid10505691\rsid13726773\rsid14047122\rsid14576392\rsid15756354\rsid16472473\rsid16525787}{\*\generator Micr osoft Word 11.0.6359;}{\info{\title [[ScreenTitle]]}{\author }{\operator }{\creatim\yr2004\mo12\dy21\hr12\min7}{\revtim\yr2004\mo12\dy21\hr16\min16}{\version7}{\edmins5}{\nofpages1}{\nofwords6}{\nofchars38} {\*\company robocoder corporation}{\nofcharsws43}{\vern24703}}\margl1440\margr1440 \widowctrl\ftnbj\aenddoc\noxlattoyen\expshrtn\noultrlspc\dntblnsbdb\nospaceforul\hyphcaps0\formshade\horzdoc\dgmargin\dghspace180\dgvspace180\dghorigin1440\dgvorigin1440 \dghshow1\dgvshow1\jexpand\viewkind1\viewscale100\pgbrdrhead\pgbrdrfoot\splytwnine\ftnlytwnine\htmautsp\nolnhtadjtbl\useltbaln\alntblind\lytcalctblwd\lyttblrtgr\lnbrkrule\nobrkwrptbl\snaptogridincell\allowfieldendsel\wrppunct \asianbrkrule\rsidroot4855636\newtblstyruls\nogrowautofit \fet0\sectd \linex0\endnhere\sectlinegrid360\sectdefaultcl\sectrsid7497391\sftnbj {\*\pnseclvl1\pnucrm\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl2\pnucltr\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl3\pndec\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl4\pnlcltr\pnstart1\pnindent720\pnhang {\pntxta )}}{\*\pnseclvl5\pndec\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl6\pnlcltr\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl7\pnlcrm\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl8\pnlcltr\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl9\pnlcrm\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}\pard\plain \qc \li0\ri0\widctlpar\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0\pararsid4855636 \fs24\lang1033\langfe1033\cgrid\langnp1033\langfenp1033 {\b\fs32\insrsid4855636\charrsid6645578 [[TitleLabel]]}{\b\fs32\insrsid16472473\charrsid6645578 \par }{\insrsid4855636 \par }{\b\i\fs18\insrsid4855636\charrsid8936003 [[GlobalFilter]] \par }\pard \ql \li0\ri0\widctlpar\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0\pararsid8259185 {\insrsid7497391 \par }\pard \qc \li0\ri0\widctlpar\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0\pararsid4855636 {\f37\fs16\insrsid4855636\charrsid1574081 [[Grid]] \par }\pard \ql \li0\ri0\widctlpar\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 {\insrsid4855636 \par }}"); sb.Replace("[[TitleLabel]]", cTitleLabel.Text); sb.Replace("[[GlobalFilter]]", cGlobalFilter.Text); sb.Replace("[[Grid]]", GetRtfGrid(dv)); bExpNow.Value = "Y"; Session["ExportFnm"] = "AdmServerRule.rtf"; Session["ExportStr"] = sb; } } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); } } private string GetRtfGrid(DataView dv) { StringBuilder sb = new StringBuilder(""); try { int iColCnt = 0; DataTable dtAu; dtAu = (new AdminSystem()).GetAuthExp(14,base.LUser.CultureId,base.LImpr,base.LCurr,LcSysConnString,LcAppPw); if (dtAu != null) { if (dtAu.Rows[0]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;} if (dtAu.Rows[1]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;} if (dtAu.Rows[2]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;} if (dtAu.Rows[3]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;} if (dtAu.Rows[4]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;} if (dtAu.Rows[5]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;} if (dtAu.Rows[6]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;} if (dtAu.Rows[7]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;} if (dtAu.Rows[8]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;} if (dtAu.Rows[9]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;} if (dtAu.Rows[10]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;} if (dtAu.Rows[11]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;} if (dtAu.Rows[12]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;} if (dtAu.Rows[13]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;} if (dtAu.Rows[14]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;} if (dtAu.Rows[15]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;} if (dtAu.Rows[16]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;} if (dtAu.Rows[19]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;} if (dtAu.Rows[20]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;} if (dtAu.Rows[21]["ColExport"].ToString() == "Y") {iColCnt = iColCnt + 1;} //Create Header sb.Append(@"\trowd \irow0\irowband0\lastrow \ts15\trgaph108\trleft-108\trbrdrt\brdrs\brdrw10 \trbrdrl\brdrs\brdrw10 \trbrdrb\brdrs\brdrw10 \trbrdrr\brdrs\brdrw10 \trbrdrh\brdrs\brdrw10 \trbrdrv\brdrs\brdrw10 "); sb.Append(@"\trftsWidth1\trftsWidthB3\trautofit1\trpaddl108\trpaddr108\trpaddfl3\trpaddft3\trpaddfb3\trpaddfr3\tblrsid2981395\tbllkhdrrows\tbllklastrow\tbllkhdrcols\tbllklastcol "); sb.Append("\r\n"); sb.Append(GenCellx(iColCnt)); sb.Append(@"\pard \ql \li0\ri0\widctlpar\intbl\aspalpha\aspnum\adjustright\rin0\lin0 \lang1033\langfe1033\cgrid\langnp1033\langfenp1033 "); sb.Append("\r\n"); sb.Append(@"\b"); sb.Append(@"{"); if (dtAu.Rows[0]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[0]["ColumnHeader"].ToString() + @"\cell ");} if (dtAu.Rows[1]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[1]["ColumnHeader"].ToString() + @"\cell ");} if (dtAu.Rows[2]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[2]["ColumnHeader"].ToString() + @"\cell ");} if (dtAu.Rows[3]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[3]["ColumnHeader"].ToString() + @"\cell ");} if (dtAu.Rows[4]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[4]["ColumnHeader"].ToString() + @"\cell ");} if (dtAu.Rows[5]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[5]["ColumnHeader"].ToString() + @"\cell ");} if (dtAu.Rows[6]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[6]["ColumnHeader"].ToString() + @"\cell ");} if (dtAu.Rows[7]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[7]["ColumnHeader"].ToString() + @"\cell ");} if (dtAu.Rows[8]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[8]["ColumnHeader"].ToString() + @"\cell ");} if (dtAu.Rows[9]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[9]["ColumnHeader"].ToString() + @"\cell ");} if (dtAu.Rows[10]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[10]["ColumnHeader"].ToString() + @"\cell ");} if (dtAu.Rows[11]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[11]["ColumnHeader"].ToString() + @"\cell ");} if (dtAu.Rows[12]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[12]["ColumnHeader"].ToString() + @"\cell ");} if (dtAu.Rows[13]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[13]["ColumnHeader"].ToString() + @"\cell ");} if (dtAu.Rows[14]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[14]["ColumnHeader"].ToString() + @"\cell ");} if (dtAu.Rows[15]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[15]["ColumnHeader"].ToString() + @"\cell ");} if (dtAu.Rows[16]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[16]["ColumnHeader"].ToString() + @"\cell ");} if (dtAu.Rows[19]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[19]["ColumnHeader"].ToString() + @"\cell ");} if (dtAu.Rows[20]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[20]["ColumnHeader"].ToString() + @"\cell ");} if (dtAu.Rows[21]["ColExport"].ToString() == "Y") {sb.Append(dtAu.Rows[21]["ColumnHeader"].ToString() + @"\cell ");} sb.Append(@"}"); sb.Append(@"\b0"); sb.Append("\r\n"); sb.Append(@"\pard \ql \li0\ri0\widctlpar\intbl\aspalpha\aspnum\adjustright\rin0\lin0 {"); sb.Append(@"\insrsid2981395 \trowd \irow0\irowband0\lastrow \ts15\trgaph108\trleft-108\trbrdrt\brdrs\brdrw10 \trbrdrl\brdrs\brdrw10 \trbrdrb\brdrs\brdrw10 \trbrdrr\brdrs\brdrw10 \trbrdrh\brdrs\brdrw10 \trbrdrv\brdrs\brdrw10 "); sb.Append(@"\trftsWidth1\trftsWidthB3\trautofit1\trpaddl108\trpaddr108\trpaddfl3\trpaddft3\trpaddfb3\trpaddfr3\tblrsid2981395\tbllkhdrrows\tbllklastrow\tbllkhdrcols\tbllklastcol "); sb.Append("\r\n"); sb.Append(GenCellx(iColCnt)); sb.Append("\r\n"); sb.Append(@"\row }"); sb.Append("\r\n"); } //Create Data Rows foreach (DataRowView drv in dv) { sb.Append(@"\trowd \irow0\irowband0\lastrow \ts15\trgaph108\trleft-108\trbrdrt\brdrs\brdrw10 \trbrdrl\brdrs\brdrw10 \trbrdrb\brdrs\brdrw10 \trbrdrr\brdrs\brdrw10 \trbrdrh\brdrs\brdrw10 \trbrdrv\brdrs\brdrw10 "); sb.Append(@"\trftsWidth1\trftsWidthB3\trautofit1\trpaddl108\trpaddr108\trpaddfl3\trpaddft3\trpaddfb3\trpaddfr3\tblrsid2981395\tbllkhdrrows\tbllklastrow\tbllkhdrcols\tbllklastcol "); sb.Append("\r\n"); sb.Append(GenCellx(iColCnt)); sb.Append(@"\pard \ql \li0\ri0\widctlpar\intbl\aspalpha\aspnum\adjustright\rin0\lin0 \lang1033\langfe1033\cgrid\langnp1033\langfenp1033 "); sb.Append("\r\n"); sb.Append(@"{"); if (dtAu.Rows[0]["ColExport"].ToString() == "Y") {sb.Append(RO.Common3.Utils.fmNumeric("0",drv["ServerRuleId24"].ToString(),base.LUser.Culture) + @"\cell ");} if (dtAu.Rows[1]["ColExport"].ToString() == "Y") {sb.Append(drv["RuleName24"].ToString().Replace("\r\n",@"\par ") + @"\cell ");} if (dtAu.Rows[2]["ColExport"].ToString() == "Y") {sb.Append(drv["RuleDescription24"].ToString().Replace("\r\n",@"\par ") + @"\cell ");} if (dtAu.Rows[3]["ColExport"].ToString() == "Y") {sb.Append(drv["RuleTypeId24Text"].ToString() + @"\cell ");} if (dtAu.Rows[4]["ColExport"].ToString() == "Y") {sb.Append(drv["ScreenId24Text"].ToString() + @"\cell ");} if (dtAu.Rows[5]["ColExport"].ToString() == "Y") {sb.Append(RO.Common3.Utils.fmNumeric("0",drv["RuleOrder24"].ToString(),base.LUser.Culture) + @"\cell ");} if (dtAu.Rows[6]["ColExport"].ToString() == "Y") {sb.Append(drv["ProcedureName24"].ToString().Replace("\r\n",@"\par ") + @"\cell ");} if (dtAu.Rows[7]["ColExport"].ToString() == "Y") {sb.Append(drv["ParameterNames24"].ToString().Replace("\r\n",@"\par ") + @"\cell ");} if (dtAu.Rows[8]["ColExport"].ToString() == "Y") {sb.Append(drv["ParameterTypes24"].ToString().Replace("\r\n",@"\par ") + @"\cell ");} if (dtAu.Rows[9]["ColExport"].ToString() == "Y") {sb.Append(drv["CallingParams24"].ToString().Replace("\r\n",@"\par ") + @"\cell ");} if (dtAu.Rows[10]["ColExport"].ToString() == "Y") {sb.Append(drv["MasterTable24"].ToString().Replace("\r\n",@"\par ") + @"\cell ");} if (dtAu.Rows[11]["ColExport"].ToString() == "Y") {sb.Append(drv["OnAdd24"].ToString().Replace("\r\n",@"\par ") + @"\cell ");} if (dtAu.Rows[12]["ColExport"].ToString() == "Y") {sb.Append(drv["OnUpd24"].ToString().Replace("\r\n",@"\par ") + @"\cell ");} if (dtAu.Rows[13]["ColExport"].ToString() == "Y") {sb.Append(drv["OnDel24"].ToString().Replace("\r\n",@"\par ") + @"\cell ");} if (dtAu.Rows[14]["ColExport"].ToString() == "Y") {sb.Append(drv["BeforeCRUD24Text"].ToString().Replace("\r\n",@"\par ") + @"\cell ");} if (dtAu.Rows[15]["ColExport"].ToString() == "Y") {sb.Append(drv["CrudTypeDesc1289"].ToString().Replace("\r\n",@"\par ") + @"\cell ");} if (dtAu.Rows[16]["ColExport"].ToString() == "Y") {sb.Append(drv["RuleCode24"].ToString().Replace("\r\n",@"\par ") + @"\cell ");} if (dtAu.Rows[19]["ColExport"].ToString() == "Y") {sb.Append(drv["ModifiedBy24Text"].ToString() + @"\cell ");} if (dtAu.Rows[20]["ColExport"].ToString() == "Y") {sb.Append(RO.Common3.Utils.fmShortDateTimeUTC(drv["ModifiedOn24"].ToString(),base.LUser.Culture,CurrTimeZoneInfo()) + @"\cell ");} if (dtAu.Rows[21]["ColExport"].ToString() == "Y") {sb.Append(drv["LastGenDt24"].ToString() + @"\cell ");} sb.Append(@"}"); sb.Append("\r\n"); sb.Append(@"\pard \ql \li0\ri0\widctlpar\intbl\aspalpha\aspnum\adjustright\rin0\lin0 {"); sb.Append(@"\insrsid2981395 \trowd \irow0\irowband0\lastrow \ts15\trgaph108\trleft-108\trbrdrt\brdrs\brdrw10 \trbrdrl\brdrs\brdrw10 \trbrdrb\brdrs\brdrw10 \trbrdrr\brdrs\brdrw10 \trbrdrh\brdrs\brdrw10 \trbrdrv\brdrs\brdrw10 "); sb.Append(@"\trftsWidth1\trftsWidthB3\trautofit1\trpaddl108\trpaddr108\trpaddfl3\trpaddft3\trpaddfb3\trpaddfr3\tblrsid2981395\tbllkhdrrows\tbllklastrow\tbllkhdrcols\tbllklastcol "); sb.Append("\r\n"); sb.Append(GenCellx(iColCnt)); sb.Append("\r\n"); sb.Append(@"\row }"); sb.Append("\r\n"); } sb.Append(@"\pard \par }"); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); } return sb.ToString(); } private StringBuilder GenCellx(int CellCnt) { StringBuilder sb = new StringBuilder(""); string strRowPre = @"\clvertalt\clbrdrt\brdrs\brdrw10 \clbrdrl\brdrs\brdrw10 \clbrdrb\brdrs\brdrw10 \clbrdrr\brdrs\brdrw10 \cltxlrtb\clftsWidth3\clwWidth4428\clshdrawnil "; for (int cnt=0; cnt<CellCnt; cnt++) {sb.Append(strRowPre + @"\cellx" + cnt.ToString() + " ");} return sb; } public void cScreenId24Search_Click(object sender, System.Web.UI.ImageClickEventArgs e) { RoboCoder.WebControls.ComboBox cc = cScreenId24; cc.SetTbVisible(); Session["CtrlAdmScreen"] = cc.FocusID; } public void cScreenId24Search_Script() { ImageButton ib = cScreenId24Search; if (ib != null) { TextBox pp = cServerRuleId24; RoboCoder.WebControls.ComboBox cc = cScreenId24; string ss = "&dsp=ComboBox"; if (cSystem.Visible) {ss = ss + "&sys=" + cSystemId.SelectedValue;} else {ss = ss + "&sys=3";} ib.Attributes["onclick"] = "SearchLink('AdmScreen.aspx?col=ScreenId" + ss + "&typ=N" + "','" + cc.FocusID + "','',''); return false;"; } } public void cCallingParams24Search_Click(object sender, System.Web.UI.ImageClickEventArgs e) { TextBox cc = cCallingParams24; Session["CtrlAdmDbTable"] = cc.ClientID; } public void cCallingParams24Search_Script() { ImageButton ib = cCallingParams24Search; if (ib != null) { TextBox pp = cServerRuleId24; TextBox cc = cCallingParams24; string ss = "?dsp=TextBox"; if (cSystem.Visible) {ss = ss + "&sys=" + cSystemId.SelectedValue;} else {ss = ss + "&sys=3";} ib.Attributes["onclick"] = "SearchLink('AdmDbTable.aspx" + ss + "&typ=N" + "','" + "','',''); return false;"; } } public void cExpTxtButton_Click(object sender, System.EventArgs e) { // *** System Button Click (Before) Web Rule starts here *** // getReport("TXT"); // *** System Button Click (After) Web Rule starts here *** // } public void cExpRtfButton_Click(object sender, System.EventArgs e) { // *** System Button Click (before) Web Rule starts here *** // getReport("RTF"); // *** System Button Click (after) Web Rule starts here *** // } public void cClearCriButton_Click(object sender, System.EventArgs e) { // *** System Button Click (before) Web Rule starts here *** // System.Web.UI.WebControls.Calendar cCalendar; ListBox cListBox; RoboCoder.WebControls.ComboBox cComboBox; DropDownList cDropDownList; RadioButtonList cRadioButtonList; CheckBox cCheckBox; TextBox cTextBox; DataView dvCri = GetScrCriteria(); foreach (DataRowView drv in dvCri) { if (drv["DisplayName"].ToString() == "ComboBox") // Reset to page 1 by reassigning the datasource: { cComboBox = (RoboCoder.WebControls.ComboBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); if (cComboBox != null && cComboBox.Items.Count > 0) { cComboBox.DataSource = cComboBox.DataSource; cComboBox.SelectByValue(cComboBox.Items[0].Value, string.Empty, true); } } else if (drv["DisplayName"].ToString() == "DropDownList") { cDropDownList = (DropDownList)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); if (cDropDownList != null && cDropDownList.Items.Count > 0) { cDropDownList.SelectedIndex = 0; } } else if (drv["DisplayName"].ToString() == "ListBox") { cListBox = (ListBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); if (cListBox != null && cListBox.Items.Count > 0) { cListBox.SelectedIndex = 0; } } else if (drv["DisplayName"].ToString() == "RadioButtonList") { cRadioButtonList = (RadioButtonList)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); if (cRadioButtonList != null && cRadioButtonList.Items.Count > 0) { cRadioButtonList.SelectedIndex = 0; } } else if (drv["DisplayName"].ToString() == "Calendar") { cCalendar = (System.Web.UI.WebControls.Calendar)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); if (cCalendar != null) { if (drv["RequiredValid"].ToString() == "N") { cCalendar.SelectedDates.Clear(); } else { cCalendar.SelectedDate = System.DateTime.Today; } } } else if (drv["DisplayName"].ToString() == "CheckBox") { cCheckBox = (CheckBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); if (cCheckBox != null) { cCheckBox.Checked = false; } } else { cTextBox = (TextBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); if (cTextBox != null) { if (drv["RequiredValid"].ToString() == "N") { cTextBox.Text = string.Empty; } else if (drv["DisplayMode"].ToString().IndexOf("Date") >= 0) { cTextBox.Text = System.DateTime.Today.ToString(); } else { cTextBox.Text = "0"; } } } } cCriButton_Click(sender, e); if (cFilterId.Items.Count > 0) { cFilterId.SelectedIndex = 0; } // *** System Button Click (after) Web Rule starts here *** // } private void GetCriteria(DataView dvCri) { try { DataTable dt; dt = (new AdminSystem()).GetLastCriteria(int.Parse(dvCri.Count.ToString()) + 1, 14, 0, base.LUser.UsrId, LcSysConnString, LcAppPw); cCriPanel.Visible = true; // Enable cCriteria.Visible to be set: if (dt.Rows.Count <= 0) { cCriteria.Visible = false; } if (!string.IsNullOrEmpty(Request.QueryString["key"]) && bUseCri.Value == string.Empty) { cCriPanel.Visible = false; cClearCriButton.Visible = false; } else { cCriPanel.Visible = (cCriteria.Visible && cCriteria.Controls.Count > 2) || cFilter.Visible; if ((bool)Session[KEY_bClCriVisible]) {cClearCriButton.Visible = cCriteria.Visible && cCriteria.Controls.Count > 2;} else {cClearCriButton.Visible = false;} } if (!IsPostBack) { int jj = 0; // Zero-based to be consistent with SQL reporting. foreach (DataRowView drv in dvCri) { if (Request.QueryString["Cri" + jj.ToString()] != null) { dt.Rows[jj+1]["LastCriteria"] = Request.QueryString["Cri" + jj.ToString()].ToString(); } jj = jj + 1; } } SetCriteria(dt, dvCri); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); } } private void GetSelectedItems(ListBox cObj, string selectedItems) { string selectedItem; bool finish; if (selectedItems == string.Empty) { try {cObj.SelectedIndex = 0;} catch {} } else { finish = false; while (!finish) { selectedItem = GetSelectedItem(ref selectedItems); if (selectedItem == string.Empty) { finish = true; } else { try { cObj.Items.FindByValue(selectedItem).Selected = true; } catch { finish = true; try {cObj.SelectedIndex = 0;} catch {} } } } } } private string GetSelectedItem(ref string selectedItems) { string selectedItem; int sIndex = selectedItems.IndexOf("'"); int eIndex = selectedItems.IndexOf("'",sIndex + 1); if (sIndex >= 0 && eIndex >= 0) { selectedItem = selectedItems.Substring(sIndex + 1, eIndex - sIndex - 1); } else { selectedItem = string.Empty; } selectedItems = selectedItems.Substring(eIndex + 1, selectedItems.Length - eIndex - 1); return selectedItem; } protected void cCriButton_Click(object sender, System.EventArgs e) { // *** Criteria Trigger (before) Web Rule starts here *** // if (IsPostBack && cCriteria.Visible) ReBindCriteria(GetScrCriteria()); UpdCriteria(true); cAdmServerRule14List.ClearSearch(); Session.Remove(KEY_dtAdmServerRule14List); PopAdmServerRule14List(sender, e, false, null); } private void SetCriteria(DataTable dt, DataView dvCri) { Label cLabel; System.Web.UI.WebControls.Calendar cCalendar; ListBox cListBox; RoboCoder.WebControls.ComboBox cComboBox; DropDownList cDropDownList; RadioButtonList cRadioButtonList; CheckBox cCheckBox; TextBox cTextBox; DataTable dtCriHlp = GetScreenCriHlp(); int ii = 1; try { foreach (DataRowView drv in dvCri) { cLabel = (Label)cCriteria.FindControl("x" + drv["ColumnName"].ToString() + "Label"); if (drv["DisplayName"].ToString() == "ComboBox") { cComboBox = (RoboCoder.WebControls.ComboBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); string val = null; try {val=dt.Rows[ii]["LastCriteria"].ToString();} catch {}; base.SetCriBehavior(cComboBox, null, cLabel, dtCriHlp.Rows[ii-1]); (new AdminSystem()).MkGetScreenIn("14", drv["ScreenCriId"].ToString(), "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), LcAppDb, LcDesDb, drv["MultiDesignDb"].ToString(), LcSysConnString, LcAppPw); DataView dv = new DataView((new AdminSystem()).GetScreenIn("14", "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), (new AdminSystem()).CountScrCri(drv["ScreenCriId"].ToString(), drv["MultiDesignDb"].ToString(), drv["MultiDesignDb"].ToString() == "N" ? LcSysConnString : (string)Session[KEY_sysConnectionString], LcAppPw), drv["RequiredValid"].ToString(), 0, string.Empty, drv["DisplayMode"].ToString() != "AutoListBox", val, base.LImpr, base.LCurr, drv["MultiDesignDb"].ToString() == "N" ? LcAppConnString : (string)Session[KEY_sysConnectionString], LcAppPw)); FilterCriteriaDdl(cCriteria, dv, drv); cComboBox.DataSource = dv; try { cComboBox.SelectByValue(dt.Rows[ii]["LastCriteria"], string.Empty, false); } catch { try { cComboBox.SelectedIndex = 0; } catch { } } } else if (drv["DisplayName"].ToString() == "DropDownList") { cDropDownList = (DropDownList)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); base.SetCriBehavior(cDropDownList, null, cLabel, dtCriHlp.Rows[ii-1]); (new AdminSystem()).MkGetScreenIn("14", drv["ScreenCriId"].ToString(), "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), LcAppDb, LcDesDb, drv["MultiDesignDb"].ToString(), LcSysConnString, LcAppPw); DataView dv = new DataView((new AdminSystem()).GetScreenIn("14", "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), (new AdminSystem()).CountScrCri(drv["ScreenCriId"].ToString(), drv["MultiDesignDb"].ToString(), drv["MultiDesignDb"].ToString() == "N" ? LcSysConnString : (string)Session[KEY_sysConnectionString], LcAppPw), drv["RequiredValid"].ToString(), 0, string.Empty, base.LImpr, base.LCurr, drv["MultiDesignDb"].ToString() == "N" ? LcAppConnString : (string)Session[KEY_sysConnectionString], LcAppPw)); FilterCriteriaDdl(cCriteria, dv, drv); cDropDownList.DataSource = dv; cDropDownList.DataBind(); try { cDropDownList.Items.FindByValue(dt.Rows[ii]["LastCriteria"].ToString()).Selected = true; } catch { try { cDropDownList.SelectedIndex = 0; } catch { } } } else if (drv["DisplayName"].ToString() == "ListBox") { cListBox = (ListBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); string val = null; try {val=dt.Rows[ii]["LastCriteria"].ToString();} catch {}; base.SetCriBehavior(cListBox, null, cLabel, dtCriHlp.Rows[ii-1]); (new AdminSystem()).MkGetScreenIn("14", drv["ScreenCriId"].ToString(), "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), LcAppDb, LcDesDb, drv["MultiDesignDb"].ToString(), LcSysConnString, LcAppPw); DataView dv = new DataView((new AdminSystem()).GetScreenIn("14", "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), (new AdminSystem()).CountScrCri(drv["ScreenCriId"].ToString(), drv["MultiDesignDb"].ToString(), drv["MultiDesignDb"].ToString() == "N" ? LcSysConnString : (string)Session[KEY_sysConnectionString], LcAppPw), drv["RequiredValid"].ToString(), 0, string.Empty, drv["DisplayMode"].ToString() != "AutoListBox", val, base.LImpr, base.LCurr, drv["MultiDesignDb"].ToString() == "N" ? LcAppConnString : (string)Session[KEY_sysConnectionString], LcAppPw)); FilterCriteriaDdl(cCriteria, dv, drv); cListBox.DataSource = dv; cListBox.DataBind(); GetSelectedItems(cListBox, dt.Rows[ii]["LastCriteria"].ToString()); } else if (drv["DisplayName"].ToString() == "RadioButtonList") { cRadioButtonList = (RadioButtonList)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); base.SetCriBehavior(cRadioButtonList, null, cLabel, dtCriHlp.Rows[ii-1]); (new AdminSystem()).MkGetScreenIn("14", drv["ScreenCriId"].ToString(), "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), LcAppDb, LcDesDb, drv["MultiDesignDb"].ToString(), LcSysConnString, LcAppPw); DataView dv = new DataView((new AdminSystem()).GetScreenIn("14", "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), (new AdminSystem()).CountScrCri(drv["ScreenCriId"].ToString(), drv["MultiDesignDb"].ToString(), drv["MultiDesignDb"].ToString() == "N" ? LcSysConnString : (string)Session[KEY_sysConnectionString], LcAppPw), drv["RequiredValid"].ToString(), 0, string.Empty, base.LImpr, base.LCurr, drv["MultiDesignDb"].ToString() == "N" ? LcAppConnString : (string)Session[KEY_sysConnectionString], LcAppPw)); FilterCriteriaDdl(cCriteria, dv, drv); cRadioButtonList.DataSource = dv; cRadioButtonList.DataBind(); try { cRadioButtonList.Items.FindByValue(dt.Rows[ii]["LastCriteria"].ToString()).Selected = true; } catch { try { cRadioButtonList.SelectedIndex = 0; } catch { } } } else if (drv["DisplayName"].ToString() == "Calendar") { cCalendar = (System.Web.UI.WebControls.Calendar)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); base.SetCriBehavior(cCalendar, null, cLabel, dtCriHlp.Rows[ii-1]); if (dt.Rows[ii]["LastCriteria"].ToString() == string.Empty) { cCalendar.SelectedDates.Clear(); } else { cCalendar.SelectedDate = DateTime.Parse(dt.Rows[ii]["LastCriteria"].ToString()); cCalendar.VisibleDate = cCalendar.SelectedDate; } } else if (drv["DisplayName"].ToString() == "CheckBox") { cCheckBox = (CheckBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); base.SetCriBehavior(cCheckBox, null, cLabel, dtCriHlp.Rows[ii-1]); if (dt.Rows[ii]["LastCriteria"].ToString() != string.Empty) { cCheckBox.Checked = base.GetBool(dt.Rows[ii]["LastCriteria"].ToString()); } } else { cTextBox = (TextBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); base.SetCriBehavior(cTextBox, null, cLabel, dtCriHlp.Rows[ii-1]); cTextBox.Text = dt.Rows[ii]["LastCriteria"].ToString(); } ii = ii + 1; } } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); } } private void ReBindCriteria(DataView dvCri) { ListBox cListBox; RoboCoder.WebControls.ComboBox cComboBox; DropDownList cDropDownList; RadioButtonList cRadioButtonList; try { foreach (DataRowView drv in dvCri) { if (string.IsNullOrEmpty(drv["DdlFtrColumnId"].ToString()) && drv["DisplayMode"].ToString() != "AutoListBox" ) continue; if (drv["DisplayName"].ToString() == "ComboBox") { cComboBox = (RoboCoder.WebControls.ComboBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); string val = cComboBox.SelectedValue; DataView dv = new DataView((new AdminSystem()).GetScreenIn("14", "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), (new AdminSystem()).CountScrCri(drv["ScreenCriId"].ToString(), drv["MultiDesignDb"].ToString(), drv["MultiDesignDb"].ToString() == "N" ? LcSysConnString : (string)Session[KEY_sysConnectionString], LcAppPw), drv["RequiredValid"].ToString(), 0, string.Empty, drv["DisplayMode"].ToString() != "AutoListBox", val, base.LImpr, base.LCurr, drv["MultiDesignDb"].ToString() == "N" ? LcAppConnString : (string)Session[KEY_sysConnectionString], LcAppPw)); FilterCriteriaDdl(cCriteria, dv, drv); cComboBox.DataSource = dv; try { cComboBox.SelectByValue(val, string.Empty, false); } catch { try { cComboBox.SelectedIndex = 0; } catch { } } } else if (drv["DisplayName"].ToString() == "DropDownList") { cDropDownList = (DropDownList)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); string val = cDropDownList.SelectedValue; DataView dv = new DataView((new AdminSystem()).GetScreenIn("14", "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), (new AdminSystem()).CountScrCri(drv["ScreenCriId"].ToString(), drv["MultiDesignDb"].ToString(), drv["MultiDesignDb"].ToString() == "N" ? LcSysConnString : (string)Session[KEY_sysConnectionString], LcAppPw), drv["RequiredValid"].ToString(), 0, string.Empty, base.LImpr, base.LCurr, drv["MultiDesignDb"].ToString() == "N" ? LcAppConnString : (string)Session[KEY_sysConnectionString], LcAppPw)); FilterCriteriaDdl(cCriteria, dv, drv); cDropDownList.DataSource = dv; cDropDownList.DataBind(); try { cDropDownList.Items.FindByValue(val).Selected = true; } catch { try { cDropDownList.SelectedIndex = 0; } catch { } } } else if (drv["DisplayName"].ToString() == "ListBox") { cListBox = (ListBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); TextBox cTextBox = (TextBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString() + "Hidden"); string selectedValues = string.Join(",", cListBox.Items.Cast<ListItem>().Where(x => x.Selected).Select(x => "'" + x.Value + "'").ToArray()); if (drv["DisplayMode"].ToString() == "AutoListBox" && cTextBox != null) selectedValues = cTextBox.Text ; DataView dv = new DataView((new AdminSystem()).GetScreenIn("14", "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), (new AdminSystem()).CountScrCri(drv["ScreenCriId"].ToString(), drv["MultiDesignDb"].ToString(), drv["MultiDesignDb"].ToString() == "N" ? LcSysConnString : (string)Session[KEY_sysConnectionString], LcAppPw), drv["RequiredValid"].ToString(), 0, string.Empty, drv["DisplayMode"].ToString() != "AutoListBox", selectedValues, base.LImpr, base.LCurr, drv["MultiDesignDb"].ToString() == "N" ? LcAppConnString : (string)Session[KEY_sysConnectionString], LcAppPw)); FilterCriteriaDdl(cCriteria, dv, drv); cListBox.DataSource = dv; cListBox.DataBind(); GetSelectedItems(cListBox, selectedValues); } else if (drv["DisplayName"].ToString() == "RadioButtonList") { cRadioButtonList = (RadioButtonList)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); string val = cRadioButtonList.SelectedValue; DataView dv = new DataView((new AdminSystem()).GetScreenIn("14", "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), (new AdminSystem()).CountScrCri(drv["ScreenCriId"].ToString(), drv["MultiDesignDb"].ToString(), drv["MultiDesignDb"].ToString() == "N" ? LcSysConnString : (string)Session[KEY_sysConnectionString], LcAppPw), drv["RequiredValid"].ToString(), 0, string.Empty, base.LImpr, base.LCurr, drv["MultiDesignDb"].ToString() == "N" ? LcAppConnString : (string)Session[KEY_sysConnectionString], LcAppPw)); FilterCriteriaDdl(cCriteria, dv, drv); cRadioButtonList.DataSource = dv; cRadioButtonList.DataBind(); try { cRadioButtonList.Items.FindByValue(val).Selected = true; } catch { try { cRadioButtonList.SelectedIndex = 0; } catch { } } } } } catch { } } private DataView GetScrCriteria() { DataTable dtScrCri = (DataTable)Session[KEY_dtScrCri]; if (dtScrCri == null) { try { dtScrCri = (new AdminSystem()).GetScrCriteria("14", LcSysConnString, LcAppPw); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); } Session[KEY_dtScrCri] = dtScrCri; } return dtScrCri.DefaultView; } private void MakeScrGrpLab(DataRowView drv) { Literal cLiteral = new Literal(); string sLabelCss = drv["LabelCss"].ToString(); if (sLabelCss != string.Empty) { if (sLabelCss.StartsWith(".")) {cLiteral.Text = "<div class=\"" + sLabelCss.Substring(1) + "\">";} else {cLiteral.Text = "<div class=\"r-labelL\" style=\"" + sLabelCss + "\">";} } else {cLiteral.Text = "<div class=\"r-labelL\">";} cCriteria.Controls.Add(cLiteral); Label cLabel = new Label(); cLabel.ID = "x" + drv["ColumnName"].ToString() + "Label"; cLabel.CssClass = "inp-lbl"; cCriteria.Controls.Add(cLabel); cLiteral = new Literal(); cLiteral.Text = "</div>"; cCriteria.Controls.Add(cLiteral); } private void MakeScrGrpInp(DataRowView drv) { System.Web.UI.WebControls.Calendar cCalendar; ListBox cListBox; RoboCoder.WebControls.ComboBox cComboBox; DropDownList cDropDownList; RadioButtonList cRadioButtonList; CheckBox cCheckBox; TextBox cTextBox; Literal cLiteral = new Literal(); string sContentCss = drv["ContentCss"].ToString(); if (sContentCss != string.Empty) { if (sContentCss.StartsWith(".")) {cLiteral.Text = "<div class=\"" + sContentCss.Substring(1) + "\">";} else {cLiteral.Text = "<div class=\"r-content\" style=\"" + sContentCss + "\">";} } else {cLiteral.Text = "<div class=\"r-content\">";} cCriteria.Controls.Add(cLiteral); if (drv["DisplayName"].ToString() == "ComboBox") { cComboBox = new RoboCoder.WebControls.ComboBox(); cComboBox.ID = "x" + drv["ColumnName"].ToString(); cComboBox.CssClass = "inp-ddl"; cComboBox.SelectedIndexChanged += new EventHandler(cCriButton_Click); cComboBox.DataValueField = drv["DdlKeyColumnName"].ToString(); cComboBox.DataTextField = drv["DdlRefColumnName"].ToString(); cComboBox.AutoPostBack = true; if (drv["DisplayMode"].ToString() == "AutoComplete") { WebControl wcFtr = (WebControl)cCriteria.FindControl("x" + drv["DdlFtrColumnName"].ToString()); System.Collections.Generic.Dictionary<string, string> context = new System.Collections.Generic.Dictionary<string, string>(); context["method"] = "GetScreenIn"; context["addnew"] = "Y"; context["sp"] = "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(); context["requiredValid"] = drv["RequiredValid"].ToString(); context["mKey"] = drv["DdlKeyColumnName"].ToString(); context["mVal"] = drv["DdlRefColumnName"].ToString(); context["mTip"] = drv["DdlRefColumnName"].ToString(); context["mImg"] = drv["DdlRefColumnName"].ToString(); context["ssd"] = Request.QueryString["ssd"]; context["scr"] = "14"; context["csy"] = "3"; context["filter"] = Utils.IsInt(cFilterId.SelectedValue)? cFilterId.SelectedValue : "0"; context["isSys"] = "N"; context["conn"] = drv["MultiDesignDb"].ToString() == "N" ? string.Empty : KEY_sysConnectionString; context["refColCID"] = wcFtr != null ? wcFtr.ClientID : null; context["refCol"] = wcFtr != null ? drv["DdlFtrColumnName"].ToString() : null; context["refColDataType"] = wcFtr != null ? drv["DdlFtrDataType"].ToString() : null; cComboBox.AutoCompleteUrl = "AutoComplete.aspx/DdlSuggests"; cComboBox.DataContext = context; cComboBox.Mode = "A"; } cCriteria.Controls.Add(cComboBox); } else if (drv["DisplayName"].ToString() == "DropDownList") { cDropDownList = new DropDownList(); cDropDownList.ID = "x" + drv["ColumnName"].ToString(); cDropDownList.CssClass = "inp-ddl"; cDropDownList.SelectedIndexChanged += new EventHandler(cCriButton_Click); cDropDownList.DataValueField = drv["DdlKeyColumnName"].ToString(); cDropDownList.DataTextField = drv["DdlRefColumnName"].ToString(); cDropDownList.AutoPostBack = true; cCriteria.Controls.Add(cDropDownList); } else if (drv["DisplayName"].ToString() == "ListBox") { cListBox = new ListBox(); cListBox.ID = "x" + drv["ColumnName"].ToString(); cListBox.SelectionMode = ListSelectionMode.Multiple; cListBox.CssClass = "inp-pic"; cListBox.SelectedIndexChanged += new EventHandler(cCriButton_Click); cListBox.DataValueField = drv["DdlKeyColumnName"].ToString(); cListBox.DataTextField = drv["DdlRefColumnName"].ToString(); cListBox.AutoPostBack = true; if (drv["RowSize"].ToString() != string.Empty) {cListBox.Rows = int.Parse(drv["RowSize"].ToString()); cListBox.Height = int.Parse(drv["RowSize"].ToString()) * 16 + 7; } cCriteria.Controls.Add(cListBox); if (drv["DisplayMode"].ToString() == "AutoListBox") { WebControl wcFtr = (WebControl)cCriteria.FindControl("x" + drv["DdlFtrColumnName"].ToString()); System.Collections.Generic.Dictionary<string, string> context = new System.Collections.Generic.Dictionary<string, string>(); context["method"] = "GetScreenIn"; context["addnew"] = "Y"; context["sp"] = "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(); context["requiredValid"] = drv["RequiredValid"].ToString(); context["mKey"] = drv["DdlKeyColumnName"].ToString(); context["mVal"] = drv["DdlRefColumnName"].ToString(); context["mTip"] = drv["DdlRefColumnName"].ToString(); context["mImg"] = drv["DdlRefColumnName"].ToString(); context["ssd"] = Request.QueryString["ssd"]; context["scr"] = "14"; context["csy"] = "3"; context["filter"] = Utils.IsInt(cFilterId.SelectedValue)? cFilterId.SelectedValue : "0"; context["isSys"] = "N"; context["conn"] = drv["MultiDesignDb"].ToString() == "N" ? string.Empty : KEY_sysConnectionString; context["refColCID"] = wcFtr != null ? wcFtr.ClientID : null; context["refCol"] = wcFtr != null ? drv["DdlFtrColumnName"].ToString() : null; context["refColDataType"] = wcFtr != null ? drv["DdlFtrDataType"].ToString() : null; Session["AdmServerRule14" + cListBox.ID] = context; cListBox.Attributes["ac_context"] = "AdmServerRule14" + cListBox.ID; cListBox.Attributes["ac_url"] = "AutoComplete.aspx/DdlSuggestsEx"; cListBox.Attributes["refColCID"] = wcFtr != null ? wcFtr.ClientID : null; cListBox.Attributes["searchable"] = ""; TextBox tb = new TextBox(); tb.ID = "x" + drv["ColumnName"].ToString() + "Hidden";tb.Attributes["style"] = "display:none;"; cCriteria.Controls.Add(tb); } } else if (drv["DisplayName"].ToString() == "RadioButtonList") { cRadioButtonList = new RadioButtonList(); cRadioButtonList.ID = "x" + drv["ColumnName"].ToString(); cRadioButtonList.CssClass = "inp-rad"; cRadioButtonList.SelectedIndexChanged += new EventHandler(cCriButton_Click); cRadioButtonList.DataValueField = drv["DdlKeyColumnName"].ToString(); cRadioButtonList.DataTextField = drv["DdlRefColumnName"].ToString(); cRadioButtonList.AutoPostBack = true; cRadioButtonList.RepeatDirection = System.Web.UI.WebControls.RepeatDirection.Horizontal; cRadioButtonList.Attributes["OnClick"] = "this.focus();"; cLiteral = new Literal(); cLiteral.Text = "<div>"; cCriteria.Controls.Add(cLiteral); cCriteria.Controls.Add(cRadioButtonList); cLiteral = new Literal(); cLiteral.Text = "</div>"; cCriteria.Controls.Add(cLiteral); } else if (drv["DisplayName"].ToString() == "Calendar") { cCalendar = new System.Web.UI.WebControls.Calendar(); cCalendar.ID = "x" + drv["ColumnName"].ToString(); cCalendar.CssClass = "inp-txt calendar"; cCalendar.SelectionChanged += new EventHandler(cCriButton_Click); cCriteria.Controls.Add(cCalendar); } else if (drv["DisplayName"].ToString() == "CheckBox") { cCheckBox = new CheckBox(); cCheckBox.ID = "x" + drv["ColumnName"].ToString(); cCheckBox.CssClass = "inp-chk"; cCheckBox.AutoPostBack = true; cCheckBox.CheckedChanged += new EventHandler(cCriButton_Click); cCriteria.Controls.Add(cCheckBox); cCheckBox.Attributes["OnClick"] = "this.focus();"; } else { cTextBox = new TextBox(); cTextBox.ID = "x" + drv["ColumnName"].ToString(); cTextBox.CssClass = "inp-txt"; cTextBox.AutoPostBack = true; cTextBox.TextChanged += new EventHandler(cCriButton_Click); if (drv["DisplayMode"].ToString() == "MultiLine") { cTextBox.TextMode = TextBoxMode.MultiLine; } else if (drv["DisplayMode"].ToString() == "Password") { cTextBox.TextMode = TextBoxMode.Password; } if (drv["ColumnJustify"].ToString() == "L") { cTextBox.Style.Value = "text-align:left;"; } else if (drv["ColumnJustify"].ToString() == "R") { cTextBox.Style.Value = "text-align:right;"; } else { cTextBox.Style.Value = "text-align:center;"; } cCriteria.Controls.Add(cTextBox); } cLiteral = new Literal(); cLiteral.Text = "</div>"; cCriteria.Controls.Add(cLiteral); } private void SetCriHolder(int ii, DataView dvCri) { Literal cLiteral; if (dvCri.Count > 0) { foreach (DataRowView drv in dvCri) { cLiteral = new Literal(); cLiteral.Text = "<div class=\"r-criteria\">"; cCriteria.Controls.Add(cLiteral); MakeScrGrpLab(drv); MakeScrGrpInp(drv); cLiteral = new Literal(); cLiteral.Text = "</div>"; cCriteria.Controls.Add(cLiteral); } } } private DataTable MakeColumns(DataTable dt) { DataColumnCollection columns = dt.Columns; DataView dvCri = GetScrCriteria(); foreach (DataRowView drv in dvCri) { if (drv["DataTypeSysName"].ToString() == "DateTime") { columns.Add(drv["ColumnName"].ToString(), typeof(DateTime)); } else if (drv["DataTypeSysName"].ToString() == "Byte") { columns.Add(drv["ColumnName"].ToString(), typeof(Byte)); } else if (drv["DataTypeSysName"].ToString() == "Int16") { columns.Add(drv["ColumnName"].ToString(), typeof(Int16)); } else if (drv["DataTypeSysName"].ToString() == "Int32") { columns.Add(drv["ColumnName"].ToString(), typeof(Int32)); } else if (drv["DataTypeSysName"].ToString() == "Int64") { columns.Add(drv["ColumnName"].ToString(), typeof(Int64)); } else if (drv["DataTypeSysName"].ToString() == "Single") { columns.Add(drv["ColumnName"].ToString(), typeof(Single)); } else if (drv["DataTypeSysName"].ToString() == "Double") { columns.Add(drv["ColumnName"].ToString(), typeof(Double)); } else if (drv["DataTypeSysName"].ToString() == "Byte[]") { columns.Add(drv["ColumnName"].ToString(), typeof(Byte[])); } else if (drv["DataTypeSysName"].ToString() == "Object") { columns.Add(drv["ColumnName"].ToString(), typeof(Object)); } else { columns.Add(drv["ColumnName"].ToString(), typeof(String)); } } return dt; } private DataSet UpdCriteria(bool bUpdate) { System.Web.UI.WebControls.Calendar cCalendar; ListBox cListBox; RoboCoder.WebControls.ComboBox cComboBox; DropDownList cDropDownList; RadioButtonList cRadioButtonList; CheckBox cCheckBox; TextBox cTextBox; DataSet ds = new DataSet(); ds.Tables.Add(MakeColumns(new DataTable("DtScreenIn"))); DataRow dr = ds.Tables["DtScreenIn"].NewRow(); DataView dvCri = GetScrCriteria(); foreach (DataRowView drv in dvCri) { if (drv["DisplayName"].ToString() == "ListBox") { cListBox = (ListBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); if (cListBox != null) { int CriCnt = (new AdminSystem()).CountScrCri(drv["ScreenCriId"].ToString(), drv["MultiDesignDb"].ToString(), drv["MultiDesignDb"].ToString() == "N" ? LcSysConnString : (string)Session[KEY_sysConnectionString], LcAppPw); int TotalChoiceCnt = new DataView((new AdminSystem()).GetScreenIn("14", "GetDdl" + drv["ColumnName"].ToString() + LCurr.SystemId.ToString() + "C" + drv["ScreenCriId"].ToString(), CriCnt, drv["RequiredValid"].ToString(), 0, string.Empty, true, string.Empty, base.LImpr, base.LCurr, drv["MultiDesignDb"].ToString() == "N" ? LcAppConnString : (string)Session[KEY_sysConnectionString], LcAppPw)).Count; string selectedValues = string.Join(",", cListBox.Items.Cast<ListItem>().Where(x => x.Selected).Select(x => "'" + x.Value + "'").ToArray()); bool noneSelected = string.IsNullOrEmpty(selectedValues) || selectedValues == "''"; dr[drv["ColumnName"].ToString()] = "("; if (noneSelected && CriCnt+1 > TotalChoiceCnt) dr[drv["ColumnName"].ToString()] = dr[drv["ColumnName"].ToString()].ToString() + "'-1'"; foreach (ListItem li in cListBox.Items) { if (li.Selected) { if (dr[drv["ColumnName"].ToString()].ToString() != "(") { dr[drv["ColumnName"].ToString()] = dr[drv["ColumnName"].ToString()].ToString() + ","; } dr[drv["ColumnName"].ToString()] = dr[drv["ColumnName"].ToString()].ToString() + "'" + li.Value + "'"; } } } if (IsPostBack && drv["RequiredValid"].ToString() == "Y" && string.IsNullOrEmpty(cListBox.SelectedValue)) { bErrNow.Value = "Y"; PreMsgPopup("Criteria column: " + drv["ColumnName"].ToString() + " cannot be empty. Please rectify and try again."); } if (dr[drv["ColumnName"].ToString()].ToString() == "(''" || dr[drv["ColumnName"].ToString()].ToString() == "(") { dr[drv["ColumnName"].ToString()] = string.Empty; } else { dr[drv["ColumnName"].ToString()] = dr[drv["ColumnName"].ToString()].ToString() + ")"; } } else if (drv["DisplayName"].ToString() == "Calendar") { cCalendar = (System.Web.UI.WebControls.Calendar)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); if (cCalendar != null && cCalendar.SelectedDate > DateTime.Parse("0001-01-01")) { dr[drv["ColumnName"].ToString()] = cCalendar.SelectedDate; } } else if (drv["DisplayName"].ToString() == "ComboBox") { cComboBox = (RoboCoder.WebControls.ComboBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); if (IsPostBack && drv["RequiredValid"].ToString() == "Y" && string.IsNullOrEmpty(cComboBox.SelectedValue)) { bErrNow.Value = "Y"; PreMsgPopup("Criteria column: " + drv["ColumnName"].ToString() + " cannot be empty. Please rectify and try again."); } if (cComboBox != null && cComboBox.SelectedIndex >= 0 && cComboBox.SelectedValue != string.Empty) { dr[drv["ColumnName"].ToString()] = cComboBox.SelectedValue; } } else if (drv["DisplayName"].ToString() == "DropDownList") { cDropDownList = (DropDownList)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); if (IsPostBack && drv["RequiredValid"].ToString() == "Y" && string.IsNullOrEmpty(cDropDownList.SelectedValue)) { bErrNow.Value = "Y"; PreMsgPopup("Criteria column: " + drv["ColumnName"].ToString() + " cannot be empty. Please rectify and try again."); } if (cDropDownList != null && cDropDownList.SelectedIndex >= 0 && cDropDownList.SelectedValue != string.Empty) { dr[drv["ColumnName"].ToString()] = cDropDownList.SelectedValue; } } else if (drv["DisplayName"].ToString() == "RadioButtonList") { cRadioButtonList = (RadioButtonList)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); if (IsPostBack && drv["RequiredValid"].ToString() == "Y" && string.IsNullOrEmpty(cRadioButtonList.SelectedValue)) { bErrNow.Value = "Y"; PreMsgPopup("Criteria column: " + drv["ColumnName"].ToString() + " cannot be empty. Please rectify and try again."); } if (cRadioButtonList != null && cRadioButtonList.SelectedIndex >= 0 && cRadioButtonList.SelectedValue != string.Empty) { dr[drv["ColumnName"].ToString()] = cRadioButtonList.SelectedValue; } } else if (drv["DisplayName"].ToString() == "CheckBox") { cCheckBox = (CheckBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); if (cCheckBox != null) { dr[drv["ColumnName"].ToString()] = base.SetBool(cCheckBox.Checked); } } else { cTextBox = (TextBox)cCriteria.FindControl("x" + drv["ColumnName"].ToString()); if (drv["RequiredValid"].ToString() == "Y" && string.IsNullOrEmpty(cTextBox.Text)) { if (IsPostBack) { bErrNow.Value = "Y"; PreMsgPopup("Criteria column: " + drv["ColumnName"].ToString() + " cannot be empty. Please rectify and try again.");} cTextBox.Text = drv["DisplayMode"].ToString().Contains("Date") ? DateTime.Today.Date.ToShortDateString() : "?"; } if (cTextBox != null && cTextBox.Text != string.Empty) { dr[drv["ColumnName"].ToString()] = (",DateUTC,DateTimeUTC,ShortDateTimeUTC,LongDateTimeUTC,".IndexOf("," + drv["DisplayMode"].ToString() + ",") >= 0) ? SetDateTimeUTC(cTextBox.Text,!bUpdate) : (drv["DisplayName"].ToString().Contains("Date") ? (DateTime.Parse(cTextBox.Text,System.Threading.Thread.CurrentThread.CurrentCulture).ToString()): cTextBox.Text); } } } ds.Tables["DtScreenIn"].Rows.Add(dr); if (bUpdate) { try { (new AdminSystem()).UpdScrCriteria("14", "AdmServerRule14", dvCri, base.LUser.UsrId, cCriteria.Visible, ds, LcAppConnString, LcAppPw); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); } } Session[KEY_dsScrCriVal] = ds; return ds; } private DataTable GetScreenTab() { CheckAuthentication(false); DataTable dtScreenTab = null; try { dtScreenTab = (new AdminSystem()).GetScreenTab(14,base.LUser.CultureId,LcSysConnString,LcAppPw); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); } return dtScreenTab; } private void SetRuleTypeId24(DropDownList ddl, string keyId) { DataTable dt = (DataTable)Session[KEY_dtRuleTypeId24]; DataView dv = dt != null ? dt.DefaultView : null; if (ddl != null) { string ss = string.Empty; ListItem li = null; bool bFirst = false; bool bAll = false; if (ddl.Enabled && ddl.Visible) {bAll = true;} if (dv == null) { bFirst = true; try { dv = new DataView((new AdminSystem()).GetDdl(14,"GetDdlRuleTypeId3S151",true,bAll,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr)); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; } } if (dv != null) { if (dv.Table.Columns.Contains("ServerRuleId")) { ss = "(ServerRuleId is null"; if (string.IsNullOrEmpty(cAdmServerRule14List.SelectedValue)) {ss = ss + ")";} else {ss = ss + " OR ServerRuleId = " + cAdmServerRule14List.SelectedValue + ")";} } if (!string.IsNullOrEmpty(keyId) && !ddl.Enabled) { ss = ss + (string.IsNullOrEmpty(ss) ? string.Empty : " AND ") + "RuleTypeId24 is not NULL"; } dv.RowFilter = ss; ddl.DataSource = dv; ddl.DataBind(); li = ddl.Items.FindByValue(keyId); if (li != null) {li.Selected = true;} else if (!bFirst) { try { dv = new DataView((new AdminSystem()).GetDdl(14,"GetDdlRuleTypeId3S151",true,bAll,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr)); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; } dv.RowFilter = ss; ddl.DataSource = dv; ddl.DataBind(); li = ddl.Items.FindByValue(keyId); if (li != null) {li.Selected = true;} } if (dv.Count <= 1 && keyId != string.Empty) // In case invalid value casued by copy action. { try { dv = new DataView((new AdminSystem()).GetDdl(14,"GetDdlRuleTypeId3S151",true,true,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr)); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; } dv.RowFilter = ss; ddl.DataSource = dv; ddl.DataBind(); li = ddl.Items.FindByValue(keyId); if (li != null) {li.Selected = true;} } Session[KEY_dtRuleTypeId24] = dv.Table; } } } protected void cbScreenId24(object sender, System.EventArgs e) { SetScreenId24((RoboCoder.WebControls.ComboBox)sender,string.Empty); } private void SetScreenId24(RoboCoder.WebControls.ComboBox ddl, string keyId) { System.Collections.Generic.Dictionary<string, string> context = new System.Collections.Generic.Dictionary<string, string>(); context["method"] = "GetDdlScreenId3S139"; context["addnew"] = "Y"; context["mKey"] = "ScreenId24"; context["mVal"] = "ScreenId24Text"; context["mTip"] = "ScreenId24Text"; context["mImg"] = "ScreenId24Text"; context["ssd"] = Request.QueryString["ssd"]; context["scr"] = "14"; context["csy"] = "3"; context["filter"] = Utils.IsInt(cFilterId.SelectedValue)? cFilterId.SelectedValue : "0"; context["isSys"] = "N"; context["conn"] = KEY_sysConnectionString; ddl.AutoCompleteUrl = "AutoComplete.aspx/DdlSuggests"; ddl.DataContext = context; if (ddl != null) { DataView dv = null; if (keyId == string.Empty && ddl.SearchText.StartsWith("**")) {keyId = ddl.SearchText.Substring(2);} try { dv = new DataView((new AdminSystem()).GetDdl(14,"GetDdlScreenId3S139",true,false,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr)); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; } if (dv != null) { if (dv.Table.Columns.Contains("ServerRuleId")) { context["pMKeyColID"] = cAdmServerRule14List.ClientID; context["pMKeyCol"] = "ServerRuleId"; string ss = "(ServerRuleId is null"; if (string.IsNullOrEmpty(cAdmServerRule14List.SelectedValue)) {ss = ss + ")";} else {ss = ss + " OR ServerRuleId = " + cAdmServerRule14List.SelectedValue + ")";} dv.RowFilter = ss; } ddl.DataSource = dv; Session[KEY_dtScreenId24] = dv.Table; try { ddl.SelectByValue(keyId,string.Empty,true); } catch { try { ddl.SelectedIndex = 0; } catch { } } } } } private void SetBeforeCRUD24(DropDownList ddl, string keyId) { DataTable dt = (DataTable)Session[KEY_dtBeforeCRUD24]; DataView dv = dt != null ? dt.DefaultView : null; if (ddl != null) { string ss = string.Empty; ListItem li = null; bool bFirst = false; bool bAll = false; if (ddl.Enabled && ddl.Visible) {bAll = true;} if (dv == null) { bFirst = true; try { dv = new DataView((new AdminSystem()).GetDdl(14,"GetDdlBeforeCRUD3S163",true,bAll,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr)); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; } } if (dv != null) { if (dv.Table.Columns.Contains("ServerRuleId")) { ss = "(ServerRuleId is null"; if (string.IsNullOrEmpty(cAdmServerRule14List.SelectedValue)) {ss = ss + ")";} else {ss = ss + " OR ServerRuleId = " + cAdmServerRule14List.SelectedValue + ")";} } if (!string.IsNullOrEmpty(keyId) && !ddl.Enabled) { ss = ss + (string.IsNullOrEmpty(ss) ? string.Empty : " AND ") + "BeforeCRUD24 is not NULL"; } dv.RowFilter = ss; ddl.DataSource = dv; ddl.DataBind(); li = ddl.Items.FindByValue(keyId); if (li != null) {li.Selected = true;} else if (!bFirst) { try { dv = new DataView((new AdminSystem()).GetDdl(14,"GetDdlBeforeCRUD3S163",true,bAll,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr)); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; } dv.RowFilter = ss; ddl.DataSource = dv; ddl.DataBind(); li = ddl.Items.FindByValue(keyId); if (li != null) {li.Selected = true;} } if (dv.Count <= 1 && keyId != string.Empty) // In case invalid value casued by copy action. { try { dv = new DataView((new AdminSystem()).GetDdl(14,"GetDdlBeforeCRUD3S163",true,true,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr)); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; } dv.RowFilter = ss; ddl.DataSource = dv; ddl.DataBind(); li = ddl.Items.FindByValue(keyId); if (li != null) {li.Selected = true;} } Session[KEY_dtBeforeCRUD24] = dv.Table; } } } private void SetModifiedBy24(DropDownList ddl, string keyId) { DataTable dt = (DataTable)Session[KEY_dtModifiedBy24]; DataView dv = dt != null ? dt.DefaultView : null; if (ddl != null) { string ss = string.Empty; ListItem li = null; bool bFirst = false; bool bAll = false; if (ddl.Enabled && ddl.Visible) {bAll = true;} if (dv == null) { bFirst = true; try { dv = new DataView((new AdminSystem()).GetDdl(14,"GetDdlModifiedBy3S1397",true,bAll,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr)); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; } } if (dv != null) { if (dv.Table.Columns.Contains("ServerRuleId")) { ss = "(ServerRuleId is null"; if (string.IsNullOrEmpty(cAdmServerRule14List.SelectedValue)) {ss = ss + ")";} else {ss = ss + " OR ServerRuleId = " + cAdmServerRule14List.SelectedValue + ")";} } if (!string.IsNullOrEmpty(keyId) && !ddl.Enabled) { ss = ss + (string.IsNullOrEmpty(ss) ? string.Empty : " AND ") + "ModifiedBy24 is not NULL"; } dv.RowFilter = ss; ddl.DataSource = dv; ddl.DataBind(); li = ddl.Items.FindByValue(keyId); if (li != null) {li.Selected = true;} else if (!bFirst) { try { dv = new DataView((new AdminSystem()).GetDdl(14,"GetDdlModifiedBy3S1397",true,bAll,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr)); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; } dv.RowFilter = ss; ddl.DataSource = dv; ddl.DataBind(); li = ddl.Items.FindByValue(keyId); if (li != null) {li.Selected = true;} } if (dv.Count <= 1 && keyId != string.Empty) // In case invalid value casued by copy action. { try { dv = new DataView((new AdminSystem()).GetDdl(14,"GetDdlModifiedBy3S1397",true,true,0,keyId,(string)Session[KEY_sysConnectionString],LcAppPw,string.Empty,base.LImpr,base.LCurr)); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; } dv.RowFilter = ss; ddl.DataSource = dv; ddl.DataBind(); li = ddl.Items.FindByValue(keyId); if (li != null) {li.Selected = true;} } Session[KEY_dtModifiedBy24] = dv.Table; } } } private DataView GetAdmServerRule14List() { DataTable dt = (DataTable)Session[KEY_dtAdmServerRule14List]; if (dt == null) { CheckAuthentication(false); int filterId = 0; string key = string.Empty; if (!string.IsNullOrEmpty(Request.QueryString["key"]) && bUseCri.Value == string.Empty) { key = Request.QueryString["key"].ToString(); } else if (Utils.IsInt(cFilterId.SelectedValue)) { filterId = int.Parse(cFilterId.SelectedValue); } try { try {dt = (new AdminSystem()).GetLis(14,"GetLisAdmServerRule14",true,"Y",0,(string)Session[KEY_sysConnectionString],LcAppPw,filterId,key,string.Empty,GetScrCriteria(),base.LImpr,base.LCurr,UpdCriteria(false));} catch {dt = (new AdminSystem()).GetLis(14,"GetLisAdmServerRule14",true,"N",0,(string)Session[KEY_sysConnectionString],LcAppPw,filterId,key,string.Empty,GetScrCriteria(),base.LImpr,base.LCurr,UpdCriteria(false));} } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return new DataView(); } dt = SetFunctionality(dt); } return (new DataView(dt,"","",System.Data.DataViewRowState.CurrentRows)); } private void PopAdmServerRule14List(object sender, System.EventArgs e, bool bPageLoad, object ID) { DataView dv = GetAdmServerRule14List(); System.Collections.Generic.Dictionary<string, string> context = new System.Collections.Generic.Dictionary<string, string>(); context["method"] = "GetLisAdmServerRule14"; context["mKey"] = "ServerRuleId24"; context["mVal"] = "ServerRuleId24Text"; context["mTip"] = "ServerRuleId24Text"; context["mImg"] = "ServerRuleId24Text"; context["ssd"] = Request.QueryString["ssd"]; context["scr"] = "14"; context["csy"] = "3"; context["filter"] = Utils.IsInt(cFilterId.SelectedValue) && cFilter.Visible ? cFilterId.SelectedValue : "0"; context["isSys"] = "N"; context["conn"] = KEY_sysConnectionString; cAdmServerRule14List.AutoCompleteUrl = "AutoComplete.aspx/LisSuggests"; cAdmServerRule14List.DataContext = context; if (dv.Table == null) return; cAdmServerRule14List.DataSource = dv; cAdmServerRule14List.Visible = true; if (cAdmServerRule14List.Items.Count <= 0) {cAdmServerRule14List.Visible = false; cAdmServerRule14List_SelectedIndexChanged(sender,e);} else { if (bPageLoad && !string.IsNullOrEmpty(Request.QueryString["key"]) && bUseCri.Value == string.Empty) { try {cAdmServerRule14List.SelectByValue(Request.QueryString["key"],string.Empty,true);} catch {cAdmServerRule14List.Items[0].Selected = true; cAdmServerRule14List_SelectedIndexChanged(sender, e);} cScreenSearch.Visible = false; cSystem.Visible = false; cEditButton.Visible = true; cSaveCloseButton.Visible = cSaveButton.Visible; } else { if (ID != null) {if (!cAdmServerRule14List.SelectByValue(ID,string.Empty,true)) {ID = null;}} if (ID == null) { cAdmServerRule14List_SelectedIndexChanged(sender, e); } } } } private void SetColumnAuthority() { DataTable dtAuth = GetAuthCol(); DataTable dtLabel = GetLabel(); cTabFolder.CssClass = "TabFolder rmvSpace"; foreach (DataRow dr in dtAuth.Rows) {if (dr["MasterTable"].ToString() == "Y" && dr["ColVisible"].ToString() == "Y") {cTabFolder.CssClass = "TabFolder"; break;}} if (dtAuth != null && dtLabel != null) { base.SetFoldBehavior(cServerRuleId24, dtAuth.Rows[0], cServerRuleId24P1, cServerRuleId24Label, cServerRuleId24P2, null, dtLabel.Rows[0], null, null, null); base.SetFoldBehavior(cRuleName24, dtAuth.Rows[1], cRuleName24P1, cRuleName24Label, cRuleName24P2, null, dtLabel.Rows[1], cRFVRuleName24, null, null); base.SetFoldBehavior(cRuleDescription24, dtAuth.Rows[2], cRuleDescription24P1, cRuleDescription24Label, cRuleDescription24P2, cRuleDescription24E, null, dtLabel.Rows[2], null, null, null); cRuleDescription24E.Attributes["label_id"] = cRuleDescription24Label.ClientID; cRuleDescription24E.Attributes["target_id"] = cRuleDescription24.ClientID; base.SetFoldBehavior(cRuleTypeId24, dtAuth.Rows[3], cRuleTypeId24P1, cRuleTypeId24Label, cRuleTypeId24P2, null, dtLabel.Rows[3], cRFVRuleTypeId24, null, null); base.SetFoldBehavior(cScreenId24, dtAuth.Rows[4], cScreenId24P1, cScreenId24Label, cScreenId24P2, null, dtLabel.Rows[4], null, null, null); SetScreenId24(cScreenId24,string.Empty); base.SetFoldBehavior(cRuleOrder24, dtAuth.Rows[5], cRuleOrder24P1, cRuleOrder24Label, cRuleOrder24P2, null, dtLabel.Rows[5], cRFVRuleOrder24, null, null); base.SetFoldBehavior(cProcedureName24, dtAuth.Rows[6], cProcedureName24P1, cProcedureName24Label, cProcedureName24P2, null, dtLabel.Rows[6], cRFVProcedureName24, null, null); base.SetFoldBehavior(cParameterNames24, dtAuth.Rows[7], cParameterNames24P1, cParameterNames24Label, cParameterNames24P2, null, dtLabel.Rows[7], null, null, null); base.SetFoldBehavior(cParameterTypes24, dtAuth.Rows[8], cParameterTypes24P1, cParameterTypes24Label, cParameterTypes24P2, null, dtLabel.Rows[8], null, null, null); base.SetFoldBehavior(cCallingParams24, dtAuth.Rows[9], cCallingParams24P1, cCallingParams24Label, cCallingParams24P2, null, dtLabel.Rows[9], null, null, null); base.SetFoldBehavior(cMasterTable24, dtAuth.Rows[10], cMasterTable24P1, cMasterTable24Label, cMasterTable24P2, null, dtLabel.Rows[10], null, null, null); base.SetFoldBehavior(cOnAdd24, dtAuth.Rows[11], cOnAdd24P1, cOnAdd24Label, cOnAdd24P2, null, dtLabel.Rows[11], null, null, null); base.SetFoldBehavior(cOnUpd24, dtAuth.Rows[12], cOnUpd24P1, cOnUpd24Label, cOnUpd24P2, null, dtLabel.Rows[12], null, null, null); base.SetFoldBehavior(cOnDel24, dtAuth.Rows[13], cOnDel24P1, cOnDel24Label, cOnDel24P2, null, dtLabel.Rows[13], null, null, null); base.SetFoldBehavior(cBeforeCRUD24, dtAuth.Rows[14], cBeforeCRUD24P1, cBeforeCRUD24Label, cBeforeCRUD24P2, null, dtLabel.Rows[14], cRFVBeforeCRUD24, null, null); base.SetFoldBehavior(cCrudTypeDesc1289, dtAuth.Rows[15], null, null, null, dtLabel.Rows[15], null, null, null); base.SetFoldBehavior(cRuleCode24, dtAuth.Rows[16], cRuleCode24P1, cRuleCode24Label, cRuleCode24P2, cRuleCode24E, null, dtLabel.Rows[16], null, null, null); cRuleCode24E.Attributes["label_id"] = cRuleCode24Label.ClientID; cRuleCode24E.Attributes["target_id"] = cRuleCode24.ClientID; base.SetFoldBehavior(cSyncByDb, dtAuth.Rows[17], cSyncByDbP1, cSyncByDbLabel, cSyncByDbP2, null, dtLabel.Rows[17], null, null, null); base.SetFoldBehavior(cSyncToDb, dtAuth.Rows[18], cSyncToDbP1, cSyncToDbLabel, cSyncToDbP2, null, dtLabel.Rows[18], null, null, null); base.SetFoldBehavior(cModifiedBy24, dtAuth.Rows[19], cModifiedBy24P1, cModifiedBy24Label, cModifiedBy24P2, null, dtLabel.Rows[19], null, null, null); base.SetFoldBehavior(cModifiedOn24, dtAuth.Rows[20], cModifiedOn24P1, cModifiedOn24Label, cModifiedOn24P2, null, dtLabel.Rows[20], null, null, null); base.SetFoldBehavior(cLastGenDt24, dtAuth.Rows[21], cLastGenDt24P1, cLastGenDt24Label, cLastGenDt24P2, null, dtLabel.Rows[21], null, null, null); } if ((cRuleName24.Attributes["OnChange"] == null || cRuleName24.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cRuleName24.Visible && !cRuleName24.ReadOnly) {cRuleName24.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";} if ((cRuleDescription24.Attributes["OnChange"] == null || cRuleDescription24.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cRuleDescription24.Visible && !cRuleDescription24.ReadOnly) {cRuleDescription24.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";} if ((cRuleTypeId24.Attributes["OnChange"] == null || cRuleTypeId24.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cRuleTypeId24.Visible && cRuleTypeId24.Enabled) {cRuleTypeId24.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";} if ((cScreenId24.Attributes["OnChange"] == null || cScreenId24.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cScreenId24.Visible && cScreenId24.Enabled) {cScreenId24.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";} if (cScreenId24Search.Attributes["OnClick"] == null || cScreenId24Search.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cScreenId24Search.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";} if ((cRuleOrder24.Attributes["OnChange"] == null || cRuleOrder24.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cRuleOrder24.Visible && !cRuleOrder24.ReadOnly) {cRuleOrder24.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";} if ((cProcedureName24.Attributes["OnChange"] == null || cProcedureName24.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cProcedureName24.Visible && !cProcedureName24.ReadOnly) {cProcedureName24.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";} if ((cParameterNames24.Attributes["OnChange"] == null || cParameterNames24.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cParameterNames24.Visible && !cParameterNames24.ReadOnly) {cParameterNames24.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";} if ((cParameterTypes24.Attributes["OnChange"] == null || cParameterTypes24.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cParameterTypes24.Visible && !cParameterTypes24.ReadOnly) {cParameterTypes24.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";} if ((cCallingParams24.Attributes["OnChange"] == null || cCallingParams24.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cCallingParams24.Visible && !cCallingParams24.ReadOnly) {cCallingParams24.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";} if (cCallingParams24Search.Attributes["OnClick"] == null || cCallingParams24Search.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cCallingParams24Search.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";} if ((cMasterTable24.Attributes["OnClick"] == null || cMasterTable24.Attributes["OnClick"].IndexOf("ChkPgDirty") < 0) && cMasterTable24.Visible && cMasterTable24.Enabled) {cMasterTable24.Attributes["OnClick"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty(); this.focus();";} if ((cOnAdd24.Attributes["OnClick"] == null || cOnAdd24.Attributes["OnClick"].IndexOf("ChkPgDirty") < 0) && cOnAdd24.Visible && cOnAdd24.Enabled) {cOnAdd24.Attributes["OnClick"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty(); this.focus();";} if ((cOnUpd24.Attributes["OnClick"] == null || cOnUpd24.Attributes["OnClick"].IndexOf("ChkPgDirty") < 0) && cOnUpd24.Visible && cOnUpd24.Enabled) {cOnUpd24.Attributes["OnClick"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty(); this.focus();";} if ((cOnDel24.Attributes["OnClick"] == null || cOnDel24.Attributes["OnClick"].IndexOf("ChkPgDirty") < 0) && cOnDel24.Visible && cOnDel24.Enabled) {cOnDel24.Attributes["OnClick"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty(); this.focus();";} if ((cBeforeCRUD24.Attributes["OnChange"] == null || cBeforeCRUD24.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cBeforeCRUD24.Visible && cBeforeCRUD24.Enabled) {cBeforeCRUD24.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();document.getElementById('" + bConfirm.ClientID + "').value='N';";} if ((cCrudTypeDesc1289.Attributes["OnChange"] == null || cCrudTypeDesc1289.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cCrudTypeDesc1289.Visible && cCrudTypeDesc1289.Enabled) {cCrudTypeDesc1289.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";} if ((cRuleCode24.Attributes["OnChange"] == null || cRuleCode24.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cRuleCode24.Visible && !cRuleCode24.ReadOnly) {cRuleCode24.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";} if ((cSyncByDb.Attributes["OnChange"] == null || cSyncByDb.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cSyncByDb.Visible && cSyncByDb.Enabled) {cSyncByDb.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();document.getElementById('" + bConfirm.ClientID + "').value='N';";} if ((cSyncToDb.Attributes["OnChange"] == null || cSyncToDb.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cSyncToDb.Visible && cSyncToDb.Enabled) {cSyncToDb.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();document.getElementById('" + bConfirm.ClientID + "').value='N';";} if ((cModifiedBy24.Attributes["OnChange"] == null || cModifiedBy24.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cModifiedBy24.Visible && cModifiedBy24.Enabled) {cModifiedBy24.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";} if ((cModifiedOn24.Attributes["OnChange"] == null || cModifiedOn24.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cModifiedOn24.Visible && !cModifiedOn24.ReadOnly) {cModifiedOn24.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";} if ((cLastGenDt24.Attributes["OnChange"] == null || cLastGenDt24.Attributes["OnChange"].IndexOf("ChkPgDirty") < 0) && cLastGenDt24.Visible && !cLastGenDt24.ReadOnly) {cLastGenDt24.Attributes["OnChange"] += "document.getElementById('" + bPgDirty.ClientID + "').value='Y'; ChkPgDirty();";} } private DataTable SetFunctionality(DataTable dt) { DataTable dtAuthRow = GetAuthRow(); if (dtAuthRow != null) { DataRow dr = dtAuthRow.Rows[0]; if (dr["AllowDel"].ToString() == "N" || (Request.QueryString["enb"] != null && Request.QueryString["enb"] == "N")) { if ((bool)Session[KEY_bDeleteVisible]) {cDeleteButton.Visible = false; Session[KEY_bDeleteVisible] = false;} } else if ((bool)Session[KEY_bDeleteVisible]) {cDeleteButton.Visible = true; cDeleteButton.Enabled = true;} if ((dr["AllowUpd"].ToString() == "N" && dr["AllowAdd"].ToString() == "N") || (Request.QueryString["enb"] != null && Request.QueryString["enb"] == "N")) { cUndoAllButton.Visible = false; cSaveButton.Visible = false; cSaveCloseButton.Visible = false; } else { if ((bool)Session[KEY_bUndoAllVisible]) {cUndoAllButton.Visible = true; cUndoAllButton.Enabled = true;} if ((bool)Session[KEY_bUpdateVisible]) {cSaveButton.Visible = true; cSaveButton.Enabled = true;} } if (dr["AllowAdd"].ToString() == "N" || (Request.QueryString["enb"] != null && Request.QueryString["enb"] == "N")) { cNewButton.Visible = false; cNewSaveButton.Visible = false; cCopyButton.Visible = false; cCopySaveButton.Visible = false; if (dt != null && dt.Rows.Count > 0) {dt.Rows[0].Delete();} } else { if ((bool)Session[KEY_bNewVisible]) {cNewButton.Visible = true; cNewButton.Enabled = true;} else {cNewButton.Visible = false;} if ((bool)Session[KEY_bNewSaveVisible]) {cNewSaveButton.Visible = true; cNewSaveButton.Enabled = true;} else {cNewSaveButton.Visible = false;} if ((bool)Session[KEY_bCopyVisible]) {cCopyButton.Visible = true; cCopyButton.Enabled = true;} else {cCopyButton.Visible = false;} if ((bool)Session[KEY_bCopySaveVisible]) {cCopySaveButton.Visible = true; cCopySaveButton.Enabled = true;} else {cCopySaveButton.Visible = false;} } } return dt; } protected void cFilterId_SelectedIndexChanged(object sender, System.EventArgs e) { cNewButton_Click(sender, new EventArgs()); } protected void cSystemId_SelectedIndexChanged(object sender, System.EventArgs e) { base.LCurr.DbId = byte.Parse(cSystemId.SelectedValue); DataTable dtSystems = (DataTable)Session[KEY_dtSystems]; Session[KEY_sysConnectionString] = Config.GetConnStr(dtSystems.Rows[cSystemId.SelectedIndex]["dbAppProvider"].ToString(), dtSystems.Rows[cSystemId.SelectedIndex]["ServerName"].ToString(), dtSystems.Rows[cSystemId.SelectedIndex]["dbDesDatabase"].ToString(), "", dtSystems.Rows[cSystemId.SelectedIndex]["dbAppUserId"].ToString()); Session.Remove(KEY_dtRuleTypeId24); Session.Remove(KEY_dtScreenId24); Session.Remove(KEY_dtBeforeCRUD24); Session.Remove(KEY_dtModifiedBy24); GetCriteria(GetScrCriteria()); cFilterId_SelectedIndexChanged(sender, e); cScreenId24Search_Script(); cCallingParams24Search_Script(); } private void ClearMaster(object sender, System.EventArgs e) { DataTable dt = GetAuthCol(); if (dt.Rows[1]["ColVisible"].ToString() == "Y" && dt.Rows[1]["ColReadOnly"].ToString() != "Y") {cRuleName24.Text = string.Empty;} if (dt.Rows[2]["ColVisible"].ToString() == "Y" && dt.Rows[2]["ColReadOnly"].ToString() != "Y") {cRuleDescription24.Text = string.Empty;} if (dt.Rows[3]["ColVisible"].ToString() == "Y" && dt.Rows[3]["ColReadOnly"].ToString() != "Y") {SetRuleTypeId24(cRuleTypeId24,string.Empty);} if (dt.Rows[4]["ColVisible"].ToString() == "Y" && dt.Rows[4]["ColReadOnly"].ToString() != "Y") {cScreenId24.ClearSearch();} if (dt.Rows[5]["ColVisible"].ToString() == "Y" && dt.Rows[5]["ColReadOnly"].ToString() != "Y") {cRuleOrder24.Text = string.Empty;} if (dt.Rows[6]["ColVisible"].ToString() == "Y" && dt.Rows[6]["ColReadOnly"].ToString() != "Y") {cProcedureName24.Text = string.Empty;} if (dt.Rows[7]["ColVisible"].ToString() == "Y" && dt.Rows[7]["ColReadOnly"].ToString() != "Y") {cParameterNames24.Text = string.Empty;} if (dt.Rows[8]["ColVisible"].ToString() == "Y" && dt.Rows[8]["ColReadOnly"].ToString() != "Y") {cParameterTypes24.Text = string.Empty;} if (dt.Rows[9]["ColVisible"].ToString() == "Y" && dt.Rows[9]["ColReadOnly"].ToString() != "Y") {cCallingParams24.Text = string.Empty;} if (dt.Rows[10]["ColVisible"].ToString() == "Y" && dt.Rows[10]["ColReadOnly"].ToString() != "Y") {cMasterTable24.Checked = base.GetBool("N");} if (dt.Rows[11]["ColVisible"].ToString() == "Y" && dt.Rows[11]["ColReadOnly"].ToString() != "Y") {cOnAdd24.Checked = base.GetBool("N");} if (dt.Rows[12]["ColVisible"].ToString() == "Y" && dt.Rows[12]["ColReadOnly"].ToString() != "Y") {cOnUpd24.Checked = base.GetBool("N");} if (dt.Rows[13]["ColVisible"].ToString() == "Y" && dt.Rows[13]["ColReadOnly"].ToString() != "Y") {cOnDel24.Checked = base.GetBool("N");} if (dt.Rows[14]["ColVisible"].ToString() == "Y" && dt.Rows[14]["ColReadOnly"].ToString() != "Y") {SetBeforeCRUD24(cBeforeCRUD24,string.Empty); cBeforeCRUD24_SelectedIndexChanged(cBeforeCRUD24, new EventArgs());} if (dt.Rows[16]["ColVisible"].ToString() == "Y" && dt.Rows[16]["ColReadOnly"].ToString() != "Y") {cRuleCode24.Text = string.Empty;} if (dt.Rows[17]["ColVisible"].ToString() == "Y" && dt.Rows[17]["ColReadOnly"].ToString() != "Y") {cSyncByDb.ImageUrl = "~/images/custom/adm/SyncByDb.gif"; } if (dt.Rows[18]["ColVisible"].ToString() == "Y" && dt.Rows[18]["ColReadOnly"].ToString() != "Y") {cSyncToDb.ImageUrl = "~/images/custom/adm/SyncToDb.gif"; } if (dt.Rows[19]["ColVisible"].ToString() == "Y" && dt.Rows[19]["ColReadOnly"].ToString() != "Y") {SetModifiedBy24(cModifiedBy24,string.Empty);} if (dt.Rows[20]["ColVisible"].ToString() == "Y" && dt.Rows[20]["ColReadOnly"].ToString() != "Y") {cModifiedOn24.Text = string.Empty;} if (dt.Rows[21]["ColVisible"].ToString() == "Y" && dt.Rows[21]["ColReadOnly"].ToString() != "Y") {cLastGenDt24.Text = string.Empty;} // *** Default Value (Folder) Web Rule starts here *** // } private void InitMaster(object sender, System.EventArgs e) { cServerRuleId24.Text = string.Empty; cRuleName24.Text = string.Empty; cRuleDescription24.Text = string.Empty; SetRuleTypeId24(cRuleTypeId24,string.Empty); cScreenId24.ClearSearch(); cRuleOrder24.Text = string.Empty; cProcedureName24.Text = string.Empty; cParameterNames24.Text = string.Empty; cParameterTypes24.Text = string.Empty; cCallingParams24.Text = string.Empty; cMasterTable24.Checked = base.GetBool("N"); cOnAdd24.Checked = base.GetBool("N"); cOnUpd24.Checked = base.GetBool("N"); cOnDel24.Checked = base.GetBool("N"); SetBeforeCRUD24(cBeforeCRUD24,string.Empty); cBeforeCRUD24_SelectedIndexChanged(cBeforeCRUD24, new EventArgs()); cRuleCode24.Text = string.Empty; cSyncByDb.ImageUrl = "~/images/custom/adm/SyncByDb.gif"; cSyncToDb.ImageUrl = "~/images/custom/adm/SyncToDb.gif"; SetModifiedBy24(cModifiedBy24,string.Empty); cModifiedOn24.Text = string.Empty; cLastGenDt24.Text = string.Empty; // *** Default Value (Folder) Web Rule starts here *** // } protected void cAdmServerRule14List_TextChanged(object sender, System.EventArgs e) { ScriptManager.GetCurrent(Parent.Page).SetFocus(((RoboCoder.WebControls.ComboBox)sender).FocusID); } protected void cAdmServerRule14List_DDFindClick(object sender, System.EventArgs e) { ScriptManager.GetCurrent(Parent.Page).SetFocus(((RoboCoder.WebControls.ComboBox)sender).FocusID); } protected void cAdmServerRule14List_SelectedIndexChanged(object sender, System.EventArgs e) { InitMaster(sender, e); // Do this first to enable defaults for non-database columns. DataTable dt = null; try { dt = (new AdminSystem()).GetMstById("GetAdmServerRule14ById",cAdmServerRule14List.SelectedValue,(string)Session[KEY_sysConnectionString],LcAppPw); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; } if (dt != null) { CheckAuthentication(false); if (dt.Rows.Count > 0) { cAdmServerRule14List.SetDdVisible(); DataRow dr = dt.Rows[0]; try {cServerRuleId24.Text = RO.Common3.Utils.fmNumeric("0",dr["ServerRuleId24"].ToString(),base.LUser.Culture);} catch {cServerRuleId24.Text = string.Empty;} try {cRuleName24.Text = dr["RuleName24"].ToString();} catch {cRuleName24.Text = string.Empty;} try {cRuleDescription24.Text = dr["RuleDescription24"].ToString();} catch {cRuleDescription24.Text = string.Empty;} SetRuleTypeId24(cRuleTypeId24,dr["RuleTypeId24"].ToString()); SetScreenId24(cScreenId24,dr["ScreenId24"].ToString()); cScreenId24Search_Script(); try {cRuleOrder24.Text = RO.Common3.Utils.fmNumeric("0",dr["RuleOrder24"].ToString(),base.LUser.Culture);} catch {cRuleOrder24.Text = string.Empty;} try {cProcedureName24.Text = dr["ProcedureName24"].ToString();} catch {cProcedureName24.Text = string.Empty;} try {cParameterNames24.Text = dr["ParameterNames24"].ToString();} catch {cParameterNames24.Text = string.Empty;} try {cParameterTypes24.Text = dr["ParameterTypes24"].ToString();} catch {cParameterTypes24.Text = string.Empty;} try {cCallingParams24.Text = dr["CallingParams24"].ToString();} catch {cCallingParams24.Text = string.Empty;} cCallingParams24Search_Script(); try {cMasterTable24.Checked = base.GetBool(dr["MasterTable24"].ToString());} catch {cMasterTable24.Checked = false;} try {cOnAdd24.Checked = base.GetBool(dr["OnAdd24"].ToString());} catch {cOnAdd24.Checked = false;} try {cOnUpd24.Checked = base.GetBool(dr["OnUpd24"].ToString());} catch {cOnUpd24.Checked = false;} try {cOnDel24.Checked = base.GetBool(dr["OnDel24"].ToString());} catch {cOnDel24.Checked = false;} SetBeforeCRUD24(cBeforeCRUD24,dr["BeforeCRUD24"].ToString()); cBeforeCRUD24_SelectedIndexChanged(cBeforeCRUD24, new EventArgs()); try {cRuleCode24.Text = dr["RuleCode24"].ToString();} catch {cRuleCode24.Text = string.Empty;} cSyncByDb.ImageUrl = "~/images/custom/adm/SyncByDb.gif"; cSyncToDb.ImageUrl = "~/images/custom/adm/SyncToDb.gif"; SetModifiedBy24(cModifiedBy24,dr["ModifiedBy24"].ToString()); try {cModifiedOn24.Text = RO.Common3.Utils.fmShortDateTimeUTC(dr["ModifiedOn24"].ToString(),base.LUser.Culture,CurrTimeZoneInfo());} catch {cModifiedOn24.Text = string.Empty;} try {cLastGenDt24.Text = dr["LastGenDt24"].ToString();} catch {cLastGenDt24.Text = string.Empty;} } } cButPanel.DataBind(); ScriptManager.GetCurrent(Parent.Page).SetFocus(cAdmServerRule14List.FocusID); ShowDirty(false); PanelTop.Update(); // *** List Selection (End of) Web Rule starts here *** // } protected void cScreenId24_TextChanged(object sender, System.EventArgs e) { ScriptManager.GetCurrent(Parent.Page).SetFocus(((RoboCoder.WebControls.ComboBox)sender).FocusID); } protected void cScreenId24_DDFindClick(object sender, System.EventArgs e) { ScriptManager.GetCurrent(Parent.Page).SetFocus(((RoboCoder.WebControls.ComboBox)sender).FocusID); } protected void cScreenId24_SelectedIndexChanged(object sender, System.EventArgs e) { // *** On Change/ On Click Web Rule starts here *** // EnableValidators(true); // Do not remove; Need to reenable after postback, especially in the grid. TextBox pwd = null; if (cScreenId24.Items.Count > 0 && cScreenId24.DataSource != null) { DataView dv = (DataView) cScreenId24.DataSource; dv.RowFilter = string.Empty; DataRowView dr = cScreenId24.DataSetIndex >= 0 && cScreenId24.DataSetIndex < dv.Count ? dv[cScreenId24.DataSetIndex] : dv[0]; cScreenId24Search_Script(); if (pwd != null) {ScriptManager.GetCurrent(Parent.Page).SetFocus(pwd.ClientID);} else {ScriptManager.GetCurrent(Parent.Page).SetFocus(SenderFocusId(sender));} } } protected void cCallingParams24_TextChanged(object sender, System.EventArgs e) { // *** On Change/ On Click Web Rule starts here *** // EnableValidators(true); // Do not remove; Need to reenable after postback, especially in the grid. if (cCallingParams24.Text != string.Empty) { cCallingParams24Search_Script(); } } protected void cBeforeCRUD24_SelectedIndexChanged(object sender, System.EventArgs e) { //WebRule: Hide fields, change order, etc. if (cBeforeCRUD24.SelectedValue == "C") { cMasterTable24.Checked = true; cMasterTable24P1.Visible = false; cMasterTable24P2.Visible = false; } else { cMasterTable24P1.Visible = true; cMasterTable24P2.Visible = true; } // *** WebRule End *** // EnableValidators(true); // Do not remove; Need to reenable after postback, especially in the grid. TextBox pwd = null; if (cBeforeCRUD24.Items.Count > 0 && Session[KEY_dtBeforeCRUD24] != null) { DataView dv = ((DataTable)Session[KEY_dtBeforeCRUD24]).DefaultView; dv.RowFilter = string.Empty; DataRowView dr = cBeforeCRUD24.SelectedIndex >= 0 && cBeforeCRUD24.SelectedIndex < dv.Count ? dv[cBeforeCRUD24.SelectedIndex] : dv[0]; cCrudTypeDesc1289.Text = dr["CrudTypeDesc1289"].ToString(); if (pwd != null) {ScriptManager.GetCurrent(Parent.Page).SetFocus(pwd.ClientID);} else {ScriptManager.GetCurrent(Parent.Page).SetFocus(SenderFocusId(sender));} } } protected void cSyncByDb_Click(object sender, System.Web.UI.ImageClickEventArgs e) { //WebRule: Obtain sp from the physical database string ss = string.Empty; if (Config.AppNameSpace != "RO" && base.LCurr.DbId == 3) { bErrNow.Value = "Y"; PreMsgPopup("Please do not manipulate this administration stored procedure."); } else if (cServerRuleId24.Text == string.Empty) { bErrNow.Value = "Y"; PreMsgPopup("Please add this server rule first then try again."); } else { WebRule wr = new WebRule(); try { ss = wr.WrGetSvrRule(cServerRuleId24.Text, base.LCurr.DbId, Session[KEY_sysConnectionString].ToString(), LcAppPw); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; } if (ss != string.Empty) { cRuleCode24.Text = ss; try { ss = wr.WrUpdSvrRule(cServerRuleId24.Text, Session[KEY_sysConnectionString].ToString(), LcAppPw); } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; } cLastGenDt24.Text = ss; cSaveButton_Click(sender, new EventArgs()); } } // *** WebRule End *** // EnableValidators(true); // Do not remove; Need to reenable after postback, especially in the grid. } protected void cSyncToDb_Click(object sender, System.Web.UI.ImageClickEventArgs e) { //WebRule: Synchronize to the physical database string err = string.Empty; if (Config.AppNameSpace != "RO" && base.LCurr.DbId == 3) { bErrNow.Value = "Y"; PreMsgPopup("Please do not synchronize this administration stored procedure to physical database."); } else if (cServerRuleId24.Text == string.Empty) { bErrNow.Value = "Y"; PreMsgPopup("Please add this server rule first then try again."); } else if (cRuleCode24.Text.Trim() == string.Empty) { bErrNow.Value = "Y"; PreMsgPopup("Please add the stored procedure above and try again."); } else if (LImpr.UsrGroups == "1") { bInfoNow.Value = "Y"; PreMsgPopup("This function is temporary blocked from your access. Please contact administrator if you have any quesitons."); } else { WebRule wr = new WebRule(); DataView dv = new DataView(wr.WrGetSvrRuleSys(cScreenId24.SelectedValue, base.LCurr.DbId, Session[KEY_sysConnectionString].ToString(), LcAppPw)); foreach (DataRowView drv in dv) { err = wr.WrSyncProc(cProcedureName24.Text, cRuleCode24.Text, Config.GetConnStr(drv["dbProvider"].ToString(), drv["dbServer"].ToString(), drv["dbDatabase"].ToString(), "", drv["dbUserId"].ToString()), LcAppPw); if (err != string.Empty) { break; } } if (err != string.Empty) { bErrNow.Value = "Y"; PreMsgPopup(err); } else { cLastGenDt24.Text = wr.WrUpdSvrRule(cServerRuleId24.Text, Session[KEY_sysConnectionString].ToString(), LcAppPw); try { SaveDb(sender, new EventArgs()); bInfoNow.Value = "Y"; PreMsgPopup("Stored procedure synchronized to the physical database successfully."); } catch (Exception er) { bErrNow.Value = "Y"; PreMsgPopup(er.Message); return; } } } // *** WebRule End *** // EnableValidators(true); // Do not remove; Need to reenable after postback, especially in the grid. } public void cNewSaveButton_Click(object sender, System.EventArgs e) { // *** System Button Click (Before) Web Rule starts here *** // try { string msg = SaveDb(sender, new EventArgs()); cNewButton_Click(sender, new EventArgs()); if (msg != string.Empty && Config.PromptMsg) { bInfoNow.Value = "Y"; PreMsgPopup(msg); } } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; } // *** System Button Click (After) Web Rule starts here *** // } public void cNewButton_Click(object sender, System.EventArgs e) { // *** System Button Click (Before) Web Rule starts here *** // cAdmServerRule14List.ClearSearch(); Session.Remove(KEY_dtAdmServerRule14List); PopAdmServerRule14List(sender, e, false, null); // *** System Button Click (After) Web Rule starts here *** // } public void cClearButton_Click(object sender, System.EventArgs e) { // *** System Button Click (Before) Web Rule starts here *** // ClearMaster(sender, e); // *** System Button Click (After) Web Rule starts here *** // } public void cCopyButton_Click(object sender, System.EventArgs e) { // *** System Button Click (Before) Web Rule starts here *** // cServerRuleId24.Text = string.Empty; cAdmServerRule14List.ClearSearch(); Session.Remove(KEY_dtAdmServerRule14List); ShowDirty(true); // *** System Button Click (After) Web Rule starts here *** // } public void cCopySaveButton_Click(object sender, System.EventArgs e) { // *** System Button Click (Before) Web Rule starts here *** // try { string msg = SaveDb(sender, new EventArgs()); cCopyButton_Click(sender, new EventArgs()); if (msg != string.Empty && Config.PromptMsg) { bInfoNow.Value = "Y"; PreMsgPopup(msg); } } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; } // *** System Button Click (After) Web Rule starts here *** // } public void cUndoAllButton_Click(object sender, System.EventArgs e) { // *** System Button Click (Before) Web Rule starts here *** // if (cServerRuleId24.Text == string.Empty) { cClearButton_Click(sender, new EventArgs()); ShowDirty(false); PanelTop.Update();} else { PopAdmServerRule14List(sender, e, false, cServerRuleId24.Text); } // *** System Button Click (After) Web Rule starts here *** // } public void cPreviewButton_Click(object sender, System.EventArgs e) { // *** System Button Click (Before) Web Rule starts here *** // // *** System Button Click (After) Web Rule starts here *** // } public void cEditButton_Click(object sender, System.EventArgs e) { // *** System Button Click (Before) Web Rule starts here *** // cScreenSearch.Visible = true; cSystem.Visible = true; bUseCri.Value = "Y"; GetCriteria(GetScrCriteria()); Session.Remove(KEY_dtAdmServerRule14List); PopAdmServerRule14List(sender, e, false, null); cEditButton.Visible = false; // *** System Button Click (After) Web Rule starts here *** // } public void cSaveCloseButton_Click(object sender, System.EventArgs e) { // *** System Button Click (Before) Web Rule starts here *** // try { string msg = SaveDb(sender, new EventArgs()); if (msg != string.Empty) { ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "closeDlg", @"<script type='text/javascript'>window.parent.closeParentDlg();</script>", false); } } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; } // *** System Button Click (After) Web Rule starts here *** // } private string SaveDb(object sender, System.EventArgs e) { string rtn = string.Empty; // *** System Button Click (Before) Web Rule starts here *** // string pid = string.Empty; if (ValidPage()) { AdmServerRule14 ds = PrepAdmServerRuleData(null,cServerRuleId24.Text == string.Empty); if (string.IsNullOrEmpty(cAdmServerRule14List.SelectedValue)) // Add { if (ds != null) { pid = (new AdminSystem()).AddData(14,false,base.LUser,base.LImpr,base.LCurr,ds,(string)Session[KEY_sysConnectionString],LcAppPw,base.CPrj,base.CSrc); } if (!string.IsNullOrEmpty(pid)) { cAdmServerRule14List.ClearSearch(); Session.Remove(KEY_dtAdmServerRule14List); ShowDirty(false); bUseCri.Value = "Y"; PopAdmServerRule14List(sender, e, false, pid); rtn = GetScreenHlp().Rows[0]["AddMsg"].ToString(); } } else { bool bValid7 = false; if (ds != null && (new AdminSystem()).UpdData(14,false,base.LUser,base.LImpr,base.LCurr,ds,(string)Session[KEY_sysConnectionString],LcAppPw,base.CPrj,base.CSrc)) {bValid7 = true;} if (bValid7) { cAdmServerRule14List.ClearSearch(); Session.Remove(KEY_dtAdmServerRule14List); ShowDirty(false); PopAdmServerRule14List(sender, e, false, ds.Tables["AdmServerRule"].Rows[0]["ServerRuleId24"]); rtn = GetScreenHlp().Rows[0]["UpdMsg"].ToString(); } } } // *** System Button Click (After) Web Rule starts here *** // return rtn; } public void cSaveButton_Click(object sender, System.EventArgs e) { try { string msg = SaveDb(sender, e); if (msg != string.Empty && Config.PromptMsg) { bInfoNow.Value = "Y"; PreMsgPopup(msg); } } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; } } public void cDeleteButton_Click(object sender, System.EventArgs e) { // *** System Button Click (Before) Web Rule starts here *** // if (cServerRuleId24.Text != string.Empty) { AdmServerRule14 ds = PrepAdmServerRuleData(null,false); try { if (ds != null && (new AdminSystem()).DelData(14,false,base.LUser,base.LImpr,base.LCurr,ds,(string)Session[KEY_sysConnectionString],LcAppPw,base.CPrj,base.CSrc)) { cAdmServerRule14List.ClearSearch(); Session.Remove(KEY_dtAdmServerRule14List); ShowDirty(false); PopAdmServerRule14List(sender, e, false, null); if (Config.PromptMsg) {bInfoNow.Value = "Y"; PreMsgPopup(GetScreenHlp().Rows[0]["DelMsg"].ToString());} } } catch (Exception err) { bErrNow.Value = "Y"; PreMsgPopup(err.Message); return; } } // *** System Button Click (After) Web Rule starts here *** // } private AdmServerRule14 PrepAdmServerRuleData(DataView dv, bool bAdd) { AdmServerRule14 ds = new AdmServerRule14(); DataRow dr = ds.Tables["AdmServerRule"].NewRow(); DataRow drType = ds.Tables["AdmServerRule"].NewRow(); DataRow drDisp = ds.Tables["AdmServerRule"].NewRow(); if (bAdd) { dr["ServerRuleId24"] = string.Empty; } else { dr["ServerRuleId24"] = cServerRuleId24.Text; } drType["ServerRuleId24"] = "Numeric"; drDisp["ServerRuleId24"] = "TextBox"; try {dr["RuleName24"] = cRuleName24.Text.Trim();} catch {} drType["RuleName24"] = "VarWChar"; drDisp["RuleName24"] = "TextBox"; try {dr["RuleDescription24"] = cRuleDescription24.Text;} catch {} drType["RuleDescription24"] = "VarWChar"; drDisp["RuleDescription24"] = "MultiLine"; try {dr["RuleTypeId24"] = cRuleTypeId24.SelectedValue;} catch {} drType["RuleTypeId24"] = "Numeric"; drDisp["RuleTypeId24"] = "DropDownList"; try {dr["ScreenId24"] = cScreenId24.SelectedValue;} catch {} drType["ScreenId24"] = "Numeric"; drDisp["ScreenId24"] = "AutoComplete"; try {dr["RuleOrder24"] = cRuleOrder24.Text.Trim();} catch {} drType["RuleOrder24"] = "Numeric"; drDisp["RuleOrder24"] = "TextBox"; try {dr["ProcedureName24"] = cProcedureName24.Text.Trim();} catch {} drType["ProcedureName24"] = "VarChar"; drDisp["ProcedureName24"] = "TextBox"; try {dr["ParameterNames24"] = cParameterNames24.Text.Trim();} catch {} drType["ParameterNames24"] = "VarChar"; drDisp["ParameterNames24"] = "TextBox"; try {dr["ParameterTypes24"] = cParameterTypes24.Text.Trim();} catch {} drType["ParameterTypes24"] = "VarChar"; drDisp["ParameterTypes24"] = "TextBox"; try {dr["CallingParams24"] = cCallingParams24.Text.Trim();} catch {} drType["CallingParams24"] = "VarChar"; drDisp["CallingParams24"] = "TextBox"; try {dr["MasterTable24"] = base.SetBool(cMasterTable24.Checked);} catch {} drType["MasterTable24"] = "Char"; drDisp["MasterTable24"] = "CheckBox"; try {dr["OnAdd24"] = base.SetBool(cOnAdd24.Checked);} catch {} drType["OnAdd24"] = "Char"; drDisp["OnAdd24"] = "CheckBox"; try {dr["OnUpd24"] = base.SetBool(cOnUpd24.Checked);} catch {} drType["OnUpd24"] = "Char"; drDisp["OnUpd24"] = "CheckBox"; try {dr["OnDel24"] = base.SetBool(cOnDel24.Checked);} catch {} drType["OnDel24"] = "Char"; drDisp["OnDel24"] = "CheckBox"; try {dr["BeforeCRUD24"] = cBeforeCRUD24.SelectedValue;} catch {} drType["BeforeCRUD24"] = "Char"; drDisp["BeforeCRUD24"] = "DropDownList"; try {dr["RuleCode24"] = cRuleCode24.Text;} catch {} drType["RuleCode24"] = "VarWChar"; drDisp["RuleCode24"] = "MultiLine"; try {dr["ModifiedBy24"] = base.LUser.UsrId.ToString();} catch {}; drType["ModifiedBy24"] = "Numeric"; drDisp["ModifiedBy24"] = "DropDownList"; try {dr["LastGenDt24"] = cLastGenDt24.Text.Trim();} catch {} drType["LastGenDt24"] = "DBTimeStamp"; drDisp["LastGenDt24"] = "TextBox"; if (bAdd) { } ds.Tables["AdmServerRule"].Rows.Add(dr); ds.Tables["AdmServerRule"].Rows.Add(drType); ds.Tables["AdmServerRule"].Rows.Add(drDisp); return ds; } public bool CanAct(char typ) { return CanAct(typ, GetAuthRow(), cAdmServerRule14List.SelectedValue.ToString()); } private bool ValidPage() { EnableValidators(true); Page.Validate(); if (!Page.IsValid) { PanelTop.Update(); return false; } DataTable dt = null; dt = (DataTable)Session[KEY_dtRuleTypeId24]; if (dt != null && dt.Rows.Count <= 0) { bErrNow.Value = "Y"; PreMsgPopup("Value is expected for 'RuleTypeId', please investigate."); return false; } dt = (DataTable)Session[KEY_dtBeforeCRUD24]; if (dt != null && dt.Rows.Count <= 0) { bErrNow.Value = "Y"; PreMsgPopup("Value is expected for 'BeforeCRUD', please investigate."); return false; } return true; } protected void cbPostBack(object sender, System.EventArgs e) { } protected void IgnoreHeaderConfirm(LinkButton lb) { if (lb != null && (lb.Attributes["OnClick"] == null || lb.Attributes["OnClick"].IndexOf("_bConfirm") < 0) && lb.Visible) { lb.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';"; } } protected void IgnoreConfirm() { if (cExpTxtButton.Attributes["OnClick"] == null || cExpTxtButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cExpTxtButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";} if (cExpRtfButton.Attributes["OnClick"] == null || cExpRtfButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cExpRtfButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";} if (cUndoAllButton.Attributes["OnClick"] == null || cUndoAllButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cUndoAllButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";} if (cSaveCloseButton.Attributes["OnClick"] == null || cSaveCloseButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cSaveCloseButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";} if (cSaveButton.Attributes["OnClick"] == null || cSaveButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cSaveButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";} if (cNewSaveButton.Attributes["OnClick"] == null || cNewSaveButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cNewSaveButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";} if (cCopySaveButton.Attributes["OnClick"] == null || cCopySaveButton.Attributes["OnClick"].IndexOf("_bConfirm") < 0) {cCopySaveButton.Attributes["OnClick"] += "document.getElementById('" + bConfirm.ClientID + "').value='N';";} if (cDeleteButton.Attributes["OnClick"] == null || cDeleteButton.Attributes["OnClick"].IndexOf("return confirm") < 0) {cDeleteButton.Attributes["OnClick"] += "return confirm('Delete this record for sure?');";} if (cClearButton.Attributes["OnClick"] == null || cClearButton.Attributes["OnClick"].IndexOf("return confirm") < 0) {cClearButton.Attributes["OnClick"] += "return confirm('Clear this record for sure and assume initial defaulted values except non-editable fields? You may click the New button if you wish to create a new record instead.');";} } protected void InitPreserve() { cSystemId.Attributes["onchange"] = "javascript:return CanPostBack(true,this);";cSystemId.Attributes["NeedConfirm"] = "Y"; cFilterId.Attributes["onchange"] = "javascript:return CanPostBack(true,this);";cFilterId.Attributes["NeedConfirm"] = "Y"; } protected void ShowDirty(bool bShow) { if (bShow) {bPgDirty.Value = "Y";} else {bPgDirty.Value = "N";} } private void PreMsgPopup(string msg) { PreMsgPopup(msg,cAdmServerRule14List,null); } private void PreMsgPopup(string msg, RoboCoder.WebControls.ComboBox cb, WebControl wc) { if (string.IsNullOrEmpty(msg)) return; int MsgPos = msg.IndexOf("RO.SystemFramewk.ApplicationAssert"); string iconUrl = "images/warning.gif"; string focusOnCloseId = cb != null ? cb.FocusID : (wc != null ? wc.ClientID : string.Empty); string msgContent = ReformatErrMsg(msg); if (MsgPos >= 0 && LUser.TechnicalUsr != "Y") { msgContent = ReformatErrMsg(msg.Substring(0, MsgPos - 3)); } if (bErrNow.Value == "Y") { iconUrl = "images/error.gif"; bErrNow.Value = "N"; } else if (bInfoNow.Value == "Y") { iconUrl = "images/info.gif"; bInfoNow.Value = "N"; } string script = @"<script type='text/javascript' lang='javascript'> PopDialog('" + iconUrl + "','" + msgContent.Replace(@"\", @"\\").Replace("'", @"\'") + "','" + focusOnCloseId + @"'); </script>"; ScriptManager.RegisterStartupScript(cMsgContent, typeof(Label), "Popup", script, false); } private Control FindEditableControl(Control root) { Control found = null; if (IsEditableControl(root)) { found = root; return found; } foreach (Control c in root.Controls) { found = FindEditableControl(c); if (found != null) return found; } return null; } } }
60.750973
634
0.671043
[ "Apache-2.0" ]
robocoder-media/Low-Code-Development-Platform
Web/modules/AdmServerRuleModule.ascx.cs
140,517
C#
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Options; using Abp.Authorization; using Abp.MiniBlog.Authorization.Roles; using Abp.MiniBlog.Authorization.Users; using Abp.MiniBlog.MultiTenancy; namespace Abp.MiniBlog.Identity { public class SecurityStampValidator : AbpSecurityStampValidator<Tenant, Role, User> { public SecurityStampValidator( IOptions<SecurityStampValidatorOptions> options, SignInManager signInManager, ISystemClock systemClock) : base( options, signInManager, systemClock) { } } }
28.24
87
0.671388
[ "MIT" ]
liuzhenyulive/Abp.MiniBlog
src/Abp.MiniBlog.Core/Identity/SecurityStampValidator.cs
708
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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AndSByte() { var test = new SimpleBinaryOpTest__AndSByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AndSByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<SByte> _fld1; public Vector128<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AndSByte testClass) { var result = Sse2.And(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AndSByte testClass) { fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = Sse2.And( Sse2.LoadVector128((SByte*)(pFld1)), Sse2.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector128<SByte> _clsVar1; private static Vector128<SByte> _clsVar2; private Vector128<SByte> _fld1; private Vector128<SByte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AndSByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public SimpleBinaryOpTest__AndSByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, new SByte[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.And( Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.And( Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.And( Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.And( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<SByte>* pClsVar1 = &_clsVar1) fixed (Vector128<SByte>* pClsVar2 = &_clsVar2) { var result = Sse2.And( Sse2.LoadVector128((SByte*)(pClsVar1)), Sse2.LoadVector128((SByte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr); var result = Sse2.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)); var result = Sse2.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)); var result = Sse2.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AndSByte(); var result = Sse2.And(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__AndSByte(); fixed (Vector128<SByte>* pFld1 = &test._fld1) fixed (Vector128<SByte>* pFld2 = &test._fld2) { var result = Sse2.And( Sse2.LoadVector128((SByte*)(pFld1)), Sse2.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.And(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = Sse2.And( Sse2.LoadVector128((SByte*)(pFld1)), Sse2.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.And(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.And( Sse2.LoadVector128((SByte*)(&test._fld1)), Sse2.LoadVector128((SByte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<SByte> op1, Vector128<SByte> op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((sbyte)(left[0] & right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((sbyte)(left[i] & right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.And)}<SByte>(Vector128<SByte>, Vector128<SByte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
41.554608
187
0.57665
[ "MIT" ]
06needhamt/runtime
src/coreclr/tests/src/JIT/HardwareIntrinsics/X86/Sse2/And.SByte.cs
24,351
C#
using System; using System.Collections.Generic; using System.Linq; namespace P01_GenericBox { class Program { static void Main(string[] args) { List<Box<int> > boxes = new List<Box<int>>(); var nLines = int.Parse(Console.ReadLine()); for (int i = 0; i < nLines; i++) { var input = int.Parse(Console.ReadLine()); var box = new Box<int>(input); boxes.Add(box); } boxes = SwapElements(boxes); boxes.ToList().ForEach(Console.WriteLine); } private static List<Box<T>> SwapElements<T>(List<Box<T>> boxes) { var indexes = Console.ReadLine().Split().Select(int.Parse).ToArray(); var temp = boxes[indexes[0]]; boxes[indexes[0]] = boxes[indexes[1]]; boxes[indexes[1]] = temp; return boxes; } } }
25.236842
81
0.500521
[ "MIT" ]
ignatovg/Software-University
C#-Fundamentals/03_CSharp_OOP_Advanced/02_Generic/Generic_Exercises/P01_GenericBox/Program.cs
961
C#
using System; using System.Collections.Generic; using System.Reflection; using FFImageLoading.Forms; using FFImageLoading.Forms.WinUWP; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace JobInTown.UWP { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> public sealed partial class App : Application { /// <summary> /// Initializes a new instance of the <see cref="App"/> class. /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { InitializeComponent(); Suspending += OnSuspending; } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; var assembliesToInclude = new List<Assembly>() { typeof(CachedImage).GetTypeInfo().Assembly, typeof(CachedImageRenderer).GetTypeInfo().Assembly }; Xamarin.Forms.Forms.Init(e, assembliesToInclude); if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(MainPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); } /// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> private void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception("Failed to load Page " + e.SourcePageType.FullName); } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); deferral.Complete(); } } }
37.851852
99
0.603718
[ "MIT" ]
danimart1991/xamarin-example-jobintown
src/App/JobInTown.UWP/App.xaml.cs
4,090
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.Network.V20191101 { /// <summary> /// Private link service resource. /// </summary> [AzureNextGenResourceType("azure-nextgen:network/v20191101:PrivateLinkService")] public partial class PrivateLinkService : Pulumi.CustomResource { /// <summary> /// The alias of the private link service. /// </summary> [Output("alias")] public Output<string> Alias { get; private set; } = null!; /// <summary> /// The auto-approval list of the private link service. /// </summary> [Output("autoApproval")] public Output<Outputs.PrivateLinkServicePropertiesResponseAutoApproval?> AutoApproval { get; private set; } = null!; /// <summary> /// Whether the private link service is enabled for proxy protocol or not. /// </summary> [Output("enableProxyProtocol")] public Output<bool?> EnableProxyProtocol { get; private set; } = null!; /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> [Output("etag")] public Output<string> Etag { get; private set; } = null!; /// <summary> /// The list of Fqdn. /// </summary> [Output("fqdns")] public Output<ImmutableArray<string>> Fqdns { get; private set; } = null!; /// <summary> /// An array of private link service IP configurations. /// </summary> [Output("ipConfigurations")] public Output<ImmutableArray<Outputs.PrivateLinkServiceIpConfigurationResponse>> IpConfigurations { get; private set; } = null!; /// <summary> /// An array of references to the load balancer IP configurations. /// </summary> [Output("loadBalancerFrontendIpConfigurations")] public Output<ImmutableArray<Outputs.FrontendIPConfigurationResponse>> LoadBalancerFrontendIpConfigurations { get; private set; } = null!; /// <summary> /// Resource location. /// </summary> [Output("location")] public Output<string?> Location { get; private set; } = null!; /// <summary> /// Resource name. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// An array of references to the network interfaces created for this private link service. /// </summary> [Output("networkInterfaces")] public Output<ImmutableArray<Outputs.NetworkInterfaceResponse>> NetworkInterfaces { get; private set; } = null!; /// <summary> /// An array of list about connections to the private endpoint. /// </summary> [Output("privateEndpointConnections")] public Output<ImmutableArray<Outputs.PrivateEndpointConnectionResponse>> PrivateEndpointConnections { get; private set; } = null!; /// <summary> /// The provisioning state of the private link service resource. /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// Resource tags. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// Resource type. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// The visibility list of the private link service. /// </summary> [Output("visibility")] public Output<Outputs.PrivateLinkServicePropertiesResponseVisibility?> Visibility { get; private set; } = null!; /// <summary> /// Create a PrivateLinkService resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public PrivateLinkService(string name, PrivateLinkServiceArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:network/v20191101:PrivateLinkService", name, args ?? new PrivateLinkServiceArgs(), MakeResourceOptions(options, "")) { } private PrivateLinkService(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:network/v20191101:PrivateLinkService", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:network:PrivateLinkService"}, new Pulumi.Alias { Type = "azure-nextgen:network/latest:PrivateLinkService"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:PrivateLinkService"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:PrivateLinkService"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:PrivateLinkService"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:PrivateLinkService"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:PrivateLinkService"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:PrivateLinkService"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:PrivateLinkService"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:PrivateLinkService"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:PrivateLinkService"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:PrivateLinkService"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:PrivateLinkService"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200801:PrivateLinkService"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing PrivateLinkService resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static PrivateLinkService Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new PrivateLinkService(name, id, options); } } public sealed class PrivateLinkServiceArgs : Pulumi.ResourceArgs { /// <summary> /// The auto-approval list of the private link service. /// </summary> [Input("autoApproval")] public Input<Inputs.PrivateLinkServicePropertiesAutoApprovalArgs>? AutoApproval { get; set; } /// <summary> /// Whether the private link service is enabled for proxy protocol or not. /// </summary> [Input("enableProxyProtocol")] public Input<bool>? EnableProxyProtocol { get; set; } [Input("fqdns")] private InputList<string>? _fqdns; /// <summary> /// The list of Fqdn. /// </summary> public InputList<string> Fqdns { get => _fqdns ?? (_fqdns = new InputList<string>()); set => _fqdns = value; } /// <summary> /// Resource ID. /// </summary> [Input("id")] public Input<string>? Id { get; set; } [Input("ipConfigurations")] private InputList<Inputs.PrivateLinkServiceIpConfigurationArgs>? _ipConfigurations; /// <summary> /// An array of private link service IP configurations. /// </summary> public InputList<Inputs.PrivateLinkServiceIpConfigurationArgs> IpConfigurations { get => _ipConfigurations ?? (_ipConfigurations = new InputList<Inputs.PrivateLinkServiceIpConfigurationArgs>()); set => _ipConfigurations = value; } [Input("loadBalancerFrontendIpConfigurations")] private InputList<Inputs.FrontendIPConfigurationArgs>? _loadBalancerFrontendIpConfigurations; /// <summary> /// An array of references to the load balancer IP configurations. /// </summary> public InputList<Inputs.FrontendIPConfigurationArgs> LoadBalancerFrontendIpConfigurations { get => _loadBalancerFrontendIpConfigurations ?? (_loadBalancerFrontendIpConfigurations = new InputList<Inputs.FrontendIPConfigurationArgs>()); set => _loadBalancerFrontendIpConfigurations = value; } /// <summary> /// Resource location. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the private link service. /// </summary> [Input("serviceName")] public Input<string>? ServiceName { get; set; } [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Resource tags. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } /// <summary> /// The visibility list of the private link service. /// </summary> [Input("visibility")] public Input<Inputs.PrivateLinkServicePropertiesVisibilityArgs>? Visibility { get; set; } public PrivateLinkServiceArgs() { } } }
41.528302
154
0.608087
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Network/V20191101/PrivateLinkService.cs
11,005
C#
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Options; using Abp.Authorization; using PrototipoSistemaFGV.Authorization.Roles; using PrototipoSistemaFGV.Authorization.Users; using PrototipoSistemaFGV.MultiTenancy; using Microsoft.Extensions.Logging; namespace PrototipoSistemaFGV.Identity { public class SecurityStampValidator : AbpSecurityStampValidator<Tenant, Role, User> { public SecurityStampValidator( IOptions<SecurityStampValidatorOptions> options, SignInManager signInManager, ISystemClock systemClock, ILoggerFactory loggerFactory) : base(options, signInManager, systemClock, loggerFactory) { } } }
32.041667
87
0.750325
[ "MIT" ]
DevsBueller/Proj-Angular-Core
aspnet-core/src/PrototipoSistemaFGV.Core/Identity/SecurityStampValidator.cs
771
C#
using Microsoft.Web.Administration; using PI.Plugin.Exception; using PI.Plugin.Interface; using System; using System.Collections.Generic; using System.Linq; namespace PInstaller.BuiltInBlocks { class IISApplicationPools : PIPlugin { private class IISWebApplicationPool { public string Name { get; set; } public bool IsIntegrated { get; set; } public bool Enable32Bit { get; set; } public string ManagedRuntimeVersion { get; set; } public bool AutoStart { get; set; } public bool AlwaysRunning { get; set; } public IISWebApplicationPool() { IsIntegrated = true; Enable32Bit = true; ManagedRuntimeVersion = "v4.0"; AutoStart = true; AlwaysRunning = true; } } public string BlockType() { return "IISApplicationPools"; } public void Process(string jsonBlock, MainParameters mainParameters) { var appPools = GetData(jsonBlock); if (appPools.Count == 0) return; using (var iisManager = new ServerManager()) { Console.WriteLine("Removing existing ApplicationPools..."); foreach (var appPool in appPools) { try { var pool = iisManager.ApplicationPools.FirstOrDefault(ap => ap.Name.ToLower() == appPool.Name.ToLower()); if (pool != null) { Console.WriteLine("\tApplicationPool: {0}", appPool.Name); if (pool.State != ObjectState.Stopped) { try { pool.Stop(); } catch { } } iisManager.ApplicationPools.Remove(pool); } iisManager.CommitChanges(); } catch (Exception ex) { if (mainParameters.IsVerbose()) Console.WriteLine("Error: {0}", ex.Message); throw new PluginException(true, string.Format("Couldn't remove ApplicationPool: {0}", appPool.Name)); } } Console.WriteLine("Creating ApplicationPools..."); foreach (var appPool in appPools) { try { Console.WriteLine("\tApplicationPool: {0}", appPool.Name); ApplicationPool newPool = iisManager.ApplicationPools.Add(appPool.Name); newPool.ManagedRuntimeVersion = appPool.ManagedRuntimeVersion; newPool.AutoStart = appPool.AutoStart; newPool.Enable32BitAppOnWin64 = appPool.Enable32Bit; newPool.ManagedPipelineMode = appPool.IsIntegrated ? ManagedPipelineMode.Integrated : ManagedPipelineMode.Classic; newPool.Recycling.PeriodicRestart.PrivateMemory = 1024 * 1024; newPool.Recycling.PeriodicRestart.Time = TimeSpan.Zero; newPool.ProcessModel.IdleTimeout = TimeSpan.Zero; var attr = newPool.Attributes.FirstOrDefault(a => a.Name == "startMode"); if (attr != null) attr.Value = appPool.AlwaysRunning ? 1 : 0; // OnDemand = 0; AlwaysRunning = 1 iisManager.CommitChanges(); } catch (Exception ex) { if (mainParameters.IsVerbose()) Console.WriteLine("Error: {0}", ex.Message); throw new PluginException(true, string.Format("Couldn't create ApplicationPool: {0}", appPool.Name)); } } } } private List<IISWebApplicationPool> GetData(string jsonBlock) { List<IISWebApplicationPool> data = null; try { data = Newtonsoft.Json.JsonConvert.DeserializeObject<List<IISWebApplicationPool>>(jsonBlock); } catch (Exception ex) { throw new PluginException(true, "Couldn't parse config block"); } return data; } } }
41.205357
138
0.488191
[ "MIT" ]
hoffmannj/PackageInstaller
PInstaller/BuiltInBlocks/IISApplicationPools.cs
4,617
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercicio_1e2_EstruturaDados { public class Funcionario { public string nome; public double salario; } }
17.4
38
0.724138
[ "MIT" ]
LuizGuiTM/Exercicios-Estrutura-de-Dados
Exercicio 1/Exercicio 1e2 EstruturaDados/Funcionario.cs
263
C#
//--------------------------------------------------------------------- // <copyright file="Validator.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner Microsoft // @backupOwner Microsoft //--------------------------------------------------------------------- using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data.Common.Utils; using System.Data.Mapping.ViewGeneration.Structures; using System.Data.Mapping.ViewGeneration.Utils; using System.Data.Mapping.ViewGeneration.Validation; using System.Data.Metadata.Edm; using System.Diagnostics; using System.Linq; namespace System.Data.Mapping.ViewGeneration { using System.Data.Entity; using BasicSchemaConstraints = SchemaConstraints<BasicKeyConstraint>; using ViewSchemaConstraints = SchemaConstraints<ViewKeyConstraint>; // This class is responsible for validating the incoming cells for a schema class CellGroupValidator { #region Constructor // requires: cells are not normalized, i.e., no slot is null in the cell queries // effects: Constructs a validator object that is capable of // validating all the schema cells together internal CellGroupValidator(IEnumerable<Cell> cells, ConfigViewGenerator config) { m_cells = cells; m_config = config; m_errorLog = new ErrorLog(); } #endregion #region Fields private IEnumerable<Cell> m_cells; private ConfigViewGenerator m_config; private ErrorLog m_errorLog; // Keeps track of errors for this set of cells private ViewSchemaConstraints m_cViewConstraints; private ViewSchemaConstraints m_sViewConstraints; #endregion #region External Methods // effects: Performs the validation of the cells in this and returns // an error log of all the errors/warnings that were discovered internal ErrorLog Validate() { // Check for errors not checked by "C-implies-S principle" if (m_config.IsValidationEnabled) { if (PerformSingleCellChecks() == false) { return m_errorLog; } } else //Note that Metadata loading guarantees that DISTINCT flag is not present { // when update views (and validation) is disabled if (CheckCellsWithDistinctFlag() == false) { return m_errorLog; } } BasicSchemaConstraints cConstraints = new BasicSchemaConstraints(); BasicSchemaConstraints sConstraints = new BasicSchemaConstraints(); // Construct intermediate "view relations" and the basic cell // relations along with the basic constraints ConstructCellRelationsWithConstraints(cConstraints, sConstraints); if (m_config.IsVerboseTracing) { // Trace Basic constraints Trace.WriteLine(String.Empty); Trace.WriteLine("C-Level Basic Constraints"); Trace.WriteLine(cConstraints); Trace.WriteLine("S-Level Basic Constraints"); Trace.WriteLine(sConstraints); } // Propagate the constraints m_cViewConstraints = PropagateConstraints(cConstraints); m_sViewConstraints = PropagateConstraints(sConstraints); // Make some basic checks on the view and basic cell constraints CheckConstraintSanity(cConstraints, sConstraints, m_cViewConstraints, m_sViewConstraints); if (m_config.IsVerboseTracing) { // Trace View constraints Trace.WriteLine(String.Empty); Trace.WriteLine("C-Level View Constraints"); Trace.WriteLine(m_cViewConstraints); Trace.WriteLine("S-Level View Constraints"); Trace.WriteLine(m_sViewConstraints); } // Check for implication if (m_config.IsValidationEnabled) { CheckImplication(m_cViewConstraints, m_sViewConstraints); } return m_errorLog; } #endregion #region Basic Constraint Creation // effects: Creates the base cell relation and view cell relations // for each cellquery/cell. Also generates the C-Side and S-side // basic constraints and stores them into cConstraints and // sConstraints. Stores them in cConstraints and sConstraints private void ConstructCellRelationsWithConstraints(BasicSchemaConstraints cConstraints, BasicSchemaConstraints sConstraints) { // Populate single cell constraints int cellNumber = 0; foreach (Cell cell in m_cells) { // We have to create the ViewCellRelation so that the // BasicCellRelations can be created. cell.CreateViewCellRelation(cellNumber); BasicCellRelation cCellRelation = cell.CQuery.BasicCellRelation; BasicCellRelation sCellRelation = cell.SQuery.BasicCellRelation; // Populate the constraints for the C relation and the S Relation PopulateBaseConstraints(cCellRelation, cConstraints); PopulateBaseConstraints(sCellRelation, sConstraints); cellNumber++; } // Populate two-cell constraints, i.e., inclusion foreach (Cell firstCell in m_cells) { foreach (Cell secondCell in m_cells) { if (Object.ReferenceEquals(firstCell, secondCell)) { // We do not want to set up self-inclusion constraints unnecessarily continue; } } } } // effects: Generates the single-cell key+domain constraints for // baseRelation and adds them to constraints private static void PopulateBaseConstraints(BasicCellRelation baseRelation, BasicSchemaConstraints constraints) { // Populate key constraints baseRelation.PopulateKeyConstraints(constraints); } #endregion #region Constraint Propagation // effects: Propagates baseConstraints derived from the cellrelations // to the corresponding viewCellRelations and returns the list of // propagated constraints private static ViewSchemaConstraints PropagateConstraints(BasicSchemaConstraints baseConstraints) { ViewSchemaConstraints propagatedConstraints = new ViewSchemaConstraints(); // Key constraint propagation foreach (BasicKeyConstraint keyConstraint in baseConstraints.KeyConstraints) { ViewKeyConstraint viewConstraint = keyConstraint.Propagate(); if (viewConstraint != null) { propagatedConstraints.Add(viewConstraint); } } return propagatedConstraints; } #endregion #region Checking for Implication // effects: Checks if all sViewConstraints are implied by the // constraints in cViewConstraints. If some S-level constraints are // not implied, adds errors/warnings to m_errorLog private void CheckImplication(ViewSchemaConstraints cViewConstraints, ViewSchemaConstraints sViewConstraints) { // Check key constraints // i.e., if S has a key <k1, k2>, C must have a key that is a subset of this CheckImplicationKeyConstraints(cViewConstraints, sViewConstraints); // For updates, we need to ensure the following: for every // extent E, table T pair, some key of E is implied by T's key // Get all key constraints for each extent and each table KeyToListMap<ExtentPair, ViewKeyConstraint> extentPairConstraints = new KeyToListMap<ExtentPair, ViewKeyConstraint>(EqualityComparer<ExtentPair>.Default); foreach (ViewKeyConstraint cKeyConstraint in cViewConstraints.KeyConstraints) { ExtentPair pair = new ExtentPair(cKeyConstraint.Cell.CQuery.Extent, cKeyConstraint.Cell.SQuery.Extent); extentPairConstraints.Add(pair, cKeyConstraint); } // Now check that we guarantee at least one constraint per // extent/table pair foreach (ExtentPair extentPair in extentPairConstraints.Keys) { ReadOnlyCollection<ViewKeyConstraint> cKeyConstraints = extentPairConstraints.ListForKey(extentPair); bool sImpliesSomeC = false; // Go through all key constraints for the extent/table pair, and find one that S implies foreach (ViewKeyConstraint cKeyConstraint in cKeyConstraints) { foreach (ViewKeyConstraint sKeyConstraint in sViewConstraints.KeyConstraints) { if (sKeyConstraint.Implies(cKeyConstraint)) { sImpliesSomeC = true; break; // The implication holds - so no problem } } } if (sImpliesSomeC == false) { // Indicate that at least one key must be ensured on the S-side m_errorLog.AddEntry(ViewKeyConstraint.GetErrorRecord(cKeyConstraints)); } } } // effects: Checks for key constraint implication problems from // leftViewConstraints to rightViewConstraints. Adds errors/warning to m_errorLog private void CheckImplicationKeyConstraints(ViewSchemaConstraints leftViewConstraints, ViewSchemaConstraints rightViewConstraints) { // if cImpliesS is true, every rightKeyConstraint must be implied // if it is false, at least one key constraint for each C-level // extent must be implied foreach (ViewKeyConstraint rightKeyConstraint in rightViewConstraints.KeyConstraints) { // Go through all the left Side constraints and check for implication bool found = false; foreach (ViewKeyConstraint leftKeyConstraint in leftViewConstraints.KeyConstraints) { if (leftKeyConstraint.Implies(rightKeyConstraint)) { found = true; break; // The implication holds - so no problem } } if (false == found) { // No C-side key constraint implies this S-level key constraint // Report a problem m_errorLog.AddEntry(ViewKeyConstraint.GetErrorRecord(rightKeyConstraint)); } } } #endregion #region Miscellaneous checks /// <summary> /// Checks that if a DISTINCT operator exists between some C-Extent and S-Extent, there are no additional /// mapping fragments between that C-Extent and S-Extent. /// We need to enforce this because DISTINCT is not understood by viewgen machinery, and two fragments may be merged /// despite one of them having DISTINCT. /// </summary> private bool CheckCellsWithDistinctFlag() { int errorLogSize = m_errorLog.Count; foreach (Cell cell in m_cells) { if (cell.SQuery.SelectDistinctFlag == CellQuery.SelectDistinct.Yes) { var cExtent = cell.CQuery.Extent; var sExtent = cell.SQuery.Extent; //There should be no other fragments mapping cExtent to sExtent var mapepdFragments = m_cells.Where(otherCell => otherCell != cell) .Where(otherCell => otherCell.CQuery.Extent == cExtent && otherCell.SQuery.Extent == sExtent); if (mapepdFragments.Any()) { var cellsToReport = Enumerable.Union(Enumerable.Repeat(cell, 1), mapepdFragments); ErrorLog.Record record = new ErrorLog.Record(true, ViewGenErrorCode.MultipleFragmentsBetweenCandSExtentWithDistinct, Strings.Viewgen_MultipleFragmentsBetweenCandSExtentWithDistinct(cExtent.Name, sExtent.Name), cellsToReport, String.Empty); m_errorLog.AddEntry(record); } } } return m_errorLog.Count == errorLogSize; } // effects: Check for problems in each cell that are not detected by the // "C-constraints-imply-S-constraints" principle. If the check fails, // adds relevant error info to m_errorLog and returns false. Else // retrns true private bool PerformSingleCellChecks() { int errorLogSize = m_errorLog.Count; foreach (Cell cell in m_cells) { // Check for duplication of element in a single cell name1, name2 // -> name Could be done by implication but that would require // setting self-inclusion constraints etc That seems unnecessary // We need this check only for the C side. if we map cname1 // and cmane2 to sname, that is a problem. But mapping sname1 // and sname2 to cname is ok ErrorLog.Record error = cell.SQuery.CheckForDuplicateFields(cell.CQuery, cell); if (error != null) { m_errorLog.AddEntry(error); } // Check that the EntityKey and the Table key are mapped // (Key for association is all ends) error = cell.CQuery.VerifyKeysPresent(cell, Strings.ViewGen_EntitySetKey_Missing, Strings.ViewGen_AssociationSetKey_Missing, ViewGenErrorCode.KeyNotMappedForCSideExtent); if (error != null) { m_errorLog.AddEntry(error); } error = cell.SQuery.VerifyKeysPresent(cell, Strings.ViewGen_TableKey_Missing, null, ViewGenErrorCode.KeyNotMappedForTable); if (error != null) { m_errorLog.AddEntry(error); } // Check that if any side has a not-null constraint -- if so, // we must project that slot error = cell.CQuery.CheckForProjectedNotNullSlots(cell, m_cells.Where(c=> c.SQuery.Extent is AssociationSet)); if (error != null) { m_errorLog.AddEntry(error); } error = cell.SQuery.CheckForProjectedNotNullSlots(cell, m_cells.Where(c => c.CQuery.Extent is AssociationSet)); if (error != null) { m_errorLog.AddEntry(error); } } return m_errorLog.Count == errorLogSize; } // effects: Checks for some sanity issues between the basic and view constraints. Adds to m_errorLog if needed [Conditional("DEBUG")] private static void CheckConstraintSanity(BasicSchemaConstraints cConstraints, BasicSchemaConstraints sConstraints, ViewSchemaConstraints cViewConstraints, ViewSchemaConstraints sViewConstraints) { Debug.Assert(cConstraints.KeyConstraints.Count() == cViewConstraints.KeyConstraints.Count(), "Mismatch in number of C basic and view key constraints"); Debug.Assert(sConstraints.KeyConstraints.Count() == sViewConstraints.KeyConstraints.Count(), "Mismatch in number of S basic and view key constraints"); } #endregion // Keeps track of two extent objects private class ExtentPair { internal ExtentPair(EntitySetBase acExtent, EntitySetBase asExtent) { cExtent = acExtent; sExtent = asExtent; } internal EntitySetBase cExtent; internal EntitySetBase sExtent; public override bool Equals(object obj) { if (object.ReferenceEquals(this, obj)) { return true; } ExtentPair pair = obj as ExtentPair; if (pair == null) { return false; } return pair.cExtent.Equals(cExtent) && pair.sExtent.Equals(sExtent); } public override int GetHashCode() { return cExtent.GetHashCode() ^ sExtent.GetHashCode(); } } } }
42.496368
150
0.580423
[ "MIT" ]
Abdalla-rabie/referencesource
System.Data.Entity/System/Data/Mapping/ViewGeneration/Validator.cs
17,551
C#
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; namespace LinqToDB.DataProvider.MySql { using SqlQuery; using SqlProvider; class MySqlSqlBuilder : BasicSqlBuilder { public MySqlSqlBuilder(ISqlOptimizer sqlOptimizer, SqlProviderFlags sqlProviderFlags, ValueToSqlConverter valueToSqlConverter) : base(sqlOptimizer, sqlProviderFlags, valueToSqlConverter) { } static MySqlSqlBuilder() { ParameterSymbol = '@'; } protected override bool IsRecursiveCteKeywordRequired => true; public override bool IsNestedJoinParenthesisRequired => true; protected override bool CanSkipRootAliases(SqlStatement statement) { if (statement.SelectQuery != null) { return statement.SelectQuery.From.Tables.Count > 0; } return true; } public override int CommandCount(SqlStatement statement) { return statement.NeedsIdentity() ? 2 : 1; } protected override void BuildCommand(SqlStatement statement, int commandNumber) { StringBuilder.AppendLine("SELECT LAST_INSERT_ID()"); } protected override ISqlBuilder CreateSqlBuilder() { return new MySqlSqlBuilder(SqlOptimizer, SqlProviderFlags, ValueToSqlConverter); } protected override string LimitFormat(SelectQuery selectQuery) { return "LIMIT {0}"; } protected override void BuildOffsetLimit(SelectQuery selectQuery) { if (selectQuery.Select.SkipValue == null) base.BuildOffsetLimit(selectQuery); else { AppendIndent() .AppendFormat( "LIMIT {0},{1}", WithStringBuilder(new StringBuilder(), () => BuildExpression(selectQuery.Select.SkipValue)), selectQuery.Select.TakeValue == null ? long.MaxValue.ToString() : WithStringBuilder(new StringBuilder(), () => BuildExpression(selectQuery.Select.TakeValue).ToString())) .AppendLine(); } } protected override void BuildDataType(SqlDataType type, bool createDbType) { switch (type.DataType) { case DataType.Int16 : case DataType.Int32 : case DataType.Int64 : if (createDbType) goto default; StringBuilder.Append("Signed"); break; case DataType.SByte : case DataType.Byte : case DataType.UInt16 : case DataType.UInt32 : case DataType.UInt64 : if (createDbType) goto default; StringBuilder.Append("Unsigned"); break; case DataType.Money : StringBuilder.Append("Decimal(19,4)"); break; case DataType.SmallMoney : StringBuilder.Append("Decimal(10,4)"); break; case DataType.DateTime2 : case DataType.SmallDateTime : StringBuilder.Append("DateTime"); break; case DataType.Boolean : StringBuilder.Append("Boolean"); break; case DataType.Double : case DataType.Single : base.BuildDataType(SqlDataType.Decimal, createDbType); break; case DataType.VarChar : case DataType.NVarChar : // yep, char(0) is allowed if (type.Length == null || type.Length > 255 || type.Length < 0) StringBuilder.Append("Char(255)"); else StringBuilder.Append($"Char({type.Length})"); break; default: base.BuildDataType(type, createDbType); break; } } protected override void BuildDeleteClause(SqlDeleteStatement deleteStatement) { var table = deleteStatement.Table != null ? (deleteStatement.SelectQuery.From.FindTableSource(deleteStatement.Table) ?? deleteStatement.Table) : deleteStatement.SelectQuery.From.Tables[0]; AppendIndent() .Append("DELETE ") .Append(Convert(GetTableAlias(table), ConvertType.NameToQueryTableAlias)) .AppendLine(); } protected override void BuildUpdateClause(SqlStatement statement, SelectQuery selectQuery, SqlUpdateClause updateClause) { base.BuildFromClause(statement, selectQuery); StringBuilder.Remove(0, 4).Insert(0, "UPDATE"); base.BuildUpdateSet(selectQuery, updateClause); } protected override void BuildFromClause(SqlStatement statement, SelectQuery selectQuery) { if (!statement.IsUpdate()) base.BuildFromClause(statement, selectQuery); } public static char ParameterSymbol { get; set; } public static bool TryConvertParameterSymbol { get; set; } private static string _commandParameterPrefix = string.Empty; public static string CommandParameterPrefix { get => _commandParameterPrefix; set => _commandParameterPrefix = value ?? string.Empty; } private static string _sprocParameterPrefix = string.Empty; public static string SprocParameterPrefix { get => _sprocParameterPrefix; set => _sprocParameterPrefix = value ?? string.Empty; } private static List<char> _convertParameterSymbols; public static List<char> ConvertParameterSymbols { get => _convertParameterSymbols; set => _convertParameterSymbols = value ?? new List<char>(); } public override object Convert(object value, ConvertType convertType) { switch (convertType) { case ConvertType.NameToQueryParameter: return ParameterSymbol + value.ToString(); case ConvertType.NameToCommandParameter: return ParameterSymbol + CommandParameterPrefix + value; case ConvertType.NameToSprocParameter: { var valueStr = value.ToString(); if(string.IsNullOrEmpty(valueStr)) throw new ArgumentException("Argument 'value' must represent parameter name."); if (valueStr[0] == ParameterSymbol) valueStr = valueStr.Substring(1); if (valueStr.StartsWith(SprocParameterPrefix, StringComparison.Ordinal)) valueStr = valueStr.Substring(SprocParameterPrefix.Length); return ParameterSymbol + SprocParameterPrefix + valueStr; } case ConvertType.SprocParameterToName: { var str = value.ToString(); str = (str.Length > 0 && (str[0] == ParameterSymbol || (TryConvertParameterSymbol && ConvertParameterSymbols.Contains(str[0])))) ? str.Substring(1) : str; if (!string.IsNullOrEmpty(SprocParameterPrefix) && str.StartsWith(SprocParameterPrefix)) str = str.Substring(SprocParameterPrefix.Length); return str; } case ConvertType.NameToQueryField : case ConvertType.NameToQueryFieldAlias: case ConvertType.NameToQueryTableAlias: { var name = value.ToString(); if (name.Length > 0 && name[0] == '`') return value; return "`" + value + "`"; } case ConvertType.NameToDatabase : case ConvertType.NameToSchema : case ConvertType.NameToQueryTable : if (value != null) { var name = value.ToString(); if (name.Length > 0 && name[0] == '`') return value; if (name.IndexOf('.') > 0) value = string.Join("`.`", name.Split('.')); return "`" + value + "`"; } break; } return value; } protected override StringBuilder BuildExpression( ISqlExpression expr, bool buildTableName, bool checkParentheses, string alias, ref bool addAlias, bool throwExceptionIfTableNotFound = true) { return base.BuildExpression( expr, buildTableName && Statement.QueryType != QueryType.InsertOrUpdate, checkParentheses, alias, ref addAlias, throwExceptionIfTableNotFound); } protected override void BuildInsertOrUpdateQuery(SqlInsertOrUpdateStatement insertOrUpdate) { var position = StringBuilder.Length; BuildInsertQuery(insertOrUpdate, insertOrUpdate.Insert, false); if (insertOrUpdate.Update.Items.Count > 0) { AppendIndent().AppendLine("ON DUPLICATE KEY UPDATE"); Indent++; var first = true; foreach (var expr in insertOrUpdate.Update.Items) { if (!first) StringBuilder.Append(',').AppendLine(); first = false; AppendIndent(); BuildExpression(expr.Column, false, true); StringBuilder.Append(" = "); BuildExpression(expr.Expression, false, true); } Indent--; StringBuilder.AppendLine(); } else { var sql = StringBuilder.ToString(); var insertIndex = sql.IndexOf("INSERT", position); StringBuilder.Clear() .Append(sql.Substring(0, insertIndex)) .Append("INSERT IGNORE") .Append(sql.Substring(insertIndex + "INSERT".Length)); } } protected override void BuildEmptyInsert(SqlInsertClause insertClause) { StringBuilder.AppendLine("() VALUES ()"); } protected override void BuildCreateTableIdentityAttribute1(SqlField field) { StringBuilder.Append("AUTO_INCREMENT"); } protected override void BuildCreateTablePrimaryKey(SqlCreateTableStatement createTable, string pkName, IEnumerable<string> fieldNames) { AppendIndent(); StringBuilder.Append("CONSTRAINT ").Append(pkName).Append(" PRIMARY KEY CLUSTERED ("); StringBuilder.Append(fieldNames.Aggregate((f1,f2) => f1 + ", " + f2)); StringBuilder.Append(")"); } public override StringBuilder BuildTableName(StringBuilder sb, string database, string schema, string table) { if (database != null && database.Length == 0) database = null; if (database != null) sb.Append(database).Append("."); return sb.Append(table); } protected override string GetProviderTypeName(IDbDataParameter parameter) { dynamic p = parameter; return p.MySqlDbType.ToString(); } protected override void BuildTruncateTable(SqlTruncateTableStatement truncateTable) { if (truncateTable.ResetIdentity || truncateTable.Table.Fields.Values.All(f => !f.IsIdentity)) StringBuilder.Append("TRUNCATE TABLE "); else StringBuilder.Append("DELETE FROM "); } protected override void BuildDropTableStatement(SqlDropTableStatement dropTable) { BuildDropTableStatementIfExists(dropTable); } } }
30.564179
161
0.663444
[ "MIT" ]
Partiolainen/linq2db
Source/LinqToDB/DataProvider/MySql/MySqlSqlBuilder.cs
10,241
C#
using System.Collections.Generic; namespace FoxTunes { public static class BassParametricEqualizerStreamComponentConfiguration { public const string SECTION = BassOutputConfiguration.SECTION; public const string ENABLED = "AAAAF34F-A090-4AEE-BD65-128561960C92"; public const string BANDWIDTH = "AAAB688D-9CA0-41B3-8E11-AC252DF03BE4"; public const string BAND_32 = "BBBBC109-B99A-49C1-909D-16A862EFF344"; public const string BAND_64 = "CCCCDD9E-7430-4123-B7CA-FDDD7680EF2C"; public const string BAND_125 = "DDDD4934-28A4-4841-BC31-9BB895B13A14"; public const string BAND_250 = "EEEE45E7-0B32-4E73-B394-2D510A34FB05"; public const string BAND_500 = "FFFFD2A0-40A7-4772-9829-48D7C8CDCF52"; public const string BAND_1000 = "GGGGEFB4-F65D-444F-A021-5B8F0B643AC5"; public const string BAND_2000 = "HHHHB649-B83F-48D0-AF02-FA127FFC9F04"; public const string BAND_4000 = "IIIIE3B6-1026-4505-8C77-294185F61452"; public const string BAND_8000 = "JJJJAADF-5286-46BA-AC4F-80CFB1115215"; public const string BAND_16000 = "KKKKD105-FC44-40F4-AF85-972CF7F328E9"; public static IEnumerable<ConfigurationSection> GetConfigurationSections() { var section = new ConfigurationSection(SECTION) .WithElement( new BooleanConfigurationElement(ENABLED, "Enabled", path: "Parametric Equalizer") .WithValue(false)) .WithElement( new DoubleConfigurationElement(BANDWIDTH, "Bandwidth", path: "Parametric Equalizer") .WithValue(2.5) .DependsOn(BassOutputConfiguration.SECTION, ENABLED) .WithValidationRule( new DoubleValidationRule( PeakEQ.MIN_BANDWIDTH, PeakEQ.MAX_BANDWIDTH, 0.1 ) )); foreach (var band in Bands) { section.WithElement( new DoubleConfigurationElement( band.Key, band.Value < 1000 ? band.Value.ToString() + "Hz" : band.Value.ToString() + "kHz", path: "Parametric Equalizer") .WithValue(0) .DependsOn(BassOutputConfiguration.SECTION, ENABLED) .WithValidationRule( new DoubleValidationRule( PeakEQ.MIN_GAIN, PeakEQ.MAX_GAIN ) ) ); } yield return section; } public static IEnumerable<KeyValuePair<string, int>> Bands { get { yield return new KeyValuePair<string, int>(BAND_32, 32); yield return new KeyValuePair<string, int>(BAND_64, 64); yield return new KeyValuePair<string, int>(BAND_125, 125); yield return new KeyValuePair<string, int>(BAND_250, 250); yield return new KeyValuePair<string, int>(BAND_500, 500); yield return new KeyValuePair<string, int>(BAND_1000, 1000); yield return new KeyValuePair<string, int>(BAND_2000, 2000); yield return new KeyValuePair<string, int>(BAND_4000, 4000); yield return new KeyValuePair<string, int>(BAND_8000, 8000); yield return new KeyValuePair<string, int>(BAND_16000, 16000); } } } }
42.644444
110
0.543773
[ "MIT" ]
DJCALIEND/FoxTunes
FoxTunes.Output.Bass.ParametricEqualizer/BassParametricEqualizerStreamComponentConfiguration.cs
3,840
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class KnightController : MonoBehaviour { public BoxCollider2D stopCollider; public Transform leftPosition; private Rigidbody2D body2d; private Transform knightTransform; private Transform stopColPosition; private Vector3 stopColVector; private Animator anim; private bool waiting = true; private bool isFlipped = false; private void Start() { body2d = GetComponent<Rigidbody2D>(); knightTransform = GetComponent<Transform>(); stopColPosition = stopCollider.gameObject.transform; stopColVector = new Vector3(stopColPosition.position.x, stopColPosition.position.y, stopColPosition.position.z); anim = GetComponent<Animator>(); } private void OnTriggerEnter2D(Collider2D collision) { if (collision == stopCollider && !isFlipped) { anim.SetBool("Attacking", false); body2d.velocity = Vector2.zero; transform.localScale = new Vector3(transform.localScale.x * -1, transform.localScale.y, transform.localScale.z); var newPosition = new Vector3(leftPosition.position.x, leftPosition.position.y, leftPosition.position.z); stopCollider.gameObject.transform.SetPositionAndRotation(newPosition, Quaternion.identity); isFlipped = !isFlipped; } else if (collision == stopCollider && isFlipped) { anim.SetBool("Attacking", false); body2d.velocity = Vector2.zero; transform.localScale = new Vector3(transform.localScale.x * -1, transform.localScale.y, transform.localScale.z); var newPosition = stopColVector; stopCollider.gameObject.transform.SetPositionAndRotation(newPosition, Quaternion.identity); isFlipped = !isFlipped; } } }
38.632653
124
0.685684
[ "MIT" ]
kmikus/team2-ist440
Project-CandleLIT/Assets/Scripts/KnightController.cs
1,895
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BCModel; namespace BCBL { public interface IFavoriteBookBL { Task<FavoriteBook> AddBooksReadAsync(FavoriteBook book); Task<List<FavoriteBook>> GetAllBooksReadAsync(); Task<List<Book>> GetBooksReadByUserAsync(string email); } }
22.764706
64
0.736434
[ "MIT" ]
210503-Reston-NET/BAR-P2
BookClub/BCBL/IFavoriteBookBL.cs
389
C#
/* Copyright (C) 2012 dbreeze.tiesky.com / Alex Solovyov / Ivars Sudmalis. It's a free software for those, who think that it should be free. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DBreeze; using DBreeze.Utils; namespace DBreeze.DataStructures { /// <summary> /// Ierarchical DataStructure. Any node can have subnodes and own binary content /// </summary> public class DataAsTree { /// <summary> /// Node name /// </summary> public string NodeName = String.Empty; public long NodeId = 0; public long ParentNodeId = 0; /// <summary> /// This can be filled via constructor or extra when we insert a node /// </summary> public byte[] NodeContent = null; /// <summary> /// Internal. Holds reference to DataBlock representing Content. node.GetContent must be used to read out content. /// </summary> protected byte[] ContentRef = null; /// <summary> /// Real table name in DBreeze, that will hold the structure /// </summary> protected string DBreezeTableName = String.Empty; protected DBreeze.Transactions.Transaction Transaction = null; protected DBreeze.DataTypes.NestedTable nt2Read = null; protected DBreeze.DataTypes.NestedTable nt3Read = null; protected DBreeze.DataTypes.NestedTable nt2Write = null; //Storing structure in format ParentId(long)+NodeId(long). Value depends upon type of file or folder protected DBreeze.DataTypes.NestedTable nt3Write = null; //Storing node name for easy search protected DataAsTree RootNode = null; protected bool maximalInsertSpeed = false; /// <summary> /// Initializing Root Node /// </summary> /// <param name="DBreezeTableName">Real table name in DBreeze, that will hold the structure, must be synchronized with other tables in transaction</param> /// <param name="tran"></param> /// <param name="maximalInsertSpeed">will use DBreeze Technical_SetTable_OverwriteIsNotAllowed among transaction for DBreezeTableName</param> public DataAsTree(string DBreezeTableName, DBreeze.Transactions.Transaction tran, bool maximalInsertSpeed = false) { if (tran == null) throw new Exception("Transaction is null"); if (RootNode != null) throw new Exception("Can't be more then one root node, use other constructor"); //Setting up RootNode this.RootNode = this; this.Transaction = tran; this.maximalInsertSpeed = maximalInsertSpeed; this.DBreezeTableName = DBreezeTableName; this.NodeId = 0; this.ParentNodeId = 0; } /// <summary> /// Init nodes for insert under another node /// </summary> /// <param name="name"></param> /// <param name="content">optionaly can supply NodeContent</param> public DataAsTree(string name, byte[] content = null) { if (String.IsNullOrEmpty(name)) throw new Exception("Node name can't be empty"); if (name.To_UTF8Bytes().Length > 256) throw new Exception("Node name can't be more then 256"); this.NodeContent = content; this.NodeName = name; } /// <summary> /// Internal /// </summary> protected DataAsTree() { } /// <summary> /// Internal /// </summary> /// <param name="node"></param> void CopyInternals(DataAsTree node) { node.RootNode = this.RootNode; //node.DBreezeTableName = this.DBreezeTableName; //node.Transaction = this.Transaction; //node.nt2Write = this.nt2Write; //node.nt2Read = this.nt2Read; //node.nt3Write = this.nt3Write; //node.nt3Read = this.nt3Read; } /// <summary> /// Internal /// </summary> /// <param name="tran"></param> void SetupReadTables() { if (this.RootNode.nt2Read == null) { this.RootNode.nt2Read = this.RootNode.Transaction.SelectTable(this.RootNode.DBreezeTableName, new byte[] { 2 }, 0); this.RootNode.nt2Read.ValuesLazyLoadingIsOn = false; this.RootNode.nt3Read = this.RootNode.Transaction.SelectTable(this.RootNode.DBreezeTableName, new byte[] { 3 }, 0); this.RootNode.nt3Read.ValuesLazyLoadingIsOn = false; } } /// <summary> /// Internal /// </summary> /// <param name="tran"></param> /// <param name="maximalSpeed"></param> void SetupWriteTables() { if (this.RootNode.nt2Write == null) { //under new byte[] { 1 } we store Id of the entity(long) this.RootNode.nt2Write = this.RootNode.Transaction.InsertTable(this.RootNode.DBreezeTableName, new byte[] { 2 }, 0); //here is a structure table this.RootNode.nt2Write.ValuesLazyLoadingIsOn = false; this.RootNode.nt3Write = this.RootNode.Transaction.InsertTable(this.RootNode.DBreezeTableName, new byte[] { 3 }, 0); //here is a search by NodeName table this.RootNode.nt3Write.ValuesLazyLoadingIsOn = false; } if (this.RootNode.maximalInsertSpeed) { this.RootNode.nt2Write.Technical_SetTable_OverwriteIsNotAllowed(); this.RootNode.nt3Write.Technical_SetTable_OverwriteIsNotAllowed(); } } /// <summary> /// Internal /// </summary> /// <param name="tran"></param> void CheckTransaction() { //if (tran == null) // throw new Exception("Transaction is null"); //if (tran.ManagedThreadId != Transaction.ManagedThreadId || tran.CreatedUdt != Transaction.CreatedUdt) // throw new Exception("Wrong transaction is supplied"); if (this.RootNode == null || this.RootNode.Transaction == null) throw new Exception("RootNode or Transaction is null"); //if (tran.ManagedThreadId != Transaction.ManagedThreadId || tran.CreatedUdt != Transaction.CreatedUdt) // throw new Exception("Wrong transaction is supplied"); } /// <summary> /// Returns node by ParentIdAndNodeId /// </summary> /// <param name="parentNodeId"></param> /// <param name="nodeId"></param> /// <returns></returns> public DataAsTree GetNodeByParentIdAndNodeId(long parentNodeId, long nodeId) { CheckTransaction(); SetupReadTables(); var row = this.RootNode.nt2Read.Select<byte[], byte[]>(parentNodeId.To_8_bytes_array_BigEndian().Concat(nodeId.To_8_bytes_array_BigEndian())); if (row.Exists) return SetupNodeFromRow(row); return null; } /// <summary> /// Returns nodes with suppled StartsWith name or complete name /// </summary> /// <param name="nameStartsWithPart"></param> /// <param name="tran"></param> /// <returns></returns> public IEnumerable<DataAsTree> GetNodesByName(string nameStartsWithPart) { CheckTransaction(); SetupReadTables(); byte[] val = null; byte[] prt = null; DBreeze.DataTypes.Row<byte[], byte[]> nodeRow = null; foreach (var row in this.RootNode.nt3Read.SelectForwardStartsWith<string, byte[]>(nameStartsWithPart)) { val = row.Value; int i = 0; while ((prt = val.Substring(i, 16)) != null) { nodeRow = this.RootNode.nt2Read.Select<byte[], byte[]>(prt); if (nodeRow.Exists) yield return SetupNodeFromRow(nodeRow); i += 16; } } } /// <summary> /// Returns first level nodes by their parent. To go depper, for every returned node can be used ReadOutAllChildrenNodesFromCurrentRecursively /// </summary> /// <param name="parentId"></param> /// <returns></returns> public IEnumerable<DataAsTree> GetFirstLevelChildrenNodesByParentId(long parentId) { CheckTransaction(); SetupReadTables(); byte[] fromKey = parentId.To_8_bytes_array_BigEndian().Concat(long.MinValue.To_8_bytes_array_BigEndian()); byte[] toKey = parentId.To_8_bytes_array_BigEndian().Concat(long.MaxValue.To_8_bytes_array_BigEndian()); foreach (var row in this.RootNode.nt3Read.SelectForwardFromTo<byte[], byte[]>(fromKey, true, toKey, true)) { yield return SetupNodeFromRow(row); } } /// <summary> /// Internal /// </summary> /// <param name="node"></param> /// <param name="protocolVersion"></param> /// <returns></returns> byte[] SetupValueRowFromNode(DataAsTree node, byte protocolVersion) { byte[] val = null; if (String.IsNullOrEmpty(node.NodeName)) throw new Exception("Node name can't be empty"); byte[] name = node.NodeName.To_UTF8Bytes(); if (name.Length > 256) throw new Exception("Node name can't be more then 256"); /* Protocol: 1byte - protocol version (starting from 1) ... than due to the protocol description */ switch (protocolVersion) { case 1: //First protocol type /* Protocol: 1byte - protocol version (starting from 1) 16bytes link to content (or 0) 1byte - lenght of NodeName Nbytes - Name */ val = new byte[] { protocolVersion }.ConcatMany ( (node.ContentRef != null) ? node.ContentRef : new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, new byte[] { (byte)name.Length }, name ); break; } return val; } /// <summary> /// Internal /// </summary> /// <param name="row"></param> /// <returns></returns> DataAsTree SetupNodeFromRow(DBreeze.DataTypes.Row<byte[], byte[]> row) { DataAsTree node = null; byte[] val = row.Value; /* Protocol: 1byte - protocol version (starting from 1) ... than due to the protocol description */ node = new DataAsTree(); switch (val[0]) { case 1: //First protocol type /* Protocol: 1byte - protocol version (starting from 1) 16bytes link to content (or 0) 1byte - lenght of NodeName Nbytes - Name */ if ((val[1] | val[2] | val[3] | val[4] | val[5] | val[6] | val[7] | val[8]) != 0) { //We got content node.ContentRef = val.Substring(1, 16); } node.NodeName = System.Text.Encoding.UTF8.GetString(val.Substring(18, val[17])); break; } node.ParentNodeId = row.Key.Substring(0, 8).To_Int64_BigEndian(); node.NodeId = row.Key.Substring(8, 8).To_Int64_BigEndian(); CopyInternals(node); return node; } /// <summary> /// Reading all children nodes /// </summary> /// <returns></returns> public IEnumerable<DataAsTree> GetChildren() { CheckTransaction(); SetupReadTables(); byte[] fromKey = this.NodeId.To_8_bytes_array_BigEndian().Concat(long.MinValue.To_8_bytes_array_BigEndian()); byte[] toKey = this.NodeId.To_8_bytes_array_BigEndian().Concat(long.MaxValue.To_8_bytes_array_BigEndian()); foreach (var row in this.RootNode.nt2Read.SelectForwardFromTo<byte[], byte[]>(fromKey, true, toKey, true)) { yield return SetupNodeFromRow(row); } } /// <summary> /// Removes node /// </summary> /// <param name="parentNodeId"></param> /// <param name="nodeId"></param> /// <param name="tran"></param> public void RemoveNode(long parentNodeId, long nodeId) { CheckTransaction(); SetupWriteTables(); /*Removing from NameIndex*/ var oldRow = this.RootNode.nt2Write.Select<byte[], byte[]>(parentNodeId.To_8_bytes_array_BigEndian().Concat(nodeId.To_8_bytes_array_BigEndian())); if (oldRow.Exists) { var oldNode = SetupNodeFromRow(oldRow); RemoveOldNodeFromNameIndex(oldNode.NodeName, parentNodeId.To_8_bytes_array_BigEndian().Concat(nodeId.To_8_bytes_array_BigEndian())); } /***************************/ this.RootNode.nt2Write.RemoveKey<byte[]>(parentNodeId.To_8_bytes_array_BigEndian().Concat(nodeId.To_8_bytes_array_BigEndian())); } /// <summary> /// Removes node /// </summary> /// <param name="node"></param> /// <param name="tran"></param> /// <param name="maximalSpeed"></param> public void RemoveNode(DataAsTree node) { this.RemoveNode(node.ParentNodeId, node.NodeId); } /// <summary> /// <para>Adding children to the node</para> /// Table, storing data structure, must be in tran.SynchronizeTables list. /// Then transaction must be Committed in the end by the programmer. /// </summary> /// <param name="nodes">Nodes to add to current node</param> /// <param name="tran">Existing transaction. Table, storing data structure, must be in tran.SynchronizeTables list</param> /// <param name="maximalSpeed">set it to true to gain maximal saving speed</param> public void AddNodes(IEnumerable<DataAsTree> nodes) { CheckTransaction(); if (nodes == null || nodes.Count() == 0) throw new Exception("Nodes are not supplied"); SetupWriteTables(); byte[] val = null; long maxId = this.RootNode.Transaction.Select<byte[], long>(this.RootNode.DBreezeTableName, new byte[] { 1 }).Value; DBreeze.DataTypes.Row<string, byte[]> nodeNameIndexRow = null; byte[] btNodeNameIndex = null; bool skipToFillNameIndex = false; foreach (var node in nodes) { if (node == null) throw new Exception("Node can't be empty"); skipToFillNameIndex = false; if (node.NodeId == 0) { //Insert node.ParentNodeId = this.NodeId; maxId++; node.NodeId = maxId; } else { if (node.NodeId == node.ParentNodeId) throw new Exception("node.NodeId can't be equal to node.ParentNodeId"); //Update var oldRow = this.RootNode.nt2Write.Select<byte[], byte[]>(node.ParentNodeId.To_8_bytes_array_BigEndian().Concat(node.NodeId.To_8_bytes_array_BigEndian())); if (oldRow.Exists) { var oldNode = SetupNodeFromRow(oldRow); if (!oldNode.NodeName.Equals(node.NodeName, StringComparison.OrdinalIgnoreCase)) RemoveOldNodeFromNameIndex(oldNode.NodeName, node.ParentNodeId.To_8_bytes_array_BigEndian().Concat(node.NodeId.To_8_bytes_array_BigEndian())); else skipToFillNameIndex = true; } else { if (maxId >= node.NodeId && maxId >= node.ParentNodeId) { //Such NodeId was probably deleted, and now wants to be reconnected. //We allow that } else { if (node.NodeId == node.ParentNodeId) throw new Exception("Supplied node.NodeId or node.ParentNodeId don't exist"); } } } //ParentNodeId(long),NodeId(long) byte[] key = node.ParentNodeId.To_8_bytes_array_BigEndian() .Concat(node.NodeId.To_8_bytes_array_BigEndian()); if (node.NodeContent != null) { node.ContentRef = this.RootNode.nt2Write.InsertDataBlock(node.ContentRef, node.NodeContent); } else node.ContentRef = null; val = SetupValueRowFromNode(node, 1); CopyInternals(node); this.RootNode.nt2Write.Insert<byte[], byte[]>(key, val); /*node.NodeName index support*/ if (!skipToFillNameIndex) { nodeNameIndexRow = this.RootNode.nt3Write.Select<string, byte[]>(node.NodeName.ToLower()); if (nodeNameIndexRow.Exists) btNodeNameIndex = nodeNameIndexRow.Value.Concat(key); else btNodeNameIndex = key; this.RootNode.nt3Write.Insert<string, byte[]>(node.NodeName.ToLower(), btNodeNameIndex); } /*-----------------------------*/ } //Latest used Id this.RootNode.Transaction.Insert<byte[], long>(this.RootNode.DBreezeTableName, new byte[] { 1 }, maxId); }//eo func /// <summary> /// Internal /// </summary> /// <param name="nameIndexRow"></param> /// <param name="keyToRemove"></param> /// <returns>new nameIndexRow</returns> void RemoveOldNodeFromNameIndex(string oldNodeName, byte[] keyToRemove) { var oldNodeNameIndexRow = this.RootNode.nt3Write.Select<string, byte[]>(oldNodeName.ToLower()); if (oldNodeNameIndexRow.Exists) { byte[] val = oldNodeNameIndexRow.Value; byte[] prt = null; int i = 0; List<byte[]> keys = new List<byte[]>(); int size = 0; while ((prt = val.Substring(i, 16)) != null) { i += 16; if (prt._ByteArrayEquals(keyToRemove)) continue; size += 16; keys.Add(prt); } if (keys.Count > 0) { byte[] newVal = new byte[size]; i = 0; foreach (var key in keys) { newVal.CopyInside(i, key); i += 16; } this.RootNode.nt3Write.Insert<string, byte[]>(oldNodeName.ToLower(), newVal); } else { this.RootNode.nt3Write.RemoveKey<string>(oldNodeName.ToLower()); } } } /// <summary> /// <para>Adding children to the node</para> /// Table, storing data structure, must be in tran.SynchronizeTables list. /// Then transaction must be Committed in the end by the programmer. /// </summary> /// <param name="nodes">Nodes to add to current node</param> /// <param name="tran">Existing transaction. Table, storing data structure, must be in tran.SynchronizeTables list</param> /// <param name="maximalSpeed">set it to true to gain maximal saving speed</param> /// <returns>return node with setup parent id</returns> public DataAsTree AddNode(DataAsTree node) { CheckTransaction(); if (node == null) throw new Exception("Nodes is not supplied"); SetupWriteTables(); byte[] val = null; long maxId = this.RootNode.Transaction.Select<byte[], long>(this.RootNode.DBreezeTableName, new byte[] { 1 }).Value; bool skipToFillNameIndex = false; if (node.NodeId == 0) { //Insert node.ParentNodeId = this.NodeId; maxId++; node.NodeId = maxId; } else { //Update if (node.NodeId == node.ParentNodeId) throw new Exception("node.NodeId can't be equal to node.ParentNodeId"); var oldRow = this.RootNode.nt2Write.Select<byte[], byte[]>(node.ParentNodeId.To_8_bytes_array_BigEndian().Concat(node.NodeId.To_8_bytes_array_BigEndian())); if (oldRow.Exists) { var oldNode = SetupNodeFromRow(oldRow); if (!oldNode.NodeName.Equals(node.NodeName, StringComparison.OrdinalIgnoreCase)) RemoveOldNodeFromNameIndex(oldNode.NodeName, node.ParentNodeId.To_8_bytes_array_BigEndian().Concat(node.NodeId.To_8_bytes_array_BigEndian())); else skipToFillNameIndex = true; } else { if (maxId >= node.NodeId && maxId >= node.ParentNodeId) { //Such NodeId was probably deleted, and now wants to be reconnected. //We allow that } else { if (node.NodeId == node.ParentNodeId) throw new Exception("Supplied node.NodeId or node.ParentNodeId don't exist"); } } } //ParentNodeId(long),NodeId(long) byte[] key = node.ParentNodeId.To_8_bytes_array_BigEndian() .Concat(node.NodeId.To_8_bytes_array_BigEndian()); if (node.NodeContent != null) { node.ContentRef = this.RootNode.nt2Write.InsertDataBlock(node.ContentRef, node.NodeContent); } else node.ContentRef = null; val = SetupValueRowFromNode(node, 1); CopyInternals(node); this.RootNode.nt2Write.Insert<byte[], byte[]>(key, val); /*node.NodeName index support*/ if (!skipToFillNameIndex) { DBreeze.DataTypes.Row<string, byte[]> nodeNameIndexRow = null; byte[] btNodeNameIndex = null; nodeNameIndexRow = nt3Write.Select<string, byte[]>(node.NodeName.ToLower()); if (nodeNameIndexRow.Exists) btNodeNameIndex = nodeNameIndexRow.Value.Concat(key); else btNodeNameIndex = key; this.RootNode.nt3Write.Insert<string, byte[]>(node.NodeName.ToLower(), btNodeNameIndex); } /*-----------------------------*/ //Latest used Id this.RootNode.Transaction.Insert<byte[], long>(this.RootNode.DBreezeTableName, new byte[] { 1 }, maxId); return node; }//eo func /// <summary> /// GetContent of a node, /// </summary> /// <returns>null if content is absent</returns> public byte[] GetContent() { CheckTransaction(); if (this.ContentRef == null) return null; this.SetupReadTables(); return this.RootNode.nt2Read.SelectDataBlock(this.ContentRef); } /// <summary> /// Recursively reads out all children nodes starting from this recursiverly /// </summary> /// <returns></returns> public IEnumerable<DataAsTree> ReadOutAllChildrenNodesFromCurrentRecursively() { CheckTransaction(); foreach (var node in ReadOutNodes(this)) yield return node; } IEnumerable<DataAsTree> ReadOutNodes(DataAsTree node) { foreach (var tn in node.GetChildren()) { yield return tn; foreach (var inode in ReadOutNodes(tn)) yield return inode; } } ///// <summary> ///// ///// </summary> ///// <param name="tran"></param> //public void Test() //{ // this.SetupReadTables(); // byte[] val = null; // DataAsTree node = null; // foreach (var row in this.RootNode.nt2Read.SelectForward<byte[], byte[]>().Take(200)) // { // val = row.Value; // node = this.SetupNodeFromRow(row); // Console.WriteLine("Parent: " + node.ParentNodeId + "; Node: " + node.NodeId + "; " + node.NodeName); // } //} } }
37.796657
177
0.501032
[ "BSD-2-Clause" ]
ScriptBox99/DBreeze
DBreeze.UWP/DataStructures/DataAsTree.cs
27,140
C#
using System; using System.Management.Automation; using SnipeSharp.Models; using SnipeSharp.PowerShell.BindingTypes; namespace SnipeSharp.PowerShell.Cmdlets { /// <summary>Changes the properties of an existing Snipe-IT manufacturer.</summary> /// <remarks>The Set-Manufacturer cmdlet changes the properties of an existing Snipe-IT manufacturer object.</remarks> /// <example> /// <code>Set-Manufacturer -Name "Potato Peelers Inc." -SupportPhoneNumber '+1 (555) 555-5555'</code> /// <para>Changes the support phone number for manufacturer "Potato Peelers Inc." to "+1 (555) 555-5555".</para> /// </example> [Cmdlet(VerbsCommon.Set, nameof(Manufacturer))] [OutputType(typeof(Manufacturer))] public class SetManufacturer: SetObject<Manufacturer, ObjectBinding<Manufacturer>> { /// <summary> /// The new name for the manufacturer. /// </summary> [Parameter] [ValidateNotNullOrEmpty] public string NewName { get; set; } /// <summary> /// The updated url for the manufacturer's website. /// </summary> [Parameter] public Uri Url { get; set; } /// <summary> /// The updated uri of the image for the manufacturer. /// </summary> [Parameter] public Uri ImageUri { get; set; } /// <summary> /// The updated url for the manufacturer's support portal. /// </summary> [Parameter] public Uri SupportUrl { get; set; } /// <summary> /// The updated phone number for the manufacturer's support line. /// </summary> [Parameter] public string SupportPhoneNumber { get; set; } /// <summary> /// The updated email address to contact the manufacturer by for support. /// </summary> [Parameter] public string SupportEmailAddress { get; set; } /// <inheritdoc /> protected override bool PopulateItem(Manufacturer item) { if(MyInvocation.BoundParameters.ContainsKey(nameof(NewName))) item.Name = this.NewName; if(MyInvocation.BoundParameters.ContainsKey(nameof(Url))) item.Url = this.Url; if(MyInvocation.BoundParameters.ContainsKey(nameof(ImageUri))) item.ImageUri = this.ImageUri; if(MyInvocation.BoundParameters.ContainsKey(nameof(SupportUrl))) item.SupportUrl = this.SupportUrl; if(MyInvocation.BoundParameters.ContainsKey(nameof(SupportPhoneNumber))) item.SupportPhoneNumber = this.SupportPhoneNumber; if(MyInvocation.BoundParameters.ContainsKey(nameof(SupportEmailAddress))) item.SupportEmailAddress = this.SupportEmailAddress; return true; } } }
38.418919
122
0.622934
[ "MIT" ]
cofl/SnipeSharp
SnipeSharp.PowerShell/Cmdlets/Set/SetManufacturer.cs
2,843
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace MVVMLogin { public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); } } }
17.526316
47
0.675676
[ "MIT" ]
JPiantini98/IntecLoginMVVM
MVVMLogin/MVVMLogin/MVVMLogin/MainPage.xaml.cs
335
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.V20170601.Inputs { /// <summary> /// Network security rule. /// </summary> public sealed class SecurityRuleArgs : Pulumi.ResourceArgs { /// <summary> /// The network traffic is allowed or denied. Possible values are: 'Allow' and 'Deny'. /// </summary> [Input("access", required: true)] public InputUnion<string, Pulumi.AzureNative.Network.V20170601.SecurityRuleAccess> Access { get; set; } = null!; /// <summary> /// A description for this rule. Restricted to 140 chars. /// </summary> [Input("description")] public Input<string>? Description { get; set; } /// <summary> /// The destination address prefix. CIDR or destination IP range. Asterisk '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. /// </summary> [Input("destinationAddressPrefix")] public Input<string>? DestinationAddressPrefix { get; set; } [Input("destinationAddressPrefixes")] private InputList<string>? _destinationAddressPrefixes; /// <summary> /// The destination address prefixes. CIDR or destination IP ranges. /// </summary> public InputList<string> DestinationAddressPrefixes { get => _destinationAddressPrefixes ?? (_destinationAddressPrefixes = new InputList<string>()); set => _destinationAddressPrefixes = value; } /// <summary> /// The destination port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports. /// </summary> [Input("destinationPortRange")] public Input<string>? DestinationPortRange { get; set; } [Input("destinationPortRanges")] private InputList<string>? _destinationPortRanges; /// <summary> /// The destination port ranges. /// </summary> public InputList<string> DestinationPortRanges { get => _destinationPortRanges ?? (_destinationPortRanges = new InputList<string>()); set => _destinationPortRanges = value; } /// <summary> /// The direction of the rule. The direction specifies if rule will be evaluated on incoming or outgoing traffic. Possible values are: 'Inbound' and 'Outbound'. /// </summary> [Input("direction", required: true)] public InputUnion<string, Pulumi.AzureNative.Network.V20170601.SecurityRuleDirection> Direction { get; set; } = null!; /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> [Input("etag")] public Input<string>? Etag { get; set; } /// <summary> /// Resource ID. /// </summary> [Input("id")] public Input<string>? Id { get; set; } /// <summary> /// The name of the resource that is unique within a resource group. This name can be used to access the resource. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// The priority of the rule. The value can be between 100 and 4096. The priority number must be unique for each rule in the collection. The lower the priority number, the higher the priority of the rule. /// </summary> [Input("priority")] public Input<int>? Priority { get; set; } /// <summary> /// Network protocol this rule applies to. Possible values are 'Tcp', 'Udp', and '*'. /// </summary> [Input("protocol", required: true)] public InputUnion<string, Pulumi.AzureNative.Network.V20170601.SecurityRuleProtocol> Protocol { get; set; } = null!; /// <summary> /// The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. /// </summary> [Input("provisioningState")] public Input<string>? ProvisioningState { get; set; } /// <summary> /// The CIDR or source IP range. Asterisk '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. /// </summary> [Input("sourceAddressPrefix")] public Input<string>? SourceAddressPrefix { get; set; } [Input("sourceAddressPrefixes")] private InputList<string>? _sourceAddressPrefixes; /// <summary> /// The CIDR or source IP ranges. /// </summary> public InputList<string> SourceAddressPrefixes { get => _sourceAddressPrefixes ?? (_sourceAddressPrefixes = new InputList<string>()); set => _sourceAddressPrefixes = value; } /// <summary> /// The source port or range. Integer or range between 0 and 65535. Asterisk '*' can also be used to match all ports. /// </summary> [Input("sourcePortRange")] public Input<string>? SourcePortRange { get; set; } [Input("sourcePortRanges")] private InputList<string>? _sourcePortRanges; /// <summary> /// The source port ranges. /// </summary> public InputList<string> SourcePortRanges { get => _sourcePortRanges ?? (_sourcePortRanges = new InputList<string>()); set => _sourcePortRanges = value; } public SecurityRuleArgs() { } } }
40.020134
265
0.614959
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Network/V20170601/Inputs/SecurityRuleArgs.cs
5,963
C#
using System.Reflection; using Microsoft.Extensions.DependencyInjection; namespace Klinked.Cqrs { public static class CqrsBus { public static ICqrsBusBuilder UseAssembly(Assembly assembly, IServiceCollection services = null) { var builder = new CqrsBusBuilder(new CqrsOptionsBuilder(services)); return builder.UseAssembly(assembly); } public static ICqrsBusBuilder UseAssemblyFor<T>(IServiceCollection services = null) { return UseAssembly(typeof(T).Assembly, services); } } }
30.210526
104
0.682927
[ "MIT" ]
bryceklinker/dotnet-common
src/Klinked.Cqrs/CqrsBus.cs
574
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SchedulerService { public class Program { public static void Main ( string[] args ) { CreateHostBuilder ( args ).Build ().Run (); } public static IHostBuilder CreateHostBuilder ( string[] args ) => Host.CreateDefaultBuilder ( args ) .ConfigureWebHostDefaults ( webBuilder => { webBuilder.UseStartup<Startup> (); } ); } }
26.391304
67
0.744646
[ "MIT" ]
P-RCollaboration/Scheduler.Services
src/Services/SchedulerService/SchedulerService/Program.cs
607
C#
// -------------------------------------------------------------------------------------------- // Version: MPL 1.1/GPL 2.0/LGPL 2.1 // // The contents of this file are subject to the Mozilla Public License Version // 1.1 (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.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" basis, // WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License // for the specific language governing rights and limitations under the // License. // // <remarks> // Generated by IDLImporter from file nsIDOMElementCSSInlineStyle.idl // // You should use these interfaces when you access the COM objects defined in the mentioned // IDL/IDH file. // </remarks> // -------------------------------------------------------------------------------------------- namespace Gecko { using System; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Runtime.CompilerServices; /// <summary> /// The nsIDOMElementCSSInlineStyle interface allows access to the inline /// style information for elements. /// /// For more information on this interface please see /// http://www.w3.org/TR/DOM-Level-2-Style /// </summary> [ComImport()] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("99715845-95fc-4a56-aa53-214b65c26e22")] internal interface nsIDOMElementCSSInlineStyle { /// <summary> /// The nsIDOMElementCSSInlineStyle interface allows access to the inline /// style information for elements. /// /// For more information on this interface please see /// http://www.w3.org/TR/DOM-Level-2-Style /// </summary> [return: MarshalAs(UnmanagedType.Interface)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] nsIDOMCSSStyleDeclaration GetStyleAttribute(); } }
37.203704
95
0.653559
[ "MIT" ]
haga-rak/Freezer
Freezer/GeckoFX/__Core/Generated/nsIDOMElementCSSInlineStyle.cs
2,009
C#
using System; public static class TwoFer { public static string Speak(string input = null) { return $"One for {(input == null ? "you" : input)}, one for me."; } }
20.333333
73
0.595628
[ "MIT" ]
ErikSchierboom/csharp-analyzer
test/Exercism.Analyzers.CSharp.IntegrationTests/Solutions/TwoFer/Interpolation/Null/Block/TwoFer.cs
183
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("Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Tests")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cb003bb7-7c10-4b05-83a6-ec04f8a57d61")] // 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.351351
85
0.723749
[ "MIT" ]
TeamBrett/Angllisense
Tests/Properties/AssemblyInfo.cs
1,422
C#
using System; using System.Collections.Generic; using System.ComponentModel; namespace sakwa { public class IDomainObjectImpl : IBaseNodeImpl, IDomainObject { public IDomainObjectImpl() : base() { NodeType = eNodeType.DomainObject; } public IDomainObjectImpl(string name, eNodeType nodeType) : base(name, eNodeType.Expression) { NodeType = eNodeType.DomainObject; } List<string> IDomainObject.Methods { get { return _Methods; } } IDataPersistence IDomainObject.DataPersistence { get { return DataPersistence; } } protected override bool Persist(IPersistence persistence, ref ePersistence phase) { base.Persist(persistence, ref phase); switch (phase) { case ePersistence.Initial: persistence.UpsertField(Constants.Domain_Short_Name, _ShortName); string relativePath = persistence.GetRelativePath(_Model); persistence.UpsertField(Constants.Domain_Sub_Model, relativePath); persistence.UpsertFieldArray(Constants.Domain_Methods, _Methods.ToArray()); DataPersistence.Persist(persistence); break; } return true; } protected override bool Retrieve(IPersistence persistence, ref ePersistence phase) { base.Retrieve(persistence, ref phase); switch (phase) { case ePersistence.Initial: _ShortName = persistence.GetFieldValue(Constants.Domain_Short_Name, ""); string relativePath = persistence.GetFieldValue(Constants.Domain_Sub_Model, ""); _Model = persistence.GetFullPath(relativePath); if (_Model != "") Tree.AddSubModel(this); _Methods.Clear(); _Methods.AddRange(persistence.GetFieldValues(Constants.Domain_Methods, "")); DataPersistence.Retrieve(persistence); break; } return true; } protected override bool IsReadOnly() { return _Model != ""; } protected override NodeEqualityCollection Compare(IBaseNode compareWith, eCompareMode mode) { NodeEqualityCollection result = base.Compare(compareWith, mode); if(!result.HasEqualityType(eNodeEquality.basetype)) { if (this._Model != (compareWith as IDomainObjectImpl).FullModelName) result.Add(eDomainObjectEquality.submodel, false, false, "Different sub models"); if (compareWith is EnumVariableImpl) { List<string> equal = new List<string>(); foreach (string elem in (compareWith as IDomainObject).Methods) if (_Methods.Contains(elem)) equal.Add(elem); if (_Methods.Count != equal.Count || (compareWith as IDomainObject).Methods.Count != equal.Count) result.Add(eDomainObjectEquality.methods, false, false, "Different number of methods"); } } return result; } protected bool isEqual(List<string> list, string[] input) { if (input.Length != list.Count) return false; for (int i = 0; i < input.Length; i++) if (input[i] != list[i]) return false; return true; } protected override string GetName() { if (_ShortName != "") return _ShortName; string result = _Name; IBaseNode parent = Parent; while(parent != null && parent.NodeType == eNodeType.DomainObject) { string[] parentNames = (parent as IBaseNode).Name.Split(new char[] { '.'}); result = parentNames[parentNames.Length -1] + "." + result; parent = parent.Parent; } return result; } protected string _ShortName = ""; protected string _Model = ""; protected List<string> _Methods = new List<string>(); protected IDataPersistence DataPersistence = new IDataPersistenceImpl(); [Browsable(false)] public string FullModelName { get { return _Model; } set { _Model = value; } } } }
33.452555
117
0.555095
[ "Apache-2.0" ]
sakwa-im/design-studio
sakwa-core/implementation/nodes/IDomainObjectImpl.cs
4,585
C#
//----------------------------------------------------------------------------- // Filename: RTPPacket.cs // // Description: Encapsulation of an RTP packet. // // Author(s): // Aaron Clauson (aaron@sipsorcery.com) // // History: // 24 May 2005 Aaron Clauson Created, Dublin, Ireland. // 11 Aug 2019 Aaron Clauson Added full license header. // // License: // BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file. //----------------------------------------------------------------------------- using System; namespace SIPSorcery.Net { public class RTPPacket { public RTPHeader Header; public byte[] Payload; public RTPPacket() { Header = new RTPHeader(); } public RTPPacket(int payloadSize) { Header = new RTPHeader(); Payload = new byte[payloadSize]; } public RTPPacket(byte[] packet) { Header = new RTPHeader(packet); Payload = new byte[packet.Length - Header.Length]; Array.Copy(packet, Header.Length, Payload, 0, Payload.Length); } public byte[] GetBytes() { byte[] header = Header.GetBytes(); byte[] packet = new byte[header.Length + Payload.Length]; Array.Copy(header, packet, header.Length); Array.Copy(Payload, 0, packet, header.Length, Payload.Length); return packet; } private byte[] GetNullPayload(int numBytes) { byte[] payload = new byte[numBytes]; for (int byteCount = 0; byteCount < numBytes; byteCount++) { payload[byteCount] = 0xff; } return payload; } } }
25.911765
79
0.50454
[ "MIT" ]
GB28181/GB28181.Platform2016
sipsorcery/src/net/RTP/RTPPacket.cs
1,762
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; using DiscordChannelRolesManager.Helpers.TypeReaders; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace DiscordChannelRolesManager.Services { public class CommandHandler { private readonly CommandService _commands; private readonly DiscordSocketClient _client; private readonly IServiceProvider _services; private readonly ILogger<CommandHandler> _logger; public CommandHandler( CommandService commands, IServiceProvider services, ILogger<CommandHandler> logger, DiscordSocketClient client ) { _commands = commands; _services = services; _logger = logger; _client = client; _commands.CommandExecuted += CommandExecutedAsync; _client.MessageReceived += MessageReceivedAsync; _client.ReactionAdded += ReactionAdded; _client.ReactionRemoved += ReactionRemoved; } public async Task InitializeAsync() { _commands.AddTypeReader(typeof(IDictionary<string, string>), new DictionaryTypeReader()); await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services); } private async Task ReactionRemoved( Cacheable<IUserMessage, ulong> cachedMessage, ISocketMessageChannel originChannel, SocketReaction reaction ) { IUserMessage message = await cachedMessage.GetOrDownloadAsync(); if (message.Author.IsBot && message.Author.DiscriminatorValue == 2666) { var dd = message.Embeds.First().Description .Split("\n") .Select( line => { var l = line[2..].Split(" -> "); return new KeyValuePair<string, string>(l[0], l[1]); } ) .ToDictionary(pair => pair.Key, pair => pair.Value); if (dd.TryGetValue(reaction.Emote.Name, out var s)) { var context = new CommandContext( _services.GetService<DiscordSocketClient>(), message ); var gu = await context.Guild.GetUserAsync(reaction.UserId); var role = context.Guild.Roles.First(r => r.Name == s); await gu.RemoveRoleAsync(role); } } } private async Task ReactionAdded( Cacheable<IUserMessage, ulong> cachedMessage, ISocketMessageChannel originChannel, SocketReaction reaction ) { IUserMessage message = await cachedMessage.GetOrDownloadAsync(); if (message.Author.IsBot && !reaction.User.Value.IsBot && message.Author.DiscriminatorValue == 2666) { var dd = message.Embeds.First().Description .Split("\n") .Select( line => { var l = line[2..].Split(" -> "); return new KeyValuePair<string, string>(l[0], l[1]); } ) .ToDictionary(pair => pair.Key, pair => pair.Value); if (dd.TryGetValue(reaction.Emote.Name, out var s)) { var context = new CommandContext( _services.GetService<DiscordSocketClient>(), message ); var gu = await context.Guild.GetUserAsync(reaction.UserId); var role = context.Guild.Roles.First(r => r.Name == s); await gu.AddRoleAsync(role); } } } private async Task MessageReceivedAsync(SocketMessage rawMessage) { if (rawMessage is not SocketUserMessage {Source: MessageSource.User} message) return; _logger.LogDebug($"MessageReceivedHandler {rawMessage.Content}"); var argPos = 0; if (!message.HasCharPrefix('!', ref argPos)) return; var context = new SocketCommandContext(_client, message); var result = await _commands.ExecuteAsync(context, argPos, _services); if (result.IsSuccess) { _logger.LogInformation($"MessageReceivedHandler {result}"); } } private async Task CommandExecutedAsync(Optional<CommandInfo> command, ICommandContext context, IResult result) { if (!command.IsSpecified || result.IsSuccess) return; _logger.LogError($"CommandExecutedAsync {result}"); await context.Channel.SendMessageAsync($"error: {result}"); } } }
38.559441
119
0.514509
[ "MIT" ]
jjzajac/DiscordChannelRolesManager
DiscordChannelRolesManager/Services/CommandHandler.cs
5,514
C#
 namespace MultiTenancy.Northwind.Forms { using Serenity.ComponentModel; using System; using System.ComponentModel; [ColumnsScript("Northwind.Shipper")] [BasedOnRow(typeof(Entities.ShipperRow), CheckNames = true)] public class ShipperColumns { [EditLink, DisplayName("Db.Shared.RecordId"), AlignRight] public Int32 ShipperID { get; set; } [EditLink, Width(300)] public String CompanyName { get; set; } [Width(150)] public String Phone { get; set; } } }
29.052632
66
0.628623
[ "Unlicense" ]
pratikto/MultiTenancy
MultiTenancy/MultiTenancy.Web/Modules/Northwind/Shipper/ShipperColumns.cs
554
C#
using System.Collections.Generic; namespace USchedule.Shared.Models { public class InstituteSharedModel { public string ShortTitle { get; set; } public IList<GroupSharedModel> Groups { get; set; } public InstituteSharedModel() { Groups = new List<GroupSharedModel>(); } } }
21.8125
59
0.60745
[ "MIT" ]
stenvix/uschedule-api
src/USchedule.Shared/Models/InstituteSharedModel.cs
351
C#
using System.ComponentModel.DataAnnotations; namespace PutProduct.Model { public class CommentModel { public int Id { get; set; } [Required] public string Message { get; set; } [Required] public int ProductId { get; set; } public string? Name { get; set; } public DateTime CommentDateTime { get; set; } } }
18.571429
53
0.579487
[ "Apache-2.0" ]
mohamedabotir/PutProduct
PutProduct/Model/CommentModel.cs
392
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace DotNetOracleLogger { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // TODO: response as json format. } } }
29.103448
70
0.702607
[ "MIT" ]
AppantasyArthurLai/.NetOracleLogger
Global.asax.cs
846
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; using Raven.Client.Documents; using Raven.Client.Documents.Linq; using Raven.Client.Documents.Queries.Facets; using Digitalisert.Models; namespace Digitalisert.Controllers { [Route("api/[controller]")] public class ResourceController : Controller { private readonly IDocumentStore _store; public ResourceController() { _store = DocumentStoreHolder.Store; } [HttpGet] public IEnumerable<object> Get([FromQuery] Models.ResourceModel.Resource[] resources) { using(var session = _store.OpenSession()) { var query = session.Advanced.DocumentQuery<ResourceModel.Resource, ResourceModel.ResourceIndex>(); query = ResourceModel.QueryByExample(query, resources); return query.ToQueryable().ProjectInto<ResourceModel.Resource>().Take(100).ToList(); } } [HttpGet("{context}/{*id}")] public IEnumerable<object> Resource(string context, string id) { using(var session = _store.OpenSession()) { var query = session .Query<ResourceModel.Resource, ResourceModel.ResourceIndex>() .Include<ResourceModel.Resource>(r => r.Properties.SelectMany(p => p.Resources).SelectMany(re => re.Source)) .Where(r => r.Context == context && r.ResourceId == id); foreach(var resource in query.ProjectInto<ResourceModel.Resource>()) { yield return resource; } } } [HttpGet("Facet")] public Dictionary<string, FacetResult> Facet([FromQuery] Models.ResourceModel.Resource[] resources) { using(var session = _store.OpenSession()) { var query = session.Advanced.DocumentQuery<ResourceModel.Resource, ResourceModel.ResourceIndex>(); query = ResourceModel.QueryByExample(query, resources); return query .AggregateBy(ResourceModel.Facets) .Execute(); } } [HttpGet("Deploy")] public void Deploy() { new ResourceModel.ResourceIndex().Execute(DocumentStoreHolder.Store); } } }
33.824324
129
0.572113
[ "MIT" ]
askildolsen/digitalisert
Controllers/ResourceController.cs
2,503
C#
using System.Threading.Tasks; using Volo.Abp.Data; using Volo.Abp.DependencyInjection; using Volo.Abp.Guids; using Volo.Abp.MultiTenancy; namespace Bamboo.Employee { public class EmployeeDataSeedContributor : IDataSeedContributor, ITransientDependency { private readonly IGuidGenerator _guidGenerator; private readonly ICurrentTenant _currentTenant; public EmployeeDataSeedContributor( IGuidGenerator guidGenerator, ICurrentTenant currentTenant) { _guidGenerator = guidGenerator; _currentTenant = currentTenant; } public Task SeedAsync(DataSeedContext context) { /* Instead of returning the Task.CompletedTask, you can insert your test data * at this point! */ using (_currentTenant.Change(context?.TenantId)) { return Task.CompletedTask; } } } }
28.058824
89
0.647799
[ "MIT" ]
BlazorHub/bamboomodules
Bamboo.Employee/test/Bamboo.Employee.TestBase/EmployeeDataSeedContributor.cs
956
C#
namespace _09.BoolLibrary { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; public class BoolLibrary { public const string inputFilePath = "input.txt"; public const string outputFilePath = "output.txt"; static void Main() { using (StreamWriter writer = File.CreateText(outputFilePath)) { using (StreamReader reader = new StreamReader(new FileStream(inputFilePath, FileMode.Open))) { while (!reader.EndOfStream) { int n = int.Parse(reader.ReadLine()); List<Book> library = new List<Book>(); for (int i = 0; i < n; i++) { string[] input = reader.ReadLine().Split(); library.Add( new Book( input[0], input[1], input[2], DateTime.ParseExact(input[3], "dd.MM.yyyy", CultureInfo.InvariantCulture), input[4], decimal.Parse(input[5]))); } var dict = new Dictionary<string, decimal>(); foreach (var book in library) { if (!dict.ContainsKey(book.Author)) { dict.Add(book.Author, book.Price); } else { dict[book.Author] = (dict[book.Author] + book.Price); } } dict .OrderByDescending(x => x.Value) .ThenBy(x => x.Key) .ToList() .ForEach(x => writer.WriteLine($"{x.Key} -> {x.Value:F2}")); } } } } } public class Book { // title, author, publisher, release date(in dd.MM.yyyy format), ISBN-number and price. public string Title { get; set; } public string Author { get; set; } public string Publisher { get; set; } public DateTime ReleaseDate { get; set; } public string ISBN { get; set; } public decimal Price { get; set; } public Book(string title, string author, string publisher, DateTime releaseDate, string ISBN, decimal price) { this.Title = title; this.Author = author; this.Publisher = publisher; this.ReleaseDate = releaseDate; this.ISBN = ISBN; this.Price = price; } } }
33.522222
116
0.411999
[ "MIT" ]
Steffkn/SoftUni
02.TechModule-09.2017/Fundamentals/11.FilesAndExceptions/09.BookLibrary/BoolLibrary.cs
3,019
C#
using UnityEngine; namespace FirstGearGames.Utilities.Maths { public class FrameRateCalculator { #region Private. /// <summary> /// Time used to generate Frames. /// </summary> private float _timePassed = 0f; /// <summary> /// Frames performed in TimePassed. Float is used to reduce casting. /// </summary> private float _frames = 0; #endregion #region Const. /// <summary> /// How many frames to pass before slicing calculation values. /// </summary> private const int RESET_FRAME_COUNT = 60; /// <summary> /// Percentage to slice calculation values by. Higher percentages result in smoother frame rate adjustments. /// </summary> private const float CALCULATION_SLICE_PERCENT = 0.7f; #endregion /// <summary> /// Gets the current frame rate. /// </summary> /// <returns></returns> public int GetIntFrameRate() { return Mathf.CeilToInt((_frames / _timePassed)); } /// <summary> /// Gets the current frame rate. /// </summary> /// <returns></returns> public float GetFloatFrameRate() { return (_frames / _timePassed); } /// <summary> /// Updates frame count and time passed. /// </summary> public bool Update(float unscaledDeltaTime) { _timePassed += unscaledDeltaTime; _frames++; if (_frames > RESET_FRAME_COUNT) { _frames *= CALCULATION_SLICE_PERCENT; _timePassed *= CALCULATION_SLICE_PERCENT; return true; } else { return false; } } } }
27.014493
116
0.521459
[ "Apache-2.0" ]
Levalego/SoulGate
Arena Game/Assets/Plugin/FirstGearGames/Scripts/Utilities/FrameRateCalculator.cs
1,866
C#
using System; using System.Collections.Generic; using System.Text; using ConsoleApp236.Layouts; namespace ConsoleApp236.Factories { public class LayoutFactory { private ILayout layout; public ILayout CreateLayout(string type) { switch (type) { case "SimpleLayout": layout = new SimpleLayout(); break; case "XmlLayout": layout = new XmlLayout(); break; } return layout; } } }
21.555556
48
0.498282
[ "MIT" ]
grekssi/Softuni-Courses
SoftUni/01. .NET Courses/04. C# OOP/07. SOLID/Assignment/Factories/LayoutFactory.cs
584
C#
using System.Windows; using MessageBox = Xceed.Wpf.Toolkit.MessageBox; using ThemeHelper2 = Catel.ThemeHelper; namespace PresetMagician.Views { /// <summary> /// Interaktionslogik für MainWindow.xaml /// </summary> public partial class ThemeControlsWindow { public ThemeControlsWindow() { InitializeComponent(); } private void Button_Click_1(object sender, RoutedEventArgs e) { MessageBox mb = new MessageBox(); mb.Caption = "Caption"; mb.Text = "Text"; mb.ShowDialog(); } private void Button_Click_2(object sender, RoutedEventArgs e) { } } }
24.172414
69
0.594864
[ "MIT" ]
PresetMagician/PresetMagician
PresetMagician/Views/ThemeControlsWindow.xaml.cs
702
C#
using System; namespace L._01.StudentInfoV02 { class Program { static void Main(string[] args) { //"Name: {student name}, Age: {student age}, Grade: {student grade}" string studentName = Console.ReadLine(); int age = int.Parse(Console.ReadLine()); double averageGrade = double.Parse(Console.ReadLine()); Console.WriteLine($"Name: {studentName}, Age: {age}, Grade: {averageGrade:f2}"); } } }
28.764706
92
0.572597
[ "MIT" ]
denismironov97/Software-Engineering-SoftUni
C# Fundamentals/BasicSyntaxConditionalStatementsAndLoops/L.01.StudentInfoV02/Program.cs
491
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("PairsMatching")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PairsMatching")] [assembly: AssemblyCopyright("Copyright © 2008")] [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("311e041f-3489-4742-972d-e56d0bc36984")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.382353
85
0.731707
[ "MIT" ]
aazhbd/PairsMatching
PairsMatching/Properties/AssemblyInfo.cs
1,274
C#
using Amazon.JSII.Runtime.Deputy; #pragma warning disable CS0672,CS0809,CS1591 namespace Amazon.JSII.Tests.CalculatorNamespace { [JsiiTypeProxy(nativeType: typeof(IStableStruct), fullyQualifiedName: "jsii-calc.StableStruct")] internal sealed class StableStructProxy : DeputyBase, Amazon.JSII.Tests.CalculatorNamespace.IStableStruct { private StableStructProxy(ByRefValue reference): base(reference) { } [JsiiProperty(name: "readonlyProperty", typeJson: "{\"primitive\":\"string\"}")] public string ReadonlyProperty { get => GetInstanceProperty<string>(); } } }
30.857143
109
0.692901
[ "Apache-2.0" ]
digitalsanctum/jsii
packages/jsii-pacmak/test/expected.jsii-calc/dotnet/Amazon.JSII.Tests.CalculatorPackageId/Amazon/JSII/Tests/CalculatorNamespace/StableStructProxy.cs
648
C#
namespace OnlyT.Models { public class LanguageItem { public string LanguageId { get; set; } public string LanguageName { get; set; } } }
16.7
48
0.60479
[ "MIT" ]
Vikingo80/OnlyT
OnlyT/Models/LanguageItem.cs
169
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace TypeProviderInCSharp { static class Helpers { public static void TraceCall() { //var st = new StackTrace(); //var caller_sf = st.GetFrames()[1]; //var caller_method = caller_sf.GetMethod(); //// var caller_params = caller_method.GetParameters(); //Console.WriteLine("Called {0}.{1}.{2}", caller_method.DeclaringType.Namespace, caller_method.DeclaringType.Name, caller_method.Name); } } }
28.227273
147
0.626409
[ "Apache-2.0" ]
AliBaghernejad/visualfsharp
tests/fsharpqa/Source/TypeProviders/Events/TestTP/Helpers.cs
623
C#