content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; namespace SmtpServer { public static class TaskExtensions { /// <summary> /// Configures an awaiter used to await this <see cref="T:System.Threading.Tasks.Task`1" />. /// </summary> /// <param name="task">The task to modify the capture context on.</param> /// <returns>An object used to await this task.</returns> public static ConfiguredTaskAwaitable ReturnOnAnyThread(this Task task) { if (task == null) { throw new ArgumentNullException(nameof(task)); } return task.ConfigureAwait(false); } /// <summary> /// Configures an awaiter used to await this <see cref="T:System.Threading.Tasks.Task`1" />. /// </summary> /// <typeparam name="TResult">The result of the Task.</typeparam> /// <param name="task">The task to modify the capture context on.</param> /// <returns>An object used to await this task.</returns> public static ConfiguredTaskAwaitable<TResult> ReturnOnAnyThread<TResult>(this Task<TResult> task) { if (task == null) { throw new ArgumentNullException(nameof(task)); } return task.ConfigureAwait(false); } /// <summary> /// Configures the task to stop waiting when the cancellation has been requested. /// </summary> /// <param name="task">The task to wait for.</param> /// <param name="cancellationToken">The cancellation token to watch.</param> /// <returns>The original task.</returns> public static async Task WithCancellation(this Task task, CancellationToken cancellationToken) { var tcs = new TaskCompletionSource<bool>(); using (cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs)) { if (task != await Task.WhenAny(task, tcs.Task).ConfigureAwait(false)) { throw new OperationCanceledException(cancellationToken); } } await task.ConfigureAwait(false); } /// <summary> /// Configures the task to stop waiting when the cancellation has been requested. /// </summary> /// <typeparam name="T">The return type of the task.</typeparam> /// <param name="task">The task to wait for.</param> /// <param name="cancellationToken">The cancellation token to watch.</param> /// <returns>The original task.</returns> public static async Task<T> WithCancellation<T>(this Task<T> task, CancellationToken cancellationToken) { var tcs = new TaskCompletionSource<bool>(); using (cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs)) { if (task != await Task.WhenAny(task, tcs.Task).ConfigureAwait(false)) { throw new OperationCanceledException(cancellationToken); } } return await task.ConfigureAwait(false); } /// <summary> /// Configures the task to stop waiting when the cancellation has been requested. /// </summary> /// <typeparam name="T">The return type of the task.</typeparam> /// <param name="task">The task to wait for.</param> /// <param name="timeout">The timeout to apply to the task.</param> /// <param name="cancellationToken">The cancellation token to watch.</param> /// <returns>The original task.</returns> public static async Task<T> WithTimeout<T>(this Task<T> task, TimeSpan timeout, CancellationToken cancellationToken) { if (task != await Task.WhenAny(task, Task.Delay(timeout, cancellationToken))) { if (cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(cancellationToken); } throw new TimeoutException(); } return await task.ConfigureAwait(false); } } }
40.299065
124
0.588126
[ "MIT" ]
AdomasL/SmtpServer1
Src/SmtpServer/Extensions/TaskExtensions.cs
4,314
C#
using System; using System.Collections.Generic; using System.Linq; using backend.Models; using Microsoft.EntityFrameworkCore; namespace backend.DAL { public class BoxLocationDataAccess { private BatmanContext _context; public BoxLocationDataAccess(BatmanContext context) { _context = context; } public List<BoxLocation> GetBoxLocations() { return _context.BoxLocations.Include(a => a.Records).ThenInclude(r => r.First().AcousticData).ToList(); } public BoxLocation GetBoxLocationById(int boxLocationId) { return _context.BoxLocations.Where(b => b.Id == boxLocationId).FirstOrDefault(); } public void AddBoxLocation(BoxLocation boxLocation) { _context.BoxLocations.Add(boxLocation); _context.SaveChangesAsync(); } internal IEnumerable<BoxLocation> GetBoxNotFinishLocations() { return _context.BoxLocations.Where(a => a.EndDay == null).ToList(); } } }
27.615385
115
0.632312
[ "MIT", "Unlicense" ]
wearespacey/Batman
backend/DAL/BoxLocationDataAccess.cs
1,077
C#
using System.Reflection; 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("Bloom.Analytics.ArtistModule")] [assembly: AssemblyDescription("Bloom Analytics artist Prism module.")] [assembly: AssemblyConfiguration("")] [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("6eaaf2bb-9090-421b-ae89-0e026113beab")]
43.6
84
0.77867
[ "Apache-2.0" ]
RobDixonIII/Bloom
Analytics/Bloom.Analytics.Modules/Bloom.Analytics.Modules.ArtistModule/Properties/AssemblyInfo.cs
874
C#
/******************************************************************************* * Copyright 2009-2016 Amazon Services. 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://aws.amazon.com/apache2.0 * 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. ******************************************************************************* * Cancel Fulfillment Order Request * API Version: 2010-10-01 * Library Version: 2016-10-19 * Generated: Wed Oct 19 08:37:54 PDT 2016 */ using System; using System.Xml; using System.Xml.Serialization; using Claytondus.AmazonMWS.Runtime; namespace Claytondus.AmazonMWS.FbaOutbound.Model { [XmlType(Namespace = "http://mws.amazonaws.com/FulfillmentOutboundShipment/2010-10-01/")] [XmlRoot(Namespace = "http://mws.amazonaws.com/FulfillmentOutboundShipment/2010-10-01/", IsNullable = false)] public class CancelFulfillmentOrderRequest : AbstractMwsObject { private string _sellerId; private string _mwsAuthToken; private string _marketplace; private string _sellerFulfillmentOrderId; /// <summary> /// Gets and sets the SellerId property. /// </summary> [XmlElement(ElementName = "SellerId")] public string SellerId { get { return this._sellerId; } set { this._sellerId = value; } } /// <summary> /// Sets the SellerId property. /// </summary> /// <param name="sellerId">SellerId property.</param> /// <returns>this instance.</returns> public CancelFulfillmentOrderRequest WithSellerId(string sellerId) { this._sellerId = sellerId; return this; } /// <summary> /// Checks if SellerId property is set. /// </summary> /// <returns>true if SellerId property is set.</returns> public bool IsSetSellerId() { return this._sellerId != null; } /// <summary> /// Gets and sets the MWSAuthToken property. /// </summary> [XmlElement(ElementName = "MWSAuthToken")] public string MWSAuthToken { get { return this._mwsAuthToken; } set { this._mwsAuthToken = value; } } /// <summary> /// Sets the MWSAuthToken property. /// </summary> /// <param name="mwsAuthToken">MWSAuthToken property.</param> /// <returns>this instance.</returns> public CancelFulfillmentOrderRequest WithMWSAuthToken(string mwsAuthToken) { this._mwsAuthToken = mwsAuthToken; return this; } /// <summary> /// Checks if MWSAuthToken property is set. /// </summary> /// <returns>true if MWSAuthToken property is set.</returns> public bool IsSetMWSAuthToken() { return this._mwsAuthToken != null; } /// <summary> /// Gets and sets the Marketplace property. /// </summary> [XmlElement(ElementName = "Marketplace")] public string Marketplace { get { return this._marketplace; } set { this._marketplace = value; } } /// <summary> /// Sets the Marketplace property. /// </summary> /// <param name="marketplace">Marketplace property.</param> /// <returns>this instance.</returns> public CancelFulfillmentOrderRequest WithMarketplace(string marketplace) { this._marketplace = marketplace; return this; } /// <summary> /// Checks if Marketplace property is set. /// </summary> /// <returns>true if Marketplace property is set.</returns> public bool IsSetMarketplace() { return this._marketplace != null; } /// <summary> /// Gets and sets the SellerFulfillmentOrderId property. /// </summary> [XmlElement(ElementName = "SellerFulfillmentOrderId")] public string SellerFulfillmentOrderId { get { return this._sellerFulfillmentOrderId; } set { this._sellerFulfillmentOrderId = value; } } /// <summary> /// Sets the SellerFulfillmentOrderId property. /// </summary> /// <param name="sellerFulfillmentOrderId">SellerFulfillmentOrderId property.</param> /// <returns>this instance.</returns> public CancelFulfillmentOrderRequest WithSellerFulfillmentOrderId(string sellerFulfillmentOrderId) { this._sellerFulfillmentOrderId = sellerFulfillmentOrderId; return this; } /// <summary> /// Checks if SellerFulfillmentOrderId property is set. /// </summary> /// <returns>true if SellerFulfillmentOrderId property is set.</returns> public bool IsSetSellerFulfillmentOrderId() { return this._sellerFulfillmentOrderId != null; } public override void ReadFragmentFrom(IMwsReader reader) { _sellerId = reader.Read<string>("SellerId"); _mwsAuthToken = reader.Read<string>("MWSAuthToken"); _marketplace = reader.Read<string>("Marketplace"); _sellerFulfillmentOrderId = reader.Read<string>("SellerFulfillmentOrderId"); } public override void WriteFragmentTo(IMwsWriter writer) { writer.Write("SellerId", _sellerId); writer.Write("MWSAuthToken", _mwsAuthToken); writer.Write("Marketplace", _marketplace); writer.Write("SellerFulfillmentOrderId", _sellerFulfillmentOrderId); } public override void WriteTo(IMwsWriter writer) { writer.Write("http://mws.amazonaws.com/FulfillmentOutboundShipment/2010-10-01/", "CancelFulfillmentOrderRequest", this); } public CancelFulfillmentOrderRequest (string sellerId,string sellerFulfillmentOrderId) : base() { this._sellerId = sellerId; this._sellerFulfillmentOrderId = sellerFulfillmentOrderId; } public CancelFulfillmentOrderRequest() : base() { } } }
34.919786
132
0.597856
[ "Apache-2.0" ]
claytondus/Claytondus.AmazonMWS
Claytondus.AmazonMWS.FbaOutbound/Model/CancelFulfillmentOrderRequest.cs
6,530
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("15_NeighbourWars")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("15_NeighbourWars")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("4fc18278-fe93-43eb-9482-60f647795db0")] // 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")]
37.972973
84
0.746619
[ "MIT" ]
nellypeneva/SoftUniProjects
01_ProgrFundamentalsMay/06_Conditional-Statements-and-Loops-Exercises/15_NeighbourWars/Properties/AssemblyInfo.cs
1,408
C#
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; using System.Text; using System.Web.UI.HtmlControls; using ClosedXML; using System.Data.SqlClient; using ClosedXML.Excel; public partial class RemittanceRepo : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { try { if (!IsPostBack) { locationCls obj = new locationCls(); DataTable dt = obj.getVirtualLocation("2"); virtualLocation.DataSource = dt; virtualLocation.DataBind(); } else { ScriptManager.RegisterClientScriptBlock(this, GetType(), "mykey", "firedtSearch();", true); } } catch (Exception ex) { RecordExceptionCls obj = new RecordExceptionCls(); obj.recordException(ex); } } public void BindData() { try { payment_reportCls obj = new payment_reportCls(); DataTable dt = obj.BindRemittance(virtualLocation.SelectedValue); rpt_salesidnotexits.DataSource = dt; rpt_salesidnotexits.DataBind(); //// } catch (Exception ex) { RecordExceptionCls obj = new RecordExceptionCls(); obj.recordException(ex); } } protected void rpt_salesidnotexits_ItemDataBound(object sender, RepeaterItemEventArgs e) { try { object IGST = 0; object SGST = 0; object CGSt = 0; object selling_price =0; object cp = 0; object logictic = 0; object spincgst = 0; object spexcgst = 0; object chnellcommsion = 0; object Utax = 0; object percent = 0; object gateway = 0; object mis = 0; decimal DectIncgst = 0; decimal Dectexcgst = 0; decimal TotalDectIncgst = 0; decimal TotalDectexcgst = 0; decimal SetllAmtinc = 0; decimal SetllAmtexc = 0; decimal SetllAmtincper = 0; decimal SetllAmtexcper = 0; decimal Netpro = 0; decimal Netper = 0; decimal TOtalGst = 0; IGST =((DataRowView)e.Item.DataItem)["totIGST"].ToString().Equals("") ? "0" : ((DataRowView)e.Item.DataItem)["totIGST"].ToString(); SGST = ((DataRowView)e.Item.DataItem)["totSGST"].ToString().Equals("") ? "0" : ((DataRowView)e.Item.DataItem)["totSGST"].ToString(); CGSt = ((DataRowView)e.Item.DataItem)["totCGST"].ToString().Equals("") ? "0" : ((DataRowView)e.Item.DataItem)["totCGST"].ToString(); cp = ((DataRowView)e.Item.DataItem)["cp"].ToString().Equals("") ? "0" : ((DataRowView)e.Item.DataItem)["cp"].ToString(); chnellcommsion = ((DataRowView)e.Item.DataItem)["channel_commsion"].ToString().Equals("") ? "0" : ((DataRowView)e.Item.DataItem)["channel_commsion"].ToString(); gateway = ((DataRowView)e.Item.DataItem)["Channel_Gateway"].ToString().Equals("") ? "0" : ((DataRowView)e.Item.DataItem)["Channel_Gateway"].ToString(); selling_price = ((DataRowView)e.Item.DataItem)["sys_sp"].ToString().Equals("") ? "0" : ((DataRowView)e.Item.DataItem)["sys_sp"].ToString(); spincgst = ((DataRowView)e.Item.DataItem)["spincgst"].ToString().Equals("") ? "0" : ((DataRowView)e.Item.DataItem)["spincgst"].ToString(); spexcgst = ((DataRowView)e.Item.DataItem)["spexcgst"].ToString().Equals("") ? "0" : ((DataRowView)e.Item.DataItem)["spexcgst"].ToString(); logictic = ((DataRowView)e.Item.DataItem)["VL_Logistics"].ToString().Equals("") ? "0" : ((DataRowView)e.Item.DataItem)["VL_Logistics"].ToString(); Utax = ((DataRowView)e.Item.DataItem)["utax"].ToString().Equals("") ? "0" : ((DataRowView)e.Item.DataItem)["utax"].ToString(); percent = ((DataRowView)e.Item.DataItem)["percentage"].ToString().Equals("") ? "0" : ((DataRowView)e.Item.DataItem)["percentage"].ToString(); TOtalGst = (Convert.ToDecimal(selling_price) * Convert.ToDecimal(percent)) / 100; Label lbltotdecinc = e.Item.FindControl("lbltotdecinc") as Label; Label lbltotdecexc = e.Item.FindControl("lbltotdecexc") as Label; Label setamtinc = e.Item.FindControl("setamtinc") as Label; Label setperinc = e.Item.FindControl("setperinc") as Label; Label setamtexc = e.Item.FindControl("setamtexc") as Label; Label setperexc = e.Item.FindControl("setperexc") as Label; Label netpro = e.Item.FindControl("netpro") as Label; Label lblnetper = e.Item.FindControl("lblnetper") as Label; //Total Deduction Inc(GST) DectIncgst = Math.Abs(Convert.ToDecimal(selling_price)) - Math.Abs(Convert.ToDecimal(chnellcommsion)) - Math.Abs(Convert.ToDecimal(logictic))-Math.Abs(Convert.ToDecimal(gateway)); TotalDectIncgst= Math.Round(Convert.ToDecimal(selling_price) - Convert.ToDecimal(DectIncgst),2); //Total Deduction exc(GST) Dectexcgst = Math.Abs(Convert.ToDecimal(selling_price)) - Math.Abs(Convert.ToDecimal(chnellcommsion)) - Math.Abs(Convert.ToDecimal(logictic)) - Math.Abs(Convert.ToDecimal(TOtalGst)); TotalDectexcgst = Math.Round(Convert.ToDecimal(selling_price) - Convert.ToDecimal(Dectexcgst), 2); //Settled Amount (sales_price - total deduction -cp) SetllAmtinc = Math.Round(Convert.ToDecimal(selling_price) - TotalDectIncgst - Convert.ToDecimal(cp), 2);//incgst SetllAmtexc = Math.Round(Convert.ToDecimal(selling_price) - TotalDectexcgst - Convert.ToDecimal(cp),2);//exc gst try { SetllAmtincper = Math.Round((SetllAmtinc / Convert.ToDecimal(selling_price)) * 100, 2); //Math.Round((SetllAmtinc / Convert.ToDecimal(spincgst)) * 100, 2); } catch (Exception ex) { SetllAmtincper = 0; } //settled Percentage (setamt/salesprice*100)Exc GSt try { SetllAmtexcper = Math.Round((SetllAmtexc / (Convert.ToDecimal(selling_price)- TOtalGst)) * 100, 2); } catch (Exception ex) { SetllAmtexcper = 0; } //Net Profit (sales Price -commission -cp) Netpro = Math.Round(Convert.ToDecimal(selling_price) - Convert.ToDecimal(chnellcommsion) - Convert.ToDecimal(cp), 2); //Net Percentages ((netprofit/salesprice)*100) try { Netper = Math.Round((Netpro / Convert.ToDecimal(selling_price)) * 100, 2); } catch (Exception ex) { Netper = 0; } lbltotdecinc.Text = Convert.ToString(TotalDectIncgst); lbltotdecexc.Text = Convert.ToString(TotalDectexcgst); setamtinc.Text = Convert.ToString(SetllAmtinc); setperinc.Text = Convert.ToString(SetllAmtincper); setamtexc.Text = Convert.ToString(SetllAmtexc); setperexc.Text = Convert.ToString(SetllAmtexcper); netpro.Text = Convert.ToString(Netpro); lblnetper.Text = Convert.ToString(Netper); //setamtinc.Text = ""; //setperinc.Text = ""; //setamtexc.Text = ""; //setperexc.Text = ""; //netpro.Text = ""; //lblnetper.Text = ""; } catch(Exception ex) { RecordExceptionCls obj = new RecordExceptionCls(); obj.recordException(ex); } } protected void btnexporttoexcel_Click(object sender, EventArgs e) { try { payment_reportCls obj = new payment_reportCls(); DataTable dtExcel = obj.BindRemittance(virtualLocation.SelectedValue); if (!dtExcel.Rows.Count.Equals(0)) { object IGST = 0; object SGST = 0; object CGSt = 0; object selling_price = 0; object cp = 0; object logictic = 0; object spincgst = 0; object spexcgst = 0; object chnellcommsion = 0; object Utax = 0; object percent = 0; decimal DectIncgst = 0; decimal Dectexcgst = 0; decimal TotalDectIncgst = 0; decimal TotalDectexcgst = 0; decimal SetllAmtinc = 0; decimal SetllAmtexc = 0; decimal SetllAmtincper = 0; decimal SetllAmtexccper = 0; decimal Netpro = 0; decimal Netper = 0; decimal TOtalGst = 0; object gateway = 0; object mis = 0; object penlty = 0; object paybleamnt = 0; object salesid; object mrp; decimal calnet = 0; DataTable dt = new DataTable(); dt.Columns.Add("Pmt Date", typeof(string)); dt.Columns.Add("Pmt Month", typeof(string)); dt.Columns.Add("Pmt Year", typeof(string)); dt.Columns.Add("Sales Date", typeof(string)); dt.Columns.Add("Sales Month", typeof(string)); dt.Columns.Add("Sales Year", typeof(string)); dt.Columns.Add("Channel(VL)", typeof(string)); dt.Columns.Add("Invoice #", typeof(Int32)); dt.Columns.Add("Order id#", typeof(string)); dt.Columns.Add("StockUp id#", typeof(Int32)); dt.Columns.Add("Payment Status", typeof(string)); dt.Columns.Add("Pmt Effecting Status", typeof(string)); dt.Columns.Add("System Status", typeof(string)); dt.Columns.Add("Lot#", typeof(string)); dt.Columns.Add("Brand", typeof(string)); dt.Columns.Add("Title", typeof(string)); dt.Columns.Add("Size", typeof(string)); dt.Columns.Add("Article", typeof(string)); dt.Columns.Add("Age Bucket(Lot)", typeof(Int32)); dt.Columns.Add("Age Bucket(Barcode)", typeof(Int32)); dt.Columns.Add("MRP", typeof(decimal)); dt.Columns.Add("CP", typeof(decimal)); dt.Columns.Add("Pmt Sales Price", typeof(decimal)); dt.Columns.Add("System Sales Price", typeof(decimal)); dt.Columns.Add("Channel(VL) Commision", typeof(decimal)); dt.Columns.Add("Channel Gateway", typeof(decimal)); dt.Columns.Add("Channel Logistics", typeof(decimal)); dt.Columns.Add("VL Penalty", typeof(decimal)); dt.Columns.Add("VL Misc", typeof(decimal)); dt.Columns.Add("Total IGST", typeof(decimal)); dt.Columns.Add("Total SGST", typeof(decimal)); dt.Columns.Add("Total CSGT", typeof(decimal)); dt.Columns.Add("Total Deduction(inc GST)", typeof(decimal)); dt.Columns.Add("Total Deduction(exl GST)", typeof(decimal)); dt.Columns.Add("Settled Amount(inc GST)", typeof(decimal)); dt.Columns.Add("Settled %(inc GST)", typeof(decimal)); dt.Columns.Add("Settled Amount(exl GST)", typeof(decimal)); dt.Columns.Add("Settled %(exl GST)", typeof(decimal)); dt.Columns.Add("Net profit", typeof(decimal)); dt.Columns.Add("Net Profit %", typeof(decimal)); foreach (DataRow dr in dtExcel.Rows) { //decimal salesid = dr["salesid"].ToString().Equals("") ? "0" : dr["salesid"].ToString(); Utax = dr["utax"].ToString().Equals("") ? "0" : dr["utax"].ToString(); cp = dr["cp"].ToString().Equals("") ? "0" : dr["cp"].ToString(); percent = dr["percentage"].ToString().Equals("") ? "0" : dr["percentage"].ToString(); IGST = dr["totIGST"].ToString().Equals("") ? "0" : dr["totIGST"].ToString(); SGST = dr["totSGST"].ToString().Equals("") ? "0" : dr["totSGST"].ToString(); CGSt = dr["totCGST"].ToString().Equals("") ? "0" : dr["totCGST"].ToString(); cp = dr["cp"].ToString().Equals("") ? "0" : dr["cp"].ToString(); chnellcommsion = dr["channel_commsion"].ToString().Equals("") ? "0" : dr["channel_commsion"].ToString(); gateway = dr["Channel_Gateway"].ToString().Equals("") ? "0" : dr["Channel_Gateway"].ToString(); paybleamnt = dr["Payable_Amoun"].ToString().Equals("") ? "0" : dr["Payable_Amoun"].ToString(); selling_price = dr["pmt_sp"].ToString().Equals("") ? "0" : dr["pmt_sp"].ToString(); spexcgst = dr["spexcgst"].ToString().Equals("") ? "0" : dr["spexcgst"].ToString(); spincgst = dr["spincgst"].ToString().Equals("") ? "0" : dr["spincgst"].ToString(); logictic = dr["VL_Logistics"].ToString().Equals("") ? "0" : dr["VL_Logistics"].ToString(); penlty = dr["VLPenalty"].ToString().Equals("") ? "0" : dr["VLPenalty"].ToString(); mis = dr["misccharges"].ToString().Equals("") ? "0" : dr["misccharges"].ToString(); mrp = dr["mrp"].ToString().Equals("") ? "0" : dr["mrp"].ToString(); if (cp.ToString().Equals("-1")) { decimal Total = Math.Abs(Convert.ToDecimal(IGST)) + Math.Abs(Convert.ToDecimal(SGST)) + Math.Abs(Convert.ToDecimal(CGSt)); TOtalGst = Total; } else { decimal Total = (Convert.ToDecimal(selling_price) * Convert.ToDecimal(percent)) / 100; TOtalGst = Total + Math.Abs(Convert.ToDecimal(Utax)); } if (salesid.ToString().Equals("7221826380")) { } DectIncgst = Math.Round(Math.Abs(Convert.ToDecimal(paybleamnt)) + Math.Abs(Convert.ToDecimal(mis)), 2); TotalDectIncgst = Math.Abs(Convert.ToDecimal(selling_price)) - DectIncgst; TotalDectexcgst = Math.Round(Convert.ToDecimal(TotalDectIncgst) - Convert.ToDecimal(TOtalGst), 2); try { calnet = Convert.ToDecimal(mrp) / Convert.ToDecimal(cp); } catch (Exception ex) { calnet = 0; } SetllAmtinc = Math.Round(Math.Abs(Convert.ToDecimal(selling_price)) - TotalDectIncgst - Convert.ToDecimal(calnet), 2);//incgst SetllAmtexc = Math.Round(Math.Abs(Convert.ToDecimal(selling_price)) - TotalDectexcgst - Convert.ToDecimal(calnet), 2);//exc gst try { SetllAmtincper = Math.Round((SetllAmtinc / Math.Abs(Convert.ToDecimal(selling_price))) * 100, 2); //Math.Round((SetllAmtinc / Convert.ToDecimal(spincgst)) * 100, 2); } catch (Exception ex) { SetllAmtincper = 0; } try { SetllAmtexccper = Math.Round((SetllAmtexc / Math.Abs((Convert.ToDecimal(selling_price)) - TOtalGst)) * 100, 2); } catch (Exception ex) { SetllAmtexccper = 0; } Netpro = Math.Round(Math.Abs(Convert.ToDecimal(selling_price)) - Math.Abs(Convert.ToDecimal(chnellcommsion)) - Math.Abs(Convert.ToDecimal(logictic)) - Math.Abs(Convert.ToDecimal(calnet)), 2); try { Netper = Math.Round(Netpro / Math.Abs(Convert.ToDecimal(selling_price)) * 100, 2); } catch(Exception ex) { Netper = 0; } DataRow row = dt.NewRow(); row["Pmt Date"] = dr["pmt_date"]; row["Pmt Month"] = dr["pmt_Month"]; row["Pmt Year"] = dr["pmt_year"]; row["Sales Date"] = dr["date"]; row["Sales Month"] = dr["Month"]; row["Sales Year"] = dr["year"]; row["Channel(VL)"] = dr["Location"]; row["Invoice #"] = dr["invoiceid"]; row["Order id#"] = dr["salesid"]; row["StockUp id#"] = dr["stockupId"]; row["Payment Status"] = dr["payment_status"]; row["Pmt Effecting Status"] = dr["pmt_effecting_status"]; row["System Status"] = dr["sys_status"]; row["Lot#"] = dr["Lotno"]; row["Brand"] = dr["brand"]; row["Title"] = dr["Title"]; row["Size"] = dr["Size"]; row["Article"] = dr["articel"]; row["Age Bucket(Lot)"] = dr["lotAge"]; row["Age Bucket(Barcode)"] = dr["stockAge"]; row["MRP"] = dr["mrp"]; row["CP"] = calnet; row["Pmt Sales Price"] = dr["pmt_sp"]; row["System Sales Price"] = dr["sys_sp"]; row["Channel(VL) Commision"] = dr["channel_commsion"]; row["Channel Gateway"] = dr["Channel_Gateway"]; row["Channel Logistics"] = dr["VL_Logistics"]; row["VL Penalty"] = dr["VLPenalty"]; row["VL Misc"] = mis; row["Total IGST"] = TOtalGst; row["Total SGST"] = dr["totSGST"]; row["Total CSGT"] = dr["totCGST"]; row["Total Deduction(inc GST)"] = TotalDectIncgst; row["Total Deduction(exl GST)"] = TotalDectexcgst; row["Settled Amount(inc GST)"] = SetllAmtinc; row["Settled %(inc GST)"] = SetllAmtincper; row["Settled Amount(exl GST)"] = SetllAmtexc; row["Settled %(exl GST)"] = SetllAmtexccper; row["Net profit"] = Netpro; row["Net Profit %"] = Netper; //row["Total Deduction(exl GST)"]= TotalDectexcgst; //row["Settled Amount"] = SetllAmtinc; //row["Settled %"] = SetllAmtincper; //row["Net profit"] = Netpro; //row["Net Profit %"] = Netper; dt.Rows.Add(row); } using (XLWorkbook wb = new XLWorkbook()) { wb.Worksheets.Add(dt, "Remittance Report"); Response.Clear(); Response.Buffer = true; Response.Charset = ""; Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; string fname = virtualLocation.SelectedItem.Text+" Remittance-Repo_" + DateTime.Now.ToString("dd-MM-yyyy-HH:mm:ss"); Response.AddHeader("content-disposition", "attachment;filename=" + fname + ".xlsx"); using (MemoryStream MyMemoryStream = new MemoryStream()) { wb.SaveAs(MyMemoryStream); MyMemoryStream.WriteTo(Response.OutputStream); Response.Flush(); Response.End(); } } } else { } } catch(Exception ex) { RecordExceptionCls obj = new RecordExceptionCls(); obj.recordException(ex); } } protected void btnsearch_Click(object sender, EventArgs e) { BindData(); maindiv.Visible = true; } }
47.038549
211
0.511762
[ "MIT" ]
hasnainsayed/MNMNew
RemittanceRepo.aspx.cs
20,746
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using NewLife; using NewLife.Collections; using NewLife.Data; using NewLife.Web; using XCode.TDengine; namespace XCode.DataAccessLayer { class TDengine : RemoteDb { #region 属性 /// <summary>返回数据库类型。</summary> public override DatabaseType Type => DatabaseType.TDengine; ///// <summary>工厂</summary> //public override DbProviderFactory Factory => TDengineFactory.Instance; private static DbProviderFactory _Factory; /// <summary>工厂</summary> public override DbProviderFactory Factory { get { if (_Factory == null) { lock (typeof(TDengine)) { //GetProviderFactory("NewLife.TDengine.dll", "NewLife.TDengine.TDengineFactory"); var links = GetLinkNames("NewLife.TDengine.dll", true); var type = PluginHelper.LoadPlugin("NewLife.TDengine.TDengineFactory", null, "taos.dll", links.Join(",")); _Factory = TDengineFactory.Instance; } } return _Factory; } } const String Server_Key = "Server"; protected override void OnSetConnectionString(ConnectionStringBuilder builder) { base.OnSetConnectionString(builder); var key = builder[Server_Key]; if (key.EqualIgnoreCase(".", "localhost")) builder[Server_Key] = IPAddress.Loopback.ToString(); } #endregion #region 方法 /// <summary>创建数据库会话</summary> /// <returns></returns> protected override IDbSession OnCreateSession() => new TDengineSession(this); /// <summary>创建元数据对象</summary> /// <returns></returns> protected override IMetaData OnCreateMetaData() => new TDengineMetaData(); public override Boolean Support(String providerName) { providerName = providerName.ToLower(); if (providerName.EqualIgnoreCase("TD", "TDengine")) return true; return false; } #endregion #region 数据库特性 protected override String ReservedWordsStr { get { return "ACCESSIBLE,ADD,ALL,ALTER,ANALYZE,AND,AS,ASC,ASENSITIVE,BEFORE,BETWEEN,BIGINT,BINARY,BLOB,BOTH,BY,CALL,CASCADE,CASE,CHANGE,CHAR,CHARACTER,CHECK,COLLATE,COLUMN,CONDITION,CONNECTION,CONSTRAINT,CONTINUE,CONTRIBUTORS,CONVERT,CREATE,CROSS,CURRENT_DATE,CURRENT_TIME,CURRENT_TIMESTAMP,CURRENT_USER,CURSOR,DATABASE,DATABASES,DAY_HOUR,DAY_MICROSECOND,DAY_MINUTE,DAY_SECOND,DEC,DECIMAL,DECLARE,DEFAULT,DELAYED,DELETE,DESC,DESCRIBE,DETERMINISTIC,DISTINCT,DISTINCTROW,DIV,DOUBLE,DROP,DUAL,EACH,ELSE,ELSEIF,ENCLOSED,ESCAPED,EXISTS,EXIT,EXPLAIN,FALSE,FETCH,FLOAT,FLOAT4,FLOAT8,FOR,FORCE,FOREIGN,FROM,FULLTEXT,GRANT,GROUP,HAVING,HIGH_PRIORITY,HOUR_MICROSECOND,HOUR_MINUTE,HOUR_SECOND,IF,IGNORE,IN,INDEX,INFILE,INNER,INOUT,INSENSITIVE,INSERT,INT,INT1,INT2,INT3,INT4,INT8,INTEGER,INTERVAL,INTO,IS,ITERATE,JOIN,KEY,KEYS,KILL,LEADING,LEAVE,LEFT,LIKE,LIMIT,LINEAR,LINES,LOAD,LOCALTIME,LOCALTIMESTAMP,LOCK,LONG,LONGBLOB,LONGTEXT,LOOP,LOW_PRIORITY,MATCH,MEDIUMBLOB,MEDIUMINT,MEDIUMTEXT,MIDDLEINT,MINUTE_MICROSECOND,MINUTE_SECOND,MOD,MODIFIES,NATURAL,NOT,NO_WRITE_TO_BINLOG,NULL,NUMERIC,ON,OPTIMIZE,OPTION,OPTIONALLY,OR,ORDER,OUT,OUTER,OUTFILE,PRECISION,PRIMARY,PROCEDURE,PURGE,RANGE,READ,READS,READ_ONLY,READ_WRITE,REAL,REFERENCES,REGEXP,RELEASE,RENAME,REPEAT,REPLACE,REQUIRE,RESTRICT,RETURN,REVOKE,RIGHT,RLIKE,SCHEMA,SCHEMAS,SECOND_MICROSECOND,SELECT,SENSITIVE,SEPARATOR,SET,SHOW,SMALLINT,SPATIAL,SPECIFIC,SQL,SQLEXCEPTION,SQLSTATE,SQLWARNING,SQL_BIG_RESULT,SQL_CALC_FOUND_ROWS,SQL_SMALL_RESULT,SSL,STARTING,STRAIGHT_JOIN,TABLE,TERMINATED,THEN,TINYBLOB,TINYINT,TINYTEXT,TO,TRAILING,TRIGGER,TRUE,UNDO,UNION,UNIQUE,UNLOCK,UNSIGNED,UPDATE,UPGRADE,USAGE,USE,USING,UTC_DATE,UTC_TIME,UTC_TIMESTAMP,VALUES,VARBINARY,VARCHAR,VARCHARACTER,VARYING,WHEN,WHERE,WHILE,WITH,WRITE,X509,XOR,YEAR_MONTH,ZEROFILL," + "TBName," + "LOG,User,Role,Admin,Rank,Member"; } } /// <summary>格式化关键字</summary> /// <param name="keyWord">关键字</param> /// <returns></returns> public override String FormatKeyWord(String keyWord) { //if (String.IsNullOrEmpty(keyWord)) throw new ArgumentNullException("keyWord"); if (keyWord.IsNullOrEmpty()) return keyWord; if (keyWord.StartsWith("`") && keyWord.EndsWith("`")) return keyWord; return $"`{keyWord}`"; } /// <summary>格式化数据为SQL数据</summary> /// <param name="field">字段</param> /// <param name="value">数值</param> /// <returns></returns> public override String FormatValue(IDataColumn field, Object value) { var code = System.Type.GetTypeCode(field.DataType); if (code == TypeCode.String) { if (value == null) return field.Nullable ? "null" : "''"; return "'" + value.ToString() .Replace("\\", "\\\\")//反斜杠需要这样才能插入到数据库 .Replace("'", @"\'") + "'"; } else if (code == TypeCode.Boolean) { return value.ToBoolean() ? "1" : "0"; } return base.FormatValue(field, value); } /// <summary>格式化时间为SQL字符串</summary> /// <remarks> /// 优化DateTime转为全字符串,平均耗时从25.76ns降为15.07。 /// 调用非常频繁,每分钟都有数百万次调用。 /// </remarks> /// <param name="dateTime">时间值</param> /// <returns></returns> public override String FormatDateTime(DateTime dateTime) => $"'{dateTime:yyyy-MM-dd HH:mm:ss.fff}'"; /// <summary>长文本长度</summary> public override Int32 LongTextLength => 4000; internal protected override String ParamPrefix => "?"; /// <summary>创建参数</summary> /// <param name="name">名称</param> /// <param name="value">值</param> /// <param name="type">类型</param> /// <returns></returns> public override IDataParameter CreateParameter(String name, Object value, Type type = null) { var dp = base.CreateParameter(name, value, type); //var type = field?.DataType; if (type == null) type = value?.GetType(); // TDengine的枚举要用 DbType.String if (type == typeof(Boolean)) { var v = value.ToBoolean(); dp.DbType = DbType.Int16; dp.Value = v ? 1 : 0; } return dp; } /// <summary>系统数据库名</summary> public override String SystemDatabaseName => "db"; /// <summary>字符串相加</summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public override String StringConcat(String left, String right) => $"concat({(!String.IsNullOrEmpty(left) ? left : "\'\'")},{(!String.IsNullOrEmpty(right) ? right : "\'\'")})"; #endregion } /// <summary>TDengine数据库</summary> internal class TDengineSession : RemoteDbSession { #region 构造函数 public TDengineSession(IDatabase db) : base(db) { } #endregion #region 基本方法 查询/执行 /// <summary>执行插入语句并返回新增行的自动编号</summary> /// <param name="sql">SQL语句</param> /// <param name="type">命令类型,默认SQL文本</param> /// <param name="ps">命令参数</param> /// <returns>新增行的自动编号</returns> public override Int64 InsertAndGetIdentity(String sql, CommandType type = CommandType.Text, params IDataParameter[] ps) => throw new NotSupportedException(); public override Task<Int64> InsertAndGetIdentityAsync(String sql, CommandType type = CommandType.Text, params IDataParameter[] ps) => throw new NotSupportedException(); #endregion #region 批量操作 /* insert into stat (siteid,statdate,`count`,cost,createtime,updatetime) values (1,'2018-08-11 09:34:00',1,123,now(),now()), (2,'2018-08-11 09:34:00',1,456,now(),now()), (3,'2018-08-11 09:34:00',1,789,now(),now()), (2,'2018-08-11 09:34:00',1,456,now(),now()) on duplicate key update `count`=`count`+values(`count`),cost=cost+values(cost), updatetime=values(updatetime); */ private String GetBatchSql(String action, IDataTable table, IDataColumn[] columns, ICollection<String> updateColumns, ICollection<String> addColumns, IEnumerable<IExtend> list) { var sb = Pool.StringBuilder.Get(); var db = Database as DbBase; // 字段列表 if (columns == null) columns = table.Columns.ToArray(); BuildInsert(sb, db, action, table, columns); // 值列表 sb.Append(" Values"); BuildBatchValues(sb, db, action, table, columns, list); // 重复键执行update BuildDuplicateKey(sb, db, columns, updateColumns, addColumns); return sb.Put(true); } public override Int32 Insert(IDataTable table, IDataColumn[] columns, IEnumerable<IExtend> list) { var sql = GetBatchSql("Insert Into", table, columns, null, null, list); return Execute(sql); } public override Int32 Upsert(IDataTable table, IDataColumn[] columns, ICollection<String> updateColumns, ICollection<String> addColumns, IEnumerable<IExtend> list) { var sql = GetBatchSql("Insert Into", table, columns, updateColumns, addColumns, list); return Execute(sql); } #endregion #region 架构 public override DataTable GetSchema(DbConnection conn, String collectionName, String[] restrictionValues) => null; #endregion } /// <summary>TDengine元数据</summary> class TDengineMetaData : RemoteDbMetaData { public TDengineMetaData() => Types = _DataTypes; #region 数据类型 protected override List<KeyValuePair<Type, Type>> FieldTypeMaps { get { if (_FieldTypeMaps == null) { var list = base.FieldTypeMaps; if (!list.Any(e => e.Key == typeof(Byte) && e.Value == typeof(Boolean))) list.Add(new KeyValuePair<Type, Type>(typeof(Byte), typeof(Boolean))); } return base.FieldTypeMaps; } } /// <summary>数据类型映射</summary> private static readonly Dictionary<Type, String[]> _DataTypes = new() { { typeof(Byte), new String[] { "TINYINT" } }, { typeof(Int16), new String[] { "SMALLINT" } }, { typeof(Int32), new String[] { "INT" } }, { typeof(Int64), new String[] { "BIGINT" } }, { typeof(Single), new String[] { "FLOAT" } }, { typeof(Double), new String[] { "DOUBLE" } }, { typeof(Decimal), new String[] { "DOUBLE" } }, { typeof(DateTime), new String[] { "TIMESTAMP" } }, { typeof(String), new String[] { "NCHAR({0})", "BINARY({0})" } }, { typeof(Boolean), new String[] { "BOOL" } }, //{ typeof(Byte[]), new String[] { "BINARY" } }, }; #endregion #region 架构 protected override List<IDataTable> OnGetTables(String[] names) { var ss = Database.CreateSession(); var list = new List<IDataTable>(); var old = ss.ShowSQL; ss.ShowSQL = false; try { var sql = "SHOW TABLES"; var dt = ss.Query(sql, null); if (dt.Rows.Count == 0) return null; var hs = new HashSet<String>(names ?? new String[0], StringComparer.OrdinalIgnoreCase); // 所有表 foreach (var dr in dt) { var name = dr["table_name"] + ""; if (name.IsNullOrEmpty() || hs.Count > 0 && !hs.Contains(name)) continue; var table = DAL.CreateTable(); table.TableName = name; table.Owner = dr["stable_name"] as String; #region 字段 sql = $"DESCRIBE {name}"; var dcs = ss.Query(sql, null); foreach (var dc in dcs) { var field = table.CreateColumn(); field.ColumnName = dc["Field"] + ""; field.RawType = dc["Type"] + ""; field.DataType = GetDataType(field.RawType); field.Length = dc["Length"].ToInt(); field.Master = dc["Note"] as String == "TAGS"; field.Fix(); table.Columns.Add(field); } #endregion // 修正关系数据 table.Fix(); list.Add(table); } } finally { ss.ShowSQL = old; } return list; } /// <summary> /// 快速取得所有表名 /// </summary> /// <returns></returns> public override IList<String> GetTableNames() { var list = new List<String>(); var dt = base.Database.CreateSession().Query("SHOW TABLES", null); if (dt.Rows.Count == 0) return list; // 所有表 foreach (var dr in dt) { var name = dr["table_name"] + ""; if (!name.IsNullOrEmpty()) list.Add(name); } return list; } public override String FieldClause(IDataColumn field, Boolean onlyDefine) { var sb = new StringBuilder(); // 字段名 sb.AppendFormat("{0} ", FormatName(field)); String typeName = null; // 每种数据库的自增差异太大,理应由各自处理,而不采用原始值 if (Database.Type == field.Table.DbType && !field.Identity) typeName = field.RawType; if (String.IsNullOrEmpty(typeName)) typeName = GetFieldType(field); sb.Append(typeName); return sb.ToString(); } #endregion #region 反向工程 protected override Boolean DatabaseExist(String databaseName) { var ss = Database.CreateSession(); var sql = $"SHOW DATABASES"; var dt = ss.Query(sql, null); return dt != null && dt.Rows != null && dt.Rows.Any(e => e[0] as String == databaseName); } public override String CreateDatabaseSQL(String dbname, String file) => $"Create Database If Not Exists {Database.FormatName(dbname)}"; //public override String CreateDatabaseSQL(String dbname, String file) => $"Create Database If Not Exists {Database.FormatName(dbname)} KEEP 365 DAYS 10 BLOCKS 6 UPDATE 1;"; public override String DropDatabaseSQL(String dbname) => $"Drop Database If Exists {Database.FormatName(dbname)}"; public override String CreateTableSQL(IDataTable table) { var fs = new List<IDataColumn>(table.Columns); var sb = Pool.StringBuilder.Get(); sb.AppendFormat("Create Table If Not Exists {0}(", FormatName(table)); var ss = fs.Where(e => !e.Master).ToList(); var ms = fs.Where(e => e.Master).ToList(); sb.Append(ss.Join(",", e => FieldClause(e, true))); sb.Append(')'); if (ms.Count > 0) { sb.Append(" TAGS ("); sb.Append(ms.Join(",", e => FieldClause(e, true))); sb.Append(')'); } sb.Append(';'); return sb.Put(true); } public override String AddTableDescriptionSQL(IDataTable table) => // 返回String.Empty表示已经在别的SQL中处理 String.Empty; public override String AlterColumnSQL(IDataColumn field, IDataColumn oldfield) => $"Alter Table {FormatName(field.Table)} Modify Column {FieldClause(field, false)}"; public override String AddColumnDescriptionSQL(IDataColumn field) => // 返回String.Empty表示已经在别的SQL中处理 String.Empty; #endregion } }
39.36643
1,800
0.566178
[ "MIT" ]
qaz734913414/X
XCode/DataAccessLayer/Database/TDengine.cs
17,290
C#
namespace Nest { public class CreateAutoFollowPatternResponse : AcknowledgedResponseBase { } }
19.4
76
0.814433
[ "Apache-2.0" ]
591094733/elasticsearch-net
src/Nest/XPack/CrossClusterReplication/AutoFollow/CreateAutoFollowPattern/CreateAutoFollowPatternResponse.cs
99
C#
using Stylet; using SyncTrayzor.Pages; using SyncTrayzor.Pages.Settings; using SyncTrayzor.Pages.Tray; using SyncTrayzor.Services; using SyncTrayzor.Services.Config; using SyncTrayzor.Syncthing; using SyncTrayzor.Syncthing.Folders; using SyncTrayzor.Utils; using System; using System.Linq; using System.Windows.Input; namespace SyncTrayzor.NotifyIcon { public class NotifyIconViewModel : PropertyChangedBase, IDisposable { private readonly IWindowManager windowManager; private readonly ISyncthingManager syncthingManager; private readonly Func<SettingsViewModel> settingsViewModelFactory; private readonly IProcessStartProvider processStartProvider; private readonly IAlertsManager alertsManager; private readonly IConfigurationProvider configurationProvider; public bool Visible { get; set; } public bool MainWindowVisible { get; set; } public BindableCollection<FolderViewModel> Folders { get; private set; } public FileTransfersTrayViewModel FileTransfersViewModel { get; private set; } public event EventHandler WindowOpenRequested; public event EventHandler WindowCloseRequested; public event EventHandler ExitRequested; public SyncthingState SyncthingState { get; set; } public bool SyncthingDevicesPaused => this.alertsManager.PausedDeviceIdsFromMetering.Count > 0; public bool SyncthingWarning => this.alertsManager.AnyWarnings; public bool SyncthingStarted => this.SyncthingState == SyncthingState.Running; public bool SyncthingSyncing { get; private set; } private IconAnimationMode iconAnimationmode; public NotifyIconViewModel( IWindowManager windowManager, ISyncthingManager syncthingManager, Func<SettingsViewModel> settingsViewModelFactory, IProcessStartProvider processStartProvider, IAlertsManager alertsManager, FileTransfersTrayViewModel fileTransfersViewModel, IConfigurationProvider configurationProvider) { this.windowManager = windowManager; this.syncthingManager = syncthingManager; this.settingsViewModelFactory = settingsViewModelFactory; this.processStartProvider = processStartProvider; this.alertsManager = alertsManager; this.FileTransfersViewModel = fileTransfersViewModel; this.configurationProvider = configurationProvider; this.syncthingManager.StateChanged += this.StateChanged; this.SyncthingState = this.syncthingManager.State; this.syncthingManager.TotalConnectionStatsChanged += this.TotalConnectionStatsChanged; this.syncthingManager.Folders.FoldersChanged += this.FoldersChanged; this.syncthingManager.Folders.SyncStateChanged += this.FolderSyncStateChanged; this.alertsManager.AlertsStateChanged += this.AlertsStateChanged; this.configurationProvider.ConfigurationChanged += this.ConfigurationChanged; this.iconAnimationmode = this.configurationProvider.Load().IconAnimationMode; } private void StateChanged(object sender, SyncthingStateChangedEventArgs e) { this.SyncthingState = e.NewState; if (e.NewState != SyncthingState.Running) this.SyncthingSyncing = false; // Just make sure we reset this.. } private void TotalConnectionStatsChanged(object sender, ConnectionStatsChangedEventArgs e) { if (this.iconAnimationmode == IconAnimationMode.DataTransferring) { var stats = e.TotalConnectionStats; this.SyncthingSyncing = stats.InBytesPerSecond > 0 || stats.OutBytesPerSecond > 0; } } private void FoldersChanged(object sender, EventArgs e) { this.Folders = new BindableCollection<FolderViewModel>(this.syncthingManager.Folders.FetchAll() .Select(x => new FolderViewModel(x, this.processStartProvider)) .OrderBy(x => x.FolderLabel)); } private void FolderSyncStateChanged(object sender, FolderSyncStateChangedEventArgs e) { if (this.iconAnimationmode == IconAnimationMode.Syncing) { var anySyncing = this.syncthingManager.Folders.FetchAll().Any(x => x.SyncState == FolderSyncState.Syncing); this.SyncthingSyncing = anySyncing; } } private void AlertsStateChanged(object sender, EventArgs e) { this.NotifyOfPropertyChange(nameof(this.SyncthingDevicesPaused)); this.NotifyOfPropertyChange(nameof(this.SyncthingWarning)); } private void ConfigurationChanged(object sender, ConfigurationChangedEventArgs e) { this.iconAnimationmode = e.NewConfiguration.IconAnimationMode; // Reset, just in case this.SyncthingSyncing = false; } public void DoubleClick() { this.OnWindowOpenRequested(); } public void ShowSettings() { var vm = this.settingsViewModelFactory(); this.windowManager.ShowDialog(vm); } public void Restore() { this.OnWindowOpenRequested(); } public void Minimize() { this.OnWindowCloseRequested(); } public bool CanStart => this.SyncthingState == SyncthingState.Stopped; public async void Start() { await this.syncthingManager.StartWithErrorDialogAsync(this.windowManager); } public bool CanStop => this.SyncthingState == SyncthingState.Running; public void Stop() { this.syncthingManager.StopAsync(); } public bool CanRestart => this.SyncthingState == SyncthingState.Running; public void Restart() { this.syncthingManager.RestartAsync(); } public bool CanRescanAll => this.SyncthingState == SyncthingState.Running; public void RescanAll() { this.syncthingManager.ScanAsync(null, null); } public void Exit() { this.OnExitRequested(); } private void OnWindowOpenRequested() => this.WindowOpenRequested?.Invoke(this, EventArgs.Empty); private void OnWindowCloseRequested() => this.WindowCloseRequested?.Invoke(this, EventArgs.Empty); private void OnExitRequested() => this.ExitRequested?.Invoke(this, EventArgs.Empty); public void Dispose() { this.syncthingManager.StateChanged -= this.StateChanged; this.syncthingManager.TotalConnectionStatsChanged -= this.TotalConnectionStatsChanged; this.syncthingManager.Folders.SyncStateChanged -= this.FolderSyncStateChanged; this.syncthingManager.Folders.FoldersChanged -= this.FoldersChanged; this.alertsManager.AlertsStateChanged -= this.AlertsStateChanged; this.configurationProvider.ConfigurationChanged -= this.ConfigurationChanged; } } // Slightly hacky, as we can't use s:Action in a style setter... public class FolderViewModel : ICommand { private readonly Folder folder; private readonly IProcessStartProvider processStartProvider; public string FolderLabel => this.folder.Label; public FolderViewModel(Folder folder, IProcessStartProvider processStartProvider) { this.folder = folder; this.processStartProvider = processStartProvider; } public event EventHandler CanExecuteChanged { add { } remove { } } public bool CanExecute(object parameter) => true; public void Execute(object parameter) { this.processStartProvider.ShowFolderInExplorer(this.folder.Path); } } }
38.302326
124
0.652823
[ "MIT" ]
Surfndez/SyncTrayzor
src/SyncTrayzor/NotifyIcon/NotifyIconViewModel.cs
8,023
C#
using System.Reflection; 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("GifImporter")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GifImporter")] [assembly: AssemblyCopyright("Copyright © 2021")] [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("0322B2EF-7452-479D-BAE2-FCAB75033337")] // 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.1.1.0")] [assembly: AssemblyFileVersion("1.1.1.0")]
37.527778
84
0.743893
[ "MIT-0" ]
kazu0617/GifImporter
GifImporter/Properties/AssemblyInfo.cs
1,354
C#
using System; using System.Windows.Input; using UrbanSketchers.Data; namespace UrbanSketchers { /// <summary> /// Navigation menu item /// </summary> public class NavigationMenuItem : BaseDataObject { private ICommand _command; private string _icon; private bool _isEnabled = true; private string _label; /// <summary> /// Gets or sets the label /// </summary> public string Label { get => _label; set => SetProperty(ref _label, value); } /// <summary> /// Gets or sets the icon /// </summary> public string Icon { get => _icon; set => SetProperty(ref _icon, value); } /// <summary> /// Gets or sets the command /// </summary> public ICommand Command { get => _command; set { if (_command != null) _command.CanExecuteChanged -= _command_CanExecuteChanged; if (SetProperty(ref _command, value) && _command != null) _command.CanExecuteChanged += _command_CanExecuteChanged; } } /// <summary> /// Gets or sets a value indicating whether the menu item is enabled. /// </summary> public bool IsEnabled { get => _isEnabled; set => SetProperty(ref _isEnabled, value); } private void _command_CanExecuteChanged(object sender, EventArgs e) { IsEnabled = Command != null && Command.CanExecute(null); } } }
25.029412
81
0.508226
[ "MIT" ]
mscherotter/UrbanSketchers
UrbanSketchers/UrbanSketchers/NavigationMenuItem.cs
1,704
C#
using MxNet.Gluon; using System; using System.Collections.Generic; using System.Text; namespace MxNet.GluonCV.ModelZoo.SEResnet { public class SE_BottleneckV2 : HybridBlock { public SE_BottleneckV2(int channels, int stride, bool downsample = false, int in_channels = 0, string norm_layer = "BatchNorm", FuncArgs norm_kwargs = null, string prefix = null, ParameterDict @params = null) : base(prefix, @params) { } public override NDArrayOrSymbol HybridForward(NDArrayOrSymbol x, params NDArrayOrSymbol[] args) { throw new NotImplementedException(); } } }
31.4
240
0.694268
[ "Apache-2.0" ]
AnshMittal1811/MxNet.Sharp
src/MxNet.GluonCV/ModelZoo/SEResnet/SE_BottleneckV2.cs
630
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Web.Http { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public sealed class ActionNameAttribute : Attribute { public ActionNameAttribute(string name) { Name = name; } public string Name { get; private set; } } }
28.9375
133
0.671706
[ "Apache-2.0" ]
Darth-Fx/AspNetMvcStack
src/System.Web.Http/ActionNameAttribute.cs
465
C#
using Newtonsoft.Json; using Nextt_Gestao_Compra.Aplicacao.Utils; using System.Collections.Generic; namespace Nextt_Gestao_Compra.Aplicacao.ViewModel { public class ParametroNotaVM { public int IDPedido { get; set; } public string Distribuicao { get; set; } public string Tipo { get; set; } public int Numero { get; set; } public string ChaveAcesso { get; set; } public string DataCadastroInicio { get; set; } public string DataCadastroFinal { get; set; } public string DataEntregaInicio { get; set; } public string DataEntregaFinal { get; set; } public string CodigoProduto { get; set; } public List<FornecedorVM> Fornecedores { get; set; } public List<SegmanetosVM> Segmentos { get; set; } public List<MarcaVinculadaVM> Marcas { get; set; } public List<FiliaisVM> Filiais { get; set; } public List<StatusNFVM> StatusNFFornecedores { get; set; } public string RetornaJsonParametroConsultaEntrada() { var jsonResolver = new PropertyRenameAndIgnoreSerializerContractResolver(); var ignorarChild = new string[] { "Nome", "TotalItens", "TotalCusto","QtdeCarteira", "QtdeEstoque", "QtdeVenda", "QtdePack", "PartVendas", "PartCobertura", "PartAtualizada", "VlrMedio" }; var ignorarMain = new string[] { "IDPedido","Distribuicao","Tipo" }; jsonResolver.IgnoreProperty(typeof(FiliaisVM), ignorarChild); jsonResolver.IgnoreProperty(typeof(ParametroNotaVM), ignorarMain); var jsonSettings = new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, ContractResolver = jsonResolver }; return JsonConvert.SerializeObject(this, jsonSettings); } public string RetornaJsonParametroConsultaPedido() { var jsonResolver = new PropertyRenameAndIgnoreSerializerContractResolver(); var ignorarChild = new string[] { "Nome", "TotalItens", "TotalCusto","QtdeCarteira", "QtdeEstoque", "QtdeVenda", "QtdePack", "PartVendas", "PartCobertura", "PartAtualizada", "VlrMedio" }; var ignorarMain = new string[] { "Distribuicao","Tipo","Numero", "ChaveAcesso", "DataCadastroInicio","DataCadastroFinal" }; jsonResolver.RenameProperty(typeof(ParametroNotaVM), "StatusNFFornecedores", "StatusPedidos"); jsonResolver.IgnoreProperty(typeof(FiliaisVM), ignorarChild); jsonResolver.IgnoreProperty(typeof(ParametroNotaVM), ignorarMain); var jsonSettings = new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, ContractResolver = jsonResolver }; return JsonConvert.SerializeObject(this, jsonSettings); } public string RetornaJsonParametroAddPackPedido() { var jsonResolver = new PropertyRenameAndIgnoreSerializerContractResolver(); var ignorarMain = new string[] { "Fornecedores","Tipo","Numero", "ChaveAcesso", "DataCadastroInicio","DataCadastroFinal", "Marcas","Segmentos","Filiais","StatusNFFornecedores", "DataEntregaInicio","DataEntregaFinal", "CodigoProduto" }; jsonResolver.IgnoreProperty(typeof(ParametroNotaVM), ignorarMain); var jsonSettings = new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, ContractResolver = jsonResolver }; return JsonConvert.SerializeObject(this, jsonSettings); } } }
51.486111
150
0.653089
[ "MIT" ]
Philipe1985/NexttWeb
Nextt_Gestao_Compra/Nextt_Gestao_Compra.Aplicacao/ViewModel/ParametroNotaVM.cs
3,709
C#
using System; using System.ComponentModel; using EfsTools.Attributes; using EfsTools.Utils; using Newtonsoft.Json; using EfsTools.Items.Data; namespace EfsTools.Items.Nv { [Serializable] [NvItemId(1593)] [Attributes(9)] public class C0Bc3ImLevel1 { [ElementsCount(1)] [ElementType("uint8")] [Description("")] public byte Value { get; set; } } }
19.636364
40
0.608796
[ "MIT" ]
HomerSp/EfsTools
EfsTools/Items/Nv/C0Bc3ImLevel1I.cs
432
C#
// This file is part of NovelRT.NET. // // You may modify and distribute NovelRT.NET under the terms // of the MIT license. See the LICENSE file for details. using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Text; using Silk.NET.Core.Native; using Silk.NET.Core.Attributes; using Silk.NET.Core.Contexts; using Silk.NET.Core.Loader; #pragma warning disable 1591 namespace NovelRT.NET { [NativeName("Name", "IteratorHandle")] public unsafe partial struct IteratorHandle { } }
21.96
60
0.752277
[ "MIT" ]
Perksey/NovelRT.NET
src/NovelRT.NET/Structs/IteratorHandle.gen.cs
549
C#
using System; using System.Collections.Concurrent; using System.Globalization; namespace AntDesign.Docs.Routing { internal abstract class RouteConstraint { // note: the things that prevent this cache from growing unbounded is that // we're the only caller to this code path, and the fact that there are only // 8 possible instances that we create. // // The values passed in here for parsing are always static text defined in route attributes. private static readonly ConcurrentDictionary<string, RouteConstraint> _cachedConstraints = new ConcurrentDictionary<string, RouteConstraint>(); public abstract bool Match(string pathSegment, out object convertedValue); public static RouteConstraint Parse(string template, string segment, string constraint) { if (string.IsNullOrEmpty(constraint)) { throw new ArgumentException($"Malformed segment '{segment}' in route '{template}' contains an empty constraint."); } if (_cachedConstraints.TryGetValue(constraint, out var cachedInstance)) { return cachedInstance; } else { var newInstance = CreateRouteConstraint(constraint); if (newInstance != null) { // We've done to the work to create the constraint now, but it's possible // we're competing with another thread. GetOrAdd can ensure only a single // instance is returned so that any extra ones can be GC'ed. return _cachedConstraints.GetOrAdd(constraint, newInstance); } else { throw new ArgumentException($"Unsupported constraint '{constraint}' in route '{template}'."); } } } private static RouteConstraint CreateRouteConstraint(string constraint) { switch (constraint) { case "bool": return new TypeRouteConstraint<bool>(bool.TryParse); case "datetime": return new TypeRouteConstraint<DateTime>((string str, out DateTime result) => DateTime.TryParse(str, CultureInfo.InvariantCulture, DateTimeStyles.None, out result)); case "decimal": return new TypeRouteConstraint<decimal>((string str, out decimal result) => decimal.TryParse(str, NumberStyles.Number, CultureInfo.InvariantCulture, out result)); case "double": return new TypeRouteConstraint<double>((string str, out double result) => double.TryParse(str, NumberStyles.Number, CultureInfo.InvariantCulture, out result)); case "float": return new TypeRouteConstraint<float>((string str, out float result) => float.TryParse(str, NumberStyles.Number, CultureInfo.InvariantCulture, out result)); case "guid": return new TypeRouteConstraint<Guid>(Guid.TryParse); case "int": return new TypeRouteConstraint<int>((string str, out int result) => int.TryParse(str, NumberStyles.Integer, CultureInfo.InvariantCulture, out result)); case "long": return new TypeRouteConstraint<long>((string str, out long result) => long.TryParse(str, NumberStyles.Integer, CultureInfo.InvariantCulture, out result)); default: return null; } } } internal class TypeRouteConstraint<T> : RouteConstraint { public delegate bool TryParseDelegate(string str, out T result); private readonly TryParseDelegate _parser; public TypeRouteConstraint(TryParseDelegate parser) { _parser = parser; } public override bool Match(string pathSegment, out object convertedValue) { if (_parser(pathSegment, out var result)) { convertedValue = result; return true; } else { convertedValue = null; return false; } } } }
39.714286
130
0.573067
[ "MIT" ]
1051324354/ant-design-blazor
site/AntDesign.Docs/Routing/RouteConstraint.cs
4,450
C#
using MalikP.IVAO.Library.Test.Common; using MalikP.IVAO.Library.Tests.Abstracts; using NUnit.Framework; namespace MalikP.IVAO.Library.Test.Models { [Category(Categories.Models)] public abstract class ModelAbstractTest : AbstractTest { } }
19.923077
58
0.752896
[ "MIT" ]
peterM/IVAO-Library
src/MalikP. IVAO Library/MalikP.IVAO.Library.Test/Models/ModelAbstractTest.cs
261
C#
using System.Threading.Tasks; namespace Lykke.Service.EthereumWorker.Core.DistributedLock { public interface IDistributedLock { Task<IDistributedLockToken> WaitAsync(); } }
19.5
59
0.738462
[ "MIT" ]
LykkeCity/Lykke.Service.Ethereum
src/Lykke.Service.EthereumWorker.Core/DistributedLock/IDistributedLock.cs
197
C#
using System; namespace Example { [Obsolete("Xyz 123. Will be removed in version 2.0.0.", true)] public class MissingNextVersionClassWithRemoveInNextMajor { } }
20.555556
67
0.675676
[ "MIT" ]
Particular/APIComparer
ExampleV1/MissingNextVersionClassWithRemoveInNextMajor.cs
177
C#
using System; using System.Collections.Generic; using System.Linq; namespace Skender.Stock.Indicators { public static partial class Indicator { // MONEY FLOW INDEX /// <include file='./info.xml' path='indicator/*' /> /// public static IEnumerable<MfiResult> GetMfi<TQuote>( this IEnumerable<TQuote> quotes, int lookbackPeriods = 14) where TQuote : IQuote { // sort quotes List<TQuote> quotesList = quotes.Sort(); // check parameter arguments ValidateMfi(quotes, lookbackPeriods); // initialize int size = quotesList.Count; List<MfiResult> results = new(size); decimal[] tp = new decimal[size]; // true price decimal[] mf = new decimal[size]; // raw MF value int[] direction = new int[size]; // direction decimal? prevTP = null; // roll through quotes, to get preliminary data for (int i = 0; i < quotesList.Count; i++) { TQuote q = quotesList[i]; MfiResult result = new() { Date = q.Date }; // true price tp[i] = (q.High + q.Low + q.Close) / 3; // raw money flow mf[i] = tp[i] * q.Volume; // direction if (prevTP == null || tp[i] == prevTP) { direction[i] = 0; } else if (tp[i] > prevTP) { direction[i] = 1; } else if (tp[i] < prevTP) { direction[i] = -1; } results.Add(result); prevTP = tp[i]; } // add money flow index for (int i = lookbackPeriods; i < results.Count; i++) { MfiResult r = results[i]; int index = i + 1; decimal sumPosMFs = 0; decimal sumNegMFs = 0; for (int p = index - lookbackPeriods; p < index; p++) { if (direction[p] == 1) { sumPosMFs += mf[p]; } else if (direction[p] == -1) { sumNegMFs += mf[p]; } } // handle no negative case if (sumNegMFs == 0) { r.Mfi = 100; continue; } // calculate MFI normally decimal mfRatio = sumPosMFs / sumNegMFs; r.Mfi = 100 - (100 / (1 + mfRatio)); } return results; } // remove recommended periods /// <include file='../_Common/Results/info.xml' path='info/type[@name="Prune"]/*' /> /// public static IEnumerable<MfiResult> RemoveWarmupPeriods( this IEnumerable<MfiResult> results) { int removePeriods = results .ToList() .FindIndex(x => x.Mfi != null); return results.Remove(removePeriods); } // parameter validation private static void ValidateMfi<TQuote>( IEnumerable<TQuote> quotes, int lookbackPeriods) where TQuote : IQuote { // check parameter arguments if (lookbackPeriods <= 1) { throw new ArgumentOutOfRangeException(nameof(lookbackPeriods), lookbackPeriods, "Lookback periods must be greater than 1 for MFI."); } // check quotes int qtyHistory = quotes.Count(); int minHistory = lookbackPeriods + 1; if (qtyHistory < minHistory) { string message = "Insufficient quotes provided for Money Flow Index. " + string.Format( EnglishCulture, "You provided {0} periods of quotes when at least {1} is required.", qtyHistory, minHistory); throw new BadQuotesException(nameof(quotes), message); } } } }
29.446667
95
0.437401
[ "Apache-2.0" ]
kyapp69/Stock.Indicators
indicators/Mfi/Mfi.cs
4,419
C#
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Globalization; using System.Text; using System.Threading; namespace BankProject { public class BankAccount { public static List<Account> filelist = new List<Account>(); private decimal amount; //View one Account Method(admin) public void ViewOneAccount(string connectionstring, string username) { using (SqlConnection conn = new SqlConnection(connectionstring)) { conn.Open(); using (SqlCommand cmd = new SqlCommand($"SELECT username, transaction_date, amount " + $"FROM accounts INNER JOIN users ON users.id = accounts.user_id WHERE username=@username", conn)) { cmd.Parameters.AddWithValue("@username", username); SqlDataReader myData = cmd.ExecuteReader(); while (myData.Read()) { Thread.CurrentThread.CurrentCulture = new CultureInfo("el-gr"); Console.OutputEncoding = Encoding.UTF8; Console.WriteLine($"Hello {myData[0].ToString()} your last transaction date was on: " + $"{myData[1].ToString()} and your current balance is: {myData[2].ToString()}€"); } } } } //View All Accounts Method(admin) public void ViewAllAccounts(string connectionstring, string username) { using (SqlConnection conn = new SqlConnection(connectionstring)) { conn.Open(); using (SqlCommand cmd = new SqlCommand($"SELECT username, transaction_date, amount " + $"FROM accounts INNER JOIN users ON users.id = accounts.user_id WHERE username!=@username", conn)) { Thread.CurrentThread.CurrentCulture = new CultureInfo("el-gr"); ; Console.OutputEncoding = Encoding.UTF8; cmd.Parameters.AddWithValue("@username", username); SqlDataReader myData = cmd.ExecuteReader(); while (myData.Read()) { for (int i = 0; i < myData.FieldCount; i++) { if (i != 2) { Console.Write($"{myData[i].ToString()}\t"); } else { Console.Write($"{myData[i].ToString()}€\t"); } } Console.WriteLine(); } } } } //Deposit Method(all users) public void DepositToAcc(string connectionstring, string username, string recipient, decimal deposit) { using (SqlConnection conn = new SqlConnection(connectionstring)) { conn.Open(); using (SqlCommand command = new SqlCommand($"SELECT amount FROM accounts INNER JOIN users " + $"ON users.id = accounts.user_id WHERE username=@username", conn)) { command.Parameters.AddWithValue("@username", username); SqlDataReader data = command.ExecuteReader(); while (data.Read()) { amount = data.GetDecimal(0); } } conn.Close(); if (deposit <= amount && recipient != username) { conn.Open(); using (SqlCommand cmd = new SqlCommand($"UPDATE accounts SET amount=amount-@deposit " + $"WHERE user_id= (select id from users where username=@username)", conn)) { cmd.Parameters.AddWithValue("@username", username); cmd.Parameters.AddWithValue("@deposit", deposit); cmd.ExecuteNonQuery(); } using (SqlCommand cmd = new SqlCommand($"UPDATE accounts SET amount=amount+@deposit " + $"WHERE user_id= (SELECT id FROM users WHERE username=@recipient)", conn)) { cmd.Parameters.AddWithValue("@recipient", recipient); cmd.Parameters.AddWithValue("@deposit", deposit); cmd.ExecuteNonQuery(); } Console.WriteLine("\nSuccessful transaction. Thank you."); amount = amount - deposit; filelist.Add(new Account { Username = username, TransactionDate = DateTime.Now, Amount = amount }); } else { Console.WriteLine("Error.We were unable to fulfill the transaction.\n\nPlease try again."); } } } //Withdraw Method(admin) public void WithdrawFromMember(string connectionstring, string username, string withdrawer, decimal withdraw) { using (SqlConnection conn = new SqlConnection(connectionstring)) { conn.Open(); using (SqlCommand command = new SqlCommand($"SELECT amount FROM accounts INNER JOIN users " + $"ON users.id = accounts.user_id WHERE username=@withdrawer", conn)) { command.Parameters.AddWithValue("@withdrawer", withdrawer); SqlDataReader data = command.ExecuteReader(); while (data.Read()) { amount = data.GetDecimal(0); } } conn.Close(); if (withdraw <= amount && withdrawer != username) { conn.Open(); using (SqlCommand cmd = new SqlCommand($"UPDATE accounts SET amount=amount-@withdraw " + $"WHERE user_id= (select id from users where username=@withdrawer)", conn)) { cmd.Parameters.AddWithValue("@withdrawer", withdrawer); cmd.Parameters.AddWithValue("@withdraw", withdraw); cmd.ExecuteNonQuery(); } using (SqlCommand cmd = new SqlCommand($"UPDATE accounts SET amount=amount+@withdraw " + $"WHERE user_id= (SELECT id FROM users WHERE username=@username)", conn)) { cmd.Parameters.AddWithValue("@username", username); cmd.Parameters.AddWithValue("@withdraw", withdraw); cmd.ExecuteNonQuery(); } Console.WriteLine("\nSuccessful transaction. Thank you."); using (SqlCommand command = new SqlCommand($"SELECT amount FROM accounts INNER JOIN users " + $"ON users.id = accounts.user_id WHERE username=@username", conn)) { command.Parameters.AddWithValue("@username", username); SqlDataReader data = command.ExecuteReader(); while (data.Read()) { amount = data.GetDecimal(0); } } conn.Close(); amount = amount + withdraw; filelist.Add(new Account { Username = username, TransactionDate = DateTime.Now, Amount = amount }); } else { Console.WriteLine("Error.We were unable to fulfill the transaction.\n\nPlease try again."); } } } } }
45.225275
120
0.471632
[ "Unlicense" ]
HarrysV/BankProject
BankProject/BankProject/BankAccount.cs
8,237
C#
using System; using System.Collections.Generic; using System.IO; using System.Net; using Newtonsoft.Json.Linq; using AustinHarris.JsonRpc; using System.Linq; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Reactive.Concurrency; using System.Diagnostics; namespace AustinHarris.JsonRpc { public class JsonRpcClient { private static object idLock = new object(); private static int id = 0; public Uri ServiceEndpoint = null; public JsonRpcClient(Uri serviceEndpoint) { ServiceEndpoint = serviceEndpoint; } private static Stream CopyAndClose(Stream inputStream) { const int readSize = 256; byte[] buffer = new byte[readSize]; MemoryStream ms = new MemoryStream(); int count = inputStream.Read(buffer, 0, readSize); while (count > 0) { ms.Write(buffer, 0, count); count = inputStream.Read(buffer, 0, readSize); } ms.Position = 0; inputStream.Close(); return ms; } public IObservable<JsonResponse<T>> Invoke<T>(string method, object arg, IScheduler scheduler) { var req = new AustinHarris.JsonRpc.JsonRequest() { Method = method, Params = new object[] { arg } }; return Invoke<T>(req, scheduler); } public IObservable<JsonResponse<T>> Invoke<T>(string method, object[] args, IScheduler scheduler) { var req = new AustinHarris.JsonRpc.JsonRequest() { Method = method, Params = args }; return Invoke<T>(req,scheduler); } public IObservable<JsonResponse<T>> Invoke<T>(JsonRequest jsonRpc, IScheduler scheduler) { var res = Observable.Create<JsonResponse<T>>((obs) => scheduler.Schedule(()=>{ WebRequest req = null; try { int myId; lock (idLock) { myId = ++id; } jsonRpc.Id = myId.ToString(); req = HttpWebRequest.Create(new Uri(ServiceEndpoint, "?callid=" + myId.ToString())); req.Method = "Post"; req.ContentType = "application/json-rpc"; } catch (Exception ex) { obs.OnError(ex); } var ar = req.BeginGetRequestStream(new AsyncCallback((iar) => { HttpWebRequest request = null; try { request = (HttpWebRequest)iar.AsyncState; var stream = new StreamWriter(req.EndGetRequestStream(iar)); var json = Newtonsoft.Json.JsonConvert.SerializeObject(jsonRpc); stream.Write(json); stream.Close(); } catch (Exception ex) { obs.OnError(ex); } var rar = req.BeginGetResponse(new AsyncCallback((riar) => { JsonResponse<T> rjson = null; string sstream = ""; try { var request1 = (HttpWebRequest)riar.AsyncState; var resp = (HttpWebResponse)request1.EndGetResponse(riar); using (var rstream = new StreamReader(CopyAndClose(resp.GetResponseStream()))) { sstream = rstream.ReadToEnd(); } rjson = Newtonsoft.Json.JsonConvert.DeserializeObject<JsonResponse<T>>(sstream); } catch (Exception ex) { Debug.WriteLine(ex.Message); Debugger.Break(); } if (rjson == null) { if (!string.IsNullOrEmpty(sstream)) { JObject jo = Newtonsoft.Json.JsonConvert.DeserializeObject(sstream) as JObject; obs.OnError(new Exception(jo["Error"].ToString())); } else { obs.OnError(new Exception("Empty response")); } } obs.OnNext(rjson); obs.OnCompleted(); }), request); }), req); })); return res; } } }
36.120805
115
0.413229
[ "MIT" ]
Astn/JSON-RPC.NET
AustinHarris.JsonRpc.Client/client.cs
5,382
C#
using System; namespace Azure.Security.Interfaces { using Microsoft.Azure.Cosmos.Table; public interface ISymmetricKeyTableManager { SymmetricKey GetKey(Guid? userId); void DeleteSymmetricKey(SymmetricKey key); void AddSymmetricKey(SymmetricKey key); CloudTable CreateTableIfNotExists(); void DeleteTableIfExists(); } }
19.15
50
0.697128
[ "MIT" ]
cmatskas/Azure.Security
Azure.Security/Interfaces/ISymmetricKeyTableManager.cs
385
C#
// This file is part of YamlDotNet - A .NET library for YAML. // Copyright (c) Antoine Aubry and contributors // // 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. namespace YamlDotNet.Core { internal enum EmitterState { StreamStart, StreamEnd, FirstDocumentStart, DocumentStart, DocumentContent, DocumentEnd, FlowSequenceFirstItem, FlowSequenceItem, FlowMappingFirstKey, FlowMappingKey, FlowMappingSimpleValue, FlowMappingValue, BlockSequenceFirstItem, BlockSequenceItem, BlockMappingFirstKey, BlockMappingKey, BlockMappingSimpleValue, BlockMappingValue } }
38.76087
83
0.702748
[ "MIT" ]
Arakade/YamlDotNet
YamlDotNet/Core/EmitterState.cs
1,785
C#
using System.Reflection; 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("AWSSDK.DocDB")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon DocumentDB with MongoDB compatibility. Amazon DocumentDB is a fast, reliable, and fully managed MongoDB compatible database service.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // 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("3.3")] [assembly: AssemblyFileVersion("3.3.102.27")]
46.5625
219
0.752349
[ "Apache-2.0" ]
damianh/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/DocDB/Properties/AssemblyInfo.cs
1,490
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110 { using static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Extensions; /// <summary>VMwareCbt specific migrate input.</summary> public partial class VMwareCbtMigrateInput { /// <summary> /// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json); /// <summary> /// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject" /// /> before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container); /// <summary> /// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of /// the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> /// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return /// instantly.</param> partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json, ref bool returnNow); /// <summary> /// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the /// object before it is serialized. /// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container, ref bool returnNow); /// <summary> /// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IVMwareCbtMigrateInput. /// </summary> /// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" /> to deserialize from.</param> /// <returns> /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IVMwareCbtMigrateInput. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IVMwareCbtMigrateInput FromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode node) { return node is Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json ? new VMwareCbtMigrateInput(json) : null; } /// <summary> /// Serializes this instance of <see cref="VMwareCbtMigrateInput" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" />. /// </summary> /// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller /// passes in <c>null</c>, a new instance will be created and returned to the caller.</param> /// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode"/>.</param> /// <returns> /// a serialized instance of <see cref="VMwareCbtMigrateInput" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" />. /// </returns> public Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode serializationMode) { container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject(); bool returnNow = false; BeforeToJson(ref container, ref returnNow); if (returnNow) { return container; } __migrateProviderSpecificInput?.ToJson(container, serializationMode); AddIf( null != (((object)this._performShutdown)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString(this._performShutdown.ToString()) : null, "performShutdown" ,container.Add ); AfterToJson(ref container); return container; } /// <summary> /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject into a new instance of <see cref="VMwareCbtMigrateInput" />. /// </summary> /// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject instance to deserialize from.</param> internal VMwareCbtMigrateInput(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json) { bool returnNow = false; BeforeFromJson(json, ref returnNow); if (returnNow) { return; } __migrateProviderSpecificInput = new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.MigrateProviderSpecificInput(json); {_performShutdown = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString>("performShutdown"), out var __jsonPerformShutdown) ? (string)__jsonPerformShutdown : (string)PerformShutdown;} AfterFromJson(json); } } }
67.718447
291
0.687312
[ "MIT" ]
3quanfeng/azure-powershell
src/Migrate/generated/api/Models/Api20180110/VMwareCbtMigrateInput.json.cs
6,873
C#
//------------------ //-- Create By lookchem 3.0 //-- File: Bll/BllW_ProductPackage.cs //-- 2020/3/9 14:05:43 //------------------ using System; using System.Collections.Generic; using System.Text; using Dal; using System.Data; using Model.HardwareMall; using System.Data.SqlClient; using HardwareMall.Tool.DataTableHelp; using HardwareMall.Web.Model; using System.Linq; namespace Bll.HardwareMall { public class BllW_ProductPackage:Bll.Base.HardwareMall.BllW_ProductPackage { private readonly BllW_ProductFormat _productFormat = Bll.Base.HardwareMall.BllW_ProductFormat.Instance(); /// <summary> /// 获取产品的所有包装信息 /// </summary> /// <param name="ProductId"></param> /// <returns></returns> public List<ModW_ProductPackage> GetProductPackageList(int ProductId) { string sql1 = "select top 1 * from W_ProductPackage where ProductId=@ProductId order by Price desc"; string sql2 = "select top 1 * from W_ProductPackage where ProductId=@ProductId order by Price asc"; SqlParameter[] parameters = { new SqlParameter("@ProductId", ProductId) }; var PackageInfoMax = dal.ExecuteDataset(sql1, parameters).Tables[0].ToList<ModW_ProductPackage>().FirstOrDefault(); var PackageInfoMin = dal.ExecuteDataset(sql2, parameters).Tables[0].ToList<ModW_ProductPackage>().FirstOrDefault(); List<ModW_ProductPackage> result = new List<ModW_ProductPackage>(); if (PackageInfoMin != null) { result.Add(PackageInfoMin); } if (PackageInfoMax != null) { result.Add(PackageInfoMax); } return result; } /// <summary> /// 获取规格的所有包装信息 /// </summary> /// <param name="ProductId"></param> /// <returns></returns> public List<ModW_ProductPackage> GetFormatPackageList(int FormatId) { string sql = "select * from W_ProductPackage where FormatId=@FormatId order by Sort"; SqlParameter[] parameters = { new SqlParameter("@FormatId", FormatId) }; var DataTable = dal.ExecuteDataset(sql, parameters).Tables[0]; return DataTable.ToList<ModW_ProductPackage>(); } /// <summary> /// 获取包装信息列表 /// </summary> /// <param name="page"></param> /// <param name="limit"></param> /// <param name="ProductId"></param> /// <returns></returns> public PageDTModel GetPackagePage(int page,int limit,int ProductId,int FormatId) { string where = "ProductId=" + ProductId + " and Isdel=0 and FormatId=" + FormatId; int totalCount = 0; var PageList = dal.GetPageList2("W_ProductPackage", "*", where, "order by Sort asc", limit, page, ref totalCount).Tables[0]; var PageCount = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(limit))); return new PageDTModel() { PageIndex = page, PageCount = PageCount, PageSize = limit, data = PageList, code = 0, msg = "获取成功", count = totalCount }; } /// <summary> /// 保存包装信息 /// </summary> /// <param name="data"></param> /// <param name="Type"></param> public void SaveProdcutPagckage(ModW_ProductPackage data) { string sql = "update W_ProductPackage set PriceType=@PriceType,Price=@Price,Package=@Package,Sort=@Sort,PNum=@PNum,ProductId=@ProductId,FormatId=@FormatId where Id=@Id"; SqlParameter[] parameters = { new SqlParameter("@PriceType",data.PriceType), new SqlParameter("@Price",data.Price), new SqlParameter("@Package",data.Package), new SqlParameter("@Sort",data.Sort), new SqlParameter("@PNum",data.PNum), new SqlParameter("@ProductId",data.ProductId), new SqlParameter("@FormatId",data.FormatId), new SqlParameter("@Id",data.Id), }; dal.ExecuteNonQuery(sql, parameters); } /// <summary> /// 删除产品包装信息(标记删除) /// </summary> /// <param name="Id"></param> public void DelProdcutPagckage(int Id) { string sql = "update W_ProductPackage set Isdel=1 where Id=" + Id; dal.ExecuteNonQuery(sql); } /// <summary> /// 验证是否能够添加包装信息 /// </summary> /// <param name="ProductId"></param> /// <returns></returns> public bool IsAddPagckage(int FormatId) { string sql = "select * from W_ProductPackage where Isdel=0 and FormatId=" + FormatId; var data = dal.ExecuteDataset(sql).Tables[0].ToList<ModW_ProductPackage>(); if (data != null) { if (data.Count >= 3) { return false; } else { return true; } } return true; } } }
37.274648
181
0.553183
[ "Apache-2.0" ]
THAyou/HardWareMall
HardwareMall.BLL/HardwareMall/W/BllW_ProductPackage.cs
5,423
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osuTK.Graphics; using System; namespace osu.Framework.Extensions.Color4Extensions { public static class Color4Extensions { public const double GAMMA = 2.4; public static double ToLinear(double color) => color <= 0.04045 ? color / 12.92 : Math.Pow((color + 0.055) / 1.055, GAMMA); public static double ToSRGB(double color) => color < 0.0031308 ? 12.92 * color : 1.055 * Math.Pow(color, 1.0 / GAMMA) - 0.055; public static Color4 Opacity(this Color4 color, float a) => new Color4(color.R, color.G, color.B, a); public static Color4 Opacity(this Color4 color, byte a) => new Color4(color.R, color.G, color.B, a / 255f); public static Color4 ToLinear(this Color4 colour) => new Color4( (float)ToLinear(colour.R), (float)ToLinear(colour.G), (float)ToLinear(colour.B), colour.A); public static Color4 ToSRGB(this Color4 colour) => new Color4( (float)ToSRGB(colour.R), (float)ToSRGB(colour.G), (float)ToSRGB(colour.B), colour.A); public static Color4 MultiplySRGB(Color4 first, Color4 second) { if (first.Equals(Color4.White)) return second; if (second.Equals(Color4.White)) return first; first = first.ToLinear(); second = second.ToLinear(); return new Color4( first.R * second.R, first.G * second.G, first.B * second.B, first.A * second.A).ToSRGB(); } public static Color4 Multiply(Color4 first, Color4 second) { if (first.Equals(Color4.White)) return second; if (second.Equals(Color4.White)) return first; return new Color4( first.R * second.R, first.G * second.G, first.B * second.B, first.A * second.A); } /// <summary> /// Returns a lightened version of the colour. /// </summary> /// <param name="colour">Original colour</param> /// <param name="amount">Decimal light addition</param> public static Color4 Lighten(this Color4 colour, float amount) => Multiply(colour, 1 + amount); /// <summary> /// Returns a darkened version of the colour. /// </summary> /// <param name="colour">Original colour</param> /// <param name="amount">Percentage light reduction</param> public static Color4 Darken(this Color4 colour, float amount) => Multiply(colour, 1 / (1 + amount)); /// <summary> /// Multiply the RGB coordinates by a scalar. /// </summary> /// <param name="colour">Original colour</param> /// <param name="scalar">A scalar to multiply with</param> /// <returns></returns> public static Color4 Multiply(this Color4 colour, float scalar) { if (scalar < 0) throw new ArgumentOutOfRangeException(nameof(scalar), scalar, "Can not multiply colours by negative values."); return new Color4( Math.Min(1, colour.R * scalar), Math.Min(1, colour.G * scalar), Math.Min(1, colour.B * scalar), colour.A); } } }
36.643564
135
0.535531
[ "MIT" ]
Aergwyn/osu-framework
osu.Framework/Extensions/Color4Extensions/Color4Extensions.cs
3,603
C#
/* Copyright 2019 Nils Kopal <Nils.Kopal<at>CrypTool.org 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; namespace CrypTool.Plugins.FEAL { /// <summary> /// Implementation of the Fast Data Encipherement Algorithm (FEAL) /// /// based on the specification written in the paper: /// Shimizu, Akihiro, and Shoji Miyaguchi. /// "Fast data encipherment algorithm FEAL." /// Workshop on the Theory and Application of of Cryptographic Techniques. /// Springer, Berlin, Heidelberg, 1987. /// /// Test vector for standard FEAL8 rounds: /// P = 00 00 00 00 00 00 00 00 /// K = 01 23 45 67 89 AB CD EF /// C = CE EF 2C 86 F2 49 07 52 (without parity bits set in key) /// C = 6A 72 2D 1C 46 B3 93 36 (with parity bits set in key) /// </summary> public class FEAL_Algorithms { /// <summary> /// Encrypts one block plaintext with FEAL using the given key and 4 rounds /// </summary> /// <param name="P"></param> /// <param name="K"></param> /// <returns></returns> public static byte[] FEAL4_EncryptBlock(byte[] P, byte[] key) { if (P == null || P.Length != 8) { throw new ArgumentException("P has to be byte[8]"); } if (key == null || key.Length != 8) { throw new ArgumentException("key has to be byte[8]"); } byte[][] K = FEAL_Algorithms.K(key, 6); byte[][] L = new byte[4 + 1][]; byte[][] R = new byte[4 + 1][]; L[0] = new byte[4]; R[0] = new byte[4]; Array.Copy(P, 0, L[0], 0, 4); Array.Copy(P, 4, R[0], 0, 4); L[0] = XOR(L[0], Concat(K[4], K[5])); R[0] = XOR(R[0], Concat(K[6], K[7])); R[0] = XOR(R[0], L[0]); for (uint r = 1; r <= 4; r++) { R[r] = XOR(L[r - 1], f(R[r - 1], K[r - 1])); L[r] = R[r - 1]; } L[3] = XOR(L[3], R[3]); R[3] = XOR(R[3], Concat(K[8], K[9])); L[3] = XOR(L[3], Concat(K[10], K[11])); return Concat(R[3], L[3]); } /// <summary> /// Decrypts one block ciphertext with FEAL using the given key and 4 rounds /// </summary> /// <param name="C"></param> /// <param name="key"></param> /// <returns></returns> public static byte[] FEAL4_DecryptBlock(byte[] C, byte[] key) { if (C == null || C.Length != 8) { throw new ArgumentException("C has to be byte[8]"); } if (key == null || key.Length != 8) { throw new ArgumentException("key has to be byte[8]"); } byte[][] K = FEAL_Algorithms.K(key, 6); byte[][] R = new byte[4][]; byte[][] L = new byte[4][]; R[3] = new byte[4]; L[3] = new byte[4]; Array.Copy(C, 0, R[3], 0, 4); Array.Copy(C, 4, L[3], 0, 4); R[3] = XOR(R[3], Concat(K[8], K[9])); L[3] = XOR(L[3], Concat(K[10], K[11])); L[3] = XOR(L[3], R[3]); for (uint r = 3; r >= 1; r--) { L[r - 1] = XOR(R[r], f(L[r], K[r - 1])); R[r - 1] = L[r]; } R[0] = XOR(R[0], L[0]); L[0] = XOR(L[0], Concat(K[4], K[5])); R[0] = XOR(R[0], Concat(K[6], K[7])); return Concat(L[0], R[0]); } /// <summary> /// Encrypts one block plaintext with FEAL using the given key and 8 rounds /// </summary> /// <param name="P"></param> /// <param name="K"></param> /// <returns></returns> public static byte[] FEAL8_EncryptBlock(byte[] P, byte[] key) { if (P == null || P.Length != 8) { throw new ArgumentException("P has to be byte[8]"); } if (key == null || key.Length != 8) { throw new ArgumentException("key has to be byte[8]"); } byte[][] K = FEAL_Algorithms.K(key, 8); byte[][] L = new byte[8 + 1][]; byte[][] R = new byte[8 + 1][]; L[0] = new byte[4]; R[0] = new byte[4]; Array.Copy(P, 0, L[0], 0, 4); Array.Copy(P, 4, R[0], 0, 4); L[0] = XOR(L[0], Concat(K[8], K[9])); R[0] = XOR(R[0], Concat(K[10], K[11])); R[0] = XOR(R[0], L[0]); for (uint r = 1; r <= 8; r++) { R[r] = XOR(L[r - 1], f(R[r - 1], K[r - 1])); L[r] = R[r - 1]; } L[8] = XOR(L[8], R[8]); R[8] = XOR(R[8], Concat(K[12], K[13])); L[8] = XOR(L[8], Concat(K[14], K[15])); return Concat(R[8], L[8]); } /// <summary> /// Decrypts one block ciphertext with FEAL using the given key and 8 rounds /// </summary> /// <param name="C"></param> /// <param name="key"></param> /// <returns></returns> public static byte[] FEAL8_DecryptBlock(byte[] C, byte[] key) { if (C == null || C.Length != 8) { throw new ArgumentException("C has to be byte[8]"); } if (key == null || key.Length != 8) { throw new ArgumentException("key has to be byte[8]"); } byte[][] K = FEAL_Algorithms.K(key, 8); byte[][] R = new byte[8 + 1][]; byte[][] L = new byte[8 + 1][]; R[8] = new byte[4]; L[8] = new byte[4]; Array.Copy(C, 0, R[8], 0, 4); Array.Copy(C, 4, L[8], 0, 4); R[8] = XOR(R[8], Concat(K[12], K[13])); L[8] = XOR(L[8], Concat(K[14], K[15])); L[8] = XOR(L[8], R[8]); for (uint r = 8; r >= 1; r--) { L[r - 1] = XOR(R[r], f(L[r], K[r - 1])); R[r - 1] = L[r]; } R[0] = XOR(R[0], L[0]); L[0] = XOR(L[0], Concat(K[8], K[9])); R[0] = XOR(R[0], Concat(K[10], K[11])); return Concat(L[0], R[0]); } /// <summary> /// S-function of FEAL /// Computes (X1 + X2 + delta) mod 256 /// </summary> /// <param name="X1"></param> /// <param name="X2"></param> /// <param name="delta"></param> /// <returns></returns> public static byte S(byte X1, byte X2, byte delta) { byte T = (byte)((X1 + X2 + delta) % 256); return ROT2(T); } /// <summary> /// Rotate a byte by 2 bits to the left /// </summary> /// <param name="value"></param> public static byte ROT2(byte value) { byte low = (byte)(value & 0xC0); low = (byte)(low >> 6); return (byte)(((value << 2) & 255) | low); } /// <summary> /// FEAL fk-function /// </summary> /// <param name="alpha"></param> /// <param name="beta"></param> /// <returns></returns> public static byte[] fk(byte[] alpha, byte[] beta) { byte[] fk = new byte[4]; fk[1] = (byte)(alpha[1] ^ alpha[0]); fk[2] = (byte)(alpha[2] ^ alpha[3]); fk[1] = S(fk[1], (byte)(fk[2] ^ beta[0]), 1); fk[2] = S(fk[2], (byte)(fk[1] ^ beta[1]), 0); fk[0] = S(alpha[0], (byte)(fk[1] ^ beta[2]), 0); fk[3] = S(alpha[3], (byte)(fk[2] ^ beta[3]), 1); return fk; } /// <summary> /// FEAL f-function /// </summary> /// <param name="alpha"></param> /// <param name="beta"></param> /// <returns></returns> public static byte[] f(byte[] alpha, byte[] beta) { byte[] f = new byte[4]; f[1] = (byte)(alpha[1] ^ beta[0] ^ alpha[0]); f[2] = (byte)(alpha[2] ^ beta[1] ^ alpha[3]); f[1] = S(f[1], f[2], 1); f[2] = S(f[2], f[1], 0); f[0] = S(alpha[0], f[1], 0); f[3] = S(alpha[3], f[2], 1); return f; } /// <summary> /// Calculates a XOR b /// </summary> /// <param name="a"></param> /// <param name="b"></param> public static byte[] XOR(byte[] a, byte[] b) { byte[] c = new byte[a.Length]; for (int i = 0; i < c.Length; i++) { c[i] = (byte)(a[i] ^ b[i]); } return c; } /// <summary> /// Key processing of FEAL /// </summary> /// <param name="key"></param> /// <param name="rounds"></param> /// <returns></returns> public static byte[][] K(byte[] key, uint rounds = 8) { byte[][] K = new byte[rounds * 2][]; byte[][] A = new byte[rounds + 1][]; byte[][] B = new byte[rounds + 1][]; byte[][] D = new byte[rounds + 1][]; A[0] = new byte[4]; B[0] = new byte[4]; D[0] = new byte[4]; Array.Copy(key, 0, A[0], 0, 4); Array.Copy(key, 4, B[0], 0, 4); for (uint r = 1; r <= rounds; r++) { D[r] = A[r - 1]; A[r] = B[r - 1]; B[r] = fk(A[r - 1], XOR(B[r - 1], D[r - 1])); K[2 * (r - 1)] = new byte[] { B[r][0], B[r][1] }; K[2 * (r - 1) + 1] = new byte[] { B[r][2], B[r][3] }; } return K; } /// <summary> /// Concatenates 2 byte arrays /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static byte[] Concat(byte[] a, byte[] b) { byte[] c = new byte[a.Length + b.Length]; for (int i = 0; i < a.Length; i++) { c[i] = a[i]; } for (int i = 0; i < b.Length; i++) { c[a.Length + i] = b[i]; } return c; } } }
30.89548
84
0.409984
[ "Apache-2.0" ]
ekzyis/CrypTool-2
CrypPlugins/FEAL/FEAL_Algorithms.cs
10,939
C#
using System; namespace Courier.Core.Commands.Users { public class SignIn : ICommand { public Guid UserId { get; set; } public string Email { get; } public string Password { get; } public SignIn(string email, string password) { Email = email; Password = password; } } }
20.882353
52
0.55493
[ "MIT" ]
pawlos/wszib-courier
src/Courier.Core/Commands/Users/SignIn.cs
355
C#
//////////////////////////////////////////////////////////////////////////// // // This file is part of Rpi.SenseHat // // Copyright (c) 2015, Mattias Larsson // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the // Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Threading; using System.Threading.Tasks; using Windows.ApplicationModel.Core; using Windows.Graphics.Imaging; using Windows.Storage; using Windows.UI; using Windows.UI.Core; namespace Emmellsoft.IoT.Rpi.SenseHat { public static class PixelSupport { /// <summary> /// Gets a 2-dimensional pixel array from an image. /// </summary> /// <param name="imageUri">The URI to the image.</param> public static async Task<Color[,]> GetPixels(Uri imageUri) { Color[,] pixels = null; var pixelsLoadedEvent = new ManualResetEvent(false); await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { StorageFile imageFile = await StorageFile.GetFileFromApplicationUriAsync(imageUri); using (var imageContent = await imageFile.OpenReadAsync()) { BitmapDecoder bitmapDecoder = await BitmapDecoder.CreateAsync(imageContent); pixels = new Color[bitmapDecoder.PixelWidth, bitmapDecoder.PixelHeight]; PixelDataProvider pixelDataProvider = await bitmapDecoder.GetPixelDataAsync( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, new BitmapTransform(), ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage); byte[] pixelData = pixelDataProvider.DetachPixelData(); int pixelDataIndex = 0; for (int y = 0; y < bitmapDecoder.PixelHeight; y++) { for (int x = 0; x < bitmapDecoder.PixelWidth; x++) { byte b = pixelData[pixelDataIndex]; byte g = pixelData[pixelDataIndex + 1]; byte r = pixelData[pixelDataIndex + 2]; byte a = pixelData[pixelDataIndex + 3]; pixels[x, y] = Color.FromArgb(a, r, g, b); pixelDataIndex += 4; } } } pixelsLoadedEvent.Set(); }); pixelsLoadedEvent.WaitOne(); return pixels; } internal static void ConvertDirectionParameters( DisplayDirection direction, bool flipHorizontal, bool flipVertical, out bool leftToRight, out bool topToBottom, out bool flipAxis) { switch (direction) { case DisplayDirection.Deg0: if (!flipHorizontal && !flipVertical) { leftToRight = true; topToBottom = true; } else if (flipHorizontal && !flipVertical) { leftToRight = false; topToBottom = true; } else if (!flipHorizontal /* && flipVertical */) { leftToRight = true; topToBottom = false; } else /* if (flipHorizontal && flipVertical) */ { leftToRight = false; topToBottom = false; } flipAxis = false; break; case DisplayDirection.Deg90: if (!flipHorizontal && !flipVertical) { leftToRight = false; topToBottom = true; } else if (flipHorizontal && !flipVertical) { leftToRight = true; topToBottom = true; } else if (!flipHorizontal /* && flipVertical */) { leftToRight = false; topToBottom = false; } else /* if (flipHorizontal && flipVertical) */ { leftToRight = true; topToBottom = false; } flipAxis = true; break; case DisplayDirection.Deg180: if (!flipHorizontal && !flipVertical) { leftToRight = false; topToBottom = false; } else if (flipHorizontal && !flipVertical) { leftToRight = true; topToBottom = false; } else if (!flipHorizontal /* && flipVertical */) { leftToRight = false; topToBottom = true; } else /* if (flipHorizontal && flipVertical) */ { leftToRight = true; topToBottom = true; } flipAxis = false; break; case DisplayDirection.Deg270: if (!flipHorizontal && !flipVertical) { leftToRight = true; topToBottom = false; } else if (flipHorizontal && !flipVertical) { leftToRight = false; topToBottom = false; } else if (!flipHorizontal /* && flipVertical */) { leftToRight = true; topToBottom = true; } else /* if (flipHorizontal && flipVertical) */ { leftToRight = false; topToBottom = true; } flipAxis = true; break; default: throw new ArgumentOutOfRangeException(nameof(direction), direction, null); } } public static Color[,] Convert1DTo2D(Color[] pixels) { if (pixels.Length != 64) { throw new ArgumentException("The pixel array must be 64 bytes long (i.e. 8x8).", nameof(pixels)); } var pixels2D = new Color[8, 8]; int i = 0; for (int y = 0; y < 8; y++) { for (int x = 0; x < 8; x++) { pixels2D[x, y] = pixels[i++]; } } return pixels2D; } } }
26.431718
107
0.633333
[ "MIT" ]
HLDAzure/RPi.SenseHat.SBLite
RPi.SenseHat/Rpi.SenseHat/PixelSupport.cs
6,002
C#
using System; namespace ApiHooker.Model { public class CallStackEntry { public ulong Address { get; set; } public ProcessModule Module { get; set; } } }
19
50
0.6
[ "MIT" ]
koczkatamas/apihooker
WindowsController/Model/CallStackEntry.cs
190
C#
using System; using System.Collections.Generic; using System.Linq; using FirstPopCoffee.Common.Domain.Model; namespace FirstPopCoffee.Common.Events { public class EventStore : IEventStore { private readonly IEventPublisher _publisher; private struct EventDescriptor { public readonly Event EventData; public readonly Guid Id; public readonly int Version; public EventDescriptor(Guid id, Event eventData, int version) { EventData = eventData; Version = version; Id = id; } } public EventStore(IEventPublisher publisher) { _publisher = publisher; } private readonly Dictionary<Guid, List<EventDescriptor>> _current = new Dictionary<Guid, List<EventDescriptor>>(); public void SaveEvents(Guid aggregateId, IEnumerable<Event> events, int expectedVersion) { List<EventDescriptor> eventDescriptors; // try to get event descriptors list for given aggregate id // otherwise -> create empty dictionary if (!_current.TryGetValue(aggregateId, out eventDescriptors)) { eventDescriptors = new List<EventDescriptor>(); _current.Add(aggregateId, eventDescriptors); } // check whether latest event version matches current aggregate version // otherwise -> throw exception else if (eventDescriptors[eventDescriptors.Count - 1].Version != expectedVersion && expectedVersion != -1) { throw new ConcurrencyException(); } var i = expectedVersion; // iterate through current aggregate events increasing version with each processed event foreach (var @event in events) { i++; @event.Version = i; // push event to the event descriptors list for current aggregate eventDescriptors.Add(new EventDescriptor(aggregateId, @event, i)); // publish current event to the bus for further processing by subscribers _publisher.Publish(@event); } } // collect all processed events for given aggregate and return them as a list // used to build up an aggregate from its history (Domain.LoadsFromHistory) public List<Event> GetEventsForAggregate(Guid aggregateId) { List<EventDescriptor> eventDescriptors; if (!_current.TryGetValue(aggregateId, out eventDescriptors)) { throw new AggregateNotFoundException(); } return eventDescriptors.Select(desc => desc.EventData).ToList(); } } public class AggregateNotFoundException : Exception { } public class ConcurrencyException : Exception { } }
37.285714
122
0.624521
[ "MIT" ]
heynickc/firstpopcoffee
Common/Events/EventStore.cs
2,873
C#
using System.Configuration; using System.Xml; namespace InstagramFeed.Azure { public class AzureSettingsHandler : IConfigurationSectionHandler { object IConfigurationSectionHandler.Create(object parent, object configContext, XmlNode section) { if (section == null || section.Attributes == null) throw new ConfigurationErrorsException("Required attributes missing."); // REQUIRED attributes if (section.Attributes["connectionString"] == null || section.Attributes["connectionString"].Value.Length == 0) throw new ConfigurationErrorsException("Required attribute 'connectionString' missing from config."); string connectionString = section.Attributes["connectionString"].Value; return new AzureSettings { ConnectionString = connectionString }; } } }
36.8
123
0.658696
[ "MIT" ]
shukriadams/InstagramFeed
InstagramFeed.Azure/Helpers/AzureSettingsHandler.cs
922
C#
/* The MIT License (MIT) Copyright (c) 2007 - 2021 Microting A/S 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. */ namespace eFormAPI.Web.Infrastructure.Models.Settings.Admin { public class HeaderSettingsModel { public string MainText { get; set; } public bool MainTextVisible { get; set; } public string SecondaryText { get; set; } public bool SecondaryTextVisible { get; set; } public string ImageLink { get; set; } public bool ImageLinkVisible { get; set; } } }
42.942857
78
0.756487
[ "MIT" ]
Gid733/eform-angular-frontend
eFormAPI/eFormAPI.Web/Infrastructure/Models/Settings/Admin/HeaderSettingsModel.cs
1,505
C#
using System.Collections.Generic; using System.IO; namespace DotLToExcel.Classes { public class Parser { public List<string> ProcessFile(string filePath, string[] fields) { var data = new List<string>(); using (StreamReader readFile = new StreamReader(filePath)) { string s = string.Empty; while ((s = readFile.ReadLine()) != null) { foreach (var field in fields) { if (Helper.CheckFields(s, field)) { data.Add(Helper.CleanFieldString(s, field)); } } } } return data; } } }
26.566667
73
0.431619
[ "MIT" ]
Vanquish875/DotLToExcel
Classes/Parser.cs
799
C#
using ISAAR.MSolve.Discretization.Interfaces; using ISAAR.MSolve.LinearAlgebra.Matrices; using ISAAR.MSolve.FEM.Interfaces; namespace ISAAR.MSolve.FEM.Providers { public class ElementFirstSpaceDerivativeXProvider : IElementMatrixProvider { public IMatrix Matrix(IElement element) { IConvectionDiffusionElement elementType = (IConvectionDiffusionElement)element.ElementType; return elementType.FirstSpaceDerivativeXMatrix(element); } } }
31.1875
103
0.751503
[ "Apache-2.0" ]
TheoChristo/MSolve.Bio
ISAAR.MSolve.FEM/Providers/ElementFirstSpaceDerivativeXProvider.cs
501
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; using System.IO; using CropModelMKS; namespace CropModelMKS_GUI { public partial class Platform : Form { private readonly Dictionary<string, Dictionary<string, List<string>>> informations; private Dictionary<string, List<string>> states_informations; private readonly Dictionary<string, ListView> list_dict; private readonly Dictionary<string, ComboBox> cbx_dict; private readonly Dictionary<string, TabControl> inputs_dict; private readonly Simulator simulator; private string current_project; private readonly string global_path; private readonly string user_name; public Platform() { InitializeComponent(); global_path = @"C:\Program Files\CropModelMKS"; user_name = Environment.UserName; if (!Directory.Exists(global_path + @"\System\Registrations")) { Directory.CreateDirectory(global_path + @"\System\Registrations"); } if (!Directory.Exists(global_path + @"\System\Descriptions")) { Directory.CreateDirectory(global_path + @"\System\Descriptions"); } if (!Directory.Exists(@"C:\Users\" + user_name + @"\Documents\CropModelMKS\Projects\Simulation")) { Directory.CreateDirectory(@"C:\Users\" + user_name + @"\Documents\CropModelMKS\Projects\Simulation"); } if (!Directory.Exists(@"C:\Users\" + user_name + @"\Documents\CropModelMKS\Projects\Analysis")) { Directory.CreateDirectory(@"C:\Users\" + user_name + @"\Documents\CropModelMKS\Projects\Analysis"); } if (!Directory.Exists(@"C:\Users\" + user_name + @"\Documents\CropModelMKS\Parameters\")) { Directory.CreateDirectory(@"C:\Users\" + user_name + @"\Documents\CropModelMKS\Parameters\"); } if (!Directory.Exists(@"C:\Users\" + user_name + @"\Documents\CropModelMKS\Converted\")) { Directory.CreateDirectory(@"C:\Users\" + user_name + @"\Documents\CropModelMKS\Converted\"); } if (!Directory.Exists(@"C:\Users\" + user_name + @"\Documents\CropModelMKS\Outputs\")) { Directory.CreateDirectory(@"C:\Users\" + user_name + @"\Documents\CropModelMKS\Outputs\"); } informations = new Dictionary<string, Dictionary<string, List<string>>> { { "climate", new Dictionary<string, List<string>>{ } }, { "plant", new Dictionary<string, List<string>>{ } }, { "environment", new Dictionary<string, List<string>>{ } }, { "management", new Dictionary<string, List<string>>{ } }, { "analysis", new Dictionary<string, List<string>>{ } } }; foreach (string type in informations.Keys) { string path = global_path + @"\System\Registrations\" + type + ".XML"; if (!File.Exists(path)) { XmlDocument reg = new XmlDocument(); XmlElement root = reg.CreateElement("Registration"); reg.AppendChild(root); reg.Save(path); } if (!Directory.Exists(global_path + @"\Components\" + type)) { Directory.CreateDirectory(global_path + @"\Components\" + type); } } simulator = new Simulator(); list_dict = new Dictionary<string, ListView> { { "climate", climate_ListView}, { "plant", plant_ListView}, { "environment", environment_ListView}, { "management", management_ListView} }; cbx_dict = new Dictionary<string, ComboBox> { { "climate", cli_cbx}, { "plant",plt_cbx}, { "environment", env_cbx}, { "management", mgt_cbx}, { "analysis", analysis_cbx} }; inputs_dict = new Dictionary<string, TabControl> { { "climate", climate_inputs}, { "plant", plant_inputs}, { "environment", environment_inputs}, { "management", management_inputs} }; XmlDocument doc = new XmlDocument(); foreach (string type in cbx_dict.Keys) { doc.Load(global_path + @"\System\Registrations\" + type + ".XML"); foreach (XmlElement component in doc.GetElementsByTagName("Component")) { string ProgID = component.ChildNodes[0].InnerText; string language = component.ChildNodes[1].InnerText; string location = component.ChildNodes[2].InnerText; informations[type][ProgID] = new List<string>{ language, location}; cbx_dict[type].Items.Add(ProgID); } try { cbx_dict[type].SelectedIndex = 0; } catch { cbx_dict[type].SelectedIndex = -1; } } } private void btn_select_simulator_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog { InitialDirectory = @"C:\Users\" + user_name + @"\Documents\CropModelMKS\Projects\Simulation", Filter = "Simulation Project|*.XML", RestoreDirectory = true, FilterIndex = 1 }; if (dialog.ShowDialog() == DialogResult.Cancel) { simulator_project.Text = ""; return; } simulator_project.Text = dialog.FileName; XmlDocument doc = new XmlDocument(); doc.Load(dialog.FileName); begin_simulator.Text = doc.GetElementsByTagName("Begin")[0].InnerText; end_simulator.Text = doc.GetElementsByTagName("End")[0].InnerText; foreach(XmlElement module in doc.GetElementsByTagName("Module")) { string type = module.GetAttribute("type"); list_dict[type].Items.Clear(); foreach (XmlElement library in module.GetElementsByTagName("Library")) { string begin = library.ChildNodes[3].InnerText; string end = library.ChildNodes[4].InnerText; string ProgID = library.ChildNodes[1].InnerText; string parameter = library.ChildNodes[5].InnerText; Add_To_List(begin, end, ProgID, parameter, list_dict[type]); } } } private void btn_mgt_add_Click(object sender, EventArgs e) { Add_To_List(mgt_begin.Text, mgt_end.Text, mgt_cbx.Text, mgt_parameters.Text, management_ListView); } private void Add_To_List(string begin, string end, string ProgID, string parameter, ListView list) { list.BeginUpdate(); ListViewItem item = new ListViewItem { Text = begin }; item.SubItems.Add(end); item.SubItems.Add(ProgID); item.SubItems.Add(parameter); list.Items.Add(item); list.EndUpdate(); } private void btn_cli_add_Click(object sender, EventArgs e) { Add_To_List(cli_begin.Text, cli_end.Text, cli_cbx.Text, cli_parameters.Text, climate_ListView); } private void btn_plt_add_Click(object sender, EventArgs e) { Add_To_List(plt_begin.Text, plt_end.Text, plt_cbx.Text, plt_parameters.Text, plant_ListView); } private void btn_env_add_Click(object sender, EventArgs e) { Add_To_List(env_begin.Text, env_end.Text, env_cbx.Text, env_parameters.Text, environment_ListView); } private void btn_simulate_Click(object sender, EventArgs e) { if (simulator_project.Text == "") { MessageBox.Show("Please Select A Project File", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } try { simulator.Configurate(simulator_project.Text); simulator.Simulate(); current_project = simulator_project.Text; MessageBox.Show("Simulation Finished!", "NOTICE", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch { MessageBox.Show("Simulation Failed!\n Internal Error In Simulator", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Information); } return; } private void btn_cli_remove_Click(object sender, EventArgs e) { Remove_From_List(climate_ListView); } private void btn_plt_remove_Click(object sender, EventArgs e) { Remove_From_List(plant_ListView); } private void btn_env_remove_Click(object sender, EventArgs e) { Remove_From_List(environment_ListView); } private void btn_mgt_remove_Click(object sender, EventArgs e) { Remove_From_List(management_ListView); } private void Remove_From_List(ListView list) { list.BeginUpdate(); foreach (ListViewItem item in list.SelectedItems) { list.Items.Remove(item); //按项移除 } list.EndUpdate(); } private void btn_save_simulation_project_Click(object sender, EventArgs e) { SaveFileDialog dialog = new SaveFileDialog { InitialDirectory = @"C:\Users\" + user_name + @"\Documents\CropModelMKS\Projects\Simulation", Filter = "Simulation Project|*.XML", RestoreDirectory = true, FilterIndex = 1 }; if (dialog.ShowDialog() == DialogResult.Cancel) { return; } string path = dialog.FileName; simulator_project.Text = path; Dictionary<string, ListView> list_dict= new Dictionary<string, ListView> { }; list_dict["climate"] = climate_ListView; list_dict["plant"] = plant_ListView; list_dict["environment"] = environment_ListView; list_dict["management"] = management_ListView; XmlDocument doc = new XmlDocument(); XmlElement root = doc.CreateElement("Configuration"); doc.AppendChild(root); XmlElement clock = doc.CreateElement("Clock"); root.AppendChild(clock); XmlElement begin_s = doc.CreateElement("Begin"); begin_s.InnerText = begin_simulator.Text; clock.AppendChild(begin_s); XmlElement end_s = doc.CreateElement("End"); end_s.InnerText = end_simulator.Text; clock.AppendChild(end_s); foreach (var list in list_dict) { XmlElement module = doc.CreateElement("Module"); module.SetAttribute("type", list.Key); foreach (ListViewItem item in list.Value.Items) { XmlElement library = doc.CreateElement("Library"); string progid = item.SubItems[2].Text; XmlElement language = doc.CreateElement("language"); language.InnerText = informations[list.Key][progid][0]; library.AppendChild(language); XmlElement ProgID = doc.CreateElement("ProgID"); ProgID.InnerText = progid; library.AppendChild(ProgID); XmlElement location = doc.CreateElement("location"); location.InnerText = informations[list.Key][progid][1]; library.AppendChild(location); XmlElement begin = doc.CreateElement("begin"); begin.InnerText = item.SubItems[0].Text; library.AppendChild(begin); XmlElement end = doc.CreateElement("end"); end.InnerText = item.SubItems[1].Text; library.AppendChild(end); XmlElement parameter = doc.CreateElement("parameters"); parameter.InnerText = item.SubItems[3].Text; string parameter_type = parameter.InnerText.Split('\\').ToArray().Last(). Split('.').ToArray().Last(); library.AppendChild(parameter); if (parameter_type.ToLower() != "xml") { parameter.SetAttribute("type", "Custom"); XmlElement converted = doc.CreateElement("converted"); converted.InnerText = Check.Convert(parameter.InnerText, ProgID.InnerText, language.InnerText, location.InnerText); library.AppendChild(converted); } module.AppendChild(library); } root.AppendChild(module); } doc.Save(path); MessageBox.Show("Simulation Project Saved!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void btn_cli_select_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog { InitialDirectory = "./Progjects/", Filter = "Any File|*.*", RestoreDirectory = true, FilterIndex = 1 }; if (dialog.ShowDialog() == DialogResult.Cancel) { cli_parameters.Text = ""; return; } cli_parameters.Text = dialog.FileName; } private void btn_plt_select_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog { InitialDirectory = "./Progjects/", Filter = "Any File|*.*", RestoreDirectory = true, FilterIndex = 1 }; if (dialog.ShowDialog() == DialogResult.Cancel) { plt_parameters.Text = ""; return; } plt_parameters.Text = dialog.FileName; } private void btn_env_select_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog { InitialDirectory = "./Progjects/", Filter = "Any File|*.*", RestoreDirectory = true, FilterIndex = 1 }; if (dialog.ShowDialog() == DialogResult.Cancel) { env_parameters.Text = ""; return; } env_parameters.Text = dialog.FileName; } private void btn_mgt_select_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog { InitialDirectory = "./Progjects/", Filter = "Any File|*.*", RestoreDirectory = true, FilterIndex = 1 }; if (dialog.ShowDialog() == DialogResult.Cancel) { mgt_parameters.Text = ""; return; } mgt_parameters.Text = dialog.FileName; } private void btn_select_algorithm_Click(object sender, EventArgs e) { Set_Alogrithm(analysis_cbx.Text); } private void Set_Alogrithm(string ProgID) { XmlDocument doc = new XmlDocument(); doc.Load(global_path + @"\System\Descriptions\" + ProgID + ".XML"); while (algorithm_datagrid.Rows.Count != 0) { algorithm_datagrid.Rows.RemoveAt(0); } foreach (XmlElement parameter in doc.GetElementsByTagName("item")) { int index = algorithm_datagrid.Rows.Add(); algorithm_datagrid.Rows[index].Cells[0].Value = parameter.GetAttribute("name"); algorithm_datagrid.Rows[index].Cells[1].Value = ""; algorithm_datagrid.Rows[index].Cells[2].Value = parameter.GetAttribute("size"); algorithm_datagrid.Rows[index].Cells[3].Value = parameter.GetAttribute("type"); } } private void addOneComponentToolStripMenuItem_Click(object sender, EventArgs e) { Form form = new Register_GUI { Text = "Registration" }; form.ShowDialog(); } private void checkTheRegistrationsToolStripMenuItem_Click(object sender, EventArgs e) { Register register = new Register(); register.Check(); MessageBox.Show("Invalid Registrations Removed!", "NOTICE", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void btn_select_simulation_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog { InitialDirectory = @"C:\Users\" + user_name + @"\Documents\CropModelMKS\Projects\Simulation", Filter = "Simulation Project|*.XML", RestoreDirectory = true, FilterIndex = 1 }; if (dialog.ShowDialog() == DialogResult.Cancel) { txt_simulation.Text = ""; return; } txt_simulation.Text = dialog.FileName; Set_Simulation(txt_simulation.Text); } private void Set_Simulation(string path) { Check check = new Check(path); foreach (XmlElement module in check.Parameters().GetElementsByTagName("Module")) { string type = module.GetAttribute("type"); inputs_dict[type].Controls.Clear(); foreach (XmlElement library in module.GetElementsByTagName("Parameters")) { TabPage page = new TabPage { Text = library.GetAttribute("ProgID") }; inputs_dict[type].Controls.Add(page); TabControl control = new TabControl() { Width = 506, Height = 207, Anchor = (AnchorStyles)(Top | Bottom | Left | Right) }; page.Controls.Add(control); foreach (XmlElement section in library.GetElementsByTagName("section")) { TabPage section_page = new TabPage { Text = section.GetAttribute("name") }; control.Controls.Add(section_page); DataGridView data = new DataGridView() { ColumnCount = 6, Left = 0, Top = 0, Width = 496, Height = 181, ColumnHeadersVisible = true, AllowUserToAddRows = false }; section_page.Controls.Add(data); data.Columns[0].Name = "name"; data.Columns[1].Name = "intial value"; data.Columns[2].Name = "max value"; data.Columns[3].Name = "min value"; data.Columns[4].Name = "size"; data.Columns[5].Name = "type"; data.Columns[0].ReadOnly = true; data.Columns[4].ReadOnly = true; data.Columns[5].ReadOnly = true; foreach (XmlElement parameter in section.GetElementsByTagName("item")) { int index = data.Rows.Add(); data.Rows[index].Cells[0].Value = parameter.GetAttribute("name"); data.Rows[index].Cells[1].Value = ""; data.Rows[index].Cells[2].Value = ""; data.Rows[index].Cells[3].Value = ""; data.Rows[index].Cells[4].Value = parameter.GetAttribute("size"); data.Rows[index].Cells[5].Value = parameter.GetAttribute("type"); } } } } out_tree.Nodes.Clear(); states_informations = new Dictionary<string, List<string>> { }; foreach (XmlElement module in check.States().GetElementsByTagName("Module")) { TreeNode current = new TreeNode { Text = module.GetAttribute("type") }; out_tree.Nodes.Add(current); foreach(XmlElement state in module.GetElementsByTagName("item")) { string name = state.GetAttribute("name"); states_informations[name] = new List<string> { state.GetAttribute("size"), state.GetAttribute("type") }; TreeNode item = new TreeNode { Checked = false, Text = name }; current.Nodes.Add(item); } } } private void btn_save_analysis_Click(object sender, EventArgs e) { SaveFileDialog dialog = new SaveFileDialog { InitialDirectory = @"C:\Users\" + user_name + @"\Documents\CropModelMKS\Projects\Analysis\", Filter = "Analysis Project|*.XML", RestoreDirectory = true, FilterIndex = 1 }; if (dialog.ShowDialog() == DialogResult.Cancel) { return; } txt_analysis.Text = dialog.FileName; XmlDocument doc = new XmlDocument(); XmlElement root = doc.CreateElement("Configuration"); doc.AppendChild(root); //Analyzer Configuration XmlElement analyzer_configuration = doc.CreateElement("AnalyzerConfiguration"); root.AppendChild(analyzer_configuration); XmlElement ProgID = doc.CreateElement("ProgID"); ProgID.InnerText = analysis_cbx.Text; analyzer_configuration.AppendChild(ProgID); XmlElement language = doc.CreateElement("language"); language.InnerText = informations["analysis"][analysis_cbx.Text][0]; analyzer_configuration.AppendChild(language); XmlElement location = doc.CreateElement("ProgID"); location.InnerText = informations["analysis"][analysis_cbx.Text][1]; analyzer_configuration.AppendChild(location); //Algorithm Parameters XmlElement parameters = doc.CreateElement("Parameters"); analyzer_configuration.AppendChild(parameters); foreach (DataGridViewRow row in algorithm_datagrid.Rows) { XmlElement parameter = doc.CreateElement("Parameter"); parameter.SetAttribute("size", row.Cells[2].Value.ToString()); parameter.SetAttribute("type", row.Cells[3].Value.ToString()); XmlElement name = doc.CreateElement("name"); parameter.AppendChild(name); name.InnerText = row.Cells[0].Value.ToString(); XmlElement value = doc.CreateElement("value"); parameter.AppendChild(value); value.InnerText = row.Cells[1].Value.ToString(); parameters.AppendChild(parameter); } //Simulator configurations XmlElement simulator_configurations = doc.CreateElement("SimulationConfiguration"); root.AppendChild(simulator_configurations); //Project XmlElement project = doc.CreateElement("Project"); project.InnerText = txt_simulation.Text; simulator_configurations.AppendChild(project); //Inputs XmlElement inputs = doc.CreateElement("Inputs"); simulator_configurations.AppendChild(inputs); Dictionary<string, int> ProgID_count = new Dictionary<string, int> { }; foreach (TabControl module in inputs_dict.Values) { foreach(TabPage page in module.Controls) { string ID = page.Text; try { ProgID_count[ID] += 1; } catch (KeyNotFoundException) { ProgID_count[ID] = 1; } foreach(TabPage section in page.Controls[0].Controls) { foreach (DataGridView data in section.Controls) { foreach (DataGridViewRow row in data.Rows) { if (row.Cells[1].Value.ToString() == "") { continue; } XmlElement paramter = doc.CreateElement("Parameter"); inputs.AppendChild(paramter); paramter.SetAttribute("ProgID", ID); paramter.SetAttribute("index", ProgID_count[ID].ToString()); XmlElement name = doc.CreateElement("name"); name.InnerText = row.Cells[0].Value.ToString(); paramter.AppendChild(name); XmlElement initial = doc.CreateElement("initial"); initial.InnerText = row.Cells[1].Value.ToString(); paramter.AppendChild(initial); XmlElement upper = doc.CreateElement("upper"); upper.InnerText = row.Cells[2].Value.ToString(); paramter.AppendChild(upper); XmlElement lower = doc.CreateElement("lower"); lower.InnerText = row.Cells[3].Value.ToString(); paramter.AppendChild(lower); } } } } } //Outputs XmlElement outputs = doc.CreateElement("Outputs"); simulator_configurations.AppendChild(outputs); foreach (TreeNode module in out_tree.Nodes) { foreach (TreeNode state in module.Nodes) { if (!state.Checked) { continue; } string name = state.Text; XmlElement item = doc.CreateElement("item"); item.SetAttribute("name", name); item.SetAttribute("size", states_informations[name][0]); item.SetAttribute("type", states_informations[name][1]); outputs.AppendChild(item); } } doc.Save(txt_analysis.Text); MessageBox.Show("Analysis Project Saved Successfully!", "Inforamtion", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void btn_select_analysis_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog { InitialDirectory = @"C:\Users\" + Environment.UserName + @"\Documents\CropModelMKS\Projects\Analysis\", Filter = "Analysis Project|*.XML", RestoreDirectory = false, FilterIndex = 1 }; if (dialog.ShowDialog() == DialogResult.Cancel) { txt_analysis.Text = ""; return; } txt_analysis.Text = dialog.FileName; XmlDocument doc = new XmlDocument(); doc.Load(txt_analysis.Text); txt_simulation.Text = doc.GetElementsByTagName("Project")[0].InnerText; Set_Simulation(txt_simulation.Text); analysis_cbx.Text = doc.GetElementsByTagName("ProgID")[0].InnerText; Set_Alogrithm(analysis_cbx.Text); //Set Analysis Parameters XmlElement parameters = (XmlElement)doc.GetElementsByTagName("Parameters")[0]; foreach (XmlElement parameter in parameters.GetElementsByTagName("Parameter")) { string name = parameter.ChildNodes[0].InnerText; string value = parameter.ChildNodes[1].InnerText; foreach (DataGridViewRow row in algorithm_datagrid.Rows) { if (row.Cells[0].Value.ToString() == name) { row.Cells[1].Value = value; } } }; //Set Simulation Parameters XmlElement inputs = (XmlElement)doc.GetElementsByTagName("Inputs")[0]; Dictionary<string, int> ProgID_count = new Dictionary<string, int> { }; foreach (TabControl module in inputs_dict.Values) { foreach (TabPage page in module.Controls) { string ID = page.Text; try { ProgID_count[ID] += 1; } catch (KeyNotFoundException) { ProgID_count[ID] = 1; } foreach (TabPage section in page.Controls[0].Controls) { foreach (DataGridView data in section.Controls) { foreach (DataGridViewRow row in data.Rows) { foreach (XmlElement parameter in inputs.GetElementsByTagName("Parameter")) { if (ID != parameter.GetAttribute("ProgID")) { continue; } if (int.Parse(parameter.GetAttribute("index")) != ProgID_count[ID]) { continue; } if (parameter.ChildNodes[0].InnerText == row.Cells[0].Value.ToString()) { row.Cells[1].Value = parameter.ChildNodes[1].InnerText; row.Cells[2].Value = parameter.ChildNodes[2].InnerText; row.Cells[3].Value = parameter.ChildNodes[3].InnerText; break; } } } } } } } //Set Outputs foreach (XmlElement state in doc.GetElementsByTagName("item")) { string name = state.GetAttribute("name"); foreach (TreeNode module in out_tree.Nodes) { foreach (TreeNode node in module.Nodes) { if (node.Text == name) { node.Checked = true; } } } } } private void btn_cli_create_Click(object sender, EventArgs e) { Parameter_GUI dialog = new Parameter_GUI(cli_cbx.Text) { Text = "Parameters" }; dialog.ShowDialog(); } private void btn_analyze_Click(object sender, EventArgs e) { if (txt_analysis.Text == "") { MessageBox.Show("Please Select A Project File", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Analyzer analyzer = new Analyzer(); analyzer.Configurate(txt_analysis.Text); analyzer.Analyze(); MessageBox.Show("Analysis Completed!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void btn_display_Click(object sender, EventArgs e) { if (current_project == null) { MessageBox.Show("No Simulation Carried Out Yet!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Check check = new Check(current_project); Display_GUI dialog = new Display_GUI(simulator, check.States()) { Text = "Display" }; dialog.ShowDialog(); } private void updateTheDescriptionsToolStripMenuItem_Click(object sender, EventArgs e) { Register register = new Register(); register.Update(); MessageBox.Show("Descriptions Updated!", "NOTICE", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void btn_save_result_Click(object sender, EventArgs e) { if (simulator_project.Text == "") { MessageBox.Show("Please Select A Simulation Project!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (current_project == null) { MessageBox.Show("No Simulation Carried Out Yet!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } FolderBrowserDialog dialog = new FolderBrowserDialog { Description = "Select A Folder to Save the Results", SelectedPath = @"C:\Users\" + Environment.UserName + @"\Documents\CropModelMKS\Outputs\" }; if (dialog.ShowDialog() == DialogResult.OK) { Check check = new Check(current_project); XmlDocument states = check.States(); foreach (XmlElement module in states.GetElementsByTagName("Module")) { string current_folder = dialog.SelectedPath + @"\" + module.GetAttribute("type"); Directory.CreateDirectory(current_folder); List<string> single_values = new List<string>(); List<string> array_values = new List<string>(); foreach (XmlElement item in module.GetElementsByTagName("item")) { if (item.GetAttribute("size") == "single") { single_values.Add(item.GetAttribute("name")); } else { array_values.Add(item.GetAttribute("name")); } } FileStream fs = new FileStream(current_folder + @"\Single Value Results.txt", FileMode.Create); StreamWriter sw = new StreamWriter(fs); foreach (string name in single_values) { sw.Write(name + "\t"); } sw.Write('\n'); int i = 1; while (true) { try { foreach (string name in single_values) { object value = simulator.Inquire(name, i); sw.Write(value); sw.Write("\t"); } sw.Write("\n"); i++; } catch { //clear the buffer sw.Flush(); //close the stream sw.Close(); fs.Close(); break; } } foreach (string name in array_values) { FileStream file_array = new FileStream(current_folder + @"\" + name + ".txt", FileMode.Create); StreamWriter stream_array = new StreamWriter(file_array); i = 1; while (true) { try { try { float[] values = (float[])simulator.Inquire(name, i); stream_array.Write(i); stream_array.Write("\t"); foreach (float value in values) { stream_array.Write(value); stream_array.Write("\t"); } } catch { try { double[] values = (double[])simulator.Inquire(name, i); stream_array.Write(i); stream_array.Write("\t"); foreach (double value in values) { stream_array.Write(value); stream_array.Write("\t"); } } catch { int[] values = (int[])simulator.Inquire(name, i); stream_array.Write(i); stream_array.Write("\t"); foreach (int value in values) { stream_array.Write(value); stream_array.Write("\t"); } } } stream_array.Write("\n"); i++; } catch { //clear the buffer stream_array.Flush(); //close the stream stream_array.Close(); file_array.Close(); break; } } } } MessageBox.Show("Simulation Results Saved!\n in " + dialog.SelectedPath, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } }
37.14557
119
0.472775
[ "MIT" ]
SongJim624/CropModelMKS
Compile Solution/CropModelMKS/CropModelMKS_GUI/Platform.cs
41,093
C#
using System; using Feedz.Client.Resources; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Feedz.Client.Plumbing.Converters { public class PackageJsonConverter : JsonConverter { public override bool CanConvert(Type objectType) => typeof(PackageResource).IsAssignableFrom(objectType); public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JObject jo = JObject.Load(reader); var type = jo["type"].Value<string>(); switch (type) { case "NuGet": return jo.ToObject<NuGetPackageResource>(); case "Generic": return jo.ToObject<GenericPackageResource>(); case "Npm": return jo.ToObject<NpmPackageResource>(); default: throw new NotSupportedException("This version of the client does not support packages of type " + type); } } public override bool CanWrite => false; public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } } }
34.648649
124
0.604524
[ "Apache-2.0" ]
feedz-io/Client
src/Client/Plumbing/Converters/PackageJsonConverter.cs
1,282
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! namespace Google.Cloud.Dialogflow.Cx.V3Beta1.Snippets { using Google.Cloud.Dialogflow.Cx.V3Beta1; public sealed partial class GeneratedSessionsClientStandaloneSnippets { /// <summary>Snippet for MatchIntent</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void MatchIntentRequestObject() { // Create client SessionsClient sessionsClient = SessionsClient.Create(); // Initialize request argument(s) MatchIntentRequest request = new MatchIntentRequest { SessionAsSessionName = SessionName.FromProjectLocationAgentSession("[PROJECT]", "[LOCATION]", "[AGENT]", "[SESSION]"), QueryParams = new QueryParameters(), QueryInput = new QueryInput(), }; // Make the request MatchIntentResponse response = sessionsClient.MatchIntent(request); } } }
39.181818
134
0.668213
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/cloud/dialogflow/cx/v3beta1/google-cloud-dialogflow-cx-v3beta1-csharp/Google.Cloud.Dialogflow.Cx.V3Beta1.StandaloneSnippets/SessionsClient.MatchIntentRequestObjectSnippet.g.cs
1,724
C#
using Couchbase; using Couchbase.Configuration.Client; using Couchbase.Core.Serialization; using Newtonsoft.Json; using System; using System.Collections.Generic; using Tweek.ApiService.Addons; using Tweek.Engine.Drivers.Context; namespace Tweek.Drivers.Context.Couchbase.IntegrationTests { public class CouchbaseIntegrationTests: ContextIntegrationTests.IntegrationTests { public CouchbaseIntegrationTests() { var url = Environment.GetEnvironmentVariable("COUCHBASE_TEST_URL"); const string bucketName = "testbucket"; const string bucketPassword = "password"; if (!ClusterHelper.Initialized) { ClusterHelper.Initialize(new ClientConfiguration { Servers = new List<Uri> { new Uri(url) }, BucketConfigs = new Dictionary<string, BucketConfiguration> { [bucketName] = new BucketConfiguration { BucketName = bucketName, Password = bucketPassword, PoolConfiguration = new PoolConfiguration() { MaxSize = 30, MinSize = 5 } }, }, Serializer = () => new DefaultSerializer( new JsonSerializerSettings() { ContractResolver = new TweekContractResolver() }, new JsonSerializerSettings() { ContractResolver = new TweekContractResolver() }) }); } Driver = new CouchBaseDriver(ClusterHelper.GetBucket, bucketName); } protected sealed override IContextDriver Driver { get; set; } } }
36.125
84
0.501236
[ "MIT" ]
Gabrn/tweek
addons/Context/Tweek.Drivers.Context.Couchbase.IntegrationTests/CouchbaseIntegrationTests.cs
2,023
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using View.Windows.Forms.Controls.Enums; namespace View.Windows.Forms.Controls { [DefaultEvent("ThemeStyleChanged"), DefaultProperty("ThemeStyle")] public partial class ControlSet : Component { // 字段 private static ThemeType _themeStyle = ThemeType.Light; private static Color themeColor = Color.FromArgb(41, 98, 255); private static Color lightForeColor = Color.FromArgb(33, 33, 33); private static Color lightBackColor = Color.FromArgb(242, 242, 242); private static Color drakForeColor = Color.FromArgb(239, 239, 239); private static Color drakBackColor = Color.FromArgb(43, 43, 43); // 构造 /// <summary> /// 初始化 /// </summary> public ControlSet() { InitializeComponent(); } /// <summary> /// 初始化 /// </summary> /// <param name="container"></param> public ControlSet(IContainer container) { container.Add(this); InitializeComponent(); } // 事件 /// <summary> /// 当背景色改变时发生 /// </summary> [Browsable(true), Description("当主题样式改变时发生")] public static event EventHandler ThemeStyleChanged; /// <summary> /// 当主题色改变时发生 /// </summary> [Browsable(true), Description("当主题色改变时发生")] public static event EventHandler ThemeColorChanged; // 属性 /// <summary> /// 获取或设置所有控件的主题样式 /// </summary> [Browsable(true), Category("数据"), Description("获取或设置所有控件的主题样式")] public static ThemeType ThemeStyle { get { return _themeStyle; } set { _themeStyle = value; ThemeStyleChanged?.Invoke(_themeStyle, new EventArgs()); } } /// <summary> /// 获取或设置所有控件的主题色 /// </summary> [Browsable(true), Category("数据"), Description("获取或设置所有控件的主题色")] public static Color ThemeColor { get { return themeColor; } set { themeColor = value; ThemeColorChanged?.Invoke(themeColor, new EventArgs()); } } /// <summary> /// 获取或设置当前主题下的背景色 /// </summary> [Browsable(true), Category("数据"), Description("获取或设置当前主题下的背景色")] public static Color BackColor { get { if (_themeStyle == ThemeType.Light) { return lightBackColor; } else { return drakBackColor; } } set { if (_themeStyle == ThemeType.Light) { lightBackColor = value; } else { drakBackColor = value; } } } /// <summary> /// 获取或设置当前主题下的前景色 /// </summary> [Browsable(true), Category("数据"), Description("获取或设置当前主题下的前景色")] public static Color ForeColor { get { if (_themeStyle == ThemeType.Light) { return lightForeColor; } else { return drakForeColor; } } set { if (_themeStyle == ThemeType.Light) { lightForeColor = value; } else { drakForeColor = value; } } } } }
27.285714
76
0.464473
[ "MIT" ]
View12138/View.Libraries
src/View.Windows.Forms.Controls/Controls/ControlSet.cs
4,351
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace FavourAPI.Data.Models { public class Subscription { [Key] [Column(TypeName = "uniqueidentifier")] public Guid Id { get; set; } public DateTime Start { get; set; } public DateTime End { get; set; } public virtual Role Role { get; set; } public virtual User User { get; set; } public double Amount { get; set; } } }
22.8
51
0.647368
[ "MIT" ]
indeavr/favour-api
FavourAPI.Data/Models/User/Subscription.cs
572
C#
// <copyright file="ActionResult.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> using System; using System.Collections.Generic; using System.Xml.Linq; using JetBrains.Annotations; namespace FubarDev.WebDavServer.Engines { /// <summary> /// The result of an action /// </summary> public class ActionResult { /// <summary> /// Initializes a new instance of the <see cref="ActionResult"/> class. /// </summary> /// <param name="status">The status of the action</param> /// <param name="target">The element this status is for</param> public ActionResult(ActionStatus status, [NotNull] ITarget target) { Status = status; Target = target; Href = target.DestinationUrl; } /// <summary> /// Gets the status of the action /// </summary> public ActionStatus Status { get; } /// <summary> /// Gets the target entry this action status is for /// </summary> [NotNull] public ITarget Target { get; } /// <summary> /// Gets or sets the destination URL for the <see cref="Target"/> /// </summary> [NotNull] public Uri Href { get; set; } /// <summary> /// Gets or sets the exception that occurred during the execution of the action /// </summary> [CanBeNull] public Exception Exception { get; set; } /// <summary> /// Gets or sets the names of properties that couldn't be set. /// </summary> [CanBeNull] [ItemNotNull] public IReadOnlyCollection<XName> FailedProperties { get; set; } /// <summary> /// Gets a value indicating whether the action failed /// </summary> public bool IsFailure => Status != ActionStatus.Created && Status != ActionStatus.Overwritten; } }
30.106061
102
0.580775
[ "MIT" ]
FubarDevelopment/WebDavServer
src/FubarDev.WebDavServer/Engines/ActionResult.cs
1,989
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using BookCave.Models; using BookCave.Data.EntityModels; using Microsoft.AspNetCore.Diagnostics; using BookCave.Services; using Microsoft.AspNetCore.Http; namespace BookCave.Controllers { public class HomeController : Controller { private readonly BookService _bookService; private readonly CookieService _cookieService; private readonly IHttpContextAccessor _httpContextAccessor; public HomeController(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; _bookService = new BookService(); _cookieService = new CookieService(_httpContextAccessor); } public IActionResult Index() { var books = _bookService.Recommended(); //_cookieService.InitializeCookie(); //_cookieService.AddToCartCookie(2, "2323"); //_cookieService.RemoveFromCartCookie(2323); _cookieService.InitializeCookie(); return View(books); } public IActionResult Error() { return View("Error"); } public IActionResult Error404() { return View("PageNotFound"); } } }
28.730769
72
0.64257
[ "MIT" ]
Ingi-Thor/Book-Cave
Controllers/HomeController.cs
1,494
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace TrayWebApp { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
17.944444
40
0.705882
[ "MIT" ]
ZeRoZeRoRaZ/TrayWebApp
TrayWebApp/App.xaml.cs
325
C#
// ----------------------------------------------------------------------- // <copyright file="DbContextConfig.cs" company="OSharp开源团队"> // Copyright (c) 2014-2017 OSharp. All rights reserved. // </copyright> // <site>http://www.osharp.org</site> // <last-editor>郭明锋</last-editor> // <last-date>2017-09-03 0:54</last-date> // ----------------------------------------------------------------------- using System; using OSharp.Entity; namespace OSharp.Core.Options { /// <summary> /// 数据上下文配置节点 /// </summary> public class OSharpDbContextOptions { /// <summary> /// 初始化一个<see cref="OSharpDbContextOptions"/>类型的新实例 /// </summary> public OSharpDbContextOptions() { LazyLoadingProxiesEnabled = false; AuditEntityEnabled = false; AutoMigrationEnabled = false; } /// <summary> /// 获取 上下文类型 /// </summary> public Type DbContextType => string.IsNullOrEmpty(DbContextTypeName) ? null : Type.GetType(DbContextTypeName); /// <summary> /// 获取或设置 上下文类型全名 /// </summary> public string DbContextTypeName { get; set; } /// <summary> /// 获取或设置 连接字符串 /// </summary> public string ConnectionString { get; set; } /// <summary> /// 获取或设置 数据库类型 /// </summary> public DatabaseType DatabaseType { get; set; } /// <summary> /// 获取或设置 是否启用延迟加载代理 /// </summary> public bool LazyLoadingProxiesEnabled { get; set; } /// <summary> /// 获取或设置 是否允许审计实体 /// </summary> public bool AuditEntityEnabled { get; set; } /// <summary> /// 获取或设置 是否自动迁移 /// </summary> public bool AutoMigrationEnabled { get; set; } } }
27.298507
118
0.505194
[ "Apache-2.0" ]
Caoyt688/osharp-ns20
src/OSharp/Core/Options/OSharpDbContextOptions.cs
2,041
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Data; using OpenMetaverse; using OpenSim.Framework; #if CSharpSqlite using Community.CsharpSqlite.Sqlite; #else using Mono.Data.Sqlite; #endif namespace OpenSim.Data.SQLite { /// <summary> /// A database interface class to a user profile storage system /// </summary> public class SQLiteFramework { protected Object m_lockObject = new Object(); protected SQLiteFramework(string connectionString) { } ////////////////////////////////////////////////////////////// // // All non queries are funneled through one connection // to increase performance a little // protected int ExecuteNonQuery(SqliteCommand cmd, SqliteConnection connection) { lock (connection) { /* SqliteConnection newConnection = (SqliteConnection)((ICloneable)connection).Clone(); newConnection.Open(); cmd.Connection = newConnection; */ cmd.Connection = connection; //Console.WriteLine("XXX " + cmd.CommandText); return cmd.ExecuteNonQuery(); } } protected IDataReader ExecuteReader(SqliteCommand cmd, SqliteConnection connection) { lock (connection) { //SqliteConnection newConnection = // (SqliteConnection)((ICloneable)connection).Clone(); //newConnection.Open(); //cmd.Connection = newConnection; cmd.Connection = connection; //Console.WriteLine("XXX " + cmd.CommandText); return cmd.ExecuteReader(); } } protected void CloseCommand(SqliteCommand cmd) { cmd.Connection.Close(); cmd.Connection.Dispose(); cmd.Dispose(); } } }
36.35
91
0.640715
[ "BSD-3-Clause" ]
N3X15/VoxelSim
OpenSim/Data/SQLite/SQLiteFramework.cs
3,635
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace HotChocolate.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class CoreResources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal CoreResources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("HotChocolate.Properties.CoreResources", typeof(CoreResources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Unable to find a compatible input type for the exported object type.. /// </summary> internal static string BatchColVars_NoCompatibleType { get { return ResourceManager.GetString("BatchColVars_NoCompatibleType", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not serialize the specified variable.. /// </summary> internal static string BatchQueryExec_CannotSerialize { get { return ResourceManager.GetString("BatchQueryExec_CannotSerialize", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The query key mustn&apos;t be null or empty.. /// </summary> internal static string CachedQuery_Key_Is_Null { get { return ResourceManager.GetString("CachedQuery_Key_Is_Null", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not resolve the actual object type from `{0}` for the abstract type `{1}`.. /// </summary> internal static string CompleteCompositeType_UnknownSchemaType { get { return ResourceManager.GetString("CompleteCompositeType_UnknownSchemaType", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Undefined scalar field serialization error.. /// </summary> internal static string CompleteLeadType_UndefinedError { get { return ResourceManager.GetString("CompleteLeadType_UndefinedError", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The internal resolver value could not be converted to a valid value of `{0}`.. /// </summary> internal static string CompleteLeafType_CannotConvertValue { get { return ResourceManager.GetString("CompleteLeafType_CannotConvertValue", resourceCulture); } } /// <summary> /// Looks up a localized string similar to A list values must implement `{0}` in order to be completed.. /// </summary> internal static string CompleteList_ListTypeInvalid { get { return ResourceManager.GetString("CompleteList_ListTypeInvalid", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The {0} if-argument value has to be a &apos;Boolean&apos;.. /// </summary> internal static string DirectiveCollectionExtensions_IfNotBoolean { get { return ResourceManager.GetString("DirectiveCollectionExtensions_IfNotBoolean", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The {0}-directive is missing the if-argument.. /// </summary> internal static string DirectiveCollectionExtensions_NotValid { get { return ResourceManager.GetString("DirectiveCollectionExtensions_NotValid", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Unexpected Execution Error. /// </summary> internal static string ErrorHandler_ErrorIsNull { get { return ResourceManager.GetString("ErrorHandler_ErrorIsNull", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Unexpected Execution Error. /// </summary> internal static string ErrorHandler_UnexpectedError { get { return ResourceManager.GetString("ErrorHandler_UnexpectedError", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The execute operation middleware expects the query document to be parsed and the operation to be resolved.. /// </summary> internal static string ExecuteOperationMiddleware_InComplete { get { return ResourceManager.GetString("ExecuteOperationMiddleware_InComplete", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Operation not supported.. /// </summary> internal static string ExecutionStrategyResolver_NotSupported { get { return ResourceManager.GetString("ExecutionStrategyResolver_NotSupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not resolve the specified field.. /// </summary> internal static string FieldCollector_FieldNotFound { get { return ResourceManager.GetString("FieldCollector_FieldNotFound", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The specified operation `{0}` does not exist.. /// </summary> internal static string GetOperation_InvalidOperationName { get { return ResourceManager.GetString("GetOperation_InvalidOperationName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Only queries that contain one operation can be executed without specifying the opartion name.. /// </summary> internal static string GetOperation_MultipleOperations { get { return ResourceManager.GetString("GetOperation_MultipleOperations", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Cannot return null for non-nullable field.. /// </summary> internal static string HandleNonNullViolation_Message { get { return ResourceManager.GetString("HandleNonNullViolation_Message", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The operation that shall be executed has a complexity of {0}. ///The maximum allowed query complexity is {1}.. /// </summary> internal static string MaxComplexityMiddleware_NotAllowed { get { return ResourceManager.GetString("MaxComplexityMiddleware_NotAllowed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The max complexity middleware expects the query document to be parsed and the operation to be resolved.. /// </summary> internal static string MaxComplexityMiddleware_Prerequisite { get { return ResourceManager.GetString("MaxComplexityMiddleware_Prerequisite", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The specified query type is not supported.. /// </summary> internal static string ParseQuery_Middleware_QueryTypeNotSupported { get { return ResourceManager.GetString("ParseQuery_Middleware_QueryTypeNotSupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The parse query middleware expects a valid query request.. /// </summary> internal static string ParseQueryMiddleware_InComplete { get { return ResourceManager.GetString("ParseQueryMiddleware_InComplete", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The argument name mustn&apos;t be null or empty.. /// </summary> internal static string QueryError_ArgumentIsNull { get { return ResourceManager.GetString("QueryError_ArgumentIsNull", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The error message mustn&apos;t be null or empty.. /// </summary> internal static string QueryError_MessageIsNull { get { return ResourceManager.GetString("QueryError_MessageIsNull", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The variable name mustn&apos;t be null or empty.. /// </summary> internal static string QueryError_VariableIsNull { get { return ResourceManager.GetString("QueryError_VariableIsNull", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The execution pipeline yielded no query result.. /// </summary> internal static string QueryExecutor_NoResult { get { return ResourceManager.GetString("QueryExecutor_NoResult", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The query mustn&apos;t be null or empty.. /// </summary> internal static string QueryExecutorExtensions_QueryIsNullOrEmpty { get { return ResourceManager.GetString("QueryExecutorExtensions_QueryIsNullOrEmpty", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The read persisted query middleware expects a valid query request.. /// </summary> internal static string Read_PQ_Middleware_Incomplete { get { return ResourceManager.GetString("Read_PQ_Middleware_Incomplete", resourceCulture); } } /// <summary> /// Looks up a localized string similar to PersistedQueryNotFound. /// </summary> internal static string Read_PQ_Middleware_QueryNotFound { get { return ResourceManager.GetString("Read_PQ_Middleware_QueryNotFound", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The specified query type is not supported.. /// </summary> internal static string Read_PQ_Middleware_QueryTypeNotSupported { get { return ResourceManager.GetString("Read_PQ_Middleware_QueryTypeNotSupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Execution timeout has been exceeded.. /// </summary> internal static string RequestTimeoutMiddleware_Timeout { get { return ResourceManager.GetString("RequestTimeoutMiddleware_Timeout", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The specified type is not supported.. /// </summary> internal static string ResolveObjectType_TypeNotSupported { get { return ResourceManager.GetString("ResolveObjectType_TypeNotSupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not convert argument `{0}` from `{1}` to `{2}`.. /// </summary> internal static string ResolverContext_ArgumentConversion { get { return ResourceManager.GetString("ResolverContext_ArgumentConversion", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The specified property does not exist.. /// </summary> internal static string ResolverContext_CustomPropertyNotExists { get { return ResourceManager.GetString("ResolverContext_CustomPropertyNotExists", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not cast the source object to `{0}`.. /// </summary> internal static string ResolverContext_Parent_InvalidCast { get { return ResourceManager.GetString("ResolverContext_Parent_InvalidCast", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The specified root type `{0}` does not exist.. /// </summary> internal static string ResolveRootType_DoesNotExist { get { return ResourceManager.GetString("ResolveRootType_DoesNotExist", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The error message cannot be null or empty.. /// </summary> internal static string ResolverTask_ErrorMessageIsNull { get { return ResourceManager.GetString("ResolverTask_ErrorMessageIsNull", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Register a event registry as service in order to use subsciptions.. /// </summary> internal static string SubscriptionExecutionStrategy_NoEventRegistry { get { return ResourceManager.GetString("SubscriptionExecutionStrategy_NoEventRegistry", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Subscriptions must have one and only one root field.. /// </summary> internal static string Subscriptions_SingleRootField { get { return ResourceManager.GetString("Subscriptions_SingleRootField", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Only query results are supported.. /// </summary> internal static string ToJson_OnlyQueryResultsSupported { get { return ResourceManager.GetString("ToJson_OnlyQueryResultsSupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The validation middleware expects the query document to be parsed.. /// </summary> internal static string ValidateQueryMiddleware_NoDocument { get { return ResourceManager.GetString("ValidateQueryMiddleware_NoDocument", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The specified variable was not declared.. /// </summary> internal static string VariableCollection_VariableNotDeclared { get { return ResourceManager.GetString("VariableCollection_VariableNotDeclared", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Unable to convert the specified variable value.. /// </summary> internal static string VarRewriter_CannotConvert { get { return ResourceManager.GetString("VarRewriter_CannotConvert", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Unknown field.. /// </summary> internal static string VarRewriter_UnknownField { get { return ResourceManager.GetString("VarRewriter_UnknownField", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The write persisted query middleware expects a valid query request.. /// </summary> internal static string Write_PQ_Middleware_Incomplete { get { return ResourceManager.GetString("Write_PQ_Middleware_Incomplete", resourceCulture); } } } }
41.59436
186
0.595254
[ "MIT" ]
Asshiah/hotchocolate
src/HotChocolate/Core/src/Core/Properties/CoreResources.Designer.cs
19,177
C#
namespace Azure.ResourceManager.KeyVault { public static partial class ArmClientExtensions { public static Azure.ResourceManager.KeyVault.DeletedManagedHsm GetDeletedManagedHsm(this Azure.ResourceManager.ArmClient client, Azure.Core.ResourceIdentifier id) { throw null; } public static Azure.ResourceManager.KeyVault.DeletedVault GetDeletedVault(this Azure.ResourceManager.ArmClient client, Azure.Core.ResourceIdentifier id) { throw null; } public static Azure.ResourceManager.KeyVault.ManagedHsm GetManagedHsm(this Azure.ResourceManager.ArmClient client, Azure.Core.ResourceIdentifier id) { throw null; } public static Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection GetMhsmPrivateEndpointConnection(this Azure.ResourceManager.ArmClient client, Azure.Core.ResourceIdentifier id) { throw null; } public static Azure.ResourceManager.KeyVault.PrivateEndpointConnection GetPrivateEndpointConnection(this Azure.ResourceManager.ArmClient client, Azure.Core.ResourceIdentifier id) { throw null; } public static Azure.ResourceManager.KeyVault.Secret GetSecret(this Azure.ResourceManager.ArmClient client, Azure.Core.ResourceIdentifier id) { throw null; } public static Azure.ResourceManager.KeyVault.Vault GetVault(this Azure.ResourceManager.ArmClient client, Azure.Core.ResourceIdentifier id) { throw null; } public static Azure.ResourceManager.KeyVault.VaultKey GetVaultKey(this Azure.ResourceManager.ArmClient client, Azure.Core.ResourceIdentifier id) { throw null; } public static Azure.ResourceManager.KeyVault.VaultKeyVersion GetVaultKeyVersion(this Azure.ResourceManager.ArmClient client, Azure.Core.ResourceIdentifier id) { throw null; } } public partial class DeletedManagedHsm : Azure.ResourceManager.Core.ArmResource { public static readonly Azure.Core.ResourceType ResourceType; protected DeletedManagedHsm() { } public virtual Azure.ResourceManager.KeyVault.DeletedManagedHsmData Data { get { throw null; } } public virtual bool HasData { get { throw null; } } public static Azure.Core.ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string location, string name) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.DeletedManagedHsm> Get(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.DeletedManagedHsm>> GetAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.ResourceManager.ArmOperation PurgeDeleted(bool waitForCompletion, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation> PurgeDeletedAsync(bool waitForCompletion, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class DeletedManagedHsmCollection : Azure.ResourceManager.Core.ArmCollection { protected DeletedManagedHsmCollection() { } public virtual Azure.Response<bool> Exists(string location, string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<bool>> ExistsAsync(string location, string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.DeletedManagedHsm> Get(string location, string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.DeletedManagedHsm>> GetAsync(string location, string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.DeletedManagedHsm> GetIfExists(string location, string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.DeletedManagedHsm>> GetIfExistsAsync(string location, string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class DeletedManagedHsmData : Azure.ResourceManager.Models.ResourceData { internal DeletedManagedHsmData() { } public Azure.ResourceManager.KeyVault.Models.DeletedManagedHsmProperties Properties { get { throw null; } } } public partial class DeletedVault : Azure.ResourceManager.Core.ArmResource { public static readonly Azure.Core.ResourceType ResourceType; protected DeletedVault() { } public virtual Azure.ResourceManager.KeyVault.DeletedVaultData Data { get { throw null; } } public virtual bool HasData { get { throw null; } } public static Azure.Core.ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string location, string vaultName) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.DeletedVault> Get(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.DeletedVault>> GetAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.ResourceManager.ArmOperation PurgeDeleted(bool waitForCompletion, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation> PurgeDeletedAsync(bool waitForCompletion, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class DeletedVaultCollection : Azure.ResourceManager.Core.ArmCollection { protected DeletedVaultCollection() { } public virtual Azure.Response<bool> Exists(string location, string vaultName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<bool>> ExistsAsync(string location, string vaultName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.DeletedVault> Get(string location, string vaultName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.DeletedVault>> GetAsync(string location, string vaultName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.DeletedVault> GetIfExists(string location, string vaultName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.DeletedVault>> GetIfExistsAsync(string location, string vaultName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class DeletedVaultData : Azure.ResourceManager.Models.ResourceData { internal DeletedVaultData() { } public Azure.ResourceManager.KeyVault.Models.DeletedVaultProperties Properties { get { throw null; } } } public partial class KeyData : Azure.ResourceManager.KeyVault.Models.KeyVaultResource { public KeyData() { } public Azure.ResourceManager.KeyVault.Models.KeyAttributes Attributes { get { throw null; } set { } } public Azure.ResourceManager.KeyVault.Models.JsonWebKeyCurveName? CurveName { get { throw null; } set { } } public System.Collections.Generic.IList<Azure.ResourceManager.KeyVault.Models.JsonWebKeyOperation> KeyOps { get { throw null; } } public int? KeySize { get { throw null; } set { } } public System.Uri KeyUri { get { throw null; } } public string KeyUriWithVersion { get { throw null; } } public Azure.ResourceManager.KeyVault.Models.JsonWebKeyType? Kty { get { throw null; } set { } } } public partial class ManagedHsm : Azure.ResourceManager.Core.ArmResource { public static readonly Azure.Core.ResourceType ResourceType; protected ManagedHsm() { } public virtual Azure.ResourceManager.KeyVault.ManagedHsmData Data { get { throw null; } } public virtual bool HasData { get { throw null; } } public virtual Azure.Response<Azure.ResourceManager.KeyVault.ManagedHsm> AddTag(string key, string value, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.ManagedHsm>> AddTagAsync(string key, string value, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static Azure.Core.ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string name) { throw null; } public virtual Azure.ResourceManager.ArmOperation Delete(bool waitForCompletion, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation> DeleteAsync(bool waitForCompletion, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.ManagedHsm> Get(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.ManagedHsm>> GetAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnectionCollection GetMhsmPrivateEndpointConnections() { throw null; } public virtual Azure.Pageable<Azure.ResourceManager.KeyVault.Models.MhsmPrivateLinkResource> GetMhsmPrivateLinkResources(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.ResourceManager.KeyVault.Models.MhsmPrivateLinkResource> GetMhsmPrivateLinkResourcesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.ManagedHsm> RemoveTag(string key, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.ManagedHsm>> RemoveTagAsync(string key, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.ManagedHsm> SetTags(System.Collections.Generic.IDictionary<string, string> tags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.ManagedHsm>> SetTagsAsync(System.Collections.Generic.IDictionary<string, string> tags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.ResourceManager.ArmOperation<Azure.ResourceManager.KeyVault.ManagedHsm> Update(bool waitForCompletion, Azure.ResourceManager.KeyVault.ManagedHsmData parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation<Azure.ResourceManager.KeyVault.ManagedHsm>> UpdateAsync(bool waitForCompletion, Azure.ResourceManager.KeyVault.ManagedHsmData parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class ManagedHsmCollection : Azure.ResourceManager.Core.ArmCollection, System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.KeyVault.ManagedHsm>, System.Collections.Generic.IEnumerable<Azure.ResourceManager.KeyVault.ManagedHsm>, System.Collections.IEnumerable { protected ManagedHsmCollection() { } public virtual Azure.ResourceManager.ArmOperation<Azure.ResourceManager.KeyVault.ManagedHsm> CreateOrUpdate(bool waitForCompletion, string name, Azure.ResourceManager.KeyVault.ManagedHsmData parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation<Azure.ResourceManager.KeyVault.ManagedHsm>> CreateOrUpdateAsync(bool waitForCompletion, string name, Azure.ResourceManager.KeyVault.ManagedHsmData parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<bool> Exists(string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<bool>> ExistsAsync(string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.ManagedHsm> Get(string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.ResourceManager.KeyVault.ManagedHsm> GetAll(int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.ResourceManager.KeyVault.ManagedHsm> GetAllAsync(int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.ManagedHsm>> GetAsync(string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.ManagedHsm> GetIfExists(string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.ManagedHsm>> GetIfExistsAsync(string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } System.Collections.Generic.IAsyncEnumerator<Azure.ResourceManager.KeyVault.ManagedHsm> System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.KeyVault.ManagedHsm>.GetAsyncEnumerator(System.Threading.CancellationToken cancellationToken) { throw null; } System.Collections.Generic.IEnumerator<Azure.ResourceManager.KeyVault.ManagedHsm> System.Collections.Generic.IEnumerable<Azure.ResourceManager.KeyVault.ManagedHsm>.GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public partial class ManagedHsmData : Azure.ResourceManager.KeyVault.Models.ManagedHsmResource { public ManagedHsmData(Azure.Core.AzureLocation location) : base (default(Azure.Core.AzureLocation)) { } public Azure.ResourceManager.KeyVault.Models.ManagedHsmProperties Properties { get { throw null; } set { } } } public partial class MhsmPrivateEndpointConnection : Azure.ResourceManager.Core.ArmResource { public static readonly Azure.Core.ResourceType ResourceType; protected MhsmPrivateEndpointConnection() { } public virtual Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnectionData Data { get { throw null; } } public virtual bool HasData { get { throw null; } } public virtual Azure.Response<Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection> AddTag(string key, string value, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection>> AddTagAsync(string key, string value, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static Azure.Core.ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string name, string privateEndpointConnectionName) { throw null; } public virtual Azure.ResourceManager.ArmOperation<Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection> Delete(bool waitForCompletion, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation<Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection>> DeleteAsync(bool waitForCompletion, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection> Get(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection>> GetAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection> RemoveTag(string key, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection>> RemoveTagAsync(string key, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection> SetTags(System.Collections.Generic.IDictionary<string, string> tags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection>> SetTagsAsync(System.Collections.Generic.IDictionary<string, string> tags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class MhsmPrivateEndpointConnectionCollection : Azure.ResourceManager.Core.ArmCollection, System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection>, System.Collections.Generic.IEnumerable<Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection>, System.Collections.IEnumerable { protected MhsmPrivateEndpointConnectionCollection() { } public virtual Azure.ResourceManager.ArmOperation<Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection> CreateOrUpdate(bool waitForCompletion, string privateEndpointConnectionName, Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnectionData properties, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation<Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection>> CreateOrUpdateAsync(bool waitForCompletion, string privateEndpointConnectionName, Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnectionData properties, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<bool> Exists(string privateEndpointConnectionName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<bool>> ExistsAsync(string privateEndpointConnectionName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection> Get(string privateEndpointConnectionName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection> GetAll(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection> GetAllAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection>> GetAsync(string privateEndpointConnectionName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection> GetIfExists(string privateEndpointConnectionName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection>> GetIfExistsAsync(string privateEndpointConnectionName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } System.Collections.Generic.IAsyncEnumerator<Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection> System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection>.GetAsyncEnumerator(System.Threading.CancellationToken cancellationToken) { throw null; } System.Collections.Generic.IEnumerator<Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection> System.Collections.Generic.IEnumerable<Azure.ResourceManager.KeyVault.MhsmPrivateEndpointConnection>.GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public partial class MhsmPrivateEndpointConnectionData : Azure.ResourceManager.KeyVault.Models.ManagedHsmResource { public MhsmPrivateEndpointConnectionData(Azure.Core.AzureLocation location) : base (default(Azure.Core.AzureLocation)) { } public string Etag { get { throw null; } set { } } public Azure.ResourceManager.Resources.Models.SubResource PrivateEndpoint { get { throw null; } set { } } public Azure.ResourceManager.KeyVault.Models.MhsmPrivateLinkServiceConnectionState PrivateLinkServiceConnectionState { get { throw null; } set { } } public Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState? ProvisioningState { get { throw null; } set { } } } public partial class PrivateEndpointConnection : Azure.ResourceManager.Core.ArmResource { public static readonly Azure.Core.ResourceType ResourceType; protected PrivateEndpointConnection() { } public virtual Azure.ResourceManager.KeyVault.PrivateEndpointConnectionData Data { get { throw null; } } public virtual bool HasData { get { throw null; } } public static Azure.Core.ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string vaultName, string privateEndpointConnectionName) { throw null; } public virtual Azure.ResourceManager.ArmOperation<Azure.ResourceManager.KeyVault.PrivateEndpointConnection> Delete(bool waitForCompletion, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation<Azure.ResourceManager.KeyVault.PrivateEndpointConnection>> DeleteAsync(bool waitForCompletion, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.PrivateEndpointConnection> Get(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.PrivateEndpointConnection>> GetAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class PrivateEndpointConnectionCollection : Azure.ResourceManager.Core.ArmCollection, System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.KeyVault.PrivateEndpointConnection>, System.Collections.Generic.IEnumerable<Azure.ResourceManager.KeyVault.PrivateEndpointConnection>, System.Collections.IEnumerable { protected PrivateEndpointConnectionCollection() { } public virtual Azure.ResourceManager.ArmOperation<Azure.ResourceManager.KeyVault.PrivateEndpointConnection> CreateOrUpdate(bool waitForCompletion, string privateEndpointConnectionName, Azure.ResourceManager.KeyVault.PrivateEndpointConnectionData properties, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation<Azure.ResourceManager.KeyVault.PrivateEndpointConnection>> CreateOrUpdateAsync(bool waitForCompletion, string privateEndpointConnectionName, Azure.ResourceManager.KeyVault.PrivateEndpointConnectionData properties, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<bool> Exists(string privateEndpointConnectionName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<bool>> ExistsAsync(string privateEndpointConnectionName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.PrivateEndpointConnection> Get(string privateEndpointConnectionName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.ResourceManager.KeyVault.PrivateEndpointConnection> GetAll(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.ResourceManager.KeyVault.PrivateEndpointConnection> GetAllAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.PrivateEndpointConnection>> GetAsync(string privateEndpointConnectionName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.PrivateEndpointConnection> GetIfExists(string privateEndpointConnectionName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.PrivateEndpointConnection>> GetIfExistsAsync(string privateEndpointConnectionName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } System.Collections.Generic.IAsyncEnumerator<Azure.ResourceManager.KeyVault.PrivateEndpointConnection> System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.KeyVault.PrivateEndpointConnection>.GetAsyncEnumerator(System.Threading.CancellationToken cancellationToken) { throw null; } System.Collections.Generic.IEnumerator<Azure.ResourceManager.KeyVault.PrivateEndpointConnection> System.Collections.Generic.IEnumerable<Azure.ResourceManager.KeyVault.PrivateEndpointConnection>.GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public partial class PrivateEndpointConnectionData : Azure.ResourceManager.KeyVault.Models.KeyVaultResource { public PrivateEndpointConnectionData() { } public string Etag { get { throw null; } set { } } public Azure.ResourceManager.Resources.Models.SubResource PrivateEndpoint { get { throw null; } set { } } public Azure.ResourceManager.KeyVault.Models.PrivateLinkServiceConnectionState PrivateLinkServiceConnectionState { get { throw null; } set { } } public Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState? ProvisioningState { get { throw null; } set { } } } public static partial class ResourceGroupExtensions { public static Azure.ResourceManager.KeyVault.ManagedHsmCollection GetManagedHsms(this Azure.ResourceManager.Resources.ResourceGroup resourceGroup) { throw null; } public static Azure.ResourceManager.KeyVault.VaultCollection GetVaults(this Azure.ResourceManager.Resources.ResourceGroup resourceGroup) { throw null; } } public partial class Secret : Azure.ResourceManager.Core.ArmResource { public static readonly Azure.Core.ResourceType ResourceType; protected Secret() { } public virtual Azure.ResourceManager.KeyVault.SecretData Data { get { throw null; } } public virtual bool HasData { get { throw null; } } public static Azure.Core.ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string vaultName, string secretName) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.Secret> Get(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.Secret>> GetAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.Secret> Update(Azure.ResourceManager.KeyVault.Models.SecretPatchParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.Secret>> UpdateAsync(Azure.ResourceManager.KeyVault.Models.SecretPatchParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class SecretCollection : Azure.ResourceManager.Core.ArmCollection, System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.KeyVault.Secret>, System.Collections.Generic.IEnumerable<Azure.ResourceManager.KeyVault.Secret>, System.Collections.IEnumerable { protected SecretCollection() { } public virtual Azure.ResourceManager.ArmOperation<Azure.ResourceManager.KeyVault.Secret> CreateOrUpdate(bool waitForCompletion, string secretName, Azure.ResourceManager.KeyVault.Models.SecretCreateOrUpdateParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation<Azure.ResourceManager.KeyVault.Secret>> CreateOrUpdateAsync(bool waitForCompletion, string secretName, Azure.ResourceManager.KeyVault.Models.SecretCreateOrUpdateParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<bool> Exists(string secretName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<bool>> ExistsAsync(string secretName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.Secret> Get(string secretName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.ResourceManager.KeyVault.Secret> GetAll(int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.ResourceManager.KeyVault.Secret> GetAllAsync(int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.Secret>> GetAsync(string secretName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.Secret> GetIfExists(string secretName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.Secret>> GetIfExistsAsync(string secretName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } System.Collections.Generic.IAsyncEnumerator<Azure.ResourceManager.KeyVault.Secret> System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.KeyVault.Secret>.GetAsyncEnumerator(System.Threading.CancellationToken cancellationToken) { throw null; } System.Collections.Generic.IEnumerator<Azure.ResourceManager.KeyVault.Secret> System.Collections.Generic.IEnumerable<Azure.ResourceManager.KeyVault.Secret>.GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public partial class SecretData : Azure.ResourceManager.KeyVault.Models.KeyVaultResource { public SecretData(Azure.ResourceManager.KeyVault.Models.SecretProperties properties) { } public Azure.ResourceManager.KeyVault.Models.SecretProperties Properties { get { throw null; } set { } } } public static partial class SubscriptionExtensions { public static Azure.Response<Azure.ResourceManager.KeyVault.Models.CheckNameAvailabilityResult> CheckKeyVaultNameAvailability(this Azure.ResourceManager.Resources.Subscription subscription, Azure.ResourceManager.KeyVault.Models.VaultCheckNameAvailabilityParameters vaultName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.Models.CheckNameAvailabilityResult>> CheckKeyVaultNameAvailabilityAsync(this Azure.ResourceManager.Resources.Subscription subscription, Azure.ResourceManager.KeyVault.Models.VaultCheckNameAvailabilityParameters vaultName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static Azure.ResourceManager.KeyVault.DeletedManagedHsmCollection GetDeletedManagedHsms(this Azure.ResourceManager.Resources.Subscription subscription) { throw null; } public static Azure.Pageable<Azure.ResourceManager.KeyVault.DeletedManagedHsm> GetDeletedManagedHsms(this Azure.ResourceManager.Resources.Subscription subscription, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static Azure.AsyncPageable<Azure.ResourceManager.KeyVault.DeletedManagedHsm> GetDeletedManagedHsmsAsync(this Azure.ResourceManager.Resources.Subscription subscription, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static Azure.ResourceManager.KeyVault.DeletedVaultCollection GetDeletedVaults(this Azure.ResourceManager.Resources.Subscription subscription) { throw null; } public static Azure.Pageable<Azure.ResourceManager.KeyVault.DeletedVault> GetDeletedVaults(this Azure.ResourceManager.Resources.Subscription subscription, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static Azure.AsyncPageable<Azure.ResourceManager.KeyVault.DeletedVault> GetDeletedVaultsAsync(this Azure.ResourceManager.Resources.Subscription subscription, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static Azure.Pageable<Azure.ResourceManager.KeyVault.ManagedHsm> GetManagedHsms(this Azure.ResourceManager.Resources.Subscription subscription, int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static Azure.AsyncPageable<Azure.ResourceManager.KeyVault.ManagedHsm> GetManagedHsmsAsync(this Azure.ResourceManager.Resources.Subscription subscription, int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static Azure.Pageable<Azure.ResourceManager.KeyVault.Vault> GetVaults(this Azure.ResourceManager.Resources.Subscription subscription, int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static Azure.AsyncPageable<Azure.ResourceManager.KeyVault.Vault> GetVaultsAsync(this Azure.ResourceManager.Resources.Subscription subscription, int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class Vault : Azure.ResourceManager.Core.ArmResource { public static readonly Azure.Core.ResourceType ResourceType; protected Vault() { } public virtual Azure.ResourceManager.KeyVault.VaultData Data { get { throw null; } } public virtual bool HasData { get { throw null; } } public static Azure.Core.ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string vaultName) { throw null; } public virtual Azure.ResourceManager.ArmOperation Delete(bool waitForCompletion, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation> DeleteAsync(bool waitForCompletion, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.Vault> Get(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.Vault>> GetAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.ResourceManager.KeyVault.PrivateEndpointConnectionCollection GetPrivateEndpointConnections() { throw null; } public virtual Azure.Pageable<Azure.ResourceManager.KeyVault.Models.PrivateLinkResource> GetPrivateLinkResources(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.ResourceManager.KeyVault.Models.PrivateLinkResource> GetPrivateLinkResourcesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.ResourceManager.KeyVault.SecretCollection GetSecrets() { throw null; } public virtual Azure.ResourceManager.KeyVault.VaultKeyCollection GetVaultKeys() { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.Vault> Update(Azure.ResourceManager.KeyVault.Models.VaultPatchParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.Models.VaultAccessPolicyParameters> UpdateAccessPolicy(Azure.ResourceManager.KeyVault.Models.AccessPolicyUpdateKind operationKind, Azure.ResourceManager.KeyVault.Models.VaultAccessPolicyParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.Models.VaultAccessPolicyParameters>> UpdateAccessPolicyAsync(Azure.ResourceManager.KeyVault.Models.AccessPolicyUpdateKind operationKind, Azure.ResourceManager.KeyVault.Models.VaultAccessPolicyParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.Vault>> UpdateAsync(Azure.ResourceManager.KeyVault.Models.VaultPatchParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class VaultCollection : Azure.ResourceManager.Core.ArmCollection, System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.KeyVault.Vault>, System.Collections.Generic.IEnumerable<Azure.ResourceManager.KeyVault.Vault>, System.Collections.IEnumerable { protected VaultCollection() { } public virtual Azure.ResourceManager.ArmOperation<Azure.ResourceManager.KeyVault.Vault> CreateOrUpdate(bool waitForCompletion, string vaultName, Azure.ResourceManager.KeyVault.Models.VaultCreateOrUpdateParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation<Azure.ResourceManager.KeyVault.Vault>> CreateOrUpdateAsync(bool waitForCompletion, string vaultName, Azure.ResourceManager.KeyVault.Models.VaultCreateOrUpdateParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<bool> Exists(string vaultName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<bool>> ExistsAsync(string vaultName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.Vault> Get(string vaultName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.ResourceManager.KeyVault.Vault> GetAll(int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.ResourceManager.KeyVault.Vault> GetAllAsync(int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.Vault>> GetAsync(string vaultName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.Vault> GetIfExists(string vaultName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.Vault>> GetIfExistsAsync(string vaultName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } System.Collections.Generic.IAsyncEnumerator<Azure.ResourceManager.KeyVault.Vault> System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.KeyVault.Vault>.GetAsyncEnumerator(System.Threading.CancellationToken cancellationToken) { throw null; } System.Collections.Generic.IEnumerator<Azure.ResourceManager.KeyVault.Vault> System.Collections.Generic.IEnumerable<Azure.ResourceManager.KeyVault.Vault>.GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public partial class VaultData : Azure.ResourceManager.Models.ResourceData { internal VaultData() { } public string Location { get { throw null; } } public Azure.ResourceManager.KeyVault.Models.VaultProperties Properties { get { throw null; } } public System.Collections.Generic.IReadOnlyDictionary<string, string> Tags { get { throw null; } } } public partial class VaultKey : Azure.ResourceManager.Core.ArmResource { public static readonly Azure.Core.ResourceType ResourceType; protected VaultKey() { } public virtual Azure.ResourceManager.KeyVault.KeyData Data { get { throw null; } } public virtual bool HasData { get { throw null; } } public static Azure.Core.ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string vaultName, string keyName) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.VaultKey> Get(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.VaultKey>> GetAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.ResourceManager.KeyVault.VaultKeyVersionCollection GetVaultKeyVersions() { throw null; } } public partial class VaultKeyCollection : Azure.ResourceManager.Core.ArmCollection, System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.KeyVault.VaultKey>, System.Collections.Generic.IEnumerable<Azure.ResourceManager.KeyVault.VaultKey>, System.Collections.IEnumerable { protected VaultKeyCollection() { } public virtual Azure.ResourceManager.ArmOperation<Azure.ResourceManager.KeyVault.VaultKey> CreateOrUpdate(bool waitForCompletion, string keyName, Azure.ResourceManager.KeyVault.Models.KeyCreateParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation<Azure.ResourceManager.KeyVault.VaultKey>> CreateOrUpdateAsync(bool waitForCompletion, string keyName, Azure.ResourceManager.KeyVault.Models.KeyCreateParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<bool> Exists(string keyName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<bool>> ExistsAsync(string keyName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.VaultKey> Get(string keyName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.ResourceManager.KeyVault.VaultKey> GetAll(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.ResourceManager.KeyVault.VaultKey> GetAllAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.VaultKey>> GetAsync(string keyName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.VaultKey> GetIfExists(string keyName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.VaultKey>> GetIfExistsAsync(string keyName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } System.Collections.Generic.IAsyncEnumerator<Azure.ResourceManager.KeyVault.VaultKey> System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.KeyVault.VaultKey>.GetAsyncEnumerator(System.Threading.CancellationToken cancellationToken) { throw null; } System.Collections.Generic.IEnumerator<Azure.ResourceManager.KeyVault.VaultKey> System.Collections.Generic.IEnumerable<Azure.ResourceManager.KeyVault.VaultKey>.GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public partial class VaultKeyVersion : Azure.ResourceManager.Core.ArmResource { public static readonly Azure.Core.ResourceType ResourceType; protected VaultKeyVersion() { } public virtual Azure.ResourceManager.KeyVault.KeyData Data { get { throw null; } } public virtual bool HasData { get { throw null; } } public static Azure.Core.ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string vaultName, string keyName, string keyVersion) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.VaultKeyVersion> Get(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.VaultKeyVersion>> GetAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class VaultKeyVersionCollection : Azure.ResourceManager.Core.ArmCollection, System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.KeyVault.VaultKeyVersion>, System.Collections.Generic.IEnumerable<Azure.ResourceManager.KeyVault.VaultKeyVersion>, System.Collections.IEnumerable { protected VaultKeyVersionCollection() { } public virtual Azure.Response<bool> Exists(string keyVersion, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<bool>> ExistsAsync(string keyVersion, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.VaultKeyVersion> Get(string keyVersion, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.ResourceManager.KeyVault.VaultKeyVersion> GetAll(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.ResourceManager.KeyVault.VaultKeyVersion> GetAllAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.VaultKeyVersion>> GetAsync(string keyVersion, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.KeyVault.VaultKeyVersion> GetIfExists(string keyVersion, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.KeyVault.VaultKeyVersion>> GetIfExistsAsync(string keyVersion, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } System.Collections.Generic.IAsyncEnumerator<Azure.ResourceManager.KeyVault.VaultKeyVersion> System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.KeyVault.VaultKeyVersion>.GetAsyncEnumerator(System.Threading.CancellationToken cancellationToken) { throw null; } System.Collections.Generic.IEnumerator<Azure.ResourceManager.KeyVault.VaultKeyVersion> System.Collections.Generic.IEnumerable<Azure.ResourceManager.KeyVault.VaultKeyVersion>.GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } } namespace Azure.ResourceManager.KeyVault.Models { public partial class AccessPermissions { public AccessPermissions() { } public System.Collections.Generic.IList<Azure.ResourceManager.KeyVault.Models.CertificatePermissions> Certificates { get { throw null; } } public System.Collections.Generic.IList<Azure.ResourceManager.KeyVault.Models.KeyPermissions> Keys { get { throw null; } } public System.Collections.Generic.IList<Azure.ResourceManager.KeyVault.Models.SecretPermissions> Secrets { get { throw null; } } public System.Collections.Generic.IList<Azure.ResourceManager.KeyVault.Models.StoragePermissions> Storage { get { throw null; } } } public partial class AccessPolicyEntry { public AccessPolicyEntry(System.Guid tenantId, string objectId, Azure.ResourceManager.KeyVault.Models.AccessPermissions permissions) { } public System.Guid? ApplicationId { get { throw null; } set { } } public string ObjectId { get { throw null; } set { } } public Azure.ResourceManager.KeyVault.Models.AccessPermissions Permissions { get { throw null; } set { } } public System.Guid TenantId { get { throw null; } set { } } } public enum AccessPolicyUpdateKind { Add = 0, Replace = 1, Remove = 2, } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct ActionsRequired : System.IEquatable<Azure.ResourceManager.KeyVault.Models.ActionsRequired> { private readonly object _dummy; private readonly int _dummyPrimitive; public ActionsRequired(string value) { throw null; } public static Azure.ResourceManager.KeyVault.Models.ActionsRequired None { get { throw null; } } public bool Equals(Azure.ResourceManager.KeyVault.Models.ActionsRequired other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.KeyVault.Models.ActionsRequired left, Azure.ResourceManager.KeyVault.Models.ActionsRequired right) { throw null; } public static implicit operator Azure.ResourceManager.KeyVault.Models.ActionsRequired (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.KeyVault.Models.ActionsRequired left, Azure.ResourceManager.KeyVault.Models.ActionsRequired right) { throw null; } public override string ToString() { throw null; } } public partial class BaseAttributes { public BaseAttributes() { } public System.DateTimeOffset? Created { get { throw null; } } public bool? Enabled { get { throw null; } set { } } public System.DateTimeOffset? Expires { get { throw null; } set { } } public System.DateTimeOffset? NotBefore { get { throw null; } set { } } public System.DateTimeOffset? Updated { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct CertificatePermissions : System.IEquatable<Azure.ResourceManager.KeyVault.Models.CertificatePermissions> { private readonly object _dummy; private readonly int _dummyPrimitive; public CertificatePermissions(string value) { throw null; } public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions All { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Backup { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Create { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Delete { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Deleteissuers { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Get { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Getissuers { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Import { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions List { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Listissuers { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Managecontacts { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Manageissuers { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Purge { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Recover { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Restore { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Setissuers { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.CertificatePermissions Update { get { throw null; } } public bool Equals(Azure.ResourceManager.KeyVault.Models.CertificatePermissions other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.KeyVault.Models.CertificatePermissions left, Azure.ResourceManager.KeyVault.Models.CertificatePermissions right) { throw null; } public static implicit operator Azure.ResourceManager.KeyVault.Models.CertificatePermissions (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.KeyVault.Models.CertificatePermissions left, Azure.ResourceManager.KeyVault.Models.CertificatePermissions right) { throw null; } public override string ToString() { throw null; } } public partial class CheckNameAvailabilityResult { internal CheckNameAvailabilityResult() { } public string Message { get { throw null; } } public bool? NameAvailable { get { throw null; } } public Azure.ResourceManager.KeyVault.Models.NameAvailabilityReason? Reason { get { throw null; } } } public enum CreateMode { Recover = 0, Default = 1, } public partial class DeletedManagedHsmProperties { internal DeletedManagedHsmProperties() { } public System.DateTimeOffset? DeletionDate { get { throw null; } } public string Location { get { throw null; } } public string MhsmId { get { throw null; } } public bool? PurgeProtectionEnabled { get { throw null; } } public System.DateTimeOffset? ScheduledPurgeDate { get { throw null; } } public System.Collections.Generic.IReadOnlyDictionary<string, string> Tags { get { throw null; } } } public partial class DeletedVaultProperties { internal DeletedVaultProperties() { } public System.DateTimeOffset? DeletionDate { get { throw null; } } public string Location { get { throw null; } } public bool? PurgeProtectionEnabled { get { throw null; } } public System.DateTimeOffset? ScheduledPurgeDate { get { throw null; } } public System.Collections.Generic.IReadOnlyDictionary<string, string> Tags { get { throw null; } } public string VaultId { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct DeletionRecoveryLevel : System.IEquatable<Azure.ResourceManager.KeyVault.Models.DeletionRecoveryLevel> { private readonly object _dummy; private readonly int _dummyPrimitive; public DeletionRecoveryLevel(string value) { throw null; } public static Azure.ResourceManager.KeyVault.Models.DeletionRecoveryLevel Purgeable { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.DeletionRecoveryLevel Recoverable { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.DeletionRecoveryLevel RecoverableProtectedSubscription { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.DeletionRecoveryLevel RecoverablePurgeable { get { throw null; } } public bool Equals(Azure.ResourceManager.KeyVault.Models.DeletionRecoveryLevel other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.KeyVault.Models.DeletionRecoveryLevel left, Azure.ResourceManager.KeyVault.Models.DeletionRecoveryLevel right) { throw null; } public static implicit operator Azure.ResourceManager.KeyVault.Models.DeletionRecoveryLevel (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.KeyVault.Models.DeletionRecoveryLevel left, Azure.ResourceManager.KeyVault.Models.DeletionRecoveryLevel right) { throw null; } public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct IdentityType : System.IEquatable<Azure.ResourceManager.KeyVault.Models.IdentityType> { private readonly object _dummy; private readonly int _dummyPrimitive; public IdentityType(string value) { throw null; } public static Azure.ResourceManager.KeyVault.Models.IdentityType Application { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.IdentityType Key { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.IdentityType ManagedIdentity { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.IdentityType User { get { throw null; } } public bool Equals(Azure.ResourceManager.KeyVault.Models.IdentityType other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.KeyVault.Models.IdentityType left, Azure.ResourceManager.KeyVault.Models.IdentityType right) { throw null; } public static implicit operator Azure.ResourceManager.KeyVault.Models.IdentityType (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.KeyVault.Models.IdentityType left, Azure.ResourceManager.KeyVault.Models.IdentityType right) { throw null; } public override string ToString() { throw null; } } public partial class IPRule { public IPRule(string value) { } public string Value { get { throw null; } set { } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct JsonWebKeyCurveName : System.IEquatable<Azure.ResourceManager.KeyVault.Models.JsonWebKeyCurveName> { private readonly object _dummy; private readonly int _dummyPrimitive; public JsonWebKeyCurveName(string value) { throw null; } public static Azure.ResourceManager.KeyVault.Models.JsonWebKeyCurveName P256 { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.JsonWebKeyCurveName P256K { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.JsonWebKeyCurveName P384 { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.JsonWebKeyCurveName P521 { get { throw null; } } public bool Equals(Azure.ResourceManager.KeyVault.Models.JsonWebKeyCurveName other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.KeyVault.Models.JsonWebKeyCurveName left, Azure.ResourceManager.KeyVault.Models.JsonWebKeyCurveName right) { throw null; } public static implicit operator Azure.ResourceManager.KeyVault.Models.JsonWebKeyCurveName (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.KeyVault.Models.JsonWebKeyCurveName left, Azure.ResourceManager.KeyVault.Models.JsonWebKeyCurveName right) { throw null; } public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct JsonWebKeyOperation : System.IEquatable<Azure.ResourceManager.KeyVault.Models.JsonWebKeyOperation> { private readonly object _dummy; private readonly int _dummyPrimitive; public JsonWebKeyOperation(string value) { throw null; } public static Azure.ResourceManager.KeyVault.Models.JsonWebKeyOperation Decrypt { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.JsonWebKeyOperation Encrypt { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.JsonWebKeyOperation Import { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.JsonWebKeyOperation Sign { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.JsonWebKeyOperation UnwrapKey { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.JsonWebKeyOperation Verify { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.JsonWebKeyOperation WrapKey { get { throw null; } } public bool Equals(Azure.ResourceManager.KeyVault.Models.JsonWebKeyOperation other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.KeyVault.Models.JsonWebKeyOperation left, Azure.ResourceManager.KeyVault.Models.JsonWebKeyOperation right) { throw null; } public static implicit operator Azure.ResourceManager.KeyVault.Models.JsonWebKeyOperation (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.KeyVault.Models.JsonWebKeyOperation left, Azure.ResourceManager.KeyVault.Models.JsonWebKeyOperation right) { throw null; } public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct JsonWebKeyType : System.IEquatable<Azure.ResourceManager.KeyVault.Models.JsonWebKeyType> { private readonly object _dummy; private readonly int _dummyPrimitive; public JsonWebKeyType(string value) { throw null; } public static Azure.ResourceManager.KeyVault.Models.JsonWebKeyType EC { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.JsonWebKeyType ECHSM { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.JsonWebKeyType RSA { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.JsonWebKeyType RSAHSM { get { throw null; } } public bool Equals(Azure.ResourceManager.KeyVault.Models.JsonWebKeyType other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.KeyVault.Models.JsonWebKeyType left, Azure.ResourceManager.KeyVault.Models.JsonWebKeyType right) { throw null; } public static implicit operator Azure.ResourceManager.KeyVault.Models.JsonWebKeyType (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.KeyVault.Models.JsonWebKeyType left, Azure.ResourceManager.KeyVault.Models.JsonWebKeyType right) { throw null; } public override string ToString() { throw null; } } public partial class KeyAttributes { public KeyAttributes() { } public long? Created { get { throw null; } } public bool? Enabled { get { throw null; } set { } } public long? Expires { get { throw null; } set { } } public bool? Exportable { get { throw null; } set { } } public long? NotBefore { get { throw null; } set { } } public Azure.ResourceManager.KeyVault.Models.DeletionRecoveryLevel? RecoveryLevel { get { throw null; } } public long? Updated { get { throw null; } } } public partial class KeyCreateParameters { public KeyCreateParameters(Azure.ResourceManager.KeyVault.Models.KeyProperties properties) { } public Azure.ResourceManager.KeyVault.Models.KeyProperties Properties { get { throw null; } } public System.Collections.Generic.IDictionary<string, string> Tags { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct KeyPermissions : System.IEquatable<Azure.ResourceManager.KeyVault.Models.KeyPermissions> { private readonly object _dummy; private readonly int _dummyPrimitive; public KeyPermissions(string value) { throw null; } public static Azure.ResourceManager.KeyVault.Models.KeyPermissions All { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Backup { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Create { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Decrypt { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Delete { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Encrypt { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Get { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Import { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.KeyPermissions List { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Purge { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Recover { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Restore { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Sign { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.KeyPermissions UnwrapKey { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Update { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.KeyPermissions Verify { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.KeyPermissions WrapKey { get { throw null; } } public bool Equals(Azure.ResourceManager.KeyVault.Models.KeyPermissions other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.KeyVault.Models.KeyPermissions left, Azure.ResourceManager.KeyVault.Models.KeyPermissions right) { throw null; } public static implicit operator Azure.ResourceManager.KeyVault.Models.KeyPermissions (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.KeyVault.Models.KeyPermissions left, Azure.ResourceManager.KeyVault.Models.KeyPermissions right) { throw null; } public override string ToString() { throw null; } } public partial class KeyProperties { public KeyProperties() { } public Azure.ResourceManager.KeyVault.Models.KeyAttributes Attributes { get { throw null; } set { } } public Azure.ResourceManager.KeyVault.Models.JsonWebKeyCurveName? CurveName { get { throw null; } set { } } public System.Collections.Generic.IList<Azure.ResourceManager.KeyVault.Models.JsonWebKeyOperation> KeyOps { get { throw null; } } public int? KeySize { get { throw null; } set { } } public System.Uri KeyUri { get { throw null; } } public string KeyUriWithVersion { get { throw null; } } public Azure.ResourceManager.KeyVault.Models.JsonWebKeyType? Kty { get { throw null; } set { } } } public partial class KeyVaultResource : Azure.ResourceManager.Models.ResourceData { public KeyVaultResource() { } public string Location { get { throw null; } } public System.Collections.Generic.IReadOnlyDictionary<string, string> Tags { get { throw null; } } } public partial class ManagedHsmProperties { public ManagedHsmProperties() { } public Azure.ResourceManager.KeyVault.Models.CreateMode? CreateMode { get { throw null; } set { } } public bool? EnablePurgeProtection { get { throw null; } set { } } public bool? EnableSoftDelete { get { throw null; } set { } } public System.Uri HsmUri { get { throw null; } } public System.Collections.Generic.IList<string> InitialAdminObjectIds { get { throw null; } } public Azure.ResourceManager.KeyVault.Models.MhsmNetworkRuleSet NetworkAcls { get { throw null; } set { } } public System.Collections.Generic.IReadOnlyList<Azure.ResourceManager.KeyVault.Models.MhsmPrivateEndpointConnectionItem> PrivateEndpointConnections { get { throw null; } } public Azure.ResourceManager.KeyVault.Models.ProvisioningState? ProvisioningState { get { throw null; } } public Azure.ResourceManager.KeyVault.Models.PublicNetworkAccess? PublicNetworkAccess { get { throw null; } set { } } public System.DateTimeOffset? ScheduledPurgeDate { get { throw null; } } public int? SoftDeleteRetentionInDays { get { throw null; } set { } } public string StatusMessage { get { throw null; } } public System.Guid? TenantId { get { throw null; } set { } } } public partial class ManagedHsmResource : Azure.ResourceManager.Models.TrackedResourceData { public ManagedHsmResource(Azure.Core.AzureLocation location) : base (default(Azure.Core.AzureLocation)) { } public Azure.ResourceManager.KeyVault.Models.ManagedHsmSku Sku { get { throw null; } set { } } } public partial class ManagedHsmSku { public ManagedHsmSku(Azure.ResourceManager.KeyVault.Models.ManagedHsmSkuFamily family, Azure.ResourceManager.KeyVault.Models.ManagedHsmSkuName name) { } public Azure.ResourceManager.KeyVault.Models.ManagedHsmSkuFamily Family { get { throw null; } set { } } public Azure.ResourceManager.KeyVault.Models.ManagedHsmSkuName Name { get { throw null; } set { } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct ManagedHsmSkuFamily : System.IEquatable<Azure.ResourceManager.KeyVault.Models.ManagedHsmSkuFamily> { private readonly object _dummy; private readonly int _dummyPrimitive; public ManagedHsmSkuFamily(string value) { throw null; } public static Azure.ResourceManager.KeyVault.Models.ManagedHsmSkuFamily B { get { throw null; } } public bool Equals(Azure.ResourceManager.KeyVault.Models.ManagedHsmSkuFamily other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.KeyVault.Models.ManagedHsmSkuFamily left, Azure.ResourceManager.KeyVault.Models.ManagedHsmSkuFamily right) { throw null; } public static implicit operator Azure.ResourceManager.KeyVault.Models.ManagedHsmSkuFamily (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.KeyVault.Models.ManagedHsmSkuFamily left, Azure.ResourceManager.KeyVault.Models.ManagedHsmSkuFamily right) { throw null; } public override string ToString() { throw null; } } public enum ManagedHsmSkuName { StandardB1 = 0, CustomB32 = 1, } public partial class MhsmipRule { public MhsmipRule(string value) { } public string Value { get { throw null; } set { } } } public partial class MhsmNetworkRuleSet { public MhsmNetworkRuleSet() { } public Azure.ResourceManager.KeyVault.Models.NetworkRuleBypassOptions? Bypass { get { throw null; } set { } } public Azure.ResourceManager.KeyVault.Models.NetworkRuleAction? DefaultAction { get { throw null; } set { } } public System.Collections.Generic.IList<Azure.ResourceManager.KeyVault.Models.MhsmipRule> IpRules { get { throw null; } } public System.Collections.Generic.IList<Azure.ResourceManager.Resources.Models.WritableSubResource> VirtualNetworkRules { get { throw null; } } } public partial class MhsmPrivateEndpointConnectionItem { internal MhsmPrivateEndpointConnectionItem() { } public Azure.ResourceManager.Resources.Models.SubResource PrivateEndpoint { get { throw null; } } public Azure.ResourceManager.KeyVault.Models.MhsmPrivateLinkServiceConnectionState PrivateLinkServiceConnectionState { get { throw null; } } public Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState? ProvisioningState { get { throw null; } } } public partial class MhsmPrivateLinkResource : Azure.ResourceManager.KeyVault.Models.ManagedHsmResource { public MhsmPrivateLinkResource(Azure.Core.AzureLocation location) : base (default(Azure.Core.AzureLocation)) { } public string GroupId { get { throw null; } } public System.Collections.Generic.IReadOnlyList<string> RequiredMembers { get { throw null; } } public System.Collections.Generic.IList<string> RequiredZoneNames { get { throw null; } } } public partial class MhsmPrivateLinkResourceListResult { internal MhsmPrivateLinkResourceListResult() { } public System.Collections.Generic.IReadOnlyList<Azure.ResourceManager.KeyVault.Models.MhsmPrivateLinkResource> Value { get { throw null; } } } public partial class MhsmPrivateLinkServiceConnectionState { public MhsmPrivateLinkServiceConnectionState() { } public Azure.ResourceManager.KeyVault.Models.ActionsRequired? ActionsRequired { get { throw null; } set { } } public string Description { get { throw null; } set { } } public Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus? Status { get { throw null; } set { } } } public enum NameAvailabilityReason { AccountNameInvalid = 0, AlreadyExists = 1, } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct NetworkRuleAction : System.IEquatable<Azure.ResourceManager.KeyVault.Models.NetworkRuleAction> { private readonly object _dummy; private readonly int _dummyPrimitive; public NetworkRuleAction(string value) { throw null; } public static Azure.ResourceManager.KeyVault.Models.NetworkRuleAction Allow { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.NetworkRuleAction Deny { get { throw null; } } public bool Equals(Azure.ResourceManager.KeyVault.Models.NetworkRuleAction other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.KeyVault.Models.NetworkRuleAction left, Azure.ResourceManager.KeyVault.Models.NetworkRuleAction right) { throw null; } public static implicit operator Azure.ResourceManager.KeyVault.Models.NetworkRuleAction (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.KeyVault.Models.NetworkRuleAction left, Azure.ResourceManager.KeyVault.Models.NetworkRuleAction right) { throw null; } public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct NetworkRuleBypassOptions : System.IEquatable<Azure.ResourceManager.KeyVault.Models.NetworkRuleBypassOptions> { private readonly object _dummy; private readonly int _dummyPrimitive; public NetworkRuleBypassOptions(string value) { throw null; } public static Azure.ResourceManager.KeyVault.Models.NetworkRuleBypassOptions AzureServices { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.NetworkRuleBypassOptions None { get { throw null; } } public bool Equals(Azure.ResourceManager.KeyVault.Models.NetworkRuleBypassOptions other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.KeyVault.Models.NetworkRuleBypassOptions left, Azure.ResourceManager.KeyVault.Models.NetworkRuleBypassOptions right) { throw null; } public static implicit operator Azure.ResourceManager.KeyVault.Models.NetworkRuleBypassOptions (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.KeyVault.Models.NetworkRuleBypassOptions left, Azure.ResourceManager.KeyVault.Models.NetworkRuleBypassOptions right) { throw null; } public override string ToString() { throw null; } } public partial class NetworkRuleSet { public NetworkRuleSet() { } public Azure.ResourceManager.KeyVault.Models.NetworkRuleBypassOptions? Bypass { get { throw null; } set { } } public Azure.ResourceManager.KeyVault.Models.NetworkRuleAction? DefaultAction { get { throw null; } set { } } public System.Collections.Generic.IList<Azure.ResourceManager.KeyVault.Models.IPRule> IpRules { get { throw null; } } public System.Collections.Generic.IList<Azure.ResourceManager.KeyVault.Models.VirtualNetworkRule> VirtualNetworkRules { get { throw null; } } } public partial class PrivateEndpointConnectionItem { internal PrivateEndpointConnectionItem() { } public string Etag { get { throw null; } } public string Id { get { throw null; } } public Azure.ResourceManager.Resources.Models.SubResource PrivateEndpoint { get { throw null; } } public Azure.ResourceManager.KeyVault.Models.PrivateLinkServiceConnectionState PrivateLinkServiceConnectionState { get { throw null; } } public Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState? ProvisioningState { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct PrivateEndpointConnectionProvisioningState : System.IEquatable<Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState> { private readonly object _dummy; private readonly int _dummyPrimitive; public PrivateEndpointConnectionProvisioningState(string value) { throw null; } public static Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState Creating { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState Deleting { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState Disconnected { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState Failed { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState Succeeded { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState Updating { get { throw null; } } public bool Equals(Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState left, Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState right) { throw null; } public static implicit operator Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState left, Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionProvisioningState right) { throw null; } public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct PrivateEndpointServiceConnectionStatus : System.IEquatable<Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus> { private readonly object _dummy; private readonly int _dummyPrimitive; public PrivateEndpointServiceConnectionStatus(string value) { throw null; } public static Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus Approved { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus Disconnected { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus Pending { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus Rejected { get { throw null; } } public bool Equals(Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus left, Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus right) { throw null; } public static implicit operator Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus left, Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus right) { throw null; } public override string ToString() { throw null; } } public partial class PrivateLinkResource : Azure.ResourceManager.KeyVault.Models.KeyVaultResource { public PrivateLinkResource() { } public string GroupId { get { throw null; } } public System.Collections.Generic.IReadOnlyList<string> RequiredMembers { get { throw null; } } public System.Collections.Generic.IList<string> RequiredZoneNames { get { throw null; } } } public partial class PrivateLinkResourceListResult { internal PrivateLinkResourceListResult() { } public System.Collections.Generic.IReadOnlyList<Azure.ResourceManager.KeyVault.Models.PrivateLinkResource> Value { get { throw null; } } } public partial class PrivateLinkServiceConnectionState { public PrivateLinkServiceConnectionState() { } public Azure.ResourceManager.KeyVault.Models.ActionsRequired? ActionsRequired { get { throw null; } set { } } public string Description { get { throw null; } set { } } public Azure.ResourceManager.KeyVault.Models.PrivateEndpointServiceConnectionStatus? Status { get { throw null; } set { } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct ProvisioningState : System.IEquatable<Azure.ResourceManager.KeyVault.Models.ProvisioningState> { private readonly object _dummy; private readonly int _dummyPrimitive; public ProvisioningState(string value) { throw null; } public static Azure.ResourceManager.KeyVault.Models.ProvisioningState Activated { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.ProvisioningState Deleting { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.ProvisioningState Failed { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.ProvisioningState Provisioning { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.ProvisioningState Restoring { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.ProvisioningState SecurityDomainRestore { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.ProvisioningState Succeeded { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.ProvisioningState Updating { get { throw null; } } public bool Equals(Azure.ResourceManager.KeyVault.Models.ProvisioningState other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.KeyVault.Models.ProvisioningState left, Azure.ResourceManager.KeyVault.Models.ProvisioningState right) { throw null; } public static implicit operator Azure.ResourceManager.KeyVault.Models.ProvisioningState (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.KeyVault.Models.ProvisioningState left, Azure.ResourceManager.KeyVault.Models.ProvisioningState right) { throw null; } public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct PublicNetworkAccess : System.IEquatable<Azure.ResourceManager.KeyVault.Models.PublicNetworkAccess> { private readonly object _dummy; private readonly int _dummyPrimitive; public PublicNetworkAccess(string value) { throw null; } public static Azure.ResourceManager.KeyVault.Models.PublicNetworkAccess Disabled { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.PublicNetworkAccess Enabled { get { throw null; } } public bool Equals(Azure.ResourceManager.KeyVault.Models.PublicNetworkAccess other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.KeyVault.Models.PublicNetworkAccess left, Azure.ResourceManager.KeyVault.Models.PublicNetworkAccess right) { throw null; } public static implicit operator Azure.ResourceManager.KeyVault.Models.PublicNetworkAccess (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.KeyVault.Models.PublicNetworkAccess left, Azure.ResourceManager.KeyVault.Models.PublicNetworkAccess right) { throw null; } public override string ToString() { throw null; } } public partial class SecretAttributes : Azure.ResourceManager.KeyVault.Models.BaseAttributes { public SecretAttributes() { } } public partial class SecretCreateOrUpdateParameters { public SecretCreateOrUpdateParameters(Azure.ResourceManager.KeyVault.Models.SecretProperties properties) { } public Azure.ResourceManager.KeyVault.Models.SecretProperties Properties { get { throw null; } } public System.Collections.Generic.IDictionary<string, string> Tags { get { throw null; } } } public partial class SecretPatchParameters { public SecretPatchParameters() { } public Azure.ResourceManager.KeyVault.Models.SecretPatchProperties Properties { get { throw null; } set { } } public System.Collections.Generic.IDictionary<string, string> Tags { get { throw null; } } } public partial class SecretPatchProperties { public SecretPatchProperties() { } public Azure.ResourceManager.KeyVault.Models.SecretAttributes Attributes { get { throw null; } set { } } public string ContentType { get { throw null; } set { } } public string Value { get { throw null; } set { } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct SecretPermissions : System.IEquatable<Azure.ResourceManager.KeyVault.Models.SecretPermissions> { private readonly object _dummy; private readonly int _dummyPrimitive; public SecretPermissions(string value) { throw null; } public static Azure.ResourceManager.KeyVault.Models.SecretPermissions All { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.SecretPermissions Backup { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.SecretPermissions Delete { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.SecretPermissions Get { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.SecretPermissions List { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.SecretPermissions Purge { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.SecretPermissions Recover { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.SecretPermissions Restore { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.SecretPermissions Set { get { throw null; } } public bool Equals(Azure.ResourceManager.KeyVault.Models.SecretPermissions other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.KeyVault.Models.SecretPermissions left, Azure.ResourceManager.KeyVault.Models.SecretPermissions right) { throw null; } public static implicit operator Azure.ResourceManager.KeyVault.Models.SecretPermissions (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.KeyVault.Models.SecretPermissions left, Azure.ResourceManager.KeyVault.Models.SecretPermissions right) { throw null; } public override string ToString() { throw null; } } public partial class SecretProperties { public SecretProperties() { } public Azure.ResourceManager.KeyVault.Models.SecretAttributes Attributes { get { throw null; } set { } } public string ContentType { get { throw null; } set { } } public System.Uri SecretUri { get { throw null; } } public string SecretUriWithVersion { get { throw null; } } public string Value { get { throw null; } set { } } } public partial class Sku { public Sku(Azure.ResourceManager.KeyVault.Models.SkuFamily family, Azure.ResourceManager.KeyVault.Models.SkuName name) { } public Azure.ResourceManager.KeyVault.Models.SkuFamily Family { get { throw null; } set { } } public Azure.ResourceManager.KeyVault.Models.SkuName Name { get { throw null; } set { } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct SkuFamily : System.IEquatable<Azure.ResourceManager.KeyVault.Models.SkuFamily> { private readonly object _dummy; private readonly int _dummyPrimitive; public SkuFamily(string value) { throw null; } public static Azure.ResourceManager.KeyVault.Models.SkuFamily A { get { throw null; } } public bool Equals(Azure.ResourceManager.KeyVault.Models.SkuFamily other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.KeyVault.Models.SkuFamily left, Azure.ResourceManager.KeyVault.Models.SkuFamily right) { throw null; } public static implicit operator Azure.ResourceManager.KeyVault.Models.SkuFamily (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.KeyVault.Models.SkuFamily left, Azure.ResourceManager.KeyVault.Models.SkuFamily right) { throw null; } public override string ToString() { throw null; } } public enum SkuName { Standard = 0, Premium = 1, } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct StoragePermissions : System.IEquatable<Azure.ResourceManager.KeyVault.Models.StoragePermissions> { private readonly object _dummy; private readonly int _dummyPrimitive; public StoragePermissions(string value) { throw null; } public static Azure.ResourceManager.KeyVault.Models.StoragePermissions All { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Backup { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Delete { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Deletesas { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Get { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Getsas { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.StoragePermissions List { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Listsas { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Purge { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Recover { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Regeneratekey { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Restore { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Set { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Setsas { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.StoragePermissions Update { get { throw null; } } public bool Equals(Azure.ResourceManager.KeyVault.Models.StoragePermissions other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.KeyVault.Models.StoragePermissions left, Azure.ResourceManager.KeyVault.Models.StoragePermissions right) { throw null; } public static implicit operator Azure.ResourceManager.KeyVault.Models.StoragePermissions (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.KeyVault.Models.StoragePermissions left, Azure.ResourceManager.KeyVault.Models.StoragePermissions right) { throw null; } public override string ToString() { throw null; } } public partial class VaultAccessPolicyParameters : Azure.ResourceManager.Models.ResourceData { public VaultAccessPolicyParameters(Azure.ResourceManager.KeyVault.Models.VaultAccessPolicyProperties properties) { } public string Location { get { throw null; } } public Azure.ResourceManager.KeyVault.Models.VaultAccessPolicyProperties Properties { get { throw null; } set { } } } public partial class VaultAccessPolicyProperties { public VaultAccessPolicyProperties(System.Collections.Generic.IEnumerable<Azure.ResourceManager.KeyVault.Models.AccessPolicyEntry> accessPolicies) { } public System.Collections.Generic.IList<Azure.ResourceManager.KeyVault.Models.AccessPolicyEntry> AccessPolicies { get { throw null; } } } public partial class VaultCheckNameAvailabilityParameters { public VaultCheckNameAvailabilityParameters(string name) { } public string Name { get { throw null; } } public string Type { get { throw null; } } } public partial class VaultCreateOrUpdateParameters { public VaultCreateOrUpdateParameters(string location, Azure.ResourceManager.KeyVault.Models.VaultProperties properties) { } public string Location { get { throw null; } } public Azure.ResourceManager.KeyVault.Models.VaultProperties Properties { get { throw null; } } public System.Collections.Generic.IDictionary<string, string> Tags { get { throw null; } } } public partial class VaultPatchParameters { public VaultPatchParameters() { } public Azure.ResourceManager.KeyVault.Models.VaultPatchProperties Properties { get { throw null; } set { } } public System.Collections.Generic.IDictionary<string, string> Tags { get { throw null; } } } public partial class VaultPatchProperties { public VaultPatchProperties() { } public System.Collections.Generic.IList<Azure.ResourceManager.KeyVault.Models.AccessPolicyEntry> AccessPolicies { get { throw null; } } public Azure.ResourceManager.KeyVault.Models.CreateMode? CreateMode { get { throw null; } set { } } public bool? EnabledForDeployment { get { throw null; } set { } } public bool? EnabledForDiskEncryption { get { throw null; } set { } } public bool? EnabledForTemplateDeployment { get { throw null; } set { } } public bool? EnablePurgeProtection { get { throw null; } set { } } public bool? EnableRbacAuthorization { get { throw null; } set { } } public bool? EnableSoftDelete { get { throw null; } set { } } public Azure.ResourceManager.KeyVault.Models.NetworkRuleSet NetworkAcls { get { throw null; } set { } } public string PublicNetworkAccess { get { throw null; } set { } } public Azure.ResourceManager.KeyVault.Models.Sku Sku { get { throw null; } set { } } public int? SoftDeleteRetentionInDays { get { throw null; } set { } } public System.Guid? TenantId { get { throw null; } set { } } } public partial class VaultProperties { public VaultProperties(System.Guid tenantId, Azure.ResourceManager.KeyVault.Models.Sku sku) { } public System.Collections.Generic.IList<Azure.ResourceManager.KeyVault.Models.AccessPolicyEntry> AccessPolicies { get { throw null; } } public Azure.ResourceManager.KeyVault.Models.CreateMode? CreateMode { get { throw null; } set { } } public bool? EnabledForDeployment { get { throw null; } set { } } public bool? EnabledForDiskEncryption { get { throw null; } set { } } public bool? EnabledForTemplateDeployment { get { throw null; } set { } } public bool? EnablePurgeProtection { get { throw null; } set { } } public bool? EnableRbacAuthorization { get { throw null; } set { } } public bool? EnableSoftDelete { get { throw null; } set { } } public string HsmPoolResourceId { get { throw null; } } public Azure.ResourceManager.KeyVault.Models.NetworkRuleSet NetworkAcls { get { throw null; } set { } } public System.Collections.Generic.IReadOnlyList<Azure.ResourceManager.KeyVault.Models.PrivateEndpointConnectionItem> PrivateEndpointConnections { get { throw null; } } public Azure.ResourceManager.KeyVault.Models.VaultProvisioningState? ProvisioningState { get { throw null; } set { } } public string PublicNetworkAccess { get { throw null; } set { } } public Azure.ResourceManager.KeyVault.Models.Sku Sku { get { throw null; } set { } } public int? SoftDeleteRetentionInDays { get { throw null; } set { } } public System.Guid TenantId { get { throw null; } set { } } public System.Uri VaultUri { get { throw null; } set { } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct VaultProvisioningState : System.IEquatable<Azure.ResourceManager.KeyVault.Models.VaultProvisioningState> { private readonly object _dummy; private readonly int _dummyPrimitive; public VaultProvisioningState(string value) { throw null; } public static Azure.ResourceManager.KeyVault.Models.VaultProvisioningState RegisteringDns { get { throw null; } } public static Azure.ResourceManager.KeyVault.Models.VaultProvisioningState Succeeded { get { throw null; } } public bool Equals(Azure.ResourceManager.KeyVault.Models.VaultProvisioningState other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.KeyVault.Models.VaultProvisioningState left, Azure.ResourceManager.KeyVault.Models.VaultProvisioningState right) { throw null; } public static implicit operator Azure.ResourceManager.KeyVault.Models.VaultProvisioningState (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.KeyVault.Models.VaultProvisioningState left, Azure.ResourceManager.KeyVault.Models.VaultProvisioningState right) { throw null; } public override string ToString() { throw null; } } public partial class VirtualNetworkRule { public VirtualNetworkRule(string id) { } public string Id { get { throw null; } set { } } public bool? IgnoreMissingVnetServiceEndpoint { get { throw null; } set { } } } }
103.913279
433
0.777027
[ "MIT" ]
LeszekKalibrate/azure-sdk-for-net
sdk/keyvault/Azure.ResourceManager.KeyVault/api/Azure.ResourceManager.KeyVault.netstandard2.0.cs
115,032
C#
using System; using System.IO; #pragma warning disable 618 namespace LocalsInit.Tests { internal static class FixtureHelper { public static string IsolateAssembly<T>() { var assembly = typeof(T).Assembly; var assemblyPath = assembly.Location!; var assemblyDir = Path.GetDirectoryName(assemblyPath)!; var rootTestDir = Path.Combine(assemblyDir, "WeavingTest"); var asmTestDir = Path.Combine(rootTestDir, Path.GetFileNameWithoutExtension(assemblyPath)!); EmptyDirectory(asmTestDir); Directory.CreateDirectory(asmTestDir); var destFile = CopyFile(assemblyPath, asmTestDir); CopyFile(Path.Combine(assemblyDir, "LocalsInit.dll"), asmTestDir); return destFile; } private static string CopyFile(string fileName, string targetDir) { if (!File.Exists(fileName)) throw new InvalidOperationException($"File not found: {fileName}"); var dest = Path.Combine(targetDir, Path.GetFileName(fileName)!); File.Copy(fileName, dest); return dest; } private static void EmptyDirectory(string path) { var directoryInfo = new DirectoryInfo(path); if (!directoryInfo.Exists) return; foreach (var file in directoryInfo.GetFiles()) file.Delete(); foreach (var dir in directoryInfo.GetDirectories()) dir.Delete(true); } } }
30.784314
104
0.602548
[ "MIT" ]
ltrzesniewski/LocalsInit.Fody
src/LocalsInit.Tests/FixtureHelper.cs
1,570
C#
 // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. // https://github.com/dotnet/roslyn-analyzers/issues/955 [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "RS0006:Do not mix attributes from different versions of MEF", Justification = "<Pending>", Scope = "type", Target = "~T:Microsoft.VisualStudio.ProjectSystem.PropertiesFolderProjectTreePropertiesProvider")]
73.5
280
0.787415
[ "Apache-2.0" ]
HydAu/RoslynProjectSystem
src/Microsoft.VisualStudio.ProjectSystem.CSharp/GlobalSuppressions.cs
590
C#
using System; using System.Collections.Generic; using System.Text; public class ExceptionsHomework { public static T[] Subsequence<T>(T[] arr, int startIndex, int count) { int length = arr.Length; if (length == 0) { throw new ArgumentException("Array must not be empty."); } if (startIndex < 0 || startIndex > length - 1) { throw new ArgumentOutOfRangeException(string.Format("Start index must be a value between 0 and {0}.", length - 1)); } if (count < 1) { throw new ArgumentOutOfRangeException(string.Format("Count must be greater than 0.")); } if (startIndex + count > length) { throw new ArgumentOutOfRangeException(string.Format("'startIndex + count <= arrayLength' must hold true.")); } List<T> result = new List<T>(); for (int i = startIndex; i < startIndex + count; i++) { result.Add(arr[i]); } return result.ToArray(); } public static string ExtractEnding(string str, int count) { if (count < 1) { throw new ArgumentOutOfRangeException("Count cannot be less than 1."); } if (count > str.Length) { throw new ArgumentOutOfRangeException("Count cannot be greater than length of string."); } StringBuilder result = new StringBuilder(); for (int i = str.Length - count; i < str.Length; i++) { result.Append(str[i]); } return result.ToString(); } public static bool CheckIfPrime(int number) { bool isPrime = true; if (number < 2) { isPrime = false; return isPrime; } for (int divisor = 2; divisor <= Math.Sqrt(number); divisor++) { if (number % divisor == 0) { isPrime = false; break; } } return isPrime; } public static void Main() { var substr = Subsequence("Hello!".ToCharArray(), 2, 3); Console.WriteLine(substr); var subarr = Subsequence(new int[] { -1, 3, 2, 1 }, 0, 2); Console.WriteLine(string.Join(" ", subarr)); var allarr = Subsequence(new int[] { -1, 3, 2, 1 }, 0, 4); Console.WriteLine(string.Join(" ", allarr)); // var emptyarr = Subsequence(new int[] { -1, 3, 2, 1 }, 0, 0); // Console.WriteLine(string.Join(" ", emptyarr)); Console.WriteLine(ExtractEnding("I love C#", 2)); Console.WriteLine(ExtractEnding("Nakov", 4)); Console.WriteLine(ExtractEnding("beer", 4)); // Console.WriteLine(ExtractEnding("Hi", 100)); Console.WriteLine("23 is prime = {0}", CheckIfPrime(23)); List<Exam> peterExams = new List<Exam>() { new SimpleMathExam(2), new CSharpExam(55), new CSharpExam(100), new SimpleMathExam(1), new CSharpExam(0), }; Student peter = new Student("Peter", "Petrov", peterExams); double peterAverageResult = peter.CalcAverageExamResultInPercents(); Console.WriteLine("Average results = {0:p0}", peterAverageResult); } }
28.290598
127
0.54139
[ "MIT" ]
Hris21/High-Quality-Code
Defensive Programming and Exceptions/Exceptions-Homework/ExceptionsHomework.cs
3,312
C#
using System; using System.Runtime.CompilerServices; namespace SafelyUnsafe { /// <summary> /// a restricted System.Runtime.CompilerServices.Unsafe class rapper for "unmanaged". /// </summary> public static partial class UnsafeUnmanaged { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref byte AsByteRef<T>(ref T source) where T : unmanaged => ref Unsafe.As<T, byte>(ref source); [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static IntPtr ByteOffset<T>(T* origin, T* target) where T : unmanaged { CheckAligned<T>(origin); CheckAligned<T>(target); return Unsafe.ByteOffset(ref Unsafe.AsRef<T>(origin), ref Unsafe.AsRef<T>(target)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static int ElementOffset<T>(T* origin, T* target) where T : unmanaged { CheckAligned<T>(origin); CheckAligned<T>(target); return (int)((long)ByteOffset(origin, target) / Unsafe.SizeOf<T>()); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static int ElementOffset<T>(ref T origin, ref T target) where T : unmanaged => (int)((long)ByteOffset(ref origin, ref target) / Unsafe.SizeOf<T>()); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsAddressGeq<T>(ref T left, ref T right) where T : unmanaged => AreSame(ref left, ref right) || IsAddressGreaterThan(ref left, ref right); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsAddressLeq<T>(ref T left, ref T right) where T : unmanaged => AreSame(ref left, ref right) || IsAddressLessThan(ref left, ref right); // ----------------------------------------------------- [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static T Read<T>(void* source) where T : unmanaged => Unsafe.Read<T>(source); [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static T ReadUnaligned<T>(void* source) where T : unmanaged => Unsafe.ReadUnaligned<T>(source); [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static T ReadUnaligned<T>(ref byte source) where T : unmanaged => Unsafe.ReadUnaligned<T>(ref source); [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static void Write<T>(void* destination, T value) where T : unmanaged => Unsafe.Write<T>(destination, value); [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static void WriteUnaligned<T>(void* destination, T value) where T : unmanaged => Unsafe.WriteUnaligned(destination, value); [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static void WriteUnaligned<T>(ref byte destination, T value) where T : unmanaged => Unsafe.WriteUnaligned(ref destination, value); [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static void Copy<T>(void* destination, ref T source) where T : unmanaged => Unsafe.Copy(destination, ref source); [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static void Copy<T>(ref T destination, void* source) where T : unmanaged => Unsafe.Copy(ref destination, source); [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static T* AsPointer<T>(ref T value) where T : unmanaged => (T*)Unsafe.AsPointer(ref value); [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static int SizeOf<T>() where T : unmanaged => Unsafe.SizeOf<T>(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static ref T AsRef<T>(T* source) where T : unmanaged => ref Unsafe.AsRef<T>(source); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T AsRef<T>(in T source) where T : unmanaged => ref Unsafe.AsRef(in source); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref TTo As<TFrom, TTo>(ref TFrom source) where TFrom : unmanaged where TTo : unmanaged => ref Unsafe.As<TFrom, TTo>(ref source); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T Add<T>(ref T source, int elementOffset) where T : unmanaged => ref Unsafe.Add(ref source, elementOffset); [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static void* Add<T>(void* source, int elementOffset) where T : unmanaged => Unsafe.Add<T>(source, elementOffset); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T Add<T>(ref T source, IntPtr elementOffset) where T : unmanaged => ref Unsafe.Add(ref source, elementOffset); [Obsolete] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T AddByteOffset<T>(ref T source, IntPtr byteOffset) where T : unmanaged => ref Unsafe.AddByteOffset(ref source, byteOffset); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T Subtract<T>(ref T source, int elementOffset) where T : unmanaged => ref Unsafe.Subtract(ref source, elementOffset); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T Subtract<T>(ref T source, IntPtr elementOffset) where T : unmanaged => ref Unsafe.Subtract(ref source, elementOffset); [Obsolete] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T SubtractByteOffset<T>(ref T source, IntPtr byteOffset) where T : unmanaged => ref Unsafe.SubtractByteOffset(ref source, byteOffset); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static IntPtr ByteOffset<T>(ref T origin, ref T target) where T : unmanaged => Unsafe.ByteOffset(ref origin, ref target); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool AreSame<T>(ref T left, ref T right) where T : unmanaged => Unsafe.AreSame(ref left, ref right); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsAddressGreaterThan<T>(ref T left, ref T right) where T : unmanaged => Unsafe.IsAddressGreaterThan(ref left, ref right); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsAddressLessThan<T>(ref T left, ref T right) where T : unmanaged => Unsafe.IsAddressLessThan(ref left, ref right); } }
41
95
0.631929
[ "MIT" ]
udaken/EnsafedUnsafe
src/UnsafeUnmanaged.Wrapper.cs
7,218
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Net; using Microsoft.Azure.Management.Resources; using Microsoft.Azure.Management.CosmosDB; using Xunit; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Microsoft.Azure.Management.CosmosDB.Models; using System.Collections.Generic; using System; namespace CosmosDB.Tests.ScenarioTests { public class GraphResourcesOperationsTests { const string location = "EAST US"; // using an existing DB account, since Account provisioning takes 10-15 minutes const string resourceGroupName = "CosmosDBResourceGroup3668"; const string databaseAccountName = "db4096"; const string databaseName = "databaseName1002"; const string databaseName2 = "databaseName21002"; const string gremlinGraphName = "gremlinGraphName1002"; const string graphThroughputType = "Microsoft.DocumentDB/databaseAccounts/gremlinDatabases/throughputSettings"; const int sampleThroughput = 700; Dictionary<string, string> additionalProperties = new Dictionary<string, string> { {"foo","bar" } }; Dictionary<string, string> tags = new Dictionary<string, string> { {"key3","value3"}, {"key4","value4"} }; [Fact] public void GraphCRUDTests() { var handler1 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { // Create client CosmosDBManagementClient cosmosDBManagementClient = CosmosDBTestUtilities.GetCosmosDBClient(context, handler1); bool isDatabaseNameExists = cosmosDBManagementClient.DatabaseAccounts.CheckNameExistsWithHttpMessagesAsync(databaseAccountName).GetAwaiter().GetResult().Body; if (!isDatabaseNameExists) { return; } GremlinDatabaseCreateUpdateParameters gremlinDatabaseCreateUpdateParameters = new GremlinDatabaseCreateUpdateParameters { Resource = new GremlinDatabaseResource {Id = databaseName}, Options = new CreateUpdateOptions() }; GremlinDatabaseGetResults gremlinDatabaseGetResults = cosmosDBManagementClient.GremlinResources.CreateUpdateGremlinDatabaseWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, gremlinDatabaseCreateUpdateParameters).GetAwaiter().GetResult().Body; Assert.NotNull(gremlinDatabaseGetResults); Assert.Equal(databaseName, gremlinDatabaseGetResults.Name); GremlinDatabaseGetResults gremlinDatabaseGetResults1 = cosmosDBManagementClient.GremlinResources.GetGremlinDatabaseWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName).GetAwaiter().GetResult().Body; Assert.NotNull(gremlinDatabaseGetResults1); Assert.Equal(databaseName, gremlinDatabaseGetResults1.Name); VerifyEqualGremlinDatabases(gremlinDatabaseGetResults, gremlinDatabaseGetResults1); GremlinDatabaseCreateUpdateParameters gremlinDatabaseCreateUpdateParameters2 = new GremlinDatabaseCreateUpdateParameters { Location = location, Tags = tags, Resource = new GremlinDatabaseResource { Id = databaseName2 }, Options = new CreateUpdateOptions { Throughput = sampleThroughput } }; GremlinDatabaseGetResults gremlinDatabaseGetResults2 = cosmosDBManagementClient.GremlinResources.CreateUpdateGremlinDatabaseWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName2, gremlinDatabaseCreateUpdateParameters2).GetAwaiter().GetResult().Body; Assert.NotNull(gremlinDatabaseGetResults2); Assert.Equal(databaseName2, gremlinDatabaseGetResults2.Name); IEnumerable<GremlinDatabaseGetResults> gremlinDatabases = cosmosDBManagementClient.GremlinResources.ListGremlinDatabasesWithHttpMessagesAsync(resourceGroupName, databaseAccountName).GetAwaiter().GetResult().Body; Assert.NotNull(gremlinDatabases); ThroughputSettingsGetResults throughputSettingsGetResults = cosmosDBManagementClient.GremlinResources.GetGremlinDatabaseThroughputWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName2).GetAwaiter().GetResult().Body; Assert.NotNull(throughputSettingsGetResults); Assert.NotNull(throughputSettingsGetResults.Name); Assert.Equal(throughputSettingsGetResults.Resource.Throughput, sampleThroughput); Assert.Equal(graphThroughputType, throughputSettingsGetResults.Type); GremlinGraphCreateUpdateParameters gremlinGraphCreateUpdateParameters = new GremlinGraphCreateUpdateParameters { Resource = new GremlinGraphResource { Id = gremlinGraphName, DefaultTtl = -1, PartitionKey = new ContainerPartitionKey { Kind = "Hash", Paths = new List<string> { "/address"} }, IndexingPolicy = new IndexingPolicy { Automatic = true, IndexingMode = IndexingMode.Consistent, IncludedPaths = new List<IncludedPath> { new IncludedPath { Path = "/*"} }, ExcludedPaths = new List<ExcludedPath> { new ExcludedPath { Path = "/pathToNotIndex/*"} }, CompositeIndexes = new List<IList<CompositePath>> { new List<CompositePath> { new CompositePath { Path = "/orderByPath1", Order = CompositePathSortOrder.Ascending }, new CompositePath { Path = "/orderByPath2", Order = CompositePathSortOrder.Descending } }, new List<CompositePath> { new CompositePath { Path = "/orderByPath3", Order = CompositePathSortOrder.Ascending }, new CompositePath { Path = "/orderByPath4", Order = CompositePathSortOrder.Descending } } } } }, Options = new CreateUpdateOptions { Throughput = sampleThroughput } }; GremlinGraphGetResults gremlinGraphGetResults = cosmosDBManagementClient.GremlinResources.CreateUpdateGremlinGraphWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, gremlinGraphName, gremlinGraphCreateUpdateParameters).GetAwaiter().GetResult().Body; Assert.NotNull(gremlinGraphGetResults); VerifyGremlinGraphCreation(gremlinGraphGetResults, gremlinGraphCreateUpdateParameters); IEnumerable<GremlinGraphGetResults> gremlinGraphs = cosmosDBManagementClient.GremlinResources.ListGremlinGraphsWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName).GetAwaiter().GetResult().Body; Assert.NotNull(gremlinGraphs); foreach (GremlinGraphGetResults gremlinGraph in gremlinGraphs) { cosmosDBManagementClient.GremlinResources.DeleteGremlinGraphWithHttpMessagesAsync(resourceGroupName, databaseAccountName, databaseName, gremlinGraph.Name); } foreach (GremlinDatabaseGetResults gremlinDatabase in gremlinDatabases) { cosmosDBManagementClient.GremlinResources.DeleteGremlinDatabaseWithHttpMessagesAsync(resourceGroupName, databaseAccountName, gremlinDatabase.Name); } } } private void VerifyGremlinGraphCreation(GremlinGraphGetResults gremlinGraphGetResults, GremlinGraphCreateUpdateParameters gremlinGraphCreateUpdateParameters) { Assert.Equal(gremlinGraphGetResults.Resource.Id, gremlinGraphCreateUpdateParameters.Resource.Id); Assert.Equal(gremlinGraphGetResults.Resource.IndexingPolicy.IndexingMode.ToLower(), gremlinGraphCreateUpdateParameters.Resource.IndexingPolicy.IndexingMode.ToLower()); //Assert.Equal(gremlinGraphGetResults.Resource.IndexingPolicy.ExcludedPaths, gremlinGraphCreateUpdateParameters.Resource.IndexingPolicy.ExcludedPaths); Assert.Equal(gremlinGraphGetResults.Resource.PartitionKey.Kind, gremlinGraphCreateUpdateParameters.Resource.PartitionKey.Kind); Assert.Equal(gremlinGraphGetResults.Resource.PartitionKey.Paths, gremlinGraphCreateUpdateParameters.Resource.PartitionKey.Paths); Assert.Equal(gremlinGraphGetResults.Resource.DefaultTtl, gremlinGraphCreateUpdateParameters.Resource.DefaultTtl); } private void VerifyEqualGremlinDatabases(GremlinDatabaseGetResults expectedValue, GremlinDatabaseGetResults actualValue) { Assert.Equal(expectedValue.Resource.Id, actualValue.Resource.Id); Assert.Equal(expectedValue.Resource._rid, actualValue.Resource._rid); Assert.Equal(expectedValue.Resource._ts, actualValue.Resource._ts); Assert.Equal(expectedValue.Resource._etag, actualValue.Resource._etag); } } }
57.297753
290
0.647907
[ "MIT" ]
Ohad-Fein/azure-sdk-for-net
sdk/cosmosdb/Microsoft.Azure.Management.CosmosDB/tests/ScenarioTests/GraphResourcesOperationsTests.cs
10,201
C#
using System; using System.Linq.Expressions; using System.Text.RegularExpressions; using System.Xml; namespace Highway.Data.OData.Parser.Readers { internal class TimeSpanExpressionFactory : ValueExpressionFactoryBase<TimeSpan> { private static readonly Regex TimeSpanRegex = new Regex(@"^time['\""](P.+)['\""]$", RegexOptions.Compiled | RegexOptions.IgnoreCase); public override ConstantExpression Convert(string token) { var match = TimeSpanRegex.Match(token); if (match.Success) { try { var timespan = XmlConvert.ToTimeSpan(match.Groups[1].Value); return Expression.Constant(timespan); } catch { throw new FormatException("Could not read " + token + " as TimeSpan."); } } throw new FormatException("Could not read " + token + " as TimeSpan."); } } }
32.09375
91
0.555988
[ "MIT" ]
daveh551/Highway.Data
Highway/src/Highway.Data/OData/Parser/Readers/TimeSpanExpressionFactory.cs
1,029
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Utilities; using System; using System.Collections.Generic; using TMPro; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.UI { /// <summary> /// Theme Engine to control initialized GameObject's scale, local position offset, and color based on state changes /// For color, will try to set on first available text object in order of TextMesh, Text, TextMeshPro, and TextMeshProUGUI /// If none found, then Theme will target first Renderer component available and target the associated shader property found in ThemeDefinition /// </summary> public class ScaleOffsetColorTheme : InteractableColorTheme { protected Vector3 originalPosition; protected Vector3 originalScale; protected Transform hostTransform; public ScaleOffsetColorTheme() { Types = new Type[] { typeof(Transform), typeof(TextMesh), typeof(TextMesh), typeof(TextMeshPro), typeof(TextMeshProUGUI), typeof(Renderer) }; Name = "Default: Scale, Offset, Color"; } /// <inheritdoc /> public override ThemeDefinition GetDefaultThemeDefinition() { return new ThemeDefinition() { ThemeType = GetType(), StateProperties = new List<ThemeStateProperty>() { new ThemeStateProperty() { Name = "Scale", Type = ThemePropertyTypes.Vector3, Values = new List<ThemePropertyValue>(), Default = new ThemePropertyValue() { Vector3 = Vector3.one } }, new ThemeStateProperty() { Name = "Offset", Type = ThemePropertyTypes.Vector3, Values = new List<ThemePropertyValue>(), Default = new ThemePropertyValue() { Vector3 = Vector3.zero } }, new ThemeStateProperty() { Name = "Color", Type = ThemePropertyTypes.Color, Values = new List<ThemePropertyValue>(), Default = new ThemePropertyValue() { Color = Color.white }, TargetShader = StandardShaderUtility.MrtkStandardShader, ShaderPropertyName = DefaultShaderProperty, }, }, CustomProperties = new List<ThemeProperty>(), }; } /// <inheritdoc /> public override void Init(GameObject host, ThemeDefinition settings) { base.Init(host, settings); hostTransform = Host.transform; originalPosition = hostTransform.localPosition; originalScale = hostTransform.localScale; } /// <inheritdoc /> public override ThemePropertyValue GetProperty(ThemeStateProperty property) { ThemePropertyValue start = new ThemePropertyValue(); switch (property.Name) { case "Scale": start.Vector3 = hostTransform.localScale; break; case "Offset": start.Vector3 = hostTransform.localPosition; break; case "Color": start = base.GetProperty(property); break; default: break; } return start; } /// <inheritdoc /> public override void SetValue(ThemeStateProperty property, int index, float percentage) { switch (property.Name) { case "Scale": hostTransform.localScale = Vector3.Lerp(property.StartValue.Vector3, Vector3.Scale(originalScale, property.Values[index].Vector3), percentage); break; case "Offset": hostTransform.localPosition = Vector3.Lerp(property.StartValue.Vector3, originalPosition + property.Values[index].Vector3, percentage); break; case "Color": base.SetValue(property, index, percentage); break; default: break; } } } }
39.818966
163
0.540593
[ "MIT" ]
ABak9/AR-Sharing
Assets/MixedRealityToolkit.SDK/Features/UX/Scripts/VisualThemes/ThemeEngines/ScaleOffsetColorTheme.cs
4,621
C#
/* Destroy any object that goes outide of the trigger Approximately when leaving the screen */ using UnityEngine; public class DestoyOffscreen : MonoBehaviour { void OnTriggerExit2D(Collider2D col) { if (col.tag == "Bullet") { Destroy(col.gameObject); } } }
17.166667
50
0.634304
[ "MIT" ]
gilecheverria/MoonPatroller
Assets/Scripts/Game/DestoyOffscreen.cs
311
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.AwsNative.Glue.Inputs { public sealed class TableSchemaReferenceArgs : Pulumi.ResourceArgs { [Input("schemaId")] public Input<Inputs.TableSchemaIdArgs>? SchemaId { get; set; } [Input("schemaVersionId")] public Input<string>? SchemaVersionId { get; set; } [Input("schemaVersionNumber")] public Input<int>? SchemaVersionNumber { get; set; } public TableSchemaReferenceArgs() { } } }
27.068966
81
0.675159
[ "Apache-2.0" ]
AaronFriel/pulumi-aws-native
sdk/dotnet/Glue/Inputs/TableSchemaReferenceArgs.cs
785
C#
// ----------------------------------------------------------------------- // Licensed to The .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ----------------------------------------------------------------------- using System; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using Kerberos.NET.Dns; namespace Kerberos.NET.Client { internal class TcpSocket : ITcpSocket { private readonly NamedPool pool; private readonly TcpClient client; public string TargetName { get; private set; } public TimeSpan ReceiveTimeout { get => TimeSpan.FromMilliseconds(this.client.ReceiveTimeout); set => this.client.ReceiveTimeout = (int)value.TotalMilliseconds; } public TimeSpan SendTimeout { get => TimeSpan.FromMilliseconds(this.client.SendTimeout); set => this.client.SendTimeout = (int)value.TotalMilliseconds; } public bool Connected => this.client.Connected; public DateTimeOffset LastRelease { get; private set; } public TcpSocket(NamedPool pool) { this.pool = pool; this.client = new TcpClient(AddressFamily.InterNetwork) { NoDelay = true, LingerState = new LingerOption(false, 0) }; } public async Task<bool> Connect(DnsRecord target, TimeSpan connectTimeout) { var tcs = new TaskCompletionSource<bool>(); using (var cts = new CancellationTokenSource(connectTimeout)) { var connectTask = this.client.ConnectAsync(target.Target, target.Port); using (cts.Token.Register(() => tcs.TrySetResult(true))) { if (connectTask != await Task.WhenAny(connectTask, tcs.Task).ConfigureAwait(false)) { return false; } if (connectTask.Exception?.InnerException != null) { throw connectTask.Exception.InnerException; } } } this.TargetName = target.Target; return true; } public void Free() { this.client.Dispose(); } public void Dispose() { this.pool.Release(this); this.LastRelease = DateTimeOffset.UtcNow; } public NetworkStream GetStream() { return this.client.GetStream(); } } }
28.892473
103
0.524377
[ "MIT" ]
AlexanderSemenyak/Kerberos.NET
Kerberos.NET/Client/Transport/TcpSocket.cs
2,689
C#
#region License // Copyright (c) 2009, ClearCanvas Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of ClearCanvas Inc. nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, // OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY // OF SUCH DAMAGE. #endregion using System; using System.Collections; using ClearCanvas.Common.Utilities; using ClearCanvas.ImageViewer.Services.LocalDataStore; using ClearCanvas.Common; using System.Threading; namespace ClearCanvas.ImageViewer.Shreds.DicomServer { internal class LocalDataStoreEventPublisher { private class PublishThreadPool : BlockingThreadPool<object> { public PublishThreadPool() : base(1, false) { } private static void Publish(object item) { LocalDataStoreServiceClient proxy = new LocalDataStoreServiceClient(); try { proxy.Open(); if (item is StoreScpReceivedFileInformation) { proxy.FileReceived(item as StoreScpReceivedFileInformation); } else if (item is StoreScuSentFileInformation) { proxy.FileSent(item as StoreScuSentFileInformation); } if (item is RetrieveStudyInformation) { proxy.RetrieveStarted(item as RetrieveStudyInformation); } else if (item is SendStudyInformation) { proxy.SendStarted(item as SendStudyInformation); } else if (item is ReceiveErrorInformation) { proxy.ReceiveError(item as ReceiveErrorInformation); } else if (item is SendErrorInformation) { proxy.SendError(item as SendErrorInformation); } proxy.Close(); } catch (Exception e) { proxy.Abort(); LogPublishError(item, e); } } private static void LogPublishError(object item, Exception e) { if (item is RetrieveStudyInformation) { Platform.Log(LogLevel.Warn, e, "Failed to notify the local data store service that a retrieve operation has begun."); } else if (item is SendStudyInformation) { Platform.Log(LogLevel.Warn, e, "Failed to notify the local data store service that a send operation has begun."); } else if (item is StoreScpReceivedFileInformation) { StoreScpReceivedFileInformation receivedFileInformation = (StoreScpReceivedFileInformation)item; String message = String.Format( "Failed to notify local data store service that a file has been received ({0})." + " The file must be imported manually.", receivedFileInformation.FileName); Platform.Log(LogLevel.Warn, e, message); } else if (item is StoreScuSentFileInformation) { StoreScuSentFileInformation sentFileInformation = (StoreScuSentFileInformation)item; string message = String.Format("Failed to notify local data store service that a file has been sent ({0}).", sentFileInformation.FileName); Platform.Log(LogLevel.Warn, e, message); } else if (item is SendErrorInformation) { Platform.Log(LogLevel.Warn, e, "Failed to notify local data store service that a send error occurred."); } else if (item is ReceiveErrorInformation) { Platform.Log(LogLevel.Warn, e, "Failed to notify local data store service that a receive error occurred."); } } protected override void ProcessItem(object item) { Publish(item); } } public static readonly LocalDataStoreEventPublisher Instance = new LocalDataStoreEventPublisher(); private readonly PublishThreadPool _pool; private LocalDataStoreEventPublisher() { _pool = new PublishThreadPool(); } private void AddToQueue(object item) { _pool.Enqueue(item); } public void Start() { _pool.Start(); } public void Stop() { _pool.Stop(); } public void FileSent(StoreScuSentFileInformation info) { AddToQueue(info); } public void FileReceived(StoreScpReceivedFileInformation info) { AddToQueue(info); } public void SendStarted(SendStudyInformation info) { AddToQueue(info); } public void RetrieveStarted(RetrieveStudyInformation info) { AddToQueue(info); } public void SendError(SendErrorInformation info) { AddToQueue(info); } public void ReceiveError(ReceiveErrorInformation info) { AddToQueue(info); } } }
29.846154
102
0.689347
[ "Apache-2.0" ]
econmed/ImageServer20
ImageViewer/Shreds/DicomServer/LocalDataStoreEventPublisher.cs
5,822
C#
using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using Xamarin.Forms; namespace Horus.Core.Behaviors { public class EmailValidatorBehavior : Behavior<Entry> { const string emailRegex = @"( |^)[^ ]*@mail\.com( |$)"; static readonly BindablePropertyKey IsValidPropertyKey = BindableProperty.CreateReadOnly("IsValid", typeof(bool), typeof(NumericValidationBehavior), false); public static readonly BindableProperty IsValidProperty = IsValidPropertyKey.BindableProperty; public bool IsValid { get { return (bool)base.GetValue(IsValidProperty); } private set { base.SetValue(IsValidPropertyKey, value); } } protected override void OnAttachedTo(Entry bindable) { bindable.TextChanged += HandleTextChanged; } protected override void OnDetachingFrom(Entry bindable) { bindable.TextChanged -= HandleTextChanged; } void HandleTextChanged(object sender, TextChangedEventArgs e) { IsValid = (Regex.IsMatch(e.NewTextValue, emailRegex, RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250))); ((Entry)sender).TextColor = IsValid ? Color.Default : Color.Red; } } }
31.47619
164
0.670197
[ "MIT" ]
mtotaro/HorusChallenge
Horus.Core/Behaviors/EmailValidatorBehavior.cs
1,324
C#
using System; using System.Xml.Serialization; namespace Doktr { [Serializable] [XmlType(TypeName = "Target")] public class DoktrTarget { public string Assembly { get; init; } = ""; public string XmlFile { get; init; } = ""; } }
15.681818
34
0.463768
[ "MIT" ]
zsr2531/Doktr
src/Doktr/DoktrTarget.cs
345
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics.ContractsLight; using BuildXL.FrontEnd.Script.Ambients.Map; using BuildXL.FrontEnd.Script.Ambients.Set; using BuildXL.FrontEnd.Script.Values; using BuildXL.Pips; using BuildXL.Pips.Operations; using BuildXL.Utilities; using static BuildXL.Utilities.FormattableStringEx; namespace BuildXL.FrontEnd.Script.Runtime { /// <summary> /// Helpers for RuntimeTypeId /// </summary> public static class RuntimeTypeIdExtensions { /// <nodoc /> private static readonly string[] s_runtimeStrings = CreateRuntimeStrings(); /// <summary> /// Maps the RuntimeTypeId to a the runtime string representation /// </summary> public static string ToRuntimeString(this RuntimeTypeId runtimeTypeId) { Contract.Requires(runtimeTypeId != RuntimeTypeId.Unknown); return s_runtimeStrings[(int)runtimeTypeId]; } /// <nodoc /> private static string[] CreateRuntimeStrings() { var result = new string[24]; result[(int)RuntimeTypeId.Unknown] = "<unknown>"; result[(int)RuntimeTypeId.Undefined] = "undefined"; result[(int)RuntimeTypeId.String] = "string"; result[(int)RuntimeTypeId.Boolean] = "boolean"; result[(int)RuntimeTypeId.Number] = "number"; result[(int)RuntimeTypeId.Array] = "array"; result[(int)RuntimeTypeId.Object] = "object"; result[(int)RuntimeTypeId.Enum] = "enum"; result[(int)RuntimeTypeId.Function] = "function"; result[(int)RuntimeTypeId.ModuleLiteral] = "object"; result[(int)RuntimeTypeId.Map] = "Map"; result[(int)RuntimeTypeId.Set] = "Set"; result[(int)RuntimeTypeId.Path] = "Path"; result[(int)RuntimeTypeId.File] = "File"; result[(int)RuntimeTypeId.Directory] = "Directory"; result[(int)RuntimeTypeId.StaticDirectory] = "StaticDirectory"; result[(int)RuntimeTypeId.SharedOpaqueDirectory] = "SharedOpaqueDirectory"; result[(int)RuntimeTypeId.ExclusiveOpaqueDirectory] = "ExclusiveOpaqueDirectory"; result[(int)RuntimeTypeId.SourceTopDirectory] = "SourceTopDirectory"; result[(int)RuntimeTypeId.SourceAllDirectory] = "SourceAllDirectory"; result[(int)RuntimeTypeId.FullStaticContentDirectory] = "FullStaticContentDirectory"; result[(int)RuntimeTypeId.PartialStaticContentDirectory] = "PartialStaticContentDirectory"; result[(int)RuntimeTypeId.RelativePath] = "RelativePath"; result[(int)RuntimeTypeId.PathAtom] = "PathAtom"; #if DEBUG // In debug builds do some quick validation. This is only done once per app so okay to embed in product code. Contract.Assert(result.Length == Enum.GetValues(typeof(RuntimeTypeId)).Length, "Must have the same number of values in the enum as in the array we build."); for (int i = 0; i < result.Length; i++) { Contract.Assert(!string.IsNullOrEmpty(result[i]), "Each entry must be set."); } #endif return result; } /// <summary> /// Dynamically inspects the object and returns the RuntimeTypeId /// </summary> public static RuntimeTypeId ComputeTypeOfKind(object value) { Contract.Assume(value != null); // In the future we'd like to use C# 7's Switch statements with patterns https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/ // Checking runtime type per pattern of: https://blogs.msdn.microsoft.com/vancem/2006/10/01/drilling-into-net-runtime-microbenchmarks-typeof-optimizations/ if (value == UndefinedValue.Instance) { return RuntimeTypeId.Undefined; } var runtimeType = value.GetType(); // Need to handle both cases: ArrayLiteral itself, and generic version. // In latter case, checking that runtimeType is assignable to ArrayLiteral. if (runtimeType == typeof(ArrayLiteral) || typeof(ArrayLiteral).IsAssignableFrom(runtimeType)) { return RuntimeTypeId.Array; } if (runtimeType.IsObjectLikeLiteralType()) { return RuntimeTypeId.Object; } if (runtimeType.IsModuleLiteral()) { // We want to expand this to proper namespace node in the future when we deprecate moduleliteral return RuntimeTypeId.ModuleLiteral; } if (runtimeType == typeof(AbsolutePath)) { return RuntimeTypeId.Path; } if (runtimeType == typeof(FileArtifact)) { return RuntimeTypeId.File; } if (runtimeType == typeof(DirectoryArtifact)) { return RuntimeTypeId.Directory; } if (runtimeType == typeof(StaticDirectory)) { return GetRuntimeTypeForStaticDirectory(value as StaticDirectory); } if (runtimeType == typeof(RelativePath)) { return RuntimeTypeId.RelativePath; } if (runtimeType == typeof(PathAtom)) { return RuntimeTypeId.PathAtom; } if (runtimeType == typeof(string)) { return RuntimeTypeId.String; } if (runtimeType == typeof(bool)) { return RuntimeTypeId.Boolean; } if (runtimeType == typeof(int)) { // We only support integers during evaluation, we'll have to expand this when we support more. return RuntimeTypeId.Number; } if (runtimeType == typeof(Closure)) { return RuntimeTypeId.Function; } if (runtimeType == typeof(EnumValue)) { return RuntimeTypeId.Enum; } if (runtimeType == typeof(OrderedSet)) { return RuntimeTypeId.Set; } if (runtimeType == typeof(OrderedMap)) { return RuntimeTypeId.Map; } throw Contract.AssertFailure(I($"Unexpected runtime value with type '{runtimeType}' encountered.")); } private static RuntimeTypeId GetRuntimeTypeForStaticDirectory(StaticDirectory staticDirectory) { Contract.Requires(staticDirectory != null); switch (staticDirectory.SealDirectoryKind) { case SealDirectoryKind.Full: return RuntimeTypeId.FullStaticContentDirectory; case SealDirectoryKind.Partial: return RuntimeTypeId.PartialStaticContentDirectory; case SealDirectoryKind.Opaque: return RuntimeTypeId.ExclusiveOpaqueDirectory; case SealDirectoryKind.SharedOpaque: return RuntimeTypeId.SharedOpaqueDirectory; case SealDirectoryKind.SourceAllDirectories: return RuntimeTypeId.SourceAllDirectory; case SealDirectoryKind.SourceTopDirectoryOnly: return RuntimeTypeId.SourceTopDirectory; default: throw Contract.AssertFailure(I($"Unexpected runtime kind '{staticDirectory.SealDirectoryKind}' encountered.")); } } private static bool IsModuleLiteral(this Type runtimeType) { return runtimeType == typeof(FileModuleLiteral) || runtimeType == typeof(TypeOrNamespaceModuleLiteral); } /// <summary> /// CHecks if the runtimeType is an object literal or not. /// </summary> private static bool IsObjectLikeLiteralType(this Type runtimeType) { return runtimeType == typeof(ObjectLiteral) || runtimeType == typeof(ObjectLiteral0) || typeof(ObjectLiteralSlim).IsAssignableFrom(runtimeType) || runtimeType == typeof(ObjectLiteralN); } } }
40.050228
169
0.578953
[ "MIT" ]
AzureMentor/BuildXL
Public/Src/FrontEnd/Script/Runtime/RuntimeTypeIdExtensions.cs
8,771
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using Xunit; namespace Microsoft.Data.SqlClient.ManualTesting.Tests { public class EventSourceTest { [ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))] public void EventSourceTestAll() { using DataTestUtility.MDSEventListener TraceListener = new(); using (SqlConnection connection = new(DataTestUtility.TCPConnectionString)) { connection.Open(); using SqlCommand command = new("SELECT @@VERSION", connection); using SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { // Flush data } } // Need to investigate better way of validating traces in sequential runs, // For now we're collecting all traces to improve code coverage. Assert.All(TraceListener.IDs, item => { Assert.Contains(item, Enumerable.Range(1, 21)); }); } } }
36.852941
103
0.624102
[ "MIT" ]
AraHaan/SqlClient
src/Microsoft.Data.SqlClient/tests/ManualTests/TracingTests/EventSourceTest.cs
1,255
C#
//********************************************************************* //xCAD //Copyright(C) 2020 Xarial Pty Limited //Product URL: https://www.xcad.net //License: https://xcad.xarial.com/license/ //********************************************************************* using SolidWorks.Interop.sldworks; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using Xarial.XCad.Base; using Xarial.XCad.Geometry; using Xarial.XCad.Geometry.Primitives; using Xarial.XCad.Geometry.Structures; using Xarial.XCad.Geometry.Wires; using Xarial.XCad.Services; using Xarial.XCad.SolidWorks.Geometry.Curves; using Xarial.XCad.SolidWorks.Geometry.Exceptions; namespace Xarial.XCad.SolidWorks.Geometry.Primitives { public interface ISwTempExtrusion : IXExtrusion, ISwTempPrimitive { new ISwTempRegion[] Profiles { get; set; } } internal class SwTempExtrusion : SwTempPrimitive, ISwTempExtrusion { IXRegion[] IXExtrusion.Profiles { get => Profiles; set => Profiles = value?.Cast<ISwTempRegion>().ToArray(); } public double Depth { get => m_Creator.CachedProperties.Get<double>(); set { if (IsCommitted) { throw new CommitedSegmentReadOnlyParameterException(); } else { m_Creator.CachedProperties.Set(value); } } } public Vector Direction { get => m_Creator.CachedProperties.Get<Vector>(); set { if (IsCommitted) { throw new CommitedSegmentReadOnlyParameterException(); } else { m_Creator.CachedProperties.Set(value); } } } public ISwTempRegion[] Profiles { get => m_Creator.CachedProperties.Get<ISwTempRegion[]>(); set { if (IsCommitted) { throw new CommitedSegmentReadOnlyParameterException(); } else { m_Creator.CachedProperties.Set(value); } } } internal SwTempExtrusion(IMathUtility mathUtils, IModeler modeler, SwTempBody[] bodies, bool isCreated) : base(mathUtils, modeler, bodies, isCreated) { } protected override ISwTempBody[] CreateBodies(CancellationToken cancellationToken) { var dir = m_MathUtils.CreateVector(Direction.ToArray()) as MathVector; var bodies = new List<ISwTempBody>(); foreach (var profile in Profiles) { var body = m_Modeler.CreateExtrudedBody((Body2)profile.PlanarSheetBody.Body, dir, Depth) as IBody2; if (body == null) { throw new Exception("Failed to create extrusion"); } bodies.Add(SwSelObject.FromDispatch<SwTempBody>(body)); } return bodies.ToArray(); } } }
29.04386
115
0.524011
[ "MIT" ]
jonnypjohnston/Xarial-xcad
src/SolidWorks/Geometry/Primitives/SwTempExtrusion.cs
3,313
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CommandLine.Initializer { public interface IAddContent { void Add(object v); } }
16.357143
33
0.724891
[ "MIT" ]
HierGibtEsDrachen/CommandLine
CommandLine/CommandLine/Initializer/IAddContent.cs
231
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ReMi.TestUtils.UnitTests { public static class RandomData { private static readonly Random _random = new Random(Guid.NewGuid().GetHashCode()); private const String _alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; //private static String _alphaNumeric = _alpha + "0123456789"; public static String RandomString(Int32 min, Int32 max) { var builder = new StringBuilder(); for (Int32 i = 0; i < _random.Next(min, max); i++) { builder.Append(_alpha[_random.Next(0, _alpha.Length)]); } return builder.ToString(); } public static String RandomString(Int32 length) { return RandomString(length, length); } public static String RandomEmail() { return string.Format("{0}@{1}.{2}", RandomString(10), RandomString(5), RandomString(3)); } public static Int32 RandomInt(Int32 min, Int32 max) { return _random.Next(min, max); } public static Int32 RandomInt(Int32 max) { return _random.Next(max); } public static Int64 RandomLong(Int64 min, Int64 max) { if (min > max) { throw new ArgumentOutOfRangeException("min", "min is greater than max"); } return min + Convert.ToInt64((max - min) * _random.NextDouble()); } public static Double Random() { return _random.NextDouble(); } public static DateTime RandomDate() { return RandomDate(new DateTime(1900, 1, 1), DateTime.Today); } public static DateTime RandomDate(DateTime min, DateTime max) { return min.AddDays(_random.Next((max - min).Days)).Date; } public static DateTime RandomDateTime(DateTimeKind kind = DateTimeKind.Local) { return RandomDateTime(new DateTime(1900, 1, 1).Ticks, DateTime.Now.Ticks, kind); } public static DateTime RandomDateTime(long minTicks, long maxTicks, DateTimeKind kind = DateTimeKind.Local) { return new DateTime((Int64)((maxTicks - minTicks) * _random.NextDouble()), kind); } public static T RandomEnum<T>() { return RandomElement((T[])Enum.GetValues(typeof(T))); } public static T RandomEnum<T>(params T[] exclude) { return RandomElement(((T[])Enum.GetValues(typeof(T))).Where(t => exclude == null || !exclude.Contains(t)).ToArray()); } public static T RandomEnumOf<T>(params T[] allowed) { if (allowed == null) { throw new ArgumentNullException("allowed"); } if (allowed.Length == 0) { throw new ArgumentOutOfRangeException("allowed", "collection of enum values can not be empty"); } return RandomElement(((T[])Enum.GetValues(typeof(T))).Where(allowed.Contains).ToArray()); } public static bool RandomBool() { return Convert.ToBoolean(_random.Next(100) % 2); } public static T RandomElement<T>(IEnumerable<T> enumerable) { return enumerable.ElementAt(_random.Next(enumerable.Count())); } } }
30.145299
129
0.568472
[ "MIT" ]
vishalishere/remi
ReMi.Utils/ReMi.TestUtils/UnitTests/RandomData.cs
3,527
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Azure.Core.Http; using Azure.Core.Pipeline; namespace Azure.Core.Testing { public static class RandomExtensions { public static Guid NewGuid(this Random random) { var bytes = new byte[16]; random.NextBytes(bytes); return new Guid(bytes); } } public class RecordTransport : HttpPipelineTransport { private readonly HttpPipelineTransport _innerTransport; private readonly Func<RecordEntry, bool> _filter; private readonly Random _random; private readonly RecordSession _session; public RecordTransport(RecordSession session, HttpPipelineTransport innerTransport, Func<RecordEntry, bool> filter, Random random) { _innerTransport = innerTransport; _filter = filter; _random = random; _session = session; } public override void Process(HttpPipelineMessage message) { _innerTransport.Process(message); Record(message); } public override async Task ProcessAsync(HttpPipelineMessage message) { await _innerTransport.ProcessAsync(message); Record(message); } private void Record(HttpPipelineMessage message) { RecordEntry recordEntry = CreateEntry(message.Request, message.Response); if (_filter(recordEntry)) { _session.Record(recordEntry); } } public override Request CreateRequest() { Request request = _innerTransport.CreateRequest(); lock (_random) { // Override ClientRequestId to avoid excessive diffs request.ClientRequestId = _random.NewGuid().ToString("N"); } return request; } public RecordEntry CreateEntry(Request request, Response response) { var entry = new RecordEntry { RequestUri = request.UriBuilder.ToString(), RequestMethod = request.Method, RequestHeaders = new SortedDictionary<string, string[]>(StringComparer.OrdinalIgnoreCase), ResponseHeaders = new SortedDictionary<string, string[]>(StringComparer.OrdinalIgnoreCase), RequestBody = ReadToEnd(request.Content), ResponseBody = ReadToEnd(response), StatusCode = response.Status }; foreach (HttpHeader requestHeader in request.Headers) { var gotHeader = request.Headers.TryGetValues(requestHeader.Name, out IEnumerable<string> headerValues); Debug.Assert(gotHeader); entry.RequestHeaders.Add(requestHeader.Name, headerValues.ToArray()); } // Make sure we record Content-Length even if it's not set explicitly if (!request.Headers.TryGetValue("Content-Length", out _) && request.Content != null && request.Content.TryComputeLength(out long computedLength)) { entry.RequestHeaders.Add("Content-Length", new [] { computedLength.ToString(CultureInfo.InvariantCulture) }); } foreach (HttpHeader responseHeader in response.Headers) { var gotHeader = response.Headers.TryGetValues(responseHeader.Name, out IEnumerable<string> headerValues); Debug.Assert(gotHeader); entry.ResponseHeaders.Add(responseHeader.Name, headerValues.ToArray()); } return entry; } private byte[] ReadToEnd(Response response) { Stream responseContentStream = response.ContentStream; if (responseContentStream == null) { return null; } var memoryStream = new NonSeekableMemoryStream(); responseContentStream.CopyTo(memoryStream); responseContentStream.Dispose(); memoryStream.Reset(); response.ContentStream = memoryStream; return memoryStream.ToArray(); } private byte[] ReadToEnd(HttpPipelineRequestContent requestContent) { if (requestContent == null) { return null; } using var memoryStream = new MemoryStream(); requestContent.WriteTo(memoryStream, CancellationToken.None); return memoryStream.ToArray(); } } }
33.611111
158
0.606818
[ "MIT" ]
abkmr/azure-sdk-for-net
sdk/core/Azure.Core/tests/TestFramework/RecordTransport.cs
4,842
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Axe.Windows.Core.Bases; using Axe.Windows.Core.Enums; using Axe.Windows.Rules.PropertyConditions; using Axe.Windows.Rules.Resources; using System; using System.Globalization; using static Axe.Windows.Rules.PropertyConditions.ControlType; namespace Axe.Windows.Rules.Library { [RuleInfo(ID = RuleId.ContentViewCheckBoxStructure)] class ContentViewCheckBoxStructure : Rule { public ContentViewCheckBoxStructure() { this.Info.Description = string.Format(CultureInfo.InvariantCulture, Descriptions.Structure, ContentView.CheckBoxStructure); this.Info.HowToFix = string.Format(CultureInfo.InvariantCulture, HowToFix.Structure, ContentView.CheckBoxStructure); this.Info.Standard = A11yCriteriaId.InfoAndRelationships; this.Info.ErrorCode = EvaluationCode.NeedsReview; } public override bool PassesTest(IA11yElement e) { if (e == null) throw new ArgumentNullException(nameof(e)); return ContentView.CheckBoxStructure.Matches(e); } protected override Condition CreateCondition() { return CheckBox; } } // class } // namespace
37.486486
136
0.693583
[ "MIT" ]
Microsoft/axe-windows
src/Rules/Library/Structure/ContentView/CheckBox.cs
1,351
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using DotnetApiDemo.Data; namespace DotnetApiDemo.Migrations { [DbContext(typeof(DataContext))] partial class DataContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.9") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("DotnetApiDemo.Models.Todo", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<bool>("Done") .HasColumnType("bit"); b.Property<string>("Message") .HasColumnType("nvarchar(max)"); b.Property<int?>("UserId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("Todos"); }); modelBuilder.Entity("DotnetApiDemo.Models.User", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<byte[]>("PasswordHash") .HasColumnType("varbinary(max)"); b.Property<byte[]>("PasswordSalt") .HasColumnType("varbinary(max)"); b.Property<string>("Username") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Users"); }); modelBuilder.Entity("DotnetApiDemo.Models.Todo", b => { b.HasOne("DotnetApiDemo.Models.User", "User") .WithMany("Todos") .HasForeignKey("UserId"); b.Navigation("User"); }); modelBuilder.Entity("DotnetApiDemo.Models.User", b => { b.Navigation("Todos"); }); #pragma warning restore 612, 618 } } }
34.373494
125
0.518051
[ "Unlicense" ]
Adeas/DotnetApiDemo
Migrations/DataContextModelSnapshot.cs
2,855
C#
using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Lucene.Net.Store { using Lucene.Net.Support; using System; /* * 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. */ // javadocs using CodecUtil = Lucene.Net.Codecs.CodecUtil; // javadocs using CorruptIndexException = Lucene.Net.Index.CorruptIndexException; using IndexFileNames = Lucene.Net.Index.IndexFileNames; using IOUtils = Lucene.Net.Util.IOUtils; /// <summary> /// Class for accessing a compound stream. /// this class implements a directory, but is limited to only read operations. /// Directory methods that would normally modify data throw an exception. /// <p> /// All files belonging to a segment have the same name with varying extensions. /// The extensions correspond to the different file formats used by the <seealso cref="Codec"/>. /// When using the Compound File format these files are collapsed into a /// single <tt>.cfs</tt> file (except for the <seealso cref="LiveDocsFormat"/>, with a /// corresponding <tt>.cfe</tt> file indexing its sub-files. /// <p> /// Files: /// <ul> /// <li><tt>.cfs</tt>: An optional "virtual" file consisting of all the other /// index files for systems that frequently run out of file handles. /// <li><tt>.cfe</tt>: The "virtual" compound file's entry table holding all /// entries in the corresponding .cfs file. /// </ul> /// <p>Description:</p> /// <ul> /// <li>Compound (.cfs) --&gt; Header, FileData <sup>FileCount</sup></li> /// <li>Compound Entry Table (.cfe) --&gt; Header, FileCount, &lt;FileName, /// DataOffset, DataLength&gt; <sup>FileCount</sup>, Footer</li> /// <li>Header --&gt; <seealso cref="CodecUtil#writeHeader CodecHeader"/></li> /// <li>FileCount --&gt; <seealso cref="DataOutput#writeVInt VInt"/></li> /// <li>DataOffset,DataLength --&gt; <seealso cref="DataOutput#writeLong UInt64"/></li> /// <li>FileName --&gt; <seealso cref="DataOutput#writeString String"/></li> /// <li>FileData --&gt; raw file data</li> /// <li>Footer --&gt; <seealso cref="CodecUtil#writeFooter CodecFooter"/></li> /// </ul> /// <p>Notes:</p> /// <ul> /// <li>FileCount indicates how many files are contained in this compound file. /// The entry table that follows has that many entries. /// <li>Each directory entry contains a long pointer to the start of this file's data /// section, the files length, and a String with that file's name. /// </ul> /// /// @lucene.experimental /// </summary> public sealed class CompoundFileDirectory : BaseDirectory { /// <summary> /// Offset/Length for a slice inside of a compound file </summary> public sealed class FileEntry { internal long Offset; internal long Length; } private readonly Directory Directory_Renamed; private readonly string FileName; private readonly int ReadBufferSize; private readonly IDictionary<string, FileEntry> Entries; private readonly bool OpenForWrite; private static readonly IDictionary<string, FileEntry> SENTINEL = CollectionsHelper.EmptyMap<string, FileEntry>(); private readonly CompoundFileWriter Writer; private readonly IndexInputSlicer Handle; /// <summary> /// Create a new CompoundFileDirectory. /// </summary> public CompoundFileDirectory(Directory directory, string fileName, IOContext context, bool openForWrite) { this.Directory_Renamed = directory; this.FileName = fileName; this.ReadBufferSize = BufferedIndexInput.BufferSize(context); this.isOpen = false; this.OpenForWrite = openForWrite; if (!openForWrite) { bool success = false; Handle = directory.CreateSlicer(fileName, context); try { this.Entries = ReadEntries(Handle, directory, fileName); success = true; } finally { if (!success) { IOUtils.CloseWhileHandlingException(Handle); } } this.isOpen = true; Writer = null; } else { Debug.Assert(!(directory is CompoundFileDirectory), "compound file inside of compound file: " + fileName); this.Entries = SENTINEL; this.isOpen = true; Writer = new CompoundFileWriter(directory, fileName); Handle = null; } } // LUCENENET NOTE: These MUST be sbyte because they can be negative private static readonly sbyte CODEC_MAGIC_BYTE1 = (sbyte)Number.URShift(CodecUtil.CODEC_MAGIC, 24); private static readonly sbyte CODEC_MAGIC_BYTE2 = (sbyte)Number.URShift(CodecUtil.CODEC_MAGIC, 16); private static readonly sbyte CODEC_MAGIC_BYTE3 = (sbyte)Number.URShift(CodecUtil.CODEC_MAGIC, 8); private static readonly sbyte CODEC_MAGIC_BYTE4 = unchecked((sbyte)CodecUtil.CODEC_MAGIC); /// <summary> /// Helper method that reads CFS entries from an input stream </summary> private static IDictionary<string, FileEntry> ReadEntries(IndexInputSlicer handle, Directory dir, string name) { System.IO.IOException priorE = null; IndexInput stream = null; ChecksumIndexInput entriesStream = null; // read the first VInt. If it is negative, it's the version number // otherwise it's the count (pre-3.1 indexes) try { IDictionary<string, FileEntry> mapping; stream = handle.OpenFullSlice(); int firstInt = stream.ReadVInt(); // impossible for 3.0 to have 63 files in a .cfs, CFS writer was not visible // and separate norms/etc are outside of cfs. if (firstInt == CODEC_MAGIC_BYTE1) { sbyte secondByte = (sbyte)stream.ReadByte(); sbyte thirdByte = (sbyte)stream.ReadByte(); sbyte fourthByte = (sbyte)stream.ReadByte(); if (secondByte != CODEC_MAGIC_BYTE2 || thirdByte != CODEC_MAGIC_BYTE3 || fourthByte != CODEC_MAGIC_BYTE4) { throw new CorruptIndexException("Illegal/impossible header for CFS file: " + secondByte + "," + thirdByte + "," + fourthByte); } int version = CodecUtil.CheckHeaderNoMagic(stream, CompoundFileWriter.DATA_CODEC, CompoundFileWriter.VERSION_START, CompoundFileWriter.VERSION_CURRENT); string entriesFileName = IndexFileNames.SegmentFileName(IndexFileNames.StripExtension(name), "", IndexFileNames.COMPOUND_FILE_ENTRIES_EXTENSION); entriesStream = dir.OpenChecksumInput(entriesFileName, IOContext.READONCE); CodecUtil.CheckHeader(entriesStream, CompoundFileWriter.ENTRY_CODEC, CompoundFileWriter.VERSION_START, CompoundFileWriter.VERSION_CURRENT); int numEntries = entriesStream.ReadVInt(); mapping = new Dictionary<string, FileEntry>(numEntries); for (int i = 0; i < numEntries; i++) { FileEntry fileEntry = new FileEntry(); string id = entriesStream.ReadString(); //If the key was already present if (mapping.ContainsKey(id)) { throw new CorruptIndexException("Duplicate cfs entry id=" + id + " in CFS: " + entriesStream); } else { mapping[id] = fileEntry; } fileEntry.Offset = entriesStream.ReadLong(); fileEntry.Length = entriesStream.ReadLong(); } if (version >= CompoundFileWriter.VERSION_CHECKSUM) { CodecUtil.CheckFooter(entriesStream); } else { CodecUtil.CheckEOF(entriesStream); } } else { // TODO remove once 3.x is not supported anymore mapping = ReadLegacyEntries(stream, firstInt); } return mapping; } catch (System.IO.IOException ioe) { priorE = ioe; } finally { IOUtils.CloseWhileHandlingException(priorE, stream, entriesStream); } // this is needed until Java 7's real try-with-resources: throw new InvalidOperationException("impossible to get here"); } private static IDictionary<string, FileEntry> ReadLegacyEntries(IndexInput stream, int firstInt) { IDictionary<string, FileEntry> entries = new Dictionary<string, FileEntry>(); int count; bool stripSegmentName; if (firstInt < CompoundFileWriter.FORMAT_PRE_VERSION) { if (firstInt < CompoundFileWriter.FORMAT_NO_SEGMENT_PREFIX) { throw new CorruptIndexException("Incompatible format version: " + firstInt + " expected >= " + CompoundFileWriter.FORMAT_NO_SEGMENT_PREFIX + " (resource: " + stream + ")"); } // It's a post-3.1 index, read the count. count = stream.ReadVInt(); stripSegmentName = false; } else { count = firstInt; stripSegmentName = true; } // read the directory and init files long streamLength = stream.Length(); FileEntry entry = null; for (int i = 0; i < count; i++) { long offset = stream.ReadLong(); if (offset < 0 || offset > streamLength) { throw new CorruptIndexException("Invalid CFS entry offset: " + offset + " (resource: " + stream + ")"); } string id = stream.ReadString(); if (stripSegmentName) { // Fix the id to not include the segment names. this is relevant for // pre-3.1 indexes. id = IndexFileNames.StripSegmentName(id); } if (entry != null) { // set length of the previous entry entry.Length = offset - entry.Offset; } entry = new FileEntry(); entry.Offset = offset; FileEntry previous; if (entries.TryGetValue(id, out previous)) { throw new CorruptIndexException("Duplicate cfs entry id=" + id + " in CFS: " + stream); } else { entries[id] = entry; } } // set the length of the final entry if (entry != null) { entry.Length = streamLength - entry.Offset; } return entries; } public Directory Directory { get { return Directory_Renamed; } } public string Name { get { return FileName; } } public override void Dispose() { lock (this) { if (!IsOpen) { // allow double close - usually to be consistent with other closeables return; // already closed } isOpen = false; if (Writer != null) { Debug.Assert(OpenForWrite); Writer.Dispose(); } else { IOUtils.Close(Handle); } } } public override IndexInput OpenInput(string name, IOContext context) { lock (this) { EnsureOpen(); Debug.Assert(!OpenForWrite); string id = IndexFileNames.StripSegmentName(name); FileEntry entry; if (!Entries.TryGetValue(id, out entry)) { throw new Exception("No sub-file with id " + id + " found (fileName=" + name + " files: " + Arrays.ToString(Entries.Keys) + ")"); } return Handle.OpenSlice(name, entry.Offset, entry.Length); } } /// <summary> /// Returns an array of strings, one for each file in the directory. </summary> public override string[] ListAll() { EnsureOpen(); string[] res; if (Writer != null) { res = Writer.ListAll(); } else { res = Entries.Keys.ToArray(); // Add the segment name string seg = IndexFileNames.ParseSegmentName(FileName); for (int i = 0; i < res.Length; i++) { res[i] = seg + res[i]; } } return res; } /// <summary> /// Returns true iff a file with the given name exists. </summary> [Obsolete] public override bool FileExists(string name) { EnsureOpen(); if (this.Writer != null) { return Writer.FileExists(name); } return Entries.ContainsKey(IndexFileNames.StripSegmentName(name)); } /// <summary> /// Not implemented </summary> /// <exception cref="UnsupportedOperationException"> always: not supported by CFS </exception> public override void DeleteFile(string name) { throw new System.NotSupportedException(); } /// <summary> /// Not implemented </summary> /// <exception cref="UnsupportedOperationException"> always: not supported by CFS </exception> public void RenameFile(string from, string to) { throw new System.NotSupportedException(); } /// <summary> /// Returns the length of a file in the directory. </summary> /// <exception cref="System.IO.IOException"> if the file does not exist </exception> public override long FileLength(string name) { EnsureOpen(); if (this.Writer != null) { return Writer.FileLength(name); } FileEntry e = Entries[IndexFileNames.StripSegmentName(name)]; if (e == null) { throw new Exception(name); } return e.Length; } public override IndexOutput CreateOutput(string name, IOContext context) { EnsureOpen(); return Writer.CreateOutput(name, context); } public override void Sync(ICollection<string> names) { throw new System.NotSupportedException(); } /// <summary> /// Not implemented </summary> /// <exception cref="UnsupportedOperationException"> always: not supported by CFS </exception> public override Lock MakeLock(string name) { throw new System.NotSupportedException(); } public override IndexInputSlicer CreateSlicer(string name, IOContext context) { EnsureOpen(); Debug.Assert(!OpenForWrite); string id = IndexFileNames.StripSegmentName(name); FileEntry entry = Entries[id]; if (entry == null) { throw new Exception("No sub-file with id " + id + " found (fileName=" + name + " files: " + Entries.Keys + ")"); } return new IndexInputSlicerAnonymousInnerClassHelper(this, entry); } private class IndexInputSlicerAnonymousInnerClassHelper : IndexInputSlicer { private readonly CompoundFileDirectory OuterInstance; private Lucene.Net.Store.CompoundFileDirectory.FileEntry Entry; public IndexInputSlicerAnonymousInnerClassHelper(CompoundFileDirectory outerInstance, Lucene.Net.Store.CompoundFileDirectory.FileEntry entry) : base(outerInstance) { this.OuterInstance = outerInstance; this.Entry = entry; } public override void Dispose(bool disposing) { } public override IndexInput OpenSlice(string sliceDescription, long offset, long length) { return OuterInstance.Handle.OpenSlice(sliceDescription, Entry.Offset + offset, length); } [Obsolete] public override IndexInput OpenFullSlice() { return OpenSlice("full-slice", 0, Entry.Length); } } public override string ToString() { return "CompoundFileDirectory(file=\"" + FileName + "\" in dir=" + Directory_Renamed + ")"; } } }
39.757384
192
0.537755
[ "Apache-2.0" ]
BlueCurve-Team/lucenenet
src/Lucene.Net.Core/Store/CompoundFileDirectory.cs
18,845
C#
using System.Collections.Generic; namespace MyRoutine.Web.Areas.Admin.ViewModels.Statistics { public class StatisticsViewModel { public StatisticsViewModel() { UserRegistrationsPerMonth = new List<PerMonthViewModel>(); TasksCreatedPerMonth = new List<PerMonthViewModel>(); TasksCompletedPerMonth = new List<PerMonthViewModel>(); } public int UserRegistrationsToday { get; set; } public int TasksCreatedToday { get; set; } public int TasksCompletedToday { get; set; } public List<PerMonthViewModel> UserRegistrationsPerMonth { get; set; } public List<PerMonthViewModel> TasksCreatedPerMonth { get; set; } public List<PerMonthViewModel> TasksCompletedPerMonth { get; set; } } }
36.681818
78
0.672862
[ "MIT" ]
davidtimovski/my-routine
MyRoutine.Web/Areas/Admin/ViewModels/Statistics/StatisticsViewModel.cs
809
C#
using System; using System.Collections.Generic; namespace GraphQL { public static class EnumerableExtensions { /// <summary> /// Performs the indicated action on each item. /// </summary> /// <param name="items">The list of items to act on.</param> /// <param name="action">The action to be performed.</param> /// <remarks>If an exception occurs, the action will not be performed on the remaining items.</remarks> public static void Apply<T>(this IEnumerable<T> items, Action<T> action) { foreach (var item in items) { action(item); } } /// <summary> /// Performs the indicated action on each item. Boxing free for <c>List+Enumerator{T}</c>. /// </summary> /// <param name="items">The list of items to act on.</param> /// <param name="action">The action to be performed.</param> /// <remarks>If an exception occurs, the action will not be performed on the remaining items.</remarks> public static void Apply<T>(this List<T> items, Action<T> action) { foreach (var item in items) { action(item); } } /// <summary> /// Performs the indicated action on each key-value pair. /// </summary> /// <param name="items">The dictionary of items to act on.</param> /// <param name="action">The action to be performed.</param> /// <remarks>If an exception occurs, the action will not be performed on the remaining items.</remarks> public static void Apply(this System.Collections.IDictionary items, Action<object, object> action) { foreach (object key in items.Keys) { action(key, items[key]); } } } }
36.784314
111
0.566631
[ "MIT" ]
Rensvind/graphql-dotnet
src/GraphQL/EnumerableExtensions.cs
1,876
C#
using System; using Vk.Api.Schema.Enums.Wall; namespace Vk.Api.Schema.Common.Wall { /// <summary> /// Интерфейс, представляющий данные о способе размещения записи на стене /// </summary> public interface IPostSource { /// <summary> /// Тип источника /// </summary> SourceType Type { get; } /// <summary> /// Название платформы, если доступно, /// иначе <see langword="null"/> /// </summary> SourcePlatform? Platform { get; } /// <summary> /// Тип действия, если доступно, /// иначе <see langword="null"/> /// </summary> SourceData? Data { get; } /// <summary> /// Url ресурса, с которого была опубликованая запись /// </summary> Uri Url { get; } } }
24.909091
77
0.530414
[ "MIT" ]
extremecodetv/Vk.Api.Schema
src/Vk.Api.Schema/Common/Wall/~Interfaces/IPostSource.cs
997
C#
using System; namespace LBC_Beauty_Parlour_Management.Web.Models { public class ErrorViewModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } }
19.333333
70
0.693966
[ "MIT" ]
Last-Bench-Coder/LBC-Beauty-Parlour-Management
LBC-Beauty-Parlour-Management.Web/Models/ErrorViewModel.cs
232
C#
using SharpDX; using SharpDX.DirectInput; using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using XOutput.Tools; namespace XOutput.Devices.Input.DirectInput { /// <summary> /// Device that contains data for a DirectInput device /// </summary> public sealed class DirectDevice : IInputDevice { #region Constants /// <summary> /// The delay in milliseconds to sleep between input reads. /// </summary> public const int ReadDelayMs = 1; private static readonly Regex hidRegex = new Regex("(hid)#([^#]+)#([^#]+)"); #endregion #region Events /// <summary> /// Triggered periodically to trigger input read from Direct input device. /// <para>Implements <see cref="IDevice.InputChanged"/></para> /// </summary> public event DeviceInputChangedHandler InputChanged; /// <summary> /// Triggered when the any read or write fails. /// <para>Implements <see cref="IInputDevice.Disconnected"/></para> /// </summary> public event DeviceDisconnectedHandler Disconnected; #endregion #region Properties /// <summary> /// Gets the GUID of the controller. /// </summary> public Guid Id => deviceInstance.InstanceGuid; /// <summary> /// <para>Implements <see cref="IInputDevice.UniqueId"/></para> /// </summary> public string UniqueId => deviceInstance.InstanceGuid.ToString(); /// <summary> /// Gets the product name of the device. /// <para>Implements <see cref="IInputDevice.DisplayName"/></para> /// </summary> public string DisplayName => deviceInstance.ProductName; /// <summary> /// Gets or sets if the device is connected and ready to use. /// <para>Implements <see cref="IInputDevice.Connected"/></para> /// </summary> public bool Connected { get => connected; set { if (value != connected) { if (!connected) { Disconnected?.Invoke(this, new DeviceDisconnectedEventArgs()); } connected = value; } } } /// <summary> /// <para>Implements <see cref="IDevice.DPads"/></para> /// </summary> public IEnumerable<DPadDirection> DPads => state.DPads; /// <summary> /// <para>Implements <see cref="IDevice.Sources"/></para> /// </summary> public IEnumerable<InputSource> Sources => sources; /// <summary> /// <para>Implements <see cref="IInputDevice.ForceFeedbackCount"/></para> /// </summary> public int ForceFeedbackCount => actuators.Count; /// <summary> /// <para>Implements <see cref="IInputDevice.InputConfiguration"/></para> /// </summary> public InputConfig InputConfiguration => inputConfig; public string HardwareID { get { if (deviceInstance.IsHumanInterfaceDevice) { return IdHelper.GetHardwareId(joystick.Properties.InterfacePath); } return null; } } #endregion // private static readonly ILogger logger = LoggerFactory.GetLogger(typeof(DirectDevice)); private readonly DeviceInstance deviceInstance; private readonly Joystick joystick; private readonly DirectInputSource[] sources; private readonly DeviceState state; private readonly EffectInfo force; private readonly List<DirectDeviceForceFeedback> actuators = new List<DirectDeviceForceFeedback>(); private readonly InputConfig inputConfig; private bool connected = false; private readonly Thread inputRefresher; private bool disposed = false; private DeviceInputChangedEventArgs deviceInputChangedEventArgs; /// <summary> /// Creates a new DirectDevice instance. /// </summary> /// <param name="deviceInstance">SharpDX instanse</param> /// <param name="joystick">SharpDX joystick</param> public DirectDevice(DeviceInstance deviceInstance, Joystick joystick) { this.deviceInstance = deviceInstance; this.joystick = joystick; DeviceObjectInstance[] buttonObjectInstances = joystick.GetObjects(DeviceObjectTypeFlags.Button).Where(b => b.Usage > 0).OrderBy(b => b.ObjectId.InstanceNumber).Take(128).ToArray(); DirectInputSource[] buttons = buttonObjectInstances.Select((b, i) => new DirectInputSource(this, "Button " + b.Usage, InputSourceTypes.Button, b.Offset, state => state.Buttons[i] ? 1 : 0)).ToArray(); IEnumerable<DirectInputSource> axes = GetAxes().OrderBy(a => a.Usage).Take(24).Select(GetAxisSource); IEnumerable<DirectInputSource> sliders = GetSliders().OrderBy(a => a.Usage).Select(GetSliderSource); IEnumerable<DirectInputSource> dpads = new DirectInputSource[0]; if (joystick.Capabilities.PovCount > 0) { dpads = Enumerable.Range(0, joystick.Capabilities.PovCount) .SelectMany(i => new DirectInputSource[] { new DirectInputSource(this, "DPad" + (i + 1) + " Up", InputSourceTypes.Dpad, 1000 + i * 4, state => GetDPadValue(i).HasFlag(DPadDirection.Up) ? 1 : 0), new DirectInputSource(this, "DPad" + (i + 1) + " Down", InputSourceTypes.Dpad, 1001 + i * 4, state => GetDPadValue(i).HasFlag(DPadDirection.Down) ? 1 : 0), new DirectInputSource(this, "DPad" + (i + 1) + " Left", InputSourceTypes.Dpad, 1002 + i * 4, state => GetDPadValue(i).HasFlag(DPadDirection.Left) ? 1 : 0), new DirectInputSource(this, "DPad" + (i + 1) + " Right", InputSourceTypes.Dpad, 1003 + i * 4, state => GetDPadValue(i).HasFlag(DPadDirection.Right) ? 1 : 0), }); } sources = buttons.Concat(axes).Concat(sliders).Concat(dpads).ToArray(); joystick.Properties.AxisMode = DeviceAxisMode.Absolute; joystick.Acquire(); if (deviceInstance.ForceFeedbackDriverGuid != Guid.Empty) { EffectInfo constantForce = joystick.GetEffects().FirstOrDefault(x => x.Guid == EffectGuid.ConstantForce); if (constantForce == null) { force = joystick.GetEffects().FirstOrDefault(); } else { force = constantForce; } DeviceObjectInstance[] actuatorAxes = joystick.GetObjects().Where(doi => doi.ObjectId.Flags.HasFlag(DeviceObjectTypeFlags.ForceFeedbackActuator)).ToArray(); for (int i = 0; i < actuatorAxes.Length; i++) { if (i + 1 < actuatorAxes.Length) { actuators.Add(new DirectDeviceForceFeedback(joystick, force, actuatorAxes[i], actuatorAxes[i + 1])); i++; } else { actuators.Add(new DirectDeviceForceFeedback(joystick, force, actuatorAxes[i])); } } } state = new DeviceState(sources, joystick.Capabilities.PovCount); deviceInputChangedEventArgs = new DeviceInputChangedEventArgs(this); inputConfig = new InputConfig(ForceFeedbackCount); inputRefresher = new Thread(InputRefresher) { Name = ToString() + " input reader" }; inputRefresher.SetApartmentState(ApartmentState.STA); inputRefresher.IsBackground = true; Connected = true; inputRefresher.Start(); } ~DirectDevice() { Dispose(); } /// <summary> /// Disposes all resources. /// </summary> public void Dispose() { if (!disposed) { disposed = true; inputRefresher?.Interrupt(); foreach (DirectDeviceForceFeedback actuator in actuators) { actuator.Dispose(); } joystick.Dispose(); } } /// <summary> /// Display name followed by the deviceID. /// <para>Overrides <see cref="object.ToString()"/></para> /// </summary> /// <returns>Friendly name</returns> public override string ToString() { return UniqueId; } private void InputRefresher() { try { while (Connected) { Connected = RefreshInput(); Thread.Sleep(ReadDelayMs); } } catch (ThreadInterruptedException) { // Thread has been interrupted } } /// <summary> /// Gets the current state of the inputTpye. /// <para>Implements <see cref="IDevice.Get(InputSource)"/></para> /// </summary> /// <param name="source">Type of input</param> /// <returns>Value</returns> public double Get(InputSource source) { return source.Value; } /// <summary> /// Sets the force feedback motor values. /// <para>Implements <see cref="IInputDevice.SetForceFeedback(double, double)"/></para> /// </summary> /// <param name="big">Big motor value</param> /// <param name="small">Small motor value</param> public void SetForceFeedback(double big, double small) { if (ForceFeedbackCount == 0) { return; } if (!inputConfig.ForceFeedback) { big = 0; small = 0; } foreach (DirectDeviceForceFeedback actuator in actuators) { actuator.SetForceFeedback(big, small); } } /// <summary> /// Refreshes the current state. Triggers <see cref="InputChanged"/> event. /// </summary> /// <returns>if the input was available</returns> public bool RefreshInput(bool force = false) { state.ResetChanges(); if (!disposed) { try { joystick.Poll(); for (int i = 0; i < state.DPads.Count(); i++) { state.SetDPad(i, GetDPadValue(i)); } foreach (DirectInputSource source in sources) { if (source.Refresh(GetCurrentState())) { state.MarkChanged(source); } } IEnumerable<InputSource> changes = state.GetChanges(force); IEnumerable<int> dpadChanges = state.GetChangedDpads(force); if (changes.Any() || dpadChanges.Any()) { deviceInputChangedEventArgs.Refresh(changes, dpadChanges); InputChanged?.Invoke(this, deviceInputChangedEventArgs); } return true; } catch (Exception) { Console.WriteLine($"Poll failed for {ToString()}"); return false; } } return false; } /// <summary> /// Gets the current value of an axis. /// </summary> /// <param name="axis">Axis index</param> /// <returns>Value</returns> private int GetAxisValue(int instanceNumber) { JoystickState currentState = GetCurrentState(); if (instanceNumber < 0) { throw new ArgumentException(nameof(instanceNumber)); } switch (instanceNumber) { case 0: return currentState.X; case 1: return ushort.MaxValue - currentState.Y; case 2: return currentState.Z; case 3: return currentState.RotationX; case 4: return ushort.MaxValue - currentState.RotationY; case 5: return currentState.RotationZ; case 6: return currentState.AccelerationX; case 7: return ushort.MaxValue - currentState.AccelerationY; case 8: return currentState.AccelerationZ; case 9: return currentState.AngularAccelerationX; case 10: return ushort.MaxValue - currentState.AngularAccelerationY; case 11: return currentState.AngularAccelerationZ; case 12: return currentState.ForceX; case 13: return ushort.MaxValue - currentState.ForceY; case 14: return currentState.ForceZ; case 15: return currentState.TorqueX; case 16: return ushort.MaxValue - currentState.TorqueY; case 17: return currentState.TorqueZ; case 18: return currentState.VelocityX; case 19: return ushort.MaxValue - currentState.VelocityY; case 20: return currentState.VelocityZ; case 21: return currentState.AngularVelocityX; case 22: return ushort.MaxValue - currentState.AngularVelocityY; case 23: return currentState.AngularVelocityZ; default: return 0; } } /// <summary> /// Gets the current value of a slider. /// </summary> /// <param name="slider">Slider index</param> /// <returns>Value</returns> private int GetSliderValue(int slider) { JoystickState currentState = GetCurrentState(); if (slider < 1) { throw new ArgumentException(nameof(slider)); } return currentState.Sliders[slider - 1]; } /// <summary> /// Gets the current value of a DPad. /// </summary> /// <param name="dpad">DPad index</param> /// <returns>Value</returns> private DPadDirection GetDPadValue(int dpad) { JoystickState currentState = GetCurrentState(); switch (currentState.PointOfViewControllers[dpad]) { case -1: return DPadDirection.None; case 0: return DPadDirection.Up; case 4500: return DPadDirection.Up | DPadDirection.Right; case 9000: return DPadDirection.Right; case 13500: return DPadDirection.Down | DPadDirection.Right; case 18000: return DPadDirection.Down; case 22500: return DPadDirection.Down | DPadDirection.Left; case 27000: return DPadDirection.Left; case 31500: return DPadDirection.Up | DPadDirection.Left; default: throw new ArgumentException(nameof(dpad)); } } /// <summary> /// Gets and initializes available axes for the device. /// </summary> /// <returns><see cref="DirectInputTypes"/> of the axes</returns> private DeviceObjectInstance[] GetAxes() { DeviceObjectInstance[] axes = joystick.GetObjects(DeviceObjectTypeFlags.AbsoluteAxis).Where(o => o.ObjectType != ObjectGuid.Slider).ToArray(); foreach (DeviceObjectInstance axis in axes) { ObjectProperties properties = joystick.GetObjectPropertiesById(axis.ObjectId); try { properties.Range = new InputRange(ushort.MinValue, ushort.MaxValue); properties.DeadZone = 0; properties.Saturation = 10000; } catch (SharpDXException ex) { Console.WriteLine($"[❌] {ex.Message}"); } } return axes; } /// <summary> /// Gets available sliders for the device. /// </summary> /// <returns><see cref="DirectInputTypes"/> of the axes</returns> private DeviceObjectInstance[] GetSliders() { return joystick.GetObjects().Where(o => o.ObjectType == ObjectGuid.Slider).ToArray(); } /// <summary> /// Reads the current state of the device. /// </summary> /// <returns>state</returns> private JoystickState GetCurrentState() { try { return joystick.GetCurrentState(); } catch (Exception) { Connected = false; throw; } } private DirectInputSource GetAxisSource(DeviceObjectInstance instance) { InputSourceTypes type = InputSourceTypes.AxisX; if (instance.ObjectType == ObjectGuid.XAxis || instance.ObjectType == ObjectGuid.RxAxis) { type = InputSourceTypes.AxisX; } else if (instance.ObjectType == ObjectGuid.YAxis || instance.ObjectType == ObjectGuid.RyAxis) { type = InputSourceTypes.AxisY; } else if (instance.ObjectType == ObjectGuid.ZAxis || instance.ObjectType == ObjectGuid.RzAxis) { type = InputSourceTypes.AxisZ; } int axisCount; if (instance.Usage >= 48) { axisCount = instance.Usage - 48; } else { axisCount = instance.ObjectId.InstanceNumber; } string name = instance.Name; return new DirectInputSource(this, name, type, instance.Offset, state => (GetAxisValue(axisCount)) / (double)ushort.MaxValue); } private DirectInputSource GetSliderSource(DeviceObjectInstance instance, int i) { string name = instance.Name; return new DirectInputSource(this, name, InputSourceTypes.Slider, instance.Offset, state => (GetSliderValue(i + 1)) / (double)ushort.MaxValue); } } }
39.881048
212
0.509529
[ "MIT" ]
Cai1Hsu/BlackShark2Driver
DirectDevice.cs
19,783
C#
// Copyright (c) Microsoft. All rights reserved. using SDKTemplate.Common; using SplashScreenSample; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace SDKTemplate { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> sealed partial class App : Application { /// <summary> /// 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() { this.InitializeComponent(); this.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 (e.PreviousExecutionState != ApplicationExecutionState.Running) { bool loadState = (e.PreviousExecutionState == ApplicationExecutionState.Terminated); ExtendedSplash extendedSplash = new ExtendedSplash(e.SplashScreen, loadState); Window.Current.Content = extendedSplash; } 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> 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 async void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); await SuspensionManager.SaveAsync(); deferral.Complete(); } } }
37.487805
100
0.657775
[ "MIT" ]
Ranin26/msdn-code-gallery-microsoft
Official Windows Platform Sample/Splash screen sample/[C#]-Splash screen sample/C#/Shared/App.xaml.cs
3,074
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.IO; using System.Security.Cryptography.X509Certificates; namespace Microsoft.Azure.Management.ResourceManager.Fluent.Authentication { public class ServicePrincipalLoginInformation { public string ClientId { get; set; } public string ClientSecret { get; set; } public byte[] Certificate { get; set; } public string CertificatePassword { get; set; } #if NET45 public X509Certificate2 X509Certificate { get; set; } #endif } }
27.166667
95
0.719325
[ "MIT" ]
abharath27/azure-libraries-for-net
src/ResourceManagement/ResourceManager/Authentication/ServicePrincipalLoginInformation.cs
654
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using MOE.Common.Business.Bins; using MOE.Common.Business.WCFServiceLibrary; using MOE.Common.Business.WCFServiceLibrary.Tests; using MOE.Common.Models; using MOE.Common.Models.Repositories; using MOE.CommonTests.Models; namespace MOE.CommonTests.Business.WCFServiceLibrary.PreemptionAggregationChart { [TestClass] public class PreemptionsAggregationChartTests: SignalAggregationCreateMetricTestsBase { protected override void SetSpecificAggregateRepositoriesForTest() { SignalEventCountAggregationRepositoryFactory.SetRepository(new InMemorySignalEventCountAggregationRepository(Db)); PreemptAggregationDatasRepositoryFactory.SetArchivedMetricsRepository(new InMemoryPreemptAggregationDatasRepository(Db)); foreach (var signal in Db.Signals) { PopulateSignalData(signal); } } protected override void PopulateSignalData(Signal signal) { Db.PopulatePreemptAggregations(Convert.ToDateTime("1/1/2016"), Convert.ToDateTime("1/1/2018"), signal.SignalID, signal.VersionID); Db.PopulateSignalEventCountwithRandomValues(Convert.ToDateTime("1/1/2016"), Convert.ToDateTime("1/1/2018"), signal); } [TestMethod] public void CreateTimeMetricStartToFinishAllBinSizesAllAggregateDataTypesTest() { var options = new PreemptionAggregationOptions(); base.CreateTimeMetricStartToFinishAllBinSizesAllAggregateDataTypesTest(options); } } }
40.190476
142
0.744076
[ "Apache-2.0" ]
avenueconsultants/ATSPM
MOE.CommonTests/Business/WCFServiceLibrary/PreemptionAggregationChart/PreemptionsAggregationChartTests.cs
1,690
C#
#region Copyright // // DotNetNuke® - http://www.dotnetnuke.com // Copyright (c) 2002-2018 // by DotNetNuke Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions // of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #endregion using System; using System.Collections; using System.Diagnostics; using System.IO; using System.Reflection; using System.Web; using System.Web.UI.WebControls; using Components; using DNNtc; using DotNetNuke.Common.Lists; using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Tabs; using DotNetNuke.Security; using DotNetNuke.Security.Roles; using DotNetNuke.Services.Exceptions; using DotNetNuke.Services.FileSystem; using DotNetNuke.Services.Localization; using DotNetNuke.Web.UI.WebControls.Extensions; using Microsoft.VisualBasic; using Telerik.Web.UI; using FirstDayOfWeek = System.Web.UI.WebControls.FirstDayOfWeek; using Globals = DotNetNuke.Common.Globals; namespace DotNetNuke.Modules.Events { [ModuleControlProperties("EventSettings", "Event Settings", ControlType.View, "https://github.com/DNNCommunity/DNN.Events/wiki", true, true)] public partial class EventSettings : EventBase { #region Private Data private readonly EventMasterController _objCtlMasterEvent = new EventMasterController(); #endregion protected override void OnInit(EventArgs e) { base.OnInit(e); // Add the click event cmdUpdateTemplate.Click += cmdUpdateTemplate_Click; cmdResetTemplate.Click += cmdResetTemplate_Click; } #region Web Form Designer Generated Code //This call is required by the Web Form Designer. [DebuggerStepThrough] private void InitializeComponent() { } private void Page_Init(object sender, EventArgs e) { //CODEGEN: This method call is required by the Web Form Designer //Do not modify it using the code editor. InitializeComponent(); } #endregion #region Help Methods // If adding new Setting also see 'SetDefaultModuleSettings' method in EventInfoHelper Class /// <summary> /// Load current settings into the controls from the modulesettings /// </summary> /// <remarks></remarks> private void Page_Load(object sender, EventArgs e) { if (PortalSecurity.IsInRole(PortalSettings.AdministratorRoleName) || IsSettingsEditor()) { } else { Response.Redirect(GetSocialNavigateUrl(), true); } // Set the selected theme SetTheme(pnlEventsModuleSettings); // Do we have to load the settings if (!Page.IsPostBack) { LoadSettings(); } // Add the javascript to the page AddJavaScript(); } private void LoadSettings() { var availableFields = new ArrayList(); var selectedFields = new ArrayList(); // Create Lists and Schedule - they should always exist var objEventController = new EventController(); objEventController.CreateListsAndSchedule(); //Set text and tooltip from resourcefile chkMonthAllowed.Text = Localization.GetString("Month", LocalResourceFile); chkWeekAllowed.Text = Localization.GetString("Week", LocalResourceFile); chkListAllowed.Text = Localization.GetString("List", LocalResourceFile); cmdAdd.ToolTip = Localization.GetString("Add", LocalResourceFile); cmdAddAll.ToolTip = Localization.GetString("AddAll", LocalResourceFile); cmdRemove.ToolTip = Localization.GetString("Remove", LocalResourceFile); cmdRemoveAll.ToolTip = Localization.GetString("RemoveAll", LocalResourceFile); cmdAddCals.ToolTip = Localization.GetString("AddCals", LocalResourceFile); cmdAddAllCals.ToolTip = Localization.GetString("AddAllCals", LocalResourceFile); cmdRemoveCals.ToolTip = Localization.GetString("RemoveCals", LocalResourceFile); cmdRemoveAllCals.ToolTip = Localization.GetString("RemoveAllCals", LocalResourceFile); chkIconMonthPrio.Text = Localization.GetString("Priority", LocalResourceFile); imgIconMonthPrioHigh.AlternateText = Localization.GetString("HighPrio", LocalResourceFile); imgIconMonthPrioLow.AlternateText = Localization.GetString("LowPrio", LocalResourceFile); chkIconMonthRec.Text = Localization.GetString("Recurring", LocalResourceFile); imgIconMonthRec.AlternateText = Localization.GetString("RecurringEvent", LocalResourceFile); chkIconMonthReminder.Text = Localization.GetString("Reminder", LocalResourceFile); imgIconMonthReminder.AlternateText = Localization.GetString("ReminderEnabled", LocalResourceFile); chkIconMonthEnroll.Text = Localization.GetString("Enroll", LocalResourceFile); imgIconMonthEnroll.AlternateText = Localization.GetString("EnrollEnabled", LocalResourceFile); chkIconWeekPrio.Text = Localization.GetString("Priority", LocalResourceFile); imgIconWEEKPrioHigh.AlternateText = Localization.GetString("HighPrio", LocalResourceFile); imgIconWeekPrioLow.AlternateText = Localization.GetString("LowPrio", LocalResourceFile); chkIconWeekRec.Text = Localization.GetString("Recurring", LocalResourceFile); imgIconWeekRec.AlternateText = Localization.GetString("RecurringEvent", LocalResourceFile); chkIconWeekReminder.Text = Localization.GetString("Reminder", LocalResourceFile); imgIconWeekReminder.AlternateText = Localization.GetString("ReminderEnabled", LocalResourceFile); chkIconWeekEnroll.Text = Localization.GetString("Enroll", LocalResourceFile); imgIconWeekEnroll.AlternateText = Localization.GetString("EnrollEnabled", LocalResourceFile); chkIconListPrio.Text = Localization.GetString("Priority", LocalResourceFile); imgIconListPrioHigh.AlternateText = Localization.GetString("HighPrio", LocalResourceFile); imgIconListPrioLow.AlternateText = Localization.GetString("LowPrio", LocalResourceFile); chkIconListRec.Text = Localization.GetString("Recurring", LocalResourceFile); imgIconListRec.AlternateText = Localization.GetString("RecurringEvent", LocalResourceFile); chkIconListReminder.Text = Localization.GetString("Reminder", LocalResourceFile); imgIconListReminder.AlternateText = Localization.GetString("ReminderEnabled", LocalResourceFile); chkIconListEnroll.Text = Localization.GetString("Enroll", LocalResourceFile); imgIconListEnroll.AlternateText = Localization.GetString("EnrollEnabled", LocalResourceFile); cmdUpdateTemplate.Text = Localization.GetString("cmdUpdateTemplate", LocalResourceFile); rbThemeStandard.Text = Localization.GetString("rbThemeStandard", LocalResourceFile); rbThemeCustom.Text = Localization.GetString("rbThemeCustom", LocalResourceFile); ddlModuleCategories.EmptyMessage = Localization.GetString("NoCategories", LocalResourceFile); ddlModuleCategories.Localization.AllItemsCheckedString = Localization.GetString("AllCategories", LocalResourceFile); ddlModuleCategories.Localization.CheckAllString = Localization.GetString("SelectAllCategories", LocalResourceFile); ddlModuleLocations.EmptyMessage = Localization.GetString("NoLocations", LocalResourceFile); ddlModuleLocations.Localization.AllItemsCheckedString = Localization.GetString("AllLocations", LocalResourceFile); ddlModuleLocations.Localization.CheckAllString = Localization.GetString("SelectAllLocations", LocalResourceFile); //Add templates link // lnkTemplatesHelp.HRef = AddSkinContainerControls(EditUrl("", "", "TemplateHelp", "dnnprintmode=true"), "?") lnkTemplatesHelp.HRef = AddSkinContainerControls( Globals.NavigateURL(TabId, PortalSettings, "", "mid=" + Convert.ToString(ModuleId), "ctl=TemplateHelp", "ShowNav=False", "dnnprintmode=true"), "?"); lnkTemplatesHelp.InnerText = Localization.GetString("TemplatesHelp", LocalResourceFile); //Support for Time Interval Dropdown var ctlLists = new ListController(); var colThreadStatus = ctlLists.GetListEntryInfoItems("Timeinterval"); ddlTimeInterval.Items.Clear(); foreach (var entry in colThreadStatus) { ddlTimeInterval.Items.Add(entry.Value); } ddlTimeInterval.Items.FindByValue(Settings.Timeinterval).Selected = true; // Set Dropdown TimeZone cboTimeZone.DataBind(Settings.TimeZoneId); chkEnableEventTimeZones.Checked = Settings.EnableEventTimeZones; BindToEnum(typeof(EventModuleSettings.TimeZones), ddlPrimaryTimeZone); ddlPrimaryTimeZone.Items.FindByValue(Convert.ToString((int) Settings.PrimaryTimeZone)).Selected = true; BindToEnum(typeof(EventModuleSettings.TimeZones), ddlSecondaryTimeZone); ddlSecondaryTimeZone.Items.FindByValue(Convert.ToString((int) Settings.SecondaryTimeZone)) .Selected = true; chkToolTipMonth.Checked = Settings.Eventtooltipmonth; chkToolTipWeek.Checked = Settings.Eventtooltipweek; chkToolTipDay.Checked = Settings.Eventtooltipday; chkToolTipList.Checked = Settings.Eventtooltiplist; txtTooltipLength.Text = Settings.Eventtooltiplength.ToString(); chkImageEnabled.Checked = Settings.Eventimage; txtMaxThumbHeight.Text = Settings.MaxThumbHeight.ToString(); txtMaxThumbWidth.Text = Settings.MaxThumbWidth.ToString(); chkMonthCellEvents.Checked = true; if (Settings.Monthcellnoevents) { chkMonthCellEvents.Checked = false; } chkAddSubModuleName.Checked = Settings.Addsubmodulename; chkEnforceSubCalPerms.Checked = Settings.Enforcesubcalperms; BindToEnum(typeof(EventModuleSettings.DisplayCategories), ddlEnableCategories); ddlEnableCategories.Items.FindByValue(Convert.ToString((int) Settings.Enablecategories)) .Selected = true; chkRestrictCategories.Checked = Settings.Restrictcategories; BindToEnum(typeof(EventModuleSettings.DisplayLocations), ddlEnableLocations); ddlEnableLocations.Items.FindByValue(Convert.ToString((int) Settings.Enablelocations)).Selected = true; chkRestrictLocations.Checked = Settings.Restrictlocations; chkEnableContainerSkin.Checked = Settings.Enablecontainerskin; chkEventDetailNewPage.Checked = Settings.Eventdetailnewpage; chkEnableEnrollPopup.Checked = Settings.Enableenrollpopup; chkEventImageMonth.Checked = Settings.EventImageMonth; chkEventImageWeek.Checked = Settings.EventImageWeek; chkEventDayNewPage.Checked = Settings.Eventdaynewpage; chkFullTimeScale.Checked = Settings.Fulltimescale; chkCollapseRecurring.Checked = Settings.Collapserecurring; chkIncludeEndValue.Checked = Settings.Includeendvalue; chkShowValueMarks.Checked = Settings.Showvaluemarks; chkEnableSEO.Checked = Settings.EnableSEO; txtSEODescriptionLength.Text = Settings.SEODescriptionLength.ToString(); chkEnableSitemap.Checked = Settings.EnableSitemap; txtSitemapPriority.Text = Settings.SiteMapPriority.ToString(); txtSitemapDaysBefore.Text = Settings.SiteMapDaysBefore.ToString(); txtSitemapDaysAfter.Text = Settings.SiteMapDaysAfter.ToString(); chkiCalOnIconBar.Checked = Settings.IcalOnIconBar; chkiCalEmailEnable.Checked = Settings.IcalEmailEnable; chkiCalURLinLocation.Checked = Settings.IcalURLInLocation; chkiCalIncludeCalname.Checked = Settings.IcalIncludeCalname; txtiCalDaysBefore.Text = Settings.IcalDaysBefore.ToString(); txtiCalDaysAfter.Text = Settings.IcalDaysAfter.ToString(); txtiCalURLAppend.Text = Settings.IcalURLAppend; ctliCalDefaultImage.FileFilter = Globals.glbImageFileTypes; ctliCalDefaultImage.Url = ""; chkiCalDisplayImage.Checked = false; if (Settings.IcalDefaultImage != "") { ctliCalDefaultImage.Url = Settings.IcalDefaultImage.Substring(6); chkiCalDisplayImage.Checked = true; } if (ctliCalDefaultImage.Url.StartsWith("FileID=")) { var fileId = int.Parse(Convert.ToString(ctliCalDefaultImage.Url.Substring(7))); var objFileInfo = FileManager.Instance.GetFile(fileId); if (!ReferenceEquals(objFileInfo, null)) { ctliCalDefaultImage.Url = objFileInfo.Folder + objFileInfo.FileName; } else { ctliCalDefaultImage.Url = ""; } } var socialGroupId = GetUrlGroupId(); var socialGroupStr = ""; if (socialGroupId > 0) { socialGroupStr = "&groupid=" + socialGroupId; } lbliCalURL.Text = Globals.AddHTTP(PortalSettings.PortalAlias.HTTPAlias + "/DesktopModules/Events/EventVCal.aspx?ItemID=0&Mid=" + Convert.ToString(ModuleId) + "&tabid=" + Convert.ToString(TabId) + socialGroupStr); // Set Up Themes LoadThemes(); txtPayPalURL.Text = Settings.Paypalurl; chkEnableEventNav.Checked = true; if (Settings.DisableEventnav) { chkEnableEventNav.Checked = false; } chkAllowRecurring.Checked = Settings.Allowreoccurring; txtMaxRecurrences.Text = Settings.Maxrecurrences; chkEventNotify.Checked = Settings.Eventnotify; chkDetailPageAllowed.Checked = Settings.DetailPageAllowed; chkEnrollmentPageAllowed.Checked = Settings.EnrollmentPageAllowed; txtEnrollmentPageDefaultURL.Text = Settings.EnrollmentPageDefaultUrl; chkNotifyAnon.Checked = Settings.Notifyanon; chkSendReminderDefault.Checked = Settings.Sendreminderdefault; rblNewEventEmail.Items[0].Selected = true; switch (Settings.Neweventemails) { case "Subscribe": rblNewEventEmail.Items[1].Selected = true; break; case "Role": rblNewEventEmail.Items[2].Selected = true; break; } LoadNewEventEmailRoles(Settings.Neweventemailrole); chkNewPerEventEmail.Checked = Settings.Newpereventemail; ddlDefaultView.Items.Clear(); ddlDefaultView.Items.Add(new ListItem(Localization.GetString("Month", LocalResourceFile), "EventMonth.ascx")); ddlDefaultView.Items.Add(new ListItem(Localization.GetString("Week", LocalResourceFile), "EventWeek.ascx")); ddlDefaultView.Items.Add(new ListItem(Localization.GetString("List", LocalResourceFile), "EventList.ascx")); ddlDefaultView.Items.FindByValue(Settings.DefaultView).Selected = true; chkMonthAllowed.Checked = Settings.MonthAllowed; chkWeekAllowed.Checked = Settings.WeekAllowed; chkListAllowed.Checked = Settings.ListAllowed; chkEnableSearch.Checked = Settings.Eventsearch; chkPreventConflicts.Checked = Settings.Preventconflicts; chkLocationConflict.Checked = Settings.Locationconflict; chkShowEventsAlways.Checked = Settings.ShowEventsAlways; chkTimeInTitle.Checked = Settings.Timeintitle; chkMonthDaySelect.Checked = Settings.Monthdayselect; chkEventSignup.Checked = Settings.Eventsignup; chkEventSignupAllowPaid.Checked = Settings.Eventsignupallowpaid; chkDefaultEnrollView.Checked = Settings.Eventdefaultenrollview; chkHideFullEnroll.Checked = Settings.Eventhidefullenroll; txtMaxNoEnrolees.Text = Settings.Maxnoenrolees.ToString(); txtCancelDays.Text = Settings.Enrolcanceldays.ToString(); chkFridayWeekend.Checked = Settings.Fridayweekend; chkModerateAll.Checked = Settings.Moderateall; chkTZDisplay.Checked = Settings.Tzdisplay; chkListViewUseTime.Checked = Settings.ListViewUseTime; txtPayPalAccount.Text = Settings.Paypalaccount; if (txtPayPalAccount.Text.Length == 0) { txtPayPalAccount.Text = PortalSettings.Email; } txtReminderFrom.Text = Settings.Reminderfrom; if (txtReminderFrom.Text.Length == 0) { txtReminderFrom.Text = PortalSettings.Email; } txtStandardEmail.Text = Settings.StandardEmail; if (txtStandardEmail.Text.Length == 0) { txtStandardEmail.Text = PortalSettings.Email; } BindSubEvents(); BindAvailableEvents(); chkMasterEvent.Checked = Settings.MasterEvent; Enable_Disable_Cals(); chkIconMonthPrio.Checked = Settings.IconMonthPrio; chkIconWeekPrio.Checked = Settings.IconWeekPrio; chkIconListPrio.Checked = Settings.IconListPrio; chkIconMonthRec.Checked = Settings.IconMonthRec; chkIconWeekRec.Checked = Settings.IconMonthRec; chkIconListRec.Checked = Settings.IconListRec; chkIconMonthReminder.Checked = Settings.IconMonthReminder; chkIconWeekReminder.Checked = Settings.IconWeekReminder; chkIconListReminder.Checked = Settings.IconListReminder; chkIconMonthEnroll.Checked = Settings.IconMonthEnroll; chkIconWeekEnroll.Checked = Settings.IconWeekEnroll; chkIconListEnroll.Checked = Settings.IconListEnroll; txtPrivateMessage.Text = Settings.PrivateMessage; var columnNo = 0; for (columnNo = 1; columnNo <= 13; columnNo++) { var columnAcronym = GetListColumnAcronym(columnNo); var columnName = GetListColumnName(columnAcronym); if (Settings.EventsListFields.LastIndexOf(columnAcronym, StringComparison.Ordinal) > -1) { selectedFields.Add(columnName); } else { availableFields.Add(columnName); } } lstAvailable.DataSource = availableFields; lstAvailable.DataBind(); Sort(lstAvailable); lstAssigned.DataSource = selectedFields; lstAssigned.DataBind(); Sort(lstAssigned); if (Settings.EventsListSelectType == rblSelectionTypeDays.Value) { rblSelectionTypeDays.Checked = true; rblSelectionTypeEvents.Checked = false; } else { rblSelectionTypeDays.Checked = false; rblSelectionTypeEvents.Checked = true; } if (Settings.ListViewGrid) { rblListViewGrid.Items[0].Selected = true; } else { rblListViewGrid.Items[1].Selected = true; } chkListViewTable.Checked = Settings.ListViewTable; txtRptColumns.Text = Settings.RptColumns.ToString(); txtRptRows.Text = Settings.RptRows.ToString(); // Do we have to display the EventsList header if (Settings.EventsListShowHeader != "No") { rblShowHeader.Items[0].Selected = true; } else { rblShowHeader.Items[1].Selected = true; } txtDaysBefore.Text = Settings.EventsListBeforeDays.ToString(); txtDaysAfter.Text = Settings.EventsListAfterDays.ToString(); txtNumEvents.Text = Settings.EventsListNumEvents.ToString(); txtEventDays.Text = Settings.EventsListEventDays.ToString(); chkRestrictCategoriesToTimeFrame.Checked = Settings.RestrictCategoriesToTimeFrame; chkRestrictLocationsToTimeFrame.Checked = Settings.RestrictLocationsToTimeFrame; chkCustomField1.Checked = Settings.EventsCustomField1; chkCustomField2.Checked = Settings.EventsCustomField2; ddlPageSize.Items.FindByValue(Convert.ToString(Settings.EventsListPageSize)).Selected = true; ddlListSortedFieldDirection.Items.Clear(); ddlListSortedFieldDirection.Items.Add( new ListItem(Localization.GetString("Asc", LocalResourceFile), "ASC")); ddlListSortedFieldDirection.Items.Add( new ListItem(Localization.GetString("Desc", LocalResourceFile), "DESC")); ddlListSortedFieldDirection.Items.FindByValue(Settings.EventsListSortDirection).Selected = true; ddlListDefaultColumn.Items.Clear(); ddlListDefaultColumn.Items.Add( new ListItem(Localization.GetString("SortEventID", LocalResourceFile), "EventID")); ddlListDefaultColumn.Items.Add( new ListItem(Localization.GetString("SortEventDateBegin", LocalResourceFile), "EventDateBegin")); ddlListDefaultColumn.Items.Add( new ListItem(Localization.GetString("SortEventDateEnd", LocalResourceFile), "EventDateEnd")); ddlListDefaultColumn.Items.Add( new ListItem(Localization.GetString("SortEventName", LocalResourceFile), "EventName")); ddlListDefaultColumn.Items.Add( new ListItem(Localization.GetString("SortDuration", LocalResourceFile), "Duration")); ddlListDefaultColumn.Items.Add( new ListItem(Localization.GetString("SortCategoryName", LocalResourceFile), "CategoryName")); ddlListDefaultColumn.Items.Add( new ListItem(Localization.GetString("SortCustomField1", LocalResourceFile), "CustomField1")); ddlListDefaultColumn.Items.Add( new ListItem(Localization.GetString("SortCustomField2", LocalResourceFile), "CustomField2")); ddlListDefaultColumn.Items.Add( new ListItem(Localization.GetString("SortDescription", LocalResourceFile), "Description")); ddlListDefaultColumn.Items.Add( new ListItem(Localization.GetString("SortLocationName", LocalResourceFile), "LocationName")); ddlListDefaultColumn.Items.FindByValue(Settings.EventsListSortColumn).Selected = true; ddlWeekStart.Items.Clear(); ddlWeekStart.Items.Add(new ListItem(FirstDayOfWeek.Default.ToString(), Convert.ToInt32(FirstDayOfWeek.Default).ToString())); ddlWeekStart.Items.Add(new ListItem(FirstDayOfWeek.Monday.ToString(), Convert.ToInt32(FirstDayOfWeek.Monday).ToString())); ddlWeekStart.Items.Add(new ListItem(FirstDayOfWeek.Tuesday.ToString(), Convert.ToInt32(FirstDayOfWeek.Tuesday).ToString())); ddlWeekStart.Items.Add(new ListItem(FirstDayOfWeek.Wednesday.ToString(), Convert.ToInt32(FirstDayOfWeek.Wednesday).ToString())); ddlWeekStart.Items.Add(new ListItem(FirstDayOfWeek.Thursday.ToString(), Convert.ToInt32(FirstDayOfWeek.Thursday).ToString())); ddlWeekStart.Items.Add(new ListItem(FirstDayOfWeek.Friday.ToString(), Convert.ToInt32(FirstDayOfWeek.Friday).ToString())); ddlWeekStart.Items.Add(new ListItem(FirstDayOfWeek.Saturday.ToString(), Convert.ToInt32(FirstDayOfWeek.Saturday).ToString())); ddlWeekStart.Items.Add(new ListItem(FirstDayOfWeek.Sunday.ToString(), Convert.ToInt32(FirstDayOfWeek.Sunday).ToString())); ddlWeekStart.Items.FindByValue(Convert.ToInt32(Settings.WeekStart).ToString()).Selected = true; if (Settings.EnrollEditFields.LastIndexOf("01", StringComparison.Ordinal) > -1) { rblEnUserEdit.Checked = true; } else if (Settings.EnrollViewFields.LastIndexOf("01", StringComparison.Ordinal) > -1) { rblEnUserView.Checked = true; } else if (Settings.EnrollAnonFields.LastIndexOf("01", StringComparison.Ordinal) > -1) { rblEnUserAnon.Checked = true; } else { rblEnUserNone.Checked = true; } if (Settings.EnrollEditFields.LastIndexOf("02", StringComparison.Ordinal) > -1) { rblEnDispEdit.Checked = true; } else if (Settings.EnrollViewFields.LastIndexOf("02", StringComparison.Ordinal) > -1) { rblEnDispView.Checked = true; } else if (Settings.EnrollAnonFields.LastIndexOf("02", StringComparison.Ordinal) > -1) { rblEnDispAnon.Checked = true; } else { rblEnDispNone.Checked = true; } if (Settings.EnrollEditFields.LastIndexOf("03", StringComparison.Ordinal) > -1) { rblEnEmailEdit.Checked = true; } else if (Settings.EnrollViewFields.LastIndexOf("03", StringComparison.Ordinal) > -1) { rblEnEmailView.Checked = true; } else if (Settings.EnrollAnonFields.LastIndexOf("03", StringComparison.Ordinal) > -1) { rblEnEmailAnon.Checked = true; } else { rblEnEmailNone.Checked = true; } if (Settings.EnrollEditFields.LastIndexOf("04", StringComparison.Ordinal) > -1) { rblEnPhoneEdit.Checked = true; } else if (Settings.EnrollViewFields.LastIndexOf("04", StringComparison.Ordinal) > -1) { rblEnPhoneView.Checked = true; } else if (Settings.EnrollAnonFields.LastIndexOf("04", StringComparison.Ordinal) > -1) { rblEnPhoneAnon.Checked = true; } else { rblEnPhoneNone.Checked = true; } if (Settings.EnrollEditFields.LastIndexOf("05", StringComparison.Ordinal) > -1) { rblEnApproveEdit.Checked = true; } else if (Settings.EnrollViewFields.LastIndexOf("05", StringComparison.Ordinal) > -1) { rblEnApproveView.Checked = true; } else if (Settings.EnrollAnonFields.LastIndexOf("05", StringComparison.Ordinal) > -1) { rblEnApproveAnon.Checked = true; } else { rblEnApproveNone.Checked = true; } if (Settings.EnrollEditFields.LastIndexOf("06", StringComparison.Ordinal) > -1) { rblEnNoEdit.Checked = true; } else if (Settings.EnrollViewFields.LastIndexOf("06", StringComparison.Ordinal) > -1) { rblEnNoView.Checked = true; } else if (Settings.EnrollAnonFields.LastIndexOf("06", StringComparison.Ordinal) > -1) { rblEnNoAnon.Checked = true; } else { rblEnNoNone.Checked = true; } chkRSSEnable.Checked = Settings.RSSEnable; ddlRSSDateField.Items.Clear(); ddlRSSDateField.Items.Add(new ListItem(Localization.GetString("UpdatedDate", LocalResourceFile), "UPDATEDDATE")); ddlRSSDateField.Items.Add(new ListItem(Localization.GetString("CreationDate", LocalResourceFile), "CREATIONDATE")); ddlRSSDateField.Items.Add(new ListItem(Localization.GetString("EventDate", LocalResourceFile), "EVENTDATE")); ddlRSSDateField.Items.FindByValue(Settings.RSSDateField).Selected = true; txtRSSDays.Text = Settings.RSSDays.ToString(); txtRSSTitle.Text = Settings.RSSTitle; txtRSSDesc.Text = Settings.RSSDesc; txtExpireEvents.Text = Settings.Expireevents; chkExportOwnerEmail.Checked = Settings.Exportowneremail; chkExportAnonOwnerEmail.Checked = Settings.Exportanonowneremail; chkOwnerChangeAllowed.Checked = Settings.Ownerchangeallowed; txtFBAdmins.Text = Settings.FBAdmins; txtFBAppID.Text = Settings.FBAppID; switch (Settings.IconBar) { case "BOTTOM": rblIconBar.Items[1].Selected = true; break; case "NONE": rblIconBar.Items[2].Selected = true; break; default: rblIconBar.Items[0].Selected = true; break; } switch (Settings.HTMLEmail) { case "auto": rblHTMLEmail.Items[1].Selected = true; break; case "text": rblHTMLEmail.Items[2].Selected = true; break; default: rblHTMLEmail.Items[0].Selected = true; break; } chkEnrollMessageApproved.Checked = Settings.SendEnrollMessageApproved; chkEnrollMessageWaiting.Checked = Settings.SendEnrollMessageWaiting; chkEnrollMessageDenied.Checked = Settings.SendEnrollMessageDenied; chkEnrollMessageAdded.Checked = Settings.SendEnrollMessageAdded; chkEnrollMessageDeleted.Checked = Settings.SendEnrollMessageDeleted; chkEnrollMessagePaying.Checked = Settings.SendEnrollMessagePaying; chkEnrollMessagePending.Checked = Settings.SendEnrollMessagePending; chkEnrollMessagePaid.Checked = Settings.SendEnrollMessagePaid; chkEnrollMessageIncorrect.Checked = Settings.SendEnrollMessageIncorrect; chkEnrollMessageCancelled.Checked = Settings.SendEnrollMessageCancelled; chkAllowAnonEnroll.Checked = Settings.AllowAnonEnroll; BindToEnum(typeof(EventModuleSettings.SocialModule), ddlSocialGroupModule); ddlSocialGroupModule.Items.FindByValue(Convert.ToString((int) Settings.SocialGroupModule)) .Selected = true; chkSocialUserPrivate.Checked = Settings.SocialUserPrivate; BindToEnum(typeof(EventModuleSettings.SocialGroupPrivacy), ddlSocialGroupSecurity); ddlSocialGroupSecurity.Items.FindByValue(Convert.ToString((int) Settings.SocialGroupSecurity)) .Selected = true; ddlEnrolListSortDirection.Items.Clear(); ddlEnrolListSortDirection.Items.Add( new ListItem(Localization.GetString("Asc", LocalResourceFile), "0")); ddlEnrolListSortDirection.Items.Add( new ListItem(Localization.GetString("Desc", LocalResourceFile), "1")); ddlEnrolListSortDirection.Items .FindByValue(Convert.ToInt32(Settings.EnrolListSortDirection).ToString()).Selected = true; txtEnrolListDaysBefore.Text = Settings.EnrolListDaysBefore.ToString(); txtEnrolListDaysAfter.Text = Settings.EnrolListDaysAfter.ToString(); chkJournalIntegration.Checked = Settings.JournalIntegration; LoadCategories(); LoadLocations(); LoadTemplates(); } private void AddJavaScript() { //Add the external Validation.js to the Page const string csname = "ExtValidationScriptFile"; var cstype = MethodBase.GetCurrentMethod().GetType(); var cstext = "<script src=\"" + ResolveUrl("~/DesktopModules/Events/Scripts/Validation.js") + "\" type=\"text/javascript\"></script>"; if (!Page.ClientScript.IsClientScriptBlockRegistered(csname)) { Page.ClientScript.RegisterClientScriptBlock(cstype, csname, cstext, false); } // Add javascript actions where required and build startup script var script = ""; var cstext2 = ""; cstext2 += "<script type=\"text/javascript\">"; cstext2 += "EventSettingsStartupScript = function() {"; script = "disableactivate('" + ddlDefaultView.ClientID + "','" + chkMonthAllowed.ClientID + "','" + chkWeekAllowed.ClientID + "','" + chkListAllowed.ClientID + "');"; cstext2 += script; ddlDefaultView.Attributes.Add("onchange", script); script = "disableControl('" + chkPreventConflicts.ClientID + "',false, '" + chkLocationConflict.ClientID + "');"; cstext2 += script; chkPreventConflicts.InputAttributes.Add("onclick", script); script = "disableControl('" + chkMonthCellEvents.ClientID + "',true, '" + chkEventDayNewPage.ClientID + "');"; script += "disableControl('" + chkMonthCellEvents.ClientID + "',false, '" + chkMonthDaySelect.ClientID + "');"; script += "disableControl('" + chkMonthCellEvents.ClientID + "',false, '" + chkTimeInTitle.ClientID + "');"; script += "disableControl('" + chkMonthCellEvents.ClientID + "',false, '" + chkEventImageMonth.ClientID + "');"; script += "disableControl('" + chkMonthCellEvents.ClientID + "',false, '" + chkIconMonthPrio.ClientID + "');"; script += "disableControl('" + chkMonthCellEvents.ClientID + "',false, '" + chkIconMonthRec.ClientID + "');"; script += "disableControl('" + chkMonthCellEvents.ClientID + "',false, '" + chkIconMonthReminder.ClientID + "');"; script += "disableControl('" + chkMonthCellEvents.ClientID + "',false, '" + chkIconMonthEnroll.ClientID + "');"; cstext2 += script; chkMonthCellEvents.InputAttributes.Add("onclick", script); script = "disableRbl('" + rblListViewGrid.ClientID + "', 'Repeater', '" + chkListViewTable.ClientID + "');"; script += "disableRbl('" + rblListViewGrid.ClientID + "', 'Repeater', '" + txtRptColumns.ClientID + "');"; script += "disableRbl('" + rblListViewGrid.ClientID + "', 'Repeater', '" + txtRptRows.ClientID + "');"; script += "disableRbl('" + rblListViewGrid.ClientID + "', 'Grid', '" + rblShowHeader.ClientID + "');"; script += "disableRbl('" + rblListViewGrid.ClientID + "', 'Grid', '" + lstAvailable.ClientID + "');"; script += "disableRbl('" + rblListViewGrid.ClientID + "', 'Grid', '" + cmdAdd.ClientID + "');"; script += "disableRbl('" + rblListViewGrid.ClientID + "', 'Grid', '" + cmdRemove.ClientID + "');"; script += "disableRbl('" + rblListViewGrid.ClientID + "', 'Grid', '" + cmdAddAll.ClientID + "');"; script += "disableRbl('" + rblListViewGrid.ClientID + "', 'Grid', '" + cmdRemoveAll.ClientID + "');"; script += "disableRbl('" + rblListViewGrid.ClientID + "', 'Grid', '" + lstAssigned.ClientID + "');"; script += "disableRbl('" + rblListViewGrid.ClientID + "', 'Grid', '" + ddlPageSize.ClientID + "');"; script += "disableRbl('" + rblListViewGrid.ClientID + "', 'Grid', '" + chkIconListEnroll.ClientID + "');"; script += "disableRbl('" + rblListViewGrid.ClientID + "', 'Grid', '" + chkIconListPrio.ClientID + "');"; script += "disableRbl('" + rblListViewGrid.ClientID + "', 'Grid', '" + chkIconListRec.ClientID + "');"; script += "disableRbl('" + rblListViewGrid.ClientID + "', 'Grid', '" + chkIconListReminder.ClientID + "');"; cstext2 += script; rblListViewGrid.Attributes.Add("onclick", script); script = "CheckBoxFalse('" + chkIncludeEndValue.ClientID + "', true, '" + chkShowValueMarks.ClientID + "');"; cstext2 += script; chkIncludeEndValue.InputAttributes.Add("onclick", script); script = "disablelistsettings('" + rblSelectionTypeDays.ClientID + "',true,'" + txtDaysBefore.ClientID + "','" + txtDaysAfter.ClientID + "','" + txtNumEvents.ClientID + "','" + txtEventDays.ClientID + "');"; cstext2 += script; rblSelectionTypeDays.Attributes.Add("onclick", script); script = "disablelistsettings('" + rblSelectionTypeEvents.ClientID + "',false,'" + txtDaysBefore.ClientID + "','" + txtDaysAfter.ClientID + "','" + txtNumEvents.ClientID + "','" + txtEventDays.ClientID + "');"; cstext2 += script; rblSelectionTypeEvents.Attributes.Add("onclick", script); script = "showTbl('" + chkEventNotify.ClientID + "','" + divEventNotify.ClientID + "');"; cstext2 += script; chkEventNotify.InputAttributes.Add("onclick", script); script = "showTbl('" + chkRSSEnable.ClientID + "','" + divRSSEnable.ClientID + "');"; cstext2 += script; chkRSSEnable.InputAttributes.Add("onclick", script); script = "showTbl('" + chkImageEnabled.ClientID + "','" + diviCalEventImage.ClientID + "'); showTbl('" + chkImageEnabled.ClientID + "','" + divImageEnabled.ClientID + "');"; cstext2 += script; chkImageEnabled.InputAttributes.Add("onclick", script); script = "showTbl('" + chkiCalDisplayImage.ClientID + "','" + diviCalDisplayImage.ClientID + "');"; cstext2 += script; chkiCalDisplayImage.InputAttributes.Add("onclick", script); script = "disableControl('" + chkExportOwnerEmail.ClientID + "',false, '" + chkExportAnonOwnerEmail.ClientID + "');"; cstext2 += script; chkExportOwnerEmail.InputAttributes.Add("onclick", script); script = "disableDDL('" + ddlSocialGroupModule.ClientID + "','" + Convert.ToInt32(EventModuleSettings.SocialModule.UserProfile) + "','" + chkSocialUserPrivate.ClientID + "');"; cstext2 += script; ddlSocialGroupModule.Attributes.Add("onclick", script); if (Settings.SocialGroupModule == EventModuleSettings.SocialModule.No) { script = "disableRbl('" + rblNewEventEmail.ClientID + "', 'Role', '" + ddNewEventEmailRoles.ClientID + "');"; cstext2 += script; rblNewEventEmail.Attributes.Add("onclick", script); } if (Settings.SocialGroupModule != EventModuleSettings.SocialModule.UserProfile) { script = "showTbl('" + chkEventSignup.ClientID + "','" + divEventSignup.ClientID + "');"; cstext2 += script; chkEventSignup.InputAttributes.Add("onclick", script); script = "showTbl('" + chkEventSignupAllowPaid.ClientID + "','" + divEventSignupAllowPaid.ClientID + "');"; cstext2 += script; chkEventSignupAllowPaid.InputAttributes.Add("onclick", script); script = "showTbl('" + chkEnableSEO.ClientID + "','" + divSEOEnable.ClientID + "');"; cstext2 += script; chkEnableSEO.InputAttributes.Add("onclick", script); script = "showTbl('" + chkEnableSitemap.ClientID + "','" + divSitemapEnable.ClientID + "');"; cstext2 += script; chkEnableSitemap.InputAttributes.Add("onclick", script); } cstext2 += "};"; cstext2 += "EventSettingsStartupScript();"; cstext2 += "Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EventEndRequestHandler);"; cstext2 += "function EventEndRequestHandler(sender, args) { EventSettingsStartupScript(); }"; cstext2 += "</script>"; // Register the startup script const string csname2 = "EventSettingsStartupScript"; var cstype2 = MethodBase.GetCurrentMethod().GetType(); if (!Page.ClientScript.IsStartupScriptRegistered(csname2)) { Page.ClientScript.RegisterStartupScript(cstype2, csname2, cstext2, false); } } private void BindToEnum(Type enumType, DropDownList ddl) { // get the names from the enumeration var names = Enum.GetNames(enumType); // get the values from the enumeration var values = Enum.GetValues(enumType); // turn it into a hash table ddl.Items.Clear(); for (var i = 0; i <= names.Length - 1; i++) { // note the cast to integer here is important // otherwise we'll just get the enum string back again ddl.Items.Add(new ListItem(Localization.GetString(names[i], LocalResourceFile), Convert.ToString(Convert.ToInt32(values.GetValue(i))))); } // return the dictionary to be bound to } private string GetListColumnName(string columnAcronym) { switch (columnAcronym) { case "EB": return "01 - " + Localization.GetString("EditButton", LocalResourceFile); case "BD": return "02 - " + Localization.GetString("BeginDateTime", LocalResourceFile); case "ED": return "03 - " + Localization.GetString("EndDateTime", LocalResourceFile); case "EN": return "04 - " + Localization.GetString("EventName", LocalResourceFile); case "IM": return "05 - " + Localization.GetString("Image", LocalResourceFile); case "DU": return "06 - " + Localization.GetString("Duration", LocalResourceFile); case "CA": return "07 - " + Localization.GetString("Category", LocalResourceFile); case "LO": return "08 - " + Localization.GetString("Location", LocalResourceFile); case "C1": return "09 - " + Localization.GetString("CustomField1", LocalResourceFile); case "C2": return "10 - " + Localization.GetString("CustomField2", LocalResourceFile); case "DE": return "11 - " + Localization.GetString("Description", LocalResourceFile); case "RT": return "12 - " + Localization.GetString("RecurText", LocalResourceFile); case "RU": return "13 - " + Localization.GetString("RecurUntil", LocalResourceFile); default: return ""; } } private string GetListColumnAcronym(int columnNo) { switch (columnNo) { case 1: return "EB"; case 2: return "BD"; case 3: return "ED"; case 4: return "EN"; case 5: return "IM"; case 6: return "DU"; case 7: return "CA"; case 8: return "LO"; case 9: return "C1"; case 10: return "C2"; case 11: return "DE"; case 12: return "RT"; case 13: return "RU"; default: return ""; } } /// <summary> /// Fill the themelist based on selection for default or custom skins /// </summary> /// <remarks></remarks> private void LoadThemes() { try { const string moduleThemesDirectoryPath = "/DesktopModules/Events/Themes"; //Clear list ddlThemeStandard.Items.Clear(); ddlThemeCustom.Items.Clear(); //Add javascript to enable/disable ddl's rbThemeCustom.Attributes.Add( "onclick", string.Format("{0}.disabled='disabled';{1}.disabled=''", ddlThemeStandard.ClientID, ddlThemeCustom.ClientID)); rbThemeStandard.Attributes.Add( "onclick", string.Format("{0}.disabled='disabled';{1}.disabled=''", ddlThemeCustom.ClientID, ddlThemeStandard.ClientID)); //Get the settings var themeSettings = new ThemeSetting(); if (themeSettings.ValidateSetting(Settings.EventTheme) == false) { themeSettings.ReadSetting(Settings.EventThemeDefault, PortalId); } else if (Settings.EventTheme != "") { themeSettings.ReadSetting(Settings.EventTheme, PortalId); } switch (themeSettings.SettingType) { case ThemeSetting.ThemeSettingTypeEnum.CustomTheme: rbThemeCustom.Checked = true; break; case ThemeSetting.ThemeSettingTypeEnum.DefaultTheme: rbThemeStandard.Checked = true; break; } //Is default or custom selected var moduleThemesDirectory = Globals.ApplicationPath + moduleThemesDirectoryPath; var serverThemesDirectory = Server.MapPath(moduleThemesDirectory); var themeDirectories = Directory.GetDirectories(serverThemesDirectory); var themeDirectory = ""; foreach (var tempLoopVar_themeDirectory in themeDirectories) { themeDirectory = tempLoopVar_themeDirectory; var dirparts = themeDirectory.Split('\\'); ddlThemeStandard.Items.Add( new ListItem(dirparts[dirparts.Length - 1], dirparts[dirparts.Length - 1])); } if (themeSettings.SettingType == ThemeSetting.ThemeSettingTypeEnum.DefaultTheme) { if (!ReferenceEquals(ddlThemeStandard.Items.FindByText(themeSettings.ThemeName), null)) { ddlThemeStandard.Items.FindByText(themeSettings.ThemeName).Selected = true; } } else { ddlThemeStandard.Attributes.Add("disabled", "disabled"); } //Add custom event theme's var pc = new PortalController(); var with_1 = pc.GetPortal(PortalId); var eventSkinPath = string.Format("{0}\\DNNEvents\\Themes", with_1.HomeDirectoryMapPath); if (!Directory.Exists(eventSkinPath)) { Directory.CreateDirectory(eventSkinPath); } foreach (var d in Directory.GetDirectories(eventSkinPath)) { ddlThemeCustom.Items.Add(new ListItem(new DirectoryInfo(d).Name, new DirectoryInfo(d).Name)); } if (ddlThemeCustom.Items.Count == 0) { rbThemeCustom.Enabled = false; } if (themeSettings.SettingType == ThemeSetting.ThemeSettingTypeEnum.CustomTheme) { if (!ReferenceEquals(ddlThemeCustom.Items.FindByText(themeSettings.ThemeName), null)) { ddlThemeCustom.Items.FindByText(themeSettings.ThemeName).Selected = true; } } else { ddlThemeCustom.Attributes.Add("disabled", "disabled"); } } catch (Exception ex) { Debug.Write(ex.ToString()); } } private void LoadTemplates() { ddlTemplates.Items.Clear(); var t = Settings.Templates.GetType(); var p = default(PropertyInfo); foreach (var tempLoopVar_p in t.GetProperties()) { p = tempLoopVar_p; ddlTemplates.Items.Add( new ListItem(Localization.GetString(p.Name + "Name", LocalResourceFile), p.Name)); } ddlTemplates.Items.FindByValue("EventDetailsTemplate").Selected = true; txtEventTemplate.Text = Settings.Templates.GetTemplate(ddlTemplates.SelectedValue); lblTemplateUpdated.Visible = false; } private void LoadNewEventEmailRoles(int roleID) { var objRoles = new RoleController(); ddNewEventEmailRoles.DataSource = objRoles.GetPortalRoles(PortalId); ddNewEventEmailRoles.DataTextField = "RoleName"; ddNewEventEmailRoles.DataValueField = "RoleID"; ddNewEventEmailRoles.DataBind(); if (roleID < 0 || ReferenceEquals(ddNewEventEmailRoles.Items.FindByValue(Convert.ToString(roleID)), null)) { try { ddNewEventEmailRoles.Items.FindByValue(PortalSettings.RegisteredRoleId.ToString()) .Selected = true; } catch { } } else { ddNewEventEmailRoles.Items.FindByValue(Convert.ToString(roleID)).Selected = true; } } private void LoadCategories() { ddlModuleCategories.Items.Clear(); var ctrlEventCategories = new EventCategoryController(); var lstCategories = ctrlEventCategories.EventsCategoryList(PortalId); ddlModuleCategories.DataSource = lstCategories; ddlModuleCategories.DataBind(); if (Settings.ModuleCategoriesSelected == EventModuleSettings.CategoriesSelected.Some) { foreach (string moduleCategory in Settings.ModuleCategoryIDs) { foreach (RadComboBoxItem item in ddlModuleCategories.Items) { if (item.Value == moduleCategory) { item.Checked = true; } } } } else if (Settings.ModuleCategoriesSelected == EventModuleSettings.CategoriesSelected.All) { foreach (RadComboBoxItem item in ddlModuleCategories.Items) { item.Checked = true; } } } private void LoadLocations() { ddlModuleLocations.Items.Clear(); var ctrlEventLocations = new EventLocationController(); var lstLocations = ctrlEventLocations.EventsLocationList(PortalId); ddlModuleLocations.DataSource = lstLocations; ddlModuleLocations.DataBind(); if (Settings.ModuleLocationsSelected == EventModuleSettings.LocationsSelected.Some) { foreach (string moduleLocation in Settings.ModuleLocationIDs) { foreach (RadComboBoxItem item in ddlModuleLocations.Items) { if (item.Value == moduleLocation) { item.Checked = true; } } } } else if (Settings.ModuleLocationsSelected == EventModuleSettings.LocationsSelected.All) { foreach (RadComboBoxItem item in ddlModuleLocations.Items) { item.Checked = true; } } } /// <summary> /// Take all settings and write them back to the database /// </summary> /// <remarks></remarks> private void UpdateSettings() { var repository = new EventModuleSettingsRepository(); var emSettings = repository.GetSettings(ModuleConfiguration); emSettings.Timeinterval = ddlTimeInterval.SelectedValue.Trim(); emSettings.TimeZoneId = cboTimeZone.SelectedValue; emSettings.EnableEventTimeZones = chkEnableEventTimeZones.Checked; emSettings.PrimaryTimeZone = (EventModuleSettings.TimeZones) int.Parse(ddlPrimaryTimeZone.SelectedValue); try { emSettings.Timeinterval = ddlTimeInterval.SelectedValue.Trim(); emSettings.TimeZoneId = cboTimeZone.SelectedValue; emSettings.EnableEventTimeZones = chkEnableEventTimeZones.Checked; emSettings.PrimaryTimeZone = (EventModuleSettings.TimeZones) int.Parse(ddlPrimaryTimeZone.SelectedValue); emSettings.SecondaryTimeZone = (EventModuleSettings.TimeZones) int.Parse(ddlSecondaryTimeZone.SelectedValue); emSettings.Eventtooltipmonth = chkToolTipMonth.Checked; emSettings.Eventtooltipweek = chkToolTipWeek.Checked; emSettings.Eventtooltipday = chkToolTipDay.Checked; emSettings.Eventtooltiplist = chkToolTipList.Checked; emSettings.Eventtooltiplength = int.Parse(txtTooltipLength.Text); if (chkMonthCellEvents.Checked) { emSettings.Monthcellnoevents = false; } else { emSettings.Monthcellnoevents = true; } emSettings.Enablecategories = (EventModuleSettings.DisplayCategories) int.Parse(ddlEnableCategories.SelectedValue); emSettings.Restrictcategories = chkRestrictCategories.Checked; emSettings.Enablelocations = (EventModuleSettings.DisplayLocations) int.Parse(ddlEnableLocations.SelectedValue); emSettings.Restrictlocations = chkRestrictLocations.Checked; emSettings.Enablecontainerskin = chkEnableContainerSkin.Checked; emSettings.Eventdetailnewpage = chkEventDetailNewPage.Checked; emSettings.Enableenrollpopup = chkEnableEnrollPopup.Checked; emSettings.Eventdaynewpage = chkEventDayNewPage.Checked; emSettings.EventImageMonth = chkEventImageMonth.Checked; emSettings.EventImageWeek = chkEventImageWeek.Checked; emSettings.Eventnotify = chkEventNotify.Checked; emSettings.DetailPageAllowed = chkDetailPageAllowed.Checked; emSettings.EnrollmentPageAllowed = chkEnrollmentPageAllowed.Checked; emSettings.EnrollmentPageDefaultUrl = txtEnrollmentPageDefaultURL.Text; emSettings.Notifyanon = chkNotifyAnon.Checked; emSettings.Sendreminderdefault = chkSendReminderDefault.Checked; emSettings.Neweventemails = rblNewEventEmail.SelectedValue; emSettings.Neweventemailrole = int.Parse(ddNewEventEmailRoles.SelectedValue); emSettings.Newpereventemail = chkNewPerEventEmail.Checked; emSettings.Tzdisplay = chkTZDisplay.Checked; emSettings.Paypalurl = txtPayPalURL.Text; if (chkEnableEventNav.Checked) { emSettings.DisableEventnav = false; } else { emSettings.DisableEventnav = true; } emSettings.Fulltimescale = chkFullTimeScale.Checked; emSettings.Collapserecurring = chkCollapseRecurring.Checked; emSettings.Includeendvalue = chkIncludeEndValue.Checked; emSettings.Showvaluemarks = chkShowValueMarks.Checked; emSettings.Eventimage = chkImageEnabled.Checked; emSettings.MaxThumbHeight = int.Parse(txtMaxThumbHeight.Text); emSettings.MaxThumbWidth = int.Parse(txtMaxThumbWidth.Text); emSettings.Allowreoccurring = chkAllowRecurring.Checked; emSettings.Maxrecurrences = txtMaxRecurrences.Text; emSettings.Eventsearch = chkEnableSearch.Checked; emSettings.Addsubmodulename = chkAddSubModuleName.Checked; emSettings.Enforcesubcalperms = chkEnforceSubCalPerms.Checked; emSettings.Preventconflicts = chkPreventConflicts.Checked; emSettings.Locationconflict = chkLocationConflict.Checked; emSettings.ShowEventsAlways = chkShowEventsAlways.Checked; emSettings.Timeintitle = chkTimeInTitle.Checked; emSettings.Monthdayselect = chkMonthDaySelect.Checked; emSettings.MasterEvent = chkMasterEvent.Checked; emSettings.Eventsignup = chkEventSignup.Checked; emSettings.Eventsignupallowpaid = chkEventSignupAllowPaid.Checked; emSettings.Eventdefaultenrollview = chkDefaultEnrollView.Checked; emSettings.Eventhidefullenroll = chkHideFullEnroll.Checked; emSettings.Maxnoenrolees = int.Parse(txtMaxNoEnrolees.Text); emSettings.Enrolcanceldays = int.Parse(txtCancelDays.Text); emSettings.Fridayweekend = chkFridayWeekend.Checked; emSettings.Moderateall = chkModerateAll.Checked; emSettings.Paypalaccount = txtPayPalAccount.Text; emSettings.Reminderfrom = txtReminderFrom.Text; emSettings.StandardEmail = txtStandardEmail.Text; emSettings.EventsCustomField1 = chkCustomField1.Checked; emSettings.EventsCustomField2 = chkCustomField2.Checked; emSettings.DefaultView = ddlDefaultView.SelectedItem.Value; emSettings.EventsListPageSize = int.Parse(ddlPageSize.SelectedItem.Value); emSettings.EventsListSortDirection = ddlListSortedFieldDirection.SelectedItem.Value; emSettings.EventsListSortColumn = ddlListDefaultColumn.SelectedItem.Value; emSettings.RSSEnable = chkRSSEnable.Checked; emSettings.RSSDateField = ddlRSSDateField.SelectedItem.Value; emSettings.RSSDays = int.Parse(txtRSSDays.Text); emSettings.RSSTitle = txtRSSTitle.Text; emSettings.RSSDesc = txtRSSDesc.Text; emSettings.Expireevents = txtExpireEvents.Text; emSettings.Exportowneremail = chkExportOwnerEmail.Checked; emSettings.Exportanonowneremail = chkExportAnonOwnerEmail.Checked; emSettings.Ownerchangeallowed = chkOwnerChangeAllowed.Checked; emSettings.IconMonthPrio = chkIconMonthPrio.Checked; emSettings.IconMonthRec = chkIconMonthRec.Checked; emSettings.IconMonthReminder = chkIconMonthReminder.Checked; emSettings.IconMonthEnroll = chkIconMonthEnroll.Checked; emSettings.IconWeekPrio = chkIconWeekPrio.Checked; emSettings.IconWeekRec = chkIconWeekRec.Checked; emSettings.IconWeekReminder = chkIconWeekReminder.Checked; emSettings.IconWeekEnroll = chkIconWeekEnroll.Checked; emSettings.IconListPrio = chkIconListPrio.Checked; emSettings.IconListRec = chkIconListRec.Checked; emSettings.IconListReminder = chkIconListReminder.Checked; emSettings.IconListEnroll = chkIconListEnroll.Checked; emSettings.PrivateMessage = txtPrivateMessage.Text.Trim(); emSettings.EnableSEO = chkEnableSEO.Checked; emSettings.SEODescriptionLength = int.Parse(txtSEODescriptionLength.Text); emSettings.EnableSitemap = chkEnableSitemap.Checked; emSettings.SiteMapPriority = Convert.ToSingle(Convert.ToSingle(txtSitemapPriority.Text)); emSettings.SiteMapDaysBefore = int.Parse(txtSitemapDaysBefore.Text); emSettings.SiteMapDaysAfter = int.Parse(txtSitemapDaysAfter.Text); emSettings.WeekStart = (FirstDayOfWeek) int.Parse(ddlWeekStart.SelectedValue); emSettings.ListViewUseTime = chkListViewUseTime.Checked; emSettings.IcalOnIconBar = chkiCalOnIconBar.Checked; emSettings.IcalEmailEnable = chkiCalEmailEnable.Checked; emSettings.IcalURLInLocation = chkiCalURLinLocation.Checked; emSettings.IcalIncludeCalname = chkiCalIncludeCalname.Checked; emSettings.IcalDaysBefore = int.Parse(txtiCalDaysBefore.Text); emSettings.IcalDaysAfter = int.Parse(txtiCalDaysAfter.Text); emSettings.IcalURLAppend = txtiCalURLAppend.Text; if (chkiCalDisplayImage.Checked) { emSettings.IcalDefaultImage = "Image=" + ctliCalDefaultImage.Url; } else { emSettings.IcalDefaultImage = ""; } //objModules.UpdateModuleSetting(ModuleId, "EventDetailsTemplate", txtEventDetailsTemplate.Text.Trim) var moduleCategories = new ArrayList(); if (ddlModuleCategories.CheckedItems.Count != ddlModuleCategories.Items.Count) { foreach (var item in ddlModuleCategories.CheckedItems) { moduleCategories.Add(item.Value); } } else { moduleCategories.Add("-1"); } emSettings.ModuleCategoryIDs = moduleCategories; var moduleLocations = new ArrayList(); if (ddlModuleLocations.CheckedItems.Count != ddlModuleLocations.Items.Count) { foreach (var item in ddlModuleLocations.CheckedItems) { moduleLocations.Add(item.Value); } } else { moduleLocations.Add("-1"); } emSettings.ModuleLocationIDs = moduleLocations; // ReSharper disable LocalizableElement if (chkMonthAllowed.Checked || ddlDefaultView.SelectedItem.Value == "EventMonth.ascx") { emSettings.MonthAllowed = true; } else { emSettings.MonthAllowed = false; } if (chkWeekAllowed.Checked || ddlDefaultView.SelectedItem.Value == "EventWeek.ascx") { emSettings.WeekAllowed = true; } else { emSettings.WeekAllowed = false; } if (chkListAllowed.Checked || ddlDefaultView.SelectedItem.Value == "EventList.ascx") { emSettings.ListAllowed = true; } else { emSettings.ListAllowed = false; } // ReSharper restore LocalizableElement switch (rblIconBar.SelectedIndex) { case 0: emSettings.IconBar = "TOP"; break; case 1: emSettings.IconBar = "BOTTOM"; break; case 2: emSettings.IconBar = "NONE"; break; } switch (rblHTMLEmail.SelectedIndex) { case 0: emSettings.HTMLEmail = "html"; break; case 1: emSettings.HTMLEmail = "auto"; break; case 2: emSettings.HTMLEmail = "text"; break; } //EPT: Be sure we start next display time in the correct view // Update the cookie so the appropriate view is shown when settings page is exited var objCookie = new HttpCookie("DNNEvents" + Convert.ToString(ModuleId)); objCookie.Value = ddlDefaultView.SelectedItem.Value; if (ReferenceEquals(Request.Cookies.Get("DNNEvents" + Convert.ToString(ModuleId)), null)) { Response.Cookies.Add(objCookie); } else { Response.Cookies.Set(objCookie); } //Set eventtheme data var themeSettings = new ThemeSetting(); if (rbThemeStandard.Checked) { themeSettings.SettingType = ThemeSetting.ThemeSettingTypeEnum.DefaultTheme; themeSettings.ThemeName = ddlThemeStandard.SelectedItem.Text; themeSettings.ThemeFile = ""; } else if (rbThemeCustom.Checked) { themeSettings.SettingType = ThemeSetting.ThemeSettingTypeEnum.CustomTheme; themeSettings.ThemeName = ddlThemeCustom.SelectedItem.Text; themeSettings.ThemeFile = ""; } emSettings.EventTheme = themeSettings.ToString(); //List Events Mode Stuff //Update Fields to Display var objListItem = default(ListItem); var listFields = ""; foreach (ListItem tempLoopVar_objListItem in lstAssigned.Items) { objListItem = tempLoopVar_objListItem; var columnNo = int.Parse(objListItem.Text.Substring(0, 2)); var columnAcronym = GetListColumnAcronym(columnNo); if (listFields.Length > 0) { listFields = listFields + ";" + columnAcronym; } else { listFields = columnAcronym; } } emSettings.EventsListFields = listFields; listFields = EnrollListFields(rblEnUserAnon.Checked, rblEnDispAnon.Checked, rblEnEmailAnon.Checked, rblEnPhoneAnon.Checked, rblEnApproveAnon.Checked, rblEnNoAnon.Checked); emSettings.EnrollAnonFields = listFields; listFields = EnrollListFields(rblEnUserView.Checked, rblEnDispView.Checked, rblEnEmailView.Checked, rblEnPhoneView.Checked, rblEnApproveView.Checked, rblEnNoView.Checked); emSettings.EnrollViewFields = listFields; listFields = EnrollListFields(rblEnUserEdit.Checked, rblEnDispEdit.Checked, rblEnEmailEdit.Checked, rblEnPhoneEdit.Checked, rblEnApproveEdit.Checked, rblEnNoEdit.Checked); emSettings.EnrollEditFields = listFields; if (rblSelectionTypeDays.Checked) { emSettings.EventsListSelectType = rblSelectionTypeDays.Value; } else { emSettings.EventsListSelectType = rblSelectionTypeEvents.Value; } if (rblListViewGrid.Items[0].Selected) { emSettings.ListViewGrid = true; } else { emSettings.ListViewGrid = false; } emSettings.ListViewTable = chkListViewTable.Checked; emSettings.RptColumns = int.Parse(txtRptColumns.Text.Trim()); emSettings.RptRows = int.Parse(txtRptRows.Text.Trim()); if (rblShowHeader.Items[0].Selected) { emSettings.EventsListShowHeader = rblShowHeader.Items[0].Value; } else { emSettings.EventsListShowHeader = rblShowHeader.Items[1].Value; } emSettings.EventsListBeforeDays = int.Parse(txtDaysBefore.Text.Trim()); emSettings.EventsListAfterDays = int.Parse(txtDaysAfter.Text.Trim()); emSettings.EventsListNumEvents = int.Parse(txtNumEvents.Text.Trim()); emSettings.EventsListEventDays = int.Parse(txtEventDays.Text.Trim()); emSettings.RestrictCategoriesToTimeFrame = chkRestrictCategoriesToTimeFrame.Checked; emSettings.RestrictLocationsToTimeFrame = chkRestrictLocationsToTimeFrame.Checked; emSettings.FBAdmins = txtFBAdmins.Text; emSettings.FBAppID = txtFBAppID.Text; emSettings.SendEnrollMessageApproved = chkEnrollMessageApproved.Checked; emSettings.SendEnrollMessageWaiting = chkEnrollMessageWaiting.Checked; emSettings.SendEnrollMessageDenied = chkEnrollMessageDenied.Checked; emSettings.SendEnrollMessageAdded = chkEnrollMessageAdded.Checked; emSettings.SendEnrollMessageDeleted = chkEnrollMessageDeleted.Checked; emSettings.SendEnrollMessagePaying = chkEnrollMessagePaying.Checked; emSettings.SendEnrollMessagePending = chkEnrollMessagePending.Checked; emSettings.SendEnrollMessagePaid = chkEnrollMessagePaid.Checked; emSettings.SendEnrollMessageIncorrect = chkEnrollMessageIncorrect.Checked; emSettings.SendEnrollMessageCancelled = chkEnrollMessageCancelled.Checked; emSettings.AllowAnonEnroll = chkAllowAnonEnroll.Checked; emSettings.SocialGroupModule = (EventModuleSettings.SocialModule) int.Parse(ddlSocialGroupModule.SelectedValue); if (emSettings.SocialGroupModule != EventModuleSettings.SocialModule.No) { emSettings.Ownerchangeallowed = false; emSettings.Neweventemails = "Never"; emSettings.MasterEvent = false; } if (emSettings.SocialGroupModule == EventModuleSettings.SocialModule.UserProfile) { emSettings.EnableSitemap = false; emSettings.Eventsearch = false; emSettings.Eventsignup = false; emSettings.Moderateall = false; } emSettings.SocialUserPrivate = chkSocialUserPrivate.Checked; emSettings.SocialGroupSecurity = (EventModuleSettings.SocialGroupPrivacy) int.Parse(ddlSocialGroupSecurity.SelectedValue); emSettings.EnrolListSortDirection = (SortDirection) int.Parse(ddlEnrolListSortDirection.SelectedValue); emSettings.EnrolListDaysBefore = int.Parse(txtEnrolListDaysBefore.Text); emSettings.EnrolListDaysAfter = int.Parse(txtEnrolListDaysAfter.Text); emSettings.JournalIntegration = chkJournalIntegration.Checked; var objDesktopModule = DesktopModuleController.GetDesktopModuleByModuleName("DNN_Events", 0); emSettings.Version = objDesktopModule.Version; repository.SaveSettings(ModuleConfiguration, emSettings); CreateThemeDirectory(); } catch (Exception exc) //Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } } /// <summary> /// Get Assigned Sub Events and Bind to Grid /// </summary> /// <remarks></remarks> private void BindSubEvents() { lstAssignedCals.DataTextField = "SubEventTitle"; lstAssignedCals.DataValueField = "MasterID"; lstAssignedCals.DataSource = null; lstAssignedCals.DataBind(); lstAssignedCals.DataSource = _objCtlMasterEvent.EventsMasterAssignedModules(ModuleId); lstAssignedCals.DataBind(); } /// <summary> /// Get Avaiable Sub Events for Portal and Bind to DropDown /// </summary> /// <remarks></remarks> private void BindAvailableEvents() { lstAvailableCals.DataTextField = "SubEventTitle"; lstAvailableCals.DataValueField = "SubEventID"; lstAvailableCals.DataSource = null; lstAvailableCals.DataBind(); lstAvailableCals.DataSource = _objCtlMasterEvent.EventsMasterAvailableModules(PortalId, ModuleId); lstAvailableCals.DataBind(); } private void Enable_Disable_Cals() { divMasterEvent.Visible = chkMasterEvent.Checked; } private string EnrollListFields(bool blUser, bool blDisp, bool blEmail, bool blPhone, bool blApprove, bool blNo) { var listFields = ""; if (blUser) { listFields = listFields + "01;"; } if (blDisp) { listFields = listFields + "02;"; } if (blEmail) { listFields = listFields + "03;"; } if (blPhone) { listFields = listFields + "04;"; } if (blApprove) { listFields = listFields + "05;"; } if (blNo) { listFields = listFields + "06;"; } return listFields; } public string AddSkinContainerControls(string url, string addchar) { var objCtlTab = new TabController(); var objTabInfo = objCtlTab.GetTab(TabId, PortalId, false); string skinSrc = null; if (!(objTabInfo.SkinSrc == string.Empty)) { skinSrc = objTabInfo.SkinSrc; if (skinSrc.Substring(skinSrc.Length - 5, 5) == ".ascx") { skinSrc = skinSrc.Substring(0, skinSrc.Length - 5); } } var objCtlModule = new ModuleController(); var objModuleInfo = objCtlModule.GetModule(ModuleId, TabId, false); string containerSrc = null; if (objModuleInfo.DisplayTitle) { if (!(objModuleInfo.ContainerSrc == string.Empty)) { containerSrc = objModuleInfo.ContainerSrc; } else if (!(objTabInfo.ContainerSrc == string.Empty)) { containerSrc = objTabInfo.ContainerSrc; } if (!string.IsNullOrEmpty(containerSrc)) { if (containerSrc.Substring(containerSrc.Length - 5, 5) == ".ascx") { containerSrc = containerSrc.Substring(0, containerSrc.Length - 5); } } } else { containerSrc = "[G]Containers/_default/No+Container"; } if (!string.IsNullOrEmpty(containerSrc)) { url += addchar + "ContainerSrc=" + HttpUtility.HtmlEncode(containerSrc); addchar = "&"; } if (!string.IsNullOrEmpty(skinSrc)) { url += addchar + "SkinSrc=" + HttpUtility.HtmlEncode(skinSrc); } return url; } #endregion #region Links, Buttons and Events protected void chkMasterEvent_CheckedChanged(object sender, EventArgs e) { cmdRemoveAllCals_Click(sender, e); Enable_Disable_Cals(); } protected void cmdAdd_Click(object sender, EventArgs e) { var objListItem = default(ListItem); var objList = new ArrayList(); foreach (ListItem tempLoopVar_objListItem in lstAvailable.Items) { objListItem = tempLoopVar_objListItem; objList.Add(objListItem); } foreach (ListItem tempLoopVar_objListItem in objList) { objListItem = tempLoopVar_objListItem; if (objListItem.Selected) { lstAvailable.Items.Remove(objListItem); lstAssigned.Items.Add(objListItem); } } lstAvailable.ClearSelection(); lstAssigned.ClearSelection(); Sort(lstAssigned); } protected void cmdRemove_Click(object sender, EventArgs e) { var objListItem = default(ListItem); var objList = new ArrayList(); foreach (ListItem tempLoopVar_objListItem in lstAssigned.Items) { objListItem = tempLoopVar_objListItem; objList.Add(objListItem); } foreach (ListItem tempLoopVar_objListItem in objList) { objListItem = tempLoopVar_objListItem; if (objListItem.Selected) { lstAssigned.Items.Remove(objListItem); lstAvailable.Items.Add(objListItem); } } lstAvailable.ClearSelection(); lstAssigned.ClearSelection(); Sort(lstAvailable); } protected void cmdAddAll_Click(object sender, EventArgs e) { var objListItem = default(ListItem); foreach (ListItem tempLoopVar_objListItem in lstAvailable.Items) { objListItem = tempLoopVar_objListItem; lstAssigned.Items.Add(objListItem); } lstAvailable.Items.Clear(); lstAvailable.ClearSelection(); lstAssigned.ClearSelection(); Sort(lstAssigned); } protected void cmdRemoveAll_Click(object sender, EventArgs e) { var objListItem = default(ListItem); foreach (ListItem tempLoopVar_objListItem in lstAssigned.Items) { objListItem = tempLoopVar_objListItem; lstAvailable.Items.Add(objListItem); } lstAssigned.Items.Clear(); lstAvailable.ClearSelection(); lstAssigned.ClearSelection(); Sort(lstAvailable); } protected void Sort(ListBox ctlListBox) { var arrListItems = new ArrayList(); var objListItem = default(ListItem); // store listitems in temp arraylist foreach (ListItem tempLoopVar_objListItem in ctlListBox.Items) { objListItem = tempLoopVar_objListItem; arrListItems.Add(objListItem); } // sort arraylist based on text value arrListItems.Sort(new ListItemComparer()); // clear control ctlListBox.Items.Clear(); // add listitems to control foreach (ListItem tempLoopVar_objListItem in arrListItems) { objListItem = tempLoopVar_objListItem; ctlListBox.Items.Add(objListItem); } } protected void cmdAddCals_Click(object sender, EventArgs e) { var objListItem = default(ListItem); var masterEvent = new EventMasterInfo(); foreach (ListItem tempLoopVar_objListItem in lstAvailableCals.Items) { objListItem = tempLoopVar_objListItem; if (objListItem.Selected) { masterEvent.MasterID = 0; masterEvent.ModuleID = ModuleId; masterEvent.SubEventID = Convert.ToInt32(objListItem.Value); _objCtlMasterEvent.EventsMasterSave(masterEvent); } } BindSubEvents(); BindAvailableEvents(); } protected void cmdAddAllCals_Click(object sender, EventArgs e) { var objListItem = default(ListItem); var masterEvent = new EventMasterInfo(); foreach (ListItem tempLoopVar_objListItem in lstAvailableCals.Items) { objListItem = tempLoopVar_objListItem; masterEvent.MasterID = 0; masterEvent.ModuleID = ModuleId; masterEvent.SubEventID = Convert.ToInt32(objListItem.Value); _objCtlMasterEvent.EventsMasterSave(masterEvent); } BindSubEvents(); BindAvailableEvents(); } protected void cmdRemoveCals_Click(object sender, EventArgs e) { var objListItem = default(ListItem); foreach (ListItem tempLoopVar_objListItem in lstAssignedCals.Items) { objListItem = tempLoopVar_objListItem; if (objListItem.Selected) { _objCtlMasterEvent.EventsMasterDelete(int.Parse(objListItem.Value), ModuleId); } } BindSubEvents(); BindAvailableEvents(); } protected void cmdRemoveAllCals_Click(object sender, EventArgs e) { var objListItem = default(ListItem); foreach (ListItem tempLoopVar_objListItem in lstAssignedCals.Items) { objListItem = tempLoopVar_objListItem; _objCtlMasterEvent.EventsMasterDelete(int.Parse(objListItem.Value), ModuleId); } BindSubEvents(); BindAvailableEvents(); } protected void cmdUpdateTemplate_Click(object sender, EventArgs e) { var strTemplate = ddlTemplates.SelectedValue; Settings.Templates.SaveTemplate(ModuleId, strTemplate, txtEventTemplate.Text.Trim()); lblTemplateUpdated.Visible = true; lblTemplateUpdated.Text = string.Format(Localization.GetString("TemplateUpdated", LocalResourceFile), Localization.GetString(strTemplate + "Name", LocalResourceFile)); } protected void cmdResetTemplate_Click(object sender, EventArgs e) { var strTemplate = ddlTemplates.SelectedValue; Settings.Templates.ResetTemplate(ModuleId, strTemplate, LocalResourceFile); txtEventTemplate.Text = Settings.Templates.GetTemplate(strTemplate); lblTemplateUpdated.Visible = true; lblTemplateUpdated.Text = string.Format(Localization.GetString("TemplateReset", LocalResourceFile), Localization.GetString(strTemplate + "Name", LocalResourceFile)); } protected void ddlTemplates_SelectedIndexChanged(object sender, EventArgs e) { txtEventTemplate.Text = Settings.Templates.GetTemplate(ddlTemplates.SelectedValue); lblTemplateUpdated.Visible = false; } protected void cancelButton_Click(object sender, EventArgs e) { try { Response.Redirect(GetSocialNavigateUrl(), true); } catch (Exception) //Module failed to load { //ProcessModuleLoadException(Me, exc) } } protected void updateButton_Click(object sender, EventArgs e) { try { UpdateSettings(); Response.Redirect(GetSocialNavigateUrl(), true); } catch (Exception) //Module failed to load { //ProcessModuleLoadException(Me, exc) } } #endregion } #region Comparer Class public class ListItemComparer : IComparer { public int Compare(object x, object y) { var a = (ListItem) x; var b = (ListItem) y; var c = new CaseInsensitiveComparer(); return c.Compare(a.Text, b.Text); } } #endregion #region DataClasses public class ThemeSetting { #region Enumerators public enum ThemeSettingTypeEnum { DefaultTheme = 0, CustomTheme = 1 } #endregion #region Overrides public override string ToString() { return string.Format("{0},{1},{2}", Convert.ToInt32(SettingType), ThemeName, ThemeFile); } #endregion #region Member Variables public ThemeSettingTypeEnum SettingType; public string ThemeName; public string ThemeFile; public string CssClass; #endregion #region Methods public bool ValidateSetting(string setting) { var s = setting.Split(','); if (!(s.GetUpperBound(0) == 2)) { return false; } if (!Information.IsNumeric(s[0])) { return false; } return true; } public void ReadSetting(string setting, int portalID) { if (!ValidateSetting(setting)) { throw new Exception("Setting is not right format to convert into ThemeSetting"); } var s = setting.Split(','); SettingType = (ThemeSettingTypeEnum) int.Parse(s[0]); ThemeName = s[1]; CssClass = "Theme" + ThemeName; switch (SettingType) { case ThemeSettingTypeEnum.DefaultTheme: ThemeFile = string.Format("{0}/DesktopModules/Events/Themes/{1}/{1}.css", Globals.ApplicationPath, ThemeName); break; case ThemeSettingTypeEnum.CustomTheme: var pc = new PortalController(); var with_1 = pc.GetPortal(portalID); ThemeFile = string.Format("{0}/{1}/DNNEvents/Themes/{2}/{2}.css", Globals.ApplicationPath, with_1.HomeDirectory, ThemeName); break; } } #endregion } #endregion }
45.229622
145
0.574669
[ "MIT" ]
MaiklT/DNN.Events
EventSettings.ascx.cs
91,003
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Runtime.CompilerServices; using UnityEngine; [assembly: InternalsVisibleTo("Microsoft.MixedReality.Toolkit.Tests.PlayModeTests")] namespace Microsoft.MixedReality.Toolkit.Experimental.Physics { public class QuaternionElasticSystem : IElasticSystem<Quaternion> { private Quaternion currentValue; private Quaternion currentVelocity; private QuaternionElasticExtent extent; private ElasticProperties elasticProperties; /// <summary> /// Default constructor; initializes the elastic system with the specified /// initial value, velocity, extent, and elastic properties. /// </summary> public QuaternionElasticSystem(Quaternion initialValue, Quaternion initialVelocity, QuaternionElasticExtent extentInfo, ElasticProperties elasticProperties) { currentValue = initialValue; currentVelocity = initialVelocity; this.extent = extentInfo; this.elasticProperties = elasticProperties; } /// <inheritdoc/> public Quaternion ComputeIteration(Quaternion forcingValue, float deltaTime) { // If the dot product is negative, we need to negate the forcing // quaternion so that the force is coherent/wraps correctly. if (Quaternion.Dot(forcingValue, currentValue) < 0) { forcingValue = new Quaternion(-forcingValue.x, -forcingValue.y, -forcingValue.z, -forcingValue.w); } // Displacement of the forcing value compared to the current state's value. Quaternion displacement = Quaternion.Inverse(currentValue) * forcingValue; // The force applied is an approximation of F=(kx - vd) in 4-space Quaternion force = Add(Scale(displacement, elasticProperties.HandK), Scale(currentVelocity, -elasticProperties.Drag)); // Euler representation of the current elastic quaternion state. Vector3 eulers = currentValue.eulerAngles; foreach (var snapPoint in extent.SnapPoints) { // If we are set to repeat the snap points (i.e., tiling them across the sphere), // we use the nearest integer multiple of the snap point. If it is not repeated, // we use the snap point directly. Vector3 nearest = extent.RepeatSnapPoints ? GetNearest(eulers, snapPoint) : snapPoint; // Convert the nearest point to a quaternion representation. Quaternion nearestQuat = Quaternion.Euler(nearest.x, nearest.y, nearest.z); // If the dot product is negative, we need to negate the snap // quaternion so that the snap force is coherent/wraps correctly. if (Quaternion.Dot(nearestQuat, currentValue) < 0) { nearestQuat = Scale(nearestQuat, -1.0f); } // Displacement from the current value to the snap quaternion. Quaternion snapDisplacement = Quaternion.Inverse(currentValue) * nearestQuat; // Angle of the snapping displacement, used to calculate the snapping magnitude. float snapAngle = Quaternion.Angle(currentValue, nearestQuat); // Strength of the snapping force, function of the snap angle and the configured // snapping radius. float snapFactor = ComputeSnapFactor(snapAngle, extent.SnapRadius); // Accumulate the force from every snap point. force = Add(force, Scale(snapDisplacement, elasticProperties.SnapK * snapFactor)); } // Performing Euler integration in 4-space. // Acceleration = F/m Quaternion accel = Scale(force, (1 / elasticProperties.Mass)); // v' = v + a * deltaT currentVelocity = Add(currentVelocity, Scale(accel, deltaTime)); // x' = x + v' * deltaT currentValue *= Scale(currentVelocity, deltaTime).normalized; // As the current value is a quaternion, we must renormalize the quaternion // before using it as a representation of a rotation. currentValue = currentValue.normalized; return currentValue; } /// <inheritdoc/> public Quaternion GetCurrentValue() => currentValue; /// <inheritdoc/> public Quaternion GetCurrentVelocity() => currentVelocity; // Find the nearest integer multiple of the specified interval private Vector3 GetNearest(Vector3 target, Vector3 interval) { return new Vector3(GetNearest(target.x, interval.x), GetNearest(target.y, interval.y), GetNearest(target.z, interval.z)); } // Find the nearest integer multiple of the specified interval private float GetNearest(float target, float interval) { return Mathf.Round(target / interval) * interval; } private float ComputeSnapFactor(float angleFromPoint, float radius) { // Snap force is calculated by multiplying the "-kx" factor by // a clamped distance factor. This results in an overall // hyperbolic profile to the force imparted by the snap point. return (1.0f - Mathf.Clamp01(Mathf.Abs(angleFromPoint / radius))); } // Elementwise quaternion addition. private Quaternion Add(Quaternion p, Quaternion q) { return new Quaternion(p.x + q.x, p.y + q.y, p.z + q.z, p.w + q.w); } // Elementwise quaternion scale. private Quaternion Scale(Quaternion p, float t) { return new Quaternion(p.x * t, p.y * t, p.z * t, p.w * t); } } }
43.014286
133
0.616905
[ "MIT" ]
AdsyArena/ARbot
Assets/MRTK/SDK/Experimental/Elastic/Scripts/QuaternionElasticSystem.cs
6,024
C#
using DotVVM.Framework.Controls.Bootstrap; using DotVVM.Framework.ViewModel; using System; using System.Collections.Generic; using System.Linq; using System.Text; using DotVVM.Framework.Hosting; namespace DotvvmWeb.Views.Docs.Controls.bootstrap.Alert.sample3 { public class ViewModel : MyViewModelBase { public void DoSomething() { ExecuteWithAlert(() => { // the action }); } } }
21
63
0.621118
[ "Apache-2.0" ]
Duzij/dotvvm-docs
Controls/bootstrap/Alert/sample3/ViewModel.cs
483
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// Credits : https://www.patrykgalach.com/2020/01/27/assigning-interface-in-unity-inspector/ /// </summary> namespace Aokoro { /// <summary> /// Attribute that require implementation of the provided interface. /// </summary> public class RequireInterfaceAttribute : PropertyAttribute { // Interface type. public System.Type requiredType { get; private set; } /// <summary> /// Requiring implementation of the <see cref="T:RequireInterfaceAttribute"/> interface. /// </summary> /// <param name="type">Interface type.</param> public RequireInterfaceAttribute(System.Type type) { this.requiredType = type; } } }
30.074074
96
0.646552
[ "MIT" ]
AokoroTeam/UPQP_House
Assets/Plugins/Aokoro/Core/Serialisation/Interfaces/RequireInterfaceAttribute.cs
812
C#
/* * Wrap over vJoyInterfaceWrap itself to make it an optional dependency. */ using vJoyInterfaceWrap; // --------------------------------------------------------------------------------------------------------------------------------- namespace SimElation { /// <summary>vJoyInterfaceWrap wrap.</summary> public class VJoyWrap { /// <summary /> public VJoyWrap() { m_vJoy = new vJoy(); } /// <summary /> public bool DriverMatch(ref uint dllVersion, ref uint driverVersion) { return m_vJoy.DriverMatch(ref dllVersion, ref driverVersion); } /// <summary /> public VjdStat GetVJDStatus(uint id) { return m_vJoy.GetVJDStatus(id); } /// <summary /> public bool AcquireVJD(uint id) { return m_vJoy.AcquireVJD(id); } /// <summary /> public bool SetBtn(bool isSet, uint id, uint buttonId) { return m_vJoy.SetBtn(isSet, id, buttonId); } private readonly vJoy m_vJoy; } }
19.893617
132
0.571123
[ "MIT" ]
simelation/simhub-plugins
packages/simhub-sli-plugin/src/VJoyWrap.cs
937
C#
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System.Collections.Generic; namespace IdentityServer.Quickstart.Consent { public class ConsentViewModel : ConsentInputModel { public string ClientName { get; set; } public string ClientUrl { get; set; } public string ClientLogoUrl { get; set; } public bool AllowRememberConsent { get; set; } public IEnumerable<ScopeViewModel> IdentityScopes { get; set; } public IEnumerable<ScopeViewModel> ResourceScopes { get; set; } } }
33.55
107
0.703428
[ "MPL-2.0" ]
CristiHabliuc/stam-acasa
backend/src/StamAcasa.IdentityServer/Quickstart/Consent/ConsentViewModel.cs
673
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using VkNet.Model.RequestParams; using VkNet.Utils; namespace VkNet.Categories { /// <inheritdoc /> public partial class PlacesCategory { /// <inheritdoc /> public async Task<object> AddAsync(PlacesAddParams placesAddParams) { return await TypeHelper.TryInvokeMethodAsync(func: () => _vk.Places.Add(placesAddParams: placesAddParams)); } /// <inheritdoc /> public async Task<object> CheckinAsync(PlacesCheckinParams placesCheckinParams) { return await TypeHelper.TryInvokeMethodAsync(func: () => _vk.Places.Checkin(placesCheckinParams: placesCheckinParams)); } /// <inheritdoc /> public async Task<IEnumerable<object>> GetByIdAsync(IEnumerable<ulong> places) { return await TypeHelper.TryInvokeMethodAsync(func: () => _vk.Places.GetById(places: places)); } /// <inheritdoc /> public async Task<IEnumerable<object>> GetCheckinsAsync(PlacesGetCheckinsParams placesGetCheckinsParams) { return await TypeHelper.TryInvokeMethodAsync(func: () => _vk.Places.GetCheckins(placesGetCheckinsParams: placesGetCheckinsParams)); } /// <inheritdoc /> public async Task<IEnumerable<object>> GetTypesAsync() { return await TypeHelper.TryInvokeMethodAsync(func: () => _vk.Places.GetTypes()); } /// <inheritdoc /> public async Task<Uri> SearchAsync(PlacesSearchParams placesSearchParams) { return await TypeHelper.TryInvokeMethodAsync(func: () => _vk.Places.Search(placesSearchParams: placesSearchParams)); } } }
31.673469
122
0.748711
[ "MIT" ]
slay9090/vk
VkNet/Categories/Async/PlacesCategoryAsync.cs
1,554
C#
namespace SharpShell.Interop { /// <summary> /// Action flag. /// </summary> public enum PSPCB : uint { /// <summary> /// Version 5.80 or later. A page is being created. The return value is not used. /// </summary> PSPCB_ADDREF = 0, /// <summary> /// A page is being destroyed. The return value is ignored. /// </summary> PSPCB_RELEASE = 1, /// <summary> /// A dialog box for a page is being created. Return nonzero to allow it to be created, or zero to prevent it. /// </summary> PSPCB_CREATE = 2 } }
27.086957
118
0.539326
[ "MIT" ]
0x4a616e/sharpshell
SharpShell/SharpShell/Interop/PSPCB.cs
623
C#
using System; namespace Pootis_Bot.Module.Reminders.Entities { public class Reminder { public ulong UserId { get; set; } public string Message { get; set; } public string MessageUrl { get; set; } public DateTime EndTime { get; set; } public DateTime StartTime { get; set; } } }
22.1875
49
0.574648
[ "MIT" ]
Voltstro/Pootis-Bot
src/Modules/Pootis-Bot.Module.Reminders/Entities/Reminder.cs
357
C#
using System; namespace AngularJSExample.Areas.HelpPage.ModelDescriptions { public class ParameterAnnotation { public Attribute AnnotationAttribute { get; set; } public string Documentation { get; set; } } }
21.545455
59
0.704641
[ "Unlicense" ]
SiddharthMishraPersonal/InterviewPreperation
AngularJS/Code/AngularJSExample/AngularJSExample/Areas/HelpPage/ModelDescriptions/ParameterAnnotation.cs
237
C#
using System; using System.Web.UI.WebControls; using CMS.Base.Web.UI; using CMS.UIControls; public partial class CMSMasterPages_UI_Dashboard : CMSMasterPage { /// <summary> /// Head elements /// </summary> public override Literal HeadElements { get { return ltlTags; } set { ltlTags = value; } } /// <summary> /// Page title control /// </summary> public override PageTitle Title { get { return titleElem; } } /// <summary> /// Body panel. /// </summary> public override Panel PanelBody { get { return pnlBody; } } /// <summary> /// Ensures that for dashboard pages there is not global messages placeholder /// </summary> protected override MessagesPlaceHolder EnsureMessagesPlaceHolder() { return null; } protected void Page_Load(object sender, EventArgs e) { BodyClass += " DashboardMode ContentBody"; } }
17.253968
81
0.541858
[ "MIT" ]
BryanSoltis/KenticoMVCWidgetShowcase
CMS/CMSMasterPages/UI/Dashboard.master.cs
1,089
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; using Glimpse.Server.Resources; using Microsoft.AspNetCore.Http; using Glimpse.Internal.Extensions; using Tavis.UriTemplates; namespace Glimpse.Server.Internal { public class ResourceManager : IResourceManager { private IDictionary<string, string> _templateTable = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private IDictionary<string, ResourceManagerItem> _resourceTable = new Dictionary<string, ResourceManagerItem>(StringComparer.OrdinalIgnoreCase); public void Register(string name, string uriTemplate) { _templateTable.Add(name, uriTemplate); } public void Register(string name, string uriTemplate, ResourceType type, Func<HttpContext, IDictionary<string, string>, Task> resource) { _resourceTable.Add(name, new ResourceManagerItem(name, type, uriTemplate, resource)); Register(name, uriTemplate); } public ResourceManagerResult Match(HttpContext context) { var request = context.Request; var url = $"{request.Scheme}://{request.Host}{request.PathBase}{request.Path}{request.QueryString}"; var path = request.Path; var remainingPath = (PathString)null; var startingSegment = path.StartingSegment(out remainingPath); var parameters = (IDictionary<string, string>)null; var managerItem = (ResourceManagerItem)null; if (!string.IsNullOrEmpty(startingSegment) && _resourceTable.TryGetValue(startingSegment, out managerItem) && MatchUriTemplate(managerItem.UriTemplate, url, out parameters)) { return new ResourceManagerResult(parameters, managerItem.Resource, managerItem.Type); } return null; } public IReadOnlyDictionary<string, string> RegisteredUris => new ReadOnlyDictionary<string, string>(_templateTable); private bool MatchUriTemplate(UriTemplate uriTemplate, string url, out IDictionary<string, string> parameters) { if (uriTemplate == null || string.IsNullOrEmpty(url)) { parameters = new Dictionary<string, string>(); } else { var parsed = uriTemplate.GetParameters(new Uri(url)); parameters = parsed.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToString()); } return true; } private class ResourceManagerItem { public ResourceManagerItem(string name, ResourceType type, string uriTemplate, Func<HttpContext, IDictionary<string, string>, Task> resource) { Type = type; UriTemplate = uriTemplate != null ? new UriTemplate(name + "/" + uriTemplate) : null; Resource = resource; } public ResourceType Type { get; set; } public UriTemplate UriTemplate { get; } public Func<HttpContext, IDictionary<string, string>, Task> Resource { get; } } } }
39.902439
153
0.636002
[ "MIT" ]
Glimpse/Glimpse.Prototype
src/Glimpse.Server/Internal/ResourceManager.cs
3,272
C#
// ========================================================================== // SwaggerHelper.cs // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex Group // All rights reserved. // ========================================================================== using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using NJsonSchema; using NJsonSchema.Generation; using NSwag; using Squidex.Config; using Squidex.Controllers.Api; using Squidex.Shared.Identity; namespace Squidex.Pipeline.Swagger { public static class SwaggerHelper { public static string LoadDocs(string name) { var assembly = typeof(SwaggerHelper).GetTypeInfo().Assembly; using (var resourceStream = assembly.GetManifestResourceStream($"Squidex.Docs.{name}.md")) { var streamReader = new StreamReader(resourceStream); return streamReader.ReadToEnd(); } } public static SwaggerDocument CreateApiDocument(HttpContext context, MyUrlsOptions urlOptions, string appName) { var scheme = string.Equals(context.Request.Scheme, "http", StringComparison.OrdinalIgnoreCase) ? SwaggerSchema.Http : SwaggerSchema.Https; var document = new SwaggerDocument { Tags = new List<SwaggerTag>(), Schemes = new List<SwaggerSchema> { scheme }, Consumes = new List<string> { "application/json" }, Produces = new List<string> { "application/json" }, Info = new SwaggerInfo { ExtensionData = new Dictionary<string, object> { ["x-logo"] = new { url = urlOptions.BuildUrl("images/logo-white.png", false), backgroundColor = "#3f83df" } }, Title = $"Suidex API for {appName} App" }, BasePath = "/api" }; if (!string.IsNullOrWhiteSpace(context.Request.Host.Value)) { document.Host = context.Request.Host.Value; } document.SecurityDefinitions.Add("OAuth2", CreateOAuthSchema(urlOptions)); return document; } public static SwaggerSecurityScheme CreateOAuthSchema(MyUrlsOptions urlOptions) { var tokenUrl = urlOptions.BuildUrl($"{Constants.IdentityPrefix}/connect/token"); var securityDocs = LoadDocs("security"); var securityDescription = securityDocs.Replace("<TOKEN_URL>", tokenUrl); var result = new SwaggerSecurityScheme { TokenUrl = tokenUrl, Type = SwaggerSecuritySchemeType.OAuth2, Flow = SwaggerOAuth2Flow.Application, Scopes = new Dictionary<string, string> { { Constants.ApiScope, "Read and write access to the API" }, { SquidexRoles.AppOwner, "App contributor with Owner permission." }, { SquidexRoles.AppEditor, "Client (writer) or App contributor with Editor permission." }, { SquidexRoles.AppReader, "Client (readonly) or App contributor with Editor permission." }, { SquidexRoles.AppDeveloper, "App contributor with Developer permission." } }, Description = securityDescription }; return result; } public static async Task<JsonSchema4> GetErrorDtoSchemaAsync(this JsonSchemaGenerator schemaGenerator, JsonSchemaResolver resolver) { var errorType = typeof(ErrorDto); return await schemaGenerator.GenerateWithReference<JsonSchema4>(errorType, Enumerable.Empty<Attribute>(), resolver); } public static void AddQueryParameter(this SwaggerOperation operation, string name, JsonObjectType type, string description = null) { var parameter = new SwaggerParameter { Type = type, Name = name, Kind = SwaggerParameterKind.Query }; if (!string.IsNullOrWhiteSpace(description)) { parameter.Description = description; } operation.Parameters.Add(parameter); } public static void AddPathParameter(this SwaggerOperation operation, string name, JsonObjectType type, string description = null) { var parameter = new SwaggerParameter { Type = type, Name = name, Kind = SwaggerParameterKind.Path }; if (!string.IsNullOrWhiteSpace(description)) { parameter.Description = description; } parameter.IsRequired = true; parameter.IsNullableRaw = false; operation.Parameters.Add(parameter); } public static void AddBodyParameter(this SwaggerOperation operation, string name, JsonSchema4 schema, string description) { var parameter = new SwaggerParameter { Schema = schema, Name = name, Kind = SwaggerParameterKind.Body }; if (!string.IsNullOrWhiteSpace(description)) { parameter.Description = description; } parameter.IsRequired = true; parameter.IsNullableRaw = false; operation.Parameters.Add(parameter); } public static void AddResponse(this SwaggerOperation operation, string statusCode, string description, JsonSchema4 schema = null) { var response = new SwaggerResponse { Description = description, Schema = schema }; operation.Responses.Add(statusCode, response); } } }
37.144578
139
0.557736
[ "MIT" ]
andrewhoi/squidex
src/Squidex/Pipeline/Swagger/SwaggerHelper.cs
6,168
C#
using System; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using Android.Content; using Android.Content.Res; using Android.Support.Design.Widget; using Android.Support.V7.Widget; using Android.Widget; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; using Xfx; using Xfx.Controls.Droid.Renderers; using Xfx.Controls.Droid.XfxComboBox; using Resource = Android.Resource; [assembly: ExportRenderer(typeof(XfxComboBox), typeof(XfxComboBoxRendererDroid))] namespace Xfx.Controls.Droid.Renderers { public class XfxComboBoxRendererDroid : XfxEntryRendererDroid { public XfxComboBoxRendererDroid(Context context) : base(context) { } private AppCompatAutoCompleteTextView AutoComplete => (AppCompatAutoCompleteTextView)Control?.EditText; protected override TextInputLayout CreateNativeControl() { var textInputLayout = new TextInputLayout(Context); var autoComplete = new AppCompatAutoCompleteTextView(Context) { SupportBackgroundTintList = ColorStateList.ValueOf(GetPlaceholderColor()) }; textInputLayout.AddView(autoComplete); return textInputLayout; } protected override void OnElementChanged(ElementChangedEventArgs<XfxEntry> e) { base.OnElementChanged(e); if (Element == null || Control == null || Control.Handle == IntPtr.Zero || EditText == null || EditText.Handle == IntPtr.Zero || AutoComplete == null || AutoComplete.Handle == IntPtr.Zero) return; if (e.OldElement != null) { // unsubscribe AutoComplete.ItemClick -= AutoCompleteOnItemSelected; if (e.OldElement is Xfx.XfxComboBox elm) elm.CollectionChanged -= ItemsSourceCollectionChanged; } if (e.NewElement != null) { // subscribe SetItemsSource(); SetThreshold(); KillPassword(); AutoComplete.ItemClick += AutoCompleteOnItemSelected; if (e.NewElement is Xfx.XfxComboBox elm) elm.CollectionChanged += ItemsSourceCollectionChanged; } } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (Element == null || Control == null || Control.Handle == IntPtr.Zero || EditText == null || EditText.Handle == IntPtr.Zero || AutoComplete == null || AutoComplete.Handle == IntPtr.Zero) return; if (e.PropertyName == Entry.IsPasswordProperty.PropertyName) KillPassword(); if (e.PropertyName == Xfx.XfxComboBox.ItemsSourceProperty.PropertyName) SetItemsSource(); else if (e.PropertyName == Xfx.XfxComboBox.ThresholdProperty.PropertyName) SetThreshold(); } private void AutoCompleteOnItemSelected(object sender, AdapterView.ItemClickEventArgs args) { // Method is called via event subscription which could result to a call to a disposed object. if (Element == null || Control == null || Control.Handle == IntPtr.Zero || EditText == null || EditText.Handle == IntPtr.Zero || AutoComplete == null || AutoComplete.Handle == IntPtr.Zero) return; var view = (AutoCompleteTextView) sender; var selectedItemArgs = new XfxSelectedItemChangedEventArgs(view.Text, args.Position); var element = (Xfx.XfxComboBox) Element; element.OnItemSelectedInternal(Element, selectedItemArgs); HideKeyboard(); } private void ItemsSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs) { // Method is called via event subscription which could result to a call to a disposed object. if (Element == null || Control == null || Control.Handle == IntPtr.Zero || EditText == null || EditText.Handle == IntPtr.Zero || AutoComplete == null || AutoComplete.Handle == IntPtr.Zero) return; var element = (Xfx.XfxComboBox) Element; ResetAdapter(element); } private void KillPassword() { if (Element.IsPassword) throw new NotImplementedException("Cannot set IsPassword on a XfxComboBox"); } private void ResetAdapter(Xfx.XfxComboBox element) { var adapter = new XfxComboBoxArrayAdapter(Context, Resource.Layout.SimpleDropDownItem1Line, element.ItemsSource.ToList(), element.SortingAlgorithm); AutoComplete.Adapter = adapter; adapter.NotifyDataSetChanged(); } private void SetItemsSource() { var element = (Xfx.XfxComboBox) Element; if (element.ItemsSource == null) return; ResetAdapter(element); } private void SetThreshold() { var element = (Xfx.XfxComboBox) Element; AutoComplete.Threshold = element.Threshold; } } }
38.941606
200
0.625867
[ "MIT" ]
breyed/Xfx.Controls
src/Xfx.Controls.Droid/Renderers/XfxComboBoxRendererDroid.cs
5,337
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.Cbs.V20170312.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class BindAutoSnapshotPolicyResponse : AbstractModel { /// <summary> /// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 /// </summary> [JsonProperty("RequestId")] public string RequestId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "RequestId", this.RequestId); } } }
30.409091
81
0.665919
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Cbs/V20170312/Models/BindAutoSnapshotPolicyResponse.cs
1,396
C#
#region License // Copyright (c) 2011, ClearCanvas Inc. // All rights reserved. // http://www.clearcanvas.ca // // This software is licensed under the Open Software License v3.0. // For the complete license, see http://www.clearcanvas.ca/OSLv3.0 #endregion using System; using System.Collections.Generic; using System.IO; using ClearCanvas.ImageServer.Common; using ClearCanvas.ImageServer.Common.Command; using ClearCanvas.ImageServer.Model; namespace ClearCanvas.ImageServer.Services.WorkQueue { /// <summary> /// Represents the execution context where the WorkQueue item processor is run. /// </summary> public class WorkQueueProcessorContext : ServerExecutionContext { #region Private Fields private readonly Model.WorkQueue _item; #endregion public WorkQueueProcessorContext(Model.WorkQueue item) :base(item.GetKey().Key.ToString()) { _item = item; } protected override string GetTemporaryPath() { IList<StudyStorageLocation> storages = StudyStorageLocation.FindStorageLocations(StudyStorage.Load(_item.StudyStorageKey)); if (storages == null || storages.Count == 0) { // ??? return base.GetTemporaryPath(); } ServerFilesystemInfo filesystem = FilesystemMonitor.Instance.GetFilesystemInfo(storages[0].FilesystemKey); if (filesystem == null) { // not ready? return base.GetTemporaryPath(); } string basePath = GetTempPathRoot(); if (String.IsNullOrEmpty(basePath)) { basePath = Path.Combine(filesystem.Filesystem.FilesystemPath, "temp"); } String tempDirectory = Path.Combine(basePath, String.Format("{0}-{1}", _item.WorkQueueTypeEnum.Lookup, _item.GetKey())); for (int i = 2; i < 1000; i++) { if (!Directory.Exists(tempDirectory)) { break; } tempDirectory = Path.Combine(basePath, String.Format("{0}-{1}({2})", _item.WorkQueueTypeEnum.Lookup, _item.GetKey(), i)); } if (!Directory.Exists(tempDirectory)) Directory.CreateDirectory(tempDirectory); return tempDirectory; } } }
32.518519
123
0.550494
[ "Apache-2.0" ]
SNBnani/Xian
ImageServer/Services/WorkQueue/WorkQueueProcessorContext.cs
2,634
C#
using System; using System.Diagnostics; using System.Threading.Tasks; using CascadingAutoCompleteViews.Portable.Interfaces; using Telerik.XamarinForms.Input; using Xamarin.Forms; namespace CascadingAutoCompleteViews.Portable { public partial class MvvmPage : ContentPage, IAutoCompleteService { public MvvmPage() { InitializeComponent(); viewModel.AutoCompleteService = this; } public void Focus(string controlName) { this.FindByName<RadAutoCompleteView>(controlName)?.Focus(); } } }
24.73913
71
0.70123
[ "MIT" ]
LanceMcCarthy/CustomXamarinDemos
src/CascadingAutoCompleteViews/CascadingAutoCompleteViews/Portable/MvvmPage.xaml.cs
571
C#
using Microsoft.Extensions.Configuration; namespace WebApi.Modules { public class ConfigurationProvider : Application.Providers.IConfigurationProvider { private readonly IConfiguration Configuration; public ConfigurationProvider(IConfiguration configuration) { Configuration = configuration; } public string GetConfiguration(string key) { return Configuration.GetValue<string>(key); } } }
24.25
85
0.676289
[ "MIT" ]
TiagosCz/DotNepWebAppTemplate
src/WebApi/WebApi/Modules/ConfigurationProvider .cs
487
C#
using System; using System.Collections.Generic; using MirRemakeBackend.Data; namespace MirRemakeBackend.DataEntity { class DE_Unit { public readonly IReadOnlyDictionary<ActorUnitConcreteAttributeType, int> m_attrDict; public int m_MaxHp { get { return m_attrDict[ActorUnitConcreteAttributeType.MAX_HP]; } } public int m_MaxMp { get { return m_attrDict[ActorUnitConcreteAttributeType.MAX_MP]; } } public int m_DeltaHpPerSecond { get { return m_attrDict[ActorUnitConcreteAttributeType.DELTA_HP_PER_SECOND]; } } public int m_DeltaMpPerSecond { get { return m_attrDict[ActorUnitConcreteAttributeType.DELTA_MP_PER_SECOND]; } } public int m_Attack { get { return m_attrDict[ActorUnitConcreteAttributeType.ATTACK]; } } public int m_Magic { get { return m_attrDict[ActorUnitConcreteAttributeType.MAGIC]; } } public int m_Defence { get { return m_attrDict[ActorUnitConcreteAttributeType.DEFENCE]; } } public int m_Resistance { get { return m_attrDict[ActorUnitConcreteAttributeType.RESISTANCE]; } } public int m_Tenacity { get { return m_attrDict[ActorUnitConcreteAttributeType.TENACITY]; } } public int m_Speed { get { return m_attrDict[ActorUnitConcreteAttributeType.SPEED]; } } public int m_CriticalRate { get { return m_attrDict[ActorUnitConcreteAttributeType.CRITICAL_RATE]; } } public int m_CriticalBonus { get { return m_attrDict[ActorUnitConcreteAttributeType.CRITICAL_BONUS]; } } public int m_HitRate { get { return m_attrDict[ActorUnitConcreteAttributeType.HIT_RATE]; } } public int m_DodgeRate { get { return m_attrDict[ActorUnitConcreteAttributeType.DODGE_RATE]; } } public int m_LifeSteal { get { return m_attrDict[ActorUnitConcreteAttributeType.LIFE_STEAL]; } } public int m_PhysicsVulernability { get { return m_attrDict[ActorUnitConcreteAttributeType.PHYSICS_VULERNABILITY]; } } public int m_MagicVulernability { get { return m_attrDict[ActorUnitConcreteAttributeType.MAGIC_VULERNABILITY]; } } public int m_DamageReduction { get { return m_attrDict[ActorUnitConcreteAttributeType.DAMAGE_REDUCTION]; } } private DE_Unit (ValueTuple<ActorUnitConcreteAttributeType, int>[] attrArr) { var conAttrDict = new Dictionary<ActorUnitConcreteAttributeType, int> (); var attrTypeArr = Enum.GetValues (typeof (ActorUnitConcreteAttributeType)); foreach (var attrType in attrTypeArr) conAttrDict.Add ((ActorUnitConcreteAttributeType) attrType, 0); foreach (var item in attrArr) conAttrDict[item.Item1] = item.Item2; m_attrDict = conAttrDict; } public DE_Unit (DO_Monster monster) : this (monster.m_attrArr) { } public DE_Unit (DO_Character charDo) : this (charDo.m_concreteAttributeArr) { } } class DE_MonsterData { public readonly short m_monsterId; public readonly MonsterType m_monsterType; public readonly short m_level; public readonly IReadOnlyList<ValueTuple<short, short>> m_skillIdAndLevelList; public readonly IReadOnlyList<short> m_dropItemIdList; public DE_MonsterData (DO_Monster monsterDo) { m_monsterId = monsterDo.m_monsterId; m_monsterType = monsterDo.m_monsterType; m_level = monsterDo.m_level; m_skillIdAndLevelList = new List<ValueTuple<short, short>> (monsterDo.m_skillIdAndLevelArr); m_dropItemIdList = new List<short> (monsterDo.m_dropItemIdArr); } } class DE_CharacterData { public readonly short m_level; public readonly int m_upgradeExperienceInNeed; public readonly IReadOnlyList<ValueTuple<ActorUnitMainAttributeType, int>> m_mainAttributeList; public readonly short m_mainAttributePointNum; public DE_CharacterData (DO_Character charDo) { m_level = charDo.m_level; m_upgradeExperienceInNeed = charDo.m_upgradeExperienceInNeed; m_mainAttributeList = new List<ValueTuple<ActorUnitMainAttributeType, int>> (charDo.m_mainAttributeArr); m_mainAttributePointNum = charDo.m_mainAttrPointNumber; } } class DE_Character { public readonly OccupationType m_occupation; public readonly short m_characterMaxLevel; public readonly IReadOnlyList<DE_Unit> m_unitAllLevel; public readonly IReadOnlyList<DE_CharacterData> m_characterDataAllLevel; public DE_Character (OccupationType ocp, short mxLv, IReadOnlyList<DE_Unit> unitAllLv, IReadOnlyList<DE_CharacterData> charDataAllLv) { m_occupation = ocp; m_characterMaxLevel = mxLv; m_unitAllLevel = unitAllLv; m_characterDataAllLevel = charDataAllLv; } } class DE_SkillData { public readonly short m_upgradeCharacterLevelInNeed; public readonly long m_upgradeMoneyInNeed; public readonly int m_upgradeMasterlyInNeed; public readonly int m_mpCost; public readonly float m_castFrontTime; public readonly float m_castBackTime; public readonly float m_coolDownTime; public readonly byte m_targetNumber; public readonly float m_castRange; /// <summary> /// 技能伤害判定的范围参数 /// </summary> public readonly IReadOnlyList < (SkillAimParamType, float) > m_damageParamList; public readonly DE_Effect m_skillEffect; public DE_SkillData (DO_SkillData curDo, DO_SkillData nextLvDo, short skId) { m_upgradeCharacterLevelInNeed = nextLvDo.m_upgradeCharacterLevelInNeed; m_upgradeMoneyInNeed = nextLvDo.m_upgradeMoneyInNeed; m_upgradeMasterlyInNeed = nextLvDo.m_upgradeMasterlyInNeed; m_mpCost = curDo.m_mpCost; m_castFrontTime = curDo.m_castFrontTime; m_castBackTime = curDo.m_castBackTime; m_coolDownTime = curDo.m_coolDownTime; m_targetNumber = curDo.m_targetNumber; m_castRange = (float) curDo.m_castRange * 0.01f; var damageParamList = new List < (SkillAimParamType, float) > (curDo.m_damageParamArr.Length); for (int i = 0; i < curDo.m_damageParamArr.Length; i++) damageParamList.Add ((curDo.m_damageParamArr[i].Item1, (float) curDo.m_damageParamArr[i].Item2 * 0.01f)); m_damageParamList = damageParamList; m_skillEffect = new DE_Effect (curDo.m_skillEffect, skId); } } class DE_Skill { public readonly short m_skillId; public readonly short m_skillMaxLevel; public readonly IReadOnlyList<short> m_fatherIdList; public readonly IReadOnlyList<short> m_childrenIdList; public readonly SkillAimType m_skillAimType; public readonly CampType m_targetCamp; /// <summary> /// 0级为未习得 /// </summary> public readonly IReadOnlyList<DE_SkillData> m_skillDataAllLevel; public DE_Skill (DO_Skill skillDo) { m_skillId = skillDo.m_skillId; m_skillMaxLevel = skillDo.m_skillMaxLevel; m_skillAimType = skillDo.m_skillAimType; m_targetCamp = skillDo.m_targetCamp; DE_SkillData[] dataArr = new DE_SkillData[m_skillMaxLevel + 1]; dataArr[0] = new DE_SkillData (skillDo.m_skillDataAllLevel[0], skillDo.m_skillDataAllLevel[0], m_skillId); for (int i = 1; i <= m_skillMaxLevel - 1; i++) dataArr[i] = new DE_SkillData (skillDo.m_skillDataAllLevel[i - 1], skillDo.m_skillDataAllLevel[i], m_skillId); dataArr[m_skillMaxLevel] = new DE_SkillData (skillDo.m_skillDataAllLevel[m_skillMaxLevel - 1], skillDo.m_skillDataAllLevel[m_skillMaxLevel - 1], m_skillId); m_skillDataAllLevel = new List<DE_SkillData> (dataArr); } } class DE_Effect { public readonly EffectType m_type; public readonly float m_hitRate; public readonly float m_criticalRate; public readonly int m_deltaHp; public readonly int m_deltaMp; public readonly IReadOnlyList < (ActorUnitConcreteAttributeType, float) > m_attrBonus; public readonly IReadOnlyList < (short, float, float) > m_statusIdAndValueAndTimeList; public DE_Effect (DO_Effect effectDo, short animId) { m_type = effectDo.m_type; m_hitRate = effectDo.m_hitRate; m_criticalRate = effectDo.m_criticalRate; m_deltaHp = effectDo.m_deltaHp; m_deltaMp = effectDo.m_deltaMp; m_attrBonus = effectDo.m_attributeBonusArr ?? new (ActorUnitConcreteAttributeType, float) [0]; m_statusIdAndValueAndTimeList = new List<ValueTuple<short, float, float>> (effectDo.m_statusIdAndValueAndTimeArr); } } class DE_Status { public readonly short m_id; public readonly StatusType m_type; public readonly bool m_isBuff; public DE_Status (DO_Status sDo) { m_id = sDo.m_statusId; m_type = sDo.m_type; m_isBuff = sDo.m_isBuff; } } class DE_ConcreteAttributeStatus { IReadOnlyList < (ActorUnitConcreteAttributeType, int) > m_conAttrList; public DE_ConcreteAttributeStatus (DO_ConcreteAttributeStatus casDo) { m_conAttrList = new List < (ActorUnitConcreteAttributeType, int) > (casDo.m_conAttrArr); } } class DE_SpecialAttributeStatus { public readonly ActorUnitSpecialAttributeType m_spAttr; public DE_SpecialAttributeStatus (DO_SpecialAttributeStatus sasDo) { m_spAttr = sasDo.m_spAttr; } } class DE_MallItem { public readonly short m_id; public readonly long m_virtualCyPrice; public readonly long m_chargeCyPrice; public DE_MallItem (DO_MallItem mallItemDo) { m_id = mallItemDo.m_itemId; m_virtualCyPrice = mallItemDo.m_virtualCyPrice; m_chargeCyPrice = mallItemDo.m_chargeCyPrice; } } class DE_Item { public readonly short m_id; public readonly ItemType m_type; public readonly short m_maxNum; public readonly ItemQuality m_quality; public readonly long m_buyPrice; public readonly long m_sellPrice; public DE_Item (DO_Item itemDo) { m_id = itemDo.m_itemId; m_type = itemDo.m_type; m_maxNum = itemDo.m_maxNum; m_quality = itemDo.m_quality; m_buyPrice = itemDo.m_buyPrice; m_sellPrice = itemDo.m_sellPrice; } public DE_Item () { m_id = -1; m_type = ItemType.EMPTY; m_maxNum = 0; m_quality = ItemQuality.POOR; m_buyPrice = 0; m_sellPrice = 0; } } class DE_ConsumableData { public readonly DE_Effect m_itemEffect; public DE_ConsumableData (DO_Consumable consumDo) { m_itemEffect = new DE_Effect (consumDo.m_effect, (short) (consumDo.m_itemId * 100)); } } class DE_EquipmentData { public readonly OccupationType m_validOccupation; public readonly short m_equipLevelInNeed; public readonly EquipmentPosition m_equipPosition; public readonly IReadOnlyList<ValueTuple<ActorUnitConcreteAttributeType, int>> m_attrList; public readonly float m_attrWave; public DE_EquipmentData (DO_Equipment equipDo) { m_validOccupation = equipDo.m_validOccupation; m_equipLevelInNeed = equipDo.m_equipLevelInNeed; m_equipPosition = equipDo.m_equipPosition; m_attrList = new List<ValueTuple<ActorUnitConcreteAttributeType, int>> (equipDo.m_equipmentAttributeArr); m_attrWave = equipDo.m_attrWave; } } class DE_GemData { public readonly IReadOnlyList < (ActorUnitConcreteAttributeType, int) > m_attrList; public DE_GemData (DO_Gem gemDo) { m_attrList = new List < (ActorUnitConcreteAttributeType, int) > (gemDo.m_equipmentAttributeArr); } } class DE_Mission { public readonly short m_id; public readonly OccupationType m_occupation; public readonly short m_levelInNeed; public readonly IReadOnlyList<short> m_fatherIdList; public readonly IReadOnlyList<short> m_childrenIdList; /// <summary> /// 一个任务有多个目标 /// 一个目标由 目标类型, Id参数, 数值参数 三个变量描述 /// 例: 与Npc交流 Id参数为NpcId 数值参数为1 /// 例: 击杀怪物 Id参数为怪物Id 数值参数为要击杀的怪物数量 /// </summary> public readonly IReadOnlyList < (MissionTargetType, short) > m_targetList; public readonly long m_bonusVirtualCurrency; public readonly int m_bonusExperience; public readonly IReadOnlyList < (short, short) > m_bonusItemIdAndNumList; public DE_Mission (DO_Mission mDo) { m_id = mDo.m_id; m_occupation = mDo.m_missionOccupation; m_levelInNeed = mDo.m_levelInNeed; m_fatherIdList = new List<short> (mDo.m_fatherMissionIdArr); m_childrenIdList = new List<short> (mDo.m_childrenMissionArr); m_targetList = new List<ValueTuple<MissionTargetType, short>> (mDo.m_missionTargetArr); m_bonusVirtualCurrency = mDo.m_bonusMoney; m_bonusExperience = mDo.m_bonusExperience; m_bonusItemIdAndNumList = new List<ValueTuple<short, short>> (mDo.m_bonusItemIdAndNumArr); } } class DE_Title { public readonly IReadOnlyList < (ActorUnitConcreteAttributeType, int) > m_attr; public DE_Title ((ActorUnitConcreteAttributeType, int) [] attrArr) { m_attr = new List < (ActorUnitConcreteAttributeType, int) > (attrArr); } } class DE_MissionTargetKillMonster { public readonly short m_id; public readonly short m_monsterId; public readonly short m_targetNum; public DE_MissionTargetKillMonster (DO_MissionTargetKillMonsterData mtDo) { m_id = mtDo.m_id; m_monsterId = mtDo.m_targetMonsterId; m_targetNum = mtDo.m_targetNum; } } class DE_MissionTargetGainItem { public readonly short m_id; public readonly short m_itemId; public readonly short m_targetNum; public DE_MissionTargetGainItem (DO_MissionTargetGainItemData mtDo) { m_id = mtDo.m_id; m_itemId = mtDo.m_targetItemId; m_targetNum = mtDo.m_targetNum; } } class DE_MissionTargetLevelUpSkill { public readonly short m_id; public readonly short m_skillId; public readonly short m_targetLv; public DE_MissionTargetLevelUpSkill (DO_MissionTargetLevelUpSkillData mtDo) { m_id = mtDo.m_id; m_skillId = mtDo.m_targetLevel; m_targetLv = mtDo.m_targetLevel; } } class DE_MissionTargetChargeAdequately { public readonly short m_id; public readonly int m_targetMoney; public DE_MissionTargetChargeAdequately (DO_MissionTargetChargeAdequatelyData mtDo) { m_id = mtDo.m_id; m_targetMoney = mtDo.m_amount; } } }
49.587662
168
0.679303
[ "MIT" ]
HeBomou/mir-remake-ios-server
DataEntity/DataEntities.cs
15,435
C#