content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Web.Http; using API.WindowsService.Filters; using API.WindowsService.Models; using Contract; namespace API.WindowsService.Controllers { [ApiAuthorization] public class JobController : ApiController { private readonly IJobRepository _repository; private readonly ILogging _logging; public JobController(IJobRepository repository, ILogging logging) { if (repository == null) throw new ArgumentNullException(nameof(repository)); if (logging == null) throw new ArgumentNullException(nameof(logging)); _repository = repository; _logging = logging; } [HttpDelete] public bool DeleteJob(Guid jobCorrelationId) { if (jobCorrelationId == Guid.Empty) throw new ArgumentOutOfRangeException(nameof(jobCorrelationId), "Specified jobCorrelationId is invalid"); var res = _repository.DeleteJob(jobCorrelationId); if (res) _logging.Info($"Job {jobCorrelationId} deleted"); else _logging.Warn($"Failed to delete job {jobCorrelationId}"); return res; } [HttpPatch] public bool PatchJob(Guid jobCorrelationId, Command command) { if (jobCorrelationId == Guid.Empty) throw new ArgumentOutOfRangeException(nameof(jobCorrelationId), "Specified jobCorrelationId is invalid"); bool res; switch (command) { case Command.Pause: res = _repository.PauseJob(jobCorrelationId); break; case Command.Resume: res = _repository.ResumeJob(jobCorrelationId); break; case Command.Cancel: res = _repository.CancelJob(jobCorrelationId); break; case Command.Unknown: default: throw new ArgumentOutOfRangeException(nameof(command), $"unsupported {command}", nameof(command)); } if (res) _logging.Info($"Recived valid {command} order for job {jobCorrelationId}."); else _logging.Warn($"Recived invalid {command} order for job {jobCorrelationId}."); return res; } } }
35.294118
121
0.583333
[ "BSD-3-Clause" ]
drdk/ffmpeg-farm
ffmpeg-farm-server/API.WindowsService/Controllers/JobController.cs
2,402
C#
using RestIdentity.DataAccess.Models; namespace RestIdentity.DataAccess.Repositories; public interface IUserAvatarsRepository { string CreateAvatarHashForUser(string userId); string CreateAvatarHashForUser(UserRecord user); Task<UserAvatarRecord?> FindByUserIdAsync(string userId); Task<UserAvatarRecord?> FindByUserNameAsync(string userName); Task<UserAvatarRecord?> FindByAvatarHashAsync(string avatarHash); Task<UserAvatarRecord> AddUserAvatarAsync(UserRecord user); Task<UserAvatarRecord> AddOrUpdateUserAvatarAsync(UserRecord user); Task<UserAvatarRecord?> UpdateUserAvatarAsync(UserRecord user); Task<UserAvatarRecord?> UseDefaultAvatarForUserAsync(string userId); Task<UserAvatarRecord?> UseAvatarForUserAsync(string userId, string imageExtension); }
38.285714
88
0.81592
[ "MIT" ]
Abooow/RestIdentity
src/RestIdentity.DataAccess/Repositories/IUserAvatarsRepository.cs
806
C#
using System.Collections.Generic; using System.Threading.Tasks; using SendGrid.Helpers.Mail; namespace AppLensV3.Services { /// <summary> /// Empty email notification service. /// </summary> public class NullableEmailNotificationService : IEmailNotificationService { /// <inheritdoc/> public Task SendPublishingAlert(string alias, string detectorId, string link, List<EmailAddress> tos) { return Task.FromResult(true); } } }
26.052632
109
0.674747
[ "MIT" ]
solankisamir/Azure-AppServices-Diagnostics-Portal
ApplensBackend/Services/EmailNotificationService/NullableEmailNotificationService.cs
497
C#
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using DataGridControl = System.Windows.Controls.DataGrid; using ActiproSoftware.Windows.Media; namespace ActiproSoftware.Windows.Controls.DataGrid { /// <summary> /// Provides attached behavior for <see cref="DataGridControl"/> controls to track the selection. /// </summary> public static class SelectionBehavior { #region Dependency Property Keys /// <summary> /// Identifies the <c>IsSelectedHeader</c> dependency property key. This field is read-only. /// </summary> /// <value>The identifier for the <c>IsSelectedHeader</c> dependency property key.</value> private static readonly DependencyPropertyKey IsSelectedHeaderPropertyKey = DependencyProperty.RegisterAttachedReadOnly("IsSelectedHeader", typeof(bool), typeof(SelectionBehavior), new FrameworkPropertyMetadata(false)); #endregion // Dependency Property Keys #region Dependency Properties /// <summary> /// Identifies the <c>IsSelectedHeader</c> attached dependency property. This field is read-only. /// </summary> /// <value>The identifier for the <c>IsSelectedHeader</c> attached dependency property.</value> public static readonly DependencyProperty IsSelectedHeaderProperty = IsSelectedHeaderPropertyKey.DependencyProperty; /// <summary> /// Identifies the <c>TrackingModes</c> attached dependency property. This field is read-only. /// </summary> /// <value>The identifier for the <c>TrackingModes</c> attached dependency property.</value> public static readonly DependencyProperty TrackingModesProperty = DependencyProperty.RegisterAttached("TrackingModes", typeof(SelectionTrackingModes), typeof(SelectionBehavior), new FrameworkPropertyMetadata(SelectionTrackingModes.None, OnTrackingModesPropertyValueChanged)); #endregion // Dependency Properties ///////////////////////////////////////////////////////////////////////////////////////////////////// #region NON-PUBLIC PROCEDURES ///////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Handles the <c>SelectedCellsChanged</c> event of a <see cref="DataGridControl"/>. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <c>SelectedCellsChangedEventArgs</c> instance containing the event data.</param> private static void OnDatagridSelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e) { UpdateSelectedHeaders(sender as DataGridControl); } /// <summary> /// Called when <see cref="TrackingModesProperty"/> is changed. /// </summary> /// <param name="d">The dependency object that was changed.</param> /// <param name="e">The <see cref="DependencyPropertyChangedEventArgs"/> instance containing the event data.</param> private static void OnTrackingModesPropertyValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { DataGridControl datagrid = d as DataGridControl; if (null == datagrid) return; SelectionTrackingModes trackingModes = (SelectionTrackingModes)e.NewValue; if (SelectionTrackingModes.None != trackingModes) datagrid.SelectedCellsChanged += new SelectedCellsChangedEventHandler(OnDatagridSelectedCellsChanged); else datagrid.SelectedCellsChanged -= new SelectedCellsChangedEventHandler(OnDatagridSelectedCellsChanged); UpdateSelectedHeaders(datagrid); } /// <summary> /// Updates the selected <see cref="DataGridColumnHeader"/>. /// </summary> /// <param name="datagrid">The datagrid.</param> private static void UpdateSelectedHeaders(DataGridControl datagrid) { if (null == datagrid) return; // Get the list of headers IList<DependencyObject> headers = VisualTreeHelperExtended.GetAllDescendants(datagrid, typeof(DataGridColumnHeader)); if (null == headers || 0 == headers.Count) return; // Update the selection based on the current tracking modes SelectionTrackingModes trackingModes = GetTrackingModes(datagrid); if (0 != (trackingModes & SelectionTrackingModes.Headers)) { // Update header selections, if any foreach (DataGridColumnHeader header in headers) { // Determine if the column associated with this header has any selected cells bool isSelected = false; foreach (DataGridCellInfo cellInfo in datagrid.SelectedCells) { if (cellInfo.Column == header.Column) { isSelected = true; break; } } // Update the selection for this header if (isSelected != GetIsSelectedHeader(header)) { if (isSelected) header.SetValue(IsSelectedHeaderPropertyKey, true); else header.ClearValue(IsSelectedHeaderPropertyKey); } } } else { // Clear header selections, if any foreach (DataGridColumnHeader header in headers) { if (GetIsSelectedHeader(header)) header.ClearValue(IsSelectedHeaderPropertyKey); } } } #endregion // NON-PUBLIC PROCEDURES ///////////////////////////////////////////////////////////////////////////////////////////////////// #region PUBLIC PROCEDURES ///////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Gets a value indicating whether a <see cref="DataGridColumnHeader"/> corresponds to the column /// of the a currently selected <see cref="DataGridCell"/>. /// </summary> /// <param name="obj">The object from which the property value is read.</param> /// <returns>The object's value.</returns> [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public static bool GetIsSelectedHeader(DataGridColumnHeader obj) { if (obj == null) throw new ArgumentNullException("obj"); return (bool)obj.GetValue(IsSelectedHeaderProperty); } /// <summary> /// Gets the value of the <see cref="TrackingModesProperty"/> attached property for a specified <see cref="DataGridControl"/>. /// </summary> /// <param name="obj">The object to which the attached property is retrieved.</param> /// <returns> /// The selections that should be tracked in a <see cref="DataGridControl"/>. /// </returns> [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public static SelectionTrackingModes GetTrackingModes(DataGridControl obj) { if (null == obj) throw new ArgumentNullException("obj"); return (SelectionTrackingModes)obj.GetValue(SelectionBehavior.TrackingModesProperty); } /// <summary> /// Sets the value of the <see cref="TrackingModesProperty"/> attached property to a specified <see cref="DataGridControl"/>. /// </summary> /// <param name="obj">The object to which the attached property is written.</param> /// <param name="value"> /// A value indicating the selections that should be tracked in a <see cref="DataGridControl"/>. /// </param> [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public static void SetTrackingModes(DataGridControl obj, SelectionTrackingModes value) { if (null == obj) throw new ArgumentNullException("obj"); obj.SetValue(SelectionBehavior.TrackingModesProperty, value); } #endregion // PUBLIC PROCEDURES } }
43.081871
159
0.698113
[ "MIT" ]
Actipro/WPF-Controls
Source/DataGrid.Contrib/Windows/Controls.DataGrid/SelectionBehavior.cs
7,367
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 databrew-2017-07-25.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.GlueDataBrew.Model { /// <summary> /// Container for the parameters to the UpdateDataset operation. /// Modifies the definition of an existing DataBrew dataset. /// </summary> public partial class UpdateDatasetRequest : AmazonGlueDataBrewRequest { private FormatOptions _formatOptions; private Input _input; private string _name; /// <summary> /// Gets and sets the property FormatOptions. /// </summary> public FormatOptions FormatOptions { get { return this._formatOptions; } set { this._formatOptions = value; } } // Check to see if FormatOptions property is set internal bool IsSetFormatOptions() { return this._formatOptions != null; } /// <summary> /// Gets and sets the property Input. /// </summary> [AWSProperty(Required=true)] public Input Input { get { return this._input; } set { this._input = value; } } // Check to see if Input property is set internal bool IsSetInput() { return this._input != null; } /// <summary> /// Gets and sets the property Name. /// <para> /// The name of the dataset to be updated. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=255)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } } }
28.467391
106
0.605575
[ "Apache-2.0" ]
diegodias/aws-sdk-net
sdk/src/Services/GlueDataBrew/Generated/Model/UpdateDatasetRequest.cs
2,619
C#
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections; using System.Collections.Generic; using WebsitePanel.EnterpriseServer; namespace WebsitePanel.Ecommerce.EnterpriseServer { public class HostingPackageController : ServiceProvisioningBase, IServiceProvisioning { // public const string SOURCE_NAME = "SPF_HOSTING_PKG"; #region Trace Messages public const string START_ACTIVATION_MSG = "Starting package activation"; public const string START_SUSPENSION_MSG = "Starting package suspension"; public const string START_CANCELLATION_MSG = "Starting package cancellation"; public const string CREATE_PCKG_MSG = "Creating new hosting package"; public const string CREATE_PCKG_ERROR_MSG = "Could not create hosting package"; public const string ERROR_ACTIVATE_PCKG_MSG = "Could not activate hosting package"; public const string ERROR_SUSPEND_PCKG_MSG = "Could not suspend hosting package"; public const string ERROR_CANCEL_PCKG_MSG = "Could not cancel hosting package"; public const string START_USR_ACTIVATION_MSG = "Activating service consumer account"; public const string START_CHANGE_USR_ROLE_MSG = "Changing consumer user role"; public const string ERROR_USR_ACTIVATION_MSG = "Could not activate consumer account"; public const string ERROR_CHANGE_USR_ROLE_MSG = "Could not change consumer user role"; public const string PCKG_PROVISIONED_MSG = "Package has been provisioned"; #endregion protected HostingPackageSvc GetHostingPackageSvc(int serviceId) { return ObjectUtils.FillObjectFromDataReader<HostingPackageSvc>( EcommerceProvider.GetHostingPackageSvc(SecurityContext.User.UserId, serviceId)); } protected InvoiceItem GetSetupFeeInvoiceLine(HostingPackageSvc service) { InvoiceItem line = new InvoiceItem(); line.ItemName = service.ServiceName; line.Quantity = 1; line.UnitPrice = service.SetupFee; line.TypeName = "Setup Fee"; return line; } protected InvoiceItem GetRecurringFeeInvoiceLine(HostingPackageSvc service) { InvoiceItem line = new InvoiceItem(); line.ItemName = service.ServiceName; line.ServiceId = service.ServiceId; line.Quantity = 1; line.UnitPrice = service.RecurringFee; line.TypeName = (service.Status == ServiceStatus.Ordered) ? Product.HOSTING_PLAN_NAME : "Recurring Fee"; return line; } #region IServiceProvisioning Members public ServiceHistoryRecord[] GetServiceHistory(int serviceId) { List<ServiceHistoryRecord> history = ObjectUtils.CreateListFromDataReader<ServiceHistoryRecord>( EcommerceProvider.GetHostingPackageSvcHistory(SecurityContext.User.UserId, serviceId)); if (history != null) return history.ToArray(); return new ServiceHistoryRecord[] { }; } public InvoiceItem[] CalculateInvoiceLines(int serviceId) { List<InvoiceItem> lines = new List<InvoiceItem>(); // load svc HostingPackageSvc packageSvc = GetHostingPackageSvc(serviceId); // recurring fee lines.Add(GetRecurringFeeInvoiceLine(packageSvc)); // setup fee if (packageSvc.Status == ServiceStatus.Ordered && packageSvc.SetupFee > 0M) lines.Add(GetSetupFeeInvoiceLine(packageSvc)); return lines.ToArray(); } public int AddServiceInfo(string contractId, string currency, OrderItem orderItem) { return EcommerceProvider.AddHostingPlanSvc(contractId, orderItem.ProductId, orderItem.ItemName, orderItem.BillingCycle, currency); } public Service GetServiceInfo(int serviceId) { return GetHostingPackageSvc(serviceId); } public int UpdateServiceInfo(Service service) { HostingPackageSvc packageSvc = (HostingPackageSvc)service; // return EcommerceProvider.UpdateHostingPlanSvc(SecurityContext.User.UserId, packageSvc.ServiceId, packageSvc.ProductId, packageSvc.ServiceName, (int)packageSvc.Status, packageSvc.PlanId, packageSvc.PackageId, (int)packageSvc.UserRole, (int)packageSvc.InitialStatus); } public GenericSvcResult ActivateService(ProvisioningContext context) { GenericSvcResult result = new GenericSvcResult(); // SaveObjectState(SERVICE_INFO, context.ServiceInfo); // SaveObjectState(CONSUMER_INFO, context.ConsumerInfo); // concretize service to be provisioned HostingPackageSvc packageSvc = (HostingPackageSvc)context.ServiceInfo; // try { // TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.SVC_ACTIVATE); // LOG INFO TaskManager.Write(START_ACTIVATION_MSG); TaskManager.WriteParameter(USERNAME_PARAM, context.ConsumerInfo[ContractAccount.USERNAME]); TaskManager.WriteParameter(SVC_PARAM, context.ServiceInfo.ServiceName); TaskManager.WriteParameter(SVC_ID_PARAM, context.ServiceInfo.ServiceId); TaskManager.UpdateParam(SystemTaskParams.PARAM_SEND_EMAIL, context.SendEmail); // 0. Do security checks if (!CheckOperationClientPermissions(result)) { // LOG ERROR TaskManager.WriteError(ERROR_CLIENT_OPERATION_PERMISSIONS); TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode); // EXIT return result; } // if (!CheckOperationClientStatus(result)) { // LOG ERROR TaskManager.WriteError(ERROR_CLIENT_OPERATION_STATUS); TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode); // EXIT return result; } // 1. Hosting package is just ordered if (context.ServiceInfo.Status == ServiceStatus.Ordered && context.ContractInfo.CustomerId > 0) { // LOG INFO TaskManager.Write(CREATE_PCKG_MSG); // create new package PackageResult apiResult = PackageController.AddPackage(context.ContractInfo.CustomerId, packageSvc.PlanId, packageSvc.ServiceName, String.Empty, (int)packageSvc.InitialStatus, DateTime.Now, true, true); // failed to instantiate package if (apiResult.Result <= 0) { result.ResultCode = apiResult.Result; // result.Succeed = false; // LOG ERROR TaskManager.WriteError(CREATE_PCKG_ERROR_MSG); TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode); // EXIT return result; } // save result PackageId packageSvc.PackageId = apiResult.Result; } else // 2. Package requires only to update its status { // LOG INFO TaskManager.Write(START_ACTIVATION_MSG); // int apiResult = PackageController.ChangePackageStatus(packageSvc.PackageId, PackageStatus.Active, false); // if (apiResult < 0) { result.ResultCode = apiResult; // result.Succeed = false; // LOG ERROR TaskManager.WriteError(ERROR_ACTIVATE_PCKG_MSG); TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode); // EXIT return result; } } // check user role if (context.ContractInfo.CustomerId > 0) { UserInfo user = UserController.GetUserInternally(context.ContractInfo.CustomerId); // check user status // if (user.Status != UserStatus.Active) { // LOG INFO TaskManager.Write(START_USR_ACTIVATION_MSG); // trying to change user status int userResult = UserController.ChangeUserStatus(context.ContractInfo.CustomerId, UserStatus.Active); // failed to activate user account if (userResult < 0) { result.ResultCode = userResult; // result.Succeed = false; // LOG ERROR TaskManager.WriteError(ERROR_USR_ACTIVATION_MSG); TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode); // ROLLBACK CHANGES RollbackOperation(result.ResultCode); // EXIT return result; } } // check user role if (user.Role != packageSvc.UserRole) { // LOG INFO TaskManager.Write(START_CHANGE_USR_ROLE_MSG); // user.Role = packageSvc.UserRole; // trying to change user role int roleResult = UserController.UpdateUser(user); // failed to change user role if (roleResult < 0) { result.ResultCode = roleResult; // result.Succeed = false; // TaskManager.WriteError(ERROR_CHANGE_USR_ROLE_MSG); TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode); // ROLLBACK CHANGES RollbackOperation(result.ResultCode); // EXIT return result; } } } // update plan status if necessary if (packageSvc.Status != ServiceStatus.Active) { // change service status to active packageSvc.Status = ServiceStatus.Active; // put data into metabase int svcResult = UpdateServiceInfo(packageSvc); // error updating svc details if (svcResult < 0) { result.ResultCode = svcResult; // result.Succeed = false; // ROLLBACK CHANGES RollbackOperation(packageSvc.PackageId); // LOG ERROR TaskManager.WriteError(ERROR_SVC_UPDATE_MSG); TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode); // EXIT return result; } } // SetOutboundParameters(context); // LOG INFO TaskManager.Write(PCKG_PROVISIONED_MSG); // result.Succeed = true; } catch (Exception ex) { // TaskManager.WriteError(ex); // ROLLBACK CHANGES RollbackOperation(packageSvc.PackageId); // result.Succeed = false; // result.Error = ex.Message; } finally { // complete task TaskManager.CompleteTask(); } // return result; } public GenericSvcResult SuspendService(ProvisioningContext context) { GenericSvcResult result = new GenericSvcResult(); // SaveObjectState(SERVICE_INFO, context.ServiceInfo); // SaveObjectState(CONSUMER_INFO, context.ConsumerInfo); // concretize service to be provisioned HostingPackageSvc packageSvc = (HostingPackageSvc)context.ServiceInfo; // try { // TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.SVC_SUSPEND); // LOG INFO TaskManager.Write(START_SUSPENSION_MSG); TaskManager.WriteParameter(CONTRACT_PARAM, context.ConsumerInfo[ContractAccount.USERNAME]); TaskManager.WriteParameter(SVC_PARAM, context.ServiceInfo.ServiceName); TaskManager.WriteParameter(SVC_ID_PARAM, context.ServiceInfo.ServiceId); // 0. Do security checks if (!CheckOperationClientPermissions(result)) { // LOG ERROR TaskManager.WriteError(ERROR_CLIENT_OPERATION_PERMISSIONS); TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode); // EXIT return result; } // if (!CheckOperationClientStatus(result)) { // LOG ERROR TaskManager.WriteError(ERROR_CLIENT_OPERATION_STATUS); TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode); // EXIT return result; } // suspend hosting package int apiResult = PackageController.ChangePackageStatus(packageSvc.PackageId, PackageStatus.Suspended, false); // check WebsitePanel API result if (apiResult < 0) { result.ResultCode = apiResult; // result.Succeed = false; // LOG ERROR TaskManager.WriteError(ERROR_SUSPEND_PCKG_MSG); TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode); // exit return result; } // change service status to Suspended packageSvc.Status = ServiceStatus.Suspended; // put data into metabase int svcResult = UpdateServiceInfo(packageSvc); // if (svcResult < 0) { result.ResultCode = svcResult; // result.Succeed = false; // LOG ERROR TaskManager.WriteError(ERROR_SVC_UPDATE_MSG); TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode); // ROLLBACK CHANGES RollbackOperation(packageSvc.PackageId); // return result; } // SetOutboundParameters(context); // LOG INFO TaskManager.Write(PCKG_PROVISIONED_MSG); // result.Succeed = true; } catch (Exception ex) { // TaskManager.WriteError(ex); // ROLLBACK CHANGES RollbackOperation(packageSvc.PackageId); // result.Succeed = false; // result.Error = ex.Message; } finally { // complete task TaskManager.CompleteTask(); } // return result; } public GenericSvcResult CancelService(ProvisioningContext context) { GenericSvcResult result = new GenericSvcResult(); // SaveObjectState(SERVICE_INFO, context.ServiceInfo); // SaveObjectState(CONSUMER_INFO, context.ConsumerInfo); // concretize service to be provisioned HostingPackageSvc packageSvc = (HostingPackageSvc)context.ServiceInfo; // try { // TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.SVC_CANCEL); // LOG INFO TaskManager.Write(START_CANCELLATION_MSG); TaskManager.WriteParameter(CONTRACT_PARAM, context.ConsumerInfo[ContractAccount.USERNAME]); TaskManager.WriteParameter(SVC_PARAM, context.ServiceInfo.ServiceName); TaskManager.WriteParameter(SVC_ID_PARAM, context.ServiceInfo.ServiceId); // 0. Do security checks if (!CheckOperationClientPermissions(result)) { // LOG ERROR TaskManager.WriteError(ERROR_CLIENT_OPERATION_PERMISSIONS); TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode); // EXIT return result; } // if (!CheckOperationClientStatus(result)) { // LOG ERROR TaskManager.WriteError(ERROR_CLIENT_OPERATION_STATUS); TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode); // EXIT return result; } // cancel hosting package int apiResult = PackageController.ChangePackageStatus(packageSvc.PackageId, PackageStatus.Cancelled, false); // check WebsitePanel API result if (apiResult < 0) { // result.ResultCode = apiResult; // result.Succeed = false; // LOG ERROR TaskManager.WriteError(ERROR_CANCEL_PCKG_MSG); TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode); // EXIT return result; } // change service status to Cancelled packageSvc.Status = ServiceStatus.Cancelled; // put data into metabase int svcResult = UpdateServiceInfo(packageSvc); // if (svcResult < 0) { result.ResultCode = svcResult; // result.Error = ERROR_SVC_UPDATE_MSG; // result.Succeed = false; // ROLLBACK CHANGES RollbackOperation(packageSvc.PackageId); // LOG ERROR TaskManager.WriteError(result.Error); TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode); // EXIT return result; } // SetOutboundParameters(context); // LOG INFO TaskManager.Write(PCKG_PROVISIONED_MSG); // result.Succeed = true; } catch (Exception ex) { // TaskManager.WriteError(ex); // ROLLBACK CHANGES RollbackOperation(packageSvc.PackageId); // result.Succeed = false; // result.Error = ex.Message; } finally { // complete task TaskManager.CompleteTask(); } // return result; } public void LogServiceUsage(ProvisioningContext context) { // concretize service to be logged HostingPackageSvc packageSvc = (HostingPackageSvc)context.ServiceInfo; // log service usage base.LogServiceUsage(context.ServiceInfo, packageSvc.SvcCycleId, packageSvc.BillingPeriod, packageSvc.PeriodLength); } protected void RollbackOperation(int packageId) { // check input parameters first if (packageId < 1) return; // exit // try { TaskManager.Write("Trying rollback operation"); // restore service HostingPackageSvc packageSvc = (HostingPackageSvc)RestoreObjectState("ServiceInfo"); // restore consumer UserInfo consumer = (UserInfo)RestoreObjectState("ConsumerInfo"); // int apiResult = 0; // rollback consumer changes first apiResult = UserController.UpdateUser(consumer); // check WebsitePanel API result if (apiResult < 0) { // TaskManager.WriteError("Could not rollback consumer changes"); // TaskManager.WriteParameter("ResultCode", apiResult); } // during rollback package should be reverted to its original state // compensation logic - revert back package status switch (packageSvc.Status) { // Active State case ServiceStatus.Active: apiResult = PackageController.ChangePackageStatus(packageId, PackageStatus.Active, false); break; // Suspended State case ServiceStatus.Suspended: apiResult = PackageController.ChangePackageStatus(packageId, PackageStatus.Suspended, false); break; // Cancelled State case ServiceStatus.Cancelled: apiResult = PackageController.ChangePackageStatus(packageId, PackageStatus.Cancelled, false); break; // service has been just ordered & during rollback should be removed case ServiceStatus.Ordered: // compensation logic - remove created package apiResult = PackageController.DeletePackage(packageId); break; } // check WebsitePanel API result if (apiResult < 0) { // if (packageSvc.Status == ServiceStatus.Ordered) TaskManager.WriteError("Could not rollback operation and delete package"); else TaskManager.WriteError("Could not rollback operation and revert package state"); // TaskManager.WriteParameter("ResultCode", apiResult); } // rollback service changes in EC metabase apiResult = UpdateServiceInfo(packageSvc); // check API result if (apiResult < 0) { // TaskManager.WriteError("Could not rollback service changes"); // TaskManager.WriteParameter("ResultCode", apiResult); } // TaskManager.Write("Rollback succeed"); } catch (Exception ex) { TaskManager.WriteError(ex); } } #endregion } }
31.39233
113
0.646918
[ "BSD-3-Clause" ]
mkramer74/WebSitePanel
WebsitePanel/Sources/WebsitePanel.EnterpriseServer.Code/Ecommerce/Provisioning/HostingPackageController.cs
21,284
C#
using System; using System.Collections; using System.Collections.Generic; namespace Bubble.Sort { public class Bubble<T> : IEnumerable<T> where T : IComparable { private IList<T> data; public Bubble(params T[] items) { this.data = new List<T>(); foreach (var item in items) { this.data.Add(item); } this.Sort(); } public void Add(T item) { this.data.Add(item); this.Sort(); } public IEnumerator<T> GetEnumerator() { return this.data.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } private void Sort() { for (int i = 0; i < this.data.Count; i++) { for (int sort = 0; sort < this.data.Count - 1; sort++) { if (this.data[sort].CompareTo(this.data[sort + 1]) == 1) { T temp = this.data[sort + 1]; this.data[sort + 1] = this.data[sort]; this.data[sort] = temp; } } } } } }
24.055556
76
0.425712
[ "MIT" ]
IvelinMarinov/SoftUni
06. OOP Advanced - Jul2017/06. Unit Tests - Exercise/Bubble.Sort/Bubble.cs
1,301
C#
using System.Collections.Generic; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using NUnit.Framework; using RoslynTestKit; namespace CsharpMacros.Test.General { public class GeneralTest : CodeFixTestFixture { [Test] public void should_be_able_to_add_single_filter() { TestCodeFixAtLine(TestCases._001_WithSingleFilter, TestCases._001_WithSIngleFilter_FIXED, MacroCodeAnalyzer.DiagnosticId, 21); } [Test] public void should_be_able_to_add_multiple_filters() { TestCodeFixAtLine(TestCases._002_WithMultipleFilters, TestCases._002_WIthMultipleFIlters_FIXED, MacroCodeAnalyzer.DiagnosticId, 21); } [Test] public void should_be_able_to_execute_macro_below_the_comment() { TestCodeFixAtLine(TestCases._003_CommentAboveTheMacro, TestCases._003_CommentAboveTheMacro_FIXED, MacroCodeAnalyzer.DiagnosticId, 22); } [Test] public void should_be_able_to_execute_macro_when_is_single_expression_in_method() { TestCodeFixAtLine(TestCases._004_WhenMacroIsSingleExpressionInMethod, TestCases._004_WhenMacroIsSingleExpressionInMethod_FIXED, MacroCodeAnalyzer.DiagnosticId, 14); } [Test] public void should_be_able_to_execute_macro_when_is_first_expression_in_method() { TestCodeFixAtLine(TestCases._005_WhenMacroIsFirstExpressionInMethod, TestCases._005_WhenMacroIsFirstExpressionInMethod_FIXED, MacroCodeAnalyzer.DiagnosticId, 14); } [Test] public void should_be_able_to_execute_macro_when_is_last_expression_in_method() { TestCodeFixAtLine(TestCases._006_WhenMacroIsLastExpressionInMethod, TestCases._006_WhenMacroIsLastExpressionInMethod_FIXED, MacroCodeAnalyzer.DiagnosticId, 15); } [Test] public void should_be_able_to_execute_macro_inside_if() { TestCodeFixAtLine(TestCases._007_WhenMacroIsInsideIf_, TestCases._007_WhenMacroIsInsideIf_FIXED, MacroCodeAnalyzer.DiagnosticId, 16); } [Test] public void should_be_able_to_execute_macro_inside_if_without_bracket() { TestCodeFixAtLine(TestCases._008_WhenMacroIsInsideIfWithoutBracket, TestCases._008_WhenMacroIsInsideIfWithoutBracket_FIXED, MacroCodeAnalyzer.DiagnosticId, 15); } [Test] public void should_be_able_to_execute_macro_outside_method() { TestCodeFixAtLine(TestCases._009_WhenMacroIsOutsideMethod, TestCases._009_WhenMacroIsOutsideMethod_FIXED, MacroCodeAnalyzer.DiagnosticId, 5); } [Test] public void should_be_able_to_execute_macro_outside_method_and_nothing_more() { TestCodeFixAtLine(TestCases._010_WhenMacroIsOutsideMethodAndNothingMore, TestCases._010_WhenMacroIsOutsideMethodAndNothingMore_FIXED, MacroCodeAnalyzer.DiagnosticId, 5); } protected override string LanguageName => LanguageNames.CSharp; protected override CodeFixProvider CreateProvider() => new CsharpMacrosCodeFixProvider(); protected override IReadOnlyCollection<DiagnosticAnalyzer> CreateAdditionalAnalyzers() => new[] { new MacroCodeAnalyzer() }; } }
43.202532
182
0.731321
[ "MIT" ]
cezarypiatek/CsharpMacros
src/CsharpMacros.Test/General/GeneralTest.cs
3,415
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Reactive { class ImmutableList<T> { T[] data; public ImmutableList() { data = new T[0]; } public ImmutableList(T[] data) { this.data = data; } public ImmutableList<T> Add(T value) { var newData = new T[data.Length + 1]; Array.Copy(data, newData, data.Length); newData[data.Length] = value; return new ImmutableList<T>(newData); } public ImmutableList<T> Remove(T value) { var i = IndexOf(value); if (i < 0) return this; var newData = new T[data.Length - 1]; Array.Copy(data, 0, newData, 0, i); Array.Copy(data, i + 1, newData, i, data.Length - i - 1); return new ImmutableList<T>(newData); } public int IndexOf(T value) { for (var i = 0; i < data.Length; ++i) if (data[i].Equals(value)) return i; return -1; } public T[] Data { get { return data; } } } }
25.173077
133
0.477464
[ "Apache-2.0" ]
Distrotech/mono
external/rx/Rx/NET/Source/System.Reactive.Linq/Reactive/Internal/ImmutableList.cs
1,311
C#
using System; using System.Collections.Generic; using UnityEngine; namespace Marklight.Themes { [Serializable] public class StyleClass { #region Private Fields private static readonly char[] StyleSeperator = new char[] { ' ' }; [SerializeField] private string _className; [NonSerialized] private string[] _classNames; [NonSerialized] private string _selector; #endregion #region Constructors public StyleClass() { } public StyleClass(string className) { _className = SortClassNames(className ?? ""); } #endregion #region Methods public override int GetHashCode() { return _className.GetHashCode(); } public override bool Equals(object obj) { var other = obj as StyleClass; if (other == null) return false; return other._className == _className; } /// <summary> /// Sort a space delimited string of style class names alphabetically. /// </summary> public static string SortClassNames(string className) { if (string.IsNullOrEmpty(className)) return className; var names = new List<string>(className.Split(StyleSeperator, StringSplitOptions.RemoveEmptyEntries)); if (names.Count == 1) return names[0]; names.Sort(StringComparer.Ordinal); return string.Join(" ", names.ToArray()); } #endregion #region Property public bool IsSet { get { return !string.IsNullOrEmpty(_className); } } public string ClassName { get { return _className; } } public string[] ClassNames { get { return _classNames ?? (_classNames = _className.Split(' ')); } } public string Selector { get { return _selector ?? (_selector = "." + string.Join(".", ClassNames)); } } #endregion } }
22.381443
113
0.538922
[ "MIT" ]
JCThePants/marklight
Source/Assets/MarkLight/Source/Plugins/Themes/StyleClass.cs
2,173
C#
using System; 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; namespace UserControls { public partial class UCUredjivanjeEdukacija : UserControl { public UCUredjivanjeEdukacija() { InitializeComponent(); } } }
17.904762
58
0.784574
[ "MIT" ]
NovakVed/cs-learning
CSeLearning/UCUredjivanjeEdukacija.cs
378
C#
using QuizScoreTracker.Managers; using System.Windows.Forms; namespace QuizScoreTracker.Forms { partial class AboutDialog : Form { public AboutDialog() { InitializeComponent(); Text = $"About {AssemblyManager.Title}"; labelProductName.Text = AssemblyManager.Product; labelVersion.Text = $"Version {AssemblyManager.Version}"; labelCopyright.Text = AssemblyManager.Copyright; labelCompanyName.Text = AssemblyManager.Company; textBoxDescription.Text = AssemblyManager.Description; } } }
31.842105
69
0.649587
[ "MIT" ]
AbyssDarkstar/QuizScoreTracker
QuizScoreTracker/Forms/AboutDialog.cs
607
C#
using Game.Engine.Monsters; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Game.Engine { class Q3Strategy : IBattleStrategy { private int q3; public void Execute(GameSession parentSession, Monster monster, KilledMonstersCounter _newCounter) { if (monster.Name == "monster0001") { q3 = _newCounter.RatsCounter; q3++; _newCounter.CheckQuestStatus(); if ((q3 - 3) == 0) { parentSession.SendText("Quest finished"); } else if ((q3 - 3) < 0) { parentSession.SendText($"It seems you killed the right one. You have to kill {3 - q3} more rats"); } else if ((q3 - 3) > 0) { _newCounter.RatsCounter = 0; } else { // quest inactive } } } } }
24.8
118
0.46147
[ "MIT" ]
kamilkozinski/GameC
Engine/Q3Strategy.cs
1,118
C#
using System; using System.Collections.Generic; using System.Xml.Serialization; namespace Alipay.AopSdk.Core.Domain { /// <summary> /// SignTaskFileResult Data Structure. /// </summary> [Serializable] public class SignTaskFileResult : AopObject { /// <summary> /// 业务初始化时传入的流水号 /// </summary> [XmlElement("biz_id")] public string BizId { get; set; } /// <summary> /// 扩展参数信息,可根据不同接入方需求定制内容 /// </summary> [XmlElement("biz_info")] public string BizInfo { get; set; } /// <summary> /// 已签名文档列表 /// </summary> [XmlArray("signed_file_list")] [XmlArrayItem("signed_file_info")] public List<SignedFileInfo> SignedFileList { get; set; } /// <summary> /// 签约结果 1)FAIL | 解释:签约失败 2)SUCCESS | 解释:完成 3)PROCESS | 解释:签约中 4)EXPIRED | 解释:任务过期 /// </summary> [XmlElement("status")] public string Status { get; set; } /// <summary> /// 签约任务编号 /// </summary> [XmlElement("task_id")] public string TaskId { get; set; } } }
25.511111
94
0.540941
[ "MIT" ]
leixf2005/Alipay.AopSdk.Core
Alipay.AopSdk.Core/Domain/SignTaskFileResult.cs
1,306
C#
using SuperHeroAPI.Models; namespace SuperHeroAPI.Repositories.Interfaces { public interface ISuperHeroRespository { Task<List<SuperHero>> GetAll(); Task<SuperHero?> GetAsync(string id); Task<SuperHero> AddAsync(SuperHero hero); Task<SuperHero> UpdateAsync(SuperHero hero); Task<bool> DeleteAsync(string id); } }
26.214286
52
0.686649
[ "MIT" ]
xLonelyPlayer/ApsDotNetCoreWebAPIV1
SuperHeroAPI/SuperHeroAPI/Repositories/Interfaces/ISuperHero.cs
369
C#
//------------------------------------------------------------------------------ // <auto-generated> // Ce code a été généré par un outil. // Version du runtime :4.0.30319.42000 // // Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si // le code est régénéré. // </auto-generated> //------------------------------------------------------------------------------ namespace DesktopApp.Properties { /// <summary> /// Une classe de ressource fortement typée destinée, entre autres, à la consultation des chaînes localisées. /// </summary> // Cette classe a été générée automatiquement par la classe StronglyTypedResourceBuilder // à l'aide d'un outil, tel que ResGen ou Visual Studio. // Pour ajouter ou supprimer un membre, modifiez votre fichier .ResX, puis réexécutez ResGen // avec l'option /str ou régénérez votre projet VS. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Retourne l'instance ResourceManager mise en cache utilisée par cette classe. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DesktopApp.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Remplace la propriété CurrentUICulture du thread actuel pour toutes /// les recherches de ressources à l'aide de cette classe de ressource fortement typée. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
40.819444
176
0.616876
[ "MIT" ]
Aimene-BAHRI/Hacktober-2019
WPF apps/Fun facts Calculator/Properties/Resources.Designer.cs
2,973
C#
// // ProcessTest.cs - NUnit Test Cases for System.Diagnostics.Process // // Authors: // Gert Driesen (drieseng@users.sourceforge.net) // Robert Jordan <robertj@gmx.net> // // (C) 2007 Gert Driesen // using System; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; using NUnit.Framework; namespace MonoTests.System.Diagnostics { [TestFixture] public class ProcessTest { [Test] public void GetProcessById_MachineName_Null () { try { Process.GetProcessById (1, (string) null); Assert.Fail ("#1"); } catch (ArgumentNullException ex) { Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2"); Assert.IsNotNull (ex.Message, "#3"); Assert.IsNotNull (ex.ParamName, "#4"); Assert.AreEqual ("machineName", ex.ParamName, "#5"); Assert.IsNull (ex.InnerException, "#6"); } } [Test] public void GetProcesses_MachineName_Null () { try { Process.GetProcesses ((string) null); Assert.Fail ("#1"); } catch (ArgumentNullException ex) { Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2"); Assert.IsNotNull (ex.Message, "#3"); Assert.IsNotNull (ex.ParamName, "#4"); Assert.AreEqual ("machineName", ex.ParamName, "#5"); Assert.IsNull (ex.InnerException, "#6"); } } [Test] public void PriorityClass_NotStarted () { Process process = new Process (); try { process.PriorityClass = ProcessPriorityClass.Normal; Assert.Fail ("#A1"); } catch (InvalidOperationException ex) { // No process is associated with this object Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#A2"); Assert.IsNull (ex.InnerException, "#A3"); Assert.IsNotNull (ex.Message, "#A4"); } try { Assert.Fail ("#B1:" + process.PriorityClass); } catch (InvalidOperationException ex) { // No process is associated with this object Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2"); Assert.IsNull (ex.InnerException, "#B3"); Assert.IsNotNull (ex.Message, "#B4"); } } [Test] public void PriorityClass_Invalid () { Process process = new Process (); try { process.PriorityClass = (ProcessPriorityClass) 666; Assert.Fail ("#1"); } catch (InvalidEnumArgumentException ex) { Assert.AreEqual (typeof (InvalidEnumArgumentException), ex.GetType (), "#2"); Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); Assert.IsTrue (ex.Message.IndexOf ("666") != -1, "#5"); Assert.IsTrue (ex.Message.IndexOf (typeof (ProcessPriorityClass).Name) != -1, "#6"); Assert.IsNotNull (ex.ParamName, "#7"); Assert.AreEqual ("value", ex.ParamName, "#8"); } } [Test] // Start () public void Start1_FileName_Empty () { Process process = new Process (); process.StartInfo = new ProcessStartInfo (string.Empty); // no shell process.StartInfo.UseShellExecute = false; try { process.Start (); Assert.Fail ("#A1"); } catch (InvalidOperationException ex) { // Cannot start process because a file name has // not been provided Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#A2"); Assert.IsNull (ex.InnerException, "#A3"); Assert.IsNotNull (ex.Message, "#A4"); } // shell process.StartInfo.UseShellExecute = true; try { process.Start (); Assert.Fail ("#B1"); } catch (InvalidOperationException ex) { // Cannot start process because a file name has // not been provided Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2"); Assert.IsNull (ex.InnerException, "#B3"); Assert.IsNotNull (ex.Message, "#B4"); } } [Test] // Start () public void Start1_FileName_InvalidPathCharacters () { if (RunningOnUnix) // on unix, all characters are allowed return; string systemDir = Environment.GetFolderPath (Environment.SpecialFolder.System); string exe = "\"" + Path.Combine (systemDir, "calc.exe") + "\""; Process process = new Process (); process.StartInfo = new ProcessStartInfo (exe); // no shell process.StartInfo.UseShellExecute = false; Assert.IsTrue (process.Start ()); process.Kill (); // shell process.StartInfo.UseShellExecute = true; Assert.IsTrue (process.Start ()); process.Kill (); } [Test] // Start () public void Start1_FileName_NotFound () { Process process = new Process (); string exe = RunningOnUnix ? exe = "/usr/bin/shouldnoteverexist" : @"c:\shouldnoteverexist.exe"; // absolute path, no shell process.StartInfo = new ProcessStartInfo (exe); process.StartInfo.UseShellExecute = false; try { process.Start (); Assert.Fail ("#A1"); } catch (Win32Exception ex) { // The system cannot find the file specified Assert.AreEqual (typeof (Win32Exception), ex.GetType (), "#A2"); Assert.AreEqual (-2147467259, ex.ErrorCode, "#A3"); Assert.IsNull (ex.InnerException, "#A4"); Assert.IsNotNull (ex.Message, "#A5"); Assert.AreEqual (2, ex.NativeErrorCode, "#A6"); } // relative path, no shell process.StartInfo.FileName = "shouldnoteverexist.exe"; process.StartInfo.UseShellExecute = false; try { process.Start (); Assert.Fail ("#B1"); } catch (Win32Exception ex) { // The system cannot find the file specified Assert.AreEqual (typeof (Win32Exception), ex.GetType (), "#B2"); Assert.AreEqual (-2147467259, ex.ErrorCode, "#B3"); Assert.IsNull (ex.InnerException, "#B4"); Assert.IsNotNull (ex.Message, "#B5"); Assert.AreEqual (2, ex.NativeErrorCode, "#B6"); } if (RunningOnUnix) Assert.Ignore ("On Unix and Mac OS X, we try " + "to open any file (using xdg-open, ...)" + " and we do not report an exception " + "if this fails."); // absolute path, shell process.StartInfo.FileName = exe; process.StartInfo.UseShellExecute = true; try { process.Start (); Assert.Fail ("#C1"); } catch (Win32Exception ex) { // The system cannot find the file specified Assert.AreEqual (typeof (Win32Exception), ex.GetType (), "#C2"); Assert.AreEqual (-2147467259, ex.ErrorCode, "#C3"); Assert.IsNull (ex.InnerException, "#C4"); Assert.IsNotNull (ex.Message, "#C5"); Assert.AreEqual (2, ex.NativeErrorCode, "#C6"); } // relative path, shell process.StartInfo.FileName = "shouldnoteverexist.exe"; process.StartInfo.UseShellExecute = true; try { process.Start (); Assert.Fail ("#D1"); } catch (Win32Exception ex) { // The system cannot find the file specified Assert.AreEqual (typeof (Win32Exception), ex.GetType (), "#D2"); Assert.AreEqual (-2147467259, ex.ErrorCode, "#D3"); Assert.IsNull (ex.InnerException, "#D4"); Assert.IsNotNull (ex.Message, "#D5"); Assert.AreEqual (2, ex.NativeErrorCode, "#D6"); } } [Test] // Start () public void Start1_FileName_Null () { Process process = new Process (); process.StartInfo = new ProcessStartInfo ((string) null); // no shell process.StartInfo.UseShellExecute = false; try { process.Start (); Assert.Fail ("#A1"); } catch (InvalidOperationException ex) { // Cannot start process because a file name has // not been provided Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#A2"); Assert.IsNull (ex.InnerException, "#A3"); Assert.IsNotNull (ex.Message, "#A4"); } // shell process.StartInfo.UseShellExecute = true; try { process.Start (); Assert.Fail ("#B1"); } catch (InvalidOperationException ex) { // Cannot start process because a file name has // not been provided Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2"); Assert.IsNull (ex.InnerException, "#B3"); Assert.IsNotNull (ex.Message, "#B4"); } } [Test] // Start () public void Start1_FileName_Whitespace () { Process process = new Process (); process.StartInfo = new ProcessStartInfo (" "); process.StartInfo.UseShellExecute = false; try { process.Start (); Assert.Fail ("#1"); } catch (Win32Exception ex) { // The system cannot find the file specified Assert.AreEqual (typeof (Win32Exception), ex.GetType (), "#2"); Assert.AreEqual (-2147467259, ex.ErrorCode, "#3"); Assert.IsNull (ex.InnerException, "#4"); Assert.IsNotNull (ex.Message, "#5"); Assert.AreEqual (2, ex.NativeErrorCode, "#6"); } } [Test] // Start (ProcessStartInfo) public void Start2_FileName_Empty () { ProcessStartInfo startInfo = new ProcessStartInfo (string.Empty); // no shell startInfo.UseShellExecute = false; try { Process.Start (startInfo); Assert.Fail ("#A1"); } catch (InvalidOperationException ex) { // Cannot start process because a file name has // not been provided Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#A2"); Assert.IsNull (ex.InnerException, "#A3"); Assert.IsNotNull (ex.Message, "#A4"); } // shell startInfo.UseShellExecute = true; try { Process.Start (startInfo); Assert.Fail ("#B1"); } catch (InvalidOperationException ex) { // Cannot start process because a file name has // not been provided Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2"); Assert.IsNull (ex.InnerException, "#B3"); Assert.IsNotNull (ex.Message, "#B4"); } } [Test] // Start (ProcessStartInfo) public void Start2_FileName_NotFound () { ProcessStartInfo startInfo = new ProcessStartInfo (); string exe = RunningOnUnix ? exe = "/usr/bin/shouldnoteverexist" : @"c:\shouldnoteverexist.exe"; // absolute path, no shell startInfo.FileName = exe; startInfo.UseShellExecute = false; try { Process.Start (startInfo); Assert.Fail ("#A1"); } catch (Win32Exception ex) { // The system cannot find the file specified Assert.AreEqual (typeof (Win32Exception), ex.GetType (), "#A2"); Assert.AreEqual (-2147467259, ex.ErrorCode, "#A3"); Assert.IsNull (ex.InnerException, "#A4"); Assert.IsNotNull (ex.Message, "#A5"); Assert.AreEqual (2, ex.NativeErrorCode, "#A6"); } // relative path, no shell startInfo.FileName = "shouldnoteverexist.exe"; startInfo.UseShellExecute = false; try { Process.Start (startInfo); Assert.Fail ("#B1"); } catch (Win32Exception ex) { // The system cannot find the file specified Assert.AreEqual (typeof (Win32Exception), ex.GetType (), "#B2"); Assert.AreEqual (-2147467259, ex.ErrorCode, "#B3"); Assert.IsNull (ex.InnerException, "#B4"); Assert.IsNotNull (ex.Message, "#B5"); Assert.AreEqual (2, ex.NativeErrorCode, "#B6"); } if (RunningOnUnix) Assert.Ignore ("On Unix and Mac OS X, we try " + "to open any file (using xdg-open, ...)" + " and we do not report an exception " + "if this fails."); // absolute path, shell startInfo.FileName = exe; startInfo.UseShellExecute = true; try { Process.Start (startInfo); Assert.Fail ("#C1"); } catch (Win32Exception ex) { // The system cannot find the file specified Assert.AreEqual (typeof (Win32Exception), ex.GetType (), "#C2"); Assert.AreEqual (-2147467259, ex.ErrorCode, "#C3"); Assert.IsNull (ex.InnerException, "#C4"); Assert.IsNotNull (ex.Message, "#C5"); Assert.AreEqual (2, ex.NativeErrorCode, "#C6"); } // relative path, shell startInfo.FileName = "shouldnoteverexist.exe"; startInfo.UseShellExecute = true; try { Process.Start (startInfo); Assert.Fail ("#D1"); } catch (Win32Exception ex) { // The system cannot find the file specified Assert.AreEqual (typeof (Win32Exception), ex.GetType (), "#D2"); Assert.AreEqual (-2147467259, ex.ErrorCode, "#D3"); Assert.IsNull (ex.InnerException, "#D4"); Assert.IsNotNull (ex.Message, "#D5"); Assert.AreEqual (2, ex.NativeErrorCode, "#D6"); } } [Test] // Start (ProcessStartInfo) public void Start2_FileName_Null () { ProcessStartInfo startInfo = new ProcessStartInfo ((string) null); // no shell startInfo.UseShellExecute = false; try { Process.Start (startInfo); Assert.Fail ("#A1"); } catch (InvalidOperationException ex) { // Cannot start process because a file name has // not been provided Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#A2"); Assert.IsNull (ex.InnerException, "#A3"); Assert.IsNotNull (ex.Message, "#A4"); } // shell startInfo.UseShellExecute = true; try { Process.Start (startInfo); Assert.Fail ("#B1"); } catch (InvalidOperationException ex) { // Cannot start process because a file name has // not been provided Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2"); Assert.IsNull (ex.InnerException, "#B3"); Assert.IsNotNull (ex.Message, "#B4"); } } [Test] // Start (ProcessStartInfo) public void Start2_FileName_Whitespace () { ProcessStartInfo startInfo = new ProcessStartInfo (" "); startInfo.UseShellExecute = false; try { Process.Start (startInfo); Assert.Fail ("#1"); } catch (Win32Exception ex) { // The system cannot find the file specified Assert.AreEqual (typeof (Win32Exception), ex.GetType (), "#2"); Assert.AreEqual (-2147467259, ex.ErrorCode, "#3"); Assert.IsNull (ex.InnerException, "#4"); Assert.IsNotNull (ex.Message, "#5"); Assert.AreEqual (2, ex.NativeErrorCode, "#6"); } } [Test] // Start (ProcessStartInfo) public void Start2_StartInfo_Null () { try { Process.Start ((ProcessStartInfo) null); Assert.Fail ("#1"); } catch (ArgumentNullException ex) { Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2"); Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); Assert.IsNotNull (ex.ParamName, "#5"); Assert.AreEqual ("startInfo", ex.ParamName, "#6"); } } [Test] // Start (string) public void Start3_FileName_Empty () { try { Process.Start (string.Empty); Assert.Fail ("#1"); } catch (InvalidOperationException ex) { // Cannot start process because a file name has // not been provided Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#2"); Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); } } [Test] // Start (string) public void Start3_FileName_NotFound () { if (RunningOnUnix) Assert.Ignore ("On Unix and Mac OS X, we try " + "to open any file (using xdg-open, ...)" + " and we do not report an exception " + "if this fails."); string exe = @"c:\shouldnoteverexist.exe"; // absolute path, no shell try { Process.Start (exe); Assert.Fail ("#A1"); } catch (Win32Exception ex) { // The system cannot find the file specified Assert.AreEqual (typeof (Win32Exception), ex.GetType (), "#A2"); Assert.AreEqual (-2147467259, ex.ErrorCode, "#A3"); Assert.IsNull (ex.InnerException, "#A4"); Assert.IsNotNull (ex.Message, "#A5"); Assert.AreEqual (2, ex.NativeErrorCode, "#A6"); } // relative path, no shell try { Process.Start ("shouldnoteverexist.exe"); Assert.Fail ("#B1"); } catch (Win32Exception ex) { // The system cannot find the file specified Assert.AreEqual (typeof (Win32Exception), ex.GetType (), "#B2"); Assert.AreEqual (-2147467259, ex.ErrorCode, "#B3"); Assert.IsNull (ex.InnerException, "#B4"); Assert.IsNotNull (ex.Message, "#B5"); Assert.AreEqual (2, ex.NativeErrorCode, "#B6"); } } [Test] // Start (string) public void Start3_FileName_Null () { try { Process.Start ((string) null); Assert.Fail ("#1"); } catch (InvalidOperationException ex) { // Cannot start process because a file name has // not been provided Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#2"); Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); } } [Test] // Start (string, string) public void Start4_Arguments_Null () { if (RunningOnUnix) Assert.Ignore ("On Unix and Mac OS X, we try " + "to open any file (using xdg-open, ...)" + " and we do not report an exception " + "if this fails."); string exe = @"c:\shouldnoteverexist.exe"; try { Process.Start ("whatever.exe", (string) null); Assert.Fail ("#1"); } catch (Win32Exception ex) { // The system cannot find the file specified Assert.AreEqual (typeof (Win32Exception), ex.GetType (), "#B2"); Assert.AreEqual (-2147467259, ex.ErrorCode, "#B3"); Assert.IsNull (ex.InnerException, "#B4"); Assert.IsNotNull (ex.Message, "#B5"); Assert.AreEqual (2, ex.NativeErrorCode, "#B6"); } } [Test] // Start (string, string) public void Start4_FileName_Empty () { try { Process.Start (string.Empty, string.Empty); Assert.Fail ("#1"); } catch (InvalidOperationException ex) { // Cannot start process because a file name has // not been provided Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#2"); Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); } } [Test] // Start (string, string) public void Start4_FileName_NotFound () { if (RunningOnUnix) Assert.Ignore ("On Unix and Mac OS X, we try " + "to open any file (using xdg-open, ...)" + " and we do not report an exception " + "if this fails."); string exe = @"c:\shouldnoteverexist.exe"; // absolute path, no shell try { Process.Start (exe, string.Empty); Assert.Fail ("#A1"); } catch (Win32Exception ex) { // The system cannot find the file specified Assert.AreEqual (typeof (Win32Exception), ex.GetType (), "#A2"); Assert.AreEqual (-2147467259, ex.ErrorCode, "#A3"); Assert.IsNull (ex.InnerException, "#A4"); Assert.IsNotNull (ex.Message, "#A5"); Assert.AreEqual (2, ex.NativeErrorCode, "#A6"); } // relative path, no shell try { Process.Start ("shouldnoteverexist.exe", string.Empty); Assert.Fail ("#B1"); } catch (Win32Exception ex) { // The system cannot find the file specified Assert.AreEqual (typeof (Win32Exception), ex.GetType (), "#B2"); Assert.AreEqual (-2147467259, ex.ErrorCode, "#B3"); Assert.IsNull (ex.InnerException, "#B4"); Assert.IsNotNull (ex.Message, "#B5"); Assert.AreEqual (2, ex.NativeErrorCode, "#B6"); } } #if NET_2_0 [Test] public void Start_UseShellExecuteWithEmptyUserName () { if (RunningOnUnix) Assert.Ignore ("On Unix and Mac OS X, we try " + "to open any file (using xdg-open, ...)" + " and we do not report an exception " + "if this fails."); string exe = @"c:\shouldnoteverexist.exe"; try { Process p = new Process (); p.StartInfo.FileName = exe; p.StartInfo.UseShellExecute = true; p.StartInfo.UserName = ""; p.Start (); Assert.Fail ("#1"); } catch (InvalidOperationException) { Assert.Fail ("#2"); } catch (Win32Exception) { } try { Process p = new Process (); p.StartInfo.FileName = exe; p.StartInfo.UseShellExecute = true; p.StartInfo.UserName = null; p.Start (); Assert.Fail ("#3"); } catch (InvalidOperationException) { Assert.Fail ("#4"); } catch (Win32Exception) { } } #endif [Test] // Start (string, string) public void Start4_FileName_Null () { try { Process.Start ((string) null, string.Empty); Assert.Fail ("#1"); } catch (InvalidOperationException ex) { // Cannot start process because a file name has // not been provided Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#2"); Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); } } [Test] public void StartInfo () { ProcessStartInfo startInfo = new ProcessStartInfo (); Process p = new Process (); Assert.IsNotNull (p.StartInfo, "#A1"); p.StartInfo = startInfo; Assert.AreSame (startInfo, p.StartInfo, "#A2"); } [Test] public void StartInfo_Null () { Process p = new Process (); try { p.StartInfo = null; Assert.Fail ("#1"); } catch (ArgumentNullException ex) { Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2"); Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); Assert.IsNotNull (ex.ParamName, "#5"); Assert.AreEqual ("value", ex.ParamName, "#6"); } } [Test] [NUnit.Framework.Category ("NotDotNet")] public void TestRedirectedOutputIsAsync () { // Test requires cygwin, so we just bail out for now. if (Path.DirectorySeparatorChar == '\\') return; Process p = new Process (); p.StartInfo = new ProcessStartInfo ("/bin/sh", "-c \"sleep 2; echo hello\""); p.StartInfo.RedirectStandardOutput = true; p.StartInfo.UseShellExecute = false; p.Start (); Stream stdout = p.StandardOutput.BaseStream; byte [] buffer = new byte [200]; // start async Read operation DateTime start = DateTime.Now; IAsyncResult ar = stdout.BeginRead (buffer, 0, buffer.Length, new AsyncCallback (Read), stdout); Assert.IsTrue ((DateTime.Now - start).TotalMilliseconds < 1000, "#01 BeginRead was not async"); p.WaitForExit (); Assert.AreEqual (0, p.ExitCode, "#02 script failure"); /* ar.AsyncWaitHandle.WaitOne (2000, false); if (bytesRead < "hello".Length) Assert.Fail ("#03 got {0} bytes", bytesRead); Assert.AreEqual ("hello", Encoding.Default.GetString (buffer, 0, 5), "#04"); */ } void Read (IAsyncResult ar) { Stream stm = (Stream) ar.AsyncState; bytesRead = stm.EndRead (ar); } static bool RunningOnUnix { get { int p = (int)Environment.OSVersion.Platform; return ((p == 128) || (p == 4) || (p == 6)); } } int bytesRead = -1; #if NET_2_0 // Not technically a 2.0 only test, but I use lambdas, so I need gmcs [Test] // This was for bug #459450 public void TestEventRaising () { EventWaitHandle errorClosed = new ManualResetEvent(false); EventWaitHandle outClosed = new ManualResetEvent(false); EventWaitHandle exited = new ManualResetEvent(false); Process p = new Process(); p.StartInfo = GetCrossPlatformStartInfo (); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.RedirectStandardInput = false; p.OutputDataReceived += (object sender, DataReceivedEventArgs e) => { if (e.Data == null) { outClosed.Set(); } }; p.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => { if (e.Data == null) { errorClosed.Set(); } }; p.Exited += (object sender, EventArgs e) => { exited.Set (); }; p.EnableRaisingEvents = true; p.Start(); p.BeginErrorReadLine(); p.BeginOutputReadLine(); Console.WriteLine("started, waiting for handles"); bool r = WaitHandle.WaitAll(new WaitHandle[] { errorClosed, outClosed, exited }, 10000, false); Assert.AreEqual (true, r, "Null Argument Events Raised"); } private ProcessStartInfo GetCrossPlatformStartInfo () { return RunningOnUnix ? new ProcessStartInfo ("/bin/ls", "/") : new ProcessStartInfo ("help", ""); } [Test] public void ProcessName_NotStarted () { Process p = new Process (); Exception e = null; try { String.IsNullOrEmpty (p.ProcessName); } catch (Exception ex) { e = ex; } Assert.IsNotNull (e, "ProcessName should raise if process was not started"); //msg should be "No process is associated with this object" Assert.AreEqual (e.GetType (), typeof (InvalidOperationException), "exception should be IOE, I got: " + e.GetType ().Name); Assert.IsNull (e.InnerException, "IOE inner exception should be null"); } [Test] public void ProcessName_AfterExit () { Process p = new Process (); p.StartInfo = GetCrossPlatformStartInfo (); p.Start (); p.WaitForExit (); String.IsNullOrEmpty (p.ExitCode + ""); Exception e = null; try { String.IsNullOrEmpty (p.ProcessName); } catch (Exception ex) { e = ex; } Assert.IsNotNull (e, "ProcessName should raise if process was finished"); //msg should be "Process has exited, so the requested information is not available" Assert.AreEqual (e.GetType (), typeof (InvalidOperationException), "exception should be IOE, I got: " + e.GetType ().Name); Assert.IsNull (e.InnerException, "IOE inner exception should be null"); } #endif } }
30.149091
100
0.643388
[ "MIT" ]
zlxy/Genesis-3D
Engine/extlibs/IosLibs/mono-2.6.7/mcs/class/System/Test/System.Diagnostics/ProcessTest.cs
24,873
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using CommunityToolkit.WinUI.Helpers; namespace UnitTests { internal class TestDeepLinkParser : DeepLinkParser { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "Call stack reviewed.")] public TestDeepLinkParser(string uri) : base(uri) { } public TestDeepLinkParser(Uri uri) : base(uri) { } } }
30.173913
168
0.684438
[ "MIT" ]
ehtick/Uno.WindowsCommunityToolkit
UnitTests/UnitTests.UWP/Helpers/TestDeepLinkParser.cs
694
C#
#region Copyright // ****************************************************************************************** // // SimplePath, Copyright © 2011, Alex Kring // // ****************************************************************************************** #endregion using UnityEngine; using System; using System.Collections.Generic; using SimpleAI.Planning; namespace SimpleAI.Navigation { /// <summary> ///These are the objects that can navigate. Inherit from this interface to define your own type ///of entity that can navigate around the world. /// </summary> public interface IPathAgent { /// <summary> ///Get the position of the path agent's feet (the position where his feet touch the ground). /// </summary> /// <returns> /// A <see cref="Vector3"/> /// </returns> Vector3 GetPathAgentFootPos(); /// <summary> ///Called when the agent's path request successfully completes. /// </summary> /// <param name="request"> /// A <see cref="IPathRequestQuery"/> /// </param> void OnPathAgentRequestSucceeded(IPathRequestQuery request); /// <summary> ///Called when the agent's path request fails to complete. /// </summary> void OnPathAgentRequestFailed(); } }
29.295455
100
0.54616
[ "Apache-2.0" ]
RutgersUniversityVirtualWorlds/FreshTherapyOffice
Assets/SimplePath/Main/Code/AI/Navigation/Pathing/IPathAgent.cs
1,292
C#
// Copyright 2018 Google Inc. 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. // NOTE: This file is a modified version of NdrParser.cs from OleViewDotNet // https://github.com/tyranid/oleviewdotnet. It's been relicensed from GPLv3 by // the original author James Forshaw to be used under the Apache License for this // project. using NtApiDotNet.Utilities.Memory; using NtApiDotNet.Win32; using NtApiDotNet.Win32.Debugger; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; namespace NtApiDotNet.Ndr { #pragma warning disable 1591 [Flags] [Serializable] public enum NdrInterpreterOptFlags : byte { ServerMustSize = 0x01, ClientMustSize = 0x02, HasReturn = 0x04, HasPipes = 0x08, HasAsyncUuid = 0x20, HasExtensions = 0x40, HasAsyncHandle = 0x80, } [Flags] [Serializable] public enum NdrInterpreterOptFlags2 : byte { HasNewCorrDesc = 0x01, ClientCorrCheck = 0x02, ServerCorrCheck = 0x04, HasNotify = 0x08, HasNotify2 = 0x10, HasComplexReturn = 0x20, HasRangeOnConformance = 0x40, HasBigByValParam = 0x80, Valid = HasNewCorrDesc | ClientCorrCheck | ServerCorrCheck | HasNotify | HasNotify2 | HasRangeOnConformance } #pragma warning restore 1591 internal class NdrTypeCache { private int _complex_id; public Dictionary<IntPtr, NdrBaseTypeReference> Cache { get; } public int GetNextComplexId() { return _complex_id++; } public NdrTypeCache() { Cache = new Dictionary<IntPtr, NdrBaseTypeReference>(); } internal void FixupLateBoundTypes() { foreach (var type in Cache.Values) { type.FixupLateBoundTypes(); } } } internal class NdrParseContext { public NdrTypeCache TypeCache { get; } public ISymbolResolver SymbolResolver { get; } public MIDL_STUB_DESC StubDesc { get; } public IntPtr TypeDesc { get; } public IMemoryReader Reader { get; } public NdrParserFlags Flags { get; } public NDR_EXPR_DESC ExprDesc { get; } public NdrInterpreterOptFlags2 OptFlags { get; } public bool HasFlag(NdrParserFlags flags) { return (Flags & flags) == flags; } internal NdrParseContext(NdrTypeCache type_cache, ISymbolResolver symbol_resolver, MIDL_STUB_DESC stub_desc, IntPtr type_desc, NDR_EXPR_DESC expr_desc, NdrInterpreterOptFlags2 opt_flags, IMemoryReader reader, NdrParserFlags parser_flags) { TypeCache = type_cache; SymbolResolver = symbol_resolver; StubDesc = stub_desc; TypeDesc = type_desc; ExprDesc = expr_desc; OptFlags = opt_flags; Reader = reader; Flags = parser_flags; } } /// <summary> /// Flags for the parser. /// </summary> [Flags] public enum NdrParserFlags { /// <summary> /// No flags. /// </summary> None = 0, /// <summary> /// Ignore processing any complex user marshal types. /// </summary> IgnoreUserMarshal = 1, } /// <summary> /// Class to parse NDR data into a structured format. /// </summary> public sealed class NdrParser { #region Private Members private readonly NdrTypeCache _type_cache; private readonly ISymbolResolver _symbol_resolver; private readonly IMemoryReader _reader; private readonly NdrParserFlags _parser_flags; private static NdrRpcServerInterface ReadRpcServerInterface(IMemoryReader reader, RPC_SERVER_INTERFACE server_interface, NdrTypeCache type_cache, ISymbolResolver symbol_resolver, NdrParserFlags parser_flags) { RPC_DISPATCH_TABLE dispatch_table = server_interface.GetDispatchTable(reader); var procs = ReadProcs(reader, server_interface.GetServerInfo(reader), 0, dispatch_table.DispatchTableCount, type_cache, symbol_resolver, null, parser_flags); return new NdrRpcServerInterface(server_interface.InterfaceId, server_interface.TransferSyntax, procs, server_interface.GetProtSeq(reader).Select(s => new NdrProtocolSequenceEndpoint(s, reader))); } private static IEnumerable<NdrProcedureDefinition> ReadProcs(IMemoryReader reader, MIDL_SERVER_INFO server_info, int start_offset, int dispatch_count, NdrTypeCache type_cache, ISymbolResolver symbol_resolver, IList<string> names, NdrParserFlags parser_flags) { RPC_SYNTAX_IDENTIFIER transfer_syntax = server_info.GetTransferSyntax(reader); IntPtr proc_str = IntPtr.Zero; IntPtr fmt_str_ofs = IntPtr.Zero; if (transfer_syntax.SyntaxGUID != NdrNativeUtils.DCE_TransferSyntax) { MIDL_SYNTAX_INFO[] syntax_info = server_info.GetSyntaxInfo(reader); if (!syntax_info.Any(s => s.TransferSyntax.SyntaxGUID == NdrNativeUtils.DCE_TransferSyntax)) { throw new NdrParserException("Can't parse NDR64 syntax data"); } MIDL_SYNTAX_INFO dce_syntax_info = syntax_info.First(s => s.TransferSyntax.SyntaxGUID == NdrNativeUtils.DCE_TransferSyntax); proc_str = dce_syntax_info.ProcString; fmt_str_ofs = dce_syntax_info.FmtStringOffset; } else { proc_str = server_info.ProcString; fmt_str_ofs = server_info.FmtStringOffset; } IntPtr[] dispatch_funcs = server_info.GetDispatchTable(reader, dispatch_count); MIDL_STUB_DESC stub_desc = server_info.GetStubDesc(reader); IntPtr type_desc = stub_desc.pFormatTypes; NDR_EXPR_DESC expr_desc = stub_desc.GetExprDesc(reader); List<NdrProcedureDefinition> procs = new List<NdrProcedureDefinition>(); if (fmt_str_ofs != IntPtr.Zero) { for (int i = start_offset; i < dispatch_count; ++i) { int fmt_ofs = reader.ReadInt16(fmt_str_ofs + i * 2); if (fmt_ofs >= 0) { string name = null; if (names != null) { name = names[i - start_offset]; } procs.Add(new NdrProcedureDefinition(reader, type_cache, symbol_resolver, stub_desc, proc_str + fmt_ofs, type_desc, expr_desc, dispatch_funcs[i], name, parser_flags)); } } } return procs.AsReadOnly(); } private void ReadTypes(IntPtr midl_type_pickling_info_ptr, IntPtr midl_stub_desc_ptr, IEnumerable<int> fmt_offsets) { if (midl_type_pickling_info_ptr == IntPtr.Zero) { throw new ArgumentException("Must specify the MIDL_TYPE_PICKLING_INFO pointer"); } if (midl_stub_desc_ptr == IntPtr.Zero) { throw new ArgumentException("Must specify the MIDL_STUB_DESC pointer"); } var pickle_info = _reader.ReadStruct<MIDL_TYPE_PICKLING_INFO>(midl_type_pickling_info_ptr); if (pickle_info.Version != 0x33205054) { throw new ArgumentException($"Unsupported picking type version {pickle_info.Version:X}"); } var flags = pickle_info.Flags.HasFlag(MidlTypePicklingInfoFlags.NewCorrDesc) ? NdrInterpreterOptFlags2.HasNewCorrDesc : 0; MIDL_STUB_DESC stub_desc = _reader.ReadStruct<MIDL_STUB_DESC>(midl_stub_desc_ptr); NdrParseContext context = new NdrParseContext(_type_cache, null, stub_desc, stub_desc.pFormatTypes, stub_desc.GetExprDesc(_reader), flags, _reader, NdrParserFlags.IgnoreUserMarshal); foreach (var i in fmt_offsets) { NdrBaseTypeReference.Read(context, i); } } [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void GetProxyDllInfo(out IntPtr pInfo, out IntPtr pId); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int DllGetClassObject(ref Guid clsid, ref Guid riid, out IntPtr ppv); private IList<NdrProcedureDefinition> ReadProcs(Guid base_iid, CInterfaceStubHeader stub) { int start_ofs = 3; if (base_iid == NdrNativeUtils.IID_IDispatch) { start_ofs = 7; } return ReadFromMidlServerInfo(stub.pServerInfo, start_ofs, stub.DispatchTableCount).ToList().AsReadOnly(); } private static IntPtr FindProxyDllInfo(SafeLoadLibraryHandle lib, Guid clsid) { try { GetProxyDllInfo get_proxy_dllinfo = lib.GetFunctionPointer<GetProxyDllInfo>(); get_proxy_dllinfo(out IntPtr pInfo, out IntPtr pId); return pInfo; } catch (Win32Exception) { } IntPtr psfactory = IntPtr.Zero; try { DllGetClassObject dll_get_class_object = lib.GetFunctionPointer<DllGetClassObject>(); Guid IID_IPSFactoryBuffer = NdrNativeUtils.IID_IPSFactoryBuffer; int hr = dll_get_class_object(ref clsid, ref IID_IPSFactoryBuffer, out psfactory); if (hr != 0) { throw new Win32Exception(hr); } // The PSFactoryBuffer object seems to be structured like on Win10 at least. // VTABLE* // Reference Count // ProxyFileInfo* IntPtr pInfo = System.Runtime.InteropServices.Marshal.ReadIntPtr(psfactory, 2 * IntPtr.Size); // TODO: Should add better checks here, // for example VTable should be in COMBASE and the pointer should be in the // server DLL's rdata section. But this is probably good enough for now. using (SafeLoadLibraryHandle module = SafeLoadLibraryHandle.GetModuleHandle(pInfo)) { if (module == null || lib.DangerousGetHandle() != module.DangerousGetHandle()) { return IntPtr.Zero; } } return pInfo; } catch (Win32Exception) { return IntPtr.Zero; } finally { if (psfactory != IntPtr.Zero) { System.Runtime.InteropServices.Marshal.Release(psfactory); } } } private bool InitFromProxyFileInfo(ProxyFileInfo proxy_file_info, IList<NdrComProxyDefinition> interfaces, HashSet<Guid> iid_set) { string[] names = proxy_file_info.GetNames(_reader); CInterfaceStubHeader[] stubs = proxy_file_info.GetStubs(_reader); Guid[] base_iids = proxy_file_info.GetBaseIids(_reader); for (int i = 0; i < names.Length; ++i) { Guid iid = stubs[i].GetIid(_reader); if (iid_set.Count == 0 || iid_set.Contains(iid)) { interfaces.Add(new NdrComProxyDefinition(names[i], iid, base_iids[i], stubs[i].DispatchTableCount, ReadProcs(base_iids[i], stubs[i]))); } } return true; } private bool InitFromProxyFileInfoArray(IntPtr proxy_file_info_array, IList<NdrComProxyDefinition> interfaces, HashSet<Guid> iid_set) { foreach (var file_info in _reader.EnumeratePointerList<ProxyFileInfo>(proxy_file_info_array)) { if (!InitFromProxyFileInfo(file_info, interfaces, iid_set)) { return false; } } return true; } private bool InitFromFile(string path, Guid clsid, IList<NdrComProxyDefinition> interfaces, IEnumerable<Guid> iids) { if (iids == null) { iids = new Guid[0]; } HashSet<Guid> iid_set = new HashSet<Guid>(iids); using (SafeLoadLibraryHandle lib = SafeLoadLibraryHandle.LoadLibrary(path)) { _symbol_resolver?.LoadModule(path, lib.DangerousGetHandle()); IntPtr pInfo = FindProxyDllInfo(lib, clsid); if (pInfo == IntPtr.Zero) { return false; } return InitFromProxyFileInfoArray(pInfo, interfaces, iid_set); } } private static void CheckSymbolResolver(NtProcess process, ISymbolResolver symbol_resolver) { int pid = process == null ? NtProcess.Current.ProcessId : process.ProcessId; if (symbol_resolver is DbgHelpSymbolResolver dbghelp_resolver) { if (dbghelp_resolver.Process.ProcessId != pid) { throw new ArgumentException("Symbol resolver must be for the same process as the passed process"); } } } [HandleProcessCorruptedStateExceptions] private static T RunWithAccessCatch<T>(Func<T> func) { try { return func(); } catch (Exception ex) { if (ex is NdrParserException) { // Re-throw if already is an NDR parser exception. throw; } throw new NdrParserException("Error while parsing NDR structures"); } } private static void RunWithAccessCatch(Action func) { RunWithAccessCatch(() => { func(); return 0; } ); } private static IMemoryReader CreateReader(NtProcess process) { if (process == null || process.ProcessId == NtProcess.Current.ProcessId) { return new CurrentProcessMemoryReader(); } else { return ProcessMemoryReader.Create(process); } } #endregion #region Internal Members /// <summary> /// Constructor. /// </summary> /// <param name="reader">Memory reader to parse from.</param> /// <param name="process">Process to read from.</param> /// <param name="symbol_resolver">Specify a symbol resolver to use for looking up symbols.</param> /// <param name="parser_flags">Flags which affect the parsing operation.</param> internal NdrParser(IMemoryReader reader, NtProcess process, ISymbolResolver symbol_resolver, NdrParserFlags parser_flags) { CheckSymbolResolver(process, symbol_resolver); _reader = reader; _symbol_resolver = symbol_resolver; _type_cache = new NdrTypeCache(); _parser_flags = parser_flags; } #endregion #region Public Constructors /// <summary> /// Constructor. /// </summary> /// <param name="process">Process to parse from.</param> /// <param name="symbol_resolver">Specify a symbol resolver to use for looking up symbols.</param> public NdrParser(NtProcess process, ISymbolResolver symbol_resolver) : this(process, symbol_resolver, NdrParserFlags.None) { } /// <summary> /// Constructor. /// </summary> /// <param name="process">Process to parse from.</param> /// <param name="symbol_resolver">Specify a symbol resolver to use for looking up symbols.</param> /// <param name="parser_flags">Flags which affect the parsing operation.</param> public NdrParser(NtProcess process, ISymbolResolver symbol_resolver, NdrParserFlags parser_flags) : this(CreateReader(process), process, symbol_resolver, parser_flags) { } /// <summary> /// Constructor. /// </summary> /// <param name="symbol_resolver">Specify a symbol resolver to use for looking up symbols.</param> public NdrParser(ISymbolResolver symbol_resolver) : this(null, symbol_resolver) { } /// <summary> /// Constructor. /// </summary> /// <param name="process">Process to parse from.</param> public NdrParser(NtProcess process) : this(process, null) { } /// <summary> /// Constructor. /// </summary> public NdrParser() : this(null, null) { } #endregion #region Public Methods /// <summary> /// Read COM proxy information from a ProxyFileInfo structure. /// </summary> /// <param name="proxy_file_info">The address of the ProxyFileInfo structure.</param> /// <returns>The list of parsed proxy definitions.</returns> public IEnumerable<NdrComProxyDefinition> ReadFromProxyFileInfo(IntPtr proxy_file_info) { List<NdrComProxyDefinition> interfaces = new List<NdrComProxyDefinition>(); if (!RunWithAccessCatch(() => InitFromProxyFileInfo(_reader.ReadStruct<ProxyFileInfo>(proxy_file_info), interfaces, new HashSet<Guid>()))) { throw new NdrParserException("Can't find proxy information in server DLL"); } return interfaces.AsReadOnly(); } /// <summary> /// Read COM proxy information from an array of pointers to ProxyFileInfo structures. /// </summary> /// <param name="proxy_file_info_array">The address of an array of pointers to ProxyFileInfo structures. The last pointer should be NULL.</param> /// <returns>The list of parsed proxy definitions.</returns> public IEnumerable<NdrComProxyDefinition> ReadFromProxyFileInfoArray(IntPtr proxy_file_info_array) { List<NdrComProxyDefinition> interfaces = new List<NdrComProxyDefinition>(); if (!RunWithAccessCatch(() => InitFromProxyFileInfoArray(proxy_file_info_array, interfaces, new HashSet<Guid>()))) { throw new NdrParserException("Can't find proxy information in server DLL"); } return interfaces.AsReadOnly(); } /// <summary> /// Read COM proxy information from a file. /// </summary> /// <param name="path">The path to the DLL containing the proxy.</param> /// <param name="clsid">Optional CLSID for the proxy class.</param> /// <param name="iids">List of IIDs to parse.</param> /// <returns>The list of parsed proxy definitions.</returns> public IEnumerable<NdrComProxyDefinition> ReadFromComProxyFile(string path, Guid clsid, IEnumerable<Guid> iids) { if (!_reader.InProcess) { throw new NdrParserException("Can't parse COM proxy information from a file out of process."); } List<NdrComProxyDefinition> interfaces = new List<NdrComProxyDefinition>(); if (!RunWithAccessCatch(() => InitFromFile(path, clsid, interfaces, iids))) { throw new NdrParserException("Can't find proxy information in server DLL"); } return interfaces.AsReadOnly(); } /// <summary> /// Read COM proxy information from a file. /// </summary> /// <param name="path">The path to the DLL containing the proxy.</param> /// <param name="clsid">Optional CLSID for the proxy class.</param> /// <returns>The list of parsed proxy definitions.</returns> public IEnumerable<NdrComProxyDefinition> ReadFromComProxyFile(string path, Guid clsid) { return ReadFromComProxyFile(path, clsid, null); } /// <summary> /// Read COM proxy information from a file. /// </summary> /// <param name="path">The path to the DLL containing the proxy.</param> /// <returns>The list of parsed proxy definitions.</returns> public IEnumerable<NdrComProxyDefinition> ReadFromComProxyFile(string path) { return ReadFromComProxyFile(path, Guid.Empty); } /// <summary> /// Parse NDR content from an RPC_SERVER_INTERFACE structure in memory. /// </summary> /// <param name="server_interface">Pointer to the RPC_SERVER_INTERFACE.</param> /// <returns>The parsed NDR content.</returns> public NdrRpcServerInterface ReadFromRpcServerInterface(IntPtr server_interface) { return RunWithAccessCatch(() => ReadRpcServerInterface(_reader, _reader.ReadStruct<RPC_SERVER_INTERFACE>(server_interface), _type_cache, _symbol_resolver, _parser_flags)); } /// <summary> /// Parse NDR content from an RPC_SERVER_INTERFACE structure in memory. Deprecated. /// </summary> /// <param name="server_interface">Pointer to the RPC_SERVER_INTERFACE.</param> /// <returns>The parsed NDR content.</returns> [Obsolete("Use ReadFromRpcServerInterface instead.")] public NdrRpcServerInterface ReadRpcServerInterface(IntPtr server_interface) { return ReadFromRpcServerInterface(server_interface); } /// <summary> /// Parse NDR content from an RPC_SERVER_INTERFACE structure in memory. /// </summary> /// <param name="dll_path">The path to a DLL containing the RPC_SERVER_INTERFACE.</param> /// <param name="offset">Offset to the RPC_SERVER_INTERFACE from the base of the DLL.</param> /// <returns>The parsed NDR content.</returns> public NdrRpcServerInterface ReadFromRpcServerInterface(string dll_path, int offset) { using (var lib = SafeLoadLibraryHandle.LoadLibrary(dll_path, LoadLibraryFlags.DontResolveDllReferences)) { _symbol_resolver?.LoadModule(dll_path, lib.DangerousGetHandle()); return ReadFromRpcServerInterface(lib.DangerousGetHandle() + offset); } } /// <summary> /// Parse NDR procedures from an MIDL_SERVER_INFO structure in memory. /// </summary> /// <param name="server_info">Pointer to the MIDL_SERVER_INFO.</param> /// <param name="dispatch_count">Number of dispatch functions to parse.</param> /// <param name="start_offset">The start offset to parse from. This is used for COM where the first few proxy stubs are not implemented.</param> /// <param name="names">List of names for the valid procedures. Should either be null or a list equal in size to dispatch_count - start_offset.</param> /// <returns>The parsed NDR content.</returns> public IEnumerable<NdrProcedureDefinition> ReadFromMidlServerInfo(IntPtr server_info, int start_offset, int dispatch_count, IList<string> names) { if (names != null && names.Count != (dispatch_count - start_offset)) { throw new NdrParserException("List of names must be same size of the total methods to parse"); } return RunWithAccessCatch(() => ReadProcs(_reader, _reader.ReadStruct<MIDL_SERVER_INFO>(server_info), start_offset, dispatch_count, _type_cache, _symbol_resolver, names, _parser_flags)); } /// <summary> /// Parse NDR procedures from an MIDL_SERVER_INFO structure in memory. /// </summary> /// <param name="server_info">Pointer to the MIDL_SERVER_INFO.</param> /// <param name="dispatch_count">Number of dispatch functions to parse.</param> /// <param name="start_offset">The start offset to parse from. This is used for COM where the first few proxy stubs are not implemented.</param> /// <returns>The parsed NDR content.</returns> public IEnumerable<NdrProcedureDefinition> ReadFromMidlServerInfo(IntPtr server_info, int start_offset, int dispatch_count) { return RunWithAccessCatch(() => ReadProcs(_reader, _reader.ReadStruct<MIDL_SERVER_INFO>(server_info), start_offset, dispatch_count, _type_cache, _symbol_resolver, null, _parser_flags)); } #endregion #region Public Properties /// <summary> /// List of parsed types from the NDR. /// </summary> public IEnumerable<NdrBaseTypeReference> Types { get { _type_cache.FixupLateBoundTypes(); return _type_cache.Cache.Values; } } /// <summary> /// List of parsed complex types from the NDR. /// </summary> public IEnumerable<NdrComplexTypeReference> ComplexTypes { get { return Types.OfType<NdrComplexTypeReference>(); } } #endregion #region Static Methods /// <summary> /// Parse NDR complex type information from a pickling structure. Used to extract explicit Encode/Decode method information. /// </summary> /// <param name="process">The process to read from.</param> /// <param name="midl_type_pickling_info">Pointer to the MIDL_TYPE_PICKLING_INFO structure.</param> /// <param name="midl_stub_desc">The pointer to the MIDL_STUB_DESC structure.</param> /// <param name="start_offsets">Offsets into the format string to the start of the types.</param> /// <returns>The list of complex types.</returns> /// <remarks>This function is used to extract type information for calls to NdrMesTypeDecode2. MIDL_TYPE_PICKLING_INFO is the second parameter, /// MIDL_STUB_DESC is the third (minus the offset).</remarks> public static IEnumerable<NdrComplexTypeReference> ReadPicklingComplexTypes(NtProcess process, IntPtr midl_type_pickling_info, IntPtr midl_stub_desc, params int[] start_offsets) { if (start_offsets.Length == 0) { return new NdrComplexTypeReference[0]; } NdrParser parser = new NdrParser(process, null, NdrParserFlags.IgnoreUserMarshal); RunWithAccessCatch(() => parser.ReadTypes(midl_type_pickling_info, midl_stub_desc, start_offsets)); return parser.ComplexTypes; } /// <summary> /// Parse NDR complex type information from a pickling structure. Used to extract explicit Encode/Decode method information. /// </summary> /// <param name="midl_type_pickling_info">Pointer to the MIDL_TYPE_PICKLING_INFO structure.</param> /// <param name="midl_stub_desc">The pointer to the MIDL_STUB_DESC structure.</param> /// <param name="start_offsets">Offsets into the format string to the start of the types.</param> /// <returns>The list of complex types.</returns> /// <remarks>This function is used to extract type information for calls to NdrMesTypeDecode2. MIDL_TYPE_PICKLING_INFO is the second parameter, /// MIDL_STUB_DESC is the third (minus the offset).</remarks> public static IEnumerable<NdrComplexTypeReference> ReadPicklingComplexTypes(IntPtr midl_type_pickling_info, IntPtr midl_stub_desc, params int[] start_offsets) { return ReadPicklingComplexTypes(null, midl_type_pickling_info, midl_stub_desc, start_offsets); } #endregion } }
41.906706
185
0.611695
[ "Apache-2.0" ]
InitRoot/sandbox-attacksurface-analysis-tools
NtApiDotNet/Ndr/NdrParser.cs
28,750
C#
using System; using System.IO; using System.Text.Json; using System.Threading.Tasks; using Covidiot.Models; namespace Covidiot.Services { public static class JsonReadService { public static Task<TimedNodeAction> ReadAction(MapNodeCoordinate coordinate) => ReadAction($"{coordinate.XCoordinate}{coordinate.YCoordinate}"); internal static async Task<TimedNodeAction> ReadAction(string tileCoordinate) { var location = Path.Join(Startup.DataDirectory, $"{tileCoordinate}.json"); var reader = File.Open(location, FileMode.Open, FileAccess.Read); var model = await JsonSerializer.DeserializeAsync<TimedNodeAction>(reader); reader.Close(); return model; } } }
35.045455
87
0.682231
[ "MIT" ]
WhatzGames/Hackathon-Leer-2021
Covidiot/Covidiot/Services/JsonReadService.cs
773
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Runtime.Serialization.Json; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Geocoding.Here { /// <remarks> /// https://github.com/chadly/Geocoding.net/blob/master/src/Geocoding.Here/HereGeocoder.cs /// https://developer.here.com/documentation/geocoder/topics/request-constructing.html /// </remarks> public class HereGeocoder : IGeocoder { const string GeocodingQuery = "https://geocoder.ls.hereapi.com/6.2/geocode.json?apiKey={0}&{1}"; const string ReverseGeocodingQuery = "https://reverse.geocoder.ls.hereapi.com/6.2/reversegeocode.json?apiKey={0}&mode=retrieveAddresses&{1}"; const string Searchtext = "searchtext={0}"; const string Prox = "prox={0}"; const string Street = "street={0}"; const string City = "city={0}"; const string State = "state={0}"; const string PostalCode = "postalcode={0}"; const string Country = "country={0}"; readonly string _apiKey; public IWebProxy Proxy { get; set; } public Location UserLocation { get; set; } public Bounds UserMapView { get; set; } public int? MaxResults { get; set; } public HereGeocoder(string apiKey) { if (string.IsNullOrWhiteSpace(apiKey)) throw new ArgumentException("apiKey can not be null or empty"); this._apiKey = apiKey; } private string GetQueryUrl(string address) { var parameters = new StringBuilder(); var first = AppendParameter(parameters, address, Searchtext, true); AppendGlobalParameters(parameters, first); return string.Format(GeocodingQuery, _apiKey, parameters); } private string GetQueryUrl(string street, string city, string state, string postalCode, string country) { var parameters = new StringBuilder(); var first = AppendParameter(parameters, street, Street, true); first = AppendParameter(parameters, city, City, first); first = AppendParameter(parameters, state, State, first); first = AppendParameter(parameters, postalCode, PostalCode, first); first = AppendParameter(parameters, country, Country, first); AppendGlobalParameters(parameters, first); return string.Format(GeocodingQuery, _apiKey, parameters); } private string GetQueryUrl(double latitude, double longitude) { var parameters = new StringBuilder(); var first = AppendParameter(parameters, string.Format(CultureInfo.InvariantCulture, "{0},{1}", latitude, longitude), Prox, true); AppendGlobalParameters(parameters, first); return string.Format(ReverseGeocodingQuery, _apiKey, parameters); } private IEnumerable<KeyValuePair<string, string>> GetGlobalParameters() { if (UserLocation != null) yield return new KeyValuePair<string, string>("prox", UserLocation.ToString()); if (UserMapView != null) yield return new KeyValuePair<string, string>("mapview", string.Concat(UserMapView.SouthWest.ToString(), ",", UserMapView.NorthEast.ToString())); if (MaxResults != null && MaxResults.Value > 0) yield return new KeyValuePair<string, string>("maxresults", MaxResults.Value.ToString(CultureInfo.InvariantCulture)); } // ReSharper disable once UnusedMethodReturnValue.Local private bool AppendGlobalParameters(StringBuilder parameters, bool first) { var values = GetGlobalParameters().ToArray(); if (!first) parameters.Append("&"); parameters.Append(BuildQueryString(values)); return first && !values.Any(); } private string BuildQueryString(IEnumerable<KeyValuePair<string, string>> parameters) { var builder = new StringBuilder(); foreach (var pair in parameters) { if (builder.Length > 0) builder.Append("&"); builder.Append(UrlEncode(pair.Key)); builder.Append("="); builder.Append(UrlEncode(pair.Value)); } return builder.ToString(); } public async Task<IEnumerable<HereAddress>> GeocodeAsync(string address, CancellationToken cancellationToken = default(CancellationToken)) { try { var url = GetQueryUrl(address); var response = await GetResponse(url, cancellationToken).ConfigureAwait(false); return ParseResponse(response); } catch (Exception ex) { throw new HereGeocodingException(ex); } } public async Task<IEnumerable<HereAddress>> GeocodeAsync(string street, string city, string state, string postalCode, string country, CancellationToken cancellationToken = default(CancellationToken)) { try { var url = GetQueryUrl(street, city, state, postalCode, country); var response = await GetResponse(url, cancellationToken).ConfigureAwait(false); return ParseResponse(response); } catch (Exception ex) { throw new HereGeocodingException(ex); } } public async Task<IEnumerable<HereAddress>> ReverseGeocodeAsync(Location location, CancellationToken cancellationToken = default(CancellationToken)) { if (location == null) throw new ArgumentNullException(nameof(location)); return await ReverseGeocodeAsync(location.Latitude, location.Longitude, cancellationToken).ConfigureAwait(false); } public async Task<IEnumerable<HereAddress>> ReverseGeocodeAsync(double latitude, double longitude, CancellationToken cancellationToken = default(CancellationToken)) { try { var url = GetQueryUrl(latitude, longitude); var response = await GetResponse(url, cancellationToken).ConfigureAwait(false); return ParseResponse(response); } catch (Exception ex) { throw new HereGeocodingException(ex); } } async Task<IEnumerable<Address>> IGeocoder.GeocodeAsync(string address, CancellationToken cancellationToken) { return await GeocodeAsync(address, cancellationToken).ConfigureAwait(false); } async Task<IEnumerable<Address>> IGeocoder.GeocodeAsync(string street, string city, string state, string postalCode, string country, CancellationToken cancellationToken) { return await GeocodeAsync(street, city, state, postalCode, country, cancellationToken).ConfigureAwait(false); } async Task<IEnumerable<Address>> IGeocoder.ReverseGeocodeAsync(Location location, CancellationToken cancellationToken) { return await ReverseGeocodeAsync(location, cancellationToken).ConfigureAwait(false); } async Task<IEnumerable<Address>> IGeocoder.ReverseGeocodeAsync(double latitude, double longitude, CancellationToken cancellationToken) { return await ReverseGeocodeAsync(latitude, longitude, cancellationToken).ConfigureAwait(false); } private bool AppendParameter(StringBuilder sb, string parameter, string format, bool first) { if (!string.IsNullOrEmpty(parameter)) { if (!first) { sb.Append('&'); } sb.Append(string.Format(format, UrlEncode(parameter))); return false; } return first; } private IEnumerable<HereAddress> ParseResponse(Json.Response response) { foreach (var view in response.View) { foreach (var result in view.Result) { var location = result.Location; yield return new HereAddress( location.Address.Label, new Location(location.DisplayPosition.Latitude, location.DisplayPosition.Longitude), location.Address.Street, location.Address.HouseNumber, location.Address.City, location.Address.State, location.Address.PostalCode, location.Address.Country, (HereLocationType)Enum.Parse(typeof(HereLocationType), location.LocationType, true)); } } } private HttpRequestMessage CreateRequest(string url) { return new HttpRequestMessage(HttpMethod.Get, url); } private HttpClient BuildClient() { if (this.Proxy == null) return new HttpClient(); var handler = new HttpClientHandler {Proxy = this.Proxy}; return new HttpClient(handler); } private async Task<Json.Response> GetResponse(string queryUrl, CancellationToken cancellationToken) { using (var client = BuildClient()) { var response = await client.SendAsync(CreateRequest(queryUrl), cancellationToken).ConfigureAwait(false); using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { var jsonSerializer = new DataContractJsonSerializer(typeof(Json.ServerResponse)); var serverResponse = (Json.ServerResponse)jsonSerializer.ReadObject(stream); if (serverResponse.ErrorType != null) { throw new HereGeocodingException(serverResponse.Details, serverResponse.ErrorType, serverResponse.ErrorType); } return serverResponse.Response; } } } private string UrlEncode(string toEncode) { if (string.IsNullOrEmpty(toEncode)) return string.Empty; return WebUtility.UrlEncode(toEncode); } } }
33.421456
201
0.736329
[ "MIT" ]
StanDeMan/Geocoding
src/Geocoding.Here/HereGeocoder.cs
8,725
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; namespace System.Linq.Expressions { /// <summary> /// The base type for all nodes in Expression Trees. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] public abstract partial class Expression { private static readonly CacheDict<Type, MethodInfo> s_lambdaDelegateCache = new CacheDict<Type, MethodInfo>(40); private static volatile CacheDict<Type, Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>> s_lambdaFactories; // For 4.0, many frequently used Expression nodes have had their memory // footprint reduced by removing the Type and NodeType fields. This has // large performance benefits to all users of Expression Trees. // // To support the 3.5 protected constructor, we store the fields that // used to be here in a ConditionalWeakTable. private class ExtensionInfo { public ExtensionInfo(ExpressionType nodeType, Type type) { NodeType = nodeType; Type = type; } internal readonly ExpressionType NodeType; internal readonly Type Type; } private static ConditionalWeakTable<Expression, ExtensionInfo> s_legacyCtorSupportTable; /// <summary> /// Constructs a new instance of <see cref="Expression"/>. /// </summary> /// <param name="nodeType">The <see ctype="ExpressionType"/> of the <see cref="Expression"/>.</param> /// <param name="type">The <see cref="Type"/> of the <see cref="Expression"/>.</param> [Obsolete("use a different constructor that does not take ExpressionType. Then override NodeType and Type properties to provide the values that would be specified to this constructor.")] protected Expression(ExpressionType nodeType, Type type) { // Can't enforce anything that V1 didn't if (s_legacyCtorSupportTable == null) { Interlocked.CompareExchange( ref s_legacyCtorSupportTable, new ConditionalWeakTable<Expression, ExtensionInfo>(), null ); } s_legacyCtorSupportTable.Add(this, new ExtensionInfo(nodeType, type)); } /// <summary> /// Constructs a new instance of <see cref="Expression"/>. /// </summary> protected Expression() { } /// <summary> /// The <see cref="ExpressionType"/> of the <see cref="Expression"/>. /// </summary> public virtual ExpressionType NodeType { get { ExtensionInfo extInfo; if (s_legacyCtorSupportTable != null && s_legacyCtorSupportTable.TryGetValue(this, out extInfo)) { return extInfo.NodeType; } // the extension expression failed to override NodeType throw Error.ExtensionNodeMustOverrideProperty("Expression.NodeType"); } } /// <summary> /// The <see cref="Type"/> of the value represented by this <see cref="Expression"/>. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public virtual Type Type { get { ExtensionInfo extInfo; if (s_legacyCtorSupportTable != null && s_legacyCtorSupportTable.TryGetValue(this, out extInfo)) { return extInfo.Type; } // the extension expression failed to override Type throw Error.ExtensionNodeMustOverrideProperty("Expression.Type"); } } /// <summary> /// Indicates that the node can be reduced to a simpler node. If this /// returns true, Reduce() can be called to produce the reduced form. /// </summary> public virtual bool CanReduce { get { return false; } } /// <summary> /// Reduces this node to a simpler expression. If CanReduce returns /// true, this should return a valid expression. This method is /// allowed to return another node which itself must be reduced. /// </summary> /// <returns>The reduced expression.</returns> public virtual Expression Reduce() { if (CanReduce) throw Error.ReducibleMustOverrideReduce(); return this; } /// <summary> /// Reduces the node and then calls the visitor delegate on the reduced expression. /// Throws an exception if the node isn't reducible. /// </summary> /// <param name="visitor">An instance of <see cref="Func{Expression, Expression}"/>.</param> /// <returns>The expression being visited, or an expression which should replace it in the tree.</returns> /// <remarks> /// Override this method to provide logic to walk the node's children. /// A typical implementation will call visitor.Visit on each of its /// children, and if any of them change, should return a new copy of /// itself with the modified children. /// </remarks> protected internal virtual Expression VisitChildren(ExpressionVisitor visitor) { if (!CanReduce) throw Error.MustBeReducible(); return visitor.Visit(ReduceAndCheck()); } /// <summary> /// Dispatches to the specific visit method for this node type. For /// example, <see cref="MethodCallExpression" /> will call into /// <see cref="ExpressionVisitor.VisitMethodCall" />. /// </summary> /// <param name="visitor">The visitor to visit this node with.</param> /// <returns>The result of visiting this node.</returns> /// <remarks> /// This default implementation for <see cref="ExpressionType.Extension" /> /// nodes will call <see cref="ExpressionVisitor.VisitExtension" />. /// Override this method to call into a more specific method on a derived /// visitor class of ExprressionVisitor. However, it should still /// support unknown visitors by calling VisitExtension. /// </remarks> protected internal virtual Expression Accept(ExpressionVisitor visitor) { return visitor.VisitExtension(this); } /// <summary> /// Reduces this node to a simpler expression. If CanReduce returns /// true, this should return a valid expression. This method is /// allowed to return another node which itself must be reduced. /// </summary> /// <returns>The reduced expression.</returns> /// <remarks > /// Unlike Reduce, this method checks that the reduced node satisfies /// certain invariants. /// </remarks> public Expression ReduceAndCheck() { if (!CanReduce) throw Error.MustBeReducible(); var newNode = Reduce(); // 1. Reduction must return a new, non-null node // 2. Reduction must return a new node whose result type can be assigned to the type of the original node if (newNode == null || newNode == this) throw Error.MustReduceToDifferent(); if (!TypeUtils.AreReferenceAssignable(Type, newNode.Type)) throw Error.ReducedNotCompatible(); return newNode; } /// <summary> /// Reduces the expression to a known node type (i.e. not an Extension node) /// or simply returns the expression if it is already a known type. /// </summary> /// <returns>The reduced expression.</returns> public Expression ReduceExtensions() { var node = this; while (node.NodeType == ExpressionType.Extension) { node = node.ReduceAndCheck(); } return node; } /// <summary> /// Creates a <see cref="String"/> representation of the Expression. /// </summary> /// <returns>A <see cref="String"/> representation of the Expression.</returns> public override string ToString() { return ExpressionStringBuilder.ExpressionToString(this); } /// <summary> /// Creates a <see cref="String"/> representation of the Expression. /// </summary> /// <returns>A <see cref="String"/> representation of the Expression.</returns> private string DebugView { // Note that this property is often accessed using reflection. As such it will have more dependencies than one // might surmise from its being internal, and removing it requires greater caution than with other internal methods. get { using (System.IO.StringWriter writer = new System.IO.StringWriter(CultureInfo.CurrentCulture)) { DebugViewWriter.WriteTo(this, writer); return writer.ToString(); } } } /// <summary> /// Helper used for ensuring we only return 1 instance of a ReadOnlyCollection of T. /// /// This is called from various methods where we internally hold onto an IList of T /// or a readonly collection of T. We check to see if we've already returned a /// readonly collection of T and if so simply return the other one. Otherwise we do /// a thread-safe replacement of the list w/ a readonly collection which wraps it. /// /// Ultimately this saves us from having to allocate a ReadOnlyCollection for our /// data types because the compiler is capable of going directly to the IList of T. /// </summary> internal static ReadOnlyCollection<T> ReturnReadOnly<T>(ref IList<T> collection) { return ExpressionUtils.ReturnReadOnly<T>(ref collection); } /// <summary> /// Helper used for ensuring we only return 1 instance of a ReadOnlyCollection of T. /// /// This is similar to the ReturnReadOnly of T. This version supports nodes which hold /// onto multiple Expressions where one is typed to object. That object field holds either /// an expression or a ReadOnlyCollection of Expressions. When it holds a ReadOnlyCollection /// the IList which backs it is a ListArgumentProvider which uses the Expression which /// implements IArgumentProvider to get 2nd and additional values. The ListArgumentProvider /// continues to hold onto the 1st expression. /// /// This enables users to get the ReadOnlyCollection w/o it consuming more memory than if /// it was just an array. Meanwhile The DLR internally avoids accessing which would force /// the readonly collection to be created resulting in a typical memory savings. /// </summary> internal static ReadOnlyCollection<Expression> ReturnReadOnly(IArgumentProvider provider, ref object collection) { return ExpressionUtils.ReturnReadOnly(provider, ref collection); } /// <summary> /// Helper which is used for specialized subtypes which use ReturnReadOnly(ref object, ...). /// This is the reverse version of ReturnReadOnly which takes an IArgumentProvider. /// /// This is used to return the 1st argument. The 1st argument is typed as object and either /// contains a ReadOnlyCollection or the Expression. We check for the Expression and if it's /// present we return that, otherwise we return the 1st element of the ReadOnlyCollection. /// </summary> internal static T ReturnObject<T>(object collectionOrT) where T : class { return ExpressionUtils.ReturnObject<T>(collectionOrT); } private static void RequiresCanRead(Expression expression, string paramName) { ExpressionUtils.RequiresCanRead(expression, paramName); } private static void RequiresCanRead(IReadOnlyList<Expression> items, string paramName) { Debug.Assert(items != null); // this is called a lot, avoid allocating an enumerator if we can... for (int i = 0; i < items.Count; i++) { RequiresCanRead(items[i], paramName); } } private static void RequiresCanWrite(Expression expression, string paramName) { if (expression == null) { throw new ArgumentNullException(paramName); } switch (expression.NodeType) { case ExpressionType.Index: PropertyInfo indexer = ((IndexExpression)expression).Indexer; if (indexer == null || indexer.CanWrite) { return; } break; case ExpressionType.MemberAccess: MemberInfo member = ((MemberExpression)expression).Member; PropertyInfo prop = member as PropertyInfo; if (prop != null) { if(prop.CanWrite) { return; } } else { Debug.Assert(member is FieldInfo); FieldInfo field = (FieldInfo)member; if (!(field.IsInitOnly || field.IsLiteral)) { return; } } break; case ExpressionType.Parameter: return; } throw new ArgumentException(Strings.ExpressionMustBeWriteable, paramName); } } }
42.883721
194
0.593818
[ "MIT" ]
Priya91/corefx-1
src/System.Linq.Expressions/src/System/Linq/Expressions/Expression.cs
14,752
C#
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\EnvironmentQuery\EnvQueryDebugHelpers.h:157 namespace UnrealEngine { public partial class UEnvQueryDebugHelpers : UObject { public UEnvQueryDebugHelpers(IntPtr adress) : base(adress) { } public UEnvQueryDebugHelpers(UObject Parent = null, string Name = "EnvQueryDebugHelpers") : base(IntPtr.Zero) { NativePointer = E_NewObject_UEnvQueryDebugHelpers(Parent, Name); NativeManager.AddNativeWrapper(NativePointer, this); } #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_NewObject_UEnvQueryDebugHelpers(IntPtr Parent, string Name); #endregion public static implicit operator IntPtr(UEnvQueryDebugHelpers self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator UEnvQueryDebugHelpers(ObjectPointerDescription PtrDesc) { return NativeManager.GetWrapper<UEnvQueryDebugHelpers>(PtrDesc); } } }
31.818182
134
0.767857
[ "Apache-2.0" ]
mrkriv/UnrealDotNet
Plugins/UnrealDotNet/Source/UnrealEngineSharp/Generate/Class/UEnvQueryDebugHelpers.cs
1,400
C#
 using ExtCore.Mvc.Infrastructure.Actions; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Builder; using System; namespace Barebone.Actions { public class UseMvcAction : IUseMvcAction { public int Priority => 1000; public void Execute(IRouteBuilder routeBuilder, IServiceProvider serviceProvider) { routeBuilder.MapRoute(name: "Default", template: "{controller}/{action}", defaults: new {controller = "Barebone", action="Index" }); } } }
27
144
0.697856
[ "Apache-2.0" ]
cedriclange/EducationSolution
EducationSolution/Barebone/Actions/UseMvcAction.cs
515
C#
using System; namespace LibrarySystem.Web.Models { public class ErrorViewModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } }
19.545455
70
0.674419
[ "MIT" ]
DiyanLyubchev/LibraryManagementSystem
LibraryDataBaseEF/LibrarySystem.Web/Models/ErrorViewModel.cs
215
C#
#region License /* Copyright © 2014-2021 European Support Limited 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 amdocs.ginger.GingerCoreNET; using Amdocs.Ginger.Common; using Amdocs.Ginger.Common.Enums; using Amdocs.Ginger.Common.InterfacesLib; using Amdocs.Ginger.Repository; using Ginger; using Ginger.SolutionWindows.TreeViewItems; using GingerCore; using GingerCore.Platforms; using GingerWPF.TreeViewItemsLib; using GingerWPF.UserControlsLib.UCTreeView; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Windows; using System.Windows.Controls; namespace GingerWPF.AgentsLib { /// <summary> /// Interaction logic for MapApplicationAgentPage.xaml /// </summary> public partial class MapApplicationAgentPage : Page { ObservableList<IApplicationAgent> mApps; public MapApplicationAgentPage(ObservableList<IApplicationAgent> Apps) { InitializeComponent(); mApps = Apps; AppsListBox.ItemsSource = Apps; AppsListBox.SelectionChanged += AppsListBox_SelectionChanged; } private void AppsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { mApps.CurrentItem = (ApplicationAgent)AppsListBox.SelectedItem; } public GenericWindow ShowAsWindow(System.Windows.Window owner) { Button AddBtn = new Button(); AddBtn.Content = "Add Agent"; AddBtn.Name = "AddAgent"; AddBtn.Click += new RoutedEventHandler(AddAgentButton_Click); ObservableList<Button> Buttons = new ObservableList<Button>(); Buttons.Add(AddBtn); GenericWindow genWin = null; GenericWindow.LoadGenericWindow(ref genWin, owner, eWindowShowStyle.Free, this.Title, this, Buttons); return genWin; } private void AddAgentButton_Click(object sender, RoutedEventArgs e) { // Temp dummy mApps.Add(new ApplicationAgent() { AppName = "koko" }); } private void StartButton_Click(object sender, RoutedEventArgs e) { ApplicationAgent a = (ApplicationAgent)mApps.CurrentItem; ((Agent) a.Agent).StartDriver(); } private void StopButton_Click(object sender, RoutedEventArgs e) { //ApplicationAgent a = (ApplicationAgent)mApps.CurrentItem; //a.Agent.CloseDriver(); } private void SelectAgentButton_Click(object sender, RoutedEventArgs e) { //ApplicationAgent AP = (ApplicationAgent)mApps.CurrentItem; //if (AP == null) return; //TODO: fix me must have selected row, so make the select button row selected //RepositoryFolder<NewAgent> f = WorkSpace.Instance.SolutionRepository.GetRepositoryItemRootFolder<NewAgent>(); //NewAgentsFolderTreeItem agents = new NewAgentsFolderTreeItem(f, eBusinessFlowsTreeViewMode.ReadOnly); //SingleItemTreeViewSelectionPage p = new SingleItemTreeViewSelectionPage("Select Agent", eImageType.Agent, agents); //List<object> selected = p.ShowAsWindow("Select Agent for Application - '" + AP.AppName + "'"); //if (selected != null) //{ // NewAgent agent = (NewAgent)selected[0]; // ((ApplicationAgent)mApps.CurrentItem).Agent = agent; //} } private void AttachDisplayButton_Click(object sender, RoutedEventArgs e) { ////TODO: start only once !!!!!!!!!!!!!!! ////First we search in the same folder as GingerWPF.exe - if is runtime/install folder all exes in the same folder //string FilePath = Assembly.GetExecutingAssembly().Location.Replace("GingerWPF.exe", "GingerWPFDriverWindow.exe"); //if (!File.Exists(FilePath)) //{ // // in case we are in debug // FilePath = FilePath.Replace(@"\GingerWPF\", @"\GingerWPFDriverWindow\"); // if (!File.Exists(FilePath)) // { // throw new Exception("Cannot find GingerWPFDriverWindow.exe"); // } //} //System.Diagnostics.Process.Start(FilePath); //// TODO: start in port... and send back keep connection //ApplicationAgent a = (ApplicationAgent)mApps.CurrentItem; //a.Agent.AttachDisplay(); } } }
37.977273
128
0.651307
[ "Apache-2.0" ]
Ginger-Automation/Ginger
Ginger/Ginger/Agents/AgentsNew/MapApplicationAgentPage.xaml.cs
5,014
C#
using System; using System.Buffers; using System.Diagnostics; using System.Text; namespace Lidgren.Network { public class NetBuffer : IBitBuffer { /// <summary> /// Number of extra bytes to overallocate for message buffers to avoid resizing. /// </summary> protected const int ExtraGrowAmount = 512; // TODO: move to config public static Encoding StringEncoding { get; } = new UTF8Encoding(false, false); private int _bitPosition; private int _bitLength; private byte[] _buffer; private bool _isRecyclableBuffer; private bool _isDisposed; public ArrayPool<byte> StoragePool { get; } public int BitPosition { get => _bitPosition; set => _bitPosition = value; } public int BytePosition { get => NetUtility.DivBy8(BitPosition); set => BitPosition = value * 8; } public int BitLength { get => _bitLength; set { EnsureBitCapacity(value); _bitLength = value; if (_bitPosition > _bitLength) _bitPosition = _bitLength; } } public int ByteLength { get => NetBitWriter.BytesForBits(_bitLength); set => BitLength = value * 8; } public int BitCapacity { get => _buffer.Length * 8; set => ByteCapacity = NetBitWriter.BytesForBits(value); } public int ByteCapacity { get => _buffer.Length; set { Debug.Assert(value >= 0); if (value > _buffer.Length) { if (_isDisposed) throw new ObjectDisposedException(GetType().FullName); byte[] newBuffer = StoragePool.Rent(value); _buffer.AsMemory(0, ByteLength).CopyTo(newBuffer); SetBuffer(newBuffer, true); } } } public NetBuffer(ArrayPool<byte> storagePool) { StoragePool = storagePool ?? throw new ArgumentNullException(nameof(storagePool)); _buffer = Array.Empty<byte>(); } public void EnsureBitCapacity(int bitCount) { Debug.Assert(bitCount >= 0); int byteLength = NetBitWriter.BytesForBits(bitCount); if (ByteCapacity < byteLength) ByteCapacity = byteLength + ExtraGrowAmount; } public void IncrementBitPosition(int bitCount) { Debug.Assert(bitCount >= 0); _bitPosition += bitCount; this.SetLengthByPosition(); } public byte[] GetBuffer() { return _buffer; } public void SetBuffer(byte[] buffer, bool isRecyclable) { if (_isRecyclableBuffer) { StoragePool.Return(_buffer); _buffer = Array.Empty<byte>(); } _buffer = buffer ?? throw new ArgumentNullException(nameof(buffer)); _isRecyclableBuffer = isRecyclable; } public void TrimExcess() { if (_bitLength == 0) Recycle(); } private void Recycle() { if (_isRecyclableBuffer) { StoragePool.Return(_buffer); _buffer = Array.Empty<byte>(); _bitLength = 0; _bitPosition = 0; _isRecyclableBuffer = false; } } protected virtual void Dispose(bool disposing) { if (!_isDisposed) { if (disposing) { Recycle(); } _isDisposed = true; } } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } }
26.235669
94
0.491867
[ "MIT" ]
AntonyChurch/lidgren-network-gen3
Lidgren.Network/Buffer/NetBuffer.cs
4,121
C#
using System; using System.Windows.Forms; using Microsoft.Win32; namespace MRUManager_dotNet4_example { public class MRUManager { // TODO implement 'maxNumberOfFiles' and 'maxDisplayLength' #region Private members private string NameOfProgram; private string SubKeyName; private ToolStripMenuItem ParentMenuItem; private Action<object, EventArgs> OnRecentFileClick; private Action<object, EventArgs> OnClearRecentFilesClick; private byte maxNumberOfFiles; private byte maxDisplayLength; private void _onClearRecentFiles_Click(object obj, EventArgs evt) { try { RegistryKey rK = Registry.CurrentUser.OpenSubKey(SubKeyName, true); if (rK == null) { return; } string[] values = rK.GetValueNames(); foreach (string valueName in values) { rK.DeleteValue(valueName, true); } rK.Close(); ParentMenuItem.DropDownItems.Clear(); ParentMenuItem.Enabled = false; } catch (Exception ex) { Console.WriteLine(ex.ToString()); } if (OnClearRecentFilesClick != null) { OnClearRecentFilesClick(obj, evt); } } private void _refreshRecentFilesMenu() { RegistryKey rK; string s; ToolStripItem tSI; try { rK = Registry.CurrentUser.OpenSubKey(SubKeyName, false); if (rK == null) { ParentMenuItem.Enabled = false; return; } } catch (Exception ex) { MessageBox.Show("Cannot open recent files registry key:\n" + ex); return; } ParentMenuItem.DropDownItems.Clear(); string[] valueNames = rK.GetValueNames(); foreach (string valueName in valueNames) { s = rK.GetValue(valueName, null) as string; if (s == null) { continue; } tSI = ParentMenuItem.DropDownItems.Add(s); tSI.Click += new EventHandler(OnRecentFileClick); } if (ParentMenuItem.DropDownItems.Count == 0) { ParentMenuItem.Enabled = false; return; } ParentMenuItem.DropDownItems.Add("-"); tSI = ParentMenuItem.DropDownItems.Add("Clear list"); tSI.Click += new EventHandler(_onClearRecentFiles_Click); ParentMenuItem.Enabled = true; } #endregion #region Public members public void AddRecentFile(string fileNameWithFullPath) { string s; try { // Registry location: HKCU\Software\Application name\MRU\ RegistryKey rK = Registry.CurrentUser.CreateSubKey(SubKeyName, RegistryKeyPermissionCheck.ReadWriteSubTree); for (int i = 0; true; i++) { s = rK.GetValue(i.ToString(), null) as string; if (s == null) { rK.SetValue(i.ToString(), fileNameWithFullPath); rK.Close(); break; } else if (s == fileNameWithFullPath) { rK.Close(); break; } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } _refreshRecentFilesMenu(); } public void RemoveRecentFile(string fileNameWithFullPath) { try { RegistryKey rK = Registry.CurrentUser.OpenSubKey(SubKeyName, true); string[] valuesNames = rK.GetValueNames(); foreach (string valueName in valuesNames) { if ((rK.GetValue(valueName, null) as string) == fileNameWithFullPath) { rK.DeleteValue(valueName, true); _refreshRecentFilesMenu(); break; } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } _refreshRecentFilesMenu(); } #endregion /// <exception cref="ArgumentException"> /// If anything is null or nameOfProgram contains a forward slash or is empty. /// </exception> public MRUManager(ToolStripMenuItem parentMenuItem, string nameOfProgram, Action<object, EventArgs> onRecentFileClick, Action<object, EventArgs> onClearRecentFilesClick = null) { if (parentMenuItem == null || onRecentFileClick == null || nameOfProgram == null || nameOfProgram.Length == 0 || nameOfProgram.Contains("\\")) { MessageBox.Show("Bad argument."); // throw new ArgumentException("Bad argument."); } ParentMenuItem = parentMenuItem; NameOfProgram = nameOfProgram; OnRecentFileClick = onRecentFileClick; OnClearRecentFilesClick = onClearRecentFilesClick; SubKeyName = string.Format("Software\\{0}\\MRU", NameOfProgram); _refreshRecentFilesMenu(); } } }
27.073864
180
0.600839
[ "MIT" ]
fredatgithub/MRUManager
MRUManager_dotNet4_example/MRUManager.cs
4,767
C#
/* * File: GtmpVoiceServer.Players.cs * Date: 21.2.2018, * * MIT License * * Copyright (c) 2018 JustAnotherVoiceChat * * 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 GrandTheftMultiplayer.Server.Elements; using JustAnotherVoiceChat.Server.GTMP.Interfaces; namespace JustAnotherVoiceChat.Server.GTMP.Elements.Server { public partial class GtmpVoiceServer { private const string PlayerDataKey = "JV_HANDLE"; public IGtmpVoiceClient GetVoiceClient(Client player) { if (player.hasData(PlayerDataKey)) { return (IGtmpVoiceClient) player.getData(PlayerDataKey); } return FindClient(c => c.Player == player); } private IGtmpVoiceClient RegisterPlayer(Client player) { var voiceClient = PrepareClient(player); if (voiceClient == null) { return null; } player.setData(PlayerDataKey, voiceClient); OnClientPrepared?.Invoke(voiceClient); return voiceClient; } private void UnregisterPlayer(Client player) { if (player == null) { throw new ArgumentNullException(nameof(player)); } var client = GetVoiceClient(player); if (client != null) { RemoveClient(client); client.Player.resetData(PlayerDataKey); } } } }
33.025316
81
0.638559
[ "MIT" ]
AlternateLife/JustAnotherVoiceChat-Server
JustAnotherVoiceChat.Server.GTMP/src/Elements/Server/GtmpVoiceServer.Players.cs
2,611
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 amplify-2017-07-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.Amplify.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Amplify.Model.Internal.MarshallTransformations { /// <summary> /// GetBackendEnvironment Request Marshaller /// </summary> public class GetBackendEnvironmentRequestMarshaller : IMarshaller<IRequest, GetBackendEnvironmentRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((GetBackendEnvironmentRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(GetBackendEnvironmentRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.Amplify"); request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-07-25"; request.HttpMethod = "GET"; if (!publicRequest.IsSetAppId()) throw new AmazonAmplifyException("Request object does not have required field AppId set"); request.AddPathResource("{appId}", StringUtils.FromString(publicRequest.AppId)); if (!publicRequest.IsSetEnvironmentName()) throw new AmazonAmplifyException("Request object does not have required field EnvironmentName set"); request.AddPathResource("{environmentName}", StringUtils.FromString(publicRequest.EnvironmentName)); request.ResourcePath = "/apps/{appId}/backendenvironments/{environmentName}"; request.MarshallerVersion = 2; return request; } private static GetBackendEnvironmentRequestMarshaller _instance = new GetBackendEnvironmentRequestMarshaller(); internal static GetBackendEnvironmentRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static GetBackendEnvironmentRequestMarshaller Instance { get { return _instance; } } } }
38.362637
158
0.649957
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/Amplify/Generated/Model/Internal/MarshallTransformations/GetBackendEnvironmentRequestMarshaller.cs
3,491
C#
namespace FakeProvider { public interface IFake { INamedTileCollection Provider { get; } int Index { get; set; } int RelativeX { get; set; } int RelativeY { get; set; } int X { get; set; } int Y { get; set; } ushort[] TileTypes { get; } } }
22.142857
46
0.516129
[ "MIT" ]
AnzhelikaO/FakeProvider
FakeProvider/TileProvider/Entities/IFake.cs
312
C#
using System.Collections.Generic; using CSUtil.Commons; using TrafficManager.Geometry.Impl; using TrafficManager.Traffic; using TrafficManager.Util; namespace TrafficManager.TrafficLight { public interface ITimedTrafficLights : IObserver<NodeGeometry> { IDictionary<ushort, IDictionary<ushort, ArrowDirection>> Directions { get; } ushort NodeId { get; } ushort MasterNodeId { get; set; } // TODO private set short RotationOffset { get; } int CurrentStep { get; set; } bool TestMode { get; set; } // TODO private set IList<ushort> NodeGroup { get; set; } // TODO private set ITimedTrafficLightsStep AddStep(int minTime, int maxTime, StepChangeMetric changeMetric, float waitFlowBalance, bool makeRed = false); long CheckNextChange(ushort segmentId, bool startNode, ExtVehicleType vehicleType, int lightType); ITimedTrafficLightsStep GetStep(int stepId); bool Housekeeping(); // TODO improve & remove bool IsMasterNode(); bool IsStarted(); bool IsInTestMode(); void SetTestMode(bool testMode); void Destroy(); ITimedTrafficLights MasterLights(); void MoveStep(int oldPos, int newPos); int NumSteps(); void RemoveStep(int id); void ResetSteps(); void RotateLeft(); void RotateRight(); void Join(ITimedTrafficLights otherTimedLight); void PasteSteps(ITimedTrafficLights sourceTimedLight); void ChangeLightMode(ushort segmentId, ExtVehicleType vehicleType, LightMode mode); void SetLights(bool noTransition = false); void SimulationStep(); void SkipStep(bool setLights = true, int prevStepRefIndex = -1); void Start(); void Start(int step); void Stop(); void OnGeometryUpdate(); void RemoveNodeFromGroup(ushort otherNodeId); } }
37.688889
136
0.760024
[ "MIT" ]
Emphasia/CitiesSkylines-TrafficManagerP
TLM/TLM/TrafficLight/ITimedTrafficLights.cs
1,698
C#
namespace MassTransit.Conductor.Configurators { using System; using System.Collections.Generic; public class ServiceClientConfigurator : IServiceClientConfigurator { public ServiceClientConfigurator() { Options = new ServiceClientOptions(); } public ServiceClientOptions Options { get; } T IOptionsSet.Options<T>(Action<T> configure) { return Options.Options(configure); } T IOptionsSet.Options<T>(T options, Action<T> configure) { return Options.Options(options, configure); } bool IOptionsSet.TryGetOptions<T>(out T options) { return Options.TryGetOptions(out options); } IEnumerable<T> IOptionsSet.SelectOptions<T>() where T : class { return ((IOptionsSet)Options).SelectOptions<T>(); } } }
23.820513
64
0.589882
[ "ECL-2.0", "Apache-2.0" ]
AndoxADX/MassTransit
src/MassTransit/Conductor/Configuration/Configurators/ServiceClientConfigurator.cs
929
C#
// CodeContracts // // 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. using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Text; namespace Microsoft.Research.CodeAnalysis { public enum WarningKind { Nonnull, MinValueNegation, DivByZero, ArithmeticOverflow, FloatEqualityPrecisionMismatch, ArrayCreation, ArrayLowerBound, ArrayUpperBound, Unsafe, Requires, Ensures, Invariant, Assume, Assert, Purity, Informational, UnreachedCode, Enum, MissingPrecondition, Suggestion } [ContractClass(typeof(IOutputResultsContracts))] public interface IOutputResults : IOutput { /// <returns>false if the witness has been filtered</returns> bool EmitOutcome(Witness witness, string format, params object[] args); // special case for baselining //bool EmitOutcome(Witness witness, string format, byte[] hash, params object[] args); /// <returns>false if the witness has been filtered</returns> bool EmitOutcomeAndRelated(Witness witness, string format, params object[] args); void Statistic(string format, params object[] args); /// <summary> /// Print final stats. This is separate, so in VS we can pump it as a message /// </summary> void FinalStatistic(string assemblyName, string message); /// <summary> /// Called once at end to make sure any output files are closed. /// </summary> void Close(); /// <summary>If this is a regression output, it returns the number of regressions.</summary> int RegressionErrors(); bool ErrorsWereEmitted { get; } /// <returns> /// True if the particular witness is masked /// </returns> bool IsMasked(Witness witness); new ILogOptions LogOptions { get; } } #region Contracts for IOutputResults [ContractClassFor(typeof(IOutputResults))] abstract class IOutputResultsContracts : IOutputResults { #region IOutputResults Members public bool EmitOutcome(Witness witness, string format, params object[] args) { Contract.Requires(witness != null); Contract.Requires(format != null); return false; } public bool EmitOutcomeAndRelated(Witness witness, string format, params object[] args) { Contract.Requires(witness != null); Contract.Requires(format != null); return false; } public void Statistic(string format, params object[] args) { Contract.Requires(format != null); } public void FinalStatistic(string assemblyName, string message) { Contract.Requires(assemblyName != null); } public bool IsMasked(Witness witness) { Contract.Requires(witness != null); return false; } public void Close() { } public int RegressionErrors() { return default(int); } public ILogOptions LogOptions { get { Contract.Ensures(Contract.Result<ILogOptions>() != null); return default(ILogOptions); } } #endregion #region IOutput Members - No contracts on them public void WriteLine(string format, params object[] args) { throw new NotImplementedException(); } public void Suggestion(ClousotSuggestion.Kind type, string kind, APC pc, string suggestion, List<uint> causes, ClousotSuggestion.ExtraSuggestionInfo extraInfo) { throw new NotImplementedException(); } public void EmitError(System.CodeDom.Compiler.CompilerError error) { throw new NotImplementedException(); } IFrameworkLogOptions IOutput.LogOptions { get { throw new NotImplementedException(); } } public bool ErrorsWereEmitted { get { throw new NotImplementedException(); } } #endregion } #endregion }
27.858757
463
0.693774
[ "MIT" ]
Acidburn0zzz/CodeContracts
Microsoft.Research/Analyzers/IOutputResults.cs
4,931
C#
/* SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. * * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. * * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. 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 OpenSearch.Net.Utf8Json; namespace Osc { [InterfaceDataContract] [ReadAs(typeof(MatchNoneQuery))] public interface IMatchNoneQuery : IQuery { } public class MatchNoneQuery : QueryBase, IMatchNoneQuery { protected override bool Conditionless => false; internal override void InternalWrapInContainer(IQueryContainer container) => container.MatchNone = this; } public class MatchNoneQueryDescriptor : QueryDescriptorBase<MatchNoneQueryDescriptor, IMatchNoneQuery> , IMatchNoneQuery { protected override bool Conditionless => false; } }
32.72
106
0.77445
[ "Apache-2.0" ]
Bit-Quill/opensearch-net
src/Osc/QueryDsl/MatchNoneQuery.cs
1,636
C#
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; // 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("RepoDb")] [assembly: AssemblyDescription("A dynamic, lightweight, efficient and very fast Hybrid ORM library for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RepoDb")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //[assembly: AllowPartiallyTrustedCallers()] // 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("4C31598D-BB13-4EA7-AC8C-A954C64A8A74")] // 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.9.3.0")] [assembly: AssemblyFileVersion("1.9.3.0")] [assembly: NeutralResourcesLanguage("")]
37.833333
110
0.753304
[ "Apache-2.0" ]
orm-core-group/RepoDb
RepoDb/RepoDb/Properties/AssemblyInfo.cs
1,592
C#
// // WebProxyTest.cs - NUnit Test Cases for System.Net.WebProxy // // Authors: // Lawrence Pit (loz@cable.a2000.nl) // Martin Willemoes Hansen (mwh@sysrq.dk) // Gert Driesen (drieseng@users.sourceforge.net) // // (C) 2003 Martin Willemoes Hansen // using System; using System.Collections; using System.IO; using System.Net; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Runtime.Serialization.Formatters.Binary; using System.Threading; using NUnit.Framework; namespace MonoTests.System.Net { [TestFixture] public class WebProxyTest { [Test] public void Constructors () { WebProxy p = new WebProxy (); Assert.IsTrue (p.Address == null, "#1"); Assert.AreEqual (0, p.BypassArrayList.Count, "#2"); Assert.AreEqual (0, p.BypassList.Length, "#3"); Assert.AreEqual (false, p.BypassProxyOnLocal, "#4"); try { p.BypassList = null; Assert.Fail ("#5 not spec'd, but should follow ms.net implementation"); } catch (ArgumentNullException) { } p = new WebProxy ("webserver.com", 8080); Assert.AreEqual (new Uri ("http://webserver.com:8080/"), p.Address, "#6"); p = new WebProxy ("webserver"); Assert.AreEqual (new Uri ("http://webserver"), p.Address, "#7"); p = new WebProxy ("webserver.com"); Assert.AreEqual (new Uri ("http://webserver.com"), p.Address, "#8"); p = new WebProxy ("http://webserver.com"); Assert.AreEqual (new Uri ("http://webserver.com"), p.Address, "#9"); p = new WebProxy ("file://webserver"); Assert.AreEqual (new Uri ("file://webserver"), p.Address, "#10"); p = new WebProxy ("http://www.contoso.com", true, null, null); Assert.AreEqual (0, p.BypassList.Length, "#11"); Assert.AreEqual (0, p.BypassArrayList.Count, "#12"); try { p = new WebProxy ("http://contoso.com", true, new string [] { "?^!@#$%^&}{][" }, null); Assert.Fail ("#13: illegal regular expression"); } catch (ArgumentException) { } } [Test] public void BypassArrayList () { Uri proxy1 = new Uri ("http://proxy.contoso.com"); Uri proxy2 = new Uri ("http://proxy2.contoso.com"); WebProxy p = new WebProxy (proxy1, true); p.BypassArrayList.Add ("http://proxy2.contoso.com"); p.BypassArrayList.Add ("http://proxy2.contoso.com"); Assert.AreEqual (2, p.BypassList.Length, "#1"); Assert.IsTrue (!p.IsBypassed (new Uri ("http://www.google.com")), "#2"); Assert.IsTrue (p.IsBypassed (proxy2), "#3"); Assert.AreEqual (proxy2, p.GetProxy (proxy2), "#4"); p.BypassArrayList.Add ("?^!@#$%^&}{]["); Assert.AreEqual (3, p.BypassList.Length, "#10"); try { Assert.IsTrue (!p.IsBypassed (proxy2), "#11"); Assert.IsTrue (!p.IsBypassed (new Uri ("http://www.x.com")), "#12"); Assert.AreEqual (proxy1, p.GetProxy (proxy2), "#13"); // hmm... although #11 and #13 succeeded before (#3 resp. #4), // it now fails to bypass, and the IsByPassed and GetProxy // methods do not fail.. so when an illegal regular // expression is added through this property it's ignored. // probably an ms.net bug?? :( } catch (ArgumentException) { Assert.Fail ("#15: illegal regular expression"); } } [Test] public void BypassList () { Uri proxy1 = new Uri ("http://proxy.contoso.com"); Uri proxy2 = new Uri ("http://proxy2.contoso.com"); WebProxy p = new WebProxy (proxy1, true); try { p.BypassList = new string [] { "http://proxy2.contoso.com", "?^!@#$%^&}{][" }; Assert.Fail ("#1"); } catch (ArgumentException) { // weird, this way invalid regex's fail again.. } Assert.AreEqual (2, p.BypassList.Length, "#2"); // but it did apparenly store the regex's ! p.BypassList = new string [] { "http://www.x.com" }; Assert.AreEqual (1, p.BypassList.Length, "#3"); try { p.BypassList = null; Assert.Fail ("#4"); } catch (ArgumentNullException) { } Assert.AreEqual (1, p.BypassList.Length, "#4"); } [Test] public void GetProxy () { } [Test] public void IsByPassed () { WebProxy p = new WebProxy ("http://proxy.contoso.com", true); Assert.IsTrue (!p.IsBypassed (new Uri ("http://www.google.com")), "#1"); Assert.IsTrue (p.IsBypassed (new Uri ("http://localhost/index.html")), "#2"); Assert.IsTrue (p.IsBypassed (new Uri ("http://localhost:8080/index.html")), "#3"); Assert.IsTrue (p.IsBypassed (new Uri ("http://loopback:8080/index.html")), "#4"); Assert.IsTrue (p.IsBypassed (new Uri ("http://127.0.0.01:8080/index.html")), "#5"); Assert.IsTrue (p.IsBypassed (new Uri ("http://webserver/index.html")), "#6"); Assert.IsTrue (!p.IsBypassed (new Uri ("http://webserver.com/index.html")), "#7"); p = new WebProxy ("http://proxy.contoso.com", false); Assert.IsTrue (!p.IsBypassed (new Uri ("http://www.google.com")), "#11"); Assert.IsTrue (p.IsBypassed (new Uri ("http://localhost/index.html")), "#12: lamespec of ms.net"); Assert.IsTrue (p.IsBypassed (new Uri ("http://localhost:8080/index.html")), "#13: lamespec of ms.net"); Assert.IsTrue (p.IsBypassed (new Uri ("http://loopback:8080/index.html")), "#14: lamespec of ms.net"); Assert.IsTrue (p.IsBypassed (new Uri ("http://127.0.0.01:8080/index.html")), "#15: lamespec of ms.net"); Assert.IsTrue (!p.IsBypassed (new Uri ("http://webserver/index.html")), "#16"); p.BypassList = new string [] { "google.com", "contoso.com" }; Assert.IsTrue (p.IsBypassed (new Uri ("http://www.google.com")), "#20"); Assert.IsTrue (p.IsBypassed (new Uri ("http://www.GOOGLE.com")), "#21"); Assert.IsTrue (p.IsBypassed (new Uri ("http://www.contoso.com:8080/foo/bar/index.html")), "#22"); Assert.IsTrue (!p.IsBypassed (new Uri ("http://www.contoso2.com:8080/foo/bar/index.html")), "#23"); Assert.IsTrue (!p.IsBypassed (new Uri ("http://www.foo.com:8080/contoso.com.html")), "#24"); p.BypassList = new string [] { "https" }; Assert.IsTrue (!p.IsBypassed (new Uri ("http://www.google.com")), "#30"); Assert.IsTrue (p.IsBypassed (new Uri ("https://www.google.com")), "#31"); } [Test] public void IsByPassed_Address_Null () { WebProxy p = new WebProxy ((Uri) null, false); Assert.IsTrue (p.IsBypassed (new Uri ("http://www.google.com")), "#1"); p = new WebProxy ((Uri) null, true); Assert.IsTrue (p.IsBypassed (new Uri ("http://www.google.com")), "#2"); } [Test] #if TARGET_JVM [Ignore ("TD BUG ID: 7213")] #endif public void IsByPassed_Host_Null () { WebProxy p = new WebProxy ("http://proxy.contoso.com", true); try { p.IsBypassed (null); Assert.Fail ("#A1"); #if NET_2_0 } catch (ArgumentNullException ex) { Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#A2"); Assert.IsNotNull (ex.Message, "#A3"); Assert.IsNotNull (ex.ParamName, "#A4"); Assert.AreEqual ("host", ex.ParamName, "#A5"); Assert.IsNull (ex.InnerException, "#A6"); } #else } catch (NullReferenceException) { } #endif p = new WebProxy ((Uri) null); try { p.IsBypassed (null); Assert.Fail ("#B1"); #if NET_2_0 } catch (ArgumentNullException ex) { Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#B2"); Assert.IsNotNull (ex.Message, "#B3"); Assert.IsNotNull (ex.ParamName, "#B4"); Assert.AreEqual ("host", ex.ParamName, "#B5"); Assert.IsNull (ex.InnerException, "#B6"); } #else } catch (NullReferenceException) { } #endif p = new WebProxy ((Uri) null, true); try { p.IsBypassed (null); Assert.Fail ("#C1"); #if NET_2_0 } catch (ArgumentNullException ex) { Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#C2"); Assert.IsNotNull (ex.Message, "#C3"); Assert.IsNotNull (ex.ParamName, "#C4"); Assert.AreEqual ("host", ex.ParamName, "#C5"); Assert.IsNull (ex.InnerException, "#C6"); } #else } catch (NullReferenceException) { } #endif } [Test] #if TARGET_JVM [Ignore ("The MS compliant binary serialization is not supported")] #endif public void GetObjectData () { SerializationInfo si = new SerializationInfo (typeof (WebHeaderCollection), new FormatterConverter ()); WebProxy proxy = new WebProxy ("proxy.ximian.com"); ((ISerializable) proxy).GetObjectData (si, new StreamingContext ()); #if NET_2_0 Assert.AreEqual (4, si.MemberCount, "#A1"); #else Assert.AreEqual (3, si.MemberCount, "#A1"); #endif int i = 0; foreach (SerializationEntry entry in si) { Assert.IsNotNull (entry.Name, "#A2:" + i); Assert.IsNotNull (entry.ObjectType, "#A3:" + i); switch (i) { case 0: Assert.AreEqual ("_BypassOnLocal", entry.Name, "#A4:" + i); Assert.AreEqual (typeof (bool), entry.ObjectType, "#A5:" + i); Assert.IsNotNull (entry.Value, "#A6:" + i); Assert.AreEqual (false, entry.Value, "#A7:" + i); break; case 1: Assert.AreEqual ("_ProxyAddress", entry.Name, "#A4:" + i); Assert.AreEqual (typeof (Uri), entry.ObjectType, "#A5:" + i); Assert.IsNotNull (entry.Value, "#A6:" + i); break; case 2: Assert.AreEqual ("_BypassList", entry.Name, "#A4:" + i); Assert.AreEqual (typeof (object), entry.ObjectType, "#A5:" + i); Assert.IsNull (entry.Value, "#A6:" + i); break; #if NET_2_0 case 3: Assert.AreEqual ("_UseDefaultCredentials", entry.Name, "#A4:" + i); Assert.AreEqual (typeof (bool), entry.ObjectType, "#A5:" + i); Assert.IsNotNull (entry.Value, "#A6:" + i); Assert.AreEqual (false, entry.Value, "#A7:" + i); break; #endif } i++; } } } }
33.763251
107
0.627839
[ "Apache-2.0" ]
121468615/mono
mcs/class/System/Test/System.Net/WebProxyTest.cs
9,555
C#
using System; using Org.BouncyCastle.Math; namespace Org.BouncyCastle.Crypto.Parameters { public class RsaBlindingParameters : ICipherParameters { private readonly RsaKeyParameters publicKey; private readonly BigInteger blindingFactor; public RsaBlindingParameters( RsaKeyParameters publicKey, BigInteger blindingFactor) { if (publicKey.IsPrivate) throw new ArgumentException("RSA parameters should be for a public key"); this.publicKey = publicKey; this.blindingFactor = blindingFactor; } public RsaKeyParameters PublicKey { get { return publicKey; } } public BigInteger BlindingFactor { get { return blindingFactor; } } } }
19.657143
77
0.747093
[ "MIT" ]
0x070696E65/Symnity
Assets/Plugins/Symnity/Pulgins/crypto/src/crypto/parameters/RSABlindingParameters.cs
688
C#
using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; namespace CodingMilitia.GrpcExtensions.ScopedRequestHandlerClientSample { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
26.777778
77
0.639004
[ "MIT" ]
CodingMilitia/GrpcExtensions
samples/CodingMilitia.GrpcExtensions.ScopedRequestHandlerClientSample/Program.cs
484
C#
using Logger.Core; using System; namespace Logger { public class StartUp { public static void Main() { IRunnable engine = new Engine(); engine.Run(); } } }
14.533333
44
0.513761
[ "MIT" ]
anidz/Software-University---C-OOP---February-2022-Solutions
SOLID_Exercises/Logger/StartUp.cs
220
C#
using System; using System.Collections.Generic; using System.Data; using NUnit.Framework; using Omu.ValueInjecter; namespace Tests { public class DanRyanIDataReaderTests { [Test] public void Main() { var persons = new List<Person>(); var table = CreateSampleDataTable(); var reader = table.CreateDataReader(); while (reader.Read()) { var p = new Person(); p.InjectFrom<ReaderInjection>(reader); p.name = new Name(); p.name.InjectFrom<ReaderInjection>(reader); persons.Add(p); } persons.Count.IsEqualTo(5); persons[0].id.IsEqualTo(100); persons[0].name.first_name.IsEqualTo("Jeff"); persons[0].name.last_name.IsEqualTo("Barnes"); } public class Person { public int id { get; set; } public Name name { get; set; } } public class Name { public string first_name { get; set; } public string last_name { get; set; } } private static DataTable CreateSampleDataTable() { var table = new DataTable(); table.Columns.Add("id", typeof(int)); table.Columns.Add("first_name", typeof(string)); table.Columns.Add("last_name", typeof(string)); table.Rows.Add(100, "Jeff", "Barnes"); table.Rows.Add(101, "George", "Costanza"); table.Rows.Add(102, "Stewie", "Griffin"); table.Rows.Add(103, "Stan", "Marsh"); table.Rows.Add(104, "Eric", "Cartman"); return table; } public class ReaderInjection : KnownSourceValueInjection<IDataReader> { protected override void Inject(IDataReader source, object target) { for (var i = 0; i < source.FieldCount; i++) { var activeTarget = target.GetProps().GetByName(source.GetName(i), true); if (activeTarget == null) continue; var value = source.GetValue(i); if (value == DBNull.Value) continue; activeTarget.SetValue(target, value); } } } } }
29.185185
92
0.51269
[ "MIT" ]
cristi-badila/.Net2.0-ValueInjecter
Tests/DanRyanIDataReaderTests.cs
2,366
C#
// Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Threading.Tasks; using Hazelcast.Messaging; using Hazelcast.Protocol.Codecs; using Hazelcast.Serialization; using Microsoft.Extensions.Logging; namespace Hazelcast.DistributedObjects.Impl { internal partial class HList<T> // Events { protected override ClientMessage CreateSubscribeRequest(bool includeValue, bool isSmartRouting) => ListAddListenerCodec.EncodeRequest(Name, includeValue, isSmartRouting); protected override ClientMessage CreateUnsubscribeRequest(Guid subscriptionId, SubscriptionState<CollectionItemEventHandlers<T>> state) => ListRemoveListenerCodec.EncodeRequest(Name, subscriptionId); protected override Guid ReadSubscribeResponse(ClientMessage responseMessage, SubscriptionState<CollectionItemEventHandlers<T>> state) => ListAddListenerCodec.DecodeResponse(responseMessage).Response; protected override bool ReadUnsubscribeResponse(ClientMessage unsubscribeResponseMessage, SubscriptionState<CollectionItemEventHandlers<T>> state) => ListRemoveListenerCodec.DecodeResponse(unsubscribeResponseMessage).Response; protected override ValueTask CodecHandleEventAsync(ClientMessage eventMessage, Func<IData, Guid, int, ValueTask> f, ILoggerFactory loggerFactory) => ListAddListenerCodec.HandleEventAsync( eventMessage, (itemData, memberId, eventTypeData) => f(itemData, memberId, eventTypeData), loggerFactory); } }
47.688889
154
0.760019
[ "Apache-2.0" ]
BigYellowHammer/hazelcast-csharp-client
src/Hazelcast.Net/DistributedObjects/Impl/HList.Events.cs
2,148
C#
#if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using XLua; using System.Collections.Generic; namespace XLua.CSObjectWrap { using Utils = XLua.Utils; public class XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapXLuaReflectionUseAttributeWrapWrapWrapWrapWrap { public static void __Register(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Type type = typeof(XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapXLuaReflectionUseAttributeWrapWrapWrapWrap); Utils.BeginObjectRegister(type, L, translator, 0, 0, 0, 0); Utils.EndObjectRegister(type, L, translator, null, null, null, null, null); Utils.BeginClassRegister(type, L, __CreateInstance, 2, 0, 0); Utils.RegisterFunc(L, Utils.CLS_IDX, "__Register", _m___Register_xlua_st_); Utils.EndClassRegister(type, L, translator); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __CreateInstance(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); if(LuaAPI.lua_gettop(L) == 1) { XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapXLuaReflectionUseAttributeWrapWrapWrapWrap gen_ret = new XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapXLuaReflectionUseAttributeWrapWrapWrapWrap(); translator.Push(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapXLuaReflectionUseAttributeWrapWrapWrapWrap constructor!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m___Register_xlua_st_(RealStatePtr L) { try { { System.IntPtr _L = LuaAPI.lua_touserdata(L, 1); XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapXLuaReflectionUseAttributeWrapWrapWrapWrap.__Register( _L ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } } }
27.227273
239
0.615693
[ "MIT" ]
zxsean/DCET
Unity/Assets/Model/XLua/Gen/XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapXLuaReflectionUseAttributeWrapWrapWrapWrapWrap.cs
2,997
C#
using System; using System.Collections.Generic; using System.Text; namespace ProjetoSingleton { class singletonClass { private static singletonClass singletonObject; public int numero = 12; private singletonClass() { } public static singletonClass GetInstance { get { if (singletonObject == null) { singletonObject = new singletonClass(); } return singletonObject; } } } }
18.580645
59
0.508681
[ "MIT" ]
KeilaLCrispim/ExProjSingleton
singletonClass.cs
578
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("P08-Average-Grades")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("P08-Average-Grades")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e82c68b2-6b25-4680-9528-343c61d36cfe")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.945946
84
0.747151
[ "MIT" ]
jeliozver/SoftUni-Work
Programming-Fundamentals-September-2017/10-Files-and-Exceptions-Exercises/P08-Average-Grades/Properties/AssemblyInfo.cs
1,407
C#
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.42000 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ namespace MazeSolver.Properties { using System; /// <summary> /// 一个强类型的资源类,用于查找本地化的字符串等。 /// </summary> // 此类是由 StronglyTypedResourceBuilder // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen // (以 /str 作为命令选项),或重新生成 VS 项目。 [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// 返回此类使用的缓存的 ResourceManager 实例。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MazeSolver.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// 使用此强类型资源类,为所有资源查找 /// 重写当前线程的 CurrentUICulture 属性。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// 查找 System.Drawing.Bitmap 类型的本地化资源。 /// </summary> internal static System.Drawing.Bitmap cat { get { object obj = ResourceManager.GetObject("cat", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// 查找 System.Drawing.Bitmap 类型的本地化资源。 /// </summary> internal static System.Drawing.Bitmap 喵喵 { get { object obj = ResourceManager.GetObject("喵喵", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// 查找 System.Drawing.Bitmap 类型的本地化资源。 /// </summary> internal static System.Drawing.Bitmap 皮卡丘 { get { object obj = ResourceManager.GetObject("皮卡丘", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// 查找 System.Drawing.Bitmap 类型的本地化资源。 /// </summary> internal static System.Drawing.Bitmap 雯雯 { get { object obj = ResourceManager.GetObject("雯雯", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } } }
36.269231
176
0.551166
[ "MIT" ]
DavidYQY/MazeSolver
MazeSolver/Properties/Resources.Designer.cs
4,238
C#
/** * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. */ using Xunit; // disable parallelization for this test assembly to avoid // issues based on singleton values e.g. ReferenceLink.BaseUrl [assembly: CollectionBehavior(DisableTestParallelization = true)]
24.25
65
0.756014
[ "MIT" ]
Chongruiyuan893/TeamCloud
src/TeamCloud.Model.Tests/CollectionBehavior.cs
293
C#
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; namespace Borks.Graphics3D.CoDXAsset.Tokens { /// <summary> /// A class to hold a token of the specified type /// </summary> public class TokenDataVector2 : TokenData { /// <summary> /// Gets or Sets the data /// </summary> public Vector2 Data { get; set; } /// <summary> /// Initializes a new instance of the <see cref="TokenDataVector2"/> class /// </summary> /// <param name="data">Data</param> /// <param name="token">Token</param> public TokenDataVector2(Vector2 data, Token token) : base(token) { Data = data; } } }
25.677419
82
0.589196
[ "MIT" ]
Scobalula/BorkLib
src/cs/Borks.Graphics3D.CoDXAsset/Tokens/TokenDataVector2.cs
798
C#
using System; using UIKit; namespace Nightscout.iOS { public partial class ViewController : UIViewController { int count = 1; public ViewController (IntPtr handle) : base (handle) { } public override void ViewDidLoad () { base.ViewDidLoad (); // Perform any additional setup after loading the view, typically from a nib. Button.AccessibilityIdentifier = "myButton"; Button.TouchUpInside += delegate { var title = string.Format ("{0} clicks!", count++); Button.SetTitle (title, UIControlState.Normal); }; } public override void DidReceiveMemoryWarning () { base.DidReceiveMemoryWarning (); // Release any cached data, images, etc that aren't in use. } } }
20.542857
80
0.685675
[ "MIT" ]
colbylwilliams/nightscout
Nightscout/Nightscout.iOS/ViewControllers/ViewController.cs
721
C#
using ProtoBuildBot.Classes.Automation; using ProtoBuildBot.Classes.Messages.Base; using ProtoBuildBot.DataStore; using ProtoBuildBot.Enums; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.ReplyMarkups; using static ProtoBuildBot.Classes.MessageHelpers; namespace ProtoBuildBot.Classes.Messages.Commands { public class GetRingStatesCommand : UnregMessageBase { public override string[] SupportedCommands => new[] { "/getringstates", "/grs" }; public override bool IsAuthorizationTargeted => false; public override AuthLevel MinimalAuthorizationLevelForGroups => AuthLevel.UNREGISTERED; public override bool IsGroupSupported => true; public override void HandleCallbackQueryFromGroup(GroupState groupState, CallbackQuery callbackQuery, string command, string param) { if (groupState.IsRegistered) Common(groupState, callbackQuery.From, callbackQuery.Message, command, param, false); } public override void HandleCallbackQuery(UserState userState, CallbackQuery callbackQuery, string command, string param) => Common(userState, callbackQuery.From, callbackQuery.Message, command, param, false); private void Common(UserStateBase userState, User user, Message message, string command, string param, bool sendOnly = false) { if (!string.IsNullOrEmpty(param)) { var grs = SharedDBcmd.GetLatestBuildLabForeachBuildFrom(); StringBuilder sb = new StringBuilder(); if (param == "EVERYTHING") grs.ForEach(itm => { if (SearchHelpers.GetSearchItemsForGRS.FirstOrDefault(u => u.DeviceFamily.Split('-')[0].Equals(itm.DeviceFamily.Split('-')[0], StringComparison.OrdinalIgnoreCase) && u.Ring.Equals(itm.Ring, StringComparison.OrdinalIgnoreCase) && u.Arch.Equals(itm.Architecture, StringComparison.OrdinalIgnoreCase)) != null) { if (itm.DeviceFamily.Contains('-', StringComparison.Ordinal)) sb.Append($"➡️ <b>{itm.DeviceFamily.Split('-')[0]}</b> ({itm.DeviceFamily.Split('-')[1]}) - <b>{itm.Ring}</b>:\n <code>{itm.BuildLab}</code>\n"); else sb.Append($"➡️ <b>{itm.DeviceFamily}</b> - <b>{itm.Ring}</b>:\n <code>{itm.BuildLab}</code>\n"); } }); else { var specificFamily = grs.Where(f => f.DeviceFamily.ToUpperInvariant().StartsWith(param, StringComparison.Ordinal)).ToList(); var specificReferenceFilter = SearchHelpers.GetSearchItemsForGRS.Where(u => u.DeviceFamily.ToUpperInvariant().Split('-')[0] == param).ToList(); specificFamily.ForEach(itm => { if (specificReferenceFilter.FirstOrDefault(u => u.Ring.ToUpperInvariant() == itm.Ring.ToUpperInvariant() && u.Arch.ToUpperInvariant() == itm.Architecture.ToUpperInvariant()) != null) { if (itm.DeviceFamily.Contains('-', StringComparison.Ordinal)) sb.Append($"➡️ <b>{itm.Ring}</b> ({itm.DeviceFamily.Split('-')[1]}):\n <code>{itm.BuildLab}</code>\n\n"); else sb.Append($"➡️ <b>{itm.Ring}</b>:\n <code>{itm.BuildLab}</code>\n\n"); } }); } if (sb.Length == 0) sb.Append("-"); EditOrSendMessageText(message.Chat.Id, message.MessageId, string.Format(CultureInfo.InvariantCulture, GetLocalizedText("P_DetailedUpdates", userState), param, sb.ToString()), InlKeyboardDetailedPage(userState), sendOnly); } else { EditOrSendMessageText(message.Chat.Id, message.MessageId, GetLocalizedText("P_Updates", userState), InlKeyboardMainPage(userState), sendOnly); } } private static InlineKeyboardMarkup InlKeyboardDetailedPage(UserStateBase userState) { List<InlineKeyboardButton[]> buttons = new List<InlineKeyboardButton[]> { new InlineKeyboardButton[] { GetDefaultBackButton(userState, "/getringstates") } }; return new InlineKeyboardMarkup(buttons); } private static InlineKeyboardMarkup InlKeyboardMainPage(UserStateBase userState) { var stringId = userState is UserState ? userState.GetID().ToString(CultureInfo.InvariantCulture) : "GROUP"; List<InlineKeyboardButton[]> buttons = new List<InlineKeyboardButton[]>(); var grs = SharedDBcmd.GetLatestBuildLabForeachBuildFrom(); var families = grs.GroupBy(f => f.DeviceFamily.Split("-")[0]); foreach (var family in families) { //Everything that MS messed up ends up here if (family.Key.StartsWith("MESSED", StringComparison.OrdinalIgnoreCase)) continue; var famStr = family.Key; if (SearchHelpers.GetEmojiIconFromDeviceFamily.TryGetValue(family.Key, out var icon)) famStr = icon + " " + family.Key; buttons.Add(new InlineKeyboardButton[] { MakeInlButton(famStr, stringId, "/getringstates", family.Key) }); } if (families.Count() > 1) { buttons.Add(new InlineKeyboardButton[] { MakeInlButton(GetLocalizedText("B_Everything", userState), stringId, "/getringstates", "EVERYTHING") }); } buttons.Add(new InlineKeyboardButton[] { GetDefaultBackButton(userState, "/start") }); return new InlineKeyboardMarkup(buttons); } public override async void HandleCommandMessage(UserState userState, Message message, string command) => SendMessageText(message.Chat.Id, GetLocalizedText("P_UseInteractiveVersion", userState), GetDefaultStartButton(userState)); private static bool IsMatch(string item, string filter) => filter.Contains(item.Split('-')[0], StringComparison.OrdinalIgnoreCase); } }
47.662069
206
0.572855
[ "MIT" ]
ADeltaX/ProtoBuildBot
src/ProtoBuildBot/Classes/Messages/Commands/GetRingStatesCommand.cs
6,929
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Haushaltsbuch.Resources { class HaushaltsbuchGesamtDtoModel : IHaushaltsbuchDtoModel { public decimal Kassenbestand { get; set; } public string Monat { get; set; } public string Jahr { get; set; } public List<KategorieDtoModel> Kategorien { get; set; } } }
21.6
63
0.694444
[ "MIT" ]
adb-solutions/Schulung_12-2018
Jason/Haushaltsbuch/Haushaltsbuch.Resources/HaushaltsbuchGesamtDtoModel.cs
434
C#
using Meridian.ViewModel.Common; using Windows.System; using Windows.UI.Xaml.Controls; // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238 namespace Meridian.View.Common { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class LastFmLoginView : Page { public LastFmLoginViewModel ViewModel => (LastFmLoginViewModel)DataContext; public LastFmLoginView() { this.InitializeComponent(); } private void LoginBox_OnKeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e) { if (e.Key != VirtualKey.Enter) return; if (string.IsNullOrWhiteSpace(PasswordBox.Password)) { PasswordBox.Focus(Windows.UI.Xaml.FocusState.Keyboard); } else { ViewModel.LoginCommand.Execute(null); } } private void PasswordBox_OnKeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e) { if (e.Key != VirtualKey.Enter) return; if (!string.IsNullOrWhiteSpace(PasswordBox.Password)) { if (string.IsNullOrWhiteSpace(LoginTextBox.Text)) { LoginTextBox.Focus(Windows.UI.Xaml.FocusState.Keyboard); } else { ViewModel.LoginCommand.Execute(null); } } } } }
29.907407
101
0.563467
[ "Apache-2.0" ]
Elorucov/meridian-uwp
Meridian/View/Common/LastFmLoginView.xaml.cs
1,617
C#
// ********************************************************************************************************************** // // Copyright © 2005-2020 Trading Technologies International, Inc. // All Rights Reserved Worldwide // // * * * S T R I C T L Y P R O P R I E T A R Y * * * // // WARNING: This file and all related programs (including any computer programs, example programs, and all source code) // are the exclusive property of Trading Technologies International, Inc. (“TT”), are protected by copyright law and // international treaties, and are for use only by those with the express written permission from TT. Unauthorized // possession, reproduction, distribution, use or disclosure of this file and any related program (or document) derived // from it is prohibited by State and Federal law, and by local law outside of the U.S. and may result in severe civil // and criminal penalties. // // ************************************************************************************************************************ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace TTNETAPI_Sample_Console_PriceDetailedDepthSubscription_EPIQ { class Program { static void Main(string[] args) { try { // Add your app secret Key here . The app_key looks like : 00000000-0000-0000-0000-000000000000:00000000-0000-0000-0000-000000000000 string appSecretKey = "Add your app secret key here"; // Set the environment the app needs to run in here tt_net_sdk.ServiceEnvironment environment = tt_net_sdk.ServiceEnvironment.UatCert; // Select the mode in which you wish to run -- Client (outside the TT datacenter) // or Server (on a dedicated machine inside TT datacenter) tt_net_sdk.TTAPIOptions.SDKMode sdkMode = tt_net_sdk.TTAPIOptions.SDKMode.Client; tt_net_sdk.TTAPIOptions apiConfig = new tt_net_sdk.TTAPIOptions( sdkMode, environment, appSecretKey, 5000); //Set to true if EPIQ is to be calculated apiConfig.EnableEstimatedPositionInQueue = true; // set any other SDK options you need configured apiConfig.ProfitLossCalculationType = tt_net_sdk.ProfitLossCalculationType.RiskWaterfall; // Start the TT API on the same thread TTNetApiFunctions tf = new TTNetApiFunctions(); Thread workerThread = new Thread(() => tf.Start(apiConfig)); workerThread.Name = "TT NET SDK Thread"; workerThread.Start(); while (true) { string input = System.Console.ReadLine(); if (input == "q") break; } tf.Dispose(); } catch (Exception e) { Console.WriteLine(e.Message + "\n" + e.StackTrace); } } } }
42.363636
148
0.550276
[ "BSD-3-Clause" ]
LevyForchh/TT_Samples
TT_NET_CLIENT_SIDE/TTNETAPI_Sample_Console_PriceDetailedDepthSubscription_EPIQ/Program.cs
3,269
C#
/* Copyright (c) 2014 ABB Group All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v10.html Contributors: Christian Manteuffel (University of Groningen) Spyros Ioakeimidis (University of Groningen) */ using EAFacade.Model; namespace DecisionArchitect.Logic.Validation { public abstract class ElementRule : AbstractRule { protected ElementRule(string errorMessage) : base(errorMessage) { } public override sealed RuleType GetRuleType() { return RuleType.Element; } public new abstract bool ValidateElement(IEAElement element); } }
26.290323
70
0.70184
[ "EPL-1.0" ]
cmanteuffel/DecisionArchitect
DecisionArchitect/Logic/Validation/ElementRule.cs
815
C#
using System; using System.Collections.Generic; using NBitcoin; using Newtonsoft.Json; using Stratis.Bitcoin.Features.RPC.Models; using Stratis.Bitcoin.Features.Wallet; using Stratis.Bitcoin.Features.Wallet.JsonConverters; namespace Stratis.Bitcoin.Features.WatchOnlyWallet.Models { /// <summary> /// Represents a watch-only wallet to be used as an API return object. /// </summary> public class WatchOnlyWalletModel { /// <summary> /// Initializes a new instance of the <see cref="WatchOnlyWalletModel"/> class. /// </summary> public WatchOnlyWalletModel() { this.WatchedAddresses = new List<WatchedAddressModel>(); } /// <summary> /// The network this wallet is for. /// </summary> [JsonProperty(PropertyName = "network")] [JsonConverter(typeof(NetworkConverter))] public Network Network { get; set; } /// <summary> /// The type of coin, Bitcoin or Stratis. /// </summary> [JsonProperty(PropertyName = "coinType")] public CoinType CoinType { get; set; } /// <summary> /// The time this wallet was created. /// </summary> [JsonProperty(PropertyName = "creationTime")] [JsonConverter(typeof(DateTimeOffsetConverter))] public DateTimeOffset CreationTime { get; set; } /// <summary> /// The list of <see cref="WatchedAddress"/>es being watched. /// </summary> [JsonProperty(PropertyName = "watchedAddresses")] public ICollection<WatchedAddressModel> WatchedAddresses { get; set; } } /// <summary> /// An object contaning an address being watched along with any transactions affecting it. /// </summary> public class WatchedAddressModel { /// <summary> /// Initializes a new instance of the <see cref="WatchedAddressModel"/> class. /// </summary> public WatchedAddressModel() { this.Transactions = new List<TransactionVerboseModel>(); } /// <summary> /// A base58 address being watched for transactions affecting it. /// </summary> [JsonProperty(PropertyName = "address")] public string Address { get; set; } /// <summary> /// The list of transactions affecting the address being watched. /// </summary> [JsonProperty(PropertyName = "transactions")] public ICollection<TransactionVerboseModel> Transactions { get; set; } } }
33.38961
94
0.612213
[ "MIT" ]
obsidianplatform/ObsidianStratisNode
src/Stratis.Bitcoin.Features.WatchOnlyWallet/Models/WatchOnlyWalletModel.cs
2,573
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Kunai.Cache { public static class CacheExtensions { public static IEnumerable<T> Cache<T>(this IEnumerable<T> source) { return CacheHelper(source.GetEnumerator()); } private static IEnumerable<T> CacheHelper<T>(IEnumerator<T> source) { var isEmpty = new Lazy<bool>(() => !source.MoveNext()); var head = new Lazy<T>(() => source.Current); var tail = new Lazy<IEnumerable<T>>(() => CacheHelper(source)); return CacheHelper(isEmpty, head, tail); } private static IEnumerable<T> CacheHelper<T>( Lazy<bool> isEmpty, Lazy<T> head, Lazy<IEnumerable<T>> tail) { if (isEmpty.Value) yield break; yield return head.Value; foreach (var value in tail.Value) yield return value; } } }
22.102564
69
0.689095
[ "Apache-2.0" ]
evilz/kunai
src/Kunai/Cache/CacheExtensions.cs
864
C#
// MIT License Copyright 2014 (c) David Melendez. All rights reserved. See License.txt in the project root for license information. using ElCamino.AspNet.Identity.Dynamo.Model; using Microsoft.AspNet.Identity; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Linq; namespace ElCamino.AspNet.Identity.Dynamo.Tests { [TestClass] public class RoleStoreTests { private static IdentityRole CurrentRole; [TestInitialize] public void Initialize() { using (RoleStore<IdentityRole> store = new RoleStore<IdentityRole>()) { var taskCreateTables = store.CreateTableIfNotExistsAsync(); taskCreateTables.Wait(); } CreateRole(); } [TestMethod] [TestCategory("Identity.Dynamo.RoleStore")] public void RoleStoreCtors() { try { new RoleStore<IdentityRole>(null); } catch (ArgumentException) { } } [TestMethod] [TestCategory("Identity.Dynamo.RoleStore")] public void CreateRole() { using (RoleStore<IdentityRole> store = new RoleStore<IdentityRole>()) { using (RoleManager<IdentityRole> manager = new RoleManager<IdentityRole>(store)) { string roleNew = string.Format("TestRole_{0}", Guid.NewGuid()); var role = new IdentityRole(roleNew); var createTask = manager.CreateAsync(role); createTask.Wait(); CurrentRole = role; try { var task = store.CreateAsync(null); task.Wait(); } catch (Exception ex) { Assert.IsNotNull(ex, "Argument exception not raised"); } } } } [TestMethod] [TestCategory("Identity.Dynamo.RoleStore")] public void ThrowIfDisposed() { using (RoleStore<IdentityRole> store = new RoleStore<IdentityRole>()) { RoleManager<IdentityRole> manager = new RoleManager<IdentityRole>(store); manager.Dispose(); try { var task = store.DeleteAsync(null); } catch (ArgumentException) { } } } [TestMethod] [TestCategory("Identity.Dynamo.RoleStore")] public void UpdateRole() { using (RoleStore<IdentityRole> store = new RoleStore<IdentityRole>()) { using (RoleManager<IdentityRole> manager = new RoleManager<IdentityRole>(store)) { string roleNew = string.Format("TestRole_{0}", Guid.NewGuid()); var role = new IdentityRole(roleNew); var createTask = manager.CreateAsync(role); createTask.Wait(); role.Name = Guid.NewGuid() + role.Name; var updateTask = manager.UpdateAsync(role); updateTask.Wait(); var findTask = manager.FindByIdAsync(role.Id); Assert.IsNotNull(findTask.Result, "Find Role Result is null"); Assert.AreEqual<string>(role.Id, findTask.Result.Id, "RowKeys don't match."); Assert.AreNotEqual<string>(roleNew, findTask.Result.Name, "Name not updated."); try { var task = store.UpdateAsync(null); task.Wait(); } catch (Exception ex) { Assert.IsNotNull(ex, "Argument exception not raised"); } } } } [TestMethod] [TestCategory("Identity.Dynamo.RoleStore")] public void UpdateRole2() { using (RoleStore<IdentityRole> store = new RoleStore<IdentityRole>()) { using (RoleManager<IdentityRole> manager = new RoleManager<IdentityRole>(store)) { string roleNew = string.Format("{0}_TestRole", Guid.NewGuid()); var role = new IdentityRole(roleNew); var createTask = manager.CreateAsync(role); createTask.Wait(); role.Name = role.Name + Guid.NewGuid(); var updateTask = manager.UpdateAsync(role); updateTask.Wait(); var findTask = manager.FindByIdAsync(role.Id); Assert.IsNotNull(findTask.Result, "Find Role Result is null"); Assert.AreEqual<string>(role.Id, findTask.Result.Id, "RowKeys don't match."); Assert.AreNotEqual<string>(roleNew, findTask.Result.Name, "Name not updated."); } } } [TestMethod] [TestCategory("Identity.Dynamo.RoleStore")] public void DeleteRole() { using (RoleStore<IdentityRole> store = new RoleStore<IdentityRole>()) { using (RoleManager<IdentityRole> manager = new RoleManager<IdentityRole>(store)) { string roleNew = string.Format("TestRole_{0}", Guid.NewGuid()); var role = new IdentityRole(roleNew); var createTask = manager.CreateAsync(role); createTask.Wait(); var delTask = manager.DeleteAsync(role); delTask.Wait(); var findTask = manager.FindByIdAsync(role.Id); Assert.IsNull(findTask.Result, "Role not deleted "); try { var task = store.DeleteAsync(null); task.Wait(); } catch (Exception ex) { Assert.IsNotNull(ex, "Argument exception not raised"); } } } } [TestMethod] [TestCategory("Identity.Dynamo.RoleStore")] public void RolesGetter() { using (RoleStore<IdentityRole> store = new RoleStore<IdentityRole>()) { string roleNew = string.Format("TestRole_{0}", Guid.NewGuid()); IdentityRole role; using (RoleManager<IdentityRole> manager = new RoleManager<IdentityRole>(store)) { role = new IdentityRole(roleNew); var createTask = manager.CreateAsync(role); createTask.Wait(); var findTask = manager.FindByIdAsync(role.Id); Assert.IsNotNull(findTask.Result, "Role wasn't created"); var roles = store.Roles; Assert.IsNotNull(roles); var foundRole = from r in roles where r.Name == roleNew select r; Assert.IsNotNull(foundRole.FirstOrDefault()); try { var task = store.DeleteAsync(null); task.Wait(); } catch (Exception ex) { Assert.IsNotNull(ex, "Argument exception not raised"); } } } } [TestMethod] [TestCategory("Identity.Dynamo.RoleStore")] public void FindRoleById() { using (RoleStore<IdentityRole> store = new RoleStore<IdentityRole>()) { using (RoleManager<IdentityRole> manager = new RoleManager<IdentityRole>(store)) { var findTask = manager.FindByIdAsync(CurrentRole.Id); Assert.IsNotNull(findTask.Result, "Find Role Result is null"); Assert.AreEqual<string>(CurrentRole.Id, findTask.Result.Id, "RowKeys don't match."); } } } [TestMethod] [TestCategory("Identity.Dynamo.RoleStore")] public void FindRoleByName() { using (RoleStore<IdentityRole> store = new RoleStore<IdentityRole>()) { using (RoleManager<IdentityRole> manager = new RoleManager<IdentityRole>(store)) { var findTask = manager.FindByNameAsync(CurrentRole.Name); Assert.IsNotNull(findTask.Result, "Find Role Result is null"); Assert.AreEqual<string>(CurrentRole.Name, findTask.Result.Name, "Role names don't match."); } } } } }
36.560976
132
0.495886
[ "MIT" ]
c0achmcguirk/AspNetIdentity_DynamoDB
tests/identity.dynamo.tests/RoleStoreTests.cs
8,996
C#
using FluentBootstrap.Buttons; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FluentBootstrap { public static class ButtonExtensions { // Button public static Button<THelper> Button<THelper>(this IButtonCreator<THelper> creator, string text = null, ButtonType buttonType = ButtonType.Button, object value = null) where THelper : BootstrapHelper<THelper> { return new Button<THelper>(creator, buttonType).SetText(text).SetValue(value); } // Button groups public static ButtonGroup<THelper> ButtonGroup<THelper>(this IButtonGroupCreator<THelper> creator) where THelper : BootstrapHelper<THelper> { return new ButtonGroup<THelper>(creator); } public static ButtonGroup<THelper> SetSize<THelper>(this ButtonGroup<THelper> buttonGroup, ButtonGroupSize size) where THelper : BootstrapHelper<THelper> { buttonGroup.ToggleCss(size); return buttonGroup; } public static ButtonGroup<THelper> SetVertical<THelper>(this ButtonGroup<THelper> buttonGroup, bool vertical = true) where THelper : BootstrapHelper<THelper> { if (vertical) { buttonGroup.ToggleCss(Css.BtnGroupVertical, true, Css.BtnGroup); } else { buttonGroup.ToggleCss(Css.BtnGroup, true, Css.BtnGroupVertical); } return buttonGroup; } public static ButtonGroup<THelper> SetJustified<THelper>(this ButtonGroup<THelper> buttonGroup, bool justified = true) where THelper : BootstrapHelper<THelper> { buttonGroup.ToggleCss(Css.BtnGroupJustified, justified); return buttonGroup; } public static ButtonToolbar<THelper> ButtonToolbar<THelper>(this IButtonToolbarCreator<THelper> creator) where THelper : BootstrapHelper<THelper> { return new ButtonToolbar<THelper>(creator); } // Dropdown buttons public static DropdownButton<THelper> DropdownButton<THelper>(this IDropdownButtonCreator<THelper> creator) where THelper : BootstrapHelper<THelper> { return new DropdownButton<THelper>(creator); } public static DropdownButton<THelper> SetDropup<THelper>(this DropdownButton<THelper> dropdownButton, bool dropup = true) where THelper : BootstrapHelper<THelper> { dropdownButton.ToggleCss(Css.Dropup, dropup); return dropdownButton; } // LinkButton public static LinkButton<THelper> LinkButton<THelper>(this ILinkButtonCreator<THelper> creator, string text, string href = "#") where THelper : BootstrapHelper<THelper> { return new LinkButton<THelper>(creator).SetText(text).SetHref(href); } public static LinkButton<THelper> SetDisabled<THelper>(this LinkButton<THelper> linkButton, bool disabled = true) where THelper : BootstrapHelper<THelper> { linkButton.ToggleCss(Css.Disabled, disabled); return linkButton; } // IHasButtonExtensions public static TThis SetSize<THelper, TThis, TWrapper>(this Component<THelper, TThis, TWrapper> component, ButtonSize size) where THelper : BootstrapHelper<THelper> where TThis : Tag<THelper, TThis, TWrapper>, IHasButtonExtensions where TWrapper : TagWrapper<THelper>, new() { return component.GetThis().ToggleCss(size); } public static TThis SetBlock<THelper, TThis, TWrapper>(this Component<THelper, TThis, TWrapper> component, bool block = true) where THelper : BootstrapHelper<THelper> where TThis : Tag<THelper, TThis, TWrapper>, IHasButtonExtensions where TWrapper : TagWrapper<THelper>, new() { return component.GetThis().ToggleCss(Css.BtnBlock, block); } // IHasButtonStateExtensions public static TThis SetState<THelper, TThis, TWrapper>(this Component<THelper, TThis, TWrapper> component, ButtonState state) where THelper : BootstrapHelper<THelper> where TThis : Tag<THelper, TThis, TWrapper>, IHasButtonStateExtensions where TWrapper : TagWrapper<THelper>, new() { return component.GetThis().ToggleCss(state); } } }
38.181818
175
0.643074
[ "MIT" ]
jbgriffith/FluentBootstrap
FluentBootstrap/Buttons/ButtonExtensions.cs
4,622
C#
using System; namespace alabala { class Program { static void Main(string[] args) { double num = 0.0001; Console.WriteLine(num + num + num + num + num + num == 0.0006); } } }
16.928571
75
0.489451
[ "MIT" ]
dimitarLaleksandrov/first-steps-in-coding-C-
Homework/Fundamentals whit C#/9.1 More Exercise Data Types and Variables/alabala/Program.cs
239
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace Budget.WebApi.Migrations { public partial class CustomizeImporto : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<float>( name: "Importo_Amount", table: "Spese", type: "real", nullable: false, defaultValue: 0f, oldClrType: typeof(double), oldType: "float", oldNullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<double>( name: "Importo_Amount", table: "Spese", type: "float", nullable: true, oldClrType: typeof(float), oldType: "real"); } } }
29.125
71
0.522532
[ "MIT" ]
AngeloDotNet/FacileBudget-2
src/FacileBudget/Backend/Budget.WebApi/Migrations/20211210173452_CustomizeImporto.cs
934
C#
using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif namespace UnityStandardAssets.Utility { #if UNITY_EDITOR [ExecuteInEditMode] #endif public class PlatformSpecificContent : MonoBehaviour #if UNITY_EDITOR , UnityEditor.Build.IActiveBuildTargetChanged #endif { private enum BuildTargetGroup { Standalone, Mobile } [SerializeField] private BuildTargetGroup m_BuildTargetGroup; [SerializeField] private GameObject[] m_Content = new GameObject[0]; [SerializeField] private MonoBehaviour[] m_MonoBehaviours = new MonoBehaviour[0]; [SerializeField] private bool m_ChildrenOfThisObject; #if !UNITY_EDITOR void OnEnable() { CheckEnableContent(); } #else public int callbackOrder { get { return 1; } } #endif #if UNITY_EDITOR private void OnEnable() { EditorApplication.update += Update; } private void OnDisable() { EditorApplication.update -= Update; } public void OnActiveBuildTargetChanged(BuildTarget previousTarget, BuildTarget newTarget) { CheckEnableContent(); } private void Update() { CheckEnableContent(); } #endif private void CheckEnableContent() { #if (UNITY_IPHONE || UNITY_ANDROID || UNITY_WP8 || UNITY_TIZEN) if (m_BuildTargetGroup == BuildTargetGroup.Mobile) { EnableContent(true); } else { EnableContent(false); } #endif #if !(UNITY_IPHONE || UNITY_ANDROID || UNITY_WP8 || UNITY_TIZEN) if (m_BuildTargetGroup == BuildTargetGroup.Mobile) { EnableContent(false); } else { EnableContent(true); } #endif } private void EnableContent(bool enabled) { if (m_Content.Length > 0) { foreach (var g in m_Content) { if (g != null) { g.SetActive(enabled); } } } if (m_ChildrenOfThisObject) { foreach (Transform t in transform) { t.gameObject.SetActive(enabled); } } if (m_MonoBehaviours.Length > 0) { foreach (var monoBehaviour in m_MonoBehaviours) { monoBehaviour.enabled = enabled; } } } } }
23.206612
98
0.497151
[ "BSD-3-Clause" ]
TheRealCatherine/StageMechanic
StageMechanic/Assets/Standard Assets/Utility/PlatformSpecificContent.cs
2,688
C#
using System; using System.Collections.Generic; using System.Text; namespace gov.va.medora.mdo { public class MdoConstants { public const string TIMESTAMP_FORMAT = "yyyyMMdd.HHmmss"; } }
17.333333
65
0.711538
[ "Apache-2.0" ]
VHAINNOVATIONS/RAPTOR
OtherComponents/MDWSvistalayer/MDWS Source/mdo/mdo/src/mdo/domain/MdoConstants.cs
208
C#
using Marten.Linq.SqlGeneration; using Marten.Storage; using Marten.Storage.Metadata; using Marten.Util; using NpgsqlTypes; namespace Marten.Linq.Filters { /// <summary> /// SQL WHERE fragment for a specific tenant /// </summary> internal class SpecificTenantFilter: ISqlFragment { private readonly ITenant _tenant; public SpecificTenantFilter(ITenant tenant) { _tenant = tenant; } public void Apply(CommandBuilder builder) { builder.Append($"d.{TenantIdColumn.Name} = :"); var parameter = builder.AddParameter(_tenant.TenantId, NpgsqlDbType.Varchar); builder.Append(parameter.ParameterName); } public bool Contains(string sqlText) { return false; } } }
24.176471
89
0.624088
[ "MIT" ]
barclayadam/marten
src/Marten/Linq/Filters/SpecificTenantFilter.cs
822
C#
using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace Elysium { public interface IConnection { Uri BaseAddress { get; } ICredentialStore CredentialStore { get; } Credentials Credentials { get; set; } void SetRequestTimeout(TimeSpan timeout); Task<IApiResponse<T>> SendData<T>( Uri uri, HttpMethod method, object body, IDictionary<string, string> headers, TimeSpan? customTimeout, CancellationToken cancellationToken, Uri baseAddress = null); } }
23.857143
49
0.63024
[ "MIT" ]
ElysiumLabs/Elysium-Client
Source/Elysium.Service.Client/Http/IConnection.cs
670
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Forms; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Collections.Specialized; using System.Net; using System.Diagnostics; using System.Threading; using System.IO; using System.Runtime.InteropServices; using System.Drawing; using CSharpAnalytics; namespace BeanfunLogin { public partial class main : Form { private string otp; // Login do work. private void loginWorker_DoWork(object sender, DoWorkEventArgs e) { while (this.pingWorker.IsBusy) Thread.Sleep(137); Debug.WriteLine("loginWorker starting"); Thread.CurrentThread.Name = "Login Worker"; e.Result = ""; try { if (Properties.Settings.Default.loginMethod != (int)LoginMethod.QRCode) this.bfClient = new BeanfunClient(); this.bfClient.Login(this.accountInput.Text, this.passwdInput.Text, Properties.Settings.Default.loginMethod, this.qrcodeClass, this.service_code, this.service_region); if (this.bfClient.errmsg != null) e.Result = this.bfClient.errmsg; else e.Result = null; } catch (Exception ex) { e.Result = "登入失敗,未知的錯誤。\n\n" + ex.Message + "\n" + ex.StackTrace; } } // Login completed. private void loginWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (Properties.Settings.Default.GAEnabled && this.timedActivity != null) { AutoMeasurement.Client.Track(this.timedActivity); this.timedActivity = null; } if (Properties.Settings.Default.keepLogged && !this.pingWorker.IsBusy) this.pingWorker.RunWorkerAsync(); Debug.WriteLine("loginWorker end"); this.panel2.Enabled = true; this.UseWaitCursor = false; this.loginButton.Text = "登入"; if (e.Error != null) { errexit(e.Error.Message, 1); return; } if ((string)e.Result != null) { errexit((string)e.Result, 1); return; } try { redrawSAccountList(); // Handle panel switching. this.ActiveControl = null; this.Size = new System.Drawing.Size(300, this.Size.Height); this.panel2.SendToBack(); this.panel1.BringToFront(); this.AcceptButton = this.getOtpButton; if (Properties.Settings.Default.autoSelectIndex < this.listView1.Items.Count) this.listView1.Items[Properties.Settings.Default.autoSelectIndex].Selected = true; this.listView1.Select(); if (Properties.Settings.Default.autoSelect == true && Properties.Settings.Default.autoSelectIndex < this.bfClient.accountList.Count()) { if (this.pingWorker.IsBusy) { this.pingWorker.CancelAsync(); } this.textBox3.Text = "獲取密碼中..."; this.listView1.Enabled = false; this.getOtpButton.Enabled = false; timedActivity = new CSharpAnalytics.Activities.AutoTimedEventActivity("GetOTP", Properties.Settings.Default.loginMethod.ToString()); if (Properties.Settings.Default.GAEnabled) { AutoMeasurement.Client.TrackEvent("GetOTP" + Properties.Settings.Default.loginMethod.ToString(), "GetOTP"); } this.getOtpWorker.RunWorkerAsync(Properties.Settings.Default.autoSelectIndex); } if (Properties.Settings.Default.keepLogged && !this.pingWorker.IsBusy) this.pingWorker.RunWorkerAsync(); ShowToolTip(listView1, "步驟1", "選擇欲開啟的遊戲帳號,雙擊以複製帳號。"); ShowToolTip(getOtpButton, "步驟2", "按下以在右側產生並自動複製密碼,至遊戲中貼上帳密登入。"); Tip.SetToolTip(getOtpButton, "點擊獲取密碼"); Tip.SetToolTip(listView1, "雙擊即自動複製"); Tip.SetToolTip(textBox3, "點擊一次即自動複製"); Properties.Settings.Default.showTip = false; Properties.Settings.Default.Save(); } catch { errexit("登入失敗,無法取得帳號列表。", 1); } } private void redrawSAccountList() { listView1.Items.Clear(); foreach (var account in this.bfClient.accountList) { string[] row = { WebUtility.HtmlDecode(account.sname), account.sacc }; var listViewItem = new ListViewItem(row); this.listView1.Items.Add(listViewItem); } } // getOTP do work. private void getOtpWorker_DoWork(object sender, DoWorkEventArgs e) { while (this.pingWorker.IsBusy) Thread.Sleep(133); Debug.WriteLine("getOtpWorker start"); Thread.CurrentThread.Name = "GetOTP Worker"; int index = (int)e.Argument; e.Result = index; Debug.WriteLine("Count = " + this.bfClient.accountList.Count + " | index = " + index); if (this.bfClient.accountList.Count <= index) { return; } Debug.WriteLine("call GetOTP"); this.otp = this.bfClient.GetOTP(Properties.Settings.Default.loginMethod, this.bfClient.accountList[index], this.service_code, this.service_region); Debug.WriteLine("call GetOTP done"); if (this.otp == null) { e.Result = -1; return; } if (false == Properties.Settings.Default.opengame) { Debug.WriteLine("no open game"); return; } string procPath = gamePaths.Get(service_name); string sacc = this.bfClient.accountList[index].sacc; string otp = new string(this.otp.Where(c => char.IsLetter(c) || char.IsDigit(c)).ToArray()); if (!File.Exists(procPath)) return; if (Properties.Settings.Default.GAEnabled) { try { AutoMeasurement.Client.TrackEvent(Path.GetFileName(procPath), "processName"); } catch { Debug.WriteLine("invalid path:" + procPath); } } if (procPath.Contains("elsword.exe")) { processStart(procPath, sacc + " " + otp + " TW"); } else if (procPath.Contains("KartRider.exe")) { processStart(procPath, "-id:" + sacc + " -password:" + otp + " -region:1"); } else if (procPath.Contains("mabinogi.exe")) { processStart(procPath, "/N:" + sacc + " /V:" + otp + " /T:gamania"); } else // fallback to default strategy { if (procPath.Contains("MapleStory.exe")) { foreach (Process process in Process.GetProcesses()) { if (process.ProcessName == "MapleStory") { Debug.WriteLine("find game"); return; } } } processStart(procPath, "tw.login.maplestory.gamania.com 8484 BeanFun " + sacc + " " + otp); } return; } private void processStart(string prog, string arg) { try { Debug.WriteLine("try open game"); ProcessStartInfo psInfo = new ProcessStartInfo(); psInfo.FileName = prog; psInfo.Arguments = arg; psInfo.WorkingDirectory = Path.GetDirectoryName(prog); Process.Start(psInfo); Debug.WriteLine("try open game done"); } catch { errexit("啟動失敗,請嘗試手動以系統管理員身分啟動遊戲。", 2); } } // getOTP completed. private void getOtpWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (Properties.Settings.Default.GAEnabled && this.timedActivity != null) { AutoMeasurement.Client.Track(this.timedActivity); this.timedActivity = null; } const int VK_TAB = 0x09; const byte VK_CONTROL = 0x11; const int VK_V = 0x56; const int VK_ENTER = 0x0d; const byte KEYEVENTF_EXTENDEDKEY = 0x1; const byte KEYEVENTF_KEYUP = 0x2; Debug.WriteLine("getOtpWorker end"); this.getOtpButton.Text = "獲取密碼"; this.listView1.Enabled = true; this.getOtpButton.Enabled = true; this.comboBox2.Enabled = true; if (e.Error != null) { this.textBox3.Text = "獲取失敗"; errexit(e.Error.Message, 2); return; } int index = (int)e.Result; if (index == -1) { this.textBox3.Text = "獲取失敗"; errexit(this.bfClient.errmsg, 2); } else { int accIndex = listView1.SelectedItems[0].Index; string acc = this.bfClient.accountList[index].sacc; this.Text = "進行遊戲 - " + WebUtility.HtmlDecode(this.bfClient.accountList[index].sname); try { Clipboard.SetText(acc); } catch { return; } IntPtr hWnd; if (autoPaste.Checked == true && (hWnd = WindowsAPI.FindWindow(null, "MapleStory")) != IntPtr.Zero) { WindowsAPI.SetForegroundWindow(hWnd); WindowsAPI.keybd_event(VK_CONTROL, 0x9d, KEYEVENTF_EXTENDEDKEY, 0); WindowsAPI.keybd_event(VK_V, 0x9e, 0, 0); Thread.Sleep(200); WindowsAPI.keybd_event(VK_V, 0x9e, KEYEVENTF_KEYUP, 0); Thread.Sleep(200); WindowsAPI.keybd_event(VK_CONTROL, 0x9d, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0); WindowsAPI.keybd_event(VK_TAB, 0, KEYEVENTF_EXTENDEDKEY, 0); WindowsAPI.keybd_event(VK_TAB, 0, KEYEVENTF_KEYUP, 0); } this.textBox3.Text = this.otp; try { Clipboard.SetText(textBox3.Text); } catch { return; } Thread.Sleep(250); if (autoPaste.Checked == true && (hWnd = WindowsAPI.FindWindow(null, "MapleStory")) != IntPtr.Zero) { WindowsAPI.keybd_event(VK_CONTROL, 0x9d, KEYEVENTF_EXTENDEDKEY, 0); WindowsAPI.keybd_event(VK_V, 0x9e, 0, 0); Thread.Sleep(200); WindowsAPI.keybd_event(VK_V, 0x9e, KEYEVENTF_KEYUP, 0); Thread.Sleep(200); WindowsAPI.keybd_event(VK_CONTROL, 0x9d, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0); WindowsAPI.keybd_event(VK_ENTER, 0, 0, 0); WindowsAPI.keybd_event(VK_ENTER, 0, KEYEVENTF_KEYUP, 0); listView1.Items[accIndex].BackColor = Color.Green; listView1.Items[accIndex].Selected = false; } } if (Properties.Settings.Default.keepLogged && !this.pingWorker.IsBusy) this.pingWorker.RunWorkerAsync(); } // Ping to Beanfun website. private void pingWorker_DoWork(object sender, DoWorkEventArgs e) { Thread.CurrentThread.Name = "ping Worker"; Debug.WriteLine("pingWorker start"); const int WaitSecs = 60; // 1min while (Properties.Settings.Default.keepLogged) { if (this.pingWorker.CancellationPending) { Debug.WriteLine("break duo to cancel"); break; } if (this.getOtpWorker.IsBusy || this.loginWorker.IsBusy) { Debug.WriteLine("ping.busy sleep 1s"); System.Threading.Thread.Sleep(1000 * 1); continue; } if (this.bfClient != null) this.bfClient.Ping(); for (int i = 0; i < WaitSecs; ++i) { if (this.pingWorker.CancellationPending) break; System.Threading.Thread.Sleep(1000 * 1); } } } private void pingWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { Debug.WriteLine("ping.done"); } private void qrWorker_DoWork(object sender, DoWorkEventArgs e) { this.bfClient = new BeanfunClient(); string skey = this.bfClient.GetSessionkey(); this.qrcodeClass = this.bfClient.GetQRCodeValue(skey, (bool)e.Argument); } private void qrWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { this.loginMethodInput.Enabled = true; wait_qrWorker_notify.Visible = false; if (this.qrcodeClass == null) wait_qrWorker_notify.Text = "QRCode取得失敗"; else { qrcodeImg.Image = qrcodeClass.bitmap; qrCheckLogin.Enabled = true; } } private void qrCheckLogin_Tick(object sender, EventArgs e) { if (this.qrcodeClass == null) { MessageBox.Show("QRCode not get yet"); return; } int res = this.bfClient.QRCodeCheckLoginStatus(this.qrcodeClass); if (res != 0) this.qrCheckLogin.Enabled = false; if (res == 1) { loginButton_Click(null, null); } if (res == -2) { comboBox1_SelectedIndexChanged(null, null); } } } }
36.740196
182
0.506604
[ "MIT" ]
Markful/BeanfunLogin
BeanfunLogin/Form1.Connect.cs
15,286
C#
#region Header // // Copyright 2003-2014 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // #endregion // Header using System; using System.Diagnostics; using System.Drawing; using System.Collections; using System.Collections.Generic; using System.Linq; using System.ComponentModel; using System.Windows.Forms; using Autodesk.Revit.DB; namespace RevitLookup.Snoop.Forms { /// <summary> /// Summary description for Object form. /// </summary> public class Objects : System.Windows.Forms.Form { protected System.Windows.Forms.Button m_bnOK; protected System.Windows.Forms.TreeView m_tvObjs; protected System.Windows.Forms.ContextMenu m_cntxMenuObjId; protected System.Windows.Forms.MenuItem m_mnuItemBrowseReflection; protected System.Windows.Forms.ListView m_lvData; protected System.Windows.Forms.ColumnHeader m_lvCol_label; protected System.Windows.Forms.ColumnHeader m_lvCol_value; protected Snoop.Collectors.CollectorObj m_snoopCollector = new Snoop.Collectors.CollectorObj(); protected System.Object m_curObj; protected ArrayList m_treeTypeNodes = new ArrayList(); protected ArrayList m_types = new ArrayList(); private ContextMenuStrip listViewContextMenuStrip; private System.Windows.Forms.MenuItem m_mnuItemCopy; private ToolStripMenuItem copyToolStripMenuItem; private ToolStrip toolStrip1; private ToolStripButton toolStripButton1; private ToolStripButton toolStripButton2; private PrintDialog m_printDialog; private System.Drawing.Printing.PrintDocument m_printDocument; private PrintPreviewDialog m_printPreviewDialog; private IContainer components; private Int32[] m_maxWidths; private ToolStripButton toolStripButton3; private Int32 m_currentPrintItem = 0; protected Objects() { // this constructor is for derived classes to call InitializeComponent(); } public Objects( System.Object obj ) { InitializeComponent(); // get in array form so we can call normal processing code. ArrayList objs = new ArrayList(); objs.Add( obj ); CommonInit( objs ); } public Objects( ArrayList objs ) { InitializeComponent(); CommonInit( objs ); } public Objects( Document doc, ICollection<ElementId> ids ) { InitializeComponent(); ICollection<Element> elemSet = new List<Element>( ids.Select<ElementId, Element>( id => doc.GetElement( id ) ) ); CommonInit( elemSet ); } protected void CommonInit( IEnumerable objs ) { m_tvObjs.BeginUpdate(); AddObjectsToTree( objs ); // if the tree isn't well populated, expand it and select the first item // so its not a pain for the user when there is only one relevant item in the tree if( m_tvObjs.Nodes.Count == 1 ) { m_tvObjs.Nodes[0].Expand(); if( m_tvObjs.Nodes[0].Nodes.Count == 0 ) m_tvObjs.SelectedNode = m_tvObjs.Nodes[0]; else m_tvObjs.SelectedNode = m_tvObjs.Nodes[0].Nodes[0]; } m_tvObjs.EndUpdate(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if( 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> protected void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager( typeof( Objects ) ); this.m_tvObjs = new System.Windows.Forms.TreeView(); this.m_cntxMenuObjId = new System.Windows.Forms.ContextMenu(); this.m_mnuItemCopy = new System.Windows.Forms.MenuItem(); this.m_mnuItemBrowseReflection = new System.Windows.Forms.MenuItem(); this.m_bnOK = new System.Windows.Forms.Button(); this.m_lvData = new System.Windows.Forms.ListView(); this.m_lvCol_label = new System.Windows.Forms.ColumnHeader(); this.m_lvCol_value = new System.Windows.Forms.ColumnHeader(); this.listViewContextMenuStrip = new System.Windows.Forms.ContextMenuStrip( this.components ); this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.m_printDialog = new System.Windows.Forms.PrintDialog(); this.m_printDocument = new System.Drawing.Printing.PrintDocument(); this.m_printPreviewDialog = new System.Windows.Forms.PrintPreviewDialog(); this.toolStripButton3 = new System.Windows.Forms.ToolStripButton(); this.listViewContextMenuStrip.SuspendLayout(); this.toolStrip1.SuspendLayout(); this.SuspendLayout(); // // m_tvObjs // this.m_tvObjs.Anchor = ( (System.Windows.Forms.AnchorStyles) ( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom ) | System.Windows.Forms.AnchorStyles.Left ) ) ); this.m_tvObjs.ContextMenu = this.m_cntxMenuObjId; this.m_tvObjs.HideSelection = false; this.m_tvObjs.Location = new System.Drawing.Point( 12, 28 ); this.m_tvObjs.Name = "m_tvObjs"; this.m_tvObjs.Size = new System.Drawing.Size( 248, 430 ); this.m_tvObjs.TabIndex = 0; this.m_tvObjs.NodeMouseClick += new TreeNodeMouseClickEventHandler( this.TreeNodeSelected ); this.m_tvObjs.AfterSelect += new System.Windows.Forms.TreeViewEventHandler( this.TreeNodeSelected ); // // m_cntxMenuObjId // this.m_cntxMenuObjId.MenuItems.AddRange( new System.Windows.Forms.MenuItem[] { this.m_mnuItemCopy, this.m_mnuItemBrowseReflection} ); // // m_mnuItemCopy // this.m_mnuItemCopy.Index = 0; this.m_mnuItemCopy.Text = "Copy"; this.m_mnuItemCopy.Click += new System.EventHandler( this.ContextMenuClick_Copy ); // // m_mnuItemBrowseReflection // this.m_mnuItemBrowseReflection.Index = 1; this.m_mnuItemBrowseReflection.Text = "Browse Using Reflection..."; this.m_mnuItemBrowseReflection.Click += new System.EventHandler( this.ContextMenuClick_BrowseReflection ); // // m_bnOK // this.m_bnOK.Anchor = System.Windows.Forms.AnchorStyles.Bottom; this.m_bnOK.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.m_bnOK.FlatStyle = System.Windows.Forms.FlatStyle.System; this.m_bnOK.Location = new System.Drawing.Point( 365, 464 ); this.m_bnOK.Name = "m_bnOK"; this.m_bnOK.Size = new System.Drawing.Size( 75, 23 ); this.m_bnOK.TabIndex = 2; this.m_bnOK.Text = "OK"; // // m_lvData // this.m_lvData.Anchor = ( (System.Windows.Forms.AnchorStyles) ( ( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom ) | System.Windows.Forms.AnchorStyles.Left ) | System.Windows.Forms.AnchorStyles.Right ) ) ); this.m_lvData.Columns.AddRange( new System.Windows.Forms.ColumnHeader[] { this.m_lvCol_label, this.m_lvCol_value} ); this.m_lvData.ContextMenuStrip = this.listViewContextMenuStrip; this.m_lvData.FullRowSelect = true; this.m_lvData.GridLines = true; this.m_lvData.Location = new System.Drawing.Point( 284, 28 ); this.m_lvData.Name = "m_lvData"; this.m_lvData.ShowItemToolTips = true; this.m_lvData.Size = new System.Drawing.Size( 504, 430 ); this.m_lvData.TabIndex = 3; this.m_lvData.UseCompatibleStateImageBehavior = false; this.m_lvData.View = System.Windows.Forms.View.Details; this.m_lvData.DoubleClick += new System.EventHandler( this.DataItemSelected ); this.m_lvData.Click += new System.EventHandler( this.DataItemSelected ); // // m_lvCol_label // this.m_lvCol_label.Text = "Field"; this.m_lvCol_label.Width = 200; // // m_lvCol_value // this.m_lvCol_value.Text = "Value"; this.m_lvCol_value.Width = 300; // // listViewContextMenuStrip // this.listViewContextMenuStrip.Items.AddRange( new System.Windows.Forms.ToolStripItem[] { this.copyToolStripMenuItem} ); this.listViewContextMenuStrip.Name = "listViewContextMenuStrip"; this.listViewContextMenuStrip.Size = new System.Drawing.Size( 100, 26 ); // // copyToolStripMenuItem // this.copyToolStripMenuItem.Image = global::RevitLookup.Properties.Resources.COPY; this.copyToolStripMenuItem.Name = "copyToolStripMenuItem"; this.copyToolStripMenuItem.Size = new System.Drawing.Size( 99, 22 ); this.copyToolStripMenuItem.Text = "Copy"; this.copyToolStripMenuItem.Click += new System.EventHandler( this.CopyToolStripMenuItem_Click ); // // toolStrip1 // this.toolStrip1.Items.AddRange( new System.Windows.Forms.ToolStripItem[] { this.toolStripButton1, this.toolStripButton2, this.toolStripButton3} ); this.toolStrip1.Location = new System.Drawing.Point( 0, 0 ); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size( 800, 25 ); this.toolStrip1.TabIndex = 4; // // toolStripButton1 // this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton1.Image = global::RevitLookup.Properties.Resources.Print; this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton1.Name = "toolStripButton1"; this.toolStripButton1.Size = new System.Drawing.Size( 23, 22 ); this.toolStripButton1.Text = "Print"; this.toolStripButton1.Click += new System.EventHandler( this.PrintMenuItem_Click ); // // toolStripButton2 // this.toolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton2.Image = global::RevitLookup.Properties.Resources.Preview; this.toolStripButton2.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton2.Name = "toolStripButton2"; this.toolStripButton2.Size = new System.Drawing.Size( 23, 22 ); this.toolStripButton2.Text = "Print Preview"; this.toolStripButton2.Click += new System.EventHandler( this.PrintPreviewMenuItem_Click ); // // m_printDialog // this.m_printDialog.Document = this.m_printDocument; this.m_printDialog.UseEXDialog = true; // // m_printDocument // this.m_printDocument.PrintPage += new System.Drawing.Printing.PrintPageEventHandler( this.PrintDocument_PrintPage ); // // m_printPreviewDialog // this.m_printPreviewDialog.AutoScrollMargin = new System.Drawing.Size( 0, 0 ); this.m_printPreviewDialog.AutoScrollMinSize = new System.Drawing.Size( 0, 0 ); this.m_printPreviewDialog.ClientSize = new System.Drawing.Size( 400, 300 ); this.m_printPreviewDialog.Document = this.m_printDocument; this.m_printPreviewDialog.Enabled = true; this.m_printPreviewDialog.Icon = ( (System.Drawing.Icon) ( resources.GetObject( "m_printPreviewDialog.Icon" ) ) ); this.m_printPreviewDialog.Name = "m_printPreviewDialog"; this.m_printPreviewDialog.Visible = false; // // toolStripButton3 // this.toolStripButton3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton3.Image = global::RevitLookup.Properties.Resources.COPY; this.toolStripButton3.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton3.Name = "toolStripButton3"; this.toolStripButton3.Size = new System.Drawing.Size( 23, 22 ); this.toolStripButton3.Text = "Copy To Clipboard"; this.toolStripButton3.Click += new System.EventHandler( this.ContextMenuClick_Copy ); // // Objects // this.AutoScaleBaseSize = new System.Drawing.Size( 5, 13 ); this.ClientSize = new System.Drawing.Size( 800, 492 ); this.Controls.Add( this.toolStrip1 ); this.Controls.Add( this.m_lvData ); this.Controls.Add( this.m_tvObjs ); this.Controls.Add( this.m_bnOK ); this.MaximizeBox = false; this.MinimizeBox = false; this.MinimumSize = new System.Drawing.Size( 650, 200 ); this.Name = "Objects"; this.ShowInTaskbar = false; this.Text = "Snoop Objects"; this.listViewContextMenuStrip.ResumeLayout( false ); this.toolStrip1.ResumeLayout( false ); this.toolStrip1.PerformLayout(); this.ResumeLayout( false ); this.PerformLayout(); } #endregion protected void AddObjectsToTree( IEnumerable objs ) { m_tvObjs.Sorted = true; // initialize the tree control foreach( Object tmpObj in objs ) { // hook this up to the correct spot in the tree based on the object's type TreeNode parentNode = GetExistingNodeForType( tmpObj.GetType() ); if( parentNode == null ) { parentNode = new TreeNode( tmpObj.GetType().Name ); m_tvObjs.Nodes.Add( parentNode ); // record that we've seen this one m_treeTypeNodes.Add( parentNode ); m_types.Add( tmpObj.GetType() ); } // add the new node for this element TreeNode tmpNode = new TreeNode( Snoop.Utils.ObjToLabelStr( tmpObj ) ); tmpNode.Tag = tmpObj; parentNode.Nodes.Add( tmpNode ); } } /// <summary> /// If we've already seen this type before, return the existing TreeNode object /// </summary> /// <param name="objType">System.Type we're looking to find</param> /// <returns>The existing TreeNode or NULL</returns> protected TreeNode GetExistingNodeForType( System.Type objType ) { int len = m_types.Count; for( int i = 0; i < len; i++ ) { if( (System.Type) m_types[i] == objType ) return (TreeNode) m_treeTypeNodes[i]; } return null; } #region Events protected void TreeNodeSelected( object sender, System.Windows.Forms.TreeViewEventArgs e ) { m_curObj = e.Node.Tag; // collect the data about this object m_snoopCollector.Collect( m_curObj ); // display it Snoop.Utils.Display( m_lvData, m_snoopCollector ); } protected void TreeNodeSelected( object sender, System.Windows.Forms.TreeNodeMouseClickEventArgs e ) { m_curObj = e.Node.Tag; // collect the data about this object m_snoopCollector.Collect( m_curObj ); // display it Snoop.Utils.Display( m_lvData, m_snoopCollector ); } protected void DataItemSelected( object sender, System.EventArgs e ) { Snoop.Utils.DataItemSelected( m_lvData ); } private void ContextMenuClick_Copy( object sender, System.EventArgs e ) { if( m_tvObjs.SelectedNode != null ) { Utils.CopyToClipboard( m_lvData ); } } private void ContextMenuClick_BrowseReflection( object sender, System.EventArgs e ) { Snoop.Utils.BrowseReflection( m_curObj ); } private void CopyToolStripMenuItem_Click( object sender, System.EventArgs e ) { if( m_lvData.SelectedItems.Count > 0 ) { Utils.CopyToClipboard( m_lvData.SelectedItems[0], false ); } else { Clipboard.Clear(); } } private void PrintMenuItem_Click( object sender, EventArgs e ) { Utils.UpdatePrintSettings( m_printDocument, m_tvObjs, m_lvData, ref m_maxWidths ); Utils.PrintMenuItemClick( m_printDialog, m_tvObjs ); } private void PrintPreviewMenuItem_Click( object sender, EventArgs e ) { Utils.UpdatePrintSettings( m_printDocument, m_tvObjs, m_lvData, ref m_maxWidths ); Utils.PrintPreviewMenuItemClick( m_printPreviewDialog, m_tvObjs ); } private void PrintDocument_PrintPage( object sender, System.Drawing.Printing.PrintPageEventArgs e ) { m_currentPrintItem = Utils.Print( m_tvObjs.SelectedNode.Text, m_lvData, e, m_maxWidths[0], m_maxWidths[1], m_currentPrintItem ); } #endregion } }
38.43129
158
0.661789
[ "MIT" ]
jabirLJ/RevitLookup
CS/Snoop/Forms/Objects.cs
18,178
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WaapiCS.Communication; namespace ak { public static partial class wwise { public static class ui { /// <summary> /// Gets the currently selected Wwise objects. /// </summary> /// <returns>Details about the selected objects.</returns> public static List<Dictionary<string, object>> GetSelectedObjects() { if (packet.results != null) packet.results.Clear(); packet.procedure = "ak.wwise.ui.getSelectedObjects"; packet.callback = new Callback(packet); packet.options.@return = returnValues2017_1_0_6302; results = connection.Execute(packet); packet.Clear(); return (List<Dictionary<string, object>>)results; } public static void BringToForeground() { if (packet.results != null) packet.results.Clear(); packet.procedure = "ak.wwise.ui.bringToForeground"; packet.callback = new Callback(packet); results = connection.Execute(packet); packet.Clear(); } public static class project { /// <summary> /// Closes the current Wwise project. /// </summary> /// <param name="bypassSave">if set to <c>true</c> [bypass save].</param> public static void Close(bool bypassSave) { if (packet.results != null) packet.results.Clear(); packet.procedure = "ak.wwise.ui.project.close"; packet.callback = new Callback(packet); results = connection.Execute(packet); packet.Clear(); } /// <summary> /// Opens the "open project" dialogue in Wwise. /// </summary> /// <param name="bypassSave">if set to <c>true</c> [bypass save].</param> public static void Open(bool bypassSave) { if (packet.results != null) packet.results.Clear(); packet.procedure = "ak.wwise.ui.project.open"; packet.callback = new Callback(packet); results = connection.Execute(packet); packet.Clear(); } } public static class commands { /// <summary> /// Executes the specified command. Command list can be retrieved via "GetCommands". /// </summary> /// <param name="command">The command to run.</param> public static void Execute(string command, string[] objects = null) { if (packet.results != null) packet.results.Clear(); if (objects != null) packet.keywordArguments.Add("objects", objects); packet.keywordArguments.Add("command", command); packet.callback = new Callback(packet); packet.procedure = "ak.wwise.ui.commands.execute"; results = connection.Execute(packet); packet.Clear(); } /// <summary> /// Gets the available list of commands for Wwise to execute. /// </summary> /// <returns>The List<string> of commands.</returns> public static List<string> GetCommands() { packet.results = new List<string>(); packet.results.Clear(); packet.callback = new Callback(packet); packet.procedure = "ak.wwise.ui.commands.getCommands"; results = connection.Execute(packet); packet.Clear(); return (List<string>)results; } } } } }
39.357798
101
0.47972
[ "MIT" ]
adamtcroft/WaapiCS
WaapiCS/UI.cs
4,292
C#
/*********************************************************************************************************************** Copyright (c) 2016, Imagination Technologies Limited and/or its affiliated group companies. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DTLS { //struct { // HandshakeType msg_type; // uint24 length; // uint16 message_seq; // New field // uint24 fragment_offset; // New field // uint24 fragment_length; // New field // select (HandshakeType) { // case hello_request: HelloRequest; // case client_hello: ClientHello; // case server_hello: ServerHello; // case hello_verify_request: HelloVerifyRequest; // New field // case certificate:Certificate; // case server_key_exchange: ServerKeyExchange; // case certificate_request: CertificateRequest; // case server_hello_done:ServerHelloDone; // case certificate_verify: CertificateVerify; // case client_key_exchange: ClientKeyExchange; // case finished: Finished; // } body; } Handshake; internal class HandshakeRecord { public const int RECORD_OVERHEAD = 12; THandshakeType _MessageType; uint _Length; ushort _MessageSeq; uint _FragmentOffset; uint _FragmentLength; public THandshakeType MessageType { get { return _MessageType; } set { _MessageType = value; } } public uint Length { get { return _Length; } set { _Length = value; } } public ushort MessageSeq { get { return _MessageSeq; } set { _MessageSeq = value; } } public uint FragmentOffset { get { return _FragmentOffset; } set { _FragmentOffset = value; } } public uint FragmentLength { get { return _FragmentLength; } set { _FragmentLength = value; } } public static HandshakeRecord Deserialise(System.IO.Stream stream) { HandshakeRecord result = new HandshakeRecord(); result._MessageType = (THandshakeType)stream.ReadByte(); result._Length = NetworkByteOrderConverter.ToUInt24(stream); result._MessageSeq = NetworkByteOrderConverter.ToUInt16(stream); result._FragmentOffset = NetworkByteOrderConverter.ToUInt24(stream); result._FragmentLength = NetworkByteOrderConverter.ToUInt24(stream); return result; } public void Serialise(System.IO.Stream stream) { stream.WriteByte((byte)_MessageType); NetworkByteOrderConverter.WriteUInt24(stream, _Length); NetworkByteOrderConverter.WriteUInt16(stream, _MessageSeq); NetworkByteOrderConverter.WriteUInt24(stream, _FragmentOffset); NetworkByteOrderConverter.WriteUInt24(stream, _FragmentLength); } } // struct { // ProtocolVersion server_version; // opaque cookie<0..2^8-1>; } HelloVerifyRequest; }
37.747899
121
0.686999
[ "BSD-3-Clause" ]
CreatorDev/DTLS.Net
src/DTLS.Net/Records/HandshakeRecord.cs
4,494
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Expenses { public partial class About { } }
23.722222
81
0.398126
[ "MIT" ]
rlphila/expenses
Expenses/About.aspx.designer.cs
429
C#
namespace VRTK.UnityEventHelper { using UnityEngine.Events; using System; public sealed class VRTK_PlayerClimb_UnityEvents : VRTK_UnityEvents<VRTK_PlayerClimb> { [Serializable] public sealed class PlayerClimbEvent : UnityEvent<object, PlayerClimbEventArgs> { } public PlayerClimbEvent OnPlayerClimbStarted = new PlayerClimbEvent(); public PlayerClimbEvent OnPlayerClimbEnded = new PlayerClimbEvent(); protected override void AddListeners(VRTK_PlayerClimb component) { component.PlayerClimbStarted += PlayerClimbStarted; component.PlayerClimbEnded += PlayerClimbEnded; } protected override void RemoveListeners(VRTK_PlayerClimb component) { component.PlayerClimbStarted -= PlayerClimbStarted; component.PlayerClimbEnded -= PlayerClimbEnded; } private void PlayerClimbStarted(object o, PlayerClimbEventArgs e) { OnPlayerClimbStarted.Invoke(o, e); } private void PlayerClimbEnded(object o, PlayerClimbEventArgs e) { OnPlayerClimbEnded.Invoke(o, e); } } }
32.722222
91
0.67657
[ "MIT" ]
FullBoreStudios/FBVRK
Assets/VRTK/Scripts/Utilities/UnityEvents/VRTK_PlayerClimb_UnityEvents.cs
1,180
C#
using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; namespace DensoCreate.LightningReview.ReviewFile.Models.V10 { /// <summary> /// ドキュメント /// </summary> [XmlRoot] public class Document : IDocument { #region プロパティ /// <summary> /// グローバルID(V10定義) /// </summary> [XmlAttribute] public string GlobalID { get; set; } /// <summary> /// グローバルID /// </summary> public string GID { get => GlobalID; set => GlobalID = value; } /// <summary> /// ローカルID(V10定義) /// </summary> [XmlAttribute] public string ID { get; set; } /// <summary> /// ローカルID /// </summary> public string LID { get => ID; set => ID = value; } /// <summary> /// ドキュメント名 /// </summary> [XmlAttribute] public string Name { get; set; } /// <summary> /// ドキュメントの絶対パス /// </summary> [XmlElement] public string AbsolutePath { get; set; } /// <summary> /// 関連づいているアプリケーション /// </summary> [XmlElement] public string ApplicationType { get; set; } /// <summary> /// このドキュメントに関連づくアウトラインの一覧 /// </summary> public IEnumerable<IOutlineNode> OutlineNodes => throw new NotImplementedException(); #endregion } }
22.828125
93
0.509925
[ "MIT" ]
denso-create/LightningReview-ReviewFile
src/ReviewFile/Models/V10/Document.cs
1,647
C#
using Dm; using FreeSql.DatabaseModel; using FreeSql.Internal; using FreeSql.Internal.Model; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace FreeSql.Dameng { class DamengDbFirst : IDbFirst { IFreeSql _orm; protected CommonUtils _commonUtils; protected CommonExpression _commonExpression; public DamengDbFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) { _orm = orm; _commonUtils = commonUtils; _commonExpression = commonExpression; } public int GetDbType(DbColumnInfo column) => (int)GetSqlDbType(column); DmDbType GetSqlDbType(DbColumnInfo column) { var dbfull = column.DbTypeTextFull.ToLower(); switch (dbfull) { case "number(1)": return DmDbType.Bit; case "number(4)": return DmDbType.SByte; case "number(6)": return DmDbType.Int16; case "number(11)": return DmDbType.Int32; case "number(21)": return DmDbType.Int64; case "number(3)": return DmDbType.Byte; case "number(5)": return DmDbType.UInt16; case "number(10)": return DmDbType.UInt32; case "number(20)": return DmDbType.UInt64; case "float(126)": return DmDbType.Double; case "float(63)": return DmDbType.Float; case "number(10,2)": return DmDbType.Decimal; case "interval day(2) to second(6)": return DmDbType.Time; case "timestamp(6)": return DmDbType.DateTime; case "timestamp(6) with local time zone": return DmDbType.DateTime; case "blob": return DmDbType.VarBinary; case "nvarchar2(255)": return DmDbType.VarChar; case "char(36)": return DmDbType.Char; } switch (column.DbTypeText.ToLower()) { case "bit": _dicDbToCs.TryAdd(dbfull, _dicDbToCs["number(1)"]); return DmDbType.Bit; case "smallint": _dicDbToCs.TryAdd(dbfull, _dicDbToCs["number(4)"]); return DmDbType.UInt16; case "byte": _dicDbToCs.TryAdd(dbfull, _dicDbToCs["number(3)"]); return DmDbType.Byte; case "tinyint": _dicDbToCs.TryAdd(dbfull, _dicDbToCs["number(3)"]); return DmDbType.Byte; case "integer": _dicDbToCs.TryAdd(dbfull, _dicDbToCs["number(11)"]); return DmDbType.Int32; case "bigint": _dicDbToCs.TryAdd(dbfull, _dicDbToCs["number(21)"]); return DmDbType.Int64; case "dec": case "decimal": case "numeric": case "number": _dicDbToCs.TryAdd(dbfull, _dicDbToCs["number(10,2)"]); return DmDbType.Decimal; case "time": case "interval day to second": case "interval year to month": case "interval year": case "interval month": case "interval day": case "interval day to hour": case "interval day to minute": case "interval hour": case "interval hour to minute": case "interval hour to second": case "interval minute": case "interval minute to second": case "interval second": case "time with time zone": _dicDbToCs.TryAdd(dbfull, _dicDbToCs["interval day(2) to second(6)"]); return DmDbType.Time; case "date": _dicDbToCs.TryAdd(dbfull, _dicDbToCs["date(7)"]); return DmDbType.DateTime; case "timestamp": _dicDbToCs.TryAdd(dbfull, _dicDbToCs["timestamp(6)"]); return DmDbType.DateTime; case "timestamp with local time zone": case "timestamp with time zone": _dicDbToCs.TryAdd(dbfull, _dicDbToCs["timestamp(6) with local time zone"]); return DmDbType.DateTime; case "binary": case "varbinary": case "blob": case "image": case "longvarbinary": case "bfile": _dicDbToCs.TryAdd(dbfull, _dicDbToCs["blob"]); return DmDbType.VarBinary; case "nvarchar2": _dicDbToCs.TryAdd(dbfull, _dicDbToCs["nvarchar2(255)"]); return DmDbType.VarChar; case "varchar": case "varchar2": case "text": case "longvarchar": _dicDbToCs.TryAdd(dbfull, _dicDbToCs["nvarchar2(255)"]); return DmDbType.VarChar; case "character": case "char": _dicDbToCs.TryAdd(dbfull, _dicDbToCs["nvarchar2(255)"]); return DmDbType.Char; case "nchar": _dicDbToCs.TryAdd(dbfull, _dicDbToCs["nvarchar2(255)"]); return DmDbType.Char; case "clob": _dicDbToCs.TryAdd(dbfull, _dicDbToCs["nvarchar2(255)"]); return DmDbType.VarChar; case "nclob": _dicDbToCs.TryAdd(dbfull, _dicDbToCs["nvarchar2(255)"]); return DmDbType.VarChar; case "raw": _dicDbToCs.TryAdd(dbfull, _dicDbToCs["blob"]); return DmDbType.VarBinary; case "long raw": _dicDbToCs.TryAdd(dbfull, _dicDbToCs["blob"]); return DmDbType.VarBinary; case "real": case "binary_float": _dicDbToCs.TryAdd(dbfull, _dicDbToCs["float(63)"]); return DmDbType.Float; case "double": case "float": case "double precision": case "binary_double": _dicDbToCs.TryAdd(dbfull, _dicDbToCs["float(126)"]); return DmDbType.Double; case "rowid": default: _dicDbToCs.TryAdd(dbfull, _dicDbToCs["nvarchar2(255)"]); return DmDbType.VarChar; } throw new NotImplementedException($"未实现 {column.DbTypeTextFull} 类型映射"); } static ConcurrentDictionary<string, DbToCs> _dicDbToCs = new ConcurrentDictionary<string, DbToCs>(StringComparer.CurrentCultureIgnoreCase); static DamengDbFirst() { var defaultDbToCs = new Dictionary<string, DbToCs>() { { "number(1)", new DbToCs("(bool?)", "{0} == \"1\"", "{0} == true ? \"1\" : \"0\"", "bool?", typeof(bool), typeof(bool?), "{0}.Value", "GetBoolean") }, { "number(4)", new DbToCs("(sbyte?)", "sbyte.Parse({0})", "{0}.ToString()", "sbyte?", typeof(sbyte), typeof(sbyte?), "{0}.Value", "GetInt16") }, { "number(6)", new DbToCs("(short?)", "short.Parse({0})", "{0}.ToString()", "short?", typeof(short), typeof(short?), "{0}.Value", "GetInt16") }, { "number(11)", new DbToCs("(int?)", "int.Parse({0})", "{0}.ToString()", "int?", typeof(int), typeof(int?), "{0}.Value", "GetInt32") }, { "number(21)", new DbToCs("(long?)", "long.Parse({0})", "{0}.ToString()", "long?", typeof(long), typeof(long?), "{0}.Value", "GetInt64") }, { "number(3)", new DbToCs("(byte?)", "byte.Parse({0})", "{0}.ToString()", "byte?", typeof(byte), typeof(byte?), "{0}.Value", "GetByte") }, { "number(5)", new DbToCs("(ushort?)", "ushort.Parse({0})", "{0}.ToString()", "ushort?", typeof(ushort), typeof(ushort?), "{0}.Value", "GetInt32") }, { "number(10)", new DbToCs("(uint?)", "uint.Parse({0})", "{0}.ToString()", "uint?", typeof(uint), typeof(uint?), "{0}.Value", "GetInt64") }, { "number(20)", new DbToCs("(ulong?)", "ulong.Parse({0})", "{0}.ToString()", "ulong?", typeof(ulong), typeof(ulong?), "{0}.Value", "GetDecimal") }, { "float(126)", new DbToCs("(double?)", "double.Parse({0})", "{0}.ToString()", "double?", typeof(double), typeof(double?), "{0}.Value", "GetDouble") }, { "float(63)", new DbToCs("(float?)", "float.Parse({0})", "{0}.ToString()", "float?", typeof(float), typeof(float?), "{0}.Value", "GetFloat") }, { "number(10,2)", new DbToCs("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") }, { "interval day(2) to second(6)", new DbToCs("(TimeSpan?)", "TimeSpan.Parse(double.Parse({0}))", "{0}.Ticks.ToString()", "TimeSpan?", typeof(TimeSpan), typeof(TimeSpan?), "{0}.Value", "GetValue") }, { "date(7)", new DbToCs("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetValue") }, { "timestamp(6)", new DbToCs("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetValue") }, { "timestamp(6) with local time zone", new DbToCs("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetValue") }, { "blob", new DbToCs("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, { "nvarchar2(255)", new DbToCs("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, { "char(36 char)", new DbToCs("(Guid?)", "Guid.Parse({0})", "{0}.ToString()", "Guid?", typeof(Guid), typeof(Guid?), "{0}.Value", "GetGuid") }, }; foreach (var kv in defaultDbToCs) _dicDbToCs.TryAdd(kv.Key, kv.Value); } public string GetCsConvert(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbTypeTextFull, out var trydc) ? (column.IsNullable ? trydc.csConvert : trydc.csConvert.Replace("?", "")) : null; public string GetCsParse(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbTypeTextFull, out var trydc) ? trydc.csParse : null; public string GetCsStringify(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbTypeTextFull, out var trydc) ? trydc.csStringify : null; public string GetCsType(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbTypeTextFull, out var trydc) ? (column.IsNullable ? trydc.csType : trydc.csType.Replace("?", "")) : null; public Type GetCsTypeInfo(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbTypeTextFull, out var trydc) ? trydc.csTypeInfo : null; public string GetCsTypeValue(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbTypeTextFull, out var trydc) ? trydc.csTypeValue : null; public string GetDataReaderMethod(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbTypeTextFull, out var trydc) ? trydc.dataReaderMethod : null; public List<string> GetDatabases() { var sql = @" select username from all_users"; var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); return ds.Select(a => a.FirstOrDefault()?.ToString()).ToList(); } public List<DbTableInfo> GetTablesByDatabase(params string[] database2) { var loc1 = new List<DbTableInfo>(); var loc2 = new Dictionary<string, DbTableInfo>(); var loc3 = new Dictionary<string, Dictionary<string, DbColumnInfo>>(); var database = database2?.ToArray(); if (database == null || database.Any() == false) { var userUsers = _orm.Ado.ExecuteScalar(" select username from user_users")?.ToString(); if (string.IsNullOrEmpty(userUsers)) return loc1; database = new[] { userUsers }; } var databaseIn = string.Join(",", database.Select(a => _commonUtils.FormatSql("{0}", a))); var sql = string.Format(@" select a.owner || '.' || a.table_name, a.owner, a.table_name, b.comments, 'TABLE' from all_tables a left join all_tab_comments b on b.owner = a.owner and b.table_name = a.table_name and b.table_type = 'TABLE' where a.owner in ({0})", databaseIn); var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); if (ds == null) return loc1; var loc6 = new List<string[]>(); var loc66 = new List<string[]>(); var loc6_1000 = new List<string>(); var loc66_1000 = new List<string>(); foreach (var row in ds) { var table_id = string.Concat(row[0]); var schema = string.Concat(row[1]); var table = string.Concat(row[2]); var comment = string.Concat(row[3]); var type = string.Concat(row[4]) == "VIEW" ? DbTableType.VIEW : DbTableType.TABLE; if (database.Length == 1) { table_id = table_id.Substring(table_id.IndexOf('.') + 1); schema = ""; } loc2.Add(table_id, new DbTableInfo { Id = table_id, Schema = schema, Name = table, Comment = comment, Type = type }); loc3.Add(table_id, new Dictionary<string, DbColumnInfo>()); switch (type) { case DbTableType.TABLE: case DbTableType.VIEW: loc6_1000.Add(table.Replace("'", "''")); if (loc6_1000.Count >= 999) { loc6.Add(loc6_1000.ToArray()); loc6_1000.Clear(); } break; case DbTableType.StoreProcedure: loc66_1000.Add(table.Replace("'", "''")); if (loc66_1000.Count >= 999) { loc66.Add(loc66_1000.ToArray()); loc66_1000.Clear(); } break; } } if (loc6_1000.Count > 0) loc6.Add(loc6_1000.ToArray()); if (loc66_1000.Count > 0) loc66.Add(loc66_1000.ToArray()); if (loc6.Count == 0) return loc1; var loc8 = new StringBuilder().Append("("); for (var loc8idx = 0; loc8idx < loc6.Count; loc8idx++) { if (loc8idx > 0) loc8.Append(" OR "); loc8.Append("a.table_name in ("); for (var loc8idx2 = 0; loc8idx2 < loc6[loc8idx].Length; loc8idx2++) { if (loc8idx2 > 0) loc8.Append(","); loc8.Append($"'{loc6[loc8idx][loc8idx2]}'"); } loc8.Append(")"); } loc8.Append(")"); sql = string.Format(@" select a.owner || '.' || a.table_name, a.column_name, a.data_type, a.data_length, a.data_precision, a.data_scale, a.char_used, case when a.nullable = 'N' then 0 else 1 end, nvl((select 1 from user_sequences where upper(sequence_name)=upper(a.table_name||'_seq_'||a.column_name) and rownum < 2), 0), b.comments, a.data_default from all_tab_cols a left join all_col_comments b on b.owner = a.owner and b.table_name = a.table_name and b.column_name = a.column_name where a.owner in ({1}) and {0} ", loc8, databaseIn); ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); if (ds == null) return loc1; var ds2 = new List<object[]>(); foreach (var row in ds) { var ds2item = new object[9]; ds2item[0] = row[0]; ds2item[1] = row[1]; ds2item[2] = Regex.Replace(string.Concat(row[2]), @"\(\d+\)", ""); ds2item[4] = DamengCodeFirst.GetDamengSqlTypeFullName(new object[] { row[1], row[2], row[3], row[4], row[5], row[6] }); ds2item[5] = string.Concat(row[7]) == "1"; ds2item[6] = string.Concat(row[8]) == "1"; ds2item[7] = string.Concat(row[9]); ds2item[8] = string.Concat(row[10]); ds2.Add(ds2item); } var position = 0; foreach (var row in ds2) { string table_id = string.Concat(row[0]); string column = string.Concat(row[1]); string type = string.Concat(row[2]); //long max_length = long.Parse(string.Concat(row[3])); string sqlType = string.Concat(row[4]); var m_len = Regex.Match(sqlType, @"\w+\((\d+)"); int max_length = m_len.Success ? int.Parse(m_len.Groups[1].Value) : -1; bool is_nullable = string.Concat(row[5]) == "1"; bool is_identity = string.Concat(row[6]) == "1"; string comment = string.Concat(row[7]); string defaultValue = string.Concat(row[8]); if (max_length == 0) max_length = -1; if (database.Length == 1) { table_id = table_id.Substring(table_id.IndexOf('.') + 1); } loc3[table_id].Add(column, new DbColumnInfo { Name = column, MaxLength = max_length, IsIdentity = is_identity, IsNullable = is_nullable, IsPrimary = false, DbTypeText = type, DbTypeTextFull = sqlType, Table = loc2[table_id], Coment = comment, DefaultValue = defaultValue, Position = ++position }); loc3[table_id][column].DbType = this.GetDbType(loc3[table_id][column]); loc3[table_id][column].CsType = this.GetCsTypeInfo(loc3[table_id][column]); } sql = string.Format(@" select a.table_owner || '.' || a.table_name, c.column_name, c.index_name, case when a.uniqueness = 'UNIQUE' then 1 else 0 end, case when exists(select 1 from all_constraints where constraint_name = a.index_name and constraint_type = 'P') then 1 else 0 end, 0, case when c.descend = 'DESC' then 1 else 0 end, c.column_position from all_indexes a, all_ind_columns c where a.index_name = c.index_name and a.table_owner = c.table_owner and a.table_name = c.table_name and a.table_owner in ({1}) and {0} ", loc8, databaseIn); ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); if (ds == null) return loc1; var indexColumns = new Dictionary<string, Dictionary<string, DbIndexInfo>>(); var uniqueColumns = new Dictionary<string, Dictionary<string, DbIndexInfo>>(); foreach (var row in ds) { string table_id = string.Concat(row[0]); string column = string.Concat(row[1]).Trim('"'); string index_id = string.Concat(row[2]); bool is_unique = string.Concat(row[3]) == "1"; bool is_primary_key = string.Concat(row[4]) == "1"; bool is_clustered = string.Concat(row[5]) == "1"; bool is_desc = string.Concat(row[6]) == "1"; if (database.Length == 1) table_id = table_id.Substring(table_id.IndexOf('.') + 1); if (loc3.ContainsKey(table_id) == false || loc3[table_id].ContainsKey(column) == false) continue; var loc9 = loc3[table_id][column]; if (loc9.IsPrimary == false && is_primary_key) loc9.IsPrimary = is_primary_key; if (is_primary_key) continue; Dictionary<string, DbIndexInfo> loc10 = null; DbIndexInfo loc11 = null; if (!indexColumns.TryGetValue(table_id, out loc10)) indexColumns.Add(table_id, loc10 = new Dictionary<string, DbIndexInfo>()); if (!loc10.TryGetValue(index_id, out loc11)) loc10.Add(index_id, loc11 = new DbIndexInfo()); loc11.Columns.Add(new DbIndexColumnInfo { Column = loc9, IsDesc = is_desc }); if (is_unique && !is_primary_key) { if (!uniqueColumns.TryGetValue(table_id, out loc10)) uniqueColumns.Add(table_id, loc10 = new Dictionary<string, DbIndexInfo>()); if (!loc10.TryGetValue(index_id, out loc11)) loc10.Add(index_id, loc11 = new DbIndexInfo()); loc11.Columns.Add(new DbIndexColumnInfo { Column = loc9, IsDesc = is_desc }); } } foreach (string table_id in indexColumns.Keys) { foreach (var column in indexColumns[table_id]) loc2[table_id].IndexesDict.Add(column.Key, column.Value); } foreach (string table_id in uniqueColumns.Keys) { foreach (var column in uniqueColumns[table_id]) { column.Value.Columns.Sort((c1, c2) => c1.Column.Name.CompareTo(c2.Column.Name)); loc2[table_id].UniquesDict.Add(column.Key, column.Value); } } sql = string.Format(@" select a.owner || '.' || a.table_name, c.column_name, c.constraint_name, b.owner || '.' || b.table_name, 1, d.column_name -- a.owner 外键拥有者, -- a.table_name 外键表, -- c.column_name 外键列, -- b.owner 主键拥有者, -- b.table_name 主键表, -- d.column_name 主键列, -- c.constraint_name 外键名, -- d.constraint_name 主键名 from all_constraints a, all_constraints b, all_cons_columns c, --外键表 all_cons_columns d --主键表 where a.r_constraint_name = b.constraint_name and a.constraint_type = 'R' and b.constraint_type = 'P' and a.r_owner = b.owner and a.constraint_name = c.constraint_name and b.constraint_name = d.constraint_name and a.owner = c.owner and a.table_name = c.table_name and b.owner = d.owner and b.table_name = d.table_name and a.owner in ({1}) and {0} ", loc8, databaseIn); ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); if (ds == null) return loc1; var fkColumns = new Dictionary<string, Dictionary<string, DbForeignInfo>>(); foreach (var row in ds) { string table_id = string.Concat(row[0]); string column = string.Concat(row[1]); string fk_id = string.Concat(row[2]); string ref_table_id = string.Concat(row[3]); bool is_foreign_key = string.Concat(row[4]) == "1"; string referenced_column = string.Concat(row[5]); if (database.Length == 1) { table_id = table_id.Substring(table_id.IndexOf('.') + 1); ref_table_id = ref_table_id.Substring(ref_table_id.IndexOf('.') + 1); } if (loc3.ContainsKey(table_id) == false || loc3[table_id].ContainsKey(column) == false) continue; var loc9 = loc3[table_id][column]; if (loc2.ContainsKey(ref_table_id) == false) continue; var loc10 = loc2[ref_table_id]; var loc11 = loc3[ref_table_id][referenced_column]; Dictionary<string, DbForeignInfo> loc12 = null; DbForeignInfo loc13 = null; if (!fkColumns.TryGetValue(table_id, out loc12)) fkColumns.Add(table_id, loc12 = new Dictionary<string, DbForeignInfo>()); if (!loc12.TryGetValue(fk_id, out loc13)) loc12.Add(fk_id, loc13 = new DbForeignInfo { Table = loc2[table_id], ReferencedTable = loc10 }); loc13.Columns.Add(loc9); loc13.ReferencedColumns.Add(loc11); } foreach (var table_id in fkColumns.Keys) foreach (var fk in fkColumns[table_id]) loc2[table_id].ForeignsDict.Add(fk.Key, fk.Value); foreach (var table_id in loc3.Keys) { foreach (var loc5 in loc3[table_id].Values) { loc2[table_id].Columns.Add(loc5); if (loc5.IsIdentity) loc2[table_id].Identitys.Add(loc5); if (loc5.IsPrimary) loc2[table_id].Primarys.Add(loc5); } } foreach (var loc4 in loc2.Values) { //if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0) //{ // foreach (var loc5 in loc4.UniquesDict.First().Value.Columns) // { // loc5.Column.IsPrimary = true; // loc4.Primarys.Add(loc5.Column); // } //} loc4.Primarys.Sort((c1, c2) => c1.Name.CompareTo(c2.Name)); loc4.Columns.Sort((c1, c2) => { int compare = c2.IsPrimary.CompareTo(c1.IsPrimary); if (compare == 0) { bool b1 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c1.Name).Any()).Any(); bool b2 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c2.Name).Any()).Any(); compare = b2.CompareTo(b1); } if (compare == 0) compare = c1.Name.CompareTo(c2.Name); return compare; }); loc1.Add(loc4); } loc1.Sort((t1, t2) => { var ret = t1.Schema.CompareTo(t2.Schema); if (ret == 0) ret = t1.Name.CompareTo(t2.Name); return ret; }); loc2.Clear(); loc3.Clear(); return loc1; } public List<DbEnumInfo> GetEnumsByDatabase(params string[] database) { return new List<DbEnumInfo>(); } } }
47.919786
215
0.527136
[ "MIT" ]
1051324354/FreeSql
Providers/FreeSql.Provider.Dameng/DamengDbFirst.cs
26,967
C#
namespace TDAmeritradeApi.Client.Models.Streamer { public enum ListOptionType { BOTH, CALLS, PUTS } }
13.9
49
0.582734
[ "Apache-2.0" ]
bmello4688/TDAmeritradeApi
TDAmeritrade.Client/Models/Streamer/ListOptionType.cs
141
C#
#region Project Description [About this] // ================================================================================= // The whole Project is Licensed under the MIT License // ================================================================================= // ================================================================================= // Wiesend's Dynamic Link Library is a collection of reusable code that // I've written, or found throughout my programming career. // // I tried my very best to mention all of the original copyright holders. // I hope that all code which I've copied from others is mentioned and all // their copyrights are given. The copied code (or code snippets) could // already be modified by me or others. // ================================================================================= #endregion of Project Description #region Original Source Code [Links to all original source code] // ================================================================================= // Original Source Code [Links to all original source code] // ================================================================================= // https://github.com/JaCraig/Craig-s-Utility-Library // ================================================================================= // I didn't wrote this source totally on my own, this class could be nearly a // clone of the project of James Craig, I did highly get inspired by him, so // this piece of code isn't totally mine, shame on me, I'm not the best! // ================================================================================= #endregion of where is the original source code #region Licenses [MIT Licenses] #region MIT License [James Craig] // ================================================================================= // Copyright(c) 2014 <a href="http://www.gutgames.com">James Craig</a> // // 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 of MIT License [James Craig] #region MIT License [Dominik Wiesend] // ================================================================================= // Copyright(c) 2016 Dominik Wiesend. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice 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 of MIT License [Dominik Wiesend] #endregion of Licenses [MIT Licenses] using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; namespace Wiesend.DataTypes { /// <summary> /// Used to count the number of times something is added to the list /// </summary> /// <typeparam name="T">Type of data within the bag</typeparam> public class Bag<T> : ICollection<T> { /// <summary> /// Constructor /// </summary> public Bag() { Items = new ConcurrentDictionary<T, int>(); } /// <summary> /// Number of items in the bag /// </summary> public virtual int Count { get { return Items.Count; } } /// <summary> /// Is this read only? /// </summary> public virtual bool IsReadOnly { get { return false; } } /// <summary> /// Actual internal container /// </summary> protected ConcurrentDictionary<T, int> Items { get; private set; } /// <summary> /// Gets a specified item /// </summary> /// <param name="index">Item to get</param> /// <returns>The number of this item in the bag</returns> public virtual int this[T index] { get { return Items.GetValue(index); } set { Items.SetValue(index, value); } } /// <summary> /// Adds an item to the bag /// </summary> /// <param name="item">Item to add</param> public virtual void Add(T item) { Items.SetValue(item, Items.GetValue(item, 0) + 1); } /// <summary> /// Clears the bag /// </summary> public virtual void Clear() { Items.Clear(); } /// <summary> /// Determines if the bag contains an item /// </summary> /// <param name="item">Item to check</param> /// <returns>True if it does, false otherwise</returns> public virtual bool Contains(T item) { return Items.ContainsKey(item); } /// <summary> /// Copies the bag to an array /// </summary> /// <param name="array">Array to copy to</param> /// <param name="arrayIndex">Index to start at</param> public virtual void CopyTo(T[] array, int arrayIndex) { Array.Copy(this.Items.ToList().ToArray(x => x.Key), 0, array, arrayIndex, this.Count); } /// <summary> /// Gets the enumerator /// </summary> /// <returns>The enumerator</returns> public virtual IEnumerator<T> GetEnumerator() { foreach (T Key in this.Items.Keys) yield return Key; } /// <summary> /// Removes an item from the bag /// </summary> /// <param name="item">Item to remove</param> /// <returns>True if it is removed, false otherwise</returns> public virtual bool Remove(T item) { int Value = 0; return Items.TryRemove(item, out Value); } /// <summary> /// Gets the enumerator /// </summary> /// <returns>The enumerator</returns> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { foreach (T Key in this.Items.Keys) yield return Key; } } }
41.576531
98
0.544975
[ "MIT" ]
DominikWiesend/wiesend
projects/Wiesend.DataTypes/DataTypes/Bag.cs
8,151
C#
using System.Collections.Generic; using EmlakApp.Entities; namespace EmlakApp.Business.Abstract { public interface IAdService { List<Ev> GetAds(); Ev GetAdById(int evId); Ev CreateAd(Ev ev); Ev UpdateAd(Ev ev); void DeleteAd(int evId); } }
19.6
36
0.629252
[ "MIT" ]
RamazanAltuntepe/Basit-Katmanli--Asp-Web-Api-Uygulamasi
EmlakApp/EmlakApp.Business/Abstract/IAdService.cs
296
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using Mirror; using UnityEngine.UI; using UnityEngine.EventSystems; /// <summary> /// /// </summary> public class UIUtils { // instantiate/remove enough prefabs to match amount public static void BalancePrefabs(GameObject prefab, int amount, Transform parent) { // instantiate until amount for (int i = parent.childCount; i < amount; ++i) { GameObject go = GameObject.Instantiate(prefab); go.transform.SetParent(parent, false); } // delete everything that's too much // (backwards loop because Destroy changes childCount) for (int i = parent.childCount - 1; i >= amount; --i) GameObject.Destroy(parent.GetChild(i).gameObject); } // find out if any input is currently active by using Selectable.all // (FindObjectsOfType<InputField>() is far too slow for huge scenes) public static bool AnyInputActive() { // avoid Linq.Any because it is HEAVY(!) on GC and performance foreach (Selectable sel in Selectable.allSelectables) if (sel is InputField inputField && inputField.isFocused) return true; return false; } // deselect any UI element carefully // (it throws an error when doing it while clicking somewhere, so we have to // double check) public static void DeselectCarefully() { if (!Input.GetMouseButton(0) && !Input.GetMouseButton(1) && !Input.GetMouseButton(2)) EventSystem.current.SetSelectedGameObject(null); } }
32.980769
87
0.623324
[ "MIT" ]
zfy1045056938/THDN_Script
THDN/CORE/Scripts/UI/UIUtils.cs
1,717
C#
namespace E_Shop.Service.ProductFilters { using System.Collections.Generic; public static class ProductFilterList { public static List<IProductFilter> BaseFiltersForAdmin() { var list = new List<IProductFilter> { new ProductDeletedFilter(false) }; return list; } public static List<IProductFilter> RequiredFiltersForCustomer() { var list = new List<IProductFilter> { new ProductDeletedFilter(false) }; return list; } } }
26.8
84
0.626866
[ "MIT" ]
nixelt/E-Shop
E-Shop/E-Shop.Service/ProductFilters/ProductFilterList.cs
538
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 comprehendmedical-2018-10-30.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.ComprehendMedical.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.ComprehendMedical.Model.Internal.MarshallTransformations { /// <summary> /// InferRxNorm Request Marshaller /// </summary> public class InferRxNormRequestMarshaller : IMarshaller<IRequest, InferRxNormRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((InferRxNormRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(InferRxNormRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.ComprehendMedical"); string target = "ComprehendMedical_20181030.InferRxNorm"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2018-10-30"; request.HttpMethod = "POST"; request.ResourcePath = "/"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetText()) { context.Writer.WritePropertyName("Text"); context.Writer.Write(publicRequest.Text); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static InferRxNormRequestMarshaller _instance = new InferRxNormRequestMarshaller(); internal static InferRxNormRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static InferRxNormRequestMarshaller Instance { get { return _instance; } } } }
35.971429
138
0.611067
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/ComprehendMedical/Generated/Model/Internal/MarshallTransformations/InferRxNormRequestMarshaller.cs
3,777
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright company="Aspose" file="Names.cs"> // Copyright (c) 2016 Aspose.Cells for Cloud // </copyright> // <summary> // 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. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Aspose.Cells.Cloud.SDK.Model { using System; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Converters; /// <summary> /// /// </summary> [DataContract] public class Names { /// <summary> /// Gets or sets Link /// </summary> [DataMember(Name="link", EmitDefaultValue=false)] public Link Link { get; set; } /// <summary> /// Gets or sets Count /// </summary> [DataMember(Name="Count", EmitDefaultValue=false)] public int? Count { get; set; } /// <summary> /// Gets or sets NameList /// </summary> [DataMember(Name="NameList", EmitDefaultValue=false)] public List<LinkElement> NameList { get; set; } /// <summary> /// Get 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 Names {\n"); sb.Append(" Link: ").Append(this.Link).Append("\n"); sb.Append(" Count: ").Append(this.Count).Append("\n"); sb.Append(" NameList: ").Append(this.NameList).Append("\n"); sb.Append("}\n"); return sb.ToString(); } } }
38.618421
119
0.588075
[ "MIT" ]
aspose-cells-cloud/aspose-cells-cloud-dotnet
Aspose.Cells.Cloud.SDK/Model/Names.cs
2,935
C#
using Books.Domain.AggregatedModel.AggragatedBooks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; using System.Text; namespace Books.Infra.EntityConfigurations { class BookEntityTypeConfiguration : IEntityTypeConfiguration<Book> { public void Configure(EntityTypeBuilder<Book> builder) { builder.ToTable("books", BookContext.DEFAULT_SCHEMA); builder.HasKey(b => b.Id); builder.Ignore(b => b.DomainEvents); builder.Property(b => b.Name); builder.Property<int>("BookStatusId").IsRequired(); } } }
31.227273
70
0.695779
[ "MIT" ]
ormarom/examples
books/Services/BooksSimapleWithDomainEventsAndState/Books.Infra/EntityConfigurations/BookEntityTypeConfiguration.cs
689
C#
using System; using System.Collections.Generic; using GitTools.Testing; using GitVersion; using GitVersion.Configuration; using GitVersion.Extensions; using GitVersion.VersionCalculation; using GitVersionCore.Tests.Helpers; using GitVersionCore.Tests.Mocks; using LibGit2Sharp; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; using Shouldly; namespace GitVersionCore.Tests.VersionCalculation { public class NextVersionCalculatorTests : TestBase { [Test] public void ShouldIncrementVersionBasedOnConfig() { var semanticVersionBuildMetaData = new SemanticVersionBuildMetaData("ef7d0d7e1e700f1c7c9fa01ea6791bb778a5c37c", 1, "master", "b1a34edbd80e141f7cc046c074f109be7d022074", "b1a34e", DateTimeOffset.Now); var sp = ConfigureServices(services => { services.AddSingleton<IBaseVersionCalculator>(new TestBaseVersionCalculator(true, new SemanticVersion(1), new MockCommit())); services.AddSingleton<IMetaDataCalculator>(new TestMetaDataCalculator(semanticVersionBuildMetaData)); }); var nextVersionCalculator = sp.GetService<INextVersionCalculator>() as NextVersionCalculator; nextVersionCalculator.ShouldNotBeNull(); var context = new GitVersionContextBuilder().WithConfig(new Config()).Build(); var version = nextVersionCalculator.FindVersionInternal(context); version.ToString().ShouldBe("1.0.1"); } [Test] public void DoesNotIncrementWhenBaseVersionSaysNotTo() { var semanticVersionBuildMetaData = new SemanticVersionBuildMetaData("ef7d0d7e1e700f1c7c9fa01ea6791bb778a5c37c", 1, "master", "b1a34edbd80e141f7cc046c074f109be7d022074", "b1a34e", DateTimeOffset.Now); var sp = ConfigureServices(services => { services.AddSingleton<IBaseVersionCalculator>(new TestBaseVersionCalculator(false, new SemanticVersion(1), new MockCommit())); services.AddSingleton<IMetaDataCalculator>(new TestMetaDataCalculator(semanticVersionBuildMetaData)); }); var nextVersionCalculator = sp.GetService<INextVersionCalculator>() as NextVersionCalculator; nextVersionCalculator.ShouldNotBeNull(); var context = new GitVersionContextBuilder().WithConfig(new Config()).Build(); var version = nextVersionCalculator.FindVersionInternal(context); version.ToString().ShouldBe("1.0.0"); } [Test] public void AppliesBranchPreReleaseTag() { var semanticVersionBuildMetaData = new SemanticVersionBuildMetaData("ef7d0d7e1e700f1c7c9fa01ea6791bb778a5c37c", 2, "develop", "b1a34edbd80e141f7cc046c074f109be7d022074", "b1a34e", DateTimeOffset.Now); var sp = ConfigureServices(services => { services.AddSingleton<IBaseVersionCalculator>(new TestBaseVersionCalculator(false, new SemanticVersion(1), new MockCommit())); services.AddSingleton<IMetaDataCalculator>(new TestMetaDataCalculator(semanticVersionBuildMetaData)); }); var nextVersionCalculator = sp.GetService<INextVersionCalculator>() as NextVersionCalculator; nextVersionCalculator.ShouldNotBeNull(); var context = new GitVersionContextBuilder() .WithDevelopBranch() .Build(); var version = nextVersionCalculator.FindVersionInternal(context); version.ToString("f").ShouldBe("1.0.0-alpha.1+2"); } [Test] public void PreReleaseTagCanUseBranchName() { var config = new Config { NextVersion = "1.0.0", Branches = new Dictionary<string, BranchConfig> { { "custom", new BranchConfig { Regex = "custom/", Tag = "useBranchName", SourceBranches = new List<string>() } } } }; using var fixture = new EmptyRepositoryFixture(); fixture.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeACommit(); fixture.BranchTo("custom/foo"); fixture.MakeACommit(); fixture.AssertFullSemver(config, "1.0.0-foo.1+2"); } [Test] public void PreReleaseTagCanUseBranchNameVariable() { var config = new Config { NextVersion = "1.0.0", Branches = new Dictionary<string, BranchConfig> { { "custom", new BranchConfig { Regex = "custom/", Tag = "alpha.{BranchName}", SourceBranches = new List<string>() } } } }; using var fixture = new EmptyRepositoryFixture(); fixture.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeACommit(); fixture.BranchTo("custom/foo"); fixture.MakeACommit(); fixture.AssertFullSemver(config, "1.0.0-alpha.foo.1+2"); } [Test] public void PreReleaseNumberShouldBeScopeToPreReleaseLabelInContinuousDelivery() { var config = new Config { VersioningMode = VersioningMode.ContinuousDelivery, Branches = new Dictionary<string, BranchConfig> { { "master", new BranchConfig { Tag = "beta" } }, } }; using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeACommit(); fixture.Repository.CreateBranch("feature/test"); Commands.Checkout(fixture.Repository, "feature/test"); fixture.Repository.MakeATaggedCommit("0.1.0-test.1"); fixture.Repository.MakeACommit(); fixture.AssertFullSemver(config, "0.1.0-test.2+2"); Commands.Checkout(fixture.Repository, "master"); fixture.Repository.Merge(fixture.Repository.FindBranch("feature/test"), Generate.SignatureNow()); fixture.AssertFullSemver(config, "0.1.0-beta.1+2"); } } }
38.114286
212
0.586807
[ "MIT" ]
teyc/GitVersion
src/GitVersionCore.Tests/VersionCalculation/NextVersionCalculatorTests.cs
6,670
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Schema; using Microsoft.Extensions.DependencyInjection; namespace HospitalitySkill.Bots { public class DialogBot<T> : IBot where T : Dialog { private readonly Dialog _dialog; private readonly BotState _conversationState; private readonly BotState _userState; private readonly IBotTelemetryClient _telemetryClient; public DialogBot(IServiceProvider serviceProvider, T dialog) { _dialog = dialog; _conversationState = serviceProvider.GetService<ConversationState>(); _userState = serviceProvider.GetService<UserState>(); _telemetryClient = serviceProvider.GetService<IBotTelemetryClient>(); } public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken)) { // Client notifying this bot took to long to respond (timed out) if (turnContext.Activity.Code == EndOfConversationCodes.BotTimedOut) { _telemetryClient.TrackTrace($"Timeout in {turnContext.Activity.ChannelId} channel: Bot took too long to respond.", Severity.Information, null); return; } await _dialog.RunAsync(turnContext, _conversationState.CreateProperty<DialogState>(nameof(DialogState)), cancellationToken); // Save any state changes that might have occured during the turn. await _conversationState.SaveChangesAsync(turnContext, false, cancellationToken); await _userState.SaveChangesAsync(turnContext, false, cancellationToken); } } }
40.255319
159
0.70296
[ "MIT" ]
Damarus999/botframework-solutions
skills/src/csharp/experimental/hospitalityskill/Bots/DialogBot.cs
1,894
C#
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Esprima; using Esprima.Ast; using Jint.Native; using Jint.Native.Argument; using Jint.Native.Array; using Jint.Native.Boolean; using Jint.Native.Date; using Jint.Native.Error; using Jint.Native.Function; using Jint.Native.Global; using Jint.Native.Iterator; using Jint.Native.Json; using Jint.Native.Map; using Jint.Native.Math; using Jint.Native.Number; using Jint.Native.Object; using Jint.Native.Proxy; using Jint.Native.Reflect; using Jint.Native.RegExp; using Jint.Native.Set; using Jint.Native.String; using Jint.Native.Symbol; using Jint.Pooling; using Jint.Runtime; using Jint.Runtime.CallStack; using Jint.Runtime.Debugger; using Jint.Runtime.Descriptors; using Jint.Runtime.Descriptors.Specialized; using Jint.Runtime.Environments; using Jint.Runtime.Interop; using Jint.Runtime.Interpreter; using Jint.Runtime.References; using ExecutionContext = Jint.Runtime.Environments.ExecutionContext; namespace Jint { public class Engine { private static readonly ParserOptions DefaultParserOptions = new ParserOptions { AdaptRegexp = true, Tolerant = true, Loc = true }; private static readonly JsString _errorFunctionName = new JsString("Error"); private static readonly JsString _evalErrorFunctionName = new JsString("EvalError"); private static readonly JsString _rangeErrorFunctionName = new JsString("RangeError"); private static readonly JsString _referenceErrorFunctionName = new JsString("ReferenceError"); private static readonly JsString _syntaxErrorFunctionName = new JsString("SyntaxError"); private static readonly JsString _typeErrorFunctionName = new JsString("TypeError"); private static readonly JsString _uriErrorFunctionName = new JsString("URIError"); private readonly ExecutionContextStack _executionContexts; private JsValue _completionValue = JsValue.Undefined; private int _statementsCount; private long _initialMemoryUsage; private long _timeoutTicks; internal INode _lastSyntaxNode; // lazy properties private ErrorConstructor _error; private ErrorConstructor _evalError; private ErrorConstructor _rangeError; private ErrorConstructor _referenceError; private ErrorConstructor _syntaxError; private ErrorConstructor _typeError; private ErrorConstructor _uriError; private DebugHandler _debugHandler; private List<BreakPoint> _breakPoints; // cached access private readonly bool _isDebugMode; internal readonly bool _isStrict; private readonly int _maxStatements; private readonly long _memoryLimit; internal readonly bool _runBeforeStatementChecks; internal readonly IReferenceResolver _referenceResolver; internal readonly ReferencePool _referencePool; internal readonly ArgumentsInstancePool _argumentsInstancePool; internal readonly JsValueArrayPool _jsValueArrayPool; public ITypeConverter ClrTypeConverter { get; set; } // cache of types used when resolving CLR type names internal readonly Dictionary<string, Type> TypeCache = new Dictionary<string, Type>(); internal static Dictionary<Type, Func<Engine, object, JsValue>> TypeMappers = new Dictionary<Type, Func<Engine, object, JsValue>> { { typeof(bool), (engine, v) => (bool) v ? JsBoolean.True : JsBoolean.False }, { typeof(byte), (engine, v) => JsNumber.Create((byte)v) }, { typeof(char), (engine, v) => JsString.Create((char)v) }, { typeof(DateTime), (engine, v) => engine.Date.Construct((DateTime)v) }, { typeof(DateTimeOffset), (engine, v) => engine.Date.Construct((DateTimeOffset)v) }, { typeof(decimal), (engine, v) => (JsValue) (double)(decimal)v }, { typeof(double), (engine, v) => (JsValue)(double)v }, { typeof(Int16), (engine, v) => JsNumber.Create((Int16)v) }, { typeof(Int32), (engine, v) => JsNumber.Create((Int32)v) }, { typeof(Int64), (engine, v) => (JsValue)(Int64)v }, { typeof(SByte), (engine, v) => JsNumber.Create((SByte)v) }, { typeof(Single), (engine, v) => (JsValue)(Single)v }, { typeof(string), (engine, v) => JsString.Create((string) v) }, { typeof(UInt16), (engine, v) => JsNumber.Create((UInt16)v) }, { typeof(UInt32), (engine, v) => JsNumber.Create((UInt32)v) }, { typeof(UInt64), (engine, v) => JsNumber.Create((UInt64)v) }, { typeof(System.Text.RegularExpressions.Regex), (engine, v) => engine.RegExp.Construct((System.Text.RegularExpressions.Regex)v, "", engine) } }; // shared frozen version internal readonly PropertyDescriptor _getSetThrower; internal readonly struct ClrPropertyDescriptorFactoriesKey : IEquatable<ClrPropertyDescriptorFactoriesKey> { public ClrPropertyDescriptorFactoriesKey(Type type, in Key propertyName) { Type = type; PropertyName = propertyName; } private readonly Type Type; private readonly Key PropertyName; public bool Equals(ClrPropertyDescriptorFactoriesKey other) { return Type == other.Type && PropertyName == other.PropertyName; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } return obj is ClrPropertyDescriptorFactoriesKey other && Equals(other); } public override int GetHashCode() { unchecked { return (Type.GetHashCode() * 397) ^ PropertyName.GetHashCode(); } } } internal readonly Dictionary<ClrPropertyDescriptorFactoriesKey, Func<Engine, object, PropertyDescriptor>> ClrPropertyDescriptorFactories = new Dictionary<ClrPropertyDescriptorFactoriesKey, Func<Engine, object, PropertyDescriptor>>(); internal readonly JintCallStack CallStack = new JintCallStack(); static Engine() { var methodInfo = typeof(GC).GetMethod("GetAllocatedBytesForCurrentThread"); if (methodInfo != null) { GetAllocatedBytesForCurrentThread = (Func<long>)Delegate.CreateDelegate(typeof(Func<long>), null, methodInfo); } } public Engine() : this(null) { } public Engine(Action<Options> options) { _executionContexts = new ExecutionContextStack(2); Global = GlobalObject.CreateGlobalObject(this); Object = ObjectConstructor.CreateObjectConstructor(this); Function = FunctionConstructor.CreateFunctionConstructor(this); _getSetThrower = new GetSetPropertyDescriptor.ThrowerPropertyDescriptor(Function.ThrowTypeError); Symbol = SymbolConstructor.CreateSymbolConstructor(this); Array = ArrayConstructor.CreateArrayConstructor(this); Map = MapConstructor.CreateMapConstructor(this); Set = SetConstructor.CreateSetConstructor(this); Iterator = IteratorConstructor.CreateIteratorConstructor(this); String = StringConstructor.CreateStringConstructor(this); RegExp = RegExpConstructor.CreateRegExpConstructor(this); Number = NumberConstructor.CreateNumberConstructor(this); Boolean = BooleanConstructor.CreateBooleanConstructor(this); Date = DateConstructor.CreateDateConstructor(this); Math = MathInstance.CreateMathObject(this); Json = JsonInstance.CreateJsonObject(this); Proxy = ProxyConstructor.CreateProxyConstructor(this); Reflect = ReflectInstance.CreateReflectObject(this); GlobalSymbolRegistry = new GlobalSymbolRegistry(); // Because the properties might need some of the built-in object // their configuration is delayed to a later step // trigger initialization Global.GetProperty(JsString.Empty); // this is implementation dependent, and only to pass some unit tests Global._prototype = Object.PrototypeObject; Object._prototype = Function.PrototypeObject; // create the global environment http://www.ecma-international.org/ecma-262/5.1/#sec-10.2.3 GlobalEnvironment = LexicalEnvironment.NewGlobalEnvironment(this, Global); // create the global execution context http://www.ecma-international.org/ecma-262/5.1/#sec-10.4.1.1 EnterExecutionContext(GlobalEnvironment, GlobalEnvironment, Global); Options = new Options(); options?.Invoke(Options); // gather some options as fields for faster checks _isDebugMode = Options.IsDebugMode; _isStrict = Options.IsStrict; _maxStatements = Options._MaxStatements; _referenceResolver = Options.ReferenceResolver; _memoryLimit = Options._MemoryLimit; _runBeforeStatementChecks = (_maxStatements > 0 &&_maxStatements < int.MaxValue) || Options._TimeoutInterval.Ticks > 0 || _memoryLimit > 0 || _isDebugMode; _referencePool = new ReferencePool(); _argumentsInstancePool = new ArgumentsInstancePool(this); _jsValueArrayPool = new JsValueArrayPool(); Eval = new EvalFunctionInstance(this, System.Array.Empty<string>(), LexicalEnvironment.NewDeclarativeEnvironment(this, ExecutionContext.LexicalEnvironment), StrictModeScope.IsStrictModeCode); Global.SetProperty(CommonProperties.Eval, new PropertyDescriptor(Eval, PropertyFlag.Configurable | PropertyFlag.Writable)); if (Options._IsClrAllowed) { Global.SetProperty("System", new PropertyDescriptor(new NamespaceReference(this, "System"), PropertyFlag.AllForbidden)); Global.SetProperty("importNamespace", new PropertyDescriptor(new ClrFunctionInstance( this, "importNamespace", (thisObj, arguments) => new NamespaceReference(this, TypeConverter.ToString(arguments.At(0)))), PropertyFlag.AllForbidden)); } ClrTypeConverter = new DefaultTypeConverter(this); } internal LexicalEnvironment GlobalEnvironment { get; } public GlobalObject Global { get; } public ObjectConstructor Object { get; } public FunctionConstructor Function { get; } public ArrayConstructor Array { get; } public MapConstructor Map { get; } public SetConstructor Set { get; } public IteratorConstructor Iterator { get; } public StringConstructor String { get; } public RegExpConstructor RegExp { get; } public BooleanConstructor Boolean { get; } public NumberConstructor Number { get; } public DateConstructor Date { get; } public MathInstance Math { get; } public JsonInstance Json { get; } public ProxyConstructor Proxy { get; } public ReflectInstance Reflect { get; } public SymbolConstructor Symbol { get; } public EvalFunctionInstance Eval { get; } public ErrorConstructor Error => _error ??= ErrorConstructor.CreateErrorConstructor(this, _errorFunctionName); public ErrorConstructor EvalError => _evalError ??= ErrorConstructor.CreateErrorConstructor(this, _evalErrorFunctionName); public ErrorConstructor SyntaxError => _syntaxError ??= ErrorConstructor.CreateErrorConstructor(this, _syntaxErrorFunctionName); public ErrorConstructor TypeError => _typeError ??= ErrorConstructor.CreateErrorConstructor(this, _typeErrorFunctionName); public ErrorConstructor RangeError => _rangeError ??= ErrorConstructor.CreateErrorConstructor(this, _rangeErrorFunctionName); public ErrorConstructor ReferenceError => _referenceError ??= ErrorConstructor.CreateErrorConstructor(this, _referenceErrorFunctionName); public ErrorConstructor UriError => _uriError ??= ErrorConstructor.CreateErrorConstructor(this, _uriErrorFunctionName); public ref readonly ExecutionContext ExecutionContext { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => ref _executionContexts.Peek(); } public GlobalSymbolRegistry GlobalSymbolRegistry { get; } internal long CurrentMemoryUsage { get; private set; } internal Options Options { [MethodImpl(MethodImplOptions.AggressiveInlining)] get; } #region Debugger public delegate StepMode DebugStepDelegate(object sender, DebugInformation e); public delegate StepMode BreakDelegate(object sender, DebugInformation e); public event DebugStepDelegate Step; public event BreakDelegate Break; internal DebugHandler DebugHandler => _debugHandler ?? (_debugHandler = new DebugHandler(this)); public List<BreakPoint> BreakPoints => _breakPoints ?? (_breakPoints = new List<BreakPoint>()); internal StepMode? InvokeStepEvent(DebugInformation info) { return Step?.Invoke(this, info); } internal StepMode? InvokeBreakEvent(DebugInformation info) { return Break?.Invoke(this, info); } #endregion private static readonly Func<long> GetAllocatedBytesForCurrentThread; public void EnterExecutionContext( LexicalEnvironment lexicalEnvironment, LexicalEnvironment variableEnvironment, JsValue thisBinding) { var context = new ExecutionContext( lexicalEnvironment, variableEnvironment, thisBinding); _executionContexts.Push(context); } public Engine SetValue(JsValue name, Delegate value) { Global.FastAddProperty(name, new DelegateWrapper(this, value), true, false, true); return this; } public Engine SetValue(JsValue name, string value) { return SetValue(name, new JsString(value)); } public Engine SetValue(JsValue name, double value) { return SetValue(name, JsNumber.Create(value)); } public Engine SetValue(JsValue name, int value) { return SetValue(name, JsNumber.Create(value)); } public Engine SetValue(JsValue name, bool value) { return SetValue(name, value ? JsBoolean.True : JsBoolean.False); } public Engine SetValue(JsValue name, JsValue value) { Global.Set(name, value, Global); return this; } public Engine SetValue(JsValue name, object obj) { return SetValue(name, JsValue.FromObject(this, obj)); } public void LeaveExecutionContext() { _executionContexts.Pop(); } /// <summary> /// Initializes the statements count /// </summary> public void ResetStatementsCount() { _statementsCount = 0; } public void ResetMemoryUsage() { if (GetAllocatedBytesForCurrentThread != null) { _initialMemoryUsage = GetAllocatedBytesForCurrentThread(); } } public void ResetTimeoutTicks() { var timeoutIntervalTicks = Options._TimeoutInterval.Ticks; _timeoutTicks = timeoutIntervalTicks > 0 ? DateTime.UtcNow.Ticks + timeoutIntervalTicks : 0; } /// <summary> /// Initializes list of references of called functions /// </summary> public void ResetCallStack() { CallStack.Clear(); } public Engine Execute(string source) { return Execute(source, DefaultParserOptions); } public Engine Execute(string source, ParserOptions parserOptions) { var parser = new JavaScriptParser(source, parserOptions); return Execute(parser.ParseScript()); } public Engine Execute(Script program) { ResetStatementsCount(); if (_memoryLimit > 0) { ResetMemoryUsage(); } ResetTimeoutTicks(); ResetLastStatement(); ResetCallStack(); using (new StrictModeScope(_isStrict || program.Strict)) { DeclarationBindingInstantiation( DeclarationBindingType.GlobalCode, program.HoistingScope, functionInstance: null, arguments: null); var list = new JintStatementList(this, null, program.Body); var result = list.Execute(); if (result.Type == CompletionType.Throw) { var ex = new JavaScriptException(result.GetValueOrDefault()).SetCallstack(this, result.Location); throw ex; } _completionValue = result.GetValueOrDefault(); } return this; } private void ResetLastStatement() { _lastSyntaxNode = null; } /// <summary> /// Gets the last evaluated statement completion value /// </summary> public JsValue GetCompletionValue() { return _completionValue; } internal void RunBeforeExecuteStatementChecks(Statement statement) { if (_maxStatements > 0 && _statementsCount++ > _maxStatements) { ExceptionHelper.ThrowStatementsCountOverflowException(); } if (_timeoutTicks > 0 && _timeoutTicks < DateTime.UtcNow.Ticks) { ExceptionHelper.ThrowTimeoutException(); } if (_memoryLimit > 0) { if (GetAllocatedBytesForCurrentThread != null) { CurrentMemoryUsage = GetAllocatedBytesForCurrentThread() - _initialMemoryUsage; if (CurrentMemoryUsage > _memoryLimit) { ExceptionHelper.ThrowMemoryLimitExceededException($"Script has allocated {CurrentMemoryUsage} but is limited to {_memoryLimit}"); } } else { ExceptionHelper.ThrowPlatformNotSupportedException("The current platform doesn't support MemoryLimit."); } } if (_isDebugMode) { DebugHandler.OnStep(statement); } } /// <summary> /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.7.1 /// </summary> public JsValue GetValue(object value) { return GetValue(value, false); } internal JsValue GetValue(object value, bool returnReferenceToPool) { if (value is JsValue jsValue) { return jsValue; } if (!(value is Reference reference)) { return ((Completion) value).Value; } return GetValue(reference, returnReferenceToPool); } internal JsValue GetValue(Reference reference, bool returnReferenceToPool) { var baseValue = reference.GetBase(); if (baseValue._type == InternalTypes.Undefined) { if (_referenceResolver != null && _referenceResolver.TryUnresolvableReference(this, reference, out JsValue val)) { return val; } ExceptionHelper.ThrowReferenceError(this, reference); } if (_referenceResolver != null && (baseValue._type & InternalTypes.ObjectEnvironmentRecord) == 0 && _referenceResolver.TryPropertyReference(this, reference, ref baseValue)) { return baseValue; } if (reference.IsPropertyReference()) { var property = reference.GetReferencedName(); if (returnReferenceToPool) { _referencePool.Return(reference); } if (baseValue.IsObject()) { var o = TypeConverter.ToObject(this, baseValue); var v = o.Get(property); return v; } else { // check if we are accessing a string, boxing operation can be costly to do index access // we have good chance to have fast path with integer or string indexer ObjectInstance o = null; if ((property._type & (InternalTypes.String | InternalTypes.Integer)) != 0 && baseValue is JsString s && TryHandleStringValue(property, s, ref o, out var jsValue)) { return jsValue; } if (o is null) { o = TypeConverter.ToObject(this, baseValue); } var desc = o.GetProperty(property); if (desc == PropertyDescriptor.Undefined) { return JsValue.Undefined; } if (desc.IsDataDescriptor()) { return desc.Value; } var getter = desc.Get; if (getter.IsUndefined()) { return Undefined.Instance; } var callable = (ICallable) getter.AsObject(); return callable.Call(baseValue, Arguments.Empty); } } if (!(baseValue is EnvironmentRecord record)) { return ExceptionHelper.ThrowArgumentException<JsValue>(); } var bindingValue = record.GetBindingValue(reference.GetReferencedName().ToString(), reference.IsStrictReference()); if (returnReferenceToPool) { _referencePool.Return(reference); } return bindingValue; } private bool TryHandleStringValue(JsValue property, JsString s, ref ObjectInstance o, out JsValue jsValue) { if (property == CommonProperties.Length) { jsValue = JsNumber.Create((uint) s.Length); return true; } if (property is JsNumber number && number.IsInteger()) { var index = number.AsInteger(); var str = s._value; if (index < 0 || index >= str.Length) { jsValue = JsValue.Undefined; return true; } jsValue = JsString.Create(str[index]); return true; } if (property is JsString propertyString && propertyString._value.Length > 0 && char.IsLower(propertyString._value[0])) { // trying to find property that's always in prototype o = String.PrototypeObject; } jsValue = JsValue.Undefined; return false; } /// <summary> /// http://www.ecma-international.org/ecma-262/#sec-putvalue /// </summary> internal void PutValue(Reference reference, JsValue value) { var property = reference.GetReferencedName(); var baseValue = reference.GetBase(); if (reference.IsUnresolvableReference()) { if (reference.IsStrictReference()) { ExceptionHelper.ThrowReferenceError(this, reference); } Global.Set(property, value); } else if (reference.IsPropertyReference()) { if (reference.HasPrimitiveBase()) { baseValue = TypeConverter.ToObject(this, baseValue); } var thisValue = GetThisValue(reference); var succeeded = baseValue.Set(property, value, thisValue); if (!succeeded && reference.IsStrictReference()) { ExceptionHelper.ThrowTypeError(this); } } else { ((EnvironmentRecord) baseValue).SetMutableBinding(property.ToString(), value, reference.IsStrictReference()); } } private static JsValue GetThisValue(Reference reference) { if (reference.IsSuperReference()) { return ExceptionHelper.ThrowNotImplementedException<JsValue>(); } return reference.GetBase(); } /// <summary> /// Invoke the current value as function. /// </summary> /// <param name="propertyName">The name of the function to call.</param> /// <param name="arguments">The arguments of the function call.</param> /// <returns>The value returned by the function call.</returns> public JsValue Invoke(string propertyName, params object[] arguments) { return Invoke(propertyName, null, arguments); } /// <summary> /// Invoke the current value as function. /// </summary> /// <param name="propertyName">The name of the function to call.</param> /// <param name="thisObj">The this value inside the function call.</param> /// <param name="arguments">The arguments of the function call.</param> /// <returns>The value returned by the function call.</returns> public JsValue Invoke(string propertyName, object thisObj, object[] arguments) { var value = GetValue(propertyName); return Invoke(value, thisObj, arguments); } /// <summary> /// Invoke the current value as function. /// </summary> /// <param name="value">The function to call.</param> /// <param name="arguments">The arguments of the function call.</param> /// <returns>The value returned by the function call.</returns> public JsValue Invoke(JsValue value, params object[] arguments) { return Invoke(value, null, arguments); } /// <summary> /// Invoke the current value as function. /// </summary> /// <param name="value">The function to call.</param> /// <param name="thisObj">The this value inside the function call.</param> /// <param name="arguments">The arguments of the function call.</param> /// <returns>The value returned by the function call.</returns> public JsValue Invoke(JsValue value, object thisObj, object[] arguments) { var callable = value as ICallable ?? ExceptionHelper.ThrowArgumentException<ICallable>("Can only invoke functions"); var items = _jsValueArrayPool.RentArray(arguments.Length); for (int i = 0; i < arguments.Length; ++i) { items[i] = JsValue.FromObject(this, arguments[i]); } var result = callable.Call(JsValue.FromObject(this, thisObj), items); _jsValueArrayPool.ReturnArray(items); return result; } /// <summary> /// Gets a named value from the Global scope. /// </summary> /// <param name="propertyName">The name of the property to return.</param> public JsValue GetValue(string propertyName) { return GetValue(Global, new JsString(propertyName)); } /// <summary> /// Gets the last evaluated <see cref="INode"/>. /// </summary> public INode GetLastSyntaxNode() { return _lastSyntaxNode; } /// <summary> /// Gets a named value from the specified scope. /// </summary> /// <param name="scope">The scope to get the property from.</param> /// <param name="property">The name of the property to return.</param> public JsValue GetValue(JsValue scope, JsValue property) { var reference = _referencePool.Rent(scope, property, _isStrict); var jsValue = GetValue(reference, false); _referencePool.Return(reference); return jsValue; } // http://www.ecma-international.org/ecma-262/5.1/#sec-10.5 internal ArgumentsInstance DeclarationBindingInstantiation( DeclarationBindingType declarationBindingType, HoistingScope hoistingScope, FunctionInstance functionInstance, JsValue[] arguments) { var env = ExecutionContext.VariableEnvironment._record; bool configurableBindings = declarationBindingType == DeclarationBindingType.EvalCode; var strict = StrictModeScope.IsStrictModeCode; ArgumentsInstance argsObj = null; var der = env as DeclarativeEnvironmentRecord; if (declarationBindingType == DeclarationBindingType.FunctionCode) { // arrow functions don't needs arguments var arrowFunctionInstance = functionInstance as ArrowFunctionInstance; argsObj = arrowFunctionInstance is null ? _argumentsInstancePool.Rent(functionInstance, functionInstance._formalParameters, arguments, env, strict) : null; var functionDeclaration = (functionInstance as ScriptFunctionInstance)?.FunctionDeclaration ?? arrowFunctionInstance?.FunctionDeclaration; if (!ReferenceEquals(der, null)) { der.AddFunctionParameters(arguments, argsObj, functionDeclaration); } else { // TODO: match functionality with DeclarationEnvironmentRecord.AddFunctionParameters here // slow path var parameters = functionInstance._formalParameters; for (uint i = 0; i < (uint) parameters.Length; i++) { var argName = parameters[i]; var v = i + 1 > arguments.Length ? Undefined.Instance : arguments[i]; v = DeclarativeEnvironmentRecord.HandleAssignmentPatternIfNeeded(functionDeclaration, v, i); var argAlreadyDeclared = env.HasBinding(argName); if (!argAlreadyDeclared) { env.CreateMutableBinding(argName, v); } env.SetMutableBinding(argName, v, strict); } env.CreateMutableBinding("arguments", argsObj); } } var functionDeclarations = hoistingScope.FunctionDeclarations; if (functionDeclarations.Count > 0) { AddFunctionDeclarations(ref functionDeclarations, env, configurableBindings, strict); } var variableDeclarations = hoistingScope.VariableDeclarations; if (variableDeclarations.Count == 0) { return argsObj; } // process all variable declarations in the current parser scope if (!ReferenceEquals(der, null)) { der.AddVariableDeclarations(ref variableDeclarations); } else { // slow path var variableDeclarationsCount = variableDeclarations.Count; for (var i = 0; i < variableDeclarationsCount; i++) { var variableDeclaration = variableDeclarations[i]; var declarations = variableDeclaration.Declarations; var declarationsCount = declarations.Count; for (var j = 0; j < declarationsCount; j++) { var d = declarations[j]; if (d.Id is Identifier id1) { var name = id1.Name; var varAlreadyDeclared = env.HasBinding(name); if (!varAlreadyDeclared) { env.CreateMutableBinding(name, Undefined.Instance); } } } } } return argsObj; } private void AddFunctionDeclarations( ref NodeList<IFunctionDeclaration> functionDeclarations, EnvironmentRecord env, bool configurableBindings, bool strict) { var functionDeclarationsCount = functionDeclarations.Count; for (var i = 0; i < functionDeclarationsCount; i++) { var f = functionDeclarations[i]; var fn = f.Id.Name; var fo = Function.CreateFunctionObject(f); var funcAlreadyDeclared = env.HasBinding(f.Id.Name); if (!funcAlreadyDeclared) { env.CreateMutableBinding(fn, configurableBindings); } else { if (ReferenceEquals(env, GlobalEnvironment._record)) { var go = Global; var existingProp = go.GetProperty(fn); if (existingProp.Configurable) { var flags = PropertyFlag.Writable | PropertyFlag.Enumerable; if (configurableBindings) { flags |= PropertyFlag.Configurable; } var descriptor = new PropertyDescriptor(Undefined.Instance, flags); go.DefinePropertyOrThrow(fn, descriptor); } else { if (existingProp.IsAccessorDescriptor() || !existingProp.Enumerable) { ExceptionHelper.ThrowTypeError(this); } } } } env.SetMutableBinding(fn, fo, strict); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void UpdateLexicalEnvironment(LexicalEnvironment newEnv) { _executionContexts.ReplaceTopLexicalEnvironment(newEnv); } private static void AssertNotNullOrEmpty(string propertyName, string propertyValue) { if (string.IsNullOrEmpty(propertyValue)) { ExceptionHelper.ThrowArgumentException(propertyName); } } } }
38.988147
203
0.573588
[ "BSD-2-Clause" ]
takenet/jint
Jint/Engine.cs
36,183
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MortelAuContact : MonoBehaviour { void OnTriggerEnter(Collider other) { if (other.gameObject.tag == "Player") { other.gameObject.GetComponent<PlayerLife>().Hit(); } } void OnTriggerStay(Collider other) { if (other.gameObject.tag == "Player") { other.gameObject.GetComponent<PlayerLife>().Hit(); } } }
21.434783
62
0.606491
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
spip2001/NierProtomata
Assets/Scripts/Decor/MortelAuContact.cs
495
C#
using System; using Snuggle.Core.IO; using Snuggle.Core.Models.Serialization; using Snuggle.Core.Options; namespace Snuggle.Core.Implementations; public class NamedObject : SerializedObject { public NamedObject(BiEndianBinaryReader reader, UnityObjectInfo info, SerializedFile serializedFile) : base(reader, info, serializedFile) => Name = reader.ReadString32(); public NamedObject(UnityObjectInfo info, SerializedFile serializedFile) : base(info, serializedFile) => Name = string.Empty; public string Name { get; set; } public override int GetHashCode() => HashCode.Combine(base.GetHashCode(), Name); public override void Serialize(BiEndianBinaryWriter writer, AssetSerializationOptions options) { base.Serialize(writer, options); writer.WriteString32(Name); } public override string ToString() => string.IsNullOrWhiteSpace(Name) ? base.ToString() : Name; }
41.318182
174
0.760176
[ "MIT" ]
yretenai/Snuggle
Snuggle.Core/Implementations/NamedObject.cs
911
C#
// Copyright (c) 2001-2021 Aspose Pty Ltd. All Rights Reserved. // // This file is part of Aspose.Words. The source code in this file // is only intended as a supplement to the documentation, and is provided // "as is", without warranty of any kind, either expressed or implied. ////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Linq; using System.Globalization; using System.IO; using Aspose.Pdf.Tagged; using Aspose.Words; using Aspose.Words.DigitalSignatures; using Aspose.Words.Fonts; using Aspose.Words.Markup; using Aspose.Words.Saving; using Aspose.Words.Settings; using NUnit.Framework; using ColorMode = Aspose.Words.Saving.ColorMode; using Document = Aspose.Words.Document; using IWarningCallback = Aspose.Words.IWarningCallback; using PdfSaveOptions = Aspose.Words.Saving.PdfSaveOptions; using SaveFormat = Aspose.Words.SaveFormat; using SaveOptions = Aspose.Words.Saving.SaveOptions; using WarningInfo = Aspose.Words.WarningInfo; using WarningType = Aspose.Words.WarningType; using Image = #if NET48 || JAVA System.Drawing.Image; #elif NET5_0 || __MOBILE__ SkiaSharp.SKBitmap; using SkiaSharp; #endif #if NET48 || NET5_0 || JAVA using Aspose.Pdf; using Aspose.Pdf.Annotations; using Aspose.Pdf.Facades; using Aspose.Pdf.Forms; using Aspose.Pdf.Operators; using Aspose.Pdf.Text; #endif namespace ApiExamples { [TestFixture] internal class ExPdfSaveOptions : ApiExampleBase { [Test] public void OnePage() { //ExStart //ExFor:FixedPageSaveOptions.PageSet //ExFor:Document.Save(Stream, SaveOptions) //ExSummary:Shows how to convert only some of the pages in a document to PDF. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Writeln("Page 1."); builder.InsertBreak(BreakType.PageBreak); builder.Writeln("Page 2."); builder.InsertBreak(BreakType.PageBreak); builder.Writeln("Page 3."); using (Stream stream = File.Create(ArtifactsDir + "PdfSaveOptions.OnePage.pdf")) { // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "PageIndex" to "1" to render a portion of the document starting from the second page. options.PageSet = new PageSet(1); // This document will contain one page starting from page two, which will only contain the second page. doc.Save(stream, options); } //ExEnd #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.OnePage.pdf"); Assert.AreEqual(1, pdfDocument.Pages.Count); TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(); pdfDocument.Pages.Accept(textFragmentAbsorber); Assert.AreEqual("Page 2.", textFragmentAbsorber.Text); #endif } [Test] public void HeadingsOutlineLevels() { //ExStart //ExFor:ParagraphFormat.IsHeading //ExFor:PdfSaveOptions.OutlineOptions //ExFor:PdfSaveOptions.SaveFormat //ExSummary:Shows how to limit the headings' level that will appear in the outline of a saved PDF document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert headings that can serve as TOC entries of levels 1, 2, and then 3. builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1; Assert.True(builder.ParagraphFormat.IsHeading); builder.Writeln("Heading 1"); builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2; builder.Writeln("Heading 1.1"); builder.Writeln("Heading 1.2"); builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading3; builder.Writeln("Heading 1.2.1"); builder.Writeln("Heading 1.2.2"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions saveOptions = new PdfSaveOptions(); saveOptions.SaveFormat = SaveFormat.Pdf; // The output PDF document will contain an outline, which is a table of contents that lists headings in the document body. // Clicking on an entry in this outline will take us to the location of its respective heading. // Set the "HeadingsOutlineLevels" property to "2" to exclude all headings whose levels are above 2 from the outline. // The last two headings we have inserted above will not appear. saveOptions.OutlineOptions.HeadingsOutlineLevels = 2; doc.Save(ArtifactsDir + "PdfSaveOptions.HeadingsOutlineLevels.pdf", saveOptions); //ExEnd #if NET48 || NET5_0 || JAVA PdfBookmarkEditor bookmarkEditor = new PdfBookmarkEditor(); bookmarkEditor.BindPdf(ArtifactsDir + "PdfSaveOptions.HeadingsOutlineLevels.pdf"); Bookmarks bookmarks = bookmarkEditor.ExtractBookmarks(); Assert.AreEqual(3, bookmarks.Count); #endif } [TestCase(false)] [TestCase(true)] public void CreateMissingOutlineLevels(bool createMissingOutlineLevels) { //ExStart //ExFor:OutlineOptions.CreateMissingOutlineLevels //ExFor:PdfSaveOptions.OutlineOptions //ExSummary:Shows how to work with outline levels that do not contain any corresponding headings when saving a PDF document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert headings that can serve as TOC entries of levels 1 and 5. builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1; Assert.True(builder.ParagraphFormat.IsHeading); builder.Writeln("Heading 1"); builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading5; builder.Writeln("Heading 1.1.1.1.1"); builder.Writeln("Heading 1.1.1.1.2"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions saveOptions = new PdfSaveOptions(); // The output PDF document will contain an outline, which is a table of contents that lists headings in the document body. // Clicking on an entry in this outline will take us to the location of its respective heading. // Set the "HeadingsOutlineLevels" property to "5" to include all headings of levels 5 and below in the outline. saveOptions.OutlineOptions.HeadingsOutlineLevels = 5; // This document contains headings of levels 1 and 5, and no headings with levels of 2, 3, and 4. // The output PDF document will treat outline levels 2, 3, and 4 as "missing". // Set the "CreateMissingOutlineLevels" property to "true" to include all missing levels in the outline, // leaving blank outline entries since there are no usable headings. // Set the "CreateMissingOutlineLevels" property to "false" to ignore missing outline levels, // and treat the outline level 5 headings as level 2. saveOptions.OutlineOptions.CreateMissingOutlineLevels = createMissingOutlineLevels; doc.Save(ArtifactsDir + "PdfSaveOptions.CreateMissingOutlineLevels.pdf", saveOptions); //ExEnd #if NET48 || NET5_0 || JAVA PdfBookmarkEditor bookmarkEditor = new PdfBookmarkEditor(); bookmarkEditor.BindPdf(ArtifactsDir + "PdfSaveOptions.CreateMissingOutlineLevels.pdf"); Bookmarks bookmarks = bookmarkEditor.ExtractBookmarks(); Assert.AreEqual(createMissingOutlineLevels ? 6 : 3, bookmarks.Count); #endif } [TestCase(false)] [TestCase(true)] public void TableHeadingOutlines(bool createOutlinesForHeadingsInTables) { //ExStart //ExFor:OutlineOptions.CreateOutlinesForHeadingsInTables //ExSummary:Shows how to create PDF document outline entries for headings inside tables. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Create a table with three rows. The first row, // whose text we will format in a heading-type style, will serve as the column header. builder.StartTable(); builder.InsertCell(); builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1; builder.Write("Customers"); builder.EndRow(); builder.InsertCell(); builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Normal; builder.Write("John Doe"); builder.EndRow(); builder.InsertCell(); builder.Write("Jane Doe"); builder.EndTable(); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions pdfSaveOptions = new PdfSaveOptions(); // The output PDF document will contain an outline, which is a table of contents that lists headings in the document body. // Clicking on an entry in this outline will take us to the location of its respective heading. // Set the "HeadingsOutlineLevels" property to "1" to get the outline // to only register headings with heading levels that are no larger than 1. pdfSaveOptions.OutlineOptions.HeadingsOutlineLevels = 1; // Set the "CreateOutlinesForHeadingsInTables" property to "false" to exclude all headings within tables, // such as the one we have created above from the outline. // Set the "CreateOutlinesForHeadingsInTables" property to "true" to include all headings within tables // in the outline, provided that they have a heading level that is no larger than the value of the "HeadingsOutlineLevels" property. pdfSaveOptions.OutlineOptions.CreateOutlinesForHeadingsInTables = createOutlinesForHeadingsInTables; doc.Save(ArtifactsDir + "PdfSaveOptions.TableHeadingOutlines.pdf", pdfSaveOptions); //ExEnd #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDoc = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.TableHeadingOutlines.pdf"); if (createOutlinesForHeadingsInTables) { Assert.AreEqual(1, pdfDoc.Outlines.Count); Assert.AreEqual("Customers", pdfDoc.Outlines[1].Title); } else Assert.AreEqual(0, pdfDoc.Outlines.Count); TableAbsorber tableAbsorber = new TableAbsorber(); tableAbsorber.Visit(pdfDoc.Pages[1]); Assert.AreEqual("Customers", tableAbsorber.TableList[0].RowList[0].CellList[0].TextFragments[1].Text); Assert.AreEqual("John Doe", tableAbsorber.TableList[0].RowList[1].CellList[0].TextFragments[1].Text); Assert.AreEqual("Jane Doe", tableAbsorber.TableList[0].RowList[2].CellList[0].TextFragments[1].Text); #endif } [Test] public void ExpandedOutlineLevels() { //ExStart //ExFor:Document.Save(String, SaveOptions) //ExFor:PdfSaveOptions //ExFor:OutlineOptions.HeadingsOutlineLevels //ExFor:OutlineOptions.ExpandedOutlineLevels //ExSummary:Shows how to convert a whole document to PDF with three levels in the document outline. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert headings of levels 1 to 5. builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1; Assert.True(builder.ParagraphFormat.IsHeading); builder.Writeln("Heading 1"); builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2; builder.Writeln("Heading 1.1"); builder.Writeln("Heading 1.2"); builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading3; builder.Writeln("Heading 1.2.1"); builder.Writeln("Heading 1.2.2"); builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading4; builder.Writeln("Heading 1.2.2.1"); builder.Writeln("Heading 1.2.2.2"); builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading5; builder.Writeln("Heading 1.2.2.2.1"); builder.Writeln("Heading 1.2.2.2.2"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // The output PDF document will contain an outline, which is a table of contents that lists headings in the document body. // Clicking on an entry in this outline will take us to the location of its respective heading. // Set the "HeadingsOutlineLevels" property to "4" to exclude all headings whose levels are above 4 from the outline. options.OutlineOptions.HeadingsOutlineLevels = 4; // If an outline entry has subsequent entries of a higher level inbetween itself and the next entry of the same or lower level, // an arrow will appear to the left of the entry. This entry is the "owner" of several such "sub-entries". // In our document, the outline entries from the 5th heading level are sub-entries of the second 4th level outline entry, // the 4th and 5th heading level entries are sub-entries of the second 3rd level entry, and so on. // In the outline, we can click on the arrow of the "owner" entry to collapse/expand all its sub-entries. // Set the "ExpandedOutlineLevels" property to "2" to automatically expand all heading level 2 and lower outline entries // and collapse all level and 3 and higher entries when we open the document. options.OutlineOptions.ExpandedOutlineLevels = 2; doc.Save(ArtifactsDir + "PdfSaveOptions.ExpandedOutlineLevels.pdf", options); //ExEnd #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.ExpandedOutlineLevels.pdf"); Assert.AreEqual(1, pdfDocument.Outlines.Count); Assert.AreEqual(5, pdfDocument.Outlines.VisibleCount); Assert.True(pdfDocument.Outlines[1].Open); Assert.AreEqual(1, pdfDocument.Outlines[1].Level); Assert.False(pdfDocument.Outlines[1][1].Open); Assert.AreEqual(2, pdfDocument.Outlines[1][1].Level); Assert.True(pdfDocument.Outlines[1][2].Open); Assert.AreEqual(2, pdfDocument.Outlines[1][2].Level); #endif } [TestCase(false)] [TestCase(true)] public void UpdateFields(bool updateFields) { //ExStart //ExFor:PdfSaveOptions.Clone //ExFor:SaveOptions.UpdateFields //ExSummary:Shows how to update all the fields in a document immediately before saving it to PDF. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert text with PAGE and NUMPAGES fields. These fields do not display the correct value in real time. // We will need to manually update them using updating methods such as "Field.Update()", and "Document.UpdateFields()" // each time we need them to display accurate values. builder.Write("Page "); builder.InsertField("PAGE", ""); builder.Write(" of "); builder.InsertField("NUMPAGES", ""); builder.InsertBreak(BreakType.PageBreak); builder.Writeln("Hello World!"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "UpdateFields" property to "false" to not update all the fields in a document right before a save operation. // This is the preferable option if we know that all our fields will be up to date before saving. // Set the "UpdateFields" property to "true" to iterate through all the document // fields and update them before we save it as a PDF. This will make sure that all the fields will display // the most accurate values in the PDF. options.UpdateFields = updateFields; // We can clone PdfSaveOptions objects. Assert.AreNotSame(options, options.Clone()); doc.Save(ArtifactsDir + "PdfSaveOptions.UpdateFields.pdf", options); //ExEnd #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.UpdateFields.pdf"); TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(); pdfDocument.Pages.Accept(textFragmentAbsorber); Assert.AreEqual(updateFields ? "Page 1 of 2" : "Page of ", textFragmentAbsorber.TextFragments[1].Text); #endif } [TestCase(false)] [TestCase(true)] public void PreserveFormFields(bool preserveFormFields) { //ExStart //ExFor:PdfSaveOptions.PreserveFormFields //ExSummary:Shows how to save a document to the PDF format using the Save method and the PdfSaveOptions class. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Write("Please select a fruit: "); // Insert a combo box which will allow a user to choose an option from a collection of strings. builder.InsertComboBox("MyComboBox", new[] { "Apple", "Banana", "Cherry" }, 0); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions pdfOptions = new PdfSaveOptions(); // Set the "PreserveFormFields" property to "true" to save form fields as interactive objects in the output PDF. // Set the "PreserveFormFields" property to "false" to freeze all form fields in the document at // their current values and display them as plain text in the output PDF. pdfOptions.PreserveFormFields = preserveFormFields; doc.Save(ArtifactsDir + "PdfSaveOptions.PreserveFormFields.pdf", pdfOptions); //ExEnd #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.PreserveFormFields.pdf"); Assert.AreEqual(1, pdfDocument.Pages.Count); TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(); pdfDocument.Pages.Accept(textFragmentAbsorber); if (preserveFormFields) { Assert.AreEqual("Please select a fruit: ", textFragmentAbsorber.Text); TestUtil.FileContainsString("11 0 obj\r\n" + "<</Type /Annot/Subtype /Widget/P 5 0 R/FT /Ch/F 4/Rect [168.39199829 707.35101318 217.87442017 722.64007568]/Ff 131072/T(þÿ\0M\0y\0C\0o\0m\0b\0o\0B\0o\0x)/Opt " + "[(þÿ\0A\0p\0p\0l\0e) (þÿ\0B\0a\0n\0a\0n\0a) (þÿ\0C\0h\0e\0r\0r\0y) ]/V(þÿ\0A\0p\0p\0l\0e)/DA(0 g /FAAABD 12 Tf )/AP<</N 12 0 R>>>>", ArtifactsDir + "PdfSaveOptions.PreserveFormFields.pdf"); Aspose.Pdf.Forms.Form form = pdfDocument.Form; Assert.AreEqual(1, pdfDocument.Form.Count); ComboBoxField field = (ComboBoxField)form.Fields[0]; Assert.AreEqual("MyComboBox", field.FullName); Assert.AreEqual(3, field.Options.Count); Assert.AreEqual("Apple", field.Value); } else { Assert.AreEqual("Please select a fruit: Apple", textFragmentAbsorber.Text); Assert.Throws<AssertionException>(() => { TestUtil.FileContainsString("/Widget", ArtifactsDir + "PdfSaveOptions.PreserveFormFields.pdf"); }); Assert.AreEqual(0, pdfDocument.Form.Count); } #endif } [TestCase(PdfCompliance.PdfA2u)] [TestCase(PdfCompliance.Pdf17)] [TestCase(PdfCompliance.PdfA2a)] public void Compliance(PdfCompliance pdfCompliance) { //ExStart //ExFor:PdfSaveOptions.Compliance //ExFor:PdfCompliance //ExSummary:Shows how to set the PDF standards compliance level of saved PDF documents. Document doc = new Document(MyDir + "Images.docx"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions saveOptions = new PdfSaveOptions(); // Set the "Compliance" property to "PdfCompliance.PdfA1b" to comply with the "PDF/A-1b" standard, // which aims to preserve the visual appearance of the document as Aspose.Words convert it to PDF. // Set the "Compliance" property to "PdfCompliance.Pdf17" to comply with the "1.7" standard. // Set the "Compliance" property to "PdfCompliance.PdfA1a" to comply with the "PDF/A-1a" standard, // which complies with "PDF/A-1b" as well as preserving the document structure of the original document. // This helps with making documents searchable but may significantly increase the size of already large documents. saveOptions.Compliance = pdfCompliance; doc.Save(ArtifactsDir + "PdfSaveOptions.Compliance.pdf", saveOptions); //ExEnd #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.Compliance.pdf"); switch (pdfCompliance) { case PdfCompliance.Pdf17: Assert.AreEqual(PdfFormat.v_1_7, pdfDocument.PdfFormat); Assert.AreEqual("1.7", pdfDocument.Version); break; case PdfCompliance.PdfA2a: Assert.AreEqual(PdfFormat.PDF_A_2A, pdfDocument.PdfFormat); Assert.AreEqual("1.7", pdfDocument.Version); break; case PdfCompliance.PdfA2u: Assert.AreEqual(PdfFormat.PDF_A_2U, pdfDocument.PdfFormat); Assert.AreEqual("1.7", pdfDocument.Version); break; } #endif } [TestCase(PdfTextCompression.None)] [TestCase(PdfTextCompression.Flate)] public void TextCompression(PdfTextCompression pdfTextCompression) { //ExStart //ExFor:PdfSaveOptions //ExFor:PdfSaveOptions.TextCompression //ExFor:PdfTextCompression //ExSummary:Shows how to apply text compression when saving a document to PDF. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); for (int i = 0; i < 100; i++) builder.Writeln("Lorem ipsum dolor sit amet, consectetur adipiscing elit, " + "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "TextCompression" property to "PdfTextCompression.None" to not apply any // compression to text when we save the document to PDF. // Set the "TextCompression" property to "PdfTextCompression.Flate" to apply ZIP compression // to text when we save the document to PDF. The larger the document, the bigger the impact that this will have. options.TextCompression = pdfTextCompression; doc.Save(ArtifactsDir + "PdfSaveOptions.TextCompression.pdf", options); //ExEnd switch (pdfTextCompression) { case PdfTextCompression.None: Assert.That(60000, Is.LessThan(new FileInfo(ArtifactsDir + "PdfSaveOptions.TextCompression.pdf").Length)); TestUtil.FileContainsString("12 0 obj\r\n<</Length 13 0 R>>stream", ArtifactsDir + "PdfSaveOptions.TextCompression.pdf"); break; case PdfTextCompression.Flate: Assert.That(30000, Is.AtLeast(new FileInfo(ArtifactsDir + "PdfSaveOptions.TextCompression.pdf").Length)); TestUtil.FileContainsString("12 0 obj\r\n<</Length 13 0 R/Filter /FlateDecode>>stream", ArtifactsDir + "PdfSaveOptions.TextCompression.pdf"); break; } } [TestCase(PdfImageCompression.Auto)] [TestCase(PdfImageCompression.Jpeg)] public void ImageCompression(PdfImageCompression pdfImageCompression) { //ExStart //ExFor:PdfSaveOptions.ImageCompression //ExFor:PdfSaveOptions.JpegQuality //ExFor:PdfImageCompression //ExSummary:Shows how to specify a compression type for all images in a document that we are converting to PDF. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Writeln("Jpeg image:"); builder.InsertImage(ImageDir + "Logo.jpg"); builder.InsertParagraph(); builder.Writeln("Png image:"); builder.InsertImage(ImageDir + "Transparent background logo.png"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions pdfSaveOptions = new PdfSaveOptions(); // Set the "ImageCompression" property to "PdfImageCompression.Auto" to use the // "ImageCompression" property to control the quality of the Jpeg images that end up in the output PDF. // Set the "ImageCompression" property to "PdfImageCompression.Jpeg" to use the // "ImageCompression" property to control the quality of all images that end up in the output PDF. pdfSaveOptions.ImageCompression = pdfImageCompression; // Set the "JpegQuality" property to "10" to strengthen compression at the cost of image quality. pdfSaveOptions.JpegQuality = 10; doc.Save(ArtifactsDir + "PdfSaveOptions.ImageCompression.pdf", pdfSaveOptions); //ExEnd #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.ImageCompression.pdf"); Stream pdfDocImageStream = pdfDocument.Pages[1].Resources.Images[1].ToStream(); using (pdfDocImageStream) { TestUtil.VerifyImage(400, 400, pdfDocImageStream); } pdfDocImageStream = pdfDocument.Pages[1].Resources.Images[2].ToStream(); using (pdfDocImageStream) { switch (pdfImageCompression) { case PdfImageCompression.Auto: Assert.That(50000, Is.LessThan(new FileInfo(ArtifactsDir + "PdfSaveOptions.ImageCompression.pdf").Length)); #if NET48 Assert.Throws<ArgumentException>(() => { TestUtil.VerifyImage(400, 400, pdfDocImageStream); }); #elif NET5_0 Assert.Throws<NullReferenceException>(() => { TestUtil.VerifyImage(400, 400, pdfDocImageStream); }); #endif break; case PdfImageCompression.Jpeg: Assert.That(42000, Is.AtLeast(new FileInfo(ArtifactsDir + "PdfSaveOptions.ImageCompression.pdf").Length)); TestUtil.VerifyImage(400, 400, pdfDocImageStream); break; } } #endif } [TestCase(PdfImageColorSpaceExportMode.Auto)] [TestCase(PdfImageColorSpaceExportMode.SimpleCmyk)] public void ImageColorSpaceExportMode(PdfImageColorSpaceExportMode pdfImageColorSpaceExportMode) { //ExStart //ExFor:PdfImageColorSpaceExportMode //ExFor:PdfSaveOptions.ImageColorSpaceExportMode //ExSummary:Shows how to set a different color space for images in a document as we export it to PDF. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Writeln("Jpeg image:"); builder.InsertImage(ImageDir + "Logo.jpg"); builder.InsertParagraph(); builder.Writeln("Png image:"); builder.InsertImage(ImageDir + "Transparent background logo.png"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions pdfSaveOptions = new PdfSaveOptions(); // Set the "ImageColorSpaceExportMode" property to "PdfImageColorSpaceExportMode.Auto" to get Aspose.Words to // automatically select the color space for images in the document that it converts to PDF. // In most cases, the color space will be RGB. // Set the "ImageColorSpaceExportMode" property to "PdfImageColorSpaceExportMode.SimpleCmyk" // to use the CMYK color space for all images in the saved PDF. // Aspose.Words will also apply Flate compression to all images and ignore the "ImageCompression" property's value. pdfSaveOptions.ImageColorSpaceExportMode = pdfImageColorSpaceExportMode; doc.Save(ArtifactsDir + "PdfSaveOptions.ImageColorSpaceExportMode.pdf", pdfSaveOptions); //ExEnd #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.ImageColorSpaceExportMode.pdf"); XImage pdfDocImage = pdfDocument.Pages[1].Resources.Images[1]; switch (pdfImageColorSpaceExportMode) { case PdfImageColorSpaceExportMode.Auto: Assert.That(20000, Is.LessThan(pdfDocImage.ToStream().Length)); break; case PdfImageColorSpaceExportMode.SimpleCmyk: Assert.That(100000, Is.LessThan(pdfDocImage.ToStream().Length)); break; } Assert.AreEqual(400, pdfDocImage.Width); Assert.AreEqual(400, pdfDocImage.Height); Assert.AreEqual(ColorType.Rgb, pdfDocImage.GetColorType()); pdfDocImage = pdfDocument.Pages[1].Resources.Images[2]; switch (pdfImageColorSpaceExportMode) { case PdfImageColorSpaceExportMode.Auto: Assert.That(25000, Is.AtLeast(pdfDocImage.ToStream().Length)); break; case PdfImageColorSpaceExportMode.SimpleCmyk: Assert.That(18000, Is.LessThan(pdfDocImage.ToStream().Length)); break; } Assert.AreEqual(400, pdfDocImage.Width); Assert.AreEqual(400, pdfDocImage.Height); Assert.AreEqual(ColorType.Rgb, pdfDocImage.GetColorType()); #endif } [Test] public void DownsampleOptions() { //ExStart //ExFor:DownsampleOptions //ExFor:DownsampleOptions.DownsampleImages //ExFor:DownsampleOptions.Resolution //ExFor:DownsampleOptions.ResolutionThreshold //ExFor:PdfSaveOptions.DownsampleOptions //ExSummary:Shows how to change the resolution of images in the PDF document. Document doc = new Document(MyDir + "Images.docx"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // By default, Aspose.Words downsample all images in a document that we save to PDF to 220 ppi. Assert.True(options.DownsampleOptions.DownsampleImages); Assert.AreEqual(220, options.DownsampleOptions.Resolution); Assert.AreEqual(0, options.DownsampleOptions.ResolutionThreshold); doc.Save(ArtifactsDir + "PdfSaveOptions.DownsampleOptions.Default.pdf", options); // Set the "Resolution" property to "36" to downsample all images to 36 ppi. options.DownsampleOptions.Resolution = 36; // Set the "ResolutionThreshold" property to only apply the downsampling to // images with a resolution that is above 128 ppi. options.DownsampleOptions.ResolutionThreshold = 128; // Only the first two images from the document will be downsampled at this stage. doc.Save(ArtifactsDir + "PdfSaveOptions.DownsampleOptions.LowerResolution.pdf", options); //ExEnd #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.DownsampleOptions.Default.pdf"); XImage pdfDocImage = pdfDocument.Pages[1].Resources.Images[1]; Assert.That(300000, Is.LessThan(pdfDocImage.ToStream().Length)); Assert.AreEqual(ColorType.Rgb, pdfDocImage.GetColorType()); #endif } [TestCase(ColorMode.Grayscale)] [TestCase(ColorMode.Normal)] public void ColorRendering(ColorMode colorMode) { //ExStart //ExFor:PdfSaveOptions //ExFor:ColorMode //ExFor:FixedPageSaveOptions.ColorMode //ExSummary:Shows how to change image color with saving options property. Document doc = new Document(MyDir + "Images.docx"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. // Set the "ColorMode" property to "Grayscale" to render all images from the document in black and white. // The size of the output document may be larger with this setting. // Set the "ColorMode" property to "Normal" to render all images in color. PdfSaveOptions pdfSaveOptions = new PdfSaveOptions { ColorMode = colorMode }; doc.Save(ArtifactsDir + "PdfSaveOptions.ColorRendering.pdf", pdfSaveOptions); //ExEnd #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.ColorRendering.pdf"); XImage pdfDocImage = pdfDocument.Pages[1].Resources.Images[1]; switch (colorMode) { case ColorMode.Normal: Assert.That(300000, Is.LessThan(pdfDocImage.ToStream().Length)); Assert.AreEqual(ColorType.Rgb, pdfDocImage.GetColorType()); break; case ColorMode.Grayscale: Assert.That(1000000, Is.LessThan(pdfDocImage.ToStream().Length)); Assert.AreEqual(ColorType.Grayscale, pdfDocImage.GetColorType()); break; } #endif } [TestCase(false)] [TestCase(true)] public void DocTitle(bool displayDocTitle) { //ExStart //ExFor:PdfSaveOptions.DisplayDocTitle //ExSummary:Shows how to display the title of the document as the title bar. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Writeln("Hello world!"); doc.BuiltInDocumentProperties.Title = "Windows bar pdf title"; // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. // Set the "DisplayDocTitle" to "true" to get some PDF readers, such as Adobe Acrobat Pro, // to display the value of the document's "Title" built-in property in the tab that belongs to this document. // Set the "DisplayDocTitle" to "false" to get such readers to display the document's filename. PdfSaveOptions pdfSaveOptions = new PdfSaveOptions { DisplayDocTitle = displayDocTitle }; doc.Save(ArtifactsDir + "PdfSaveOptions.DocTitle.pdf", pdfSaveOptions); //ExEnd #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.DocTitle.pdf"); Assert.AreEqual(displayDocTitle, pdfDocument.DisplayDocTitle); Assert.AreEqual("Windows bar pdf title", pdfDocument.Info.Title); #endif } [TestCase(false)] [TestCase(true)] public void MemoryOptimization(bool memoryOptimization) { //ExStart //ExFor:SaveOptions.CreateSaveOptions(SaveFormat) //ExFor:SaveOptions.MemoryOptimization //ExSummary:Shows an option to optimize memory consumption when rendering large documents to PDF. Document doc = new Document(MyDir + "Rendering.docx"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. SaveOptions saveOptions = SaveOptions.CreateSaveOptions(SaveFormat.Pdf); // Set the "MemoryOptimization" property to "true" to lower the memory footprint of large documents' saving operations // at the cost of increasing the duration of the operation. // Set the "MemoryOptimization" property to "false" to save the document as a PDF normally. saveOptions.MemoryOptimization = memoryOptimization; doc.Save(ArtifactsDir + "PdfSaveOptions.MemoryOptimization.pdf", saveOptions); //ExEnd } [TestCase(@"https://www.google.com/search?q= aspose", "https://www.google.com/search?q=%20aspose")] [TestCase(@"https://www.google.com/search?q=%20aspose", "https://www.google.com/search?q=%20aspose")] public void EscapeUri(string uri, string result) { Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.InsertHyperlink("Testlink", uri, false); doc.Save(ArtifactsDir + "PdfSaveOptions.EscapedUri.pdf"); #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.EscapedUri.pdf"); Page page = pdfDocument.Pages[1]; LinkAnnotation linkAnnot = (LinkAnnotation)page.Annotations[1]; GoToURIAction action = (GoToURIAction)linkAnnot.Action; Assert.AreEqual(result, action.URI); #endif } [TestCase(false)] [TestCase(true)] public void OpenHyperlinksInNewWindow(bool openHyperlinksInNewWindow) { //ExStart //ExFor:PdfSaveOptions.OpenHyperlinksInNewWindow //ExSummary:Shows how to save hyperlinks in a document we convert to PDF so that they open new pages when we click on them. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.InsertHyperlink("Testlink", @"https://www.google.com/search?q=%20aspose", false); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "OpenHyperlinksInNewWindow" property to "true" to save all hyperlinks using Javascript code // that forces readers to open these links in new windows/browser tabs. // Set the "OpenHyperlinksInNewWindow" property to "false" to save all hyperlinks normally. options.OpenHyperlinksInNewWindow = openHyperlinksInNewWindow; doc.Save(ArtifactsDir + "PdfSaveOptions.OpenHyperlinksInNewWindow.pdf", options); //ExEnd if (openHyperlinksInNewWindow) TestUtil.FileContainsString( "<</Type /Annot/Subtype /Link/Rect [70.84999847 707.35101318 110.17799377 721.15002441]/BS " + "<</Type/Border/S/S/W 0>>/A<</Type /Action/S /JavaScript/JS(app.launchURL\\(\"https://www.google.com/search?q=%20aspose\", true\\);)>>>>", ArtifactsDir + "PdfSaveOptions.OpenHyperlinksInNewWindow.pdf"); else TestUtil.FileContainsString( "<</Type /Annot/Subtype /Link/Rect [70.84999847 707.35101318 110.17799377 721.15002441]/BS " + "<</Type/Border/S/S/W 0>>/A<</Type /Action/S /URI/URI(https://www.google.com/search?q=%20aspose)>>>>", ArtifactsDir + "PdfSaveOptions.OpenHyperlinksInNewWindow.pdf"); #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.OpenHyperlinksInNewWindow.pdf"); Page page = pdfDocument.Pages[1]; LinkAnnotation linkAnnot = (LinkAnnotation) page.Annotations[1]; Assert.AreEqual(openHyperlinksInNewWindow ? typeof(JavascriptAction) : typeof(GoToURIAction), linkAnnot.Action.GetType()); #endif } //ExStart //ExFor:MetafileRenderingMode //ExFor:MetafileRenderingOptions //ExFor:MetafileRenderingOptions.EmulateRasterOperations //ExFor:MetafileRenderingOptions.RenderingMode //ExFor:IWarningCallback //ExFor:FixedPageSaveOptions.MetafileRenderingOptions //ExSummary:Shows added a fallback to bitmap rendering and changing type of warnings about unsupported metafile records. [Test, Category("SkipMono")] //ExSkip public void HandleBinaryRasterWarnings() { Document doc = new Document(MyDir + "WMF with image.docx"); MetafileRenderingOptions metafileRenderingOptions = new MetafileRenderingOptions(); // Set the "EmulateRasterOperations" property to "false" to fall back to bitmap when // it encounters a metafile, which will require raster operations to render in the output PDF. metafileRenderingOptions.EmulateRasterOperations = false; // Set the "RenderingMode" property to "VectorWithFallback" to try to render every metafile using vector graphics. metafileRenderingOptions.RenderingMode = MetafileRenderingMode.VectorWithFallback; // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF and applies the configuration // in our MetafileRenderingOptions object to the saving operation. PdfSaveOptions saveOptions = new PdfSaveOptions(); saveOptions.MetafileRenderingOptions = metafileRenderingOptions; HandleDocumentWarnings callback = new HandleDocumentWarnings(); doc.WarningCallback = callback; doc.Save(ArtifactsDir + "PdfSaveOptions.HandleBinaryRasterWarnings.pdf", saveOptions); Assert.AreEqual(1, callback.Warnings.Count); Assert.AreEqual("'R2_XORPEN' binary raster operation is partly supported.", callback.Warnings[0].Description); } /// <summary> /// Prints and collects formatting loss-related warnings that occur upon saving a document. /// </summary> public class HandleDocumentWarnings : IWarningCallback { public void Warning(WarningInfo info) { if (info.WarningType == WarningType.MinorFormattingLoss) { Console.WriteLine("Unsupported operation: " + info.Description); Warnings.Warning(info); } } public WarningInfoCollection Warnings = new WarningInfoCollection(); } //ExEnd [TestCase(Aspose.Words.Saving.HeaderFooterBookmarksExportMode.None)] [TestCase(Aspose.Words.Saving.HeaderFooterBookmarksExportMode.First)] [TestCase(Aspose.Words.Saving.HeaderFooterBookmarksExportMode.All)] public void HeaderFooterBookmarksExportMode(HeaderFooterBookmarksExportMode headerFooterBookmarksExportMode) { //ExStart //ExFor:HeaderFooterBookmarksExportMode //ExFor:OutlineOptions //ExFor:OutlineOptions.DefaultBookmarksOutlineLevel //ExFor:PdfSaveOptions.HeaderFooterBookmarksExportMode //ExFor:PdfSaveOptions.PageMode //ExFor:PdfPageMode //ExSummary:Shows to process bookmarks in headers/footers in a document that we are rendering to PDF. Document doc = new Document(MyDir + "Bookmarks in headers and footers.docx"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions saveOptions = new PdfSaveOptions(); // Set the "PageMode" property to "PdfPageMode.UseOutlines" to display the outline navigation pane in the output PDF. saveOptions.PageMode = PdfPageMode.UseOutlines; // Set the "DefaultBookmarksOutlineLevel" property to "1" to display all // bookmarks at the first level of the outline in the output PDF. saveOptions.OutlineOptions.DefaultBookmarksOutlineLevel = 1; // Set the "HeaderFooterBookmarksExportMode" property to "HeaderFooterBookmarksExportMode.None" to // not export any bookmarks that are inside headers/footers. // Set the "HeaderFooterBookmarksExportMode" property to "HeaderFooterBookmarksExportMode.First" to // only export bookmarks in the first section's header/footers. // Set the "HeaderFooterBookmarksExportMode" property to "HeaderFooterBookmarksExportMode.All" to // export bookmarks that are in all headers/footers. saveOptions.HeaderFooterBookmarksExportMode = headerFooterBookmarksExportMode; doc.Save(ArtifactsDir + "PdfSaveOptions.HeaderFooterBookmarksExportMode.pdf", saveOptions); //ExEnd #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDoc = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.HeaderFooterBookmarksExportMode.pdf"); string inputDocLocaleName = new CultureInfo(doc.Styles.DefaultFont.LocaleId).Name; TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(); pdfDoc.Pages.Accept(textFragmentAbsorber); switch (headerFooterBookmarksExportMode) { case Aspose.Words.Saving.HeaderFooterBookmarksExportMode.None: TestUtil.FileContainsString($"<</Type /Catalog/Pages 3 0 R/Lang({inputDocLocaleName})/Metadata 4 0 R>>\r\n", ArtifactsDir + "PdfSaveOptions.HeaderFooterBookmarksExportMode.pdf"); Assert.AreEqual(0, pdfDoc.Outlines.Count); break; case Aspose.Words.Saving.HeaderFooterBookmarksExportMode.First: case Aspose.Words.Saving.HeaderFooterBookmarksExportMode.All: TestUtil.FileContainsString( $"<</Type /Catalog/Pages 3 0 R/Outlines 14 0 R/PageMode /UseOutlines/Lang({inputDocLocaleName})/Metadata 4 0 R>>", ArtifactsDir + "PdfSaveOptions.HeaderFooterBookmarksExportMode.pdf"); OutlineCollection outlineItemCollection = pdfDoc.Outlines; Assert.AreEqual(4, outlineItemCollection.Count); Assert.AreEqual("Bookmark_1", outlineItemCollection[1].Title); Assert.AreEqual("1 XYZ 233 806 0", outlineItemCollection[1].Destination.ToString()); Assert.AreEqual("Bookmark_2", outlineItemCollection[2].Title); Assert.AreEqual("1 XYZ 84 47 0", outlineItemCollection[2].Destination.ToString()); Assert.AreEqual("Bookmark_3", outlineItemCollection[3].Title); Assert.AreEqual("2 XYZ 85 806 0", outlineItemCollection[3].Destination.ToString()); Assert.AreEqual("Bookmark_4", outlineItemCollection[4].Title); Assert.AreEqual("2 XYZ 85 48 0", outlineItemCollection[4].Destination.ToString()); break; } #endif } [Test] public void UnsupportedImageFormatWarning() { Document doc = new Document(MyDir + "Corrupted image.docx"); SaveWarningCallback saveWarningCallback = new SaveWarningCallback(); doc.WarningCallback = saveWarningCallback; doc.Save(ArtifactsDir + "PdfSaveOption.UnsupportedImageFormatWarning.pdf", SaveFormat.Pdf); Assert.That(saveWarningCallback.SaveWarnings[0].Description, Is.EqualTo("Image can not be processed. Possibly unsupported image format.")); } public class SaveWarningCallback : IWarningCallback { public void Warning(WarningInfo info) { if (info.WarningType == WarningType.MinorFormattingLoss) { Console.WriteLine($"{info.WarningType}: {info.Description}."); SaveWarnings.Warning(info); } } internal WarningInfoCollection SaveWarnings = new WarningInfoCollection(); } [TestCase(false)] [TestCase(true)] public void FontsScaledToMetafileSize(bool scaleWmfFonts) { //ExStart //ExFor:MetafileRenderingOptions.ScaleWmfFontsToMetafileSize //ExSummary:Shows how to WMF fonts scaling according to metafile size on the page. Document doc = new Document(MyDir + "WMF with text.docx"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions saveOptions = new PdfSaveOptions(); // Set the "ScaleWmfFontsToMetafileSize" property to "true" to scale fonts // that format text within WMF images according to the size of the metafile on the page. // Set the "ScaleWmfFontsToMetafileSize" property to "false" to // preserve the default scale of these fonts. saveOptions.MetafileRenderingOptions.ScaleWmfFontsToMetafileSize = scaleWmfFonts; doc.Save(ArtifactsDir + "PdfSaveOptions.FontsScaledToMetafileSize.pdf", saveOptions); //ExEnd #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.FontsScaledToMetafileSize.pdf"); TextFragmentAbsorber textAbsorber = new TextFragmentAbsorber(); pdfDocument.Pages[1].Accept(textAbsorber); Rectangle textFragmentRectangle = textAbsorber.TextFragments[3].Rectangle; Assert.AreEqual(scaleWmfFonts ? 1.589d : 5.045d, textFragmentRectangle.Width, 0.001d); #endif } [TestCase(false)] [TestCase(true)] public void EmbedFullFonts(bool embedFullFonts) { //ExStart //ExFor:PdfSaveOptions.#ctor //ExFor:PdfSaveOptions.EmbedFullFonts //ExSummary:Shows how to enable or disable subsetting when embedding fonts while rendering a document to PDF. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Font.Name = "Arial"; builder.Writeln("Hello world!"); builder.Font.Name = "Arvo"; builder.Writeln("The quick brown fox jumps over the lazy dog."); // Configure our font sources to ensure that we have access to both the fonts in this document. FontSourceBase[] originalFontsSources = FontSettings.DefaultInstance.GetFontsSources(); Aspose.Words.Fonts.FolderFontSource folderFontSource = new Aspose.Words.Fonts.FolderFontSource(FontsDir, true); FontSettings.DefaultInstance.SetFontsSources(new[] { originalFontsSources[0], folderFontSource }); FontSourceBase[] fontSources = FontSettings.DefaultInstance.GetFontsSources(); Assert.True(fontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Arial")); Assert.True(fontSources[1].GetAvailableFonts().Any(f => f.FullFontName == "Arvo")); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Since our document contains a custom font, embedding in the output document may be desirable. // Set the "EmbedFullFonts" property to "true" to embed every glyph of every embedded font in the output PDF. // The document's size may become very large, but we will have full use of all fonts if we edit the PDF. // Set the "EmbedFullFonts" property to "false" to apply subsetting to fonts, saving only the glyphs // that the document is using. The file will be considerably smaller, // but we may need access to any custom fonts if we edit the document. options.EmbedFullFonts = embedFullFonts; doc.Save(ArtifactsDir + "PdfSaveOptions.EmbedFullFonts.pdf", options); if (embedFullFonts) Assert.That(500000, Is.LessThan(new FileInfo(ArtifactsDir + "PdfSaveOptions.EmbedFullFonts.pdf").Length)); else Assert.That(25000, Is.AtLeast(new FileInfo(ArtifactsDir + "PdfSaveOptions.EmbedFullFonts.pdf").Length)); // Restore the original font sources. FontSettings.DefaultInstance.SetFontsSources(originalFontsSources); //ExEnd #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.EmbedFullFonts.pdf"); Aspose.Pdf.Text.Font[] pdfDocFonts = pdfDocument.FontUtilities.GetAllFonts(); Assert.AreEqual("ArialMT", pdfDocFonts[0].FontName); Assert.AreNotEqual(embedFullFonts, pdfDocFonts[0].IsSubset); Assert.AreEqual("Arvo", pdfDocFonts[1].FontName); Assert.AreNotEqual(embedFullFonts, pdfDocFonts[1].IsSubset); #endif } [TestCase(PdfFontEmbeddingMode.EmbedAll)] [TestCase(PdfFontEmbeddingMode.EmbedNone)] [TestCase(PdfFontEmbeddingMode.EmbedNonstandard)] public void EmbedWindowsFonts(PdfFontEmbeddingMode pdfFontEmbeddingMode) { //ExStart //ExFor:PdfSaveOptions.FontEmbeddingMode //ExFor:PdfFontEmbeddingMode //ExSummary:Shows how to set Aspose.Words to skip embedding Arial and Times New Roman fonts into a PDF document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // "Arial" is a standard font, and "Courier New" is a nonstandard font. builder.Font.Name = "Arial"; builder.Writeln("Hello world!"); builder.Font.Name = "Courier New"; builder.Writeln("The quick brown fox jumps over the lazy dog."); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "EmbedFullFonts" property to "true" to embed every glyph of every embedded font in the output PDF. options.EmbedFullFonts = true; // Set the "FontEmbeddingMode" property to "EmbedAll" to embed all fonts in the output PDF. // Set the "FontEmbeddingMode" property to "EmbedNonstandard" to only allow nonstandard fonts' embedding in the output PDF. // Set the "FontEmbeddingMode" property to "EmbedNone" to not embed any fonts in the output PDF. options.FontEmbeddingMode = pdfFontEmbeddingMode; doc.Save(ArtifactsDir + "PdfSaveOptions.EmbedWindowsFonts.pdf", options); switch (pdfFontEmbeddingMode) { case PdfFontEmbeddingMode.EmbedAll: Assert.That(1000000, Is.LessThan(new FileInfo(ArtifactsDir + "PdfSaveOptions.EmbedWindowsFonts.pdf").Length)); break; case PdfFontEmbeddingMode.EmbedNonstandard: Assert.That(480000, Is.LessThan(new FileInfo(ArtifactsDir + "PdfSaveOptions.EmbedWindowsFonts.pdf").Length)); break; case PdfFontEmbeddingMode.EmbedNone: Assert.That(4217, Is.AtLeast(new FileInfo(ArtifactsDir + "PdfSaveOptions.EmbedWindowsFonts.pdf").Length)); break; } //ExEnd #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.EmbedWindowsFonts.pdf"); Aspose.Pdf.Text.Font[] pdfDocFonts = pdfDocument.FontUtilities.GetAllFonts(); Assert.AreEqual("ArialMT", pdfDocFonts[0].FontName); Assert.AreEqual(pdfFontEmbeddingMode == PdfFontEmbeddingMode.EmbedAll, pdfDocFonts[0].IsEmbedded); Assert.AreEqual("CourierNewPSMT", pdfDocFonts[1].FontName); Assert.AreEqual(pdfFontEmbeddingMode == PdfFontEmbeddingMode.EmbedAll || pdfFontEmbeddingMode == PdfFontEmbeddingMode.EmbedNonstandard, pdfDocFonts[1].IsEmbedded); #endif } [TestCase(false)] [TestCase(true)] public void EmbedCoreFonts(bool useCoreFonts) { //ExStart //ExFor:PdfSaveOptions.UseCoreFonts //ExSummary:Shows how enable/disable PDF Type 1 font substitution. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Font.Name = "Arial"; builder.Writeln("Hello world!"); builder.Font.Name = "Courier New"; builder.Writeln("The quick brown fox jumps over the lazy dog."); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "UseCoreFonts" property to "true" to replace some fonts, // including the two fonts in our document, with their PDF Type 1 equivalents. // Set the "UseCoreFonts" property to "false" to not apply PDF Type 1 fonts. options.UseCoreFonts = useCoreFonts; doc.Save(ArtifactsDir + "PdfSaveOptions.EmbedCoreFonts.pdf", options); if (useCoreFonts) Assert.That(3000, Is.AtLeast(new FileInfo(ArtifactsDir + "PdfSaveOptions.EmbedCoreFonts.pdf").Length)); else Assert.That(30000, Is.LessThan(new FileInfo(ArtifactsDir + "PdfSaveOptions.EmbedCoreFonts.pdf").Length)); //ExEnd #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.EmbedCoreFonts.pdf"); Aspose.Pdf.Text.Font[] pdfDocFonts = pdfDocument.FontUtilities.GetAllFonts(); if (useCoreFonts) { Assert.AreEqual("Helvetica", pdfDocFonts[0].FontName); Assert.AreEqual("Courier", pdfDocFonts[1].FontName); } else { Assert.AreEqual("ArialMT", pdfDocFonts[0].FontName); Assert.AreEqual("CourierNewPSMT", pdfDocFonts[1].FontName); } Assert.AreNotEqual(useCoreFonts, pdfDocFonts[0].IsEmbedded); Assert.AreNotEqual(useCoreFonts, pdfDocFonts[1].IsEmbedded); #endif } [TestCase(false)] [TestCase(true)] public void AdditionalTextPositioning(bool applyAdditionalTextPositioning) { //ExStart //ExFor:PdfSaveOptions.AdditionalTextPositioning //ExSummary:Show how to write additional text positioning operators. Document doc = new Document(MyDir + "Text positioning operators.docx"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions saveOptions = new PdfSaveOptions { TextCompression = PdfTextCompression.None, // Set the "AdditionalTextPositioning" property to "true" to attempt to fix incorrect // element positioning in the output PDF, should there be any, at the cost of increased file size. // Set the "AdditionalTextPositioning" property to "false" to render the document as usual. AdditionalTextPositioning = applyAdditionalTextPositioning }; doc.Save(ArtifactsDir + "PdfSaveOptions.AdditionalTextPositioning.pdf", saveOptions); //ExEnd #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.AdditionalTextPositioning.pdf"); TextFragmentAbsorber textAbsorber = new TextFragmentAbsorber(); pdfDocument.Pages[1].Accept(textAbsorber); SetGlyphsPositionShowText tjOperator = (SetGlyphsPositionShowText) textAbsorber.TextFragments[1].Page.Contents[85]; if (applyAdditionalTextPositioning) { Assert.That(100000, Is.LessThan(new FileInfo(ArtifactsDir + "PdfSaveOptions.AdditionalTextPositioning.pdf").Length)); Assert.AreEqual( "[0 (S) 0 (a) 0 (m) 0 (s) 0 (t) 0 (a) -1 (g) 1 (,) 0 ( ) 0 (1) 0 (0) 0 (.) 0 ( ) 0 (N) 0 (o) 0 (v) 0 (e) 0 (m) 0 (b) 0 (e) 0 (r) -1 ( ) 1 (2) -1 (0) 0 (1) 0 (8)] TJ", tjOperator.ToString()); } else { Assert.That(97000, Is.LessThan(new FileInfo(ArtifactsDir + "PdfSaveOptions.AdditionalTextPositioning.pdf").Length)); Assert.AreEqual("[(Samsta) -1 (g) 1 (, 10. November) -1 ( ) 1 (2) -1 (018)] TJ", tjOperator.ToString()); } #endif } [TestCase(false, Category = "SkipMono")] [TestCase(true, Category = "SkipMono")] public void SaveAsPdfBookFold(bool renderTextAsBookfold) { //ExStart //ExFor:PdfSaveOptions.UseBookFoldPrintingSettings //ExSummary:Shows how to save a document to the PDF format in the form of a book fold. Document doc = new Document(MyDir + "Paragraphs.docx"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "UseBookFoldPrintingSettings" property to "true" to arrange the contents // in the output PDF in a way that helps us use it to make a booklet. // Set the "UseBookFoldPrintingSettings" property to "false" to render the PDF normally. options.UseBookFoldPrintingSettings = renderTextAsBookfold; // If we are rendering the document as a booklet, we must set the "MultiplePages" // properties of the page setup objects of all sections to "MultiplePagesType.BookFoldPrinting". if (renderTextAsBookfold) foreach (Section s in doc.Sections) { s.PageSetup.MultiplePages = MultiplePagesType.BookFoldPrinting; } // Once we print this document on both sides of the pages, we can fold all the pages down the middle at once, // and the contents will line up in a way that creates a booklet. doc.Save(ArtifactsDir + "PdfSaveOptions.SaveAsPdfBookFold.pdf", options); //ExEnd #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.SaveAsPdfBookFold.pdf"); TextAbsorber textAbsorber = new TextAbsorber(); pdfDocument.Pages.Accept(textAbsorber); if (renderTextAsBookfold) { Assert.True(textAbsorber.Text.IndexOf("Heading #1", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #2", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #2", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #3", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #3", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #4", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #4", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #5", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #5", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #6", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #6", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #7", StringComparison.Ordinal)); Assert.False(textAbsorber.Text.IndexOf("Heading #7", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #8", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #8", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #9", StringComparison.Ordinal)); Assert.False(textAbsorber.Text.IndexOf("Heading #9", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #10", StringComparison.Ordinal)); } else { Assert.True(textAbsorber.Text.IndexOf("Heading #1", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #2", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #2", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #3", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #3", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #4", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #4", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #5", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #5", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #6", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #6", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #7", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #7", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #8", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #8", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #9", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #9", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #10", StringComparison.Ordinal)); } #endif } [Test] public void ZoomBehaviour() { //ExStart //ExFor:PdfSaveOptions.ZoomBehavior //ExFor:PdfSaveOptions.ZoomFactor //ExFor:PdfZoomBehavior //ExSummary:Shows how to set the default zooming that a reader applies when opening a rendered PDF document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Writeln("Hello world!"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. // Set the "ZoomBehavior" property to "PdfZoomBehavior.ZoomFactor" to get a PDF reader to // apply a percentage-based zoom factor when we open the document with it. // Set the "ZoomFactor" property to "25" to give the zoom factor a value of 25%. PdfSaveOptions options = new PdfSaveOptions { ZoomBehavior = PdfZoomBehavior.ZoomFactor, ZoomFactor = 25 }; // When we open this document using a reader such as Adobe Acrobat, we will see the document scaled at 1/4 of its actual size. doc.Save(ArtifactsDir + "PdfSaveOptions.ZoomBehaviour.pdf", options); //ExEnd #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.ZoomBehaviour.pdf"); GoToAction action = (GoToAction)pdfDocument.OpenAction; Assert.AreEqual(0.25d, (action.Destination as XYZExplicitDestination).Zoom); #endif } [TestCase(PdfPageMode.FullScreen)] [TestCase(PdfPageMode.UseThumbs)] [TestCase(PdfPageMode.UseOC)] [TestCase(PdfPageMode.UseOutlines)] [TestCase(PdfPageMode.UseNone)] public void PageMode(PdfPageMode pageMode) { //ExStart //ExFor:PdfSaveOptions.PageMode //ExFor:PdfPageMode //ExSummary:Shows how to set instructions for some PDF readers to follow when opening an output document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Writeln("Hello world!"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "PageMode" property to "PdfPageMode.FullScreen" to get the PDF reader to open the saved // document in full-screen mode, which takes over the monitor's display and has no controls visible. // Set the "PageMode" property to "PdfPageMode.UseThumbs" to get the PDF reader to display a separate panel // with a thumbnail for each page in the document. // Set the "PageMode" property to "PdfPageMode.UseOC" to get the PDF reader to display a separate panel // that allows us to work with any layers present in the document. // Set the "PageMode" property to "PdfPageMode.UseOutlines" to get the PDF reader // also to display the outline, if possible. // Set the "PageMode" property to "PdfPageMode.UseNone" to get the PDF reader to display just the document itself. options.PageMode = pageMode; doc.Save(ArtifactsDir + "PdfSaveOptions.PageMode.pdf", options); //ExEnd string docLocaleName = new CultureInfo(doc.Styles.DefaultFont.LocaleId).Name; switch (pageMode) { case PdfPageMode.FullScreen: TestUtil.FileContainsString( $"<</Type /Catalog/Pages 3 0 R/PageMode /FullScreen/Lang({docLocaleName})/Metadata 4 0 R>>\r\n", ArtifactsDir + "PdfSaveOptions.PageMode.pdf"); break; case PdfPageMode.UseThumbs: TestUtil.FileContainsString( $"<</Type /Catalog/Pages 3 0 R/PageMode /UseThumbs/Lang({docLocaleName})/Metadata 4 0 R>>", ArtifactsDir + "PdfSaveOptions.PageMode.pdf"); break; case PdfPageMode.UseOC: TestUtil.FileContainsString( $"<</Type /Catalog/Pages 3 0 R/PageMode /UseOC/Lang({docLocaleName})/Metadata 4 0 R>>\r\n", ArtifactsDir + "PdfSaveOptions.PageMode.pdf"); break; case PdfPageMode.UseOutlines: case PdfPageMode.UseNone: TestUtil.FileContainsString($"<</Type /Catalog/Pages 3 0 R/Lang({docLocaleName})/Metadata 4 0 R>>\r\n", ArtifactsDir + "PdfSaveOptions.PageMode.pdf"); break; } #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.PageMode.pdf"); switch (pageMode) { case PdfPageMode.UseNone: case PdfPageMode.UseOutlines: Assert.AreEqual(Aspose.Pdf.PageMode.UseNone, pdfDocument.PageMode); break; case PdfPageMode.UseThumbs: Assert.AreEqual(Aspose.Pdf.PageMode.UseThumbs, pdfDocument.PageMode); break; case PdfPageMode.FullScreen: Assert.AreEqual(Aspose.Pdf.PageMode.FullScreen, pdfDocument.PageMode); break; case PdfPageMode.UseOC: Assert.AreEqual(Aspose.Pdf.PageMode.UseOC, pdfDocument.PageMode); break; } #endif } [TestCase(false)] [TestCase(true)] public void NoteHyperlinks(bool createNoteHyperlinks) { //ExStart //ExFor:PdfSaveOptions.CreateNoteHyperlinks //ExSummary:Shows how to make footnotes and endnotes function as hyperlinks. Document doc = new Document(MyDir + "Footnotes and endnotes.docx"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "CreateNoteHyperlinks" property to "true" to turn all footnote/endnote symbols // in the text act as links that, upon clicking, take us to their respective footnotes/endnotes. // Set the "CreateNoteHyperlinks" property to "false" not to have footnote/endnote symbols link to anything. options.CreateNoteHyperlinks = createNoteHyperlinks; doc.Save(ArtifactsDir + "PdfSaveOptions.NoteHyperlinks.pdf", options); //ExEnd if (createNoteHyperlinks) { TestUtil.FileContainsString( "<</Type /Annot/Subtype /Link/Rect [157.80099487 720.90106201 159.35600281 733.55004883]/BS <</Type/Border/S/S/W 0>>/Dest[5 0 R /XYZ 85 677 0]>>", ArtifactsDir + "PdfSaveOptions.NoteHyperlinks.pdf"); TestUtil.FileContainsString( "<</Type /Annot/Subtype /Link/Rect [202.16900635 720.90106201 206.06201172 733.55004883]/BS <</Type/Border/S/S/W 0>>/Dest[5 0 R /XYZ 85 79 0]>>", ArtifactsDir + "PdfSaveOptions.NoteHyperlinks.pdf"); TestUtil.FileContainsString( "<</Type /Annot/Subtype /Link/Rect [212.23199463 699.2510376 215.34199524 711.90002441]/BS <</Type/Border/S/S/W 0>>/Dest[5 0 R /XYZ 85 654 0]>>", ArtifactsDir + "PdfSaveOptions.NoteHyperlinks.pdf"); TestUtil.FileContainsString( "<</Type /Annot/Subtype /Link/Rect [258.15499878 699.2510376 262.04800415 711.90002441]/BS <</Type/Border/S/S/W 0>>/Dest[5 0 R /XYZ 85 68 0]>>", ArtifactsDir + "PdfSaveOptions.NoteHyperlinks.pdf"); TestUtil.FileContainsString( "<</Type /Annot/Subtype /Link/Rect [85.05000305 68.19904327 88.66500092 79.69804382]/BS <</Type/Border/S/S/W 0>>/Dest[5 0 R /XYZ 202 733 0]>>", ArtifactsDir + "PdfSaveOptions.NoteHyperlinks.pdf"); TestUtil.FileContainsString( "<</Type /Annot/Subtype /Link/Rect [85.05000305 56.70004272 88.66500092 68.19904327]/BS <</Type/Border/S/S/W 0>>/Dest[5 0 R /XYZ 258 711 0]>>", ArtifactsDir + "PdfSaveOptions.NoteHyperlinks.pdf"); TestUtil.FileContainsString( "<</Type /Annot/Subtype /Link/Rect [85.05000305 666.10205078 86.4940033 677.60107422]/BS <</Type/Border/S/S/W 0>>/Dest[5 0 R /XYZ 157 733 0]>>", ArtifactsDir + "PdfSaveOptions.NoteHyperlinks.pdf"); TestUtil.FileContainsString( "<</Type /Annot/Subtype /Link/Rect [85.05000305 643.10406494 87.93800354 654.60308838]/BS <</Type/Border/S/S/W 0>>/Dest[5 0 R /XYZ 212 711 0]>>", ArtifactsDir + "PdfSaveOptions.NoteHyperlinks.pdf"); } else { if (!IsRunningOnMono()) Assert.Throws<AssertionException>(() => TestUtil.FileContainsString("<</Type /Annot/Subtype /Link/Rect", ArtifactsDir + "PdfSaveOptions.NoteHyperlinks.pdf")); } #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.NoteHyperlinks.pdf"); Page page = pdfDocument.Pages[1]; AnnotationSelector annotationSelector = new AnnotationSelector(new LinkAnnotation(page, Rectangle.Trivial)); page.Accept(annotationSelector); List<LinkAnnotation> linkAnnotations = annotationSelector.Selected.Cast<LinkAnnotation>().ToList(); if (createNoteHyperlinks) { Assert.AreEqual(8, linkAnnotations.Count(a => a.AnnotationType == AnnotationType.Link)); Assert.AreEqual("1 XYZ 85 677 0", linkAnnotations[0].Destination.ToString()); Assert.AreEqual("1 XYZ 85 79 0", linkAnnotations[1].Destination.ToString()); Assert.AreEqual("1 XYZ 85 654 0", linkAnnotations[2].Destination.ToString()); Assert.AreEqual("1 XYZ 85 68 0", linkAnnotations[3].Destination.ToString()); Assert.AreEqual("1 XYZ 202 733 0", linkAnnotations[4].Destination.ToString()); Assert.AreEqual("1 XYZ 258 711 0", linkAnnotations[5].Destination.ToString()); Assert.AreEqual("1 XYZ 157 733 0", linkAnnotations[6].Destination.ToString()); Assert.AreEqual("1 XYZ 212 711 0", linkAnnotations[7].Destination.ToString()); } else { Assert.AreEqual(0, annotationSelector.Selected.Count); } #endif } [TestCase(PdfCustomPropertiesExport.None)] [TestCase(PdfCustomPropertiesExport.Standard)] [TestCase(PdfCustomPropertiesExport.Metadata)] public void CustomPropertiesExport(PdfCustomPropertiesExport pdfCustomPropertiesExportMode) { //ExStart //ExFor:PdfCustomPropertiesExport //ExFor:PdfSaveOptions.CustomPropertiesExport //ExSummary:Shows how to export custom properties while converting a document to PDF. Document doc = new Document(); doc.CustomDocumentProperties.Add("Company", "My value"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "CustomPropertiesExport" property to "PdfCustomPropertiesExport.None" to discard // custom document properties as we save the document to .PDF. // Set the "CustomPropertiesExport" property to "PdfCustomPropertiesExport.Standard" // to preserve custom properties within the output PDF document. // Set the "CustomPropertiesExport" property to "PdfCustomPropertiesExport.Metadata" // to preserve custom properties in an XMP packet. options.CustomPropertiesExport = pdfCustomPropertiesExportMode; doc.Save(ArtifactsDir + "PdfSaveOptions.CustomPropertiesExport.pdf", options); //ExEnd switch (pdfCustomPropertiesExportMode) { case PdfCustomPropertiesExport.None: if (!IsRunningOnMono()) { Assert.Throws<AssertionException>(() => TestUtil.FileContainsString( doc.CustomDocumentProperties[0].Name, ArtifactsDir + "PdfSaveOptions.CustomPropertiesExport.pdf")); Assert.Throws<AssertionException>(() => TestUtil.FileContainsString( "<</Type /Metadata/Subtype /XML/Length 8 0 R/Filter /FlateDecode>>", ArtifactsDir + "PdfSaveOptions.CustomPropertiesExport.pdf")); } break; case PdfCustomPropertiesExport.Standard: TestUtil.FileContainsString( "<</Creator(þÿ\0A\0s\0p\0o\0s\0e\0.\0W\0o\0r\0d\0s)/Producer(þÿ\0A\0s\0p\0o\0s\0e\0.\0W\0o\0r\0d\0s\0 \0f\0o\0r\0", ArtifactsDir + "PdfSaveOptions.CustomPropertiesExport.pdf"); TestUtil.FileContainsString("/Company (þÿ\0M\0y\0 \0v\0a\0l\0u\0e)>>", ArtifactsDir + "PdfSaveOptions.CustomPropertiesExport.pdf"); break; case PdfCustomPropertiesExport.Metadata: TestUtil.FileContainsString("<</Type /Metadata/Subtype /XML/Length 8 0 R/Filter /FlateDecode>>", ArtifactsDir + "PdfSaveOptions.CustomPropertiesExport.pdf"); break; } #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.CustomPropertiesExport.pdf"); Assert.AreEqual("Aspose.Words", pdfDocument.Info.Creator); Assert.True(pdfDocument.Info.Producer.StartsWith("Aspose.Words")); switch (pdfCustomPropertiesExportMode) { case PdfCustomPropertiesExport.None: Assert.AreEqual(2, pdfDocument.Info.Count); Assert.AreEqual(3, pdfDocument.Metadata.Count); break; case PdfCustomPropertiesExport.Metadata: Assert.AreEqual(2, pdfDocument.Info.Count); Assert.AreEqual(4, pdfDocument.Metadata.Count); Assert.AreEqual("Aspose.Words", pdfDocument.Metadata["xmp:CreatorTool"].ToString()); Assert.AreEqual("Company", pdfDocument.Metadata["custprops:Property1"].ToString()); break; case PdfCustomPropertiesExport.Standard: Assert.AreEqual(3, pdfDocument.Info.Count); Assert.AreEqual(3, pdfDocument.Metadata.Count); Assert.AreEqual("My value", pdfDocument.Info["Company"]); break; } #endif } [TestCase(DmlEffectsRenderingMode.None)] [TestCase(DmlEffectsRenderingMode.Simplified)] [TestCase(DmlEffectsRenderingMode.Fine)] public void DrawingMLEffects(DmlEffectsRenderingMode effectsRenderingMode) { //ExStart //ExFor:DmlRenderingMode //ExFor:DmlEffectsRenderingMode //ExFor:PdfSaveOptions.DmlEffectsRenderingMode //ExFor:SaveOptions.DmlEffectsRenderingMode //ExFor:SaveOptions.DmlRenderingMode //ExSummary:Shows how to configure the rendering quality of DrawingML effects in a document as we save it to PDF. Document doc = new Document(MyDir + "DrawingML shape effects.docx"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "DmlEffectsRenderingMode" property to "DmlEffectsRenderingMode.None" to discard all DrawingML effects. // Set the "DmlEffectsRenderingMode" property to "DmlEffectsRenderingMode.Simplified" // to render a simplified version of DrawingML effects. // Set the "DmlEffectsRenderingMode" property to "DmlEffectsRenderingMode.Fine" to // render DrawingML effects with more accuracy and also with more processing cost. options.DmlEffectsRenderingMode = effectsRenderingMode; Assert.AreEqual(DmlRenderingMode.DrawingML, options.DmlRenderingMode); doc.Save(ArtifactsDir + "PdfSaveOptions.DrawingMLEffects.pdf", options); //ExEnd #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.DrawingMLEffects.pdf"); ImagePlacementAbsorber imagePlacementAbsorber = new ImagePlacementAbsorber(); imagePlacementAbsorber.Visit(pdfDocument.Pages[1]); TableAbsorber tableAbsorber = new TableAbsorber(); tableAbsorber.Visit(pdfDocument.Pages[1]); switch (effectsRenderingMode) { case DmlEffectsRenderingMode.None: case DmlEffectsRenderingMode.Simplified: TestUtil.FileContainsString("5 0 obj\r\n" + "<</Type /Page/Parent 3 0 R/Contents 6 0 R/MediaBox [0 0 612 792]/Resources<</Font<</FAAAAI 8 0 R>>>>/Group <</Type/Group/S/Transparency/CS/DeviceRGB>>>>", ArtifactsDir + "PdfSaveOptions.DrawingMLEffects.pdf"); Assert.AreEqual(0, imagePlacementAbsorber.ImagePlacements.Count); Assert.AreEqual(28, tableAbsorber.TableList.Count); break; case DmlEffectsRenderingMode.Fine: TestUtil.FileContainsString( "5 0 obj\r\n<</Type /Page/Parent 3 0 R/Contents 6 0 R/MediaBox [0 0 612 792]/Resources<</Font<</FAAAAI 8 0 R>>/XObject<</X1 10 0 R/X2 11 0 R/X3 12 0 R/X4 13 0 R>>>>/Group <</Type/Group/S/Transparency/CS/DeviceRGB>>>>", ArtifactsDir + "PdfSaveOptions.DrawingMLEffects.pdf"); Assert.AreEqual(21, imagePlacementAbsorber.ImagePlacements.Count); Assert.AreEqual(4, tableAbsorber.TableList.Count); break; } #endif } [TestCase(DmlRenderingMode.Fallback)] [TestCase(DmlRenderingMode.DrawingML)] public void DrawingMLFallback(DmlRenderingMode dmlRenderingMode) { //ExStart //ExFor:DmlRenderingMode //ExFor:SaveOptions.DmlRenderingMode //ExSummary:Shows how to render fallback shapes when saving to PDF. Document doc = new Document(MyDir + "DrawingML shape fallbacks.docx"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "DmlRenderingMode" property to "DmlRenderingMode.Fallback" // to substitute DML shapes with their fallback shapes. // Set the "DmlRenderingMode" property to "DmlRenderingMode.DrawingML" // to render the DML shapes themselves. options.DmlRenderingMode = dmlRenderingMode; doc.Save(ArtifactsDir + "PdfSaveOptions.DrawingMLFallback.pdf", options); //ExEnd switch (dmlRenderingMode) { case DmlRenderingMode.DrawingML: TestUtil.FileContainsString( "<</Type /Page/Parent 3 0 R/Contents 6 0 R/MediaBox [0 0 612 792]/Resources<</Font<</FAAAAI 8 0 R/FAAABB 11 0 R>>>>/Group <</Type/Group/S/Transparency/CS/DeviceRGB>>>>", ArtifactsDir + "PdfSaveOptions.DrawingMLFallback.pdf"); break; case DmlRenderingMode.Fallback: TestUtil.FileContainsString( "5 0 obj\r\n<</Type /Page/Parent 3 0 R/Contents 6 0 R/MediaBox [0 0 612 792]/Resources<</Font<</FAAAAI 8 0 R/FAAABD 13 0 R>>/ExtGState<</GS1 10 0 R/GS2 11 0 R>>>>/Group <</Type/Group/S/Transparency/CS/DeviceRGB>>>>", ArtifactsDir + "PdfSaveOptions.DrawingMLFallback.pdf"); break; } #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.DrawingMLFallback.pdf"); ImagePlacementAbsorber imagePlacementAbsorber = new ImagePlacementAbsorber(); imagePlacementAbsorber.Visit(pdfDocument.Pages[1]); TableAbsorber tableAbsorber = new TableAbsorber(); tableAbsorber.Visit(pdfDocument.Pages[1]); switch (dmlRenderingMode) { case DmlRenderingMode.DrawingML: Assert.AreEqual(6, tableAbsorber.TableList.Count); break; case DmlRenderingMode.Fallback: Assert.AreEqual(15, tableAbsorber.TableList.Count); break; } #endif } [TestCase(false)] [TestCase(true)] public void ExportDocumentStructure(bool exportDocumentStructure) { //ExStart //ExFor:PdfSaveOptions.ExportDocumentStructure //ExSummary:Shows how to preserve document structure elements, which can assist in programmatically interpreting our document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.ParagraphFormat.Style = doc.Styles["Heading 1"]; builder.Writeln("Hello world!"); builder.ParagraphFormat.Style = doc.Styles["Normal"]; builder.Write( "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "ExportDocumentStructure" property to "true" to make the document structure, such tags, available via the // "Content" navigation pane of Adobe Acrobat at the cost of increased file size. // Set the "ExportDocumentStructure" property to "false" to not export the document structure. options.ExportDocumentStructure = exportDocumentStructure; // Suppose we export document structure while saving this document. In that case, // we can open it using Adobe Acrobat and find tags for elements such as the heading // and the next paragraph via "View" -> "Show/Hide" -> "Navigation panes" -> "Tags". doc.Save(ArtifactsDir + "PdfSaveOptions.ExportDocumentStructure.pdf", options); //ExEnd if (exportDocumentStructure) { TestUtil.FileContainsString("5 0 obj\r\n" + "<</Type /Page/Parent 3 0 R/Contents 6 0 R/MediaBox [0 0 612 792]/Resources<</Font<</FAAAAI 8 0 R/FAAABC 12 0 R>>/ExtGState<</GS1 10 0 R/GS2 14 0 R>>>>/Group <</Type/Group/S/Transparency/CS/DeviceRGB>>/StructParents 0/Tabs /S>>", ArtifactsDir + "PdfSaveOptions.ExportDocumentStructure.pdf"); } else { TestUtil.FileContainsString("5 0 obj\r\n" + "<</Type /Page/Parent 3 0 R/Contents 6 0 R/MediaBox [0 0 612 792]/Resources<</Font<</FAAAAI 8 0 R/FAAABB 11 0 R>>>>/Group <</Type/Group/S/Transparency/CS/DeviceRGB>>>>", ArtifactsDir + "PdfSaveOptions.ExportDocumentStructure.pdf"); } } #if NET48 || JAVA [TestCase(false, Category = "SkipMono")] [TestCase(true, Category = "SkipMono")] public void PreblendImages(bool preblendImages) { //ExStart //ExFor:PdfSaveOptions.PreblendImages //ExSummary:Shows how to preblend images with transparent backgrounds while saving a document to PDF. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); Image img = Image.FromFile(ImageDir + "Transparent background logo.png"); builder.InsertImage(img); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "PreblendImages" property to "true" to preblend transparent images // with a background, which may reduce artifacts. // Set the "PreblendImages" property to "false" to render transparent images normally. options.PreblendImages = preblendImages; doc.Save(ArtifactsDir + "PdfSaveOptions.PreblendImages.pdf", options); //ExEnd Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.PreblendImages.pdf"); XImage image = pdfDocument.Pages[1].Resources.Images[1]; using (MemoryStream stream = new MemoryStream()) { image.Save(stream); if (preblendImages) { TestUtil.FileContainsString("11 0 obj\r\n20849 ", ArtifactsDir + "PdfSaveOptions.PreblendImages.pdf"); Assert.AreEqual(17898, stream.Length); } else { TestUtil.FileContainsString("11 0 obj\r\n19289 ", ArtifactsDir + "PdfSaveOptions.PreblendImages.pdf"); Assert.AreEqual(19216, stream.Length); } } } [TestCase(false)] [TestCase(true)] public void InterpolateImages(bool interpolateImages) { //ExStart //ExFor:PdfSaveOptions.InterpolateImages //ExSummary:Shows how to perform interpolation on images while saving a document to PDF. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); Image img = Image.FromFile(ImageDir + "Transparent background logo.png"); builder.InsertImage(img); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions saveOptions = new PdfSaveOptions(); // Set the "InterpolateImages" property to "true" to get the reader that opens this document to interpolate images. // Their resolution should be lower than that of the device that is displaying the document. // Set the "InterpolateImages" property to "false" to make it so that the reader does not apply any interpolation. saveOptions.InterpolateImages = interpolateImages; // When we open this document with a reader such as Adobe Acrobat, we will need to zoom in on the image // to see the interpolation effect if we saved the document with it enabled. doc.Save(ArtifactsDir + "PdfSaveOptions.InterpolateImages.pdf", saveOptions); //ExEnd if (interpolateImages) { TestUtil.FileContainsString("7 0 obj\r\n" + "<</Type /XObject/Subtype /Image/Width 400/Height 400/ColorSpace /DeviceRGB/BitsPerComponent 8/SMask 10 0 R/Interpolate true/Length 11 0 R/Filter /FlateDecode>>", ArtifactsDir + "PdfSaveOptions.InterpolateImages.pdf"); } else { TestUtil.FileContainsString("7 0 obj\r\n" + "<</Type /XObject/Subtype /Image/Width 400/Height 400/ColorSpace /DeviceRGB/BitsPerComponent 8/SMask 10 0 R/Length 11 0 R/Filter /FlateDecode>>", ArtifactsDir + "PdfSaveOptions.InterpolateImages.pdf"); } } [Test, Category("SkipMono")] public void Dml3DEffectsRenderingModeTest() { Document doc = new Document(MyDir + "DrawingML shape 3D effects.docx"); RenderCallback warningCallback = new RenderCallback(); doc.WarningCallback = warningCallback; PdfSaveOptions saveOptions = new PdfSaveOptions(); saveOptions.Dml3DEffectsRenderingMode = Dml3DEffectsRenderingMode.Advanced; doc.Save(ArtifactsDir + "PdfSaveOptions.Dml3DEffectsRenderingModeTest.pdf", saveOptions); Assert.AreEqual(38, warningCallback.Count); } public class RenderCallback : IWarningCallback { public void Warning(WarningInfo info) { Console.WriteLine($"{info.WarningType}: {info.Description}."); mWarnings.Add(info); } public WarningInfo this[int i] => mWarnings[i]; /// <summary> /// Clears warning collection. /// </summary> public void Clear() { mWarnings.Clear(); } public int Count => mWarnings.Count; /// <summary> /// Returns true if a warning with the specified properties has been generated. /// </summary> public bool Contains(WarningSource source, WarningType type, string description) { return mWarnings.Any(warning => warning.Source == source && warning.WarningType == type && warning.Description == description); } private readonly List<WarningInfo> mWarnings = new List<WarningInfo>(); } #elif NET5_0 [TestCase(false)] [TestCase(true)] public void PreblendImagesNetStandard2(bool preblendImages) { //ExStart //ExFor:PdfSaveOptions.PreblendImages //ExSummary:Shows how to preblend images with transparent backgrounds (.NetStandard 2.0). Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); using (Image image = Image.Decode(ImageDir + "Transparent background logo.png")) builder.InsertImage(image); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "PreblendImages" property to "true" to preblend transparent images // with a background, which may reduce artifacts. // Set the "PreblendImages" property to "false" to render transparent images normally. options.PreblendImages = preblendImages; doc.Save(ArtifactsDir + "PdfSaveOptions.PreblendImagesNetStandard2.pdf", options); //ExEnd Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.PreblendImagesNetStandard2.pdf"); XImage xImage = pdfDocument.Pages[1].Resources.Images[1]; using (MemoryStream stream = new MemoryStream()) { xImage.Save(stream); if (preblendImages) { TestUtil.FileContainsString("11 0 obj\r\n20849 ", ArtifactsDir + "PdfSaveOptions.PreblendImagesNetStandard2.pdf"); Assert.AreEqual(17898, stream.Length); } else { TestUtil.FileContainsString("11 0 obj\r\n20266 ", ArtifactsDir + "PdfSaveOptions.PreblendImagesNetStandard2.pdf"); Assert.AreEqual(19135, stream.Length); } } } [TestCase(false)] [TestCase(true)] public void InterpolateImagesNetStandard2(bool interpolateImages) { //ExStart //ExFor:PdfSaveOptions.InterpolateImages //ExSummary:Shows how to improve the quality of an image in the rendered documents (.NetStandard 2.0). Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); using (Image image = Image.Decode(ImageDir + "Transparent background logo.png")) builder.InsertImage(image); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions saveOptions = new PdfSaveOptions(); // Set the "InterpolateImages" property to "true" to get the reader that opens this document to interpolate images. // Their resolution should be lower than that of the device that is displaying the document. // Set the "InterpolateImages" property to "false" to make it so that the reader does not apply any interpolation. saveOptions.InterpolateImages = interpolateImages; // When we open this document with a reader such as Adobe Acrobat, we will need to zoom in on the image // to see the interpolation effect if we saved the document with it enabled. doc.Save(ArtifactsDir + "PdfSaveOptions.InterpolateImagesNetStandard2.pdf", saveOptions); //ExEnd if (interpolateImages) { TestUtil.FileContainsString("7 0 obj\r\n" + "<</Type /XObject/Subtype /Image/Width 400/Height 400/ColorSpace /DeviceRGB/BitsPerComponent 8/SMask 10 0 R/Interpolate true/Length 11 0 R/Filter /FlateDecode>>", ArtifactsDir + "PdfSaveOptions.InterpolateImagesNetStandard2.pdf"); } else { TestUtil.FileContainsString("7 0 obj\r\n" + "<</Type /XObject/Subtype /Image/Width 400/Height 400/ColorSpace /DeviceRGB/BitsPerComponent 8/SMask 10 0 R/Length 11 0 R/Filter /FlateDecode>>", ArtifactsDir + "PdfSaveOptions.InterpolateImagesNetStandard2.pdf"); } } #endif [Test] public void PdfDigitalSignature() { //ExStart //ExFor:PdfDigitalSignatureDetails //ExFor:PdfDigitalSignatureDetails.#ctor //ExFor:PdfDigitalSignatureDetails.#ctor(CertificateHolder, String, String, DateTime) //ExFor:PdfDigitalSignatureDetails.HashAlgorithm //ExFor:PdfDigitalSignatureDetails.Location //ExFor:PdfDigitalSignatureDetails.Reason //ExFor:PdfDigitalSignatureDetails.SignatureDate //ExFor:PdfDigitalSignatureHashAlgorithm //ExFor:PdfSaveOptions.DigitalSignatureDetails //ExSummary:Shows how to sign a generated PDF document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Writeln("Contents of signed PDF."); CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Configure the "DigitalSignatureDetails" object of the "SaveOptions" object to // digitally sign the document as we render it with the "Save" method. DateTime signingTime = DateTime.Now; options.DigitalSignatureDetails = new PdfDigitalSignatureDetails(certificateHolder, "Test Signing", "My Office", signingTime); options.DigitalSignatureDetails.HashAlgorithm = PdfDigitalSignatureHashAlgorithm.Sha256; Assert.AreEqual("Test Signing", options.DigitalSignatureDetails.Reason); Assert.AreEqual("My Office", options.DigitalSignatureDetails.Location); Assert.AreEqual(signingTime.ToUniversalTime(), options.DigitalSignatureDetails.SignatureDate.ToUniversalTime()); doc.Save(ArtifactsDir + "PdfSaveOptions.PdfDigitalSignature.pdf", options); //ExEnd TestUtil.FileContainsString("7 0 obj\r\n" + "<</Type /Annot/Subtype /Widget/Rect [0 0 0 0]/FT /Sig/DR <<>>/F 132/V 8 0 R/P 5 0 R/T(þÿ\0A\0s\0p\0o\0s\0e\0D\0i\0g\0i\0t\0a\0l\0S\0i\0g\0n\0a\0t\0u\0r\0e)/AP <</N 9 0 R>>>>", ArtifactsDir + "PdfSaveOptions.PdfDigitalSignature.pdf"); Assert.False(FileFormatUtil.DetectFileFormat(ArtifactsDir + "PdfSaveOptions.PdfDigitalSignature.pdf") .HasDigitalSignature); #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.PdfDigitalSignature.pdf"); Assert.False(pdfDocument.Form.SignaturesExist); SignatureField signatureField = (SignatureField)pdfDocument.Form[1]; Assert.AreEqual("AsposeDigitalSignature", signatureField.FullName); Assert.AreEqual("AsposeDigitalSignature", signatureField.PartialName); Assert.AreEqual(typeof(Aspose.Pdf.Forms.PKCS7), signatureField.Signature.GetType()); Assert.AreEqual(DateTime.Today, signatureField.Signature.Date.Date); Assert.AreEqual("þÿ\0M\0o\0r\0z\0a\0l\0.\0M\0e", signatureField.Signature.Authority); Assert.AreEqual("þÿ\0M\0y\0 \0O\0f\0f\0i\0c\0e", signatureField.Signature.Location); Assert.AreEqual("þÿ\0T\0e\0s\0t\0 \0S\0i\0g\0n\0i\0n\0g", signatureField.Signature.Reason); #endif } [Test] public void PdfDigitalSignatureTimestamp() { //ExStart //ExFor:PdfDigitalSignatureDetails.TimestampSettings //ExFor:PdfDigitalSignatureTimestampSettings //ExFor:PdfDigitalSignatureTimestampSettings.#ctor //ExFor:PdfDigitalSignatureTimestampSettings.#ctor(String,String,String) //ExFor:PdfDigitalSignatureTimestampSettings.#ctor(String,String,String,TimeSpan) //ExFor:PdfDigitalSignatureTimestampSettings.Password //ExFor:PdfDigitalSignatureTimestampSettings.ServerUrl //ExFor:PdfDigitalSignatureTimestampSettings.Timeout //ExFor:PdfDigitalSignatureTimestampSettings.UserName //ExSummary:Shows how to sign a saved PDF document digitally and timestamp it. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Writeln("Signed PDF contents."); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Create a digital signature and assign it to our SaveOptions object to sign the document when we save it to PDF. CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw"); options.DigitalSignatureDetails = new PdfDigitalSignatureDetails(certificateHolder, "Test Signing", "Aspose Office", DateTime.Now); // Create a timestamp authority-verified timestamp. options.DigitalSignatureDetails.TimestampSettings = new PdfDigitalSignatureTimestampSettings("https://freetsa.org/tsr", "JohnDoe", "MyPassword"); // The default lifespan of the timestamp is 100 seconds. Assert.AreEqual(100.0d, options.DigitalSignatureDetails.TimestampSettings.Timeout.TotalSeconds); // We can set our timeout period via the constructor. options.DigitalSignatureDetails.TimestampSettings = new PdfDigitalSignatureTimestampSettings("https://freetsa.org/tsr", "JohnDoe", "MyPassword", TimeSpan.FromMinutes(30)); Assert.AreEqual(1800.0d, options.DigitalSignatureDetails.TimestampSettings.Timeout.TotalSeconds); Assert.AreEqual("https://freetsa.org/tsr", options.DigitalSignatureDetails.TimestampSettings.ServerUrl); Assert.AreEqual("JohnDoe", options.DigitalSignatureDetails.TimestampSettings.UserName); Assert.AreEqual("MyPassword", options.DigitalSignatureDetails.TimestampSettings.Password); // The "Save" method will apply our signature to the output document at this time. doc.Save(ArtifactsDir + "PdfSaveOptions.PdfDigitalSignatureTimestamp.pdf", options); //ExEnd Assert.False(FileFormatUtil.DetectFileFormat(ArtifactsDir + "PdfSaveOptions.PdfDigitalSignatureTimestamp.pdf").HasDigitalSignature); TestUtil.FileContainsString("7 0 obj\r\n" + "<</Type /Annot/Subtype /Widget/Rect [0 0 0 0]/FT /Sig/DR <<>>/F 132/V 8 0 R/P 5 0 R/T(þÿ\0A\0s\0p\0o\0s\0e\0D\0i\0g\0i\0t\0a\0l\0S\0i\0g\0n\0a\0t\0u\0r\0e)/AP <</N 9 0 R>>>>", ArtifactsDir + "PdfSaveOptions.PdfDigitalSignatureTimestamp.pdf"); #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.PdfDigitalSignatureTimestamp.pdf"); Assert.False(pdfDocument.Form.SignaturesExist); SignatureField signatureField = (SignatureField)pdfDocument.Form[1]; Assert.AreEqual("AsposeDigitalSignature", signatureField.FullName); Assert.AreEqual("AsposeDigitalSignature", signatureField.PartialName); Assert.AreEqual(typeof(Aspose.Pdf.Forms.PKCS7), signatureField.Signature.GetType()); Assert.AreEqual(new DateTime(1, 1, 1, 0, 0, 0), signatureField.Signature.Date); Assert.AreEqual("þÿ\0M\0o\0r\0z\0a\0l\0.\0M\0e", signatureField.Signature.Authority); Assert.AreEqual("þÿ\0A\0s\0p\0o\0s\0e\0 \0O\0f\0f\0i\0c\0e", signatureField.Signature.Location); Assert.AreEqual("þÿ\0T\0e\0s\0t\0 \0S\0i\0g\0n\0i\0n\0g", signatureField.Signature.Reason); Assert.Null(signatureField.Signature.TimestampSettings); #endif } [TestCase(EmfPlusDualRenderingMode.Emf)] [TestCase(EmfPlusDualRenderingMode.EmfPlus)] [TestCase(EmfPlusDualRenderingMode.EmfPlusWithFallback)] public void RenderMetafile(EmfPlusDualRenderingMode renderingMode) { //ExStart //ExFor:EmfPlusDualRenderingMode //ExFor:MetafileRenderingOptions.EmfPlusDualRenderingMode //ExFor:MetafileRenderingOptions.UseEmfEmbeddedToWmf //ExSummary:Shows how to configure Enhanced Windows Metafile-related rendering options when saving to PDF. Document doc = new Document(MyDir + "EMF.docx"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions saveOptions = new PdfSaveOptions(); // Set the "EmfPlusDualRenderingMode" property to "EmfPlusDualRenderingMode.Emf" // to only render the EMF part of an EMF+ dual metafile. // Set the "EmfPlusDualRenderingMode" property to "EmfPlusDualRenderingMode.EmfPlus" to // to render the EMF+ part of an EMF+ dual metafile. // Set the "EmfPlusDualRenderingMode" property to "EmfPlusDualRenderingMode.EmfPlusWithFallback" // to render the EMF+ part of an EMF+ dual metafile if all of the EMF+ records are supported. // Otherwise, Aspose.Words will render the EMF part. saveOptions.MetafileRenderingOptions.EmfPlusDualRenderingMode = renderingMode; // Set the "UseEmfEmbeddedToWmf" property to "true" to render embedded EMF data // for metafiles that we can render as vector graphics. saveOptions.MetafileRenderingOptions.UseEmfEmbeddedToWmf = true; doc.Save(ArtifactsDir + "PdfSaveOptions.RenderMetafile.pdf", saveOptions); //ExEnd #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.RenderMetafile.pdf"); switch (renderingMode) { case EmfPlusDualRenderingMode.Emf: case EmfPlusDualRenderingMode.EmfPlusWithFallback: Assert.AreEqual(0, pdfDocument.Pages[1].Resources.Images.Count); TestUtil.FileContainsString("5 0 obj\r\n" + "<</Type /Page/Parent 3 0 R/Contents 6 0 R/MediaBox [0 0 595.29998779 841.90002441]/Resources<</Font<</FAAAAI 8 0 R/FAAABB 11 0 R/FAAABE 14 0 R>>>>/Group <</Type/Group/S/Transparency/CS/DeviceRGB>>>>", ArtifactsDir + "PdfSaveOptions.RenderMetafile.pdf"); break; case EmfPlusDualRenderingMode.EmfPlus: Assert.AreEqual(1, pdfDocument.Pages[1].Resources.Images.Count); TestUtil.FileContainsString("5 0 obj\r\n" + "<</Type /Page/Parent 3 0 R/Contents 6 0 R/MediaBox [0 0 595.29998779 841.90002441]/Resources<</Font<</FAAAAI 8 0 R/FAAABC 12 0 R/FAAABF 15 0 R>>/XObject<</X1 10 0 R>>>>/Group <</Type/Group/S/Transparency/CS/DeviceRGB>>>>", ArtifactsDir + "PdfSaveOptions.RenderMetafile.pdf"); break; } #endif } [Test] public void EncryptionPermissions() { //ExStart //ExFor:PdfEncryptionDetails.#ctor //ExFor:PdfSaveOptions.EncryptionDetails //ExFor:PdfEncryptionDetails.Permissions //ExFor:PdfEncryptionDetails.EncryptionAlgorithm //ExFor:PdfEncryptionDetails.OwnerPassword //ExFor:PdfEncryptionDetails.UserPassword //ExFor:PdfEncryptionAlgorithm //ExFor:PdfPermissions //ExFor:PdfEncryptionDetails //ExSummary:Shows how to set permissions on a saved PDF document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Writeln("Hello world!"); PdfEncryptionDetails encryptionDetails = new PdfEncryptionDetails("password", string.Empty, PdfEncryptionAlgorithm.RC4_128); // Start by disallowing all permissions. encryptionDetails.Permissions = PdfPermissions.DisallowAll; // Extend permissions to allow the editing of annotations. encryptionDetails.Permissions = PdfPermissions.ModifyAnnotations | PdfPermissions.DocumentAssembly; // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions saveOptions = new PdfSaveOptions(); // Enable encryption via the "EncryptionDetails" property. saveOptions.EncryptionDetails = encryptionDetails; // When we open this document, we will need to provide the password before accessing its contents. doc.Save(ArtifactsDir + "PdfSaveOptions.EncryptionPermissions.pdf", saveOptions); //ExEnd #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument; Assert.Throws<InvalidPasswordException>(() => pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.EncryptionPermissions.pdf")); pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.EncryptionPermissions.pdf", "password"); TextFragmentAbsorber textAbsorber = new TextFragmentAbsorber(); pdfDocument.Pages[1].Accept(textAbsorber); Assert.AreEqual("Hello world!", textAbsorber.Text); #endif } [TestCase(NumeralFormat.ArabicIndic)] [TestCase(NumeralFormat.Context)] [TestCase(NumeralFormat.EasternArabicIndic)] [TestCase(NumeralFormat.European)] [TestCase(NumeralFormat.System)] public void SetNumeralFormat(NumeralFormat numeralFormat) { //ExStart //ExFor:FixedPageSaveOptions.NumeralFormat //ExFor:NumeralFormat //ExSummary:Shows how to set the numeral format used when saving to PDF. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Font.LocaleId = new CultureInfo("ar-AR").LCID; builder.Writeln("1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 50, 100"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "NumeralFormat" property to "NumeralFormat.ArabicIndic" to // use glyphs from the U+0660 to U+0669 range as numbers. // Set the "NumeralFormat" property to "NumeralFormat.Context" to // look up the locale to determine what number of glyphs to use. // Set the "NumeralFormat" property to "NumeralFormat.EasternArabicIndic" to // use glyphs from the U+06F0 to U+06F9 range as numbers. // Set the "NumeralFormat" property to "NumeralFormat.European" to use european numerals. // Set the "NumeralFormat" property to "NumeralFormat.System" to determine the symbol set from regional settings. options.NumeralFormat = numeralFormat; doc.Save(ArtifactsDir + "PdfSaveOptions.SetNumeralFormat.pdf", options); //ExEnd #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.SetNumeralFormat.pdf"); TextFragmentAbsorber textAbsorber = new TextFragmentAbsorber(); pdfDocument.Pages[1].Accept(textAbsorber); switch (numeralFormat) { case NumeralFormat.European: Assert.AreEqual("1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 50, 100", textAbsorber.Text); break; case NumeralFormat.ArabicIndic: Assert.AreEqual(", ٢, ٣, ٤, ٥, ٦, ٧, ٨, ٩, ١٠, ٥٠, ١١٠٠", textAbsorber.Text); break; case NumeralFormat.EasternArabicIndic: Assert.AreEqual("۱۰۰ ,۵۰ ,۱۰ ,۹ ,۸ ,۷ ,۶ ,۵ ,۴ ,۳ ,۲ ,۱", textAbsorber.Text); break; } #endif } [Test] public void ExportPageSet() { //ExStart //ExFor:FixedPageSaveOptions.PageSet //ExSummary:Shows how to export Odd pages from the document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); for (int i = 0; i < 5; i++) { builder.Writeln($"Page {i + 1} ({(i % 2 == 0 ? "odd" : "even")})"); if (i < 4) builder.InsertBreak(BreakType.PageBreak); } // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Below are three PageSet properties that we can use to filter out a set of pages from // our document to save in an output PDF document based on the parity of their page numbers. // 1 - Save only the even-numbered pages: options.PageSet = PageSet.Even; doc.Save(ArtifactsDir + "PdfSaveOptions.ExportPageSet.Even.pdf", options); // 2 - Save only the odd-numbered pages: options.PageSet = PageSet.Odd; doc.Save(ArtifactsDir + "PdfSaveOptions.ExportPageSet.Odd.pdf", options); // 3 - Save every page: options.PageSet = PageSet.All; doc.Save(ArtifactsDir + "PdfSaveOptions.ExportPageSet.All.pdf", options); //ExEnd #if NET48 || NET5_0 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.ExportPageSet.Even.pdf"); TextAbsorber textAbsorber = new TextAbsorber(); pdfDocument.Pages.Accept(textAbsorber); Assert.AreEqual("Page 2 (even)\r\n" + "Page 4 (even)", textAbsorber.Text); pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.ExportPageSet.Odd.pdf"); textAbsorber = new TextAbsorber(); pdfDocument.Pages.Accept(textAbsorber); Assert.AreEqual("Page 1 (odd)\r\n" + "Page 3 (odd)\r\n" + "Page 5 (odd)", textAbsorber.Text); pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.ExportPageSet.All.pdf"); textAbsorber = new TextAbsorber(); pdfDocument.Pages.Accept(textAbsorber); Assert.AreEqual("Page 1 (odd)\r\n" + "Page 2 (even)\r\n" + "Page 3 (odd)\r\n" + "Page 4 (even)\r\n" + "Page 5 (odd)", textAbsorber.Text); #endif } [Test] public void ExportLanguageToSpanTag() { //ExStart //ExFor:PdfSaveOptions.ExportLanguageToSpanTag //ExSummary:Shows how to create a "Span" tag in the document structure to export the text language. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Writeln("Hello world!"); builder.Writeln("Hola mundo!"); PdfSaveOptions saveOptions = new PdfSaveOptions { // Note, when "ExportDocumentStructure" is false, "ExportLanguageToSpanTag" is ignored. ExportDocumentStructure = true, ExportLanguageToSpanTag = true }; doc.Save(ArtifactsDir + "PdfSaveOptions.ExportLanguageToSpanTag.pdf", saveOptions); //ExEnd } } }
51.642739
273
0.62787
[ "MIT" ]
alex-dudin/Aspose.Words-for-.NET
Examples/ApiExamples/ApiExamples/ExPdfSaveOptions.cs
125,248
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Azure.Core; using Microsoft.Azure.WebJobs.Extensions.DurableTask; using Microsoft.Azure.WebJobs.Extensions.DurableTask.Auth; using Microsoft.Azure.WebJobs.Extensions.DurableTask.Tests; using Microsoft.Extensions.Azure; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Moq; using Moq.Language; using Xunit; using AppAuthTokenCredential = Microsoft.WindowsAzure.Storage.Auth.TokenCredential; using AzureTokenCredential = Azure.Core.TokenCredential; namespace WebJobs.Extensions.DurableTask.Tests.V2 { public class AzureCredentialFactoryTests { [Fact] [Trait("Category", PlatformSpecificHelpers.TestCategory)] public void Create() { // Create test data IConfiguration config = new ConfigurationBuilder().Build(); // Setup mocks AzureCredentialFactory factory = SetupCredentialsFactory(config, new AccessToken("AAAA", DateTime.UtcNow.AddMinutes(5))); // Assert behavior through events (int Renewing, int Renewed, int RenewedFailed) invocations = (0, 0, 0); factory.Renewing += s => invocations.Renewing++; factory.Renewed += n => invocations.Renewed++; factory.RenewalFailed += (i, n, e) => invocations.RenewedFailed++; // Create the credential and assert its state using AppAuthTokenCredential credential = factory.Create(config, TimeSpan.Zero, TimeSpan.Zero); // Wait a short amount of time in case of erroneous renewal Thread.Sleep(1000); // Validate Assert.Equal("AAAA", credential.Token); Assert.Equal((0, 0, 0), invocations); } [Fact] [Trait("Category", PlatformSpecificHelpers.TestCategory)] public void Renew() { // Create test data IConfiguration config = new ConfigurationBuilder().Build(); DateTimeOffset start = DateTimeOffset.UtcNow; TimeSpan expiration = TimeSpan.FromSeconds(1); TimeSpan offset = TimeSpan.FromMinutes(10); TimeSpan delay = TimeSpan.FromMinutes(1); var expected = new AccessToken[] { new AccessToken("AAAA", start + expiration), new AccessToken("BBBB", start + expiration + expiration), new AccessToken("CCCC", start + offset + offset), }; // Setup mocks AzureCredentialFactory factory = SetupCredentialsFactory(config, expected); // Assert behavior through events (int Renewing, int Renewed, int RenewedFailed) invocations = (0, 0, 0); factory.Renewing += s => { invocations.Renewing++; Assert.Equal(offset, s.RefreshOffset); Assert.Equal(delay, s.RefreshDelay); Assert.Equal("https://storage.azure.com/.default", s.Context.Scopes.Single()); Assert.Null(s.Context.TenantId); Assert.Equal(expected[invocations.Renewing - 1], s.Previous); }; factory.Renewed += n => { invocations.Renewed++; Assert.Equal(expected[invocations.Renewed].Token, n.Token); if (invocations.Renewed < expected.Length - 1) { // The expirations are so short for the first entries that they will renew immediately! Assert.Equal(TimeSpan.Zero, n.Frequency); } else { // We expect to renew this token within the offset from the expiration time TimeSpan max = expected[^1].ExpiresOn - start - offset; Assert.True(n.Frequency <= max); } }; factory.RenewalFailed += (i, n, e) => invocations.RenewedFailed++; // Create the credential and assert its state using AppAuthTokenCredential credential = factory.Create(config, offset, delay); // Wait until the final renewal complete WaitUntilRenewal(credential, expected[^1].Token, TimeSpan.FromSeconds(5)); Assert.Equal((expected.Length - 1, expected.Length - 1, 0), invocations); } [Fact] [Trait("Category", PlatformSpecificHelpers.TestCategory)] public void ConnectionFailure() { // Create test data IConfiguration config = new ConfigurationBuilder().Build(); DateTimeOffset start = DateTimeOffset.UtcNow; TimeSpan expiration = TimeSpan.FromSeconds(1); TimeSpan offset = TimeSpan.FromMinutes(10); TimeSpan delay = TimeSpan.FromSeconds(1); var expected = new AccessToken[] { new AccessToken("AAAA", start + expiration), new AccessToken("BBBB", start + expiration + expiration), new AccessToken("CCCC", start + offset + offset), }; // Setup mocks AzureCredentialFactory factory = SetupCredentialsFactoryWithError(config, expected); // Assert behavior through events (int Renewing, int Renewed, int RenewedFailed) invocations = (0, 0, 0); factory.Renewing += s => invocations.Renewing++; factory.Renewed += n => invocations.Renewed++; factory.RenewalFailed += (i, n, e) => { // The renewal failure should occur after successfully fetching "BBBB" Assert.Equal(++invocations.RenewedFailed, i); Assert.Equal(expected[^2].Token, n.Token); Assert.Equal(delay, n.Frequency); }; // Create the credential and assert its state using AppAuthTokenCredential credential = factory.Create(config, offset, delay); // Wait until the final renewal complete (including the extra retry on error) WaitUntilRenewal(credential, expected[^1].Token, TimeSpan.FromSeconds(5)); Assert.Equal(expected[^1].Token, credential.Token); Assert.Equal((expected.Length, expected.Length - 1, 1), invocations); } private static AzureCredentialFactory SetupCredentialsFactory(IConfiguration config, params AccessToken[] tokens) { var mockFactory = new Mock<AzureComponentFactory>(MockBehavior.Strict); var mockCredential = new Mock<AzureTokenCredential>(MockBehavior.Strict); mockFactory.Setup(f => f.CreateTokenCredential(config)).Returns(mockCredential.Object); // Call pattern is a synchronous call to GetToken followed by asynchronous calls to GetTokenAsync in the callback mockCredential .SetupSequence(c => c.GetToken( It.Is<TokenRequestContext>(cxt => cxt.Scopes.Single() == "https://storage.azure.com/.default"), It.IsAny<CancellationToken>())) .Returns(tokens.First()); ISetupSequentialResult<ValueTask<AccessToken>> asyncResult = mockCredential .SetupSequence(c => c.GetTokenAsync( It.Is<TokenRequestContext>(cxt => cxt.Scopes.Single() == "https://storage.azure.com/.default"), It.IsAny<CancellationToken>())) .ReturnsSequenceAsync(tokens.Skip(1)); return new AzureCredentialFactory(Options.Create(new DurableTaskOptions()), mockFactory.Object, NullLoggerFactory.Instance); } private static AzureCredentialFactory SetupCredentialsFactoryWithError(IConfiguration config, params AccessToken[] tokens) { var mockFactory = new Mock<AzureComponentFactory>(MockBehavior.Strict); var mockCredential = new Mock<AzureTokenCredential>(MockBehavior.Strict); mockFactory.Setup(f => f.CreateTokenCredential(config)).Returns(mockCredential.Object); // Call pattern is a synchronous call to GetToken followed by asynchronous calls to GetTokenAsync in the callback mockCredential .SetupSequence(c => c.GetToken( It.Is<TokenRequestContext>(cxt => cxt.Scopes.Single() == "https://storage.azure.com/.default"), It.IsAny<CancellationToken>())) .Returns(tokens.First()); // Inject an error in the 2nd to last call ISetupSequentialResult<ValueTask<AccessToken>> asyncResult = mockCredential .SetupSequence(c => c.GetTokenAsync( It.Is<TokenRequestContext>(cxt => cxt.Scopes.Single() == "https://storage.azure.com/.default"), It.IsAny<CancellationToken>())) .ReturnsSequenceAsync(tokens.Skip(1).Take(tokens.Length - 2)) .Throws<Exception>() .Returns(new ValueTask<AccessToken>(tokens[^1])); return new AzureCredentialFactory(Options.Create(new DurableTaskOptions()), mockFactory.Object, NullLoggerFactory.Instance); } private static void WaitUntilRenewal(AppAuthTokenCredential credential, string token, TimeSpan timeout) { // We need to spin-loop to wait for the renewal as there is no "hook" for waiting until // the TokenCredential object has updated its Token (only after we've fetched the new value). using var source = new CancellationTokenSource(); source.CancelAfter(timeout); while (credential.Token != token) { Assert.False(source.IsCancellationRequested, $"Could not renew credentials within {timeout}"); } } } }
46.319635
136
0.611297
[ "MIT" ]
wsugarman/azure-functions-durable-extension
test/FunctionsV2/AzureCredentialFactoryTests.cs
10,146
C#
using System; using Bittrex.Net.Converters.V3; using Newtonsoft.Json; namespace Bittrex.Net.Objects.V3 { /// <summary> /// Withdrawal info /// </summary> public class BittrexWithdrawalV3 { /// <summary> /// The id of the withdrawal /// </summary> public string Id { get; set; } = ""; /// <summary> /// The currency of the withdrawal /// </summary> [JsonProperty("currencySymbol")] public string Currency { get; set; } = ""; /// <summary> /// The quantity of the withdrawal /// </summary> public decimal Quantity { get; set; } /// <summary> /// The address the withdrawal is to /// </summary> [JsonProperty("cryptoAddress")] public string Address { get; set; } = ""; /// <summary> /// The tag of the address /// </summary> [JsonProperty("cryptoAddressTag")] public string AddressTag { get; set; } = ""; /// <summary> /// The transaction cost of the withdrawal /// </summary> [JsonProperty("txCost")] public decimal TransactionCost { get; set; } /// <summary> /// The transaction id /// </summary> [JsonProperty("txId")] public string TransactionId { get; set; } = ""; /// <summary> /// The status of the withdrawal /// </summary> [JsonConverter(typeof(WithdrawalStatusConverter))] public WithdrawalStatus Status { get; set; } /// <summary> /// The time the withdrawal was created /// </summary> public DateTime CreatedAt { get; set; } /// <summary> /// The time the withdrawal was completed /// </summary> public DateTime? CompletedAt { get; set; } } }
30.766667
58
0.529252
[ "MIT" ]
NektoDron/Bittrex.Net
Bittrex.Net/Objects/V3/BittrexWithdrawalV3.cs
1,848
C#
using Domain.CinemaModel; using Domain.Enums; using Domain.MovieModel; using System; using System.Collections.Generic; using System.Linq; namespace Services { public class CinemaService { public void CinemaRepertuar() { Cinema cineplexx = new Cinema("Cineplex"); Cinema milenium = new Cinema("Milenium"); List<Movie> cineplexMovies = MovieService.CineplexxMovieList(); List<Movie> mileniumMovies = MovieService.MileniumMovieList(); cineplexx.Movies = cineplexMovies; milenium.Movies = mileniumMovies; List<Cinema> cinemas = new List<Cinema>(); cinemas.Add(cineplexx); cinemas.Add(milenium); Console.WriteLine(" WELCOME TO THE MOVIE WORLD.\n" + "\n" + "Enter movie to see if it`s on cinemas repertuar;"); string userImput = Console.ReadLine(); GetCinemas(cinemas, userImput); } //cineplexCineam public void CinemaChuser(char[] arr) { if (arr[0] == '1' || arr[0] == 'c' || arr[0] == 'C') { Console.WriteLine("Do you like to see list of all movies or filtered by genre?\n" + "\n" + "Input 1 or 2 to select your preference\n" + "" + "1.All\n" + "2.Genre"); string userAll_Genre_Preference = Console.ReadLine(); if (userAll_Genre_Preference == "1" || userAll_Genre_Preference == "All") { List<Movie> cineplexmovies = MovieService.CineplexxMovieList(); PrintAllMovies(cineplexmovies); //Get all Movies larger than "Rating" /// ***DONE*** //Get Movies below "TicketPrice" //Done //Get Movies above "TicketPrice"//Done Console.WriteLine("\n" + "\n" + "Woud you like to filter movies by 'larger than rating'? Y/N"); string userRatingFilterImput = Console.ReadLine(); MovieService service = new MovieService(); service.LargerThenRating(userRatingFilterImput, cineplexmovies); Console.WriteLine("Woud you like to filter movies by Price?Y/N"); string userImput = Console.ReadLine(); service.TiketPrice(userImput, cineplexmovies); Console.WriteLine("\n" + "Which move do you like to watch"); string userMoveSelect = Console.ReadLine(); Movie movie = cineplexmovies.SingleOrDefault(m => m.Title.ToLower() == userMoveSelect); MovieSelectorLogic(userMoveSelect, movie); } else { List<Movie> cineplexmovies = MovieService.CineplexxMovieList(); PrintMoviesByGenre(cineplexmovies); Console.WriteLine("\n" + "Select favorite genre from the list "); string userGenreSelect = Console.ReadLine(); Genre genre = new Genre(); GenerSelectLogic(userGenreSelect, ref genre); List<Movie> filtratedByGener = FilteredMoviesByGender(cineplexmovies, genre); PrintMoviesByGenre(filtratedByGener); Console.WriteLine("\n" + "Select one of the movie on the list."); string userSelctMovieByGener = Console.ReadLine(); Movie userSelectedByGenerMovie = filtratedByGener.SingleOrDefault(m => m.Title.ToLower() == userSelctMovieByGener.ToLower()); MovieSelectorLogic(userSelctMovieByGener, userSelectedByGenerMovie); } } ///MileniumCinema else if (arr[0] == '2' || arr[0] == 'm' || arr[0] == 'M') { //Console.WriteLine(" You are in the Millenium Cinema.\n" + // " We are colosed until further notice.\n" + // " thank you for your understanding in advance.\n" + // " Buy :) "); Console.WriteLine("Do you like to see list of all movies or filtered by genre?\n" + "\n" + "Input 1 or 2 to select your preference\n" + "" + "1.All\n" + "2.Genre"); string userAll_Genre_Preference = Console.ReadLine(); if (userAll_Genre_Preference == "1" || userAll_Genre_Preference == "All") { List<Movie> milenium = MovieService.MileniumMovieList(); PrintAllMovies(milenium); Console.WriteLine("\n" + "\n" + "Woud you like to filter movies by 'larger than rating'? Y/N"); string userRatingFilterImput = Console.ReadLine(); MovieService service = new MovieService(); service.LargerThenRating(userRatingFilterImput, milenium); Console.WriteLine("Woud you like to filter movies by Price?Y/N"); string userImput = Console.ReadLine(); service.TiketPrice(userImput, milenium); Console.WriteLine("\n" + "Which move do you like to watch"); string userMoveSelect = Console.ReadLine(); Movie movie = milenium.SingleOrDefault(m => m.Title.ToLower() == userMoveSelect); MovieSelectorLogic(userMoveSelect, movie); } else { List<Movie> milenium = MovieService.MileniumMovieList(); PrintMoviesByGenre(milenium); Console.WriteLine("\n" + "Select favorite genre from the list "); string userGenreSelect = Console.ReadLine(); Genre genre = new Genre(); GenerSelectLogic(userGenreSelect, ref genre); List<Movie> filtratedByGener = FilteredMoviesByGender(milenium, genre); PrintMoviesByGenre(filtratedByGener); Console.WriteLine("\n" + "Select one of the movie on the list."); string userSelctMovieByGener = Console.ReadLine(); Movie userSelectedByGenerMovie = filtratedByGener.SingleOrDefault(m => m.Title.ToLower() == userSelctMovieByGener.ToLower()); MovieSelectorLogic(userSelctMovieByGener, userSelectedByGenerMovie); } } } public void MoviePlaying(Movie movie) { Console.WriteLine($"Watching movie {movie.Title}"); } public static void PrintAllMovies(List<Movie> movies) { movies.ForEach(movie => Console.WriteLine(movie.Title)); } public static void PrintMoviesByGenre(List<Movie> movies) { movies.ForEach(movie => Console.WriteLine($"{movie.Genre,25} {movie.Title,25}")); } public static void MovieSelectorLogic(string input, Movie movie) { CinemaService mPlaying = new CinemaService(); if (movie == null) { Console.WriteLine(" Error...Wrong movie selected.Enter movie name whith white spaces including."); //throw new Exception("Error...wrong move selection!"); } else { mPlaying.MoviePlaying(movie); } } public static List<Movie> FilteredMoviesByGender(List<Movie> movies, Genre genre) { return movies.Where(m => m.Genre == genre).ToList(); } public static void GenerSelectLogic(string input, ref Genre genre) { switch (input.ToLower()) { case "comedy": genre = Genre.Comedy; break; case "horror": genre = Genre.Horror; break; case "action": genre = Genre.Action; break; case "drama": genre = Genre.Drama; break; case "sci-fi": genre = Genre.SciFi; break; } } /// Get all Cinemas that hava a "Movie" on their list public void GetCinemas(List<Cinema> cinemas, string input) { foreach (Cinema c in cinemas) { foreach (Movie m in c.Movies) { if (m.Title.ToLower() == input.ToLower()) { Console.WriteLine($"{c.Name} {m.Title} {m.TicketPrice} $"); } } } } /// Get all Cinemas that hava a "Movie" on their list >> METHOD //STAGE 1 //public void GetCinemas1(List<Cinema> cinemas, string input) //{ // foreach (Cinema c in cinemas) // { // foreach (Movie m in c.Movies) // { // if (m.Title.ToLower() == input.ToLower()) // { // Console.WriteLine($"{c.Name} {m.Title} {m.TicketPrice} $"); // } // } // } //} /// STAGE 2 // public void GetCinemas(List<Cinema> cinemas, string input) //{ // stage 2 // foreach (Cinema c in cinemas) // { // c.Movies.Where(m => m.Title == input).ToList(); // } // STAGE 3 kompletno vo linija // cinemas.ForEach(c => c.Movies.Where(m => m.Title == input).ToList()); // } } }
34.083612
145
0.49269
[ "MIT" ]
Isko82mk/HomeWorks
HomeWorkClass10_Refactored/Services/CinemaService.cs
10,193
C#
 //------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace CSS.Database { using System; using System.Data.Entity; using System.Data.Entity.Infrastructure; public partial class CSSdbEntities : DbContext { public CSSdbEntities() : base("name=CSSdbEntities") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { throw new UnintentionalCodeFirstException(); } public virtual DbSet<Clan> Clan { get; set; } public virtual DbSet<Player> Player { get; set; } } }
21.302326
85
0.570961
[ "MIT" ]
skyprolk/Clash-Of-SL
Clash SL Server [UCS 7.4.0]/Database/CSSdb.Context.cs
918
C#
using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using System.Windows.Threading; namespace EventHook.Helpers { /// <summary> /// A class to create a dummy message pump if we don't have one /// A message pump is required for most of our hooks to succeed /// </summary> internal class SharedMessagePump { private static bool hasUIThread = false; static Lazy<TaskScheduler> scheduler; static Lazy<MessageHandler> messageHandler; static SharedMessagePump() { scheduler = new Lazy<TaskScheduler>(() => { //if the calling thread is a UI thread then return its synchronization context //no need to create a message pump Dispatcher dispatcher = Dispatcher.FromThread(Thread.CurrentThread); if (dispatcher != null) { if (SynchronizationContext.Current != null) { hasUIThread = true; return TaskScheduler.FromCurrentSynchronizationContext(); } } TaskScheduler current = null; //if current task scheduler is null, create a message pump //http://stackoverflow.com/questions/2443867/message-pump-in-net-windows-service //use async for performance gain! new Task(() => { Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => { Volatile.Write(ref current, TaskScheduler.FromCurrentSynchronizationContext()); } ), DispatcherPriority.Normal); Dispatcher.Run(); }).Start(); //we called dispatcher begin invoke to get the Message Pump Sync Context //we check every 10ms until synchronization context is copied while (Volatile.Read(ref current) == null) { Thread.Sleep(10); } return Volatile.Read(ref current); }); messageHandler = new Lazy<MessageHandler>(() => { MessageHandler msgHandler = null; //get the mesage handler dummy window created using the UI sync context new Task((e) => { Volatile.Write(ref msgHandler, new MessageHandler()); }, GetTaskScheduler()).Start(); //wait here until the window is created on UI thread while (Volatile.Read(ref msgHandler) == null) { Thread.Sleep(10); }; return Volatile.Read(ref msgHandler); }); Initialize(); } /// <summary> /// Initialize the required message pump for all the hooks /// </summary> private static void Initialize() { GetTaskScheduler(); GetHandle(); } /// <summary> /// Get the UI task scheduler /// </summary> /// <returns></returns> internal static TaskScheduler GetTaskScheduler() { return scheduler.Value; } /// <summary> /// Get the handle of the window we created on the UI thread /// </summary> /// <returns></returns> internal static IntPtr GetHandle() { var handle = IntPtr.Zero; if (hasUIThread) { try { handle = Process.GetCurrentProcess().MainWindowHandle; if (handle != IntPtr.Zero) return handle; } catch { } } return messageHandler.Value.Handle; } } /// <summary> /// A dummy class to create a dummy invisible window object /// </summary> internal class MessageHandler : NativeWindow { internal MessageHandler() { CreateHandle(new CreateParams()); } protected override void WndProc(ref Message msg) { base.WndProc(ref msg); } } }
30.744828
103
0.498654
[ "MIT" ]
tongshunmin/Windows-User-Action-Hook
EventHook/Helpers/SharedMessagePump.cs
4,460
C#
using System.Collections.Generic; using RimWorld; using Verse; using Verse.AI; namespace ReconAndDiscovery { public class JobDriver_TakeBodyToOsirisCasket : JobDriver { private const TargetIndex CorpseIndex = TargetIndex.A; private const TargetIndex GraveIndex = TargetIndex.B; public JobDriver_TakeBodyToOsirisCasket() { rotateToFace = TargetIndex.B; } private Corpse Corpse => (Corpse) pawn.CurJob.GetTarget(TargetIndex.A).Thing; private Building_CryptosleepCasket Casket => (Building_CryptosleepCasket) pawn.CurJob.GetTarget(TargetIndex.B).Thing; public override bool TryMakePreToilReservations(bool errorOnFailed) { return pawn.Reserve(job.targetA, job, 1, -1, null, errorOnFailed); } protected override IEnumerable<Toil> MakeNewToils() { yield return Toils_Reserve.Reserve(TargetIndex.A); yield return Toils_Reserve.Reserve(TargetIndex.B); yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.ClosestTouch); yield return Toils_Haul.StartCarryThing(TargetIndex.A); yield return Toils_Haul.CarryHauledThingToCell(TargetIndex.B); yield return Toils_Haul.DepositHauledThingInContainer(TargetIndex.B, TargetIndex.A); yield return Toils_Reserve.Release(TargetIndex.A); yield return Toils_Reserve.Release(TargetIndex.B); } } }
36.292683
96
0.688844
[ "MIT" ]
Garethp/ReconAndDiscovery
Source/ReconAndDiscovery/JobDriver_TakeBodyToOsirisCasket.cs
1,490
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 Aliyun.Acs.Core.Transform; using Aliyun.Acs.Rds.Model.V20140815; using System; using System.Collections.Generic; namespace Aliyun.Acs.Rds.Transform.V20140815 { public class DescribeCollationTimeZonesResponseUnmarshaller { public static DescribeCollationTimeZonesResponse Unmarshall(UnmarshallerContext context) { DescribeCollationTimeZonesResponse describeCollationTimeZonesResponse = new DescribeCollationTimeZonesResponse(); describeCollationTimeZonesResponse.HttpResponse = context.HttpResponse; describeCollationTimeZonesResponse.RequestId = context.StringValue("DescribeCollationTimeZones.RequestId"); List<DescribeCollationTimeZonesResponse.DescribeCollationTimeZones_CollationTimeZone> describeCollationTimeZonesResponse_collationTimeZones = new List<DescribeCollationTimeZonesResponse.DescribeCollationTimeZones_CollationTimeZone>(); for (int i = 0; i < context.Length("DescribeCollationTimeZones.CollationTimeZones.Length"); i++) { DescribeCollationTimeZonesResponse.DescribeCollationTimeZones_CollationTimeZone collationTimeZone = new DescribeCollationTimeZonesResponse.DescribeCollationTimeZones_CollationTimeZone(); collationTimeZone.TimeZone = context.StringValue("DescribeCollationTimeZones.CollationTimeZones["+ i +"].TimeZone"); collationTimeZone.StandardTimeOffset = context.StringValue("DescribeCollationTimeZones.CollationTimeZones["+ i +"].StandardTimeOffset"); collationTimeZone.Description = context.StringValue("DescribeCollationTimeZones.CollationTimeZones["+ i +"].Description"); describeCollationTimeZonesResponse_collationTimeZones.Add(collationTimeZone); } describeCollationTimeZonesResponse.CollationTimeZones = describeCollationTimeZonesResponse_collationTimeZones; return describeCollationTimeZonesResponse; } } }
54.44898
238
0.805847
[ "Apache-2.0" ]
brightness007/unofficial-aliyun-openapi-net-sdk
aliyun-net-sdk-rds/Rds/Transform/V20140815/DescribeCollationTimeZonesResponseUnmarshaller.cs
2,668
C#
namespace SonarQube.Core.Api { public class Issue { public string Severity { get; set; } public string Line { get; set; } public string Message { get; set; } public string Effort { get; set; } public string Type { get; set; } public string Component { get; set; } public string SubProject { get; set; } } }
21.684211
46
0.521845
[ "MIT" ]
mamcer/sonarqube-report
src/SonarQube.Core/Api/Issue.cs
412
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Visafe.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Visafe.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// </summary> public static System.Drawing.Icon logo_footer { get { object obj = ResourceManager.GetObject("logo_footer", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// </summary> public static System.Drawing.Icon turnoff { get { object obj = ResourceManager.GetObject("turnoff", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// </summary> public static System.Drawing.Icon turnon { get { object obj = ResourceManager.GetObject("turnon", resourceCulture); return ((System.Drawing.Icon)(obj)); } } } }
41.531915
172
0.585041
[ "Apache-2.0" ]
VisafeTeam/VisafeWindows
Visafe/Visafe/Properties/Resources.Designer.cs
3,906
C#
using System; using System.Collections.Generic; using System.Linq; using System.Security.Principal; using System.Text; using System.Threading.Tasks; namespace CLK.AspNet.Identity { public abstract class PermissionAuthorize { // Constructors internal PermissionAuthorize() { } // Methods public abstract bool Authorize(IPrincipal user, string permissionName); } public class PermissionAuthorize<TPermission, TKey> : PermissionAuthorize where TPermission : class, CLK.AspNet.Identity.IPermission<TKey> where TKey : IEquatable<TKey> { // Fields private PermissionManager<TPermission, TKey> _permissionManager = null; // Constructors public PermissionAuthorize(PermissionManager<TPermission, TKey> permissionManager) { #region Contracts if (permissionManager == null) throw new ArgumentNullException("permissionManager"); #endregion // Default _permissionManager = permissionManager; } // Methods public override bool Authorize(IPrincipal user, string permissionName = null) { #region Contracts if (user == null) throw new ArgumentNullException("user"); #endregion // Require if (user.Identity.IsAuthenticated == false) return false; if (string.IsNullOrEmpty(permissionName) == true) return true; // PermissionRoles var permissionRoles = _permissionManager.GetRolesByName(permissionName); if (permissionRoles == null) throw new InvalidOperationException(); // Authorize if (permissionRoles.Count > 0 && permissionRoles.Any(user.IsInRole) == false) { return false; } if (permissionRoles.Count == 0 && string.IsNullOrEmpty(permissionName) == false) return false; // Return return true; } } }
28.507042
106
0.623024
[ "MIT" ]
Clark159/CLK.AspNet.Identity
src/CLK.AspNet.Identity/PermissionAuthorize.cs
2,026
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using HansKindberg.IdentityServer.Identity.Data; using Microsoft.AspNetCore.Identity; using RegionOrebroLan.Security.Claims; using UserEntity = HansKindberg.IdentityServer.Identity.User; using UserLoginModel = HansKindberg.IdentityServer.Identity.Models.UserLogin; using UserModel = HansKindberg.IdentityServer.Identity.Models.User; namespace HansKindberg.IdentityServer.Identity { public interface IIdentityFacade { #region Properties IdentityContext DatabaseContext { get; } IQueryable<UserEntity> Users { get; } #endregion #region Methods Task<IdentityResult> DeleteUserAsync(UserEntity user); Task<UserEntity> GetUserAsync(string userName); Task<UserEntity> GetUserAsync(string provider, string userIdentifier); Task<IEnumerable<UserLoginInfo>> GetUserLoginsAsync(string id); Task<UserEntity> ResolveUserAsync(IClaimBuilderCollection claims, string provider, string userIdentifier); Task<IdentityResult> SaveUserAsync(UserModel user); /// <summary> /// Saves a user-login. /// </summary> /// <param name="userLogin">The model for the user-login.</param> /// <param name="allowMultipleLoginsForUser">If multiple user-logins are allowed for the same user-id or not.</param> Task<IdentityResult> SaveUserLoginAsync(UserLoginModel userLogin, bool allowMultipleLoginsForUser = false); Task<SignInResult> SignInAsync(string password, bool persistent, string userName); Task SignOutAsync(); Task<IdentityResult> ValidateUserAsync(UserModel user); #endregion } }
36.227273
119
0.79611
[ "MIT" ]
HansKindberg/IdentityServer-Extensions
Source/Project/Identity/IIdentityFacade.cs
1,594
C#
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V5.Resources; namespace Google.Ads.GoogleAds.V5.Services { public partial class GetUserInterestRequest { /// <summary> /// <see cref="gagvr::UserInterestName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> public gagvr::UserInterestName ResourceNameAsUserInterestName { get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::UserInterestName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
37.060606
128
0.696648
[ "Apache-2.0" ]
PierrickVoulet/google-ads-dotnet
src/V5/Services/UserInterestServiceResourceNames.g.cs
1,223
C#
using System.Collections.Generic; using System.Linq; using MySql.Data.MySqlClient; namespace TestSupport.Data { public class TestDatabaseSupport { public static string RegistrationConnectionString => ConnectionString("tracker_registration_dotnet_test"); public static string BacklogConnectionString => ConnectionString("tracker_backlog_dotnet_test"); public static string AllocationsConnectionString => ConnectionString("tracker_allocations_dotnet_test"); public static string TimesheetsConnectionString => ConnectionString("tracker_timesheets_dotnet_test"); private const string DbUser = "tracker_dotnet"; private const string DbPassword = "password"; public static string ConnectionString(string database) => $"server=127.0.0.1;uid={DbUser};pwd={DbPassword};database={database}"; private readonly string _connectionString; public TestDatabaseSupport(string connectionString) { _connectionString = connectionString; } public void ExecSql(string sql) { using (var connection = new MySqlConnection(_connectionString)) { connection.Open(); using (var command = connection.CreateCommand()) { command.CommandText = sql; command.ExecuteNonQuery(); } } } public IList<IDictionary<string, object>> QuerySql(string sql) { var result = new List<IDictionary<string, object>>(); using (var connection = new MySqlConnection(_connectionString)) { connection.Open(); using (var command = connection.CreateCommand()) { command.CommandText = sql; using (var reader = command.ExecuteReader()) { while (reader.HasRows) { while (reader.Read()) { var rowData = Enumerable.Range(0, reader.FieldCount) .ToDictionary(reader.GetName, reader.GetValue); result.Add(rowData); } reader.NextResult(); } } } } return result; } public void TruncateAllTables() { var dbName = new MySqlConnectionStringBuilder(_connectionString).Database; var tableNameSql = $@"set foreign_key_checks = 0; select table_name FROM information_schema.tables where table_schema='{dbName}' and table_name != 'schema_version';"; var truncateSql = ""; using (var connection = new MySqlConnection(_connectionString)) { connection.Open(); using (var command = connection.CreateCommand()) { command.CommandText = tableNameSql; using (var reader = command.ExecuteReader()) { while (reader.HasRows) { while (reader.Read()) { var table = reader.GetString(0); truncateSql += $"truncate {table};"; } reader.NextResult(); } } } using (var command = connection.CreateCommand()) { command.CommandText = truncateSql; command.ExecuteNonQuery(); } } } } }
34.619469
114
0.497699
[ "BSD-2-Clause" ]
vmware-tanzu-learning/pal-tracker-distributed-dotnet
Components/TestSupport/Data/TestDatabaseSupport.cs
3,912
C#