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 |
|---|---|---|---|---|---|---|---|---|
//
// Copyright (c) Microsoft and contributors. 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.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.Azure.Management.KeyVault;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.KeyVault
{
/// <summary>
/// Vault operations
/// </summary>
internal partial class VaultOperations : IServiceOperations<KeyVaultManagementClient>, IVaultOperations
{
/// <summary>
/// Initializes a new instance of the VaultOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal VaultOperations(KeyVaultManagementClient client)
{
this._client = client;
}
private KeyVaultManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.KeyVault.KeyVaultManagementClient.
/// </summary>
public KeyVaultManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Creates a new Azure key vault.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='vaultName'>
/// Required. Name of the vault
/// </param>
/// <param name='parameters'>
/// Required. Parameters to create or update the vault
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Vault information.
/// </returns>
public async Task<VaultGetResponse> CreateOrUpdateAsync(string resourceGroupName, string vaultName, VaultCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (vaultName == null)
{
throw new ArgumentNullException("vaultName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Location == null)
{
throw new ArgumentNullException("parameters.Location");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.KeyVault";
url = url + "/vaults/";
url = url + Uri.EscapeDataString(vaultName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject vaultCreateOrUpdateParametersValue = new JObject();
requestDoc = vaultCreateOrUpdateParametersValue;
JObject propertiesValue = new JObject();
vaultCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Properties.VaultUri != null)
{
propertiesValue["vaultUri"] = parameters.Properties.VaultUri;
}
propertiesValue["tenantId"] = parameters.Properties.TenantId.ToString();
if (parameters.Properties.Sku != null)
{
JObject skuValue = new JObject();
propertiesValue["sku"] = skuValue;
if (parameters.Properties.Sku.Family != null)
{
skuValue["family"] = parameters.Properties.Sku.Family;
}
if (parameters.Properties.Sku.Name != null)
{
skuValue["name"] = parameters.Properties.Sku.Name;
}
}
if (parameters.Properties.AccessPolicies != null)
{
if (parameters.Properties.AccessPolicies is ILazyCollection == false || ((ILazyCollection)parameters.Properties.AccessPolicies).IsInitialized)
{
JArray accessPoliciesArray = new JArray();
foreach (AccessPolicyEntry accessPoliciesItem in parameters.Properties.AccessPolicies)
{
JObject accessPolicyEntryValue = new JObject();
accessPoliciesArray.Add(accessPolicyEntryValue);
accessPolicyEntryValue["tenantId"] = accessPoliciesItem.TenantId.ToString();
accessPolicyEntryValue["objectId"] = accessPoliciesItem.ObjectId.ToString();
if (accessPoliciesItem.ApplicationId != null)
{
accessPolicyEntryValue["applicationId"] = accessPoliciesItem.ApplicationId.Value.ToString();
}
if (accessPoliciesItem.PermissionsRawJsonString != null)
{
accessPolicyEntryValue["permissions"] = JObject.Parse(accessPoliciesItem.PermissionsRawJsonString);
}
}
propertiesValue["accessPolicies"] = accessPoliciesArray;
}
}
propertiesValue["enabledForDeployment"] = parameters.Properties.EnabledForDeployment;
if (parameters.Properties.EnabledForDiskEncryption != null)
{
propertiesValue["enabledForDiskEncryption"] = parameters.Properties.EnabledForDiskEncryption.Value;
}
if (parameters.Properties.EnabledForTemplateDeployment != null)
{
propertiesValue["enabledForTemplateDeployment"] = parameters.Properties.EnabledForTemplateDeployment.Value;
}
vaultCreateOrUpdateParametersValue["location"] = parameters.Location;
if (parameters.Tags != null)
{
JObject tagsDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in parameters.Tags)
{
string tagsKey = pair.Key;
string tagsValue = pair.Value;
tagsDictionary[tagsKey] = tagsValue;
}
vaultCreateOrUpdateParametersValue["tags"] = tagsDictionary;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VaultGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VaultGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Vault vaultInstance = new Vault();
result.Vault = vaultInstance;
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
VaultProperties propertiesInstance = new VaultProperties();
vaultInstance.Properties = propertiesInstance;
JToken vaultUriValue = propertiesValue2["vaultUri"];
if (vaultUriValue != null && vaultUriValue.Type != JTokenType.Null)
{
string vaultUriInstance = ((string)vaultUriValue);
propertiesInstance.VaultUri = vaultUriInstance;
}
JToken tenantIdValue = propertiesValue2["tenantId"];
if (tenantIdValue != null && tenantIdValue.Type != JTokenType.Null)
{
Guid tenantIdInstance = Guid.Parse(((string)tenantIdValue));
propertiesInstance.TenantId = tenantIdInstance;
}
JToken skuValue2 = propertiesValue2["sku"];
if (skuValue2 != null && skuValue2.Type != JTokenType.Null)
{
Sku skuInstance = new Sku();
propertiesInstance.Sku = skuInstance;
JToken familyValue = skuValue2["family"];
if (familyValue != null && familyValue.Type != JTokenType.Null)
{
string familyInstance = ((string)familyValue);
skuInstance.Family = familyInstance;
}
JToken nameValue = skuValue2["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
skuInstance.Name = nameInstance;
}
}
JToken accessPoliciesArray2 = propertiesValue2["accessPolicies"];
if (accessPoliciesArray2 != null && accessPoliciesArray2.Type != JTokenType.Null)
{
foreach (JToken accessPoliciesValue in ((JArray)accessPoliciesArray2))
{
AccessPolicyEntry accessPolicyEntryInstance = new AccessPolicyEntry();
propertiesInstance.AccessPolicies.Add(accessPolicyEntryInstance);
JToken tenantIdValue2 = accessPoliciesValue["tenantId"];
if (tenantIdValue2 != null && tenantIdValue2.Type != JTokenType.Null)
{
Guid tenantIdInstance2 = Guid.Parse(((string)tenantIdValue2));
accessPolicyEntryInstance.TenantId = tenantIdInstance2;
}
JToken objectIdValue = accessPoliciesValue["objectId"];
if (objectIdValue != null && objectIdValue.Type != JTokenType.Null)
{
Guid objectIdInstance = Guid.Parse(((string)objectIdValue));
accessPolicyEntryInstance.ObjectId = objectIdInstance;
}
JToken applicationIdValue = accessPoliciesValue["applicationId"];
if (applicationIdValue != null && applicationIdValue.Type != JTokenType.Null)
{
Guid applicationIdInstance = Guid.Parse(((string)applicationIdValue));
accessPolicyEntryInstance.ApplicationId = applicationIdInstance;
}
JToken permissionsValue = accessPoliciesValue["permissions"];
if (permissionsValue != null && permissionsValue.Type != JTokenType.Null)
{
string permissionsInstance = permissionsValue.ToString(Newtonsoft.Json.Formatting.Indented);
accessPolicyEntryInstance.PermissionsRawJsonString = permissionsInstance;
}
}
}
JToken enabledForDeploymentValue = propertiesValue2["enabledForDeployment"];
if (enabledForDeploymentValue != null && enabledForDeploymentValue.Type != JTokenType.Null)
{
bool enabledForDeploymentInstance = ((bool)enabledForDeploymentValue);
propertiesInstance.EnabledForDeployment = enabledForDeploymentInstance;
}
JToken enabledForDiskEncryptionValue = propertiesValue2["enabledForDiskEncryption"];
if (enabledForDiskEncryptionValue != null && enabledForDiskEncryptionValue.Type != JTokenType.Null)
{
bool enabledForDiskEncryptionInstance = ((bool)enabledForDiskEncryptionValue);
propertiesInstance.EnabledForDiskEncryption = enabledForDiskEncryptionInstance;
}
JToken enabledForTemplateDeploymentValue = propertiesValue2["enabledForTemplateDeployment"];
if (enabledForTemplateDeploymentValue != null && enabledForTemplateDeploymentValue.Type != JTokenType.Null)
{
bool enabledForTemplateDeploymentInstance = ((bool)enabledForTemplateDeploymentValue);
propertiesInstance.EnabledForTemplateDeployment = enabledForTemplateDeploymentInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
vaultInstance.Id = idInstance;
}
JToken nameValue2 = responseDoc["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
vaultInstance.Name = nameInstance2;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
vaultInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
vaultInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey2 = ((string)property.Name);
string tagsValue2 = ((string)property.Value);
vaultInstance.Tags.Add(tagsKey2, tagsValue2);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Deletes the specified Azure key vault.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the vault belongs.
/// </param>
/// <param name='vaultName'>
/// Required. The name of the vault to delete
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Vault information.
/// </returns>
public async Task<VaultGetResponse> DeleteAsync(string resourceGroupName, string vaultName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (vaultName == null)
{
throw new ArgumentNullException("vaultName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vaultName", vaultName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.KeyVault";
url = url + "/vaults/";
url = url + Uri.EscapeDataString(vaultName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VaultGetResponse result = null;
// Deserialize Response
result = new VaultGetResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets the specified Azure key vault.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the vault belongs.
/// </param>
/// <param name='vaultName'>
/// Required. The name of the vault.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Vault information.
/// </returns>
public async Task<VaultGetResponse> GetAsync(string resourceGroupName, string vaultName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (vaultName == null)
{
throw new ArgumentNullException("vaultName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("vaultName", vaultName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.KeyVault";
url = url + "/vaults/";
url = url + Uri.EscapeDataString(vaultName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VaultGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VaultGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Vault vaultInstance = new Vault();
result.Vault = vaultInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
VaultProperties propertiesInstance = new VaultProperties();
vaultInstance.Properties = propertiesInstance;
JToken vaultUriValue = propertiesValue["vaultUri"];
if (vaultUriValue != null && vaultUriValue.Type != JTokenType.Null)
{
string vaultUriInstance = ((string)vaultUriValue);
propertiesInstance.VaultUri = vaultUriInstance;
}
JToken tenantIdValue = propertiesValue["tenantId"];
if (tenantIdValue != null && tenantIdValue.Type != JTokenType.Null)
{
Guid tenantIdInstance = Guid.Parse(((string)tenantIdValue));
propertiesInstance.TenantId = tenantIdInstance;
}
JToken skuValue = propertiesValue["sku"];
if (skuValue != null && skuValue.Type != JTokenType.Null)
{
Sku skuInstance = new Sku();
propertiesInstance.Sku = skuInstance;
JToken familyValue = skuValue["family"];
if (familyValue != null && familyValue.Type != JTokenType.Null)
{
string familyInstance = ((string)familyValue);
skuInstance.Family = familyInstance;
}
JToken nameValue = skuValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
skuInstance.Name = nameInstance;
}
}
JToken accessPoliciesArray = propertiesValue["accessPolicies"];
if (accessPoliciesArray != null && accessPoliciesArray.Type != JTokenType.Null)
{
foreach (JToken accessPoliciesValue in ((JArray)accessPoliciesArray))
{
AccessPolicyEntry accessPolicyEntryInstance = new AccessPolicyEntry();
propertiesInstance.AccessPolicies.Add(accessPolicyEntryInstance);
JToken tenantIdValue2 = accessPoliciesValue["tenantId"];
if (tenantIdValue2 != null && tenantIdValue2.Type != JTokenType.Null)
{
Guid tenantIdInstance2 = Guid.Parse(((string)tenantIdValue2));
accessPolicyEntryInstance.TenantId = tenantIdInstance2;
}
JToken objectIdValue = accessPoliciesValue["objectId"];
if (objectIdValue != null && objectIdValue.Type != JTokenType.Null)
{
Guid objectIdInstance = Guid.Parse(((string)objectIdValue));
accessPolicyEntryInstance.ObjectId = objectIdInstance;
}
JToken applicationIdValue = accessPoliciesValue["applicationId"];
if (applicationIdValue != null && applicationIdValue.Type != JTokenType.Null)
{
Guid applicationIdInstance = Guid.Parse(((string)applicationIdValue));
accessPolicyEntryInstance.ApplicationId = applicationIdInstance;
}
JToken permissionsValue = accessPoliciesValue["permissions"];
if (permissionsValue != null && permissionsValue.Type != JTokenType.Null)
{
string permissionsInstance = permissionsValue.ToString(Newtonsoft.Json.Formatting.Indented);
accessPolicyEntryInstance.PermissionsRawJsonString = permissionsInstance;
}
}
}
JToken enabledForDeploymentValue = propertiesValue["enabledForDeployment"];
if (enabledForDeploymentValue != null && enabledForDeploymentValue.Type != JTokenType.Null)
{
bool enabledForDeploymentInstance = ((bool)enabledForDeploymentValue);
propertiesInstance.EnabledForDeployment = enabledForDeploymentInstance;
}
JToken enabledForDiskEncryptionValue = propertiesValue["enabledForDiskEncryption"];
if (enabledForDiskEncryptionValue != null && enabledForDiskEncryptionValue.Type != JTokenType.Null)
{
bool enabledForDiskEncryptionInstance = ((bool)enabledForDiskEncryptionValue);
propertiesInstance.EnabledForDiskEncryption = enabledForDiskEncryptionInstance;
}
JToken enabledForTemplateDeploymentValue = propertiesValue["enabledForTemplateDeployment"];
if (enabledForTemplateDeploymentValue != null && enabledForTemplateDeploymentValue.Type != JTokenType.Null)
{
bool enabledForTemplateDeploymentInstance = ((bool)enabledForTemplateDeploymentValue);
propertiesInstance.EnabledForTemplateDeployment = enabledForTemplateDeploymentInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
vaultInstance.Id = idInstance;
}
JToken nameValue2 = responseDoc["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
vaultInstance.Name = nameInstance2;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
vaultInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
vaultInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
vaultInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The List operation gets information about the vaults associated
/// either with the subscription if no resource group is specified or
/// within the specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// Optional. An optional argument which specifies the name of the
/// resource group that constrains the set of vaults that are returned.
/// </param>
/// <param name='top'>
/// Required. Maximum number of results to return.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of vaults
/// </returns>
public async Task<VaultListResponse> ListAsync(string resourceGroupName, int top, CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("top", top);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
if (resourceGroupName != null)
{
url = url + Uri.EscapeDataString(resourceGroupName);
}
url = url + "/resources";
List<string> queryParameters = new List<string>();
List<string> odataFilter = new List<string>();
odataFilter.Add("resourceType eq 'Microsoft.KeyVault/vaults' ");
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter));
}
queryParameters.Add("$top=" + Uri.EscapeDataString(top.ToString()));
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VaultListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VaultListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Vault vaultInstance = new Vault();
result.Vaults.Add(vaultInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
VaultProperties propertiesInstance = new VaultProperties();
vaultInstance.Properties = propertiesInstance;
JToken vaultUriValue = propertiesValue["vaultUri"];
if (vaultUriValue != null && vaultUriValue.Type != JTokenType.Null)
{
string vaultUriInstance = ((string)vaultUriValue);
propertiesInstance.VaultUri = vaultUriInstance;
}
JToken tenantIdValue = propertiesValue["tenantId"];
if (tenantIdValue != null && tenantIdValue.Type != JTokenType.Null)
{
Guid tenantIdInstance = Guid.Parse(((string)tenantIdValue));
propertiesInstance.TenantId = tenantIdInstance;
}
JToken skuValue = propertiesValue["sku"];
if (skuValue != null && skuValue.Type != JTokenType.Null)
{
Sku skuInstance = new Sku();
propertiesInstance.Sku = skuInstance;
JToken familyValue = skuValue["family"];
if (familyValue != null && familyValue.Type != JTokenType.Null)
{
string familyInstance = ((string)familyValue);
skuInstance.Family = familyInstance;
}
JToken nameValue = skuValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
skuInstance.Name = nameInstance;
}
}
JToken accessPoliciesArray = propertiesValue["accessPolicies"];
if (accessPoliciesArray != null && accessPoliciesArray.Type != JTokenType.Null)
{
foreach (JToken accessPoliciesValue in ((JArray)accessPoliciesArray))
{
AccessPolicyEntry accessPolicyEntryInstance = new AccessPolicyEntry();
propertiesInstance.AccessPolicies.Add(accessPolicyEntryInstance);
JToken tenantIdValue2 = accessPoliciesValue["tenantId"];
if (tenantIdValue2 != null && tenantIdValue2.Type != JTokenType.Null)
{
Guid tenantIdInstance2 = Guid.Parse(((string)tenantIdValue2));
accessPolicyEntryInstance.TenantId = tenantIdInstance2;
}
JToken objectIdValue = accessPoliciesValue["objectId"];
if (objectIdValue != null && objectIdValue.Type != JTokenType.Null)
{
Guid objectIdInstance = Guid.Parse(((string)objectIdValue));
accessPolicyEntryInstance.ObjectId = objectIdInstance;
}
JToken applicationIdValue = accessPoliciesValue["applicationId"];
if (applicationIdValue != null && applicationIdValue.Type != JTokenType.Null)
{
Guid applicationIdInstance = Guid.Parse(((string)applicationIdValue));
accessPolicyEntryInstance.ApplicationId = applicationIdInstance;
}
JToken permissionsValue = accessPoliciesValue["permissions"];
if (permissionsValue != null && permissionsValue.Type != JTokenType.Null)
{
string permissionsInstance = permissionsValue.ToString(Newtonsoft.Json.Formatting.Indented);
accessPolicyEntryInstance.PermissionsRawJsonString = permissionsInstance;
}
}
}
JToken enabledForDeploymentValue = propertiesValue["enabledForDeployment"];
if (enabledForDeploymentValue != null && enabledForDeploymentValue.Type != JTokenType.Null)
{
bool enabledForDeploymentInstance = ((bool)enabledForDeploymentValue);
propertiesInstance.EnabledForDeployment = enabledForDeploymentInstance;
}
JToken enabledForDiskEncryptionValue = propertiesValue["enabledForDiskEncryption"];
if (enabledForDiskEncryptionValue != null && enabledForDiskEncryptionValue.Type != JTokenType.Null)
{
bool enabledForDiskEncryptionInstance = ((bool)enabledForDiskEncryptionValue);
propertiesInstance.EnabledForDiskEncryption = enabledForDiskEncryptionInstance;
}
JToken enabledForTemplateDeploymentValue = propertiesValue["enabledForTemplateDeployment"];
if (enabledForTemplateDeploymentValue != null && enabledForTemplateDeploymentValue.Type != JTokenType.Null)
{
bool enabledForTemplateDeploymentInstance = ((bool)enabledForTemplateDeploymentValue);
propertiesInstance.EnabledForTemplateDeployment = enabledForTemplateDeploymentInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
vaultInstance.Id = idInstance;
}
JToken nameValue2 = valueValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
vaultInstance.Name = nameInstance2;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
vaultInstance.Type = typeInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
vaultInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
vaultInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get the next set of vaults based on the previously returned
/// NextLink value.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of vaults
/// </returns>
public async Task<VaultListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
VaultListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new VaultListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Vault vaultInstance = new Vault();
result.Vaults.Add(vaultInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
VaultProperties propertiesInstance = new VaultProperties();
vaultInstance.Properties = propertiesInstance;
JToken vaultUriValue = propertiesValue["vaultUri"];
if (vaultUriValue != null && vaultUriValue.Type != JTokenType.Null)
{
string vaultUriInstance = ((string)vaultUriValue);
propertiesInstance.VaultUri = vaultUriInstance;
}
JToken tenantIdValue = propertiesValue["tenantId"];
if (tenantIdValue != null && tenantIdValue.Type != JTokenType.Null)
{
Guid tenantIdInstance = Guid.Parse(((string)tenantIdValue));
propertiesInstance.TenantId = tenantIdInstance;
}
JToken skuValue = propertiesValue["sku"];
if (skuValue != null && skuValue.Type != JTokenType.Null)
{
Sku skuInstance = new Sku();
propertiesInstance.Sku = skuInstance;
JToken familyValue = skuValue["family"];
if (familyValue != null && familyValue.Type != JTokenType.Null)
{
string familyInstance = ((string)familyValue);
skuInstance.Family = familyInstance;
}
JToken nameValue = skuValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
skuInstance.Name = nameInstance;
}
}
JToken accessPoliciesArray = propertiesValue["accessPolicies"];
if (accessPoliciesArray != null && accessPoliciesArray.Type != JTokenType.Null)
{
foreach (JToken accessPoliciesValue in ((JArray)accessPoliciesArray))
{
AccessPolicyEntry accessPolicyEntryInstance = new AccessPolicyEntry();
propertiesInstance.AccessPolicies.Add(accessPolicyEntryInstance);
JToken tenantIdValue2 = accessPoliciesValue["tenantId"];
if (tenantIdValue2 != null && tenantIdValue2.Type != JTokenType.Null)
{
Guid tenantIdInstance2 = Guid.Parse(((string)tenantIdValue2));
accessPolicyEntryInstance.TenantId = tenantIdInstance2;
}
JToken objectIdValue = accessPoliciesValue["objectId"];
if (objectIdValue != null && objectIdValue.Type != JTokenType.Null)
{
Guid objectIdInstance = Guid.Parse(((string)objectIdValue));
accessPolicyEntryInstance.ObjectId = objectIdInstance;
}
JToken applicationIdValue = accessPoliciesValue["applicationId"];
if (applicationIdValue != null && applicationIdValue.Type != JTokenType.Null)
{
Guid applicationIdInstance = Guid.Parse(((string)applicationIdValue));
accessPolicyEntryInstance.ApplicationId = applicationIdInstance;
}
JToken permissionsValue = accessPoliciesValue["permissions"];
if (permissionsValue != null && permissionsValue.Type != JTokenType.Null)
{
string permissionsInstance = permissionsValue.ToString(Newtonsoft.Json.Formatting.Indented);
accessPolicyEntryInstance.PermissionsRawJsonString = permissionsInstance;
}
}
}
JToken enabledForDeploymentValue = propertiesValue["enabledForDeployment"];
if (enabledForDeploymentValue != null && enabledForDeploymentValue.Type != JTokenType.Null)
{
bool enabledForDeploymentInstance = ((bool)enabledForDeploymentValue);
propertiesInstance.EnabledForDeployment = enabledForDeploymentInstance;
}
JToken enabledForDiskEncryptionValue = propertiesValue["enabledForDiskEncryption"];
if (enabledForDiskEncryptionValue != null && enabledForDiskEncryptionValue.Type != JTokenType.Null)
{
bool enabledForDiskEncryptionInstance = ((bool)enabledForDiskEncryptionValue);
propertiesInstance.EnabledForDiskEncryption = enabledForDiskEncryptionInstance;
}
JToken enabledForTemplateDeploymentValue = propertiesValue["enabledForTemplateDeployment"];
if (enabledForTemplateDeploymentValue != null && enabledForTemplateDeploymentValue.Type != JTokenType.Null)
{
bool enabledForTemplateDeploymentInstance = ((bool)enabledForTemplateDeploymentValue);
propertiesInstance.EnabledForTemplateDeployment = enabledForTemplateDeploymentInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
vaultInstance.Id = idInstance;
}
JToken nameValue2 = valueValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
vaultInstance.Name = nameInstance2;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
vaultInstance.Type = typeInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
vaultInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
vaultInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| 53.403555 | 186 | 0.426504 | [
"Apache-2.0"
] | ailn/azure-sdk-for-net | src/ResourceManagement/KeyVaultManagement/KeyVaultManagement/Generated/VaultOperations.cs | 81,120 | C# |
using System;
using TestWrapper.Container.Multi.Base;
using TestWrapper.Facades.Info;
using TestWrapper.Utils.Exceptions;
using TestWrapper.Workers.Wrappers;
namespace TestWrapper.Facades
{
internal abstract class WorkFacade<TWorkerWrapper, TMultiContainer> : IWorkFacade
where TWorkerWrapper : class, IWorkerWrapper
where TMultiContainer : class, IMultiContainer
{
protected TMultiContainer MultiContainer => _multiContainer;
protected TWorkerWrapper WorkerWrapper => _workerWrapper;
private readonly TMultiContainer _multiContainer;
private readonly TWorkerWrapper _workerWrapper;
private readonly IWorkWrapperInfo _info;
public WorkFacade(string testName, TWorkerWrapper workerWrapper, TMultiContainer multiContainer)
{
_workerWrapper = workerWrapper;
_multiContainer = multiContainer;
_info = new WorkWrapperInfo(testName, WorkerWrapper.Info(), _multiContainer.Info());
}
#region SetUp
public void SetUp()
{
try
{
SetUpUnSafe();
_workerWrapper.CustomSetUp();
}
catch (Exception e)
{
throw new TestRunnerException(nameof(SetUp), Info(), e);
}
}
protected virtual void SetUpUnSafe()
{
_multiContainer.SetUp();
}
#endregion
#region Run
public void Run()
{
try
{
_workerWrapper.Run();
}
catch (Exception e)
{
throw new TestRunnerException(nameof(Run), Info(), e);
}
}
#endregion
#region CleanUp
public void CleanUp()
{
try
{
_workerWrapper.CustomCleanUp();
CleanUpUnSafe();
}
catch (Exception e)
{
throw new TestRunnerException(nameof(CleanUp), Info(), e);
}
}
protected virtual void CleanUpUnSafe()
{
_multiContainer.CleanUp();
}
#endregion
public IWorkWrapperInfo Info()
{
return _info;
}
}
} | 25.108696 | 104 | 0.549784 | [
"MIT"
] | ErikMoczi/Unity.TestRunner.Jobs | Assets/TestWrapper/Facades/WorkFacade.cs | 2,312 | C# |
using System;
using System.Globalization;
namespace NosAyudamos
{
[NoExport]
public abstract class DomainEvent : IEventMetadata
{
protected DomainEvent() => EventId = PreciseTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ", CultureInfo.InvariantCulture);
[System.Text.Json.Serialization.JsonIgnore]
[Newtonsoft.Json.JsonIgnore]
public string EventId { get; set; }
[System.Text.Json.Serialization.JsonIgnore]
[Newtonsoft.Json.JsonIgnore]
public DateTime EventTime { get; set; } = DateTime.UtcNow;
[System.Text.Json.Serialization.JsonIgnore]
[Newtonsoft.Json.JsonIgnore]
public string? SourceId { get; set; }
[System.Text.Json.Serialization.JsonIgnore]
[Newtonsoft.Json.JsonIgnore]
public int Version { get; set; }
/// <devdoc>
/// When surfacing the <see cref="EventId"/> for use outside the owning
/// <see cref="DomainObject"/>, we must ensure that the identifier is globally
/// unique. Since it's based on a (however precise) timing, we add the domain
/// object identifier as a suffix, which would guarantee uniqueness since it's
/// impossible to genenerate two identical identifiers in a single process
/// by using our <see cref="PreciseTime"/> (there's a unit test for that). And
/// it's highly unlikely that the same domain object will be processed simultaneously
/// and generate a new event at the exact same time in two processes or machines
/// within a 10th of a microsecond of another.
/// </devdoc>
string IEventMetadata.EventId => EventId + "_" + SourceId;
DateTime? IEventMetadata.EventTime => EventTime;
string? IEventMetadata.Subject => SourceId;
/// <summary>
/// The other type of event is a System-generated one, outside of a <see cref="DomainObject"/>.
/// </summary>
string? IEventMetadata.Topic => "Domain";
}
}
| 40.46 | 135 | 0.652496 | [
"MIT"
] | devlooped/api.nosayudamos.org | Core/Infrastructure/DomainEvent.cs | 2,025 | C# |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace BookShop.Data.Repositories
{
public class BookShopRepository<T> : IBookShopRepository<T> where T : class
{
private DbContext context;
private IDbSet<T> set;
public BookShopRepository(DbContext context)
{
this.context = context;
this.set = context.Set<T>();
}
public IQueryable<T> All()
{
return this.set;
}
public T Find(object id)
{
return this.set.Find(id);
}
public IQueryable<T> Search(Expression<Func<T, bool>> predicate)
{
return this.set.Where(predicate);
}
public T Add(T entity)
{
this.ChangeState(entity, EntityState.Added);
return entity;
}
public void Update(T entity)
{
this.ChangeState(entity, EntityState.Modified);
}
public void Update(object id)
{
var entity = this.Find(id);
if (null != entity)
{
this.ChangeState(entity, EntityState.Modified);
}
}
public T Delete(object Id)
{
var entity = this.Find(Id);
if (null != entity)
{
this.ChangeState(entity, EntityState.Deleted);
}
return entity;
}
public T Delete(T entity)
{
this.ChangeState(entity, EntityState.Deleted);
return entity;
}
public void Detach(T entity)
{
this.ChangeState(entity, EntityState.Detached);
}
public void Attach(T entity)
{
this.set.Attach(entity);
}
public int SaveChanges()
{
return this.context.SaveChanges();
}
private void ChangeState(T entity, EntityState state)
{
var entry = this.context.Entry(entity);
if (entry.State == EntityState.Detached)
{
this.set.Attach(entity);
}
entry.State = state;
}
}
}
| 23.11 | 79 | 0.515794 | [
"MIT"
] | ttitto/WebDevelopment | Web Services and Cloud/WebApiServicesHW/BookShop/BookShop.Data/Repositories/BookShopRepository.cs | 2,313 | C# |
namespace UblTr.Common
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
[System.Xml.Serialization.XmlRootAttribute("OperatingYearsQuantity", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2", IsNullable = false)]
public partial class OperatingYearsQuantityType : QuantityType1
{
}
} | 53 | 177 | 0.777015 | [
"MIT"
] | enisgurkann/UblTr | Ubl-Tr/Common/CommonBasicComponents/OperatingYearsQuantityType.cs | 583 | C# |
using System;
using System.Reflection;
namespace DragonSpark.Composition
{
public struct AppliedExport
{
public AppliedExport( Type subject, MemberInfo location, Type exportAs )
{
Subject = subject;
Location = location;
ExportAs = exportAs;
}
public Type Subject {get; }
public MemberInfo Location { get; }
public Type ExportAs { get; }
}
} | 17.52381 | 74 | 0.711957 | [
"MIT"
] | DragonSpark/VoteReporter | Framework/DragonSpark/Composition/AppliedExport.cs | 368 | C# |
using System.Text.Json.Serialization;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// AlipayOpenAppDeveloperCheckdevelopervalidQueryModel Data Structure.
/// </summary>
public class AlipayOpenAppDeveloperCheckdevelopervalidQueryModel : AlipayObject
{
/// <summary>
/// 支付宝账号
/// </summary>
[JsonPropertyName("logon_id")]
public string LogonId { get; set; }
}
}
| 26.588235 | 83 | 0.661504 | [
"MIT"
] | LuohuaRain/payment | src/Essensoft.AspNetCore.Payment.Alipay/Domain/AlipayOpenAppDeveloperCheckdevelopervalidQueryModel.cs | 464 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
class TcpListener
{
public static IPAddress getIp()
{
string host = Dns.GetHostName();
var address = Dns.GetHostEntry(host);
foreach (var ip in address.AddressList)
{
return ip;
}
return null;
}
public static void getData(Socket handler, Socket listener)
{
String data = null;
byte[] bytes = null;
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("8==.") > -1)
{
break;
}
Console.WriteLine("TEXT RECEIVED: " + data);
listener.Listen(100);
handler = listener.Accept();
}
}
public static void socketInit(IPEndPoint endPoint, IPAddress ip)
{
Socket listener = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(endPoint);
listener.Listen(100);
Console.WriteLine("Awaiting connection...\n");
Socket handler = listener.Accept();
Console.WriteLine("Connected!");
getData(handler, listener);
}
public static void Main(string[] Args)
{
//try{
Int32 port = 6942;
IPAddress ip = getIp();
IPEndPoint ipEndPoint = new IPEndPoint(ip, port);
Console.WriteLine("ENDPOINT:" + ipEndPoint);
socketInit(ipEndPoint, ip);
//}
}
}
| 22.932432 | 92 | 0.553329 | [
"MIT"
] | RacoonCode/KeyLogger | server/main.cs | 1,697 | C# |
// Different states of the game
public enum GameState
{
NotStarted,
Started,
Paused,
GameOver
} | 12.555556 | 32 | 0.654867 | [
"MIT"
] | ThaiDuongVu/MoonPath | Assets/Scripts/GameState.cs | 115 | C# |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json.Serialization;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
#if DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
{
[TestFixture]
public class CustomContractResolver : TestFixtureBase
{
#region Types
public class DynamicContractResolver : DefaultContractResolver
{
private readonly char _startingWithChar;
public DynamicContractResolver(char startingWithChar)
{
_startingWithChar = startingWithChar;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
// only serializer properties that start with the specified character
properties =
properties.Where(p => p.PropertyName.StartsWith(_startingWithChar.ToString())).ToList();
return properties;
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName
{
get { return FirstName + " " + LastName; }
}
}
#endregion
[Test]
public void Example()
{
#region Usage
Person person = new Person
{
FirstName = "Dennis",
LastName = "Deepwater-Diver"
};
string startingWithF = JsonConvert.SerializeObject(person, Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('F') });
Console.WriteLine(startingWithF);
// {
// "FirstName": "Dennis",
// "FullName": "Dennis Deepwater-Diver"
// }
string startingWithL = JsonConvert.SerializeObject(person, Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('L') });
Console.WriteLine(startingWithL);
// {
// "LastName": "Deepwater-Diver"
// }
#endregion
Assert.AreEqual(@"{
""LastName"": ""Deepwater-Diver""
}", startingWithL);
}
}
} | 33.104348 | 119 | 0.641713 | [
"MIT"
] | jkorell/Newtonsoft.Json | Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/CustomContractResolver.cs | 3,809 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using gView.Framework.Data;
using gView.Framework.Geometry;
using System.IO;
using System.Xml;
using gView.Framework.system;
using gView.Framework.Carto;
using gView.Framework.OGC.GML;
using gView.Framework.FDB;
namespace gView.Interoperability.OGC.Dataset.GML
{
[gView.Framework.system.RegisterPlugIn("DBABE7F1-FE46-4731-AB2B-8A324C60554E")]
public class Dataset : DatasetMetadata, IFeatureDataset
{
private string _connectionString;
private DatasetState _state = DatasetState.unknown;
private IEnvelope _envelope = null;
private ISpatialReference _sRef = null;
private string _errMsg = "";
private XmlDocument _doc = null;
private XmlNamespaceManager _ns = null;
private XmlNode _featureCollection = null;
private List<IDatasetElement> _elements = new List<IDatasetElement>();
private string _gml_file = "", _xsd_file = "";
private Database _database = new Database();
private GmlVersion _gmlVersion = GmlVersion.v1;
public XmlNamespaceManager NamespaceManager
{
get { return _ns; }
}
public XmlNode FeatureCollection
{
get { return _featureCollection; }
}
public string GmlFileName
{
get { return _gml_file; }
}
public bool Delete()
{
try
{
if (_state != DatasetState.opened) return false;
FileInfo fi = new FileInfo(_gml_file);
if(fi.Exists) fi.Delete();
fi = new FileInfo(_xsd_file);
if(fi.Exists) fi.Delete();
return true;
}
catch
{
return false;
}
}
internal GMLFile GMLFile
{
get
{
try
{
if (_state != DatasetState.opened) return null;
FileInfo fi = new FileInfo(_connectionString);
if (fi.Exists)
{
return new GMLFile(_connectionString);
}
return null;
}
catch
{
return null;
}
}
}
internal string targetNamespace
{
get
{
if (_ns == null) return String.Empty;
return _ns.LookupNamespace("myns");
}
}
#region IFeatureDataset Member
public gView.Framework.Geometry.IEnvelope Envelope
{
get { return _envelope; }
}
public gView.Framework.Geometry.ISpatialReference SpatialReference
{
get
{
return _sRef;
}
set
{
_sRef = value;
}
}
#endregion
#region IDataset Member
public string ConnectionString
{
get
{
return _connectionString;
}
set
{
_connectionString = value;
_database.DirectoryName = _connectionString;
}
}
public string DatasetGroupName
{
get { return "OGC/GML Dataset"; }
}
public string DatasetName
{
get { return "GML Dataset"; }
}
public string ProviderName
{
get { return "gView GML Provider"; }
}
public DatasetState State
{
get { return _state; }
}
public bool Open()
{
try
{
_state = DatasetState.unknown;
_elements.Clear();
FileInfo fi_gml = new FileInfo(_connectionString);
if (!fi_gml.Exists) return false;
FileInfo fi_xsd = new FileInfo(fi_gml.FullName.Substring(0, fi_gml.FullName.Length - fi_gml.Extension.Length) + ".xsd");
if (!fi_xsd.Exists) return false;
_gml_file = fi_gml.FullName;
_xsd_file = fi_xsd.FullName;
XmlDocument schema = new XmlDocument();
schema.Load(fi_xsd.FullName);
XmlSchemaReader schemaReader = new XmlSchemaReader(schema);
string targetNamespace = schemaReader.TargetNamespaceURI;
if (targetNamespace == String.Empty) return false;
PlugInManager compMan = new PlugInManager();
foreach (string elementName in schemaReader.ElementNames)
{
string shapeFieldName;
geometryType geomType;
Fields fields = schemaReader.ElementFields(elementName, out shapeFieldName, out geomType);
FeatureClass fc = new FeatureClass(this, elementName, fields);
fc.ShapeFieldName = shapeFieldName;
fc.GeometryType = geomType;
IFeatureLayer layer = LayerFactory.Create(fc) as IFeatureLayer;
if (layer == null) continue;
//layer.FeatureRenderer = compMan.getComponent(KnownObjects.Carto_UniversalGeometryRenderer) as IFeatureRenderer;
_elements.Add(layer);
}
XmlTextReader xmlTextReader = new XmlTextReader(fi_gml.FullName);
xmlTextReader.ReadToDescendant("boundedBy", "http://www.opengis.net/gml");
string boundedBy = xmlTextReader.ReadOuterXml();
_doc = new XmlDocument();
_doc.LoadXml(boundedBy);
_ns = new XmlNamespaceManager(_doc.NameTable);
_ns.AddNamespace("GML", "http://www.opengis.net/gml");
_ns.AddNamespace("WFS", "http://www.opengis.net/wfs");
_ns.AddNamespace("OGC", "http://www.opengis.net/ogc");
_ns.AddNamespace("myns", targetNamespace);
XmlNode boundedByNode = _doc.ChildNodes[0];
if (boundedByNode != null)
{
XmlNode geomNode = boundedByNode.SelectSingleNode("GML:*", _ns);
if (geomNode != null)
{
_envelope = GeometryTranslator.GML2Geometry(geomNode.OuterXml, _gmlVersion) as IEnvelope;
if (geomNode.Attributes["srsName"] != null)
{
_sRef = gView.Framework.Geometry.SpatialReference.FromID(geomNode.Attributes["srsName"].Value);
}
}
}
_state = DatasetState.opened;
return true;
}
catch(Exception ex)
{
_errMsg = ex.Message;
return false;
}
}
public string lastErrorMsg
{
get { return _errMsg; }
}
public List<IDatasetElement> Elements
{
get
{
return ListOperations<IDatasetElement>.Clone(_elements);
}
}
public string Query_FieldPrefix
{
get { return ""; }
}
public string Query_FieldPostfix
{
get { return ""; }
}
public gView.Framework.FDB.IDatabase Database
{
get { return _database; }
}
public IDatasetElement this[string title]
{
get
{
foreach (IDatasetElement element in _elements)
if (element.Title == title) return element;
try
{
DirectoryInfo di = new DirectoryInfo(_connectionString);
if (!di.Exists) return null;
Dataset ds = new Dataset();
ds.ConnectionString = di + @"\" + title + ".gml";
if (ds.Open())
{
return ds[title];
}
}
catch { }
return null;
}
}
public void RefreshClasses()
{
}
#endregion
#region IDisposable Member
public void Dispose()
{
}
#endregion
}
}
| 29.211604 | 136 | 0.493399 | [
"MIT"
] | chandusekhar/gViewGisOS | gView.Interoperability.OGC/Dataset/GML/Dataset.cs | 8,559 | C# |
using System;
namespace PSTk.Networking
{
/// <summary>
/// Represents current flag of connection routines.
/// </summary>
[Flags, Obsolete]
public enum ConnectionFlag
{
/// <summary>
/// When not listening for inbound connections.
/// </summary>
Idle,
/// <summary>
/// When listening for inbound traffic.
/// </summary>
Listening,
/// <summary>
/// When listener aborted and no new connection is stablished along inbound traffic.
/// </summary>
Aborted
}
}
| 21.740741 | 92 | 0.550256 | [
"MIT"
] | Devwarlt/core-algorithms | PSTk.Networking/ConnectionFlag.cs | 589 | C# |
//-----------------------------------------------------------------------
// <copyright file="KnowledgeSourceBase.cs" company="Breanos GmbH">
// Copyright Notice:
// DAIPAN - This file, program or part of a program is considered part of the DAIPAN framework by Breanos GmbH for Industrie 4.0
// Published in 2018 by Gerhard Eder gerhard.eder@breanos.com and Achim Bernhard achim.bernhard@breanos.com
// To the extent possible under law, the publishers have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
// You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
// <date>Monday, December 3, 2018 3:34:35 PM</date>
// </copyright>
//-----------------------------------------------------------------------
///////////////////////////////////////////////////////////
// KnowledgeSourceBase.cs
// Implementation of the Class KnowledgeSourceBase
// Generated by Enterprise Architect
// Created on: 02-Feb-2018 10:26:57
// Original author: bezdedeanu
///////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using NLog;
using AssistantUtilities;
namespace BlackboardClassLibrary.KnowledgeSources
{
/// <summary>
/// Abstracte Basisklasse für eine KS
/// </summary>
public abstract class KnowledgeSourceBase : IKnowledgeSource
{
/// <summary>
/// Logger variable
/// </summary>
//private static Logger logger = LogManager.GetCurrentClassLogger();
private static BreanosLogger logger;
/// <summary>
/// Referenz auf das Blackboard
/// </summary>
internal Blackboard.Blackboard blackboard;
/// <summary>
/// Öffentlicher Konstruktor
/// </summary>
public KnowledgeSourceBase()
{
if (logger == null) logger = BreanosLoggerFactory.DuplicateGet(Blackboard.Blackboard.BlackboardLoggerKey, nameof(KnowledgeSourceBase));
}
/// <summary>
/// Destruktor
/// </summary>
~KnowledgeSourceBase()
{
}
/// <summary>
/// Jede KS kennt das Blackboard
/// </summary>
/// <param name="blackboard"></param>
public virtual void Configure(Blackboard.Blackboard blackboard)
{
logger.Debug("KnowledgeSourceBase.Configure called");
this.blackboard = blackboard;
}
/// <summary>
/// Wird konkret in jeder KU implementiert
/// </summary>
public virtual void ExecuteAction()
{
}
/// <summary>
/// KUs können abgeschalten werden.
/// </summary>
public virtual bool IsEnabled { get; set; } = true;
/// <summary>
/// Legt den KS Type fest
/// </summary>
public abstract KnowledgeSourceType KSType { get; }
/// <summary>
/// Jede KS hat eine Priorität
/// </summary>
public virtual KnowledgeSourcePriority Priority { get; set; }
}//end KnowledgeSourceBase
}
| 33.428571 | 215 | 0.586081 | [
"CC0-1.0"
] | BREANOS-ABE/daipan | Assistant/Assistant/BlackboardClassLibrary/KnowledgeSources/KnowledgeSourceBase.cs | 3,282 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TygaSoft.BLL;
using TygaSoft.Model;
namespace TygaSoft.Web.Admin.Sys
{
public partial class AddCategory : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Bind();
}
}
private void Bind()
{
Guid Id = Guid.Empty;
if (!string.IsNullOrWhiteSpace(Request.QueryString["Id"]))
{
Guid.TryParse(Request.QueryString["Id"], out Id);
}
string action = Request.QueryString["action"];
switch (action)
{
case "add":
InitAdd(Id);
break;
case "edit":
InitEdit(Id);
break;
default:
break;
}
}
private void InitAdd(Guid parentId)
{
hParentId.Value = parentId.ToString();
var bll = new Category();
txtCode.Value = bll.CreateCode(parentId);
}
private void InitEdit(Guid Id)
{
var bll = new Category();
var model = bll.GetModel(Id);
if (model != null)
{
hId.Value = model.Id.ToString();
hParentId.Value = model.ParentId.ToString();
txtCode.Value = model.CategoryCode;
txtName.Value = model.CategoryName;
txtRemark.Value = model.Remark;
txtSort.Value = model.Sort.ToString();
}
}
}
} | 27.276923 | 70 | 0.481105 | [
"MIT"
] | Arainsd/Wms | src/TygaSoft/Web/Admin/Base/AddCategory.aspx.cs | 1,775 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Linq;
#if ASPNETWEBAPI
using System.Web.Http.Routing.Constraints;
#else
using System.Web.Mvc.Routing.Constraints;
using System.Web.Routing;
#endif
using Microsoft.TestCommon;
#if ASPNETWEBAPI
namespace System.Web.Http.Routing
#else
namespace System.Web.Mvc.Routing
#endif
{
public class InlineRouteTemplateParserTests
{
#if ASPNETWEBAPI
private static readonly RouteParameter OptionalParameter = RouteParameter.Optional;
#else
private static readonly UrlParameter OptionalParameter = UrlParameter.Optional;
#endif
[Fact]
public void ParseRouteTemplate_ChainedConstraintAndDefault()
{
var result = Act(@"hello/{param:int=111111}");
Assert.Equal("hello/{param}", result.RouteUrl);
Assert.Equal("111111", result.Defaults["param"]);
Assert.IsType<IntRouteConstraint>(result.Constraints["param"]);
}
[Fact]
public void ParseRouteTemplate_ChainedConstraintWithArgumentsAndDefault()
{
var result = Act(@"hello/{param:regex(\d+)=111111}");
Assert.Equal("hello/{param}", result.RouteUrl);
Assert.Equal("111111", result.Defaults["param"]);
var regexRouteConstraint = Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]);
Assert.Equal(@"\d+", regexRouteConstraint.Pattern);
}
[Fact]
public void ParseRouteTemplate_ChainedConstraintAndOptional()
{
var result = Act(@"hello/{param:int?}");
Assert.Equal("hello/{param}", result.RouteUrl);
Assert.Equal(OptionalParameter, result.Defaults["param"]);
var constraint = Assert.IsType<OptionalRouteConstraint>(result.Constraints["param"]);
Assert.IsType<IntRouteConstraint>(constraint.InnerConstraint);
}
[Fact]
public void ParseRouteTemplate_ChainedConstraintWithArgumentsAndOptional()
{
var result = Act(@"hello/{param:regex(\d+)?}");
Assert.Equal("hello/{param}", result.RouteUrl);
Assert.Equal(OptionalParameter, result.Defaults["param"]);
var constraint = Assert.IsType<OptionalRouteConstraint>(result.Constraints["param"]);
Assert.Equal(@"\d+", Assert.IsType<RegexRouteConstraint>(constraint.InnerConstraint).Pattern);
}
[Fact]
public void ParseRouteTemplate_ChainedConstraints()
{
var result = Act(@"hello/{param:regex(\d+):regex(\w+)}");
Assert.Equal("hello/{param}", result.RouteUrl);
CompoundRouteConstraint constraint = Assert.IsType<CompoundRouteConstraint>(result.Constraints["param"]);
Assert.Equal(@"\d+", Assert.IsType<RegexRouteConstraint>(constraint.Constraints.ElementAt(0)).Pattern);
Assert.Equal(@"\w+", Assert.IsType<RegexRouteConstraint>(constraint.Constraints.ElementAt(1)).Pattern);
}
[Fact]
public void ParseRouteTemplate_Constraint()
{
var result = Act(@"hello/{param:regex(\d+)}");
Assert.Equal("hello/{param}", result.RouteUrl);
var constraint = Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]);
Assert.Equal(@"\d+", constraint.Pattern);
}
[Fact]
public void ParseRouteTemplate_ConstraintsDefaultsAndOptionalsInMultipleSections()
{
var result = Act(@"some/url-{p1:alpha:length(3)=hello}/{p2=abc}/{p3?}");
Assert.Equal("some/url-{p1}/{p2}/{p3}", result.RouteUrl);
Assert.Equal("hello", result.Defaults["p1"]);
Assert.Equal("abc", result.Defaults["p2"]);
Assert.Equal(OptionalParameter, result.Defaults["p3"]);
CompoundRouteConstraint constraint = Assert.IsType<CompoundRouteConstraint>(result.Constraints["p1"]);
Assert.IsType<AlphaRouteConstraint>(constraint.Constraints.ElementAt(0));
Assert.IsType<LengthRouteConstraint>(constraint.Constraints.ElementAt(1));
}
[Fact]
public void ParseRouteTemplate_NoTokens()
{
var result = Act("hello/world");
Assert.Equal("hello/world", result.RouteUrl);
}
[Fact]
public void ParseRouteTemplate_OptionalParam()
{
var result = Act("hello/{param?}");
Assert.Equal("hello/{param}", result.RouteUrl);
Assert.Equal(OptionalParameter, result.Defaults["param"]);
}
[Fact]
public void ParseRouteTemplate_ParamDefault()
{
var result = Act("hello/{param=world}");
Assert.Equal("hello/{param}", result.RouteUrl);
Assert.Equal("world", result.Defaults["param"]);
}
[Fact]
public void ParseRouteTemplate_RegexConstraintWithClosingBraceInPattern()
{
var result = Act(@"hello/{param:regex(\})}");
Assert.Equal("hello/{param}", result.RouteUrl);
var constraint = Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]);
Assert.Equal(@"\}", constraint.Pattern);
}
[Fact]
public void ParseRouteTemplate_RegexConstraintWithClosingParenInPattern()
{
var result = Act(@"hello/{param:regex(\))}");
Assert.Equal("hello/{param}", result.RouteUrl);
var constraint = Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]);
Assert.Equal(@"\)", constraint.Pattern);
}
[Fact]
public void ParseRouteTemplate_RegexConstraintWithColonInPattern()
{
var result = Act(@"hello/{param:regex(:)}");
Assert.Equal("hello/{param}", result.RouteUrl);
var constraint = Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]);
Assert.Equal(@":", constraint.Pattern);
}
[Fact]
public void ParseRouteTemplate_RegexConstraintWithCommaInPattern()
{
var result = Act(@"hello/{param:regex(\w,\w)}");
Assert.Equal("hello/{param}", result.RouteUrl);
var constraint = Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]);
Assert.Equal(@"\w,\w", constraint.Pattern);
}
[Fact]
public void ParseRouteTemplate_RegexConstraintWithEqualsSignInPattern()
{
var result = Act(@"hello/{param:regex(=)}");
Assert.Equal("hello/{param}", result.RouteUrl);
Assert.DoesNotContain("param", result.Defaults.Keys);
var constraint = Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]);
Assert.Equal(@"=", constraint.Pattern);
}
[Fact]
public void ParseRouteTemplate_RegexConstraintWithOpenBraceInPattern()
{
var result = Act(@"hello/{param:regex(\{)}");
Assert.Equal("hello/{param}", result.RouteUrl);
var constraint = Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]);
Assert.Equal(@"\{", constraint.Pattern);
}
[Fact]
public void ParseRouteTemplate_RegexConstraintWithOpenParenInPattern()
{
var result = Act(@"hello/{param:regex(\()}");
Assert.Equal("hello/{param}", result.RouteUrl);
var constraint = Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]);
Assert.Equal(@"\(", constraint.Pattern);
}
[Fact]
public void ParseRouteTemplate_RegexConstraintWithQuestionMarkInPattern()
{
var result = Act(@"hello/{param:regex(\?)}");
Assert.Equal("hello/{param}", result.RouteUrl);
Assert.DoesNotContain("param", result.Defaults.Keys);
var constraint = Assert.IsType<RegexRouteConstraint>(result.Constraints["param"]);
Assert.Equal(@"\?", constraint.Pattern);
}
private ParseResult Act(string template)
{
var result = new ParseResult();
#if ASPNETWEBAPI
result.Constraints = new HttpRouteValueDictionary();
result.Defaults = new HttpRouteValueDictionary();
#else
result.Constraints = new RouteValueDictionary();
result.Defaults = new RouteValueDictionary();
#endif
result.RouteUrl = InlineRouteTemplateParser.ParseRouteTemplate(template, result.Defaults, result.Constraints, new DefaultInlineConstraintResolver());
return result;
}
struct ParseResult
{
public string RouteUrl;
#if ASPNETWEBAPI
public HttpRouteValueDictionary Defaults;
public HttpRouteValueDictionary Constraints;
#else
public RouteValueDictionary Defaults;
public RouteValueDictionary Constraints;
#endif
}
}
}
| 36.003968 | 161 | 0.623278 | [
"Apache-2.0"
] | 1508553303/AspNetWebStack | test/Common/Routing/InlineRouteTemplateParserTests.cs | 9,073 | C# |
/*
* Copyright(c) 2022 nifanfa, This code is part of the Moos licensed under the MIT licence.
*/
using Internal.Runtime.CompilerServices;
using System.Runtime.InteropServices;
static class GDT
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct GDTEntry
{
public ushort LimitLow;
public ushort BaseLow;
public byte BaseMid;
public byte Access;
public byte LimitHigh_Flags;
public byte BaseHigh;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct GDTDescriptor
{
public ushort Limit;
public ulong Base;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct TSSEntry
{
public ushort LimitLow;
public ushort BaseLow;
public byte BaseMidLow;
public byte Access;
public byte LimitHigh_Flags;
public byte BaseMidHigh;
public uint BaseHigh;
public uint Reserved;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct TSS
{
public uint Reserved0;
public uint Rsp0Low;
public uint Rsp0High;
public uint Rsp1Low;
public uint Rsp1High;
public uint Rsp2Low;
public uint Rsp2High;
public uint Reserved1;
public uint Reserved2;
public uint Ist1Low;
public uint Ist1High;
public uint Ist2Low;
public uint Ist2High;
public uint Ist3Low;
public uint Ist3High;
public uint Ist4Low;
public uint Ist4High;
public uint Ist5Low;
public uint Ist5High;
public uint Ist6Low;
public uint Ist6High;
public uint Ist7Low;
public uint Ist7High;
public ulong Reserved3;
public ushort Reserved4;
public ushort IOMapBase;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct GDTS
{
public GDTEntry Empty;
public GDTEntry KernelCode;
public GDTEntry KernelData;
public TSSEntry TSS;
}
static TSS tss;
static GDTS gdts;
static GDTDescriptor gdtr;
public static void Initialise()
{
gdts.KernelCode.LimitLow = 0xFFFF;
gdts.KernelCode.Access = 0x9A;
gdts.KernelCode.LimitHigh_Flags = 0xAF;
gdts.KernelData.LimitLow = 0xFFFF;
gdts.KernelData.Access = 0x92;
gdts.KernelData.LimitHigh_Flags = 0xCF;
unsafe
{
fixed (TSS* _tss = &tss)
{
var addr = (ulong)_tss;
gdts.TSS.LimitLow = (ushort)(Unsafe.SizeOf<TSS>() - 1);
gdts.TSS.BaseLow = (ushort)(addr & 0xFFFF);
gdts.TSS.BaseMidLow = (byte)((addr >> 16) & 0xFF);
gdts.TSS.BaseMidHigh = (byte)((addr >> 24) & 0xFF);
gdts.TSS.BaseHigh = (uint)(addr >> 32);
gdts.TSS.Access = 0x89;
gdts.TSS.LimitHigh_Flags = 0x80;
}
}
unsafe
{
fixed (GDTS* _gdts = &gdts)
{
gdtr.Limit = (ushort)(Unsafe.SizeOf<GDTEntry>() * 3 - 1);
gdtr.Base = (ulong)_gdts;
}
}
Native.Load_GDT(ref gdtr);
}
} | 26.268293 | 91 | 0.57165 | [
"MIT"
] | nifanfa/OS-Sharp64 | Kernel/Misc/GDT.cs | 3,231 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Global settings for Volumetric Lines rendering
/// </summary>
public class VolumetricLineSettings : MonoBehaviour
{
/// <summary>
/// If set to true, volumetric lines rendering will not apply scaling based on the
/// camera's field of view.
/// By default (which means, this property is set to false), scaling is enabled,
/// which means, that for varying field of view values, volumetric lines will have
/// a constant line width.
/// </summary>
[SerializeField]
private bool m_disableFieldOfViewScaling;
// Use this for initialization
void Awake ()
{
if (m_disableFieldOfViewScaling)
{
Shader.EnableKeyword("FOV_SCALING_OFF");
}
else
{
Shader.DisableKeyword("FOV_SCALING_OFF");
}
}
}
| 24.457143 | 85 | 0.691589 | [
"MIT"
] | VnceGd/CS345_FinalProject | Assets/VolumetricLines/Scripts/VolumetricLineSettings.cs | 858 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Settings Flyout item template is documented at http://go.microsoft.com/fwlink/?LinkId=273769
namespace Eqstra.DocumentDelivery.Views
{
public sealed partial class AddCustomerPage : SettingsFlyout
{
public AddCustomerPage()
{
this.InitializeComponent();
}
private void CellNumber_KeyDown(object sender, KeyRoutedEventArgs e)
{
if ((e.Key < VirtualKey.Number0) || (e.Key > VirtualKey.Number9))
{
e.Handled = true;
}
}
}
}
| 26.918919 | 99 | 0.694779 | [
"MIT"
] | pithline/FMS | Pithline.FMS.DocumentDelivery/Views/AddCustomerPage.xaml.cs | 998 | C# |
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Project.Scripts.Game;
using Project.Scripts.Sprites;
using Project.Scripts.Timer;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
// using Random = UnityEngine.Random;
namespace Project.Scripts.Output
{
/// <summary>
/// Abstract base class
/// </summary>
public abstract class OutputPresenter
{
/// <summary>
/// Base constructor
/// </summary>
/// <param name="symbol"></param>
protected OutputPresenter(Image symbol)
{
}
}
/// <summary>
/// Class to present the players symbol output
/// </summary>
[UsedImplicitly]
public sealed class PlayerOutputPresenter : OutputPresenter
{
/// <summary>
/// Static variables (private/public)
/// </summary>
public static int inputId;
private static Image _playerSymbol;
/// <summary>
/// Public constructor
/// </summary>
/// <param name="playerSymbol"></param>
public PlayerOutputPresenter(Image playerSymbol): base(playerSymbol)
{
_playerSymbol = playerSymbol;
}
/// <summary>
/// Select player output
/// </summary>
/// <param name="input"></param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void SelectPlayerOutput(string output)
{
// Assign an id to the player output based on input provided
inputId = Array.FindIndex(GamePresenter.spriteOptions, s => s.name == output);
}
/// <summary>
/// Show the players output
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ShowPlayerOutput()
{
// Based on the input id set above show the final symbol
var spriteName = GamePresenter.spriteOptions[inputId].name;
ImageAtlasPresenter.LoadAtlas(_playerSymbol, null, spriteName);
}
/// <summary>
/// Reset the players output
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ResetPlayerOutput()
{
// Assign default sprite to player image
ImageAtlasPresenter.LoadAtlas(_playerSymbol, null, "question_mark");
}
}
/// <summary>
/// Class to present AI's symbol output
/// </summary>
[UsedImplicitly]
public sealed class AIOutputPresenter : OutputPresenter
{
/// <summary>
/// Constants
/// </summary>
private const string url = "http://www.randomnumberapi.com/api/v1.0/random?min=0&max=2&count=1";
/// <summary>
/// Static variables (private/public)
/// </summary>
public static int aiFinalResult;
private static Image _opponentSymbol;
/// <summary>
/// Public constructor
/// </summary>
/// <param name="opponentSymbol"></param>
public AIOutputPresenter(Image opponentSymbol):base(opponentSymbol)
{
_opponentSymbol = opponentSymbol;
}
/// <summary>
/// Select AI's output randomly
/// </summary>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static async void SelectAIRandomOutput()
{
// Read the url and store it in a web request
var www = UnityWebRequest.Get(url);
// Begin communication with remote server and wait till operation is completed
var operation = www.SendWebRequest();
while (!operation.isDone)
await Task.Yield();
// Check if there are are any errors or not
if (www.result == UnityWebRequest.Result.Success)
{
// Parse data as text
var urlData = www.downloadHandler.text;
// Convert the text output into string
var tempDataArray = urlData.Split('[');
var tempData = tempDataArray[1];
var finalDataArray = tempData.Split(']');
// Parse integer value from string and store it in variable
aiFinalResult = int.Parse(finalDataArray[0]);
// Start the timer
LevelTimerPresenter.StartTimer();
}
else
Debug.LogError(www.error); // Show error message in console
}
// [MethodImpl(MethodImplOptions.AggressiveInlining)]
// public static void SelectAIRandomOutput()
// {
// // Select the AI output from a range of numbers from 0 to length of the options array
// aiFinalResult = Random.Range(0, GamePresenter.spriteOptions.Length);
//
// // Start the timer
// LevelTimerPresenter.StartTimer();
// }
/// <summary>
/// Show the AI's output
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ShowAIOutput()
{
// Based on the result found above show the final symbol
var spriteName = GamePresenter.spriteOptions[aiFinalResult].name;
ImageAtlasPresenter.LoadAtlas(_opponentSymbol, null, spriteName);
}
/// <summary>
/// Reset the AI's output
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ResetAIOutput()
{
// Assign default sprite to AI image
ImageAtlasPresenter.LoadAtlas(_opponentSymbol, null, "question_mark");
}
}
}
| 33.638418 | 104 | 0.567686 | [
"MIT"
] | shantanumaskeri/unity-position-test | Assets/Project/Scripts/Output/OutputPresenter.cs | 5,954 | C# |
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using ICSharpCode.Decompiler.Tests.Helpers;
using NUnit.Framework;
namespace ICSharpCode.Decompiler.Tests
{
[TestFixture, Parallelizable(ParallelScope.All)]
public class ILPrettyTestRunner
{
static readonly string TestCasePath = Tester.TestCasePath + "/ILPretty";
[Test]
public void AllFilesHaveTests()
{
var testNames = typeof(ILPrettyTestRunner).GetMethods()
.Where(m => m.GetCustomAttributes(typeof(TestAttribute), false).Any())
.Select(m => m.Name)
.ToArray();
foreach (var file in new DirectoryInfo(TestCasePath).EnumerateFiles()) {
if (file.Extension.Equals(".il", StringComparison.OrdinalIgnoreCase)) {
var testName = file.Name.Split('.')[0];
Assert.Contains(testName, testNames);
Assert.IsTrue(File.Exists(Path.Combine(TestCasePath, testName + ".cs")));
}
}
}
[Test, Ignore("Need to decide how to represent virtual methods without 'newslot' flag")]
public void Issue379()
{
Run();
}
[Test]
public void Issue646()
{
Run();
}
[Test]
public void Issue684()
{
Run();
}
[Test]
public void Issue959()
{
Run();
}
[Test]
public void Issue982()
{
Run();
}
[Test]
public void Issue1038()
{
Run();
}
[Test]
public void Issue1047()
{
Run();
}
[Test]
public void Issue1389()
{
Run();
}
[Test]
public void Issue1918()
{
Run();
}
[Test]
public void Issue1922()
{
Run();
}
[Test]
public void FSharpUsing_Debug()
{
Run(settings: new DecompilerSettings { RemoveDeadStores = true });
}
[Test]
public void FSharpUsing_Release()
{
Run(settings: new DecompilerSettings { RemoveDeadStores = true });
}
[Test]
public void DirectCallToExplicitInterfaceImpl()
{
Run();
}
[Test]
public void CS1xSwitch_Debug()
{
Run();
}
[Test]
public void CS1xSwitch_Release()
{
Run();
}
[Test]
public void Issue1145()
{
Run();
}
[Test]
public void Issue1157()
{
Run();
}
[Test]
public void Issue1256()
{
Run();
}
[Test]
public void Issue1323()
{
Run();
}
[Test]
public void Issue1325()
{
Run();
}
[Test]
public void Issue1681()
{
Run();
}
[Test]
public void Issue1454()
{
Run();
}
[Test]
public void ConstantBlobs()
{
Run();
}
[Test]
public void SequenceOfNestedIfs()
{
Run();
}
[Test]
public void Unsafe()
{
Run();
}
[Test]
public void FSharpLoops_Debug()
{
CopyFSharpCoreDll();
Run(settings: new DecompilerSettings { RemoveDeadStores = true });
}
[Test]
public void FSharpLoops_Release()
{
CopyFSharpCoreDll();
Run(settings: new DecompilerSettings { RemoveDeadStores = true });
}
[Test]
public void WeirdEnums()
{
Run();
}
void Run([CallerMemberName] string testName = null, DecompilerSettings settings = null)
{
var ilFile = Path.Combine(TestCasePath, testName + ".il");
var csFile = Path.Combine(TestCasePath, testName + ".cs");
var executable = Tester.AssembleIL(ilFile, AssemblerOptions.Library);
var decompiled = Tester.DecompileCSharp(executable, settings);
CodeAssert.FilesAreEqual(csFile, decompiled);
}
static readonly object copyLock = new object();
static void CopyFSharpCoreDll()
{
lock (copyLock) {
if (File.Exists(Path.Combine(TestCasePath, "FSharp.Core.dll")))
return;
string fsharpCoreDll = Path.Combine(TestCasePath, "..\\..\\..\\ILSpy-tests\\FSharp\\FSharp.Core.dll");
if (!File.Exists(fsharpCoreDll))
Assert.Ignore("Ignored because of missing ILSpy-tests repo. Must be checked out separately from https://github.com/icsharpcode/ILSpy-tests!");
File.Copy(fsharpCoreDll, Path.Combine(TestCasePath, "FSharp.Core.dll"));
}
}
}
}
| 20.416327 | 147 | 0.668932 | [
"MIT"
] | zer0Kerbal/ILSpy | ICSharpCode.Decompiler.Tests/ILPrettyTestRunner.cs | 5,004 | C# |
using System.Collections.Generic;
namespace Selfnet
{
public class Spout
{
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Dictionary<string, ParameterDescriptor> Params { get; set; }
}
}
| 22.846154 | 75 | 0.622896 | [
"MIT"
] | gleroi/selfnet | Selfnet/Spout.cs | 299 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AllReady.Areas.Admin.Features.Itineraries;
using AllReady.Features.Notifications;
using AllReady.Models;
using MediatR;
using Microsoft.AspNetCore.Mvc.Rendering;
using Moq;
using Xunit;
namespace AllReady.UnitTest.Areas.Admin.Features.Itineraries
{
public class AddTeamMemberCommandHandlerAsyncTests : InMemoryContextTest
{
protected override void LoadTestData()
{
var htb = new Organization
{
Name = "Humanitarian Toolbox",
LogoUrl = "http://www.htbox.org/upload/home/ht-hero.png",
WebUrl = "http://www.htbox.org",
Campaigns = new List<Campaign>()
};
var firePrev = new Campaign
{
Name = "Neighborhood Fire Prevention Days",
ManagingOrganization = htb
};
htb.Campaigns.Add(firePrev);
var queenAnne = new Event
{
Id = 1,
Name = "Queen Anne Fire Prevention Day",
Campaign = firePrev,
CampaignId = firePrev.Id,
StartDateTime = new DateTime(2015, 7, 4, 10, 0, 0).ToUniversalTime(),
EndDateTime = new DateTime(2015, 12, 31, 15, 0, 0).ToUniversalTime(),
Location = new Location { Id = 1 },
RequiredSkills = new List<EventSkill>(),
EventType = EventType.Itinerary
};
var itinerary = new Itinerary
{
Event = queenAnne,
Name = "1st Itinerary",
Id = 1,
Date = new DateTime(2016, 07, 01)
};
Context.Organizations.Add(htb);
Context.Campaigns.Add(firePrev);
Context.Events.Add(queenAnne);
Context.Itineraries.Add(itinerary);
Context.SaveChanges();
}
[Fact]
public async Task AddTeamMemberCommandHandlerAsyncReturnsFalseWhenItineraryDoesNotExist()
{
var query = new AddTeamMemberCommand
{
ItineraryId = 0,
TaskSignupId = 1
};
var handler = new AddTeamMemberCommandHandlerAsync(Context, null);
var result = await handler.Handle(query);
Assert.Equal(false, result);
}
[Fact]
public async Task AddTeamMemberCommandHandlerAsyncReturnsTrueWhenItineraryExists()
{
var query = new AddTeamMemberCommand
{
ItineraryId = 1,
TaskSignupId = 1
};
var handler = new AddTeamMemberCommandHandlerAsync(Context, Mock.Of<IMediator>());
var result = await handler.Handle(query);
Assert.Equal(true, result);
}
[Fact]
public async Task AddTeamMemberCommandHandlerAsyncSendsPotentialItineraryTeamMemberQueryWithCorrectEventId()
{
var query = new AddTeamMemberCommand
{
ItineraryId = 1,
TaskSignupId = 1
};
var mockMediator = new Mock<IMediator>();
var handler = new AddTeamMemberCommandHandlerAsync(Context, mockMediator.Object);
await handler.Handle(query);
mockMediator.Verify(x => x.SendAsync(It.Is<PotentialItineraryTeamMembersQuery>(y => y.EventId == 1)), Times.Once);
}
[Fact(Skip = "RTM Broken Tests")]
public async Task AddTeamMemberCommandHandlerAsyncPublishesItineraryVolunteerListUpdatedWhenMatchedOnTaskSignupId()
{
var query = new AddTeamMemberCommand
{
ItineraryId = 1,
TaskSignupId = 1
};
var potentialTaskSignups = new List<SelectListItem>
{
new SelectListItem
{
Text = "user@domain.tld : Test TaskName",
Value = query.TaskSignupId.ToString()
}
};
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(x => x.SendAsync(It.IsAny<PotentialItineraryTeamMembersQuery>())).ReturnsAsync(potentialTaskSignups);
var handler = new AddTeamMemberCommandHandlerAsync(Context, mockMediator.Object);
await handler.Handle(query);
mockMediator.Verify(x => x.PublishAsync(It.Is<IntineraryVolunteerListUpdated>(y => y.TaskSignupId == query.TaskSignupId && y.ItineraryId == query.ItineraryId && y.UpdateType == UpdateType.VolunteerAssigned)), Times.Once);
}
}
} | 34.522059 | 233 | 0.569542 | [
"MIT"
] | digitaldrummerj-ionic/allReady | AllReadyApp/Web-App/AllReady.UnitTest/Areas/Admin/Features/Itineraries/AddTeamMemberCommandHandlerAsyncTests.cs | 4,697 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="HtmlIndexFormatter.cs" company="PicklesDoc">
// Copyright 2011 Jeffrey Cameron
// Copyright 2012-present PicklesDoc team and community contributors
//
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO.Abstractions;
using System.Linq;
using System.Xml.Linq;
using PicklesDoc.Pickles.DirectoryCrawler;
using PicklesDoc.Pickles.Extensions;
namespace PicklesDoc.Pickles.DocumentationBuilders.Html
{
public class HtmlIndexFormatter
{
private readonly XNamespace xmlns = HtmlNamespace.Xhtml;
public XElement Format(INode node, IEnumerable<INode> features)
{
/*
<div id="feature">
<h1>Folder Name</h1>
<ul class="list">
<li><a href="[link]"><span class="title">[title]</span><span class="separator"> - </span><span class="description">[description]</span></a></li>
<li><a href="[link]"><span class="title">[title]</span><span class="separator"> - </span><span class="description">[description]</span></a></li>
<li><a href="[link]"><span class="title">[title]</span><span class="separator"> - </span><span class="description">[description]</span></a></li>
</ul>
<div>
*/
var directoryInfo = node.OriginalLocation as IDirectoryInfo;
if (directoryInfo == null)
{
throw new ArgumentOutOfRangeException("node", "Argument node must contain a DirectoryInfo.");
}
string[] files = directoryInfo.GetFiles().Select(f => f.FullName).ToArray();
INode[] featuresThatAreDirectChildrenOfFolder =
features.Where(f => f.OriginalLocation is IFileInfo).Where(
f => files.Contains(f.OriginalLocation.FullName)).ToArray();
var div = new XElement(
this.xmlns + "div",
new XAttribute("id", "feature"),
new XElement(this.xmlns + "h1", node.Name));
MarkdownNode markdownNode =
featuresThatAreDirectChildrenOfFolder.Where(n => n.IsIndexMarkDownNode()).OfType<MarkdownNode>().FirstOrDefault();
if (markdownNode != null)
{
div.Add(
new XElement(
this.xmlns + "div",
new XAttribute("class", "folderDescription"),
markdownNode.MarkdownContent));
}
div.Add(this.FormatList(node, featuresThatAreDirectChildrenOfFolder.OfType<FeatureNode>().OrderBy(feature => feature.Name)));
return div;
}
private XElement FormatList(INode node, IEnumerable<FeatureNode> items)
{
// <ul class="list">...</ul>
var list = new XElement(this.xmlns + "ul", new XAttribute("class", "list"));
foreach (
XElement li in
items.Select(
item =>
this.FormatListItem(item.GetRelativeUriTo(node.OriginalLocationUrl), item.Feature.Name, item.Feature.Description)))
{
list.Add(li);
}
return list;
}
private XElement FormatListItem(string link, string title, string description)
{
// <li><a href="[link]"><span class="title">[title]</span><span class="separator"> - </span><span class="description">[description]</span></a></li>
return new XElement(
this.xmlns + "li",
new XElement(
this.xmlns + "a",
new XAttribute("href", link),
new XElement(
this.xmlns + "span",
new XAttribute("class", "title"),
title),
new XElement(
this.xmlns + "span",
new XAttribute("class", "separator"),
" - "),
new XElement(
this.xmlns + "span",
new XAttribute("class", "description"),
description)));
}
}
}
| 41.106557 | 159 | 0.531406 | [
"Apache-2.0"
] | CoverGo/pickles | src/Pickles.DocumentationBuilders.Html/HtmlIndexFormatter.cs | 5,015 | C# |
using UnityEditor;
using UnityEngine;
namespace UGFramework.UGEditor
{
public class CommandToolxample : ScriptableObject
{
[MenuItem(MenuConfig.EXAMPLES + "/CommandTool/Shell")]
public static void Shell()
{
var filePath = "UGEditor/CommandTool/CommandToolExample/Shell.sh";
CommandTool.ExecuteShell(filePath);
}
}
} | 22.333333 | 69 | 0.755224 | [
"MIT"
] | Lu-Kye/UGFramework | Assets/UGEditor/CommandTool/CommandToolExample/Editor/CommandToolExample.cs | 337 | 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.
#nullable disable
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Composition;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
{
public partial class TestWorkspace
{
private const string CSharpExtension = ".cs";
private const string CSharpScriptExtension = ".csx";
private const string VisualBasicExtension = ".vb";
private const string VisualBasicScriptExtension = ".vbx";
private const string WorkspaceElementName = "Workspace";
private const string ProjectElementName = "Project";
private const string SubmissionElementName = "Submission";
private const string MetadataReferenceElementName = "MetadataReference";
private const string MetadataReferenceFromSourceElementName = "MetadataReferenceFromSource";
private const string ProjectReferenceElementName = "ProjectReference";
private const string CompilationOptionsElementName = "CompilationOptions";
private const string RootNamespaceAttributeName = "RootNamespace";
private const string OutputTypeAttributeName = "OutputType";
private const string ReportDiagnosticAttributeName = "ReportDiagnostic";
private const string CryptoKeyFileAttributeName = "CryptoKeyFile";
private const string StrongNameProviderAttributeName = "StrongNameProvider";
private const string DelaySignAttributeName = "DelaySign";
private const string ParseOptionsElementName = "ParseOptions";
private const string LanguageVersionAttributeName = "LanguageVersion";
private const string FeaturesAttributeName = "Features";
private const string DocumentationModeAttributeName = "DocumentationMode";
private const string DocumentElementName = "Document";
private const string AdditionalDocumentElementName = "AdditionalDocument";
private const string AnalyzerConfigDocumentElementName = "AnalyzerConfigDocument";
private const string AnalyzerElementName = "Analyzer";
private const string AssemblyNameAttributeName = "AssemblyName";
private const string CommonReferencesAttributeName = "CommonReferences";
private const string CommonReferencesWithoutValueTupleAttributeName =
"CommonReferencesWithoutValueTuple";
private const string CommonReferencesWinRTAttributeName = "CommonReferencesWinRT";
private const string CommonReferencesNet45AttributeName = "CommonReferencesNet45";
private const string CommonReferencesPortableAttributeName = "CommonReferencesPortable";
private const string CommonReferencesNetCoreAppName = "CommonReferencesNetCoreApp";
private const string CommonReferencesNetStandard20Name = "CommonReferencesNetStandard20";
private const string FilePathAttributeName = "FilePath";
private const string FoldersAttributeName = "Folders";
private const string KindAttributeName = "Kind";
private const string LanguageAttributeName = "Language";
private const string GlobalImportElementName = "GlobalImport";
private const string IncludeXmlDocCommentsAttributeName = "IncludeXmlDocComments";
private const string IsLinkFileAttributeName = "IsLinkFile";
private const string LinkAssemblyNameAttributeName = "LinkAssemblyName";
private const string LinkProjectNameAttributeName = "LinkProjectName";
private const string LinkFilePathAttributeName = "LinkFilePath";
private const string PreprocessorSymbolsAttributeName = "PreprocessorSymbols";
private const string AnalyzerDisplayAttributeName = "Name";
private const string AnalyzerFullPathAttributeName = "FullPath";
private const string AliasAttributeName = "Alias";
private const string ProjectNameAttribute = "Name";
private const string CheckOverflowAttributeName = "CheckOverflow";
private const string AllowUnsafeAttributeName = "AllowUnsafe";
private const string OutputKindName = "OutputKind";
private const string NullableAttributeName = "Nullable";
private const string DocumentFromSourceGeneratorElementName = "DocumentFromSourceGenerator";
/// <summary>
/// Creates a single buffer in a workspace.
/// </summary>
/// <param name="content">Lines of text, the buffer contents</param>
internal static TestWorkspace Create(
string language,
CompilationOptions compilationOptions,
ParseOptions parseOptions,
string content
)
{
return Create(language, compilationOptions, parseOptions, new[] { content });
}
/// <summary>
/// Creates a single buffer in a workspace.
/// </summary>
/// <param name="content">Lines of text, the buffer contents</param>
internal static TestWorkspace Create(
string workspaceKind,
string language,
CompilationOptions compilationOptions,
ParseOptions parseOptions,
string content
)
{
return Create(
workspaceKind,
language,
compilationOptions,
parseOptions,
new[] { content }
);
}
/// <param name="files">Can pass in multiple file contents: files will be named test1.cs, test2.cs, etc.</param>
internal static TestWorkspace Create(
string language,
CompilationOptions compilationOptions,
ParseOptions parseOptions,
params string[] files
)
{
return Create(language, compilationOptions, parseOptions, files, exportProvider: null);
}
/// <param name="files">Can pass in multiple file contents: files will be named test1.cs, test2.cs, etc.</param>
internal static TestWorkspace Create(
string workspaceKind,
string language,
CompilationOptions compilationOptions,
ParseOptions parseOptions,
params string[] files
)
{
return Create(
language,
compilationOptions,
parseOptions,
files,
exportProvider: null,
workspaceKind: workspaceKind
);
}
internal static string GetDefaultTestSourceDocumentName(int index, string extension) =>
"test" + (index + 1) + extension;
internal static TestWorkspace Create(
string language,
CompilationOptions compilationOptions,
ParseOptions parseOptions,
string[] files,
ExportProvider exportProvider = null,
TestComposition composition = null,
string[] metadataReferences = null,
string workspaceKind = null,
string extension = null,
bool commonReferences = true,
bool openDocuments = false,
IDocumentServiceProvider documentServiceProvider = null
)
{
var workspaceElement = CreateWorkspaceElement(
language,
compilationOptions,
parseOptions,
files,
metadataReferences,
extension,
commonReferences
);
return Create(
workspaceElement,
openDocuments,
exportProvider,
composition,
workspaceKind,
documentServiceProvider
);
}
internal static TestWorkspace Create(
string language,
CompilationOptions compilationOptions,
ParseOptions[] parseOptions,
string[] files,
ExportProvider exportProvider
)
{
Debug.Assert(
parseOptions == null || (files.Length == parseOptions.Length),
"Please specify a parse option for each file."
);
var documentElements = new List<XElement>();
var index = 0;
string extension;
for (var i = 0; i < files.Length; i++)
{
if (language == LanguageNames.CSharp)
{
extension =
parseOptions[i].Kind == SourceCodeKind.Regular
? CSharpExtension
: CSharpScriptExtension;
}
else if (language == LanguageNames.VisualBasic)
{
extension =
parseOptions[i].Kind == SourceCodeKind.Regular
? VisualBasicExtension
: VisualBasicScriptExtension;
}
else
{
extension = language;
}
documentElements.Add(
CreateDocumentElement(
files[i],
GetDefaultTestSourceDocumentName(index++, extension),
parseOptions == null ? null : parseOptions[i]
)
);
}
var workspaceElement = CreateWorkspaceElement(
CreateProjectElement(
"Test",
language,
true,
parseOptions.FirstOrDefault(),
compilationOptions,
documentElements
)
);
return Create(workspaceElement, exportProvider: exportProvider);
}
#region C#
public static TestWorkspace CreateCSharp(
string file,
ParseOptions parseOptions = null,
CompilationOptions compilationOptions = null,
ExportProvider exportProvider = null,
TestComposition composition = null,
string[] metadataReferences = null,
bool openDocuments = false
)
{
return CreateCSharp(
new[] { file },
parseOptions,
compilationOptions,
exportProvider,
composition,
metadataReferences,
openDocuments
);
}
public static TestWorkspace CreateCSharp(
string[] files,
ParseOptions parseOptions = null,
CompilationOptions compilationOptions = null,
ExportProvider exportProvider = null,
TestComposition composition = null,
string[] metadataReferences = null,
bool openDocuments = false
)
{
return Create(
LanguageNames.CSharp,
compilationOptions,
parseOptions,
files,
exportProvider,
composition,
metadataReferences,
openDocuments: openDocuments
);
}
public static TestWorkspace CreateCSharp2(
string[] files,
ParseOptions[] parseOptions = null,
CompilationOptions compilationOptions = null,
ExportProvider exportProvider = null
)
{
return Create(
LanguageNames.CSharp,
compilationOptions,
parseOptions,
files,
exportProvider
);
}
#endregion
#region VB
public static TestWorkspace CreateVisualBasic(
string file,
ParseOptions parseOptions = null,
CompilationOptions compilationOptions = null,
ExportProvider exportProvider = null,
TestComposition composition = null,
string[] metadataReferences = null,
bool openDocuments = false
)
{
return CreateVisualBasic(
new[] { file },
parseOptions,
compilationOptions,
exportProvider,
composition,
metadataReferences,
openDocuments
);
}
public static TestWorkspace CreateVisualBasic(
string[] files,
ParseOptions parseOptions = null,
CompilationOptions compilationOptions = null,
ExportProvider exportProvider = null,
TestComposition composition = null,
string[] metadataReferences = null,
bool openDocuments = false
)
{
return Create(
LanguageNames.VisualBasic,
compilationOptions,
parseOptions,
files,
exportProvider,
composition,
metadataReferences,
openDocuments: openDocuments
);
}
/// <param name="files">Can pass in multiple file contents with individual source kind: files will be named test1.vb, test2.vbx, etc.</param>
public static TestWorkspace CreateVisualBasic(
string[] files,
ParseOptions[] parseOptions = null,
CompilationOptions compilationOptions = null,
ExportProvider exportProvider = null
)
{
return Create(
LanguageNames.VisualBasic,
compilationOptions,
parseOptions,
files,
exportProvider
);
}
#endregion
}
}
| 38.49589 | 149 | 0.588357 | [
"MIT"
] | belav/roslyn | src/EditorFeatures/TestUtilities/Workspaces/TestWorkspace_Create.cs | 14,053 | C# |
using System;
using NetOffice;
using NetOffice.Attributes;
namespace NetOffice.MSHTMLApi.Enums
{
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
[EntityType(EntityType.IsEnum)]
public enum _htmlRules
{
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <remarks>0</remarks>
[SupportByVersion("MSHTML", 4)]
htmlRulesNotSet = 0,
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <remarks>1</remarks>
[SupportByVersion("MSHTML", 4)]
htmlRulesnone = 1,
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <remarks>2</remarks>
[SupportByVersion("MSHTML", 4)]
htmlRulesgroups = 2,
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <remarks>3</remarks>
[SupportByVersion("MSHTML", 4)]
htmlRulesrows = 3,
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <remarks>4</remarks>
[SupportByVersion("MSHTML", 4)]
htmlRulescols = 4,
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <remarks>5</remarks>
[SupportByVersion("MSHTML", 4)]
htmlRulesall = 5,
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <remarks>2147483647</remarks>
[SupportByVersion("MSHTML", 4)]
htmlRules_Max = 2147483647
}
} | 21.887097 | 36 | 0.61238 | [
"MIT"
] | DominikPalo/NetOffice | Source/MSHTML/Enums/_htmlRules.cs | 1,359 | C# |
/***********************************************
EasyTouch V
Copyright © 2014-2015 The Hedgehog Team
http://www.thehedgehogteam.com/Forum/
The.Hedgehog.Team@gmail.com
**********************************************/
using UnityEngine;
using System.Collections;
using UnityEngine.Events;
using UnityEngine.EventSystems;
namespace HedgehogTeam.EasyTouch{
[AddComponentMenu("EasyTouch/Quick Twist")]
public class QuickTwist : QuickBase {
#region Events
[System.Serializable] public class OnTwistAction : UnityEvent<Gesture>{}
[SerializeField]
public OnTwistAction onTwistAction;
#endregion
#region enumeration
public enum ActionTiggering {InProgress,End};
public enum ActionRotationDirection {All, Clockwise, Counterclockwise};
#endregion
#region Members
public bool isGestureOnMe = false;
public ActionTiggering actionTriggering;
public ActionRotationDirection rotationDirection;
private float axisActionValue = 0;
public bool enableSimpleAction = false;
#endregion
#region MonoBehaviour callback
public QuickTwist(){
quickActionName = "QuickTwist"+ System.Guid.NewGuid().ToString().Substring(0,7);
}
public override void OnEnable(){
EasyTouch.On_Twist += On_Twist;
EasyTouch.On_TwistEnd += On_TwistEnd;
}
public override void OnDisable(){
UnsubscribeEvent();
}
void OnDestroy(){
UnsubscribeEvent();
}
void UnsubscribeEvent(){
EasyTouch.On_Twist -= On_Twist;
EasyTouch.On_TwistEnd -= On_TwistEnd;
}
#endregion
#region EasyTouch event
void On_Twist (Gesture gesture){
if (actionTriggering == ActionTiggering.InProgress){
if (IsRightRotation(gesture)){
DoAction( gesture);
}
}
}
void On_TwistEnd (Gesture gesture){
if (actionTriggering == ActionTiggering.End){
if (IsRightRotation(gesture)){
DoAction( gesture);
}
}
}
#endregion
#region Private method
bool IsRightRotation(Gesture gesture){
axisActionValue =0;
float coef = 1;
if ( inverseAxisValue){
coef = -1;
}
switch (rotationDirection){
case ActionRotationDirection.All:
axisActionValue = gesture.twistAngle * sensibility * coef;
return true;
case ActionRotationDirection.Clockwise:
if (gesture.twistAngle<0){
axisActionValue = gesture.twistAngle * sensibility* coef;
return true;
}
break;
case ActionRotationDirection.Counterclockwise:
if (gesture.twistAngle>0){
axisActionValue = gesture.twistAngle * sensibility* coef;
return true;
}
break;
}
return false;
}
void DoAction(Gesture gesture){
if (isGestureOnMe){
if ( realType == GameObjectType.UI){
if (gesture.isOverGui ){
if ((gesture.pickedUIElement == gameObject || gesture.pickedUIElement.transform.IsChildOf( transform))){
onTwistAction.Invoke(gesture);
if (enableSimpleAction){
DoDirectAction( axisActionValue);
}
}
}
}
else{
if ((!enablePickOverUI && gesture.pickedUIElement == null) || enablePickOverUI){
if (gesture.GetCurrentPickedObject( true) == gameObject){
onTwistAction.Invoke(gesture);
if (enableSimpleAction){
DoDirectAction( axisActionValue);
}
}
}
}
}
else{
if ((!enablePickOverUI && gesture.pickedUIElement == null) || enablePickOverUI){
onTwistAction.Invoke(gesture);
if (enableSimpleAction){
DoDirectAction( axisActionValue);
}
}
}
}
#endregion
}
}
| 22.222222 | 109 | 0.690294 | [
"MIT"
] | 11one/PanzerWar | Assets/ExtraPlugins/EasyTouchBundle/EasyTouch/Plugins/Components/QuickTwist.cs | 3,401 | C# |
using System;
namespace Xamarin.Forms
{
public class OnAppTheme<T> : BindingBase
{
WeakReference<BindableObject> _weakTarget;
BindableProperty _targetProperty;
public OnAppTheme()
{
Application.Current.RequestedThemeChanged += ThemeChanged;
}
void ThemeChanged(object sender, AppThemeChangedEventArgs e)
{
Device.BeginInvokeOnMainThread(() => ApplyCore());
}
public new BindingMode Mode
{
get => base.Mode;
private set { }
}
internal override BindingBase Clone()
{
return new OnAppTheme<T> { Light = Light, Dark = Dark, Default = Default };
}
internal override void Apply(bool fromTarget)
{
base.Apply(fromTarget);
ApplyCore();
}
internal override void Apply(object context, BindableObject bindObj, BindableProperty targetProperty, bool fromBindingContextChanged = false)
{
_weakTarget = new WeakReference<BindableObject>(bindObj);
_targetProperty = targetProperty;
base.Apply(context, bindObj, targetProperty, fromBindingContextChanged);
ApplyCore();
}
void ApplyCore()
{
if (_weakTarget == null || !_weakTarget.TryGetTarget(out var target))
return;
target?.SetValueCore(_targetProperty, GetValue());
}
T _light;
T _dark;
T _default;
bool _isLightSet;
bool _isDarkSet;
bool _isDefaultSet;
public T Light
{
get => _light;
set
{
_light = value;
_isLightSet = true;
}
}
public T Dark
{
get => _dark;
set
{
_dark = value;
_isDarkSet = true;
}
}
public T Default
{
get => _default;
set
{
_default = value;
_isDefaultSet = true;
}
}
public static implicit operator T(OnAppTheme<T> onAppTheme)
{
return onAppTheme.GetValue();
}
public T Value => GetValue();
T GetValue()
{
switch (Application.Current.RequestedTheme)
{
default:
case OSAppTheme.Light:
return _isLightSet ? Light : (_isDefaultSet ? Default : default);
case OSAppTheme.Dark:
return _isDarkSet ? Dark : (_isDefaultSet ? Default : default);
}
}
}
} | 19.692308 | 143 | 0.670898 | [
"MIT"
] | Ezeji/Xamarin.Forms | Xamarin.Forms.Core/OnAppTheme.cs | 2,050 | C# |
using Huawei.SCCMPlugin.PluginUI.Entitys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Huawei.SCCMPlugin.PluginUI.Helper
{
public sealed class DictHelper
{
/// <summary>
/// 获取字典指定key的值
/// </summary>
/// <param name="dic">字典</param>
/// <param name="key">指定key</param>
/// <returns></returns>
public static string GetDicValue(Dictionary<string, object> dic, string key)
{
if (dic.ContainsKey(key))//回调函数
{
return dic[key] as string;
}
return "";
}
/// <summary>
/// 获取字典指定key的值
/// </summary>
/// <typeparam name="T">泛型参数</typeparam>
/// <param name="dic">字典</param>
/// <param name="key">指定key</param>
/// <returns></returns>
public static T GetDicValue<T>(Dictionary<string, object> dic, string key)
{
if (dic.ContainsKey(key))//回调函数
{
return CommonUtil.CoreUtil.GetObjTranNull<T>(dic[key]);
}
return default(T);
}
}
}
| 27.162791 | 84 | 0.523973 | [
"MIT"
] | Huawei/Server_Management_Plugin_SCCM | src/Client/Huawei.SCCMPlugin.PluginUI/Helper/DictHelper.cs | 1,242 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Razor.Extensions;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Razor;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.NET.Sdk.Razor.SourceGenerators
{
[Generator]
public partial class RazorSourceGenerator : ISourceGenerator
{
private static readonly ConcurrentDictionary<Guid, IReadOnlyList<TagHelperDescriptor>> _tagHelperCache = new();
public void Initialize(GeneratorInitializationContext context)
{
}
public void Execute(GeneratorExecutionContext context)
{
var razorContext = RazorSourceGenerationContext.Create(context);
if (razorContext is null ||
(razorContext.RazorFiles.Count == 0 && razorContext.CshtmlFiles.Count == 0))
{
return;
}
HandleDebugSwitch(razorContext.WaitForDebugger);
var tagHelpers = ResolveTagHelperDescriptors(context, razorContext);
var projectEngine = RazorProjectEngine.Create(razorContext.Configuration, razorContext.FileSystem, b =>
{
b.Features.Add(new DefaultTypeNameFeature());
b.SetRootNamespace(razorContext.RootNamespace);
b.Features.Add(new StaticTagHelperFeature { TagHelpers = tagHelpers, });
b.Features.Add(new DefaultTagHelperDescriptorProvider());
CompilerFeatures.Register(b);
RazorExtensions.Register(b);
b.SetCSharpLanguageVersion(((CSharpParseOptions)context.ParseOptions).LanguageVersion);
});
CodeGenerateRazorComponents(context, razorContext, projectEngine);
GenerateViews(context, razorContext, projectEngine);
}
private void GenerateViews(GeneratorExecutionContext context, RazorSourceGenerationContext razorContext, RazorProjectEngine projectEngine)
{
var files = razorContext.CshtmlFiles;
Parallel.For(0, files.Count, GetParallelOptions(context), i =>
{
var file = files[i];
var codeDocument = projectEngine.Process(projectEngine.FileSystem.GetItem(file.NormalizedPath, FileKinds.Legacy));
var csharpDocument = codeDocument.GetCSharpDocument();
for (var j = 0; j < csharpDocument.Diagnostics.Count; j++)
{
var razorDiagnostic = csharpDocument.Diagnostics[j];
var csharpDiagnostic = razorDiagnostic.AsDiagnostic();
context.ReportDiagnostic(csharpDiagnostic);
}
Directory.CreateDirectory(Path.GetDirectoryName(file.GeneratedOutputPath));
File.WriteAllText(file.GeneratedOutputPath, csharpDocument.GeneratedCode);
});
}
private static void CodeGenerateRazorComponents(GeneratorExecutionContext context, RazorSourceGenerationContext razorContext, RazorProjectEngine projectEngine)
{
var files = razorContext.RazorFiles;
var arraypool = ArrayPool<(string, SourceText)>.Shared;
var outputs = arraypool.Rent(files.Count);
Parallel.For(0, files.Count, GetParallelOptions(context), i =>
{
var file = files[i];
var projectItem = projectEngine.FileSystem.GetItem(file.NormalizedPath, FileKinds.Component);
var codeDocument = projectEngine.Process(projectItem);
var csharpDocument = codeDocument.GetCSharpDocument();
for (var j = 0; j < csharpDocument.Diagnostics.Count; j++)
{
var razorDiagnostic = csharpDocument.Diagnostics[j];
var csharpDiagnostic = razorDiagnostic.AsDiagnostic();
context.ReportDiagnostic(csharpDiagnostic);
}
var hint = GetIdentifierFromPath(file.NormalizedPath);
var generatedCode = csharpDocument.GeneratedCode;
outputs[i] = (hint, SourceText.From(generatedCode, Encoding.UTF8));
});
for (var i = 0; i < files.Count; i++)
{
var (hint, sourceText) = outputs[i];
context.AddSource(hint, sourceText);
}
arraypool.Return(outputs);
}
private static IReadOnlyList<TagHelperDescriptor> ResolveTagHelperDescriptors(GeneratorExecutionContext GeneratorExecutionContext, RazorSourceGenerationContext razorContext)
{
var tagHelperFeature = new StaticCompilationTagHelperFeature();
var langVersion = ((CSharpParseOptions)GeneratorExecutionContext.ParseOptions).LanguageVersion;
var discoveryProjectEngine = RazorProjectEngine.Create(razorContext.Configuration, razorContext.FileSystem, b =>
{
b.Features.Add(new DefaultTypeNameFeature());
b.Features.Add(new ConfigureRazorCodeGenerationOptions(options =>
{
options.SuppressPrimaryMethodBody = true;
options.SuppressChecksum = true;
}));
b.SetRootNamespace(razorContext.RootNamespace);
var metadataReferences = new List<MetadataReference>(GeneratorExecutionContext.Compilation.References);
b.Features.Add(new DefaultMetadataReferenceFeature { References = metadataReferences });
b.Features.Add(tagHelperFeature);
b.Features.Add(new DefaultTagHelperDescriptorProvider());
CompilerFeatures.Register(b);
RazorExtensions.Register(b);
b.SetCSharpLanguageVersion(langVersion);
});
var files = razorContext.RazorFiles;
var results = ArrayPool<SyntaxTree>.Shared.Rent(files.Count);
var parseOptions = (CSharpParseOptions)GeneratorExecutionContext.ParseOptions;
Parallel.For(0, files.Count, GetParallelOptions(GeneratorExecutionContext), i =>
{
var file = files[i];
var codeGen = discoveryProjectEngine.Process(discoveryProjectEngine.FileSystem.GetItem(file.NormalizedPath, FileKinds.Component));
var generatedCode = codeGen.GetCSharpDocument().GeneratedCode;
results[i] = CSharpSyntaxTree.ParseText(
generatedCode,
options: parseOptions);
});
tagHelperFeature.Compilation = GeneratorExecutionContext.Compilation.AddSyntaxTrees(results.Take(files.Count));
ArrayPool<SyntaxTree>.Shared.Return(results);
var currentMetadataReference = GeneratorExecutionContext.Compilation.GetMetadataReference(GeneratorExecutionContext.Compilation.Assembly);
tagHelperFeature.TargetReference = currentMetadataReference;
var assemblyTagHelpers = tagHelperFeature.GetDescriptors();
var refTagHelpers = GetTagHelperDescriptorsFromReferences(GeneratorExecutionContext.Compilation, tagHelperFeature);
var result = new List<TagHelperDescriptor>(refTagHelpers.Count + assemblyTagHelpers.Count);
result.AddRange(assemblyTagHelpers);
result.AddRange(refTagHelpers);
return result;
}
private static IReadOnlyList<TagHelperDescriptor> GetTagHelperDescriptorsFromReferences(Compilation compilation, StaticCompilationTagHelperFeature tagHelperFeature)
{
List<TagHelperDescriptor> tagHelperDescriptors = new();
foreach (var reference in compilation.References)
{
var guid = reference.GetModuleVersionId(compilation) ?? Guid.NewGuid();
if (!_tagHelperCache.TryGetValue(guid, out var descriptors))
{
tagHelperFeature.TargetReference = reference;
descriptors = tagHelperFeature.GetDescriptors();
_tagHelperCache.AddOrUpdate(guid, descriptors, (key, currentValue) => descriptors);
}
tagHelperDescriptors.AddRange(descriptors);
}
return tagHelperDescriptors;
}
private static string GetIdentifierFromPath(string filePath)
{
var builder = new StringBuilder(filePath.Length);
for (var i = 0; i < filePath.Length; i++)
{
builder.Append(filePath[i] switch
{
':' or '\\' or '/' => '_',
var @default => @default,
});
}
return builder.ToString();
}
private static ParallelOptions GetParallelOptions(GeneratorExecutionContext generatorExecutionContext)
{
var options = new ParallelOptions { CancellationToken = generatorExecutionContext.CancellationToken };
var isConcurrentBuild = generatorExecutionContext.Compilation.Options.ConcurrentBuild;
if (Debugger.IsAttached || !isConcurrentBuild)
{
options.MaxDegreeOfParallelism = 1;
}
return options;
}
private static void HandleDebugSwitch(bool waitForDebugger)
{
if (waitForDebugger)
{
while (!Debugger.IsAttached)
{
Thread.Sleep(3000);
}
}
}
}
}
| 41.280992 | 181 | 0.634535 | [
"MIT"
] | radical/sdk | src/RazorSdk/SourceGenerators/RazorSourceGenerator.cs | 9,990 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Quic;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
namespace System.Net.Test.Common
{
public sealed class Http3LoopbackServer : GenericLoopbackServer
{
private X509Certificate2 _cert;
private QuicListener _listener;
public override Uri Address => new Uri($"https://{_listener.ListenEndPoint}/");
public Http3LoopbackServer(GenericLoopbackOptions options = null)
{
options ??= new GenericLoopbackOptions();
_cert = Configuration.Certificates.GetSelfSigned13ServerCertificate();
var sslOpts = new SslServerAuthenticationOptions
{
EnabledSslProtocols = options.SslProtocols,
ApplicationProtocols = new List<SslApplicationProtocol> { SslApplicationProtocol.Http3 },
//ServerCertificate = _cert,
ClientCertificateRequired = false
};
_listener = new QuicListener(new IPEndPoint(options.Address, 0), sslOpts);
_listener.Start();
}
public override void Dispose()
{
_listener.Dispose();
_cert.Dispose();
}
public override async Task<GenericLoopbackConnection> EstablishGenericConnectionAsync()
{
QuicConnection con = await _listener.AcceptConnectionAsync().ConfigureAwait(false);
return new Http3LoopbackConnection(con);
}
public override async Task AcceptConnectionAsync(Func<GenericLoopbackConnection, Task> funcAsync)
{
using GenericLoopbackConnection con = await EstablishGenericConnectionAsync().ConfigureAwait(false);
await funcAsync(con).ConfigureAwait(false);
}
public override async Task<HttpRequestData> HandleRequestAsync(HttpStatusCode statusCode = HttpStatusCode.OK, IList<HttpHeaderData> headers = null, string content = "")
{
using var con = (Http3LoopbackConnection)await EstablishGenericConnectionAsync().ConfigureAwait(false);
HttpRequestData request = await con.ReadRequestDataAsync().ConfigureAwait(false);
await con.SendResponseAsync(statusCode, headers, content).ConfigureAwait(false);
await con.CloseAsync(Http3LoopbackConnection.H3_NO_ERROR);
return request;
}
}
public sealed class Http3LoopbackServerFactory : LoopbackServerFactory
{
public static Http3LoopbackServerFactory Singleton { get; } = new Http3LoopbackServerFactory();
public override Version Version => HttpVersion.Version30;
public override GenericLoopbackServer CreateServer(GenericLoopbackOptions options = null)
{
return new Http3LoopbackServer(options);
}
public override async Task CreateServerAsync(Func<GenericLoopbackServer, Uri, Task> funcAsync, int millisecondsTimeout = 60000, GenericLoopbackOptions options = null)
{
using GenericLoopbackServer server = CreateServer(options);
await funcAsync(server, server.Address).TimeoutAfter(millisecondsTimeout).ConfigureAwait(false);
}
public override Task<GenericLoopbackConnection> CreateConnectionAsync(Socket socket, Stream stream, GenericLoopbackOptions options = null)
{
// TODO: make a new overload that takes a MultiplexedConnection.
// This method is always unacceptable to call for HTTP/3.
throw new NotImplementedException("HTTP/3 does not operate over a Socket.");
}
}
}
| 41.085106 | 176 | 0.691611 | [
"MIT"
] | NicoNekoru/runtime | src/libraries/Common/tests/System/Net/Http/Http3LoopbackServer.cs | 3,862 | C# |
using UnityEngine;
namespace Quester.QuestEditor
{
public class CollectNode : QuestNode
{
public ObjectID Collectable;
public override void InitializeObjective()
{
var collectGameObject = ObjectIDMap.Instance.Get(Collectable);
var objective = collectGameObject.AddComponent<CollectObjective>();
objective.SetNode(this);
if (!Active) objective.enabled = false;
}
public override bool Evaluate()
{
return complete;
}
}
} | 25 | 79 | 0.609091 | [
"MIT"
] | nmacadam/Quester | Assets/New Quest Graph/CollectNode.cs | 552 | C# |
namespace Gu.Units
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
internal static class Ensure
{
internal static void GreaterThan<T>(T value, T min, string parameterName)
where T : IComparable<T>
{
Debug.Assert(!string.IsNullOrEmpty(parameterName), $"{nameof(parameterName)} cannot be null");
if (Comparer<T>.Default.Compare(value, min) <= 0)
{
var message = $"Expected {parameterName} to be greater than {min}, {parameterName} was {value}";
throw new ArgumentException(message, parameterName);
}
}
}
}
| 32.095238 | 112 | 0.597923 | [
"MIT"
] | GuOrg/Gu.Units | Gu.Units/Internals/Ensure/Ensure.compare.cs | 676 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using NUnit.Framework;
using NServiceKit.Common.Utils;
using NServiceKit.DataAnnotations;
using NServiceKit.OrmLite.SqlServer;
namespace NServiceKit.OrmLite.Tests
{
/// <summary>A SQL builder tests.</summary>
[TestFixture]
public class SqlBuilderTests
{
/// <summary>An user.</summary>
[Alias("Users")]
public class User
{
/// <summary>Gets or sets the identifier.</summary>
/// <value>The identifier.</value>
[AutoIncrement]
public int Id { get; set; }
/// <summary>Gets or sets the name.</summary>
/// <value>The name.</value>
public string Name { get; set; }
/// <summary>Gets or sets the age.</summary>
/// <value>The age.</value>
public int Age { get; set; }
}
/// <summary>The database.</summary>
private IDbConnection db;
/// <summary>Sets the up.</summary>
[SetUp]
public void SetUp()
{
db = Config.OpenDbConnection();
db.DropAndCreateTable<User>();
}
/// <summary>Tear down.</summary>
[TearDown]
public void TearDown()
{
}
/// <summary>Builder select clause.</summary>
[Test]
public void BuilderSelectClause()
{
var rand = new Random(8675309);
var data = new List<User>();
for (var i = 0; i < 100; i++)
{
var nU = new User { Age = rand.Next(70), Id = i, Name = Guid.NewGuid().ToString() };
data.Add(nU);
db.Insert(nU);
nU.Id = (int)db.GetLastInsertId();
}
var builder = new SqlBuilder();
var justId = builder.AddTemplate("SELECT /**select**/ FROM Users");
var all = builder.AddTemplate("SELECT /**select**/, Name, Age FROM Users");
builder.Select("Id");
var ids = db.Query<int>(justId.RawSql, justId.Parameters);
var users = db.Query<User>(all.RawSql, all.Parameters);
foreach (var u in data)
{
Assert.That(ids.Any(i => u.Id == i), "Missing ids in select");
Assert.That(users.Any(a => a.Id == u.Id && a.Name == u.Name && a.Age == u.Age), "Missing users in select");
}
}
/// <summary>Builder template wo composition.</summary>
/// <exception cref="Exception">Thrown when an exception error condition occurs.</exception>
[Test]
public void BuilderTemplateWOComposition()
{
var builder = new SqlBuilder();
var template = builder.AddTemplate("SELECT COUNT(*) FROM Users WHERE Age = @age", new { age = 5 });
if (template.RawSql == null) throw new Exception("RawSql null");
if (template.Parameters == null) throw new Exception("Parameters null");
db.Insert(new User { Age = 5, Name = "Testy McTestington" });
Assert.That(db.QueryScalar<int>(template.RawSql, template.Parameters), Is.EqualTo(1));
}
}
} | 33.402062 | 123 | 0.53858 | [
"BSD-3-Clause"
] | azraelrabbit/NServiceKit.OrmLite | tests/NServiceKit.OrmLite.Tests/SqlBuilderTests.cs | 3,242 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace FluentAssertions.Types
{
/// <summary>
/// Allows for fluent filtering a list of types.
/// </summary>
public class TypeSelector : IEnumerable<Type>
{
private List<Type> types;
public TypeSelector(Type type)
: this(new[] { type })
{
}
public TypeSelector(IEnumerable<Type> types)
{
this.types = types.ToList();
}
/// <summary>
/// The resulting <see cref="System.Type"/> objects.
/// </summary>
public Type[] ToArray()
{
return types.ToArray();
}
/// <summary>
/// Determines whether a type is a subclass of another type, but NOT the same type.
/// </summary>
public TypeSelector ThatDeriveFrom<TBase>()
{
types = types.Where(type => type.GetTypeInfo().IsSubclassOf(typeof(TBase))).ToList();
return this;
}
/// <summary>
/// Determines whether a type is not a subclass of another type.
/// </summary>
public TypeSelector ThatDoNotDeriveFrom<TBase>()
{
types = types.Where(type => !type.GetTypeInfo().IsSubclassOf(typeof(TBase))).ToList();
return this;
}
/// <summary>
/// Determines whether a type implements an interface (but is not the interface itself).
/// </summary>
public TypeSelector ThatImplement<TInterface>()
{
types = types.Where(t =>
typeof(TInterface)
.IsAssignableFrom(t) && (t != typeof(TInterface)
)).ToList();
return this;
}
/// <summary>
/// Determines whether a type does not implement an interface (but is not the interface itself).
/// </summary>
public TypeSelector ThatDoNotImplement<TInterface>()
{
types = types.Where(t =>
!typeof(TInterface)
.IsAssignableFrom(t) && (t != typeof(TInterface)
)).ToList();
return this;
}
/// <summary>
/// Determines whether a type is decorated with a particular attribute.
/// </summary>
public TypeSelector ThatAreDecoratedWith<TAttribute>()
where TAttribute : Attribute
{
types = types
.Where(t => t.GetTypeInfo().GetCustomAttributes(typeof(TAttribute), false).Any())
.ToList();
return this;
}
/// <summary>
/// Determines whether a type is decorated with, or inherits from a parent class, a particular attribute.
/// </summary>
public TypeSelector ThatAreDecoratedWithOrInherit<TAttribute>()
where TAttribute : Attribute
{
types = types
.Where(t => t.GetTypeInfo().GetCustomAttributes(typeof(TAttribute), true).Any())
.ToList();
return this;
}
/// <summary>
/// Determines whether a type is not decorated with a particular attribute.
/// </summary>
public TypeSelector ThatAreNotDecoratedWith<TAttribute>()
where TAttribute : Attribute
{
types = types
.Where(t => !t.GetTypeInfo().GetCustomAttributes(typeof(TAttribute), false).Any())
.ToList();
return this;
}
/// <summary>
/// Determines whether a type is not decorated with and does not inherit from a parent class, a particular attribute.
/// </summary>
public TypeSelector ThatAreNotDecoratedWithOrInherit<TAttribute>()
where TAttribute : Attribute
{
types = types
.Where(t => !t.GetTypeInfo().GetCustomAttributes(typeof(TAttribute), true).Any())
.ToList();
return this;
}
/// <summary>
/// Determines whether the namespace of type is exactly <paramref name="namespace"/>.
/// </summary>
public TypeSelector ThatAreInNamespace(string @namespace)
{
types = types.Where(t => t.Namespace == @namespace).ToList();
return this;
}
/// <summary>
/// Determines whether the namespace of type is exactly not <paramref name="namespace"/>.
/// </summary>
public TypeSelector ThatAreNotInNamespace(string @namespace)
{
types = types.Where(t => t.Namespace != @namespace).ToList();
return this;
}
/// <summary>
/// Determines whether the namespace of type starts with <paramref name="namespace"/>.
/// </summary>
public TypeSelector ThatAreUnderNamespace(string @namespace)
{
types = types.Where(t => t.Namespace?.StartsWith(@namespace) == true).ToList();
return this;
}
/// <summary>
/// Determines whether the namespace of type does not start with <paramref name="namespace"/>.
/// </summary>
public TypeSelector ThatAreNotUnderNamespace(string @namespace)
{
types = types.Where(t => t.Namespace?.StartsWith(@namespace) != true).ToList();
return this;
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
/// <filterpriority>1</filterpriority>
public IEnumerator<Type> GetEnumerator()
{
return types.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
/// <filterpriority>2</filterpriority>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| 32.73057 | 125 | 0.551686 | [
"Apache-2.0"
] | BrunoJuchli/fluentassertions | Src/FluentAssertions/Types/TypeSelector.cs | 6,317 | 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 CaptureThat.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", "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>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("CaptureThat.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)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap about_icon {
get {
object obj = ResourceManager.GetObject("about_icon", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap area_icon {
get {
object obj = ResourceManager.GetObject("area_icon", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.IO.UnmanagedMemoryStream similar to System.IO.MemoryStream.
/// </summary>
internal static System.IO.UnmanagedMemoryStream CameraSound {
get {
return ResourceManager.GetStream("CameraSound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap CaptureThat {
get {
object obj = ResourceManager.GetObject("CaptureThat", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.IO.UnmanagedMemoryStream similar to System.IO.MemoryStream.
/// </summary>
internal static System.IO.UnmanagedMemoryStream FailedSound {
get {
return ResourceManager.GetStream("FailedSound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap full_icon {
get {
object obj = ResourceManager.GetObject("full_icon", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap settings_icon {
get {
object obj = ResourceManager.GetObject("settings_icon", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.IO.UnmanagedMemoryStream similar to System.IO.MemoryStream.
/// </summary>
internal static System.IO.UnmanagedMemoryStream SuccessSound {
get {
return ResourceManager.GetStream("SuccessSound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap window_icon {
get {
object obj = ResourceManager.GetObject("window_icon", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
| 40.569536 | 177 | 0.577865 | [
"MIT"
] | trdwll/CaptureThat | CaptureThat/CaptureThat/Properties/Resources.Designer.cs | 6,128 | C# |
//-----------------------------------------------------------------------
// <copyright file="DashboardViewModel.cs" company="Wohs Inc.">
// Copyright © Wohs Inc.
// </copyright>
//-----------------------------------------------------------------------
namespace Lurker.UI.ViewModels
{
using System;
using System.Collections.Generic;
using System.Linq;
using Caliburn.Micro;
using Lurker.Patreon;
using Lurker.Patreon.Events;
using Lurker.Patreon.Models;
using Lurker.UI.Extensions;
using Lurker.UI.Models;
/// <summary>
/// Represents the DashboardViewModel.
/// </summary>
/// <seealso cref="Lurker.UI.ViewModels.ScreenBase" />
public class DashboardViewModel : ScreenBase
{
#region Fields
private PieChartViewModel _totalChart;
private ColumnChartViewModel _tradesChart;
private LineChartViewModel _networthChart;
private ChartViewModelBase _activeChart;
private PieChartViewModel _itemClassChart;
private IEnumerable<SimpleTradeModel> _networthTrades;
private IEnumerable<SimpleTradeModel> _leagueTrades;
private IEnumerable<SimpleTradeModel> _allTradres;
private IEnumerable<League> _leagues;
private League _selectedLeague;
private double _totalNetworth;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="DashboardViewModel"/> class.
/// </summary>
/// <param name="windowManager">The window manager.</param>
public DashboardViewModel(IWindowManager windowManager)
: base(windowManager)
{
this.DisplayName = "Dashboard";
this._networthTrades = Enumerable.Empty<SimpleTradeModel>();
this._leagueTrades = Enumerable.Empty<SimpleTradeModel>();
this._allTradres = Enumerable.Empty<SimpleTradeModel>();
this._leagues = Enumerable.Empty<League>();
}
#endregion
#region Properties
/// <summary>
/// Gets a value indicating whether this instance has active chart.
/// </summary>
public bool NoActiveChart => this._activeChart == null;
/// <summary>
/// Gets a value indicating whether this instance has active chart.
/// </summary>
public bool HasActiveChart => !this.NoActiveChart;
/// <summary>
/// Gets the active chart.
/// </summary>
public ChartViewModelBase ActiveChart
{
get
{
return this._activeChart;
}
private set
{
this._activeChart = value;
this.NotifyOfPropertyChange();
this.NotifyOfPropertyChange("NoActiveChart");
this.NotifyOfPropertyChange("HasActiveChart");
}
}
/// <summary>
/// Gets the leagues.
/// </summary>
public IEnumerable<League> Leagues
{
get
{
return this._leagues;
}
private set
{
this._leagues = value;
this.NotifyOfPropertyChange();
}
}
/// <summary>
/// Gets or sets the selected league.
/// </summary>
/// <value>The selected league.</value>
public League SelectedLeague
{
get
{
return this._selectedLeague;
}
set
{
if (this._selectedLeague != value)
{
this._selectedLeague = value;
this.Filter(this._selectedLeague);
}
}
}
/// <summary>
/// Gets the total networth.
/// </summary>
/// <value>The selected league.</value>
public double TotalNetworth
{
get
{
return this._totalNetworth;
}
private set
{
this._totalNetworth = value;
this.NotifyOfPropertyChange();
}
}
/// <summary>
/// Gets the total chart.
/// </summary>
public PieChartViewModel TotalChart
{
get
{
return this._totalChart;
}
private set
{
this._totalChart = value;
this.NotifyOfPropertyChange();
}
}
/// <summary>
/// Gets the networth chart.
/// </summary>
public LineChartViewModel NetworthChart
{
get
{
return this._networthChart;
}
private set
{
this._networthChart = value;
this.NotifyOfPropertyChange();
}
}
/// <summary>
/// Gets the networth chart.
/// </summary>
public PieChartViewModel ItemClassChart
{
get
{
return this._itemClassChart;
}
private set
{
this._itemClassChart = value;
this.NotifyOfPropertyChange();
}
}
#endregion
#region Methods
/// <summary>
/// Backs this instance.
/// </summary>
public void Back()
{
this.ActiveChart = null;
}
/// <summary>
/// Days this instance.
/// </summary>
public void Day()
{
this._networthTrades = this._leagueTrades.Where(t => DateTime.Compare(t.Date, DateTime.Now.AddDays(-1)) > 0);
this.NetworthChart = this.CreateNetworthChart();
}
/// <summary>
/// Weeks this instance.
/// </summary>
public void Week()
{
this._networthTrades = this._leagueTrades.Where(t => DateTime.Compare(t.Date, DateTime.Now.AddDays(-7)) > 0);
this.NetworthChart = this.CreateNetworthChart();
}
/// <summary>
/// Alls this instance.
/// </summary>
public void All()
{
this._networthTrades = this._leagueTrades;
this.NetworthChart = this.CreateNetworthChart();
}
/// <summary>
/// Filters the specified league.
/// </summary>
/// <param name="league">The league.</param>
public void Filter(League league)
{
this.SetLeagueTrades(league);
if (this.ItemClassChart != null)
{
this.ItemClassChart.OnSerieClick -= this.ItemClassChart_OnSerieClick;
}
if (this.TotalChart != null)
{
this.TotalChart.OnSerieClick -= this.OnSerieClick;
}
this.ItemClassChart = this.CreateItemClassChart();
this.ItemClassChart.OnSerieClick += this.ItemClassChart_OnSerieClick;
this.NetworthChart = this.CreateNetworthChart();
this.TotalChart = this.CreateTotalChart();
this.TotalChart.OnSerieClick += this.OnSerieClick;
}
/// <summary>
/// Called when activating.
/// </summary>
protected override async void OnActivate()
{
using (var service = new DatabaseService())
{
await service.CheckPledgeStatus();
this._allTradres = service.Get().Where(t => !t.IsOutgoing).OrderBy(t => t.Date).ToArray();
var leagues = this._allTradres.GroupBy(t => t.LeagueName).Select(grp => grp.Key);
this.Leagues = this.FilterLeagueNames(leagues);
if (this._allTradres.Any())
{
var lastTrade = this._allTradres.Last();
var lastLeague = this.Leagues.FirstOrDefault(l => l.PossibleNames.Contains(lastTrade.LeagueName));
this.SetLeagueTrades(lastLeague);
}
}
this.ItemClassChart = this.CreateItemClassChart();
this.ItemClassChart.OnSerieClick += this.ItemClassChart_OnSerieClick;
this.NetworthChart = this.CreateNetworthChart();
this.TotalChart = this.CreateTotalChart();
this.TotalChart.OnSerieClick += this.OnSerieClick;
base.OnActivate();
}
/// <summary>
/// Called when deactivating.
/// </summary>
/// <param name="close">Inidicates whether this instance will be closed.</param>
protected override void OnDeactivate(bool close)
{
if (close)
{
this.ItemClassChart.OnSerieClick -= this.ItemClassChart_OnSerieClick;
this.TotalChart.OnSerieClick -= this.OnSerieClick;
}
base.OnDeactivate(close);
}
/// <summary>
/// Sets the league trades.
/// </summary>
/// <param name="league">The league.</param>
private void SetLeagueTrades(League league)
{
this._selectedLeague = league;
// Needs to be notified manually
this.NotifyOfPropertyChange(nameof(this.SelectedLeague));
if (league == null)
{
this._leagueTrades = this._allTradres;
}
else
{
this._leagueTrades = this._allTradres.Where(t => !string.IsNullOrEmpty(t.LeagueName) && league.PossibleNames.Contains(t.LeagueName));
}
this._networthTrades = this._leagueTrades;
this.TotalNetworth = this._leagueTrades.Select(t => t.Price.CalculateValue()).Sum();
}
/// <summary>
/// Filters the league names.
/// </summary>
/// <param name="leagues">The leagues.</param>
/// <returns>List of Leagues.</returns>
private List<League> FilterLeagueNames(IEnumerable<string> leagues)
{
var filteredLeagues = new List<League>();
foreach (var leagueName in leagues)
{
if (string.IsNullOrEmpty(leagueName))
{
continue;
}
var trimmedLeague = leagueName.Trim('.');
var league = filteredLeagues.FirstOrDefault(f => f.DisplayName == trimmedLeague);
if (league == null)
{
league = new League() { DisplayName = trimmedLeague };
filteredLeagues.Add(league);
}
if (!league.PossibleNames.Contains(leagueName))
{
league.AddName(leagueName);
}
}
return filteredLeagues;
}
/// <summary>
/// Items the class chart on serie click.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
private void ItemClassChart_OnSerieClick(object sender, LiveCharts.ChartPoint e)
{
if (Enum.TryParse<ItemClass>(e.SeriesView.Title, true, out var value))
{
var trades = this._leagueTrades.Where(t => t.ItemClass == value);
var chart = new ColumnChartViewModel(trades.Select(t => t.ItemName).ToArray());
chart.Add(e.SeriesView.Title, trades.Select(t => t.Price.CalculateValue()));
this._tradesChart = chart;
this.ActiveChart = this._tradesChart;
}
}
/// <summary>
/// Gets the pie chart.
/// </summary>
/// <returns>The PieChart.</returns>
private PieChartViewModel CreateTotalChart()
{
var pieChart = new PieChartViewModel()
{
FontSize = 12,
LabelPosition = LiveCharts.PieLabelPosition.InsideSlice,
};
var groups = this._leagueTrades.GroupBy(i => i.Price.CurrencyType).Select(g => new { Type = g.First().Price.CurrencyType, Sum = g.Sum(i => i.Price.CalculateValue()) });
foreach (var group in groups)
{
pieChart.Add(group.Type.ToString(), group.Sum);
}
return pieChart;
}
/// <summary>
/// Gets the networth chart.
/// </summary>
/// <returns>The networth graph.</returns>
private LineChartViewModel CreateNetworthChart()
{
var lineChart = new LineChartViewModel();
var points = new List<double>();
if (this._networthTrades.Count() < 2)
{
return lineChart;
}
double previousValue = 0;
var firstTrade = this._networthTrades.First();
var lastTrade = this._networthTrades.Last();
var days = (lastTrade.Date - firstTrade.Date).TotalDays;
var tradeGroups = this._networthTrades.GroupBy(t => t.Date.Date);
var firstDate = firstTrade.Date.Date;
for (int i = 0; i < days + 1; i++)
{
var group = tradeGroups.FirstOrDefault(g => g.Key.Date == firstDate);
if (group == null)
{
points.Add(previousValue);
firstDate = firstDate.AddDays(1);
continue;
}
var value = group.Select(g => g.Price.CalculateValue()).Sum();
previousValue += value;
if (previousValue < 0)
{
points.Add(0);
}
else
{
points.Add(previousValue);
}
firstDate = firstDate.AddDays(1);
}
lineChart.Add("Networth", points);
return lineChart;
}
/// <summary>
/// Creates the item class chart.
/// </summary>
/// <returns>The PieChart.</returns>
private PieChartViewModel CreateItemClassChart()
{
var pieChart = new PieChartViewModel()
{
InnerRadius = 85,
FontSize = 18,
};
var groups = this._leagueTrades.GroupBy(i => i.ItemClass).Select(g => new { Type = g.First().ItemClass, Sum = g.Sum(i => i.Price.CalculateValue()) });
foreach (var group in groups.OrderByDescending(g => g.Sum).Take(5))
{
pieChart.Add(group.Type.ToString(), group.Sum);
}
return pieChart;
}
/// <summary>
/// Pies the chart view model on pie click.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
private void OnSerieClick(object sender, LiveCharts.ChartPoint e)
{
if (Enum.TryParse<CurrencyType>(e.SeriesView.Title, true, out var value))
{
var trades = this._leagueTrades.Where(t => t.Price.CurrencyType == value);
var chart = new ColumnChartViewModel(trades.Select(t => t.ItemName).ToArray());
chart.Add(e.SeriesView.Title, trades.Select(t => t.Price.NumberOfCurrencies));
this._tradesChart = chart;
this.ActiveChart = this._tradesChart;
}
}
#endregion
}
} | 31.692464 | 180 | 0.511664 | [
"MIT"
] | C1rdec/Poe-Lurker | src/Lurker.UI/ViewModels/DashboardViewModel.cs | 15,564 | C# |
/*********************************************
作者:曹旭升
QQ:279060597
访问博客了解详细介绍及更多内容:
http://blog.shengxunwei.com
**********************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Sheng.SailingEase.Infrastructure;
using Sheng.SailingEase.Controls;
using Sheng.SailingEase.Controls.SEAdressBar;
using Sheng.SailingEase.Localisation;
namespace Sheng.SailingEase.Core.Development
{
partial class FormFormChoose : FormViewBase
{
private IWindowComponentService _windowComponentService;
private BindingList<IEntityIndex> _formList;
private WindowFolderEntity _folder = null;
private WindowFolderEntity Folder
{
get
{
return this._folder;
}
set
{
if (_folder == value)
return;
_folder = value;
string folderId;
if (value == null)
{
folderId = String.Empty;
folderAddressBar.CurrentNode = null;
}
else
{
folderId = value.Id;
folderAddressBar.SetAddress(_windowComponentService.GetFolderFullPath(value));
}
LoadFormList();
}
}
private string selectedId = string.Empty;
public string SelectedId
{
get
{
return this._selectedFormIndex.Id;
}
}
private string selectedName = string.Empty;
public string SelectedName
{
get
{
return this._selectedFormIndex.Name;
}
}
private IEntityIndex _selectedFormIndex;
public WindowEntity SelectedForm
{
get
{
if (_selectedFormIndex == null || _selectedFormIndex is FolderEntityIndex)
return null;
WindowEntityIndex windowEntityIndex = (WindowEntityIndex)_selectedFormIndex;
return windowEntityIndex.Window;
}
}
public FormFormChoose()
{
InitializeComponent();
DataGridViewImageBinderColumn iconColumn = new DataGridViewImageBinderColumn()
{
Width = 25
};
iconColumn.Mapping(typeof(FolderEntityIndex), IconsLibrary.Folder, true);
iconColumn.Mapping(typeof(WindowEntityIndex), IconsLibrary.Form, true);
dataGridViewForms.Columns.Insert(0, iconColumn);
_windowComponentService = ServiceUnity.Container.Resolve<IWindowComponentService>();
UIHelper.ProcessDataGridView(this.dataGridViewForms);
this.folderAddressBar.Renderer = ToolStripRenders.ControlToControlLight;
this.folderAddressBar.DropDownRenderer = ToolStripRenders.Control;
Unity.ApplyResource(this);
}
private void FormFormChoose_Load(object sender, EventArgs e)
{
this.dataGridViewForms.AutoGenerateColumns = false;
this.folderAddressBar.InitializeRoot(new FolderAddressNode());
this.Folder = null;
System.Threading.Thread.Sleep(500);
LoadFormList();
}
private void folderAddressBar_SelectionChange(object sender, SEAddressBarStrip.NodeChangedArgs e)
{
string folderId = this.Folder == null ? String.Empty : this.Folder.Id;
if (String.IsNullOrEmpty(e.UniqueID))
{
this.Folder = null;
}
else if (folderId != e.UniqueID)
{
this.Folder = _windowComponentService.GetFolderEntity(e.UniqueID);
}
}
private void btnOK_Click(object sender, EventArgs e)
{
if (dataGridViewForms.SelectedRows.Count == 0)
{
_selectedFormIndex = null;
}
else
{
IEntityIndex entityIndex = (IEntityIndex)dataGridViewForms.SelectedRows[0].DataBoundItem;
_selectedFormIndex = entityIndex;
}
this.DialogResult = DialogResult.OK;
this.Close();
}
private void dataGridViewForms_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex < 0)
{
return;
}
IEntityIndex entityIndex = (IEntityIndex)dataGridViewForms.SelectedRows[0].DataBoundItem;
if (entityIndex is FolderEntityIndex)
{
FolderEntityIndex folderIndex = (FolderEntityIndex)entityIndex;
this.Folder = folderIndex.Folder;
}
}
private void ReturnToParent()
{
if (this.Folder != null)
{
this.Folder = _windowComponentService.GetFolderEntity(this.Folder.Parent);
}
}
private void LoadFormList()
{
string folderId = String.Empty;
if (this.Folder != null)
{
folderId = this.Folder.Id;
}
this._formList = new BindingList<IEntityIndex>(_windowComponentService.GetIndexList(folderId));
dataGridViewForms.DataSource = this._formList;
}
}
}
| 36.056604 | 109 | 0.541078 | [
"MIT"
] | ckalvin-hub/Sheng.Winform.IDE | SourceCode/Source/Core.Development/View/FormFormChoose.cs | 5,781 | C# |
/**
* Copyright 2003, 2004, 2005. CodeStreet 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 http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace CodeStreet.Selector.Parser
{
/// <summary> Exception thrown when a normal usage error condition is trapped.</summary>
/// <seealso cref="CodeStreet.Selector.Parser.SystemException">
/// </seealso>
/// <author> Jawaid Hakim.
/// </author>
public class BusinessException : BaseException
{
/// <summary> Ctor.</summary>
/// <param name="desc">Description of exception.
/// </param>
public BusinessException(System.String desc):base(desc)
{
}
/// <summary> Ctor.</summary>
/// <param name="original">Original throwable.
/// </param>
//UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to 'System.Exception' which has different behavior. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1100"'
public BusinessException(String desc, System.Exception original):base(desc, original)
{
}
public BusinessException(System.Exception original):base("", original)
{
}
}
} | 35.644444 | 188 | 0.699501 | [
"Apache-2.0"
] | jamsel/jamsel | src/CSHARP/Selector/CodeStreet/Selector/Parser/BusinessException.cs | 1,604 | C# |
using System;
namespace Megaphone.Core
{
public interface IFrameworkProvider
{
Uri GetUri(string serviceName, string version, bool useHttps);
}
} | 18.555556 | 70 | 0.700599 | [
"Apache-2.0"
] | thiagoloureiro/Megaphone.NetStandard | Megaphone.Core/IFrameworkProvider.cs | 169 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void ShiftRightLogicalRoundedAdd_Vector128_Byte_1()
{
var test = new ImmBinaryOpTest__ShiftRightLogicalRoundedAdd_Vector128_Byte_1();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmBinaryOpTest__ShiftRightLogicalRoundedAdd_Vector128_Byte_1
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Byte> _fld1;
public Vector128<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__ShiftRightLogicalRoundedAdd_Vector128_Byte_1 testClass)
{
var result = AdvSimd.ShiftRightLogicalRoundedAdd(_fld1, _fld2, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(ImmBinaryOpTest__ShiftRightLogicalRoundedAdd_Vector128_Byte_1 testClass)
{
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = AdvSimd.ShiftRightLogicalRoundedAdd(
AdvSimd.LoadVector128((Byte*)(pFld1)),
AdvSimd.LoadVector128((Byte*)(pFld2)),
1
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly byte Imm = 1;
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private DataTable _dataTable;
static ImmBinaryOpTest__ShiftRightLogicalRoundedAdd_Vector128_Byte_1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
}
public ImmBinaryOpTest__ShiftRightLogicalRoundedAdd_Vector128_Byte_1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.ShiftRightLogicalRoundedAdd(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.ShiftRightLogicalRoundedAdd(
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightLogicalRoundedAdd), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightLogicalRoundedAdd), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.ShiftRightLogicalRoundedAdd(
_clsVar1,
_clsVar2,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Byte>* pClsVar1 = &_clsVar1)
fixed (Vector128<Byte>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.ShiftRightLogicalRoundedAdd(
AdvSimd.LoadVector128((Byte*)(pClsVar1)),
AdvSimd.LoadVector128((Byte*)(pClsVar2)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = AdvSimd.ShiftRightLogicalRoundedAdd(op1, op2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr));
var result = AdvSimd.ShiftRightLogicalRoundedAdd(op1, op2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__ShiftRightLogicalRoundedAdd_Vector128_Byte_1();
var result = AdvSimd.ShiftRightLogicalRoundedAdd(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new ImmBinaryOpTest__ShiftRightLogicalRoundedAdd_Vector128_Byte_1();
fixed (Vector128<Byte>* pFld1 = &test._fld1)
fixed (Vector128<Byte>* pFld2 = &test._fld2)
{
var result = AdvSimd.ShiftRightLogicalRoundedAdd(
AdvSimd.LoadVector128((Byte*)(pFld1)),
AdvSimd.LoadVector128((Byte*)(pFld2)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.ShiftRightLogicalRoundedAdd(_fld1, _fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = AdvSimd.ShiftRightLogicalRoundedAdd(
AdvSimd.LoadVector128((Byte*)(pFld1)),
AdvSimd.LoadVector128((Byte*)(pFld2)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.ShiftRightLogicalRoundedAdd(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.ShiftRightLogicalRoundedAdd(
AdvSimd.LoadVector128((Byte*)(&test._fld1)),
AdvSimd.LoadVector128((Byte*)(&test._fld2)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Byte> firstOp, Vector128<Byte> secondOp, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), firstOp);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), secondOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* firstOp, void* secondOp, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] firstOp, Byte[] secondOp, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.ShiftRightLogicalRoundedAdd(firstOp[i], secondOp[i], Imm) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftRightLogicalRoundedAdd)}<Byte>(Vector128<Byte>, Vector128<Byte>, 1): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 42.646296 | 186 | 0.585219 | [
"MIT"
] | 2m0nd/runtime | src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ShiftRightLogicalRoundedAdd.Vector128.Byte.1.cs | 23,029 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RazorCompiler")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RazorCompiler")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[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("798ba5b0-b1ad-402c-ae3d-3180042157cd")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.138889 | 84 | 0.747269 | [
"MIT"
] | DiogenesPolanco/autorest | Tools/RazorCompiler/RazorCompiler/Properties/AssemblyInfo.cs | 1,375 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TestDraw
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
float tension = (float)(this.trackBar1.Value / 10.0);
DrawCurvePointTension(e, tension);
}
private void DrawCurvePointTension(PaintEventArgs e, float tension)
{
// Create pens.
Pen redPen = new Pen(Color.Red, 3);
Pen greenPen = new Pen(Color.Green, 3);
Pen bluePen = new Pen(Color.Blue, 1);
Brush brush = new SolidBrush(Color.White);
// Create points that define curve.
Point point1 = new Point(50, 50);
Point point2 = new Point(100, 25);
Point point3 = new Point(200, 5);
Point point4 = new Point(250, 50);
Point point5 = new Point(300, 100);
Point point6 = new Point(350, 200);
Point point7 = new Point(250, 250);
Point[] curvePoints = { point1, point2, point3, point4, point5, point6, point7 };
// Draw lines between original points to screen.
var g = e.Graphics;
g.SmoothingMode = SmoothingMode.AntiAlias;
g.DrawLines(redPen, curvePoints);
// Create tension.
// Draw curve to screen.
g.DrawCurve(greenPen, curvePoints, tension);
// Draw Dots
foreach (var p in curvePoints)
{
var rect = new Rectangle(p.X - 2, p.Y - 2, 4, 4);
g.FillRectangle(brush, rect);
g.DrawRectangle(bluePen, rect);
}
}
private void trackBar1_ValueChanged(object sender, EventArgs e)
{
float tension = (float)(this.trackBar1.Value / 10.0);
lblTension.Text = tension.ToString();
panel1.Invalidate();
}
}
}
| 31.309859 | 93 | 0.563653 | [
"MIT"
] | surfsky/TestWinForms | TestCurve/Form1.cs | 2,225 | C# |
namespace PlayerController
{
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class Mark : MonoBehaviour
{
AudioSource AmbientSound;
float forwardMovement = 1.0f;
float leftMovement = 1.0f;
float rightMovement = 1.0f;
float backMovement = 1.0f;
float Velocidade = 1.0f;
float VelocidadeGirar = 20.0f;
KeyCode W = KeyCode.W;
KeyCode S = KeyCode.S;
KeyCode R = KeyCode.R;
KeyCode E = KeyCode.E;
public GameObject mark;
public Light LuzPlayer;
//referencia do script de animacao do player
MarkAnimando AnimMark;
CharacterController ControleMark;
void Awake ()
{
//pega o componente de som ambiente
AmbientSound = GetComponent<AudioSource>();
//pega a luz do player
LuzPlayer = GetComponentInChildren<Light>();
//referencia de script de animacao do player
AnimMark = GetComponent<MarkAnimando>();
//seta o character controller
ControleMark = GetComponent<CharacterController>();
}
void Update ()
{
//movimentos e giro da camera
transform.Rotate (0, Input.GetAxis("Horizontal") * VelocidadeGirar *
Time.deltaTime, 0);
Vector3 forward = transform.TransformDirection (Vector3.forward);
//rotacao pelas teclas A e D, e setas direcionais
float VelocidadeGiro = Velocidade * Input.GetAxis ("Vertical");
ControleMark.SimpleMove (forward * VelocidadeGiro);
ControleMark.enabled = true;
ControleMark.detectCollisions = true;
//se o character controller esta no chao, a gravidade e inativa
if (ControleMark.isGrounded)
{
//pressionando w faz o Mark andar para frente
if (Input.GetKey(W))
{
Vector3 position = transform.TransformDirection (Vector3.forward *
forwardMovement * Time.deltaTime);
}
//pressionando s faz o Mark andar para tras
else if (Input.GetKey(S))
{
Vector3 position = transform.TransformDirection (Vector3.back *
backMovement * Time.deltaTime);
}
//Controla a ativacao da luz do Mark
//fazendo ela desligar e ligar
if (Input.GetKeyDown(E))
{
LuzPlayer.enabled = !LuzPlayer.enabled;
}
//faz o Mark correr
if (Input.GetKeyDown(R))
{
Velocidade = Input.acceleration.x * 60.0f * Time.deltaTime;
}
else
{
Velocidade = 3.0f;
}
}
}
}
} | 25.082645 | 86 | 0.521582 | [
"MIT"
] | rodrigomassanori/The-Fall-Of-Zombunny | Mark.cs | 3,037 | C# |
namespace Infra.Transacao
{
public interface IUnitOfWork
{
void Commit();
}
}
| 12.375 | 32 | 0.59596 | [
"MIT"
] | newtonisaac/API-Pattern | Infra/Transacao/IUnitOfWork.cs | 101 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace aws
{
[JsiiInterface(nativeType: typeof(IWafv2WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformation), fullyQualifiedName: "aws.Wafv2WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformation")]
public interface IWafv2WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformation
{
[JsiiProperty(name: "priority", typeJson: "{\"primitive\":\"number\"}")]
double Priority
{
get;
}
[JsiiProperty(name: "type", typeJson: "{\"primitive\":\"string\"}")]
string Type
{
get;
}
[JsiiTypeProxy(nativeType: typeof(IWafv2WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformation), fullyQualifiedName: "aws.Wafv2WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformation")]
internal sealed class _Proxy : DeputyBase, aws.IWafv2WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformation
{
private _Proxy(ByRefValue reference): base(reference)
{
}
[JsiiProperty(name: "priority", typeJson: "{\"primitive\":\"number\"}")]
public double Priority
{
get => GetInstanceProperty<double>()!;
}
[JsiiProperty(name: "type", typeJson: "{\"primitive\":\"string\"}")]
public string Type
{
get => GetInstanceProperty<string>()!;
}
}
}
}
| 45.372093 | 348 | 0.719631 | [
"MIT"
] | scottenriquez/cdktf-alpha-csharp-testing | resources/.gen/aws/aws/IWafv2WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformation.cs | 1,951 | C# |
using System.Collections;
using TG.Core;
using UnityEngine;
namespace TG.GameJamTemplate
{
/// <summary>
/// Handles gameplay functionality
/// </summary>
public class GameplayManager : Singleton<GameplayManager>
{
[Header("References")]
[SerializeField] HUDManager _hudManager = default;
[SerializeField] Camera _mainCamera = default;
PoolingController _poolingController = default;
GameObject _auxGO = default;
private void Start()
{
}
public void CreateObjectFromPool(GameObject prefab, Vector3 pos)
{
_auxGO = _poolingController.GetPooledObject(prefab);
_auxGO.transform.position = pos;
_auxGO.SetActive(true);
}
public void GameOver()
{
_hudManager.Save();
StartCoroutine(DelayGameOver());
}
private IEnumerator DelayGameOver()
{
yield return new WaitForSeconds(1);
_hudManager.ShowGameOver();
}
}
} | 24.55814 | 72 | 0.599432 | [
"MIT"
] | tarcisiotm/gamejamtemplate | Assets/3rdParty/GameJamTemplate/Scripts/Managers/GameplayManager.cs | 1,058 | C# |
//-----------------------------------------------------------------------------
// Copyright : (c) Chris Moore, 2020
// License : MIT
//-----------------------------------------------------------------------------
namespace Z0
{
using System;
using System.Runtime.CompilerServices;
using static System.Runtime.CompilerServices.Unsafe;
using static Root;
partial struct core
{
/// <summary>
/// Transforms a readonly T-cell into an editable T-cell
/// </summary>
/// <param name="src">The source cell</param>
/// <typeparam name="T">The cell type</typeparam>
[MethodImpl(Inline), Op, Closures(Closure)]
public static ref T edit<T>(in T src)
=> ref AsRef(src);
/// <summary>
/// Transforms a readonly S-cell into an editable T-cell
/// </summary>
/// <param name="src">The source cell</param>
/// <typeparam name="S">The source type</typeparam>
/// <typeparam name="T">The target type</typeparam>
[MethodImpl(Inline)]
public static ref T edit<S,T>(in S src)
=> ref As<S,T>(ref AsRef(src));
/// <summary>
/// Transforms a readonly S-cell into an editable T-cell
/// </summary>
/// <param name="src">The source cell</param>
/// <param name="dst">The target cell</param>
/// <typeparam name="S">The source type</typeparam>
/// <typeparam name="T">The target type</typeparam>
[MethodImpl(Inline)]
public static ref T edit<S,T>(in S src, ref T dst)
=> ref As<S,T>(ref AsRef(src));
/// <summary>
/// Covers the content of a readonly span with an editable span
/// </summary>
/// <param name="src">The memory source</param>
/// <param name="count">The number of source cells to read</param>
/// <typeparam name="T">The cell type</typeparam>
/// <returns>Obviously, this trick could be particularly dangerous</returns>
[MethodImpl(Inline), Op, Closures(Closure)]
public static Span<T> edit<T>(ReadOnlySpan<T> src)
=> cover(edit(first(src)), src.Length);
}
} | 39.285714 | 84 | 0.532727 | [
"BSD-3-Clause"
] | 0xCM/z0 | src/core/src/ops/edit.cs | 2,200 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mud.Engine.Runtime.Game.Character;
namespace Mud.Engine.Runtime.Game.Character
{
public class InformationMessage : CharacterMessage
{
public InformationMessage(string message, ICharacter targetCharacter)
: base(message, targetCharacter)
{
}
}
}
| 23.166667 | 77 | 0.719424 | [
"MIT"
] | zydronium/muddesigner | Main/Source/Engine/Engine.Runtime/Source/Game/Character/InformationMessage.cs | 419 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using NatureRecorder.Entities.Db;
using NatureRecorder.Interpreter.Entities;
namespace NatureRecorder.Interpreter.Base
{
public abstract class AddEditCommandBase : CommandBase
{
protected const string DateFormat = "dd/MM/yyyy";
protected readonly Map<char, Gender> _genderMap = new Map<char, Gender>
{
{ 'M', Gender.Male },
{ 'F', Gender.Female },
{ 'B', Gender.Both },
{ 'U', Gender.Unknown },
};
/// <summary>
/// Read a line of input, supporting a default value if the user just hits enter
/// </summary>
/// <param name="context"></param>
/// <param name="prompt"></param>
/// <param name="defaultValue"></param>
/// <param name="isOptionalInput"></param>
/// <returns></returns>
protected (string input, bool cancelled) ReadLineWithDefaultValue(CommandContext context, string prompt, string defaultValue, bool isOptionalInput)
{
// Construct the prompt
if (!string.IsNullOrEmpty(defaultValue))
{
prompt = $"{prompt} [{defaultValue}]";
}
// If the input is optional in the current context, blank input is always
// allowed. Otherwise, whether or not blanks are allowed depends on whether
// we have a non-empty default value (yes) or not (no)
bool allowBlank = (isOptionalInput) ? true : !string.IsNullOrEmpty(defaultValue);
// Read the user's input
string input = context.Reader.ReadLine(prompt, allowBlank);
bool cancelled = context.Reader.Cancelled;
// If the user didn't cancel and the input's blank, replace it with
// the default value
if (!cancelled)
{
if (string.IsNullOrEmpty(input))
{
input = defaultValue;
}
}
return (input, cancelled);
}
/// <summary>
/// Read a coordinate (latitude or longitude), supporting a default value
/// if the user just hits enter
/// </summary>
/// <param name="context"></param>
/// <param name="prompt"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
protected (decimal? input, bool cancelled) ReadCoordinateWithDefaultValue(CommandContext context, string prompt, decimal? defaultValue)
{
// Construct the prompt
if (defaultValue != null)
{
prompt = $"{prompt} [{defaultValue}]";
}
// Read the user's input
decimal? input = context.Reader.Read<decimal?>(prompt);
bool cancelled = context.Reader.Cancelled;
// If the user didn't cancel and the input's null, replace it with
// the default value
if (!cancelled)
{
if (input == null)
{
input = defaultValue;
}
}
return (input, cancelled);
}
/// <summary>
/// Prompt for a date
/// </summary>
/// <param name="context"></param>
/// <param name="defaultValue"></param>
/// <param name="expectExisting"></param>
/// <param name="isOptionalInput"></param>
/// <returns></returns>
protected DateTime? PromptForDate(CommandContext context, string defaultValue, bool isOptionalInput)
{
DateTime? date;
bool inputValid;
(string dateString, bool cancelled) input;
do
{
// Reset
date = null;
inputValid = false;
// Read the date
input = ReadLineWithDefaultValue(context, "Date", defaultValue, isOptionalInput);
if (!input.cancelled)
{
// Attempt to parse the input as a date/time value
inputValid = DateTime.TryParseExact(input.dateString, DateFormat, null, DateTimeStyles.None, out DateTime parsedDate);
if (inputValid)
{
// Worked, so assign the return value
date = new DateTime?(parsedDate);
}
else
{
context.Output.WriteLine($"{input.dateString} is not a valid date");
context.Output.Flush();
}
}
}
while (!inputValid && !input.cancelled);
return date;
}
/// <summary>
/// Prompt for the number of individuals seen
/// </summary>
/// <param name="context"></param>
/// <param name="defaultValue"></param>
/// <param name="isEditing"></param>
/// <returns></returns>
protected int? PromptForNumber(CommandContext context, string defaultValue, bool isEditing)
{
int? number;
bool inputValid;
(string numberString, bool cancelled) input;
do
{
// Reset
number = null;
inputValid = false;
// Read the number
input = ReadLineWithDefaultValue(context, "Number", defaultValue, isEditing);
if (!input.cancelled)
{
// Attempt to parse the input as an integer
inputValid = int.TryParse(input.numberString, out int nonNullNumber);
if (inputValid && (nonNullNumber >= 0))
{
number = nonNullNumber;
}
else
{
context.Output.WriteLine($"{input.numberString} is not a valid number of individuals");
context.Output.Flush();
}
}
}
while (!inputValid && !input.cancelled);
return number;
}
/// <summary>
/// Prompt for a location name and check that the corresponding location entity
/// exists or not according to the parameters passed in
/// </summary>
/// <param name="context"></param>
/// <param name="defaultValue"></param>
/// <param name="expectExisting"></param>
/// <returns></returns>
protected Location PromptForLocationByName(CommandContext context, string defaultValue, bool expectExisting)
{
Location location;
bool inputValid;
(string name, bool cancelled) input;
do
{
// Reset
location = null;
inputValid = false;
// Read the location name
input = ReadLineWithDefaultValue(context, "Location", defaultValue, false);
if (!input.cancelled)
{
// Clean the string for comparison with existing locations and
// retrieve the locations with that name
input.name = ToTitleCase(input.name);
location = context.Factory.Locations.Get(l => l.Name == input.name);
// Check the returned location against the "expect existing" flag
if ((location == null) && expectExisting)
{
context.Output.WriteLine($"Location {input.name} does not exist");
context.Output.Flush();
}
else if ((location != null) && !expectExisting)
{
context.Output.WriteLine($"Location {input.name} already exists");
context.Output.Flush();
}
else
{
inputValid = true;
}
}
}
while (!inputValid && !input.cancelled);
// If the location's NULL, create a new one containing the name
if (!context.Reader.Cancelled && (location == null))
{
location = new Location { Name = ToTitleCase(input.name) };
}
return location;
}
/// <summary>
/// Prompt for a location name in the context of editing an existing location
/// and confirm the name that's entered is valid in that context
/// </summary>
/// <param name="context"></param>
/// <param name="defaultValue"></param>
/// <param name="existingLocationId"></param>
/// <returns></returns>
protected (string input, bool cancelled) PromptForLocationNameWhileEditingLocation(CommandContext context, string defaultValue, int existingLocationId)
{
bool inputValid;
(string name, bool cancelled) input;
do
{
// Reset
inputValid = false;
// Read the location name
input = ReadLineWithDefaultValue(context, "Location", defaultValue, true);
if (!input.cancelled)
{
// Clean the string for comparison with existing locations and
// retrieve the locations with that name
input.name = ToTitleCase(input.name);
Location location = context.Factory.Locations.Get(l => l.Name == input.name);
// Either the location must not exist OR it's ID must be the one passed in.
// In other words, either this is a name that's not been used before or the
// name's not changed
if ((location != null) && (location.Id != existingLocationId))
{
context.Output.WriteLine($"Location {input.name} already exists");
context.Output.Flush();
}
else
{
inputValid = true;
}
}
}
while (!inputValid && !input.cancelled);
return input;
}
/// <summary>
/// Prompt for a new location name
/// </summary>
/// <param name="context"></param>
/// <param name="expectExisting"></param>
/// <returns></returns>
protected Category PromptForCategory(CommandContext context, bool expectExisting)
{
Category category;
bool done = false;
string name;
do
{
// Reset
category = null;
// Read the location name
name = context.Reader.ReadLine("Category name", false);
done = context.Reader.Cancelled;
if (!done)
{
// Clean the string for comparison with existing locations
name = ToTitleCase(name);
// See if the category already exists and generate an error
// depending on whether or not it should already exist
category = context.Factory.Categories.Get(c => c.Name == name);
if ((category == null) && expectExisting)
{
context.Output.WriteLine($"Category {name} does not exist");
context.Output.Flush();
}
else if ((category != null) && !expectExisting)
{
context.Output.WriteLine($"Category {name} already exists");
context.Output.Flush();
}
else
{
done = true;
}
}
}
while (!done);
// If the category's NULL, create a new one containing the name
if (!context.Reader.Cancelled && (category == null))
{
category = new Category { Name = name };
}
return category;
}
/// <summary>
/// Prompt for a new location name
/// </summary>
/// <param name="context"></param>
/// <param name="categoryId"></param>
/// <param name="expectExisting"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
protected Species PromptForSpecies(CommandContext context, int? categoryId, bool expectExisting, string defaultValue, bool isEditing)
{
Species species;
bool inputValid;
(string name, bool cancelled) input;
do
{
// Reset
species = null;
inputValid = false;
// Read the location name
input = ReadLineWithDefaultValue(context, "Species name", defaultValue, isEditing);
if (!input.cancelled)
{
// Clean the string for comparison with existing locations
input.name = ToTitleCase(input.name);
// See if the species already exists and generate an error
// depending on whether or not it should already exist
species = context.Factory.Species.Get(s => s.Name == input.name);
if ((species == null) && expectExisting)
{
context.Output.WriteLine($"Species {input.name} does not exist");
context.Output.Flush();
}
else if ((species != null) && !expectExisting)
{
context.Output.WriteLine($"Species {input.name} already exists");
context.Output.Flush();
}
else
{
categoryId = species?.CategoryId;
inputValid = true;
}
}
}
while (!inputValid && !input.cancelled);
// If the species is NULL, create a new one containing the name
if (!context.Reader.Cancelled && (species == null))
{
species = new Species { Name = input.name, CategoryId = categoryId ?? 0 };
}
return species;
}
/// <summary>
/// Prompt for the new location details
/// </summary>
/// <param name="context"></param>
/// <param name="editing"></param>
/// <returns></returns>
protected Location PromptForLocation(CommandContext context, Location editing)
{
Location location;
(string value, bool cancelled) input;
if (editing != null)
{
// Editing an existing location so prompt for the name and apply it to the location instance
input = PromptForLocationNameWhileEditingLocation(context, editing.Name, editing.Id);
if (input.cancelled) return null;
location = new Location { Id = editing.Id, Name = input.value };
}
else
{
// Not editing an existing location so we're adding a new one
location = PromptForLocationByName(context, null, false);
if (location == null) return null;
}
input = ReadLineWithDefaultValue(context, "Address", editing?.Address, true);
if (input.cancelled) return null;
location.Address = input.value;
input = ReadLineWithDefaultValue(context, "City", editing?.City, true);
if (input.cancelled) return null;
location.City = input.value;
input = ReadLineWithDefaultValue(context, "County", editing?.County, true);
if (input.cancelled) return null;
location.County = input.value;
input = ReadLineWithDefaultValue(context, "Postcode", editing?.Postcode, true);
if (input.cancelled) return null;
location.Postcode = input.value;
input = ReadLineWithDefaultValue(context, "Country", editing?.Country, true);
if (input.cancelled) return null;
location.Country = input.value;
// The "optional"
(decimal? value, bool cancelled) coordinate = ReadCoordinateWithDefaultValue(context, "Latitude", editing?.Latitude);
if (input.cancelled) return null;
location.Latitude = coordinate.value;
coordinate = ReadCoordinateWithDefaultValue(context, "Longitude", editing?.Longitude);
if (input.cancelled) return null;
location.Longitude = coordinate.value;
return location;
}
/// <summary>
/// Prompt for the gender associated with a sighting
/// </summary>
/// <param name="context"></param>
/// <param name="defaultValue"></param>
/// <param name="isEditing"></param>
/// <returns></returns>
protected Gender? PromptForGender(CommandContext context, Gender defaultValue, bool isEditing)
{
Gender? gender = null;
// Map the default gender to the corresponding option
char defaultOption = _genderMap.GetKey(defaultValue);
// Read the gender. A null return means the entry was cancelled
char? selection = context.Reader.PromptForOption("Gender", _genderMap.Keys, defaultOption);
if (selection != null)
{
// Map the option to the corresponding enum value
gender = _genderMap[selection ?? defaultOption];
}
return gender;
}
/// <summary>
/// Add a sighting
/// </summary>
/// <param name="context"></param>
/// <param name="editing"></param>
/// <returns></returns>
protected Sighting PromptForSighting(CommandContext context, Sighting editing)
{
// Output a spacer line
context.Output.WriteLine();
context.Output.Flush();
// Empty input is allowed when editing an existing sighting as, in that
// case, the current sighting properties will be used as the default
// values for input
bool isOptionalInput = (editing != null);
// Prompt for the location
string defaultValue = editing?.Location.Name ?? context.CurrentLocation?.Name ?? context.Settings.Location;
Location location = PromptForLocationByName(context, defaultValue, true);
if (context.Reader.Cancelled) return null;
// Prompt for the date of sighting
defaultValue = (editing?.Date ?? context.CurrentDate ?? DateTime.Now).ToString(DateFormat);
DateTime? date = PromptForDate(context, defaultValue, isOptionalInput);
if (date == null) return null;
// Prompt for the species
Species species = PromptForSpecies(context, null, true, editing?.Species.Name, isOptionalInput);
if (species == null) return null;
// Prompt for the number of individuals seen
int? number = PromptForNumber(context, (editing?.Number ?? 0).ToString(), isOptionalInput);
if (number == null) return null;
// Prompt for the gender of individuals seen
Gender? gender = PromptForGender(context, editing?.Gender ?? Gender.Unknown, isOptionalInput);
if (gender == null) return null;
// Yes/No prompt for whether or not young were also seen
bool withYoung = context.Reader.PromptForYesNo("Seen with young", 'N');
return new Sighting
{
Id = editing?.Id ?? 0,
Location = location,
LocationId = location.Id,
Species = species,
SpeciesId = species.Id,
Date = date ?? DateTime.Now,
Number = number ?? 0,
Gender = gender ?? Gender.Unknown,
WithYoung = withYoung
};
}
}
}
| 38.932075 | 159 | 0.511292 | [
"MIT"
] | davewalker5/NatureRecorderDb | src/NatureRecorder.Interpreter/Base/AddEditCommandBase.cs | 20,636 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Connection.UnitTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Connection.UnitTests")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("c25e03b0-ed03-498d-937e-83fc22ac12bc")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 26.459459 | 59 | 0.722165 | [
"Unlicense"
] | visiontrail/LMT2018 | Src/SCMT/Control/SCMTOperationCore/Connection.UnitTests/Properties/AssemblyInfo.cs | 1,330 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net.Mail;
using System.Threading.Tasks;
using System.Web.Hosting;
using AnglicanGeek.MarkdownMailer;
using Elmah;
using NuGetGallery.Configuration;
namespace NuGetGallery.Infrastructure.Mail
{
public class BackgroundMarkdownMessageService : MarkdownMessageService
{
public BackgroundMarkdownMessageService(
IMailSender mailSender,
IAppConfiguration config,
ITelemetryService telemetryService,
ErrorLog errorLog,
Func<BackgroundMarkdownMessageService> messageServiceFactory)
: base(mailSender, config, telemetryService)
{
_errorLog = errorLog ?? throw new ArgumentNullException(nameof(errorLog));
_messageServiceFactory = messageServiceFactory ?? throw new ArgumentNullException(nameof(messageServiceFactory));
_sentMessage = false;
}
private readonly ErrorLog _errorLog;
private Func<BackgroundMarkdownMessageService> _messageServiceFactory;
private bool _sentMessage;
protected override Task SendMessageInternalAsync(MailMessage mailMessage)
{
// Some MVC controller actions send more than one message. Since this method sends
// the message async, we need a new IMessageService per email, to avoid calling
// SmtpClient.SendAsync on an instance already with an Async operation in progress.
if (_sentMessage)
{
var newMessageService = _messageServiceFactory.Invoke();
return newMessageService.SendMessageInternalAsync(mailMessage);
}
else
{
_sentMessage = true;
// Send email as background task, as we don't want to delay the HTTP response.
// Particularly when sending email fails and needs to be retried with a delay.
// MailMessage is IDisposable, so first clone the message, to ensure if the
// caller disposes it, the message is available until the async task is complete.
var messageCopy = CloneMessage(mailMessage);
HostingEnvironment.QueueBackgroundWorkItem(async _ =>
{
try
{
await base.SendMessageInternalAsync(messageCopy);
}
catch (Exception ex)
{
// Log but swallow the exception.
QuietLog.LogHandledException(ex, _errorLog);
}
finally
{
messageCopy.Dispose();
}
});
return Task.CompletedTask;
}
}
private MailMessage CloneMessage(MailMessage mailMessage)
{
string from = mailMessage.From.ToString();
string to = mailMessage.To.ToString();
MailMessage copy = new MailMessage(from, to, mailMessage.Subject, mailMessage.Body);
copy.IsBodyHtml = mailMessage.IsBodyHtml;
copy.BodyTransferEncoding = mailMessage.BodyTransferEncoding;
copy.BodyEncoding = mailMessage.BodyEncoding;
copy.HeadersEncoding = mailMessage.HeadersEncoding;
foreach (System.Collections.Specialized.NameValueCollection header in mailMessage.Headers)
{
copy.Headers.Add(header);
}
copy.SubjectEncoding = mailMessage.SubjectEncoding;
copy.DeliveryNotificationOptions = mailMessage.DeliveryNotificationOptions;
foreach (var cc in mailMessage.CC)
{
copy.CC.Add(cc);
}
foreach (var attachment in mailMessage.Attachments)
{
copy.Attachments.Add(attachment);
}
foreach (var bcc in mailMessage.Bcc)
{
copy.Bcc.Add(bcc);
}
foreach (var replyTo in mailMessage.ReplyToList)
{
copy.ReplyToList.Add(replyTo);
}
copy.Sender = mailMessage.Sender;
copy.Priority = mailMessage.Priority;
foreach (var view in mailMessage.AlternateViews)
{
copy.AlternateViews.Add(view);
}
return copy;
}
}
} | 39.576271 | 125 | 0.583512 | [
"Apache-2.0"
] | 0xced/NuGetGallery | src/NuGetGallery/Infrastructure/Mail/BackgroundMarkdownMessageService.cs | 4,672 | C# |
using System;
using NUnit.Framework;
namespace JsonConfig.Tests
{
[TestFixture()]
public class InvalidJson
{
[Test]
[ExpectedException (typeof(Newtonsoft.Json.JsonReaderException))]
public void EvidentlyInvalidJson ()
{
dynamic scope = Config.Global;
scope.ApplyJson ("jibberisch");
}
[Test]
[ExpectedException(typeof(Newtonsoft.Json.JsonReaderException))]
public void MissingObjectIdentifier()
{
dynamic scope = Config.Global;
var invalid_json = @" { [1, 2, 3] }";
scope.ApplyJson (invalid_json);
}
}
}
| 20.259259 | 67 | 0.705667 | [
"MIT"
] | nefarius/JsonConfig | JsonConfig.Tests/InvalidJson.cs | 547 | C# |
using Xamarin.Forms;
using Xamarin.CommunityToolkit.Markup;
namespace GitStatus
{
public abstract class BaseStatusPage<T> : BaseContentPage<T> where T : BaseStatusViewModel
{
protected BaseStatusPage(T statusViewModel, string title) : base(statusViewModel, title)
{
BackgroundColor = Color.White;
Content = new StackLayout
{
Children =
{
new Label { TextColor = Color.Black }.Center().TextCenter()
.Bind(Label.TextProperty, nameof(BaseStatusViewModel.StatusLabelText)),
new Button { Text = "Get Status"}.Center()
.Bind(Button.CommandProperty, nameof(BaseStatusViewModel.GetStatusCommand)),
new ActivityIndicator { Color = Color.Black }.Center()
.Bind(IsVisibleProperty, nameof(BaseStatusViewModel.IsBusy))
.Bind(ActivityIndicator.IsRunningProperty, nameof(BaseStatusViewModel.IsBusy))
}
}.Center();
}
}
}
| 36.6 | 102 | 0.581056 | [
"MIT"
] | brminnick/GitStatus | Src/GitStatus/Pages/Base/BaseStatusPage.cs | 1,100 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using Chayns.Backend.Api.Models.Data;
namespace Chayns.Backend.Api.Helper
{
public static class UrlParameterConverter
{
/// <summary>
/// Serializes an object to url-parameters
/// </summary>
/// <typeparam name="TData">Datatype of the serializeable object</typeparam>
/// <param name="data">Object to serialize</param>
/// <returns>Url-parameters</returns>
public static string SerializeObject<TData>(TData data) where TData : ChangeableData
{
HashSet<string> changedProperties;
if ((changedProperties = data?.GetAllChangedProperties()) == null || changedProperties.Count == 0)
{
return "";
}
var baseType = data.GetType();
var parameters = new List<string>();
foreach (var propName in changedProperties)
{
var valStr = "";
var converter = new StringConverter();
var prop = baseType.GetProperty(propName);
var val = prop.GetValue(data);
if (val is IEnumerable && !(val is string))
{
var arrEntries = prop.GetValue(data) as IEnumerable;
if (arrEntries != null)
{
foreach (var arrEntry in arrEntries)
{
string valToAdd;
if (converter.CanConvertFrom(prop.GetType()))
{
valToAdd = converter.ConvertFrom(arrEntry)?.ToString() ?? "";
}
else
{
valToAdd = arrEntry?.ToString() ?? "";
}
if (valToAdd != "") valStr += $"{valToAdd},";
}
valStr = $"[{valStr.Remove(valStr.LastIndexOf(','), 1)}]";
}
}
else
{
if (converter.CanConvertFrom(prop.GetType()))
{
valStr = converter.ConvertFrom(val)?.ToString() ?? "";
}
else
{
valStr = val?.ToString() ?? "";
}
}
if (valStr != "") parameters.Add($"{propName}={valStr}");
}
if (parameters.Count == 0) return "";
return "?" + string.Join("&", parameters);
}
}
}
| 35.831169 | 110 | 0.433853 | [
"MIT"
] | TobitSoftware/ChaynsBackendApiHelper | ChaynsBackendApiHelper/Api/Helper/UrlParameterConverter.cs | 2,761 | C# |
#if !ASPNETCLASSIC
using System.Collections.Generic;
namespace HotChocolate.AspNetCore.Subscriptions
{
internal class DictionaryOperationMessage
: OperationMessage
{
public IReadOnlyDictionary<string, object> Payload { get; set; }
}
}
#endif
| 18.266667 | 72 | 0.722628 | [
"MIT"
] | Dolfik1/hotchocolate | src/Server/AspNetCore/Subscriptions/DictionaryOperationMessage.cs | 276 | C# |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace MicroTest {
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class TestAsync : TestAttribute {
public TestAsync() { }
public TestAsync(string description) : base(description) { }
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class TestAttribute : Attribute{
private string[] dependencies = new string[0];
public uint TimeoutSeconds { get; set; } //
public string Description { get; set; }
public string Dependencies {
get { return string.Join(",", dependencies); }
set { dependencies = (value ?? "").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); }
}
public TestAttribute() {}
public TestAttribute(string description) : base() {
this.Description = description;
}
internal static IEnumerable<Test> FindAll() {
foreach(var assembly in new Assembly[] { Assembly.GetCallingAssembly(), Assembly.GetEntryAssembly(), Assembly.GetExecutingAssembly() }) {
foreach(var type in assembly.GetTypes()){
foreach(var test in FindAll(type)) {
yield return test;
}
}
}
}
internal static IEnumerable<Test> FindAll(Type type) {
foreach(var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) {
var arguments = method.GetParameters();
if(arguments.Length == 1 && arguments[0].ParameterType == typeof(Test) && type.Namespace != "MicroTest") {
var attribute = (TestAttribute)Array.Find<object>(method.GetCustomAttributes(false), a=> a is TestAttribute);
yield return new TestImpl(
method,
type.Namespace + "." + type.Name,
method.Name.ToLower().EndsWith("Test") ? method.Name.Substring(0,method.Name.Length-4) : method.Name,
attribute != null ? attribute.Description : null,
attribute != null ? attribute.dependencies : null,
attribute != null && attribute.TimeoutSeconds>0? TimeSpan.FromSeconds( attribute.TimeoutSeconds ): (TimeSpan?) null,
attribute != null && attribute is TestAsync
);
}
}
}
private class TestImpl : Test {
private static Dictionary<Type, object> instances = new Dictionary<Type, object>();
private MethodInfo method;
public TestImpl(MethodInfo method, string @namespace, string id, string description, string[] dependencies, TimeSpan? timeout, bool async) : base(@namespace, id, description, dependencies, timeout, async) {
this.method = method;
}
protected override void Execute() {
// get create an instance to call
object instance = null;
lock(instances) {
if(!instances.TryGetValue(method.DeclaringType, out instance)) {
instances[method.DeclaringType] = instance = Activator.CreateInstance(method.DeclaringType);
}
}
// Using DynamicMethods to invoke the method instead of just calling method.Invoke(...)
// because visual studio will otherwise treat any exceptions thrown by the method as
// unhandled and jump straight to it, which is not really useful since MicroTest depends
// on being able to throw exceptions to stop tests when they fail.
if(!method.IsStatic) {
var dm = new DynamicMethod("__dynamic_test_method__", null, new Type[] { typeof(object), typeof(Test) }, true);
ILGenerator il = dm.GetILGenerator(256);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Castclass, method.DeclaringType);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Callvirt, method);
il.Emit(OpCodes.Ret);
var dynMethod = (Action<object, Test>)dm.CreateDelegate(typeof(Action<object, Test>));
dynMethod(instance, this);
} else {
var dm = new DynamicMethod("__dynamic_test_method__", null, new Type[] { typeof(Test) }, true);
ILGenerator il = dm.GetILGenerator(256);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, method);
il.Emit(OpCodes.Ret);
var dynMethod = (Action<Test>)dm.CreateDelegate(typeof(Action<Test>));
dynMethod(this);
}
}
protected override string[] FilterFailureStacktrace(string[] stacktrace) {
for(var i=stacktrace.Length-1;i>0;i--){
if(stacktrace[i].IndexOf("System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)") > -1 || stacktrace[i].IndexOf("__dynamic_test_method__")>-1) {
var newStackTrace = new string[i];
Array.Copy(stacktrace, newStackTrace, newStackTrace.Length);
return newStackTrace;
}
}
return stacktrace;
}
}
}
} | 41.491071 | 209 | 0.699161 | [
"MIT"
] | oliverkofoed/MicroTest | MicroTest/TestAttribute.cs | 4,649 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Win32ErrorTable
{
// TODO: Source info (filename with path, line number).
// TODO: HvStatus.h
public sealed partial class NtStatusH
{
private static ErrorMessage CreateMessage(uint code, string messageId, IEnumerable<string> messageTextLines)
{
return new ErrorMessage(code, new List<string> { messageId }, string.Join("\n", messageTextLines));
}
private const string Identifier = "[A-Z][A-Za-z_0-9]*";
private static readonly Regex CommentRegex = new Regex(@"^(.*)\s// (winnt|ntsubauth)$");
private static readonly Regex FacilityHexRegex = new Regex(@"^#define (FACILITY_[A-Za-z_0-9]+)\s+0x([0-9A-Fa-f]+)$");
private static readonly Regex FaciltiyHexRegex = new Regex(@"^#define (FACILTIY_[A-Za-z_0-9]+)\s+0x([0-9A-Fa-f]+)$");
private static readonly Regex SeverityHexRegex = new Regex(@"^#define STATUS_SEVERITY_([A-Za-z_0-9]+)\s+0x([0-9A-Fa-f]+)$");
private static readonly Regex MessageIdRegex = new Regex(@"^MessageId: (" + Identifier + @")$");
private static readonly Regex DefineNtStatusHexCastRegex = new Regex(@"^#define (" + Identifier + @")\s+\(\(NTSTATUS\)0x([0-9A-Fa-f]{8})L?\)$");
private string messageId;
private List<string> messageText;
private readonly List<ErrorMessage> ntstatus = new List<ErrorMessage>();
private readonly List<Facility> facilities = new List<Facility>();
private static Version TryParseVersion(string s)
{
Version result;
if (Version.TryParse(s, out result))
return result;
return null;
}
public Results Process()
{
var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Windows Kits", "10", "Include");
var selected = Directory.EnumerateDirectories(path).Select(dir => new { dir, ver = TryParseVersion(Path.GetFileName(dir)) }).OrderByDescending(x => x.ver).First();
path = selected.dir;
path = Path.Combine(path, "shared");
var lines = File.ReadAllLines(Path.Combine(path, "ntstatus.h"));
foreach (var line in lines.Select(x => x.Trim(' ', '\t', '/', '*')).Select(x =>
{
var match = CommentRegex.Match(x);
return match.Success ? match.Groups[1].Value.Trim(' ', '\t') : x;
}).Where(x => x != ""))
{
Match match;
if (messageId == null)
{
if (line.StartsWith("#if") || line.StartsWith("#else") || line.StartsWith("#endif") || line.StartsWith("#undef") || line.StartsWith("#pragma"))
continue;
if (IgnoredLines.Contains(line))
continue;
match = FacilityHexRegex.Match(line);
if (match.Success)
{
var id = match.Groups[1].Value;
var value = uint.Parse(match.Groups[2].Value, NumberStyles.AllowHexSpecifier);
var existing = facilities.FirstOrDefault(x => x.Value == value);
if (existing == null)
facilities.Add(new Facility(value, new List<FacilityName> { new FacilityName(id, FacilityDescription(id)) }));
else
existing.Names.Add(new FacilityName(id, FacilityDescription(id)));
continue;
}
match = FaciltiyHexRegex.Match(line);
if (match.Success)
{
var id = match.Groups[1].Value;
var value = uint.Parse(match.Groups[2].Value, NumberStyles.AllowHexSpecifier);
var existing = facilities.FirstOrDefault(x => x.Value == value);
if (existing == null)
facilities.Add(new Facility(value, new List<FacilityName> { new FacilityName(id, FacilityDescription(id), "Note that \"FACILTIY\" is misspelled") }));
else
existing.Names.Add(new FacilityName(id, FacilityDescription(id), "Note that \"FACILTIY\" is misspelled"));
continue;
}
match = SeverityHexRegex.Match(line);
if (match.Success)
continue;
match = MessageIdRegex.Match(line);
if (match.Success)
{
messageId = match.Groups[1].Value;
continue;
}
}
else if (messageText == null)
{
if (line == "MessageText:")
{
messageText = new List<string>();
continue;
}
}
else
{
if (line.StartsWith("#define " + messageId))
{
match = DefineNtStatusHexCastRegex.Match(line);
if (match.Success)
{
//Console.WriteLine(messageId + " = " + match.Groups[2].Value);
ntstatus.Add(CreateMessage(uint.Parse(match.Groups[2].Value, NumberStyles.AllowHexSpecifier), messageId, messageText));
messageId = null;
messageText = null;
continue;
}
}
else
{
messageText.Add(line);
continue;
}
}
Console.WriteLine("\"" + line + "\",");
System.Windows.Forms.Clipboard.SetText("\"" + line + "\",");
//Console.ReadKey();
messageId = null;
messageText = null;
}
return new Results(null, null, null, ntstatus, facilities);
}
}
}
| 44.109589 | 178 | 0.497516 | [
"MIT"
] | StephenClearyApps/WinErrorCodes | src/Win32ErrorTable/NtStatusH.cs | 6,442 | C# |
using System.Text.Json.Serialization;
using Backend.Models.Base.Metadata.POCO;
namespace Backend.Models.MetAPI.POCO
{
public class Forecast
{
[JsonPropertyName("properties")] public Properties ForecastProperties { get; set; }
[JsonPropertyName("geometry")] public Geometry ForecastGeometry { get; set; }
[JsonPropertyName("type")] public string Type { get; set; }
[JsonPropertyName("metadata")] public StoredMetadata StoredMetadata { get; set; }
}
} | 31.125 | 91 | 0.700803 | [
"Apache-2.0"
] | IT2901-SINTEF01/backend | Models/MetAPI/POCO/Forecast.cs | 500 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Pchp.Core;
using static Peachpie.Library.PDO.PDO;
using static Pchp.Library.Objects;
using Pchp.Core.Reflection;
namespace Peachpie.Library.PDO
{
/// <summary>
/// PDOStatement class
/// </summary>
[PhpType(PhpTypeAttribute.InheritName)]
[PhpExtension(PDOConfiguration.PdoExtensionName)]
public class PDOStatement : IDisposable
{
/// <summary>Runtime context. Cannot be <c>null</c>.</summary>
protected readonly Context _ctx; // "_ctx" is a special name recognized by compiler. Will be reused by inherited classes.
private PDO m_pdo;
private string m_stmt;
private PhpArray m_options;
private DbCommand m_cmd;
private DbDataReader m_dr;
private readonly Dictionary<PDO.PDO_ATTR, PhpValue> m_attributes = new Dictionary<PDO_ATTR, PhpValue>();
private string[] m_dr_names;
private bool m_positionalAttr = false;
private bool m_namedAttr = false;
private Dictionary<string, string> m_namedPlaceholders;
private List<string> m_positionalPlaceholders;
private Dictionary<string, PhpAlias> m_boundParams;
private PDO_FETCH m_fetchStyle = PDO_FETCH.Default;
private PhpArray storedQueryResult = null;
private int storedResultPosition = 0;
/// <summary>
/// Property telling whether there are any command parameter variables bound with bindParam.
/// </summary>
bool HasParamsBound => m_boundParams != null && m_boundParams.Count != 0;
/// <summary>
/// Column Number property for FETCH_COLUMN fetching.
/// </summary>
int? FetchColNo { get; set; }
/// <summary>
/// Class Name property for FETCH_CLASS fetching mode.
/// </summary>
PhpTypeInfo FetchClassName { get; set; }
/// <summary>
/// Class Constructor Args for FETCH_CLASS fetching mode.
/// </summary>
PhpValue[] FetchClassCtorArgs { get; set; }
/// <summary>
/// Class instance to results be fetched into (FETCH_INTO).
/// </summary>
object FetchClassInto { get; set; }
private bool CheckDataReader()
{
if (m_dr == null)
{
RaiseError("The data reader cannot be null.");
return false;
}
else
{
return true;
}
}
private void RaiseError(string message)
{
m_pdo.HandleError(new PDOException(message));
}
/// <summary>
/// Default constructor that does not initialize the statement.
/// </summary>
[PhpFieldsOnlyCtor]
protected PDOStatement(Context ctx)
{
Debug.Assert(ctx != null);
_ctx = ctx;
m_pdo = null;
m_stmt = null;
m_options = PhpArray.Empty;
m_cmd = null;
}
/// <summary>
/// Initializes a new instance of the <see cref="PDOStatement" /> class.
/// </summary>
/// <param name="ctx">The php context.</param>
/// <param name="pdo">The PDO statement is created for.</param>
/// <param name="statement">The statement.</param>
/// <param name="driver_options">The driver options.</param>
internal PDOStatement(Context ctx, PDO pdo, string statement, PhpArray driver_options)
: this(ctx)
{
PrepareStatement(pdo, statement, driver_options);
}
internal void PrepareStatement(PDO pdo, string statement, PhpArray driver_options)
{
if (pdo.HasExecutedQuery)
{
if (!pdo.StoreLastExecutedQuery())
{
pdo.HandleError(new PDOException("Last executed PDOStatement result set could not be saved correctly."));
}
}
this.m_pdo = pdo;
this.m_stmt = statement;
this.m_options = driver_options ?? PhpArray.Empty;
this.m_cmd = pdo.CreateCommand(this.m_stmt);
PrepareStatement();
}
private static readonly Regex regName = new Regex(@"[\w_]+", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private PhpValue FetchFromStored()
{
if (storedQueryResult != null)
{
if (storedResultPosition < storedQueryResult.Count)
{
return storedQueryResult[storedResultPosition++];
}
return PhpValue.False;
}
return PhpValue.False;
}
/// <summary>
/// Function for storing the whole dataset result of a query from the dataReader.
/// Necessary, because there can be only one data reader open for a single Db connection = single PDO instance.
/// </summary>
/// <returns>true on success, false otherwise</returns>
public bool StoreQueryResult()
{
if (m_dr != null)
{
if (m_dr.HasRows)
{
storedQueryResult = fetchAll();
storedResultPosition = 0;
}
else
{
// No rows to save - possibly a non-query statement was executed
return true;
}
}
else
{
//m_pdo.HandleError(new PDOException("There are no rows to store."));
return false;
}
return true;
}
/// <summary>
/// Prepare the PDOStatement command.
/// Set either positional, named or neither parameters mode.
/// Create the parameters, add them to the command and prepare the command.
/// </summary>
/// <returns></returns>
private bool PrepareStatement()
{
Debug.Assert(m_stmt != null && m_stmt.Length > 0);
m_namedPlaceholders = new Dictionary<string, string>();
m_positionalPlaceholders = new List<string>();
m_namedAttr = false;
m_positionalAttr = false;
int pos = 0;
var rewrittenQuery = new StringBuilder();
// Go throught the text query and find either positional or named parameters
while (pos < m_stmt.Length)
{
char currentChar = m_stmt[pos];
string paramName = "";
switch (currentChar)
{
case '?':
if (m_namedAttr)
{
throw new PDOException("Mixing positional and named parameters not allowed. Use only '?' or ':name' pattern");
}
m_positionalAttr = true;
paramName = "@p" + m_positionalPlaceholders.Count();
m_positionalPlaceholders.Add(paramName);
rewrittenQuery.Append(paramName);
break;
case ':':
if (m_positionalAttr)
{
throw new PDOException("Mixing positional and named parameters not allowed.Use only '?' or ':name' pattern");
}
m_namedAttr = true;
var match = regName.Match(m_stmt, pos);
string param = match.Value;
paramName = "@" + param;
m_namedPlaceholders[param] = paramName;
rewrittenQuery.Append(paramName);
pos += param.Length;
break;
case '"':
rewrittenQuery.Append(currentChar);
pos = SkipQuotedWord(m_stmt, rewrittenQuery, pos, '"');
break;
case '\'':
rewrittenQuery.Append(currentChar);
pos = SkipQuotedWord(m_stmt, rewrittenQuery, pos, '\'');
break;
default:
rewrittenQuery.Append(currentChar);
break;
}
pos++;
}
m_cmd.CommandText = rewrittenQuery.ToString();
m_cmd.Parameters.Clear();
if (m_positionalAttr)
{
// Mixed parameters not allowed
if (m_namedAttr)
{
m_pdo.HandleError(new PDOException("Mixed parameters mode not allowed. Use either only positional, or only named parameters."));
return false;
}
foreach (var paramName in m_positionalPlaceholders.ToArray())
{
var param = m_cmd.CreateParameter();
param.ParameterName = paramName;
m_cmd.Parameters.Add(param);
}
}
else if (m_namedAttr)
{
foreach (var paramPair in m_namedPlaceholders)
{
var param = m_cmd.CreateParameter();
param.ParameterName = paramPair.Key;
m_cmd.Parameters.Add(param);
}
}
// Finalise the command preparation
m_cmd.Prepare();
return true;
}
private void SetAttributesType()
{
throw new NotImplementedException();
}
/// <summary>
/// Skip the quoted part of query
/// </summary>
/// <param name="query">Textual query</param>
/// <param name="rewrittenBuilder">StringBuilder for the rewritten query</param>
/// <param name="pos">Current position in the query</param>
/// <param name="quoteType">Quotational character used</param>
/// <returns>New position in the query</returns>
private int SkipQuotedWord(string query, StringBuilder rewrittenBuilder, int pos, char quoteType)
{
while (++pos < query.Length)
{
char currentChar = query[pos];
rewrittenBuilder.Append(currentChar);
if (currentChar == quoteType)
break;
if (currentChar == '\\')
pos++;
}
return pos;
}
/// <inheritDoc />
void IDisposable.Dispose()
{
this.m_dr?.Dispose();
this.m_cmd.Dispose();
}
private void OpenReader()
{
if (m_dr == null)
{
PDO.PDO_CURSOR cursor = (PDO.PDO_CURSOR)this.m_attributes[PDO.PDO_ATTR.ATTR_CURSOR].ToLong();
this.m_dr = this.m_pdo.Driver.OpenReader(this.m_pdo, this.m_cmd, cursor);
switch (cursor)
{
case PDO.PDO_CURSOR.CURSOR_FWDONLY:
this.m_dr = this.m_cmd.ExecuteReader();
break;
case PDO.PDO_CURSOR.CURSOR_SCROLL:
this.m_dr = this.m_cmd.ExecuteReader();
break;
default:
throw new InvalidProgramException();
}
InitializeColumnNames();
}
}
/// <summary>
/// Bind a column to a PHP variable.
/// </summary>
/// <param name="colum">Number of the column (1-indexed) or name of the column in the result set. If using the column name, be aware that the name should match the case of the column, as returned by the driver</param>
/// <param name="param">Name of the PHP variable to which the column will be bound.</param>
/// <param name="type">Data type of the parameter, specified by the PDO::PARAM_* constants.</param>
/// <param name="maxlen">A hint for pre-allocation.</param>
/// <param name="driverdata">Optional parameter(s) for the driver.</param>
/// <returns>Returns TRUE on success or FALSE on failure</returns>
public bool bindColumn(PhpValue colum, PhpAlias param, int? type = default(int?), int? maxlen = default(int?), PhpValue? driverdata = default(PhpValue?))
{
throw new NotImplementedException();
}
/// <summary>
/// Binds a parameter to the specified variable name
/// </summary>
/// <param name="parameter">Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.</param>
/// <param name="variable">Name of the PHP variable to bind to the SQL statement parameter.</param>
/// <param name="data_type">Explicit data type for the parameter using the PDO::PARAM_* constants. To return an INOUT parameter from a stored procedure, use the bitwise OR operator to set the PDO::PARAM_INPUT_OUTPUT bits for the data_type parameter.</param>
/// <param name="length">Length of the data type. To indicate that a parameter is an OUT parameter from a stored procedure, you must explicitly set the length.</param>
/// <param name="driver_options"></param>
/// <returns>Returns TRUE on success or FALSE on failure.</returns>
public bool bindParam(PhpValue parameter, PhpAlias variable, PDO.PARAM data_type = PDO.PARAM.PARAM_STR, int length = -1, PhpValue driver_options = default(PhpValue))
{
Debug.Assert(this.m_cmd != null);
// lazy instantization
if (m_boundParams == null)
m_boundParams = new Dictionary<string, PhpAlias>();
IDbDataParameter param;
if (m_namedAttr)
{
// Mixed parameters not allowed
if (m_positionalAttr)
{
m_pdo.HandleError(new PDOException("Mixed parameters mode not allowed. Use either only positional, or only named parameters."));
return false;
}
if (parameter.IsString(out var key) && !string.IsNullOrEmpty(key))
{
if (key.Length > 0 && key[0] == ':')
{
key = key.Substring(1);
}
//Store the bounded variable reference in the dictionary
m_boundParams.Add(key, variable);
param = m_cmd.Parameters[key];
}
else
{
m_pdo.HandleError(new PDOException("Supplied parameter name must be a string."));
return false;
}
}
else if (m_positionalAttr)
{
if (parameter.IsLong(out var index)) // 1-based index
{
index--;
//Store the bounded variable.Value reference in the dictionary
m_boundParams.Add(index.ToString(), variable);
param = (index < m_positionalPlaceholders.Count)
? m_cmd.Parameters[(int)index]
: null;
}
else
{
m_pdo.HandleError(new PDOException("Supplied parameter index must be an integer."));
return false;
}
}
else
{
m_pdo.HandleError(new PDOException("No parameter mode set yet for this Statement. Possibly no parameters required?"));
return false;
}
if (param == null)
{
m_pdo.HandleError(new PDOException("No matching parameter found."));
return false;
}
switch (data_type)
{
case PDO.PARAM.PARAM_INT:
if (variable.Value.IsInteger())
{
param.DbType = DbType.Int32;
}
else
{
m_pdo.HandleError(new PDOException("Parameter type does not match the declared type."));
return false;
}
break;
case PDO.PARAM.PARAM_STR:
if (variable.Value.IsString() || variable.Value.IsNull)
{
param.DbType = DbType.String;
}
else
{
m_pdo.HandleError(new PDOException("Parameter type does not match the declared type."));
return false;
}
break;
case PDO.PARAM.PARAM_BOOL:
if (variable.Value.IsBoolean())
{
param.DbType = DbType.Boolean;
}
else
{
m_pdo.HandleError(new PDOException("Parameter type does not match the declared type."));
return false;
}
break;
case PDO.PARAM.PARAM_LOB:
if (variable.Value.IsString() || variable.Value.IsNull) // Unicode or byte[]
{
param.DbType = DbType.Binary;
}
else
{
m_pdo.HandleError(new PDOException("Parameter type does not match the declared type."));
return false;
}
break;
// Currently not supported by any drivers
case PDO.PARAM.PARAM_NULL:
case PDO.PARAM.PARAM_STMT:
throw new NotImplementedException();
}
return true;
}
/// <summary>
/// Binds a value to a parameter.
/// </summary>
/// <param name="parameter">Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.</param>
/// <param name="value">The value to bind to the parameter.</param>
/// <param name="data_type">Explicit data type for the parameter using the PDO::PARAM_* constants.</param>
/// <returns>Returns TRUE on success or FALSE on failure</returns>
public bool bindValue(PhpValue parameter, PhpValue value, PDO.PARAM data_type = (PDO.PARAM)PDO.PARAM_STR)
{
Debug.Assert(this.m_cmd != null);
IDbDataParameter param;
if (m_namedAttr)
{
// Mixed parameters not allowed
if (m_positionalAttr)
{
m_pdo.HandleError(new PDOException("Mixed parameters mode not allowed. Use either only positional, or only named parameters."));
return false;
}
if (parameter.IsString(out var key))
{
if (key.Length > 0 && key[0] == ':')
{
key = key.Substring(1);
}
param = m_cmd.Parameters[key];
//rewrite the bounded params dictionary
if (HasParamsBound)
{
m_boundParams.Remove(key);
}
}
else
{
m_pdo.HandleError(new PDOException("Supplied parameter name must be a string."));
return false;
}
}
else if (m_positionalAttr)
{
if (parameter.IsLong(out var index)) // 1-based index
{
index--;
param = (index < m_positionalPlaceholders.Count)
? m_cmd.Parameters[(int)index]
: null;
//rewrite the bounded params dictionary
if (HasParamsBound)
{
m_boundParams.Remove(index.ToString());
}
}
else
{
m_pdo.HandleError(new PDOException("Supplied parameter index must be an integer."));
return false;
}
}
else
{
m_pdo.HandleError(new PDOException("No parameter mode set yet for this Statement. Possibly no parameters required?"));
return false;
}
if (param == null)
{
m_pdo.HandleError(new PDOException("No matching parameter found."));
return false;
}
switch (data_type)
{
case PDO.PARAM.PARAM_INT:
if (value.IsInteger())
{
param.DbType = DbType.Int32;
param.Value = (int)value;
}
else
{
m_pdo.HandleError(new PDOException("Parameter type does not match the declared type."));
return false;
}
break;
case PDO.PARAM.PARAM_STR:
string str = null;
if ((str = value.ToStringOrNull()) != null)
{
param.DbType = DbType.String;
param.Value = str;
}
else
{
m_pdo.HandleError(new PDOException("Parameter type does not match the declared type."));
return false;
}
break;
case PDO.PARAM.PARAM_BOOL:
if (value.IsBoolean())
{
param.DbType = DbType.Boolean;
param.Value = value.ToBoolean();
}
else
{
m_pdo.HandleError(new PDOException("Parameter type does not match the declared type."));
return false;
}
break;
case PDO.PARAM.PARAM_LOB:
byte[] bytes = null;
if ((bytes = value.ToBytesOrNull()) != null)
{
param.DbType = DbType.Binary;
param.Value = bytes;
}
else
{
m_pdo.HandleError(new PDOException("Parameter type does not match the declared type."));
return false;
}
break;
// Currently not supported by any drivers
case PDO.PARAM.PARAM_NULL:
case PDO.PARAM.PARAM_STMT:
default:
throw new NotImplementedException();
}
return true;
}
/// <inheritDoc />
public bool bindValues(PhpValue parameter, PhpValue value, int data_type = 2)
{
throw new NotImplementedException();
}
/// <summary>
/// Closes the current data reader, so that the DbConnection can be reused.
/// Should store its state
/// </summary>
/// <returns></returns>
public bool CloseReader()
{
if (this.m_dr != null && !this.m_dr.IsClosed)
{
m_dr.Close();
}
return false;
}
/// <summary>
/// Closes the cursor, enabling the statement to be executed again.
/// </summary>
/// <returns>Returns TRUE on success or FALSE on failure</returns>
public bool closeCursor()
{
if (this.m_dr != null)
{
((IDisposable)this.m_dr).Dispose();
this.m_dr = null;
return true;
}
return false;
}
/// <summary>
/// Returns the number of columns in the result set
/// </summary>
/// <returns>Returns the number of columns in the result set represented by the PDOStatement object, even if the result set is empty. If there is no result set, PDOStatement::columnCount() returns 0</returns>
public int columnCount()
{
if (CheckDataReader())
{
return this.m_dr.FieldCount;
}
else
{
return 0;
}
}
/// <summary>
/// Dump an SQL prepared command.
/// </summary>
public void debugDumpParams()
{
throw new NotImplementedException();
}
/// <summary>
/// Fetch the SQLSTATE associated with the last operation on the statement handle
/// </summary>
/// <returns>Identical to PDO::errorCode(), except that PDOStatement::errorCode() only retrieves error codes for operations performed with PDOStatement objects</returns>
public string errorCode()
{
throw new NotImplementedException();
}
/// <summary>
/// Fetch extended error information associated with the last operation on the statement handle.
/// </summary>
/// <returns>PDOStatement::errorInfo() returns an array of error information about the last operation performed by this statement handle.</returns>
public PhpArray errorInfo()
{
throw new NotImplementedException();
}
/// <summary>
/// Executes a prepared statement
/// </summary>
/// <param name="input_parameters">An array of values with as many elements as there are bound parameters in the SQL statement being executed. All values are treated as PDO::PARAM_STR.</param>
/// <returns>Returns TRUE on success or FALSE on failure</returns>
public bool execute(PhpArray input_parameters = null)
{
// Sets PDO executed flag
m_pdo.HasExecutedQuery = true;
// Assign the bound variables from bindParam() function if any present
if (HasParamsBound)
{
foreach (var pair in m_boundParams)
{
IDbDataParameter param = null;
if (m_namedAttr)
{
// Mixed parameters not allowed
if (m_positionalAttr)
{
m_pdo.HandleError(new PDOException("Mixed parameters mode not allowed. Use either only positional, or only named parameters."));
return false;
}
param = m_cmd.Parameters[pair.Key];
}
else if (m_positionalAttr)
{
if (int.TryParse(pair.Key, out var index))
{
param = m_cmd.Parameters[index];
}
else
{
m_pdo.HandleError(new PDOException("The string for positional parameter index must be an integer."));
return false;
}
}
else
{
m_pdo.HandleError(new PDOException("No parameter mode set yet for this Statement. Possibly no parameters required?"));
return false;
}
if (pair.Value.Value.IsNull)
{
param.Value = DBNull.Value;
}
else
{
switch (param.DbType)
{
case DbType.Int32:
if (pair.Value.Value.IsLong(out var l))
{
param.Value = (int)l;
}
else
{
m_pdo.HandleError(new PDOException("Parameter type does not match the declared type."));
return false;
}
break;
case DbType.Int64:
if (pair.Value.Value.IsLong(out l))
{
param.Value = l;
}
else
{
m_pdo.HandleError(new PDOException("Parameter type does not match the declared type."));
return false;
}
break;
case DbType.String:
if (pair.Value.Value.IsString(out var str))
{
param.Value = str;
}
else
{
m_pdo.HandleError(new PDOException("Parameter type does not match the declared type."));
return false;
}
break;
case DbType.Boolean:
if (pair.Value.Value.IsBoolean(out var b))
{
param.Value = b;
}
else
{
m_pdo.HandleError(new PDOException("Parameter type does not match the declared type."));
return false;
}
break;
case DbType.Binary:
var bytes = pair.Value.Value.ToBytesOrNull(_ctx);
if (bytes != null || pair.Value.Value.IsNull)
{
param.Value = bytes;
}
else
{
m_pdo.HandleError(new PDOException("Parameter type does not match the declared type."));
return false;
}
break;
default:
throw new NotImplementedException();
}
}
}
}
// assign the parameters passed as an argument
if (input_parameters != null)
{
foreach (var pair in input_parameters)
{
IDbDataParameter param = null;
if (m_namedAttr)
{
// Mixed parameters not allowed
if (m_positionalAttr)
{
m_pdo.HandleError(new PDOException("Mixed parameters mode not allowed. Use either only positional, or only named parameters."));
return false;
}
string key = pair.Key.String;
if (key.Length > 0 && key[0] == ':')
{
key = key.Substring(1);
}
param = m_cmd.Parameters[key];
}
else if (m_positionalAttr)
{
if (pair.Key.IsInteger)
{
param = m_cmd.Parameters[pair.Key.Integer];
}
else
{
m_pdo.HandleError(new PDOException("The string for positional parameter index must be an integer."));
return false;
}
}
else
{
m_pdo.HandleError(new PDOException("No parameter mode set yet for this Statement. Possibly no parameters required?"));
return false;
}
// Assign the value as a string
param.Value = pair.Value.ToString();
}
}
// Close the previously used reader, so that the same connection can open a new one
if (m_dr != null)
{
if (!m_dr.IsClosed)
{
m_dr.Close();
}
m_dr = null;
}
// Actually execute
try
{
m_dr = m_cmd.ExecuteReader();
}
catch (Exception e)
{
m_pdo.HandleError(new PDOException("Query could not be executed; \n" + e.Message));
return false;
}
return true;
}
/// <summary>
/// Fetches the specified fetch style.
/// </summary>
/// <param name="fetch_style">Controls how the next row will be returned to the caller. This value must be one of the PDO::FETCH_* constants.</param>
/// <param name="cursor_orientation">This value determines which row will be returned to the caller.</param>
/// <param name="cursor_offet">Relative or absolute position move for the cursor.</param>
/// <returns>The return value of this function on success depends on the fetch type. In all cases, FALSE is returned on failure.</returns>
public PhpValue fetch(PDO.PDO_FETCH fetch_style = PDO_FETCH.Default/*0*/, PDO_FETCH_ORI cursor_orientation = PDO_FETCH_ORI.FETCH_ORI_NEXT/*0*/, int cursor_offet = 0)
{
this.m_pdo.ClearError();
if (storedQueryResult != null)
{
return FetchFromStored();
}
else
{
if (cursor_orientation != PDO_FETCH_ORI.FETCH_ORI_NEXT) // 0
{
throw new NotSupportedException(nameof(cursor_orientation));
}
try
{
// read next row
if (!this.m_dr.Read())
{
return PhpValue.False;
}
if (m_dr_names == null)
{
// Get the column schema, if possible,
// for the associative fetch
InitializeColumnNames();
}
var style = fetch_style != PDO_FETCH.Default ? fetch_style : m_fetchStyle;
var flags = style & PDO_FETCH.Flags;
switch (style & ~PDO_FETCH.Flags)
{
case PDO_FETCH.FETCH_ASSOC:
return this.ReadArray(true, false);
case PDO_FETCH.FETCH_NUM:
return this.ReadArray(false, true);
case PDO_FETCH.Default:
case PDO_FETCH.FETCH_BOTH:
return this.ReadArray(true, true);
case PDO_FETCH.FETCH_OBJ:
return this.ReadObj();
case PDO_FETCH.FETCH_COLUMN:
if (FetchColNo.HasValue)
{
return this.ReadColumn(FetchColNo.Value);
}
else
{
m_pdo.HandleError(new PDOException("The column number for FETCH_COLUMN mode is not set."));
return PhpValue.False;
}
//case PDO.PDO_FETCH.FETCH_CLASS:
// if (FetchClassName != null)
// {
// var obj = FetchClassName.Creator(_ctx, FetchClassCtorArgs ?? Array.Empty<PhpValue>());
// // TODO: set properties
// return PhpValue.FromClass(obj);
// }
// else
// {
// m_pdo.HandleError(new PDOException("The className for FETCH_CLASS mode is not set."));
// return PhpValue.False;
// }
case PDO_FETCH.FETCH_NAMED:
return this.ReadNamed();
//case PDO_FETCH.FETCH_LAZY:
// return new PDORow( ... ) reads columns lazily
//case PDO_FETCH.FETCH_INTO:
//case PDO_FETCH.FETCH_FUNC:
//case PDO_FETCH.FETCH_KEY_PAIR:
default:
throw new NotImplementedException($"fetch {style}");
}
}
catch (System.Exception ex)
{
this.m_pdo.HandleError(ex);
return PhpValue.False;
}
}
}
private PhpValue ReadObj()
{
return PhpValue.FromClass(this.ReadArray(true, false).ToObject());
}
private PhpValue ReadColumn(int column)
{
return this.m_dr.IsDBNull(column) ? PhpValue.Null : PhpValue.FromClr(this.m_dr.GetValue(column));
}
private PhpArray ReadArray(bool assoc, bool num, int from = 0)
{
var arr = new PhpArray(m_dr.FieldCount);
for (int i = from; i < this.m_dr.FieldCount; i++)
{
var value = ReadColumn(i);
if (assoc) arr.Add(this.m_dr_names[i], value);
if (num) arr.Add(i, value);
}
return arr;
}
private PhpArray ReadNamed(int from = 0)
{
var arr = new PhpArray(m_dr.FieldCount);
for (int i = from; i < this.m_dr.FieldCount; i++)
{
var key = new IntStringKey(this.m_dr_names[i]);
var value = ReadColumn(i);
ref var bucket = ref arr.GetItemRef(key);
if (bucket.IsSet)
{
var nested = bucket.AsArray();
if (nested != null)
{
nested.Add(value);
}
else
{
bucket = new PhpArray(2) { bucket, value };
}
}
else
{
bucket = value;
}
}
return arr;
}
/// <summary>
/// Controls the contents of the returned array as documented in PDOStatement::fetch()
/// </summary>
/// <param name="fetch_style">The fetch style.</param>
/// <param name="fetch_argument">This argument has a different meaning depending on the value of the fetch_style parameter.</param>
/// <param name="ctor_args">Arguments of custom class constructor when the fetch_style parameter is PDO::FETCH_CLASS.</param>
/// <returns>An array containing all of the remaining rows in the result set. <c>FALSE</c> on failure.</returns>
[return: CastToFalse]
public PhpArray fetchAll(PDO.PDO_FETCH fetch_style = default, PhpValue fetch_argument = default, PhpArray ctor_args = null)
{
// check parameters
if (fetch_style == PDO.PDO_FETCH.FETCH_COLUMN)
{
if (!fetch_argument.IsDefault && fetch_argument.IsLong(out var l))
{
FetchColNo = (int)l;
}
else
{
m_pdo.HandleError(new PDOException("The fetch_argument must be an integer for FETCH_COLUMN."));
return null;
}
}
if (!CheckDataReader())
{
// nothing to read from,
return null;
}
if (m_dr_names == null)
{
// Get the column schema, if possible,
// for the associative fetch
InitializeColumnNames();
}
var style = fetch_style != PDO_FETCH.Default ? fetch_style : m_fetchStyle;
var flags = style & PDO_FETCH.Flags;
var result = new PhpArray();
switch (style)
{
case PDO_FETCH.FETCH_KEY_PAIR:
Debug.Assert(m_dr.FieldCount == 2);
while (m_dr.Read())
{
// 1st col => 2nd col
result.Add(ReadColumn(0).ToIntStringKey(), ReadColumn(1));
}
break;
case PDO_FETCH.FETCH_UNIQUE:
Debug.Assert(m_dr.FieldCount >= 1);
while (m_dr.Read())
{
// 1st col => [ 2nd col, 3rd col, ... ]
result.Add(ReadColumn(0).ToIntStringKey(), ReadArray(true, false, from: 1));
}
break;
default:
for (; ; )
{
var value = fetch(style);
if (value.IsFalse)
break;
result.Add(value);
}
break;
}
return result;
}
/// <summary>
/// Returns a single column from the next row of a result set.
/// </summary>
/// <param name="column_number">0-indexed number of the column you wish to retrieve from the row. If no value is supplied, PDOStatement::fetchColumn() fetches the first column</param>
/// <returns>Single column from the next row of a result set or FALSE if there are no more rows</returns>
public PhpValue fetchColumn(int column_number = 0)
{
if (!CheckDataReader())
{
return PhpValue.False;
}
// read next row
if (!this.m_dr.Read())
{
return PhpValue.False;
}
return this.ReadArray(false, true)[column_number].GetValue();
}
/// <summary>
/// Fetches the next row and returns it as an object.
/// </summary>
/// <param name="class_name">Name of the created class.</param>
/// <param name="ctor_args">Elements of this array are passed to the constructor.</param>
/// <returns>Returns an instance of the required class with property names that correspond to the column names or FALSE on failure</returns>
[return: CastToFalse]
public object fetchObject(string class_name = nameof(stdClass), PhpArray ctor_args = null)
{
if (!CheckDataReader())
{
return null;
}
// read next row
if (!this.m_dr.Read())
{
return PhpValue.False;
}
if (string.IsNullOrEmpty(class_name) || class_name == nameof(stdClass))
{
return this.ReadObj();
}
else
{
var args = ctor_args != null ? ctor_args.GetValues() : Array.Empty<PhpValue>();
var obj = _ctx.Create(class_name, args);
// TODO: set properties
throw new NotImplementedException();
//return obj;
}
}
/// <summary>
/// Retrieve a statement attribute
/// </summary>
/// <param name="attribute"></param>
/// <returns>Returns the attribute value</returns>
public PhpValue getAttribute(int attribute)
{
throw new NotImplementedException();
}
/// <summary>
/// Returns metadata for a column in a result set.
/// </summary>
/// <param name="column">The 0-indexed column in the result set.</param>
/// <returns>Returns an associative array containing the values representing the metadata for a single column</returns>
[return: CastToFalse]
public PhpArray getColumnMeta(int column)
{
if (!CheckDataReader())
{
return null;
}
if (column < 0 || column >= m_dr.FieldCount)
{
// TODO: invalid arg warning
return null;
}
// If the column names are not initialized, then initialize them
if (m_dr_names == null)
{
InitializeColumnNames();
}
PhpArray meta = new PhpArray();
meta.Add("native_type", m_dr.GetFieldType(column)?.FullName);
meta.Add("driver:decl_type", m_dr.GetDataTypeName(column));
//meta.Add("flags", PhpValue.Null);
meta.Add("name", m_dr_names[column]);
//meta.Add("table", PhpValue.Null);
//meta.Add("len", PhpValue.Null);
//meta.Add("prevision", PhpValue.Null);
//meta.Add("pdo_type", (int)PDO.PARAM.PARAM_NULL);
return meta;
}
/// <summary>
/// Advances to the next rowset in a multi-rowset statement handle.
/// </summary>
/// <returns>Returns TRUE on success or FALSE on failure</returns>
public bool nextRowset()
{
if (CheckDataReader() && this.m_dr.NextResult())
{
InitializeColumnNames();
return true;
}
else
{
return false;
}
}
/// <summary>
/// Returns the number of rows affected by the last SQL statement
/// </summary>
/// <returns></returns>
public int rowCount()
{
if (m_cmd == null)
{
m_pdo.HandleError(new PDOException("Command cannot be null."));
return -1;
}
if (m_pdo == null)
{
m_pdo.HandleError(new PDOException("The associated PDO object cannot be null."));
return -1;
}
if (m_pdo.Driver.Name == "sqlite")
{
// This method returns "0" (zero) with the SQLite driver at all times
return 0;
}
var statement = m_pdo.query("SELECT ROW_COUNT()");
var rowCount = statement.fetchColumn(0);
if (rowCount.IsInteger())
{
return (int)rowCount;
}
else
{
m_pdo.HandleError(new PDOException("The rowCount returned by the database is not a integer."));
return -1;
}
}
/// <summary>
/// Set a statement attribute.
/// </summary>
/// <param name="attribute">The attribute.</param>
/// <param name="value">The value.</param>
/// <returns>Returns TRUE on success or FALSE on failure</returns>
public bool setAttribute(int attribute, PhpValue value)
{
throw new NotImplementedException();
}
/// <summary>
/// Set the default fetch mode for this statement
///
/// </summary>
/// <param name="mode">The fetch mode.</param>
/// <param name="args">
/// args[0] For FETCH_COLUMN : column number. For FETCH_CLASS : the class name. For FETCH_INTO, the object.
/// args[1] For FETCH_CLASS : the constructor arguments.
/// </param>
/// <returns>Returns TRUE on success or FALSE on failure</returns>
public bool setFetchMode(PDO_FETCH mode, params PhpValue[] args) => setFetchMode(mode, args.AsSpan());
internal bool setFetchMode(PDO_FETCH mode, ReadOnlySpan<PhpValue> args)
{
switch (mode & ~PDO_FETCH.Flags)
{
case PDO_FETCH.Default:
case PDO_FETCH.FETCH_LAZY:
case PDO_FETCH.FETCH_ASSOC:
case PDO_FETCH.FETCH_NUM:
case PDO_FETCH.FETCH_BOTH:
case PDO_FETCH.FETCH_OBJ:
case PDO_FETCH.FETCH_BOUND:
case PDO_FETCH.FETCH_NAMED:
case PDO_FETCH.FETCH_KEY_PAIR:
if (args.Length != 0)
{
RaiseError("fetch mode doesn't allow any extra arguments");
return false;
}
else
{
m_fetchStyle = mode;
return true;
}
case PDO_FETCH.FETCH_COLUMN:
if (args.Length != 1)
{
RaiseError("fetch mode requires the colno argument");
return false;
}
else if (args[0].IsLong(out var l))
{
m_fetchStyle = mode;
FetchColNo = (int)l;
return true;
}
else
{
RaiseError("colno must be an integer");
return false;
}
case PDO_FETCH.FETCH_CLASS:
FetchClassCtorArgs = default;
if ((mode & PDO_FETCH.FETCH_CLASSTYPE) != 0)
{
// will be getting its class name from 1st column
if (args.Length != 0)
{
RaiseError("fetch mode doesn't allow any extra arguments");
return false;
}
else
{
m_fetchStyle = mode;
FetchClassName = null;
return true;
}
}
else
{
if (args.Length == 0)
{
RaiseError("fetch mode requires the classname argument");
return false;
}
else if (args.Length > 2)
{
RaiseError("too many arguments");
return false;
}
else if (args[0].IsString(out var name))
{
FetchClassName = _ctx.GetDeclaredTypeOrThrow(name, autoload: true);
if (FetchClassName != null)
{
if (args.Length > 1)
{
var ctorargs = args[1].AsArray();
if (ctorargs == null && !args[1].IsNull)
{
RaiseError("ctor_args must be either NULL or an array");
return false;
}
else if (ctorargs != null && ctorargs.Count != 0)
{
FetchClassCtorArgs = ctorargs.GetValues(); // TODO: deep copy
}
}
m_fetchStyle = mode;
return true;
}
else
{
return false;
}
}
else
{
RaiseError("classname must be a string");
return false;
}
}
case PDO_FETCH.FETCH_INTO:
if (args.Length != 1)
{
RaiseError("fetch mode requires the object parameter");
return false;
}
else
{
FetchClassInto = args[0].AsObject();
if (FetchClassInto == null)
{
RaiseError("object must be an object");
return false;
}
m_fetchStyle = mode;
return true;
}
default:
RaiseError("Invalid fetch mode specified");
return false;
}
}
// Initializes the column names by looping through the data reads columns or using the schema if it is available
private void InitializeColumnNames()
{
m_dr_names = new string[m_dr.FieldCount];
if (m_dr.CanGetColumnSchema())
{
var columnSchema = m_dr.GetColumnSchema();
for (var i = 0; i < m_dr_names.Length; i++)
{
m_dr_names[i] = columnSchema[i].ColumnName;
}
}
else
{
for (var i = 0; i < m_dr_names.Length; i++)
{
m_dr_names[i] = m_dr.GetName(i);
}
}
}
}
}
| 37.377613 | 278 | 0.451895 | [
"Apache-2.0"
] | JimBobSquarePants/peachpie | src/PDO/Peachpie.Library.PDO/PDOStatement.cs | 55,431 | C# |
using Elsa.Models;
using System.Collections.Generic;
namespace Volo.Abp.WorkFlowManagement
{
public class WorkflowDefinitionDto
{
public int Version { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Variables Variables { get; set; }
public bool IsSingleton { get; set; }
public bool IsDisabled { get; set; }
public bool IsPublished { get; set; } = false;
public bool IsLatest { get; set; }
public List<ActivityDto> Activities { get; set; }
public List<ConnectionDto> Connections { get; set; }
}
} | 31.75 | 60 | 0.628346 | [
"Apache-2.0"
] | AbpApp/volo.abp.elsa | modules/workflow-mamagement/Volo.Abp.WorkFlowManagement.Application.Contracts/Volo/Abp/WorkFlowManagement/WorkflowDefinitionDto.cs | 637 | C# |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
* This software is subject to the Microsoft Public License (Ms-PL).
* A copy of the license can be found in the license.htm file included
* in this distribution.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
namespace System.Web.Mvc {
[Serializable]
public class ModelState {
private ModelErrorCollection _errors = new ModelErrorCollection();
public ValueProviderResult Value {
get;
set;
}
public ModelErrorCollection Errors {
get {
return _errors;
}
}
}
}
| 26.28125 | 80 | 0.497027 | [
"MIT"
] | zlxy/Genesis-3D | Engine/extlibs/IosLibs/mono-2.6.7/mcs/class/System.Web.Mvc/System.Web.Mvc/ModelState.cs | 843 | C# |
using System.Threading;
using System.Threading.Tasks;
using ZeptoServer.Telnet.Responses;
namespace ZeptoServer.Ftp.Commands
{
/// <summary>
/// FTP command to print working directory.
/// </summary>
/// <remarks>
/// https://tools.ietf.org/html/rfc959
/// </remarks>
internal sealed class PrintWorkingDirectoryCommand : FtpPathCommandBase
{
/// <summary>
/// Creates a response that contains current working directory path.
/// </summary>
/// <param name="arguments">Command arguments</param>
/// <param name="session">FTP session context</param>
/// <param name="cancellation">Cancellation token</param>
/// <returns>FTP server response to send to the client.</returns>
protected override Task<IResponse> Handle(string arguments, FtpSessionState session, CancellationToken cancellation)
{
return FtpResponsesAsync.Path(session.CurrentDirectory.ToString(), session.PathEncoding);
}
}
}
| 36.321429 | 124 | 0.6647 | [
"MIT"
] | junk-machine/ZeptoServer | ZeptoServer.Ftp/Commands/PrintWorkingDirectoryCommand.cs | 1,019 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;
namespace ScriptTool
{
class Program
{
// Options
static CommandOptions options;
// ROMs
static byte[] ebRom;
static byte[] m12Rom;
// Decompiler setup
static Decompiler m12Decompiler;
static Decompiler ebDecompiler;
static IDictionary<byte, string> m12CharLookup;
static IDictionary<byte, string> ebCharLookup;
// Compiler setup
static Compiler m12Compiler;
static StreamWriter IncludeFile;
static void Main(string[] args)
{
options = ParseCommandLine(args);
if (options == null)
{
Usage();
return;
}
m12CharLookup = JsonConvert.DeserializeObject<Dictionary<byte, string>>(File.ReadAllText("m12-char-lookup.json"));
ebCharLookup = JsonConvert.DeserializeObject<Dictionary<byte, string>>(File.ReadAllText("eb-char-lookup.json"));
if (options.Command == CommandType.Decompile)
{
// Set up decompilers
m12Decompiler = new Decompiler(M12ControlCode.Codes, m12CharLookup, (rom, address) => rom[address + 1] == 0xFF);
ebDecompiler = new Decompiler(EbControlCode.Codes, ebCharLookup, (rom, address) => rom[address] < 0x20);
// Load ROMs
ebRom = File.ReadAllBytes(options.EbRom);
m12Rom = File.ReadAllBytes(options.M12Rom);
// Decompile misc string tables
if (options.DoMiscText)
{
//DecompileEbMisc();
DecompileM12Misc();
}
// Decompile main string tables
if (options.DoMainText)
{
DecompileEb();
DecompileM12();
}
}
else if (options.Command == CommandType.Compile)
{
// Set up compilers
m12Compiler = new Compiler(M12ControlCode.Codes, (rom, address) => rom[address + 1] == 0xFF);
using (IncludeFile = File.CreateText(Path.Combine(options.WorkingDirectory, "m12-includes.asm")))
{
IncludeFile.WriteLine(".gba");
IncludeFile.WriteLine(".open \"../m12.gba\",0x8000000");
// Compile main string tables
if (options.DoMainText)
{
CompileM12();
}
// Compile misc string tables
if (options.DoMiscText)
{
CompileM12Misc();
}
IncludeFile.WriteLine(".close");
}
}
}
static void Usage()
{
Console.WriteLine("Usage:");
Console.WriteLine(" ScriptTool.exe [-decompile or -compile] [-misc] [-main] workingdirectory [ebrom m12rom]");;
}
static CommandOptions ParseCommandLine(string[] args)
{
var argList = new List<string>(args);
// Check for decompile switch
CommandType command;
if (argList.Contains("-decompile") && !argList.Contains("-compile"))
{
command = CommandType.Decompile;
argList.Remove("-decompile");
}
else if (argList.Contains("-compile") && !argList.Contains("-decompile"))
{
command = CommandType.Compile;
argList.Remove("-compile");
}
else
{
return null;
}
// Check for main and misc flags
bool doMain = false;
bool doMisc = false;
if (argList.Contains("-main"))
{
doMain = true;
argList.Remove("-main");
}
if (argList.Contains("-misc"))
{
doMisc = true;
argList.Remove("-misc");
}
// Check for working directory
if (argList.Count < 1)
return null;
string working = argList[0];
if (!Directory.Exists(working))
return null;
// Check for ROM paths
string ebRom = null;
string m12Rom = null;
if (command == CommandType.Decompile && argList.Count == 3)
{
ebRom = argList[1];
m12Rom = argList[2];
if (!File.Exists(ebRom) || !File.Exists(m12Rom))
return null;
}
return new CommandOptions
{
WorkingDirectory = working,
EbRom = ebRom,
M12Rom = m12Rom,
Command = command,
DoMainText = doMain,
DoMiscText = doMisc
};
}
static void DecompileEb()
{
// Pull all string refs from the ROM
var allRefs = new List<Tuple<string, MainStringRef[]>>();
var tptTuple = EbTextTables.ReadTptRefs(ebRom);
allRefs.Add(Tuple.Create("eb-tpt-primary", tptTuple.Item1));
allRefs.Add(Tuple.Create("eb-tpt-secondary", tptTuple.Item2));
allRefs.Add(Tuple.Create("eb-battle-actions", EbTextTables.ReadBattleActionRefs(ebRom)));
allRefs.Add(Tuple.Create("eb-prayers", EbTextTables.ReadPrayerRefs(ebRom)));
allRefs.Add(Tuple.Create("eb-item-help", EbTextTables.ReadItemHelpRefs(ebRom)));
allRefs.Add(Tuple.Create("eb-psi-help", EbTextTables.ReadPsiHelpRefs(ebRom)));
allRefs.Add(Tuple.Create("eb-phone", EbTextTables.ReadPhoneRefs(ebRom)));
allRefs.Add(Tuple.Create("eb-enemy-encounters", EbTextTables.ReadEnemyEncounters(ebRom)));
allRefs.Add(Tuple.Create("eb-enemy-deaths", EbTextTables.ReadEnemyDeaths(ebRom)));
// Decompile
var allPointers = allRefs.SelectMany(rl => rl.Item2).Select(r => r.OldPointer);
ebDecompiler.LabelMap.AddRange(allPointers);
IList<int[]> textRanges = new List<int[]>();
textRanges.Add(new int[] { 0x50000, 0x5FFEC });
textRanges.Add(new int[] { 0x60000, 0x6FFE3 });
textRanges.Add(new int[] { 0x70000, 0x7FF40 });
textRanges.Add(new int[] { 0x80000, 0x8BC2D });
textRanges.Add(new int[] { 0x8D9ED, 0x8FFF3 });
textRanges.Add(new int[] { 0x90000, 0x9FF2F });
textRanges.Add(new int[] { 0x2F4E20, 0x2FA460 });
var strings = new List<string>();
foreach (var range in textRanges)
{
ebDecompiler.ScanRange(ebRom, range[0], range[1]);
}
// Bit of a hack for now -- to avoid messing up label order, add new refs *after* scanning the ROM
var doorStuff = EbTextTables.ReadDoors(ebRom);
allRefs.Add(Tuple.Create("eb-doors", doorStuff[0]));
allRefs.Add(Tuple.Create("eb-doorgaps", doorStuff[1]));
allRefs.Add(Tuple.Create("eb-dungeonman", doorStuff[2]));
ebDecompiler.LabelMap.AddRange(allRefs.Skip(9).SelectMany(r1 => r1.Item2).Select(r => r.OldPointer));
foreach (var range in textRanges)
{
strings.Add(ebDecompiler.DecompileRange(ebRom, range[0], range[1], true));
}
// Update labels for all refs and write to JSON
foreach (var refList in allRefs)
{
foreach (var stringRef in refList.Item2)
stringRef.Label = ebDecompiler.LabelMap.Labels[stringRef.OldPointer];
File.WriteAllText(Path.Combine(options.WorkingDirectory, refList.Item1 + ".json"),
JsonConvert.SerializeObject(refList.Item2, Formatting.Indented));
}
// Write the strings
File.WriteAllText(Path.Combine(options.WorkingDirectory, "eb-strings.txt"), String.Join(Environment.NewLine, strings));
}
static void DecompileM12()
{
// Pull all string refs from the ROM
var allRefs = new List<Tuple<string, MainStringRef[]>>();
var tptTuple = M12TextTables.ReadTptRefs(m12Rom);
allRefs.Add(Tuple.Create("m12-tpt-primary", tptTuple.Item1));
allRefs.Add(Tuple.Create("m12-tpt-secondary", tptTuple.Item2));
allRefs.Add(Tuple.Create("m12-psi-help", M12TextTables.ReadPsiHelpRefs(m12Rom)));
allRefs.Add(Tuple.Create("m12-battle-actions", M12TextTables.ReadBattleActionRefs(m12Rom)));
allRefs.Add(Tuple.Create("m12-item-help", M12TextTables.ReadItemHelpRefs(m12Rom)));
allRefs.Add(Tuple.Create("m12-movements", M12TextTables.ReadMovementRefs(m12Rom)));
allRefs.Add(Tuple.Create("m12-objects", M12TextTables.ReadObjectRefs(m12Rom)));
allRefs.Add(Tuple.Create("m12-phone-list", M12TextTables.ReadPhoneRefs(m12Rom)));
allRefs.Add(Tuple.Create("m12-unknown", M12TextTables.ReadUnknownRefs(m12Rom)));
allRefs.Add(Tuple.Create("m12-enemy-encounters", M12TextTables.ReadEnemyEncounters(m12Rom)));
allRefs.Add(Tuple.Create("m12-enemy-deaths", M12TextTables.ReadEnemyDeaths(m12Rom)));
allRefs.Add(Tuple.Create("m12-prayers", M12TextTables.ReadPrayerRefs(m12Rom)));
allRefs.Add(Tuple.Create("m12-asmrefs", M12TextTables.ReadAsmRefs(m12Rom)));
// Decompile
var allPointers = allRefs.SelectMany(rl => rl.Item2).Select(r => r.OldPointer);
m12Decompiler.LabelMap.AddRange(allPointers);
var strings = new List<string>();
m12Decompiler.ScanRange(m12Rom, 0x3697F, 0x8C4B0);
strings.Add(m12Decompiler.DecompileRange(m12Rom, 0x3697F, 0x8C4B0, true));
// Update labels for all refs
foreach (var refList in allRefs)
{
foreach (var stringRef in refList.Item2)
stringRef.Label = m12Decompiler.LabelMap.Labels[stringRef.OldPointer];
}
// Write to JSON
foreach (var refList in allRefs)
{
File.WriteAllText(Path.Combine(options.WorkingDirectory, refList.Item1 + ".json"),
JsonConvert.SerializeObject(refList.Item2, Formatting.Indented));
}
// Write the strings
File.WriteAllText(Path.Combine(options.WorkingDirectory, "m12-strings.txt"), String.Join(Environment.NewLine, strings));
}
static void DecompileM12Misc()
{
// Item names
var itemNames = M12TextTables.ReadItemNames(m12Rom);
DecompileM12MiscStringCollection("m12-itemnames", itemNames);
// Menu choices
var menuChoices = M12TextTables.ReadMenuChoices(m12Rom);
DecompileM12MiscStringCollection("m12-menuchoices", menuChoices);
// Misc text
var miscText = M12TextTables.ReadMiscText(m12Rom);
DecompileM12MiscStringCollection("m12-misctext", miscText);
// Dad
var dadText = M12TextTables.ReadDadText(m12Rom);
DecompileM12MiscStringCollection("m12-dadtext", dadText);
// PSI text
var psiText = M12TextTables.ReadPsiText(m12Rom);
DecompileM12MiscStringCollection("m12-psitext", psiText);
// Enemy names
var enemyNames = M12TextTables.ReadEnemyNames(m12Rom);
DecompileM12MiscStringCollection("m12-enemynames", enemyNames);
// PSI names
var psiNames = M12TextTables.ReadPsiNames(m12Rom);
DecompileFixedStringCollection(m12Decompiler, m12Rom, "m12-psinames", psiNames);
// PSI targets
var miscText2 = M12TextTables.ReadPsiTargets(m12Rom);
DecompileFixedStringCollection(m12Decompiler, m12Rom, "m12-psitargets", miscText2);
// Other
DecompileHardcodedStringCollection(m12Decompiler, m12Rom, "m12-other",
0xB1B492,
0xB1B497,
0xB1B49C,
0xB1B4A1,
0xB1B4A6,
0xB1BA00,
0xB1BA05,
0xB1BA0A,
0xB1BA0F,
0xB1BA14,
0xB1BA1A,
0xB1BA20,
0xB1BA26,
0xB1BA2C,
0xB1BA36,
0xB1BA40,
0xB1BA4A,
0xB1BA54,
0xB1BA61,
0xB1BA6E,
0xB1BA7B);
// Teleport destinations
var teleportNames = M12TextTables.ReadTeleportNames(m12Rom);
DecompileFixedStringCollection(m12Decompiler, m12Rom, "m12-teleport-names", teleportNames);
}
static void DecompileM12MiscStringCollection(string name, MiscStringCollection miscStringCollection)
{
// Decompile the strings
foreach (var miscStringRef in miscStringCollection.StringRefs)
{
string decompiledString;
if (miscStringRef.BasicMode)
{
decompiledString = m12Decompiler.ReadFFString(m12Rom, miscStringRef.OldPointer);
}
else
{
decompiledString = m12Decompiler.DecompileString(m12Rom, miscStringRef.OldPointer, false);
}
miscStringRef.Old =
miscStringRef.New = decompiledString;
}
// Write JSON
File.WriteAllText(Path.Combine(options.WorkingDirectory, name + ".json"),
JsonConvert.SerializeObject(miscStringCollection, Formatting.Indented));
}
static void DecompileFixedStringCollection(IDecompiler decompiler, byte[] rom, string name, FixedStringCollection fixedStringCollection)
{
// Decompile the strings
foreach (var fixedStringRef in fixedStringCollection.StringRefs)
{
fixedStringRef.Old =
fixedStringRef.New =
decompiler.DecompileString(rom, fixedStringRef.OldPointer, false);
}
// Write JSON
File.WriteAllText(Path.Combine(options.WorkingDirectory, name + ".json"),
JsonConvert.SerializeObject(fixedStringCollection, Formatting.Indented));
}
static void DecompileHardcodedStringCollection(IDecompiler decompiler, byte[] rom, string name,
params int[] pointers)
{
var hardcodedRefs = new List<HardcodedString>();
foreach (int pointer in pointers)
{
string str = decompiler.DecompileString(rom, pointer, false);
var references = new List<int>();
// Search for all references
for (int refAddress = 0; refAddress < 0x100000; refAddress += 4)
{
int value = rom.ReadGbaPointer(refAddress);
if (value == pointer)
{
references.Add(refAddress);
}
}
var hardcodedRef = new HardcodedString
{
Old = str,
New = "",
PointerLocations = references.ToArray(),
OldPointer = pointer
};
hardcodedRefs.Add(hardcodedRef);
}
File.WriteAllText(Path.Combine(options.WorkingDirectory, name + ".json"),
JsonConvert.SerializeObject(hardcodedRefs, Formatting.Indented));
}
static void CompileM12()
{
int baseAddress = 0xB80000;
int referenceAddress = baseAddress;
var buffer = new List<byte>();
// Get the strings
string m12Strings = File.ReadAllText(Path.Combine(options.WorkingDirectory, "m12-strings-english.txt"));
// Compile
m12Compiler.ScanString(m12Strings, ref referenceAddress, ebCharLookup, false);
referenceAddress = baseAddress;
m12Compiler.CompileString(m12Strings, buffer, ref referenceAddress, ebCharLookup);
File.WriteAllBytes(Path.Combine(options.WorkingDirectory, "m12-main-strings.bin"), buffer.ToArray());
// Update labels
string[] labelFiles = {
"m12-tpt-primary",
"m12-tpt-secondary",
"m12-psi-help",
"m12-battle-actions",
"m12-item-help",
"m12-movements",
"m12-objects",
"m12-phone-list",
"m12-unknown",
"m12-asmrefs",
"m12-enemy-encounters",
"m12-enemy-deaths",
"m12-prayers"
};
using (var labelAsmFile = File.CreateText(Path.Combine(options.WorkingDirectory, "m12-main-strings.asm")))
{
labelAsmFile.WriteLine(String.Format(".org 0x{0:X} :: .incbin \"m12-main-strings.bin\"", baseAddress | 0x8000000));
labelAsmFile.WriteLine();
foreach (var file in labelFiles)
{
var mainStringRefs = JsonConvert.DeserializeObject<MainStringRef[]>(File.ReadAllText(
Path.Combine(options.WorkingDirectory, file + ".json")));
foreach (var stringRef in mainStringRefs)
{
labelAsmFile.WriteLine(String.Format(".org 0x{0:X} :: dw 0x{1:X8}",
stringRef.PointerLocation | 0x8000000, m12Compiler.AddressMap[stringRef.Label] | 0x8000000));
}
}
}
IncludeFile.WriteLine(".include \"m12-main-strings.asm\"");
// Dump labels
using (var labelFile = File.CreateText(Path.Combine(options.WorkingDirectory, "m12-labels.txt")))
{
foreach (var kv in m12Compiler.AddressMap.OrderBy(kv => kv.Key, new LabelComparer()))
{
labelFile.WriteLine(String.Format("{0,-30}: 0x{1:X8}", kv.Key, kv.Value | 0x8000000));
}
}
}
static void CompileM12Misc()
{
int referenceAddress = 0xB70000;
// Item names
CompileM12MiscStringCollection("m12-itemnames", ref referenceAddress);
// Misc text
CompileM12MiscStringCollection("m12-misctext", ref referenceAddress);
// PSI text
CompileM12MiscStringCollection("m12-psitext", ref referenceAddress);
// Enemy names
CompileM12MiscStringCollection("m12-enemynames", ref referenceAddress);
// Menu choices
CompileM12MiscStringCollection("m12-menuchoices", ref referenceAddress);
// PSI names
var newPsiPointers = CompileM12FixedStringCollection("m12-psinames", ref referenceAddress);
// Fix pointers to specific PSI strings
int psiPointer = newPsiPointers[1];
int[] updateAddresses = {
0xC21AC,
0xC2364,
0xC2420,
0xC24DC,
0xD3998
};
IncludeFile.WriteLine();
IncludeFile.WriteLine("// Fix pointers to \"PSI \"");
foreach (var address in updateAddresses)
{
IncludeFile.WriteLine(String.Format(".org 0x{0:X} :: dw 0x{1:X8}",
address | 0x8000000, psiPointer | 0x8000000));
}
// PSI targets
CompileM12FixedStringCollection("m12-psitargets", ref referenceAddress);
// Battle command strings
CompileM12BattleCommands("m12-battle-commands", ref referenceAddress);
// Other
CompileM12HardcodedStringCollection("m12-other", ref referenceAddress);
// Teleport destinations
CompileM12FixedStringCollection("m12-teleport-names", ref referenceAddress);
}
static void CompileM12MiscStringCollection(string name, ref int referenceAddress)
{
int baseAddress = referenceAddress;
var buffer = new List<byte>();
// Read the JSON
MiscStringCollection stringCollection = JsonConvert.DeserializeObject<MiscStringCollection>(
File.ReadAllText(Path.Combine(options.WorkingDirectory, name + ".json")));
// Open the offset ASM file
using (var offsetFile = File.CreateText(Path.Combine(options.WorkingDirectory, name + ".asm")))
{
// Include the binfile
offsetFile.WriteLine(String.Format(".org 0x{0:X} :: .incbin \"{1}.bin\"",
baseAddress | 0x8000000, name));
offsetFile.WriteLine();
// Compile all strings
foreach (var str in stringCollection.StringRefs.OrderBy(s => s.Index))
{
offsetFile.WriteLine(String.Format(".org 0x{0:X} :: dw 0x{1:X8}",
str.OffsetLocation | 0x8000000, referenceAddress - stringCollection.StringsLocation));
m12Compiler.CompileString(str.New, buffer, ref referenceAddress, ebCharLookup);
}
}
// Write the buffer
File.WriteAllBytes(Path.Combine(options.WorkingDirectory, name + ".bin"), buffer.ToArray());
// Add to the include file
IncludeFile.WriteLine(".include \"" + name + ".asm\"");
}
static IList<int> CompileM12FixedStringCollection(string name, ref int referenceAddress)
{
// Align to 4 bytes
referenceAddress = referenceAddress.AlignTo(4);
int baseAddress = referenceAddress;
var buffer = new List<byte>();
var newPointers = new List<int>();
// Read the JSON
FixedStringCollection stringCollection = JsonConvert.DeserializeObject<FixedStringCollection>(
File.ReadAllText(Path.Combine(options.WorkingDirectory, name + ".json")));
// Open the data ASM file
using (var offsetFile = File.CreateText(Path.Combine(options.WorkingDirectory, name + ".asm")))
{
// Include the binfile
offsetFile.WriteLine(String.Format(".org 0x{0:X} :: .incbin \"{1}.bin\"",
baseAddress | 0x8000000, name));
offsetFile.WriteLine();
// Update table pointers
foreach (int tablePointer in stringCollection.TablePointers)
{
offsetFile.WriteLine(String.Format(".org 0x{0:X} :: dw 0x{1:X8}",
tablePointer | 0x8000000, baseAddress | 0x8000000));
}
// Compile all strings
foreach (var str in stringCollection.StringRefs.OrderBy(s => s.Index))
{
newPointers.Add(referenceAddress);
m12Compiler.CompileString(str.New, buffer, ref referenceAddress, ebCharLookup, stringCollection.EntryLength);
}
}
// Write the buffer
File.WriteAllBytes(Path.Combine(options.WorkingDirectory, name + ".bin"), buffer.ToArray());
// Add to the include file
IncludeFile.WriteLine(".include \"" + name + ".asm\"");
return newPointers;
}
static int[] CompileM12HardcodedStringCollection(string name, ref int referenceAddress)
{
int baseAddress = referenceAddress;
var buffer = new List<byte>();
// Read the JSON
var hardcodedStrings = JsonConvert.DeserializeObject<HardcodedString[]>(
File.ReadAllText(Path.Combine(options.WorkingDirectory, name + ".json")));
var stringAddresses = new int[hardcodedStrings.Length];
// Open the data ASM file
using (var offsetFile = File.CreateText(Path.Combine(options.WorkingDirectory, name + ".asm")))
{
// Include the binfile
offsetFile.WriteLine(String.Format(".org 0x{0:X} :: .incbin \"{1}.bin\"",
baseAddress | 0x8000000, name));
offsetFile.WriteLine();
// Compile all strings
int i = 0;
foreach (var str in hardcodedStrings)
{
offsetFile.WriteLine($".definelabel {name.Replace('-', '_')}_str{i},0x{referenceAddress | 0x8000000:X}");
foreach (int ptr in str.PointerLocations)
{
offsetFile.WriteLine(String.Format(".org 0x{0:X} :: dw 0x{1:X8}",
ptr | 0x8000000, referenceAddress | 0x8000000));
}
stringAddresses[i++] = referenceAddress;
m12Compiler.CompileString(str.New, buffer, ref referenceAddress, ebCharLookup);
}
}
// Write the buffer
File.WriteAllBytes(Path.Combine(options.WorkingDirectory, name + ".bin"), buffer.ToArray());
// Add to the include file
IncludeFile.WriteLine(".include \"" + name + ".asm\"");
return stringAddresses;
}
static void CompileM12BattleCommands(string name, ref int referenceAddress)
{
int baseAddress = referenceAddress;
var buffer = new List<byte>();
// Read the JSON
var hardcodedStrings = JsonConvert.DeserializeObject<HardcodedString[]>(
File.ReadAllText(Path.Combine(options.WorkingDirectory, name + ".json")));
// Open the data ASM file
using (var offsetFile = File.CreateText(Path.Combine(options.WorkingDirectory, name + ".asm")))
{
// Include the binfile
offsetFile.WriteLine(String.Format(".org 0x{0:X} :: .incbin \"{1}.bin\"",
baseAddress | 0x8000000, name));
offsetFile.WriteLine();
// The first ten strings will be fixed to 16 bytes per string;
// the rest are variable-length
for (int i = 0; i < hardcodedStrings.Length; i++)
{
var str = hardcodedStrings[i];
foreach (int ptr in str.PointerLocations)
{
offsetFile.WriteLine(String.Format(".org 0x{0:X} :: dw 0x{1:X8}",
ptr | 0x8000000, referenceAddress | 0x8000000));
}
if (i < 10)
m12Compiler.CompileString(str.New, buffer, ref referenceAddress, ebCharLookup, 16);
else
m12Compiler.CompileString(str.New, buffer, ref referenceAddress, ebCharLookup);
}
}
// Write the buffer
File.WriteAllBytes(Path.Combine(options.WorkingDirectory, name + ".bin"), buffer.ToArray());
// Add to the include file
IncludeFile.WriteLine(".include \"" + name + ".asm\"");
}
}
class LabelComparer : IComparer<string>
{
public int Compare(string x, string y)
{
if (x == null)
return (y == null) ? 0 : -1;
if (y == null)
return 1;
if (x.Length == 0 || y.Length == 0)
return x.CompareTo(y);
if (x[0] == 'L' && y[0] == 'L')
{
if (int.TryParse(x.Substring(1), out int xInt) && int.TryParse(y.Substring(1), out int yInt))
{
return xInt.CompareTo(yInt);
}
}
return x.CompareTo(y);
}
}
}
| 40.218663 | 144 | 0.536032 | [
"MIT"
] | Snakeshroom/Mother2GbaTranslation | ScriptTool/ScriptTool/Program.cs | 28,879 | C# |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System;
using NUnit.Common;
using NUnit.Framework;
namespace NUnit.ConsoleRunner.Tests
{
[TestFixture]
public sealed class DefaultOptionsProviderTests
{
private const string EnvironmentVariableTeamcityProjectName = "TEAMCITY_PROJECT_NAME";
[TearDown]
public void TearDown()
{
Environment.SetEnvironmentVariable(EnvironmentVariableTeamcityProjectName, null);
}
[Test]
public void ShouldRetTeamCityAsTrueWhenHasEnvironmentVariable_TEAMCITY_PROJECT_NAME()
{
// Given
var provider = CreateInstance();
// When
Environment.SetEnvironmentVariable(EnvironmentVariableTeamcityProjectName, "Abc");
// Then
Assert.True(provider.TeamCity);
}
[Test]
public void ShouldRetTeamCityAsFalseWhenHasNotEnvironmentVariable_TEAMCITY_PROJECT_NAME()
{
// Given
var provider = CreateInstance();
// When
Environment.SetEnvironmentVariable(EnvironmentVariableTeamcityProjectName, string.Empty);
// Then
Assert.False(provider.TeamCity);
}
private static DefaultOptionsProvider CreateInstance()
{
return new DefaultOptionsProvider();
}
}
}
| 27.538462 | 101 | 0.64176 | [
"MIT"
] | 304NotModified/nunit | src/NUnitFramework/nunitlite.tests/DefaultOptionsProviderTests.cs | 1,434 | C# |
namespace TrainConnected.Services.Mapping
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using AutoMapper;
using AutoMapper.Configuration;
public static class AutoMapperConfig
{
private static bool initialized;
public static void RegisterMappings(params Assembly[] assemblies)
{
if (initialized)
{
return;
}
initialized = true;
var types = assemblies.SelectMany(a => a.GetExportedTypes()).ToList();
var config = new MapperConfigurationExpression();
config.CreateProfile(
"ReflectionProfile",
configuration =>
{
// IMapFrom<>
foreach (var map in GetFromMaps(types))
{
configuration.CreateMap(map.Source, map.Destination);
}
// IMapTo<>
foreach (var map in GetToMaps(types))
{
configuration.CreateMap(map.Source, map.Destination);
}
// IHaveCustomMappings
foreach (var map in GetCustomMappings(types))
{
map.CreateMappings(configuration);
}
});
Mapper.Initialize(config);
}
private static IEnumerable<TypesMap> GetFromMaps(IEnumerable<Type> types)
{
var fromMaps = from t in types
from i in t.GetTypeInfo().GetInterfaces()
where i.GetTypeInfo().IsGenericType &&
i.GetGenericTypeDefinition() == typeof(IMapFrom<>) &&
!t.GetTypeInfo().IsAbstract &&
!t.GetTypeInfo().IsInterface
select new TypesMap
{
Source = i.GetTypeInfo().GetGenericArguments()[0],
Destination = t,
};
return fromMaps;
}
private static IEnumerable<TypesMap> GetToMaps(IEnumerable<Type> types)
{
var toMaps = from t in types
from i in t.GetTypeInfo().GetInterfaces()
where i.GetTypeInfo().IsGenericType &&
i.GetTypeInfo().GetGenericTypeDefinition() == typeof(IMapTo<>) &&
!t.GetTypeInfo().IsAbstract &&
!t.GetTypeInfo().IsInterface
select new TypesMap
{
Source = t,
Destination = i.GetTypeInfo().GetGenericArguments()[0],
};
return toMaps;
}
private static IEnumerable<IHaveCustomMappings> GetCustomMappings(IEnumerable<Type> types)
{
var customMaps = from t in types
from i in t.GetTypeInfo().GetInterfaces()
where typeof(IHaveCustomMappings).GetTypeInfo().IsAssignableFrom(t) &&
!t.GetTypeInfo().IsAbstract &&
!t.GetTypeInfo().IsInterface
select (IHaveCustomMappings)Activator.CreateInstance(t);
return customMaps;
}
private class TypesMap
{
public Type Source { get; set; }
public Type Destination { get; set; }
}
}
}
| 35.150943 | 99 | 0.462963 | [
"MIT"
] | StefanLB/ASP.NET-Core-MVC---June-2019---Individual-Project-Assignment | Services/TrainConnected.Services.Mapping/AutoMapperConfig.cs | 3,728 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.EntityFrameworkCore.TestUtilities;
namespace Microsoft.EntityFrameworkCore.Query.Internal
{
public class AsyncFromSqlQuerySqlServerTest : AsyncFromSqlQueryTestBase<NorthwindQuerySqlServerFixture<NoopModelCustomizer>>
{
public AsyncFromSqlQuerySqlServerTest(NorthwindQuerySqlServerFixture<NoopModelCustomizer> fixture)
: base(fixture)
{
}
}
}
| 35.9375 | 128 | 0.768696 | [
"Apache-2.0"
] | 1iveowl/efcore | test/EFCore.SqlServer.FunctionalTests/Query/AsyncFromSqlQuerySqlServerTest.cs | 575 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Authorization.Outputs
{
[OutputType]
public sealed class ResourceManagementPrivateLinkEndpointConnectionsResponse
{
/// <summary>
/// The private endpoint connections.
/// </summary>
public readonly ImmutableArray<string> PrivateEndpointConnections;
[OutputConstructor]
private ResourceManagementPrivateLinkEndpointConnectionsResponse(ImmutableArray<string> privateEndpointConnections)
{
PrivateEndpointConnections = privateEndpointConnections;
}
}
}
| 31.178571 | 123 | 0.727377 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Authorization/Outputs/ResourceManagementPrivateLinkEndpointConnectionsResponse.cs | 873 | C# |
using App_ui.Common;
using App_ui.DllImport;
using App_ui.ViewModels;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace App_ui.Views.SubViews
{
/// <summary>
/// BlurView.xaml 的交互逻辑
/// </summary>
public partial class BlurView : Window
{
public BlurView()
{
InitializeComponent();
}
#region Public field
/// <summary>
/// 当前图片信息
/// </summary>
public ImageInfo CurrImgInfo;
/// <summary>
/// 保存旧的位图信息
/// </summary>
public BitmapInfo OldBmpInfo;
#endregion
/// <summary>
/// 事件:文本框文本预改变事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
Regex re = new Regex("[^0-9.\\-]+");
e.Handled = re.IsMatch(e.Text);
}
/// <summary>
/// 事件:文本框按键按下事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9)
{
e.Handled = false;
}
else if (e.Key >= Key.D0 && e.Key <= Key.D9)
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
/// <summary>
/// 事件:鼠标点击后事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Slider_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
var vm = DataContext as MainViewModel;
var value = (int)(sender as Slider).Value;
// 计时开始
vm._watch = Stopwatch.StartNew();
CVAlgorithms.CvpBlur(OldBmpInfo.data, vm.CurrBmp.Width, vm.CurrBmp.Height, OldBmpInfo.step, value, value, ref CurrImgInfo);
byte[] imagePixels = new byte[CurrImgInfo.size];
Marshal.Copy(CurrImgInfo.data, imagePixels, 0, CurrImgInfo.size);
vm.CurrBitmapImage = ImageEx.ByteToBitmapImage(imagePixels);
// 释放内存
CVAlgorithms.ReleaseMemUseFree(CurrImgInfo.data);
// 计时结束
vm._watch.Stop();
vm.StatusText = "Execution time: " + vm._watch.ElapsedMilliseconds + " ms.";
}
/// <summary>
/// 确定按钮单击事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Btn_ok_Click(object sender, RoutedEventArgs e)
{
Close();
}
/// <summary>
/// 取消按钮单击事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Btn_cancel_Click(object sender, RoutedEventArgs e)
{
var vm = DataContext as MainViewModel;
// 计时开始
vm._watch = Stopwatch.StartNew();
// 恢复最初图像状态,此处调用0内核blur函数跳过,实现过程看CvpBlur函数实现
CVAlgorithms.CvpBlur(OldBmpInfo.data, vm.CurrBmp.Width, vm.CurrBmp.Height, OldBmpInfo.step, 0, 0, ref CurrImgInfo);
byte[] imagePixels = new byte[CurrImgInfo.size];
Marshal.Copy(CurrImgInfo.data, imagePixels, 0, CurrImgInfo.size);
vm.CurrBitmapImage = ImageEx.ByteToBitmapImage(imagePixels);
// 释放内存
CVAlgorithms.ReleaseMemUseFree(CurrImgInfo.data);
// 计时结束
vm._watch.Stop();
vm.StatusText = "Execution time: " + vm._watch.ElapsedMilliseconds + " ms.";
Close();
}
}
}
| 29.237762 | 135 | 0.552739 | [
"MIT"
] | EjiHuang/CVPlatform | CVPlatform/App_ui/Views/SubViews/BlurView.xaml.cs | 4,429 | C# |
//AUTOGENERATED, DO NOTMODIFY.
//Do not edit this file directly.
#pragma warning disable 1591 // Missing XML comment for publicly visible type or member
// ReSharper disable CheckNamespace
using System;
using RethinkDb.Driver.Ast;
using RethinkDb.Driver.Model;
using RethinkDb.Driver.Proto;
using System.Collections;
using System.Collections.Generic;
namespace RethinkDb.Driver.Ast {
public partial class Polygon : ReqlExpr {
/// <summary>
/// <para>Construct a geometry object of type Polygon. The Polygon can be specified in one of two ways:</para>
/// <ul>
/// <li>Three or more two-item arrays, specifying latitude and longitude numbers of the polygon's vertices;</li>
/// <li>Three or more <a href="/api/javascript/point">Point</a> objects specifying the polygon's vertices.</li>
/// </ul>
/// </summary>
/// <example><para>Example: Define a polygon.</para>
/// <code>r.table('geo').insert({
/// id: 101,
/// rectangle: r.polygon(
/// [-122.423246,37.779388],
/// [-122.423246,37.329898],
/// [-121.886420,37.329898],
/// [-121.886420,37.779388]
/// )
/// }).run(conn, callback);
/// </code></example>
public Polygon (object arg) : this(new Arguments(arg), null) {
}
/// <summary>
/// <para>Construct a geometry object of type Polygon. The Polygon can be specified in one of two ways:</para>
/// <ul>
/// <li>Three or more two-item arrays, specifying latitude and longitude numbers of the polygon's vertices;</li>
/// <li>Three or more <a href="/api/javascript/point">Point</a> objects specifying the polygon's vertices.</li>
/// </ul>
/// </summary>
/// <example><para>Example: Define a polygon.</para>
/// <code>r.table('geo').insert({
/// id: 101,
/// rectangle: r.polygon(
/// [-122.423246,37.779388],
/// [-122.423246,37.329898],
/// [-121.886420,37.329898],
/// [-121.886420,37.779388]
/// )
/// }).run(conn, callback);
/// </code></example>
public Polygon (Arguments args) : this(args, null) {
}
/// <summary>
/// <para>Construct a geometry object of type Polygon. The Polygon can be specified in one of two ways:</para>
/// <ul>
/// <li>Three or more two-item arrays, specifying latitude and longitude numbers of the polygon's vertices;</li>
/// <li>Three or more <a href="/api/javascript/point">Point</a> objects specifying the polygon's vertices.</li>
/// </ul>
/// </summary>
/// <example><para>Example: Define a polygon.</para>
/// <code>r.table('geo').insert({
/// id: 101,
/// rectangle: r.polygon(
/// [-122.423246,37.779388],
/// [-122.423246,37.329898],
/// [-121.886420,37.329898],
/// [-121.886420,37.779388]
/// )
/// }).run(conn, callback);
/// </code></example>
public Polygon (Arguments args, OptArgs optargs)
: base(TermType.POLYGON, args, optargs) {
}
/// <summary>
/// Get a single field from an object. If called on a sequence, gets that field from every object in the sequence, skipping objects that lack it.
/// </summary>
/// <param name="bracket"></param>
public new Bracket this[string bracket] => base[bracket];
/// <summary>
/// Get the nth element of a sequence, counting from zero. If the argument is negative, count from the last element.
/// </summary>
/// <param name="bracket"></param>
/// <returns></returns>
public new Bracket this[int bracket] => base[bracket];
}
}
| 28.204545 | 154 | 0.586086 | [
"Apache-2.0"
] | ArthurGC/RethinkDb.Driver | Source/RethinkDb.Driver/Generated/Ast/Polygon.cs | 3,723 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace IPTV_Sharp
{
public class DictionaryManager
{
private string folder_path;
private List<string> _entries;
public List<string> entries
{
get
{
return _entries;
}
}
public DictionaryManager(string folder_path)
{
this.folder_path = folder_path;
_entries = new List<string>();
}
public bool LoadDictionaries()
{
bool success = false;
if (Directory.Exists(folder_path))
{
string[] files = Directory.GetFiles(folder_path);
foreach(string file in files)
{
StreamReader reader = new StreamReader(file);
string line = string.Empty;
while((line=reader.ReadLine())!=null)
{
_entries.Add(line);
}
}
}
return success;
}
}
}
| 24.098039 | 65 | 0.469487 | [
"MIT"
] | CHATBOTSITE/IPTV-Sharp | IPTV Sharp/DictionaryManager.cs | 1,231 | 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 dms-2016-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.DatabaseMigrationService.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.DatabaseMigrationService.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DescribeEndpoints operation
/// </summary>
public class DescribeEndpointsResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
DescribeEndpointsResponse response = new DescribeEndpointsResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("Endpoints", targetDepth))
{
var unmarshaller = new ListUnmarshaller<Endpoint, EndpointUnmarshaller>(EndpointUnmarshaller.Instance);
response.Endpoints = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Marker", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.Marker = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundFault"))
{
return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonDatabaseMigrationServiceException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static DescribeEndpointsResponseUnmarshaller _instance = new DescribeEndpointsResponseUnmarshaller();
internal static DescribeEndpointsResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DescribeEndpointsResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 38.008621 | 207 | 0.647539 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/DatabaseMigrationService/Generated/Model/Internal/MarshallTransformations/DescribeEndpointsResponseUnmarshaller.cs | 4,409 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ControlBanco : MonoBehaviour
{
public Text textOro;
private int oroAcomulado;
private int oro;
public Text textTotalOro;
public int totalOro;
public GameObject signo;
public float velRotacion;
public int gemas;
public Text textoGemas;
public GameObject canvas;
//Se invoca la funcion AumentarOro para que se ejecute cada 1 segundo.
// se inicia la cantidad de oro en 100.
void Start ()
{
Invoke ("AumentarOro", 1f);
totalOro = 100;
}
// Se actualizan los textos de oro y gemas y se pone a rotar el signo que hay sobre el banco.
void Update ()
{
textOro.text = "Oro: " + oroAcomulado;
signo.transform.Rotate(Vector3.up * velRotacion * Time.deltaTime);
textTotalOro.text = ""+totalOro;
textoGemas.text = "" + gemas;
}
//Esta funcion se llama cada 120 segundos y aumenta el oro segun la cantidad de personas en la ciudad.
public void AumentarOro()
{
oroAcomulado += (canvas.GetComponent<ControlPoblacion> ().cantidadPersonas / 8);
Invoke ("AumentarOro", 30);
oro = oroAcomulado;
}
//Si se llama esta funcion aumenta el oro acumulado que puede ser recogido por el jugador.
public void ReclamarOro()
{
totalOro += oro;
oroAcomulado = 0;
}
//Si se llama esta funcion se reduce el oro respectivo al pago de alguna construccion.
public void Pagar(int cantidad)
{
if (cantidad <= totalOro)
{
totalOro -= cantidad;
}
}
//Si se llama esta funcion se reducen las gemas respectivas al pago de la construccion.
public void PagarConGemas(int cantidad)
{
if (cantidad <= gemas)
{
gemas -= cantidad;
}
}
}
| 20.337209 | 103 | 0.693539 | [
"MIT"
] | JuanBarreraU/Medellin_CITY | Assets/Game/Scripts/ControlBanco.cs | 1,751 | C# |
using PropertyChanged;
using System.ComponentModel;
namespace Saper
{
public class BaseViewModel : INotifyPropertyChanged
{
/// <summary>
/// The event that is fired when any child property changes its value
/// </summary>
public event PropertyChangedEventHandler PropertyChanged = (sender, e) => { };
/// <summary>
/// Call this to fire a <see cref="PropertyChanged"/> event
/// </summary>
/// <param name="name"></param>
public void OnPropertyChanged(string name)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
| 28.173913 | 86 | 0.608025 | [
"MIT"
] | mhnowak/saperWPF | Saper/ViewModel/Base/BaseViewModel.cs | 650 | C# |
using System.Windows;
using System;
namespace ToDoApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
WindowViewModel wvm = new WindowViewModel();
this.DataContext = wvm;
}
}
} | 15.944444 | 47 | 0.682927 | [
"MIT"
] | pingio/todo | ToDoApp/MainWindow.xaml.cs | 289 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
using System.Text.Encodings.Web;
using System.Linq;
using System.Threading.Tasks;
using ExchangeSecureTexts.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
namespace ExchangeSecureTexts.Areas.Identity.Pages.Account.Manage
{
public partial class EmailModel : PageModel
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
public EmailModel(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
}
public string Username { get; set; }
public string Email { get; set; }
public bool IsEmailConfirmed { get; set; }
[TempData]
public string StatusMessage { get; set; }
[BindProperty]
public InputModel Input { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
[Display(Name = "New email")]
public string NewEmail { get; set; }
}
private async Task LoadAsync(ApplicationUser user)
{
var email = await _userManager.GetEmailAsync(user);
Email = email;
Input = new InputModel
{
NewEmail = email,
};
IsEmailConfirmed = await _userManager.IsEmailConfirmedAsync(user);
}
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
await LoadAsync(user);
return Page();
}
public async Task<IActionResult> OnPostChangeEmailAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
if (!ModelState.IsValid)
{
await LoadAsync(user);
return Page();
}
var email = await _userManager.GetEmailAsync(user);
if (Input.NewEmail != email)
{
var userId = await _userManager.GetUserIdAsync(user);
var code = await _userManager.GenerateChangeEmailTokenAsync(user, Input.NewEmail);
var callbackUrl = Url.Page(
"/Account/ConfirmEmailChange",
pageHandler: null,
values: new { userId = userId, email = Input.NewEmail, code = code },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(
Input.NewEmail,
"Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
StatusMessage = "Confirmation link to change email sent. Please check your email.";
return RedirectToPage();
}
StatusMessage = "Your email is unchanged.";
return RedirectToPage();
}
public async Task<IActionResult> OnPostSendVerificationEmailAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
if (!ModelState.IsValid)
{
await LoadAsync(user);
return Page();
}
var userId = await _userManager.GetUserIdAsync(user);
var email = await _userManager.GetEmailAsync(user);
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = userId, code = code },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(
email,
"Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
StatusMessage = "Verification email sent. Please check your email.";
return RedirectToPage();
}
}
}
| 35.452703 | 127 | 0.56032 | [
"MIT"
] | damienbod/SendingEncryptedData | ExchangeSecureTexts/Areas/Identity/Pages/Account/Manage/Email.cshtml.cs | 5,249 | C# |
using UnityEngine;
public class SFX : MonoBehaviour
{
public AudioSource audioSource;
public void Mute()
{
audioSource.mute = !audioSource.mute;
}
} | 16.818182 | 46 | 0.621622 | [
"MIT"
] | Kridtity/3D-Pong | Scripts/SFX.cs | 187 | C# |
// This file has been generated by the GUI designer. Do not modify.
namespace QS.Updater.DB.Views
{
public partial class UpdateProcessView
{
private global::Gtk.VBox dialog1_VBox;
private global::Gtk.Label label1;
private global::Gamma.GtkWidgets.yCheckButton checkCreateBackup;
private global::Gtk.HBox hbox1;
private global::Gamma.GtkWidgets.yEntry entryFileName;
private global::Gtk.Button buttonFileChooser;
private global::QS.Widgets.ProgressWidget progressbarTotal;
private global::QS.Widgets.ProgressWidget progressbarOperation;
private global::Gtk.Expander expander1;
private global::Gtk.ScrolledWindow GtkScrolledWindow;
private global::Gamma.GtkWidgets.yTextView textviewLog;
private global::Gtk.Label GtkLabel2;
private global::Gtk.HBox hbox2;
private global::Gtk.Button buttonCancel;
private global::Gamma.GtkWidgets.yButton buttonExecute;
protected virtual void Build()
{
global::Stetic.Gui.Initialize(this);
// Widget QS.Updater.DB.Views.UpdateProcessView
global::Stetic.BinContainer.Attach(this);
this.Name = "QS.Updater.DB.Views.UpdateProcessView";
// Container child QS.Updater.DB.Views.UpdateProcessView.Gtk.Container+ContainerChild
this.dialog1_VBox = new global::Gtk.VBox();
this.dialog1_VBox.Name = "dialog1_VBox";
this.dialog1_VBox.BorderWidth = ((uint)(2));
// Container child dialog1_VBox.Gtk.Box+BoxChild
this.label1 = new global::Gtk.Label();
this.label1.Name = "label1";
this.label1.LabelProp = global::Mono.Unix.Catalog.GetString("После обновления базы, предыдущие версии программы не будут работать. Во избежани" +
"и порчи данных, убедитесь что в момент обновления никто не использует базу в раб" +
"оте.");
this.label1.Wrap = true;
this.dialog1_VBox.Add(this.label1);
global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.dialog1_VBox[this.label1]));
w1.Position = 0;
w1.Expand = false;
w1.Fill = false;
// Container child dialog1_VBox.Gtk.Box+BoxChild
this.checkCreateBackup = new global::Gamma.GtkWidgets.yCheckButton();
this.checkCreateBackup.CanFocus = true;
this.checkCreateBackup.Name = "checkCreateBackup";
this.checkCreateBackup.Label = global::Mono.Unix.Catalog.GetString("Создать резервную копию перед обновлением");
this.checkCreateBackup.Active = true;
this.checkCreateBackup.DrawIndicator = true;
this.checkCreateBackup.UseUnderline = true;
this.dialog1_VBox.Add(this.checkCreateBackup);
global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.dialog1_VBox[this.checkCreateBackup]));
w2.Position = 1;
w2.Expand = false;
w2.Fill = false;
// Container child dialog1_VBox.Gtk.Box+BoxChild
this.hbox1 = new global::Gtk.HBox();
this.hbox1.Name = "hbox1";
this.hbox1.Spacing = 6;
this.hbox1.BorderWidth = ((uint)(6));
// Container child hbox1.Gtk.Box+BoxChild
this.entryFileName = new global::Gamma.GtkWidgets.yEntry();
this.entryFileName.CanFocus = true;
this.entryFileName.Name = "entryFileName";
this.entryFileName.IsEditable = false;
this.entryFileName.InvisibleChar = '●';
this.hbox1.Add(this.entryFileName);
global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.hbox1[this.entryFileName]));
w3.Position = 0;
// Container child hbox1.Gtk.Box+BoxChild
this.buttonFileChooser = new global::Gtk.Button();
this.buttonFileChooser.CanFocus = true;
this.buttonFileChooser.Name = "buttonFileChooser";
this.buttonFileChooser.UseUnderline = true;
global::Gtk.Image w4 = new global::Gtk.Image();
w4.Pixbuf = global::Stetic.IconLoader.LoadIcon(this, "gtk-directory", global::Gtk.IconSize.Menu);
this.buttonFileChooser.Image = w4;
this.hbox1.Add(this.buttonFileChooser);
global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.hbox1[this.buttonFileChooser]));
w5.Position = 1;
w5.Expand = false;
w5.Fill = false;
this.dialog1_VBox.Add(this.hbox1);
global::Gtk.Box.BoxChild w6 = ((global::Gtk.Box.BoxChild)(this.dialog1_VBox[this.hbox1]));
w6.Position = 2;
w6.Expand = false;
w6.Fill = false;
// Container child dialog1_VBox.Gtk.Box+BoxChild
this.progressbarTotal = new global::QS.Widgets.ProgressWidget();
this.progressbarTotal.Name = "progressbarTotal";
this.dialog1_VBox.Add(this.progressbarTotal);
global::Gtk.Box.BoxChild w7 = ((global::Gtk.Box.BoxChild)(this.dialog1_VBox[this.progressbarTotal]));
w7.Position = 3;
w7.Expand = false;
w7.Fill = false;
// Container child dialog1_VBox.Gtk.Box+BoxChild
this.progressbarOperation = new global::QS.Widgets.ProgressWidget();
this.progressbarOperation.Name = "progressbarOperation";
this.dialog1_VBox.Add(this.progressbarOperation);
global::Gtk.Box.BoxChild w8 = ((global::Gtk.Box.BoxChild)(this.dialog1_VBox[this.progressbarOperation]));
w8.Position = 4;
w8.Expand = false;
w8.Fill = false;
// Container child dialog1_VBox.Gtk.Box+BoxChild
this.expander1 = new global::Gtk.Expander(null);
this.expander1.CanFocus = true;
this.expander1.Name = "expander1";
// Container child expander1.Gtk.Container+ContainerChild
this.GtkScrolledWindow = new global::Gtk.ScrolledWindow();
this.GtkScrolledWindow.HeightRequest = 246;
this.GtkScrolledWindow.Name = "GtkScrolledWindow";
this.GtkScrolledWindow.ShadowType = ((global::Gtk.ShadowType)(1));
// Container child GtkScrolledWindow.Gtk.Container+ContainerChild
this.textviewLog = new global::Gamma.GtkWidgets.yTextView();
this.textviewLog.CanFocus = true;
this.textviewLog.Name = "textviewLog";
this.GtkScrolledWindow.Add(this.textviewLog);
this.expander1.Add(this.GtkScrolledWindow);
this.GtkLabel2 = new global::Gtk.Label();
this.GtkLabel2.Name = "GtkLabel2";
this.GtkLabel2.LabelProp = global::Mono.Unix.Catalog.GetString("Технический журнал");
this.GtkLabel2.UseUnderline = true;
this.expander1.LabelWidget = this.GtkLabel2;
this.dialog1_VBox.Add(this.expander1);
global::Gtk.Box.BoxChild w11 = ((global::Gtk.Box.BoxChild)(this.dialog1_VBox[this.expander1]));
w11.Position = 5;
// Container child dialog1_VBox.Gtk.Box+BoxChild
this.hbox2 = new global::Gtk.HBox();
this.hbox2.Name = "hbox2";
this.hbox2.Spacing = 6;
// Container child hbox2.Gtk.Box+BoxChild
this.buttonCancel = new global::Gtk.Button();
this.buttonCancel.CanFocus = true;
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.UseStock = true;
this.buttonCancel.UseUnderline = true;
this.buttonCancel.Label = "gtk-cancel";
this.hbox2.Add(this.buttonCancel);
global::Gtk.Box.BoxChild w12 = ((global::Gtk.Box.BoxChild)(this.hbox2[this.buttonCancel]));
w12.Position = 1;
// Container child hbox2.Gtk.Box+BoxChild
this.buttonExecute = new global::Gamma.GtkWidgets.yButton();
this.buttonExecute.CanFocus = true;
this.buttonExecute.Name = "buttonExecute";
this.buttonExecute.UseStock = true;
this.buttonExecute.UseUnderline = true;
this.buttonExecute.Label = "gtk-execute";
this.hbox2.Add(this.buttonExecute);
global::Gtk.Box.BoxChild w13 = ((global::Gtk.Box.BoxChild)(this.hbox2[this.buttonExecute]));
w13.Position = 2;
this.dialog1_VBox.Add(this.hbox2);
global::Gtk.Box.BoxChild w14 = ((global::Gtk.Box.BoxChild)(this.dialog1_VBox[this.hbox2]));
w14.Position = 6;
w14.Expand = false;
w14.Fill = false;
this.Add(this.dialog1_VBox);
if ((this.Child != null))
{
this.Child.ShowAll();
}
this.progressbarOperation.Hide();
this.Show();
this.checkCreateBackup.Toggled += new global::System.EventHandler(this.OnCheckCreateBackupToggled);
this.buttonFileChooser.Clicked += new global::System.EventHandler(this.OnButtonFileChooserClicked);
this.buttonCancel.Clicked += new global::System.EventHandler(this.OnButtonCancelClicked);
this.buttonExecute.Clicked += new global::System.EventHandler(this.OnButtonExecuteClicked);
}
}
}
| 42.639785 | 148 | 0.735216 | [
"Apache-2.0"
] | Art8m/QSProjects | QS.Updater.Gtk/gtk-gui/QS.Updater.DB.Views.UpdateProcessView.cs | 8,125 | C# |
namespace NeinLinq;
/// <summary>
/// Create rewritten queries.
/// </summary>
public static class RewriteEntityQueryBuilder
{
/// <summary>
/// Rewrite a given query.
/// </summary>
/// <param name="value">The query to rewrite.</param>
/// <param name="rewriter">The rewriter to rewrite the query.</param>
/// <returns>The rewritten query.</returns>
public static IQueryable EntityRewrite(this IQueryable value, ExpressionVisitor rewriter)
{
if (value is null)
throw new ArgumentNullException(nameof(value));
if (rewriter is null)
throw new ArgumentNullException(nameof(rewriter));
var provider = new RewriteEntityQueryProvider(value.Provider, rewriter);
return (IQueryable)Activator.CreateInstance(
typeof(RewriteEntityQueryable<>).MakeGenericType(value.ElementType),
value, provider)!;
}
/// <summary>
/// Rewrite a given query.
/// </summary>
/// <param name="value">The query to rewrite.</param>
/// <param name="rewriter">The rewriter to rewrite the query.</param>
/// <returns>The rewritten query.</returns>
public static IOrderedQueryable EntityRewrite(this IOrderedQueryable value, ExpressionVisitor rewriter)
{
if (value is null)
throw new ArgumentNullException(nameof(value));
if (rewriter is null)
throw new ArgumentNullException(nameof(rewriter));
var provider = new RewriteEntityQueryProvider(value.Provider, rewriter);
return (IOrderedQueryable)Activator.CreateInstance(
typeof(RewriteEntityQueryable<>).MakeGenericType(value.ElementType),
value, provider)!;
}
/// <summary>
/// Rewrite a given query.
/// </summary>
/// <typeparam name="T">The type of the query data.</typeparam>
/// <param name="value">The query to rewrite.</param>
/// <param name="rewriter">The rewriter to rewrite the query.</param>
/// <returns>The rewritten query.</returns>
public static IQueryable<T> EntityRewrite<T>(this IQueryable<T> value, ExpressionVisitor rewriter)
{
if (value is null)
throw new ArgumentNullException(nameof(value));
if (rewriter is null)
throw new ArgumentNullException(nameof(rewriter));
var provider = new RewriteEntityQueryProvider(value.Provider, rewriter);
return new RewriteEntityQueryable<T>(value, provider);
}
/// <summary>
/// Rewrite a given query.
/// </summary>
/// <typeparam name="T">The type of the query data.</typeparam>
/// <param name="value">The query to rewrite.</param>
/// <param name="rewriter">The rewriter to rewrite the query.</param>
/// <returns>The rewritten query.</returns>
public static IOrderedQueryable<T> EntityRewrite<T>(this IOrderedQueryable<T> value, ExpressionVisitor rewriter)
{
if (value is null)
throw new ArgumentNullException(nameof(value));
if (rewriter is null)
throw new ArgumentNullException(nameof(rewriter));
var provider = new RewriteEntityQueryProvider(value.Provider, rewriter);
return new RewriteEntityQueryable<T>(value, provider);
}
}
| 37.755814 | 116 | 0.65907 | [
"MIT"
] | rostunic/nein-linq | src/NeinLinq.EntityFrameworkCore/RewriteEntityQueryBuilder.cs | 3,249 | C# |
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Aop.Api.Domain
{
/// <summary>
/// SearchServiceItems Data Structure.
/// </summary>
[Serializable]
public class SearchServiceItems : AopObject
{
/// <summary>
/// 申请单状态
/// </summary>
[XmlElement("box_status")]
public string BoxStatus { get; set; }
/// <summary>
/// 类目id
/// </summary>
[XmlArray("category_codes")]
[XmlArrayItem("string")]
public List<string> CategoryCodes { get; set; }
/// <summary>
/// 服务申请单提报关键词
/// </summary>
[XmlArray("key_words")]
[XmlArrayItem("string")]
public List<string> KeyWords { get; set; }
/// <summary>
/// 模板id
/// </summary>
[XmlElement("template_id")]
public string TemplateId { get; set; }
}
}
| 24.3 | 56 | 0.512346 | [
"Apache-2.0"
] | 554393109/alipay-sdk-net-all | AlipaySDKNet.Standard/Domain/SearchServiceItems.cs | 1,010 | C# |
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace General.WebUI.Identity
{
public class ApplicationIdentityDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationIdentityDbContext(DbContextOptions<ApplicationIdentityDbContext> options):base(options)
{
}
}
}
| 25.555556 | 113 | 0.782609 | [
"MIT"
] | batuhan-yilmaz/Computer-Service-company-ntier-full-crud-operation-netcore-webapp-project | General/General.WebUI/Identity/ApplicationIdentityDbContext.cs | 462 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RandomDoubles
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// The Random object used by this program.
private Random Rand = new Random();
// Set some initial values formatted for the computer's locale.
private void Form1_Load(object sender, EventArgs e)
{
minTextBox.Text = (10.5).ToString();
maxTextBox.Text = (20.7).ToString();
}
// Generate some random values.
private void goButton_Click(object sender, EventArgs e)
{
double min = double.Parse(minTextBox.Text);
double max = double.Parse(maxTextBox.Text);
doublesListBox.Items.Clear();
for (int i = 0; i < 100; i++)
doublesListBox.Items.Add(Rand.NextDouble(min, max));
}
}
}
| 27.04878 | 71 | 0.607755 | [
"MIT"
] | PacktPublishing/Improving-your-C-Sharp-Skills | Chapter16/RandomDoubles/Form1.cs | 1,111 | C# |
using System;
/*
Copyright 2016 ParticleNET
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace Particle
{
/// <summary>
/// The types of a variable value
/// </summary>
public enum VariableType
{
/// <summary>
/// Integer
/// </summary>
Int,
/// <summary>
/// Double
/// </summary>
Double,
/// <summary>
/// String
/// </summary>
String
}
}
| 22.552632 | 72 | 0.704784 | [
"Apache-2.0"
] | ParticleNET/ParticleSDK | Particle/VariableType.cs | 859 | 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("04.GameOfIntervals")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("04.GameOfIntervals")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[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("a5d26141-3173-4dee-a7b4-dfa28f9fc78e")]
// 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.748575 | [
"MIT"
] | kovachevmartin/SoftUni | Basics/Exam_18-Mar-2017/04.GameOfIntervals/Properties/AssemblyInfo.cs | 1,407 | 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 sesv2-2019-09-27.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.SimpleEmailV2.Model
{
/// <summary>
/// An HTTP 200 response if the request succeeds, or an error message if the request fails.
/// </summary>
public partial class UpdateEmailIdentityPolicyResponse : AmazonWebServiceResponse
{
}
} | 31.263158 | 104 | 0.712121 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/SimpleEmailV2/Generated/Model/UpdateEmailIdentityPolicyResponse.cs | 1,188 | C# |
#pragma checksum "D:\Users\Danilo Filitto\source\repos\AppPicker\AppPicker\AppPicker.UWP\MainPage.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "0CF45832F154FC147EBD5D103D040C1A"
//------------------------------------------------------------------------------
// <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 AppPicker.UWP
{
partial class MainPage : global::Xamarin.Forms.Platform.UWP.WindowsPage
{
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 10.0.16.0")]
private bool _contentLoaded;
/// <summary>
/// InitializeComponent()
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 10.0.16.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void InitializeComponent()
{
if (_contentLoaded)
return;
_contentLoaded = true;
global::System.Uri resourceLocator = new global::System.Uri("ms-appx:///MainPage.xaml");
global::Windows.UI.Xaml.Application.LoadComponent(this, resourceLocator, global::Windows.UI.Xaml.Controls.Primitives.ComponentResourceLocation.Application);
}
partial void UnloadObject(global::Windows.UI.Xaml.DependencyObject unloadableObject);
}
}
| 38.166667 | 180 | 0.616344 | [
"MIT"
] | dfilitto/ProjetosXamarinForms | AppPicker/AppPicker/AppPicker.UWP/obj/x86/Debug/MainPage.g.i.cs | 1,605 | C# |
using Common.Interfaces;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;
using Prism.Modularity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IO.ModuleDef
{
public class Main : IModule
{
public void Initialize()
{
IUnityContainer container = ServiceLocator.Current.GetInstance<IUnityContainer>();
container.RegisterType<ICSVReader, Reader>();
System.Diagnostics.Debug.WriteLine("Initialised: IO");
}
}
}
| 24.5 | 94 | 0.707483 | [
"MIT"
] | davidmacpherson0/CHUM | src/IO/ModuleDef/Main.cs | 590 | C# |
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DifferenceEngine;
using System.Collections;
namespace DiffCalculator
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private DiffEngineLevel diffEngineLevel;
public MainWindow()
{
InitializeComponent();
}
public static string GetFileName()
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.InitialDirectory = "c:\\";
dlg.Filter = "All files (*.*)|*.*";
dlg.FilterIndex = 1;
dlg.RestoreDirectory = true;
return (dlg.ShowDialog() == dlg.CheckFileExists) ? dlg.FileName : string.Empty;
}
private void ValidateFile(string fileName, TextBox input)
{
if(!File.Exists(fileName))
{
MessageBox.Show(string.Format("{0} is invalid.", fileName), "Invalid File");
input.Focus();
return;
}
}
private void DisplayTextDiff(string sourceFile, string destFile)
{
try
{
DiffListTextFile sLF = new DiffListTextFile(sourceFile);
DiffListTextFile dLF = new DiffListTextFile(destFile);
Engine diffEngine = new Engine();
double time = diffEngine.ProcessDiff(sLF, dLF);
ArrayList report = diffEngine.DiffReport();
ResultsWindow resultsWindow = new ResultsWindow(sLF, dLF, report, time);
resultsWindow.Show();
}
catch (Exception ex)
{
string temp = string.Format("{0}{1}{1}===STACKTRACE==={1}{2}", ex.Message, Environment.NewLine, ex.StackTrace);
MessageBox.Show(temp, "Compare Error");
throw;
}
}
private void BtnSourceFile_Click(object sender, RoutedEventArgs e)
{
txtSourceEditor.Text = GetFileName();
}
private void BtnDestFile_Click(object sender, RoutedEventArgs e)
{
txtDestEditor.Text = GetFileName();
}
private void Compare_Click(object sender, RoutedEventArgs e)
{
string sourceFile = txtSourceEditor.Text.Trim();
string destFile = txtDestEditor.Text.Trim();
ValidateFile(sourceFile, txtSourceEditor);
ValidateFile(destFile, txtDestEditor);
var diffLevelRadioBtns = new List<RadioButton> { RbFast, RbMedium, RbSlow };
RadioButton checkedDiffLevel = diffLevelRadioBtns.FirstOrDefault( (RadioButton rb) => rb.IsChecked == true);
if (checkedDiffLevel.Tag.Equals("Fast")) diffEngineLevel = DiffEngineLevel.Fast;
if (checkedDiffLevel.Tag.Equals("Medium")) diffEngineLevel = DiffEngineLevel.Medium;
if (checkedDiffLevel.Tag.Equals("Slow")) diffEngineLevel = DiffEngineLevel.Slow;
DisplayTextDiff(sourceFile, destFile);
}
}
}
| 31.654545 | 127 | 0.603676 | [
"MIT"
] | cptcrunchy/DiffEngine | DiffCalculator/MainWindow.xaml.cs | 3,484 | 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 MergeISVProject {
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", "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>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MergeISVProject.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)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to The post-build utility MergeISVProject could not compile the razor view(s). While the build was successful, the deployment was unsuccessful. Therefore, check view(s) for issue(s) (i.e. localization syntax)..
/// </summary>
internal static string Error_CouldNotCompileRazorViews {
get {
return ResourceManager.GetString("Error_CouldNotCompileRazorViews", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sorry, the folder '{0}' could not be deleted. It appears as though the '{0}' folder is locked or in use. Please ensure that there are no command prompts or File Explorer instances referring to the '{0}' folder (or any of it's sub-folders)..
/// </summary>
internal static string Error_DeploymentFolderLockedOrInUse {
get {
return ResourceManager.GetString("Error_DeploymentFolderLockedOrInUse", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0}Error parsing '{1}'. No value was set..
/// </summary>
internal static string Error_ErrorParsingOptionNoValueWasSet {
get {
return ResourceManager.GetString("Error_ErrorParsingOptionNoValueWasSet", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0}Error parsing '{1}'. The folder '{2}' does not exist..
/// </summary>
internal static string Error_ErrorParsingOptionTheFolderDoesNotExist {
get {
return ResourceManager.GetString("Error_ErrorParsingOptionTheFolderDoesNotExist", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid build profile specified. 'Release' mode must be used..
/// </summary>
internal static string Error_InvalidBuildProfile {
get {
return ResourceManager.GetString("Error_InvalidBuildProfile", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid or missing command-line parameters.
/// </summary>
internal static string Error_InvalidCommandLineParameters {
get {
return ResourceManager.GetString("Error_InvalidCommandLineParameters", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Method '{0}' was called with one or more invalid parameters..
/// </summary>
internal static string Error_MethodCalledWithInvalidParameter {
get {
return ResourceManager.GetString("Error_MethodCalledWithInvalidParameter", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sorry, the minification process appears to have failed..
/// </summary>
internal static string Error_MinificationFailed {
get {
return ResourceManager.GetString("Error_MinificationFailed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sage 300 does not appear to be installed. This is a required application..
/// </summary>
internal static string Error_Sage300Missing {
get {
return ResourceManager.GetString("Error_Sage300Missing", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The post-build utility MergeISVProject could not find the Online Web folder for the Web UIs. While the build was successful, the deployment was unsuccessful. Therefore, check view(s) for issue(s) (i.e. localization syntax)..
/// </summary>
internal static string Error_Sage300WebFolderMissing {
get {
return ResourceManager.GetString("Error_Sage300WebFolderMissing", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to find the program '{0}'. Path='[1]'.
/// </summary>
internal static string Error_UnableToFindTheProgram {
get {
return ResourceManager.GetString("Error_UnableToFindTheProgram", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Application.
/// </summary>
internal static string Msg_Application {
get {
return ResourceManager.GetString("Msg_Application", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Set the target application type. (0 = Full Solution | 1 = Single Project).
/// </summary>
internal static string Msg_ApplicationModeOption {
get {
return ResourceManager.GetString("Msg_ApplicationModeOption", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The application has completed..
/// </summary>
internal static string Msg_ApplicationRunComplete {
get {
return ResourceManager.GetString("Msg_ApplicationRunComplete", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Argument List:.
/// </summary>
internal static string Msg_ArgumentList {
get {
return ResourceManager.GetString("Msg_ArgumentList", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Begin.
/// </summary>
internal static string Msg_Begin {
get {
return ResourceManager.GetString("Msg_Begin", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Beginning minification process on directory '{0}'.
/// </summary>
internal static string Msg_BeginningMinificationProcessOnDirectory {
get {
return ResourceManager.GetString("Msg_BeginningMinificationProcessOnDirectory", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Checking for registry keys.
/// </summary>
internal static string Msg_CheckingForRegistryKeys {
get {
return ResourceManager.GetString("Msg_CheckingForRegistryKeys", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Copying file.
/// </summary>
internal static string Msg_CopyingFile {
get {
return ResourceManager.GetString("Msg_CopyingFile", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Delete File '{0}'.
/// </summary>
internal static string Msg_DeleteFile {
get {
return ResourceManager.GetString("Msg_DeleteFile", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Deployment to Sage 300 installation disabled..
/// </summary>
internal static string Msg_DeploymentToSage300InstallationDisabled {
get {
return ResourceManager.GetString("Msg_DeploymentToSage300InstallationDisabled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Destination folder.
/// </summary>
internal static string Msg_DestinationFolder {
get {
return ResourceManager.GetString("Msg_DestinationFolder", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do NOT copy assets to the local Sage 300 installation directory.
/// </summary>
internal static string Msg_DoNotCopyAssetsToSage300installationDirectory {
get {
return ResourceManager.GetString("Msg_DoNotCopyAssetsToSage300installationDirectory", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to End.
/// </summary>
internal static string Msg_End {
get {
return ResourceManager.GetString("Msg_End", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to files.Count() = {0}.
/// </summary>
internal static string Msg_FilesDotCount {
get {
return ResourceManager.GetString("Msg_FilesDotCount", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to files found.
/// </summary>
internal static string Msg_FilesFound {
get {
return ResourceManager.GetString("Msg_FilesFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Files have been deployed to local Sage 300 installation..
/// </summary>
internal static string Msg_FilesHaveBeenDeployedToLocalSage300Directory {
get {
return ResourceManager.GetString("Msg_FilesHaveBeenDeployedToLocalSage300Directory", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to folder = '{0}'.
/// </summary>
internal static string Msg_FolderEquals {
get {
return ResourceManager.GetString("Msg_FolderEquals", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Generate a log file in the current working folder.
/// </summary>
internal static string Msg_GenerateALogFileInTheCurrentWorkingFolder {
get {
return ResourceManager.GetString("Msg_GenerateALogFileInTheCurrentWorkingFolder", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Inner Exception.
/// </summary>
internal static string Msg_InnerException {
get {
return ResourceManager.GetString("Msg_InnerException", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Live Deployment. Files will actually be copied to live Sage 300 installion directory..
/// </summary>
internal static string Msg_LiveDeployment {
get {
return ResourceManager.GetString("Msg_LiveDeployment", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Log File Location : {0}.
/// </summary>
internal static string Msg_LogFileLocation {
get {
return ResourceManager.GetString("Msg_LogFileLocation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Logging Started....
/// </summary>
internal static string Msg_LoggingStarted {
get {
return ResourceManager.GetString("Msg_LoggingStarted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Microsoft Visual Studio Solution path.
/// </summary>
internal static string Msg_MicrosoftVisualStudioSolutionPath {
get {
return ResourceManager.GetString("Msg_MicrosoftVisualStudioSolutionPath", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Microsoft Visual Studio Solution Web project path.
/// </summary>
internal static string Msg_MicrosoftVisualStudioSolutionWebProjectPath {
get {
return ResourceManager.GetString("Msg_MicrosoftVisualStudioSolutionWebProjectPath", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Minification complete..
/// </summary>
internal static string Msg_MinificationComplete {
get {
return ResourceManager.GetString("Msg_MinificationComplete", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Minification Successful!.
/// </summary>
internal static string Msg_MinificationSuccessful {
get {
return ResourceManager.GetString("Msg_MinificationSuccessful", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Minify javascript files.
/// </summary>
internal static string Msg_MinifyJavascriptFiles {
get {
return ResourceManager.GetString("Msg_MinifyJavascriptFiles", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to .NET Framework path containing aspnet_compile.exe.
/// </summary>
internal static string Msg_NetFrameworkPathContainingAspnetCompileDotExe {
get {
return ResourceManager.GetString("Msg_NetFrameworkPathContainingAspnetCompileDotExe", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Only.
/// </summary>
internal static string Msg_Only {
get {
return ResourceManager.GetString("Msg_Only", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to '{0}' created..
/// </summary>
internal static string Msg_PathCreated {
get {
return ResourceManager.GetString("Msg_PathCreated", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to '{0}' deleted..
/// </summary>
internal static string Msg_PathDeleted {
get {
return ResourceManager.GetString("Msg_PathDeleted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to '{0}' exists..
/// </summary>
internal static string Msg_PathExists {
get {
return ResourceManager.GetString("Msg_PathExists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Preparing {0} folders and files for Staging....
/// </summary>
internal static string Msg_PreparingDeployFoldersAndFilesForStaging {
get {
return ResourceManager.GetString("Msg_PreparingDeployFoldersAndFilesForStaging", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Prerequisites are valid..
/// </summary>
internal static string Msg_PrerequisitesAreValid {
get {
return ResourceManager.GetString("Msg_PrerequisitesAreValid", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Program Name: {0}
///Version: {1}
///Build Date: {2}
///
///Copyright: {3}
/// All rights reserved.
///License: The MIT Licence (MIT)
///
///Required 3rd party
///programs/components: {4}
///
///
///Required Parameter(s):
///
///{5}
///
///Optional Parameter(s):
///
///{6}.
/// </summary>
internal static string Msg_ProgramUsageMessage {
get {
return ResourceManager.GetString("Msg_ProgramUsageMessage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Rename '{0}' to '{1}'.
/// </summary>
internal static string Msg_Rename1To2 {
get {
return ResourceManager.GetString("Msg_Rename1To2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Renaming complete!.
/// </summary>
internal static string Msg_RenamingComplete {
get {
return ResourceManager.GetString("Msg_RenamingComplete", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Renaming javascript files back to usable state..
/// </summary>
internal static string Msg_RenamingJavascriptFilesBackToUsableState {
get {
return ResourceManager.GetString("Msg_RenamingJavascriptFilesBackToUsableState", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Running command : {0}.
/// </summary>
internal static string Msg_RunningCommand {
get {
return ResourceManager.GetString("Msg_RunningCommand", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sage 300 Menu definition file name (i.e. XXMenuDetails.xml).
/// </summary>
internal static string Msg_Sage300MenuDefinitionFileName {
get {
return ResourceManager.GetString("Msg_Sage300MenuDefinitionFileName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Simulate copying of assets to the local Sage 300 installation directory.
/// </summary>
internal static string Msg_SimulateCopyingOfAssetsTo {
get {
return ResourceManager.GetString("Msg_SimulateCopyingOfAssetsTo", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Simulated Deployment Only. No files will actually be copied to live Sage 300 installion directory..
/// </summary>
internal static string Msg_SimulatedDeploymentOnly {
get {
return ResourceManager.GetString("Msg_SimulatedDeploymentOnly", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Simulation.
/// </summary>
internal static string Msg_Simulation {
get {
return ResourceManager.GetString("Msg_Simulation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Source folder.
/// </summary>
internal static string Msg_SourceFolder {
get {
return ResourceManager.GetString("Msg_SourceFolder", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Visual Studio project build configuration (only release supported).
/// </summary>
internal static string Msg_VisualStudioProjectBuildConfiguration {
get {
return ResourceManager.GetString("Msg_VisualStudioProjectBuildConfiguration", resourceCulture);
}
}
}
}
| 39.679181 | 328 | 0.573499 | [
"MIT"
] | Mon-Lay/Sage300-SDK | src/utilities/MergeISVProject/MergeISVProject/Resources.Designer.cs | 23,254 | C# |
using System;
using Org.BouncyCastle.Math.Raw;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
namespace Org.BouncyCastle.Math.EC.Custom.Sec
{
internal class SecP160R2Curve
: AbstractFpCurve
{
public static readonly BigInteger q = SecP160R2FieldElement.Q;
private const int SECP160R2_DEFAULT_COORDS = COORD_JACOBIAN;
private const int SECP160R2_FE_INTS = 5;
private static readonly ECFieldElement[] SECP160R2_AFFINE_ZS = new ECFieldElement[] { new SecP160R2FieldElement(BigInteger.One) };
protected readonly SecP160R2Point m_infinity;
public SecP160R2Curve()
: base(q)
{
this.m_infinity = new SecP160R2Point(this, null, null);
this.m_a = FromBigInteger(new BigInteger(1,
Hex.DecodeStrict("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC70")));
this.m_b = FromBigInteger(new BigInteger(1,
Hex.DecodeStrict("B4E134D3FB59EB8BAB57274904664D5AF50388BA")));
this.m_order = new BigInteger(1, Hex.DecodeStrict("0100000000000000000000351EE786A818F3A1A16B"));
this.m_cofactor = BigInteger.One;
this.m_coord = SECP160R2_DEFAULT_COORDS;
}
protected override ECCurve CloneCurve()
{
return new SecP160R2Curve();
}
public override bool SupportsCoordinateSystem(int coord)
{
switch (coord)
{
case COORD_JACOBIAN:
return true;
default:
return false;
}
}
public virtual BigInteger Q
{
get { return q; }
}
public override ECPoint Infinity
{
get { return m_infinity; }
}
public override int FieldSize
{
get { return q.BitLength; }
}
public override ECFieldElement FromBigInteger(BigInteger x)
{
return new SecP160R2FieldElement(x);
}
protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression)
{
return new SecP160R2Point(this, x, y, withCompression);
}
protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression)
{
return new SecP160R2Point(this, x, y, zs, withCompression);
}
public override ECLookupTable CreateCacheSafeLookupTable(ECPoint[] points, int off, int len)
{
uint[] table = new uint[len * SECP160R2_FE_INTS * 2];
{
int pos = 0;
for (int i = 0; i < len; ++i)
{
ECPoint p = points[off + i];
Nat160.Copy(((SecP160R2FieldElement)p.RawXCoord).x, 0, table, pos); pos += SECP160R2_FE_INTS;
Nat160.Copy(((SecP160R2FieldElement)p.RawYCoord).x, 0, table, pos); pos += SECP160R2_FE_INTS;
}
}
return new SecP160R2LookupTable(this, table, len);
}
public override ECFieldElement RandomFieldElement(SecureRandom r)
{
uint[] x = Nat160.Create();
SecP160R2Field.Random(r, x);
return new SecP160R2FieldElement(x);
}
public override ECFieldElement RandomFieldElementMult(SecureRandom r)
{
uint[] x = Nat160.Create();
SecP160R2Field.RandomMult(r, x);
return new SecP160R2FieldElement(x);
}
private class SecP160R2LookupTable
: AbstractECLookupTable
{
private readonly SecP160R2Curve m_outer;
private readonly uint[] m_table;
private readonly int m_size;
internal SecP160R2LookupTable(SecP160R2Curve outer, uint[] table, int size)
{
this.m_outer = outer;
this.m_table = table;
this.m_size = size;
}
public override int Size
{
get { return m_size; }
}
public override ECPoint Lookup(int index)
{
uint[] x = Nat160.Create(), y = Nat160.Create();
int pos = 0;
for (int i = 0; i < m_size; ++i)
{
uint MASK = (uint)(((i ^ index) - 1) >> 31);
for (int j = 0; j < SECP160R2_FE_INTS; ++j)
{
x[j] ^= m_table[pos + j] & MASK;
y[j] ^= m_table[pos + SECP160R2_FE_INTS + j] & MASK;
}
pos += (SECP160R2_FE_INTS * 2);
}
return CreatePoint(x, y);
}
public override ECPoint LookupVar(int index)
{
uint[] x = Nat160.Create(), y = Nat160.Create();
int pos = index * SECP160R2_FE_INTS * 2;
for (int j = 0; j < SECP160R2_FE_INTS; ++j)
{
x[j] = m_table[pos + j];
y[j] = m_table[pos + SECP160R2_FE_INTS + j];
}
return CreatePoint(x, y);
}
private ECPoint CreatePoint(uint[] x, uint[] y)
{
return m_outer.CreateRawPoint(new SecP160R2FieldElement(x), new SecP160R2FieldElement(y), SECP160R2_AFFINE_ZS, false);
}
}
}
}
| 32.162791 | 138 | 0.536876 | [
"MIT"
] | 0x070696E65/Symnity | Assets/Plugins/Symnity/Pulgins/crypto/src/math/ec/custom/sec/SecP160R2Curve.cs | 5,534 | C# |
namespace Mindstorms.Core.Music._442
{
public class G2 : Note
{
public G2(NoteType noteType = NoteType.Quarter) : base(noteType)
{
Name = "G2";
Frequency = 98.44;
WaveLength = 350.45;
}
}
}
| 20.153846 | 72 | 0.51145 | [
"MIT"
] | Mortens4444/LegoMindstromsEV3 | Mindstorms.Core/Music/442/G2.cs | 262 | C# |
using WebGLDotNET;
namespace Tests
{
public abstract class BaseTests
{
protected WebGLProgram SetUpProgram(
WebGLRenderingContextBase gl,
string vertexShaderSource = "void main() {}",
string fragmentShaderSource = "void main() {}")
{
var vertexShader = gl.CreateShader(WebGLRenderingContextBase.VERTEX_SHADER);
gl.ShaderSource(vertexShader, vertexShaderSource);
gl.CompileShader(vertexShader);
var fragmentShader = gl.CreateShader(WebGLRenderingContextBase.FRAGMENT_SHADER);
gl.ShaderSource(fragmentShader, fragmentShaderSource);
gl.CompileShader(fragmentShader);
var program = gl.CreateProgram();
gl.AttachShader(program, vertexShader);
gl.AttachShader(program, fragmentShader);
gl.LinkProgram(program);
return program;
}
}
}
| 34.592593 | 92 | 0.638116 | [
"MIT"
] | EvergineTeam/WebGL.NET | src/Tests/BaseTests.cs | 936 | C# |
// Copyright (c) 2020-2021 Vladimir Popov zor1994@gmail.com https://github.com/ZorPastaman/Behavior-Tree
using UnityEngine;
namespace Zor.BehaviorTree.Serialization.SerializedBehaviors.Leaves.Actions
{
public sealed class SerializedGetRendererInParent : SerializedGetComponentInParent<Renderer>
{
}
}
| 27.909091 | 105 | 0.820847 | [
"MIT"
] | ZorPastaman/Behavior-Tree | Runtime/Serialization/SerializedBehaviors/Leaves/Actions/SerializedGetRendererInParent.cs | 309 | C# |
using System;
using NSubstitute;
using Octokit.Reactive;
using Xunit;
namespace Octokit.Tests
{
public class ObservableEnterpriseLicenseClientTests
{
public class TheCtor
{
[Fact]
public void EnsuresNonNullArguments()
{
Assert.Throws<ArgumentNullException>(
() => new ObservableEnterpriseLicenseClient(null));
}
}
public class TheGetMethod
{
[Fact]
public void CallsIntoClient()
{
var github = Substitute.For<IGitHubClient>();
var client = new ObservableEnterpriseLicenseClient(github);
client.Get();
github.Enterprise.License.Received(1).Get();
}
}
}
}
| 23.941176 | 75 | 0.536855 | [
"MIT"
] | 3shape/octokit.net | Octokit.Tests/Reactive/Enterprise/ObservableEnterpriseLicenseClientTests.cs | 816 | C# |
using Swordfish.NET.Collections;
using Swordfish.NET.Collections.Auxiliary;
using Swordfish.NET.TestV3.Auxiliary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Swordfish.NET.Demo.ViewModels
{
public class ConcurrentObservableSortedCollectionTestViewModel : ConcurrentObservableTestBaseViewModel<string>
{
public ConcurrentObservableSortedCollectionTestViewModel()
{
}
public ConcurrentObservableSortedCollection<string> TestCollection { get; } = new ConcurrentObservableSortedCollection<string>();
public List<string> NormalCollection { get; } = new List<string>();
public List<string> NormalCollectionView { get; set; }
private RelayCommandFactory _runTestScript = new RelayCommandFactory();
public ICommand RunTestScript =>
_runTestScript.GetCommandAsync(async () =>
{
Stopwatch sw = new Stopwatch();
ClearMessages();
await Clear(false, TestCollection, NormalCollection);
// Show a message
Message("Running tests on normal, concurrent, and view collections...");
Message("");
// Create the items to addd and insert
Message($"Creating 1,000,000 items to add ...");
sw.Restart();
var itemsToAdd = await Task.Run(() =>
Enumerable.Range(0, 1000000).
Select(x => $"Value {x}").ToList());
sw.Stop();
Message("", sw.Elapsed);
// New collection supports inserts by index, test by starting at 0 and adding 3 each time
Message("");
Message($"Creating 100,000 items to to insert by index...");
sw.Restart();
var itemsToInsert = await Task.Run(() =>
Enumerable.Range(0, 100000).
Select(x => $"Insert Value {x}").ToList());
sw.Stop();
Message("", sw.Elapsed);
var itemsToRemove = itemsToInsert.Take(1000).ToList();
// Add items to all collections and then compare
Message("");
await Task.Run(() =>
Task.WaitAll(
Add(itemsToAdd, NormalCollection, false),
Add(itemsToAdd, TestCollection, false)
));
await CompareCollections();
Message("");
await Task.Run(() =>
Task.WaitAll(
InsertItems(itemsToInsert, NormalCollection, false),
InsertItems(itemsToInsert, TestCollection, false)
));
await CompareCollections();
Message("");
// Test adding range of items
await Clear(false, TestCollection);
await AddRange(itemsToAdd, TestCollection, false);
await InsertItems(itemsToInsert, TestCollection, false);
await CompareCollections();
Message("");
await Task.Run(() =>
Task.WaitAll(
Remove(itemsToRemove, NormalCollection, false),
Remove(itemsToRemove, TestCollection, false)
));
await CompareCollections();
Message("");
await Task.Run(() =>
Task.WaitAll(
// Don't do NormalDictionary, takes too long
//RemoveAtIndex(NormalDictionary, false),
RemoveAtIndexAfterSort(NormalCollection, false),
RemoveAtIndex(TestCollection, false)
));
await CompareCollections();
// Do GUI thread tests
Message("");
Message("GUI Thread Test");
Message("");
await Clear(true, TestCollection);
await AddRange(itemsToAdd, TestCollection, true);
await InsertItems(itemsToInsert, TestCollection, true);
await Clear(true, NormalCollection);
await AddRange(itemsToAdd, NormalCollection, true);
await InsertItems(itemsToInsert, NormalCollection, true);
await CompareCollections();
// Test adding and inserting from multiple threads at once
Message("");
await Clear(TestCollection, false);
await AddItemsParallel(itemsToAdd, TestCollection);
await InsertItemsParallel(itemsToInsert, TestCollection);
await CompareCollections();
Message("");
Message("-- Finished Testing --");
});
private async Task RemoveAtIndexAfterSort(List<string> collectionToSort, bool onGuiThread)
{
collectionToSort.Sort();
Action<int> preRemoveSort = (i) =>
{
collectionToSort.RemoveAt(i);
};
await RemoveAtIndex(collectionToSort, preRemoveSort, onGuiThread);
}
protected Task CompareCollections(params ICollection<string>[] collections)
{
NormalCollection.Sort();
NormalCollectionView = NormalCollection.ToList();
RaisePropertyChanged(nameof(NormalCollectionView));
var allCollections = collections.Concat(new ICollection<string>[] { NormalCollection, TestCollection, TestCollection.CollectionView });
return CompareCollectionsBase(allCollections.ToArray());
}
}
}
| 37.039474 | 147 | 0.568028 | [
"CC0-1.0"
] | stewienj/ConcurrentCollections2 | ExamplesAndTests/Swordfish.NET.TestV3/ViewModels/ConcurrentObservableSortedCollectionTestViewModel.cs | 5,632 | C# |
namespace Machete.X12Schema.V5010
{
using X12;
public interface W01 :
X12Segment
{
Value<decimal> Quantity { get; }
Value<string> UnitOrBasisOfMeasurementCode { get; }
Value<string> UPCCaseCode { get; }
Value<string> ProductOrServiceIdQualifier1 { get; }
Value<string> ProductOrServiceId1 { get; }
Value<string> ProductOrServiceIdQualifier2 { get; }
Value<string> ProductOrServiceId2 { get; }
Value<string> FreightClassCode { get; }
Value<string> RateClassCode { get; }
Value<string> CommodityCodeQualifier { get; }
Value<string> CommodityCode { get; }
Value<string> PalletBlockAndTiers { get; }
Value<string> WarehouseLotNumber { get; }
Value<string> ProductOrServiceConditionCode { get; }
Value<string> ProductOrServiceIdQualifier3 { get; }
Value<string> ProductOrServiceId3 { get; }
}
} | 26.292683 | 60 | 0.564935 | [
"Apache-2.0"
] | ahives/Machete | src/Machete.X12Schema/V5010/Segments/W01.cs | 1,078 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System.IO;
namespace Tailspin.Surveys.WebAPI
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
} | 25.478261 | 70 | 0.612628 | [
"MIT"
] | anirbansdutta/Tailspin.Surveys | src/Tailspin.Surveys.WebAPI/Program.cs | 588 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Network.V20200301.Outputs
{
/// <summary>
/// UrlPathMaps give a url path to the backend mapping information for PathBasedRouting.
/// </summary>
[OutputType]
public sealed class ApplicationGatewayUrlPathMapResponse
{
/// <summary>
/// Default backend address pool resource of URL path map.
/// </summary>
public readonly Outputs.SubResourceResponse? DefaultBackendAddressPool;
/// <summary>
/// Default backend http settings resource of URL path map.
/// </summary>
public readonly Outputs.SubResourceResponse? DefaultBackendHttpSettings;
/// <summary>
/// Default redirect configuration resource of URL path map.
/// </summary>
public readonly Outputs.SubResourceResponse? DefaultRedirectConfiguration;
/// <summary>
/// Default Rewrite rule set resource of URL path map.
/// </summary>
public readonly Outputs.SubResourceResponse? DefaultRewriteRuleSet;
/// <summary>
/// A unique read-only string that changes whenever the resource is updated.
/// </summary>
public readonly string Etag;
/// <summary>
/// Resource ID.
/// </summary>
public readonly string? Id;
/// <summary>
/// Name of the URL path map that is unique within an Application Gateway.
/// </summary>
public readonly string? Name;
/// <summary>
/// Path rule of URL path map resource.
/// </summary>
public readonly ImmutableArray<Outputs.ApplicationGatewayPathRuleResponse> PathRules;
/// <summary>
/// The provisioning state of the URL path map resource.
/// </summary>
public readonly string ProvisioningState;
/// <summary>
/// Type of the resource.
/// </summary>
public readonly string Type;
[OutputConstructor]
private ApplicationGatewayUrlPathMapResponse(
Outputs.SubResourceResponse? defaultBackendAddressPool,
Outputs.SubResourceResponse? defaultBackendHttpSettings,
Outputs.SubResourceResponse? defaultRedirectConfiguration,
Outputs.SubResourceResponse? defaultRewriteRuleSet,
string etag,
string? id,
string? name,
ImmutableArray<Outputs.ApplicationGatewayPathRuleResponse> pathRules,
string provisioningState,
string type)
{
DefaultBackendAddressPool = defaultBackendAddressPool;
DefaultBackendHttpSettings = defaultBackendHttpSettings;
DefaultRedirectConfiguration = defaultRedirectConfiguration;
DefaultRewriteRuleSet = defaultRewriteRuleSet;
Etag = etag;
Id = id;
Name = name;
PathRules = pathRules;
ProvisioningState = provisioningState;
Type = type;
}
}
}
| 34.757895 | 93 | 0.634767 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Network/V20200301/Outputs/ApplicationGatewayUrlPathMapResponse.cs | 3,302 | C# |
namespace WindowUI.HHZX.UserControls
{
partial class ucMealBookingDetail
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.labSupperMB = new System.Windows.Forms.Label();
this.labLunchMB = new System.Windows.Forms.Label();
this.labBreakfastMB = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.panel1 = new System.Windows.Forms.Panel();
this.panel2 = new System.Windows.Forms.Panel();
this.panel3 = new System.Windows.Forms.Panel();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
this.panel3.SuspendLayout();
this.SuspendLayout();
//
// labSupperMB
//
this.labSupperMB.AutoSize = true;
this.labSupperMB.BackColor = System.Drawing.Color.White;
this.labSupperMB.Font = new System.Drawing.Font("SimSun", 10F, System.Drawing.FontStyle.Underline);
this.labSupperMB.ForeColor = System.Drawing.Color.Blue;
this.labSupperMB.Location = new System.Drawing.Point(51, 5);
this.labSupperMB.Name = "labSupperMB";
this.labSupperMB.Size = new System.Drawing.Size(35, 14);
this.labSupperMB.TabIndex = 30;
this.labSupperMB.Text = "缺失";
//
// labLunchMB
//
this.labLunchMB.AutoSize = true;
this.labLunchMB.BackColor = System.Drawing.Color.White;
this.labLunchMB.Font = new System.Drawing.Font("SimSun", 10F, System.Drawing.FontStyle.Underline);
this.labLunchMB.ForeColor = System.Drawing.Color.Blue;
this.labLunchMB.Location = new System.Drawing.Point(51, 5);
this.labLunchMB.Name = "labLunchMB";
this.labLunchMB.Size = new System.Drawing.Size(35, 14);
this.labLunchMB.TabIndex = 29;
this.labLunchMB.Text = "缺失";
//
// labBreakfastMB
//
this.labBreakfastMB.AutoSize = true;
this.labBreakfastMB.BackColor = System.Drawing.Color.White;
this.labBreakfastMB.Font = new System.Drawing.Font("SimSun", 10F, System.Drawing.FontStyle.Underline);
this.labBreakfastMB.ForeColor = System.Drawing.Color.Blue;
this.labBreakfastMB.Location = new System.Drawing.Point(51, 5);
this.labBreakfastMB.Name = "labBreakfastMB";
this.labBreakfastMB.Size = new System.Drawing.Size(35, 14);
this.labBreakfastMB.TabIndex = 28;
this.labBreakfastMB.Text = "缺失";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("SimSun", 10F);
this.label1.Location = new System.Drawing.Point(3, 5);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(42, 14);
this.label1.TabIndex = 31;
this.label1.Text = "早餐:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("SimSun", 10F);
this.label2.Location = new System.Drawing.Point(3, 5);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(42, 14);
this.label2.TabIndex = 32;
this.label2.Text = "午餐:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("SimSun", 10F);
this.label3.Location = new System.Drawing.Point(3, 5);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(42, 14);
this.label3.TabIndex = 33;
this.label3.Text = "晚餐:";
//
// panel1
//
this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panel1.Controls.Add(this.labBreakfastMB);
this.panel1.Controls.Add(this.label1);
this.panel1.Location = new System.Drawing.Point(3, 5);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(90, 27);
this.panel1.TabIndex = 34;
//
// panel2
//
this.panel2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panel2.Controls.Add(this.labLunchMB);
this.panel2.Controls.Add(this.label2);
this.panel2.Location = new System.Drawing.Point(92, 5);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(90, 27);
this.panel2.TabIndex = 35;
//
// panel3
//
this.panel3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panel3.Controls.Add(this.labSupperMB);
this.panel3.Controls.Add(this.label3);
this.panel3.Location = new System.Drawing.Point(181, 5);
this.panel3.Name = "panel3";
this.panel3.Size = new System.Drawing.Size(90, 27);
this.panel3.TabIndex = 36;
//
// ucMealBookingDetail
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.panel3);
this.Controls.Add(this.panel2);
this.Controls.Add(this.panel1);
this.Name = "ucMealBookingDetail";
this.Size = new System.Drawing.Size(275, 36);
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
this.panel3.ResumeLayout(false);
this.panel3.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Label labSupperMB;
private System.Windows.Forms.Label labLunchMB;
private System.Windows.Forms.Label labBreakfastMB;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Panel panel3;
}
}
| 43.156069 | 114 | 0.57206 | [
"BSD-3-Clause"
] | sndnvaps/OneCard_ | WindowUI.HHZX/UserControls/ucMealBookingDetail.Designer.cs | 7,492 | C# |
namespace Nuages.AspNetIdentity.Stores.Mongo;
public class MongoIdentityOptions
{
public string ConnectionString { get; set; } = "";
public string Locale { get; set; } = "en";
} | 26.571429 | 54 | 0.704301 | [
"Apache-2.0"
] | nuages-io/nuages-aspnetidentity-mongo | Nuages.AspNetIdentity.Stores.Mongo/MongoIdentityOptions.cs | 186 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.