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
sequence | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace BuildXL.Utilities.VmCommandProxy
{
/// <summary>
/// Commands used by VmCommandProxy.
/// </summary>
public static class VmCommands
{
/// <summary>
/// Initialize VM.
/// </summary>
public const string InitializeVm = nameof(InitializeVm);
/// <summary>
/// Run process in VM.
/// </summary>
public const string Run = nameof(Run);
/// <summary>
/// Commands' parameters.
/// </summary>
public static class Params
{
/// <summary>
/// Input JSON file.
/// </summary>
public const string InputJsonFile = nameof(InputJsonFile);
/// <summary>
/// Output JSON file.
/// </summary>
public const string OutputJsonFile = nameof(OutputJsonFile);
}
}
/// <summary>
/// Executable.
/// </summary>
public static class VmExecutable
{
/// <summary>
/// Default relative path.
/// </summary>
public const string DefaultRelativePath = @"tools\VmCommandProxy\tools\VmCommandProxy.exe";
}
/// <summary>
/// Special environment variable for executions in VM.
/// </summary>
public static class VmSpecialEnvironmentVariables
{
/// <summary>
/// Environment variable whose value/presence indicates that the process is running in VM.
/// </summary>
public const string IsInVm = "[BUILDXL]IS_IN_VM";
/// <summary>
/// Environment variable whose value is %TEMP%, and whose presence indicates that the process in VM has relocated temporary folder.
/// </summary>
public const string VmTemp = "[BUILDXL]VM_TEMP";
/// <summary>
/// Environment variable whose value is %TEMP% before it gets relocated, and its presence indicates that the process in VM has relocated temporary folder
/// whose new value is stored in <see cref="VmTemp"/>.
/// </summary>
public const string VmOriginalTemp = "[BUILDXL]VM_ORIGINAL_TEMP";
/// <summary>
/// Property indicating if a process is running in VM.
/// </summary>
public static bool IsRunningInVm => GetFlag(IsInVm);
/// <summary>
/// Property indicating if the process in VM has relocated temporary folder.
/// </summary>
public static bool HasRelocatedTemp => IsRunningInVm && !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(VmTemp));
/// <summary>
/// Prefix for host environment variable.
/// </summary>
public const string HostEnvVarPrefix = "[BUILDXL]VM_HOST_";
/// <summary>
/// Environment variable containing path to the host's user profile, or a redirected one.
/// </summary>
public static readonly string HostUserProfile = $"{HostEnvVarPrefix}USERPROFILE";
/// <summary>
/// Environment variable indicating if the host's user profile is a redirected one.
/// </summary>
public const string HostHasRedirectedUserProfile = "[BUILDXL]IS_VM_HOST_REDIRECTED_USERPROFILE";
/// <summary>
/// Checks if host's user profile has been redirected.
/// </summary>
public static bool IsHostUserProfileRedirected => GetFlag(HostHasRedirectedUserProfile);
private static bool GetFlag(string environmentVariable)
{
string value = Environment.GetEnvironmentVariable(environmentVariable);
if (string.IsNullOrWhiteSpace(value))
{
return false;
}
switch (value.ToLowerInvariant())
{
case "0":
case "false":
return false;
case "1":
case "true":
return true;
default:
return false;
}
}
}
/// <summary>
/// Constants Vm.
/// </summary>
/// <remarks>
/// These constants constitute a kind of contract between BuildXL and VmCommandProxy.
/// </remarks>
public static class VmConstants
{
/// <summary>
/// IO for temporary folder.
/// </summary>
public static class Temp
{
/// <summary>
/// Drive for temporary folder.
/// </summary>
public const string Drive = "T";
/// <summary>
/// Root for temporary folder.
/// </summary>
public static readonly string Root = $@"{Drive}:\BxlTemp";
}
/// <summary>
/// IO relating VMs and their hosts.
/// </summary>
public static class Host
{
/// <summary>
/// Host's (net shared) drive that is net used by VM.
/// </summary>
public const string NetUseDrive = "D";
/// <summary>
/// Host IP address.
/// </summary>
public const string IpAddress = "192.168.0.1";
}
/// <summary>
/// User that runs pips in VM.
/// </summary>
public static class UserProfile
{
/// <summary>
/// The user that runs the pip in the VM is 'Administrator'.
/// </summary>
public const string Name = "Administrator";
/// <summary>
/// User profile path.
/// </summary>
public readonly static string Path = $@"C:\Users\{Name}";
/// <summary>
/// Prefix for ApplicationData special folder.
/// </summary>
public readonly static string AppDataPrefix = $@"{Path}\AppData";
/// <summary>
/// LocalApplicationData special folder.
/// </summary>
public readonly static string LocalAppData = $@"{AppDataPrefix}\Local";
private static Func<string> GetEnvFolderFunc(Environment.SpecialFolder folder) => new Func<string>(() => Environment.GetFolderPath(folder, Environment.SpecialFolderOption.DoNotVerify));
/// <summary>
/// Environment variables related to user profile.
/// </summary>
public readonly static Dictionary<string, (string value, Func<string> toVerify)> Environments = new Dictionary<string, (string, Func<string>)>(StringComparer.OrdinalIgnoreCase)
{
{ "APPDATA", ($@"{AppDataPrefix}\Roaming", GetEnvFolderFunc(Environment.SpecialFolder.ApplicationData)) },
{ "LOCALAPPDATA", (LocalAppData, GetEnvFolderFunc(Environment.SpecialFolder.LocalApplicationData)) },
{ "USERPROFILE", (Path, GetEnvFolderFunc(Environment.SpecialFolder.UserProfile)) },
{ "USERNAME", (Name, null) },
{ "HOMEDRIVE", (System.IO.Path.GetPathRoot(Path).Trim(System.IO.Path.DirectorySeparatorChar), null) },
{ "HOMEPATH", (Path.Substring(2), null) },
{ "INTERNETCACHE" , ($@"{LocalAppData}\Microsoft\Windows\INetCache", GetEnvFolderFunc(Environment.SpecialFolder.InternetCache)) },
{ "INTERNETHISTORY", ($@"{LocalAppData}\Microsoft\Windows\History", GetEnvFolderFunc(Environment.SpecialFolder.History)) },
{ "INETCOOKIES", ($@"{LocalAppData}\Microsoft\Windows\INetCookies", GetEnvFolderFunc(Environment.SpecialFolder.Cookies)) },
{ "LOCALLOW" , ($@"{AppDataPrefix}\LocalLow", new Func<string>(() => GetKnownFolderPath(new Guid("A520A1A4-1780-4FF6-BD18-167343C5AF16")))) },
};
[DllImport("shell32.dll")]
private static extern int SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, IntPtr hToken, out IntPtr pszPath);
private static string GetKnownFolderPath(Guid knownFolderId)
{
IntPtr pszPath = IntPtr.Zero;
try
{
int hr = SHGetKnownFolderPath(knownFolderId, 0, IntPtr.Zero, out pszPath);
if (hr >= 0)
return Marshal.PtrToStringAuto(pszPath);
throw Marshal.GetExceptionForHR(hr);
}
finally
{
if (pszPath != IntPtr.Zero)
Marshal.FreeCoTaskMem(pszPath);
}
}
}
}
}
| 40.655172 | 216 | 0.517282 | [
"MIT"
] | RobJellinghaus/BuildXL | Public/Src/Utilities/Utilities/VmCommandProxy/VmConstants.cs | 9,434 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace IARATesteCotacao.Domain.Entities
{
public class ItensQuotation : EntityBase
{
protected ItensQuotation()
{
}
public ItensQuotation(int itemNumber, Int64 quotationId, int productId, decimal price, int quantity, string manufacturer, string unit)
{
ItemNumber = itemNumber;
QuotationId = quotationId;
ProductId = productId;
Price = price;
Quantity = quantity;
Manufacturer = manufacturer;
Unit = unit;
}
public int ItemNumber { get; protected set; }
public Int64 QuotationId { get; protected set; }
public virtual Quotation Quotation { get; protected set; }
public int ProductId { get; protected set; }
public virtual Product Product { get; protected set; }
public decimal Price { get; protected set; }
public int Quantity { get; protected set; }
public string Manufacturer { get; protected set; }
public string Unit { get; protected set; }
public void Update(int quantity, string manufacturer, string unit)
{
Quantity = quantity;
Manufacturer = manufacturer;
Unit = unit;
}
}
}
| 31.55814 | 142 | 0.598379 | [
"MIT"
] | webersonribeiro/IARATesteCotacao | IARATesteCotacao.Domain/Entities/ItensQuotation.cs | 1,359 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2016-11-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// This is the response object from the DescribeInstanceCreditSpecifications operation.
/// </summary>
public partial class DescribeInstanceCreditSpecificationsResponse : AmazonWebServiceResponse
{
private List<InstanceCreditSpecification> _instanceCreditSpecifications = new List<InstanceCreditSpecification>();
private string _nextToken;
/// <summary>
/// Gets and sets the property InstanceCreditSpecifications.
/// <para>
/// Information about the credit option for CPU usage of an instance.
/// </para>
/// </summary>
public List<InstanceCreditSpecification> InstanceCreditSpecifications
{
get { return this._instanceCreditSpecifications; }
set { this._instanceCreditSpecifications = value; }
}
// Check to see if InstanceCreditSpecifications property is set
internal bool IsSetInstanceCreditSpecifications()
{
return this._instanceCreditSpecifications != null && this._instanceCreditSpecifications.Count > 0;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// The token to use to retrieve the next page of results. This value is <code>null</code>
/// when there are no more results to return.
/// </para>
/// </summary>
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
}
} | 34.922078 | 123 | 0.643362 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/EC2/Generated/Model/DescribeInstanceCreditSpecificationsResponse.cs | 2,689 | C# |
using $ext_projectname$.Domain.Entities;
namespace $safeprojectname$.Interfaces.Services
{
public interface IPersonSampleService : IService<PersonSample>
{
}
}
| 20.222222 | 67 | 0.71978 | [
"MIT"
] | fabioerter/Sample | GAB.Default.Domain.Core/Interfaces/Services/IPersonSampleService.cs | 184 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Routing;
using Nop.Core;
using Nop.Core.Domain.Directory;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Payments;
using Nop.Core.Domain.Shipping;
using Nop.Core.Plugins;
using Nop.Plugin.Payments.PayPalStandard.Controllers;
using Nop.Services.Configuration;
using Nop.Services.Directory;
using Nop.Services.Localization;
using Nop.Services.Orders;
using Nop.Services.Payments;
using Nop.Services.Tax;
namespace Nop.Plugin.Payments.PayPalStandard
{
/// <summary>
/// PayPalStandard payment processor
/// </summary>
public class PayPalStandardPaymentProcessor : BasePlugin, IPaymentMethod
{
#region Fields
private readonly PayPalStandardPaymentSettings _paypalStandardPaymentSettings;
private readonly ISettingService _settingService;
private readonly ICurrencyService _currencyService;
private readonly CurrencySettings _currencySettings;
private readonly IWebHelper _webHelper;
private readonly ICheckoutAttributeParser _checkoutAttributeParser;
private readonly ITaxService _taxService;
private readonly IOrderTotalCalculationService _orderTotalCalculationService;
private readonly HttpContextBase _httpContext;
#endregion
#region Ctor
public PayPalStandardPaymentProcessor(PayPalStandardPaymentSettings paypalStandardPaymentSettings,
ISettingService settingService, ICurrencyService currencyService,
CurrencySettings currencySettings, IWebHelper webHelper,
ICheckoutAttributeParser checkoutAttributeParser, ITaxService taxService,
IOrderTotalCalculationService orderTotalCalculationService, HttpContextBase httpContext)
{
this._paypalStandardPaymentSettings = paypalStandardPaymentSettings;
this._settingService = settingService;
this._currencyService = currencyService;
this._currencySettings = currencySettings;
this._webHelper = webHelper;
this._checkoutAttributeParser = checkoutAttributeParser;
this._taxService = taxService;
this._orderTotalCalculationService = orderTotalCalculationService;
this._httpContext = httpContext;
}
#endregion
#region Utilities
/// <summary>
/// Gets Paypal URL
/// </summary>
/// <returns></returns>
private string GetPaypalUrl()
{
return _paypalStandardPaymentSettings.UseSandbox ? "https://www.sandbox.paypal.com/us/cgi-bin/webscr" :
"https://www.paypal.com/us/cgi-bin/webscr";
}
/// <summary>
/// Gets PDT details
/// </summary>
/// <param name="tx">TX</param>
/// <param name="values">Values</param>
/// <param name="response">Response</param>
/// <returns>Result</returns>
public bool GetPdtDetails(string tx, out Dictionary<string, string> values, out string response)
{
var req = (HttpWebRequest)WebRequest.Create(GetPaypalUrl());
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
//now PayPal requires user-agent. otherwise, we can get 403 error
req.UserAgent = HttpContext.Current.Request.UserAgent;
string formContent = string.Format("cmd=_notify-synch&at={0}&tx={1}", _paypalStandardPaymentSettings.PdtToken, tx);
req.ContentLength = formContent.Length;
using (var sw = new StreamWriter(req.GetRequestStream(), Encoding.ASCII))
sw.Write(formContent);
using (var sr = new StreamReader(req.GetResponse().GetResponseStream()))
response = HttpUtility.UrlDecode(sr.ReadToEnd());
values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
bool firstLine = true, success = false;
foreach (string l in response.Split('\n'))
{
string line = l.Trim();
if (firstLine)
{
success = line.Equals("SUCCESS", StringComparison.OrdinalIgnoreCase);
firstLine = false;
}
else
{
int equalPox = line.IndexOf('=');
if (equalPox >= 0)
values.Add(line.Substring(0, equalPox), line.Substring(equalPox + 1));
}
}
return success;
}
/// <summary>
/// Verifies IPN
/// </summary>
/// <param name="formString">Form string</param>
/// <param name="values">Values</param>
/// <returns>Result</returns>
public bool VerifyIpn(string formString, out Dictionary<string, string> values)
{
var req = (HttpWebRequest)WebRequest.Create(GetPaypalUrl());
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
//now PayPal requires user-agent. otherwise, we can get 403 error
req.UserAgent = HttpContext.Current.Request.UserAgent;
string formContent = string.Format("{0}&cmd=_notify-validate", formString);
req.ContentLength = formContent.Length;
using (var sw = new StreamWriter(req.GetRequestStream(), Encoding.ASCII))
{
sw.Write(formContent);
}
string response;
using (var sr = new StreamReader(req.GetResponse().GetResponseStream()))
{
response = HttpUtility.UrlDecode(sr.ReadToEnd());
}
bool success = response.Trim().Equals("VERIFIED", StringComparison.OrdinalIgnoreCase);
values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (string l in formString.Split('&'))
{
string line = l.Trim();
int equalPox = line.IndexOf('=');
if (equalPox >= 0)
values.Add(line.Substring(0, equalPox), line.Substring(equalPox + 1));
}
return success;
}
#endregion
#region Methods
/// <summary>
/// Process a payment
/// </summary>
/// <param name="processPaymentRequest">Payment info required for an order processing</param>
/// <returns>Process payment result</returns>
public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
{
var result = new ProcessPaymentResult();
result.NewPaymentStatus = PaymentStatus.Pending;
return result;
}
/// <summary>
/// Post process payment (used by payment gateways that require redirecting to a third-party URL)
/// </summary>
/// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
{
var builder = new StringBuilder();
builder.Append(GetPaypalUrl());
var cmd =_paypalStandardPaymentSettings.PassProductNamesAndTotals
? "_cart"
: "_xclick";
builder.AppendFormat("?cmd={0}&business={1}", cmd, HttpUtility.UrlEncode(_paypalStandardPaymentSettings.BusinessEmail));
if (_paypalStandardPaymentSettings.PassProductNamesAndTotals)
{
builder.AppendFormat("&upload=1");
//get the items in the cart
decimal cartTotal = decimal.Zero;
var cartItems = postProcessPaymentRequest.Order.OrderItems;
int x = 1;
foreach (var item in cartItems)
{
var unitPriceExclTax = item.UnitPriceExclTax;
var priceExclTax = item.PriceExclTax;
//round
var unitPriceExclTaxRounded = Math.Round(unitPriceExclTax, 2);
builder.AppendFormat("&item_name_" + x + "={0}", HttpUtility.UrlEncode(item.Product.Name));
builder.AppendFormat("&amount_" + x + "={0}", unitPriceExclTaxRounded.ToString("0.00", CultureInfo.InvariantCulture));
builder.AppendFormat("&quantity_" + x + "={0}", item.Quantity);
x++;
cartTotal += priceExclTax;
}
//the checkout attributes that have a dollar value and send them to Paypal as items to be paid for
var attributeValues = _checkoutAttributeParser.ParseCheckoutAttributeValues(postProcessPaymentRequest.Order.CheckoutAttributesXml);
foreach (var val in attributeValues)
{
var attPrice = _taxService.GetCheckoutAttributePrice(val, false, postProcessPaymentRequest.Order.Customer);
//round
var attPriceRounded = Math.Round(attPrice, 2);
if (attPrice > decimal.Zero) //if it has a price
{
var attribute = val.CheckoutAttribute;
if (attribute != null)
{
var attName = attribute.Name; //set the name
builder.AppendFormat("&item_name_" + x + "={0}", HttpUtility.UrlEncode(attName)); //name
builder.AppendFormat("&amount_" + x + "={0}", attPriceRounded.ToString("0.00", CultureInfo.InvariantCulture)); //amount
builder.AppendFormat("&quantity_" + x + "={0}", 1); //quantity
x++;
cartTotal += attPrice;
}
}
}
//order totals
//shipping
var orderShippingExclTax = postProcessPaymentRequest.Order.OrderShippingExclTax;
var orderShippingExclTaxRounded = Math.Round(orderShippingExclTax, 2);
if (orderShippingExclTax > decimal.Zero)
{
builder.AppendFormat("&item_name_" + x + "={0}", "Shipping fee");
builder.AppendFormat("&amount_" + x + "={0}", orderShippingExclTaxRounded.ToString("0.00", CultureInfo.InvariantCulture));
builder.AppendFormat("&quantity_" + x + "={0}", 1);
x++;
cartTotal += orderShippingExclTax;
}
//payment method additional fee
var paymentMethodAdditionalFeeExclTax = postProcessPaymentRequest.Order.PaymentMethodAdditionalFeeExclTax;
var paymentMethodAdditionalFeeExclTaxRounded = Math.Round(paymentMethodAdditionalFeeExclTax, 2);
if (paymentMethodAdditionalFeeExclTax > decimal.Zero)
{
builder.AppendFormat("&item_name_" + x + "={0}", "Payment method fee");
builder.AppendFormat("&amount_" + x + "={0}", paymentMethodAdditionalFeeExclTaxRounded.ToString("0.00", CultureInfo.InvariantCulture));
builder.AppendFormat("&quantity_" + x + "={0}", 1);
x++;
cartTotal += paymentMethodAdditionalFeeExclTax;
}
//tax
var orderTax = postProcessPaymentRequest.Order.OrderTax;
var orderTaxRounded = Math.Round(orderTax, 2);
if (orderTax > decimal.Zero)
{
//builder.AppendFormat("&tax_1={0}", orderTax.ToString("0.00", CultureInfo.InvariantCulture));
//add tax as item
builder.AppendFormat("&item_name_" + x + "={0}", HttpUtility.UrlEncode("Sales Tax")); //name
builder.AppendFormat("&amount_" + x + "={0}", orderTaxRounded.ToString("0.00", CultureInfo.InvariantCulture)); //amount
builder.AppendFormat("&quantity_" + x + "={0}", 1); //quantity
cartTotal += orderTax;
x++;
}
if (cartTotal > postProcessPaymentRequest.Order.OrderTotal)
{
/* Take the difference between what the order total is and what it should be and use that as the "discount".
* The difference equals the amount of the gift card and/or reward points used.
*/
decimal discountTotal = cartTotal - postProcessPaymentRequest.Order.OrderTotal;
discountTotal = Math.Round(discountTotal, 2);
//gift card or rewared point amount applied to cart in nopCommerce - shows in Paypal as "discount"
builder.AppendFormat("&discount_amount_cart={0}", discountTotal.ToString("0.00", CultureInfo.InvariantCulture));
}
}
else
{
//pass order total
builder.AppendFormat("&item_name=Order Number {0}", postProcessPaymentRequest.Order.Id);
var orderTotal = Math.Round(postProcessPaymentRequest.Order.OrderTotal, 2);
builder.AppendFormat("&amount={0}", orderTotal.ToString("0.00", CultureInfo.InvariantCulture));
}
builder.AppendFormat("&custom={0}", postProcessPaymentRequest.Order.OrderGuid);
builder.AppendFormat("&charset={0}", "utf-8");
builder.Append(string.Format("&no_note=1¤cy_code={0}", HttpUtility.UrlEncode(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode)));
builder.AppendFormat("&invoice={0}", postProcessPaymentRequest.Order.Id);
builder.AppendFormat("&rm=2", new object[0]);
if (postProcessPaymentRequest.Order.ShippingStatus != ShippingStatus.ShippingNotRequired)
builder.AppendFormat("&no_shipping=2", new object[0]);
else
builder.AppendFormat("&no_shipping=1", new object[0]);
string returnUrl = _webHelper.GetStoreLocation(false) + "Plugins/PaymentPayPalStandard/PDTHandler";
string cancelReturnUrl = _webHelper.GetStoreLocation(false) + "Plugins/PaymentPayPalStandard/CancelOrder";
builder.AppendFormat("&return={0}&cancel_return={1}", HttpUtility.UrlEncode(returnUrl), HttpUtility.UrlEncode(cancelReturnUrl));
//Instant Payment Notification (server to server message)
if (_paypalStandardPaymentSettings.EnableIpn)
{
string ipnUrl;
if (String.IsNullOrWhiteSpace(_paypalStandardPaymentSettings.IpnUrl))
ipnUrl = _webHelper.GetStoreLocation(false) + "Plugins/PaymentPayPalStandard/IPNHandler";
else
ipnUrl = _paypalStandardPaymentSettings.IpnUrl;
builder.AppendFormat("¬ify_url={0}", ipnUrl);
}
//address
builder.AppendFormat("&address_override={0}", _paypalStandardPaymentSettings.AddressOverride ? "1" : "0");
builder.AppendFormat("&first_name={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.FirstName));
builder.AppendFormat("&last_name={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.LastName));
builder.AppendFormat("&address1={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.Address1));
builder.AppendFormat("&address2={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.Address2));
builder.AppendFormat("&city={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.City));
//if (!String.IsNullOrEmpty(postProcessPaymentRequest.Order.BillingAddress.PhoneNumber))
//{
// //strip out all non-digit characters from phone number;
// string billingPhoneNumber = System.Text.RegularExpressions.Regex.Replace(postProcessPaymentRequest.Order.BillingAddress.PhoneNumber, @"\D", string.Empty);
// if (billingPhoneNumber.Length >= 10)
// {
// builder.AppendFormat("&night_phone_a={0}", HttpUtility.UrlEncode(billingPhoneNumber.Substring(0, 3)));
// builder.AppendFormat("&night_phone_b={0}", HttpUtility.UrlEncode(billingPhoneNumber.Substring(3, 3)));
// builder.AppendFormat("&night_phone_c={0}", HttpUtility.UrlEncode(billingPhoneNumber.Substring(6, 4)));
// }
//}
if (postProcessPaymentRequest.Order.BillingAddress.StateProvince != null)
builder.AppendFormat("&state={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.StateProvince.Abbreviation));
else
builder.AppendFormat("&state={0}", "");
if (postProcessPaymentRequest.Order.BillingAddress.Country != null)
builder.AppendFormat("&country={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.Country.TwoLetterIsoCode));
else
builder.AppendFormat("&country={0}", "");
builder.AppendFormat("&zip={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.ZipPostalCode));
builder.AppendFormat("&email={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.Email));
_httpContext.Response.Redirect(builder.ToString());
}
/// <summary>
/// Returns a value indicating whether payment method should be hidden during checkout
/// </summary>
/// <param name="cart">Shoping cart</param>
/// <returns>true - hide; false - display.</returns>
public bool HidePaymentMethod(IList<ShoppingCartItem> cart)
{
//you can put any logic here
//for example, hide this payment method if all products in the cart are downloadable
//or hide this payment method if current customer is from certain country
return false;
}
/// <summary>
/// Gets additional handling fee
/// </summary>
/// <param name="cart">Shoping cart</param>
/// <returns>Additional handling fee</returns>
public decimal GetAdditionalHandlingFee(IList<ShoppingCartItem> cart)
{
var result = this.CalculateAdditionalFee(_orderTotalCalculationService, cart,
_paypalStandardPaymentSettings.AdditionalFee, _paypalStandardPaymentSettings.AdditionalFeePercentage);
return result;
}
/// <summary>
/// Captures payment
/// </summary>
/// <param name="capturePaymentRequest">Capture payment request</param>
/// <returns>Capture payment result</returns>
public CapturePaymentResult Capture(CapturePaymentRequest capturePaymentRequest)
{
var result = new CapturePaymentResult();
result.AddError("Capture method not supported");
return result;
}
/// <summary>
/// Refunds a payment
/// </summary>
/// <param name="refundPaymentRequest">Request</param>
/// <returns>Result</returns>
public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest)
{
var result = new RefundPaymentResult();
result.AddError("Refund method not supported");
return result;
}
/// <summary>
/// Voids a payment
/// </summary>
/// <param name="voidPaymentRequest">Request</param>
/// <returns>Result</returns>
public VoidPaymentResult Void(VoidPaymentRequest voidPaymentRequest)
{
var result = new VoidPaymentResult();
result.AddError("Void method not supported");
return result;
}
/// <summary>
/// Process recurring payment
/// </summary>
/// <param name="processPaymentRequest">Payment info required for an order processing</param>
/// <returns>Process payment result</returns>
public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
{
var result = new ProcessPaymentResult();
result.AddError("Recurring payment not supported");
return result;
}
/// <summary>
/// Cancels a recurring payment
/// </summary>
/// <param name="cancelPaymentRequest">Request</param>
/// <returns>Result</returns>
public CancelRecurringPaymentResult CancelRecurringPayment(CancelRecurringPaymentRequest cancelPaymentRequest)
{
var result = new CancelRecurringPaymentResult();
result.AddError("Recurring payment not supported");
return result;
}
/// <summary>
/// Gets a value indicating whether customers can complete a payment after order is placed but not completed (for redirection payment methods)
/// </summary>
/// <param name="order">Order</param>
/// <returns>Result</returns>
public bool CanRePostProcessPayment(Order order)
{
if (order == null)
throw new ArgumentNullException("order");
//let's ensure that at least 5 seconds passed after order is placed
//P.S. there's no any particular reason for that. we just do it
if ((DateTime.UtcNow - order.CreatedOnUtc).TotalSeconds < 5)
return false;
return true;
}
/// <summary>
/// Gets a route for provider configuration
/// </summary>
/// <param name="actionName">Action name</param>
/// <param name="controllerName">Controller name</param>
/// <param name="routeValues">Route values</param>
public void GetConfigurationRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues)
{
actionName = "Configure";
controllerName = "PaymentPayPalStandard";
routeValues = new RouteValueDictionary { { "Namespaces", "Nop.Plugin.Payments.PayPalStandard.Controllers" }, { "area", null } };
}
/// <summary>
/// Gets a route for payment info
/// </summary>
/// <param name="actionName">Action name</param>
/// <param name="controllerName">Controller name</param>
/// <param name="routeValues">Route values</param>
public void GetPaymentInfoRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues)
{
actionName = "PaymentInfo";
controllerName = "PaymentPayPalStandard";
routeValues = new RouteValueDictionary { { "Namespaces", "Nop.Plugin.Payments.PayPalStandard.Controllers" }, { "area", null } };
}
public Type GetControllerType()
{
return typeof(PaymentPayPalStandardController);
}
public override void Install()
{
//settings
var settings = new PayPalStandardPaymentSettings
{
UseSandbox = true,
BusinessEmail = "[email protected]",
PdtToken= "Your PDT token here...",
PdtValidateOrderTotal = true,
EnableIpn = true,
AddressOverride = true,
};
_settingService.SaveSetting(settings);
//locales
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.RedirectionTip", "You will be redirected to PayPal site to complete the order.");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.UseSandbox", "Use Sandbox");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.UseSandbox.Hint", "Check to enable Sandbox (testing environment).");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.BusinessEmail", "Business Email");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.BusinessEmail.Hint", "Specify your PayPal business email.");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.PDTToken", "PDT Identity Token");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.PDTToken.Hint", "Specify PDT identity token");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.PDTValidateOrderTotal", "PDT. Validate order total");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.PDTValidateOrderTotal.Hint", "Check if PDT handler should validate order totals.");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.AdditionalFee", "Additional fee");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.AdditionalFee.Hint", "Enter additional fee to charge your customers.");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.AdditionalFeePercentage", "Additional fee. Use percentage");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.AdditionalFeePercentage.Hint", "Determines whether to apply a percentage additional fee to the order total. If not enabled, a fixed value is used.");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.PassProductNamesAndTotals", "Pass product names and order totals to PayPal");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.PassProductNamesAndTotals.Hint", "Check if product names and order totals should be passed to PayPal.");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.EnableIpn", "Enable IPN (Instant Payment Notification)");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.EnableIpn.Hint", "Check if IPN is enabled.");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.EnableIpn.Hint2", "Leave blank to use the default IPN handler URL.");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.IpnUrl", "IPN Handler");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.IpnUrl.Hint", "Specify IPN Handler.");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.AddressOverride", "Address override");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.AddressOverride.Hint", "For people who already have PayPal accounts and whom you already prompted for a shipping address before they choose to pay with PayPal, you can use the entered address instead of the address the person has stored with PayPal.");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.ReturnFromPayPalWithoutPaymentRedirectsToOrderDetailsPage", "Return to order details page");
this.AddOrUpdatePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.ReturnFromPayPalWithoutPaymentRedirectsToOrderDetailsPage.Hint", "Enable if a customer should be redirected to the order details page when he clicks \"return to store\" link on PayPal site WITHOUT completing a payment");
base.Install();
}
public override void Uninstall()
{
//settings
_settingService.DeleteSetting<PayPalStandardPaymentSettings>();
//locales
this.DeletePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.RedirectionTip");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.UseSandbox");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.UseSandbox.Hint");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.BusinessEmail");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.BusinessEmail.Hint");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.PDTToken");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.PDTToken.Hint");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.PDTValidateOrderTotal");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.PDTValidateOrderTotal.Hint");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.AdditionalFee");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.AdditionalFee.Hint");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.AdditionalFeePercentage");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.AdditionalFeePercentage.Hint");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.PassProductNamesAndTotals");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.PassProductNamesAndTotals.Hint");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.EnableIpn");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.EnableIpn.Hint");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.EnableIpn.Hint2");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.IpnUrl");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.IpnUrl.Hint");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.AddressOverride");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.AddressOverride.Hint");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.ReturnFromPayPalWithoutPaymentRedirectsToOrderDetailsPage");
this.DeletePluginLocaleResource("Plugins.Payments.PayPalStandard.Fields.ReturnFromPayPalWithoutPaymentRedirectsToOrderDetailsPage.Hint");
base.Uninstall();
}
#endregion
#region Properties
/// <summary>
/// Gets a value indicating whether capture is supported
/// </summary>
public bool SupportCapture
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether partial refund is supported
/// </summary>
public bool SupportPartiallyRefund
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether refund is supported
/// </summary>
public bool SupportRefund
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether void is supported
/// </summary>
public bool SupportVoid
{
get
{
return false;
}
}
/// <summary>
/// Gets a recurring payment type of payment method
/// </summary>
public RecurringPaymentType RecurringPaymentType
{
get
{
return RecurringPaymentType.NotSupported;
}
}
/// <summary>
/// Gets a payment method type
/// </summary>
public PaymentMethodType PaymentMethodType
{
get
{
return PaymentMethodType.Redirection;
}
}
/// <summary>
/// Gets a value indicating whether we should display a payment information page for this plugin
/// </summary>
public bool SkipPaymentInfo
{
get
{
return false;
}
}
#endregion
}
}
| 50.47907 | 341 | 0.630578 | [
"MIT"
] | andri0331/cetaku | Plugins/Nop.Plugin.Payments.PayPalStandard/PayPalStandardPaymentProcessor.cs | 32,559 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace MiniPay.App.User
{
public sealed class DefaultUserRoles : IEnumerable<UserRoles>
{
public IEnumerator<UserRoles> GetEnumerator()
{
yield return UserRoles.Basic;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public static implicit operator HashSet<UserRoles>(DefaultUserRoles roles)
{
return roles.ToHashSet();
}
}
}
| 22.12 | 82 | 0.62387 | [
"MIT"
] | SilasReinagel/MiniPay | src/MiniPay.App/User/Roles/DefaultUserRoles.cs | 555 | C# |
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace RfpProxyLib.Messages
{
public enum SubscriptionType
{
/// <summary>
/// I will take care and answer with the updated message (may be empty)
/// </summary>
Handle,
/// <summary>
/// don't wait for an answer
/// </summary>
Listen,
/// <summary>
/// client is finished with subscribe
/// </summary>
End
}
public class SubscriptionFilter
{
/// <summary>
/// HEX encoded binary
/// </summary>
[JsonProperty("filter")]
public string Filter { get; set; }
/// <summary>
/// HEX encoded mask, how to match the <see cref="Filter"/>
/// </summary>
[JsonProperty("mask")]
public string Mask { get; set; }
}
public class Subscribe
{
/// <summary>
/// logging or editing
/// </summary>
[JsonProperty("type")]
[JsonConverter(typeof(StringEnumConverter))]
public SubscriptionType Type { get; set; }
/// <summary>
/// lower is better
/// </summary>
[JsonProperty("prio")]
public byte Priority { get; set; }
/// <summary>
/// MAC Address Filter for RFP
/// </summary>
[JsonProperty("rfp")]
public SubscriptionFilter Rfp { get; set; }
/// <summary>
/// Message Filter for the whole message
/// </summary>
[JsonProperty("filter")]
public SubscriptionFilter Message { get; set; }
}
} | 25.265625 | 79 | 0.519481 | [
"MIT"
] | eventphone/rfpproxy | RfpProxyLib/Messages/Subscribe.cs | 1,619 | C# |
using System;
using System.Runtime.InteropServices;
using System.Drawing;
using System.IO;
using Microsoft.Win32;
// From https://stackoverflow.com/questions/1061678/change-desktop-wallpaper-using-code-in-net#comment12939266_1061682
public sealed class Wallpaper
{
Wallpaper() { }
const int SPI_SETDESKWALLPAPER = 20;
const int SPIF_UPDATEINIFILE = 0x01;
const int SPIF_SENDWININICHANGE = 0x02;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
public enum Style : int
{
Tiled,
Centered,
Stretched
}
public static void Set(Uri uri, Style style)
{
System.IO.Stream s = new System.Net.WebClient().OpenRead(uri.ToString());
Image img = System.Drawing.Image.FromStream(s);
string tempPath = Path.Combine(Path.GetTempPath(), "wallpaper.bmp");
img.Save(tempPath, System.Drawing.Imaging.ImageFormat.Bmp);
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);
if (style == Style.Stretched)
{
key.SetValue(@"WallpaperStyle", 2.ToString());
key.SetValue(@"TileWallpaper", 0.ToString());
}
if (style == Style.Centered)
{
key.SetValue(@"WallpaperStyle", 1.ToString());
key.SetValue(@"TileWallpaper", 0.ToString());
}
if (style == Style.Tiled)
{
key.SetValue(@"WallpaperStyle", 1.ToString());
key.SetValue(@"TileWallpaper", 1.ToString());
}
SystemParametersInfo(SPI_SETDESKWALLPAPER,
0,
tempPath,
SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
}
} | 30.465517 | 118 | 0.632711 | [
"MIT"
] | ElTimuro/backgroundr | Wallpaper.cs | 1,767 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using TextMateSharp.Themes;
namespace TextMateSharp.Internal.Themes
{
public class ThemeRaw : Dictionary<string, object>, IRawTheme, IRawThemeSetting, IThemeSetting
{
private static string NAME = "name";
private static string INCLUDE = "include";
private static string SETTINGS = "settings";
private static string TOKEN_COLORS = "tokenColors";
private static string SCOPE = "scope";
private static string FONT_STYLE = "fontStyle";
private static string BACKGROUND = "background";
private static string FOREGROUND = "foreground";
public string GetName()
{
return TryGetObject<string>(NAME);
}
public string GetInclude()
{
return TryGetObject<string>(INCLUDE);
}
public ICollection<IRawThemeSetting> GetSettings()
{
ICollection result = TryGetObject<ICollection>(SETTINGS);
if (result == null)
return null;
return result.Cast<IRawThemeSetting>().ToList();
}
public ICollection<IRawThemeSetting> GetTokenColors()
{
ICollection result = TryGetObject<ICollection>(TOKEN_COLORS);
if (result == null)
return null;
return result.Cast<IRawThemeSetting>().ToList();
}
public object GetScope()
{
return TryGetObject<object>(SCOPE);
}
public IThemeSetting GetSetting()
{
return TryGetObject<IThemeSetting>(SETTINGS);
}
public object GetFontStyle()
{
return TryGetObject<object>(FONT_STYLE);
}
public string GetBackground()
{
return TryGetObject<string>(BACKGROUND);
}
public string GetForeground()
{
return TryGetObject<string>(FOREGROUND);
}
T TryGetObject<T>(string key)
{
object result;
if (!TryGetValue(key, out result))
return default(T);
return (T)result;
}
}
} | 26.27381 | 98 | 0.579067 | [
"MIT"
] | Takoooooo/TextMateSharp | src/TextMateSharp/Internal/Themes/ThemeRaw.cs | 2,207 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Config.Model.V20190108;
namespace Aliyun.Acs.Config.Transform.V20190108
{
public class DescribeConfigRuleResponseUnmarshaller
{
public static DescribeConfigRuleResponse Unmarshall(UnmarshallerContext _ctx)
{
DescribeConfigRuleResponse describeConfigRuleResponse = new DescribeConfigRuleResponse();
describeConfigRuleResponse.HttpResponse = _ctx.HttpResponse;
describeConfigRuleResponse.RequestId = _ctx.StringValue("DescribeConfigRule.RequestId");
DescribeConfigRuleResponse.DescribeConfigRule_ConfigRule configRule = new DescribeConfigRuleResponse.DescribeConfigRule_ConfigRule();
configRule.RiskLevel = _ctx.IntegerValue("DescribeConfigRule.ConfigRule.RiskLevel");
configRule.InputParameters = _ctx.StringValue("DescribeConfigRule.ConfigRule.InputParameters");
configRule.ConfigRuleState = _ctx.StringValue("DescribeConfigRule.ConfigRule.ConfigRuleState");
configRule.MaximumExecutionFrequency = _ctx.StringValue("DescribeConfigRule.ConfigRule.MaximumExecutionFrequency");
configRule.OrganizationRule = _ctx.BooleanValue("DescribeConfigRule.ConfigRule.OrganizationRule");
configRule.ConfigRuleArn = _ctx.StringValue("DescribeConfigRule.ConfigRule.ConfigRuleArn");
configRule.Description = _ctx.StringValue("DescribeConfigRule.ConfigRule.Description");
configRule.ConfigRuleName = _ctx.StringValue("DescribeConfigRule.ConfigRule.ConfigRuleName");
configRule.ConfigRuleId = _ctx.StringValue("DescribeConfigRule.ConfigRule.ConfigRuleId");
configRule.ModifiedTimestamp = _ctx.LongValue("DescribeConfigRule.ConfigRule.ModifiedTimestamp");
configRule.CreateTimestamp = _ctx.LongValue("DescribeConfigRule.ConfigRule.CreateTimestamp");
DescribeConfigRuleResponse.DescribeConfigRule_ConfigRule.DescribeConfigRule_Source source = new DescribeConfigRuleResponse.DescribeConfigRule_ConfigRule.DescribeConfigRule_Source();
source.Owner = _ctx.StringValue("DescribeConfigRule.ConfigRule.Source.Owner");
source.Identifier = _ctx.StringValue("DescribeConfigRule.ConfigRule.Source.Identifier");
List<DescribeConfigRuleResponse.DescribeConfigRule_ConfigRule.DescribeConfigRule_Source.DescribeConfigRule_SourceDetailsItem> source_sourceDetails = new List<DescribeConfigRuleResponse.DescribeConfigRule_ConfigRule.DescribeConfigRule_Source.DescribeConfigRule_SourceDetailsItem>();
for (int i = 0; i < _ctx.Length("DescribeConfigRule.ConfigRule.Source.SourceDetails.Length"); i++) {
DescribeConfigRuleResponse.DescribeConfigRule_ConfigRule.DescribeConfigRule_Source.DescribeConfigRule_SourceDetailsItem sourceDetailsItem = new DescribeConfigRuleResponse.DescribeConfigRule_ConfigRule.DescribeConfigRule_Source.DescribeConfigRule_SourceDetailsItem();
sourceDetailsItem.MessageType = _ctx.StringValue("DescribeConfigRule.ConfigRule.Source.SourceDetails["+ i +"].MessageType");
sourceDetailsItem.EventSource = _ctx.StringValue("DescribeConfigRule.ConfigRule.Source.SourceDetails["+ i +"].EventSource");
sourceDetailsItem.MaximumExecutionFrequency = _ctx.StringValue("DescribeConfigRule.ConfigRule.Source.SourceDetails["+ i +"].MaximumExecutionFrequency");
source_sourceDetails.Add(sourceDetailsItem);
}
source.SourceDetails = source_sourceDetails;
List<DescribeConfigRuleResponse.DescribeConfigRule_ConfigRule.DescribeConfigRule_Source.DescribeConfigRule_SourceConditionsItem> source_sourceConditions = new List<DescribeConfigRuleResponse.DescribeConfigRule_ConfigRule.DescribeConfigRule_Source.DescribeConfigRule_SourceConditionsItem>();
for (int i = 0; i < _ctx.Length("DescribeConfigRule.ConfigRule.Source.SourceConditions.Length"); i++) {
DescribeConfigRuleResponse.DescribeConfigRule_ConfigRule.DescribeConfigRule_Source.DescribeConfigRule_SourceConditionsItem sourceConditionsItem = new DescribeConfigRuleResponse.DescribeConfigRule_ConfigRule.DescribeConfigRule_Source.DescribeConfigRule_SourceConditionsItem();
sourceConditionsItem.DesiredValue = _ctx.StringValue("DescribeConfigRule.ConfigRule.Source.SourceConditions["+ i +"].DesiredValue");
sourceConditionsItem.Required = _ctx.BooleanValue("DescribeConfigRule.ConfigRule.Source.SourceConditions["+ i +"].Required");
sourceConditionsItem.Tips = _ctx.StringValue("DescribeConfigRule.ConfigRule.Source.SourceConditions["+ i +"].Tips");
sourceConditionsItem._Operator = _ctx.StringValue("DescribeConfigRule.ConfigRule.Source.SourceConditions["+ i +"].Operator");
sourceConditionsItem.Name = _ctx.StringValue("DescribeConfigRule.ConfigRule.Source.SourceConditions["+ i +"].Name");
sourceConditionsItem.SelectPath = _ctx.StringValue("DescribeConfigRule.ConfigRule.Source.SourceConditions["+ i +"].SelectPath");
source_sourceConditions.Add(sourceConditionsItem);
}
source.SourceConditions = source_sourceConditions;
configRule.Source = source;
DescribeConfigRuleResponse.DescribeConfigRule_ConfigRule.DescribeConfigRule_ManagedRule managedRule = new DescribeConfigRuleResponse.DescribeConfigRule_ConfigRule.DescribeConfigRule_ManagedRule();
managedRule.HelpUrl = _ctx.StringValue("DescribeConfigRule.ConfigRule.ManagedRule.HelpUrl");
managedRule.Description = _ctx.StringValue("DescribeConfigRule.ConfigRule.ManagedRule.Description");
managedRule.Identifier = _ctx.StringValue("DescribeConfigRule.ConfigRule.ManagedRule.Identifier");
managedRule.OptionalInputParameterDetails = _ctx.StringValue("DescribeConfigRule.ConfigRule.ManagedRule.OptionalInputParameterDetails");
managedRule.ManagedRuleName = _ctx.StringValue("DescribeConfigRule.ConfigRule.ManagedRule.ManagedRuleName");
managedRule.CompulsoryInputParameterDetails = _ctx.StringValue("DescribeConfigRule.ConfigRule.ManagedRule.CompulsoryInputParameterDetails");
List<string> managedRule_labels = new List<string>();
for (int i = 0; i < _ctx.Length("DescribeConfigRule.ConfigRule.ManagedRule.Labels.Length"); i++) {
managedRule_labels.Add(_ctx.StringValue("DescribeConfigRule.ConfigRule.ManagedRule.Labels["+ i +"]"));
}
managedRule.Labels = managedRule_labels;
List<DescribeConfigRuleResponse.DescribeConfigRule_ConfigRule.DescribeConfigRule_ManagedRule.DescribeConfigRule_SourceDetailsItem2> managedRule_sourceDetails1 = new List<DescribeConfigRuleResponse.DescribeConfigRule_ConfigRule.DescribeConfigRule_ManagedRule.DescribeConfigRule_SourceDetailsItem2>();
for (int i = 0; i < _ctx.Length("DescribeConfigRule.ConfigRule.ManagedRule.SourceDetails.Length"); i++) {
DescribeConfigRuleResponse.DescribeConfigRule_ConfigRule.DescribeConfigRule_ManagedRule.DescribeConfigRule_SourceDetailsItem2 sourceDetailsItem2 = new DescribeConfigRuleResponse.DescribeConfigRule_ConfigRule.DescribeConfigRule_ManagedRule.DescribeConfigRule_SourceDetailsItem2();
sourceDetailsItem2.MessageType = _ctx.StringValue("DescribeConfigRule.ConfigRule.ManagedRule.SourceDetails["+ i +"].MessageType");
sourceDetailsItem2.EventSource = _ctx.StringValue("DescribeConfigRule.ConfigRule.ManagedRule.SourceDetails["+ i +"].EventSource");
sourceDetailsItem2.MaximumExecutionFrequency = _ctx.StringValue("DescribeConfigRule.ConfigRule.ManagedRule.SourceDetails["+ i +"].MaximumExecutionFrequency");
managedRule_sourceDetails1.Add(sourceDetailsItem2);
}
managedRule.SourceDetails1 = managedRule_sourceDetails1;
configRule.ManagedRule = managedRule;
DescribeConfigRuleResponse.DescribeConfigRule_ConfigRule.DescribeConfigRule_CreateBy createBy = new DescribeConfigRuleResponse.DescribeConfigRule_ConfigRule.DescribeConfigRule_CreateBy();
createBy.ConfigRuleSceneId = _ctx.StringValue("DescribeConfigRule.ConfigRule.CreateBy.ConfigRuleSceneId");
createBy.CreatorName = _ctx.StringValue("DescribeConfigRule.ConfigRule.CreateBy.CreatorName");
createBy.CreatorType = _ctx.StringValue("DescribeConfigRule.ConfigRule.CreateBy.CreatorType");
createBy.CreatorId = _ctx.StringValue("DescribeConfigRule.ConfigRule.CreateBy.CreatorId");
createBy.ConfigRuleSceneName = _ctx.StringValue("DescribeConfigRule.ConfigRule.CreateBy.ConfigRuleSceneName");
configRule.CreateBy = createBy;
DescribeConfigRuleResponse.DescribeConfigRule_ConfigRule.DescribeConfigRule_Scope scope = new DescribeConfigRuleResponse.DescribeConfigRule_ConfigRule.DescribeConfigRule_Scope();
scope.ComplianceResourceId = _ctx.StringValue("DescribeConfigRule.ConfigRule.Scope.ComplianceResourceId");
List<string> scope_complianceResourceTypes = new List<string>();
for (int i = 0; i < _ctx.Length("DescribeConfigRule.ConfigRule.Scope.ComplianceResourceTypes.Length"); i++) {
scope_complianceResourceTypes.Add(_ctx.StringValue("DescribeConfigRule.ConfigRule.Scope.ComplianceResourceTypes["+ i +"]"));
}
scope.ComplianceResourceTypes = scope_complianceResourceTypes;
configRule.Scope = scope;
DescribeConfigRuleResponse.DescribeConfigRule_ConfigRule.DescribeConfigRule_ConfigRuleEvaluationStatus configRuleEvaluationStatus = new DescribeConfigRuleResponse.DescribeConfigRule_ConfigRule.DescribeConfigRule_ConfigRuleEvaluationStatus();
configRuleEvaluationStatus.LastErrorCode = _ctx.StringValue("DescribeConfigRule.ConfigRule.ConfigRuleEvaluationStatus.LastErrorCode");
configRuleEvaluationStatus.LastSuccessfulEvaluationTimestamp = _ctx.LongValue("DescribeConfigRule.ConfigRule.ConfigRuleEvaluationStatus.LastSuccessfulEvaluationTimestamp");
configRuleEvaluationStatus.FirstActivatedTimestamp = _ctx.LongValue("DescribeConfigRule.ConfigRule.ConfigRuleEvaluationStatus.FirstActivatedTimestamp");
configRuleEvaluationStatus.FirstEvaluationStarted = _ctx.BooleanValue("DescribeConfigRule.ConfigRule.ConfigRuleEvaluationStatus.FirstEvaluationStarted");
configRuleEvaluationStatus.LastSuccessfulInvocationTimestamp = _ctx.LongValue("DescribeConfigRule.ConfigRule.ConfigRuleEvaluationStatus.LastSuccessfulInvocationTimestamp");
configRuleEvaluationStatus.LastErrorMessage = _ctx.StringValue("DescribeConfigRule.ConfigRule.ConfigRuleEvaluationStatus.LastErrorMessage");
configRuleEvaluationStatus.LastFailedEvaluationTimestamp = _ctx.LongValue("DescribeConfigRule.ConfigRule.ConfigRuleEvaluationStatus.LastFailedEvaluationTimestamp");
configRuleEvaluationStatus.LastFailedInvocationTimestamp = _ctx.LongValue("DescribeConfigRule.ConfigRule.ConfigRuleEvaluationStatus.LastFailedInvocationTimestamp");
configRule.ConfigRuleEvaluationStatus = configRuleEvaluationStatus;
describeConfigRuleResponse.ConfigRule = configRule;
return describeConfigRuleResponse;
}
}
}
| 82.920863 | 303 | 0.831772 | [
"Apache-2.0"
] | pengweiqhca/aliyun-openapi-net-sdk | aliyun-net-sdk-config/Config/Transform/V20190108/DescribeConfigRuleResponseUnmarshaller.cs | 11,526 | C# |
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine.Audio;
using UnityEngine;
public class AudioManager : MonoBehaviour
{
public Sound[] sounds;
// Start is called before the first frame update
void Awake()
{
foreach (Sound s in sounds)
{
s.source = gameObject.AddComponent<AudioSource>();
s.source.clip = s.clip;
s.source.volume = s.volume;
s.source.pitch = s.pitch;
}
}
// Update is called once per frame
public void Play(string name)
{
Sound s = Array.Find(sounds, sound => sound.name == name);
s.source.Play();
}
}
| 21.6875 | 66 | 0.596542 | [
"MIT"
] | Jsinclairisto/Dungeon-Dude | DungeonDude/Assets/Scripts/AudioManager.cs | 696 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace Microsoft.VisualStudio.LiveShare.Razor
{
public sealed class ProjectChangeEventProxyArgs : EventArgs
{
public ProjectChangeEventProxyArgs(ProjectSnapshotHandleProxy older, ProjectSnapshotHandleProxy newer, ProjectProxyChangeKind kind)
{
if (older == null && newer == null)
{
throw new ArgumentException("Both projects cannot be null.");
}
Older = older;
Newer = newer;
Kind = kind;
ProjectFilePath = older?.FilePath ?? newer.FilePath;
}
public ProjectSnapshotHandleProxy Older { get; }
public ProjectSnapshotHandleProxy Newer { get; }
public Uri ProjectFilePath { get; }
public ProjectProxyChangeKind Kind { get; }
}
}
| 29.909091 | 139 | 0.64539 | [
"Apache-2.0"
] | Chatina73/AspNetCore-Tooling | src/Razor/src/Microsoft.VisualStudio.LiveShare.Razor/ProjectChangeEventProxyArgs.cs | 989 | C# |
namespace VTDev.Libraries.CEXEngine.Crypto.Enumeration
{
/// <summary>
/// <para>Key Sizes in bits. Can be cast as Key byte size integers,
/// i.e. (uint sz = KeySizes.K256) is equal to 32.</para>
/// </summary>
public enum KeySizes : int
{
/// <summary>
/// 128 bit Key
/// </summary>
K128 = 16,
/// <summary>
/// 192 bit Key
/// </summary>
K192 = 24,
/// <summary>
/// 256 bit Key
/// </summary>
K256 = 32,
/// <summary>
/// 512 bit Key
/// </summary>
K512 = 64,
/// <summary>
/// 768 bit Key
/// </summary>
K768 = 96,
/// <summary>
/// 1024 bit Key
/// </summary>
K1024 = 128,
/// <summary>
/// 1280 bit Key
/// </summary>
K1280 = 160,
/// <summary>
/// 1536 bit Key
/// </summary>
K1536 = 192,
/// <summary>
/// 1792 bit Key
/// </summary>
K1792 = 224,
/// <summary>
/// 2048 bit Key
/// </summary>
K2048 = 256,
/// <summary>
/// 2304 bit Key
/// </summary>
K2304 = 288,
/// <summary>
/// 2560 bit Key
/// </summary>
K2560 = 320,
}
}
| 22.915254 | 72 | 0.39645 | [
"MIT"
] | Felandil/Chiota | Chiota/CEXEngine/Crypto/Enumeration/KeySizes.cs | 1,354 | C# |
using masz.data;
using masz.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.CookiePolicy;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace masz.Services
{
public class IdentityManager : IIdentityManager
{
private Dictionary<string, Identity> identities = new Dictionary<string, Identity>();
private readonly ILogger<IdentityManager> logger;
private readonly IDatabase context;
private readonly IOptions<InternalConfig> config;
private readonly IDiscordAPIInterface discord;
public IdentityManager() { }
public IdentityManager(ILogger<IdentityManager> logger, IOptions<InternalConfig> config, IDiscordAPIInterface discord, IDatabase context)
{
this.logger = logger;
this.config = config;
this.discord = discord;
this.context = context;
}
private async Task RegisterNewIdentity(HttpContext httpContext)
{
logger.LogInformation("Registering new Identity.");
string key = httpContext.Request.Cookies["masz_access_token"];
string token = await httpContext.GetTokenAsync("access_token");
if (identities.ContainsKey(key))
{
identities.Remove(key);
}
Identity identity = new Identity(token, discord);
identities[key] = identity;
logger.LogInformation("New identity registered.");
}
public async Task<Identity> GetIdentity(HttpContext httpContext)
{
logger.LogInformation("Providing identity.");
string key = httpContext.Request.Cookies["masz_access_token"];
string token = await httpContext.GetTokenAsync("access_token");
if (identities.ContainsKey(key))
{
Identity identity = identities[key];
if (identity.ValidUntil >= DateTime.Now)
{
logger.LogInformation("Returning identity.");
return identity;
}
}
logger.LogInformation("Identity not registered yet or invalid. Creating new one.");
await RegisterNewIdentity(httpContext);
if (identities.ContainsKey(key))
{
Identity identity = identities[key];
if (identity.ValidUntil >= DateTime.Now)
{
logger.LogInformation("Returning identity.");
return identity;
}
}
logger.LogInformation("Identity is still null or invalid. Returning null.");
return null;
}
}
}
| 36.291139 | 145 | 0.61458 | [
"MIT"
] | matrix2113/discord-masz | backend/masz/Services/Implementations/IdentityManager.cs | 2,869 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110
{
using static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Extensions;
/// <summary>Reverse replication input.</summary>
public partial class ReverseReplicationInput :
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IReverseReplicationInput,
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IReverseReplicationInputInternal
{
/// <summary>Failover direction.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Inlined)]
public string FailoverDirection { get => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IReverseReplicationInputPropertiesInternal)Property).FailoverDirection; set => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IReverseReplicationInputPropertiesInternal)Property).FailoverDirection = value ?? null; }
/// <summary>Internal Acessors for Property</summary>
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IReverseReplicationInputProperties Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IReverseReplicationInputInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.ReverseReplicationInputProperties()); set { {_property = value;} } }
/// <summary>Internal Acessors for ProviderSpecificDetail</summary>
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IReverseReplicationProviderSpecificInput Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IReverseReplicationInputInternal.ProviderSpecificDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IReverseReplicationInputPropertiesInternal)Property).ProviderSpecificDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IReverseReplicationInputPropertiesInternal)Property).ProviderSpecificDetail = value; }
/// <summary>Backing field for <see cref="Property" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IReverseReplicationInputProperties _property;
/// <summary>Reverse replication properties</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
internal Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IReverseReplicationInputProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.ReverseReplicationInputProperties()); set => this._property = value; }
/// <summary>The class type.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Inlined)]
public string ProviderSpecificDetailInstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IReverseReplicationInputPropertiesInternal)Property).ProviderSpecificDetailInstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IReverseReplicationInputPropertiesInternal)Property).ProviderSpecificDetailInstanceType = value ?? null; }
/// <summary>Creates an new <see cref="ReverseReplicationInput" /> instance.</summary>
public ReverseReplicationInput()
{
}
}
/// Reverse replication input.
public partial interface IReverseReplicationInput :
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.IJsonSerializable
{
/// <summary>Failover direction.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Failover direction.",
SerializedName = @"failoverDirection",
PossibleTypes = new [] { typeof(string) })]
string FailoverDirection { get; set; }
/// <summary>The class type.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"The class type.",
SerializedName = @"instanceType",
PossibleTypes = new [] { typeof(string) })]
string ProviderSpecificDetailInstanceType { get; set; }
}
/// Reverse replication input.
internal partial interface IReverseReplicationInputInternal
{
/// <summary>Failover direction.</summary>
string FailoverDirection { get; set; }
/// <summary>Reverse replication properties</summary>
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IReverseReplicationInputProperties Property { get; set; }
/// <summary>Provider specific reverse replication input.</summary>
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IReverseReplicationProviderSpecificInput ProviderSpecificDetail { get; set; }
/// <summary>The class type.</summary>
string ProviderSpecificDetailInstanceType { get; set; }
}
} | 70.405405 | 537 | 0.748177 | [
"MIT"
] | 3quanfeng/azure-powershell | src/Migrate/generated/api/Models/Api20180110/ReverseReplicationInput.cs | 5,137 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("FssJpModLib")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FssJpModLib")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、このアセンブリ内の型は COM コンポーネントから
// 参照できなくなります。COM からこのアセンブリ内の型にアクセスする必要がある場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("69a98b0c-9ce4-4c65-b066-8747fec22650")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// Revision
//
// すべての値を指定するか、次を使用してビルド番号とリビジョン番号を既定に設定できます
// 以下のように '*' を使用します:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 30.297297 | 57 | 0.723461 | [
"MIT"
] | synctam/FssJpModAid | FssJpModLib/Properties/AssemblyInfo.cs | 1,706 | C# |
using Com.QueoFlow.Peanuts.Net.Core.Domain.Users;
namespace Com.QueoFlow.Peanuts.Net.Core.Persistence.Mappings {
public class UserGroupMap : EntityMap<UserGroup> {
protected UserGroupMap() {
Map(financialBrokerPool => financialBrokerPool.AdditionalInformations).Nullable().Length(4000);
Map(financialBrokerPool => financialBrokerPool.ChangedAt).Nullable();
References(financialBrokerPool => financialBrokerPool.ChangedBy).Nullable().ForeignKey("FK_USER_GROUP_CHANGED_BY_USER");
Map(financialBrokerPool => financialBrokerPool.CreatedAt).Not.Nullable();
References(financialBrokerPool => financialBrokerPool.CreatedBy).Not.Nullable().ForeignKey("FK_USER_GROUP_CREATED_BY_USER");
Map(financialBrokerPool => financialBrokerPool.Name).Not.Nullable().Length(255);
Map(financialBrokerPool => financialBrokerPool.BalanceOverdraftLimit).Nullable();
}
}
} | 56.294118 | 136 | 0.733542 | [
"MIT"
] | queoGmbH/peanuts | Peanuts.Net.Core/src/Persistence/Mappings/UserGroupMap.cs | 959 | C# |
using System;
using System.Data;
using System.Data.Common;
using System.Data.OracleClient;
using System.Xml;
using NBear.Common;
using NBear.Data;
namespace NBear.Data.Oracle
{
/// <summary>
/// <para>Represents an Oracle Database.</para>
/// </summary>
/// <remarks>
/// <para>
/// Internally uses Oracle .NET Managed Provider from Microsoft (System.Data.OracleClient) to connect to the database.
/// </para>
/// </remarks>
public class OracleDbProvider : DbProvider
{
#region Private Members
private const char PARAMETER_TOKEN = ':';
[Obsolete]
private static OracleStatementFactory _StatementFactory = new OracleStatementFactory();
#endregion
#region Public Members
/// <summary>
/// Initializes a new instance of the <see cref="OracleDbProvider"/> class.
/// </summary>
/// <param name="connStr">The conn STR.</param>
public OracleDbProvider(string connStr)
: base(connStr, OracleClientFactory.Instance)
{
}
/// <summary>
/// When overridden in a derived class, creates an <see cref="IPageSplit"/> for a SQL page splitable select query.
/// </summary>
/// <param name="db"></param>
/// <param name="selectStatement">The text of the basic select query for all rows.</param>
/// <param name="keyColumn">The sigle main DEFAULT_KEY of the query.</param>
/// <param name="paramValues">The param values of the query.</param>
/// <returns>
/// The <see cref="IPageSplit"/> for the SQL query.
/// </returns>
[Obsolete]
public override IPageSplit CreatePageSplit(Database db, string selectStatement, string keyColumn, params object[] paramValues)
{
return new OraclePageSplit(db, selectStatement, keyColumn, paramValues);
}
/// <summary>
/// Discovers the params.
/// </summary>
/// <param name="sql">The sql.</param>
/// <returns></returns>
public override string[] DiscoverParams(string sql)
{
if (sql == null)
{
return null;
}
System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(PARAMETER_TOKEN + @"([\w\d_]+)");
System.Text.RegularExpressions.MatchCollection ms = r.Matches(sql);
if (ms.Count == 0)
{
return null;
}
string[] paramNames = new string[ms.Count];
for (int i = 0; i < ms.Count; i++)
{
paramNames[i] = ms[i].Value;
}
return paramNames;
}
/// <summary>
/// Creates the SQL statement factory.
/// </summary>
/// <returns></returns>
[Obsolete]
public override IStatementFactory CreateStatementFactory()
{
return _StatementFactory;
}
/// <summary>
/// Adjusts the parameter.
/// </summary>
/// <param name="param">The param.</param>
[Obsolete]
public override void AdjustParameter(DbParameter param)
{
OracleParameter oracleParam = (OracleParameter)param;
object value = param.Value;
DbType type = param.DbType;
if (value == null || value == DBNull.Value)
{
oracleParam.Value = DBNull.Value;
if (oracleParam.DbType != DbType.Binary && oracleParam.DbType != DbType.Int32)
{
oracleParam.OracleType = OracleType.NVarChar;
}
return;
}
if (value.GetType().IsEnum)
{
oracleParam.OracleType = OracleType.Int32;
return;
}
if (value.GetType() == typeof(byte[]))
{
oracleParam.OracleType = OracleType.Blob;
return;
}
if (value.GetType() == typeof(Guid))
{
oracleParam.OracleType = OracleType.VarChar;
oracleParam.Value = value.ToString();
return;
}
if (value.GetType() == typeof(Byte) || value.GetType() == typeof(SByte) ||
value.GetType() == typeof(Int16) || value.GetType() == typeof(Int32) ||
value.GetType() == typeof(Int64) || value.GetType() == typeof(UInt16) ||
value.GetType() == typeof(UInt32) || value.GetType() == typeof(UInt64))
{
oracleParam.OracleType = OracleType.Int32;
return;
}
if (value.GetType() == typeof(Single) || value.GetType() == typeof(Double))
{
oracleParam.OracleType = OracleType.Float;
return;
}
if (value.GetType() == typeof(Boolean))
{
oracleParam.OracleType = OracleType.Int16;
oracleParam.Value = (((bool)value) ? 1 : 0);
return;
}
if (value.GetType() == typeof(Char))
{
oracleParam.OracleType = OracleType.NChar;
return;
}
if (value.GetType() == typeof(Decimal))
{
oracleParam.OracleType = OracleType.Number;
return;
}
if (value.GetType() == typeof(DateTime))
{
oracleParam.OracleType = OracleType.DateTime;
return;
}
if (value.GetType() == typeof(string))
{
oracleParam.OracleType = OracleType.NVarChar;
if (value.ToString().Length > 2000)
{
oracleParam.OracleType = OracleType.NClob;
}
return;
}
//by default, threat as string
oracleParam.OracleType = OracleType.NClob;
oracleParam.Value = NBear.Common.SerializationManager.Serialize(value);
}
/// <summary>
/// Builds the name of the parameter.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public override string BuildParameterName(string name)
{
string nameStr = name.Trim('\"');
if (nameStr[0] != PARAMETER_TOKEN)
{
return nameStr.Insert(0, new string(PARAMETER_TOKEN, 1));
}
return nameStr;
}
/// <summary>
/// Builds the name of the column.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public override string BuildColumnName(string name)
{
return "\"" + name + "\"";
}
/// <summary>
/// Gets the select last inserted row auto ID statement.
/// </summary>
/// <value>The select last inserted row auto ID statement.</value>
public override string SelectLastInsertedRowAutoIDStatement
{
get
{
return "SELECT SEQ_{1}.nextval FROM DUAL";
}
}
/// <summary>
/// Gets a value indicating whether [support AD o20 transaction].
/// </summary>
/// <value>
/// <c>true</c> if [support AD o20 transaction]; otherwise, <c>false</c>.
/// </value>
public override bool SupportADO20Transaction
{
get { return false; }
}
/// <summary>
/// Gets the left token of table name or column name.
/// </summary>
/// <value>The left token.</value>
public override string LeftToken
{
get { return "\""; }
}
/// <summary>
/// Gets the right token of table name or column name.
/// </summary>
/// <value>The right token.</value>
public override string RightToken
{
get { return "\""; }
}
/// <summary>
/// Gets the param prefix.
/// </summary>
/// <value>The param prefix.</value>
public override string ParamPrefix
{
get { return PARAMETER_TOKEN.ToString(); }
}
public override NBear.Common.ISqlQueryFactory QueryFactory
{
get { return new NBear.Common.Oracle.OracleQueryFactory(); }
}
#endregion
}
} | 31.660517 | 134 | 0.509907 | [
"BSD-3-Clause"
] | shnug/NBear | NBear.Data/Oracle/OracleDbProvider.cs | 8,580 | 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>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("SIS.Demo")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Release")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("SIS.Demo")]
[assembly: System.Reflection.AssemblyTitleAttribute("SIS.Demo")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 40.666667 | 80 | 0.642418 | [
"MIT"
] | TodorNikolov89/SoftwareUniversity | CSharpWebBasics/SIS/SIS.Demo/obj/Release/netcoreapp2.1/SIS.Demo.AssemblyInfo.cs | 976 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/DirectML.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using TerraFX.Interop.Windows;
namespace TerraFX.Interop.DirectX;
public unsafe partial struct DML_AVERAGE_POOLING_GRAD_OPERATOR_DESC
{
[NativeTypeName("const DML_TENSOR_DESC *")]
public DML_TENSOR_DESC* InputGradientTensor;
[NativeTypeName("const DML_TENSOR_DESC *")]
public DML_TENSOR_DESC* OutputGradientTensor;
public uint DimensionCount;
[NativeTypeName("const UINT *")]
public uint* Strides;
[NativeTypeName("const UINT *")]
public uint* WindowSize;
[NativeTypeName("const UINT *")]
public uint* StartPadding;
[NativeTypeName("const UINT *")]
public uint* EndPadding;
public BOOL IncludePadding;
}
| 28.117647 | 145 | 0.740586 | [
"MIT"
] | JeremyKuhne/terrafx.interop.windows | sources/Interop/Windows/DirectX/um/DirectML/DML_AVERAGE_POOLING_GRAD_OPERATOR_DESC.cs | 958 | C# |
using System;
using System.IO;
using Aspose.Cells;
using System.Drawing;
namespace Aspose.Cells.Examples.CSharp.Data
{
public class SortDataInColumnWithBackgroundColor
{
//Source directory
static string sourceDir = RunExamples.Get_SourceDirectory();
//Output directory
static string outputDir = RunExamples.Get_OutputDirectory();
public static void Main()
{
// ExStart:1
// Create a workbook object and load template file
Workbook workbook = new Workbook(sourceDir + "sampleBackGroundFile.xlsx");
// Instantiate data sorter object
DataSorter sorter = workbook.DataSorter;
// Add key for second column for red color
sorter.AddKey(1, SortOnType.CellColor, SortOrder.Descending, Color.Red);
// Sort the data based on the key
sorter.Sort(workbook.Worksheets[0].Cells, CellArea.CreateCellArea("A2", "C6"));
// Save the output file
workbook.Save(outputDir + "outputsampleBackGroundFile.xlsx");
// ExEnd:1
//Display the message
Console.WriteLine("SortDataInColumnWithBackgroundColor executed successfully.\r\n");
}
}
} | 32.179487 | 96 | 0.639044 | [
"MIT"
] | aspose-cells/Aspose.Cells-for-.NET | Examples/CSharp/Data/SortDataInColumnWithBackgroundColor.cs | 1,255 | C# |
using System;
using System.IO;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
using System.Net;
using System.Net.Http;
namespace ImageScraper
{
partial class MainForm
{
private string[] mAvailableFormats = new string[] { "jpg", "jpeg", "png", "bmp", "gif" };
private void InitializeSettings(DownloadSettings dc)
{
// ダウンロード設定
dc.Logger = mLogger;
dc.UrlContainer = new UrlContainer.UrlContainer(comboBox1.Text);
dc.Formats = PickImageFormats();
dc.ParseHrefAttr = checkBox7.Checked;
dc.ParseImgTag = checkBox8.Checked;
dc.DomainFilter = new DomainFilter(checkBox6.Checked, dc.UrlContainer);
dc.ColorFilter = new ColorFilter(checkBox5.Checked, checkBox20.Checked);
dc.ImageSizeFilter = new ValueRangeFilter(checkBox14.Checked, checkBox17.Checked, (int)numericUpDown1.Value, (int)numericUpDown10.Value);
dc.ImagesPerPageFilter = new ValueRangeFilter(checkBox15.Checked, checkBox18.Checked, (int)numericUpDown2.Value, (int)numericUpDown11.Value);
dc.TitleFilter = new KeywordFilter(checkBox11.Checked, checkBox21.Checked, checkBox22.Checked, comboBox2.Text, comboBox5.Text);
dc.UrlFilter = new KeywordFilter(checkBox12.Checked, checkBox24.Checked, checkBox23.Checked, comboBox3.Text, comboBox4.Text);
dc.RootUrlFilter = new KeywordFilter(checkBox31.Checked, checkBox30.Checked, checkBox29.Checked, comboBox9.Text, comboBox8.Text);
dc.ImageUrlFilter = new KeywordFilter(checkBox28.Checked, checkBox27.Checked, checkBox26.Checked, comboBox7.Text, comboBox6.Text);
dc.ResolutionFilter = new ResolutionFilter(checkBox16.Checked, checkBox19.Checked, (int)numericUpDown5.Value, (int)numericUpDown6.Value, (int)numericUpDown12.Value, (int)numericUpDown13.Value);
// 保存設定
var sng = new Utilities.SerialNameGenerator(textBox2.Text, (int)numericUpDown9.Value, mAvailableFormats);
dc.RootDirectory = textBox5.Text.TrimEnd('\\') + "\\";
dc.AppendsUrl = checkBox9.Checked;
dc.AppendsTitle = checkBox10.Checked;
dc.OverlappedUrlFilter = new OverlappedUrlFilter(mUrlCache, checkBox13.Checked);
dc.FileNameGenerator = new FileNameGenerator(radioButton2.Checked, sng);
// 終了条件設定
var limitStatus = new Status((int)numericUpDown3.Value, (int)numericUpDown8.Value, (int)numericUpDown4.Value, (double)numericUpDown7.Value * 1000);
dc.StatusMonitor = new StatusMonitor(radioButton12.Checked, radioButton10.Checked, radioButton5.Checked, radioButton6.Checked, radioButton7.Checked,
limitStatus, (int)numericUpDown14.Value, this.CountImages(dc.RootDirectory));
// 接続設定
UrlContainer.UrlContainer.RequestSpan = (int)numericUpDown15.Value;
HtmlContainer.HtmlContainer.RequestSpan = (int)numericUpDown15.Value;
if (checkBox25.Checked)
{
var proxy = new WebProxy(textBox1.Text, int.Parse(textBox3.Text));
UrlContainer.UrlContainer.Proxy = proxy;
HtmlContainer.HtmlContainer.Proxy = proxy;
}
else
{
UrlContainer.UrlContainer.Proxy = null;
HtmlContainer.HtmlContainer.Proxy = null;
}
}
private void UpdateComboBox(ComboBox cb)
{
string str = cb.Text;
if (!String.IsNullOrEmpty(str))
{
// 入力値の重複チェック(アイテム内に無いときは-1が返る)
if (cb.Items.IndexOf(str) != -1)
cb.Items.Remove(str);
// アイテム一覧の一番上に登録
cb.Items.Insert(0, str);
cb.Text = str;
}
}
private void InitializeForm()
{
mInfoViewItems.Clear();
listViewEx1.ClearEmbeddedControl();
listViewEx1.Items.Clear();
UpdateComboBox(comboBox1);
UpdateComboBox(comboBox2);
UpdateComboBox(comboBox3);
UpdateComboBox(comboBox4);
UpdateComboBox(comboBox5);
UpdateComboBox(comboBox6);
UpdateComboBox(comboBox7);
UpdateComboBox(comboBox8);
UpdateComboBox(comboBox9);
ReverseControls();
toolStripStatusLabel1.Text = "ダウンロード中...";
}
private void FinalizeForm()
{
ReverseControls();
toolStripStatusLabel1.Text = "完了";
}
async void RunDownloader()
{
// 入力値のチェック
SwitchControls(false);
bool result = await this.IsValidInputs();
SwitchControls(true);
if (!result)
return;
// フォームを無効化
InitializeForm();
try
{
// 設定値の反映
this.InitializeSettings(mDownloadSettings);
Directory.CreateDirectory(mDownloadSettings.RootDirectory);
for (int i = 0; i < mPlugins.Length; i++)
mPlugins[i].PreProcess();
mDownloader = new Downloader(mDownloadSettings, mPlugins, this);
// タスクの実行
await mDownloader.Start();
// 後処理
MessageBox.Show("ダウンロードが完了しました", "通知",
MessageBoxButtons.OK, MessageBoxIcon.Information);
for (int i = 0; i < mPlugins.Length; i++)
mPlugins[i].PostProcess();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "エラー",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
// フォームを有効化
FinalizeForm();
mDownloader = null;
}
}
private int CountImages(string dir)
{
int num = 0;
if (Directory.Exists(dir))
{
for (int i = 0; i < mAvailableFormats.Length; i++)
num += Directory.GetFiles(dir, "*." + mAvailableFormats[i], SearchOption.AllDirectories).Length;
}
return num;
}
private async Task<bool> IsValidProxy(string host, int port)
{
try
{
var ch = new HttpClientHandler();
ch.Proxy = new WebProxy(host, port);
ch.UseProxy = true;
var client = new HttpClient(ch);
client.Timeout = TimeSpan.FromSeconds(20.0);
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
var responseString = await client.GetStringAsync(new Uri("http://google.com/"));
sw.Stop();
if (!string.IsNullOrEmpty(responseString))
{
string mes = String.Format("有効なプロキシサーバーです > http://google.com/ {0} s", sw.Elapsed.TotalSeconds);
mLogger.Write("MainForm", mes);
return true;
}
else
{
mLogger.Write("MainForm", "無効なプロキシサーバーです");
return false;
}
}
catch (TaskCanceledException)
{
mLogger.Write("MainForm", "プロキシサーバーを用いた接続がタイムアウトしました");
return false;
}
catch
{
mLogger.Write("MainForm", "無効なプロキシサーバーです");
return false;
}
}
private async Task<bool> IsValidInputs()
{
string errorMessage = "";
Regex urlEx = new Regex(@"^(https?|ftp)://[\w/:%#\$&\?\(\)~\.=\+\-]+$", RegexOptions.IgnoreCase);
if (!urlEx.Match(comboBox1.Text).Success)
errorMessage += "URL を正しく入力してください\n";
Regex dirEx = new Regex(@"[a-zA-Z]:\\.*");
if (!dirEx.Match(textBox5.Text).Success)
errorMessage += "保存先を正しく入力してください\n";
if ((checkBox21.Checked && comboBox2.Text.Length == 0) ||
(checkBox22.Checked && comboBox5.Text.Length == 0) ||
(checkBox23.Checked && comboBox4.Text.Length == 0) ||
(checkBox24.Checked && comboBox3.Text.Length == 0))
errorMessage += "キーワードを入力してください\n";
if (checkBox25.Checked)
{
int port = 0;
if (!int.TryParse(textBox3.Text, out port))
errorMessage += "プロキシサーバーを正しく入力してください\n";
else if (!await IsValidProxy(textBox1.Text, port))
errorMessage += "プロキシサーバーを正しく入力してください\n";
}
if (errorMessage.Length != 0)
{
MessageBox.Show(errorMessage, "エラー",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
return true;
}
private string[] PickImageFormats()
{
List<string> format = new List<string>();
if (checkBox1.Checked)
format.AddRange(new string[] { "jpg", "jpeg" });
if (checkBox2.Checked)
format.Add("png");
if (checkBox3.Checked)
format.Add("bmp");
if (checkBox4.Checked)
format.Add("gif");
return format.ToArray();
}
private void SwitchControls(bool enabled)
{
button1.Enabled = enabled;
comboBox1.Enabled = enabled;
tabPage1.Enabled = enabled;
tabPage2.Enabled = enabled;
tabPage3.Enabled = enabled;
tabPage7.Enabled = enabled;
foreach (ToolStripMenuItem ddi in View_ToolStripMenuItem.DropDownItems)
ddi.Enabled = enabled;
foreach (ToolStripMenuItem ddi in Plugins_ToolStripMenuItem.DropDownItems)
ddi.Enabled = enabled;
}
private void ReverseControls()
{
if (button1.Text == "この条件でダウンロード開始")
button1.Text = "一時停止";
else
button1.Text = "この条件でダウンロード開始";
comboBox1.Enabled = !comboBox1.Enabled;
button2.Enabled = !button2.Enabled;
tabPage1.Enabled = !tabPage1.Enabled;
tabPage2.Enabled = !tabPage2.Enabled;
tabPage3.Enabled = !tabPage3.Enabled;
tabPage7.Enabled = !tabPage7.Enabled;
foreach (ToolStripMenuItem ddi in View_ToolStripMenuItem.DropDownItems)
ddi.Enabled = !ddi.Enabled;
foreach (ToolStripMenuItem ddi in Plugins_ToolStripMenuItem.DropDownItems)
ddi.Enabled = !ddi.Enabled;
}
public void UpdateStatus(Status sumStatus)
{
toolStripStatusLabel2.Text = String.Format("完了: {0} 階層, {1} ページ, {2} 枚, {3} KB",
sumStatus.Depth, sumStatus.Pages, sumStatus.Images, sumStatus.Size);
}
public void InitProgress(string title, string url, int max)
{
if (title != null && max > 0)
{
if (!listViewEx1.Items.Cast<ListViewItem>().Any(x => (string)x.Tag == url))
{
ListViewItem lvi = new ListViewItem(new string[] { title, "", "1" });
lvi.ToolTipText = url;
lvi.Tag = url;
listViewEx1.Items.Add(lvi);
int idx = listViewEx1.Items.Count - 1;
ProgressBar pb = new ProgressBar();
pb.Maximum = max;
pb.Value = 1;
// Embed the ProgressBar in Column 2
listViewEx1.AddEmbeddedControl(pb, 1, idx);
listViewEx1.EnsureVisible(idx);
}
}
else
listViewEx1.Items.Clear();
}
public void UpdateProgress(int downloadCount, int imageCount)
{
int idx = listViewEx1.Items.Count - 1;
listViewEx1.Items[idx].SubItems[2].Text = downloadCount.ToString();
ProgressBar pb = listViewEx1.GetEmbeddedControl(1, idx) as ProgressBar;
pb.Value = imageCount;
}
public void FinalizeProgress()
{
int idx = listViewEx1.Items.Count - 1;
ProgressBar pb = listViewEx1.GetEmbeddedControl(1, idx) as ProgressBar;
pb.Value = pb.Maximum;
}
public void UpdateImageInfo(ImageInfo info)
{
mUrlCache.Add(info);
mInfoViewItems.Add(info);
}
public ImageInfo FindParentUrl(string url)
{
foreach (var info in mInfoViewItems)
{
if (info.ParentUrl == url)
return info;
}
return null;
}
public void DeleteSelectedImages(string url)
{
foreach(var info in mInfoViewItems)
{
if (info.ParentUrl == url)
{
string dir = Path.GetDirectoryName(info.ImagePath);
if (File.Exists(info.ImagePath))
{
File.Delete(info.ImagePath);
Utilities.Common.DeleteEmptyDirectory(dir);
}
}
}
}
private void LoadPlugins()
{
PluginInfo[] pis = PluginInfo.FindPlugins();
mPlugins = new Plugins.IPlugin[pis.Length];
for (int i = 0; i < mPlugins.Length; i++)
{
mPlugins[i] = pis[i].CreateInstance();
mPlugins[i].Logger = mLogger;
ToolStripMenuItem mi = new ToolStripMenuItem(mPlugins[i].Name);
mi.Click += new EventHandler(menuPlugin_Click);
Plugins_ToolStripMenuItem.DropDownItems.Add(mi);
}
}
private void SerializeFormSettings()
{
FormSettings settings = new FormSettings();
settings.LoggerFormEnabled = LoggerFormEnabled_ToolStripMenuItem.Checked;
settings.Properties = Utilities.ControlProperty.Get(this.Controls);
for (int i = comboBox1.Items.Count - 1; i >= 0; i--)
settings.UrlList.Insert(0, comboBox1.Items[i].ToString());
for (int i = comboBox2.Items.Count - 1; i >= 0; i--)
settings.KeyTitleList.Insert(0, comboBox2.Items[i].ToString());
for (int i = comboBox5.Items.Count - 1; i >= 0; i--)
settings.ExKeyTitleList.Insert(0, comboBox5.Items[i].ToString());
for (int i = comboBox3.Items.Count - 1; i >= 0; i--)
settings.KeyUrlList.Insert(0, comboBox3.Items[i].ToString());
for (int i = comboBox4.Items.Count - 1; i >= 0; i--)
settings.ExKeyUrlList.Insert(0, comboBox4.Items[i].ToString());
for (int i = comboBox9.Items.Count - 1; i >= 0; i--)
settings.KeyRootUrlList.Insert(0, comboBox9.Items[i].ToString());
for (int i = comboBox8.Items.Count - 1; i >= 0; i--)
settings.ExKeyRootUrlList.Insert(0, comboBox8.Items[i].ToString());
for (int i = comboBox7.Items.Count - 1; i >= 0; i--)
settings.KeyImageUrlList.Insert(0, comboBox7.Items[i].ToString());
for (int i = comboBox6.Items.Count - 1; i >= 0; i--)
settings.ExKeyImageUrlList.Insert(0, comboBox6.Items[i].ToString());
var xs = new XmlSerializer(typeof(FormSettings));
using (var sw = new StreamWriter("ImageScraper.xml", false, new UTF8Encoding(false)))
xs.Serialize(sw, settings);
}
private void SaveSettings()
{
try
{
SerializeFormSettings();
mLogger.Write("MainForm", "フォームの設定を保存しました");
}
catch
{
mLogger.Write("MainForm", "フォームの設定を正常に保存できませんでした");
}
foreach (var plugin in mPlugins)
{
try
{
plugin.SaveSettings();
mLogger.Write(plugin.Name, "プラグインの設定を保存しました");
}
catch
{
mLogger.Write(plugin.Name, "プラグインの設定を正常に保存できませんでした");
}
}
try
{
var xs = new XmlSerializer(typeof(List<ImageInfo>));
var urlCache = mUrlCache.ToList();
using (var sw = new StreamWriter("UrlCache.xml", false, new UTF8Encoding(false)))
xs.Serialize(sw, urlCache);
mLogger.Write("MainForm", "履歴を保存しました");
}
catch
{
mLogger.Write("MainForm", "履歴を正常に保存できませんでした");
}
}
private void DeserializeFormSettings()
{
using (var sr = new StreamReader("ImageScraper.xml", new UTF8Encoding(false)))
{
var xs = new XmlSerializer(typeof(FormSettings));
var settings = xs.Deserialize(sr) as FormSettings;
if (settings.UrlList != null)
comboBox1.Items.AddRange(settings.UrlList.ToArray());
if (settings.KeyTitleList != null)
comboBox2.Items.AddRange(settings.KeyTitleList.ToArray());
if (settings.ExKeyTitleList != null)
comboBox5.Items.AddRange(settings.ExKeyTitleList.ToArray());
if (settings.KeyUrlList != null)
comboBox3.Items.AddRange(settings.KeyUrlList.ToArray());
if (settings.ExKeyUrlList != null)
comboBox4.Items.AddRange(settings.ExKeyUrlList.ToArray());
if (settings.KeyRootUrlList != null)
comboBox9.Items.AddRange(settings.KeyRootUrlList.ToArray());
if (settings.ExKeyRootUrlList != null)
comboBox8.Items.AddRange(settings.ExKeyRootUrlList.ToArray());
if (settings.KeyImageUrlList != null)
comboBox7.Items.AddRange(settings.KeyImageUrlList.ToArray());
if (settings.ExKeyImageUrlList != null)
comboBox6.Items.AddRange(settings.ExKeyImageUrlList.ToArray());
Utilities.ControlProperty.Set(this.Controls, settings.Properties);
LoggerFormEnabled_ToolStripMenuItem.Checked = settings.LoggerFormEnabled;
}
}
private void DeserializeIncompatibleUrlCache()
{
var xs = new XmlSerializer(typeof(List<Utilities.Common.KeyAndValue<string, ImageInfo>>));
using (var sr = new StreamReader("UrlCache.xml", new UTF8Encoding(false)))
{
var urlCache = (List<Utilities.Common.KeyAndValue<string, ImageInfo>>)xs.Deserialize(sr);
var urlCacheDict = Utilities.Common.ConvertListToDictionary(urlCache);
mUrlCache = new HashSet<ImageInfo>();
foreach (var pair in urlCacheDict)
{
var info = new ImageInfo();
info.ImagePath = pair.Value.ImagePath;
info.ImageUrl = pair.Key;
info.TimeStamp = pair.Value.TimeStamp;
info.ParentTitle = pair.Value.ParentTitle;
info.ParentUrl = pair.Value.ParentUrl;
mUrlCache.Add(info);
}
}
}
private void LoadSettings()
{
if (File.Exists("ImageScraper.xml"))
{
try
{
DeserializeFormSettings();
mLogger.Write("MainForm", "フォームの設定を読み込みました");
}
catch
{
mLogger.Write("MainForm", "フォームの設定を正常に読み込めませんでした");
}
}
foreach (var plugin in mPlugins)
{
try
{
plugin.LoadSettings();
mLogger.Write(plugin.Name, "プラグインの設定を読み込みました");
}
catch
{
mLogger.Write(plugin.Name, "プラグインの設定を正常に読み込めませんでした");
}
}
if (File.Exists("UrlCache.xml"))
{
try
{
var xs = new XmlSerializer(typeof(List<ImageInfo>));
using (var sr = new StreamReader("UrlCache.xml", new UTF8Encoding(false)))
{
var urlCache = xs.Deserialize(sr) as List<ImageInfo>;
mUrlCache = new HashSet<ImageInfo>(urlCache);
}
mLogger.Write("MainForm", "履歴を読み込みました");
}
catch
{
DeserializeIncompatibleUrlCache();
mLogger.Write("MainForm", "旧バージョンの履歴を読み込みました");
}
}
}
}
}
| 39.517495 | 205 | 0.527402 | [
"MIT"
] | tsurumeso/ImageScraper | ImageScraper/MainPartial.cs | 22,482 | C# |
using System;
namespace Mdmeta.Core
{
/// <summary>
/// Specify a property to receive argument of command from the user.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public sealed class CommandArgumentAttribute : Attribute
{
/// <summary>
/// Gets the argument name of a command task.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets or sets the description of the argument.
/// This will be shown when the user typed --help option.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Specify a property to receive argument of command from the user.
/// </summary>
public CommandArgumentAttribute(string argumentName)
{
Name = argumentName;
}
}
}
| 27.806452 | 76 | 0.583527 | [
"MIT"
] | dotnet-campus/markdown-metadata | src/Mdmeta.Core/Core/CommandArgumentAttribute.cs | 862 | C# |
namespace SKIT.FlurlHttpClient.Wechat.TenpayV3.Models
{
/// <summary>
/// <para>表示 [GET] /partner-transfer/batches/batch-id/{batch_id} 接口的请求。</para>
/// </summary>
public class GetPartnerTransferBatchByBatchIdRequest : GetTransferBatchByBatchIdRequest
{
}
}
| 28.3 | 91 | 0.70318 | [
"MIT"
] | OrchesAdam/DotNetCore.SKIT.FlurlHttpClient.Wechat | src/SKIT.FlurlHttpClient.Wechat.TenpayV3/Models/PartnerTransfer/Batches/GetPartnerTransferBatchByBatchIdRequest.cs | 301 | C# |
namespace ClearHl7.Codes.V270
{
/// <summary>
/// HL7 Version 2 Table 0305 - Person Location Type.
/// </summary>
/// <remarks>https://www.hl7.org/fhir/v2/0305</remarks>
public enum CodePersonLocationType
{
/// <summary>
/// C - Clinic.
/// </summary>
Clinic,
/// <summary>
/// D - Department.
/// </summary>
Department,
/// <summary>
/// H - Home.
/// </summary>
Home,
/// <summary>
/// N - Nursing Unit.
/// </summary>
NursingUnit,
/// <summary>
/// O - Provider's Office.
/// </summary>
ProvidersOffice,
/// <summary>
/// P - Phone.
/// </summary>
Phone,
/// <summary>
/// S - SNF.
/// </summary>
Snf
}
} | 20.772727 | 59 | 0.394967 | [
"MIT"
] | davebronson/clear-hl7-net | src/ClearHl7.Codes/V270/CodePersonLocationType.cs | 916 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebApplication2.Models;
using WebApplication2.Services;
using Microsoft.AspNetCore.Authorization;
using WebApplication2.Attributes;
namespace WebApplication2.Controllers
{
[TokenAuthorize]
[EnableCors("all")]
[Route("api/[controller]")]
[ApiController]
public class PostsController : ControllerBase
{
private readonly PostService _postService;
public PostsController(PostService postService)
{
_postService = postService;
}
[HttpGet]
public ActionResult<List<Post>> Get() => _postService.Get();
[HttpGet("{id:length(24)}", Name = "GetPost")]
public ActionResult<Post> Get(string id)
{
var book = _postService.Get(id);
if (book == null)
{
return NotFound();
}
return book;
}
[HttpPost]
public ActionResult<Post> Create(Post post)
{
_postService.Create(post);
return CreatedAtRoute("GetPost", new { id = post.Id.ToString() }, post);
}
[HttpPut]
public IActionResult Update(Post postIn)
{
string id = postIn.Id;
if (string.IsNullOrWhiteSpace(id))
{
return NotFound(postIn);
}
var post = _postService.Get(id);
if (post == null)
{
return NotFound(postIn);
}
_postService.Update(id, postIn);
return NoContent();
}
[HttpDelete("{id:length(24)}")]
public IActionResult Delete(string id)
{
var book = _postService.Get(id);
if (book == null)
{
return NotFound();
}
_postService.Remove(book.Id);
return NoContent();
}
}
}
| 23.438202 | 84 | 0.550336 | [
"MIT"
] | cliassi/rbac-react-redux-aspnetcore | server/WebApplication2/WebApplication2/Controllers/PostsController.cs | 2,088 | C# |
using tiorem.editor.database.repository.Base;
using tiorem.editor.database.repository.Interface;
namespace tiorem.editor.database.repository
{
public class CatalogueCategoryDAL : RepositoryBase<CatalogueCategory>, ICatalogueCategoryDAL
{
private ICatalogueCategoryDAL context;
public ApiResponse GetAllData(int id)
{
try
{
return null;
}
catch (System.Exception ex)
{
return new ApiResponse(aymkError.GetError, "aymk_api.database.account", ex);
}
}
}
}
| 23.653846 | 96 | 0.6 | [
"Apache-2.0"
] | ayagbasan/tiorem | tiorem.editor/tiorem.editor/database/repository/CatalogueCategoryDAL.cs | 617 | C# |
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Markup;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Reflection;
namespace ICSharpCode.WpfDesign.Designer
{
public class CallExtension : MarkupExtension
{
public CallExtension(string methodName)
{
this.methodName = methodName;
}
string methodName;
public override object ProvideValue(IServiceProvider serviceProvider)
{
var t = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));
return new CallCommand(t.TargetObject as FrameworkElement, methodName);
}
}
public class CallCommand : DependencyObject, ICommand
{
public CallCommand(FrameworkElement element, string methodName)
{
this.element = element;
this.methodName = methodName;
element.DataContextChanged += target_DataContextChanged;
BindingOperations.SetBinding(this, CanCallProperty, new Binding("DataContext.Can" + methodName) {
Source = element
});
GetMethod();
}
FrameworkElement element;
string methodName;
MethodInfo method;
public static readonly DependencyProperty CanCallProperty =
DependencyProperty.Register("CanCall", typeof(bool), typeof(CallCommand),
new PropertyMetadata(true));
public bool CanCall {
get { return (bool)GetValue(CanCallProperty); }
set { SetValue(CanCallProperty, value); }
}
public object DataContext {
get { return element.DataContext; }
}
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
if (e.Property == CanCallProperty) {
RaiseCanExecuteChanged();
}
}
void GetMethod()
{
if (DataContext == null) {
method = null;
}
else {
method = DataContext.GetType().GetMethod(methodName, Type.EmptyTypes);
}
}
void target_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
GetMethod();
RaiseCanExecuteChanged();
}
void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null) {
CanExecuteChanged(this, EventArgs.Empty);
}
}
#region ICommand Members
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return method != null && CanCall;
}
public void Execute(object parameter)
{
method.Invoke(DataContext, null);
}
#endregion
}
}
| 27.953125 | 100 | 0.739519 | [
"MIT"
] | galich/SharpDevelop | src/AddIns/DisplayBindings/WpfDesign/WpfDesign.Designer/Project/CallExtension.cs | 3,580 | C# |
// -------------------------------------------------------------------------------------------------
// <copyright file="SubtypeDerivationRule.cs" company="RHEA System S.A.">
//
// Copyright 2022 RHEA System S.A.
//
// 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.
//
// </copyright>
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// --------THIS IS AN AUTOMATICALLY GENERATED FILE. ANY MANUAL CHANGES WILL BE OVERWRITTEN!--------
// ------------------------------------------------------------------------------------------------
namespace Kalliope.DTO
{
using System;
using System.Collections.Generic;
using Kalliope.Common;
/// <summary>
/// A Data Transfer Object that represents a SubtypeDerivationRule
/// </summary>
/// <remarks>
/// A role path defining subtype population
/// </remarks>
[Container(typeName: "ObjectType", propertyName: "DerivationRule")]
public partial class SubtypeDerivationRule : RolePathOwner
{
/// <summary>
/// Initializes a new instance of the <see cref="SubtypeDerivationRule"/> class.
/// </summary>
public SubtypeDerivationRule()
{
this.DerivationCompleteness = DerivationCompleteness.FullyDerived;
this.DerivationStorage = DerivationStorage.NotStored;
}
/// <summary>
/// Gets or sets the unique identifier of the container
/// </summary>
public string Container {get; set;}
/// <summary>
/// Gets or sets a DerivationCompleteness
/// </summary>
[Description("Specify if a subtype can be explicitly populated without satisfying the derivation path.")]
[Property(name: "DerivationCompleteness", aggregation: AggregationKind.None, multiplicity: "1..1", typeKind: TypeKind.Enumeration, defaultValue: "FullyDerived", typeName: "DerivationCompleteness", allowOverride: false, isOverride: false, isDerived: false)]
public DerivationCompleteness DerivationCompleteness { get; set; }
/// <summary>
/// Gets or sets the unique identifier of the contained <see cref="DerivationNote"/>
/// </summary>
[Description("")]
[Property(name: "DerivationNote", aggregation: AggregationKind.Composite, multiplicity: "0..1", typeKind: TypeKind.Object, defaultValue: "", typeName: "DerivationNote", allowOverride: false, isOverride: false, isDerived: false)]
public string DerivationNote { get; set; }
/// <summary>
/// Gets or sets a DerivationStorage
/// </summary>
[Description("Specify if the derivation results are determined on demand or stored when derivation path components are changed")]
[Property(name: "DerivationStorage", aggregation: AggregationKind.None, multiplicity: "1..1", typeKind: TypeKind.Enumeration, defaultValue: "NotStored", typeName: "DerivationStorage", allowOverride: false, isOverride: false, isDerived: false)]
public DerivationStorage DerivationStorage { get; set; }
/// <summary>
/// Gets or sets a ExternalDerivation
/// </summary>
[Description("An empty path is a placeholder for an externally defined derivation rule and is not validated")]
[Property(name: "ExternalDerivation", aggregation: AggregationKind.None, multiplicity: "1..1", typeKind: TypeKind.Boolean, defaultValue: "false", typeName: "", allowOverride: false, isOverride: false, isDerived: false)]
public bool ExternalDerivation { get; set; }
/// <summary>
/// Gets the derived Id
/// </summary>
[Description("A unique identifier for this element")]
[Property(name: "Id", aggregation: AggregationKind.None, multiplicity: "1..1", typeKind: TypeKind.String, defaultValue: "", typeName: "", allowOverride: false, isOverride: true, isDerived: true)]
public override string Id => this.ComputeId();
}
}
// ------------------------------------------------------------------------------------------------
// --------THIS IS AN AUTOMATICALLY GENERATED FILE. ANY MANUAL CHANGES WILL BE OVERWRITTEN!--------
// ------------------------------------------------------------------------------------------------
| 51.56701 | 265 | 0.580168 | [
"Apache-2.0"
] | RHEAGROUP/Kalliope | Kalliope.DTO/AutoGenDto/SubtypeDerivationRule.cs | 5,002 | C# |
using System;
namespace LumiSoft.Net.SDP
{
// Token: 0x020000BF RID: 191
public class SDP_Time
{
// Token: 0x06000763 RID: 1891 RVA: 0x0002D26C File Offset: 0x0002C26C
public SDP_Time(long startTime, long stopTime)
{
bool flag = startTime < 0L;
if (flag)
{
throw new ArgumentException("Argument 'startTime' value must be >= 0.");
}
bool flag2 = stopTime < 0L;
if (flag2)
{
throw new ArgumentException("Argument 'stopTime' value must be >= 0.");
}
this.m_StartTime = startTime;
this.m_StopTime = stopTime;
}
// Token: 0x06000764 RID: 1892 RVA: 0x0002D2CC File Offset: 0x0002C2CC
public static SDP_Time Parse(string tValue)
{
StringReader stringReader = new StringReader(tValue);
stringReader.QuotedReadToDelimiter('=');
string text = stringReader.ReadWord();
bool flag = text == null;
if (flag)
{
throw new Exception("SDP message \"t\" field <start-time> value is missing !");
}
long startTime = Convert.ToInt64(text);
text = stringReader.ReadWord();
bool flag2 = text == null;
if (flag2)
{
throw new Exception("SDP message \"t\" field <stop-time> value is missing !");
}
long stopTime = Convert.ToInt64(text);
return new SDP_Time(startTime, stopTime);
}
// Token: 0x06000765 RID: 1893 RVA: 0x0002D348 File Offset: 0x0002C348
public string ToValue()
{
return string.Concat(new object[]
{
"t=",
this.StartTime,
" ",
this.StopTime,
"\r\n"
});
}
// Token: 0x17000262 RID: 610
// (get) Token: 0x06000766 RID: 1894 RVA: 0x0002D39C File Offset: 0x0002C39C
// (set) Token: 0x06000767 RID: 1895 RVA: 0x0002D3B4 File Offset: 0x0002C3B4
public long StartTime
{
get
{
return this.m_StartTime;
}
set
{
bool flag = value < 0L;
if (flag)
{
throw new ArgumentException("Property StartTime value must be >= 0 !");
}
this.m_StopTime = value;
}
}
// Token: 0x17000263 RID: 611
// (get) Token: 0x06000768 RID: 1896 RVA: 0x0002D3E0 File Offset: 0x0002C3E0
// (set) Token: 0x06000769 RID: 1897 RVA: 0x0002D3F8 File Offset: 0x0002C3F8
public long StopTime
{
get
{
return this.m_StopTime;
}
set
{
bool flag = value < 0L;
if (flag)
{
throw new ArgumentException("Property StopTime value must be >= 0 !");
}
this.m_StopTime = value;
}
}
// Token: 0x04000329 RID: 809
private long m_StartTime = 0L;
// Token: 0x0400032A RID: 810
private long m_StopTime = 0L;
}
}
| 24.523364 | 84 | 0.616235 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 0x727/metasploit-framework | external/source/Scanner/share/LumiSoft.Net/SDP/SDP_Time.cs | 2,626 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Threading.Tasks;
namespace CommandLineInjector.Tests.TestData
{
[Description("Test Command")]
public class TestCommand
{
public Task Invoke([Description("Parameter A")]string paramA, [Description("Parameter B")]int paramB, [Description("Optional Parameter")]string optional = "default value")
{
return Task.CompletedTask;
}
}
}
| 27.277778 | 179 | 0.704684 | [
"MIT"
] | jcharlesworthuk/CommandLineInjector | src/CommandLineInjector.Tests/TestData/TestCommand.cs | 493 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/WebServices.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop
{
public unsafe partial struct WS_XML_WRITER_PROPERTY
{
public WS_XML_WRITER_PROPERTY_ID id;
[NativeTypeName("void *")]
public void* value;
[NativeTypeName("ULONG")]
public uint valueSize;
}
}
| 29.631579 | 145 | 0.706927 | [
"MIT"
] | Perksey/terrafx.interop.windows | sources/Interop/Windows/um/WebServices/WS_XML_WRITER_PROPERTY.cs | 565 | C# |
/*
* Copyright 2014, 2015 Dominick Baier, Brock Allen
*
* 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 Thinktecture.IdentityServer.Core.ViewModels
{
/// <summary>
/// Models common data needed to render pages in IdentityServer.
/// </summary>
public class CommonViewModel
{
/// <summary>
/// The site URL.
/// </summary>
/// <value>
/// The site URL.
/// </value>
public string SiteUrl { get; set; }
/// <summary>
/// Gets or sets the name of the site.
/// </summary>
/// <value>
/// The name of the site.
/// </value>
public string SiteName { get; set; }
/// <summary>
/// The current logged in display name.
/// </summary>
/// <value>
/// The current user.
/// </value>
public string CurrentUser { get; set; }
}
}
| 29.591837 | 75 | 0.588276 | [
"Apache-2.0"
] | AndersAbel/IdentityServer3 | source/Core/ViewModels/CommonViewModel.cs | 1,452 | 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.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
namespace YamlDotNet
{
#if PORTABLE
/// <summary>
/// Mock SerializableAttribute to avoid having to add #if all over the place
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
internal sealed class SerializableAttribute : Attribute { }
internal static class ReflectionExtensions
{
public static bool IsValueType(this Type type)
{
return type.GetTypeInfo().IsValueType;
}
public static bool IsGenericType(this Type type)
{
return type.GetTypeInfo().IsGenericType;
}
public static bool IsInterface(this Type type)
{
return type.GetTypeInfo().IsInterface;
}
public static bool IsEnum(this Type type)
{
return type.GetTypeInfo().IsEnum;
}
/// <summary>
/// Determines whether the specified type has a default constructor.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>
/// <c>true</c> if the type has a default constructor; otherwise, <c>false</c>.
/// </returns>
public static bool HasDefaultConstructor(this Type type)
{
var typeInfo = type.GetTypeInfo();
return typeInfo.IsValueType || typeInfo.DeclaredConstructors
.Any(c => c.IsPublic && !c.IsStatic && c.GetParameters().Length == 0);
}
public static bool IsAssignableFrom(this Type type, Type source)
{
return type.IsAssignableFrom(source.GetTypeInfo());
}
public static bool IsAssignableFrom(this Type type, TypeInfo source)
{
return type.GetTypeInfo().IsAssignableFrom(source);
}
public static TypeCode GetTypeCode(this Type type)
{
if (type.IsEnum())
{
type = Enum.GetUnderlyingType(type);
}
if (type == typeof(bool))
{
return TypeCode.Boolean;
}
else if (type == typeof(char))
{
return TypeCode.Char;
}
else if (type == typeof(sbyte))
{
return TypeCode.SByte;
}
else if (type == typeof(byte))
{
return TypeCode.Byte;
}
else if (type == typeof(short))
{
return TypeCode.Int16;
}
else if (type == typeof(ushort))
{
return TypeCode.UInt16;
}
else if (type == typeof(int))
{
return TypeCode.Int32;
}
else if (type == typeof(uint))
{
return TypeCode.UInt32;
}
else if (type == typeof(long))
{
return TypeCode.Int64;
}
else if (type == typeof(ulong))
{
return TypeCode.UInt64;
}
else if (type == typeof(float))
{
return TypeCode.Single;
}
else if (type == typeof(double))
{
return TypeCode.Double;
}
else if (type == typeof(decimal))
{
return TypeCode.Decimal;
}
else if (type == typeof(DateTime))
{
return TypeCode.DateTime;
}
else if (type == typeof(String))
{
return TypeCode.String;
}
else
{
return TypeCode.Object;
}
}
public static Type[] GetGenericArguments(this Type type)
{
return type.GetTypeInfo().GenericTypeArguments;
}
public static IEnumerable<PropertyInfo> GetPublicProperties(this Type type)
{
return type.GetRuntimeProperties()
.Where(p => p.GetMethod.IsPublic && !p.GetMethod.IsStatic);
}
public static IEnumerable<MethodInfo> GetPublicMethods(this Type type)
{
return type.GetRuntimeMethods()
.Where(m => m.IsPublic && !m.IsStatic);
}
public static MethodInfo GetPublicStaticMethod(this Type type, string name, params Type[] parameterTypes)
{
return type.GetRuntimeMethods()
.FirstOrDefault(m =>
{
if (m.IsPublic && m.IsStatic && m.Name.Equals(name))
{
var parameters = m.GetParameters();
return parameters.Length == parameterTypes.Length
&& parameters.Zip(parameterTypes, (pi, pt) => pi.Equals(pt)).All(r => r);
}
return false;
});
}
public static MethodInfo GetGetMethod(this PropertyInfo property)
{
return property.GetMethod;
}
public static IEnumerable<Type> GetInterfaces(this Type type)
{
return type.GetTypeInfo().ImplementedInterfaces;
}
public static Exception Unwrap(this TargetInvocationException ex)
{
return ex.InnerException;
}
}
internal enum TypeCode
{
Empty = 0,
Object = 1,
DBNull = 2,
Boolean = 3,
Char = 4,
SByte = 5,
Byte = 6,
Int16 = 7,
UInt16 = 8,
Int32 = 9,
UInt32 = 10,
Int64 = 11,
UInt64 = 12,
Single = 13,
Double = 14,
Decimal = 15,
DateTime = 16,
String = 18,
}
internal static class StandardRegexOptions
{
public const RegexOptions Compiled = RegexOptions.None;
}
internal abstract class DBNull
{
private DBNull() {}
}
internal sealed class CultureInfoAdapter : CultureInfo
{
private readonly IFormatProvider _provider;
public CultureInfoAdapter(CultureInfo baseCulture, IFormatProvider provider)
: base(baseCulture.Name)
{
_provider = provider;
}
public override object GetFormat(Type formatType)
{
return _provider.GetFormat(formatType);
}
}
#else
internal static class ReflectionExtensions
{
public static bool IsValueType(this Type type)
{
return type.IsValueType;
}
public static bool IsGenericType(this Type type)
{
return type.IsGenericType;
}
public static bool IsInterface(this Type type)
{
return type.IsInterface;
}
public static bool IsEnum(this Type type)
{
return type.IsEnum;
}
/// <summary>
/// Determines whether the specified type has a default constructor.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>
/// <c>true</c> if the type has a default constructor; otherwise, <c>false</c>.
/// </returns>
public static bool HasDefaultConstructor(this Type type)
{
return type.IsValueType || type.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, Type.EmptyTypes, null) != null;
}
public static TypeCode GetTypeCode(this Type type)
{
return Type.GetTypeCode(type);
}
public static IEnumerable<PropertyInfo> GetPublicProperties(this Type type)
{
return type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
}
public static IEnumerable<MethodInfo> GetPublicMethods(this Type type)
{
return type.GetMethods(BindingFlags.Static | BindingFlags.Public);
}
public static MethodInfo GetPublicStaticMethod(this Type type, string name, params Type[] parameterTypes)
{
return type.GetMethod(name, BindingFlags.Public | BindingFlags.Static, null, parameterTypes, null);
}
private static readonly FieldInfo remoteStackTraceField = typeof(Exception)
.GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic);
public static Exception Unwrap(this TargetInvocationException ex)
{
var result = ex.InnerException;
if (remoteStackTraceField != null)
{
remoteStackTraceField.SetValue(ex.InnerException, ex.InnerException.StackTrace + "\r\n");
}
return result;
}
}
internal static class StandardRegexOptions
{
public const RegexOptions Compiled = RegexOptions.Compiled;
}
internal sealed class CultureInfoAdapter : CultureInfo
{
private readonly IFormatProvider _provider;
public CultureInfoAdapter(CultureInfo baseCulture, IFormatProvider provider)
: base(baseCulture.LCID)
{
_provider = provider;
}
public override object GetFormat(Type formatType)
{
return _provider.GetFormat(formatType);
}
}
#endif
}
| 26.313043 | 142 | 0.659617 | [
"MIT"
] | mattmiller85/YamlDotNet | YamlDotNet/Helpers/Portability.cs | 9,080 | C# |
using Abp.MultiTenancy;
using Abp.Zero.Configuration;
namespace HC.RetailClient.Authorization.Roles
{
public static class AppRoleConfig
{
public static void Configure(IRoleManagementConfig roleManagementConfig)
{
// Static host roles
roleManagementConfig.StaticRoles.Add(
new StaticRoleDefinition(
StaticRoleNames.Host.Admin,
MultiTenancySides.Host
)
);
// Static tenant roles
roleManagementConfig.StaticRoles.Add(
new StaticRoleDefinition(
StaticRoleNames.Tenants.Admin,
MultiTenancySides.Tenant
)
);
}
}
}
| 25.5 | 80 | 0.552941 | [
"MIT"
] | DonaldTdz/RetailClient | aspnet-core/src/HC.RetailClient.Core/Authorization/Roles/AppRoleConfig.cs | 767 | C# |
using System.Diagnostics;
var source = Enumerable.Range(1, 10_000_000);
// Opt in to PLINQ with AsParallel.
Stopwatch st = new Stopwatch();
st.Start();
// call MakeSome method...
var evenNums = from num in source
where num % 2 == 0
select Math.Pow(num,100);
st.Stop();
Stopwatch stt = new Stopwatch();
stt.Start();
// call MakeSome method...
var ovenNums = from num in source.AsParallel()
where num % 2 == 0
select Awati();
stt.Stop();
Console.WriteLine("Without PLINQ:"+st.ElapsedMilliseconds);
Console.WriteLine("With PLINQ:"+stt.ElapsedMilliseconds);
static int Awati()
{
Thread.Sleep(50000);
return 1;
}
Console.WriteLine("{0} even numbers out of {1} total",
evenNums.Count(), source.Count());
// The example displays the following output:
// 5000 even numbers out of 10000 total | 23.342105 | 59 | 0.640361 | [
"Apache-2.0"
] | behnamasaei/DotNetLearning | Asynchronous/PLINQ/Program.cs | 889 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace iSpyApplication.Controls
{
public partial class PermissionsForm : UserControl
{
private configurationGroup _group;
public PermissionsForm()
{
InitializeComponent();
label3.Text = LocRm.GetString("Password");
}
public void Init(configurationGroup group)
{
_group = group;
txtPassword.Text = EncDec.DecryptData(group.password,MainForm.Conf.EncryptCode);
if (_group.name == "Admin")
{
//force all features for admin user
_group.featureset = 1;
fpFeatures.Enabled = false;
}
var i = 1;
var feats = Enum.GetValues(typeof(Enums.Features));
foreach (var f in feats)
{
var cb = new CheckBox { Text = f.ToString(), Tag = f, AutoSize = true };
if ((Convert.ToInt32(f) & group.featureset) == i)
cb.Checked = true;
fpFeatures.Controls.Add(cb);
i = i * 2;
}
}
public bool Save()
{
if (EncDec.DecryptData(_group.password,MainForm.Conf.EncryptCode)!=txtPassword.Text)
{
var p = new Prompt(LocRm.GetString("ConfirmPassword")+": "+_group.name, "", true);
if (p.ShowDialog(this) == DialogResult.OK)
{
var v = p.Val;
if (v != txtPassword.Text)
{
MessageBox.Show(this, LocRm.GetString("PasswordMismatch"));
p.Dispose();
return false;
}
}
p.Dispose();
_group.password = EncDec.EncryptData(txtPassword.Text,MainForm.Conf.EncryptCode);
}
var tot = (from CheckBox c in fpFeatures.Controls where c.Checked select (int)c.Tag).Sum();
_group.featureset = tot;
return true;
}
private void tableLayoutPanel3_Paint(object sender, PaintEventArgs e)
{
}
private void fpFeatures_Paint(object sender, PaintEventArgs e)
{
}
}
}
| 31.5625 | 104 | 0.500594 | [
"Apache-2.0"
] | isaacandy/ispyconnect | iSpyApplication/Controls/PermissionsForm.cs | 2,527 | 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.Ckafka.V20190819.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class AppIdResponse : AbstractModel
{
/// <summary>
/// Number of eligible `AppId`
/// </summary>
[JsonProperty("TotalCount")]
public long? TotalCount{ get; set; }
/// <summary>
/// List of eligible `AppId`
/// Note: this field may return null, indicating that no valid values can be obtained.
/// </summary>
[JsonProperty("AppIdList")]
public long?[] AppIdList{ 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 + "TotalCount", this.TotalCount);
this.SetParamArraySimple(map, prefix + "AppIdList.", this.AppIdList);
}
}
}
| 31.788462 | 94 | 0.642468 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet-intl-en | TencentCloud/Ckafka/V20190819/Models/AppIdResponse.cs | 1,653 | C# |
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System;
using System.Collections.Generic;
namespace Components.Support.Tests.Entities
{
[EntityLogicalName("placeholder")]
internal class Placeholder : Entity
{
public const string EntityLogicalName = "placeholder";
[AttributeLogicalName("placeholderid")]
public Guid? placeholderid
{
get { return GetAttributeValue<Guid?>("placeholderid"); }
set { base.Id = value.HasValue ? value.Value : Guid.Empty; }
}
[AttributeLogicalName("tags")]
public string tags
{
get { return GetAttributeValue<string>("tags"); }
set { SetAttributeValue("tags", value); }
}
[RelationshipSchemaName("placeholder_tags")]
public IEnumerable<Tag> placeholder_tags
{
get { return GetRelatedEntities<Tag>("placeholder_tags", null); }
set { SetRelatedEntities("placeholder_tags", null, value); }
}
public Placeholder() :
base(EntityLogicalName)
{
}
}
}
| 28.125 | 77 | 0.605333 | [
"MIT"
] | opc-cpvp/OPC.PowerApps.PCFControls | src/Plugins/Components.Support.Tests/Entities/Placeholder.cs | 1,127 | C# |
namespace AcademiaEF6
{
partial class FormPrincipal
{
/// <summary>
/// Variável de designer necessária.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Limpar os recursos que estão sendo usados.
/// </summary>
/// <param name="disposing">true se for necessário descartar os recursos gerenciados; caso contrário, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Código gerado pelo Windows Form Designer
/// <summary>
/// Método necessário para suporte ao Designer - não modifique
/// o conteúdo deste método com o editor de código.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.btnExcluirProfessor = new System.Windows.Forms.Button();
this.btnNovoAluno = new System.Windows.Forms.Button();
this.btnNovaModalidade = new System.Windows.Forms.Button();
this.btnNovoProfessor = new System.Windows.Forms.Button();
this.dgvProfessor = new System.Windows.Forms.DataGridView();
this.dgvModalidade = new System.Windows.Forms.DataGridView();
this.dgvAluno = new System.Windows.Forms.DataGridView();
this.btnExcluirAluno = new System.Windows.Forms.Button();
this.btnExcluirModalidade = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.modalidadeDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.cPFDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.nomeDataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.telefoneDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.alunoBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.nomeDataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.vezesSemanaDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.precoHoraDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.professorDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.modalidadeBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.nomeDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.turnoDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.salarioHoraDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.professorBindingSource = new System.Windows.Forms.BindingSource(this.components);
((System.ComponentModel.ISupportInitialize)(this.dgvProfessor)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dgvModalidade)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dgvAluno)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.alunoBindingSource)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.modalidadeBindingSource)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.professorBindingSource)).BeginInit();
this.SuspendLayout();
//
// btnExcluirProfessor
//
this.btnExcluirProfessor.Location = new System.Drawing.Point(293, 402);
this.btnExcluirProfessor.Name = "btnExcluirProfessor";
this.btnExcluirProfessor.Size = new System.Drawing.Size(75, 23);
this.btnExcluirProfessor.TabIndex = 0;
this.btnExcluirProfessor.Text = "Excluir";
this.btnExcluirProfessor.UseVisualStyleBackColor = true;
this.btnExcluirProfessor.Click += new System.EventHandler(this.btnExcluirProfessor_Click);
//
// btnNovoAluno
//
this.btnNovoAluno.Location = new System.Drawing.Point(872, 402);
this.btnNovoAluno.Name = "btnNovoAluno";
this.btnNovoAluno.Size = new System.Drawing.Size(75, 23);
this.btnNovoAluno.TabIndex = 1;
this.btnNovoAluno.Text = "Novo";
this.btnNovoAluno.UseVisualStyleBackColor = true;
//
// btnNovaModalidade
//
this.btnNovaModalidade.Location = new System.Drawing.Point(413, 402);
this.btnNovaModalidade.Name = "btnNovaModalidade";
this.btnNovaModalidade.Size = new System.Drawing.Size(75, 23);
this.btnNovaModalidade.TabIndex = 2;
this.btnNovaModalidade.Text = "Novo";
this.btnNovaModalidade.UseVisualStyleBackColor = true;
this.btnNovaModalidade.Click += new System.EventHandler(this.btnNovaModalidade_Click);
//
// btnNovoProfessor
//
this.btnNovoProfessor.Location = new System.Drawing.Point(9, 402);
this.btnNovoProfessor.Name = "btnNovoProfessor";
this.btnNovoProfessor.Size = new System.Drawing.Size(75, 23);
this.btnNovoProfessor.TabIndex = 3;
this.btnNovoProfessor.Text = "Novo";
this.btnNovoProfessor.UseVisualStyleBackColor = true;
this.btnNovoProfessor.Click += new System.EventHandler(this.btnNovoProfessor_Click);
//
// dgvProfessor
//
this.dgvProfessor.AllowUserToAddRows = false;
this.dgvProfessor.AllowUserToDeleteRows = false;
this.dgvProfessor.AutoGenerateColumns = false;
this.dgvProfessor.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgvProfessor.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.nomeDataGridViewTextBoxColumn,
this.turnoDataGridViewTextBoxColumn,
this.salarioHoraDataGridViewTextBoxColumn});
this.dgvProfessor.DataSource = this.professorBindingSource;
this.dgvProfessor.Location = new System.Drawing.Point(9, 34);
this.dgvProfessor.Name = "dgvProfessor";
this.dgvProfessor.ReadOnly = true;
this.dgvProfessor.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dgvProfessor.Size = new System.Drawing.Size(359, 362);
this.dgvProfessor.TabIndex = 4;
//
// dgvModalidade
//
this.dgvModalidade.AllowUserToAddRows = false;
this.dgvModalidade.AllowUserToDeleteRows = false;
this.dgvModalidade.AutoGenerateColumns = false;
this.dgvModalidade.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgvModalidade.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.nomeDataGridViewTextBoxColumn1,
this.vezesSemanaDataGridViewTextBoxColumn,
this.precoHoraDataGridViewTextBoxColumn,
this.professorDataGridViewTextBoxColumn});
this.dgvModalidade.DataSource = this.modalidadeBindingSource;
this.dgvModalidade.Location = new System.Drawing.Point(413, 34);
this.dgvModalidade.Name = "dgvModalidade";
this.dgvModalidade.ReadOnly = true;
this.dgvModalidade.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dgvModalidade.Size = new System.Drawing.Size(419, 362);
this.dgvModalidade.TabIndex = 5;
//
// dgvAluno
//
this.dgvAluno.AutoGenerateColumns = false;
this.dgvAluno.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgvAluno.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.modalidadeDataGridViewTextBoxColumn,
this.cPFDataGridViewTextBoxColumn,
this.nomeDataGridViewTextBoxColumn2,
this.telefoneDataGridViewTextBoxColumn});
this.dgvAluno.DataSource = this.alunoBindingSource;
this.dgvAluno.Location = new System.Drawing.Point(872, 34);
this.dgvAluno.Name = "dgvAluno";
this.dgvAluno.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dgvAluno.Size = new System.Drawing.Size(456, 362);
this.dgvAluno.TabIndex = 6;
//
// btnExcluirAluno
//
this.btnExcluirAluno.Location = new System.Drawing.Point(1253, 402);
this.btnExcluirAluno.Name = "btnExcluirAluno";
this.btnExcluirAluno.Size = new System.Drawing.Size(75, 23);
this.btnExcluirAluno.TabIndex = 10;
this.btnExcluirAluno.Text = "Excluir";
this.btnExcluirAluno.UseVisualStyleBackColor = true;
//
// btnExcluirModalidade
//
this.btnExcluirModalidade.Location = new System.Drawing.Point(757, 402);
this.btnExcluirModalidade.Name = "btnExcluirModalidade";
this.btnExcluirModalidade.Size = new System.Drawing.Size(75, 23);
this.btnExcluirModalidade.TabIndex = 11;
this.btnExcluirModalidade.Text = "Excluir";
this.btnExcluirModalidade.UseVisualStyleBackColor = true;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(6, 13);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(83, 18);
this.label3.TabIndex = 9;
this.label3.Text = "Professor";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(869, 13);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(50, 18);
this.label1.TabIndex = 12;
this.label1.Text = "Aluno";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(410, 13);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(94, 18);
this.label2.TabIndex = 13;
this.label2.Text = "Modalidade";
//
// button1
//
this.button1.Location = new System.Drawing.Point(90, 402);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 3;
this.button1.Text = "Atualizar";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.btnNovoProfessor_Click);
//
// modalidadeDataGridViewTextBoxColumn
//
this.modalidadeDataGridViewTextBoxColumn.DataPropertyName = "Modalidade";
this.modalidadeDataGridViewTextBoxColumn.HeaderText = "Modalidade";
this.modalidadeDataGridViewTextBoxColumn.Name = "modalidadeDataGridViewTextBoxColumn";
//
// cPFDataGridViewTextBoxColumn
//
this.cPFDataGridViewTextBoxColumn.DataPropertyName = "CPF";
this.cPFDataGridViewTextBoxColumn.HeaderText = "CPF";
this.cPFDataGridViewTextBoxColumn.Name = "cPFDataGridViewTextBoxColumn";
//
// nomeDataGridViewTextBoxColumn2
//
this.nomeDataGridViewTextBoxColumn2.DataPropertyName = "Nome";
this.nomeDataGridViewTextBoxColumn2.HeaderText = "Nome";
this.nomeDataGridViewTextBoxColumn2.Name = "nomeDataGridViewTextBoxColumn2";
//
// telefoneDataGridViewTextBoxColumn
//
this.telefoneDataGridViewTextBoxColumn.DataPropertyName = "Telefone";
this.telefoneDataGridViewTextBoxColumn.HeaderText = "Telefone";
this.telefoneDataGridViewTextBoxColumn.Name = "telefoneDataGridViewTextBoxColumn";
//
// alunoBindingSource
//
this.alunoBindingSource.DataSource = typeof(AcademiaEF6.Dominio.Aluno);
//
// nomeDataGridViewTextBoxColumn1
//
this.nomeDataGridViewTextBoxColumn1.DataPropertyName = "Nome";
this.nomeDataGridViewTextBoxColumn1.HeaderText = "Nome";
this.nomeDataGridViewTextBoxColumn1.Name = "nomeDataGridViewTextBoxColumn1";
this.nomeDataGridViewTextBoxColumn1.ReadOnly = true;
//
// vezesSemanaDataGridViewTextBoxColumn
//
this.vezesSemanaDataGridViewTextBoxColumn.DataPropertyName = "VezesSemana";
this.vezesSemanaDataGridViewTextBoxColumn.HeaderText = "Dias da semana";
this.vezesSemanaDataGridViewTextBoxColumn.Name = "vezesSemanaDataGridViewTextBoxColumn";
this.vezesSemanaDataGridViewTextBoxColumn.ReadOnly = true;
this.vezesSemanaDataGridViewTextBoxColumn.Width = 60;
//
// precoHoraDataGridViewTextBoxColumn
//
this.precoHoraDataGridViewTextBoxColumn.DataPropertyName = "PrecoHora";
this.precoHoraDataGridViewTextBoxColumn.HeaderText = "PrecoHora";
this.precoHoraDataGridViewTextBoxColumn.Name = "precoHoraDataGridViewTextBoxColumn";
this.precoHoraDataGridViewTextBoxColumn.ReadOnly = true;
//
// professorDataGridViewTextBoxColumn
//
this.professorDataGridViewTextBoxColumn.DataPropertyName = "Professor";
this.professorDataGridViewTextBoxColumn.HeaderText = "Professor";
this.professorDataGridViewTextBoxColumn.Name = "professorDataGridViewTextBoxColumn";
this.professorDataGridViewTextBoxColumn.ReadOnly = true;
//
// modalidadeBindingSource
//
this.modalidadeBindingSource.DataSource = typeof(AcademiaEF6.Dominio.Modalidade);
//
// nomeDataGridViewTextBoxColumn
//
this.nomeDataGridViewTextBoxColumn.DataPropertyName = "Nome";
this.nomeDataGridViewTextBoxColumn.HeaderText = "Nome";
this.nomeDataGridViewTextBoxColumn.Name = "nomeDataGridViewTextBoxColumn";
this.nomeDataGridViewTextBoxColumn.ReadOnly = true;
//
// turnoDataGridViewTextBoxColumn
//
this.turnoDataGridViewTextBoxColumn.DataPropertyName = "Turno";
this.turnoDataGridViewTextBoxColumn.HeaderText = "Turno";
this.turnoDataGridViewTextBoxColumn.Name = "turnoDataGridViewTextBoxColumn";
this.turnoDataGridViewTextBoxColumn.ReadOnly = true;
//
// salarioHoraDataGridViewTextBoxColumn
//
this.salarioHoraDataGridViewTextBoxColumn.DataPropertyName = "SalarioHora";
this.salarioHoraDataGridViewTextBoxColumn.HeaderText = "SalarioHora";
this.salarioHoraDataGridViewTextBoxColumn.Name = "salarioHoraDataGridViewTextBoxColumn";
this.salarioHoraDataGridViewTextBoxColumn.ReadOnly = true;
//
// professorBindingSource
//
this.professorBindingSource.DataSource = typeof(AcademiaEF6.Dominio.Professor);
//
// FormPrincipal
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1355, 440);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.btnExcluirModalidade);
this.Controls.Add(this.btnExcluirAluno);
this.Controls.Add(this.label3);
this.Controls.Add(this.dgvAluno);
this.Controls.Add(this.dgvModalidade);
this.Controls.Add(this.dgvProfessor);
this.Controls.Add(this.button1);
this.Controls.Add(this.btnNovoProfessor);
this.Controls.Add(this.btnNovaModalidade);
this.Controls.Add(this.btnNovoAluno);
this.Controls.Add(this.btnExcluirProfessor);
this.Name = "FormPrincipal";
this.Text = "Academia";
this.Load += new System.EventHandler(this.FormPrincipal_Load);
((System.ComponentModel.ISupportInitialize)(this.dgvProfessor)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dgvModalidade)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dgvAluno)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.alunoBindingSource)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.modalidadeBindingSource)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.professorBindingSource)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnExcluirProfessor;
private System.Windows.Forms.Button btnNovoAluno;
private System.Windows.Forms.Button btnNovaModalidade;
private System.Windows.Forms.Button btnNovoProfessor;
private System.Windows.Forms.DataGridView dgvProfessor;
private System.Windows.Forms.DataGridView dgvModalidade;
private System.Windows.Forms.DataGridView dgvAluno;
private System.Windows.Forms.Button btnExcluirAluno;
private System.Windows.Forms.Button btnExcluirModalidade;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.DataGridViewTextBoxColumn nomeDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn turnoDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn salarioHoraDataGridViewTextBoxColumn;
private System.Windows.Forms.BindingSource professorBindingSource;
private System.Windows.Forms.DataGridViewTextBoxColumn nomeDataGridViewTextBoxColumn1;
private System.Windows.Forms.DataGridViewTextBoxColumn vezesSemanaDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn precoHoraDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn professorDataGridViewTextBoxColumn;
private System.Windows.Forms.BindingSource modalidadeBindingSource;
private System.Windows.Forms.DataGridViewTextBoxColumn modalidadeDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn cPFDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn nomeDataGridViewTextBoxColumn2;
private System.Windows.Forms.DataGridViewTextBoxColumn telefoneDataGridViewTextBoxColumn;
private System.Windows.Forms.BindingSource alunoBindingSource;
private System.Windows.Forms.Button button1;
}
}
| 55.967391 | 166 | 0.660614 | [
"CC0-1.0"
] | Luscas-PandC/Entra21-NoturnoLucas-Forms | AcademiaEF6/FormPrincipal.Designer.cs | 20,610 | C# |
#region Apache License Version 2.0
/*----------------------------------------------------------------
Copyright 2022 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd.
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.
Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md
----------------------------------------------------------------*/
#endregion Apache License Version 2.0
/*----------------------------------------------------------------
Copyright (C) 2022 Senparc
文件名:RedPackApi.cs
文件功能描述:普通红包发送和红包查询Api(暂缺裂变红包发送)
创建标识:Yu XiaoChou - 20160107
修改标识:Senparc - 20161024
修改描述:v14.3.102 重新整理红包发送方法
修改标识:Senparc - 20161112
修改描述:v14.3.107 SearchRedPack方法修改证书初始化方法
修改标识:Senparc - 20170110
修改描述:v14.3.118
修改标识:Senparc - 20170810
修改描述:v14.5.9 查询红包接口(SearchRedPack)添加refund_amount和remark两个参数获取
修改标识:Senparc - 20170810
修改描述:v14.6.10 添加接口:普通红包发送(服务商)
修改标识:Senparc - 20170925
修改描述:添加新规定提示:红包超过2000元必须提供scene_id参数:
https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_4&index=3
修改标识:Senparc - 20171208
修改描述:v14.8.10 修复红包接口 RedPackApi.SendNormalRedPack() 在.NET 4.6 下的XML解析问题
修改标识:Senparc - 20190121
修改描述:v16.6.9 修复:裂变红包 url 及参数不正确
修改标识:RongjieAAA - 20191122
修改描述:增加小程序红包发送API
----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using Senparc.Weixin.Exceptions;
using Senparc.Weixin.TenPay;
#if !NET451
using System.Net.Http;
#endif
namespace Senparc.Weixin.TenPay.V3
{
/// <summary>
/// 红包发送和查询Api(暂缺裂变红包发送)
/// </summary>
public partial class RedPackApi
{
private static string GetNewBillNo(string mchId)
{
//return string.Format("{0}{1}{2}", mchId, SystemTime.Now.ToString("yyyyMMdd"), TenPayV3Util.BuildRandomStr(10));
return string.Format("{0}{1}", SystemTime.Now.ToString("yyyyMMddHHmmssfff"), TenPayV3Util.BuildRandomStr(3));
}
#region 错误码
/*
错误码 描述 解决方案
NO_AUTH 发放失败,此请求可能存在风险,已被微信拦截 请提醒用户检查自身帐号是否异常。使用常用的活跃的微信号可避免这种情况。
SENDNUM_LIMIT 该用户今日领取红包个数超过限制 如有需要、请在微信支付商户平台【api安全】中重新配置 【每日同一用户领取本商户红包不允许超过的个数】。
CA_ERROR 请求未携带证书,或请求携带的证书出错 到商户平台下载证书,请求带上证书后重试。
ILLEGAL_APPID 错误传入了app的appid 接口传入的所有appid应该为公众号的appid(在mp.weixin.qq.com申请的),不能为APP的appid(在open.weixin.qq.com申请的)。
SIGN_ERROR 商户签名错误 按文档要求重新生成签名后再重试。
FREQ_LIMIT 受频率限制 请对请求做频率控制
XML_ERROR 请求的xml格式错误,或者post的数据为空 检查请求串,确认无误后重试
PARAM_ERROR 参数错误 请查看err_code_des,修改设置错误的参数
OPENID_ERROR Openid错误 根据用户在商家公众账号上的openid,获取用户在红包公众账号上的openid 错误。请核对商户自身公众号appid和用户在此公众号下的openid。
NOTENOUGH 余额不足 商户账号余额不足,请登录微信支付商户平台充值
FATAL_ERROR 重复请求时,参数与原单不一致 使用相同商户单号进行重复请求时,参数与第一次请求时不一致,请检查并修改参数后再重试。
SECOND_OVER_LIMITED 企业红包的按分钟发放受限 每分钟发送红包数量不得超过1800个;(可联系微信支付[email protected]调高额度)
DAY_ OVER_LIMITED 企业红包的按天日发放受限 单个商户日发送红包数量不大于10000个;(可联系微信支付[email protected]调高额度)
MONEY_LIMIT 红包金额发放限制 每个红包金额必须大于1元,小于1000元(可联系微信支付[email protected]调高额度至4999元)
SEND_FAILED 红包发放失败,请更换单号再重试 原商户单号已经失败,如果还要对同一个用户发放红包, 需要更换新的商户单号再试。
SYSTEMERROR 系统繁忙,请再试。 可用同一商户单号再次调用,只会发放一个红包
PROCESSING 请求已受理,请稍后使用原单号查询发放结果 二十分钟后查询,按照查询结果成功失败进行处理
*/
#endregion
/// <summary>
/// 普通红包发送
/// </summary>
/// <param name="appId">公众账号AppID</param>
/// <param name="mchId">商户MchID</param>
/// <param name="tenPayKey">支付密钥,微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置</param>
/// <param name="tenPayCertPath">证书地址(硬盘物理地址,形如E:\\cert\\apiclient_cert.p12)</param>
/// <param name="openId">要发红包的用户的OpenID</param>
/// <param name="senderName">红包发送者名称,会显示给接收红包的用户</param>
/// <param name="iP">发送红包的服务器地址</param>
/// <param name="redPackAmount">付款金额,单位分。红包金额大于200时,请求参数scene必传。</param>
/// <param name="wishingWord">祝福语</param>
/// <param name="actionName">活动名称(请注意活动名称长度,官方文档提示为32个字符,实际限制不足32个字符)</param>
/// <param name="remark">活动描述,用于低版本微信显示</param>
/// <param name="nonceStr">将nonceStr随机字符串返回,开发者可以存到数据库用于校验</param>
/// <param name="paySign">将支付签名返回,开发者可以存到数据库用于校验</param>
/// <param name="mchBillNo">商户订单号,新的订单号可以从RedPackApi.GetNewBillNo(mchId)方法获得,如果传入null,则系统自动生成</param>
/// <param name="scene">场景id(非必填),红包金额大于200时,请求参数scene必传</param>
/// <param name="riskInfo">活动信息(非必填),String(128)posttime:用户操作的时间戳。
/// <para>示例:posttime%3d123123412%26clientversion%3d234134%26mobile%3d122344545%26deviceid%3dIOS</para>
/// <para>mobile:业务系统账号的手机号,国家代码-手机号。不需要+号</para>
/// <para>deviceid :mac 地址或者设备唯一标识</para>
/// <para>clientversion :用户操作的客户端版本</para>
/// <para>把值为非空的信息用key = value进行拼接,再进行urlencode</para>
/// <para>urlencode(posttime= xx & mobile = xx & deviceid = xx)</para>
/// </param>
/// <param name="consumeMchId">资金授权商户号,服务商替特约商户发放时使用(非必填),String(32)。示例:1222000096</param>
/// <returns></returns>
public static NormalRedPackResult SendNormalRedPack(string appId, string mchId, string tenPayKey, string tenPayCertPath,
string openId, string senderName,
string iP, int redPackAmount, string wishingWord, string actionName, string remark,
out string nonceStr, out string paySign,
string mchBillNo, RedPack_Scene? scene = null, string riskInfo = null, string consumeMchId = null)
{
mchBillNo = mchBillNo ?? GetNewBillNo(mchId);
nonceStr = TenPayV3Util.GetNoncestr();
//RequestHandler packageReqHandler = new RequestHandler(null);
//string accessToken = AccessTokenContainer.GetAccessToken(ConstantClass.AppID);
//UserInfoJson userInforResult = UserApi.Info(accessToken, openID);
RequestHandler packageReqHandler = new RequestHandler();
//设置package订单参数
packageReqHandler.SetParameter("nonce_str", nonceStr); //随机字符串
packageReqHandler.SetParameter("wxappid", appId); //公众账号ID
packageReqHandler.SetParameter("mch_id", mchId); //商户号
packageReqHandler.SetParameter("mch_billno", mchBillNo); //填入商家订单号
packageReqHandler.SetParameter("send_name", senderName); //红包发送者名称
packageReqHandler.SetParameter("re_openid", openId); //接受收红包的用户的openId
packageReqHandler.SetParameter("total_amount", redPackAmount.ToString()); //付款金额,单位分
packageReqHandler.SetParameter("total_num", "1"); //红包发放总人数
packageReqHandler.SetParameter("wishing", wishingWord); //红包祝福语
packageReqHandler.SetParameter("client_ip", iP); //调用接口的机器Ip地址
packageReqHandler.SetParameter("act_name", actionName); //活动名称
packageReqHandler.SetParameter("remark", remark); //备注信息
if (scene.HasValue)
{
packageReqHandler.SetParameter("scene_id", scene.Value.ToString());//场景id
}
if (riskInfo != null)
{
packageReqHandler.SetParameter("risk_info", riskInfo);//活动信息
}
if (consumeMchId != null)
{
packageReqHandler.SetParameter("consume_mch_id", consumeMchId);//活动信息
}
paySign = packageReqHandler.CreateMd5Sign("key", tenPayKey);
packageReqHandler.SetParameter("sign", paySign); //签名
//最新的官方文档中将以下三个字段去除了
//packageReqHandler.SetParameter("nick_name", "提供方名称"); //提供方名称
//packageReqHandler.SetParameter("max_value", "100"); //最大红包金额,单位分
//packageReqHandler.SetParameter("min_value", "100"); //最小红包金额,单位分
//发红包需要post的数据
string data = packageReqHandler.ParseXML();
//发红包接口地址
string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
//本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
string cert = tenPayCertPath;
//私钥(在安装证书时设置)
string password = mchId;
//调用证书
X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
XmlDocument doc = new Senparc.CO2NET.ExtensionEntities.XmlDocument_XxeFixed();
#if NET451
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
//X509Certificate cer = new X509Certificate(cert, password);
#region 发起post请求
HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
webrequest.ClientCertificates.Add(cer);
webrequest.Method = "post";
byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
webrequest.ContentLength = postdatabyte.Length;
Stream stream = webrequest.GetRequestStream();
stream.Write(postdatabyte, 0, postdatabyte.Length);
stream.Close();
HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
string response = streamReader.ReadToEnd();
#endregion
doc.LoadXml(response);
#else
#region 发起post请求
HttpClientHandler handler = new HttpClientHandler();
handler.ClientCertificates.Add(cer);
HttpClient client = new HttpClient(handler);
HttpContent hc = new StringContent(data);
var request = client.PostAsync(url, hc).Result;
var response = request.Content.ReadAsStreamAsync().Result;
#endregion
doc.Load(response);
#endif
//XDocument xDoc = XDocument.Load(responseContent);
NormalRedPackResult normalReturn = new NormalRedPackResult
{
err_code = "",
err_code_des = ""
};
if (doc.SelectSingleNode("/xml/return_code") != null)
{
normalReturn.return_code = doc.SelectSingleNode("/xml/return_code").InnerText;
}
if (doc.SelectSingleNode("/xml/return_msg") != null)
{
normalReturn.return_msg = doc.SelectSingleNode("/xml/return_msg").InnerText;
}
if (normalReturn.ReturnCodeSuccess)
{
//redReturn.sign = doc.SelectSingleNode("/xml/sign").InnerText;
if (doc.SelectSingleNode("/xml/result_code") != null)
{
normalReturn.result_code = doc.SelectSingleNode("/xml/result_code").InnerText;
}
if (normalReturn.ResultCodeSuccess)
{
if (doc.SelectSingleNode("/xml/mch_billno") != null)
{
normalReturn.mch_billno = doc.SelectSingleNode("/xml/mch_billno").InnerText;
}
if (doc.SelectSingleNode("/xml/mch_id") != null)
{
normalReturn.mch_id = doc.SelectSingleNode("/xml/mch_id").InnerText;
}
if (doc.SelectSingleNode("/xml/wxappid") != null)
{
normalReturn.wxappid = doc.SelectSingleNode("/xml/wxappid").InnerText;
}
if (doc.SelectSingleNode("/xml/re_openid") != null)
{
normalReturn.re_openid = doc.SelectSingleNode("/xml/re_openid").InnerText;
}
if (doc.SelectSingleNode("/xml/total_amount") != null)
{
normalReturn.total_amount = doc.SelectSingleNode("/xml/total_amount").InnerText;
}
//裂变红包才有
if (doc.SelectSingleNode("/xml/send_time") != null)
{
normalReturn.send_time = doc.SelectSingleNode("/xml/send_time").InnerText;
}
//裂变红包才有
if (doc.SelectSingleNode("/xml/send_listid") != null)
{
normalReturn.send_listid = doc.SelectSingleNode("/xml/send_listid").InnerText;
}
}
else
{
if (doc.SelectSingleNode("/xml/err_code") != null)
{
normalReturn.err_code = doc.SelectSingleNode("/xml/err_code").InnerText;
}
if (doc.SelectSingleNode("/xml/err_code_des") != null)
{
normalReturn.err_code_des = doc.SelectSingleNode("/xml/err_code_des").InnerText;
}
if (doc.SelectSingleNode("/xml/mch_billno") != null)
{
normalReturn.mch_billno = doc.SelectSingleNode("/xml/mch_billno").InnerText;
}
if (doc.SelectSingleNode("/xml/mch_id") != null)
{
normalReturn.mch_id = doc.SelectSingleNode("/xml/mch_id").InnerText;
}
if (doc.SelectSingleNode("/xml/wxappid") != null)
{
normalReturn.wxappid = doc.SelectSingleNode("/xml/wxappid").InnerText;
}
if (doc.SelectSingleNode("/xml/re_openid") != null)
{
normalReturn.re_openid = doc.SelectSingleNode("/xml/re_openid").InnerText;
}
if (doc.SelectSingleNode("/xml/total_amount") != null)
{
normalReturn.total_amount = doc.SelectSingleNode("/xml/total_amount").InnerText;
}
}
}
return normalReturn;
}
#region v14.3.105中将发布
/// <summary>
/// 裂变红包发送
/// <para>裂变红包:一次可以发放一组红包。首先领取的用户为种子用户,种子用户领取一组红包当中的一个,并可以通过社交分享将剩下的红包给其他用户。裂变红包充分利用了人际传播的优势。</para>
/// </summary>
/// <param name="appId">公众账号AppID</param>
/// <param name="mchId">商户MchID</param>
/// <param name="tenPayKey">支付密钥,微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置</param>
/// <param name="tenPayCertPath">证书地址(硬盘物理地址,形如E:\\cert\\apiclient_cert.p12)</param>
/// <param name="openId">要发红包的用户的OpenID</param>
/// <param name="senderName">红包发送者名称,会显示给接收红包的用户</param>
/// <param name="iP">发送红包的服务器地址</param>
/// <param name="redPackAmount">付款金额,单位分。红包金额大于200时,请求参数scene必传。</param>
/// <param name="wishingWord">祝福语</param>
/// <param name="actionName">活动名称(请注意活动名称长度,官方文档提示为32个字符,实际限制不足32个字符)</param>
/// <param name="remark">活动描述,用于低版本微信显示</param>
/// <param name="nonceStr">将nonceStr随机字符串返回,开发者可以存到数据库用于校验</param>
/// <param name="paySign">将支付签名返回,开发者可以存到数据库用于校验</param>
/// <param name="mchBillNo">商户订单号,新的订单号可以从RedPackApi.GetNewBillNo(mchId)方法获得,如果传入null,则系统自动生成</param>
/// <param name="scene">场景id(非必填),红包金额大于200时,请求参数scene必传</param>
/// <param name="riskInfo">活动信息(非必填),String(128)posttime:用户操作的时间戳。
/// <para>示例:posttime%3d123123412%26clientversion%3d234134%26mobile%3d122344545%26deviceid%3dIOS</para>
/// <para>mobile:业务系统账号的手机号,国家代码-手机号。不需要+号</para>
/// <para>deviceid :mac 地址或者设备唯一标识</para>
/// <para>clientversion :用户操作的客户端版本</para>
/// <para>把值为非空的信息用key = value进行拼接,再进行urlencode</para>
/// <para>urlencode(posttime= xx & mobile = xx & deviceid = xx)</para>
/// </param>
/// <param name="consumeMchId">资金授权商户号,服务商替特约商户发放时使用(非必填),String(32)。示例:1222000096</param>
/// <param name="amtType">红包金额设置方式,默认填写“ALL_RAND”,ALL_RAND—全部随机,商户指定总金额和红包发放总人数,由微信支付随机计算出各红包金额</param>
/// <returns></returns>
public static NormalRedPackResult SendNGroupRedPack(string appId, string mchId, string tenPayKey, string tenPayCertPath,
string openId, string senderName,
string iP, int redPackAmount, string wishingWord, string actionName, string remark,
out string nonceStr, out string paySign, string mchBillNo, RedPack_Scene? scene = null, string riskInfo = null, string consumeMchId = null, string amtType = "ALL_RAND", int total_num = 3)
{
mchBillNo = mchBillNo ?? GetNewBillNo(mchId);
nonceStr = TenPayV3Util.GetNoncestr();
//RequestHandler packageReqHandler = new RequestHandler(null);
//string accessToken = AccessTokenContainer.GetAccessToken(ConstantClass.AppID);
//UserInfoJson userInforResult = UserApi.Info(accessToken, openID);
RequestHandler packageReqHandler = new RequestHandler();
//设置package订单参数
packageReqHandler.SetParameter("mch_billno", mchBillNo); //填入商家订单号
packageReqHandler.SetParameter("mch_id", mchId); //商户号
packageReqHandler.SetParameter("wxappid", appId); //公众账号ID
packageReqHandler.SetParameter("send_name", senderName); //红包发送者名称
packageReqHandler.SetParameter("re_openid", openId); //接受收红包的用户的openId
packageReqHandler.SetParameter("total_amount", redPackAmount.ToString()); //付款金额,单位分
packageReqHandler.SetParameter("amt_type", amtType); //签名
packageReqHandler.SetParameter("total_num", total_num.ToString()); //红包发放总人数
packageReqHandler.SetParameter("wishing", wishingWord); //红包祝福语
packageReqHandler.SetParameter("act_name", actionName); //活动名称
packageReqHandler.SetParameter("remark", remark); //备注信息
//比普通红包多的部分
if (scene.HasValue)
{
packageReqHandler.SetParameter("scene_id", scene.Value.ToString());//场景id
}
packageReqHandler.SetParameter("nonce_str", nonceStr); //随机字符串
if (riskInfo != null)
{
packageReqHandler.SetParameter("risk_info", riskInfo);//活动信息
}
if (consumeMchId != null)
{
packageReqHandler.SetParameter("consume_mch_id", consumeMchId);//活动信息
}
paySign = packageReqHandler.CreateMd5Sign("key", tenPayKey);
packageReqHandler.SetParameter("sign", paySign); //签名
//最新的官方文档中将以下三个字段去除了
//packageReqHandler.SetParameter("nick_name", "提供方名称"); //提供方名称
//packageReqHandler.SetParameter("max_value", "100"); //最大红包金额,单位分
//packageReqHandler.SetParameter("min_value", "100"); //最小红包金额,单位分
//发红包需要post的数据
string data = packageReqHandler.ParseXML();
//发红包接口地址
//string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendgroupredpack";
//本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
string cert = tenPayCertPath;
//私钥(在安装证书时设置)
string password = mchId;
//调用证书
X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
XmlDocument doc = new Senparc.CO2NET.ExtensionEntities.XmlDocument_XxeFixed();
#region 发起post请求,载入到doc中
#if NET451
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
//X509Certificate cer = new X509Certificate(cert, password);
HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
webrequest.ClientCertificates.Add(cer);
webrequest.Method = "post";
byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
webrequest.ContentLength = postdatabyte.Length;
Stream stream = webrequest.GetRequestStream();
stream.Write(postdatabyte, 0, postdatabyte.Length);
stream.Close();
HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
string response = streamReader.ReadToEnd();
doc.LoadXml(response);
#else
HttpClientHandler handler = new HttpClientHandler();
handler.ClientCertificates.Add(cer);
HttpClient client = new HttpClient(handler);
HttpContent hc = new StringContent(data);
var request = client.PostAsync(url, hc).Result;
var response = request.Content.ReadAsStreamAsync().Result;
doc.Load(response);
#endif
#endregion
//XDocument xDoc = XDocument.Load(responseContent);
//if (xDoc==null)
//{
// throw new WeixinException("微信支付XML响应格式错误");
//}
NormalRedPackResult normalReturn = new NormalRedPackResult
{
err_code = "",
err_code_des = ""
};
if (doc.SelectSingleNode("/xml/return_code") != null)
{
normalReturn.return_code = doc.SelectSingleNode("/xml/return_code").InnerText;
}
if (doc.SelectSingleNode("/xml/return_msg") != null)
{
normalReturn.return_msg = doc.SelectSingleNode("/xml/return_msg").InnerText;
}
if (normalReturn.ReturnCodeSuccess)
{
//redReturn.sign = doc.SelectSingleNode("/xml/sign").InnerText;
if (doc.SelectSingleNode("/xml/result_code") != null)
{
normalReturn.result_code = doc.SelectSingleNode("/xml/result_code").InnerText;
}
if (normalReturn.ResultCodeSuccess)
{
if (doc.SelectSingleNode("/xml/mch_billno") != null)
{
normalReturn.mch_billno = doc.SelectSingleNode("/xml/mch_billno").InnerText;
}
if (doc.SelectSingleNode("/xml/mch_id") != null)
{
normalReturn.mch_id = doc.SelectSingleNode("/xml/mch_id").InnerText;
}
if (doc.SelectSingleNode("/xml/wxappid") != null)
{
normalReturn.wxappid = doc.SelectSingleNode("/xml/wxappid").InnerText;
}
if (doc.SelectSingleNode("/xml/re_openid") != null)
{
normalReturn.re_openid = doc.SelectSingleNode("/xml/re_openid").InnerText;
}
if (doc.SelectSingleNode("/xml/total_amount") != null)
{
normalReturn.total_amount = doc.SelectSingleNode("/xml/total_amount").InnerText;
}
//裂变红包才有
if (doc.SelectSingleNode("/xml/send_time") != null)
{
normalReturn.send_time = doc.SelectSingleNode("/xml/send_time").InnerText;
}
//裂变红包才有
if (doc.SelectSingleNode("/xml/send_listid") != null)
{
normalReturn.send_listid = doc.SelectSingleNode("/xml/send_listid").InnerText;
}
}
else
{
if (doc.SelectSingleNode("/xml/err_code") != null)
{
normalReturn.err_code = doc.SelectSingleNode("/xml/err_code").InnerText;
}
if (doc.SelectSingleNode("/xml/err_code_des") != null)
{
normalReturn.err_code_des = doc.SelectSingleNode("/xml/err_code_des").InnerText;
}
if (doc.SelectSingleNode("/xml/mch_billno") != null)
{
normalReturn.mch_billno = doc.SelectSingleNode("/xml/mch_billno").InnerText;
}
if (doc.SelectSingleNode("/xml/mch_id") != null)
{
normalReturn.mch_id = doc.SelectSingleNode("/xml/mch_id").InnerText;
}
if (doc.SelectSingleNode("/xml/wxappid") != null)
{
normalReturn.wxappid = doc.SelectSingleNode("/xml/wxappid").InnerText;
}
if (doc.SelectSingleNode("/xml/re_openid") != null)
{
normalReturn.re_openid = doc.SelectSingleNode("/xml/re_openid").InnerText;
}
if (doc.SelectSingleNode("/xml/total_amount") != null)
{
normalReturn.total_amount = doc.SelectSingleNode("/xml/total_amount").InnerText;
}
}
}
return normalReturn;
}
#endregion
/// <summary>
/// 查询红包(包括普通红包和裂变红包)
/// </summary>
/// <param name="appId">公众账号AppID</param>
/// <param name="mchId">商户MchID</param>
/// <param name="tenPayKey">支付密钥,微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置</param>
/// <param name="tenPayCertPath">证书地址(硬盘地址,形如E://cert//apiclient_cert.p12)</param>
/// <param name="mchBillNo">商家订单号</param>
/// <returns></returns>
public static SearchRedPackResult SearchRedPack(string appId, string mchId, string tenPayKey, string tenPayCertPath, string mchBillNo)
{
string nonceStr = TenPayV3Util.GetNoncestr();
RequestHandler packageReqHandler = new RequestHandler();
packageReqHandler.SetParameter("nonce_str", nonceStr); //随机字符串
packageReqHandler.SetParameter("appid", appId); //公众账号ID
packageReqHandler.SetParameter("mch_id", mchId); //商户号
packageReqHandler.SetParameter("mch_billno", mchBillNo); //填入商家订单号
packageReqHandler.SetParameter("bill_type", "MCHT"); //MCHT:通过商户订单号获取红包信息。
string sign = packageReqHandler.CreateMd5Sign("key", tenPayKey);
packageReqHandler.SetParameter("sign", sign); //签名
//发红包需要post的数据
string data = packageReqHandler.ParseXML();
//发红包接口地址
string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo";
//本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
string cert = tenPayCertPath;
//私钥(在安装证书时设置)
string password = mchId;
//调用证书
//X509Certificate cer = new X509Certificate(cert, password);
X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
XmlDocument doc = new Senparc.CO2NET.ExtensionEntities.XmlDocument_XxeFixed();
#region 发起post请求,载入到doc中
#if NET451
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
webrequest.ClientCertificates.Add(cer);
webrequest.Method = "post";
byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
webrequest.ContentLength = postdatabyte.Length;
Stream stream = webrequest.GetRequestStream();
stream.Write(postdatabyte, 0, postdatabyte.Length);
stream.Close();
HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
string response = streamReader.ReadToEnd();
doc.LoadXml(response);
#else
HttpClientHandler handler = new HttpClientHandler();
handler.ClientCertificates.Add(cer);
HttpClient client = new HttpClient(handler);
HttpContent hc = new StringContent(data);
var request = client.PostAsync(url, hc).Result;
var response = request.Content.ReadAsStreamAsync().Result;
doc.Load(response);
#endif
#endregion
SearchRedPackResult searchReturn = new SearchRedPackResult
{
err_code = "",
err_code_des = ""
};
if (doc.SelectSingleNode("/xml/return_code") != null)
{
searchReturn.return_code = (doc.SelectSingleNode("/xml/return_code").InnerText.ToUpper() == "SUCCESS");
}
if (doc.SelectSingleNode("/xml/return_msg") != null)
{
searchReturn.return_msg = doc.SelectSingleNode("/xml/return_msg").InnerText;
}
if (searchReturn.return_code == true)
{
//redReturn.sign = doc.SelectSingleNode("/xml/sign").InnerText;
if (doc.SelectSingleNode("/xml/result_code") != null)
{
searchReturn.result_code = (doc.SelectSingleNode("/xml/result_code").InnerText.ToUpper() == "SUCCESS");
}
if (searchReturn.result_code == true)
{
if (doc.SelectSingleNode("/xml/mch_billno") != null)
{
searchReturn.mch_billno = doc.SelectSingleNode("/xml/mch_billno").InnerText;
}
if (doc.SelectSingleNode("/xml/mch_id") != null)
{
searchReturn.mch_id = doc.SelectSingleNode("/xml/mch_id").InnerText;
}
if (doc.SelectSingleNode("/xml/detail_id") != null)
{
searchReturn.detail_id = doc.SelectSingleNode("/xml/detail_id").InnerText;
}
if (doc.SelectSingleNode("/xml/status") != null)
{
searchReturn.status = doc.SelectSingleNode("/xml/status").InnerText;
}
if (doc.SelectSingleNode("/xml/send_type") != null)
{
searchReturn.send_type = doc.SelectSingleNode("/xml/send_type").InnerText;
}
if (doc.SelectSingleNode("/xml/hb_type") != null)
{
searchReturn.hb_type = doc.SelectSingleNode("/xml/hb_type").InnerText;
}
if (doc.SelectSingleNode("/xml/total_num") != null)
{
searchReturn.total_num = doc.SelectSingleNode("/xml/total_num").InnerText;
}
if (doc.SelectSingleNode("/xml/total_amount") != null)
{
searchReturn.total_amount = doc.SelectSingleNode("/xml/total_amount").InnerText;
}
if (doc.SelectSingleNode("/xml/reason") != null)
{
searchReturn.reason = doc.SelectSingleNode("/xml/reason").InnerText;
}
if (doc.SelectSingleNode("/xml/send_time") != null)
{
searchReturn.send_time = doc.SelectSingleNode("/xml/send_time").InnerText;
}
if (doc.SelectSingleNode("/xml/refund_time") != null)
{
searchReturn.refund_time = doc.SelectSingleNode("/xml/refund_time").InnerText;
}
if (doc.SelectSingleNode("/xml/refund_amount") != null)
{
searchReturn.refund_amount = doc.SelectSingleNode("/xml/refund_amount").InnerText;
}
if (doc.SelectSingleNode("/xml/wishing") != null)
{
searchReturn.wishing = doc.SelectSingleNode("/xml/wishing").InnerText;
}
if (doc.SelectSingleNode("/xml/remark") != null)
{
searchReturn.remark = doc.SelectSingleNode("/xml/remark").InnerText;
}
if (doc.SelectSingleNode("/xml/act_name") != null)
{
searchReturn.act_name = doc.SelectSingleNode("/xml/act_name").InnerText;
}
if (doc.SelectSingleNode("/xml/hblist") != null)
{
searchReturn.hblist = new List<RedPackHBInfo>();
foreach (XmlNode hbinfo in doc.SelectNodes("/xml/hblist/hbinfo"))
{
RedPackHBInfo wechatHBInfo = new RedPackHBInfo();
wechatHBInfo.openid = hbinfo.SelectSingleNode("openid").InnerText;
//wechatHBInfo.status = hbinfo.SelectSingleNode("status").InnerText;
wechatHBInfo.amount = hbinfo.SelectSingleNode("amount").InnerText;
wechatHBInfo.rcv_time = hbinfo.SelectSingleNode("rcv_time").InnerText;
searchReturn.hblist.Add(wechatHBInfo);
}
}
}
else
{
if (doc.SelectSingleNode("/xml/err_code") != null)
{
searchReturn.err_code = doc.SelectSingleNode("/xml/err_code").InnerText;
}
if (doc.SelectSingleNode("/xml/err_code_des") != null)
{
searchReturn.err_code_des = doc.SelectSingleNode("/xml/err_code_des").InnerText;
}
}
}
return searchReturn;
}
/// <summary>
/// 发送小程序红包
/// </summary>
/// <param name="appId">公众账号AppID</param>
/// <param name="mchId">商户MchID</param>
/// <param name="tenPayKey">支付密钥,微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置</param>
/// <param name="tenPayCertPath">证书地址(硬盘物理地址,形如E:\\cert\\apiclient_cert.p12)</param>
/// <param name="openId">要发红包的用户的OpenID</param>
/// <param name="senderName">红包发送者名称,会显示给接收红包的用户</param>
/// <param name="redPackAmount">付款金额,单位分。红包金额大于200时,请求参数scene必传。</param>
/// <param name="wishingWord">祝福语</param>
/// <param name="actionName">活动名称(请注意活动名称长度,官方文档提示为32个字符,实际限制不足32个字符)</param>
/// <param name="remark">活动描述,用于低版本微信显示</param>
/// <param name="nonceStr">将nonceStr随机字符串返回,开发者可以存到数据库用于校验</param>
/// <param name="paySign">将支付签名返回,开发者可以存到数据库用于校验</param>
/// <param name="mchBillNo">商户订单号,新的订单号可以从RedPackApi.GetNewBillNo(mchId)方法获得,如果传入null,则系统自动生成</param>
/// <param name="scene">场景id(非必填),红包金额大于200时,请求参数scene必传</param>
/// <param name="consumeMchId">资金授权商户号,服务商替特约商户发放时使用(非必填),String(32)。示例:1222000096</param>
/// <returns></returns>
public static MiniAppRedPackResult SendMiniAppRedPack(string appId, string mchId, string tenPayKey, string tenPayCertPath,
string openId, string senderName,
int redPackAmount, string wishingWord, string actionName, string remark,
out string nonceStr, out string paySign,
string mchBillNo, RedPack_Scene? scene = null, string consumeMchId = null)
{
mchBillNo = mchBillNo ?? GetNewBillNo(mchId);
nonceStr = TenPayV3Util.GetNoncestr();
RequestHandler packageReqHandler = new RequestHandler();
//设置package订单参数
packageReqHandler.SetParameter("nonce_str", nonceStr); //随机字符串
packageReqHandler.SetParameter("wxappid", appId); //公众账号ID
packageReqHandler.SetParameter("mch_id", mchId); //商户号
packageReqHandler.SetParameter("mch_billno", mchBillNo); //填入商家订单号
packageReqHandler.SetParameter("send_name", senderName); //红包发送者名称
packageReqHandler.SetParameter("re_openid", openId); //接受收红包的用户的openId
packageReqHandler.SetParameter("total_amount", redPackAmount.ToString()); //付款金额,单位分
packageReqHandler.SetParameter("total_num", "1"); //红包发放总人数
packageReqHandler.SetParameter("wishing", wishingWord); //红包祝福语
packageReqHandler.SetParameter("act_name", actionName); //活动名称
packageReqHandler.SetParameter("remark", remark); //备注信息
packageReqHandler.SetParameter("notify_way", "MINI_PROGRAM_JSAPI"); //通知用户形式,通过JSAPI方式领取红包,小程序红包固定传"MINI_PROGRAM_JSAPI"
if (scene.HasValue)
{
packageReqHandler.SetParameter("scene_id", scene.Value.ToString()); //场景id
}
if (consumeMchId != null)
{
packageReqHandler.SetParameter("consume_mch_id", consumeMchId); //活动信息
}
paySign = packageReqHandler.CreateMd5Sign("key", tenPayKey);
packageReqHandler.SetParameter("sign", paySign); //签名
//发红包需要post的数据
string data = packageReqHandler.ParseXML();
//发红包接口地址
string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendminiprogramhb";
//本地或者服务器的证书位置(证书在微信支付申请成功发来的通知邮件中)
string cert = tenPayCertPath;
//私钥(在安装证书时设置)
string password = mchId;
//调用证书
X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
XmlDocument doc = new Senparc.CO2NET.ExtensionEntities.XmlDocument_XxeFixed();
#if NET451
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
//X509Certificate cer = new X509Certificate(cert, password);
#region 发起post请求
HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
webrequest.ClientCertificates.Add(cer);
webrequest.Method = "post";
byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
webrequest.ContentLength = postdatabyte.Length;
Stream stream = webrequest.GetRequestStream();
stream.Write(postdatabyte, 0, postdatabyte.Length);
stream.Close();
HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
string response = streamReader.ReadToEnd();
#endregion
doc.LoadXml(response);
#else
#region 发起post请求
HttpClientHandler handler = new HttpClientHandler();
handler.ClientCertificates.Add(cer);
HttpClient client = new HttpClient(handler);
HttpContent hc = new StringContent(data);
var request = client.PostAsync(url, hc).Result;
var response = request.Content.ReadAsStreamAsync().Result;
#endregion
doc.Load(response);
#endif
//XDocument xDoc = XDocument.Load(responseContent);
MiniAppRedPackResult miniAppRedPackResult = new MiniAppRedPackResult
{
err_code = "",
err_code_des = ""
};
if (doc.SelectSingleNode("/xml/return_code") != null)
{
miniAppRedPackResult.return_code = doc.SelectSingleNode("/xml/return_code").InnerText;
}
if (doc.SelectSingleNode("/xml/return_msg") != null)
{
miniAppRedPackResult.return_msg = doc.SelectSingleNode("/xml/return_msg").InnerText;
}
if (miniAppRedPackResult.ReturnCodeSuccess)
{
//redReturn.sign = doc.SelectSingleNode("/xml/sign").InnerText;
if (doc.SelectSingleNode("/xml/result_code") != null)
{
miniAppRedPackResult.result_code = doc.SelectSingleNode("/xml/result_code").InnerText;
}
if (miniAppRedPackResult.ResultCodeSuccess)
{
if (doc.SelectSingleNode("/xml/mch_billno") != null)
{
miniAppRedPackResult.mch_billno = doc.SelectSingleNode("/xml/mch_billno").InnerText;
}
if (doc.SelectSingleNode("/xml/mch_id") != null)
{
miniAppRedPackResult.mch_id = doc.SelectSingleNode("/xml/mch_id").InnerText;
}
if (doc.SelectSingleNode("/xml/wxappid") != null)
{
miniAppRedPackResult.wxappid = doc.SelectSingleNode("/xml/wxappid").InnerText;
}
if (doc.SelectSingleNode("/xml/re_openid") != null)
{
miniAppRedPackResult.re_openid = doc.SelectSingleNode("/xml/re_openid").InnerText;
}
if (doc.SelectSingleNode("/xml/total_amount") != null)
{
miniAppRedPackResult.total_amount = doc.SelectSingleNode("/xml/total_amount").InnerText;
}
//小程序红包才有
if (doc.SelectSingleNode("/xml/send_listid") != null)
{
miniAppRedPackResult.package = doc.SelectSingleNode("/xml/package").InnerText;
}
}
else
{
if (doc.SelectSingleNode("/xml/err_code") != null)
{
miniAppRedPackResult.err_code = doc.SelectSingleNode("/xml/err_code").InnerText;
}
if (doc.SelectSingleNode("/xml/err_code_des") != null)
{
miniAppRedPackResult.err_code_des = doc.SelectSingleNode("/xml/err_code_des").InnerText;
}
if (doc.SelectSingleNode("/xml/mch_billno") != null)
{
miniAppRedPackResult.mch_billno = doc.SelectSingleNode("/xml/mch_billno").InnerText;
}
if (doc.SelectSingleNode("/xml/mch_id") != null)
{
miniAppRedPackResult.mch_id = doc.SelectSingleNode("/xml/mch_id").InnerText;
}
if (doc.SelectSingleNode("/xml/wxappid") != null)
{
miniAppRedPackResult.wxappid = doc.SelectSingleNode("/xml/wxappid").InnerText;
}
if (doc.SelectSingleNode("/xml/re_openid") != null)
{
miniAppRedPackResult.re_openid = doc.SelectSingleNode("/xml/re_openid").InnerText;
}
if (doc.SelectSingleNode("/xml/total_amount") != null)
{
miniAppRedPackResult.total_amount = doc.SelectSingleNode("/xml/total_amount").InnerText;
}
}
}
return miniAppRedPackResult;
}
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
if (errors == SslPolicyErrors.None)
return true;
return false;
}
}
}
| 46.629897 | 199 | 0.564967 | [
"Apache-2.0"
] | MLForkOpenSource/WeiXinMPSDK | src/Senparc.Weixin.TenPay/Senparc.Weixin.TenPay/V3/Universal/RedPackApi/RedPackApi.cs | 51,005 | C# |
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Aop.Api.Domain
{
/// <summary>
/// MybankCreditSceneprodDrawdownConfirmModel Data Structure.
/// </summary>
[Serializable]
public class MybankCreditSceneprodDrawdownConfirmModel : AopObject
{
/// <summary>
/// 网商针对一次客户主动申请生成的申请单据编号
/// </summary>
[XmlElement("apply_no")]
public string ApplyNo { get; set; }
/// <summary>
/// 证件主体名称
/// </summary>
[XmlElement("cert_name")]
public string CertName { get; set; }
/// <summary>
/// 证件号码
/// </summary>
[XmlElement("cert_no")]
public string CertNo { get; set; }
/// <summary>
/// 证件类型
/// </summary>
[XmlElement("cert_type")]
public string CertType { get; set; }
/// <summary>
/// 支用详情列表
/// </summary>
[XmlArray("drawdown_list")]
[XmlArrayItem("scene_drawdown_detail")]
public List<SceneDrawdownDetail> DrawdownList { get; set; }
/// <summary>
/// 错误原因 ,成功可以不填
/// </summary>
[XmlElement("error_msg")]
public string ErrorMsg { get; set; }
/// <summary>
/// 资方生成的申请单号
/// </summary>
[XmlElement("fin_order_no")]
public string FinOrderNo { get; set; }
/// <summary>
/// 放款结果,成功:Y,失败:N
/// </summary>
[XmlElement("process_result")]
public string ProcessResult { get; set; }
/// <summary>
/// 放款通知备注信息
/// </summary>
[XmlElement("remark")]
public string Remark { get; set; }
/// <summary>
/// 标识一次业务交互, 网商的ipRoleId+"_"YYYYMMDD+35位流水号, 最后2,3位要求是数字。
/// </summary>
[XmlElement("request_id")]
public string RequestId { get; set; }
}
}
| 26.466667 | 71 | 0.50529 | [
"Apache-2.0"
] | 554393109/alipay-sdk-net-all | AlipaySDKNet.Standard/Domain/MybankCreditSceneprodDrawdownConfirmModel.cs | 2,197 | C# |
using MassTransit;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Msape.BookKeeping.Service
{
public class MassTransitHostedService : BackgroundService
{
private readonly IBusControl _bus;
public MassTransitHostedService(IBusControl bus)
{
_bus = bus ?? throw new ArgumentNullException(nameof(bus));
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var handle = await _bus.StartAsync(stoppingToken).ConfigureAwait(false);
var tcs = new TaskCompletionSource<object>();
using(stoppingToken.Register(() => tcs.TrySetResult(new object())))
{
await tcs.Task.ConfigureAwait(false);
}
await handle.StopAsync(stoppingToken).ConfigureAwait(false);
}
}
}
| 31.466667 | 85 | 0.637712 | [
"Apache-2.0"
] | gideonkorir/Msape-sql | src/BookKeeping/Msape.BookKeeping.Service/MassTransitHostedService.cs | 946 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ark.Models
{
public interface ConnectionInfo
{
string Hostname {get; set;}
int Port {get; set;}
string Password {get; set;}
}
}
| 18.25 | 35 | 0.667808 | [
"MIT"
] | Fratser/iNGEN-Ark-RCON-Desktop | Ark/Models/ConnectionInfo.cs | 294 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using CommandLine;
namespace Test.EndToEnd.Baselining.Options
{
[Verb("debug", HelpText = "Debug Baselining for a specific Series, Log, and Result")]
public class DebugOptions : OptionsBase
{
[Value(1, Required = true, HelpText = "Debug: Series Path (path string after 'Input/')")]
public string DebugSeriesPath { get; set; }
[Value(2, Required = false, Default = -1, HelpText = "Debug: Log Index")]
public int DebugLogIndex { get; set; }
[Value(3, Required = false, Default = -1, HelpText = "Debug: Result Index")]
public int DebugResultIndex { get; set; }
}
}
| 34.571429 | 97 | 0.65427 | [
"MIT"
] | Eduardo-Silla/sarif-sdk | src/Test.EndToEnd.Baselining/Options/DebugOptions.cs | 726 | C# |
using System;
using Dapper;
using System.Collections.Generic;
namespace DTcms.Model
{
#region URL字典实体类============================
/// <summary>
/// URL字典实体类
/// </summary>
[Serializable]
public partial class url_rewrite
{
//无参构造函数
public url_rewrite() { }
private string _name = string.Empty;
private string _type = string.Empty;
private string _page = string.Empty;
private string _inherit = string.Empty;
private string _templet = string.Empty;
private string _site = string.Empty;
private string _channel = string.Empty;
private string _pagesize = string.Empty;
private string _url_rewrite_str = string.Empty;
/// <summary>
/// 名称标识
/// </summary>
public string name
{
get { return _name; }
set { _name = value; }
}
/// <summary>
/// 频道类型
/// </summary>
public string type
{
get { return _type; }
set { _type = value; }
}
/// <summary>
/// 源页面地址
/// </summary>
public string page
{
get { return _page; }
set { _page = value; }
}
/// <summary>
/// 页面继承的类名
/// </summary>
public string inherit
{
get { return _inherit; }
set { _inherit = value; }
}
/// <summary>
/// 模板文件名称
/// </summary>
public string templet
{
get { return _templet; }
set { _templet = value; }
}
/// <summary>
/// 所属网站
/// </summary>
public string site
{
get { return _site; }
set { _site = value; }
}
/// <summary>
/// 所属频道名称
/// </summary>
public string channel
{
get { return _channel; }
set { _channel = value; }
}
/// <summary>
/// 每页数量,类型为列表页时启用该字段
/// </summary>
public string pagesize
{
get { return _pagesize; }
set { _pagesize = value; }
}
/// <summary>
/// URL重写表达式连接字符串,后台编辑用到
/// </summary>
public string url_rewrite_str
{
get { return _url_rewrite_str; }
set { _url_rewrite_str = value; }
}
#region 非数据库字段
[ResultColumn]
/// <summary>
/// URL字典重写表达式
/// </summary>
public List<url_rewrite_item> url_rewrite_items { get; set; }
#endregion
}
#endregion
#region URL字典重写表达式实体类==================
/// <summary>
/// URL字典重写表达式实体类
/// </summary>
[Serializable]
public partial class url_rewrite_item
{
//无参构造函数
public url_rewrite_item() { }
private string _path = "";
private string _pattern = "";
private string _querystring = "";
/// <summary>
/// URL重写表达式
/// </summary>
public string path
{
get { return _path; }
set { _path = value; }
}
/// <summary>
/// 正则表达式
/// </summary>
public string pattern
{
get { return _pattern; }
set { _pattern = value; }
}
/// <summary>
/// 传输参数
/// </summary>
public string querystring
{
get { return _querystring; }
set { _querystring = value; }
}
}
#endregion
} | 23.63125 | 70 | 0.432954 | [
"Apache-2.0"
] | flyingsnailcode/DTCMS_MVC | DTcms.Model/url_rewrite.cs | 4,061 | C# |
// Copyright (C) 2009-2020 Xtensive LLC.
// This code is distributed under MIT license terms.
// See the License.txt file in the project root for more information.
using System.Diagnostics;
using System.Text;
using Xtensive.Sql.Dml;
using Xtensive.Sql.Model;
namespace Xtensive.Sql.Drivers.PostgreSql.v8_2
{
internal class Translator : v8_1.Translator
{
[DebuggerStepThrough]
public override string QuoteString(string str)
{
return "E'" + str.Replace("'", "''").Replace(@"\", @"\\").Replace("\0", string.Empty) + "'";
}
protected override void AppendIndexStorageParameters(StringBuilder builder, Index index)
{
if (index.FillFactor != null) {
_ = builder.AppendFormat("WITH(FILLFACTOR={0})", index.FillFactor);
}
}
public override string Translate(SqlFunctionType type)
{
switch (type) {
//date
case SqlFunctionType.CurrentDate:
return "date_trunc('day', clock_timestamp())";
case SqlFunctionType.CurrentTimeStamp:
return "clock_timestamp()";
default:
return base.Translate(type);
}
}
// Constructors
public Translator(SqlDriver driver)
: base(driver)
{
}
}
} | 25.708333 | 98 | 0.645057 | [
"MIT"
] | DataObjects-NET/dataobjects-net | Orm/Xtensive.Orm.PostgreSql/Sql.Drivers.PostgreSql/v8_2/Translator.cs | 1,234 | C# |
namespace AutomationApp
{
partial class AutomationUI
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.pageControl1 = new System.Windows.Forms.TabControl();
this.mainPage = new System.Windows.Forms.TabPage();
this.clearCache = new System.Windows.Forms.Button();
this.readCache = new System.Windows.Forms.Button();
this.invalidateToken = new System.Windows.Forms.Button();
this.expireAccessToken = new System.Windows.Forms.Button();
this.acquireTokenSilent = new System.Windows.Forms.Button();
this.acquireToken = new System.Windows.Forms.Button();
this.dataInputPage = new System.Windows.Forms.TabPage();
this.GoBtn = new System.Windows.Forms.Button();
this.dataInput = new System.Windows.Forms.TextBox();
this.resultPage = new System.Windows.Forms.TabPage();
this.messageResult = new System.Windows.Forms.Label();
this.scopeResult = new System.Windows.Forms.ListBox();
this.exceptionResult = new System.Windows.Forms.Label();
this.scope = new System.Windows.Forms.Label();
this.idTokenResult = new System.Windows.Forms.Label();
this.idToken = new System.Windows.Forms.Label();
this.userResult = new System.Windows.Forms.Label();
this.user = new System.Windows.Forms.Label();
this.tenantIdResult = new System.Windows.Forms.Label();
this.tenantId = new System.Windows.Forms.Label();
this.expiresOnResult = new System.Windows.Forms.Label();
this.expiresOn = new System.Windows.Forms.Label();
this.accessTokenResult = new System.Windows.Forms.Label();
this.accessToken = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.msalLogs = new System.Windows.Forms.TextBox();
this.Done = new System.Windows.Forms.Button();
this.pageControl1.SuspendLayout();
this.mainPage.SuspendLayout();
this.dataInputPage.SuspendLayout();
this.resultPage.SuspendLayout();
this.SuspendLayout();
//
// pageControl1
//
this.pageControl1.Controls.Add(this.mainPage);
this.pageControl1.Controls.Add(this.dataInputPage);
this.pageControl1.Controls.Add(this.resultPage);
this.pageControl1.Location = new System.Drawing.Point(9, 8);
this.pageControl1.Name = "pageControl1";
this.pageControl1.SelectedIndex = 0;
this.pageControl1.Size = new System.Drawing.Size(551, 729);
this.pageControl1.TabIndex = 0;
//
// mainPage
//
this.mainPage.Controls.Add(this.clearCache);
this.mainPage.Controls.Add(this.readCache);
this.mainPage.Controls.Add(this.invalidateToken);
this.mainPage.Controls.Add(this.expireAccessToken);
this.mainPage.Controls.Add(this.acquireTokenSilent);
this.mainPage.Controls.Add(this.acquireToken);
this.mainPage.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.mainPage.Location = new System.Drawing.Point(8, 27);
this.mainPage.Name = "mainPage";
this.mainPage.Padding = new System.Windows.Forms.Padding(3, 3, 3, 3);
this.mainPage.Size = new System.Drawing.Size(535, 694);
this.mainPage.TabIndex = 0;
this.mainPage.Text = "Main Page";
this.mainPage.UseVisualStyleBackColor = true;
//
// clearCache
//
this.clearCache.Enabled = false;
this.clearCache.Location = new System.Drawing.Point(162, 414);
this.clearCache.Name = "clearCache";
this.clearCache.Size = new System.Drawing.Size(235, 46);
this.clearCache.TabIndex = 5;
this.clearCache.Text = "Clear Cache";
this.clearCache.UseVisualStyleBackColor = true;
//
// readCache
//
this.readCache.Enabled = false;
this.readCache.Location = new System.Drawing.Point(161, 329);
this.readCache.Name = "readCache";
this.readCache.Size = new System.Drawing.Size(236, 45);
this.readCache.TabIndex = 4;
this.readCache.Text = "Read Cache";
this.readCache.UseVisualStyleBackColor = true;
//
// invalidateToken
//
this.invalidateToken.Enabled = false;
this.invalidateToken.Location = new System.Drawing.Point(159, 251);
this.invalidateToken.Name = "invalidateToken";
this.invalidateToken.Size = new System.Drawing.Size(238, 44);
this.invalidateToken.TabIndex = 3;
this.invalidateToken.Text = "Invalidate Token";
this.invalidateToken.UseVisualStyleBackColor = true;
//
// expireAccessToken
//
this.expireAccessToken.Location = new System.Drawing.Point(159, 181);
this.expireAccessToken.Name = "expireAccessToken";
this.expireAccessToken.Size = new System.Drawing.Size(240, 44);
this.expireAccessToken.TabIndex = 2;
this.expireAccessToken.Text = "Expire Access Token";
this.expireAccessToken.UseVisualStyleBackColor = true;
this.expireAccessToken.Click += new System.EventHandler(this.expireAccessToken_Click);
//
// acquireTokenSilent
//
this.acquireTokenSilent.Location = new System.Drawing.Point(159, 110);
this.acquireTokenSilent.Name = "acquireTokenSilent";
this.acquireTokenSilent.Size = new System.Drawing.Size(242, 46);
this.acquireTokenSilent.TabIndex = 1;
this.acquireTokenSilent.Text = "Acquire Token Silent";
this.acquireTokenSilent.UseVisualStyleBackColor = true;
this.acquireTokenSilent.Click += new System.EventHandler(this.acquireTokenSilent_Click);
//
// acquireToken
//
this.acquireToken.Location = new System.Drawing.Point(157, 35);
this.acquireToken.Name = "acquireToken";
this.acquireToken.Size = new System.Drawing.Size(244, 48);
this.acquireToken.TabIndex = 0;
this.acquireToken.Text = "Acquire Token";
this.acquireToken.UseVisualStyleBackColor = true;
this.acquireToken.Click += new System.EventHandler(this.acquireToken_Click);
//
// dataInputPage
//
this.dataInputPage.Controls.Add(this.GoBtn);
this.dataInputPage.Controls.Add(this.dataInput);
this.dataInputPage.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.dataInputPage.Location = new System.Drawing.Point(8, 27);
this.dataInputPage.Name = "dataInputPage";
this.dataInputPage.Padding = new System.Windows.Forms.Padding(3, 3, 3, 3);
this.dataInputPage.Size = new System.Drawing.Size(535, 694);
this.dataInputPage.TabIndex = 1;
this.dataInputPage.Text = "Data Input Page";
this.dataInputPage.UseVisualStyleBackColor = true;
//
// GoBtn
//
this.GoBtn.BackColor = System.Drawing.Color.DarkOrange;
this.GoBtn.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.GoBtn.Location = new System.Drawing.Point(191, 409);
this.GoBtn.Name = "GoBtn";
this.GoBtn.Size = new System.Drawing.Size(135, 59);
this.GoBtn.TabIndex = 1;
this.GoBtn.Text = "Go";
this.GoBtn.UseVisualStyleBackColor = false;
this.GoBtn.Click += new System.EventHandler(this.GoBtn_Click);
//
// dataInput
//
this.dataInput.BackColor = System.Drawing.Color.Bisque;
this.dataInput.Location = new System.Drawing.Point(103, 6);
this.dataInput.Multiline = true;
this.dataInput.Name = "dataInput";
this.dataInput.Size = new System.Drawing.Size(329, 397);
this.dataInput.TabIndex = 0;
//
// resultPage
//
this.resultPage.AutoScroll = true;
this.resultPage.Controls.Add(this.messageResult);
this.resultPage.Controls.Add(this.scopeResult);
this.resultPage.Controls.Add(this.exceptionResult);
this.resultPage.Controls.Add(this.scope);
this.resultPage.Controls.Add(this.idTokenResult);
this.resultPage.Controls.Add(this.idToken);
this.resultPage.Controls.Add(this.userResult);
this.resultPage.Controls.Add(this.user);
this.resultPage.Controls.Add(this.tenantIdResult);
this.resultPage.Controls.Add(this.tenantId);
this.resultPage.Controls.Add(this.expiresOnResult);
this.resultPage.Controls.Add(this.expiresOn);
this.resultPage.Controls.Add(this.accessTokenResult);
this.resultPage.Controls.Add(this.accessToken);
this.resultPage.Controls.Add(this.label1);
this.resultPage.Controls.Add(this.msalLogs);
this.resultPage.Controls.Add(this.Done);
this.resultPage.Location = new System.Drawing.Point(8, 27);
this.resultPage.Name = "resultPage";
this.resultPage.Padding = new System.Windows.Forms.Padding(3, 3, 3, 3);
this.resultPage.Size = new System.Drawing.Size(535, 694);
this.resultPage.TabIndex = 2;
this.resultPage.Text = "Result Page";
this.resultPage.UseVisualStyleBackColor = true;
//
// messageResult
//
this.messageResult.AutoSize = true;
this.messageResult.Location = new System.Drawing.Point(6, 249);
this.messageResult.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.messageResult.Name = "messageResult";
this.messageResult.Size = new System.Drawing.Size(133, 13);
this.messageResult.TabIndex = 18;
this.messageResult.Text = "Message Placeholder Text";
//
// scopeResult
//
this.scopeResult.FormattingEnabled = true;
this.scopeResult.Location = new System.Drawing.Point(84, 138);
this.scopeResult.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.scopeResult.Name = "scopeResult";
this.scopeResult.Size = new System.Drawing.Size(170, 95);
this.scopeResult.TabIndex = 17;
//
// exceptionResult
//
this.exceptionResult.AutoSize = true;
this.exceptionResult.Location = new System.Drawing.Point(230, 476);
this.exceptionResult.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.exceptionResult.Name = "exceptionResult";
this.exceptionResult.Size = new System.Drawing.Size(0, 13);
this.exceptionResult.TabIndex = 16;
//
// scope
//
this.scope.AutoSize = true;
this.scope.Location = new System.Drawing.Point(4, 138);
this.scope.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.scope.Name = "scope";
this.scope.Size = new System.Drawing.Size(38, 13);
this.scope.TabIndex = 14;
this.scope.Text = "Scope";
//
// idTokenResult
//
this.idTokenResult.AutoSize = true;
this.idTokenResult.Location = new System.Drawing.Point(82, 112);
this.idTokenResult.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.idTokenResult.Name = "idTokenResult";
this.idTokenResult.Size = new System.Drawing.Size(87, 13);
this.idTokenResult.TabIndex = 13;
this.idTokenResult.Text = "Placeholder Text";
//
// idToken
//
this.idToken.AutoSize = true;
this.idToken.Location = new System.Drawing.Point(4, 112);
this.idToken.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.idToken.Name = "idToken";
this.idToken.Size = new System.Drawing.Size(50, 13);
this.idToken.TabIndex = 12;
this.idToken.Text = "Id Token";
//
// userResult
//
this.userResult.AutoSize = true;
this.userResult.Location = new System.Drawing.Point(82, 86);
this.userResult.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.userResult.Name = "userResult";
this.userResult.Size = new System.Drawing.Size(87, 13);
this.userResult.TabIndex = 11;
this.userResult.Text = "Placeholder Text";
//
// user
//
this.user.AutoSize = true;
this.user.Location = new System.Drawing.Point(4, 86);
this.user.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.user.Name = "user";
this.user.Size = new System.Drawing.Size(29, 13);
this.user.TabIndex = 10;
this.user.Text = "User";
//
// tenantIdResult
//
this.tenantIdResult.AutoSize = true;
this.tenantIdResult.Location = new System.Drawing.Point(82, 60);
this.tenantIdResult.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.tenantIdResult.Name = "tenantIdResult";
this.tenantIdResult.Size = new System.Drawing.Size(87, 13);
this.tenantIdResult.TabIndex = 9;
this.tenantIdResult.Text = "Placeholder Text";
//
// tenantId
//
this.tenantId.AutoSize = true;
this.tenantId.Location = new System.Drawing.Point(4, 60);
this.tenantId.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.tenantId.Name = "tenantId";
this.tenantId.Size = new System.Drawing.Size(53, 13);
this.tenantId.TabIndex = 8;
this.tenantId.Text = "Tenant Id";
//
// expiresOnResult
//
this.expiresOnResult.AutoSize = true;
this.expiresOnResult.Location = new System.Drawing.Point(82, 34);
this.expiresOnResult.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.expiresOnResult.Name = "expiresOnResult";
this.expiresOnResult.Size = new System.Drawing.Size(87, 13);
this.expiresOnResult.TabIndex = 7;
this.expiresOnResult.Text = "Placeholder Text";
//
// expiresOn
//
this.expiresOn.AutoSize = true;
this.expiresOn.Location = new System.Drawing.Point(4, 34);
this.expiresOn.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.expiresOn.Name = "expiresOn";
this.expiresOn.Size = new System.Drawing.Size(58, 13);
this.expiresOn.TabIndex = 6;
this.expiresOn.Text = "Expires On";
//
// accessTokenResult
//
this.accessTokenResult.AutoSize = true;
this.accessTokenResult.BackColor = System.Drawing.Color.Transparent;
this.accessTokenResult.Location = new System.Drawing.Point(82, 8);
this.accessTokenResult.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.accessTokenResult.Name = "accessTokenResult";
this.accessTokenResult.Size = new System.Drawing.Size(87, 13);
this.accessTokenResult.TabIndex = 5;
this.accessTokenResult.Text = "Placeholder Text";
//
// accessToken
//
this.accessToken.AutoSize = true;
this.accessToken.Location = new System.Drawing.Point(4, 8);
this.accessToken.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.accessToken.Name = "accessToken";
this.accessToken.Size = new System.Drawing.Size(76, 13);
this.accessToken.TabIndex = 4;
this.accessToken.Text = "Access Token";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(17, 513);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(55, 13);
this.label1.TabIndex = 3;
this.label1.Text = "Msal Logs";
//
// msalLogs
//
this.msalLogs.BackColor = System.Drawing.Color.PowderBlue;
this.msalLogs.Location = new System.Drawing.Point(9, 529);
this.msalLogs.Multiline = true;
this.msalLogs.Name = "msalLogs";
this.msalLogs.Size = new System.Drawing.Size(528, 168);
this.msalLogs.TabIndex = 2;
//
// Done
//
this.Done.BackColor = System.Drawing.Color.LightSeaGreen;
this.Done.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Done.ForeColor = System.Drawing.SystemColors.ControlText;
this.Done.Location = new System.Drawing.Point(181, 447);
this.Done.Name = "Done";
this.Done.Size = new System.Drawing.Size(179, 55);
this.Done.TabIndex = 1;
this.Done.Text = "Done";
this.Done.UseVisualStyleBackColor = false;
this.Done.Click += new System.EventHandler(this.Done_Click);
//
// AutomationUI
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(572, 506);
this.Controls.Add(this.pageControl1);
this.Name = "AutomationUI";
this.Text = ".NET Automation App";
this.Load += new System.EventHandler(this.AutomationUI_Load);
this.pageControl1.ResumeLayout(false);
this.mainPage.ResumeLayout(false);
this.dataInputPage.ResumeLayout(false);
this.dataInputPage.PerformLayout();
this.resultPage.ResumeLayout(false);
this.resultPage.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TabControl pageControl1;
private System.Windows.Forms.TabPage mainPage;
private System.Windows.Forms.Button acquireToken;
private System.Windows.Forms.TabPage dataInputPage;
private System.Windows.Forms.TabPage resultPage;
private System.Windows.Forms.Button clearCache;
private System.Windows.Forms.Button readCache;
private System.Windows.Forms.Button invalidateToken;
private System.Windows.Forms.Button expireAccessToken;
private System.Windows.Forms.Button acquireTokenSilent;
private System.Windows.Forms.Button GoBtn;
private System.Windows.Forms.TextBox dataInput;
private System.Windows.Forms.Button Done;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox msalLogs;
private System.Windows.Forms.Label accessToken;
private System.Windows.Forms.Label expiresOnResult;
private System.Windows.Forms.Label expiresOn;
private System.Windows.Forms.Label accessTokenResult;
private System.Windows.Forms.Label tenantIdResult;
private System.Windows.Forms.Label tenantId;
private System.Windows.Forms.Label userResult;
private System.Windows.Forms.Label user;
private System.Windows.Forms.Label idTokenResult;
private System.Windows.Forms.Label idToken;
private System.Windows.Forms.Label scope;
private System.Windows.Forms.Label exceptionResult;
private System.Windows.Forms.ListBox scopeResult;
private System.Windows.Forms.Label messageResult;
}
}
| 49.346241 | 175 | 0.59627 | [
"MIT"
] | IDeliverable/azure-activedirectory-library-for-dotnet | msal/tests/AutomationApp/AutomationUI.Designer.cs | 21,665 | C# |
using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows.Forms;
namespace VenomRAT_HVNC.Server.Helper
{
public class WordTextBox : TextBox
{
public override int MaxLength
{
get
{
return base.MaxLength;
}
set
{
}
}
public bool IsHexNumber
{
get
{
return this.isHexNumber;
}
set
{
if (this.isHexNumber == value)
{
return;
}
if (value)
{
if (this.Type == WordTextBox.WordType.DWORD)
{
this.Text = this.UIntValue.ToString("x");
}
else
{
this.Text = this.ULongValue.ToString("x");
}
}
else if (this.Type == WordTextBox.WordType.DWORD)
{
this.Text = this.UIntValue.ToString();
}
else
{
this.Text = this.ULongValue.ToString();
}
this.isHexNumber = value;
this.UpdateMaxLength();
}
}
public WordTextBox.WordType Type
{
get
{
return this.type;
}
set
{
if (this.type == value)
{
return;
}
this.type = value;
this.UpdateMaxLength();
}
}
public uint UIntValue
{
get
{
uint result;
try
{
if (string.IsNullOrEmpty(this.Text))
{
result = 0U;
}
else if (this.IsHexNumber)
{
result = uint.Parse(this.Text, NumberStyles.HexNumber);
}
else
{
result = uint.Parse(this.Text);
}
}
catch (Exception)
{
result = uint.MaxValue;
}
return result;
}
}
public ulong ULongValue
{
get
{
ulong result;
try
{
if (string.IsNullOrEmpty(this.Text))
{
result = 0UL;
}
else if (this.IsHexNumber)
{
result = ulong.Parse(this.Text, NumberStyles.HexNumber);
}
else
{
result = ulong.Parse(this.Text);
}
}
catch (Exception)
{
result = ulong.MaxValue;
}
return result;
}
}
public bool IsConversionValid()
{
return string.IsNullOrEmpty(this.Text) || this.IsHexNumber || this.ConvertToHex();
}
public WordTextBox()
{
this.InitializeComponent();
base.MaxLength = 8;
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
e.Handled = !this.IsValidChar(e.KeyChar);
}
private bool IsValidChar(char ch)
{
return char.IsControl(ch) || char.IsDigit(ch) || (this.IsHexNumber && char.IsLetter(ch) && char.ToLower(ch) <= 'f');
}
private void UpdateMaxLength()
{
if (this.Type == WordTextBox.WordType.DWORD)
{
if (this.IsHexNumber)
{
base.MaxLength = 8;
return;
}
base.MaxLength = 10;
return;
}
else
{
if (this.IsHexNumber)
{
base.MaxLength = 16;
return;
}
base.MaxLength = 20;
return;
}
}
private bool ConvertToHex()
{
bool result;
try
{
if (this.Type == WordTextBox.WordType.DWORD)
{
uint.Parse(this.Text);
}
else
{
ulong.Parse(this.Text);
}
result = true;
}
catch (Exception)
{
result = false;
}
return result;
}
protected override void Dispose(bool disposing)
{
if (disposing && this.components != null)
{
this.components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.components = new Container();
}
private bool isHexNumber;
private WordTextBox.WordType type;
private IContainer components;
public enum WordType
{
DWORD,
QWORD
}
}
}
| 24.792035 | 128 | 0.356952 | [
"Unlicense"
] | GitPlaya/Venom5-HVNC-Rat | VenomRAT_HVNC/Server/Helper/WordTextBox.cs | 5,603 | C# |
/* Copyright 2010-2016 MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
namespace MongoDB.Bson
{
/// <summary>
/// A static class containing BSON utility methods.
/// </summary>
public static class BsonUtils
{
// public static methods
/// <summary>
/// Gets a friendly class name suitable for use in error messages.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>A friendly class name.</returns>
public static string GetFriendlyTypeName(Type type)
{
var typeInfo = type.GetTypeInfo();
if (!typeInfo.IsGenericType)
{
return type.Name;
}
var sb = new StringBuilder();
sb.AppendFormat("{0}<", Regex.Replace(type.Name, @"\`\d+$", ""));
foreach (var typeParameter in type.GetTypeInfo().GetGenericArguments())
{
sb.AppendFormat("{0}, ", GetFriendlyTypeName(typeParameter));
}
sb.Remove(sb.Length - 2, 2);
sb.Append(">");
return sb.ToString();
}
/// <summary>
/// Parses a hex string into its equivalent byte array.
/// </summary>
/// <param name="s">The hex string to parse.</param>
/// <returns>The byte equivalent of the hex string.</returns>
public static byte[] ParseHexString(string s)
{
if (s == null)
{
throw new ArgumentNullException("s");
}
byte[] bytes;
if ((s.Length & 1) != 0)
{
s = "0" + s; // make length of s even
}
bytes = new byte[s.Length / 2];
for (int i = 0; i < bytes.Length; i++)
{
string hex = s.Substring(2 * i, 2);
try
{
byte b = Convert.ToByte(hex, 16);
bytes[i] = b;
}
catch (FormatException e)
{
throw new FormatException(
string.Format("Invalid hex string {0}. Problem with substring {1} starting at position {2}",
s,
hex,
2 * i),
e);
}
}
return bytes;
}
/// <summary>
/// Converts from number of milliseconds since Unix epoch to DateTime.
/// </summary>
/// <param name="millisecondsSinceEpoch">The number of milliseconds since Unix epoch.</param>
/// <returns>A DateTime.</returns>
public static DateTime ToDateTimeFromMillisecondsSinceEpoch(long millisecondsSinceEpoch)
{
if (millisecondsSinceEpoch < BsonConstants.DateTimeMinValueMillisecondsSinceEpoch ||
millisecondsSinceEpoch > BsonConstants.DateTimeMaxValueMillisecondsSinceEpoch)
{
var message = string.Format(
"The value {0} for the BsonDateTime MillisecondsSinceEpoch is outside the"+
"range that can be converted to a .NET DateTime.",
millisecondsSinceEpoch);
throw new ArgumentOutOfRangeException("millisecondsSinceEpoch", message);
}
// MaxValue has to be handled specially to avoid rounding errors
if (millisecondsSinceEpoch == BsonConstants.DateTimeMaxValueMillisecondsSinceEpoch)
{
return DateTime.SpecifyKind(DateTime.MaxValue, DateTimeKind.Utc);
}
else
{
return BsonConstants.UnixEpoch.AddTicks(millisecondsSinceEpoch * 10000);
}
}
/// <summary>
/// Converts a byte array to a hex string.
/// </summary>
/// <param name="bytes">The byte array.</param>
/// <returns>A hex string.</returns>
public static string ToHexString(byte[] bytes)
{
if (bytes == null)
{
throw new ArgumentNullException("bytes");
}
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.AppendFormat("{0:x2}", b);
}
return sb.ToString();
}
/// <summary>
/// Converts a DateTime to local time (with special handling for MinValue and MaxValue).
/// </summary>
/// <param name="dateTime">A DateTime.</param>
/// <returns>The DateTime in local time.</returns>
public static DateTime ToLocalTime(DateTime dateTime)
{
if (dateTime == DateTime.MinValue)
{
return DateTime.SpecifyKind(DateTime.MinValue, DateTimeKind.Local);
}
else if (dateTime == DateTime.MaxValue)
{
return DateTime.SpecifyKind(DateTime.MaxValue, DateTimeKind.Local);
}
else
{
return dateTime.ToLocalTime();
}
}
/// <summary>
/// Converts a DateTime to number of milliseconds since Unix epoch.
/// </summary>
/// <param name="dateTime">A DateTime.</param>
/// <returns>Number of seconds since Unix epoch.</returns>
public static long ToMillisecondsSinceEpoch(DateTime dateTime)
{
var utcDateTime = ToUniversalTime(dateTime);
return (utcDateTime - BsonConstants.UnixEpoch).Ticks / 10000;
}
/// <summary>
/// Converts a DateTime to UTC (with special handling for MinValue and MaxValue).
/// </summary>
/// <param name="dateTime">A DateTime.</param>
/// <returns>The DateTime in UTC.</returns>
public static DateTime ToUniversalTime(DateTime dateTime)
{
if (dateTime == DateTime.MinValue)
{
return DateTime.SpecifyKind(DateTime.MinValue, DateTimeKind.Utc);
}
else if (dateTime == DateTime.MaxValue)
{
return DateTime.SpecifyKind(DateTime.MaxValue, DateTimeKind.Utc);
}
else
{
return dateTime.ToUniversalTime();
}
}
/// <summary>
/// Tries to parse a hex string to a byte array.
/// </summary>
/// <param name="s">The hex string.</param>
/// <param name="bytes">A byte array.</param>
/// <returns>True if the hex string was successfully parsed.</returns>
public static bool TryParseHexString(string s, out byte[] bytes)
{
try
{
bytes = ParseHexString(s);
}
catch
{
bytes = null;
return false;
}
return true;
}
}
} | 34.962963 | 116 | 0.530985 | [
"MIT"
] | 21thCenturyBoy/LandlordsProject | Landlords_Client01/Landlords_Client01/Unity/Assets/ThirdParty/MongoDB/MongoDB.Bson/BsonUtils.cs | 7,554 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.R.Host.Client.Test.Fixtures;
using Microsoft.UnitTests.Core.Threading;
using Microsoft.UnitTests.Core.XUnit;
using Microsoft.VisualStudio.ProjectSystem.FileSystemMirroring.Test;
using Microsoft.VisualStudio.R.Package.Test.Fixtures;
[assembly: TestFrameworkOverride]
[assembly: CpsAssemblyLoader]
[assembly: AssemblyFixtureImport(typeof(RPackageServicesFixture), typeof(RemoteBrokerFixture), typeof(TestMainThreadFixture))] | 49.5 | 126 | 0.8367 | [
"MIT"
] | Bhaskers-Blu-Org2/RTVS | src/Package/TestApp/Properties/AssemblyInfo.cs | 596 | C# |
using System;
using System.Linq.Expressions;
using Pushqa;
using Pushqa.Communication;
using Pushqa.SignalR;
namespace Pushqa.Linq {
/// <summary>
/// A projected event type
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
public class EventProjectedQuery<TSource, TResult> : IEventQuery<TResult> {
private readonly EventQuerySource<TSource> source;
private readonly Expression<Func<TSource, bool>> filter;
private readonly Expression<Func<TSource, TResult>> selector;
private readonly int skip;
private readonly int top;
/// <summary>
/// Initializes a new instance of the <see cref="EventProjectedQuery<TSource, TResult>"/> class.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="filter">The filter.</param>
/// <param name="selector">The selector.</param>
public EventProjectedQuery(EventQuerySource<TSource> source, Expression<Func<TSource, bool>> filter, Expression<Func<TSource, TResult>> selector) {
this.source = source;
this.filter = filter;
this.selector = selector;
}
/// <summary>
/// Initializes a new instance of the <see cref="EventProjectedQuery<TSource, TResult>"/> class.
/// </summary>
/// <param name="source">The event source.</param>
/// <param name="filter">The "where" filter.</param>
/// <param name="selector">The "select" projection.</param>
/// <param name="skip">The amount of events to skip at the start of the event stream.</param>
/// <param name="top">The number of events to observe before completing.</param>
public EventProjectedQuery(EventQuerySource<TSource> source, Expression<Func<TSource, bool>> filter, Expression<Func<TSource, TResult>> selector, int skip, int top) {
this.source = source;
this.filter = filter;
this.selector = selector;
this.skip = skip;
this.top = top;
}
/// <summary>
/// Skips the specified number of events at the start of the event stream.
/// </summary>
/// <param name="count">The count.</param>
/// <returns></returns>
public EventProjectedQuery<TSource, TResult> Skip(int count) {
return new EventProjectedQuery<TSource, TResult>(source, filter, selector, count, top);
}
/// <summary>
/// Takes the specified number of events and then completes.
/// </summary>
/// <param name="count">The number of items to observe.</param>
/// <returns></returns>
public EventProjectedQuery<TSource, TResult> Take(int count) {
return new EventProjectedQuery<TSource, TResult>(source, filter, selector, skip, count);
}
/// <summary>
/// Obtains an observable sequence object to receive the WQL query results.
/// </summary>
/// <returns>Observable sequence for query results.</returns>
public IObservable<TResult> AsObservable() {
return ((IEventQuery<TResult>)this).AsObservable(new SignalrQueryPipeline());
}
IObservable<TResult> IEventQuery<TResult>.AsObservable(IEventProviderPipeline eventProviderPipeline) {
EventQuery<TSource, TResult> query = new EventQuery<TSource, TResult> {
Source = source,
Filter = filter,
Selector = selector,
Skip = skip,
Top = top
};
return eventProviderPipeline.GetEventStream(query);
}
}
} | 43.875 | 175 | 0.598809 | [
"MIT"
] | PeteGoo/Pushqa | src/Pushqa/Linq/EventProjectedQuery.cs | 3,861 | C# |
using DataGridView.Adicionar;
using DataGridView.Edicao;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DataGridView
{
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
}
private void Form4_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'querysInnerJoinDataSet1.Usuarios' table. You can move, or remove it, as needed.
this.usuariosTableAdapter.CustomQuery(this.querysInnerJoinDataSet1.Usuarios);
}
private void DataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var userSelect = ((System.Data.DataRowView)
this.dataGridView1.Rows[e.RowIndex].DataBoundItem).Row
as DataGridView.QuerysInnerJoinDataSet1.UsuariosRow;
fmEdicaoCarros editCarro = new fmEdicaoCarros();
//editCarro.CarrosRow = userSelect;
//editCarro.ShowDialog();
this.usuariosTableAdapter.Update(editCarro.CarrosRow);
this.usuariosTableAdapter.DeleteQuery(userSelect.Id);
this.usuariosTableAdapter.CustomQuery(this.querysInnerJoinDataSet1.Usuarios);
}
private void Button1_Click(object sender, EventArgs e)
{
frmUsuarios formAdd = new frmUsuarios();
formAdd.ShowDialog();
this.usuariosTableAdapter.Insert(
formAdd.carrosRow.Usuario,
true,
1,
1,
DateTime.Now,
DateTime.Now
);
//Atualiza
this.usuariosTableAdapter.Fill(this.querysInnerJoinDataSet1.Usuarios);
}
}
}
| 30.968254 | 139 | 0.62532 | [
"MIT"
] | rudimarboeno/Hbsis-aula | 29-07-19 a 02-08-19/DataGridView/DataGridView/Form4.cs | 1,953 | C# |
using System;
using SampleRpg.Engine.Models;
namespace SampleRpg.Engine.IO
{
public class ItemQuantityModel
{
public int Id { get; set; }
public int Quantity { get; set; }
public ItemQuantity ToItemQuantity () => new ItemQuantity() { ItemId = Id, Quantity = Quantity };
}
}
| 19.6875 | 105 | 0.64127 | [
"MIT"
] | CoolDadTx/samplerpg | SampleRpg.Engine/IO/ItemQuantityModel.cs | 317 | C# |
// Copyright © TheAirBlow 2022 <[email protected]>
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
using System;
namespace TheAirBlow.Zigman.Exceptions;
public class InvalidClassException : Exception
{
public InvalidClassException()
{
}
public InvalidClassException(string msg)
: base(msg)
{
}
public InvalidClassException(string msg, Exception inner)
: base(msg, inner)
{
}
} | 23.76 | 70 | 0.688552 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | TheAirBlow/Zigman | TheAirBlow.Zigman/Exceptions/InvalidClassException.cs | 597 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace RcxJs.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
}
} | 18.647059 | 45 | 0.586751 | [
"MIT"
] | toolgood/RCX | ToolGood.RcxTest/RcxJs/Controllers/HomeController.cs | 319 | C# |
/*
* API Doctor
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the ""Software""), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace ApiDoctor.ConsoleApp
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ApiDoctor.DocumentationGeneration;
using ApiDoctor.Validation.OData.Transformation;
using AppVeyor;
using CommandLine;
using Newtonsoft.Json;
using Publishing.Html;
using Publishing.Swagger;
using Validation;
using Validation.Error;
using Validation.Http;
using Validation.Json;
using Validation.OData;
using Validation.Params;
using Validation.Writers;
class Program
{
private const int ExitCodeFailure = 1;
private const int ExitCodeSuccess = 0;
private const int ParallelTaskCount = 5;
public static readonly BuildWorkerApi BuildWorker = new BuildWorkerApi();
public static AppConfigFile CurrentConfiguration { get; private set; }
// Set to true to disable returning an error code when the app exits.
private static bool IgnoreErrors { get; set; }
private static List<UndocumentedPropertyWarning> DiscoveredUndocumentedProperties = new List<UndocumentedPropertyWarning>();
static void Main(string[] args)
{
Logging.ProviderLogger(new ConsoleAppLogger());
FancyConsole.WriteLine(ConsoleColor.Green, "API Doctor, version {0}", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
FancyConsole.WriteLine();
if (args.Length > 0)
FancyConsole.WriteLine("Command line: " + args.ComponentsJoinedByString(" "));
string verbName = null;
BaseOptions verbOptions = null;
var options = new CommandLineOptions();
if (!Parser.Default.ParseArguments(args, options,
(verb, subOptions) =>
{
// if parsing succeeds the verb name and correct instance
// will be passed to onVerbCommand delegate (string,object)
verbName = verb;
verbOptions = (BaseOptions)subOptions;
}))
{
FancyConsole.WriteLine(ConsoleColor.Red, "COMMAND LINE PARSE ERROR");
Exit(failure: true);
}
IgnoreErrors = verbOptions.IgnoreErrors;
#if DEBUG
if (verbOptions.AttachDebugger == 1)
{
Debugger.Launch();
}
#endif
SetStateFromOptions(verbOptions);
var task = Task.Run(() => RunInvokedMethodAsync(options, verbName, verbOptions));
try
{
task.Wait();
}
catch (Exception ex)
{
FancyConsole.WriteLine(FancyConsole.ConsoleErrorColor, "Uncaught exception is causing a crash: {0}", ex);
Exit(failure: true, customExitCode: 40);
}
}
private static void SetStateFromOptions(BaseOptions verbOptions)
{
if (!string.IsNullOrEmpty(verbOptions.AppVeyorServiceUrl))
{
BuildWorker.UrlEndPoint = new Uri(verbOptions.AppVeyorServiceUrl);
}
var commandOptions = verbOptions as DocSetOptions;
if (null != commandOptions)
{
FancyConsole.WriteVerboseOutput = commandOptions.EnableVerboseOutput;
}
var checkOptions = verbOptions as BasicCheckOptions;
if (null != checkOptions)
{
if (!string.IsNullOrEmpty(checkOptions.FilesChangedFromOriginalBranch))
{
if (string.IsNullOrEmpty(checkOptions.GitExecutablePath))
{
var foundPath = GitHelper.FindGitLocation();
if (null == foundPath)
{
FancyConsole.WriteLine(FancyConsole.ConsoleErrorColor, "To use changes-since-branch-only, git-path must be specified.");
Exit(failure: true, customExitCode: 41);
}
else
{
FancyConsole.WriteLine(FancyConsole.ConsoleDefaultColor, $"Using GIT executable: {foundPath}");
checkOptions.GitExecutablePath = foundPath;
}
}
}
}
FancyConsole.LogFileName = verbOptions.LogFile;
}
public static void LoadCurrentConfiguration(DocSetOptions options)
{
if (CurrentConfiguration != null)
return;
if (null != options)
{
var configurationFiles = DocSet.TryLoadConfigurationFiles<AppConfigFile>(options.DocumentationSetPath);
CurrentConfiguration = configurationFiles.FirstOrDefault();
if (null != CurrentConfiguration)
Console.WriteLine("Using configuration file: {0}", CurrentConfiguration.SourcePath);
}
}
private static async Task RunInvokedMethodAsync(CommandLineOptions origCommandLineOpts, string invokedVerb, BaseOptions options)
{
var issues = new IssueLogger()
{
#if DEBUG
DebugLine = options.AttachDebugger,
#endif
};
string[] missingProps;
if (!options.HasRequiredProperties(out missingProps))
{
issues.Error(ValidationErrorCode.MissingRequiredArguments, $"Command line is missing required arguments: {missingProps.ComponentsJoinedByString(", ")}");
FancyConsole.WriteLine(origCommandLineOpts.GetUsage(invokedVerb));
await WriteOutErrorsAndFinishTestAsync(issues, options.SilenceWarnings, printFailuresOnly: options.PrintFailuresOnly);
Exit(failure: true);
}
LoadCurrentConfiguration(options as DocSetOptions);
bool returnSuccess = true;
switch (invokedVerb)
{
case CommandLineOptions.VerbPrint:
await PrintDocInformationAsync((PrintOptions)options, issues);
break;
case CommandLineOptions.VerbCheckLinks:
returnSuccess = await CheckLinksAsync((CheckLinkOptions)options, issues);
break;
case CommandLineOptions.VerbDocs:
returnSuccess = await CheckDocsAsync((BasicCheckOptions)options, issues);
break;
case CommandLineOptions.VerbCheckAll:
returnSuccess = await CheckDocsAllAsync((CheckLinkOptions)options, issues);
break;
case CommandLineOptions.VerbService:
returnSuccess = await CheckServiceAsync((CheckServiceOptions)options, issues);
break;
case CommandLineOptions.VerbPublish:
returnSuccess = await PublishDocumentationAsync((PublishOptions)options, issues);
break;
case CommandLineOptions.VerbPublishMetadata:
returnSuccess = await PublishMetadataAsync((PublishMetadataOptions)options, issues);
break;
case CommandLineOptions.VerbMetadata:
await CheckServiceMetadataAsync((CheckMetadataOptions)options, issues);
break;
case CommandLineOptions.VerbGenerateDocs:
returnSuccess = await GenerateDocsAsync((GenerateDocsOptions)options);
break;
case CommandLineOptions.VerbFix:
returnSuccess = await FixDocsAsync((FixDocsOptions)options, issues);
break;
case CommandLineOptions.VerbAbout:
PrintAboutMessage();
Exit(failure: false);
break;
}
WriteMessages(
issues,
options.IgnoreWarnings,
indent: " ",
printUnusedSuppressions: invokedVerb == CommandLineOptions.VerbCheckAll);
if (returnSuccess)
{
if (issues.Errors.Any() ||
(issues.Warnings.Any() && !options.IgnoreErrors))
{
returnSuccess = false;
}
}
Exit(failure: !returnSuccess);
}
/// <summary>
/// Perform all of the local documentation based checks. This is the "compile"
/// command for the documentation that verifies that everything is clean inside the
/// documentation itself.
/// </summary>
/// <param name="options"></param>
/// <returns></returns>
private static async Task<bool> CheckDocsAllAsync(CheckLinkOptions options, IssueLogger issues)
{
var docset = await GetDocSetAsync(options, issues);
if (null == docset)
return false;
var checkLinksResult = await CheckLinksAsync(options, issues, docset);
var checkDocsResults = await CheckDocsAsync(options, issues, docset);
var publishOptions = new PublishMetadataOptions();
var publishResult = await PublishMetadataAsync(publishOptions, issues, docset);
return checkLinksResult && checkDocsResults && publishResult;
}
private static void PrintAboutMessage()
{
FancyConsole.WriteLine();
FancyConsole.WriteLine(ConsoleColor.Cyan, "apidoc.exe - API Documentation Test Tool");
FancyConsole.WriteLine(ConsoleColor.Cyan, "Copyright (c) 2018 Microsoft Corporation");
FancyConsole.WriteLine();
FancyConsole.WriteLine(ConsoleColor.Cyan, "For more information see http://github.com/onedrive/apidoctor");
FancyConsole.WriteLine();
}
/// <summary>
/// Create and return a document set based on input options
/// </summary>
/// <param name="options"></param>
/// <returns></returns>
private static Task<DocSet> GetDocSetAsync(DocSetOptions options, IssueLogger issues)
{
FancyConsole.VerboseWriteLine("Opening documentation from {0}", options.DocumentationSetPath);
DocSet set = null;
try
{
set = new DocSet(options.DocumentationSetPath, writeFixesBackToDisk: options is FixDocsOptions);
}
catch (System.IO.FileNotFoundException ex)
{
FancyConsole.WriteLine(FancyConsole.ConsoleErrorColor, ex.Message);
Exit(failure: true);
return Task.FromResult<DocSet>(null);
}
FancyConsole.VerboseWriteLine("Scanning documentation files...");
string tagsToInclude;
if (null == options.PageParameterDict || !options.PageParameterDict.TryGetValue("tags", out tagsToInclude))
{
tagsToInclude = String.Empty;
}
DateTimeOffset start = DateTimeOffset.Now;
set.ScanDocumentation(tagsToInclude, issues);
DateTimeOffset end = DateTimeOffset.Now;
TimeSpan duration = end.Subtract(start);
FancyConsole.WriteLine($"Took {duration.TotalSeconds} to parse {set.Files.Length} source files.");
return Task.FromResult<DocSet>(set);
}
public static void RecordWarning(string format, params object[] variables)
{
var message = string.Format(format, variables);
FancyConsole.WriteLine(FancyConsole.ConsoleWarningColor, message);
Task.Run(() => BuildWorker.AddMessageAsync(message, MessageCategory.Warning));
}
public static void RecordError(string format, params object[] variables)
{
var message = string.Format(format, variables);
FancyConsole.WriteLine(FancyConsole.ConsoleErrorColor, message);
Task.Run(() => BuildWorker.AddMessageAsync(message, MessageCategory.Error));
}
/// <summary>
/// Output information about the document set to the console
/// </summary>
/// <param name="options"></param>
/// <param name="docset"></param>
/// <returns></returns>
private static async Task PrintDocInformationAsync(PrintOptions options, IssueLogger issues, DocSet docset = null)
{
docset = docset ?? await GetDocSetAsync(options, issues);
if (null == docset)
{
return;
}
if (options.PrintFiles)
{
await PrintFilesAsync(options, docset, issues);
}
if (options.PrintResources)
{
await PrintResourcesAsync(options, docset, issues);
}
if (options.PrintMethods)
{
await PrintMethodsAsync(options, docset, issues);
}
if (options.PrintAccounts)
{
await PrintAccountsAsync(options, docset);
}
}
#region Print verb commands
/// <summary>
/// Prints a list of the documentation files in a docset to the console.
/// </summary>
/// <param name="options"></param>
/// <param name="docset"></param>
/// <returns></returns>
private static async Task PrintFilesAsync(DocSetOptions options, DocSet docset, IssueLogger issues)
{
docset = docset ?? await GetDocSetAsync(options, issues);
if (null == docset)
return;
if (null == docset)
return;
FancyConsole.WriteLine();
FancyConsole.WriteLine(FancyConsole.ConsoleHeaderColor, "Documentation files");
string format = null;
if (options.EnableVerboseOutput)
{
format = "{1} (resources: {2}, methods: {3})";
}
else
{
format = "{0} (r:{2}, m:{3})";
}
foreach (var file in docset.Files)
{
ConsoleColor color = FancyConsole.ConsoleSuccessColor;
if (file.Resources.Length == 0 && file.Requests.Length == 0)
color = FancyConsole.ConsoleWarningColor;
FancyConsole.WriteLineIndented(" ", color, format, file.DisplayName, file.FullPath, file.Resources.Length, file.Requests.Length);
}
}
/// <summary>
/// Print a list of the resources detected in the documentation set to the console.
/// </summary>
private static async Task PrintResourcesAsync(DocSetOptions options, DocSet docset, IssueLogger issues)
{
docset = docset ?? await GetDocSetAsync(options, issues);
if (null == docset)
return;
FancyConsole.WriteLine();
FancyConsole.WriteLine(FancyConsole.ConsoleHeaderColor, "Defined resources:");
FancyConsole.WriteLine();
var sortedResources = docset.Resources.OrderBy(x => x.Name);
foreach (var resource in sortedResources)
{
if (options.EnableVerboseOutput)
{
string metadata = JsonConvert.SerializeObject(resource.OriginalMetadata);
FancyConsole.Write(" ");
FancyConsole.Write(FancyConsole.ConsoleHeaderColor, resource.Name);
FancyConsole.WriteLine(" flags: {1}", resource.Name, metadata);
}
else
{
FancyConsole.WriteLineIndented(" ", FancyConsole.ConsoleHeaderColor, resource.Name);
}
FancyConsole.WriteLineIndented(" ", FancyConsole.ConsoleCodeColor, resource.ExampleText);
FancyConsole.WriteLine();
}
}
/// <summary>
/// Print a list of the methods (request/responses) discovered in the documentation to the console.
/// </summary>
private static async Task PrintMethodsAsync(DocSetOptions options, DocSet docset, IssueLogger issues)
{
docset = docset ?? await GetDocSetAsync(options, issues);
if (null == docset)
return;
FancyConsole.WriteLine();
FancyConsole.WriteLine(FancyConsole.ConsoleHeaderColor, "Defined methods:");
FancyConsole.WriteLine();
foreach (var method in docset.Methods)
{
FancyConsole.WriteLine(FancyConsole.ConsoleHeaderColor, "Method '{0}' in file '{1}'", method.Identifier, method.SourceFile.DisplayName);
var requestMetadata = options.EnableVerboseOutput ? JsonConvert.SerializeObject(method.RequestMetadata) : string.Empty;
FancyConsole.WriteLineIndented(" ", FancyConsole.ConsoleSubheaderColor, "Request: {0}", requestMetadata);
FancyConsole.WriteLineIndented(" ", FancyConsole.ConsoleCodeColor, method.Request);
if (options.EnableVerboseOutput)
{
FancyConsole.WriteLine();
var responseMetadata = JsonConvert.SerializeObject(method.ExpectedResponseMetadata);
FancyConsole.WriteLineIndented(" ", FancyConsole.ConsoleSubheaderColor, "Expected Response: {0}", responseMetadata);
FancyConsole.WriteLineIndented(" ", FancyConsole.ConsoleCodeColor, method.ExpectedResponse);
FancyConsole.WriteLine();
}
FancyConsole.WriteLine();
}
}
private static async Task PrintAccountsAsync(PrintOptions options, DocSet docset)
{
var accounts = Program.CurrentConfiguration.Accounts;
foreach(var account in accounts)
{
FancyConsole.WriteLine($"{account.Name} = {account.BaseUrl}");
}
}
#endregion
/// <summary>
/// Verifies that all markdown links inside the documentation are valid. Prints warnings
/// to the console for any invalid links. Also checks for orphaned documents.
/// </summary>
/// <param name="options"></param>
/// <param name="docs"></param>
private static async Task<bool> CheckLinksAsync(CheckLinkOptions options, IssueLogger issues, DocSet docs = null)
{
const string testName = "Check-links";
var docset = docs ?? await GetDocSetAsync(options, issues);
if (null == docset)
return false;
string[] interestingFiles = null;
if (!string.IsNullOrEmpty(options.FilesChangedFromOriginalBranch))
{
GitHelper helper = new GitHelper(options.GitExecutablePath, options.DocumentationSetPath);
interestingFiles = helper.FilesChangedFromBranch(options.FilesChangedFromOriginalBranch);
}
TestReport.StartTest(testName);
docset.ValidateLinks(options.EnableVerboseOutput, interestingFiles, issues, options.RequireFilenameCaseMatch, options.IncludeOrphanPageWarning);
foreach (var error in issues.Issues)
{
MessageCategory category;
if (error.IsWarning)
{
category = MessageCategory.Warning;
}
else if (error.IsError)
{
category = MessageCategory.Error;
}
else
{
if (!FancyConsole.WriteVerboseOutput)
{
continue;
}
category = MessageCategory.Information;
}
string message = string.Format("{1}: {0}", error.Message.FirstLineOnly(), error.Code);
await TestReport.LogMessageAsync(message, category);
}
return await WriteOutErrorsAndFinishTestAsync(issues, options.SilenceWarnings, successMessage: "No link errors detected.", testName: testName, printFailuresOnly: options.PrintFailuresOnly);
}
/// <summary>
/// Find the first instance of a method with a particular name in the docset.
/// </summary>
/// <param name="docset"></param>
/// <param name="methodName"></param>
/// <returns></returns>
private static MethodDefinition LookUpMethod(DocSet docset, string methodName)
{
var query = from m in docset.Methods
where m.Identifier.Equals(methodName, StringComparison.OrdinalIgnoreCase)
select m;
return query.FirstOrDefault();
}
/// <summary>
/// Returns a collection of methods matching the string query. This can either be the
/// literal name of the method of a wildcard match for the method name.
/// </summary>
/// <param name="docs"></param>
/// <param name="query"></param>
/// <returns></returns>
private static MethodDefinition[] FindMethods(DocSet docs, string wildcardPattern)
{
var query = from m in docs.Methods
where m.Identifier.IsWildcardMatch(wildcardPattern)
select m;
return query.ToArray();
}
/// <summary>
/// Perform internal consistency checks on the documentation, including verify that
/// code blocks have proper formatting, that resources are used properly, and that expected
/// responses and examples conform to the resource definitions.
/// </summary>
/// <param name="options"></param>
/// <param name="docs"></param>
/// <returns></returns>
private static async Task<bool> CheckDocsAsync(BasicCheckOptions options, IssueLogger issues, DocSet docs = null)
{
var docset = docs ?? await GetDocSetAsync(options, issues);
if (null == docset)
return false;
FancyConsole.WriteLine();
var resultStructure = await CheckDocStructure(options, docset, issues);
var resultMethods = await CheckMethodsAsync(options, docset, issues);
CheckResults resultExamples = new CheckResults();
if (string.IsNullOrEmpty(options.MethodName))
{
resultExamples = await CheckExamplesAsync(options, docset, issues);
}
var combinedResults = resultMethods + resultExamples + resultStructure;
if (options.IgnoreWarnings)
{
combinedResults.ConvertWarningsToSuccess();
}
combinedResults.PrintToConsole();
return combinedResults.FailureCount == 0;
}
private static async Task<CheckResults> CheckDocStructure(BasicCheckOptions options, DocSet docset, IssueLogger issues)
{
var results = new CheckResults();
TestReport.StartTest("Verify document structure");
foreach (var doc in docset.Files)
{
doc.CheckDocumentStructure(issues.For(doc.DisplayName));
}
await WriteOutErrorsAndFinishTestAsync(issues, options.SilenceWarnings, " ", "Passed.", false, "Verify document structure", "Warnings detected", "Errors detected", printFailuresOnly: options.PrintFailuresOnly);
results.IncrementResultCount(issues.Issues);
return results;
}
/// <summary>
/// Perform an internal consistency check on the examples defined in the documentation. Prints
/// the results of the tests to the console.
/// </summary>
/// <param name="options"></param>
/// <param name="docset"></param>
/// <returns></returns>
private static async Task<CheckResults> CheckExamplesAsync(BasicCheckOptions options, DocSet docset, IssueLogger issues)
{
var results = new CheckResults();
foreach (var doc in docset.Files)
{
if (doc.Examples.Length == 0)
{
continue;
}
var exampleIssues = issues.For(doc.DisplayName);
FancyConsole.WriteLine(FancyConsole.ConsoleHeaderColor, "Checking examples in \"{0}\"...", doc.DisplayName);
foreach (var example in doc.Examples)
{
if (example.Metadata == null)
continue;
if (example.Language != CodeLanguage.Json)
continue;
var testName = string.Format("check-example: {0}", example.Metadata.MethodName?.FirstOrDefault(), example.Metadata.ResourceType);
TestReport.StartTest(testName, doc.DisplayName);
docset.ResourceCollection.ValidateJsonExample(example.Metadata, example.SourceExample, exampleIssues, new ValidationOptions { RelaxedStringValidation = options.RelaxStringTypeValidation ?? true });
await WriteOutErrorsAndFinishTestAsync(exampleIssues, options.SilenceWarnings, " ", "Passed.", false, testName, "Warnings detected", "Errors detected", printFailuresOnly: options.PrintFailuresOnly);
results.IncrementResultCount(exampleIssues.Issues);
}
}
return results;
}
/// <summary>
/// Performs an internal consistency check on the methods (requests/responses) in the documentation.
/// Prints the results of the tests to the console.
/// </summary>
/// <param name="options"></param>
/// <param name="docset"></param>
/// <returns></returns>
private static async Task<CheckResults> CheckMethodsAsync(BasicCheckOptions options, DocSet docset, IssueLogger issues)
{
MethodDefinition[] methods = FindTestMethods(options, docset);
CheckResults results = new CheckResults();
foreach (var method in methods)
{
var methodIssues = issues.For(method.Identifier);
var testName = "API Request: " + method.Identifier;
TestReport.StartTest(testName, method.SourceFile.DisplayName, skipPrintingHeader: options.PrintFailuresOnly);
if (string.IsNullOrEmpty(method.ExpectedResponse))
{
await TestReport.FinishTestAsync(testName, TestOutcome.Failed, "No response was paired with this request.", printFailuresOnly: options.PrintFailuresOnly);
results.FailureCount++;
continue;
}
var parser = new HttpParser();
try
{
var expectedResponse = parser.ParseHttpResponse(method.ExpectedResponse);
method.ValidateResponse(expectedResponse, null, null, methodIssues, new ValidationOptions { RelaxedStringValidation = options.RelaxStringTypeValidation ?? true });
}
catch (Exception ex)
{
methodIssues.Error(ValidationErrorCode.ExceptionWhileValidatingMethod, method.SourceFile.DisplayName, ex);
}
await WriteOutErrorsAndFinishTestAsync(methodIssues, options.SilenceWarnings, " ", "Passed.", false, testName, "Warnings detected", "Errors detected", printFailuresOnly: options.PrintFailuresOnly);
results.IncrementResultCount(methodIssues.Issues);
}
return results;
}
private static DocFile[] GetSelectedFiles(BasicCheckOptions options, DocSet docset)
{
List<DocFile> files = new List<DocFile>();
if (!string.IsNullOrEmpty(options.FilesChangedFromOriginalBranch))
{
GitHelper helper = new GitHelper(options.GitExecutablePath, options.DocumentationSetPath);
var changedFiles = helper.FilesChangedFromBranch(options.FilesChangedFromOriginalBranch);
foreach (var filePath in changedFiles)
{
var file = docset.LookupFileForPath(filePath);
if (null != file)
files.Add(file);
}
}
else
{
files.AddRange(docset.Files);
}
return files.ToArray();
}
/// <summary>
/// Parse the command line parameters into a set of methods that match the command line parameters.
/// </summary>
/// <param name="options"></param>
/// <param name="docset"></param>
/// <returns></returns>
private static MethodDefinition[] FindTestMethods(BasicCheckOptions options, DocSet docset)
{
MethodDefinition[] methods = null;
if (!string.IsNullOrEmpty(options.FilesChangedFromOriginalBranch))
{
GitHelper helper = new GitHelper(options.GitExecutablePath, options.DocumentationSetPath);
var changedFiles = helper.FilesChangedFromBranch(options.FilesChangedFromOriginalBranch);
List<MethodDefinition> foundMethods = new List<MethodDefinition>();
foreach (var filePath in changedFiles)
{
var file = docset.LookupFileForPath(filePath);
if (null != file)
foundMethods.AddRange(file.Requests);
}
return foundMethods.ToArray();
}
else if (!string.IsNullOrEmpty(options.MethodName))
{
methods = FindMethods(docset, options.MethodName);
if (null == methods || methods.Length == 0)
{
FancyConsole.WriteLine(FancyConsole.ConsoleErrorColor, "Unable to locate method '{0}' in docset.", options.MethodName);
Exit(failure: true);
}
}
else if (!string.IsNullOrEmpty(options.FileName))
{
var selectedFileQuery = FilesMatchingFilter(docset, options.FileName);
if (!selectedFileQuery.Any())
{
FancyConsole.WriteLine(FancyConsole.ConsoleErrorColor, "Unable to locate file matching '{0}' in docset.", options.FileName);
Exit(failure: true);
}
List<MethodDefinition> foundMethods = new List<MethodDefinition>();
foreach (var docFile in selectedFileQuery)
{
foundMethods.AddRange(docFile.Requests);
}
methods = foundMethods.ToArray();
}
else
{
methods = docset.Methods;
}
return methods;
}
/// <summary>
/// Return a set of files matching a given wildcard filter
/// </summary>
/// <param name="docset"></param>
/// <param name="filter"></param>
/// <returns></returns>
private static IEnumerable<DocFile> FilesMatchingFilter(DocSet docset, string filter)
{
return from f in docset.Files
where f.DisplayName.IsWildcardMatch(filter)
select f;
}
/// <summary>
/// Print a collection of ValidationError objects to the console. Also shuts down the test runner
/// for the current test.
/// </summary>
/// <param name="errors"></param>
/// <param name="silenceWarnings"></param>
/// <param name="indent"></param>
/// <param name="successMessage"></param>
/// <param name="endLineBeforeWriting"></param>
/// <param name="testName"></param>
/// <param name="warningsMessage"></param>
/// <param name="errorsMessage"></param>
/// <returns></returns>
private static async Task<bool> WriteOutErrorsAndFinishTestAsync(IssueLogger issues, bool silenceWarnings, string indent = "", string successMessage = null, bool endLineBeforeWriting = false, string testName = null, string warningsMessage = null, string errorsMessage = null, bool printFailuresOnly = false)
{
string writeMessageHeader = null;
if (printFailuresOnly)
{
writeMessageHeader = $"Test {testName} results:";
}
WriteMessages(issues, silenceWarnings, indent, endLineBeforeWriting, beforeWriteHeader: writeMessageHeader);
TestOutcome outcome = TestOutcome.None;
string outputMessage = null;
var errorMessages = issues.Issues.Where(x => x.IsError);
var warningMessages = issues.Issues.Where(x => x.IsWarning);
if (errorMessages.Any())
{
// Write failure message
var singleError = errorMessages.First();
if (errorMessages.Count() == 1)
outputMessage = singleError.Message.FirstLineOnly();
else
outputMessage = "Multiple errors occured.";
outcome = TestOutcome.Failed;
}
else if (!silenceWarnings && warningMessages.Any())
{
// Write warning message
var singleWarning = warningMessages.First();
if (warningMessages.Count() == 1)
outputMessage = singleWarning.Message.FirstLineOnly();
else
outputMessage = "Multiple warnings occured.";
outcome = TestOutcome.Passed;
}
else
{
// write success message!
outputMessage = successMessage;
outcome = TestOutcome.Passed;
}
// Record this test's outcome in the build worker API
if (null != testName)
{
var errorMessage = (from e in issues.Issues select e.ErrorText).ComponentsJoinedByString("\r\n");
await TestReport.FinishTestAsync(testName, outcome, outputMessage, stdOut: errorMessage, printFailuresOnly: printFailuresOnly);
}
return outcome == TestOutcome.Passed;
}
/// <summary>
/// Prints ValidationError messages to the console, optionally excluding warnings and messages.
/// </summary>
private static void WriteMessages(
IssueLogger issues,
bool errorsOnly = false,
string indent = "",
bool endLineBeforeWriting = false,
string beforeWriteHeader = null,
bool printUnusedSuppressions = false)
{
bool writtenHeader = false;
foreach (var error in issues.Issues.OrderBy(err=>err.IsWarningOrError).ThenBy(err=>err.IsError).ThenBy(err=>err.Source))
{
RecordUndocumentedProperties(error);
// Skip messages if verbose output is off
if (!error.IsWarning && !error.IsError && !FancyConsole.WriteVerboseOutput)
{
continue;
}
// Skip warnings if silence warnings is enabled.
if (errorsOnly && !error.IsError)
{
continue;
}
if (endLineBeforeWriting)
{
FancyConsole.WriteLine();
}
if (!writtenHeader && beforeWriteHeader != null)
{
writtenHeader = true;
FancyConsole.WriteLine(beforeWriteHeader);
}
WriteValidationError(indent, error);
}
var usedSuppressions = issues.UsedSuppressions;
if (usedSuppressions.Count>0)
{
FancyConsole.WriteLine(ConsoleColor.DarkYellow, $"{usedSuppressions.Count} issues were suppressed with manual overrides in the docs.");
}
if (printUnusedSuppressions)
{
var unusedSuppressions = issues.UnusedSuppressions;
if (unusedSuppressions.Count > 0)
{
FancyConsole.WriteLine(ConsoleColor.Cyan, "Validation suppressions found that weren't used. Please remove:");
foreach (var sup in unusedSuppressions)
{
FancyConsole.WriteLineIndented(" ", ConsoleColor.Cyan, sup);
}
}
}
int warningCount = issues.Issues.Count(issue => issue.IsWarning);
int errorCount = issues.Issues.Count(iss => iss.IsError);
var color = ConsoleColor.Green;
var status = "PASSED";
if (warningCount > 0)
{
color = ConsoleColor.Yellow;
status = "FAILED with warnings";
FancyConsole.WriteLine(color, $"{warningCount} warnings");
}
if (errorCount > 0)
{
color = ConsoleColor.Red;
status = "FAILED with errors";
FancyConsole.WriteLine(color, $"{errorCount} errors");
}
FancyConsole.WriteLine(color, status);
}
private static void RecordUndocumentedProperties(ValidationError error)
{
if (error is UndocumentedPropertyWarning)
{
DiscoveredUndocumentedProperties.Add((UndocumentedPropertyWarning)error);
}
else if (error.InnerErrors != null && error.InnerErrors.Any())
{
foreach(var innerError in error.InnerErrors)
{
RecordUndocumentedProperties(innerError);
}
}
}
/// <summary>
/// Prints a formatted ValidationError object to the console.
/// </summary>
/// <param name="indent"></param>
/// <param name="error"></param>
internal static void WriteValidationError(string indent, ValidationError error)
{
ConsoleColor color;
if (error.IsWarning)
{
color = FancyConsole.ConsoleWarningColor;
}
else if (error.IsError)
{
color = FancyConsole.ConsoleErrorColor;
}
else
{
color = FancyConsole.ConsoleDefaultColor;
}
FancyConsole.WriteLineIndented(indent, color, error.ErrorText);
FancyConsole.WriteLine();
}
/// <summary>
/// Executes the remote service tests defined in the documentation. This is similar to CheckDocs, expect
/// that the actual requests come from the service instead of the documentation. Prints the errors to
/// the console.
/// </summary>
/// <param name="options"></param>
/// <returns></returns>
private static async Task<bool> CheckServiceAsync(CheckServiceOptions options, IssueLogger issues)
{
// See if we're supposed to run check-service on this branch (assuming we know what branch we're running on)
if (!string.IsNullOrEmpty(options.BranchName))
{
string[] validBranches = null;
if (null != CurrentConfiguration)
validBranches = CurrentConfiguration.CheckServiceEnabledBranches;
if (null != validBranches && !validBranches.Contains(options.BranchName))
{
RecordWarning("Aborting check-service run. Branch \"{0}\" wasn't in the checkServiceEnabledBranches configuration list.", options.BranchName);
return true;
}
}
// Configure HTTP request logging
Validation.HttpLog.HttpLogGenerator httpLogging = null;
if (!string.IsNullOrEmpty(options.HttpLoggerOutputPath))
{
httpLogging = new Validation.HttpLog.HttpLogGenerator(options.HttpLoggerOutputPath);
httpLogging.InitializePackage();
HttpRequest.HttpLogSession = httpLogging;
}
var docset = await GetDocSetAsync(options, issues);
if (null == docset)
{
return false;
}
FancyConsole.WriteLine();
if (!string.IsNullOrEmpty(options.ODataMetadataLevel))
{
ValidationConfig.ODataMetadataLevel = options.ODataMetadataLevel;
}
if (options.FoundAccounts == null || !options.FoundAccounts.Any(x=>x.Enabled))
{
RecordError("No account was found. Cannot connect to the service.");
return false;
}
IServiceAccount secondaryAccount = null;
if (options.SecondaryAccountName != null)
{
var secondaryAccounts = options.FoundAccounts.Where(
x => options.SecondaryAccountName.Equals(x.Name));
secondaryAccount = secondaryAccounts.FirstOrDefault();
}
var accountsToProcess =
options.FoundAccounts.Where(
x => string.IsNullOrEmpty(options.AccountName)
? x.Enabled
: options.AccountName.Equals(x.Name));
if (!accountsToProcess.Any())
{
Console.WriteLine("No accounts were selected.");
}
var methods = FindTestMethods(options, docset);
Dictionary<string, CheckResults> results = new Dictionary<string, CheckResults>();
foreach (var account in accountsToProcess)
{
// if the service root URL is also provided, override the account URL
if (!string.IsNullOrEmpty(options.ServiceRootUrl))
{
account.OverrideBaseUrl(options.ServiceRootUrl);
}
var accountResults = await CheckMethodsForAccountAsync(options, account, secondaryAccount, methods, docset);
if (null != accountResults)
{
results[account.Name] = accountResults;
}
}
// Disable http logging
if (null != httpLogging)
{
HttpRequest.HttpLogSession = null;
httpLogging.ClosePackage();
}
// Print out account summary if multiple accounts were used
foreach (var key in results.Keys)
{
FancyConsole.Write("Account {0}: ", key);
results[key].PrintToConsole(false);
}
// Print out undocumented properties, if any where found.
WriteUndocumentedProperties();
return !results.Values.Any(x => x.WereFailures);
}
private static void WriteUndocumentedProperties()
{
// Collapse all the properties we've discovered down into an easy-to-digest list of properties and resources
Dictionary<string, HashSet<string>> undocumentedProperties = new Dictionary<string, HashSet<string>>();
foreach (var props in DiscoveredUndocumentedProperties)
{
HashSet<string> foundPropertiesOnResource;
if (props.ResourceName != null)
{
if (!undocumentedProperties.TryGetValue(props.ResourceName, out foundPropertiesOnResource))
{
foundPropertiesOnResource = new HashSet<string>();
undocumentedProperties.Add(props.ResourceName, foundPropertiesOnResource);
}
foundPropertiesOnResource.Add(props.PropertyName);
}
}
string seperator = ", ";
if (undocumentedProperties.Any())
{
FancyConsole.WriteLine(FancyConsole.ConsoleWarningColor, "The following undocumented properties were detected:");
foreach (var resource in undocumentedProperties)
{
Console.WriteLine($"Resource {resource.Key}: {resource.Value.ComponentsJoinedByString(seperator)}");
}
}
}
/// <summary>
/// Execute the provided methods on the given account.
/// </summary>
/// <param name="commandLineOptions"></param>
/// <param name="account"></param>
/// <param name="methods"></param>
/// <param name="docset"></param>
/// <returns>A CheckResults instance that contains the details of the test run</returns>
private static async Task<CheckResults> CheckMethodsForAccountAsync(CheckServiceOptions commandLineOptions, IServiceAccount primaryAccount, IServiceAccount secondaryAccount, MethodDefinition[] methods, DocSet docset)
{
ConfigureAdditionalHeadersForAccount(commandLineOptions, primaryAccount);
FancyConsole.WriteLine(FancyConsole.ConsoleHeaderColor, "Testing account: {0}", primaryAccount.Name);
FancyConsole.WriteLine(FancyConsole.ConsoleCodeColor, "Preparing authentication for requests...", primaryAccount.Name);
try
{
await primaryAccount.PrepareForRequestAsync();
}
catch (Exception ex)
{
RecordError(ex.Message);
return null;
}
if (secondaryAccount != null)
{
ConfigureAdditionalHeadersForAccount(commandLineOptions, secondaryAccount);
try
{
await secondaryAccount.PrepareForRequestAsync();
}
catch (Exception ex)
{
RecordError(ex.Message);
return null;
}
}
int concurrentTasks = commandLineOptions.ParallelTests ? ParallelTaskCount : 1;
CheckResults docSetResults = new CheckResults();
await ForEachAsync(methods, concurrentTasks, async method =>
{
FancyConsole.WriteLine(
FancyConsole.ConsoleCodeColor,
"Running validation for method: {0}",
method.Identifier);
// List out the scenarios defined for this method
ScenarioDefinition[] scenarios = docset.TestScenarios.ScenariosForMethod(method);
// Test these scenarios and validate responses
ValidationResults results = await method.ValidateServiceResponseAsync(scenarios, primaryAccount, secondaryAccount,
new ValidationOptions {
RelaxedStringValidation = commandLineOptions.RelaxStringTypeValidation ?? true,
IgnoreRequiredScopes = commandLineOptions.IgnoreRequiredScopes
});
PrintResultsToConsole(method, primaryAccount, results, commandLineOptions);
await TestReport.LogMethodTestResults(method, primaryAccount, results);
docSetResults.RecordResults(results, commandLineOptions);
if (concurrentTasks == 1)
{
AddPause(commandLineOptions);
}
});
if (commandLineOptions.IgnoreWarnings || commandLineOptions.SilenceWarnings)
{
// Remove the warning flag from the outcomes
docSetResults.ConvertWarningsToSuccess();
}
docSetResults.PrintToConsole();
return docSetResults;
}
/// <summary>
/// Parallel enabled for each processor that supports async lambdas. Copied from
/// http://blogs.msdn.com/b/pfxteam/archive/2012/03/05/10278165.aspx
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source">Collection of items to iterate over</param>
/// <param name="dop">Degree of parallelism to execute.</param>
/// <param name="body">Lambda expression executed for each operation</param>
/// <returns></returns>
public static Task ForEachAsync<T>(IEnumerable<T> source, int dop, Func<T, Task> body)
{
return Task.WhenAll(
from partition in System.Collections.Concurrent.Partitioner.Create(source).GetPartitions(dop)
select Task.Run(async delegate
{
using (partition)
while (partition.MoveNext())
await body(partition.Current);
}));
}
/// <summary>
/// Write the results of a test to the output console.
/// </summary>
/// <param name="method"></param>
/// <param name="account"></param>
/// <param name="results"></param>
/// <param name="options"></param>
private static void PrintResultsToConsole(MethodDefinition method, IServiceAccount account, ValidationResults output, CheckServiceOptions options)
{
// Only allow one thread at a time to write to the console so we don't interleave our results.
lock (typeof(Program))
{
FancyConsole.WriteLine(
FancyConsole.ConsoleHeaderColor,
"Testing method {0} with account {1}",
method.Identifier,
account.Name);
foreach (var scenario in output.Results)
{
if (scenario.Errors.Count > 0)
{
FancyConsole.WriteLineIndented(
" ",
FancyConsole.ConsoleSubheaderColor,
"Scenario: {0}",
scenario.Name);
foreach (var message in scenario.Errors)
{
if (options.EnableVerboseOutput || message.IsWarningOrError)
FancyConsole.WriteLineIndented(
" ",
FancyConsole.ConsoleDefaultColor,
message.ErrorText);
RecordUndocumentedProperties(message);
}
if (options.SilenceWarnings && scenario.Outcome == ValidationOutcome.Warning)
{
scenario.Outcome = ValidationOutcome.Passed;
}
FancyConsole.WriteLineIndented(
" ",
scenario.Outcome.ConsoleColor(),
"Scenario finished with outcome: {0}. Duration: {1}",
scenario.Outcome,
scenario.Duration);
}
}
FancyConsole.WriteLineIndented(
" ",
output.OverallOutcome.ConsoleColor(),
"Method testing finished with overall outcome: {0}",
output.OverallOutcome);
FancyConsole.WriteLine();
}
}
private static void ConfigureAdditionalHeadersForAccount(CheckServiceOptions options, IServiceAccount account)
{
if (account.AdditionalHeaders != null && account.AdditionalHeaders.Length > 0)
{
// If the account needs additional headers, merge them in.
List<string> headers = new List<string>(account.AdditionalHeaders);
if (options.AdditionalHeaders != null)
{
headers.AddRange(options.AdditionalHeaders.Split('|'));
}
ValidationConfig.AdditionalHttpHeaders = headers.ToArray();
}
else if (options.AdditionalHeaders != null)
{
var headers = options.AdditionalHeaders.Split('|');
ValidationConfig.AdditionalHttpHeaders = headers.ToArray();
}
}
private static void Exit(bool failure, int? customExitCode = null)
{
int exitCode = failure ? ExitCodeFailure : ExitCodeSuccess;
if (customExitCode.HasValue)
{
exitCode = customExitCode.Value;
}
if (IgnoreErrors)
{
FancyConsole.WriteLine("Ignoring errors and returning a successful exit code.");
exitCode = ExitCodeSuccess;
}
#if DEBUG
Console.WriteLine("Exit code: " + exitCode);
if (Debugger.IsAttached)
{
Console.WriteLine();
Console.Write("Press any key to exit.");
Console.ReadKey();
}
#endif
Environment.Exit(exitCode);
}
private static void AddPause(CheckServiceOptions options)
{
if (options.PauseBetweenRequests)
{
FancyConsole.WriteLine("Press any key to continue");
Console.ReadKey();
FancyConsole.WriteLine();
}
}
public static async Task<bool> PublishMetadataAsync(PublishMetadataOptions options, IssueLogger issues, DocSet docSet = null)
{
var docs = docSet ?? await GetDocSetAsync(options, issues);
if (null == docs)
{
return false;
}
var publisher = new Publishing.CSDL.CsdlWriter(docs, options.GetOptions());
FancyConsole.WriteLine();
FancyConsole.WriteLine("Publishing metadata...");
publisher.NewMessage += publisher_NewMessage;
try
{
var outputPath = options.OutputDirectory;
await publisher.PublishToFolderAsync(outputPath, issues);
FancyConsole.WriteLine(FancyConsole.ConsoleSuccessColor, "Finished publishing metadata.");
}
catch (Exception ex)
{
FancyConsole.WriteLine(
FancyConsole.ConsoleErrorColor,
"An error occured while publishing: {0}",
ex.ToString());
Exit(failure: true, customExitCode: 99);
return false;
}
if (!string.IsNullOrEmpty(options.CompareToMetadataPath))
{
SchemaConfigFile[] schemaConfigs = DocSet.TryLoadConfigurationFiles<SchemaConfigFile>(options.DocumentationSetPath);
var schemaConfig = schemaConfigs.FirstOrDefault();
SchemaDiffConfig config = null;
if (schemaConfig?.SchemaDiffConfig != null)
{
Console.WriteLine($"Using schemadiff config file: {schemaConfig.SourcePath}");
config = schemaConfig.SchemaDiffConfig;
}
var sorter = new Publishing.CSDL.XmlSorter(config) { KeepUnrecognizedObjects = options.KeepUnrecognizedObjects };
sorter.Sort(Path.Combine(options.OutputDirectory, "metadata.xml"), options.CompareToMetadataPath);
}
return true;
}
private static async Task<bool> PublishDocumentationAsync(PublishOptions options, IssueLogger issues)
{
var outputPath = options.OutputDirectory;
FancyConsole.WriteLine("Publishing documentation to {0}", outputPath);
DocSet docs = await GetDocSetAsync(options, issues);
if (null == docs)
return false;
DocumentPublisher publisher = null;
switch (options.Format)
{
case PublishOptions.PublishFormat.Markdown:
publisher = new MarkdownPublisher(docs);
break;
case PublishOptions.PublishFormat.Html:
publisher = new DocumentPublisherHtml(docs, options);
break;
case PublishOptions.PublishFormat.Mustache:
publisher = new HtmlMustacheWriter(docs, options);
break;
case PublishOptions.PublishFormat.JsonToc:
publisher = new HtmlMustacheWriter(docs, options) { TocOnly = true };
break;
case PublishOptions.PublishFormat.Swagger2:
publisher = new SwaggerWriter(docs, "https://service.org") // TODO: Plumb in the base URL.
{
Title = options.Title,
Description = options.Description,
Version = options.Version
};
break;
case PublishOptions.PublishFormat.Outline:
publisher = new OutlinePublisher(docs);
break;
default:
FancyConsole.WriteLine(
FancyConsole.ConsoleErrorColor,
"Unsupported publishing format: {0}",
options.Format);
return false;
}
FancyConsole.WriteLineIndented(" ", "Format: {0}", publisher.GetType().Name);
publisher.VerboseLogging = options.EnableVerboseOutput;
FancyConsole.WriteLine();
FancyConsole.WriteLine("Publishing content...");
publisher.NewMessage += publisher_NewMessage;
try
{
await publisher.PublishToFolderAsync(outputPath, issues);
FancyConsole.WriteLine(FancyConsole.ConsoleSuccessColor, "Finished publishing documentation to: {0}", outputPath);
}
catch (Exception ex)
{
FancyConsole.WriteLine(
FancyConsole.ConsoleErrorColor,
"An error occured while publishing: {0}",
ex.Message);
FancyConsole.VerboseWriteLine(ex.ToString());
Exit(failure: true, customExitCode: 99);
return false;
}
return true;
}
static void publisher_NewMessage(object sender, ValidationMessageEventArgs e)
{
var msg = e.Message;
if (!FancyConsole.WriteVerboseOutput && !msg.IsError && !msg.IsWarning)
return;
WriteValidationError("", msg);
}
private static async Task<EntityFramework> TryGetMetadataEntityFrameworkAsync(CheckMetadataOptions options)
{
if (string.IsNullOrEmpty(options.ServiceMetadataLocation))
{
RecordError("No service metadata file location specified.");
return null;
}
FancyConsole.WriteLine(FancyConsole.ConsoleHeaderColor, "Loading service metadata from '{0}'...", options.ServiceMetadataLocation);
EntityFramework edmx = null;
try
{
Uri metadataUrl;
if (Uri.IsWellFormedUriString(options.ServiceMetadataLocation, UriKind.Absolute) && Uri.TryCreate(options.ServiceMetadataLocation, UriKind.Absolute, out metadataUrl))
{
edmx = await ODataParser.ParseEntityFrameworkFromUrlAsync(metadataUrl);
}
else
{
edmx = await ODataParser.ParseEntityFrameworkFromFileAsync(options.ServiceMetadataLocation);
}
}
catch (Exception ex)
{
RecordError("Error parsing service metadata: {0}", ex.Message);
return null;
}
return edmx;
}
private static async Task<List<Schema>> TryGetMetadataSchemasAsync(CheckMetadataOptions options)
{
EntityFramework edmx = await TryGetMetadataEntityFrameworkAsync(options);
return edmx.DataServices.Schemas;
}
private static async Task<bool> FixDocsAsync(FixDocsOptions options, IssueLogger issues)
{
var originalOut = Console.Out;
Console.SetOut(new System.IO.StringWriter());
// first read the reference metadata
var inputSchemas = await TryGetMetadataSchemasAsync(options);
if (inputSchemas == null)
{
return false;
}
// next read the doc set
var docSetIssues = new IssueLogger() { DebugLine = issues.DebugLine };
var docs = await GetDocSetAsync(options, docSetIssues);
if (docs == null)
{
return false;
}
var csdlOptions = new PublishMetadataOptions();
var publisher = new Publishing.CSDL.CsdlWriter(docs, csdlOptions.GetOptions());
var edmx = publisher.CreateEntityFrameworkFromDocs(docSetIssues);
Console.SetOut(originalOut);
Console.WriteLine("checking for issues...");
foreach (var inputSchema in inputSchemas)
{
var docSchema = edmx.DataServices?.Schemas?.FirstOrDefault(s => s.Namespace == inputSchema.Namespace);
if (docSchema != null)
{
// remove any superfluous 'keyProperty' declarations.
// this can happen when copy/pasting from an entity declaration, where the key property
// is inherited from a base type and not shown in the current type
foreach (var resource in docs.Resources)
{
if (!string.IsNullOrEmpty(resource.OriginalMetadata.KeyPropertyName) &&
!resource.Parameters.Any(p => p.Name == resource.KeyPropertyName))
{
if (resource.ResolvedBaseTypeReference != null &&
string.Equals(resource.OriginalMetadata.KeyPropertyName, resource.ResolvedBaseTypeReference.ExplicitOrInheritedKeyPropertyName))
{
if (!options.DryRun)
{
resource.OriginalMetadata.KeyPropertyName = null;
resource.OriginalMetadata.PatchSourceFile();
Console.WriteLine($"Removed keyProperty from {resource.Name} because it was defined by an ancestor.");
}
else
{
Console.WriteLine($"Want to remove keyProperty from {resource.Name} because it's defined by an ancestor.");
}
}
if (resource.BaseType == null)
{
if (!options.DryRun)
{
resource.OriginalMetadata.KeyPropertyName = null;
resource.OriginalMetadata.PatchSourceFile();
Console.WriteLine($"Removed keyProperty from {resource.Name} because it's probably a complex type.");
}
else
{
Console.WriteLine($"Want to remove keyProperty from {resource.Name} because it's probably a complex type.");
}
}
}
}
foreach (var inputEnum in inputSchema.Enumerations)
{
if (!docs.Enums.Any(e=>e.TypeName.TypeOnly() == inputEnum.Name.TypeOnly()))
{
// found an enum that wasn't in the docs.
// see if we can find the resource it belongs to and stick a definition table in.
var enumMembers = inputEnum.Members.ToDictionary(m => m.Name, StringComparer.OrdinalIgnoreCase);
foreach (var resource in docs.Resources)
{
if (options.Matches.Count > 0 && !options.Matches.Contains(resource.Name.TypeOnly()))
{
continue;
}
bool found = false;
string tableDescriptionToAlter = null;
foreach (var param in resource.Parameters.Where(p => p.Type?.Type == SimpleDataType.String))
{
if (param.Description != null &&
(param.Description.IContains("possible values") ||
param.Description.IContains("one of")))
{
var tokens = param.Description.TokenizedWords();
if (tokens.Count(t => enumMembers.ContainsKey(t)) >= 3)
{
found = true;
tableDescriptionToAlter = param.Description;
break;
}
}
if (param.PossibleEnumValues().Count(v=>enumMembers.ContainsKey(v)) >=2)
{
found = true;
break;
}
}
if (found)
{
// we want to stick this after #properties but before the next one.
int propertiesLineNumber = 0;
int propertiesHNumber = 0;
int nextWhiteSpaceLineNumber = 0;
var lines = File.ReadAllLines(resource.SourceFile.FullPath);
for (int i=0; i< lines.Length; i++)
{
var line = lines[i];
if (propertiesLineNumber == 0 &&
line.StartsWith("#") &&
line.Contains("Properties"))
{
propertiesLineNumber = i;
propertiesHNumber = line.Count(c => c == '#');
continue;
}
// ideally we wouldn't have to re-tokenize, but the place we did it earlier
// had markdown syntax stripped out, and we don't have that luxury here...
if (line.TokenizedWords().Count(t => enumMembers.ContainsKey(t)) >= 3)
{
// | paramName | string | description text ending with enum values
var split = line.Split('|');
if (split.Length > 3 && split[2].IContains("string"))
{
split[2] = split[2].IReplace("string", inputEnum.Name);
lines[i] = string.Join("|", split);
}
}
if (propertiesLineNumber > 0 && string.IsNullOrWhiteSpace(line))
{
nextWhiteSpaceLineNumber = i;
break;
}
}
if (propertiesLineNumber > 0)
{
// produce the table
StringBuilder table = new StringBuilder($"{new string('#', propertiesHNumber + 1)} {inputEnum.Name} values\r\n\r\n");
table.AppendLine("| Value\r\n|:-------------------------");
foreach (var member in inputEnum.Members)
{
table.AppendLine($"| {member.Name}");
}
table.AppendLine();
if (nextWhiteSpaceLineNumber == 0)
{
nextWhiteSpaceLineNumber = lines.Length - 1;
}
var final = FileSplicer(lines, nextWhiteSpaceLineNumber, table.ToString());
if (options.DryRun)
{
Console.WriteLine($"Want to splice into L{nextWhiteSpaceLineNumber + 1} of {resource.SourceFile.DisplayName}\r\n{table}");
}
else
{
File.WriteAllLines(resource.SourceFile.FullPath, final);
}
}
else
{
Console.WriteLine($"WARNING: Couldn't find where to insert enum table for {inputEnum.Name}");
}
}
}
}
}
foreach (var inputComplex in inputSchema.ComplexTypes.Concat(inputSchema.EntityTypes))
{
if (options.Matches.Count > 0 && !options.Matches.Contains(inputComplex.Name))
{
continue;
}
var docComplex =
docSchema.ComplexTypes?.FirstOrDefault(c => c.Name.IEquals(inputComplex.Name)) ??
docSchema.EntityTypes?.FirstOrDefault(c => c.Name.IEquals(inputComplex.Name));
if (docComplex != null)
{
List<Action<CodeBlockAnnotation>> fixes = new List<Action<CodeBlockAnnotation>>();
if (inputComplex.BaseType != docComplex.BaseType)
{
Console.WriteLine($"Mismatched BaseTypes: '{docComplex.Name}:{docComplex.BaseType}' vs '{inputComplex.Name}:{inputComplex.BaseType}'.");
fixes.Add(code => code.BaseType = inputComplex.BaseType);
}
if (inputComplex.Abstract != docComplex.Abstract)
{
Console.WriteLine($"Mismatched Abstract: '{docComplex.Name}:{docComplex.Abstract}' vs '{inputComplex.Name}:{inputComplex.Abstract}'.");
fixes.Add(code => code.Abstract = inputComplex.Abstract);
}
if (inputComplex.OpenType != docComplex.OpenType)
{
Console.WriteLine($"Mismatched OpenType: '{docComplex.Name}:{docComplex.OpenType}' vs '{inputComplex.Name}:{inputComplex.OpenType}'.");
fixes.Add(code => code.IsOpenType = inputComplex.OpenType);
}
var inputEntity = inputComplex as EntityType;
var docEntity = docComplex as EntityType;
if (docEntity != null && inputEntity != null)
{
if (docEntity.Key?.PropertyRef?.Name != inputEntity.Key?.PropertyRef?.Name)
{
Console.WriteLine($"Mismatched KeyProperty: '{docComplex.Name}:{docEntity.Key?.PropertyRef?.Name}' vs '{inputComplex.Name}:{inputEntity.Key?.PropertyRef?.Name}'.");
fixes.Add(code => code.KeyPropertyName = inputEntity.Key?.PropertyRef?.Name);
}
if (!docEntity.HasStream && inputEntity.HasStream)
{
Console.WriteLine($"Mismatched IsMediaEntity in {docComplex.Name}.");
fixes.Add(code => code.IsMediaEntity = true);
}
}
if (fixes.Count > 0)
{
foreach (var resource in docComplex.Contributors)
{
foreach (var fix in fixes)
{
fix(resource.OriginalMetadata);
if (!options.DryRun)
{
resource.OriginalMetadata.PatchSourceFile();
Console.WriteLine("\tFixed!");
}
}
}
}
}
}
issues.Message("Looking for composable functions that couldn't be inferred from the docs...");
foreach (var inputFunction in inputSchema.Functions.Where(fn => fn.IsComposable))
{
var pc = ParameterComparer.Instance;
var docFunctions = docSchema.Functions.
Where(fn =>
fn.Name == inputFunction.Name &&
!fn.IsComposable &&
fn.Parameters.OrderBy(p => p, pc).SequenceEqual(inputFunction.Parameters.OrderBy(p => p, pc), pc)).
ToList();
foreach (var docFunction in docFunctions)
{
var methods = docFunction.SourceMethods as List<MethodDefinition>;
if (methods != null)
{
foreach (var metadata in methods.Select(m => m.RequestMetadata).Where(md => !md.IsComposable))
{
metadata.IsComposable = true;
if (options.DryRun)
{
Console.WriteLine("Would fix " + metadata.MethodName.FirstOrDefault());
}
else
{
metadata.PatchSourceFile();
Console.WriteLine("Fixed " + metadata.MethodName.FirstOrDefault());
}
}
}
}
}
}
}
return true;
}
public static IEnumerable<string> FileSplicer(string[] original, int offset, string valueToSplice)
{
for (int i=0; i< original.Length; i++)
{
yield return original[i];
if (i == offset)
{
yield return valueToSplice;
}
}
}
/// <summary>
/// Validate that the CSDL metadata defined for a service matches the documentation.
/// </summary>
/// <param name="options"></param>
/// <returns></returns>
private static async Task<bool> CheckServiceMetadataAsync(CheckMetadataOptions options, IssueLogger issues)
{
List<Schema> schemas = await TryGetMetadataSchemasAsync(options);
if (null == schemas)
return false;
FancyConsole.WriteLine(FancyConsole.ConsoleSuccessColor, " found {0} schema definitions: {1}", schemas.Count, (from s in schemas select s.Namespace).ComponentsJoinedByString(", "));
var docSet = await GetDocSetAsync(options, issues);
if (null == docSet)
return false;
const string testname = "validate-service-metadata";
TestReport.StartTest(testname);
List<ResourceDefinition> foundResources = ODataParser.GenerateResourcesFromSchemas(schemas, issues);
CheckResults results = new CheckResults();
foreach (var resource in foundResources)
{
var resourceIssues = issues.For(resource.Name);
FancyConsole.WriteLine();
FancyConsole.Write(FancyConsole.ConsoleHeaderColor, "Checking metadata resource: {0}...", resource.Name);
FancyConsole.VerboseWriteLine();
FancyConsole.VerboseWriteLine(resource.ExampleText);
FancyConsole.VerboseWriteLine();
// Check if this resource exists in the documentation at all
ResourceDefinition matchingDocumentationResource = null;
var docResourceQuery =
from r in docSet.Resources
where r.Name == resource.Name
select r;
matchingDocumentationResource = docResourceQuery.FirstOrDefault();
if (docResourceQuery.Count() > 1)
{
// Log an error about multiple resource definitions
FancyConsole.WriteLine("Multiple resource definitions for resource {0} in files:", resource.Name);
foreach (var q in docResourceQuery)
{
FancyConsole.WriteLine(q.SourceFile.DisplayName);
}
}
if (null == matchingDocumentationResource)
{
// Couldn't find this resource in the documentation!
resourceIssues.Error(
ValidationErrorCode.ResourceTypeNotFound,
$"Resource {resource.Name} is not in the documentation.");
}
else
{
// Verify that this resource matches the documentation
docSet.ResourceCollection.ValidateJsonExample(resource.OriginalMetadata, resource.ExampleText, resourceIssues, new ValidationOptions { RelaxedStringValidation = true });
}
results.IncrementResultCount(resourceIssues.Issues);
await WriteOutErrorsAndFinishTestAsync(resourceIssues, options.SilenceWarnings, successMessage: " passed.", printFailuresOnly: options.PrintFailuresOnly);
}
if (options.IgnoreWarnings)
{
results.ConvertWarningsToSuccess();
}
var output = (from e in issues.Issues select e.ErrorText).ComponentsJoinedByString("\r\n");
await TestReport.FinishTestAsync(testname, results.WereFailures ? TestOutcome.Failed : TestOutcome.Passed, stdOut:output);
results.PrintToConsole();
return !results.WereFailures;
}
private static async Task<bool> GenerateDocsAsync(GenerateDocsOptions options)
{
EntityFramework ef = await TryGetMetadataEntityFrameworkAsync(options);
if (null == ef)
return false;
FancyConsole.WriteLine(FancyConsole.ConsoleSuccessColor, " found {0} schema definitions: {1}", ef.DataServices.Schemas.Count, (from s in ef.DataServices.Schemas select s.Namespace).ComponentsJoinedByString(", "));
DocumentationGenerator docGenerator = new DocumentationGenerator(options.ResourceTemplateFile);
docGenerator.GenerateDocumentationFromEntityFrameworkAsync(ef, options.DocumentationSetPath);
return true;
}
private class ParameterComparer : IEqualityComparer<Parameter>, IComparer<Parameter>
{
public static ParameterComparer Instance { get; } = new ParameterComparer();
private static HashSet<string> equivalentBindingParameters = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"bindParameter",
"bindingParameter",
"this",
};
private ParameterComparer()
{
}
public bool Equals(Parameter x, Parameter y)
{
if (object.ReferenceEquals(x, y))
{
return true;
}
if (x == null || y == null)
{
return false;
}
return x.Name == y.Name ||
(equivalentBindingParameters.Contains(x.Name) && equivalentBindingParameters.Contains(y.Name));
}
public int GetHashCode(Parameter obj)
{
return obj?.Name?.GetHashCode() ?? 0;
}
public int Compare(Parameter x, Parameter y)
{
if (object.ReferenceEquals(x,y))
{
return 0;
}
if (x == null)
{
return -1;
}
if (y == null)
{
return 1;
}
var xName = x.Name;
var yName = y.Name;
if (equivalentBindingParameters.Contains(xName))
{
xName = "bindingParameter";
}
if (equivalentBindingParameters.Contains(yName))
{
yName = "bindingParameter";
}
return xName.CompareTo(yName);
}
}
}
class ConsoleAppLogger : ILogHelper
{
public void RecordError(ValidationError error)
{
Program.WriteValidationError(string.Empty, error);
}
}
internal static class OutcomeExtensionMethods
{
public static ConsoleColor ConsoleColor(this ValidationOutcome outcome)
{
if ((outcome & ValidationOutcome.Error) > 0)
return FancyConsole.ConsoleErrorColor;
if ((outcome & ValidationOutcome.Warning) > 0)
return FancyConsole.ConsoleWarningColor;
if ((outcome & ValidationOutcome.Passed) > 0)
return FancyConsole.ConsoleSuccessColor;
if ((outcome & ValidationOutcome.Skipped) > 0)
return FancyConsole.ConsoleWarningColor;
return FancyConsole.ConsoleDefaultColor;
}
}
}
| 42.764764 | 315 | 0.526291 | [
"MIT"
] | MIchaelMainer/apidoctor | ApiDoctor.Console/Program.cs | 86,173 | C# |
/*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: [email protected]
* Generated by: https://openapi-generator.tech
*/
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Org.OpenAPITools.Converters;
namespace Org.OpenAPITools.Models
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class BranchImpllinks : IEquatable<BranchImpllinks>
{
/// <summary>
/// Gets or Sets Self
/// </summary>
[DataMember(Name="self", EmitDefaultValue=false)]
public Link Self { get; set; }
/// <summary>
/// Gets or Sets Actions
/// </summary>
[DataMember(Name="actions", EmitDefaultValue=false)]
public Link Actions { get; set; }
/// <summary>
/// Gets or Sets Runs
/// </summary>
[DataMember(Name="runs", EmitDefaultValue=false)]
public Link Runs { get; set; }
/// <summary>
/// Gets or Sets Queue
/// </summary>
[DataMember(Name="queue", EmitDefaultValue=false)]
public Link Queue { get; set; }
/// <summary>
/// Gets or Sets Class
/// </summary>
[DataMember(Name="_class", EmitDefaultValue=false)]
public string Class { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class BranchImpllinks {\n");
sb.Append(" Self: ").Append(Self).Append("\n");
sb.Append(" Actions: ").Append(Actions).Append("\n");
sb.Append(" Runs: ").Append(Runs).Append("\n");
sb.Append(" Queue: ").Append(Queue).Append("\n");
sb.Append(" Class: ").Append(Class).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == GetType() && Equals((BranchImpllinks)obj);
}
/// <summary>
/// Returns true if BranchImpllinks instances are equal
/// </summary>
/// <param name="other">Instance of BranchImpllinks to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(BranchImpllinks other)
{
if (other is null) return false;
if (ReferenceEquals(this, other)) return true;
return
(
Self == other.Self ||
Self != null &&
Self.Equals(other.Self)
) &&
(
Actions == other.Actions ||
Actions != null &&
Actions.Equals(other.Actions)
) &&
(
Runs == other.Runs ||
Runs != null &&
Runs.Equals(other.Runs)
) &&
(
Queue == other.Queue ||
Queue != null &&
Queue.Equals(other.Queue)
) &&
(
Class == other.Class ||
Class != null &&
Class.Equals(other.Class)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
var hashCode = 41;
// Suitable nullity checks etc, of course :)
if (Self != null)
hashCode = hashCode * 59 + Self.GetHashCode();
if (Actions != null)
hashCode = hashCode * 59 + Actions.GetHashCode();
if (Runs != null)
hashCode = hashCode * 59 + Runs.GetHashCode();
if (Queue != null)
hashCode = hashCode * 59 + Queue.GetHashCode();
if (Class != null)
hashCode = hashCode * 59 + Class.GetHashCode();
return hashCode;
}
}
#region Operators
#pragma warning disable 1591
public static bool operator ==(BranchImpllinks left, BranchImpllinks right)
{
return Equals(left, right);
}
public static bool operator !=(BranchImpllinks left, BranchImpllinks right)
{
return !Equals(left, right);
}
#pragma warning restore 1591
#endregion Operators
}
}
| 32.056818 | 106 | 0.504254 | [
"MIT"
] | cliffano/jenkins-api-clients-generator | clients/aspnetcore/generated/src/Org.OpenAPITools/Models/BranchImpllinks.cs | 5,642 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using HuaweiCloud.SDK.Core;
namespace HuaweiCloud.SDK.Iam.V3.Model
{
/// <summary>
///
/// </summary>
public class CreateCredentialResult
{
/// <summary>
/// 创建访问密钥时间。
/// </summary>
[JsonProperty("create_time", NullValueHandling = NullValueHandling.Ignore)]
public string CreateTime { get; set; }
/// <summary>
/// 创建的AK。
/// </summary>
[JsonProperty("access", NullValueHandling = NullValueHandling.Ignore)]
public string Access { get; set; }
/// <summary>
/// 创建的SK。
/// </summary>
[JsonProperty("secret", NullValueHandling = NullValueHandling.Ignore)]
public string Secret { get; set; }
/// <summary>
/// 访问密钥状态。
/// </summary>
[JsonProperty("status", NullValueHandling = NullValueHandling.Ignore)]
public string Status { get; set; }
/// <summary>
/// IAM用户ID。
/// </summary>
[JsonProperty("user_id", NullValueHandling = NullValueHandling.Ignore)]
public string UserId { get; set; }
/// <summary>
/// 访问密钥描述信息。
/// </summary>
[JsonProperty("description", NullValueHandling = NullValueHandling.Ignore)]
public string Description { get; set; }
/// <summary>
/// Get the string
/// </summary>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class CreateCredentialResult {\n");
sb.Append(" createTime: ").Append(CreateTime).Append("\n");
sb.Append(" access: ").Append(Access).Append("\n");
sb.Append(" secret: ").Append(Secret).Append("\n");
sb.Append(" status: ").Append(Status).Append("\n");
sb.Append(" userId: ").Append(UserId).Append("\n");
sb.Append(" description: ").Append(Description).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
public override bool Equals(object input)
{
return this.Equals(input as CreateCredentialResult);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
public bool Equals(CreateCredentialResult input)
{
if (input == null)
return false;
return
(
this.CreateTime == input.CreateTime ||
(this.CreateTime != null &&
this.CreateTime.Equals(input.CreateTime))
) &&
(
this.Access == input.Access ||
(this.Access != null &&
this.Access.Equals(input.Access))
) &&
(
this.Secret == input.Secret ||
(this.Secret != null &&
this.Secret.Equals(input.Secret))
) &&
(
this.Status == input.Status ||
(this.Status != null &&
this.Status.Equals(input.Status))
) &&
(
this.UserId == input.UserId ||
(this.UserId != null &&
this.UserId.Equals(input.UserId))
) &&
(
this.Description == input.Description ||
(this.Description != null &&
this.Description.Equals(input.Description))
);
}
/// <summary>
/// Get hash code
/// </summary>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.CreateTime != null)
hashCode = hashCode * 59 + this.CreateTime.GetHashCode();
if (this.Access != null)
hashCode = hashCode * 59 + this.Access.GetHashCode();
if (this.Secret != null)
hashCode = hashCode * 59 + this.Secret.GetHashCode();
if (this.Status != null)
hashCode = hashCode * 59 + this.Status.GetHashCode();
if (this.UserId != null)
hashCode = hashCode * 59 + this.UserId.GetHashCode();
if (this.Description != null)
hashCode = hashCode * 59 + this.Description.GetHashCode();
return hashCode;
}
}
}
}
| 33.253425 | 83 | 0.484037 | [
"Apache-2.0"
] | cnblogs/huaweicloud-sdk-net-v3 | Services/Iam/V3/Model/CreateCredentialResult.cs | 4,927 | C# |
using Avalonia.Threading;
namespace Omnius.Core.Avalonia;
public interface IApplicationDispatcher
{
public Task InvokeAsync(Action action, DispatcherPriority priority = DispatcherPriority.Normal);
public Task<TResult> InvokeAsync<TResult>(Func<TResult> function, DispatcherPriority priority = DispatcherPriority.Normal);
public Task InvokeAsync(Func<Task> function, DispatcherPriority priority = DispatcherPriority.Normal);
public Task<TResult> InvokeAsync<TResult>(Func<Task<TResult>> function, DispatcherPriority priority = DispatcherPriority.Normal);
}
public class ApplicationDispatcher : IApplicationDispatcher
{
public Task InvokeAsync(Action action, DispatcherPriority priority = DispatcherPriority.Normal)
{
return Dispatcher.UIThread.InvokeAsync(action, priority);
}
public Task<TResult> InvokeAsync<TResult>(Func<TResult> function, DispatcherPriority priority = DispatcherPriority.Normal)
{
return Dispatcher.UIThread.InvokeAsync(function, priority);
}
public Task InvokeAsync(Func<Task> function, DispatcherPriority priority = DispatcherPriority.Normal)
{
return Dispatcher.UIThread.InvokeAsync(function, priority);
}
public Task<TResult> InvokeAsync<TResult>(Func<Task<TResult>> function, DispatcherPriority priority = DispatcherPriority.Normal)
{
return Dispatcher.UIThread.InvokeAsync(function, priority);
}
}
| 37.605263 | 133 | 0.773968 | [
"MIT"
] | OmniusLabs/Omnix | src/Omnius.Core.Avalonia/ApplicationDispatcher.cs | 1,429 | C# |
using System.Net;
using FluentAssertions;
using HealthChecks.UI.Client;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace HealthChecks.Oracle.Tests.Functional
{
public class oracle_healthcheck_should
{
[Fact]
public async Task be_healthy_when_oracle_is_available()
{
var connectionString = "Data Source=localhost:1521/XEPDB1;User Id=system;Password=oracle";
var webHostBuilder = new WebHostBuilder()
.ConfigureServices(services =>
{
services.AddHealthChecks()
.AddOracle(connectionString, tags: new string[] { "oracle" });
})
.Configure(app =>
{
app.UseHealthChecks("/health", new HealthCheckOptions
{
Predicate = r => r.Tags.Contains("oracle"),
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});
});
using var server = new TestServer(webHostBuilder);
using var response = await server.CreateRequest("/health").GetAsync();
response.StatusCode.Should().Be(HttpStatusCode.OK, await response.Content.ReadAsStringAsync());
}
[Fact]
public async Task be_unhealthy_when_oracle_is_not_available()
{
var connectionString = "Data Source=255.255.255.255:1521/XEPDB1;User Id=system;Password=oracle";
var webHostBuilder = new WebHostBuilder()
.ConfigureServices(services =>
{
services.AddHealthChecks()
.AddOracle(connectionString, tags: new string[] { "oracle" });
})
.Configure(app =>
{
app.UseHealthChecks("/health", new HealthCheckOptions
{
Predicate = r => r.Tags.Contains("oracle")
});
});
using var server = new TestServer(webHostBuilder);
using var response = await server.CreateRequest("/health").GetAsync();
response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable);
}
[Fact]
public async Task be_unhealthy_when_sql_query_is_not_valid()
{
var connectionString = "Data Source=localhost:1521/XEPDB1;User Id=system;Password=oracle";
var webHostBuilder = new WebHostBuilder()
.ConfigureServices(services =>
{
services.AddHealthChecks()
.AddOracle(connectionString, "SELECT 1 FROM InvalidDb", tags: new string[] { "oracle" });
})
.Configure(app =>
{
app.UseHealthChecks("/health", new HealthCheckOptions
{
Predicate = r => r.Tags.Contains("oracle")
});
});
using var server = new TestServer(webHostBuilder);
using var response = await server.CreateRequest("/health").GetAsync();
response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable);
}
[Fact]
public async Task be_healthy_with_connection_string_factory_when_oracle_is_available()
{
bool factoryCalled = false;
string connectionString = "Data Source=localhost:1521/XEPDB1;User Id=system;Password=oracle";
var webHostBuilder = new WebHostBuilder()
.ConfigureServices(services =>
{
services
.AddHealthChecks()
.AddOracle(_ =>
{
factoryCalled = true;
return connectionString;
}, tags: new string[] { "oracle" });
})
.Configure(app =>
{
app.UseHealthChecks("/health", new HealthCheckOptions
{
Predicate = r => r.Tags.Contains("oracle")
});
});
using var server = new TestServer(webHostBuilder);
using var response = await server.CreateRequest("/health").GetAsync();
response.StatusCode.Should().Be(HttpStatusCode.OK, await response.Content.ReadAsStringAsync());
factoryCalled.Should().BeTrue();
}
}
}
| 39.05 | 109 | 0.542254 | [
"Apache-2.0"
] | paveldayneko/AspNetCore.Diagnostics.HealthChecks | test/HealthChecks.Oracle.Tests/Functional/OracleHealthCheckTests.cs | 4,686 | C# |
using Autofac;
using Gmich.AOP.Interceptors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Gmich.AOP.Playground
{
class Program
{
static void Main(string[] args)
{
var builder = new ContainerBuilder();
builder.RegisterType<Interceptor>().AsSelf();
var container = builder.Build();
AopSettings.InstanceFactory = type => container.Resolve(type);
var prog = new Program();
prog.Inject();
}
[Inject(typeof(TestInterceptor), InjectIn.Start)]
public void Inject()
{
Console.ReadLine();
}
}
}
| 21.323529 | 74 | 0.595862 | [
"MIT"
] | gmich/Weaving | Gmich.AOP/Gmich.AOP.Playground/Program.cs | 727 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using ETModel;
using MongoDB.Bson;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using UnityEditor;
using UnityEngine;
public struct CellInfo
{
public string Type;
public string Name;
public string Desc;
}
public class ExcelMD5Info
{
public Dictionary<string, string> fileMD5 = new Dictionary<string, string>();
public string Get(string fileName)
{
string md5 = "";
this.fileMD5.TryGetValue(fileName, out md5);
return md5;
}
public void Add(string fileName, string md5)
{
this.fileMD5[fileName] = md5;
}
}
public class ExcelExporterEditor : EditorWindow
{
[MenuItem("Tools/导出配置")]
private static void ShowWindow()
{
GetWindow(typeof(ExcelExporterEditor));
}
private const string ExcelPath = "../Excel";
private const string ServerConfigPath = "../Config/";
private bool isClient;
private ExcelMD5Info md5Info;
// Update is called once per frame
private void OnGUI()
{
try
{
const string clientPath = "./Assets/Bundles/Config";
if (GUILayout.Button("导出客户端配置"))
{
this.isClient = true;
ExportAll(clientPath);
ExportAllClass(@"./Assets/Model/Module/Demo/Config", "namespace ETModel\n{\n");
ExportAllClass(@"./Assets/Hotfix/Module/Demo/Config", "using ETModel;\n\nnamespace ETHotfix\n{\n");
Log.Info($"导出客户端配置完成!");
}
if (GUILayout.Button("导出服务端配置"))
{
this.isClient = false;
ExportAll(ServerConfigPath);
ExportAllClass(@"../Server/Model/Module/Demo/Config", "namespace ETModel\n{\n");
Log.Info($"导出服务端配置完成!");
}
}
catch (Exception e)
{
Log.Error(e);
}
}
private void ExportAllClass(string exportDir, string csHead)
{
foreach (string filePath in Directory.GetFiles(ExcelPath))
{
if (Path.GetExtension(filePath) != ".xlsx")
{
continue;
}
if (Path.GetFileName(filePath).StartsWith("~"))
{
continue;
}
ExportClass(filePath, exportDir, csHead);
Log.Info($"生成{Path.GetFileName(filePath)}类");
}
AssetDatabase.Refresh();
}
private void ExportClass(string fileName, string exportDir, string csHead)
{
XSSFWorkbook xssfWorkbook;
using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
xssfWorkbook = new XSSFWorkbook(file);
}
string protoName = Path.GetFileNameWithoutExtension(fileName);
string exportPath = Path.Combine(exportDir, $"{protoName}.cs");
using (FileStream txt = new FileStream(exportPath, FileMode.Create))
using (StreamWriter sw = new StreamWriter(txt))
{
StringBuilder sb = new StringBuilder();
ISheet sheet = xssfWorkbook.GetSheetAt(0);
sb.Append(csHead);
sb.Append($"\t[Config((int)({GetCellString(sheet, 0, 0)}))]\n");
sb.Append($"\tpublic partial class {protoName}Category : ACategory<{protoName}>\n");
sb.Append("\t{\n");
sb.Append("\t}\n\n");
sb.Append($"\tpublic class {protoName}: IConfig\n");
sb.Append("\t{\n");
sb.Append("\t\tpublic long Id { get; set; }\n");
int cellCount = sheet.GetRow(3).LastCellNum;
for (int i = 2; i < cellCount; i++)
{
string fieldDesc = GetCellString(sheet, 2, i);
if (fieldDesc.StartsWith("#"))
{
continue;
}
// s开头表示这个字段是服务端专用
if (fieldDesc.StartsWith("s") && this.isClient)
{
continue;
}
string fieldName = GetCellString(sheet, 3, i);
if (fieldName == "Id" || fieldName == "_id")
{
continue;
}
string fieldType = GetCellString(sheet, 4, i);
if (fieldType == "" || fieldName == "")
{
continue;
}
sb.Append($"\t\tpublic {fieldType} {fieldName};\n");
}
sb.Append("\t}\n");
sb.Append("}\n");
sw.Write(sb.ToString());
}
}
private void ExportAll(string exportDir)
{
string md5File = Path.Combine(ExcelPath, "md5.txt");
if (!File.Exists(md5File))
{
this.md5Info = new ExcelMD5Info();
}
else
{
this.md5Info = MongoHelper.FromJson<ExcelMD5Info>(File.ReadAllText(md5File));
}
foreach (string filePath in Directory.GetFiles(ExcelPath))
{
if (Path.GetExtension(filePath) != ".xlsx")
{
continue;
}
if (Path.GetFileName(filePath).StartsWith("~"))
{
continue;
}
string fileName = Path.GetFileName(filePath);
string oldMD5 = this.md5Info.Get(fileName);
string md5 = MD5Helper.FileMD5(filePath);
this.md5Info.Add(fileName, md5);
// if (md5 == oldMD5)
// {
// continue;
// }
Export(filePath, exportDir);
}
File.WriteAllText(md5File, this.md5Info.ToJson());
Log.Info("所有表导表完成");
AssetDatabase.Refresh();
}
private void Export(string fileName, string exportDir)
{
XSSFWorkbook xssfWorkbook;
using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
xssfWorkbook = new XSSFWorkbook(file);
}
string protoName = Path.GetFileNameWithoutExtension(fileName);
Log.Info($"{protoName}导表开始");
string exportPath = Path.Combine(exportDir, $"{protoName}.txt");
using (FileStream txt = new FileStream(exportPath, FileMode.Create))
using (StreamWriter sw = new StreamWriter(txt))
{
for (int i = 0; i < xssfWorkbook.NumberOfSheets; ++i)
{
ISheet sheet = xssfWorkbook.GetSheetAt(i);
ExportSheet(sheet, sw);
}
}
Log.Info($"{protoName}导表完成");
}
private void ExportSheet(ISheet sheet, StreamWriter sw)
{
int cellCount = sheet.GetRow(3).LastCellNum;
CellInfo[] cellInfos = new CellInfo[cellCount];
for (int i = 2; i < cellCount; i++)
{
string fieldDesc = GetCellString(sheet, 2, i);
string fieldName = GetCellString(sheet, 3, i);
string fieldType = GetCellString(sheet, 4, i);
cellInfos[i] = new CellInfo() { Name = fieldName, Type = fieldType, Desc = fieldDesc };
}
for (int i = 5; i <= sheet.LastRowNum; ++i)
{
if (GetCellString(sheet, i, 2) == "")
{
continue;
}
StringBuilder sb = new StringBuilder();
sb.Append("{");
IRow row = sheet.GetRow(i);
for (int j = 2; j < cellCount; ++j)
{
string desc = cellInfos[j].Desc.ToLower();
if (desc.StartsWith("#"))
{
continue;
}
// s开头表示这个字段是服务端专用
if (desc.StartsWith("s") && this.isClient)
{
continue;
}
// c开头表示这个字段是客户端专用
if (desc.StartsWith("c") && !this.isClient)
{
continue;
}
string fieldValue = GetCellString(row, j);
if (fieldValue == "")
{
throw new Exception($"sheet: {sheet.SheetName} 中有空白字段 {i},{j}");
}
if (j > 2)
{
sb.Append(",");
}
string fieldName = cellInfos[j].Name;
if (fieldName == "Id" || fieldName == "_id")
{
if (this.isClient)
{
fieldName = "Id";
}
else
{
fieldName = "_id";
}
}
string fieldType = cellInfos[j].Type;
sb.Append($"\"{fieldName}\":{Convert(fieldType, fieldValue)}");
}
sb.Append("}");
sw.WriteLine(sb.ToString());
}
}
private static string Convert(string type, string value)
{
switch (type)
{
case "int[]":
case "int32[]":
case "long[]":
return $"[{value}]";
case "string[]":
return $"[{value}]";
case "int":
case "int32":
case "int64":
case "long":
case "float":
case "double":
return value;
case "string":
return $"\"{value}\"";
default:
throw new Exception($"不支持此类型: {type}");
}
}
private static string GetCellString(ISheet sheet, int i, int j)
{
return sheet.GetRow(i)?.GetCell(j)?.ToString() ?? "";
}
private static string GetCellString(IRow row, int i)
{
return row?.GetCell(i)?.ToString() ?? "";
}
private static string GetCellString(ICell cell)
{
return cell?.ToString() ?? "";
}
}
| 21.997151 | 105 | 0.632042 | [
"MIT"
] | 517752548/EXET | Unity/Assets/Editor/ExcelExporterEditor/ExcelExporterEditor.cs | 7,939 | 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.Compute.V1.Snippets
{
using Google.Api.Gax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedAddressesClientSnippets
{
/// <summary>Snippet for AggregatedList</summary>
public void AggregatedListRequestObject()
{
// Snippet: AggregatedList(AggregatedListAddressesRequest, CallSettings)
// Create client
AddressesClient addressesClient = AddressesClient.Create();
// Initialize request argument(s)
AggregatedListAddressesRequest request = new AggregatedListAddressesRequest
{
OrderBy = "",
Project = "",
Filter = "",
IncludeAllScopes = false,
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<AddressAggregatedList, KeyValuePair<string, AddressesScopedList>> response = addressesClient.AggregatedList(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (KeyValuePair<string, AddressesScopedList> item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (AddressAggregatedList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, AddressesScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, AddressesScopedList>> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, AddressesScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedListAsync</summary>
public async Task AggregatedListRequestObjectAsync()
{
// Snippet: AggregatedListAsync(AggregatedListAddressesRequest, CallSettings)
// Create client
AddressesClient addressesClient = await AddressesClient.CreateAsync();
// Initialize request argument(s)
AggregatedListAddressesRequest request = new AggregatedListAddressesRequest
{
OrderBy = "",
Project = "",
Filter = "",
IncludeAllScopes = false,
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<AddressAggregatedList, KeyValuePair<string, AddressesScopedList>> response = addressesClient.AggregatedListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((KeyValuePair<string, AddressesScopedList> item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((AddressAggregatedList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, AddressesScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, AddressesScopedList>> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, AddressesScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedList</summary>
public void AggregatedList()
{
// Snippet: AggregatedList(string, string, int?, CallSettings)
// Create client
AddressesClient addressesClient = AddressesClient.Create();
// Initialize request argument(s)
string project = "";
// Make the request
PagedEnumerable<AddressAggregatedList, KeyValuePair<string, AddressesScopedList>> response = addressesClient.AggregatedList(project);
// Iterate over all response items, lazily performing RPCs as required
foreach (KeyValuePair<string, AddressesScopedList> item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (AddressAggregatedList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, AddressesScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, AddressesScopedList>> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, AddressesScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedListAsync</summary>
public async Task AggregatedListAsync()
{
// Snippet: AggregatedListAsync(string, string, int?, CallSettings)
// Create client
AddressesClient addressesClient = await AddressesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
// Make the request
PagedAsyncEnumerable<AddressAggregatedList, KeyValuePair<string, AddressesScopedList>> response = addressesClient.AggregatedListAsync(project);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((KeyValuePair<string, AddressesScopedList> item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((AddressAggregatedList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, AddressesScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, AddressesScopedList>> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, AddressesScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void DeleteRequestObject()
{
// Snippet: Delete(DeleteAddressRequest, CallSettings)
// Create client
AddressesClient addressesClient = AddressesClient.Create();
// Initialize request argument(s)
DeleteAddressRequest request = new DeleteAddressRequest
{
RequestId = "",
Region = "",
Project = "",
Address = "",
};
// Make the request
Operation response = addressesClient.Delete(request);
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteRequestObjectAsync()
{
// Snippet: DeleteAsync(DeleteAddressRequest, CallSettings)
// Additional: DeleteAsync(DeleteAddressRequest, CancellationToken)
// Create client
AddressesClient addressesClient = await AddressesClient.CreateAsync();
// Initialize request argument(s)
DeleteAddressRequest request = new DeleteAddressRequest
{
RequestId = "",
Region = "",
Project = "",
Address = "",
};
// Make the request
Operation response = await addressesClient.DeleteAsync(request);
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void Delete()
{
// Snippet: Delete(string, string, string, CallSettings)
// Create client
AddressesClient addressesClient = AddressesClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
string address = "";
// Make the request
Operation response = addressesClient.Delete(project, region, address);
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteAsync()
{
// Snippet: DeleteAsync(string, string, string, CallSettings)
// Additional: DeleteAsync(string, string, string, CancellationToken)
// Create client
AddressesClient addressesClient = await AddressesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
string address = "";
// Make the request
Operation response = await addressesClient.DeleteAsync(project, region, address);
// End snippet
}
/// <summary>Snippet for Get</summary>
public void GetRequestObject()
{
// Snippet: Get(GetAddressRequest, CallSettings)
// Create client
AddressesClient addressesClient = AddressesClient.Create();
// Initialize request argument(s)
GetAddressRequest request = new GetAddressRequest
{
Region = "",
Project = "",
Address = "",
};
// Make the request
Address response = addressesClient.Get(request);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetRequestObjectAsync()
{
// Snippet: GetAsync(GetAddressRequest, CallSettings)
// Additional: GetAsync(GetAddressRequest, CancellationToken)
// Create client
AddressesClient addressesClient = await AddressesClient.CreateAsync();
// Initialize request argument(s)
GetAddressRequest request = new GetAddressRequest
{
Region = "",
Project = "",
Address = "",
};
// Make the request
Address response = await addressesClient.GetAsync(request);
// End snippet
}
/// <summary>Snippet for Get</summary>
public void Get()
{
// Snippet: Get(string, string, string, CallSettings)
// Create client
AddressesClient addressesClient = AddressesClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
string address = "";
// Make the request
Address response = addressesClient.Get(project, region, address);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetAsync()
{
// Snippet: GetAsync(string, string, string, CallSettings)
// Additional: GetAsync(string, string, string, CancellationToken)
// Create client
AddressesClient addressesClient = await AddressesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
string address = "";
// Make the request
Address response = await addressesClient.GetAsync(project, region, address);
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void InsertRequestObject()
{
// Snippet: Insert(InsertAddressRequest, CallSettings)
// Create client
AddressesClient addressesClient = AddressesClient.Create();
// Initialize request argument(s)
InsertAddressRequest request = new InsertAddressRequest
{
RequestId = "",
Region = "",
Project = "",
AddressResource = new Address(),
};
// Make the request
Operation response = addressesClient.Insert(request);
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertRequestObjectAsync()
{
// Snippet: InsertAsync(InsertAddressRequest, CallSettings)
// Additional: InsertAsync(InsertAddressRequest, CancellationToken)
// Create client
AddressesClient addressesClient = await AddressesClient.CreateAsync();
// Initialize request argument(s)
InsertAddressRequest request = new InsertAddressRequest
{
RequestId = "",
Region = "",
Project = "",
AddressResource = new Address(),
};
// Make the request
Operation response = await addressesClient.InsertAsync(request);
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void Insert()
{
// Snippet: Insert(string, string, Address, CallSettings)
// Create client
AddressesClient addressesClient = AddressesClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
Address addressResource = new Address();
// Make the request
Operation response = addressesClient.Insert(project, region, addressResource);
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertAsync()
{
// Snippet: InsertAsync(string, string, Address, CallSettings)
// Additional: InsertAsync(string, string, Address, CancellationToken)
// Create client
AddressesClient addressesClient = await AddressesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
Address addressResource = new Address();
// Make the request
Operation response = await addressesClient.InsertAsync(project, region, addressResource);
// End snippet
}
/// <summary>Snippet for List</summary>
public void ListRequestObject()
{
// Snippet: List(ListAddressesRequest, CallSettings)
// Create client
AddressesClient addressesClient = AddressesClient.Create();
// Initialize request argument(s)
ListAddressesRequest request = new ListAddressesRequest
{
Region = "",
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<AddressList, Address> response = addressesClient.List(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Address item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (AddressList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Address item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Address> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Address item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListRequestObjectAsync()
{
// Snippet: ListAsync(ListAddressesRequest, CallSettings)
// Create client
AddressesClient addressesClient = await AddressesClient.CreateAsync();
// Initialize request argument(s)
ListAddressesRequest request = new ListAddressesRequest
{
Region = "",
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<AddressList, Address> response = addressesClient.ListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Address item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((AddressList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Address item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Address> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Address item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for List</summary>
public void List()
{
// Snippet: List(string, string, string, int?, CallSettings)
// Create client
AddressesClient addressesClient = AddressesClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
// Make the request
PagedEnumerable<AddressList, Address> response = addressesClient.List(project, region);
// Iterate over all response items, lazily performing RPCs as required
foreach (Address item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (AddressList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Address item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Address> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Address item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListAsync()
{
// Snippet: ListAsync(string, string, string, int?, CallSettings)
// Create client
AddressesClient addressesClient = await AddressesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
// Make the request
PagedAsyncEnumerable<AddressList, Address> response = addressesClient.ListAsync(project, region);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Address item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((AddressList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Address item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Address> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Address item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
}
}
| 42.137161 | 155 | 0.565216 | [
"Apache-2.0"
] | Mattlk13/google-cloud-dotnet | apis/Google.Cloud.Compute.V1/Google.Cloud.Compute.V1.Snippets/AddressesClientSnippets.g.cs | 26,420 | C# |
#region Licence
/* The MIT License (MIT)
Copyright © 2015 Ian Cooper <[email protected]>
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 Paramore.Brighter.Eventsourcing.Handlers;
namespace Paramore.Brighter.Eventsourcing.Attributes
{
/// <summary>
/// Class UseCommandSourcingAttribute.
/// We use this attribute to indicate that we want to use Event Sourcing, where the application state is the system of record
/// but we want to store the commands that led to the current application state, so that we can rebuild application state
/// or recreate commands
/// See <a href="http://martinfowler.com/eaaDev/EventSourcing.html">Martin Fowler Event Sourcing</a> for more on this approach.
/// </summary>
public class UseCommandSourcingAttribute : RequestHandlerAttribute
{
public string ContextKey { get; }
public bool OnceOnly { get; }
public OnceOnlyAction OnceOnlyAction { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="RequestHandlerAttribute"/> class.
/// </summary>
/// <param name="step">The step.</param>
/// <param name="contextKey">An identifier for the context in which the command has been processed (for example, the name of the handler)</param>
/// <param name="onceOnly">Should we prevent duplicate messages i.e. seen already</param>
/// <param name="timing">The timing.</param>
/// <param name="onceOnlyAction">Action to take if prevent duplicate messages, and we receive a duplicate message</param>
public UseCommandSourcingAttribute(int step, string contextKey = null, bool onceOnly=false, HandlerTiming timing = HandlerTiming.Before, OnceOnlyAction onceOnlyAction = OnceOnlyAction.Throw)
: base(step, timing)
{
ContextKey = contextKey;
OnceOnly = onceOnly;
OnceOnlyAction = onceOnlyAction;
}
/// <summary>
/// Initializes a new instance of the <see cref="RequestHandlerAttribute"/> class.
/// </summary>
/// <param name="step">The step.</param>
/// <param name="contextKey">An identifier for the context in which the command has been processed (for example, the type of the handler)</param>
/// <param name="onceOnly">Should we prevent duplicate messages i.e. seen already</param>
/// <param name="timing">The timing.</param>
/// <param name="onceOnlyAction">Action to take if prevent duplicate messages, and we receive a duplicate message</param>
public UseCommandSourcingAttribute(int step, Type contextKey, bool onceOnly = false, HandlerTiming timing = HandlerTiming.Before, OnceOnlyAction onceOnlyAction = OnceOnlyAction.Throw)
: this(step, contextKey.FullName, onceOnly, timing, onceOnlyAction)
{
}
public override object[] InitializerParams()
{
return new object[] {OnceOnly, ContextKey, OnceOnlyAction};
}
/// <summary>
/// Gets the type of the handler.
/// </summary>
/// <returns>Type.</returns>
public override Type GetHandlerType()
{
return typeof (CommandSourcingHandler<>);
}
}
}
| 48.613636 | 199 | 0.696587 | [
"MIT"
] | DejanMilicic/Brighter | src/Paramore.Brighter/Eventsourcing/Attributes/UseCommandSourcingAttribute.cs | 4,289 | C# |
/*
* Prime Developer Trial
*
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: v1
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = FactSet.SDK.WatchlistAPIforDigitalPortals.Client.OpenAPIDateConverter;
namespace FactSet.SDK.WatchlistAPIforDigitalPortals.Model
{
/// <summary>
/// InlineObject2
/// </summary>
[DataContract(Name = "inline_object_2")]
public partial class InlineObject2 : IEquatable<InlineObject2>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="InlineObject2" /> class.
/// </summary>
/// <param name="data">data.</param>
/// <param name="meta">meta.</param>
public InlineObject2(WatchlistModifyData data = default(WatchlistModifyData), WatchlistCreateMeta meta = default(WatchlistCreateMeta))
{
this.Data = data;
this.Meta = meta;
}
/// <summary>
/// Gets or Sets Data
/// </summary>
[DataMember(Name = "data", EmitDefaultValue = false)]
public WatchlistModifyData Data { get; set; }
/// <summary>
/// Gets or Sets Meta
/// </summary>
[DataMember(Name = "meta", EmitDefaultValue = false)]
public WatchlistCreateMeta Meta { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("class InlineObject2 {\n");
sb.Append(" Data: ").Append(Data).Append("\n");
sb.Append(" Meta: ").Append(Meta).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as InlineObject2);
}
/// <summary>
/// Returns true if InlineObject2 instances are equal
/// </summary>
/// <param name="input">Instance of InlineObject2 to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(InlineObject2 input)
{
if (input == null)
{
return false;
}
return
(
this.Data == input.Data ||
(this.Data != null &&
this.Data.Equals(input.Data))
) &&
(
this.Meta == input.Meta ||
(this.Meta != null &&
this.Meta.Equals(input.Meta))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Data != null)
{
hashCode = (hashCode * 59) + this.Data.GetHashCode();
}
if (this.Meta != null)
{
hashCode = (hashCode * 59) + this.Meta.GetHashCode();
}
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 32.591837 | 142 | 0.557504 | [
"Apache-2.0"
] | factset/enterprise-sdk | code/dotnet/WatchlistAPIforDigitalPortals/v2/src/FactSet.SDK.WatchlistAPIforDigitalPortals/Model/InlineObject2.cs | 4,791 | 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("Beerino.Infra.Data")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Beerino.Infra.Data")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("986a98e5-e84d-4d34-9aa6-9989f86f2f23")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.081081 | 84 | 0.7445 | [
"MIT"
] | marcoskoch/Beerino | Beerino.Infra.Data/Properties/AssemblyInfo.cs | 1,412 | C# |
using UnityEngine;
using System.Collections;
using Fluent;
using System;
namespace Fluent
{
public class IfNode : SequentialNode
{
Func<bool> test;
public IfNode(GameObject gameObject, Func<bool> test, FluentNode node)
: base(gameObject, node)
{
this.test = test;
}
public override void Execute()
{
if (!test())
{
Done();
return;
}
base.Execute();
}
public override void BeforeExecute()
{
}
public override string StringInEditor()
{
return "If";
}
}
public partial class FluentScript : MonoBehaviour
{
public FluentNode If(Func<bool> test, FluentNode node)
{
return new IfNode(gameObject, test, node);
}
}
}
| 19.042553 | 78 | 0.503911 | [
"MIT"
] | Mahmood34/Withering | Withering/Assets/3rdParty/FluentDialogue/Nodes/IfNode.cs | 895 | C# |
using System.Collections.Generic;
using System.Linq;
namespace Game.IteratorPattern
{
class HashIterator<T> : Agregator<T> where T : class {
private Dictionary<int, T> hashMap;
private int index;
public HashIterator() {
hashMap = new Dictionary<int, T>();
}
public override IIteratable<T> CreateIterator() {
return this;
}
public override T First() {
index = 0;
return hashMap[hashMap.Keys.ToArray()[0]];
}
public override void Add(T t) {
index = 0;
hashMap.Add(t.GetHashCode(), t);
}
public override bool HasNext() {
return index < hashMap.Keys.Count;
}
public override T Next() {
return hashMap[hashMap.Keys.ToArray()[index++]];
}
public override void Remove(T t) {
hashMap.Remove(t.GetHashCode());
}
public override Agregator<T> FromList(List<T> list) {
hashMap = new Dictionary<int, T>();
foreach (var item in list) {
Add(item);
}
return this;
}
public override List<T> ToList() {
return hashMap.Values.ToList();
}
}
}
| 23.907407 | 61 | 0.515879 | [
"MIT"
] | fr0stylo/DesginPatterns2018 | Game/Game/IteratorPattern/HashIterator.cs | 1,293 | C# |
using System;
using Chakad.Bootstraper;
using Chakad.MessageHandler.EventSubscribers;
using Chakad.Messages.Command;
using Chakad.Messages.Events;
using Chakad.Pipeline;
using Chakad.Pipeline.Core;
using Chakad.Pipeline.Core.Exceptions;
namespace Chakad.Console
{
class Program
{
private static ICommandPipeline Pipeline => ChakadServiceBus.Pipeline;
static void Main()
{
System.Console.Title = "Chakad ChakadMessage Bus Simulations";
System.Console.ForegroundColor = ConsoleColor.Red;
System.Console.WriteLine("Starting .....");
System.Console.ForegroundColor = ConsoleColor.White;
ChakadBootstraper.Run();
System.Console.ForegroundColor = ConsoleColor.Magenta;
System.Console.WriteLine("Send Activity Command ");
try
{
Pipeline.StartProcess(new StartActivityCommand1());
}
catch (ChakadPipelineNotFoundHandler exHandler)
{
System.Console.WriteLine(exHandler);
}
var res = Pipeline.StartProcess(new StartActivityCommand
{
Message = "",
Id = Guid.NewGuid()
},new TimeSpan(0,0,0,1));
if (res.Exception != null)
{
System.Console.ForegroundColor = ConsoleColor.Red;
System.Console.WriteLine("ChakadPipelineTimeoutException");
System.Console.WriteLine(res.Exception);
System.Console.ForegroundColor = ConsoleColor.Magenta;
}
res = Pipeline.StartProcess(new StartActivityCommand
{
Message = "",
Id = Guid.NewGuid()
});
PrintBreakeLine(2);
System.Console.ForegroundColor = ConsoleColor.Blue;
//System.Console.WriteLine("Raise MyDomainevent. It should be received By subscribers in unorder manner");
//var res1 = Pipeline.Publish(new MyDomainEvent
//{
// FirstName = "Mahyar",
// LastName = "Mehrnoosh"
//});
//PrintBreakeLine(2);
//System.Console.ForegroundColor = ConsoleColor.DarkGreen;
//System.Console.WriteLine("Try to set order MyDomainEvent's Subscribers");
//ChakadBootstraper.ReorderEvents();
//ChakadServiceBus.Pipeline.Publish(new MyDomainEvent
//{
// FirstName = "Mahyar",
// LastName = "Mehrnoosh"
//});
//PrintBreakeLine(2);
//System.Console.ForegroundColor = ConsoleColor.DarkYellow;
//System.Console.WriteLine("Try to unsubscribe MyDomainEventHandler 0");
//new MyEventSubscriber().DivorceFrom(typeof(MyDomainEvent));
//ChakadServiceBus.Pipeline.Publish(new MyDomainEvent
//{
// FirstName = "Mahyar",
// LastName = "Mehrnoosh"
//});
System.Console.ReadKey();
}
private static void PrintBreakeLine(int count)
{
for (int i = 0; i < count; i++)
{
System.Console.WriteLine();
}
}
}
}
| 32.038462 | 118 | 0.555822 | [
"Apache-2.0"
] | masoud-bahrami/Chakad.Pipeline4Monolith | Samples/Console/Console/Program.cs | 3,334 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace General.Entities
{
public class MyDropBox
{
public int Id { get; set; }
public string DropItemName { get; set; }
public string Date { get; set; }
public string IpAdress { get; set; }
public string DropItemFile { get; set; }
public string DataLimits { get; set; }
public string ActiveStatus { get; set; }
public int CreateUserCartId { get; set; }
public CreateUserCart CreateUserCart { get; set; }
}
public class MyTask
{
public int Id { get; set; }
public string Task { get; set; }
public string Color { get; set; }
public string Date { get; set; }
public string Status { get; set; }
public string ActiveStatus { get; set; }
public int CreateUserCartId { get; set; }
public CreateUserCart CreateUserCart { get; set; }
}
public class MyComment
{
public int Id { get; set; }
public string Name { get; set; }
public string Comments { get; set; }
public string BackLink { get; set; }
public string Img { get; set; }
public string Star { get; set; }
public string Date { get; set; }
public string Status { get; set; }
public string ActiveStatus { get; set; }
public int CreateUserCartId { get; set; }
public CreateUserCart CreateUserCart { get; set; }
}
public class UserNotification
{
public int Id { get; set; }
public string Color { get; set; }
public string Date { get; set; }
public string Subject { get; set; }
public string Descriptions { get; set; }
public string Status { get; set; }
public string ActiveStatus { get; set; }
public int CreateUserCartId { get; set; }
public CreateUserCart CreateUserCart { get; set; }
}
public class UserAdresList
{
public int Id { get; set; }
public string AdresTuru { get; set; }
public string Phone { get; set; }
public string Adres { get; set; }
public string Email { get; set; }
public string Ulke { get; set; }
public string Sehir { get; set; }
public string Semt { get; set; }
public string Mahalle { get; set; }
public string PostaKodu { get; set; }
public string AcikAdres { get; set; }
public string ActiveStatus { get; set; }
public int CreateUserCartId { get; set; }
public CreateUserCart CreateUserCart { get; set; }
}
public class UserContent
{
public int Id { get; set; }
public string Date { get; set; }
public string Content1 { get; set; }
public string Content2 { get; set; }
public string Content3 { get; set; }
public string Content4 { get; set; }
public string Content5 { get; set; }
public string Content6 { get; set; }
public string Content7 { get; set; }
public string Content8 { get; set; }
public string Content9 { get; set; }
public string Content10 { get; set; }
public int CreateUserCartId { get; set; }
public CreateUserCart CreateUserCart { get; set; }
}
public class UserRegisterFile
{
public int Id { get; set; }
public string Date { get; set; }
public string File1 { get; set; }
public string File2 { get; set; }
public string File3 { get; set; }
public string File4 { get; set; }
public string File5 { get; set; }
public int CreateUserCartId { get; set; }
public CreateUserCart CreateUserCart { get; set; }
}
}
| 30.943089 | 58 | 0.582764 | [
"MIT"
] | batuhan-yilmaz/TODO-project-asp.netcore-webapp | General.Entities/UserFunctions/UserFunctions.cs | 3,808 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/shellapi.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.Windows.UnitTests;
/// <summary>Provides validation of the <see cref="OPEN_PRINTER_PROPS_INFO64W" /> struct.</summary>
public static unsafe partial class OPEN_PRINTER_PROPS_INFO64WTests
{
/// <summary>Validates that the <see cref="OPEN_PRINTER_PROPS_INFO64W" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<OPEN_PRINTER_PROPS_INFO64W>(), Is.EqualTo(sizeof(OPEN_PRINTER_PROPS_INFO64W)));
}
/// <summary>Validates that the <see cref="OPEN_PRINTER_PROPS_INFO64W" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(OPEN_PRINTER_PROPS_INFO64W).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="OPEN_PRINTER_PROPS_INFO64W" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(OPEN_PRINTER_PROPS_INFO64W), Is.EqualTo(32));
}
else
{
Assert.That(sizeof(OPEN_PRINTER_PROPS_INFO64W), Is.EqualTo(20));
}
}
}
| 36.860465 | 145 | 0.708517 | [
"MIT"
] | reflectronic/terrafx.interop.windows | tests/Interop/Windows/Windows/um/shellapi/OPEN_PRINTER_PROPS_INFO64WTests.Manual.cs | 1,587 | C# |
using PipServices3.Components.Build;
using PipServices3.Commons.Refer;
namespace PipServices3.Components.Count
{
/// <summary>
/// Creates ICounters components by their descriptors.
/// </summary>
/// See <a href="https://rawgit.com/pip-services3-dotnet/pip-services3-components-dotnet/master/doc/api/class_pip_services_1_1_components_1_1_build_1_1_factory.html">Factory</a>,
/// <see cref="NullCounters"/>, <see cref="LogCounters"/>, <see cref="CompositeCounters"/>
public class DefaultCountersFactory : Factory
{
public static readonly Descriptor Descriptor = new Descriptor("pip-services3", "factory", "counters", "default", "1.0");
public static readonly Descriptor NullCountersDescriptor = new Descriptor("pip-services3", "counters", "null", "*", "1.0");
public static readonly Descriptor NullCountersDescriptor2 = new Descriptor("pip-services3-commons", "counters", "null", "*", "1.0");
public static readonly Descriptor LogCountersDescriptor = new Descriptor("pip-services3", "counters", "log", "*", "1.0");
public static readonly Descriptor LogCountersDescriptor2 = new Descriptor("pip-services3-commons", "counters", "log", "*", "1.0");
public static readonly Descriptor CompositeCountersDescriptor = new Descriptor("pip-services3", "counters", "composite", "*", "1.0");
public static readonly Descriptor CompositeCountersDescriptor2 = new Descriptor("pip-services3-commons", "counters", "composite", "*", "1.0");
/// <summary>
/// Create a new instance of the factory.
/// </summary>
public DefaultCountersFactory()
{
RegisterAsType(NullCountersDescriptor, typeof(NullCounters));
RegisterAsType(NullCountersDescriptor2, typeof(NullCounters));
RegisterAsType(LogCountersDescriptor, typeof(LogCounters));
RegisterAsType(LogCountersDescriptor2, typeof(LogCounters));
RegisterAsType(CompositeCountersDescriptor, typeof(CompositeCounters));
RegisterAsType(CompositeCountersDescriptor2, typeof(CompositeCounters));
}
}
}
| 60.971429 | 183 | 0.699625 | [
"MIT"
] | ajoycekyrio/pip-services3-components-dotnet | src/Count/DefaultCountersFactory.cs | 2,136 | C# |
#if ! (UNITY_DASHBOARD_WIDGET || UNITY_WEBPLAYER || UNITY_WII || UNITY_WIIU || UNITY_NACL || UNITY_FLASH || UNITY_BLACKBERRY) // Disable under unsupported platforms.
//////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014 Audiokinetic Inc. / All Rights Reserved
//
//////////////////////////////////////////////////////////////////////
public class AkTriggerMouseExit : AkTriggerBase
{
private void OnMouseExit()
{
if (triggerDelegate != null)
triggerDelegate(null);
}
}
#endif // #if ! (UNITY_DASHBOARD_WIDGET || UNITY_WEBPLAYER || UNITY_WII || UNITY_WIIU || UNITY_NACL || UNITY_FLASH || UNITY_BLACKBERRY) // Disable under unsupported platforms. | 41.882353 | 175 | 0.574438 | [
"Apache-2.0"
] | Bellseboss-Studio/ProyectoPrincipal_JuegoDePeleas | Assets/Wwise/Deployment/Components/AkTriggerMouseExit.cs | 712 | C# |
using System;
namespace CommonDeliveryFramework
{
/// <summary>
/// Notifies that a security exception has been captured and a application safe message has been added to this exception.
/// </summary>
public class SecurityException : ManagedException
{
/// <summary>
/// Creates an instance of <see cref="SecurityException"/> and returns the default exception message.
/// </summary>
public SecurityException() : base(StandardExceptionMessages.SecurityException)
{
//Intentionally blank
}
/// <summary>
/// Creates an instance of <see cref="SecurityException"/> that returns the default exception message and an imbedded exception.
/// </summary>
/// <param name="internalException">Existing exception to be added to this exception.</param>
public SecurityException(Exception internalException) : base(StandardExceptionMessages.SecurityException, internalException)
{
//Intentionally blank
}
/// <summary>
/// Creates an instance of <see cref="SecurityException"/> exception class.
/// </summary>
/// <param name="message">Message to be returned as part of the exception.</param>
public SecurityException(string message) : base(message)
{
//Intentionally blank
}
/// <summary>
/// Creates an instance of <see cref="SecurityException"/> exception class.
/// </summary>
/// <param name="message">Message to be returned as part of the exception.</param>
/// <param name="internalException">Existing exception to be added to this exception.</param>
public SecurityException(string message, Exception internalException) : base(message, internalException)
{
//Intentionally blank
}
}
}
| 40.021277 | 136 | 0.640085 | [
"MIT"
] | CodeFactoryLLC/CommonDeliveryFramework | CDF-Solution/CommonDeliveryFramework/SecurityException.cs | 1,883 | C# |
namespace HiWorld.Web.ViewModels.Home
{
using System;
using System.Collections.Generic;
using System.Text;
public class ProfileFollowingViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsProfile { get; set; }
public string ImagePath { get; set; }
}
}
| 19.333333 | 45 | 0.617816 | [
"MIT"
] | IvanMakaveev/HiWorld | HiWorld/Web/HiWorld.Web.ViewModels/Home/ProfileFollowingViewModel.cs | 350 | C# |
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NBitcoin;
using Stratis.Bitcoin.Base;
using Stratis.Bitcoin.Builder;
using Stratis.Bitcoin.Builder.Feature;
using Stratis.Bitcoin.Configuration.Logging;
using Stratis.Bitcoin.Connection;
using Stratis.Bitcoin.Consensus;
using Stratis.Bitcoin.Features.BlockStore.Controllers;
using Stratis.Bitcoin.Features.BlockStore.Pruning;
using Stratis.Bitcoin.Interfaces;
using Stratis.Bitcoin.P2P.Protocol.Payloads;
using Stratis.Bitcoin.Utilities;
[assembly: InternalsVisibleTo("Stratis.Bitcoin.Features.BlockStore.Tests")]
namespace Stratis.Bitcoin.Features.BlockStore
{
public class BlockStoreFeature : FullNodeFeature
{
private readonly Network network;
private readonly ConcurrentChain chain;
private readonly Signals.Signals signals;
private readonly BlockStoreSignaled blockStoreSignaled;
private readonly IConnectionManager connectionManager;
private readonly StoreSettings storeSettings;
private readonly IChainState chainState;
/// <summary>Instance logger.</summary>
private readonly ILogger logger;
/// <summary>Factory for creating loggers.</summary>
private readonly ILoggerFactory loggerFactory;
private readonly IBlockStoreQueue blockStoreQueue;
private readonly IConsensusManager consensusManager;
private readonly ICheckpoints checkpoints;
private readonly IPrunedBlockRepository prunedBlockRepository;
public BlockStoreFeature(
Network network,
ConcurrentChain chain,
IConnectionManager connectionManager,
Signals.Signals signals,
BlockStoreSignaled blockStoreSignaled,
ILoggerFactory loggerFactory,
StoreSettings storeSettings,
IChainState chainState,
IBlockStoreQueue blockStoreQueue,
INodeStats nodeStats,
IConsensusManager consensusManager,
ICheckpoints checkpoints,
IPrunedBlockRepository prunedBlockRepository)
{
this.network = network;
this.chain = chain;
this.blockStoreQueue = blockStoreQueue;
this.signals = signals;
this.blockStoreSignaled = blockStoreSignaled;
this.connectionManager = connectionManager;
this.logger = loggerFactory.CreateLogger(this.GetType().FullName);
this.loggerFactory = loggerFactory;
this.storeSettings = storeSettings;
this.chainState = chainState;
this.consensusManager = consensusManager;
this.checkpoints = checkpoints;
this.prunedBlockRepository = prunedBlockRepository;
nodeStats.RegisterStats(this.AddInlineStats, StatsType.Inline, 900);
}
private void AddInlineStats(StringBuilder log)
{
ChainedHeader highestBlock = this.chainState.BlockStoreTip;
if (highestBlock != null)
{
var builder = new StringBuilder();
builder.Append("BlockStore.Height: ".PadRight(LoggingConfiguration.ColumnLength + 1) + highestBlock.Height.ToString().PadRight(8));
builder.Append(" BlockStore.Hash: ".PadRight(LoggingConfiguration.ColumnLength - 1) + highestBlock.HashBlock);
log.AppendLine(builder.ToString());
}
}
public override async Task InitializeAsync()
{
this.prunedBlockRepository.InitializeAsync().GetAwaiter().GetResult();
if (!this.storeSettings.PruningEnabled && this.prunedBlockRepository.PrunedTip != null)
throw new BlockStoreException("The node cannot start as it has been previously pruned, please clear the data folders and resync.");
if (this.storeSettings.PruningEnabled)
{
if (this.storeSettings.AmountOfBlocksToKeep < this.network.Consensus.MaxReorgLength)
throw new BlockStoreException($"The amount of blocks to prune [{this.storeSettings.AmountOfBlocksToKeep}] (blocks to keep) cannot be less than the node's max reorg length of {this.network.Consensus.MaxReorgLength}.");
this.logger.LogInformation("Pruning BlockStore...");
await this.prunedBlockRepository.PruneAndCompactDatabase(this.chainState.BlockStoreTip, this.network, true);
}
// Use ProvenHeadersBlockStoreBehavior for PoS Networks
if (this.network.Consensus.IsProofOfStake)
{
this.connectionManager.Parameters.TemplateBehaviors.Add(new ProvenHeadersBlockStoreBehavior(this.network, this.chain, this.chainState, this.loggerFactory, this.consensusManager, this.checkpoints, this.blockStoreQueue));
}
else
{
this.connectionManager.Parameters.TemplateBehaviors.Add(new BlockStoreBehavior(this.chain, this.chainState, this.loggerFactory, this.consensusManager, this.blockStoreQueue));
}
// Signal to peers that this node can serve blocks.
// TODO: Add NetworkLimited which is what BTC uses for pruned nodes.
this.connectionManager.Parameters.Services = (this.storeSettings.PruningEnabled ? NetworkPeerServices.Nothing : NetworkPeerServices.Network);
// Temporary measure to support asking witness data on BTC.
// At some point NetworkPeerServices will move to the Network class,
// Then this values should be taken from there.
if (!this.network.Consensus.IsProofOfStake)
this.connectionManager.Parameters.Services |= NetworkPeerServices.NODE_WITNESS;
this.signals.SubscribeForBlocksConnected(this.blockStoreSignaled);
return;
}
/// <inheritdoc />
public override void Dispose()
{
if (this.storeSettings.PruningEnabled)
{
this.logger.LogInformation("Pruning BlockStore...");
this.prunedBlockRepository.PruneAndCompactDatabase(this.chainState.BlockStoreTip, this.network, false);
}
this.logger.LogInformation("Stopping BlockStore.");
this.blockStoreSignaled.Dispose();
}
}
/// <summary>
/// A class providing extension methods for <see cref="IFullNodeBuilder"/>.
/// </summary>
public static class FullNodeBuilderBlockStoreExtension
{
public static IFullNodeBuilder UseBlockStore(this IFullNodeBuilder fullNodeBuilder)
{
LoggingConfiguration.RegisterFeatureNamespace<BlockStoreFeature>("db");
fullNodeBuilder.ConfigureFeature(features =>
{
features
.AddFeature<BlockStoreFeature>()
.FeatureServices(services =>
{
services.AddSingleton<IBlockStoreQueue, BlockStoreQueue>().AddSingleton<IBlockStore>(provider => provider.GetService<IBlockStoreQueue>());
services.AddSingleton<IBlockRepository, BlockRepository>();
services.AddSingleton<IPrunedBlockRepository, PrunedBlockRepository>();
if (fullNodeBuilder.Network.Consensus.IsProofOfStake)
services.AddSingleton<BlockStoreSignaled, ProvenHeadersBlockStoreSignaled>();
else
services.AddSingleton<BlockStoreSignaled>();
services.AddSingleton<StoreSettings>();
services.AddSingleton<BlockStoreController>();
services.AddSingleton<IBlockStoreQueueFlushCondition, BlockStoreQueueFlushCondition>();
});
});
return fullNodeBuilder;
}
}
}
| 42.748663 | 237 | 0.663998 | [
"MIT"
] | monsieurleberre/StratisBitcoinFullNode | src/Stratis.Bitcoin.Features.BlockStore/BlockStoreFeature.cs | 7,996 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using Microsoft.Practices.Composite.Modularity;
using Microsoft.Practices.Unity;
//using Microsoft.Practices.Composite.Regions;
using TwaijaComposite.Modules.ColumnsManager.Viewmodels;
using TwaijaComposite.Modules.ColumnsManager.Column;
using TwaijaComposite.Modules.Common;
using TwaijaComposite.Modules.ColumnsManager.Views;
using TwaijaComposite.Modules.Common.Interfaces;
using TwaijaComposite.Modules.ColumnsManager.Request;
using TwaijaComposite.Modules.Common.Services;
using TwaijaComposite.Modules.Common.Preferencing;
using TwaijaComposite.Modules.ColumnsManager.Converter;
using TwaijaComposite.Modules.ColumnsManager.Column.Factories;
using TwaijaComposite.Modules.Common.DataInterfaces;
using TwaijaComposite.Modules.Common.Commands;
using TwaijaComposite.Modules.ColumnsManager.Commands;
using TwaijaComposite.Modules.ColumnsManager.Notifications;
using TwaijaComposite.Modules.ColumnsManager.Behaviors;
using TwaijaComposite.Modules.Common.Resources;
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Prism.Regions;
namespace TwaijaComposite.Modules.ColumnsManager
{
public class ColumnsManagerModule:IModule
{
#region fields
readonly IUnityContainer m_Container;
readonly IRegionManager m_RegionManager;
#endregion
public ColumnsManagerModule(IUnityContainer container, IRegionManager manager)
{
m_Container = container;
m_RegionManager = manager;
}
public void Initialize()
{
RegisterTypes();
}
private void RegisterTypes()
{
#region Converters
m_Container.RegisterType<IConverter<SingleMessage<TweetViewmodel>, ITweet>, SingleMessageConverter<TweetViewmodel, ITweet>>();
m_Container.RegisterType<IConverter<AggregateMessage<TweetViewmodel>, IList<ITweet>>, AggregateMessageConverter<TweetViewmodel, ITweet>>();
m_Container.RegisterType<IConverter<AggregateMessage<TwitterProfile_SmallViewmodel>, IList<ITwitterProfile_Small>>, AggregateMessageConverter<TwitterProfile_SmallViewmodel, ITwitterProfile_Small>>();
m_Container.RegisterType<IConverter<AggregateMessage<DirectMessageViewmodel>, IList<ITwitterDirectMessage>>, AggregateMessageConverter<DirectMessageViewmodel, ITwitterDirectMessage>>();
m_Container.RegisterType<IConverter<AggregateMessage<TrendsViewmodel>, IList<ITrend>>, AggregateMessageConverter<TrendsViewmodel, ITrend>>();
m_Container.RegisterType<IConverter<SingleMessage<TwitterProfile_LargeViewmodel>, ITwitterProfile_Large>, SingleMessageConverter<TwitterProfile_LargeViewmodel, ITwitterProfile_Large>>();
//m_Container.RegisterType(typeof(IConverter<SingleMessage<TweetViewmodel>, ITweet>), typeof(SingleMessageConverter<TweetViewmodel, ITweet>));
//m_Container.RegisterType(typeof(IConverter<AggregateMessage<TweetViewmodel>, IList<ITweet>>), typeof(AggregateMessageConverter<TweetViewmodel, ITweet>));
//m_Container.RegisterType(typeof(IConverter<AggregateMessage<TwitterProfile_SmallViewmodel>, IList<ITwitterProfile_Small>>), typeof(AggregateMessageConverter<TwitterProfile_SmallViewmodel, ITwitterProfile_Small>));
//m_Container.RegisterType(typeof(IConverter<AggregateMessage<DirectMessageViewmodel>, IList<ITwitterDirectMessage>>),typeof( AggregateMessageConverter<DirectMessageViewmodel, ITwitterDirectMessage>));
//m_Container.RegisterType(typeof(IConverter<AggregateMessage<TrendsViewmodel>, IList<ITrend>>),typeof( AggregateMessageConverter<TrendsViewmodel, ITrend>));
//m_Container.RegisterType(typeof(IConverter<SingleMessage<TwitterProfile_LargeViewmodel>, ITwitterProfile_Large>),typeof( SingleMessageConverter<TwitterProfile_LargeViewmodel, ITwitterProfile_Large>));
#endregion
#region RequestTypes
m_Container.RegisterType<HomeTimelineRequest>();
m_Container.RegisterType<MentionsRequest>();
m_Container.RegisterType<GetFollowersRequest>();
m_Container.RegisterType<DirectMessagesRequest>();
m_Container.RegisterType<GetFriendsRequest>();
m_Container.RegisterType<TrendsRequest>();
m_Container.RegisterType<TwitterProfile_LargeRequest>();
m_Container.RegisterType<ConversationRequest>();
m_Container.RegisterType<TweetSearchRequest>();
m_Container.RegisterType<UserSearchRequest>();
m_Container.RegisterType<FavouritesRequest>();
#endregion
#region ModelFactories
//Register Model Factories.
m_Container.RegisterType<IModelFactory<DirectMessageViewmodel>, DirectMessageViewmodelConverter>(new ContainerControlledLifetimeManager());
m_Container.RegisterType<IModelFactory<TweetViewmodel>, ProfileUserTimelineTweetViewmodelFactory>(ModelFactoryKeys.TweetViewmodelCustomFactoryKey,new ContainerControlledLifetimeManager());
m_Container.RegisterType<IModelFactory<TweetViewmodel>, TweetModelFactoryImp>(new ContainerControlledLifetimeManager());
m_Container.RegisterType<IModelFactory<TwitterProfile_LargeViewmodel>, TwitterProfile_LargeViewmodelFactory>(new ContainerControlledLifetimeManager());
m_Container.RegisterType<IModelFactory<TwitterProfile_SmallViewmodel>, TwitterProfile_SmallViewmodelModelFactory>(new ContainerControlledLifetimeManager());
#endregion
#region PartsFactories
m_Container.RegisterType<IColumnPartsFactory, MentionsFactory>(ColumnTypeKeys.TwitterMentionsKey, new ContainerControlledLifetimeManager());
m_Container.RegisterType<IColumnPartsFactory, DirectMessagesFactory>(ColumnTypeKeys.TwitterDirectMessagesKey, new ContainerControlledLifetimeManager());
m_Container.RegisterType<IColumnPartsFactory, TweetSearchFactory>(ColumnTypeKeys.TwitterTweetSearchKey, new ContainerControlledLifetimeManager());
m_Container.RegisterType<IColumnPartsFactory, UserSearchFactory>(ColumnTypeKeys.TwitterUserSearchKey, new ContainerControlledLifetimeManager());
m_Container.RegisterType<IColumnPartsFactory, ConversationFactory>(ColumnTypeKeys.TwitterConversationKey, new ContainerControlledLifetimeManager());
m_Container.RegisterType<IColumnPartsFactory, FriendsFactory>(ColumnTypeKeys.TwitterFriendsKey, new ContainerControlledLifetimeManager());
m_Container.RegisterType<IColumnPartsFactory, FollowersFactory>(ColumnTypeKeys.TwitterFollowersKey, new ContainerControlledLifetimeManager());
m_Container.RegisterType<IColumnPartsFactory, FavouritesFactory>(ColumnTypeKeys.TwitterFavouritesKey, new ContainerControlledLifetimeManager());
m_Container.RegisterType<IColumnPartsFactory, HomeTimelineFactory>(ColumnTypeKeys.TwitterHometimelineKey, new ContainerControlledLifetimeManager());
m_Container.RegisterType<IColumnPartsFactory, TwitterProfileFactory>(ColumnTypeKeys.TwitterProfileKey, new ContainerControlledLifetimeManager());
m_Container.RegisterType<IColumnPartsFactory, TrendsFactory>(ColumnTypeKeys.TwitterTrendsKey, new ContainerControlledLifetimeManager());
m_Container.RegisterType<IColumnPartsFactory, UserTimelineFactory>(ColumnTypeKeys.TwitterUserTimelineKey, new ContainerControlledLifetimeManager());
#endregion
#region Column Features
m_Container.RegisterType<IColumnSkeletonFactory, ColumnSkeletonFactoryImp>(new ContainerControlledLifetimeManager());
m_Container.RegisterType<IFilter, Filter.FilterImp>();
m_Container.RegisterType<ITimer, ThreadingTimerAdapter>();
//All ColumnPartsFactories should be registered before this Service is registered...
m_Container.RegisterType<IColumnResolutionService, ColumnResolutionServiceImp>(new ContainerControlledLifetimeManager(), new InjectionConstructor(new ResolvedParameter<IDirector>(),new ResolvedParameter<IColumnSkeletonFactory>(), m_Container.ResolveAll<IColumnPartsFactory>(),new ResolvedParameter<Preferences>()));
m_Container.RegisterType<IColumn, ColumnImp>();
m_Container.RegisterType<IColumn, ProfileColumnImp>("ProfileColumn");
m_Container.RegisterType<IColumn, SingleItemColumnImp>("SingleItemColumn");
#endregion
#region Others
m_Container.RegisterType<IController, NotificationsControllerImp>("NotificationsManager",new ContainerControlledLifetimeManager());
m_Container.RegisterType<INotificationViewmodel, NotificationViewmodelImp>(new ContainerControlledLifetimeManager());
m_Container.RegisterType<INotificationsView, NotificationsViewImp>(new ContainerControlledLifetimeManager());
m_Container.RegisterType<IStateBasedNetworkCommandFactory, SimpleStateBasedNetworkCommandFactory>(new ContainerControlledLifetimeManager());
m_Container.RegisterType<INetworkAndMiscCommandsFactory, SimpleNetworkAndMiscCommandFactory>(new ContainerControlledLifetimeManager());
m_Container.RegisterType<INetworkAndMiscCommandsFactory, IconifiedNetworkAndMiscCommandFactory>("IconifiedNetworkCommandFactory", new ContainerControlledLifetimeManager());
m_Container.RegisterType<IRequestState<ITimerBasedRequest>, IdleState>();
m_Container.RegisterType<IRequestState<ILoopRequest>, IdleState>();
m_Container.RegisterType<IDirector, ColumnDirector>(new ContainerControlledLifetimeManager());
m_Container.RegisterType<IToolbarViewmodel, ToolBarViewmodel>(new ContainerControlledLifetimeManager());
m_Container.RegisterType<IColumnsWorkspaceViewmodel, ColumnsWorkspaceViewmodel>(new ContainerControlledLifetimeManager());
m_Container.RegisterType<IController,ColumnsController>("ColumnManager",new ContainerControlledLifetimeManager());
m_Container.RegisterType<ParseTweetBehavior>();
m_Container.RegisterType<IinitializeUserHandler, TwitterUserInitializeHandler>("TwitterUserInitializeHandler",new ContainerControlledLifetimeManager());
m_Container.RegisterType<InitializeUserHandlerRepository>(new ContainerControlledLifetimeManager(),new InjectionConstructor(m_Container.ResolveAll<IinitializeUserHandler>()));
#endregion
#region Views
m_Container.RegisterType<Layout>(new ContainerControlledLifetimeManager());
m_Container.RegisterType<ColumnsWorkspaceView>(new ContainerControlledLifetimeManager());
m_Container.RegisterType<ToolBarView>(new ContainerControlledLifetimeManager());
m_RegionManager.RegisterViewWithRegion(RegionNames.Main_WorkareaSpace, () => m_Container.Resolve<ColumnsWorkspaceView>());
m_RegionManager.RegisterViewWithRegion(RegionNames.ToolBar_WorkareaSpace, () => m_Container.Resolve<ToolBarView>());
m_RegionManager.RegisterViewWithRegion(RegionNames.WorkareaSpace, typeof(Layout));
#endregion
}
}
}
| 75.644295 | 327 | 0.782096 | [
"MIT"
] | chidionuekwusi/Twaija | TwaijaComposite.Modules.ColumnsManager/ColumnsManagerModule.cs | 11,273 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using SeoSchema;
using SeoSchema.Enumerations;
using SuperStructs;
namespace SeoSchema.Entities
{
/// <summary>
/// The act of being defeated in a competitive activity.
/// <see cref="https://schema.org/LoseAction"/>
/// </summary>
public class LoseAction : IEntity
{
/// A sub property of participant. The winner of the action.
public Or<Person>? Winner { get; set; }
/// Indicates the current disposition of the Action.
public Or<ActionStatusType>? ActionStatus { get; set; }
/// The direct performer or driver of the action (animate or inanimate). e.g. John wrote a book.
public Or<Organization, Person>? Agent { get; set; }
/// The endTime of something. For a reserved event or service (e.g. FoodEstablishmentReservation), the time that it is expected to end. For actions that span a period of time, when the action was performed. e.g. John wrote a book from January to December.
///
/// Note that Event uses startDate/endDate instead of startTime/endTime, even when describing dates with times. This situation may be clarified in future revisions.
public Or<DateTime>? EndTime { get; set; }
/// For failed actions, more information on the cause of the failure.
public Or<Thing>? Error { get; set; }
/// The object that helped the agent perform the action. e.g. John wrote a book with a pen.
public Or<Thing>? Instrument { get; set; }
/// The location of for example where the event is happening, an organization is located, or where an action takes place.
public Or<Place, PostalAddress, string>? Location { get; set; }
/// The object upon which the action is carried out, whose state is kept intact or changed. Also known as the semantic roles patient, affected or undergoer (which change their state) or theme (which doesn't). e.g. John read a book.
public Or<Thing>? Object { get; set; }
/// Other co-agents that participated in the action indirectly. e.g. John wrote a book with Steve.
public Or<Organization, Person>? Participant { get; set; }
/// The result produced in the action. e.g. John wrote a book.
public Or<Thing>? Result { get; set; }
/// The startTime of something. For a reserved event or service (e.g. FoodEstablishmentReservation), the time that it is expected to start. For actions that span a period of time, when the action was performed. e.g. John wrote a book from January to December.
///
/// Note that Event uses startDate/endDate instead of startTime/endTime, even when describing dates with times. This situation may be clarified in future revisions.
public Or<DateTime>? StartTime { get; set; }
/// Indicates a target EntryPoint for an Action.
public Or<EntryPoint>? Target { get; set; }
/// An additional type for the item, typically used for adding more specific types from external vocabularies in microdata syntax. This is a relationship between something and a class that the thing is in. In RDFa syntax, it is better to use the native RDFa syntax - the 'typeof' attribute - for multiple types. Schema.org tools may have only weaker understanding of extra types, in particular those defined externally.
public Or<Uri>? AdditionalType { get; set; }
/// An alias for the item.
public Or<string>? AlternateName { get; set; }
/// A description of the item.
public Or<string>? Description { get; set; }
/// A sub property of description. A short description of the item used to disambiguate from other, similar items. Information from other properties (in particular, name) may be necessary for the description to be useful for disambiguation.
public Or<string>? DisambiguatingDescription { get; set; }
/// The identifier property represents any kind of identifier for any kind of Thing, such as ISBNs, GTIN codes, UUIDs etc. Schema.org provides dedicated properties for representing many of these, either as textual strings or as URL (URI) links. See background notes for more details.
public Or<PropertyValue, string, Uri>? Identifier { get; set; }
/// An image of the item. This can be a URL or a fully described ImageObject.
public Or<ImageObject, Uri>? Image { get; set; }
/// Indicates a page (or other CreativeWork) for which this thing is the main entity being described. See background notes for details. Inverse property: mainEntity.
public Or<CreativeWork, Uri>? MainEntityOfPage { get; set; }
/// The name of the item.
public Or<string>? Name { get; set; }
/// Indicates a potential Action, which describes an idealized action in which this thing would play an 'object' role.
public Or<Action>? PotentialAction { get; set; }
/// URL of a reference Web page that unambiguously indicates the item's identity. E.g. the URL of the item's Wikipedia page, Wikidata entry, or official website.
public Or<Uri>? SameAs { get; set; }
/// A CreativeWork or Event about this Thing.. Inverse property: about.
public Or<CreativeWork, Event>? SubjectOf { get; set; }
/// URL of the item.
public Or<Uri>? Url { get; set; }
}
}
| 57.595745 | 427 | 0.686738 | [
"MIT"
] | jefersonsv/SeoSchema | src/SeoSchema/Entities/LoseAction.cs | 5,414 | C# |
using Avalonia.Platform;
namespace Avalonia.Media.TextFormatting
{
/// <summary>
/// A text run that supports drawing content.
/// </summary>
public abstract class DrawableTextRun : TextRun
{
/// <summary>
/// Gets the bounds.
/// </summary>
public abstract Rect Bounds { get; }
/// <summary>
/// Draws the <see cref="DrawableTextRun"/> at the given origin.
/// </summary>
/// <param name="drawingContext">The drawing context.</param>
/// <param name="origin">The origin.</param>
public abstract void Draw(IDrawingContextImpl drawingContext, Point origin);
}
}
| 29.043478 | 84 | 0.598802 | [
"MIT"
] | Artentus/Avalonia | src/Avalonia.Visuals/Media/TextFormatting/DrawableTextRun.cs | 670 | C# |
using BS_Utils.Utilities;
using System.Reflection;
using UnityEngine;
using UnityEngine.XR;
namespace BeatSaberMultiplayerLite
{
public class OnlineVRController : VRController
{
public OnlinePlayerController owner;
Vector3 targetPos;
Quaternion targetRot;
VRPlatformHelper _platformHelper;
VRControllerTransformOffset _transformOffset;
public OnlineVRController()
{
VRController original = GetComponent<VRController>();
foreach (FieldInfo info in original.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic))
{
info.SetValue(this, info.GetValue(original));
}
_platformHelper = original.GetPrivateField<VRPlatformHelper>("_vrPlatformHelper");
_transformOffset = original.GetPrivateField<VRControllerTransformOffset>("_transformOffset");
Destroy(original);
}
public new void Update()
{
if (Client.Instance == null || !Client.Instance.connected)
{
DefaultUpdate();
}
else
{
if (owner != null && owner.playerInfo != null)
{
targetPos = (node == XRNode.LeftHand ? owner.playerInfo.updateInfo.leftHandPos : owner.playerInfo.updateInfo.rightHandPos);
targetRot = (node == XRNode.LeftHand ? owner.playerInfo.updateInfo.leftHandRot : owner.playerInfo.updateInfo.rightHandRot);
transform.position = targetPos + owner.avatarOffset;
transform.rotation = targetRot;
}
else
{
if(Time.frameCount % 90 == 0)
{
Plugin.log.Warn(owner == null ? "Controller owner is null!" : "Controller owner's player info is null!");
}
}
}
}
private void DefaultUpdate()
{
transform.localPosition = InputTracking.GetLocalPosition(node);
transform.localRotation = InputTracking.GetLocalRotation(node);
if(_transformOffset != null)
_platformHelper.AdjustPlatformSpecificControllerTransform(node, transform, _transformOffset.positionOffset, _transformOffset.rotationOffset);
else
_platformHelper.AdjustPlatformSpecificControllerTransform(node, transform, Vector3.zero, Vector3.zero);
}
}
}
| 36.485714 | 157 | 0.597494 | [
"MIT"
] | Nyrotek1/BeatSaberMultiplayer | BeatSaberMultiplayer/OverriddenClasses/OnlineVRController.cs | 2,556 | C# |
using System.Collections.Generic;
public class SoldiersList : List<Soldier>
{
public void OnSoldierKilled(object sender, KillEventArgs args)
{
args.Soldier.SoldierKilled -= this.OnSoldierKilled;
args.KingDefended.BeingAttacked -= args.Soldier.OnKingBeingAttacked;
this.Remove(args.Soldier);
}
} | 30.181818 | 76 | 0.722892 | [
"MIT"
] | TihomirIvanovIvanov/SoftUni | C#Fundamentals/C#OOP-Advanced/06CommunicationAndEvents/CommunicationAndEventsExer/KingsGambitExtended/Models/SoldiersList.cs | 334 | C# |
// Copyright (c) 2018-2020 Alexander Bogarsukov.
// Licensed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
using UnityEngine;
namespace UnityFx.Mvc
{
/// <summary>
/// A generic view.
/// </summary>
/// <remarks>
/// In the Model-View-Controller (MVC) pattern, the view handles the app's data presentation and user interaction.
/// Views are created via <see cref="IViewFactory"/> instance.
/// </remarks>
/// <seealso cref="IViewController"/>
/// <seealso cref="IViewFactory"/>
/// <seealso href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller"/>
public interface IView : IDisposable
{
/// <summary>
/// Raised when the view is disposed.
/// </summary>
event EventHandler Disposed;
/// <summary>
/// Gets the <see cref="Transform"/> this view is attached to.
/// </summary>
Transform Transform { get; }
/// <summary>
/// Gets or sets a value indicating whether the view is enabled.
/// </summary>
bool Enabled { get; set; }
}
}
| 28.351351 | 115 | 0.672069 | [
"MIT"
] | Arvtesh/UnityFx.AppStates | Assets/Plugins/UnityFx.Mvc/Runtime/Abstractions/Mvc/IView.cs | 1,051 | C# |
//
// AddinUrlAttribute.cs
//
// Author:
// Lluis Sanchez <[email protected]>
//
// Copyright (c) 2013 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace Hyena.Addins
{
/// <summary>
/// Addin URL attribute.
/// </summary>
[AttributeUsage (AttributeTargets.Assembly, AllowMultiple=false)]
public class AddinUrlAttribute: Attribute
{
/// <summary>
/// Initializes the attribute
/// </summary>
/// <param name="url">
/// Url of the add-in
/// </param>
public AddinUrlAttribute (string url)
{
this.Url = url;
}
/// <summary>
/// Url of the add-in
/// </summary>
public string Url { get; set; }
}
}
| 31.5 | 80 | 0.713698 | [
"MIT"
] | firox263/Hyena.Addins | Hyena.Addins/Hyena.Addins/AddinUrlAttribute.cs | 1,701 | C# |
#nullable enable
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using NetworkPrimitives.Ipv4;
namespace NetworkPrimitives.JsonConverters.Ipv4
{
public class Ipv4AddressRangeJsonConverter : JsonConverter<Ipv4AddressRange>
{
private Ipv4AddressRangeJsonConverter() { }
public static readonly Ipv4AddressRangeJsonConverter Instance = new ();
public override Ipv4AddressRange Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options
) => Ipv4AddressRange.Parse(reader.GetString());
public override void Write(
Utf8JsonWriter writer,
Ipv4AddressRange value,
JsonSerializerOptions options
) => writer.WriteStringValue(value.ToString());
}
} | 31.730769 | 80 | 0.698182 | [
"MIT"
] | binarycow/NetworkPrimitives | src/NetworkPrimitives.JsonConverters/Ipv4/Ipv4AddressRangeJsonConverter.cs | 827 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;
using QuestomAssets.AssetsChanger;
using QuestomAssets;
using QuestomAssets.Utils;
namespace Assplorer
{
public partial class ExploreTree : UserControl
{
public ExploreTree()
{
InitializeComponent();
}
public event EventHandler<TreeNodeMouseClickEventArgs> NodeRightClicked;
public TreeNode SelectedNode
{
get
{
return tvExplorer.SelectedNode;
}
set
{
tvExplorer.SelectedNode = value;
if (value != null)
value.EnsureVisible();
}
}
public TreeNodeCollection Nodes
{
get
{
return tvExplorer.Nodes;
}
}
public bool AutoExpand { get; set; } = true;
public Color HighlightColor { get; set; } = Color.AliceBlue;
private Node _dataSource;
public Node DataSource
{
get
{
return _dataSource;
}
set
{
if (_dataSource != value)
{
tvExplorer.Nodes.Clear();
if (value != null)
{
tvExplorer.Nodes.Add(MakeTreeNode(value as Node));
}
else
{
tvExplorer.Nodes.Clear();
}
}
_dataSource = value;
}
}
private TreeNode MakeTreeNode(Node n, int depthLimit = Int32.MaxValue, bool isClone = false)
{
TreeNode node = new TreeNode(n.Text);
if (n.StubToNode != null)
{
//node.Text += ""
node.ForeColor = Color.DarkBlue;
node.Text = node.Text + " " + n.StubToNode.Text;
node.ImageIndex = 1;
node.SelectedImageIndex = 1;
if (n.StubToNode.Nodes.Count > 0)
{
var stubnode = new TreeNode("STUB");
stubnode.Tag = node;
node.Nodes.Add(stubnode);
}
}
else if (isClone)
{
node.ForeColor = Color.DarkBlue;
}
else
{
node.ImageIndex = -1;
node.SelectedImageIndex = -1;
}
n.ExtRef = node;
node.ToolTipText = n.TypeName;
node.Tag = n;
foreach (var cn in n.Nodes)
{
if (depthLimit < 1)
{
node.Nodes.Add(new TreeNode("STUB"));
}
node.Nodes.Add(MakeTreeNode(cn, depthLimit - 1, isClone));
}
return node;
}
private const int DUPE_DEPTH_LIMIT = 5;
private void TvExplorer_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
var thisNode = e.Node.Tag as Node;
if (thisNode != null && thisNode.StubToNode != null && thisNode.StubToNode.ExtRef != null)
{
e.Node.Nodes.Clear();
foreach (var n in MakeTreeNode(thisNode.StubToNode, DUPE_DEPTH_LIMIT, true).Nodes.OfType<TreeNode>().ToList())
{
e.Node.Nodes.Add(n);
}
}
else if (e.Node.Nodes.Count == 1 && e.Node.Nodes[0].Text == "STUB")
{
var n = e.Node.Tag as Node;
if (n != null)
{
e.Node.Nodes.Clear();
foreach (var cn in MakeTreeNode(n.StubToNode ?? n, DUPE_DEPTH_LIMIT, true).Nodes.OfType<TreeNode>())
{
e.Node.Nodes.Add(cn);
}
}
}
}
private void TvExplorer_AfterSelect(object sender, TreeViewEventArgs e)
{
var selectedNode = e.Node.Tag as Node;
foreach (var node in tvExplorer.Nodes.OfType<TreeNode>())
{
HighlightNodesByTag(node, selectedNode);
}
}
private void HighlightNodesByTag(TreeNode node, Node tag)
{
var treetag = node.Tag as Node;
if (tag != null && treetag != null && tag.Obj == treetag.Obj)
{
node.BackColor = HighlightColor;
}
else
{
node.BackColor = Color.White;
}
foreach (var n in node.Nodes)
{
HighlightNodesByTag(n as TreeNode, tag);
}
}
private void TvExplorer_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (e.Button == MouseButtons.Right && e.Node.Tag != null)
{
tvExplorer.SelectedNode = e.Node;
if (NodeRightClicked == null)
{ DoRightClick(sender, e); }
else
{ NodeRightClicked?.Invoke(this, e); }
}
else if (e.Button == MouseButtons.Left)
{
}
}
private bool DoFind()
{
if (Nodes.Count < 1)
return false;
TreeNode firstTreeNode = Nodes[0];
Node firstNode = firstTreeNode.Tag as Node;
if (firstNode == null)
return false;
TreeNode startNode = SelectedNode;
var node = startNode?.Tag as Node;
if (!string.IsNullOrWhiteSpace(txtFind.Text))
{
var res = firstNode.SearchNodes(txtFind.Text, node, Node.FindType.Text);
if (res == null || res.Count < 1)
{
SelectedNode = null;
return false;
}
TreeNode tn = firstTreeNode;
while (res.Count > 0)
{
tn = tn.Nodes[res.Pop()] as TreeNode;
}
tn.EnsureVisible();
SelectedNode = tn;
return true;
}
return false;
}
public static Node ClipData { get; set; }
private void DoRightClick(object sender, TreeNodeMouseClickEventArgs e)
{
var cm = new ContextMenu();
var n = e.Node.Tag as Node;
if (n != null)
{
var ao = n.Obj as AssetsObject;
if (ao != null)
{
if (n.StubToNode != null)
{
cm.MenuItems.Add(new MenuItem("Go to Object", (o, ea) =>
{
var tn = n.StubToNode.ExtRef as TreeNode;
if (tn != null)
{
SelectedNode = null;
SelectedNode = tn;
tn.EnsureVisible();
}
}));
}
else
{
cm.MenuItems.Add(new MenuItem("Copy", (o, ea) =>
{
Clipboard.Clear();
Clipboard.SetText(n.GetHashCode().ToString(), TextDataFormat.Text);
ClipData = n;
}));
}
}
if (n.StubToNode == null)
{
if (CanPaste(n))
{
cm.MenuItems.Add(new MenuItem("Paste Clone", (o, ea) =>
{
DoPaste(n);
}));
}
if (CanPastePointer(n))
{
cm.MenuItems.Add(new MenuItem("Paste Pointer", (o, ea) =>
{
DoPastePointer(n);
}));
}
if (CanDelete(n))
{
cm.MenuItems.Add(new MenuItem("Delete", (o, ea) =>
{
DoDelete(n);
}));
}
}
if (cm.MenuItems.Count > 0)
cm.Show(sender as Control, (sender as Control).PointToClient(Cursor.Position));
}
}
private Node GetClipData()
{
var clipObj = Clipboard.GetDataObject()?.GetData(DataFormats.Text) as string;
int clipHash = 0;
if (clipObj != null && ClipData != null && Int32.TryParse(clipObj, out clipHash) && ClipData.GetHashCode() == clipHash)
{
return ClipData;
}
return null;
}
private bool CanPastePointer(Node targetNode)
{
try
{
var target = targetNode?.Obj;
if (target == null)
return false;
var source = GetClipData();
var sourceObj = source?.Obj as AssetsObject;
if (sourceObj == null)
return false;
if (target.GetType() == typeof(AssetsFile))
return false;
Type assetType = null;
var ptrList = target as IEnumerable<ISmartPtr<AssetsObject>>;
if (ptrList != null)
{
//it's a list of some kind of pointers... can possibly paste (add) into here
assetType = target.GetType().GetGenericArguments()[0].GetGenericArguments()[0];
}
var ptr = target as ISmartPtr<AssetsObject>;
if (ptr != null)
{
//if it's a pointer we can maybe replace it if it isn't in a collection.
if (ReflectionHelper.IsPropNameAssignableToType(ptr.Owner, targetNode.ParentPropertyName, typeof(IEnumerable<ISmartPtr<AssetsObject>>)))
return false;
assetType = target.GetType().GetGenericArguments()[0];
if (string.IsNullOrWhiteSpace(targetNode.ParentPropertyName))
{
Log.LogErr($"Tried to paste, but type {target.GetType().Name} on node '{source.Text}' has no ParentPropertyName set. Check MakeNode to figure out why.");
return false;
}
}
if (assetType == null)
return false;
if (assetType.IsAssignableFrom(source.Obj.GetType()))
return true;
return false;
}
catch (Exception ex)
{
Log.LogErr("Exception trying to see if paste is allowed.", ex);
return false;
}
}
private bool CanPaste(Node targetNode)
{
try
{
var target = targetNode?.Obj;
if (target == null)
return false;
var source = GetClipData();
if (source?.Obj == null)
return false;
if (target.GetType() == typeof(AssetsFile))
return true;
return CanPastePointer(targetNode);
}
catch (Exception ex)
{
Log.LogErr("Exception trying to see if paste is allowed.", ex);
return false;
}
}
private bool CanDelete(Node targetNode)
{
var target = targetNode?.Obj;
if (target == null)
return false;
var targetParent = targetNode?.Parent?.Obj as IEnumerable<ISmartPtr<AssetsObject>>;
var targetSingle = targetNode?.Parent?.Obj as AssetsObject;
if (targetParent == null && (targetSingle == null || targetNode.ParentPropertyName == null))
return false;
return true;
}
private Node FindFirstParent(Node node)
{
if (node?.Obj == null)
return null;
if (typeof(AssetsObject).IsAssignableFrom(node.Obj.GetType()))
return node;
return FindFirstParent(node.Parent);
}
private List<CloneExclusion> GetExclusionsForObject(AssetsObject o, AssetsFile targetAssetsFile)
{
List<CloneExclusion> exclusions = new List<CloneExclusion>();
//exclude any monobehaviors that the script type can't be found for
exclusions.Add(new CloneExclusion(ExclusionMode.Remove)
{
Filter = (ptr, propInfo) =>
{
var res = ptr != null && ptr.Object is MonoBehaviourObject && targetAssetsFile.Manager.GetScriptObject(ptr.Target.Type.TypeHash) == null;
if (res)
{
Log.LogMsg($"Removing MonoBehaviour object during cloning because type hash '{ptr.Target.Type.TypeHash}' doesn't exist in the target.");
}
return res;
}
});
exclusions.Add(new CloneExclusion(ExclusionMode.Remove)
{
Filter = (ptr, propInfo) =>
{
var res = ptr != null && ptr.Target.Type.ClassID == AssetsConstants.ClassID.AnimationClassID;
if (res)
{
Log.LogMsg($"Removing Animation object during cloning because it isn't supported yet.");
}
return res;
}
});
if (typeof(Transform).IsAssignableFrom(o.GetType()))
{
exclusions.Add(new CloneExclusion(ExclusionMode.LeaveRef, propertyName: "Father", pointerTarget: ((Transform)o).Father.Target.Object));
}
return exclusions;
}
// yeesh, so much copy/paste code. I WILL DO BETTER THAN THIS
//todo: refactor
private void DoPaste(Node targetNode)
{
try
{
var node = GetClipData();
var sourceObj = node?.Obj as AssetsObject;
var targetObj = targetNode?.Obj;
AssetsFile targetFile = null;
Node targetOwnerNode = null;
AssetsObject targetOwnerObj = null;
object targetDirectParentObj = null;
if (node == null || node.Obj == null || node.StubToNode != null || sourceObj == null || targetObj == null)
return;
bool isFile = false;
if (targetObj is AssetsFile)
{
isFile = true;
targetFile = targetObj as AssetsFile;
targetOwnerNode = targetNode.Parent;
}
else
{
targetOwnerNode = FindFirstParent(targetNode);
targetOwnerObj = targetOwnerNode?.Obj as AssetsObject;
targetDirectParentObj = targetNode?.Parent?.Obj;
if (targetOwnerObj == null)
{
Log.LogErr($"Tried to paste, but couldn't find the assetsobject owner on node '{targetNode.Text}'");
return;
}
if (targetDirectParentObj == null)
{
Log.LogErr($"Tried to paste, but couldn't find the actual parent on node '{targetNode.Text}'");
return;
}
if (string.IsNullOrWhiteSpace(targetNode.ParentPropertyName))
{
Log.LogErr($"Tried to paste, but parent property name was null on node '{targetNode.Text}'");
return;
}
targetFile = targetOwnerObj.ObjectInfo.ParentFile;
}
List<AssetsObject> addedObjects = new List<AssetsObject>();
AssetsObject cloned = null;
try
{
var exclus = GetExclusionsForObject(sourceObj, targetFile);
cloned = sourceObj.ObjectInfo.DeepClone(targetFile, addedObjects: addedObjects, exclusions: exclus);
}
catch (Exception ex)
{
Log.LogErr($"Exception trying to clone object of type {sourceObj.GetType().Name}!", ex);
try
{
foreach (var ao in addedObjects)
{
targetFile.DeleteObject(ao);
}
}
catch (Exception ex2)
{
Log.LogErr("Failed to clean up after bad clone!", ex2);
MessageBox.Show("A clone failed and the rollback failed too. The assets files are in an unknown state!");
}
return;
}
bool updated = false;
if (isFile)
{
updated = true;
}
else
{
var ptrList = targetObj as IEnumerable<ISmartPtr<AssetsObject>>;
if (ptrList != null)
{
try
{
var pointer = ReflectionHelper.MakeTypedPointer(targetOwnerObj, cloned);
ReflectionHelper.AddObjectToEnum(pointer, ptrList);
updated = true;
}
catch (Exception ex)
{
Log.LogErr($"Adding object to collection failed!", ex);
MessageBox.Show("Object was created, but could not be attached to the collection!");
return;
}
}
var ptr = targetObj as ISmartPtr<AssetsObject>;
if (ptr != null)
{
try
{
var pointer = ReflectionHelper.MakeTypedPointer(targetOwnerObj, cloned);
var oldPointer = ReflectionHelper.GetPtrFromPropName(targetDirectParentObj, targetNode.ParentPropertyName);
ReflectionHelper.AssignPtrToPropName(targetDirectParentObj, targetNode.ParentPropertyName, pointer);
oldPointer.Dispose();
updated = true;
}
catch (Exception ex)
{
Log.LogErr($"Replacing pointer failed on {targetDirectParentObj?.GetType()?.Name}.{targetNode.ParentPropertyName}!");
}
}
}
if (updated)
{
var res = (tvExplorer.Nodes[0].Tag as Node).GetNodePath(targetNode);
//update node, hopefully we won't have to repopulate the entire thing?
if (!isFile)
{
Node newNode = Node.MakeNode(targetOwnerObj);
var targetOwnerParentNode = targetOwnerNode.Parent;
var idx = targetOwnerNode.Parent.Nodes.IndexOf(targetOwnerNode);
targetOwnerParentNode.Nodes.RemoveAt(idx);
targetOwnerParentNode.Nodes.Insert(idx, newNode);
newNode.Parent = targetOwnerParentNode;
newNode.ParentPropertyName = targetOwnerNode.ParentPropertyName;
}
else
{
Node newNode = Node.MakeNode((AssetsFile)targetObj);
var idx = targetNode.Parent.Nodes.IndexOf(targetNode);
targetNode.Parent.Nodes.RemoveAt(idx);
targetNode.Parent.Nodes.Insert(idx, newNode);
newNode.Parent = targetNode;
newNode.ParentPropertyName = null;
}
//TODO: find a better way to refresh only the altered tree node and not the whole thing
var ds = DataSource;
DataSource = null;
DataSource = ds;
TreeNode tn = tvExplorer.Nodes[0];
while (res.Count > 0)
{
tn = tn.Nodes[res.Pop()] as TreeNode;
}
tn.EnsureVisible();
SelectedNode = tn;
tn.Expand();
return;
}
}
catch (Exception ex)
{
Log.LogErr($"Exception trying to paste object!", ex);
MessageBox.Show("Failed to paste object!");
}
}
private void DoDelete(Node targetNode)
{
try
{
var targetObj = targetNode?.Obj;
var targetParentArray = targetNode?.Parent?.Obj as IEnumerable<ISmartPtr<AssetsObject>>;
var targetParentObj = targetNode?.Parent?.Obj as AssetsObject;
if (targetObj == null || (targetParentArray == null && (targetParentObj == null || targetNode?.ParentPropertyName == null)))
return;
if (string.IsNullOrWhiteSpace(targetNode.ParentPropertyName))
{
Log.LogErr($"Tried to delete, but parent property name was null on node '{targetNode.Text}'");
return;
}
bool updated = false;
var ptr = targetObj as ISmartPtr<AssetsObject>;
if (ptr != null)
{
try
{
if (targetParentArray != null)
{
ReflectionHelper.InvokeRemove(targetParentArray, ptr);
}
else if (targetParentObj != null)
{
ReflectionHelper.AssignPtrToPropName(targetParentObj, targetNode.ParentPropertyName, null);
}
ptr.Dispose();
updated = true;
}
catch (Exception ex)
{
Log.LogErr($"Removing pointer from collection failed on collection {targetNode.ParentPropertyName}!");
return;
}
}
if (updated)
{
var res = (tvExplorer.Nodes[0].Tag as Node).GetNodePath(targetNode.Parent);
//update node, hopefully we won't have to repopulate the entire thing?
if (targetParentArray != null)
{
targetNode.Parent.Nodes.Remove(targetNode);
}
//TODO: find a better way to refresh only the altered tree node and not the whole thing
var ds = DataSource;
DataSource = null;
DataSource = ds;
TreeNode tn = tvExplorer.Nodes[0];
while (res.Count > 0)
{
tn = tn.Nodes[res.Pop()] as TreeNode;
}
tn.EnsureVisible();
SelectedNode = tn;
tn.Expand();
return;
}
}
catch (Exception ex)
{
Log.LogErr($"Exception trying to delete object!", ex);
MessageBox.Show("Failed to paste object!");
}
}
private void DoPastePointer(Node targetNode)
{
try
{
//todo: lots of copy/paste that could be cleaned up and deduped with DoPaste
var node = GetClipData();
var sourceObj = node?.Obj as AssetsObject;
var targetObj = targetNode?.Obj;
var targetOwnerNode = FindFirstParent(targetNode);
var targetOwnerObj = targetOwnerNode?.Obj as AssetsObject;
var targetDirectParentObj = targetNode?.Parent?.Obj;
if (node == null || node.Obj == null || node.StubToNode != null || sourceObj == null || targetObj == null)
return;
if (targetOwnerObj == null)
{
Log.LogErr($"Tried to paste, but couldn't find the assetsobject owner on node '{targetNode.Text}'");
return;
}
if (targetDirectParentObj == null)
{
Log.LogErr($"Tried to paste, but couldn't find the actual parent on node '{targetNode.Text}'");
return;
}
if (string.IsNullOrWhiteSpace(targetNode.ParentPropertyName))
{
Log.LogErr($"Tried to paste, but parent property name was null on node '{targetNode.Text}'");
return;
}
if (sourceObj.ObjectInfo.ParentFile.Manager != targetOwnerObj.ObjectInfo.ParentFile.Manager)
{
//can't paste a pointer to a different assets manager instance
return;
}
bool updated = false;
var ptrList = targetObj as IEnumerable<ISmartPtr<AssetsObject>>;
if (ptrList != null)
{
try
{
var pointer = ReflectionHelper.MakeTypedPointer(targetOwnerObj, sourceObj);
ReflectionHelper.AddObjectToEnum(pointer, ptrList);
updated = true;
}
catch (Exception ex)
{
Log.LogErr($"Adding object to collection failed!", ex);
return;
}
}
var ptr = targetObj as ISmartPtr<AssetsObject>;
if (ptr != null)
{
try
{
var pointer = ReflectionHelper.MakeTypedPointer(targetOwnerObj, sourceObj);
var oldPointer = ReflectionHelper.GetPtrFromPropName(targetDirectParentObj, targetNode.ParentPropertyName);
ReflectionHelper.AssignPtrToPropName(targetDirectParentObj, targetNode.ParentPropertyName, pointer);
oldPointer.Dispose();
updated = true;
}
catch (Exception ex)
{
Log.LogErr($"Replacing pointer failed on {targetDirectParentObj?.GetType()?.Name}.{targetNode.ParentPropertyName}!");
}
}
if (updated)
{
var res = (tvExplorer.Nodes[0].Tag as Node).GetNodePath(targetNode);
//update node, hopefully we won't have to repopulate the entire thing?
Node newnode = Node.MakeNode(targetOwnerObj);
var targetOwnerParentNode = targetOwnerNode.Parent;
var idx = targetOwnerNode.Parent.Nodes.IndexOf(targetOwnerNode);
targetOwnerParentNode.Nodes.RemoveAt(idx);
targetOwnerParentNode.Nodes.Insert(idx, newnode);
newnode.Parent = targetOwnerParentNode;
newnode.ParentPropertyName = targetOwnerNode.ParentPropertyName;
//TODO: find a better way to refresh only the altered tree node and not the whole thing
var ds = DataSource;
DataSource = null;
DataSource = ds;
TreeNode tn = tvExplorer.Nodes[0];
while (res.Count > 0)
{
tn = tn.Nodes[res.Pop()] as TreeNode;
}
tn.EnsureVisible();
SelectedNode = tn;
tn.Expand();
return;
}
}
catch (Exception ex)
{
Log.LogErr($"Exception trying to paste object!", ex);
MessageBox.Show("Failed to paste object!");
}
}
private void BtnFind_Click(object sender, EventArgs e)
{
DoFind();
}
private void TxtFind_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
if (DoFind())
e.SuppressKeyPress = true;
}
}
}
| 37.385482 | 178 | 0.448328 | [
"MIT"
] | Kylemc1413/QuestomAssets | Assplorer/ExploreTree.cs | 29,873 | 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.Contracts;
using System.Runtime.InteropServices;
using Conditional = System.Diagnostics.ConditionalAttribute;
namespace System.Numerics
{
/// <summary>
/// BigIntegerBuilder holds a multiprecision unsigned integer value. It is mutable and
/// supports common arithmetic operations. Be careful NOT to simply assign one
/// BigIntegerBuilder to another, unless you really know what you are doing. The proper
/// way to replicate a BigIntegerBuilder is via the constructor "BigIntegerBuilder(ref BigIntegerBuilder reg)",
/// or with reg1.Load(ref reg2). Using the ctor marks the buffer as shared so changing the
/// value of one register will not affect the other. Using Load copies the contents from
/// one to the other. Either way, the internal buffer isn't aliased incorrectly.
/// </summary>
internal struct BigIntegerBuilder
{
private const int kcbitUint = 32;
// For a single uint, _iuLast is 0.
private int _iuLast;
// Used if _iuLast == 0.
private uint _uSmall;
// Used if _iuLast > 0.
private uint[] _rgu;
// This is false whenever _rgu is null or is shared with a NewBigInteger
// or with another BigIntegerBuilder.
private bool _fWritable;
[Conditional("DEBUG")]
private void AssertValid(bool fTrimmed)
{
if (_iuLast <= 0)
{
Contract.Assert(_iuLast == 0);
Contract.Assert(!_fWritable || _rgu != null);
}
else
{
Contract.Assert(_rgu != null && _rgu.Length > _iuLast);
Contract.Assert(!fTrimmed || _rgu[_iuLast] != 0);
}
}
public BigIntegerBuilder(ref BigIntegerBuilder reg)
{
reg.AssertValid(true);
this = reg;
if (_fWritable)
{
_fWritable = false;
if (_iuLast == 0)
_rgu = null;
else
reg._fWritable = false;
}
AssertValid(true);
}
public BigIntegerBuilder(int cuAlloc)
{
_iuLast = 0;
_uSmall = 0;
if (cuAlloc > 1)
{
_rgu = new uint[cuAlloc];
_fWritable = true;
}
else
{
_rgu = null;
_fWritable = false;
}
AssertValid(true);
}
public BigIntegerBuilder(BigInteger bn)
{
_fWritable = false;
_rgu = bn._Bits;
if (_rgu == null)
{
_iuLast = 0;
_uSmall = NumericsHelpers.Abs(bn._Sign);
}
else
{
_iuLast = _rgu.Length - 1;
_uSmall = _rgu[0];
while (_iuLast > 0 && _rgu[_iuLast] == 0)
--_iuLast;
}
AssertValid(true);
}
public BigIntegerBuilder(BigInteger bn, ref int sign)
{
Contract.Requires(sign == +1 || sign == -1);
_fWritable = false;
_rgu = bn._Bits;
int n = bn._Sign;
int mask = n >> (kcbitUint - 1);
sign = (sign ^ mask) - mask;
if (_rgu == null)
{
_iuLast = 0;
_uSmall = (uint)((n ^ mask) - mask);
}
else
{
_iuLast = _rgu.Length - 1;
_uSmall = _rgu[0];
while (_iuLast > 0 && _rgu[_iuLast] == 0)
--_iuLast;
}
AssertValid(true);
}
public BigInteger GetInteger(int sign)
{
Contract.Requires(sign == +1 || sign == -1);
AssertValid(true);
uint[] bits;
GetIntegerParts(sign, out sign, out bits);
return new BigInteger(sign, bits);
}
internal void GetIntegerParts(int signSrc, out int sign, out uint[] bits)
{
Contract.Requires(signSrc == +1 || signSrc == -1);
AssertValid(true);
if (_iuLast == 0)
{
if (_uSmall <= int.MaxValue)
{
sign = signSrc * (int)_uSmall;
bits = null;
return;
}
if (_rgu == null)
_rgu = new uint[1] { _uSmall };
else if (_fWritable)
_rgu[0] = _uSmall;
else if (_rgu[0] != _uSmall)
_rgu = new uint[1] { _uSmall };
}
// The sign is +/- 1.
sign = signSrc;
int cuExtra = _rgu.Length - _iuLast - 1;
Contract.Assert(cuExtra >= 0);
if (cuExtra <= 1)
{
if (cuExtra == 0 || _rgu[_iuLast + 1] == 0)
{
_fWritable = false;
bits = _rgu;
return;
}
if (_fWritable)
{
_rgu[_iuLast + 1] = 0;
_fWritable = false;
bits = _rgu;
return;
}
// The buffer isn't writable, but has an extra uint that is non-zero,
// so we have to allocate a new buffer.
}
// Keep the bigger buffer (if it is writable), but create a smaller one for the BigInteger.
bits = _rgu;
Array.Resize(ref bits, _iuLast + 1);
if (!_fWritable)
_rgu = bits;
}
public void Set(uint u)
{
_uSmall = u;
_iuLast = 0;
AssertValid(true);
}
public void Set(ulong uu)
{
uint uHi = NumericsHelpers.GetHi(uu);
if (uHi == 0)
{
_uSmall = NumericsHelpers.GetLo(uu);
_iuLast = 0;
}
else
{
SetSizeLazy(2);
_rgu[0] = (uint)uu;
_rgu[1] = uHi;
}
AssertValid(true);
}
public int Size { get { return _iuLast + 1; } }
public uint High { get { return _iuLast == 0 ? _uSmall : _rgu[_iuLast]; } }
public void GetApproxParts(out int exp, out ulong man)
{
AssertValid(true);
if (_iuLast == 0)
{
man = (ulong)_uSmall;
exp = 0;
return;
}
int cuLeft = _iuLast - 1;
man = NumericsHelpers.MakeUlong(_rgu[cuLeft + 1], _rgu[cuLeft]);
exp = cuLeft * kcbitUint;
int cbit;
if (cuLeft > 0 && (cbit = NumericsHelpers.CbitHighZero(_rgu[cuLeft + 1])) > 0)
{
// Get 64 bits.
Contract.Assert(cbit < kcbitUint);
man = (man << cbit) | (_rgu[cuLeft - 1] >> (kcbitUint - cbit));
exp -= cbit;
}
}
private void Trim()
{
AssertValid(false);
if (_iuLast > 0 && _rgu[_iuLast] == 0)
{
_uSmall = _rgu[0];
while (--_iuLast > 0 && _rgu[_iuLast] == 0)
;
}
AssertValid(true);
}
private int CuNonZero
{
get
{
Contract.Assert(_iuLast > 0);
int cu = 0;
for (int iu = _iuLast; iu >= 0; --iu)
{
if (_rgu[iu] != 0)
cu++;
}
return cu;
}
}
// Sets the size to cu and makes sure the buffer is writable (if cu > 1),
// but makes no guarantees about the contents of the buffer.
private void SetSizeLazy(int cu)
{
Contract.Requires(cu > 0);
AssertValid(false);
if (cu <= 1)
{
_iuLast = 0;
return;
}
if (!_fWritable || _rgu.Length < cu)
{
_rgu = new uint[cu];
_fWritable = true;
}
_iuLast = cu - 1;
AssertValid(false);
}
// Sets the size to cu, makes sure the buffer is writable (if cu > 1),
// and set the contents to all zero.
private void SetSizeClear(int cu)
{
Contract.Requires(cu > 0);
AssertValid(false);
if (cu <= 1)
{
_iuLast = 0;
_uSmall = 0;
return;
}
if (!_fWritable || _rgu.Length < cu)
{
_rgu = new uint[cu];
_fWritable = true;
}
else
Array.Clear(_rgu, 0, cu);
_iuLast = cu - 1;
AssertValid(false);
}
// Sets the size to cu, makes sure the buffer is writable (if cu > 1),
// and maintains the contents. If the buffer is reallocated, cuExtra
// uints are also allocated.
private void SetSizeKeep(int cu, int cuExtra)
{
Contract.Requires(cu > 0 && cuExtra >= 0);
AssertValid(false);
if (cu <= 1)
{
if (_iuLast > 0)
_uSmall = _rgu[0];
_iuLast = 0;
return;
}
if (!_fWritable || _rgu.Length < cu)
{
uint[] rgu = new uint[cu + cuExtra];
if (_iuLast == 0)
rgu[0] = _uSmall;
else
Array.Copy(_rgu, rgu, Math.Min(cu, _iuLast + 1));
_rgu = rgu;
_fWritable = true;
}
else if (_iuLast + 1 < cu)
{
Array.Clear(_rgu, _iuLast + 1, cu - _iuLast - 1);
if (_iuLast == 0)
_rgu[0] = _uSmall;
}
_iuLast = cu - 1;
AssertValid(false);
}
// Makes sure the buffer is writable and can support cu uints.
// Preserves the contents of the buffer up to min(_iuLast + 1, cu).
// Changes the size if cu <= _iuLast and the buffer needs to be allocated.
public void EnsureWritable(int cu, int cuExtra)
{
Contract.Requires(cu > 1 && cuExtra >= 0);
AssertValid(false);
if (_fWritable && _rgu.Length >= cu)
return;
uint[] rgu = new uint[cu + cuExtra];
if (_iuLast > 0)
{
if (_iuLast >= cu)
_iuLast = cu - 1;
Array.Copy(_rgu, rgu, _iuLast + 1);
}
_rgu = rgu;
_fWritable = true;
AssertValid(false);
}
// Makes sure the buffer is writable and can support _iuLast + 1 uints.
// Preserves the contents of the buffer.
public void EnsureWritable(int cuExtra)
{
Contract.Requires(cuExtra >= 0);
AssertValid(false);
Contract.Assert(_iuLast > 0);
if (_fWritable)
return;
uint[] rgu = new uint[_iuLast + 1 + cuExtra];
Array.Copy(_rgu, rgu, _iuLast + 1);
_rgu = rgu;
_fWritable = true;
AssertValid(false);
}
public void EnsureWritable()
{
EnsureWritable(0);
}
// Loads the value of reg into this register.
public void Load(ref BigIntegerBuilder reg)
{
Load(ref reg, 0);
}
// Loads the value of reg into this register. If we need to allocate memory
// to perform the load, allocate cuExtra elements.
public void Load(ref BigIntegerBuilder reg, int cuExtra)
{
Contract.Requires(cuExtra >= 0);
AssertValid(false);
reg.AssertValid(true);
if (reg._iuLast == 0)
{
_uSmall = reg._uSmall;
_iuLast = 0;
}
else
{
if (!_fWritable || _rgu.Length <= reg._iuLast)
{
_rgu = new uint[reg._iuLast + 1 + cuExtra];
_fWritable = true;
}
_iuLast = reg._iuLast;
Array.Copy(reg._rgu, _rgu, _iuLast + 1);
}
AssertValid(true);
}
public void Add(uint u)
{
AssertValid(true);
if (_iuLast == 0)
{
if ((_uSmall += u) >= u)
return;
SetSizeLazy(2);
_rgu[0] = _uSmall;
_rgu[1] = 1;
return;
}
if (u == 0)
return;
uint uNew = _rgu[0] + u;
if (uNew < u)
{
// Have carry.
EnsureWritable(1);
ApplyCarry(1);
}
else if (!_fWritable)
EnsureWritable();
_rgu[0] = uNew;
AssertValid(true);
}
public void Add(ref BigIntegerBuilder reg)
{
AssertValid(true);
reg.AssertValid(true);
if (reg._iuLast == 0)
{
Add(reg._uSmall);
return;
}
if (_iuLast == 0)
{
uint u = _uSmall;
if (u == 0)
this = new BigIntegerBuilder(ref reg);
else
{
Load(ref reg, 1);
Add(u);
}
return;
}
EnsureWritable(Math.Max(_iuLast, reg._iuLast) + 1, 1);
int cuAdd = reg._iuLast + 1;
if (_iuLast < reg._iuLast)
{
cuAdd = _iuLast + 1;
Array.Copy(reg._rgu, _iuLast + 1, _rgu, _iuLast + 1, reg._iuLast - _iuLast);
Contract.Assert(_iuLast > 0);
_iuLast = reg._iuLast;
}
// Add, tracking carry.
uint uCarry = 0;
for (int iu = 0; iu < cuAdd; iu++)
{
uCarry = AddCarry(ref _rgu[iu], reg._rgu[iu], uCarry);
Contract.Assert(uCarry <= 1);
}
// Deal with extra carry.
if (uCarry != 0)
ApplyCarry(cuAdd);
AssertValid(true);
}
public void Sub(ref int sign, uint u)
{
Contract.Requires(sign == +1 || sign == -1);
AssertValid(true);
if (_iuLast == 0)
{
if (u <= _uSmall)
_uSmall -= u;
else
{
_uSmall = u - _uSmall;
sign = -sign;
}
AssertValid(true);
return;
}
if (u == 0)
return;
EnsureWritable();
uint uTmp = _rgu[0];
_rgu[0] = uTmp - u;
if (uTmp < u)
{
ApplyBorrow(1);
Trim();
}
AssertValid(true);
}
public void Sub(ref int sign, ref BigIntegerBuilder reg)
{
Contract.Requires(sign == +1 || sign == -1);
AssertValid(true);
reg.AssertValid(true);
if (reg._iuLast == 0)
{
Sub(ref sign, reg._uSmall);
return;
}
if (_iuLast == 0)
{
uint u = _uSmall;
if (u == 0)
this = new BigIntegerBuilder(ref reg);
else
{
Load(ref reg);
Sub(ref sign, u);
}
sign = -sign;
return;
}
if (_iuLast < reg._iuLast)
{
SubRev(ref reg);
sign = -sign;
return;
}
int cuSub = reg._iuLast + 1;
if (_iuLast == reg._iuLast)
{
// Determine which is larger.
_iuLast = BigInteger.GetDiffLength(_rgu, reg._rgu, _iuLast + 1) - 1;
if (_iuLast < 0)
{
_iuLast = 0;
_uSmall = 0;
return;
}
uint u1 = _rgu[_iuLast];
uint u2 = reg._rgu[_iuLast];
if (_iuLast == 0)
{
if (u1 < u2)
{
_uSmall = u2 - u1;
sign = -sign;
}
else
_uSmall = u1 - u2;
AssertValid(true);
return;
}
if (u1 < u2)
{
Contract.Assert(_iuLast > 0);
reg._iuLast = _iuLast;
SubRev(ref reg);
reg._iuLast = cuSub - 1;
Contract.Assert(reg._iuLast > 0);
sign = -sign;
return;
}
cuSub = _iuLast + 1;
}
EnsureWritable();
// Subtract, tracking borrow.
uint uBorrow = 0;
for (int iu = 0; iu < cuSub; iu++)
{
uBorrow = SubBorrow(ref _rgu[iu], reg._rgu[iu], uBorrow);
Contract.Assert(uBorrow <= 1);
}
if (uBorrow != 0)
{
Contract.Assert(uBorrow == 1 && cuSub <= _iuLast);
ApplyBorrow(cuSub);
}
Trim();
}
// Subtract this register from the given one and put the result in this one.
// Asserts that reg is larger in the most significant uint.
private void SubRev(ref BigIntegerBuilder reg)
{
Contract.Assert(0 < _iuLast && _iuLast <= reg._iuLast);
Contract.Assert(_iuLast < reg._iuLast || _rgu[_iuLast] < reg._rgu[_iuLast]);
EnsureWritable(reg._iuLast + 1, 0);
int cuSub = _iuLast + 1;
if (_iuLast < reg._iuLast)
{
Array.Copy(reg._rgu, _iuLast + 1, _rgu, _iuLast + 1, reg._iuLast - _iuLast);
Contract.Assert(_iuLast > 0);
_iuLast = reg._iuLast;
}
uint uBorrow = 0;
for (int iu = 0; iu < cuSub; iu++)
{
uBorrow = SubRevBorrow(ref _rgu[iu], reg._rgu[iu], uBorrow);
Contract.Assert(uBorrow <= 1);
}
if (uBorrow != 0)
{
Contract.Assert(uBorrow == 1);
ApplyBorrow(cuSub);
}
Trim();
}
public void Mul(uint u)
{
if (u == 0)
{
Set(0);
return;
}
if (u == 1)
return;
if (_iuLast == 0)
{
Set((ulong)_uSmall * u);
return;
}
EnsureWritable(1);
uint uCarry = 0;
for (int iu = 0; iu <= _iuLast; iu++)
uCarry = MulCarry(ref _rgu[iu], u, uCarry);
if (uCarry != 0)
{
SetSizeKeep(_iuLast + 2, 0);
_rgu[_iuLast] = uCarry;
}
}
// This version may share memory with regMul.
public void Mul(ref BigIntegerBuilder regMul)
{
AssertValid(true);
regMul.AssertValid(true);
if (regMul._iuLast == 0)
Mul(regMul._uSmall);
else if (_iuLast == 0)
{
uint u = _uSmall;
if (u == 1)
this = new BigIntegerBuilder(ref regMul);
else if (u != 0)
{
Load(ref regMul, 1);
Mul(u);
}
}
else
{
int cuBase = _iuLast + 1;
SetSizeKeep(cuBase + regMul._iuLast, 1);
for (int iu = cuBase; --iu >= 0;)
{
uint uMul = _rgu[iu];
_rgu[iu] = 0;
uint uCarry = 0;
for (int iuSrc = 0; iuSrc <= regMul._iuLast; iuSrc++)
uCarry = AddMulCarry(ref _rgu[iu + iuSrc], regMul._rgu[iuSrc], uMul, uCarry);
if (uCarry != 0)
{
for (int iuDst = iu + regMul._iuLast + 1; uCarry != 0 && iuDst <= _iuLast; iuDst++)
uCarry = AddCarry(ref _rgu[iuDst], 0, uCarry);
if (uCarry != 0)
{
SetSizeKeep(_iuLast + 2, 0);
_rgu[_iuLast] = uCarry;
}
}
}
AssertValid(true);
}
}
// Multiply reg1 times reg2, putting the result in 'this'. This version never shares memory
// with either of the operands. This is useful when performing a series of arithmetic operations
// and large working buffers are allocated up front.
public void Mul(ref BigIntegerBuilder reg1, ref BigIntegerBuilder reg2)
{
AssertValid(true);
reg1.AssertValid(true);
reg2.AssertValid(true);
if (reg1._iuLast == 0)
{
if (reg2._iuLast == 0)
Set((ulong)reg1._uSmall * reg2._uSmall);
else
{
Load(ref reg2, 1);
Mul(reg1._uSmall);
}
}
else if (reg2._iuLast == 0)
{
Load(ref reg1, 1);
Mul(reg2._uSmall);
}
else
{
Contract.Assert(reg1._iuLast > 0 && reg2._iuLast > 0);
SetSizeClear(reg1._iuLast + reg2._iuLast + 2);
uint[] rgu1, rgu2;
int cu1, cu2;
// We prefer more iterations on the inner loop and fewer on the outer.
if (reg1.CuNonZero <= reg2.CuNonZero)
{
rgu1 = reg1._rgu; cu1 = reg1._iuLast + 1;
rgu2 = reg2._rgu; cu2 = reg2._iuLast + 1;
}
else
{
rgu1 = reg2._rgu; cu1 = reg2._iuLast + 1;
rgu2 = reg1._rgu; cu2 = reg1._iuLast + 1;
}
for (int iu1 = 0; iu1 < cu1; iu1++)
{
uint uCur = rgu1[iu1];
if (uCur == 0)
continue;
uint uCarry = 0;
int iuRes = iu1;
for (int iu2 = 0; iu2 < cu2; iu2++, iuRes++)
uCarry = AddMulCarry(ref _rgu[iuRes], uCur, rgu2[iu2], uCarry);
while (uCarry != 0)
uCarry = AddCarry(ref _rgu[iuRes++], 0, uCarry);
}
Trim();
}
}
// Divide 'this' by uDen, leaving the quotient in 'this' and returning the remainder.
public uint DivMod(uint uDen)
{
AssertValid(true);
if (uDen == 1)
return 0;
if (_iuLast == 0)
{
uint uTmp = _uSmall;
_uSmall = uTmp / uDen;
return uTmp % uDen;
}
EnsureWritable();
ulong uu = 0;
for (int iv = _iuLast; iv >= 0; iv--)
{
uu = NumericsHelpers.MakeUlong((uint)uu, _rgu[iv]);
_rgu[iv] = (uint)(uu / uDen);
uu %= uDen;
}
Trim();
return (uint)uu;
}
// Divide regNum by uDen, returning the remainder and tossing the quotient.
public static uint Mod(ref BigIntegerBuilder regNum, uint uDen)
{
regNum.AssertValid(true);
if (uDen == 1)
return 0;
if (regNum._iuLast == 0)
return regNum._uSmall % uDen;
ulong uu = 0;
for (int iv = regNum._iuLast; iv >= 0; iv--)
{
uu = NumericsHelpers.MakeUlong((uint)uu, regNum._rgu[iv]);
uu %= uDen;
}
return (uint)uu;
}
// Divide 'this' by regDen, leaving the remainder in 'this' and tossing the quotient.
public void Mod(ref BigIntegerBuilder regDen)
{
AssertValid(true);
regDen.AssertValid(true);
if (regDen._iuLast == 0)
{
Set(Mod(ref this, regDen._uSmall));
return;
}
if (_iuLast == 0)
return;
BigIntegerBuilder regTmp = new BigIntegerBuilder();
ModDivCore(ref this, ref regDen, false, ref regTmp);
}
// Divide 'this' by regDen, leaving the quotient in 'this' and tossing the remainder.
public void Div(ref BigIntegerBuilder regDen)
{
AssertValid(true);
regDen.AssertValid(true);
if (regDen._iuLast == 0)
{
DivMod(regDen._uSmall);
return;
}
if (_iuLast == 0)
{
_uSmall = 0;
return;
}
BigIntegerBuilder regTmp = new BigIntegerBuilder();
ModDivCore(ref this, ref regDen, true, ref regTmp);
NumericsHelpers.Swap(ref this, ref regTmp);
}
// Divide regNum by regDen, leaving the remainder in regNum and the quotient in regQuo (if fQuo is true).
public void ModDiv(ref BigIntegerBuilder regDen, ref BigIntegerBuilder regQuo)
{
if (regDen._iuLast == 0)
{
regQuo.Set(DivMod(regDen._uSmall));
NumericsHelpers.Swap(ref this, ref regQuo);
return;
}
if (_iuLast == 0)
return;
ModDivCore(ref this, ref regDen, true, ref regQuo);
}
private static void ModDivCore(ref BigIntegerBuilder regNum, ref BigIntegerBuilder regDen, bool fQuo, ref BigIntegerBuilder regQuo)
{
Contract.Assert(regNum._iuLast > 0 && regDen._iuLast > 0);
regQuo.Set(0);
if (regNum._iuLast < regDen._iuLast)
return;
Contract.Assert(0 < regDen._iuLast && regDen._iuLast <= regNum._iuLast);
int cuDen = regDen._iuLast + 1;
int cuDiff = regNum._iuLast - regDen._iuLast;
// Determine whether the result will have cuDiff "digits" or cuDiff+1 "digits".
int cuQuo = cuDiff;
for (int iu = regNum._iuLast; ; iu--)
{
if (iu < cuDiff)
{
cuQuo++;
break;
}
if (regDen._rgu[iu - cuDiff] != regNum._rgu[iu])
{
if (regDen._rgu[iu - cuDiff] < regNum._rgu[iu])
cuQuo++;
break;
}
}
if (cuQuo == 0)
return;
if (fQuo)
regQuo.SetSizeLazy(cuQuo);
// Get the uint to use for the trial divisions. We normalize so the high bit is set.
uint uDen = regDen._rgu[cuDen - 1];
uint uDenNext = regDen._rgu[cuDen - 2];
int cbitShiftLeft = NumericsHelpers.CbitHighZero(uDen);
int cbitShiftRight = kcbitUint - cbitShiftLeft;
if (cbitShiftLeft > 0)
{
uDen = (uDen << cbitShiftLeft) | (uDenNext >> cbitShiftRight);
uDenNext <<= cbitShiftLeft;
if (cuDen > 2)
uDenNext |= regDen._rgu[cuDen - 3] >> cbitShiftRight;
}
Contract.Assert((uDen & 0x80000000) != 0);
// Allocate and initialize working space.
Contract.Assert(cuQuo + cuDen == regNum._iuLast + 1 || cuQuo + cuDen == regNum._iuLast + 2);
regNum.EnsureWritable();
for (int iu = cuQuo; --iu >= 0;)
{
// Get the high (normalized) bits of regNum.
uint uNumHi = (iu + cuDen <= regNum._iuLast) ? regNum._rgu[iu + cuDen] : 0;
Contract.Assert(uNumHi <= regDen._rgu[cuDen - 1]);
ulong uuNum = NumericsHelpers.MakeUlong(uNumHi, regNum._rgu[iu + cuDen - 1]);
uint uNumNext = regNum._rgu[iu + cuDen - 2];
if (cbitShiftLeft > 0)
{
uuNum = (uuNum << cbitShiftLeft) | (uNumNext >> cbitShiftRight);
uNumNext <<= cbitShiftLeft;
if (iu + cuDen >= 3)
uNumNext |= regNum._rgu[iu + cuDen - 3] >> cbitShiftRight;
}
// Divide to get the quotient digit.
ulong uuQuo = uuNum / uDen;
ulong uuRem = (uint)(uuNum % uDen);
Contract.Assert(uuQuo <= (ulong)uint.MaxValue + 2);
if (uuQuo > uint.MaxValue)
{
uuRem += uDen * (uuQuo - uint.MaxValue);
uuQuo = uint.MaxValue;
}
while (uuRem <= uint.MaxValue && uuQuo * uDenNext > NumericsHelpers.MakeUlong((uint)uuRem, uNumNext))
{
uuQuo--;
uuRem += uDen;
}
// Multiply and subtract. Note that uuQuo may be 1 too large. If we have a borrow
// at the end, we'll add the denominator back on and decrement uuQuo.
if (uuQuo > 0)
{
ulong uuBorrow = 0;
for (int iu2 = 0; iu2 < cuDen; iu2++)
{
uuBorrow += regDen._rgu[iu2] * uuQuo;
uint uSub = (uint)uuBorrow;
uuBorrow >>= kcbitUint;
if (regNum._rgu[iu + iu2] < uSub)
uuBorrow++;
regNum._rgu[iu + iu2] -= uSub;
}
Contract.Assert(uNumHi == uuBorrow || uNumHi == uuBorrow - 1);
if (uNumHi < uuBorrow)
{
// Add, tracking carry.
uint uCarry = 0;
for (int iu2 = 0; iu2 < cuDen; iu2++)
{
uCarry = AddCarry(ref regNum._rgu[iu + iu2], regDen._rgu[iu2], uCarry);
Contract.Assert(uCarry <= 1);
}
Contract.Assert(uCarry == 1);
uuQuo--;
}
regNum._iuLast = iu + cuDen - 1;
}
if (fQuo)
{
if (cuQuo == 1)
regQuo._uSmall = (uint)uuQuo;
else
regQuo._rgu[iu] = (uint)uuQuo;
}
}
Contract.Assert(cuDen > 1 && regNum._iuLast > 0);
regNum._iuLast = cuDen - 1;
regNum.Trim();
}
private static readonly double s_kdblLn2To32 = 32 * Math.Log(2);
public void ShiftRight(int cbit)
{
AssertValid(true);
if (cbit <= 0)
{
if (cbit < 0)
ShiftLeft(-cbit);
return;
}
ShiftRight(cbit / kcbitUint, cbit % kcbitUint);
}
public void ShiftRight(int cuShift, int cbitShift)
{
Contract.Requires(cuShift >= 0);
Contract.Requires(0 <= cbitShift);
Contract.Assert(cbitShift < kcbitUint);
AssertValid(true);
if ((cuShift | cbitShift) == 0)
return;
if (cuShift > _iuLast)
{
Set(0);
return;
}
if (_iuLast == 0)
{
_uSmall >>= cbitShift;
AssertValid(true);
return;
}
uint[] rguSrc = _rgu;
int cuSrc = _iuLast + 1;
_iuLast -= cuShift;
if (_iuLast == 0)
_uSmall = rguSrc[cuShift] >> cbitShift;
else
{
Contract.Assert(_rgu.Length > _iuLast);
if (!_fWritable)
{
_rgu = new uint[_iuLast + 1];
_fWritable = true;
}
if (cbitShift > 0)
{
for (int iuSrc = cuShift + 1, iuDst = 0; iuSrc < cuSrc; iuSrc++, iuDst++)
_rgu[iuDst] = (rguSrc[iuSrc - 1] >> cbitShift) | (rguSrc[iuSrc] << (kcbitUint - cbitShift));
_rgu[_iuLast] = rguSrc[cuSrc - 1] >> cbitShift;
Trim();
}
else
Array.Copy(rguSrc, cuShift, _rgu, 0, _iuLast + 1);
}
AssertValid(true);
}
public void ShiftLeft(int cbit)
{
AssertValid(true);
if (cbit <= 0)
{
if (cbit < 0)
ShiftRight(-cbit);
return;
}
ShiftLeft(cbit / kcbitUint, cbit % kcbitUint);
}
public void ShiftLeft(int cuShift, int cbitShift)
{
Contract.Requires(cuShift >= 0);
Contract.Requires(0 <= cbitShift);
Contract.Assert(cbitShift < kcbitUint);
AssertValid(true);
int iuLastNew = _iuLast + cuShift;
uint uHigh = 0;
if (cbitShift > 0)
{
uHigh = this.High >> (kcbitUint - cbitShift);
if (uHigh != 0)
iuLastNew++;
}
if (iuLastNew == 0)
{
_uSmall <<= cbitShift;
return;
}
uint[] rguSrc = _rgu;
bool fClearLow = cuShift > 0;
if (!_fWritable || _rgu.Length <= iuLastNew)
{
_rgu = new uint[iuLastNew + 1];
_fWritable = true;
fClearLow = false;
}
if (_iuLast == 0)
{
if (uHigh != 0)
_rgu[cuShift + 1] = uHigh;
_rgu[cuShift] = _uSmall << cbitShift;
}
else if (cbitShift == 0)
Array.Copy(rguSrc, 0, _rgu, cuShift, _iuLast + 1);
else
{
int iuSrc = _iuLast;
int iuDst = _iuLast + cuShift;
if (iuDst < iuLastNew)
_rgu[iuLastNew] = uHigh;
for (; iuSrc > 0; iuSrc--, iuDst--)
_rgu[iuDst] = (rguSrc[iuSrc] << cbitShift) | (rguSrc[iuSrc - 1] >> (kcbitUint - cbitShift));
_rgu[cuShift] = rguSrc[0] << cbitShift;
}
_iuLast = iuLastNew;
if (fClearLow)
Array.Clear(_rgu, 0, cuShift);
}
// Get the high two uints, combined into a ulong, zero extending to
// length cu if necessary. Asserts cu > _iuLast and _iuLast > 0.
private ulong GetHigh2(int cu)
{
Contract.Requires(cu >= 2);
Contract.Assert(_iuLast > 0);
Contract.Assert(cu > _iuLast);
if (cu - 1 <= _iuLast)
return NumericsHelpers.MakeUlong(_rgu[cu - 1], _rgu[cu - 2]);
if (cu - 2 == _iuLast)
return _rgu[cu - 2];
return 0;
}
// Apply a single carry starting at iu, extending the register
// if needed.
private void ApplyCarry(int iu)
{
Contract.Requires(0 <= iu);
Contract.Assert(_fWritable && _iuLast > 0);
Contract.Assert(iu <= _iuLast + 1);
for (; ; iu++)
{
if (iu > _iuLast)
{
if (_iuLast + 1 == _rgu.Length)
Array.Resize(ref _rgu, _iuLast + 2);
_rgu[++_iuLast] = 1;
break;
}
if (++_rgu[iu] > 0)
break;
}
}
// Apply a single borrow starting at iu. This does NOT trim the result.
private void ApplyBorrow(int iuMin)
{
Contract.Requires(0 < iuMin);
Contract.Assert(_fWritable && _iuLast > 0);
Contract.Assert(iuMin <= _iuLast);
for (int iu = iuMin; iu <= _iuLast; iu++)
{
uint u = _rgu[iu]--;
if (u > 0)
return;
}
// Borrowed off the end!
Contract.Assert(false, "Invalid call to ApplyBorrow");
}
private static uint AddCarry(ref uint u1, uint u2, uint uCarry)
{
ulong uu = (ulong)u1 + u2 + uCarry;
u1 = (uint)uu;
return (uint)(uu >> kcbitUint);
}
private static uint SubBorrow(ref uint u1, uint u2, uint uBorrow)
{
ulong uu = (ulong)u1 - u2 - uBorrow;
u1 = (uint)uu;
return (uint)-(int)(uu >> kcbitUint);
}
private static uint SubRevBorrow(ref uint u1, uint u2, uint uBorrow)
{
ulong uu = (ulong)u2 - u1 - uBorrow;
u1 = (uint)uu;
return (uint)-(int)(uu >> kcbitUint);
}
private static uint MulCarry(ref uint u1, uint u2, uint uCarry)
{
// This is guaranteed not to overflow.
ulong uuRes = (ulong)u1 * u2 + uCarry;
u1 = (uint)uuRes;
return (uint)(uuRes >> kcbitUint);
}
private static uint AddMulCarry(ref uint uAdd, uint uMul1, uint uMul2, uint uCarry)
{
// This is guaranteed not to overflow.
ulong uuRes = (ulong)uMul1 * uMul2 + uAdd + uCarry;
uAdd = (uint)uuRes;
return (uint)(uuRes >> kcbitUint);
}
public static void GCD(ref BigIntegerBuilder reg1, ref BigIntegerBuilder reg2)
{
// Use Lehmer's GCD, with improvements, after eliminating common powers of 2.
if (reg1._iuLast > 0 && reg1._rgu[0] == 0 || reg2._iuLast > 0 && reg2._rgu[0] == 0)
{
int cbit1 = reg1.MakeOdd();
int cbit2 = reg2.MakeOdd();
LehmerGcd(ref reg1, ref reg2);
int cbitMin = Math.Min(cbit1, cbit2);
if (cbitMin > 0)
reg1.ShiftLeft(cbitMin);
}
else
LehmerGcd(ref reg1, ref reg2);
}
// This leaves the GCD in reg1 and trash in reg2.
// This uses Lehmer's method, with test due to Jebelean / Belnkiy and Vidunas.
// See Knuth, vol 2, page 345; Jebelean (1993) "Improving the Multiprecision Euclidean Algorithm";
// and Belenkiy & Vidunas (1998) "A Greatest Common Divisor Algorithm".
private static void LehmerGcd(ref BigIntegerBuilder reg1, ref BigIntegerBuilder reg2)
{
// This value has no real significance. Occassionally we want to subtract
// the two registers and keep the absolute value of the difference. To do
// so we need to pass a ref sign to Sub.
int signTmp = +1;
for (; ;)
{
reg1.AssertValid(true);
reg2.AssertValid(true);
int cuMax = reg1._iuLast + 1;
int cuMin = reg2._iuLast + 1;
if (cuMax < cuMin)
{
NumericsHelpers.Swap(ref reg1, ref reg2);
NumericsHelpers.Swap(ref cuMax, ref cuMin);
}
Contract.Assert(cuMax == reg1._iuLast + 1);
Contract.Assert(cuMin == reg2._iuLast + 1);
if (cuMin == 1)
{
if (cuMax == 1)
reg1._uSmall = NumericsHelpers.GCD(reg1._uSmall, reg2._uSmall);
else if (reg2._uSmall != 0)
reg1.Set(NumericsHelpers.GCD(Mod(ref reg1, reg2._uSmall), reg2._uSmall));
return;
}
if (cuMax == 2)
{
reg1.Set(NumericsHelpers.GCD(reg1.GetHigh2(2), reg2.GetHigh2(2)));
return;
}
if (cuMin <= cuMax - 2)
{
// reg1 is much larger than reg2, so just mod.
reg1.Mod(ref reg2);
continue;
}
ulong uu1 = reg1.GetHigh2(cuMax);
ulong uu2 = reg2.GetHigh2(cuMax);
Contract.Assert(uu1 != 0 && uu2 != 0);
int cbit = NumericsHelpers.CbitHighZero(uu1 | uu2);
if (cbit > 0)
{
uu1 = (uu1 << cbit) | (reg1._rgu[cuMax - 3] >> (kcbitUint - cbit));
// Note that [cuMax - 3] is correct, NOT [cuMin - 3].
uu2 = (uu2 << cbit) | (reg2._rgu[cuMax - 3] >> (kcbitUint - cbit));
}
if (uu1 < uu2)
{
NumericsHelpers.Swap(ref uu1, ref uu2);
NumericsHelpers.Swap(ref reg1, ref reg2);
}
// Make sure we don't overflow.
if (uu1 == ulong.MaxValue || uu2 == ulong.MaxValue)
{
uu1 >>= 1;
uu2 >>= 1;
}
Contract.Assert(uu1 >= uu2); // We ensured this above.
if (uu1 == uu2)
{
// The high bits are the same, so we don't know which
// is larger. No matter, just subtract one from the other
// and keep the absolute value of the result.
Contract.Assert(cuMax == cuMin);
reg1.Sub(ref signTmp, ref reg2);
Contract.Assert(reg1._iuLast < cuMin - 1);
continue;
}
if (NumericsHelpers.GetHi(uu2) == 0)
{
// reg1 is much larger than reg2, so just mod.
reg1.Mod(ref reg2);
continue;
}
// These are the coefficients to apply to reg1 and reg2 to get
// the new values, using: a * reg1 - b * reg2 and -c * reg1 + d * reg2.
uint a = 1, b = 0;
uint c = 0, d = 1;
for (; ;)
{
Contract.Assert(uu1 + a > a); // no overflow
Contract.Assert(uu2 + d > d);
Contract.Assert(uu1 > b);
Contract.Assert(uu2 > c);
Contract.Assert(uu2 + d <= uu1 - b);
uint uQuo = 1;
ulong uuNew = uu1 - uu2;
while (uuNew >= uu2 && uQuo < 32)
{
uuNew -= uu2;
uQuo++;
}
if (uuNew >= uu2)
{
ulong uuQuo = uu1 / uu2;
if (uuQuo > uint.MaxValue)
break;
uQuo = (uint)uuQuo;
uuNew = uu1 - uQuo * uu2;
}
ulong uuAdNew = a + (ulong)uQuo * c;
ulong uuBcNew = b + (ulong)uQuo * d;
if (uuAdNew > int.MaxValue || uuBcNew > int.MaxValue)
break;
// Jebelean / Belenkiy-Vidunas conditions
if (uuNew < uuBcNew || uuNew + uuAdNew > uu2 - c)
break;
Contract.Assert(uQuo == (uu1 + a - 1) / (uu2 - c));
Contract.Assert(uQuo == (uu1 - b) / (uu2 + d));
a = (uint)uuAdNew;
b = (uint)uuBcNew;
uu1 = uuNew;
if (uu1 <= b)
{
Contract.Assert(uu1 == b);
break;
}
Contract.Assert(uu1 + a > a); // no overflow
Contract.Assert(uu2 + d > d);
Contract.Assert(uu2 > c);
Contract.Assert(uu1 > b);
Contract.Assert(uu1 + a <= uu2 - c);
uQuo = 1;
uuNew = uu2 - uu1;
while (uuNew >= uu1 && uQuo < 32)
{
uuNew -= uu1;
uQuo++;
}
if (uuNew >= uu1)
{
ulong uuQuo = uu2 / uu1;
if (uuQuo > uint.MaxValue)
break;
uQuo = (uint)uuQuo;
uuNew = uu2 - uQuo * uu1;
}
uuAdNew = d + (ulong)uQuo * b;
uuBcNew = c + (ulong)uQuo * a;
if (uuAdNew > int.MaxValue || uuBcNew > int.MaxValue)
break;
// Jebelean / Belenkiy-Vidunas conditions
if (uuNew < uuBcNew || uuNew + uuAdNew > uu1 - b)
break;
Contract.Assert(uQuo == (uu2 + d - 1) / (uu1 - b));
Contract.Assert(uQuo == (uu2 - c) / (uu1 + a));
d = (uint)uuAdNew;
c = (uint)uuBcNew;
uu2 = uuNew;
if (uu2 <= c)
{
Contract.Assert(uu2 == c);
break;
}
}
if (b == 0)
{
Contract.Assert(a == 1 && c == 0 && d == 1);
Contract.Assert(uu1 > uu2); // We ensured this above.
if (uu1 / 2 >= uu2)
reg1.Mod(ref reg2);
else
reg1.Sub(ref signTmp, ref reg2);
}
else
{
// Replace reg1 with a * reg1 - b * reg2.
// Replace reg2 with -c * reg1 + d * reg2.
// Do everything mod cuMin uint's.
reg1.SetSizeKeep(cuMin, 0);
reg2.SetSizeKeep(cuMin, 0);
int nCarry1 = 0;
int nCarry2 = 0;
for (int iu = 0; iu < cuMin; iu++)
{
uint u1 = reg1._rgu[iu];
uint u2 = reg2._rgu[iu];
long nn1 = (long)u1 * a - (long)u2 * b + nCarry1;
long nn2 = (long)u2 * d - (long)u1 * c + nCarry2;
nCarry1 = (int)(nn1 >> kcbitUint);
nCarry2 = (int)(nn2 >> kcbitUint);
reg1._rgu[iu] = (uint)nn1;
reg2._rgu[iu] = (uint)nn2;
}
reg1.Trim();
reg2.Trim();
}
}
}
public int CbitLowZero()
{
AssertValid(true);
if (_iuLast == 0)
{
if ((_uSmall & 1) != 0 || _uSmall == 0)
return 0;
return NumericsHelpers.CbitLowZero(_uSmall);
}
int iuMin = 0;
while (_rgu[iuMin] == 0)
iuMin++;
int cbit = NumericsHelpers.CbitLowZero(_rgu[iuMin]);
return cbit + iuMin * kcbitUint;
}
// Shift right until the number is odd. Return the number of bits
// shifted. Asserts that the register is trimmed.
public int MakeOdd()
{
AssertValid(true);
int cbit = CbitLowZero();
if (cbit > 0)
ShiftRight(cbit);
return cbit;
}
private static readonly byte[] s_rgbInv = new byte[128] {
0x01, 0xAB, 0xCD, 0xB7, 0x39, 0xA3, 0xC5, 0xEF,
0xF1, 0x1B, 0x3D, 0xA7, 0x29, 0x13, 0x35, 0xDF,
0xE1, 0x8B, 0xAD, 0x97, 0x19, 0x83, 0xA5, 0xCF,
0xD1, 0xFB, 0x1D, 0x87, 0x09, 0xF3, 0x15, 0xBF,
0xC1, 0x6B, 0x8D, 0x77, 0xF9, 0x63, 0x85, 0xAF,
0xB1, 0xDB, 0xFD, 0x67, 0xE9, 0xD3, 0xF5, 0x9F,
0xA1, 0x4B, 0x6D, 0x57, 0xD9, 0x43, 0x65, 0x8F,
0x91, 0xBB, 0xDD, 0x47, 0xC9, 0xB3, 0xD5, 0x7F,
0x81, 0x2B, 0x4D, 0x37, 0xB9, 0x23, 0x45, 0x6F,
0x71, 0x9B, 0xBD, 0x27, 0xA9, 0x93, 0xB5, 0x5F,
0x61, 0x0B, 0x2D, 0x17, 0x99, 0x03, 0x25, 0x4F,
0x51, 0x7B, 0x9D, 0x07, 0x89, 0x73, 0x95, 0x3F,
0x41, 0xEB, 0x0D, 0xF7, 0x79, 0xE3, 0x05, 0x2F,
0x31, 0x5B, 0x7D, 0xE7, 0x69, 0x53, 0x75, 0x1F,
0x21, 0xCB, 0xED, 0xD7, 0x59, 0xC3, 0xE5, 0x0F,
0x11, 0x3B, 0x5D, 0xC7, 0x49, 0x33, 0x55, 0xFF
};
}
}
| 33.129202 | 139 | 0.416599 | [
"MIT"
] | nslottow/corefx | src/System.Runtime.Numerics/src/System/Numerics/BigIntegerBuilder.cs | 50,257 | C# |
using JetBrains.Annotations;
using JetBrains.ReSharper.PostfixTemplates.CodeCompletion;
using JetBrains.ReSharper.PostfixTemplates.Contexts.CSharp;
using JetBrains.ReSharper.PostfixTemplates.LookupItems;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.Psi.CSharp.Tree;
namespace JetBrains.ReSharper.PostfixTemplates.Templates.CSharp
{
// todo: return foo.Bar as T.par do not works (R# bug)
[PostfixTemplate(
templateName: "par",
description: "Parenthesizes current expression",
example: "(expr)")]
public class ParenthesizedExpressionTemplate : IPostfixTemplate<CSharpPostfixTemplateContext>
{
public PostfixTemplateInfo TryCreateInfo(CSharpPostfixTemplateContext context)
{
if (context.IsPreciseMode)
{
foreach (var expressionContext in context.Expressions)
{
var castExpression = CastExpressionNavigator.GetByOp(expressionContext.Expression);
if (castExpression == null) continue; // available in auto over cast expressions
var expression = ParenthesizedExpressionNavigator.GetByExpression(castExpression);
if (expression != null) continue; // not already parenthesized
return new PostfixTemplateInfo("par", expressionContext);
}
return null;
}
var expressions = CSharpPostfixUtis.FindExpressionWithValuesContexts(context);
if (expressions.Length != 0)
{
return new PostfixTemplateInfo("par", expressions);
}
return null;
}
public PostfixTemplateBehavior CreateBehavior(PostfixTemplateInfo info)
{
return new CSharpPostfixParenthsizedExpressionBehavior(info);
}
private sealed class CSharpPostfixParenthsizedExpressionBehavior : CSharpExpressionPostfixTemplateBehavior<ICSharpExpression>
{
public CSharpPostfixParenthsizedExpressionBehavior([NotNull] PostfixTemplateInfo info) : base(info) { }
protected override string ExpressionSelectTitle
{
get { return "Select expression to parenthesize"; }
}
protected override ICSharpExpression CreateExpression(CSharpElementFactory factory, ICSharpExpression expression)
{
return factory.CreateExpression("($0)", expression);
}
}
}
} | 34.830769 | 129 | 0.734541 | [
"MIT"
] | controlflow/resharper-postfix | PostfixTemplates/Templates/CSharp/ParenthesizedExpressionTemplate.cs | 2,266 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core.Pipeline;
using Azure.Core.TestFramework.Models;
using Azure.Core.Tests.TestFramework;
namespace Azure.Core.TestFramework
{
public class TestRecording : IAsyncDisposable
{
private const string RandomSeedVariableKey = "RandomSeed";
private const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
// cspell: disable-next-line
private const string charsLower = "abcdefghijklmnopqrstuvwxyz0123456789";
private const string Sanitized = "Sanitized";
internal const string DateTimeOffsetNowVariableKey = "DateTimeOffsetNow";
public SortedDictionary<string, string> Variables => _useLegacyTransport ? Session.Variables : _variables;
private SortedDictionary<string, string> _variables = new();
public TestRecording(RecordedTestMode mode, string sessionFile, RecordedTestSanitizer sanitizer, RecordMatcher matcher, TestProxy proxy = default, bool useLegacyTransport = false)
{
Mode = mode;
_sessionFile = sessionFile;
_sanitizer = sanitizer;
_matcher = matcher;
_useLegacyTransport = useLegacyTransport;
_proxy = proxy;
if (_useLegacyTransport)
{
switch (Mode)
{
case RecordedTestMode.Record:
Session = new RecordSession();
if (File.Exists(_sessionFile))
{
try
{
_previousSession = Load();
}
catch (Exception)
{
// ignore
}
}
break;
case RecordedTestMode.Playback:
try
{
Session = Load();
}
catch (Exception ex) when (ex is FileNotFoundException || ex is DirectoryNotFoundException)
{
MismatchException = new TestRecordingMismatchException(ex.Message, ex);
}
break;
}
}
}
internal async Task InitializeProxySettingsAsync()
{
if (_useLegacyTransport)
{
return;
}
switch (Mode)
{
case RecordedTestMode.Record:
var recordResponse = await _proxy.Client.StartRecordAsync(_sessionFile);
RecordingId = recordResponse.Headers.XRecordingId;
await AddProxySanitizersAsync();
break;
case RecordedTestMode.Playback:
ResponseWithHeaders<IReadOnlyDictionary<string, string>, TestProxyStartPlaybackHeaders> playbackResponse = null;
try
{
playbackResponse = await _proxy.Client.StartPlaybackAsync(_sessionFile);
}
catch (RequestFailedException ex)
when (ex.Status == 404)
{
MismatchException = new TestRecordingMismatchException(ex.Message, ex);
return;
}
_variables = new SortedDictionary<string, string>((Dictionary<string, string>)playbackResponse.Value);
RecordingId = playbackResponse.Headers.XRecordingId;
await AddProxySanitizersAsync();
// temporary until Azure.Core fix is shipped that makes HttpWebRequestTransport consistent with HttpClientTransport
// if (!_matcher.CompareBodies)
// {
// _proxy.Client.AddBodilessMatcher(RecordingId);
// }
var excludedHeaders = new List<string>(_matcher.LegacyExcludedHeaders)
{
"Content-Type",
"Content-Length"
};
// temporary until custom matcher supports both excluded and ignored
excludedHeaders.AddRange(_matcher.IgnoredHeaders);
await _proxy.Client.AddCustomMatcherAsync(new CustomDefaultMatcher(string.Join(",", excludedHeaders), _matcher.CompareBodies),
RecordingId);
break;
}
}
private async Task AddProxySanitizersAsync()
{
foreach (string header in _sanitizer.SanitizedHeaders)
{
await _proxy.Client.AddHeaderSanitizerAsync(new HeaderRegexSanitizer(header, Sanitized), RecordingId);
}
foreach (string jsonPath in _sanitizer.JsonPathSanitizers.Select(s => s.JsonPath))
{
await _proxy.Client.AddBodyKeySanitizerAsync(new BodyKeySanitizer(Sanitized) { JsonPath = jsonPath }, RecordingId);
}
foreach (UriRegexSanitizer sanitizer in _sanitizer.UriRegexSanitizers)
{
await _proxy.Client.AddUriSanitizerAsync(sanitizer, RecordingId);
}
foreach (BodyKeySanitizer sanitizer in _sanitizer.BodyKeySanitizers)
{
await _proxy.Client.AddBodyKeySanitizerAsync(sanitizer, RecordingId);
}
foreach (BodyRegexSanitizer sanitizer in _sanitizer.BodyRegexSanitizers)
{
await _proxy.Client.AddBodyRegexSanitizerAsync(sanitizer, RecordingId);
}
}
public RecordedTestMode Mode { get; }
private readonly AsyncLocal<EntryRecordModel> _disableRecording = new AsyncLocal<EntryRecordModel>();
private readonly string _sessionFile;
private readonly RecordedTestSanitizer _sanitizer;
private readonly RecordMatcher _matcher;
private RecordSession _sessionInternal;
private RecordSession Session
{
get
{
return MismatchException switch
{
null => _sessionInternal,
_ => throw MismatchException
};
}
set
{
_sessionInternal = value;
}
}
internal TestRecordingMismatchException MismatchException;
private RecordSession _previousSession;
private TestRandom _random;
public TestRandom Random
{
get
{
if (_random == null)
{
switch (Mode)
{
case RecordedTestMode.Live:
#if NET6_0_OR_GREATER
var liveSeed = RandomNumberGenerator.GetInt32(int.MaxValue);
#else
var csp = new RNGCryptoServiceProvider();
var bytes = new byte[4];
csp.GetBytes(bytes);
var liveSeed = BitConverter.ToInt32(bytes, 0);
#endif
_random = new TestRandom(Mode, liveSeed);
break;
case RecordedTestMode.Record:
// Try get the seed from existing session
if (!(_previousSession != null &&
_previousSession.Variables.TryGetValue(RandomSeedVariableKey, out string seedString) &&
int.TryParse(seedString, out int seed)
))
{
_random = new TestRandom(Mode);
seed = _random.Next();
}
Variables[RandomSeedVariableKey] = seed.ToString();
_random = new TestRandom(Mode, seed);
break;
case RecordedTestMode.Playback:
if (IsTrack1SessionRecord())
{
//random is not really used for track 1 playback, so randomly pick one as seed
_random = new TestRandom(Mode, (int)DateTime.UtcNow.Ticks);
}
else
{
_random = new TestRandom(Mode, int.Parse(Variables[RandomSeedVariableKey]));
}
break;
default:
throw new ArgumentOutOfRangeException();
}
}
return _random;
}
}
/// <summary>
/// The moment in time that this test is being run.
/// </summary>
private DateTimeOffset? _now;
private readonly bool _useLegacyTransport;
private readonly TestProxy _proxy;
public string RecordingId { get; private set; }
/// <summary>
/// Gets the moment in time that this test is being run. This is useful
/// for any test recordings that capture the current time.
/// </summary>
public DateTimeOffset Now
{
get
{
if (_now == null)
{
switch (Mode)
{
case RecordedTestMode.Live:
_now = DateTimeOffset.Now;
break;
case RecordedTestMode.Record:
// While we can cache DateTimeOffset.Now for playing back tests,
// a number of auth mechanisms are time sensitive and will require
// values in the present when re-recording
_now = DateTimeOffset.Now;
Variables[DateTimeOffsetNowVariableKey] = _now.Value.ToString("O"); // Use the "Round-Trip Format"
break;
case RecordedTestMode.Playback:
_now = DateTimeOffset.Parse(Variables[DateTimeOffsetNowVariableKey]);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
return _now.Value;
}
}
/// <summary>
/// Gets the moment in time that this test is being run in UTC format.
/// This is useful for any test recordings that capture the current time.
/// </summary>
public DateTimeOffset UtcNow => Now.ToUniversalTime();
private RecordSession Load()
{
using FileStream fileStream = File.OpenRead(_sessionFile);
using JsonDocument jsonDocument = JsonDocument.Parse(fileStream);
return RecordSession.Deserialize(jsonDocument.RootElement);
}
public async ValueTask DisposeAsync(bool save)
{
if (_useLegacyTransport)
{
if (Mode == RecordedTestMode.Record && save && !Session.IsEmpty)
{
var directory = Path.GetDirectoryName(_sessionFile);
Directory.CreateDirectory(directory);
Session.Sanitize(_sanitizer);
using FileStream fileStream = File.Create(_sessionFile);
var utf8JsonWriter = new Utf8JsonWriter(fileStream, new JsonWriterOptions()
{
Indented = true
});
Session.Serialize(utf8JsonWriter);
utf8JsonWriter.Flush();
}
}
else if (Mode == RecordedTestMode.Record && save)
{
await _proxy.Client.StopRecordAsync(RecordingId, Variables);
}
}
public async ValueTask DisposeAsync()
{
await DisposeAsync(true);
}
public HttpPipelineTransport CreateTransport(HttpPipelineTransport currentTransport)
{
if (!_useLegacyTransport && Mode != RecordedTestMode.Live)
{
return new ProxyTransport(_proxy, currentTransport, this, () => _disableRecording.Value);
}
return Mode switch
{
RecordedTestMode.Live => currentTransport,
RecordedTestMode.Record => new RecordTransport(Session, currentTransport, entry => _disableRecording.Value, Random),
RecordedTestMode.Playback => new PlaybackTransport(Session, _matcher, _sanitizer, Random,
entry => _disableRecording.Value == EntryRecordModel.RecordWithoutRequestBody),
_ => throw new ArgumentOutOfRangeException(nameof(Mode), Mode, null),
};
}
public string GenerateId()
{
return Random.Next().ToString();
}
public string GenerateAlphaNumericId(string prefix, int? maxLength = null, bool useOnlyLowercase = false)
{
var stringChars = new char[8];
for (int i = 0; i < stringChars.Length; i++)
{
if (useOnlyLowercase)
{
stringChars[i] = charsLower[Random.Next(charsLower.Length)];
}
else
{
stringChars[i] = chars[Random.Next(chars.Length)];
}
}
var finalString = new string(stringChars);
if (maxLength.HasValue)
{
return $"{prefix}{finalString}".Substring(0, maxLength.Value);
}
else
{
return $"{prefix}{finalString}";
}
}
public string GenerateId(string prefix, int maxLength)
{
var id = $"{prefix}{Random.Next()}";
return id.Length > maxLength ? id.Substring(0, maxLength) : id;
}
public string GenerateAssetName(string prefix, [CallerMemberName] string callerMethodName = "testframework_failed")
{
if (Mode == RecordedTestMode.Playback && IsTrack1SessionRecord())
{
return Session.Names[callerMethodName].Dequeue();
}
else
{
return prefix + Random.Next(9999);
}
}
public bool IsTrack1SessionRecord()
{
return Session?.Entries.FirstOrDefault()?.IsTrack1Recording ?? false;
}
public string GetVariable(string variableName, string defaultValue, Func<string, string> sanitizer = default)
{
switch (Mode)
{
case RecordedTestMode.Record:
Variables[variableName] = sanitizer == default ? defaultValue : sanitizer.Invoke(defaultValue);
return defaultValue;
case RecordedTestMode.Live:
return defaultValue;
case RecordedTestMode.Playback:
Variables.TryGetValue(variableName, out string value);
return value;
default:
throw new ArgumentOutOfRangeException();
}
}
public void SetVariable(string variableName, string value, Func<string, string> sanitizer = default)
{
switch (Mode)
{
case RecordedTestMode.Record:
Variables[variableName] = sanitizer == default ? value : sanitizer.Invoke(value);
break;
default:
break;
}
}
public void DisableIdReuse()
{
_previousSession = null;
}
public bool HasRequests => _sessionInternal?.Entries.Count > 0;
public DisableRecordingScope DisableRecording()
{
return new DisableRecordingScope(this, EntryRecordModel.DoNotRecord);
}
public DisableRecordingScope DisableRequestBodyRecording()
{
return new DisableRecordingScope(this, EntryRecordModel.RecordWithoutRequestBody);
}
public struct DisableRecordingScope : IDisposable
{
private readonly TestRecording _testRecording;
public DisableRecordingScope(TestRecording testRecording, EntryRecordModel entryRecordModel)
{
_testRecording = testRecording;
_testRecording._disableRecording.Value = entryRecordModel;
}
public void Dispose()
{
_testRecording._disableRecording.Value = EntryRecordModel.Record;
}
}
}
}
| 37.839827 | 187 | 0.518877 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/core/Azure.Core.TestFramework/src/TestRecording.cs | 17,484 | C# |
using HotChocolate;
using HotChocolate.Types;
using Microsoft.Extensions.Localization;
using System.Linq;
using TH.POST.Address.Domain.Entities;
using TH.POST.Address.Persistence.Context;
namespace TH.POST.Address.SQLServer.GraphQL.Features.Provinces
{
public class ProvinceType : ObjectType<ProvinceEntity>
{
private readonly IStringLocalizer<ProvinceType> _localizer;
public ProvinceType(IStringLocalizer<ProvinceType> localizer) : base()
{
_localizer = localizer;
}
protected override void Configure(IObjectTypeDescriptor<ProvinceEntity> descriptor)
{
descriptor.Description(_localizer["Represents any province"]);
descriptor
.Field(c => c.Id)
.Description(_localizer["Represents the unique ID for the province"]);
descriptor
.Field(c => c.Code)
.Description(_localizer["Represents the code for the province"]);
descriptor
.Field(c => c.NameTH)
.Description(_localizer["Represents the name thai for the province"]);
descriptor
.Field(c => c.NameEN)
.Description(_localizer["Represents the name english for the province"]);
descriptor
.Field(c => c.GeographyId)
.Description(_localizer["Represents the unique ID of the geography which the province"]);
descriptor
.Field(c => c.Geography)
.ResolveWith<Resolvers>(c => c.GetGeography(default!, default!))
.UseDbContext<AppSQLServerContext>()
.Description(_localizer["This is the geography to which the province"]);
descriptor
.Field(p => p.Amphures)
.ResolveWith<Resolvers>(p => p.GetAmphures(default!, default!))
.UseDbContext<AppSQLServerContext>()
.Description(_localizer["This is the list of amphur for this province"]);
}
private class Resolvers
{
public GeographyEntity GetGeography(ProvinceEntity province, [ScopedService] AppSQLServerContext context)
{
return context.Geographies.FirstOrDefault(p => p.Id == province.GeographyId);
}
public IQueryable<AmphurEntity> GetAmphures(ProvinceEntity province, [ScopedService] AppSQLServerContext context)
{
return context.Amphures.Where(p => p.ProvinceId == province.Id);
}
}
}
}
| 36.928571 | 125 | 0.608511 | [
"MIT"
] | WutXoXo/graph-post-addr-th | src/WebGraphQL/TH.POST.Address.SQLServer.GraphQL/Features/Provinces/ProvinceType.cs | 2,587 | C# |
#region Apache Notice
/*****************************************************************************
* $Revision: 374175 $
* $LastChangedDate: 2006-04-25 19:40:27 +0200 (mar., 25 avr. 2006) $
* $LastChangedBy: gbayon $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2006/2005 - The Apache Software Foundation
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
********************************************************************************/
#endregion
using System.Collections;
using System.Data;
using IBatisNet.DataMapper.Scope;
namespace IBatisNet.DataMapper.MappedStatements.ResultStrategy
{
/// <summary>
/// <see cref="IResultStrategy"/> implementation when
/// a 'resultClass' attribute is specified.
/// </summary>
public sealed class ResultClassStrategy : IResultStrategy
{
private static IResultStrategy _simpleTypeStrategy = null;
private static IResultStrategy _dictionaryStrategy = null;
private static IResultStrategy _listStrategy = null;
private static IResultStrategy _autoMapStrategy = null;
/// <summary>
/// Initializes a new instance of the <see cref="ResultClassStrategy"/> class.
/// </summary>
public ResultClassStrategy()
{
_simpleTypeStrategy = new SimpleTypeStrategy();
_dictionaryStrategy = new DictionaryStrategy();
_listStrategy = new ListStrategy();
_autoMapStrategy = new AutoMapStrategy();
}
#region IResultStrategy Members
/// <summary>
/// Processes the specified <see cref="IDataReader"/>.
/// </summary>
/// <param name="request">The request.</param>
/// <param name="reader">The reader.</param>
/// <param name="resultObject">The result object.</param>
public object Process(RequestScope request, ref IDataReader reader, object resultObject)
{
// Check if the ResultClass is a 'primitive' Type
if (request.DataExchangeFactory.TypeHandlerFactory.IsSimpleType(request.CurrentResultMap.Class))
{
return _simpleTypeStrategy.Process(request, ref reader, resultObject);
}
else if (typeof(IDictionary).IsAssignableFrom(request.CurrentResultMap.Class))
{
return _dictionaryStrategy.Process(request, ref reader, resultObject);
}
else if (typeof(IList).IsAssignableFrom(request.CurrentResultMap.Class))
{
return _listStrategy.Process(request, ref reader, resultObject);
}
else
{
return _autoMapStrategy.Process(request, ref reader, resultObject);
}
}
#endregion
}
}
| 38.162791 | 108 | 0.619744 | [
"Apache-2.0"
] | chookrib/Castle.Facilities.IBatisNet | src/IBatisNet.DataMapper/MappedStatements/ResultStrategy/ResultClassStrategy.cs | 3,282 | C# |
//
// LocalStream.cs
//
// Authors:
// Alan McGovern [email protected]
//
// Copyright (C) 2020 Alan McGovern
//
// 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.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MonoTorrent.Client;
using MonoTorrent.Client.PiecePicking;
namespace MonoTorrent.Streaming
{
/// <summary>
/// A seekable Stream which can be used to access a <see cref="TorrentFile"/> while it is downloading.
/// If the stream seeks to a location which hasn't been downloaded yet, <see cref="Read(byte[], int, int)"/>
/// will block until the data is available. <see cref="ReadAsync(byte[], int, int, CancellationToken)"/>
/// will perform a non-blocking wait for the data.
/// </summary>
class LocalStream : Stream
{
long position;
public override bool CanRead => true;
public override bool CanSeek => true;
public override bool CanWrite => false;
internal bool Disposed { get; private set; }
public override long Length => File.Length;
public override long Position {
get => position;
set => Seek (value, SeekOrigin.Begin);
}
ITorrentFileInfo File { get; }
TorrentManager Manager { get; }
IStreamingPieceRequester Picker { get; }
public LocalStream (TorrentManager manager, ITorrentFileInfo file, IStreamingPieceRequester picker)
{
Manager = manager;
File = file;
Picker = picker;
}
protected override void Dispose (bool disposing)
{
base.Dispose (disposing);
Disposed = true;
}
public override void Flush ()
=> throw new NotSupportedException ();
public override int Read (byte[] buffer, int offset, int count)
=> ReadAsync (buffer, offset, count, CancellationToken.None).GetAwaiter ().GetResult ();
public override async Task<int> ReadAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
ThrowIfDisposed ();
// The torrent is treated as one big block of data, so this is the offset at which the current file's data starts at.
var torrentFileStartOffset = File.OffsetInTorrent;
// Clamp things so we cannot overread.
if (Position + count > Length)
count = (int) (Length - Position);
// We've reached the end of the file, so return 0 to indicate EOF.
if (count == 0)
return 0;
// Take our current position into account when calculating the start/end pieces of the data we're reading.
var startPiece = Manager.ByteOffsetToPieceIndex (torrentFileStartOffset + Position);
var endPiece = Math.Min (File.EndPieceIndex, Manager.ByteOffsetToPieceIndex (torrentFileStartOffset + Position + count));
while (Manager.State != TorrentState.Stopped && Manager.State != TorrentState.Error) {
bool allAvailable = true;
for (int i = startPiece; i <= endPiece && allAvailable; i++)
allAvailable &= Manager.Bitfield[i];
if (allAvailable)
break;
await Task.Delay (100, cancellationToken).ConfigureAwait (false);
ThrowIfDisposed ();
}
cancellationToken.ThrowIfCancellationRequested ();
// Flush any pending data.
await Manager.Engine.DiskManager.FlushAsync (Manager, startPiece, endPiece);
if (!await Manager.Engine.DiskManager.ReadAsync (File, Position, buffer, offset, count).ConfigureAwait (false))
throw new InvalidOperationException ("Could not read the requested data from the torrent");
ThrowIfDisposed ();
position += count;
Picker.ReadToPosition (File, position);
return count;
}
public override long Seek (long offset, SeekOrigin origin)
{
ThrowIfDisposed ();
long newPosition;
switch (origin) {
case SeekOrigin.Begin:
newPosition = offset;
break;
case SeekOrigin.Current:
newPosition = position + offset;
break;
case SeekOrigin.End:
newPosition = Length + offset;
break;
default:
throw new NotSupportedException ();
}
// Clamp it to within reasonable bounds.
newPosition = Math.Max (0, newPosition);
newPosition = Math.Min (newPosition, Length);
if (newPosition != position) {
position = newPosition;
Picker.SeekToPosition (File, newPosition);
}
return position;
}
public override void SetLength (long value)
=> throw new NotSupportedException ();
public override void Write (byte[] buffer, int offset, int count)
=> throw new NotSupportedException ();
void ThrowIfDisposed ()
{
if (Disposed)
throw new ObjectDisposedException (nameof (LocalStream));
}
}
}
| 36.117978 | 133 | 0.614403 | [
"MIT"
] | OneFingerCodingWarrior/monotorrent | src/MonoTorrent/MonoTorrent.Streaming/LocalStream.cs | 6,431 | C# |
namespace WebhookClient.Services;
public class WebhooksClient : IWebhooksClient
{
#region Fields
private readonly IHttpClientFactory _httpClientFactory;
private readonly Settings _settings;
#endregion
#region Ctor
public WebhooksClient(IHttpClientFactory httpClientFactory,
IOptions<Settings> settings)
{
_httpClientFactory = httpClientFactory;
_settings = settings.Value;
}
#endregion
#region Methods
public async Task<IEnumerable<WebhookResponse>> LoadWebhooks()
{
var client = _httpClientFactory.CreateClient("GrantClient");
var response = await client.GetAsync(_settings.WebhooksUrl + "/api/v1/webhooks");
var json = await response.Content.ReadAsStringAsync();
var subscriptions = JsonSerializer.Deserialize<IEnumerable<WebhookResponse>>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
return subscriptions;
}
#endregion
}
| 26.578947 | 116 | 0.69901 | [
"MIT"
] | dogaanismail/eCommerceOnContainer | src/Web/WebhookClient/Services/WebhooksClient.cs | 1,012 | C# |
using System;
using Microsoft.Maui.Handlers;
using Microsoft.Maui;
namespace Comet.Handlers
{
public partial class NavigationViewHandler: ViewHandler<ShapeView, object>
{
protected override object CreateNativeView() => throw new NotImplementedException();
}
}
| 22.416667 | 86 | 0.788104 | [
"MIT"
] | Clancey/Comet | src/Comet/Handlers/Navigation/NavigationViewHandler.Standard.cs | 271 | C# |
using System;
using System.Collections.Generic;
using Monodoc;
using Mono.Options;
namespace Mono.Documentation {
class MDocTreeDumper : MDocCommand {
public override void Run (IEnumerable<string> args)
{
var validFormats = RootTree.GetSupportedFormats ();
string cur_format = "";
var formats = new Dictionary<string, List<string>> ();
var options = new OptionSet () {
{ "f|format=",
"The documentation {FORMAT} used in FILES. " +
"Valid formats include:\n " +
string.Join ("\n ", validFormats) + "\n" +
"If not specified, no HelpSource is used. This may " +
"impact the PublicUrls displayed for nodes.",
v => {
if (Array.IndexOf (validFormats, v) < 0)
Error ("Invalid documentation format: {0}.", v);
cur_format = v;
} },
{ "<>", v => AddFormat (formats, cur_format, v) },
};
List<string> files = Parse (options, args, "dump-tree",
"[OPTIONS]+ FILES",
"Print out the nodes within the assembled .tree FILES,\n" +
"as produced by 'mdoc assemble'.");
if (files == null)
return;
foreach (string format in formats.Keys) {
foreach (string file in formats [format]) {
HelpSource hs = format == ""
? null
: RootTree.GetHelpSource (format, file.Replace (".tree", ""));
Tree t = new Tree (hs, file);
Node.PrintTree (t);
}
}
}
private void AddFormat (Dictionary<string, List<string>> d, string format, string file)
{
if (format == null)
format = "";
List<string> l;
if (!d.TryGetValue (format, out l)) {
l = new List<string> ();
d.Add (format, l);
}
l.Add (file);
}
}
}
| 27.229508 | 89 | 0.599639 | [
"Apache-2.0"
] | CRivlaldo/mono | mcs/tools/mdoc/Mono.Documentation/dump.cs | 1,661 | C# |
using Aspose.Cells.Common.Models.DTO.SEOApi;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Aspose.Cells.Common.Services
{
public class FileFormatService : BaseApiCacheService
{
public async Task<FileFormat> GetFromLocal(string extension)
{
var jsonFilePath = Path.Combine(AppContext.BaseDirectory, "App_Data/file_format.json");
using (var sr = new StreamReader(jsonFilePath))
{
var json = await sr.ReadToEndAsync();
var formats = JsonConvert.DeserializeObject<Dictionary<string, FileFormat>>(json);
return formats.Keys.Contains(extension) ? formats[extension] : null;
}
}
public async Task<Dictionary<string, FileFormat>> GetAllFromLocal()
{
var jsonFilePath = Path.Combine(AppContext.BaseDirectory, "App_Data/file_format.json");
using (var sr = new StreamReader(jsonFilePath))
{
var json = await sr.ReadToEndAsync();
return JsonConvert.DeserializeObject<Dictionary<string, FileFormat>>(json);
}
}
public FileFormat GetCached(string extension) => GetCached(FileFormats, extension, async () => await GetFromLocal(extension));
private static readonly Dictionary<string, FileFormat> FileFormats = new Dictionary<string, FileFormat>();
}
} | 38.282051 | 134 | 0.659745 | [
"MIT"
] | aspose-cells/Aspose.Cells-for-.NET | Demos/Apps/Aspose.Cells.Common/Services/FileFormatService.cs | 1,493 | C# |
namespace Root.Coding.Code.Models.E01D.Core.Reflection.Emit.DelegateFactories
{
public abstract class ReflectionDelegateFactory
{
public abstract Root.Coding.Code.Enums.E01D.Core.Reflection.Emit.DelegateFactories.ReflectionDelegateFactoryKind Kind { get; }
}
}
| 35.375 | 135 | 0.777385 | [
"Apache-2.0"
] | E01D/Base | src/E01D.Base.Clr.DotNet.Emit.Models/Coding/Code/Models/E01D/Base/Reflection/Emit/DelegateFactories/ReflectionDelegateFactory.cs | 285 | C# |
// MonoGame - Copyright (C) The MonoGame Team
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
using System;
using System.Collections.Generic;
namespace MonoGame.Tools.Pipeline
{
public interface IContentItemObserver
{
void OnItemModified(ContentItem item);
}
public interface IController : IContentItemObserver
{
/// <summary>
/// Types of content which can be created and added to a project.
/// </summary>
IEnumerable<ContentItemTemplate> Templates { get; }
List<IProjectItem> SelectedItems { get; }
IProjectItem SelectedItem { get; }
PipelineProject ProjectItem { get; }
/// <summary>
/// True if there is a project.
/// </summary>
bool ProjectOpen { get; }
/// <summary>
/// True if the project has unsaved changes.
/// </summary>
bool ProjectDirty { get; }
/// <summary>
/// True if the project is actively building.
/// </summary>
bool ProjectBuilding { get; }
/// <summary>
/// The view this controller is attached to.
/// </summary>
IView View { get; }
/// <summary>
/// Triggered when the project starts loading.
/// </summary>
event Action OnProjectLoading;
/// <summary>
/// Triggered when the project finishes loading.
/// </summary>
event Action OnProjectLoaded;
/// <summary>
/// Notify controller that a property of Project or its contents has been modified.
/// </summary>
void OnProjectModified();
/// <summary>
/// Notify controller that Project.References has been modified.
/// </summary>
void OnReferencesModified();
void NewProject();
void ImportProject();
void OpenProject();
void OpenProject(string projectFilePath);
void ClearRecentList();
void CloseProject();
bool SaveProject(bool saveAs);
void Build(bool rebuild);
void RebuildItems();
void Clean();
void CancelBuild();
bool Exit();
#region ContentItem
void DragDrop(string initialDirectory, string[] folders, string[] files);
void Include();
void IncludeFolder();
void Exclude(bool delete);
void NewItem();
void NewFolder();
void Rename();
void AddAction(IProjectAction action);
void SelectionChanged(List<IProjectItem> items);
IProjectItem GetItem(string originalPath);
void CopyAssetPath();
#endregion
#region Undo, Redo
bool CanRedo { get; }
bool CanUndo { get; }
void Undo();
void Redo();
#endregion
string GetFullPath(string filePath);
string GetRelativePath(string filePath);
}
}
| 22.355556 | 91 | 0.576209 | [
"MIT"
] | Gitspathe/MonoGame | Tools/MonoGame.Content.Builder.Editor/Common/IController.cs | 3,018 | C# |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace Senai.Optus.WebApi.Domains
{
public partial class OptusContext : DbContext
{
public OptusContext()
{
}
public OptusContext(DbContextOptions<OptusContext> options)
: base(options)
{
}
public virtual DbSet<Artistas> Artistas { get; set; }
public virtual DbSet<Estilos> Estilos { get; set; }
public virtual DbSet<Usuarios> Usuarios { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer("Data Source=.\\SqlExpress; Initial Catalog=T_Optus;User Id=sa;Pwd=132");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Artistas>(entity =>
{
entity.HasKey(e => e.IdArtista);
entity.HasIndex(e => e.Nome)
.HasName("UQ__Artistas__7D8FE3B2217AA8FE")
.IsUnique();
entity.Property(e => e.Nome)
.HasMaxLength(200)
.IsUnicode(false);
entity.HasOne(d => d.IdEstiloNavigation)
.WithMany(p => p.Artistas)
.HasForeignKey(d => d.IdEstilo)
.HasConstraintName("FK__Artistas__IdEsti__4D94879B");
});
modelBuilder.Entity<Estilos>(entity =>
{
entity.HasKey(e => e.IdEstilo);
entity.HasIndex(e => e.Nome)
.HasName("UQ__Estilos__7D8FE3B2618AC6B4")
.IsUnique();
entity.Property(e => e.Nome)
.IsRequired()
.HasMaxLength(200)
.IsUnicode(false);
});
modelBuilder.Entity<Usuarios>(entity =>
{
entity.HasKey(e => e.IdUsuario);
entity.HasIndex(e => e.Email)
.HasName("UQ__Usuarios__A9D105344A3A8656")
.IsUnique();
entity.Property(e => e.Email)
.IsRequired()
.HasMaxLength(255)
.IsUnicode(false);
entity.Property(e => e.Permissao)
.IsRequired()
.HasMaxLength(255)
.IsUnicode(false);
entity.Property(e => e.Senha)
.IsRequired()
.HasMaxLength(255)
.IsUnicode(false);
});
}
}
}
| 32.703297 | 213 | 0.517809 | [
"MIT"
] | jv-soncini/Exercicios-API | Optus/Senai.Optus.WebApi/Senai.Optus.WebApi/Contexts/OptusContext.cs | 2,978 | C# |
namespace OPS.Core.DTO
{
public class FiltroDenunciaDTO
{
public string sorting { get; set; }
public int count { get; set; }
public int page { get; set; }
public bool MensagensNaoLidas { get; set; }
public bool AguardandoRevisao { get; set; }
public bool PendenteInformacao { get; set; }
public bool Duvidoso { get; set; }
public bool Dossie { get; set; }
public bool Repetido { get; set; }
public bool NaoProcede { get; set; }
public FiltroDenunciaDTO()
{
this.count = 100;
this.page = 1;
}
}
}
| 26.625 | 52 | 0.549296 | [
"Apache-2.0"
] | VanderleiDenir/operacao-politica-supervisionada | OPS.Core/DTO/FiltroDenunciaDTO.cs | 641 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.