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 |
|---|---|---|---|---|---|---|---|---|
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.DataShare
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// DataSetMappingsOperations operations.
/// </summary>
internal partial class DataSetMappingsOperations : IServiceOperations<DataShareManagementClient>, IDataSetMappingsOperations
{
/// <summary>
/// Initializes a new instance of the DataSetMappingsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DataSetMappingsOperations(DataShareManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the DataShareManagementClient
/// </summary>
public DataShareManagementClient Client { get; private set; }
/// <summary>
/// Get DataSetMapping in a shareSubscription.
/// </summary>
/// <remarks>
/// Get a DataSetMapping in a shareSubscription
/// </remarks>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='accountName'>
/// The name of the share account.
/// </param>
/// <param name='shareSubscriptionName'>
/// The name of the shareSubscription.
/// </param>
/// <param name='dataSetMappingName'>
/// The name of the dataSetMapping.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DataShareErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<DataSetMapping>> GetWithHttpMessagesAsync(string resourceGroupName, string accountName, string shareSubscriptionName, string dataSetMappingName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (shareSubscriptionName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "shareSubscriptionName");
}
if (dataSetMappingName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "dataSetMappingName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("shareSubscriptionName", shareSubscriptionName);
tracingParameters.Add("dataSetMappingName", dataSetMappingName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataShare/accounts/{accountName}/shareSubscriptions/{shareSubscriptionName}/dataSetMappings/{dataSetMappingName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{shareSubscriptionName}", System.Uri.EscapeDataString(shareSubscriptionName));
_url = _url.Replace("{dataSetMappingName}", System.Uri.EscapeDataString(dataSetMappingName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new DataShareErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
DataShareError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DataShareError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<DataSetMapping>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<DataSetMapping>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Maps a source data set in the source share to a sink data set in the share
/// subscription.
/// Enables copying the data set from source to destination.
/// </summary>
/// <remarks>
/// Create a DataSetMapping
/// </remarks>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='accountName'>
/// The name of the share account.
/// </param>
/// <param name='shareSubscriptionName'>
/// The name of the share subscription which will hold the data set sink.
/// </param>
/// <param name='dataSetMappingName'>
/// The name of the data set mapping to be created.
/// </param>
/// <param name='dataSetMapping'>
/// Destination data set configuration details.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DataShareErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<DataSetMapping>> CreateWithHttpMessagesAsync(string resourceGroupName, string accountName, string shareSubscriptionName, string dataSetMappingName, DataSetMapping dataSetMapping, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (shareSubscriptionName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "shareSubscriptionName");
}
if (dataSetMappingName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "dataSetMappingName");
}
if (dataSetMapping == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "dataSetMapping");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("shareSubscriptionName", shareSubscriptionName);
tracingParameters.Add("dataSetMappingName", dataSetMappingName);
tracingParameters.Add("dataSetMapping", dataSetMapping);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataShare/accounts/{accountName}/shareSubscriptions/{shareSubscriptionName}/dataSetMappings/{dataSetMappingName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{shareSubscriptionName}", System.Uri.EscapeDataString(shareSubscriptionName));
_url = _url.Replace("{dataSetMappingName}", System.Uri.EscapeDataString(dataSetMappingName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(dataSetMapping != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(dataSetMapping, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new DataShareErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
DataShareError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DataShareError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<DataSetMapping>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<DataSetMapping>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<DataSetMapping>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Delete DataSetMapping in a shareSubscription.
/// </summary>
/// <remarks>
/// Delete a DataSetMapping in a shareSubscription
/// </remarks>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='accountName'>
/// The name of the share account.
/// </param>
/// <param name='shareSubscriptionName'>
/// The name of the shareSubscription.
/// </param>
/// <param name='dataSetMappingName'>
/// The name of the dataSetMapping.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DataShareErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, string shareSubscriptionName, string dataSetMappingName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (shareSubscriptionName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "shareSubscriptionName");
}
if (dataSetMappingName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "dataSetMappingName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("shareSubscriptionName", shareSubscriptionName);
tracingParameters.Add("dataSetMappingName", dataSetMappingName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataShare/accounts/{accountName}/shareSubscriptions/{shareSubscriptionName}/dataSetMappings/{dataSetMappingName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{shareSubscriptionName}", System.Uri.EscapeDataString(shareSubscriptionName));
_url = _url.Replace("{dataSetMappingName}", System.Uri.EscapeDataString(dataSetMappingName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new DataShareErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
DataShareError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DataShareError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// List DataSetMappings in a share subscription.
/// </summary>
/// <remarks>
/// List DataSetMappings in a share subscription
/// </remarks>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='accountName'>
/// The name of the share account.
/// </param>
/// <param name='shareSubscriptionName'>
/// The name of the share subscription.
/// </param>
/// <param name='skipToken'>
/// Continuation token
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DataShareErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<DataSetMapping>>> ListByShareSubscriptionWithHttpMessagesAsync(string resourceGroupName, string accountName, string shareSubscriptionName, string skipToken = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (shareSubscriptionName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "shareSubscriptionName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("shareSubscriptionName", shareSubscriptionName);
tracingParameters.Add("skipToken", skipToken);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByShareSubscription", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataShare/accounts/{accountName}/shareSubscriptions/{shareSubscriptionName}/dataSetMappings").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{shareSubscriptionName}", System.Uri.EscapeDataString(shareSubscriptionName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (skipToken != null)
{
_queryParameters.Add(string.Format("$skipToken={0}", System.Uri.EscapeDataString(skipToken)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new DataShareErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
DataShareError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DataShareError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<DataSetMapping>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<DataSetMapping>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// List DataSetMappings in a share subscription.
/// </summary>
/// <remarks>
/// List DataSetMappings in a share subscription
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="DataShareErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<DataSetMapping>>> ListByShareSubscriptionNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByShareSubscriptionNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new DataShareErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
DataShareError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<DataShareError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<DataSetMapping>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<DataSetMapping>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 46.55709 | 350 | 0.571171 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/datashare/Microsoft.Azure.Management.DataShare/src/Generated/DataSetMappingsOperations.cs | 50,561 | C# |
namespace Aspose.Tasks.Examples.CSharp
{
using System;
using NUnit.Framework;
[TestFixture]
public class ExOutlineValueCollection : ApiExampleBase
{
[Test]
public void WorkWithOutlineValueCollection()
{
// ExStart
// ExFor: OutlineValueCollection
// ExFor: OutlineValueCollection.Add(OutlineValue)
// ExFor: OutlineValueCollection.Clear
// ExFor: OutlineValueCollection.Contains(OutlineValue)
// ExFor: OutlineValueCollection.CopyTo(OutlineValue[],Int32)
// ExFor: OutlineValueCollection.Count
// ExFor: OutlineValueCollection.GetEnumerator
// ExFor: OutlineValueCollection.IndexOf(OutlineValue)
// ExFor: OutlineValueCollection.Insert(Int32,OutlineValue)
// ExFor: OutlineValueCollection.IsReadOnly
// ExFor: OutlineValueCollection.Item(Int32)
// ExFor: OutlineValueCollection.Remove(OutlineValue)
// ExFor: OutlineValueCollection.RemoveAt(Int32)
// ExSummary: Shows how to work with outline value collections.
var project = new Project(DataDir + "OutlineValues2010.mpp");
// clear value collections
foreach (var outlineCode in project.OutlineCodes)
{
// clear outline masks
if (outlineCode.Values.Count <= 0)
{
continue;
}
if (!outlineCode.Values.IsReadOnly)
{
outlineCode.Values.Clear();
}
}
var codeDefinition = new OutlineCodeDefinition
{
Alias = "New task outline code1", FieldId = ((int)ExtendedAttributeTask.OutlineCode1).ToString(), FieldName = "Outline Code1"
};
var value = new OutlineValue { Description = "Value description", ValueId = 1, Value = "123456", Type = OutlineValueType.Number };
codeDefinition.Values.Add(value);
project.OutlineCodes.Add(codeDefinition);
// update value by index access
codeDefinition.Values[0].Value = "654321";
// iterate over outline values
foreach (var definitionValue in codeDefinition.Values)
{
Console.WriteLine("Value: " + definitionValue.Value);
Console.WriteLine("Value Id: " + definitionValue.ValueId);
Console.WriteLine("Value Guid: " + definitionValue.ValueGuid);
Console.WriteLine();
}
// ...
// work with outline values
// ...
// remove a value when needed
if (codeDefinition.Values.Contains(value))
{
codeDefinition.Values.Remove(value);
}
// insert a value in the start position
codeDefinition.Values.Insert(0, value);
// check the position of inserted value
Console.WriteLine("Index of inserted value: " + codeDefinition.Values.IndexOf(value));
// ...
// work with outline values
// ...
// remove the last value from the collection
codeDefinition.Values.RemoveAt(codeDefinition.Values.Count - 1);
// one can create the another outline code definition
var codeDefinition2 = new OutlineCodeDefinition
{
Alias = "New outline code 2", FieldId = ((int)ExtendedAttributeTask.OutlineCode2).ToString(), FieldName = "Outline Code2"
};
// and then copy outline values
var outlineValues = new OutlineValue[codeDefinition.Values.Count];
codeDefinition.Values.CopyTo(outlineValues, 0);
foreach (var outlineValue in outlineValues)
{
codeDefinition2.Values.Add(outlineValue);
}
// ExEnd
}
}
} | 39.533333 | 166 | 0.551433 | [
"MIT"
] | aspose-tasks/Aspose.Tasks-for-.NET | Examples/CSharp/ExOutlineValueCollection.cs | 4,153 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace System
{
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public readonly struct Int16 : IComparable, IConvertible, IFormattable, IComparable<short>, IEquatable<short>, ISpanFormattable
{
private readonly short m_value; // Do not rename (binary serialization)
public const short MaxValue = (short)0x7FFF;
public const short MinValue = unchecked((short)0x8000);
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type Int16, this method throws an ArgumentException.
//
public int CompareTo(object value)
{
if (value == null)
{
return 1;
}
if (value is short)
{
return m_value - ((short)value).m_value;
}
throw new ArgumentException(SR.Arg_MustBeInt16);
}
public int CompareTo(short value)
{
return m_value - value;
}
public override bool Equals(object obj)
{
if (!(obj is short))
{
return false;
}
return m_value == ((short)obj).m_value;
}
[NonVersionable]
public bool Equals(short obj)
{
return m_value == obj;
}
// Returns a HashCode for the Int16
public override int GetHashCode()
{
return ((int)((ushort)m_value) | (((int)m_value) << 16));
}
public override string ToString()
{
return Number.FormatInt32(m_value, null, null);
}
public string ToString(IFormatProvider provider)
{
return Number.FormatInt32(m_value, null, provider);
}
public string ToString(string format)
{
return ToString(format, null);
}
public string ToString(string format, IFormatProvider provider)
{
if (m_value < 0 && format != null && format.Length > 0 && (format[0] == 'X' || format[0] == 'x'))
{
uint temp = (uint)(m_value & 0x0000FFFF);
return Number.FormatUInt32(temp, format, provider);
}
return Number.FormatInt32(m_value, format, provider);
}
public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null)
{
if (m_value < 0 && format.Length > 0 && (format[0] == 'X' || format[0] == 'x'))
{
uint temp = (uint)(m_value & 0x0000FFFF);
return Number.TryFormatUInt32(temp, format, provider, destination, out charsWritten);
}
return Number.TryFormatInt32(m_value, format, provider, destination, out charsWritten);
}
public static short Parse(string s)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Parse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
public static short Parse(string s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Parse((ReadOnlySpan<char>)s, style, NumberFormatInfo.CurrentInfo);
}
public static short Parse(string s, IFormatProvider provider)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Parse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
public static short Parse(string s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Parse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider));
}
public static short Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Parse(s, style, NumberFormatInfo.GetInstance(provider));
}
private static short Parse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info)
{
int i = 0;
try
{
i = Number.ParseInt32(s, style, info);
}
catch (OverflowException e)
{
throw new OverflowException(SR.Overflow_Int16, e);
}
// We need this check here since we don't allow signs to specified in hex numbers. So we fixup the result
// for negative numbers
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{ // We are parsing a hexadecimal number
if ((i < 0) || (i > ushort.MaxValue))
{
throw new OverflowException(SR.Overflow_Int16);
}
return (short)i;
}
if (i < MinValue || i > MaxValue) throw new OverflowException(SR.Overflow_Int16);
return (short)i;
}
public static bool TryParse(string s, out short result)
{
if (s == null)
{
result = 0;
return false;
}
return TryParse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
public static bool TryParse(ReadOnlySpan<char> s, out short result)
{
return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out short result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null)
{
result = 0;
return false;
}
return TryParse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider), out result);
}
public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out short result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out short result)
{
result = 0;
int i;
if (!Number.TryParseInt32(s, style, info, out i))
{
return false;
}
// We need this check here since we don't allow signs to specified in hex numbers. So we fixup the result
// for negative numbers
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{ // We are parsing a hexadecimal number
if ((i < 0) || i > ushort.MaxValue)
{
return false;
}
result = (short)i;
return true;
}
if (i < MinValue || i > MaxValue)
{
return false;
}
result = (short)i;
return true;
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.Int16;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(m_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(m_value);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(m_value);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(m_value);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return m_value;
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(m_value);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(m_value);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(m_value);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(m_value);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(m_value);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(m_value);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(m_value);
}
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(m_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int16", "DateTime"));
}
object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| 32.698413 | 145 | 0.576505 | [
"MIT"
] | AndreyAkinshin/corefx | src/Common/src/CoreLib/System/Int16.cs | 10,300 | C# |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System.Globalization;
using System.Threading;
namespace NLog
{
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Internal.Fakeables;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
/// <summary>
/// Creates and manages instances of <see cref="T:NLog.Logger" /> objects.
/// </summary>
public sealed class LogManager
{
private static readonly LogFactory globalFactory = new LogFactory();
private static IAppDomain _currentAppDomain;
private static GetCultureInfo _defaultCultureInfo = () => CultureInfo.CurrentCulture;
/// <summary>
/// Delegate used to the the culture to use.
/// </summary>
/// <returns></returns>
public delegate CultureInfo GetCultureInfo();
#if !SILVERLIGHT && !MONO
/// <summary>
/// Initializes static members of the LogManager class.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Significant logic in .cctor()")]
static LogManager()
{
try
{
SetupTerminationEvents();
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Warn("Error setting up termiation events: {0}", exception);
}
}
#endif
/// <summary>
/// Prevents a default instance of the LogManager class from being created.
/// </summary>
private LogManager()
{
}
/// <summary>
/// Occurs when logging <see cref="Configuration" /> changes.
/// </summary>
public static event EventHandler<LoggingConfigurationChangedEventArgs> ConfigurationChanged
{
add { globalFactory.ConfigurationChanged += value; }
remove { globalFactory.ConfigurationChanged -= value; }
}
#if !SILVERLIGHT
/// <summary>
/// Occurs when logging <see cref="Configuration" /> gets reloaded.
/// </summary>
public static event EventHandler<LoggingConfigurationReloadedEventArgs> ConfigurationReloaded
{
add { globalFactory.ConfigurationReloaded += value; }
remove { globalFactory.ConfigurationReloaded -= value; }
}
#endif
/// <summary>
/// Gets or sets a value indicating whether NLog should throw exceptions.
/// By default exceptions are not thrown under any circumstances.
/// </summary>
public static bool ThrowExceptions
{
get { return globalFactory.ThrowExceptions; }
set { globalFactory.ThrowExceptions = value; }
}
internal static IAppDomain CurrentAppDomain
{
get { return _currentAppDomain ?? (_currentAppDomain = AppDomainWrapper.CurrentDomain); }
set
{
#if !SILVERLIGHT
_currentAppDomain.DomainUnload -= TurnOffLogging;
_currentAppDomain.ProcessExit -= TurnOffLogging;
#endif
_currentAppDomain = value;
}
}
/// <summary>
/// Gets or sets the current logging configuration.
/// </summary>
public static LoggingConfiguration Configuration
{
get { return globalFactory.Configuration; }
set { globalFactory.Configuration = value; }
}
/// <summary>
/// Gets or sets the global log threshold. Log events below this threshold are not logged.
/// </summary>
public static LogLevel GlobalThreshold
{
get { return globalFactory.GlobalThreshold; }
set { globalFactory.GlobalThreshold = value; }
}
/// <summary>
/// Gets or sets the default culture to use.
/// </summary>
public static GetCultureInfo DefaultCultureInfo
{
get { return _defaultCultureInfo; }
set { _defaultCultureInfo = value; }
}
/// <summary>
/// Gets the logger named after the currently-being-initialized class.
/// </summary>
/// <returns>The logger.</returns>
/// <remarks>This is a slow-running method.
/// Make sure you're not doing this in a loop.</remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
public static Logger GetCurrentClassLogger()
{
string loggerName;
Type declaringType;
int framesToSkip = 1;
do
{
#if SILVERLIGHT
StackFrame frame = new StackTrace().GetFrame(framesToSkip);
#else
StackFrame frame = new StackFrame(framesToSkip, false);
#endif
var method = frame.GetMethod();
declaringType = method.DeclaringType;
if (declaringType == null)
{
loggerName = method.Name;
break;
}
framesToSkip++;
loggerName = declaringType.FullName;
} while (declaringType.Module.Name.Equals("mscorlib.dll", StringComparison.OrdinalIgnoreCase));
return globalFactory.GetLogger(loggerName);
}
/// <summary>
/// Gets the logger named after the currently-being-initialized class.
/// </summary>
/// <param name="loggerType">The logger class. The class must inherit from <see cref="Logger" />.</param>
/// <returns>The logger.</returns>
/// <remarks>This is a slow-running method.
/// Make sure you're not doing this in a loop.</remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
public static Logger GetCurrentClassLogger(Type loggerType)
{
Type declaringType;
int framesToSkip = 1;
do
{
#if SILVERLIGHT
StackFrame frame = new StackTrace().GetFrame(framesToSkip);
#else
StackFrame frame = new StackFrame(framesToSkip, false);
#endif
declaringType = frame.GetMethod().DeclaringType;
framesToSkip++;
} while (declaringType.Module.Name.Equals("mscorlib.dll", StringComparison.OrdinalIgnoreCase));
return globalFactory.GetLogger(declaringType.FullName, loggerType);
}
/// <summary>
/// Creates a logger that discards all log messages.
/// </summary>
/// <returns>Null logger which discards all log messages.</returns>
public static Logger CreateNullLogger()
{
return globalFactory.CreateNullLogger();
}
/// <summary>
/// Gets the specified named logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the same argument aren't guaranteed to return the same logger reference.</returns>
public static Logger GetLogger(string name)
{
return globalFactory.GetLogger(name);
}
/// <summary>
/// Gets the specified named logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <param name="loggerType">The logger class. The class must inherit from <see cref="Logger" />.</param>
/// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the same argument aren't guaranteed to return the same logger reference.</returns>
public static Logger GetLogger(string name, Type loggerType)
{
return globalFactory.GetLogger(name, loggerType);
}
/// <summary>
/// Loops through all loggers previously returned by GetLogger.
/// and recalculates their target and filter list. Useful after modifying the configuration programmatically
/// to ensure that all loggers have been properly configured.
/// </summary>
public static void ReconfigExistingLoggers()
{
globalFactory.ReconfigExistingLoggers();
}
#if !SILVERLIGHT
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
public static void Flush()
{
globalFactory.Flush();
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(TimeSpan timeout)
{
globalFactory.Flush(timeout);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(int timeoutMilliseconds)
{
globalFactory.Flush(timeoutMilliseconds);
}
#endif
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
public static void Flush(AsyncContinuation asyncContinuation)
{
globalFactory.Flush(asyncContinuation);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(AsyncContinuation asyncContinuation, TimeSpan timeout)
{
globalFactory.Flush(asyncContinuation, timeout);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(AsyncContinuation asyncContinuation, int timeoutMilliseconds)
{
globalFactory.Flush(asyncContinuation, timeoutMilliseconds);
}
/// <summary>Decreases the log enable counter and if it reaches -1
/// the logs are disabled.</summary>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
/// <returns>An object that iplements IDisposable whose Dispose() method
/// reenables logging. To be used with C# <c>using ()</c> statement.</returns>
public static IDisposable DisableLogging()
{
return globalFactory.DisableLogging();
}
/// <summary>Increases the log enable counter and if it reaches 0 the logs are disabled.</summary>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
public static void EnableLogging()
{
globalFactory.EnableLogging();
}
/// <summary>
/// Returns <see langword="true" /> if logging is currently enabled.
/// </summary>
/// <returns>A value of <see langword="true" /> if logging is currently enabled,
/// <see langword="false"/> otherwise.</returns>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
public static bool IsLoggingEnabled()
{
return globalFactory.IsLoggingEnabled();
}
/// <summary>
/// Dispose all targets, and shutdown logging.
/// </summary>
public static void Shutdown()
{
foreach (var target in Configuration.AllTargets)
{
target.Dispose();
}
}
#if !SILVERLIGHT && !MONO
private static void SetupTerminationEvents()
{
CurrentAppDomain.ProcessExit += TurnOffLogging;
CurrentAppDomain.DomainUnload += TurnOffLogging;
}
private static void TurnOffLogging(object sender, EventArgs args)
{
// reset logging configuration to null
// this causes old configuration (if any) to be closed.
InternalLogger.Info("Shutting down logging...");
Configuration = null;
InternalLogger.Info("Logger has been shut down.");
}
#endif
}
}
| 38.18254 | 183 | 0.627105 | [
"BSD-3-Clause"
] | ilivewithian/NLog | src/NLog/LogManager.cs | 14,433 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System;
using IdentityServer4;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
namespace IdentityServer
{
public class Startup
{
public IHostingEnvironment Environment { get; }
private IConfiguration configuration { get; set; }
public Startup(IHostingEnvironment environment, IConfiguration config)
{
Environment = environment;
configuration = config;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_1);
var builder = services.AddIdentityServer()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApis())
.AddInMemoryClients(Config.GetClients())
.AddTestUsers(Config.GetUsers());
if (Environment.IsDevelopment())
{
builder.AddDeveloperSigningCredential();
}
else
{
throw new Exception("need to configure key material");
}
services.AddAuthentication()
.AddGoogle("Google", options =>
{
options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
options.ClientId = configuration["Authentication:Google:ClientId"];
options.ClientSecret = configuration["Authentication:Google:ClientSecret"];
})
.AddOpenIdConnect("oidc", "OpenID Connect", options =>
{
options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
options.SignOutScheme = IdentityServerConstants.SignoutScheme;
options.SaveTokens = true;
options.Authority = "https://demo.identityserver.io/";
options.ClientId = "implicit";
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
RoleClaimType = "role"
};
});
}
public void Configure(IApplicationBuilder app)
{
if (Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseIdentityServer();
app.UseMvcWithDefaultRoute();
}
}
} | 35.059524 | 113 | 0.595246 | [
"Apache-2.0"
] | molnarln/IdentityServer4 | samples/Quickstarts/5_HybridFlowAuthenticationWithApiAccess/src/IdentityServer/Startup.cs | 2,947 | C# |
namespace Katameros.Enums
{
// Each value correspond to the Id in the Feasts Table
public enum Feast
{
NONE = -1,
Christmas = 1,
Ascension = 2,
LazarusSaturday = 3,
PalmSunday = 4,
PaschaMonday = 5,
PaschaTuesday = 6,
PaschaWednesday = 7,
PaschaThursday = 8,
PaschaFriday = 9,
TempleEntrance = 10,
EgyptEntrance = 11,
Annunciation = 12,
Cross = 13,
FastOfNinevah = 14,
Jonas = 15,
NativityParamoun = 16,
TheophanyParamoun = 17,
Theophany = 18,
WeddingOfCana = 19,
GreatLentPreparationSaturday = 20,
GreatLentPreparationSunday = 21,
Easter = 22,
}
}
| 25.16129 | 59 | 0.520513 | [
"MIT"
] | pierresaid/katameros-api | API/Enums/Feast.cs | 782 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using JetBrains.Annotations;
namespace LinqToDB
{
using Mapping;
using Extensions;
using SqlQuery;
partial class Sql
{
/// <summary>
/// An Attribute that allows custom Expressions to be defined
/// for a Method used within a Linq Expression.
/// </summary>
[PublicAPI]
[Serializable]
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
public class ExpressionAttribute : Attribute
{
/// <summary>
/// Creates an Expression that will be used in SQL,
/// in place of the method call decorated by this attribute.
/// </summary>
/// <param name="expression">The SQL expression. Use {0},{1}... for parameters given to the method call.</param>
public ExpressionAttribute(string? expression)
{
Expression = expression;
Precedence = SqlQuery.Precedence.Primary;
IsPure = true;
}
/// <summary>
/// Creates an Expression that will be used in SQL,
/// in place of the method call decorated by this attribute.
/// </summary>
/// <param name="expression">The SQL expression. Use {0},{1}... for parameters given to the method call.</param>
/// <param name="argIndices">Used for setting the order of the method arguments
/// being passed into the function.</param>
public ExpressionAttribute(string expression, params int[] argIndices)
{
Expression = expression;
ArgIndices = argIndices;
Precedence = SqlQuery.Precedence.Primary;
IsPure = true;
}
/// <summary>
/// Creates an Expression that will be used in SQL,
/// for the <see cref="ProviderName"/> specified,
/// in place of the method call decorated by this attribute.
/// </summary>
/// <param name="expression">The SQL expression. Use {0},{1}... for parameters given to the method call.</param>
/// <param name="configuration">The Database configuration for which this Expression will be used.</param>
public ExpressionAttribute(string configuration, string expression)
{
Configuration = configuration;
Expression = expression;
Precedence = SqlQuery.Precedence.Primary;
IsPure = true;
}
/// <summary>
/// Creates an Expression that will be used in SQL,
/// for the <see cref="ProviderName"/> specified,
/// in place of the method call decorated by this attribute.
/// </summary>
/// <param name="expression">The SQL expression. Use {0},{1}... for parameters given to the method call.</param>
/// <param name="configuration">The Database configuration for which this Expression will be used.</param>
/// <param name="argIndices">Used for setting the order of the method arguments
/// being passed into the function.</param>
public ExpressionAttribute(string configuration, string expression, params int[] argIndices)
{
Configuration = configuration;
Expression = expression;
ArgIndices = argIndices;
Precedence = SqlQuery.Precedence.Primary;
IsPure = true;
}
/// <summary>
/// The expression to be used in building the SQL.
/// </summary>
public string? Expression { get; set; }
/// <summary>
/// The order of Arguments to be passed
/// into the function from the method call.
/// </summary>
public int[]? ArgIndices { get; set; }
/// <summary>
/// Determines the priority of the expression in evaluation.
/// Refer to <see cref="LinqToDB.SqlQuery.Precedence"/>.
/// </summary>
public int Precedence { get; set; }
/// <summary>
/// If <c>null</c>, this will be treated as the default
/// evaluation for the expression. If set to a <see cref="ProviderName"/>,
/// It will only be used for that provider configuration.
/// </summary>
public string? Configuration { get; set; }
/// <summary>
/// If <c>true</c> The expression will only be evaluated on the
/// database server. If it cannot, an exception will
/// be thrown.
/// </summary>
public bool ServerSideOnly { get; set; }
/// <summary>
/// If <c>true</c> a greater effort will be made to execute
/// the expression on the DB server instead of in .NET.
/// </summary>
public bool PreferServerSide { get; set; }
/// <summary>
/// If <c>true</c> inline all parameters passed into the expression.
/// </summary>
public bool InlineParameters { get; set; }
/// <summary>
/// Used internally by <see cref="ExtensionAttribute"/>.
/// </summary>
public bool ExpectExpression { get; set; }
/// <summary>
/// If <c>true</c> the expression is treated as a Predicate
/// And when used in a Where clause will not have
/// an added comparison to 'true' in the database.
/// </summary>
public bool IsPredicate { get; set; }
/// <summary>
/// If <c>true</c>, this expression represents an aggregate result
/// Examples would be SUM(),COUNT().
/// </summary>
public bool IsAggregate { get; set; }
/// <summary>
/// If <c>true</c>, it notifies SQL Optimizer that expression returns same result if the same values/parameters are used. It gives optimizer additional information how to simplify query.
/// For example ORDER BY PureFunction("Str") can be removed because PureFunction function uses constant value.
/// <example>
/// For example Random function is NOT Pure function because it returns different result all time.
/// But expression <see cref="Sql.CurrentTimestamp"/> is Pure in case of executed query.
/// <see cref="Sql.DateAdd(LinqToDB.Sql.DateParts,System.Nullable{double},System.Nullable{System.DateTime})"/> is also Pure function because it returns the same result with the same parameters.
/// </example>
/// </summary>
public bool IsPure { get; set; }
/// <summary>
/// Used to determine whether the return type should be treated as
/// something that can be null If CanBeNull is not explicitly set.
/// <para>Default is <see cref="IsNullableType.Undefined"/>,
/// which will be treated as <c>true</c></para>
/// </summary>
public IsNullableType IsNullable { get; set; }
internal bool? _canBeNull;
/// <summary>
/// If <c>true</c>, result can be null
/// </summary>
public bool CanBeNull
{
get => _canBeNull ?? true;
set => _canBeNull = value;
}
protected bool GetCanBeNull(ISqlExpression[] parameters)
{
if (_canBeNull != null)
return _canBeNull.Value;
return CalcCanBeNull(IsNullable, parameters.Select(p => p.CanBeNull)) ?? true;
}
public static bool? CalcCanBeNull(IsNullableType isNullable, IEnumerable<bool> nullInfo)
{
switch (isNullable)
{
case IsNullableType.Undefined : return null;
case IsNullableType.Nullable : return true;
case IsNullableType.NotNullable : return false;
}
var parameters = nullInfo.ToArray();
switch (isNullable)
{
case IsNullableType.SameAsFirstParameter : return SameAs(0);
case IsNullableType.SameAsSecondParameter : return SameAs(1);
case IsNullableType.SameAsThirdParameter : return SameAs(2);
case IsNullableType.SameAsLastParameter : return SameAs(parameters.Length - 1);
case IsNullableType.IfAnyParameterNullable : return parameters.Any(p => p);
}
bool SameAs(int parameterNumber)
{
if (parameterNumber >= 0 && parameters.Length > parameterNumber)
return parameters[parameterNumber];
return true;
}
return null;
}
protected ISqlExpression[] ConvertArgs(MemberInfo member, ISqlExpression[] args)
{
if (member is MethodInfo method)
{
if (method.DeclaringType!.IsGenericType)
args = args.Concat(method.DeclaringType.GetGenericArguments().Select(t => (ISqlExpression)SqlDataType.GetDataType(t))).ToArray();
if (method.IsGenericMethod)
args = args.Concat(method.GetGenericArguments().Select(t => (ISqlExpression)SqlDataType.GetDataType(t))).ToArray();
}
if (ArgIndices != null)
{
var idxs = new ISqlExpression[ArgIndices.Length];
for (var i = 0; i < ArgIndices.Length; i++)
idxs[i] = args[ArgIndices[i]];
return idxs;
}
return args;
}
public virtual ISqlExpression GetExpression(MemberInfo member, params ISqlExpression[] args)
{
var sqlExpressions = ConvertArgs(member, args);
return new SqlExpression(member.GetMemberType(), Expression ?? member.Name, Precedence,
IsAggregate, IsPure, sqlExpressions)
{
CanBeNull = GetCanBeNull(sqlExpressions)
};
}
public virtual ISqlExpression? GetExpression(IDataContext dataContext, SelectQuery query,
Expression expression, Func<Expression, ColumnDescriptor?, ISqlExpression> converter)
{
return null;
}
public virtual bool GetIsPredicate(Expression expression) => IsPredicate;
}
}
}
| 37.754032 | 199 | 0.644345 | [
"MIT"
] | Corey-M/linq2db | Source/LinqToDB/Sql/Sql.ExpressionAttribute.cs | 9,118 | C# |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
// ReSharper disable once CheckNamespace
namespace DlibDotNet
{
public static partial class Dlib
{
internal sealed partial class Native
{
[DllImport(NativeMethods.NativeDnnLibrary, CallingConvention = NativeMethods.CallingConvention)]
public static extern ErrorType input_rgb_image_pyramid_new(PyramidType pyramidType,
uint pyramidRate,
out IntPtr ret);
[DllImport(NativeMethods.NativeDnnLibrary, CallingConvention = NativeMethods.CallingConvention)]
public static extern void input_rgb_image_pyramid_delete(IntPtr input,
PyramidType pyramidType,
uint pyramidRate);
[DllImport(NativeMethods.NativeDnnLibrary, CallingConvention = NativeMethods.CallingConvention)]
public static extern ErrorType input_rgb_image_pyramid_to_tensor(IntPtr input,
PyramidType pyramidType,
uint pyramidRate,
MatrixElementType elementType,
IntPtr matrix,
int templateRows,
int templateColumns,
uint iteratorCount,
IntPtr tensor);
[DllImport(NativeMethods.NativeDnnLibrary, CallingConvention = NativeMethods.CallingConvention)]
public static extern ErrorType input_rgb_image_pyramid_get_pyramid_padding(IntPtr input,
PyramidType pyramidType,
uint pyramidRate,
out uint pyramidPadding);
[DllImport(NativeMethods.NativeDnnLibrary, CallingConvention = NativeMethods.CallingConvention)]
public static extern ErrorType input_rgb_image_pyramid_get_pyramid_outer_padding(IntPtr input,
PyramidType pyramidType,
uint pyramidRate,
out uint pyramidOuterPadding);
[DllImport(NativeMethods.NativeDnnLibrary, CallingConvention = NativeMethods.CallingConvention)]
public static extern ErrorType input_rgb_image_pyramid_image_space_to_tensor_space(IntPtr input,
PyramidType pyramidType,
uint pyramidRate,
IntPtr data,
double scale,
IntPtr r,
out IntPtr rect);
}
}
}
| 63.953125 | 124 | 0.386025 | [
"MIT"
] | dongshengfengniaowu/DlibDotNet | src/DlibDotNet/Dnn/Dlib.cs | 4,095 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameStatePlay : State {
public GameStatePlay(Game game) {
_game = game;
}
public override void enter() {
_game._GameMenu._ButtonNewRound.Enabled = true;
_game._GameMenu._ButtonRestart.Enabled = true;
DeckDrag.Instance.autoMoveCardAndSwitchDeckCardToFinalDeck();
RoundTime = 0;
_roundTimerId = Timer.Instance.setInterval(1.0f, onRoundTimerUpdate);
}
void onRoundTimerUpdate() {
_game._GameTopMenu.setRoundTime(++RoundTime);
}
public override void exit() {
_game._GameMenu._ButtonRestart.Enabled = false;
RoundTime = -1;
Timer.Instance.clearTimeOut(_roundTimerId);
}
int RoundTime {
get { return _roundTime; }
set {
_roundTime = value;
_game._GameTopMenu.setRoundTime(_roundTime);
}
}
int _roundTime = 0;
int _roundTimerId = -1;
Game _game;
}
| 23.790698 | 77 | 0.641251 | [
"MIT"
] | wood9366/freecell | Assets/scripts/game/GameStatePlay.cs | 1,025 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BasicCrud.Models;
using BasicCrud.Services;
using BasicCrud.Utils;
using Microsoft.AspNetCore.Mvc;
namespace BasicCrud.Controllers
{
public class ViewController : Controller
{
/// <summary>
/// Used to interact with the food database
/// </summary>
private readonly FoodService _foodService;
public ViewController(FoodService foodService)
{
_foodService = foodService;
}
[HttpGet]
public async Task<IActionResult> Index(ViewViewModel model)
{
if (ModelState.IsValid)
{
// make sure we normalize the name if it's provided
if (model.Filter.Name != null)
{
model.Filter.Name = model.Filter.Name.PrepForDb();
}
// grab the foods that match the filter, ordered by the name
model.Foods = await _foodService.GetFilteredAsync(model.Filter, food => food.Name);
}
else
{
ModelState.AddModelError("", "Invalid input.");
}
return View(model);
}
}
} | 28.652174 | 100 | 0.549317 | [
"MIT"
] | collenirwin/BasicCrudExample | BasicCrud/Controllers/ViewController.cs | 1,320 | C# |
using Nez;
using Nez.Sprites;
using Nez.Textures;
using System.Linq;
namespace IceCreamJam.Components {
class CivilianComponent : Component {
private SpriteAnimator animator;
public override void OnAddedToEntity() {
base.OnAddedToEntity();
animator = Entity.GetComponent<SpriteAnimator>();
InitializeAnimations();
}
private void InitializeAnimations() {
var n = Random.NextInt(20);
var texture = Entity.Scene.Content.LoadTexture(ContentPaths.CivilianSheet);
var sprites = Sprite.SpritesFromAtlas(texture, 32, 32).Where((s, i) => i % 20 == n).ToList();
// TODO: Separate idle into blink and eyes open (blink periodically)
animator.AddAnimation("Idle", 3, Utility.SelectFromList(sprites, 0, 0, 0, 1, 2).ToArray());
animator.AddAnimation("Shock", Utility.SelectFromList(sprites, 5, 6, 7, 7).ToArray());
animator.AddAnimation("Celebration", 2, Utility.SelectFromList(sprites, 9, 10, 10, 10).ToArray());
animator.AddAnimation("Walking", sprites.GetRange(11, 6).ToArray());
animator.Play("Idle");
}
}
}
| 31.264706 | 101 | 0.709313 | [
"MIT"
] | Fungeey/IceCreamJam | IceCreamJam/IceCreamJam/Source/Components/NPC/CivilianComponent.cs | 1,065 | C# |
namespace Mailjet.Client.Resources
{
public static class ContactslistImportlist
{
public static readonly ResourceInfo Resource = new ResourceInfo("contactslist", "ImportList");
public const string Action = "Action";
public const string ListID = "ListID";
}
}
| 22.923077 | 102 | 0.687919 | [
"MIT"
] | Delly1313/mailjet-apiv3-dotnet | Mailjet.Client/Resources/ContactslistImportlist.cs | 298 | C# |
using Cysharp.Threading.Tasks;
using System;
using System.Collections.Concurrent;
using System.Threading;
using UniRx;
using UnityEngine;
namespace kumaS.Tracker.Core
{
/// <summary>
/// スケジュール可能なストリームの基底クラス。
/// </summary>
/// <typeparam name="TInput">入力のデータ型。</typeparam>
/// <typeparam name="TOutput">出力のデータ型。</typeparam>
public abstract class ScheduleStreamBase<TInput, TOutput> : MonoBehaviour, IScheduleStream
{
/// <summary>
/// このプロセスの名前。初期化をさせるため抽象化。
/// </summary>
public abstract string ProcessName { get; set; }
/// <summary>
/// このノードのId。スケジューラーに設定されるので設定はそちらに任せる。
/// </summary>
public int Id { get; set; }
/// <summary>
/// ストリームで管理が必要な型で、このクラスで使う型。
/// </summary>
public abstract Type[] UseType { get; }
/// <value>
/// スレッドが利用可能か。
/// </value>
private bool[] isThreadAvailable;
/// <value>
/// スレッドが開くのを待つキュー。
/// </value>
private readonly ConcurrentQueue<CancellationTokenSource> waitingQueue = new ConcurrentQueue<CancellationTokenSource>();
/// <value>
/// デバッグ出力をするか。
/// </value>
public BoolReactiveProperty isDebug = new BoolReactiveProperty(true);
/// <summary>
/// デバッグ出力をするか。
/// </summary>
public IReadOnlyReactiveProperty<bool> IsDebug { get => isDebug; }
/// <summary>
/// デバッグで出力するデータのキーを取得できるようにする。
/// </summary>
public abstract string[] DebugKey { get; }
/// <summary>
/// 現在利用可能か。初期化が終わったら<c>true</c>を返すようにするのを忘れずに。
/// </summary>
public abstract IReadOnlyReactiveProperty<bool> IsAvailable { get; }
/// <summary>
/// 入力のデータ型。
/// </summary>
public Type InputType { get => typeof(TInput); }
/// <summary>
/// 出力するデータ型。(ストリーム)
/// </summary>
public Type OutputType { get => typeof(TOutput); }
/// <summary>
/// 初期化。
/// </summary>
/// <param name="thread">用意するスレッド数。</param>
/// <param name="token">停止しようとしたかの通知。</param>
public void Init(int thread, CancellationToken token)
{
isThreadAvailable = new bool[thread];
for (var i = 0; i < thread; i++)
{
isThreadAvailable[i] = true;
}
InitInternal(thread, token);
}
/// <summary>
/// 派生クラスではここに初期化処理を書く。初期化が終わったら利用可能にするのを忘れずに。
/// </summary>
/// <param name="thread">用意するスレッド数。</param>
/// <param name="token">停止しようとしたかの通知。</param>
protected abstract void InitInternal(int thread, CancellationToken token);
/// <summary>
/// 処理をするプロセス。
/// </summary>
/// <param name="input">入力のストリーム。</param>
/// <returns>出力されるストリーム。</returns>
public IObservable<object> Process(IObservable<object> input)
{
return input.Cast<object, SchedulableData<TInput>>().Select(ProcessInternal).Cast<SchedulableData<TOutput>, object>();
}
/// <summary>
/// 処理をここに書く。ストリームをつなげる。(Hot変換はスケジューラー側でするのでこちらではしない。)
/// </summary>
/// <param name="input">このストリームにつなげる。</param>
/// <returns>つなげたストリームを返すようにする。</returns>
protected abstract SchedulableData<TOutput> ProcessInternal(SchedulableData<TInput> input);
/// <summary>
/// 使えるスレッドを取得。これを使ったらこちらで開放すること。<see cref="FreeThread"/>
/// </summary>
/// <param name="thread">取得したスレッド番号。</param>
/// <returns>スレッドを取得できたか。</returns>
/// <code>
/// if(TryGetThread(out var thread))
/// {
/// try
/// {
/// // 処理
/// }
/// finary
/// {
/// FreeThread(thread);
/// }
/// }
/// </code>
protected bool TryGetThread(out int thread)
{
lock (isThreadAvailable)
{
for (var i = 0; i < isThreadAvailable.Length; i++)
{
if (isThreadAvailable[i])
{
isThreadAvailable[i] = false;
thread = i;
return true;
}
}
}
thread = -1;
return false;
}
/// <summary>
/// スレッドを開放する。
/// </summary>
/// <param name="thread">解放するスレッド番号。</param>
protected void FreeThread(int thread)
{
lock (isThreadAvailable)
{
isThreadAvailable[thread] = true;
}
}
/// <summary>
/// デバッグで表示できる内容にする。
/// </summary>
/// <param name="data">この処理の後のデータ。</param>
/// <returns>デバッグで表示するデータ。</returns>
public IDebugMessage DebugLog(object data)
{
return DebugLogInternal((SchedulableData<TOutput>)data);
}
/// <summary>
/// デバッグで表示できる内容にする。
/// </summary>
/// <param name="data">この処理の後のデータ。</param>
/// <returns>デバッグで表示するデータ。</returns>
protected abstract IDebugMessage DebugLogInternal(SchedulableData<TOutput> data);
/// <summary>
/// 派生クラスではここにストリーム破棄時の処理を書く.
/// </summary>
public abstract void Dispose();
}
} | 30.637838 | 131 | 0.499118 | [
"Apache-2.0"
] | kumaS-nu/Tracking-in-Unity | Assets/kumaS/Tracker/Core/Runtime/ScheduleStreamBase.cs | 6,928 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("MakeARectangle")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MakeARectangle")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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")]
| 39.892857 | 96 | 0.755148 | [
"MIT"
] | SnareHanger/CSDX | ExampleSketch/Properties/AssemblyInfo.cs | 2,237 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Xml.Serialization
{
using System;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
internal sealed class XmlAttributeComparer : IComparer
{
public int Compare(object? o1, object? o2)
{
XmlAttribute a1 = (XmlAttribute)o1!;
XmlAttribute a2 = (XmlAttribute)o2!;
int ns = string.Compare(a1.NamespaceURI, a2.NamespaceURI, StringComparison.Ordinal);
if (ns == 0)
{
return string.Compare(a1.Name, a2.Name, StringComparison.Ordinal);
}
return ns;
}
}
internal sealed class XmlFacetComparer : IComparer
{
public int Compare(object? o1, object? o2)
{
XmlSchemaFacet f1 = (XmlSchemaFacet)o1!;
XmlSchemaFacet f2 = (XmlSchemaFacet)o2!;
return string.Compare(
f1.GetType().Name + ":" + f1.Value,
f2.GetType().Name + ":" + f2.Value,
StringComparison.Ordinal
);
}
}
internal sealed class QNameComparer : IComparer
{
public int Compare(object? o1, object? o2)
{
XmlQualifiedName qn1 = (XmlQualifiedName)o1!;
XmlQualifiedName qn2 = (XmlQualifiedName)o2!;
int ns = string.Compare(qn1.Namespace, qn2.Namespace, StringComparison.Ordinal);
if (ns == 0)
{
return string.Compare(qn1.Name, qn2.Name, StringComparison.Ordinal);
}
return ns;
}
}
internal sealed class XmlSchemaObjectComparer : IComparer
{
private readonly QNameComparer _comparer = new QNameComparer();
public int Compare(object? o1, object? o2)
{
return _comparer.Compare(NameOf((XmlSchemaObject?)o1), NameOf((XmlSchemaObject?)o2));
}
internal static XmlQualifiedName NameOf(XmlSchemaObject? o)
{
if (o is XmlSchemaAttribute)
{
return ((XmlSchemaAttribute)o).QualifiedName;
}
else if (o is XmlSchemaAttributeGroup)
{
return ((XmlSchemaAttributeGroup)o).QualifiedName;
}
else if (o is XmlSchemaComplexType)
{
return ((XmlSchemaComplexType)o).QualifiedName;
}
else if (o is XmlSchemaSimpleType)
{
return ((XmlSchemaSimpleType)o).QualifiedName;
}
else if (o is XmlSchemaElement)
{
return ((XmlSchemaElement)o).QualifiedName;
}
else if (o is XmlSchemaGroup)
{
return ((XmlSchemaGroup)o).QualifiedName;
}
else if (o is XmlSchemaGroupRef)
{
return ((XmlSchemaGroupRef)o).RefName;
}
else if (o is XmlSchemaNotation)
{
return ((XmlSchemaNotation)o).QualifiedName;
}
else if (o is XmlSchemaSequence)
{
XmlSchemaSequence s = (XmlSchemaSequence)o;
if (s.Items.Count == 0)
return new XmlQualifiedName(".sequence", Namespace(o));
return NameOf(s.Items[0]);
}
else if (o is XmlSchemaAll)
{
XmlSchemaAll a = (XmlSchemaAll)o;
if (a.Items.Count == 0)
return new XmlQualifiedName(".all", Namespace(o));
return NameOf(a.Items);
}
else if (o is XmlSchemaChoice)
{
XmlSchemaChoice c = (XmlSchemaChoice)o;
if (c.Items.Count == 0)
return new XmlQualifiedName(".choice", Namespace(o));
return NameOf(c.Items);
}
else if (o is XmlSchemaAny)
{
return new XmlQualifiedName(
"*",
SchemaObjectWriter.ToString(((XmlSchemaAny)o).NamespaceList)
);
}
else if (o is XmlSchemaIdentityConstraint)
{
return ((XmlSchemaIdentityConstraint)o).QualifiedName;
}
return new XmlQualifiedName("?", Namespace(o));
}
internal static XmlQualifiedName NameOf(XmlSchemaObjectCollection items)
{
ArrayList list = new ArrayList();
for (int i = 0; i < items.Count; i++)
{
list.Add(NameOf(items[i]));
}
list.Sort(new QNameComparer());
return (XmlQualifiedName)list[0]!;
}
internal static string? Namespace(XmlSchemaObject? o)
{
while (o != null && !(o is XmlSchema))
{
o = o.Parent;
}
return o == null ? "" : ((XmlSchema)o).TargetNamespace;
}
}
internal sealed class SchemaObjectWriter
{
private readonly StringBuilder _w = new StringBuilder();
private int _indentLevel = -1;
private void WriteIndent()
{
for (int i = 0; i < _indentLevel; i++)
{
_w.Append(' ');
}
}
private void WriteAttribute(string localName, string ns, string? value)
{
if (value == null || value.Length == 0)
return;
_w.Append(',');
_w.Append(ns);
if (ns != null && ns.Length != 0)
_w.Append(':');
_w.Append(localName);
_w.Append('=');
_w.Append(value);
}
private void WriteAttribute(string localName, string ns, XmlQualifiedName value)
{
if (value.IsEmpty)
return;
WriteAttribute(localName, ns, value.ToString());
}
private void WriteStartElement(string name)
{
NewLine();
_indentLevel++;
_w.Append('[');
_w.Append(name);
}
private void WriteEndElement()
{
_w.Append(']');
_indentLevel--;
}
private void NewLine()
{
_w.Append(Environment.NewLine);
WriteIndent();
}
private string GetString()
{
return _w.ToString();
}
private void WriteAttribute(XmlAttribute a)
{
if (a.Value != null)
{
WriteAttribute(a.Name, a.NamespaceURI, a.Value);
}
}
private void WriteAttributes(XmlAttribute[]? a, XmlSchemaObject o)
{
if (a == null)
return;
ArrayList attrs = new ArrayList();
for (int i = 0; i < a.Length; i++)
{
attrs.Add(a[i]);
}
attrs.Sort(new XmlAttributeComparer());
for (int i = 0; i < attrs.Count; i++)
{
XmlAttribute attribute = (XmlAttribute)attrs[i]!;
WriteAttribute(attribute);
}
}
[return: NotNullIfNotNull("list")]
internal static string? ToString(NamespaceList? list)
{
if (list == null)
return null;
switch (list.Type)
{
case NamespaceList.ListType.Any:
return "##any";
case NamespaceList.ListType.Other:
return "##other";
case NamespaceList.ListType.Set:
ArrayList ns = new ArrayList();
foreach (string s in list.Enumerate)
{
ns.Add(s);
}
ns.Sort();
StringBuilder sb = new StringBuilder();
bool first = true;
foreach (string s in ns)
{
if (first)
{
first = false;
}
else
{
sb.Append(' ');
}
if (s.Length == 0)
{
sb.Append("##local");
}
else
{
sb.Append(s);
}
}
return sb.ToString();
default:
return list.ToString();
}
}
internal string WriteXmlSchemaObject(XmlSchemaObject? o)
{
if (o == null)
return string.Empty;
Write3_XmlSchemaObject((XmlSchemaObject?)o);
return GetString();
}
private void WriteSortedItems(XmlSchemaObjectCollection? items)
{
if (items == null)
return;
ArrayList list = new ArrayList();
for (int i = 0; i < items.Count; i++)
{
list.Add(items[i]);
}
list.Sort(new XmlSchemaObjectComparer());
for (int i = 0; i < list.Count; i++)
{
Write3_XmlSchemaObject((XmlSchemaObject?)list[i]);
}
}
private void Write1_XmlSchemaAttribute(XmlSchemaAttribute? o)
{
if (o is null)
return;
WriteStartElement("attribute");
WriteAttribute(@"id", @"", ((string?)o.@Id));
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
WriteAttribute(@"default", @"", ((string?)o.@DefaultValue));
WriteAttribute(@"fixed", @"", ((string?)o.@FixedValue));
if (o.Parent != null && !(o.Parent is XmlSchema))
{
if (
o.QualifiedName != null
&& !o.QualifiedName.IsEmpty
&& o.QualifiedName.Namespace != null
&& o.QualifiedName.Namespace.Length != 0
)
{
WriteAttribute(@"form", @"", "qualified");
}
else
{
WriteAttribute(@"form", @"", "unqualified");
}
}
WriteAttribute(@"name", @"", ((string?)o.@Name));
if (!o.RefName.IsEmpty)
{
WriteAttribute("ref", "", o.RefName);
}
else if (!o.SchemaTypeName.IsEmpty)
{
WriteAttribute("type", "", o.SchemaTypeName);
}
XmlSchemaUse use = o.Use == XmlSchemaUse.None ? XmlSchemaUse.Optional : o.Use;
WriteAttribute(@"use", @"", Write30_XmlSchemaUse(use));
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
Write9_XmlSchemaSimpleType((XmlSchemaSimpleType?)o.@SchemaType);
WriteEndElement();
}
private void Write3_XmlSchemaObject(XmlSchemaObject? o)
{
if (o is null)
return;
System.Type t = o.GetType();
if (t == typeof(XmlSchemaComplexType))
{
Write35_XmlSchemaComplexType((XmlSchemaComplexType)o);
return;
}
else if (t == typeof(XmlSchemaSimpleType))
{
Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o);
return;
}
else if (t == typeof(XmlSchemaElement))
{
Write46_XmlSchemaElement((XmlSchemaElement)o);
return;
}
else if (t == typeof(XmlSchemaAppInfo))
{
Write7_XmlSchemaAppInfo((XmlSchemaAppInfo)o);
return;
}
else if (t == typeof(XmlSchemaDocumentation))
{
Write6_XmlSchemaDocumentation((XmlSchemaDocumentation)o);
return;
}
else if (t == typeof(XmlSchemaAnnotation))
{
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o);
return;
}
else if (t == typeof(XmlSchemaGroup))
{
Write57_XmlSchemaGroup((XmlSchemaGroup)o);
return;
}
else if (t == typeof(XmlSchemaXPath))
{
Write49_XmlSchemaXPath("xpath", "", (XmlSchemaXPath)o);
return;
}
else if (t == typeof(XmlSchemaIdentityConstraint))
{
Write48_XmlSchemaIdentityConstraint((XmlSchemaIdentityConstraint)o);
return;
}
else if (t == typeof(XmlSchemaUnique))
{
Write51_XmlSchemaUnique((XmlSchemaUnique)o);
return;
}
else if (t == typeof(XmlSchemaKeyref))
{
Write50_XmlSchemaKeyref((XmlSchemaKeyref)o);
return;
}
else if (t == typeof(XmlSchemaKey))
{
Write47_XmlSchemaKey((XmlSchemaKey)o);
return;
}
else if (t == typeof(XmlSchemaGroupRef))
{
Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o);
return;
}
else if (t == typeof(XmlSchemaAny))
{
Write53_XmlSchemaAny((XmlSchemaAny)o);
return;
}
else if (t == typeof(XmlSchemaSequence))
{
Write54_XmlSchemaSequence((XmlSchemaSequence)o);
return;
}
else if (t == typeof(XmlSchemaChoice))
{
Write52_XmlSchemaChoice((XmlSchemaChoice)o);
return;
}
else if (t == typeof(XmlSchemaAll))
{
Write43_XmlSchemaAll((XmlSchemaAll)o);
return;
}
else if (t == typeof(XmlSchemaComplexContentRestriction))
{
Write56_XmlSchemaComplexContentRestriction((XmlSchemaComplexContentRestriction)o);
return;
}
else if (t == typeof(XmlSchemaComplexContentExtension))
{
Write42_XmlSchemaComplexContentExtension((XmlSchemaComplexContentExtension)o);
return;
}
else if (t == typeof(XmlSchemaSimpleContentRestriction))
{
Write40_XmlSchemaSimpleContentRestriction((XmlSchemaSimpleContentRestriction)o);
return;
}
else if (t == typeof(XmlSchemaSimpleContentExtension))
{
Write38_XmlSchemaSimpleContentExtension((XmlSchemaSimpleContentExtension)o);
return;
}
else if (t == typeof(XmlSchemaComplexContent))
{
Write41_XmlSchemaComplexContent((XmlSchemaComplexContent)o);
return;
}
else if (t == typeof(XmlSchemaSimpleContent))
{
Write36_XmlSchemaSimpleContent((XmlSchemaSimpleContent)o);
return;
}
else if (t == typeof(XmlSchemaAnyAttribute))
{
Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o);
return;
}
else if (t == typeof(XmlSchemaAttributeGroupRef))
{
Write32_XmlSchemaAttributeGroupRef((XmlSchemaAttributeGroupRef)o);
return;
}
else if (t == typeof(XmlSchemaAttributeGroup))
{
Write31_XmlSchemaAttributeGroup((XmlSchemaAttributeGroup)o);
return;
}
else if (t == typeof(XmlSchemaSimpleTypeRestriction))
{
Write15_XmlSchemaSimpleTypeRestriction((XmlSchemaSimpleTypeRestriction)o);
return;
}
else if (t == typeof(XmlSchemaSimpleTypeList))
{
Write14_XmlSchemaSimpleTypeList((XmlSchemaSimpleTypeList)o);
return;
}
else if (t == typeof(XmlSchemaSimpleTypeUnion))
{
Write12_XmlSchemaSimpleTypeUnion((XmlSchemaSimpleTypeUnion)o);
return;
}
else if (t == typeof(XmlSchemaAttribute))
{
Write1_XmlSchemaAttribute((XmlSchemaAttribute)o);
return;
}
}
private void Write5_XmlSchemaAnnotation(XmlSchemaAnnotation? o)
{
if (o is null)
return;
WriteStartElement("annotation");
WriteAttribute(@"id", @"", ((string?)o.@Id));
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
System.Xml.Schema.XmlSchemaObjectCollection a =
(System.Xml.Schema.XmlSchemaObjectCollection)o.@Items;
if (a != null)
{
for (int ia = 0; ia < a.Count; ia++)
{
XmlSchemaObject ai = (XmlSchemaObject)a[ia];
if (ai is XmlSchemaAppInfo)
{
Write7_XmlSchemaAppInfo((XmlSchemaAppInfo)ai);
}
else if (ai is XmlSchemaDocumentation)
{
Write6_XmlSchemaDocumentation((XmlSchemaDocumentation)ai);
}
}
}
WriteEndElement();
}
private void Write6_XmlSchemaDocumentation(XmlSchemaDocumentation o)
{
if (o is null)
return;
WriteStartElement("documentation");
WriteAttribute(@"source", @"", ((string?)o.@Source));
WriteAttribute(
@"lang",
@"http://www.w3.org/XML/1998/namespace",
((string?)o.@Language)
);
XmlNode?[]? a = (XmlNode?[]?)o.@Markup;
if (a != null)
{
for (int ia = 0; ia < a.Length; ia++)
{
XmlNode ai = (XmlNode)a[ia]!;
WriteStartElement("node");
WriteAttribute("xml", "", ai.OuterXml);
}
}
WriteEndElement();
}
private void Write7_XmlSchemaAppInfo(XmlSchemaAppInfo? o)
{
if (o is null)
return;
WriteStartElement("appinfo");
WriteAttribute("source", "", o.Source);
XmlNode?[]? a = (XmlNode?[]?)o.@Markup;
if (a != null)
{
for (int ia = 0; ia < a.Length; ia++)
{
XmlNode ai = (XmlNode)a[ia]!;
WriteStartElement("node");
WriteAttribute("xml", "", ai.OuterXml);
}
}
WriteEndElement();
}
private void Write9_XmlSchemaSimpleType(XmlSchemaSimpleType? o)
{
if (o is null)
return;
WriteStartElement("simpleType");
WriteAttribute(@"id", @"", ((string?)o.@Id));
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
WriteAttribute(@"name", @"", ((string?)o.@Name));
WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved));
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
if (o.@Content is XmlSchemaSimpleTypeUnion)
{
Write12_XmlSchemaSimpleTypeUnion((XmlSchemaSimpleTypeUnion)o.@Content);
}
else if (o.@Content is XmlSchemaSimpleTypeRestriction)
{
Write15_XmlSchemaSimpleTypeRestriction((XmlSchemaSimpleTypeRestriction)o.@Content);
}
else if (o.@Content is XmlSchemaSimpleTypeList)
{
Write14_XmlSchemaSimpleTypeList((XmlSchemaSimpleTypeList)o.@Content);
}
WriteEndElement();
}
private string Write11_XmlSchemaDerivationMethod(XmlSchemaDerivationMethod v)
{
return v.ToString();
}
private void Write12_XmlSchemaSimpleTypeUnion(XmlSchemaSimpleTypeUnion? o)
{
if (o is null)
return;
WriteStartElement("union");
WriteAttribute(@"id", @"", ((string?)o.@Id));
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
if (o.MemberTypes != null)
{
ArrayList list = new ArrayList();
for (int i = 0; i < o.MemberTypes.Length; i++)
{
list.Add(o.MemberTypes[i]);
}
list.Sort(new QNameComparer());
_w.Append(',');
_w.Append("memberTypes=");
for (int i = 0; i < list.Count; i++)
{
XmlQualifiedName q = (XmlQualifiedName)list[i]!;
_w.Append(q.ToString());
_w.Append(',');
}
}
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
WriteSortedItems(o.@BaseTypes);
WriteEndElement();
}
private void Write14_XmlSchemaSimpleTypeList(XmlSchemaSimpleTypeList o)
{
if (o is null)
return;
WriteStartElement("list");
WriteAttribute(@"id", @"", ((string?)o.@Id));
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
if (!o.@ItemTypeName.IsEmpty)
{
WriteAttribute(@"itemType", @"", o.@ItemTypeName);
}
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
Write9_XmlSchemaSimpleType((XmlSchemaSimpleType?)o.@ItemType);
WriteEndElement();
}
private void Write15_XmlSchemaSimpleTypeRestriction(XmlSchemaSimpleTypeRestriction? o)
{
if (o is null)
return;
WriteStartElement("restriction");
WriteAttribute(@"id", @"", ((string?)o.@Id));
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
if (!o.@BaseTypeName.IsEmpty)
{
WriteAttribute(@"base", @"", o.@BaseTypeName);
}
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
Write9_XmlSchemaSimpleType((XmlSchemaSimpleType?)o.@BaseType);
WriteFacets(o.Facets);
WriteEndElement();
}
private void WriteFacets(XmlSchemaObjectCollection? facets)
{
if (facets == null)
return;
ArrayList a = new ArrayList();
for (int i = 0; i < facets.Count; i++)
{
a.Add(facets[i]);
}
a.Sort(new XmlFacetComparer());
for (int ia = 0; ia < a.Count; ia++)
{
XmlSchemaObject? ai = (XmlSchemaObject?)a[ia];
if (ai is XmlSchemaMinExclusiveFacet)
{
Write_XmlSchemaFacet("minExclusive", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaMaxInclusiveFacet)
{
Write_XmlSchemaFacet("maxInclusive", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaMaxExclusiveFacet)
{
Write_XmlSchemaFacet("maxExclusive", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaMinInclusiveFacet)
{
Write_XmlSchemaFacet("minInclusive", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaLengthFacet)
{
Write_XmlSchemaFacet("length", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaEnumerationFacet)
{
Write_XmlSchemaFacet("enumeration", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaMinLengthFacet)
{
Write_XmlSchemaFacet("minLength", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaPatternFacet)
{
Write_XmlSchemaFacet("pattern", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaTotalDigitsFacet)
{
Write_XmlSchemaFacet("totalDigits", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaMaxLengthFacet)
{
Write_XmlSchemaFacet("maxLength", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaWhiteSpaceFacet)
{
Write_XmlSchemaFacet("whiteSpace", (XmlSchemaFacet)ai);
}
else if (ai is XmlSchemaFractionDigitsFacet)
{
Write_XmlSchemaFacet("fractionDigit", (XmlSchemaFacet)ai);
}
}
}
private void Write_XmlSchemaFacet(string name, XmlSchemaFacet? o)
{
if (o is null)
return;
WriteStartElement(name);
WriteAttribute("id", "", o.Id);
WriteAttribute("value", "", o.Value);
if (o.IsFixed)
{
WriteAttribute(@"fixed", @"", XmlConvert.ToString(o.IsFixed));
}
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
WriteEndElement();
}
private string? Write30_XmlSchemaUse(XmlSchemaUse v)
{
string? s = null;
switch (v)
{
case XmlSchemaUse.@Optional:
s = @"optional";
break;
case XmlSchemaUse.@Prohibited:
s = @"prohibited";
break;
case XmlSchemaUse.@Required:
s = @"required";
break;
default:
break;
}
return s;
}
private void Write31_XmlSchemaAttributeGroup(XmlSchemaAttributeGroup? o)
{
if (o is null)
return;
WriteStartElement("attributeGroup");
WriteAttribute(@"id", @"", ((string?)o.@Id));
WriteAttribute(@"name", @"", ((string?)o.@Name));
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
WriteSortedItems(o.Attributes);
Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute);
WriteEndElement();
}
private void Write32_XmlSchemaAttributeGroupRef(XmlSchemaAttributeGroupRef? o)
{
if (o is null)
return;
WriteStartElement("attributeGroup");
WriteAttribute(@"id", @"", ((string?)o.@Id));
if (!o.RefName.IsEmpty)
{
WriteAttribute("ref", "", o.RefName);
}
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
WriteEndElement();
}
private void Write33_XmlSchemaAnyAttribute(XmlSchemaAnyAttribute? o)
{
if (o is null)
return;
WriteStartElement("anyAttribute");
WriteAttribute(@"id", @"", ((string?)o.@Id));
WriteAttribute("namespace", "", ToString(o.NamespaceList));
XmlSchemaContentProcessing process =
o.@ProcessContents == XmlSchemaContentProcessing.@None
? XmlSchemaContentProcessing.Strict
: o.@ProcessContents;
WriteAttribute(@"processContents", @"", Write34_XmlSchemaContentProcessing(process));
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
WriteEndElement();
}
private string? Write34_XmlSchemaContentProcessing(XmlSchemaContentProcessing v)
{
string? s = null;
switch (v)
{
case XmlSchemaContentProcessing.@Skip:
s = @"skip";
break;
case XmlSchemaContentProcessing.@Lax:
s = @"lax";
break;
case XmlSchemaContentProcessing.@Strict:
s = @"strict";
break;
default:
break;
}
return s;
}
private void Write35_XmlSchemaComplexType(XmlSchemaComplexType o)
{
if (o is null)
return;
WriteStartElement("complexType");
WriteAttribute(@"id", @"", ((string?)o.@Id));
WriteAttribute(@"name", @"", ((string?)o.@Name));
WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved));
if (((bool)o.@IsAbstract) != false)
{
WriteAttribute(@"abstract", @"", XmlConvert.ToString((bool)((bool)o.@IsAbstract)));
}
WriteAttribute(@"block", @"", Write11_XmlSchemaDerivationMethod(o.BlockResolved));
if (((bool)o.@IsMixed) != false)
{
WriteAttribute(@"mixed", @"", XmlConvert.ToString((bool)((bool)o.@IsMixed)));
}
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
if (o.@ContentModel is XmlSchemaComplexContent)
{
Write41_XmlSchemaComplexContent((XmlSchemaComplexContent)o.@ContentModel);
}
else if (o.@ContentModel is XmlSchemaSimpleContent)
{
Write36_XmlSchemaSimpleContent((XmlSchemaSimpleContent)o.@ContentModel);
}
if (o.@Particle is XmlSchemaSequence)
{
Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle);
}
else if (o.@Particle is XmlSchemaGroupRef)
{
Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o.@Particle);
}
else if (o.@Particle is XmlSchemaChoice)
{
Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle);
}
else if (o.@Particle is XmlSchemaAll)
{
Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle);
}
WriteSortedItems(o.Attributes);
Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute);
WriteEndElement();
}
private void Write36_XmlSchemaSimpleContent(XmlSchemaSimpleContent? o)
{
if (o is null)
return;
WriteStartElement("simpleContent");
WriteAttribute(@"id", @"", ((string?)o.@Id));
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
if (o.@Content is XmlSchemaSimpleContentRestriction)
{
Write40_XmlSchemaSimpleContentRestriction(
(XmlSchemaSimpleContentRestriction)o.@Content
);
}
else if (o.@Content is XmlSchemaSimpleContentExtension)
{
Write38_XmlSchemaSimpleContentExtension(
(XmlSchemaSimpleContentExtension)o.@Content
);
}
WriteEndElement();
}
private void Write38_XmlSchemaSimpleContentExtension(XmlSchemaSimpleContentExtension o)
{
if (o is null)
return;
WriteStartElement("extension");
WriteAttribute(@"id", @"", ((string?)o.@Id));
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
if (!o.@BaseTypeName.IsEmpty)
{
WriteAttribute(@"base", @"", o.@BaseTypeName);
}
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
WriteSortedItems(o.Attributes);
Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute);
WriteEndElement();
}
private void Write40_XmlSchemaSimpleContentRestriction(XmlSchemaSimpleContentRestriction? o)
{
if (o is null)
return;
WriteStartElement("restriction");
WriteAttribute(@"id", @"", ((string?)o.@Id));
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
if (!o.@BaseTypeName.IsEmpty)
{
WriteAttribute(@"base", @"", o.@BaseTypeName);
}
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
Write9_XmlSchemaSimpleType((XmlSchemaSimpleType?)o.@BaseType);
WriteFacets(o.Facets);
WriteSortedItems(o.Attributes);
Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute);
WriteEndElement();
}
private void Write41_XmlSchemaComplexContent(XmlSchemaComplexContent? o)
{
if (o is null)
return;
WriteStartElement("complexContent");
WriteAttribute(@"id", @"", ((string?)o.@Id));
WriteAttribute(@"mixed", @"", XmlConvert.ToString((bool)((bool)o.@IsMixed)));
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
if (o.@Content is XmlSchemaComplexContentRestriction)
{
Write56_XmlSchemaComplexContentRestriction(
(XmlSchemaComplexContentRestriction)o.@Content
);
}
else if (o.@Content is XmlSchemaComplexContentExtension)
{
Write42_XmlSchemaComplexContentExtension(
(XmlSchemaComplexContentExtension)o.@Content
);
}
WriteEndElement();
}
private void Write42_XmlSchemaComplexContentExtension(XmlSchemaComplexContentExtension? o)
{
if (o is null)
return;
WriteStartElement("extension");
WriteAttribute(@"id", @"", ((string?)o.@Id));
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
if (!o.@BaseTypeName.IsEmpty)
{
WriteAttribute(@"base", @"", o.@BaseTypeName);
}
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
if (o.@Particle is XmlSchemaSequence)
{
Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle);
}
else if (o.@Particle is XmlSchemaGroupRef)
{
Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o.@Particle);
}
else if (o.@Particle is XmlSchemaChoice)
{
Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle);
}
else if (o.@Particle is XmlSchemaAll)
{
Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle);
}
WriteSortedItems(o.Attributes);
Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute);
WriteEndElement();
}
private void Write43_XmlSchemaAll(XmlSchemaAll o)
{
if (o is null)
return;
WriteStartElement("all");
WriteAttribute(@"id", @"", ((string?)o.@Id));
WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs));
WriteAttribute(
"maxOccurs",
"",
o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)
);
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
WriteSortedItems(o.@Items);
WriteEndElement();
}
private void Write46_XmlSchemaElement(XmlSchemaElement? o)
{
if (o is null)
return;
WriteStartElement("element");
WriteAttribute(@"id", @"", o.Id);
WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs));
WriteAttribute(
"maxOccurs",
"",
o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)
);
if (((bool)o.@IsAbstract) != false)
{
WriteAttribute(@"abstract", @"", XmlConvert.ToString((bool)((bool)o.@IsAbstract)));
}
WriteAttribute(@"block", @"", Write11_XmlSchemaDerivationMethod(o.BlockResolved));
WriteAttribute(@"default", @"", o.DefaultValue);
WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved));
WriteAttribute(@"fixed", @"", o.FixedValue);
if (o.Parent != null && !(o.Parent is XmlSchema))
{
if (
o.QualifiedName != null
&& !o.QualifiedName.IsEmpty
&& o.QualifiedName.Namespace != null
&& o.QualifiedName.Namespace.Length != 0
)
{
WriteAttribute(@"form", @"", "qualified");
}
else
{
WriteAttribute(@"form", @"", "unqualified");
}
}
if (o.Name != null && o.Name.Length != 0)
{
WriteAttribute(@"name", @"", o.Name);
}
if (o.IsNillable)
{
WriteAttribute(@"nillable", @"", XmlConvert.ToString(o.IsNillable));
}
if (!o.SubstitutionGroup.IsEmpty)
{
WriteAttribute("substitutionGroup", "", o.SubstitutionGroup);
}
if (!o.RefName.IsEmpty)
{
WriteAttribute("ref", "", o.RefName);
}
else if (!o.SchemaTypeName.IsEmpty)
{
WriteAttribute("type", "", o.SchemaTypeName);
}
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation(o.Annotation);
if (o.SchemaType is XmlSchemaComplexType)
{
Write35_XmlSchemaComplexType((XmlSchemaComplexType)o.SchemaType);
}
else if (o.SchemaType is XmlSchemaSimpleType)
{
Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.SchemaType);
}
WriteSortedItems(o.Constraints);
WriteEndElement();
}
private void Write47_XmlSchemaKey(XmlSchemaKey? o)
{
if (o is null)
return;
WriteStartElement("key");
WriteAttribute(@"id", @"", ((string?)o.@Id));
WriteAttribute(@"name", @"", ((string?)o.@Name));
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
Write49_XmlSchemaXPath(@"selector", @"", (XmlSchemaXPath?)o.@Selector);
{
XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields;
if (a != null)
{
for (int ia = 0; ia < a.Count; ia++)
{
Write49_XmlSchemaXPath(@"field", @"", (XmlSchemaXPath)a[ia]);
}
}
}
WriteEndElement();
}
private void Write48_XmlSchemaIdentityConstraint(XmlSchemaIdentityConstraint? o)
{
if (o is null)
return;
System.Type t = o.GetType();
if (t == typeof(XmlSchemaUnique))
{
Write51_XmlSchemaUnique((XmlSchemaUnique)o);
return;
}
else if (t == typeof(XmlSchemaKeyref))
{
Write50_XmlSchemaKeyref((XmlSchemaKeyref)o);
return;
}
else if (t == typeof(XmlSchemaKey))
{
Write47_XmlSchemaKey((XmlSchemaKey)o);
return;
}
}
private void Write49_XmlSchemaXPath(string name, string ns, XmlSchemaXPath? o)
{
if (o is null)
return;
WriteStartElement(name);
WriteAttribute(@"id", @"", o.@Id);
WriteAttribute(@"xpath", @"", o.@XPath);
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
WriteEndElement();
}
private void Write50_XmlSchemaKeyref(XmlSchemaKeyref? o)
{
if (o is null)
return;
WriteStartElement("keyref");
WriteAttribute(@"id", @"", ((string?)o.@Id));
WriteAttribute(@"name", @"", ((string?)o.@Name));
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
// UNDONE compare reference here
WriteAttribute(@"refer", @"", o.@Refer);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
Write49_XmlSchemaXPath(@"selector", @"", (XmlSchemaXPath?)o.@Selector);
{
XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields;
if (a != null)
{
for (int ia = 0; ia < a.Count; ia++)
{
Write49_XmlSchemaXPath(@"field", @"", (XmlSchemaXPath)a[ia]);
}
}
}
WriteEndElement();
}
private void Write51_XmlSchemaUnique(XmlSchemaUnique? o)
{
if (o is null)
return;
WriteStartElement("unique");
WriteAttribute(@"id", @"", ((string?)o.@Id));
WriteAttribute(@"name", @"", ((string?)o.@Name));
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
Write49_XmlSchemaXPath("selector", "", (XmlSchemaXPath?)o.@Selector);
XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields;
if (a != null)
{
for (int ia = 0; ia < a.Count; ia++)
{
Write49_XmlSchemaXPath("field", "", (XmlSchemaXPath)a[ia]);
}
}
WriteEndElement();
}
private void Write52_XmlSchemaChoice(XmlSchemaChoice? o)
{
if (o is null)
return;
WriteStartElement("choice");
WriteAttribute(@"id", @"", ((string?)o.@Id));
WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs));
WriteAttribute(
@"maxOccurs",
@"",
o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)
);
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
WriteSortedItems(o.@Items);
WriteEndElement();
}
private void Write53_XmlSchemaAny(XmlSchemaAny? o)
{
if (o is null)
return;
WriteStartElement("any");
WriteAttribute(@"id", @"", o.@Id);
WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs));
WriteAttribute(
@"maxOccurs",
@"",
o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)
);
WriteAttribute(@"namespace", @"", ToString(o.NamespaceList));
XmlSchemaContentProcessing process =
o.@ProcessContents == XmlSchemaContentProcessing.@None
? XmlSchemaContentProcessing.Strict
: o.@ProcessContents;
WriteAttribute(@"processContents", @"", Write34_XmlSchemaContentProcessing(process));
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
WriteEndElement();
}
private void Write54_XmlSchemaSequence(XmlSchemaSequence? o)
{
if (o is null)
return;
WriteStartElement("sequence");
WriteAttribute(@"id", @"", ((string?)o.@Id));
WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs));
WriteAttribute(
"maxOccurs",
"",
o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)
);
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Items;
if (a != null)
{
for (int ia = 0; ia < a.Count; ia++)
{
XmlSchemaObject ai = (XmlSchemaObject)a[ia];
if (ai is XmlSchemaAny)
{
Write53_XmlSchemaAny((XmlSchemaAny)ai);
}
else if (ai is XmlSchemaSequence)
{
Write54_XmlSchemaSequence((XmlSchemaSequence)ai);
}
else if (ai is XmlSchemaChoice)
{
Write52_XmlSchemaChoice((XmlSchemaChoice)ai);
}
else if (ai is XmlSchemaElement)
{
Write46_XmlSchemaElement((XmlSchemaElement)ai);
}
else if (ai is XmlSchemaGroupRef)
{
Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)ai);
}
}
}
WriteEndElement();
}
private void Write55_XmlSchemaGroupRef(XmlSchemaGroupRef? o)
{
if (o is null)
return;
WriteStartElement("group");
WriteAttribute(@"id", @"", ((string?)o.@Id));
WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs));
WriteAttribute(
@"maxOccurs",
@"",
o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)
);
if (!o.RefName.IsEmpty)
{
WriteAttribute("ref", "", o.RefName);
}
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
WriteEndElement();
}
private void Write56_XmlSchemaComplexContentRestriction(
XmlSchemaComplexContentRestriction? o
)
{
if (o is null)
return;
WriteStartElement("restriction");
WriteAttribute(@"id", @"", ((string?)o.@Id));
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
if (!o.@BaseTypeName.IsEmpty)
{
WriteAttribute(@"base", @"", o.@BaseTypeName);
}
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
if (o.@Particle is XmlSchemaSequence)
{
Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle);
}
else if (o.@Particle is XmlSchemaGroupRef)
{
Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o.@Particle);
}
else if (o.@Particle is XmlSchemaChoice)
{
Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle);
}
else if (o.@Particle is XmlSchemaAll)
{
Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle);
}
WriteSortedItems(o.Attributes);
Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute);
WriteEndElement();
}
private void Write57_XmlSchemaGroup(XmlSchemaGroup? o)
{
if (o is null)
return;
WriteStartElement("group");
WriteAttribute(@"id", @"", ((string?)o.@Id));
WriteAttribute(@"name", @"", ((string?)o.@Name));
WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o);
Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation);
if (o.@Particle is XmlSchemaSequence)
{
Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle);
}
else if (o.@Particle is XmlSchemaChoice)
{
Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle);
}
else if (o.@Particle is XmlSchemaAll)
{
Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle);
}
WriteEndElement();
}
}
}
| 36.206872 | 100 | 0.499021 | [
"MIT"
] | belav/runtime | src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs | 50,581 | C# |
// <copyright file="IConnectorClientFactory.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Apps.Celebration.Helpers
{
using Microsoft.Bot.Connector;
/// <summary>
/// Factory for <see cref="IConnectorClient"/>
/// </summary>
public interface IConnectorClientFactory
{
/// <summary>
/// Returns the connector client to use for the specified service URL.
/// </summary>
/// <param name="serviceUrl">The service URL</param>
/// <returns>The connector client instance to use</returns>
IConnectorClient GetConnectorClient(string serviceUrl);
}
} | 32.761905 | 78 | 0.662791 | [
"MIT"
] | ITProCorner/microsoft-teams-celebrations-app | Source/Microsoft.Teams.Apps.Celebration/Helpers/IConnectorClientFactory.cs | 690 | 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 AxeWindowsCLI.Resources {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class OptionsHelpText {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal OptionsHelpText() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AxeWindowsCLI.Resources.OptionsHelpText", typeof(OptionsHelpText).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to How many seconds to delay before triggering the scan. Valid range is 0 to 60 seconds, with a default of 0..
/// </summary>
public static string DelayInSeconds {
get {
return ResourceManager.GetString("DelayInSeconds", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Output directory.
/// </summary>
public static string OutputDirectory {
get {
return ResourceManager.GetString("OutputDirectory", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Process Id.
/// </summary>
public static string ProcessId {
get {
return ResourceManager.GetString("ProcessId", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Process Name.
/// </summary>
public static string ProcessName {
get {
return ResourceManager.GetString("ProcessName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Scan ID.
/// </summary>
public static string ScanId {
get {
return ResourceManager.GetString("ScanId", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Display Third Party Notices (opens file in browser without executing scan). If specified, all other options will be ignored..
/// </summary>
public static string ShowThirdPartyNotices {
get {
return ResourceManager.GetString("ShowThirdPartyNotices", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Verbosity level (Quiet/Default/Verbose).
/// </summary>
public static string Verbosity {
get {
return ResourceManager.GetString("Verbosity", resourceCulture);
}
}
}
}
| 40.897638 | 191 | 0.56623 | [
"MIT"
] | chingucoding/axe-windows | src/CLI/Resources/OptionsHelpText.Designer.cs | 5,070 | 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("07.MultiplyBigNumbers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("07.MultiplyBigNumbers")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b00139eb-a47e-4203-bd07-1ffb196e58ad")]
// 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.243243 | 84 | 0.746996 | [
"MIT"
] | Plotso/SoftUni | Programming Fundamentals/09.StringsExercises/07.MultiplyBigNumbers/Properties/AssemblyInfo.cs | 1,418 | C# |
using System.Collections.Generic;
using UnityEngine;
namespace SpaceTrader.Util {
public class SubmeshTextureMap {
private readonly Dictionary<Texture, int> submeshByTexture;
private readonly List<Texture> textures;
public IReadOnlyList<Texture> Textures => this.textures;
private int nextIndex;
public SubmeshTextureMap() {
this.submeshByTexture = new Dictionary<Texture, int>();
this.textures = new List<Texture>();
this.nextIndex = 0;
}
public int GetSubmeshIndex(Texture texture) {
if (this.submeshByTexture.TryGetValue(texture, out var index)) {
return index;
}
index = this.nextIndex;
this.submeshByTexture.Add(texture, index);
this.textures.Add(texture);
this.nextIndex += 1;
return index;
}
public void Clear() {
this.textures.Clear();
this.submeshByTexture.Clear();
this.nextIndex = 0;
}
}
}
| 26.341463 | 76 | 0.577778 | [
"MIT"
] | spriest487/spacetrader-utils | SubmeshTextureMap.cs | 1,082 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Text.Json
{
public static partial class JsonSerializer
{
private static void GetRuntimeClassInfo(object value, ref JsonClassInfo jsonClassInfo, JsonSerializerOptions options)
{
if (value != null)
{
Type runtimeType = value.GetType();
// Nothing to do for typeof(object)
if (runtimeType != typeof(object))
{
jsonClassInfo = options.GetOrAddClass(runtimeType);
}
}
}
private static void GetRuntimePropertyInfo(object value, JsonClassInfo jsonClassInfo, ref JsonPropertyInfo jsonPropertyInfo, JsonSerializerOptions options)
{
if (value != null)
{
Type runtimeType = value.GetType();
// Nothing to do for typeof(object)
if (runtimeType != typeof(object))
{
jsonPropertyInfo = jsonClassInfo.CreatePolymorphicProperty(jsonPropertyInfo, runtimeType, options);
}
}
}
private static void VerifyValueAndType(object value, Type type)
{
if (type == null)
{
if (value != null)
{
throw new ArgumentNullException(nameof(type));
}
}
else if (value != null)
{
if (!type.IsAssignableFrom(value.GetType()))
{
ThrowHelper.ThrowArgumentException_DeserializeWrongType(type, value);
}
}
}
private static byte[] WriteCoreBytes(object value, Type type, JsonSerializerOptions options)
{
if (options == null)
{
options = JsonSerializerOptions.s_defaultOptions;
}
byte[] result;
using (var output = new PooledByteBufferWriter(options.DefaultBufferSize))
{
WriteCore(output, value, type, options);
result = output.WrittenMemory.ToArray();
}
return result;
}
private static string WriteCoreString(object value, Type type, JsonSerializerOptions options)
{
if (options == null)
{
options = JsonSerializerOptions.s_defaultOptions;
}
string result;
using (var output = new PooledByteBufferWriter(options.DefaultBufferSize))
{
WriteCore(output, value, type, options);
result = JsonReaderHelper.TranscodeHelper(output.WrittenMemory.Span);
}
return result;
}
private static string WriteValueCore(Utf8JsonWriter writer, object value, Type type, JsonSerializerOptions options)
{
if (options == null)
{
options = JsonSerializerOptions.s_defaultOptions;
}
string result;
using (var output = new PooledByteBufferWriter(options.DefaultBufferSize))
{
WriteCore(writer, output, value, type, options);
result = JsonReaderHelper.TranscodeHelper(output.WrittenMemory.Span);
}
return result;
}
private static void WriteCore(PooledByteBufferWriter output, object value, Type type, JsonSerializerOptions options)
{
using var writer = new Utf8JsonWriter(output, options.GetWriterOptions());
WriteCore(writer, output, value, type, options);
}
private static void WriteCore(Utf8JsonWriter writer, PooledByteBufferWriter output, object value, Type type, JsonSerializerOptions options)
{
Debug.Assert(type != null || value == null);
if (value == null)
{
writer.WriteNullValue();
}
else
{
// We treat typeof(object) special and allow polymorphic behavior.
if (type == typeof(object))
{
type = value.GetType();
}
WriteStack state = default;
state.Current.Initialize(type, options);
state.Current.CurrentValue = value;
Write(writer, -1, options, ref state);
}
writer.Flush();
}
}
}
| 32.604167 | 163 | 0.542918 | [
"MIT"
] | ARhj/corefx | src/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Helpers.cs | 4,697 | C# |
namespace Higgs.OpenXml
{
public enum FormulaType
{
None,
Sum
}
} | 11.625 | 27 | 0.526882 | [
"MIT"
] | Soul-Master/higgs | Higgs.OpenXml/FormulaType.cs | 93 | C# |
using ShineEngine;
/// <summary>
/// 刷新单位显示部件数据(generated by shine)
/// </summary>
public class RefreshUnitAvatarPartResponse:UnitSResponse
{
/// <summary>
/// 数据类型ID
/// </summary>
public const int dataID=SceneBaseResponseType.RefreshUnitAvatarPart;
/// <summary>
/// 改变组
/// </summary>
public IntIntMap parts;
public RefreshUnitAvatarPartResponse()
{
_dataID=SceneBaseResponseType.RefreshUnitAvatarPart;
}
/// <summary>
/// 执行
/// </summary>
protected override void execute()
{
unit.getUnitData().fightDataLogic.avatar.setAvatarPartByServer(parts);
}
/// <summary>
/// 获取数据类名
/// </summary>
public override string getDataClassName()
{
return "RefreshUnitAvatarPartResponse";
}
/// <summary>
/// 读取字节流(完整版)
/// </summary>
protected override void toReadBytesFull(BytesReadStream stream)
{
base.toReadBytesFull(stream);
stream.startReadObj();
int partsLen=stream.readLen();
if(this.parts!=null)
{
this.parts.clear();
this.parts.ensureCapacity(partsLen);
}
else
{
this.parts=new IntIntMap(partsLen);
}
IntIntMap partsT=this.parts;
for(int partsI=partsLen-1;partsI>=0;--partsI)
{
int partsK;
int partsV;
partsK=stream.readInt();
partsV=stream.readInt();
partsT.put(partsK,partsV);
}
stream.endReadObj();
}
/// <summary>
/// 读取字节流(简版)
/// </summary>
protected override void toReadBytesSimple(BytesReadStream stream)
{
base.toReadBytesSimple(stream);
int partsLen=stream.readLen();
if(this.parts!=null)
{
this.parts.clear();
this.parts.ensureCapacity(partsLen);
}
else
{
this.parts=new IntIntMap(partsLen);
}
IntIntMap partsT=this.parts;
for(int partsI=partsLen-1;partsI>=0;--partsI)
{
int partsK;
int partsV;
partsK=stream.readInt();
partsV=stream.readInt();
partsT.put(partsK,partsV);
}
}
/// <summary>
/// 转文本输出
/// </summary>
protected override void toWriteDataString(DataWriter writer)
{
base.toWriteDataString(writer);
writer.writeTabs();
writer.sb.Append("parts");
writer.sb.Append(':');
writer.sb.Append("Map<int,int>");
if(this.parts!=null)
{
writer.sb.Append('(');
writer.sb.Append(this.parts.size());
writer.sb.Append(')');
writer.writeEnter();
writer.writeLeftBrace();
if(!this.parts.isEmpty())
{
int partsKFreeValue=this.parts.getFreeValue();
int[] partsKKeys=this.parts.getKeys();
int[] partsVValues=this.parts.getValues();
for(int partsKI=partsKKeys.Length-1;partsKI>=0;--partsKI)
{
int partsK=partsKKeys[partsKI];
if(partsK!=partsKFreeValue)
{
int partsV=partsVValues[partsKI];
writer.writeTabs();
writer.sb.Append(partsK);
writer.sb.Append(':');
writer.sb.Append(partsV);
writer.writeEnter();
}
}
}
writer.writeRightBrace();
}
else
{
writer.sb.Append("=null");
}
writer.writeEnter();
}
/// <summary>
/// 回池
/// </summary>
protected override void toRelease(DataPool pool)
{
base.toRelease(pool);
this.parts=null;
}
}
| 19.656627 | 73 | 0.615078 | [
"Apache-2.0"
] | hw233/home3 | core/client/game/src/commonGame/net/sceneBaseResponse/unit/RefreshUnitAvatarPartResponse.cs | 3,357 | C# |
using System.IO;
using System.Linq;
using Unity.CompilationPipeline.Common.Diagnostics;
using Unity.CompilationPipeline.Common.ILPostProcessing;
using Mono.Cecil;
using Mono.Cecil.Cil;
using VContainer.Unity;
namespace VContainer.Editor.CodeGen
{
public sealed class VContainerILPostProcessor : ILPostProcessor
{
public override ILPostProcessor GetInstance() => this;
public override bool WillProcess(ICompiledAssembly compiledAssembly)
{
var settings = VContainerSettings.Instance;
return settings != null &&
settings.CodeGen.Enabled &&
settings.CodeGen.AssemblyNames.Contains(compiledAssembly.Name) &&
compiledAssembly.References.Any(x => x.EndsWith("VContainer.dll"));
}
public override ILPostProcessResult Process(ICompiledAssembly compiledAssembly)
{
if (!WillProcess(compiledAssembly))
return null;
var assemblyDefinition = Utils.LoadAssemblyDefinition(compiledAssembly);
var generator = new InjectionILGenerator(
assemblyDefinition.MainModule,
VContainerSettings.Instance.CodeGen.Namespaces);
if (generator.TryGenerate(out var diagnosticMessages))
{
if (diagnosticMessages.Any(d => d.DiagnosticType == DiagnosticType.Error))
{
return new ILPostProcessResult(null, diagnosticMessages);
}
var pe = new MemoryStream();
var pdb = new MemoryStream();
var writerParameters = new WriterParameters
{
SymbolWriterProvider = new PortablePdbWriterProvider(),
SymbolStream = pdb,
WriteSymbols = true
};
assemblyDefinition.Write(pe, writerParameters);
return new ILPostProcessResult(new InMemoryAssembly(pe.ToArray(), pdb.ToArray()), diagnosticMessages);
}
return new ILPostProcessResult(null, diagnosticMessages);
}
}
}
| 36.355932 | 118 | 0.617716 | [
"MIT"
] | D-RyusukeMatsumoto/VContainerTest | Assets/VContainer/Editor/CodeGen/VContainerILPostProcessor.cs | 2,145 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// 制御されます。アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更します。
[assembly: AssemblyTitle("Kujikatsu001")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Kujikatsu001")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、このアセンブリ内の型は COM コンポーネントから
// 参照できなくなります。COM からこのアセンブリ内の型にアクセスする必要がある場合は、
// その型の ComVisible 属性を true に設定します。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("09037c6d-00aa-454d-9e2c-baf896731ebb")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// リビジョン
//
// すべての値を指定するか、次を使用してビルド番号とリビジョン番号を既定に設定できます
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 29.216216 | 56 | 0.750231 | [
"MIT"
] | terry-u16/AtCoder | Kujikatsu001/Kujikatsu001/Kujikatsu001/Properties/AssemblyInfo.cs | 1,680 | C# |
using AspnetRunBasics.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace AspnetRunBasics.Services
{
public interface ICatalogService
{
Task<IEnumerable<CatalogModel>> GetCatalog();
Task<IEnumerable<CatalogModel>> GetCatalogByCategory(string category);
Task<CatalogModel> GetCatalog(string id);
Task<CatalogModel> CreateCatalog(CatalogModel model);
}
}
| 28.6 | 78 | 0.745921 | [
"MIT"
] | Aashiq2691/Microservices | src/WebApps/AspnetRunBasics/Services/ICatalogService.cs | 431 | C# |
using SharpDX;
namespace Engine.Effects
{
using Engine.Common;
/// <summary>
/// Foliage shadows effect
/// </summary>
public class EffectShadowFoliage : Drawer
{
/// <summary>
/// Foliage shadow map drawing technique
/// </summary>
public readonly EngineEffectTechnique ShadowMapFoliage4 = null;
/// <summary>
/// Foliage shadow map drawing technique
/// </summary>
public readonly EngineEffectTechnique ShadowMapFoliage8 = null;
/// <summary>
/// Foliage shadow map drawing technique
/// </summary>
public readonly EngineEffectTechnique ShadowMapFoliage16 = null;
/// <summary>
/// World view projection effect variable
/// </summary>
private readonly EngineEffectVariableMatrix worldViewProjectionVar = null;
/// <summary>
/// Eye position effect variable
/// </summary>
private readonly EngineEffectVariableVector eyePositionWorldVar = null;
/// <summary>
/// Start radius
/// </summary>
private readonly EngineEffectVariableScalar startRadiusVar = null;
/// <summary>
/// End radius
/// </summary>
private readonly EngineEffectVariableScalar endRadiusVar = null;
/// <summary>
/// Wind direction effect variable
/// </summary>
private readonly EngineEffectVariableVector windDirectionVar = null;
/// <summary>
/// Wind strength effect variable
/// </summary>
private readonly EngineEffectVariableScalar windStrengthVar = null;
/// <summary>
/// Time effect variable
/// </summary>
private readonly EngineEffectVariableScalar totalTimeVar = null;
/// <summary>
/// Position delta
/// </summary>
private readonly EngineEffectVariableVector deltaVar = null;
/// <summary>
/// Texture count variable
/// </summary>
private readonly EngineEffectVariableScalar textureCountVar = null;
/// <summary>
/// Texture effect variable
/// </summary>
private readonly EngineEffectVariableTexture texturesVar = null;
/// <summary>
/// Random texture effect variable
/// </summary>
private readonly EngineEffectVariableTexture textureRandomVar = null;
/// <summary>
/// Current texture array
/// </summary>
private EngineShaderResourceView currentTextures = null;
/// <summary>
/// Current random texture
/// </summary>
private EngineShaderResourceView currentTextureRandom = null;
/// <summary>
/// World view projection matrix
/// </summary>
protected Matrix WorldViewProjection
{
get
{
return worldViewProjectionVar.GetMatrix();
}
set
{
worldViewProjectionVar.SetMatrix(value);
}
}
/// <summary>
/// Camera eye position
/// </summary>
protected Vector3 EyePositionWorld
{
get
{
return eyePositionWorldVar.GetVector<Vector3>();
}
set
{
eyePositionWorldVar.Set(value);
}
}
/// <summary>
/// Start radius
/// </summary>
protected float StartRadius
{
get
{
return startRadiusVar.GetFloat();
}
set
{
startRadiusVar.Set(value);
}
}
/// <summary>
/// End radius
/// </summary>
protected float EndRadius
{
get
{
return endRadiusVar.GetFloat();
}
set
{
endRadiusVar.Set(value);
}
}
/// <summary>
/// Wind direction
/// </summary>
protected Vector3 WindDirection
{
get
{
return windDirectionVar.GetVector<Vector3>();
}
set
{
windDirectionVar.Set(value);
}
}
/// <summary>
/// Wind strength
/// </summary>
protected float WindStrength
{
get
{
return windStrengthVar.GetFloat();
}
set
{
windStrengthVar.Set(value);
}
}
/// <summary>
/// Time
/// </summary>
protected float TotalTime
{
get
{
return totalTimeVar.GetFloat();
}
set
{
totalTimeVar.Set(value);
}
}
/// <summary>
/// Position delta
/// </summary>
protected Vector3 Delta
{
get
{
return deltaVar.GetVector<Vector3>();
}
set
{
deltaVar.Set(value);
}
}
/// <summary>
/// Texture count
/// </summary>
protected uint TextureCount
{
get
{
return textureCountVar.GetUInt();
}
set
{
textureCountVar.Set(value);
}
}
/// <summary>
/// Texture
/// </summary>
protected EngineShaderResourceView Textures
{
get
{
return texturesVar.GetResource();
}
set
{
if (currentTextures != value)
{
texturesVar.SetResource(value);
currentTextures = value;
Counters.TextureUpdates++;
}
}
}
/// <summary>
/// Random texture
/// </summary>
protected EngineShaderResourceView TextureRandom
{
get
{
return textureRandomVar.GetResource();
}
set
{
if (currentTextureRandom != value)
{
textureRandomVar.SetResource(value);
currentTextureRandom = value;
Counters.TextureUpdates++;
}
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="graphics">Graphics device</param>
/// <param name="effect">Effect code</param>
/// <param name="compile">Compile code</param>
public EffectShadowFoliage(Graphics graphics, byte[] effect, bool compile)
: base(graphics, effect, compile)
{
ShadowMapFoliage4 = Effect.GetTechniqueByName("ShadowMapFoliage4");
ShadowMapFoliage8 = Effect.GetTechniqueByName("ShadowMapFoliage8");
ShadowMapFoliage16 = Effect.GetTechniqueByName("ShadowMapFoliage16");
worldViewProjectionVar = Effect.GetVariableMatrix("gWorldViewProjection");
eyePositionWorldVar = Effect.GetVariableVector("gEyePositionWorld");
startRadiusVar = Effect.GetVariableScalar("gStartRadius");
endRadiusVar = Effect.GetVariableScalar("gEndRadius");
textureCountVar = Effect.GetVariableScalar("gTextureCount");
texturesVar = Effect.GetVariableTexture("gTextureArray");
windDirectionVar = Effect.GetVariableVector("gWindDirection");
windStrengthVar = Effect.GetVariableScalar("gWindStrength");
totalTimeVar = Effect.GetVariableScalar("gTotalTime");
deltaVar = Effect.GetVariableVector("gDelta");
textureRandomVar = Effect.GetVariableTexture("gTextureRandom");
}
/// <summary>
/// Update per frame data
/// </summary>
/// <param name="context">Drawing context</param>
/// <param name="state">State</param>
public void UpdatePerFrame(
DrawContextShadows context,
EffectShadowFoliageState state)
{
WorldViewProjection = context.ViewProjection;
EyePositionWorld = context.EyePosition;
StartRadius = state.StartRadius;
EndRadius = state.EndRadius;
TextureCount = state.TextureCount;
Textures = state.Texture;
WindDirection = state.WindDirection;
WindStrength = state.WindStrength;
TotalTime = state.TotalTime;
Delta = state.Delta;
TextureRandom = state.RandomTexture;
}
}
}
| 29.526667 | 86 | 0.506661 | [
"MIT"
] | Selinux24/SharpDX-Tests | Engine/Effects/EffectShadowFoliage.cs | 8,860 | C# |
using System.Collections;
using System.Collections.Generic;
using ThirdEyeSoftware.GameLogic;
using ThirdEyeSoftware.GameLogic.LogicHandlers;
using UnityEngine;
public class btnPrivacyPolicyPrompt : MonoBehaviour, IComponent
{
public ILogicHandler LogicHandler { get; set; }
void OnClick()
{
LogicHandler.OnClick(this.gameObject.name);
}
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
| 17.962963 | 63 | 0.672165 | [
"BSD-3-Clause"
] | jaydpather/UnityGameEngineInterface | btnPrivacyPolicyPrompt.cs | 487 | C# |
/* _BEGIN_TEMPLATE_
{
"id": "TB_BaconUps_080",
"name": [
"斯尼德的伐木机",
"Sneed's Old Shredder"
],
"text": [
"<b>亡语:</b>随机召唤两个<b>传说</b>随从。",
"<b>Deathrattle:</b> Summon 2 random <b>Legendary</b> minions."
],
"CardClass": "NEUTRAL",
"type": "MINION",
"cost": 8,
"rarity": "LEGENDARY",
"set": "BATTLEGROUNDS",
"collectible": null,
"dbfId": 59683
}
_END_TEMPLATE_ */
namespace HREngine.Bots
{
class Sim_TB_BaconUps_080 : SimTemplate
{
}
} | 17.285714 | 67 | 0.582645 | [
"MIT"
] | chi-rei-den/Silverfish | cards/BATTLEGROUNDS/TB/Sim_TB_BaconUps_080.cs | 526 | C# |
/************************************************************************************
Copyright : Copyright 2017 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.4.1 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/sdk-3.4.1
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
using System;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
/// <summary>
/// Manages mix-reality elements
/// </summary>
internal static class OVRMixedReality
{
/// <summary>
/// Configurable parameters
/// </summary>
public static Color chromaKeyColor = Color.green;
/// <summary>
/// For Debugging purpose, we can use preset parameters to fake a camera when external camera is not available
/// </summary>
public static bool useFakeExternalCamera = false;
public static Vector3 fakeCameraPositon = new Vector3(3.0f, 0.0f, 3.0f);
public static Quaternion fakeCameraRotation = Quaternion.LookRotation((new Vector3(0.0f, 1.0f, 0.0f) - fakeCameraPositon).normalized, Vector3.up);
public static float fakeCameraFov = 60.0f;
public static float fakeCameraAspect = 16.0f / 9.0f;
/// <summary>
/// Composition object
/// </summary>
public static OVRComposition currentComposition = null;
/// <summary>
/// Updates the internal state of the Mixed Reality Camera. Called by OVRManager.
/// </summary>
public static void Update(GameObject parentObject, Camera mainCamera, OVRManager.CompositionMethod compositionMethod, bool useDynamicLighting, OVRManager.CameraDevice cameraDevice, OVRManager.DepthQuality depthQuality)
{
if (!OVRPlugin.initialized)
{
Debug.LogError("OVRPlugin not initialized");
return;
}
if (!OVRPlugin.IsMixedRealityInitialized())
OVRPlugin.InitializeMixedReality();
if (!OVRPlugin.IsMixedRealityInitialized())
{
Debug.LogError("Unable to initialize MixedReality");
return;
}
OVRPlugin.UpdateExternalCamera();
OVRPlugin.UpdateCameraDevices();
if (currentComposition != null && currentComposition.CompositionMethod() != compositionMethod)
{
currentComposition.Cleanup();
currentComposition = null;
}
if (compositionMethod == OVRManager.CompositionMethod.External)
{
if (currentComposition == null)
{
currentComposition = new OVRExternalComposition(parentObject, mainCamera);
}
}
else if (compositionMethod == OVRManager.CompositionMethod.Direct)
{
if (currentComposition == null)
{
currentComposition = new OVRDirectComposition(parentObject, mainCamera, cameraDevice, useDynamicLighting, depthQuality);
}
}
else if (compositionMethod == OVRManager.CompositionMethod.Sandwich)
{
if (currentComposition == null)
{
currentComposition = new OVRSandwichComposition(parentObject, mainCamera, cameraDevice, useDynamicLighting, depthQuality);
}
}
else
{
Debug.LogError("Unknown CompositionMethod : " + compositionMethod);
return;
}
currentComposition.Update(mainCamera);
}
public static void Cleanup()
{
if (currentComposition != null)
{
currentComposition.Cleanup();
currentComposition = null;
}
if (OVRPlugin.IsMixedRealityInitialized())
{
OVRPlugin.ShutdownMixedReality();
}
}
public static void RecenterPose()
{
if (currentComposition != null)
{
currentComposition.RecenterPose();
}
}
}
#endif | 30.343284 | 219 | 0.718888 | [
"MIT"
] | AnthonyD1/Self-Defense-VR | SelfDefenseVR/Assets/OVR/Scripts/OVRMixedReality.cs | 4,068 | C# |
version https://git-lfs.github.com/spec/v1
oid sha256:dfe92e9f2f783e6ded5061adf300c9188932ae99e6a9a4f990121e016920ecad
size 16170
| 32.5 | 75 | 0.884615 | [
"MIT"
] | Vakuzar/Multithreaded-Blood-Sim | Blood/Library/PackageCache/com.unity.burst@1.3.0-preview.12/Editor/BurstDisassembler.cs | 130 | C# |
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Ndjson.AsyncStreams.AspNetCore.Mvc.NewtonsoftJson.Internals
{
internal class NewtonsoftNdjsonWriter<T> : INdjsonWriter<T>
{
private readonly TextWriter _textResponseStreamWriter;
private readonly JsonTextWriter _jsonResponseStreamWriter;
private readonly JsonSerializer _jsonSerializer;
public NewtonsoftNdjsonWriter(TextWriter textResponseStreamWriter, JsonSerializerSettings jsonSerializerSettings, NewtonsoftNdjsonArrayPool jsonArrayPool)
{
_textResponseStreamWriter = textResponseStreamWriter ?? throw new ArgumentNullException(nameof(textResponseStreamWriter));
_jsonResponseStreamWriter = new JsonTextWriter(textResponseStreamWriter)
{
ArrayPool = jsonArrayPool,
CloseOutput = false,
AutoCompleteOnClose = false
};
_jsonSerializer = JsonSerializer.Create(jsonSerializerSettings);
}
public Task WriteAsync(T value)
{
return WriteAsync(value, CancellationToken.None);
}
public async Task WriteAsync(T value, CancellationToken cancellationToken)
{
_jsonSerializer.Serialize(_jsonResponseStreamWriter, value);
await _textResponseStreamWriter.WriteAsync("\n");
await _textResponseStreamWriter.FlushAsync();
}
public void Dispose()
{
_textResponseStreamWriter?.Dispose();
((IDisposable)_jsonResponseStreamWriter)?.Dispose();
}
}
}
| 34.770833 | 162 | 0.686639 | [
"MIT"
] | tpeczek/Ndjson.AsyncStreams | src/Ndjson.AsyncStreams.AspNetCore.Mvc.NewtonsoftJson/Internals/NewtonsoftNdjsonWriter.cs | 1,671 | C# |
using System;
namespace Journey
{
internal class Program
{
private static void Main(string[] args)
{
double budget = double.Parse(Console.ReadLine());
string season = Console.ReadLine();
string destination = "";
string place = "";
double price = 0.00;
if (budget <= 100)
{
destination = "Bulgaria";
if (season == "summer")
{
place = "Camp";
price = budget * 0.3;
}
else if (season == "winter")
{
place = "Hotel";
price = budget * 0.7;
}
}
else if (budget <= 1000)
{
destination = "Balkans";
if (season == "summer")
{
place = "Camp";
price = budget * 0.4;
}
else if (season == "winter")
{
place = "Hotel";
price = budget * 0.8;
}
}
else /* if (budget > 1000) */
{
destination = "Europe";
if (season == "summer" || season == "winter")
{
place = "Hotel";
price = budget * 0.9;
}
}
Console.WriteLine($"Somewhere in {destination}");
Console.WriteLine($"{place} - {price:f2}");
}
}
} | 27.551724 | 61 | 0.344806 | [
"MIT"
] | dzhanetGerdzhikova/Programming-Basics | 4.1.. NestedConditionalStatments-Exercise/Journey/Program.cs | 1,600 | C# |
using OpenRpg.Combat.Effects;
using OpenRpg.Data.Repositories;
namespace BK9K.Game.Data.Repositories
{
public interface ITimedEffectRepository : IReadRepository<TimedEffect, int>
{
}
} | 22 | 79 | 0.767677 | [
"MIT"
] | grofit/battle-kill-9000 | src/BK9K/BK9K.Game.Data/Repositories/ITimedEffectRepository.cs | 200 | C# |
using RandomChat.WebApi.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
namespace RandomChat.WebApi.Services
{
public class ChatsContainer : IChatsContainer
{
private string waitingClientId;
private readonly List<Chat> chats = new List<Chat>();
public string DisconnectClientAndGetSecondChatter(string connectionId)
{
if (connectionId == waitingClientId)
{
waitingClientId = null;
return null;
}
Chat chat = chats.Find(c => c.GetTargetClient(connectionId) != null);
chats?.Remove(chat);
return chat?.GetTargetClient(connectionId);
}
public string GetTargetClient(string connectionId)
{
return chats.Where(c => c.GetTargetClient(connectionId) != null).Select(c => c.GetTargetClient(connectionId)).FirstOrDefault() ?? throw new Exception();
}
public bool NewClient(string connectionId, out string secondClient)
{
if (waitingClientId != null)
{
chats.Add(new Chat(connectionId, waitingClientId));
secondClient = waitingClientId;
waitingClientId = null;
Console.WriteLine("Chat created");
return true;
}
else
{
waitingClientId = connectionId;
secondClient = null;
return false;
}
}
}
public class Chat
{
public string FirstClient { get; }
public string SecondClient { get; }
public Chat(string firstClient, string secondClient)
{
FirstClient = firstClient;
SecondClient = secondClient;
}
public string GetTargetClient(string connectionId)
{
if (connectionId == FirstClient)
{
return SecondClient;
}
else if (connectionId == SecondClient)
{
return FirstClient;
}
else
{
return null;
}
}
}
}
| 28.649351 | 164 | 0.538985 | [
"MIT"
] | misiek231/random-chat | RandomChat.WebApi/Services/ChatsContainer.cs | 2,208 | C# |
using System;
namespace Gaspra.DatabaseProcesses.Extensions
{
public static class DataReaderExtensions
{
public static T GetValue<T>(this object data)
{
if (data.GetType().Equals(typeof(DBNull)))
{
return default;
}
var nullableType = Nullable.GetUnderlyingType(typeof(T));
if (nullableType != null)
{
return (T)Convert.ChangeType(data, nullableType);
}
return (T)data;
}
public static DateTime? GetDateTimeOrNull(this object data)
{
if (data.GetType().Equals(typeof(DBNull)))
{
return null;
}
var dateValue = (DateTime)data;
if (DateTime.MinValue.Equals(dateValue))
{
return null;
}
return dateValue;
}
}
}
| 22.214286 | 69 | 0.493033 | [
"MIT"
] | Gaspra/Gaspra.Functions | src/libraries/Gaspra.DatabaseProcesses/Extensions/DataReaderExtensions.cs | 935 | C# |
using System.Collections.Generic;
using System.Linq;
namespace LeetCode.P1428
{
public class Solution
{
// Runtime: 100 ms
// Memory Usage: 27.1 MB
public int LeftMostColumnWithOne(BinaryMatrix binaryMatrix)
{
var oneIndices = new SortedSet<int>();
var dimensions = binaryMatrix.Dimensions();
for (var row = 0; row < dimensions[0]; ++row)
{
var startIndex = 0;
var endIndex = dimensions[1] - 1;
while (startIndex <= endIndex)
{
var index = startIndex + (endIndex - startIndex) / 2;
if (binaryMatrix.Get(row, index) == 0)
{
startIndex = index + 1;
}
else
{
oneIndices.Add(index);
endIndex = index - 1;
}
}
}
return oneIndices.Count == 0 ? -1 : oneIndices.First();
}
}
}
| 27.275 | 73 | 0.430797 | [
"MIT"
] | ch200c/leetcode-cs | LeetCode/P1428/Solution.cs | 1,093 | C# |
namespace SKIT.FlurlHttpClient.Wechat.Api.Models
{
/// <summary>
/// <para>表示 [POST] /componenttcb/getscflist 接口的请求。</para>
/// </summary>
public class ComponentTcbGetSCFListRequest : WechatApiRequest
{
/// <summary>
/// 获取或设置第三方平台 AccessToken。
/// </summary>
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
public string ComponentAccessToken { get; set; } = string.Empty;
/// <summary>
/// 获取或设置环境 ID。
/// </summary>
[Newtonsoft.Json.JsonProperty("env")]
[System.Text.Json.Serialization.JsonPropertyName("env")]
public string EnvironmentId { get; set; } = string.Empty;
/// <summary>
/// 获取或设置分页起始位置。
/// </summary>
[Newtonsoft.Json.JsonProperty("offset")]
[System.Text.Json.Serialization.JsonPropertyName("offset")]
public int? Offset { get; set; }
/// <summary>
/// 获取或设置分页每页数量。
/// </summary>
[Newtonsoft.Json.JsonProperty("limit")]
[System.Text.Json.Serialization.JsonPropertyName("limit")]
public int? Limit { get; set; }
/// <summary>
/// 获取或设置搜索关键词。
/// </summary>
[Newtonsoft.Json.JsonProperty("searchkey")]
[System.Text.Json.Serialization.JsonPropertyName("searchkey")]
public string? SearchKey { get; set; }
}
}
| 32.204545 | 72 | 0.584333 | [
"MIT"
] | ZUOXIANGE/DotNetCore.SKIT.FlurlHttpClient.Wechat | src/SKIT.FlurlHttpClient.Wechat.Api/Models/ComponentTcb/SCF/ComponentTcbGetSCFListRequest.cs | 1,543 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Google.Cloud.Monitoring.V3;
using Xunit;
using static Google.Api.MetricDescriptor.Types;
namespace Simple.Metrics.Stackdriver.UnitTests
{
public class FakeMetricExporter : IMetricsExporter
{
private IEnumerable<TimeSeries> _timeSeries;
public void AssertTimeSeriesCount(int expected) => Assert.Equal(expected, _timeSeries.Count());
public Task ExportAsync(IEnumerable<TimeSeries> timeSeries)
{
_timeSeries = timeSeries;
return Task.CompletedTask;
}
internal void AssertExportedInt64(
string name,
MetricKind kind,
long value,
params (string, string)[] labels)
{
var typedValue = AssertMatchingTimeSeries(name, kind, labels);
Assert.Equal(value, typedValue.Int64Value);
}
internal void AssertExportedDouble(
string name,
MetricKind kind,
double value,
params (string, string)[] labels)
{
var typedValue = AssertMatchingTimeSeries(name, kind, labels);
Assert.Equal(value, typedValue.DoubleValue, precision: 3);
}
internal void AssertExportedString(
string name,
MetricKind kind,
string value,
params (string, string)[] labels)
{
var typedValue = AssertMatchingTimeSeries(name, kind, labels);
Assert.Equal(value, typedValue.StringValue);
}
internal void AssertExportedDistribution(
string name,
MetricKind kind,
int count,
double mean,
int bucketCount,
int sumOfSquaredDeviation,
params (string, string)[] labels)
{
var typedValue = AssertMatchingTimeSeries(name, kind, labels);
Assert.NotNull(typedValue.DistributionValue);
Assert.Equal(count, typedValue.DistributionValue.Count);
Assert.Equal(mean, typedValue.DistributionValue.Mean);
Assert.Equal(bucketCount, typedValue.DistributionValue.BucketCounts.Count);
Assert.Equal(sumOfSquaredDeviation, typedValue.DistributionValue.SumOfSquaredDeviation);
}
private TypedValue AssertMatchingTimeSeries(string name, MetricKind kind, (string, string)[] labels)
{
var match = _timeSeries
.SingleOrDefault(ts => ts.Metric.Type == "custom.googleapis.com/" + name
&& ts.MetricKind == kind
&& ts.Metric.Labels.Select(l => (l.Key, l.Value)).SequenceEqual(labels));
Assert.True(match != null, $"Did not find a match for {name}.");
Assert.True(match.Points != null, $"Did not find a time series point for {name}.");
Assert.True(match.Points.Count() == 1, $"Time series {name} did not contain a single point.");
Assert.True(match.Points[0].Value != null, $"Did not find a time series value for {name}.");
return match.Points[0].Value;
}
}
} | 37.870588 | 112 | 0.604846 | [
"MIT"
] | emzeq/simple-metrics-stackdriver | test/Simple.Metrics.Stackdriver.UnitTests/FakeMetricExporter.cs | 3,219 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Ecs.Model.V20140526;
namespace Aliyun.Acs.Ecs.Transform.V20140526
{
public class DescribeSnapshotsUsageResponseUnmarshaller
{
public static DescribeSnapshotsUsageResponse Unmarshall(UnmarshallerContext _ctx)
{
DescribeSnapshotsUsageResponse describeSnapshotsUsageResponse = new DescribeSnapshotsUsageResponse();
describeSnapshotsUsageResponse.HttpResponse = _ctx.HttpResponse;
describeSnapshotsUsageResponse.SnapshotSize = _ctx.LongValue("DescribeSnapshotsUsage.SnapshotSize");
describeSnapshotsUsageResponse.RequestId = _ctx.StringValue("DescribeSnapshotsUsage.RequestId");
describeSnapshotsUsageResponse.SnapshotCount = _ctx.IntegerValue("DescribeSnapshotsUsage.SnapshotCount");
return describeSnapshotsUsageResponse;
}
}
}
| 40.619048 | 108 | 0.777843 | [
"Apache-2.0"
] | aliyun/aliyun-openapi-net-sdk | aliyun-net-sdk-ecs/Ecs/Transform/V20140526/DescribeSnapshotsUsageResponseUnmarshaller.cs | 1,706 | C# |
using HexCardGame.Runtime.Game;
using NUnit.Framework;
namespace HexCardGame.Runtime.Test
{
public partial class Mechanics_Test : BaseTestMechanics, IPreGameStart
{
public void OnPreGameStart(IPlayer[] players) => EventReceived = true;
[Test]
public void PreStartGame()
{
Game.StartGame();
Assert.IsTrue(EventReceived);
}
}
} | 23.764706 | 78 | 0.638614 | [
"MIT"
] | ycarowr/CardGameHexBoard | Assets/Scripts/Runtime/Mechanics/Editor/PreStartGame_Test.cs | 406 | C# |
using BlueprintCore.Blueprints.Configurators.Facts;
using BlueprintCore.Utils;
using Kingmaker.Blueprints;
using Kingmaker.Blueprints.Classes;
using Kingmaker.Blueprints.Classes.Selection;
using Kingmaker.Designers.Mechanics.Facts;
using System;
using System.Linq;
namespace BlueprintCore.Blueprints.Configurators.Classes
{
/// <summary>
/// Implements common fields and components for blueprints inheriting from <see cref="BlueprintFeatureBase"/>.
/// </summary>
/// <inheritdoc/>
[Configures(typeof(BlueprintFeatureBase))]
public abstract class FeatureBaseConfigurator<T, TBuilder> : BaseUnitFactConfigurator<T, TBuilder>
where T : BlueprintFeatureBase
where TBuilder : FeatureBaseConfigurator<T, TBuilder>
{
protected FeatureBaseConfigurator(string name) : base(name) { }
/// <summary>
/// Sets <see cref="BlueprintFeatureBase.HideInUi"/>
/// </summary>
public TBuilder SetHideInUi(bool hide = true)
{
return OnConfigureInternal(blueprint => blueprint.HideInUI = hide);
}
/// <summary>
/// Sets <see cref="BlueprintFeatureBase.HideInCharacterSheetAndLevelUp"/>
/// </summary>
public TBuilder SetHideInCharacterSheetAndLevelUp(bool hide = true)
{
return OnConfigureInternal(blueprint => blueprint.HideInCharacterSheetAndLevelUp = hide);
}
/// <summary>
/// Sets <see cref="BlueprintFeatureBase.HideNotAvailibleInUI"/>
/// </summary>
public TBuilder SetHideNotAvailableInUI(bool hide = true)
{
return OnConfigureInternal(blueprint => blueprint.HideNotAvailibleInUI = hide);
}
/// <summary>
/// Sets the contents of <see cref="FeatureTagsComponent"/>
/// </summary>
[Implements(typeof(FeatureTagsComponent))]
public TBuilder SetFeatureTags(params FeatureTag[] tags)
{
return OnConfigureInternal(
bp =>
{
var component = bp.GetComponent<FeatureTagsComponent>();
if (component == null)
{
component = new FeatureTagsComponent();
bp.AddComponents(component);
}
component.FeatureTags = 0;
tags.ToList().ForEach(t => component.FeatureTags |= t);
});
}
/// <summary>
/// Adds to <see cref="FeatureTagsComponent"/>
/// </summary>
[Implements(typeof(FeatureTagsComponent))]
public TBuilder AddToFeatureTags(params FeatureTag[] tags)
{
return OnConfigureInternal(
bp =>
{
var component = bp.GetComponent<FeatureTagsComponent>();
if (component == null)
{
component = new FeatureTagsComponent();
bp.AddComponents(component);
}
tags.ToList().ForEach(t => component.FeatureTags |= t);
});
}
/// <summary>
/// Removes from <see cref="FeatureTagsComponent"/>
/// </summary>
[Implements(typeof(FeatureTagsComponent))]
public TBuilder RemoveFromFeatureTags(params FeatureTag[] tags)
{
return OnConfigureInternal(
bp =>
{
var component = bp.GetComponent<FeatureTagsComponent>();
if (component == null) { return; }
tags.ToList().ForEach(t => component.FeatureTags &= ~t);
});
}
/// <summary>
/// Adds <see cref="HideFeatureInInspect"/> (Auto Generated)
/// </summary>
[Generated]
[Implements(typeof(HideFeatureInInspect))]
public TBuilder AddHideFeatureInInspect(
ComponentMerge mergeBehavior = ComponentMerge.Replace,
Action<BlueprintComponent, BlueprintComponent> mergeAction = null)
{
var component = new HideFeatureInInspect();
return AddUniqueComponent(component, mergeBehavior, mergeAction);
}
}
}
| 32.681034 | 112 | 0.644949 | [
"MIT"
] | bje259/WOTR_PATH_OF_RAGE | BlueprintCore/Blueprints/Configurators/Classes/FeatureBaseConfigurator.cs | 3,791 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VVVV.PluginInterfaces.V2;
using AssimpNet;
using System.IO;
using FeralTic.Resources.Geometry;
using VVVV.PluginInterfaces.V1;
using SlimDX.Direct3D11;
using SlimDX;
using FeralTic.DX11.Resources;
using FeralTic.DX11;
namespace VVVV.DX11.Nodes.AssetImport
{
[PluginInfo(Name = "Geometry", Category = "DX11", Version = "Assimp.Merge", Author = "vux,flateric")]
public class AssimpSimpleLoaderMergeNode : IPluginEvaluate, IDisposable, IDX11ResourceHost
{
[Input("Path", StringType = StringType.Filename, IsSingle=true)]
protected IDiffSpread<string> FInPath;
[Input("Reload", IsBang = true, IsSingle = true)]
protected ISpread<bool> FInReload;
[Output("Output", Order = 5, IsSingle=true)]
protected ISpread<DX11Resource<DX11IndexOnlyGeometry>> FOutGeom;
[Output("Position Buffer", Order = 5, IsSingle = true)]
protected ISpread<DX11Resource<IDX11ReadableStructureBuffer>> FOutPosition;
[Output("Id Buffer", Order = 6, IsSingle = true)]
protected ISpread<DX11Resource<IDX11ReadableStructureBuffer>> FOutId;
[Output("Uv Buffer", Order = 7)]
protected ISpread<DX11Resource<IDX11ReadableStructureBuffer>> FOutUvs;
[Output("Indices Buffer", Order = 8, IsSingle=true)]
protected ISpread<DX11Resource<DX11RawBuffer>> FOutIndices;
[Output("Vertices Count", Order = 9)]
protected ISpread<int> FOutVerticesCount;
[Output("Indices Count", Order = 10)]
protected ISpread<int> FOutIndicesCount;
[Output("Is Valid",Order=11)]
protected ISpread<bool> FOutValid;
private AssimpScene scene;
private bool FInvalidate;
private bool FEmpty = true;
public AssimpSimpleLoaderMergeNode()
{
}
public void Evaluate(int SpreadMax)
{
if (this.FOutGeom[0] == null)
{
this.FOutGeom[0] = new DX11Resource<DX11IndexOnlyGeometry>();
this.FOutId[0] = new DX11Resource<IDX11ReadableStructureBuffer>();
this.FOutIndices[0] = new DX11Resource<DX11RawBuffer>();
this.FOutUvs[0] = new DX11Resource<IDX11ReadableStructureBuffer>();
}
this.FInvalidate = false;
if (this.FInPath.IsChanged || this.FInReload[0])
{
this.DisposeResources();
try
{
AssimpScene scene = new AssimpScene(this.FInPath[0], true, false);
this.scene = scene;
}
catch
{
this.scene = null;
}
}
this.FInvalidate = true;
}
public void Dispose()
{
this.DisposeResources();
}
private void DisposeResources()
{
if (scene != null) { scene.Dispose(); }
if (this.FOutGeom[0] != null) { this.FOutGeom[0].Dispose(); }
if (this.FOutPosition[0] != null) { this.FOutPosition[0].Dispose(); }
if (this.FOutUvs[0] != null) { this.FOutUvs[0].Dispose(); }
this.scene = null;
}
private int currentid;
private int vertexoffset = 0;
private List<Vector3> vp = new List<Vector3>();
private List<Vector2> uvs = new List<Vector2>();
private List<Matrix> nodetransform = new List<Matrix>();
private List<int> indexbuffer = new List<int>();
private void AppendNode(AssimpNode node)
{
foreach (AssimpNode child in node.Children)
{
this.AppendNode(child);
}
/*if (node.MeshCount > 0)
{
for (int i = 0; i < node.MeshCount;i++)
{
this.AppendMesh(node, this.scene.Meshes[node.MeshIndices[i]);
}
}*/
}
private void AppendMesh(AssimpNode node, AssimpMesh mesh)
{
List<int> inds = mesh.Indices;
if (inds.Count > 0 && mesh.VerticesCount > 0)
{
for (int idx = 0; idx < inds.Count; idx++)
{
inds[idx] += vertexoffset;
}
indexbuffer.AddRange(inds);
//vp.AddRange(mesh.v)
vertexoffset += mesh.VerticesCount;
this.currentid++;
}
}
public void Update(DX11RenderContext context)
{
if ( this.scene == null) {return;}
if (this.FInvalidate || !this.FOutGeom[0].Contains(context))
{
this.AppendNode(this.scene.RootNode);
/*for (int i = 0; i < this.scenes.Count; i++)
{
if (scenes[i] != null)
{
AssimpScene scene = scenes[i];
for (int j = 0; j < scene.MeshCount; j++)
{
AssimpMesh assimpmesh = scene.Meshes[j];
List<int> inds = assimpmesh.Indices;
if (inds.Count > 0 && assimpmesh.VerticesCount > 0)
{
var indexstream = new DataStream(inds.Count * 4, true, true);
indexstream.WriteRange(inds.ToArray());
indexstream.Position = 0;
DX11IndexOnlyGeometry geom = new DX11IndexOnlyGeometry(context);
geom.IndexBuffer = new DX11IndexBuffer(context, indexstream, false, true);
geom.InputLayout = assimpmesh.GetInputElements().ToArray();
geom.Topology = PrimitiveTopology.TriangleList;
geom.HasBoundingBox = true;
geom.BoundingBox = assimpmesh.BoundingBox;
DX11DynamicStructuredBuffer<Vector3> p =
new DX11DynamicStructuredBuffer<Vector3>(context, assimpmesh.PositionPointer, assimpmesh.VerticesCount);
DX11DynamicStructuredBuffer<Vector3> n =
new DX11DynamicStructuredBuffer<Vector3>(context, assimpmesh.NormalsPointer, assimpmesh.VerticesCount);
if (assimpmesh.UvChannelCount > 0)
{
DX11DynamicStructuredBuffer<Vector3> u =
new DX11DynamicStructuredBuffer<Vector3>(context, assimpmesh.GetUvPointer(0), assimpmesh.VerticesCount);
this.FOutUvs[i][j][context] = u;
}
DX11RawBuffer rb = new DX11RawBuffer(context, geom.IndexBuffer.Buffer);
this.FOutPosition[i][j][context] = p;
this.FOutNormals[i][j][context] = n;
this.FOutGeom[i][j][context] = geom;
this.FOutIndices[i][j][context] = rb;
}
}
}*/
/* }
this.FInvalidate = false;
this.FEmpty = false;*/
}
}
public void Destroy(DX11RenderContext context, bool force)
{
}
}
}
| 34.36 | 140 | 0.505497 | [
"BSD-3-Clause"
] | azeno/dx11-vvvv | Nodes/VVVV.DX11.Nodes.Assimp/AssimpMergeLoaderNode.cs | 7,733 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.Iot.Transform;
using Aliyun.Acs.Iot.Transform.V20180120;
namespace Aliyun.Acs.Iot.Model.V20180120
{
public class CreateConsumerGroupSubscribeRelationRequest : RpcAcsRequest<CreateConsumerGroupSubscribeRelationResponse>
{
public CreateConsumerGroupSubscribeRelationRequest()
: base("Iot", "2018-01-20", "CreateConsumerGroupSubscribeRelation", "iot", "openAPI")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.Iot.Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.Iot.Endpoint.endpointRegionalType, null);
}
Method = MethodType.POST;
}
private string consumerGroupId;
private string iotInstanceId;
private string productKey;
public string ConsumerGroupId
{
get
{
return consumerGroupId;
}
set
{
consumerGroupId = value;
DictionaryUtil.Add(QueryParameters, "ConsumerGroupId", value);
}
}
public string IotInstanceId
{
get
{
return iotInstanceId;
}
set
{
iotInstanceId = value;
DictionaryUtil.Add(QueryParameters, "IotInstanceId", value);
}
}
public string ProductKey
{
get
{
return productKey;
}
set
{
productKey = value;
DictionaryUtil.Add(QueryParameters, "ProductKey", value);
}
}
public override CreateConsumerGroupSubscribeRelationResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return CreateConsumerGroupSubscribeRelationResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 29.893617 | 134 | 0.698577 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-iot/Iot/Model/V20180120/CreateConsumerGroupSubscribeRelationRequest.cs | 2,810 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.ProvideApplicationPartFactoryAttribute("Microsoft.AspNetCore.Mvc.ApplicationParts.CompiledRazorAssemblyApplicationPartFac" +
"tory, Microsoft.AspNetCore.Mvc.Razor")]
[assembly: System.Reflection.AssemblyCompanyAttribute("Online.Classified.App")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Release")]
[assembly: System.Reflection.AssemblyProductAttribute("Online.Classified.App")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyTitleAttribute("Online.Classified.App.Views")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 47.846154 | 177 | 0.691318 | [
"MIT"
] | sanoylab/Full-Stack-Dev-Challenge | asp_net_core5_mvc/Online.Classified.App/obj/Release/net5.0/Online.Classified.App.RazorTargetAssemblyInfo.cs | 1,244 | C# |
using dsbattery.Enums;
namespace dsbattery.Models
{
public class DualshockDevice
{
public DualshockDevice(string path)
{
Path = path;
}
public string Path { get; set; }
public int BatteryPercentage { get; set; }
public Ds4Status Status { get; set; }
public string Mac { get; set; }
}
} | 22.529412 | 51 | 0.548303 | [
"MIT"
] | FaithLV/dsbattery | src/dsbattery/Models/DualshockDevice.cs | 383 | C# |
using System;
using System.Collections.Generic;
using System.Drawing;
using Newtonsoft.Json;
using EnumExtend;
using Cli.Types;
namespace Cli.MasterData
{
public partial class Item
{
public string? Id { get; set; }
[JsonConverter(typeof(JsonEnumConverter<ItemType>))]
public ItemType Type { get; set; }
[JsonConverter(typeof(JsonEnumConverter<ItemSlotType>))]
public ItemSlotType SlotType { get; set; }
public string? Name { get; set; }
public float Weight { get; set; }
[JsonConverter(typeof(JsonEnumsConverter<ClassType>))]
public List<ClassType>? ClassLimit { get; set; }
public string? Icon { get; set; }
public string? Description { get; set; }
public int Lv { get; set; }
public int LvLimit { get; set; }
public int Mgt { get; set; }
public int Dex { get; set; }
public int Con { get; set; }
public int Int { get; set; }
public int Per { get; set; }
public int Res { get; set; }
}
}
| 21.653061 | 64 | 0.604147 | [
"MIT"
] | elky84/JsonTable | Cli/MasterData/Item.cs | 1,061 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using Microsoft.Templates.Core.Naming;
using Xunit;
namespace Microsoft.Templates.Core.Test
{
[Collection("Unit Test Templates")]
[Trait("ExecutionSet", "Minimum")]
public class FolderNameValidatorTests
{
[Fact]
public void Anything_InANonExistentConfigDirectory_IsValid()
{
var nonExistentDirectory = Path.Combine(Environment.CurrentDirectory, Guid.NewGuid().ToString()); // Use new GUID as a name for a folder that won't already exist
var sut = new FolderNameValidator(nonExistentDirectory);
var result = sut.Validate(Guid.NewGuid().ToString());
Assert.True(result.IsValid);
}
[Fact]
public void NewDirectory_InExistingConfigDirectory_IsValid()
{
var sut = new FolderNameValidator(Environment.CurrentDirectory);
var result = sut.Validate(Guid.NewGuid().ToString()); // Use new GUID as a name for a folder that won't already exist
Assert.True(result.IsValid);
}
[Fact]
public void ExistingDirectory_InAnExistingConfigDirectory_IsNotValid()
{
// Create directory so can be sure it exists
var existingDir = Directory.CreateDirectory(Path.Combine(Environment.CurrentDirectory, Guid.NewGuid().ToString()));
try
{
var sut = new FolderNameValidator(Environment.CurrentDirectory);
var result = sut.Validate(existingDir.Name);
Assert.False(result.IsValid);
}
finally
{
existingDir.Delete();
}
}
}
}
| 33.706897 | 174 | 0.616368 | [
"MIT"
] | MSCustomizedTemplates/CoreTemplateStudio | code/test/CoreTemplateStudio.Core.Test/Naming/FolderNameValidatorTests.cs | 1,900 | C# |
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
namespace NetOffice.MSHTMLApi
{
/// <summary>
/// DispatchInterface IHTMLDocument6
/// SupportByVersion MSHTML, 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
[EntityType(EntityType.IsDispatchInterface)]
public class IHTMLDocument6 : IHTMLDocument5
{
#pragma warning disable
#region Type Information
/// <summary>
/// Instance Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type InstanceType
{
get
{
return LateBindingApiWrapperType;
}
}
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(IHTMLDocument6);
return _type;
}
}
#endregion
#region Ctor
/// <param name="factory">current used factory core</param>
/// <param name="parentObject">object there has created the proxy</param>
/// <param name="proxyShare">proxy share instead if com proxy</param>
public IHTMLDocument6(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public IHTMLDocument6(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IHTMLDocument6(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IHTMLDocument6(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IHTMLDocument6(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IHTMLDocument6(ICOMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IHTMLDocument6() : base()
{
}
/// <param name="progId">registered progID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IHTMLDocument6(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public NetOffice.MSHTMLApi.IHTMLDocumentCompatibleInfoCollection compatible
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.MSHTMLApi.IHTMLDocumentCompatibleInfoCollection>(this, "compatible", NetOffice.MSHTMLApi.IHTMLDocumentCompatibleInfoCollection.LateBindingApiWrapperType);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object documentMode
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "documentMode");
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onstorage
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onstorage");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onstorage", value);
}
}
/// <summary>
/// SupportByVersion MSHTML 4
/// Get/Set
/// </summary>
[SupportByVersion("MSHTML", 4)]
public object onstoragecommit
{
get
{
return Factory.ExecuteVariantPropertyGet(this, "onstoragecommit");
}
set
{
Factory.ExecuteVariantPropertySet(this, "onstoragecommit", value);
}
}
#endregion
#region Methods
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
/// <param name="bstrId">string bstrId</param>
[SupportByVersion("MSHTML", 4)]
[BaseResult]
public NetOffice.MSHTMLApi.IHTMLElement2 getElementById(string bstrId)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.MSHTMLApi.IHTMLElement2>(this, "getElementById", bstrId);
}
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public void updateSettings()
{
Factory.ExecuteMethod(this, "updateSettings");
}
#endregion
#pragma warning restore
}
}
| 28.095477 | 216 | 0.69433 | [
"MIT"
] | NetOfficeFw/NetOffice | Source/MSHTML/DispatchInterfaces/IHTMLDocument6.cs | 5,593 | C# |
using System;
using ZedGraph;
using System.Linq;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;
namespace DIP_ImageProcessExample
{
class HistogramEqualization
{
TabControl tabControl1 = new TabControl();
public HistogramEqualization(TabControl tabControl)
{
this.tabControl1 = tabControl;
}
public Dictionary<string, Image> Answer(Image image)
{
List<string> problem = new List<string> { "before-histogram", "equalization", "after-histogram" };
Dictionary<string, Image> answer = new Dictionary<string, Image>();
foreach (string item in problem)
{
PictureBox pictureBox = new PictureBox();
pictureBox.Dock = DockStyle.Fill;
pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
TabPage tabPage = new TabPage(item);
tabPage.Controls.Add(pictureBox);
this.tabControl1.TabPages.Add(tabPage);
if (item.Contains("before-histogram")) Histogram(image, pictureBox);
if (item.Contains("equalization")) answer.Add(item, Equalization(image));
if (item.Contains("after-histogram")) Histogram(answer["equalization"], pictureBox);
if (answer.ContainsKey(item)) pictureBox.Image = answer[item];
}
return answer;
}
private void Histogram(Image image, PictureBox pictureBox)
{
Dictionary<int, double> pixel = new Dictionary<int, double>();
pixel = PDF(image);
PrintHistogram(pixel, pictureBox);
}
private Dictionary<int, double> PDF(Image image)
{
Bitmap bimage = new Bitmap(image);
Dictionary<int, double> pixel = new Dictionary<int, double>();
Dictionary<int, double> sortPixel = new Dictionary<int, double>();
for (int y = 0; y < image.Height; y++)
{
for (int x = 0; x < image.Width; x++)
{
Color RGB = bimage.GetPixel(x, y);
if (!pixel.ContainsKey(RGB.R)) pixel.Add(RGB.R, 0);
pixel[RGB.R] += 1;
}
}
sortPixel = pixel.OrderBy(x => x.Key).ToDictionary(x => x.Key, y => y.Value);
return sortPixel;
}
private void PrintHistogram(Dictionary<int, double> pixel, PictureBox pictureBox)
{
ZedGraphControl zedGraphControl = new ZedGraphControl();
zedGraphControl.Dock = DockStyle.Fill;
zedGraphControl.IsSynchronizeXAxes = true;
zedGraphControl.GraphPane.Title.IsVisible = false;
zedGraphControl.GraphPane.XAxis.Title.IsVisible = false;
zedGraphControl.GraphPane.YAxis.Title.IsVisible = false;
zedGraphControl.GraphPane.XAxis.MajorGrid.IsVisible = true;
zedGraphControl.GraphPane.YAxis.MajorGrid.IsVisible = true;
PointPairList pointPairList = new PointPairList();
foreach (int item in pixel.Keys) pointPairList.Add(item, pixel[item]);
GraphPane graphPane = zedGraphControl.GraphPane;
BarItem barItem = graphPane.AddBar("--", pointPairList, Color.Blue);
barItem.Label.IsVisible = false;
zedGraphControl.RestoreScale(graphPane);
pictureBox.Controls.Add(zedGraphControl);
}
private Bitmap Equalization(Image image)
{
Bitmap bimage = new Bitmap(image);
Dictionary<int, double> pdfPixel = new Dictionary<int, double>();
pdfPixel = PDF(image);
Dictionary<int, double> cdfPixel = new Dictionary<int, double>();
cdfPixel = CDF(pdfPixel);
for (int y = 0; y < image.Height; y++)
{
for (int x = 0; x < image.Width; x++)
{
Color RGB = bimage.GetPixel(x, y);
int invAvg = Convert.ToInt32(cdfPixel[RGB.R]);
bimage.SetPixel(x, y, Color.FromArgb(invAvg, invAvg, invAvg));
}
}
return bimage;
}
private Dictionary<int, double> CDF(Dictionary<int, double> pdfPixel)
{
Dictionary<int, double> cdfPixel = new Dictionary<int, double>();
foreach (int item in pdfPixel.Keys)
{
if (cdfPixel.Count == 0) cdfPixel.Add(pdfPixel.Keys.First(), pdfPixel.Values.First());
else cdfPixel.Add(item, pdfPixel[item] + cdfPixel.Values.Last());
}
Dictionary<int, double> equPixel = new Dictionary<int, double>();
foreach (int item in cdfPixel.Keys)
{
if (equPixel.Count == 0) { equPixel.Add(item, 0); continue; }
double temp = (cdfPixel[item] - cdfPixel.Values.Min()) / (cdfPixel.Values.Max() - cdfPixel.Values.Min());
equPixel.Add(item, Math.Round(temp * 255));
}
return equPixel;
}
}
}
| 39.218045 | 121 | 0.557515 | [
"MIT"
] | reverie0829/Image_Processing | VS2019_P76081116/IP_ProgramExample_C#/DIP_ImageProcessExample/HistogramEqualization.cs | 5,218 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Text.Json;
namespace Azure.Messaging.EventGrid.SystemEvents
{
/// <summary> Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceActionSuccess event. This is raised when a resource action operation succeeds. </summary>
public partial class ResourceActionSuccessEventData
{
/// <summary> Initializes a new instance of ResourceActionSuccessEventData. </summary>
internal ResourceActionSuccessEventData()
{
}
/// <summary> Initializes a new instance of ResourceActionSuccessEventData. </summary>
/// <param name="tenantId"> The tenant ID of the resource. </param>
/// <param name="subscriptionId"> The subscription ID of the resource. </param>
/// <param name="resourceGroup"> The resource group of the resource. </param>
/// <param name="resourceProvider"> The resource provider performing the operation. </param>
/// <param name="resourceUri"> The URI of the resource in the operation. </param>
/// <param name="operationName"> The operation that was performed. </param>
/// <param name="status"> The status of the operation. </param>
/// <param name="authorizationJson"> The requested authorization for the operation. </param>
/// <param name="claimsJson"> The properties of the claims. </param>
/// <param name="correlationId"> An operation ID used for troubleshooting. </param>
/// <param name="httpRequestJson"> The details of the operation. </param>
internal ResourceActionSuccessEventData(string tenantId, string subscriptionId, string resourceGroup, string resourceProvider, string resourceUri, string operationName, string status, JsonElement authorizationJson, JsonElement claimsJson, string correlationId, JsonElement httpRequestJson)
{
TenantId = tenantId;
SubscriptionId = subscriptionId;
ResourceGroup = resourceGroup;
ResourceProvider = resourceProvider;
ResourceUri = resourceUri;
OperationName = operationName;
Status = status;
AuthorizationJson = authorizationJson;
ClaimsJson = claimsJson;
CorrelationId = correlationId;
HttpRequestJson = httpRequestJson;
}
/// <summary> The tenant ID of the resource. </summary>
public string TenantId { get; }
/// <summary> The subscription ID of the resource. </summary>
public string SubscriptionId { get; }
/// <summary> The resource group of the resource. </summary>
public string ResourceGroup { get; }
/// <summary> The resource provider performing the operation. </summary>
public string ResourceProvider { get; }
/// <summary> The URI of the resource in the operation. </summary>
public string ResourceUri { get; }
/// <summary> The operation that was performed. </summary>
public string OperationName { get; }
/// <summary> The status of the operation. </summary>
public string Status { get; }
/// <summary> An operation ID used for troubleshooting. </summary>
public string CorrelationId { get; }
}
}
| 51.938462 | 297 | 0.668246 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/eventgrid/Azure.Messaging.EventGrid/src/Generated/Models/ResourceActionSuccessEventData.cs | 3,376 | C# |
using System;
using System.ComponentModel;
using System.Reflection;
/** Enumeration values for DetailedModAmpAndAngle
* The enumeration values are generated from the SISO DIS XML EBV document (R35), which was
* obtained from http://discussions.sisostds.org/default.asp?action=10&fd=31<p>
*
* Note that this has two ways to look up an enumerated instance from a value: a fast
* but brittle array lookup, and a slower and more garbage-intensive, but safer, method.
* if you want to minimize memory use, get rid of one or the other.<p>
*
* Copyright 2008-2009. This work is licensed under the BSD license, available at
* http://www.movesinstitute.org/licenses<p>
*
* @author DMcG, Jason Nelson
* Modified for use with C#:
* Peter Smith (Naval Air Warfare Center - Training Systems Division)
*/
namespace DISnet
{
public partial class DISEnumerations
{
public enum DetailedModAmpAndAngle
{
[Description("Other")]
OTHER = 0,
[Description("Amplitude and Angle")]
AMPLITUDE_AND_ANGLE = 1
}
} //End Parial Class
} //End Namespace
| 27.512195 | 92 | 0.692376 | [
"BSD-2-Clause"
] | rodneyp290/open-dis-csharp | C#/DIS#1.0/Examples/EnumerationExample/Enumerations/DetailedModAmpAndAngle.cs | 1,128 | 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 MusicPlayer
{
public partial class SignInForm : Form
{
public SignInForm()
{
InitializeComponent();
}
private void btn_SignIn_Click(object sender, EventArgs e)
{
if (txtBox_Username.Text == "")
{
MessageBox.Show("아이디를 입력하세요.");
return;
}
if (txtBox_Password.Text == "")
{
MessageBox.Show("비밀번호를 입력하세요.");
return;
}
if (txtBox_Email.Text == "")
{
MessageBox.Show("이메일을 입력하세요.");
return;
}
if (Database.Database.Instance.IsRegsistedUser(txtBox_Username.Text))
{
MessageBox.Show("이미 존재하는 아이디 입니다.");
return;
}
int index = Database.Database.Instance.GetLastIndex();
if (Database.Database.Instance.RegisterUserData(new User.User(index+1, txtBox_Username.Text, txtBox_Password.Text)))
{
MessageBox.Show("아이디가 성공적으로 만들어졌습니다.");
this.Close();
return;
}
else
{
MessageBox.Show("데이터베이스 접속에 실패했습니다. 나중에 다시 시도해주세요.");
return;
}
}
}
}
| 25.590164 | 128 | 0.504805 | [
"MIT"
] | 64byte/MusicPlayer | SignInForm.cs | 1,727 | C# |
using MXGP.Repositories.Contracts;
using MXGP.Models.Riders.Contracts;
using System.Collections.Generic;
using System.Linq;
namespace MXGP.Repositories
{
public class RiderRepository : IRepository<IRider>
{
private List<IRider> models;
public RiderRepository()
{
this.models = new List<IRider>();
}
public IReadOnlyCollection<IRider> Models
=> this.models;
public void Add(IRider model)
{
this.models.Add(model);
}
public IReadOnlyCollection<IRider> GetAll()
{
var collection = new List<IRider>();
foreach (var model in this.models)
{
collection.Add(model);
}
return collection.AsReadOnly();
}
public IRider GetByName(string name)
{
return this.models.FirstOrDefault(r => r.Name == name);
}
public bool Remove(IRider model)
{
var result = this.models.Remove(model);
return result;
}
}
}
| 23.695652 | 67 | 0.552294 | [
"MIT"
] | MrWeRtY/SoftUni-Repo | Exams/MotocrosWorldChampionshipMXGP/MXGP/Repositories/RiderRepository.cs | 1,092 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace IdentityServerHost.Quickstart.UI
{
public class LoggedOutViewModel
{
public string PostLogoutRedirectUri { get; set; }
public string ClientName { get; set; }
public string SignOutIframeUrl { get; set; }
public bool AutomaticRedirectAfterSignOut { get; set; }
public string LogoutId { get; set; }
public bool TriggerExternalSignout => ExternalAuthenticationScheme != null;
public string ExternalAuthenticationScheme { get; set; }
}
} | 36.368421 | 107 | 0.701881 | [
"Apache-2.0"
] | 10088/IdentityServer4 | samples/Quickstarts/6_AspNetIdentity/src/IdentityServerAspNetIdentity/Quickstart/Account/LoggedOutViewModel.cs | 693 | C# |
using System.Web.Mvc;
namespace SampleWeb
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
| 18.769231 | 80 | 0.643443 | [
"MIT"
] | tgrabus/feature-architecture | SampleWeb/App_Start/FilterConfig.cs | 246 | C# |
using Newtonsoft.Json;
namespace PddOpenSdk.Models.Response.Ddk
{
public partial class QueryDdkGoodsUnitResponseModel : PddResponseModel
{
/// <summary>
/// ddk_goods_unit_query_response
/// </summary>
[JsonProperty("ddk_goods_unit_query_response")]
public DdkGoodsUnitQueryResponseResponseModel DdkGoodsUnitQueryResponse { get; set; }
public partial class DdkGoodsUnitQueryResponseResponseModel : PddResponseModel
{
/// <summary>
/// 优惠券结束时间,单位:秒
/// </summary>
[JsonProperty("coupon_end_time")]
public long? CouponEndTime { get; set; }
/// <summary>
/// 优惠券id
/// </summary>
[JsonProperty("coupon_id")]
public string CouponId { get; set; }
/// <summary>
/// 优惠券开始时间,单位:秒
/// </summary>
[JsonProperty("coupon_start_time")]
public long? CouponStartTime { get; set; }
/// <summary>
/// 优惠券面额,单位:厘
/// </summary>
[JsonProperty("discount")]
public int? Discount { get; set; }
/// <summary>
/// 优惠券总数量
/// </summary>
[JsonProperty("init_quantity")]
public long? InitQuantity { get; set; }
/// <summary>
/// 商品的佣金比例,单位:千分位,比如100,表示10%
/// </summary>
[JsonProperty("rate")]
public int? Rate { get; set; }
/// <summary>
/// 优惠券剩余数量
/// </summary>
[JsonProperty("remain_quantity")]
public long? RemainQuantity { get; set; }
/// <summary>
/// 商品的推广计划类型,1-通用推广,2-专属推广,3-招商推广,4-全店推广
/// </summary>
[JsonProperty("unit_type")]
public int? UnitType { get; set; }
}
}
}
| 32.457627 | 93 | 0.49765 | [
"Apache-2.0"
] | CJ1210/open-pdd-net-sdk | PddOpenSdk/PddOpenSdk/Models/Response/Ddk/QueryDdkGoodsUnitResponseModel.cs | 2,113 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("testPrinter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("testPrinter")]
[assembly: AssemblyCopyright("Copyright © 2022")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("21853740-6cc9-409d-b195-fb4558f2c151")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 25.324324 | 56 | 0.716115 | [
"Apache-2.0"
] | xydoublez/PdfiumViewer | testPrinter/Properties/AssemblyInfo.cs | 1,278 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Terraria;
using Terraria.ModLoader;
using Microsoft.Xna.Framework;
namespace AmuletOfManyMinions.Dusts
{
class PlusDust : ModDust
{
public override void OnSpawn(Dust dust)
{
dust.noLight = true;
dust.scale = 1f;
dust.rotation = 0;
dust.frame = new Rectangle(0, 0, 10, 10);
dust.noGravity = true;
dust.alpha = 196;
}
public override bool Update(Dust dust)
{
dust.rotation = 0;
// stay above the head of the squire
Projectile myProj = Main.projectile[(int)dust.customData];
dust.velocity.X = myProj.velocity.X;
dust.velocity.Y = myProj.velocity.Y;
if(dust.alpha < 128)
{
dust.velocity.Y -= 0.1f;
} else
{
dust.velocity.Y -= 0.5f;
dust.velocity.Y -= (dust.dustIndex % 3) / 10f;
}
if(dust.alpha > 64)
{
dust.scale += 0.01f;
} else
{
dust.scale -= 0.05f;
}
dust.alpha -= 4;
if(dust.alpha <= 0)
{
dust.active = false;
}
dust.position += dust.velocity;
return false;
}
public override Color? GetAlpha(Dust dust, Color lightColor)
{
Color glowMask = Color.White;
glowMask.A = (byte)dust.alpha;
return glowMask;
}
}
class MinusDust: PlusDust
{
}
}
| 18.942029 | 62 | 0.641163 | [
"MIT"
] | Metallumere/tModLoader_Minions | Dusts/PlusDust.cs | 1,309 | C# |
using _01.Logger.Layout;
namespace _01.Logger.Factories
{
public class LayoutFactory
{
public static ILayout CreateLayout(string layoutArgs)
{
ILayout layout = null;
switch (layoutArgs)
{
case "SimpleLayout":
layout = new SimpleLayout();
break;
case "XmlLayout":
layout = new XmlLayout();
break;
}
return layout;
}
}
}
| 23 | 61 | 0.455577 | [
"MIT"
] | tsankotsanev/SoftUni-Software-University | CSharp-OOP/Homework/05.SOLID/01.Logger/Factories/LayoutFactory.cs | 531 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.SemanticLogging.Sinks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Practices.EnterpriseLibrary.SemanticLogging.Tests.EventListeners
{
[TestClass]
public class TallyKeepingFileStreamWriterTests
{
private string fileName = Guid.NewGuid().ToString();
[TestCleanup]
public void TearDown()
{
if (File.Exists(fileName))
{
File.Delete(fileName);
}
}
[TestMethod]
public void InitializesTallyForNewFile()
{
using (var writer
= new TallyKeepingFileStreamWriter(File.Open(fileName, FileMode.Append, FileAccess.Write, FileShare.Read)))
{
Assert.AreEqual(0L, writer.Tally);
}
}
[TestMethod]
public void InitializesTallyForExistingFile()
{
File.WriteAllText(fileName, "12345");
using (var writer
= new TallyKeepingFileStreamWriter(File.Open(fileName, FileMode.Append, FileAccess.Write, FileShare.Read)))
{
Assert.AreEqual(5L, writer.Tally);
}
File.WriteAllText(fileName, "12345");
using (var writer
= new TallyKeepingFileStreamWriter(File.Open(fileName, FileMode.Create, FileAccess.Write, FileShare.Read)))
{
Assert.AreEqual(0L, writer.Tally);
}
File.WriteAllText(fileName, "12345");
using (var writer
= new TallyKeepingFileStreamWriter(File.Open(fileName, FileMode.Truncate, FileAccess.Write, FileShare.Read)))
{
Assert.AreEqual(0L, writer.Tally);
}
}
[TestMethod]
public void WritingToFileUpdatesTally()
{
using (var writer
= new TallyKeepingFileStreamWriter(File.Open(fileName, FileMode.Append, FileAccess.Write, FileShare.Read)))
{
writer.Write("12345");
writer.Flush();
Assert.AreEqual(5L, writer.Tally);
}
}
[TestMethod]
public void WritingToFileWithEncodingUpdatesTally()
{
using (var writer
= new TallyKeepingFileStreamWriter(File.Open(fileName, FileMode.Append, FileAccess.Write, FileShare.Read),
Encoding.UTF32))
{
writer.Write("12345");
writer.Flush();
Assert.AreEqual(20L, writer.Tally); // BOM is not part of tally - minimal fidelity loss on new files.
}
}
}
}
| 33.420455 | 125 | 0.565794 | [
"Apache-2.0"
] | Meetsch/semantic-logging | source/Tests/SemanticLogging.Tests/Sinks/TallyKeepingFileStreamWriterTests.cs | 2,943 | C# |
using Microsoft.SharePoint.Client;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OfficeDevPnP.Core.Framework.Provisioning.Model;
using OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers;
using OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.TokenDefinitions;
using System;
namespace OfficeDevPnP.Core.Tests.Framework.ObjectHandlers
{
[TestClass]
public class TokenParserTests
{
[TestMethod]
public void ParseTests()
{
using (var ctx = TestCommon.CreateClientContext())
{
ctx.Load(ctx.Web,
w => w.Id,
w => w.ServerRelativeUrl,
w => w.Title,
w => w.AssociatedOwnerGroup.Title,
w => w.AssociatedMemberGroup.Title,
w => w.AssociatedVisitorGroup.Title,
w => w.AssociatedOwnerGroup.Id,
w => w.AssociatedMemberGroup.Id,
w => w.AssociatedVisitorGroup.Id);
ctx.Load(ctx.Site, s => s.ServerRelativeUrl, s => s.Owner);
var masterCatalog = ctx.Web.GetCatalog((int)ListTemplateType.MasterPageCatalog);
ctx.Load(masterCatalog, m => m.RootFolder.ServerRelativeUrl);
var themesCatalog = ctx.Web.GetCatalog((int)ListTemplateType.ThemeCatalog);
ctx.Load(themesCatalog, t => t.RootFolder.ServerRelativeUrl);
var expectedRoleDefinitionId = 1073741826;
var roleDefinition = ctx.Web.RoleDefinitions.GetById(expectedRoleDefinitionId);
ctx.Load(roleDefinition);
ctx.ExecuteQueryRetry();
var currentUser = ctx.Web.EnsureProperty(w => w.CurrentUser);
var ownerGroupName = ctx.Web.AssociatedOwnerGroup.Title;
ProvisioningTemplate template = new ProvisioningTemplate();
template.Parameters.Add("test", "test");
var parser = new TokenParser(ctx.Web, template);
parser.AddToken(new FieldIdToken(ctx.Web, "DemoField", new Guid("7E5E53E4-86C2-4A64-9F2E-FDFECE6219E0")));
var siteName = parser.ParseString("{sitename}");
var siteId = parser.ParseString("{siteid}");
var site = parser.ParseString("{site}/test");
var sitecol = parser.ParseString("{sitecollection}/test");
var masterUrl = parser.ParseString("{masterpagecatalog}/test");
var themeUrl = parser.ParseString("{themecatalog}/test");
var parameterTest = parser.ParseString("abc{parameter:TEST}/test");
var associatedOwnerGroup = parser.ParseString("{associatedownergroup}");
var associatedVisitorGroup = parser.ParseString("{associatedvisitorgroup}");
var associatedMemberGroup = parser.ParseString("{associatedmembergroup}");
var currentUserId = parser.ParseString("{currentuserid}");
var currentUserLoginName = parser.ParseString("{currentuserloginname}");
var currentUserFullName = parser.ParseString("{currentuserfullname}");
var guid = parser.ParseString("{guid}");
var associatedOwnerGroupId = parser.ParseString("{groupid:associatedownergroup}");
var associatedMemberGroupId = parser.ParseString("{groupid:associatedmembergroup}");
var associatedVisitorGroupId = parser.ParseString("{groupid:associatedvisitorgroup}");
var groupId = parser.ParseString($"{{groupid:{ownerGroupName}}}");
var siteOwner = parser.ParseString("{siteowner}");
var roleDefinitionId = parser.ParseString($"{{roledefinitionid:{roleDefinition.Name}}}");
var xamlEscapeString = "{}{0}Id";
var parsedXamlEscapeString = parser.ParseString(xamlEscapeString);
const string fieldRef = @"<FieldRefs><FieldRef Name=""DemoField"" ID=""{7E5E53E4-86C2-4A64-9F2E-FDFECE6219E0}"" /></FieldRefs></Field>";
var parsedFieldRef = parser.ParseString(@"<FieldRefs><FieldRef Name=""DemoField"" ID=""{{fieldid:DemoField}}"" /></FieldRefs></Field>");
Assert.IsTrue(site == $"{ctx.Web.ServerRelativeUrl}/test");
Assert.IsTrue(sitecol == $"{ctx.Site.ServerRelativeUrl}/test");
Assert.IsTrue(masterUrl == $"{masterCatalog.RootFolder.ServerRelativeUrl}/test");
Assert.IsTrue(themeUrl == $"{themesCatalog.RootFolder.ServerRelativeUrl}/test");
Assert.IsTrue(parameterTest == "abctest/test");
Assert.IsTrue(associatedOwnerGroup == ctx.Web.AssociatedOwnerGroup.Title);
Assert.IsTrue(associatedVisitorGroup == ctx.Web.AssociatedVisitorGroup.Title);
Assert.IsTrue(associatedMemberGroup == ctx.Web.AssociatedMemberGroup.Title);
Assert.IsTrue(siteName == ctx.Web.Title);
Assert.IsTrue(siteId == ctx.Web.Id.ToString());
Assert.IsTrue(currentUserId == currentUser.Id.ToString());
Assert.IsTrue(currentUserFullName == currentUser.Title);
Assert.IsTrue(currentUserLoginName.Equals(currentUser.LoginName, StringComparison.OrdinalIgnoreCase));
Guid outGuid;
Assert.IsTrue(Guid.TryParse(guid, out outGuid));
Assert.IsTrue(int.Parse(associatedOwnerGroupId) == ctx.Web.AssociatedOwnerGroup.Id);
Assert.IsTrue(int.Parse(associatedMemberGroupId) == ctx.Web.AssociatedMemberGroup.Id);
Assert.IsTrue(int.Parse(associatedVisitorGroupId) == ctx.Web.AssociatedVisitorGroup.Id);
Assert.IsTrue(associatedOwnerGroupId == groupId);
Assert.IsTrue(siteOwner == ctx.Site.Owner.LoginName);
Assert.IsTrue(roleDefinitionId == expectedRoleDefinitionId.ToString(), $"Role Definition Id was not parsed correctly (expected:{expectedRoleDefinitionId};returned:{roleDefinitionId})");
Assert.IsTrue(parsedXamlEscapeString == xamlEscapeString);
Assert.IsTrue(parsedFieldRef.ToUpperInvariant() == fieldRef.ToUpperInvariant());
}
}
[TestMethod]
public void RegexSpecialCharactersTests()
{
using (var ctx = TestCommon.CreateClientContext())
{
ctx.Load(ctx.Web, w => w.Id, w => w.ServerRelativeUrl, w => w.Title, w => w.AssociatedOwnerGroup.Title, w => w.AssociatedMemberGroup.Title, w => w.AssociatedVisitorGroup.Title);
ctx.Load(ctx.Site, s => s.ServerRelativeUrl);
ctx.ExecuteQueryRetry();
var currentUser = ctx.Web.EnsureProperty(w => w.CurrentUser);
ProvisioningTemplate template = new ProvisioningTemplate();
template.Parameters.Add("test(T)", "test");
template.Parameters.Add("a{b", "test");
var parser = new TokenParser(ctx.Web, template);
var web = ctx.Web;
var contentTypeName = "Test CT (TC) [TC].$";
var contentTypeId = "0x010801006439AECCDEAE4db2A422A3A04C79CC83";
var listGuid = Guid.NewGuid();
var listTitle = @"List (\,*+?|{[()^$.#";
var listUrl = "Lists/TestList";
var webPartTitle = @"Webpart (\*+?|{[()^$.#";
var webPartId = Guid.NewGuid();
var termSetName = @"Test TermSet (\*+?{[()^$.#";
var termGroupName = @"Group Name (\*+?{[()^$.#";
var termStoreName = @"Test TermStore (\*+?{[()^$.#";
var termSetId = Guid.NewGuid();
var termStoreId = Guid.NewGuid();
var resolvedTermGroupName = parser.ParseString("{sitecollectiontermgroupname}");
// Use fake data
parser.AddToken(new ContentTypeIdToken(web, contentTypeName, contentTypeId));
parser.AddToken(new ListIdToken(web, listTitle, listGuid));
parser.AddToken(new ListUrlToken(web, listTitle, listUrl));
parser.AddToken(new WebPartIdToken(web, webPartTitle, webPartId));
parser.AddToken(new TermSetIdToken(web, termGroupName, termSetName, termSetId));
parser.AddToken(new TermSetIdToken(web, resolvedTermGroupName, termSetName, termSetId));
parser.AddToken(new TermStoreIdToken(web, termStoreName, termStoreId));
var resolvedContentTypeId = parser.ParseString($"{{contenttypeid:{contentTypeName}}}");
var resolvedListId = parser.ParseString($"{{listid:{listTitle}}}");
var resolvedListUrl = parser.ParseString($"{{listurl:{listTitle}}}");
var parameterExpectedResult = $"abc{"test"}/test";
var parameterTest1 = parser.ParseString("abc{parameter:TEST(T)}/test");
var parameterTest2 = parser.ParseString("abc{parameter:a{b}/test");
var resolvedWebpartId = parser.ParseString($"{{webpartid:{webPartTitle}}}");
var resolvedTermSetId = parser.ParseString($"{{termsetid:{termGroupName}:{termSetName}}}");
var resolvedTermSetId2 = parser.ParseString($"{{termsetid:{{sitecollectiontermgroupname}}:{termSetName}}}");
var resolvedTermStoreId = parser.ParseString($"{{termstoreid:{termStoreName}}}");
Assert.IsTrue(contentTypeId == resolvedContentTypeId);
Assert.IsTrue(listUrl == resolvedListUrl);
Guid outGuid;
Assert.IsTrue(Guid.TryParse(resolvedListId, out outGuid));
Assert.IsTrue(parameterTest1 == parameterExpectedResult);
Assert.IsTrue(parameterTest2 == parameterExpectedResult);
Assert.IsTrue(Guid.TryParse(resolvedWebpartId, out outGuid));
Assert.IsTrue(Guid.TryParse(resolvedTermSetId, out outGuid));
Assert.IsTrue(Guid.TryParse(resolvedTermSetId2, out outGuid));
Assert.IsTrue(Guid.TryParse(resolvedTermStoreId, out outGuid));
}
}
[TestMethod]
[Timeout(1 * 60 * 1000)]
public void NestedTokenTests()
{
using (var ctx = TestCommon.CreateClientContext())
{
ctx.Load(ctx.Web, w => w.Id, w => w.ServerRelativeUrl, w => w.Title, w => w.AssociatedOwnerGroup.Title, w => w.AssociatedMemberGroup.Title, w => w.AssociatedVisitorGroup.Title);
ctx.Load(ctx.Site, s => s.ServerRelativeUrl);
ctx.ExecuteQueryRetry();
var template = new ProvisioningTemplate();
template.Parameters.Add("test3", "reallynestedvalue:{parameter:test2}");
template.Parameters.Add("test1", "testValue");
template.Parameters.Add("test2", "value:{parameter:test1}");
// Test parameters that infinitely loop
template.Parameters.Add("chain1", "{parameter:chain3}");
template.Parameters.Add("chain2", "{parameter:chain1}");
template.Parameters.Add("chain3", "{parameter:chain2}");
var parser = new TokenParser(ctx.Web, template);
var parameterTest1 = parser.ParseString("parameterTest:{parameter:test1}");
var parameterTest2 = parser.ParseString("parameterTest:{parameter:test2}");
var parameterTest3 = parser.ParseString("parameterTest:{parameter:test3}");
Assert.IsTrue(parameterTest1 == "parameterTest:testValue");
Assert.IsTrue(parameterTest2 == "parameterTest:value:testValue");
Assert.IsTrue(parameterTest3 == "parameterTest:reallynestedvalue:value:testValue");
var chainTest1 = parser.ParseString("parameterTest:{parameter:chain1}");
// Parser should stop processing parent tokens when processing nested tokens,
// so we should end up with the value of the last param (chain2) in our param chain,
// which will not get detokenized.
Assert.IsTrue(chainTest1 == "parameterTest:{parameter:chain1}");
}
}
[TestMethod]
public void WebPartTests()
{
using (var ctx = TestCommon.CreateClientContext())
{
ctx.Load(ctx.Web, w => w.Id, w => w.ServerRelativeUrl, w => w.Title, w => w.AssociatedOwnerGroup.Title, w => w.AssociatedMemberGroup.Title, w => w.AssociatedVisitorGroup.Title);
ctx.Load(ctx.Site, s => s.ServerRelativeUrl);
ctx.ExecuteQueryRetry();
var listGuid = Guid.NewGuid();
var listTitle = "MyList";
var web = ctx.Web;
ProvisioningTemplate template = new ProvisioningTemplate();
template.Parameters.Add("test", "test");
var parser = new TokenParser(ctx.Web, template);
parser.AddToken(new ListIdToken(web, listTitle, listGuid));
parser.ParseString($"{{listid:{listTitle}}}");
var listId = parser.ParseStringWebPart($"{{listid:{listTitle}}}", web, null);
Assert.IsTrue(listGuid.ToString() == listId);
var parameterValue = parser.ParseStringWebPart("{parameter:test}", web, null);
Assert.IsTrue("test" == parameterValue);
}
}
}
} | 56.443983 | 201 | 0.603837 | [
"MIT"
] | larslynch/PnP-Sites-Core | Core/OfficeDevPnP.Core.Tests/Framework/ObjectHandlers/TokenParserTests.cs | 13,605 | C# |
using Qwiq.Credentials;
using Microsoft.VisualStudio.Services.Client;
using Microsoft.VisualStudio.Services.Common;
using System;
using System.Collections.Generic;
namespace Qwiq
{
/// <exclude />
public static class IntegrationSettings
{
/// <exclude />
public static Func<AuthenticationTypes, IEnumerable<VssCredentials>> Credentials = UnitTestCredentialsFactory;
/// <exclude />
public static string[] Domains = { "microsoft.com" };
/// <exclude />
public static Guid ProjectGuid = Guid.Parse("8d47e068-03c8-4cdc-aa9b-fc6929290322");
/// <exclude />
public static string TenantId = "72F988BF-86F1-41AF-91AB-2D7CD011DB47";
private static readonly Uri Uri = new Uri("https://microsoft.visualstudio.com/defaultcollection");
/// <exclude />
public static AuthenticationOptions AuthenticationOptions { get; } = new AuthenticationOptions(Uri, AuthenticationTypes.Windows, Credentials);
/// <exclude />
public static Func<IWorkItemStore> CreateRestStore { get; } = () =>
{
var options = AuthenticationOptions;
var wis = Client.Rest.WorkItemStoreFactory.Default.Create(options);
Configure(wis);
return wis;
};
private static void Configure(IWorkItemStore wis)
{
wis.Configuration.PageSize = 200;
wis.Configuration.LazyLoadingEnabled = true;
wis.Configuration.ProxyCreationEnabled = true;
}
/// <exclude />
public static Func<IWorkItemStore> CreateSoapStore { get; } = () =>
{
var options = AuthenticationOptions;
var wis = Client.Soap.WorkItemStoreFactory.Default.Create(options);
Configure(wis);
return wis;
};
/// <exclude />
public static bool IsContiniousIntegrationEnvironment { get; } =
Comparer.OrdinalIgnoreCase.Equals("True", Environment.GetEnvironmentVariable("CI"))
|| Comparer.OrdinalIgnoreCase.Equals("True", Environment.GetEnvironmentVariable("APPVEYOR"));
private static IEnumerable<VssCredentials> UnitTestCredentialsFactory(AuthenticationTypes types)
{
if (types.HasFlag(AuthenticationTypes.Windows))
{
// User did not specify a username or a password, so use the process identity
yield return new VssClientCredentials(new WindowsCredential(false)) { Storage = new VssClientCredentialStorage(), PromptType = CredentialPromptType.DoNotPrompt };
if (IsContiniousIntegrationEnvironment) yield break;
// Use the Windows identity of the logged on user
yield return new VssClientCredentials(true) { Storage = new VssClientCredentialStorage(), PromptType = CredentialPromptType.PromptIfNeeded };
}
}
}
} | 50.917808 | 178 | 0.510358 | [
"MIT"
] | rjmurillo/Qwiq | test/Qwiq.Integration.Tests/IntegrationSettings.cs | 3,717 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2016-11-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Container for the parameters to the ResetInstanceAttribute operation.
/// Resets an attribute of an instance to its default value. To reset the <code>kernel</code>
/// or <code>ramdisk</code>, the instance must be in a stopped state. To reset the <code>sourceDestCheck</code>,
/// the instance can be either running or stopped.
///
///
/// <para>
/// The <code>sourceDestCheck</code> attribute controls whether source/destination checking
/// is enabled. The default value is <code>true</code>, which means checking is enabled.
/// This value must be <code>false</code> for a NAT instance to perform NAT. For more
/// information, see <a href="https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_NAT_Instance.html">NAT
/// Instances</a> in the <i>Amazon VPC User Guide</i>.
/// </para>
/// </summary>
public partial class ResetInstanceAttributeRequest : AmazonEC2Request
{
private InstanceAttributeName _attribute;
private string _instanceId;
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public ResetInstanceAttributeRequest() { }
/// <summary>
/// Instantiates ResetInstanceAttributeRequest with the parameterized properties
/// </summary>
/// <param name="instanceId">The ID of the instance.</param>
/// <param name="attribute">The attribute to reset. <important> You can only reset the following attributes: <code>kernel</code> | <code>ramdisk</code> | <code>sourceDestCheck</code>. </important></param>
public ResetInstanceAttributeRequest(string instanceId, InstanceAttributeName attribute)
{
_instanceId = instanceId;
_attribute = attribute;
}
/// <summary>
/// Gets and sets the property Attribute.
/// <para>
/// The attribute to reset.
/// </para>
/// <important>
/// <para>
/// You can only reset the following attributes: <code>kernel</code> | <code>ramdisk</code>
/// | <code>sourceDestCheck</code>.
/// </para>
/// </important>
/// </summary>
[AWSProperty(Required=true)]
public InstanceAttributeName Attribute
{
get { return this._attribute; }
set { this._attribute = value; }
}
// Check to see if Attribute property is set
internal bool IsSetAttribute()
{
return this._attribute != null;
}
/// <summary>
/// Gets and sets the property InstanceId.
/// <para>
/// The ID of the instance.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string InstanceId
{
get { return this._instanceId; }
set { this._instanceId = value; }
}
// Check to see if InstanceId property is set
internal bool IsSetInstanceId()
{
return this._instanceId != null;
}
}
} | 36.223214 | 212 | 0.629529 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/EC2/Generated/Model/ResetInstanceAttributeRequest.cs | 4,057 | 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("Gcpe.News.ReleaseManagement.Legacy")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Gcpe.News.ReleaseManagement.Legacy")]
[assembly: AssemblyCopyright("")]
[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("a30288c5-64e3-4f6f-a36c-70b359e84651")]
// 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.486486 | 84 | 0.748596 | [
"Apache-2.0"
] | AlessiaYChen/gcpe-hub | Hub.Legacy/Gcpe.News.ReleaseManagement.Legacy/Properties/AssemblyInfo.cs | 1,426 | C# |
using System;
using System.Reflection;
namespace SplitViewModelAssembly.ViewModels
{
public static class ViewTypeToViewModelTypeResolver
{
private static readonly Assembly LocalAssembly = typeof(ViewTypeToViewModelTypeResolver).Assembly;
public static Type Resolve(Type viewType)
{
if (viewType == null) throw new ArgumentNullException(nameof(viewType));
// ReSharper disable once PossibleNullReferenceException
var vmTypeName = $"{viewType.Namespace.Replace("Views", "ViewModels")}.{viewType.Name}ViewModel";
return LocalAssembly.GetType(vmTypeName);
}
}
}
| 34.368421 | 109 | 0.70291 | [
"MIT"
] | nuitsjp/WPF-Samples | SplitViewModelAssembly.ViewModels/ViewTypeToViewModelTypeResolver.cs | 655 | C# |
/*
This file is part of CNCLib - A library for stepper motors.
Copyright (c) Herbert Aitenbichler
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.Collections.Generic;
using System.Threading.Tasks;
using CNCLib.Repository.Abstraction.Entities;
using Framework.Repository.Abstraction;
namespace CNCLib.Repository.Abstraction
{
public interface IItemRepository : ICRUDRepository<Item, int>
{
Task<IList<Item>> Get(string typeIdString);
}
} | 49.233333 | 160 | 0.779959 | [
"MIT"
] | vpilat/CNCLib | Src/Repository.Abstraction/IItemRepository.cs | 1,479 | C# |
// File generated from our OpenAPI spec
namespace Stripe
{
public class ChargePaymentMethodDetailsCardWalletAmexExpressCheckout : StripeEntity<ChargePaymentMethodDetailsCardWalletAmexExpressCheckout>
{
}
}
| 27.25 | 144 | 0.821101 | [
"Apache-2.0"
] | GigiAkamala/stripe-dotnet | src/Stripe.net/Entities/Charges/ChargePaymentMethodDetailsCardWalletAmexExpressCheckout.cs | 218 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Bindables;
using osu.Framework.Extensions.Colour4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Localisation;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Overlays.Profile.Header;
using osu.Game.Resources.Localisation.Web;
using osu.Game.Users;
namespace osu.Game.Overlays.Profile
{
public class ProfileHeader : TabControlOverlayHeader<LocalisableString>
{
private UserCoverBackground coverContainer;
public Bindable<APIUser> User = new Bindable<APIUser>();
private CentreHeaderContainer centreHeaderContainer;
private DetailHeaderContainer detailHeaderContainer;
public ProfileHeader()
{
ContentSidePadding = UserProfileOverlay.CONTENT_X_MARGIN;
User.ValueChanged += e => updateDisplay(e.NewValue);
TabControl.AddItem(LayoutStrings.HeaderUsersShow);
TabControl.AddItem(LayoutStrings.HeaderUsersModding);
centreHeaderContainer.DetailsVisible.BindValueChanged(visible => detailHeaderContainer.Expanded = visible.NewValue, true);
}
protected override Drawable CreateBackground() =>
new Container
{
RelativeSizeAxes = Axes.X,
Height = 150,
Masking = true,
Children = new Drawable[]
{
coverContainer = new ProfileCoverBackground
{
RelativeSizeAxes = Axes.Both,
},
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = ColourInfo.GradientVertical(Colour4Extensions.FromHex("222").Opacity(0.8f), Colour4Extensions.FromHex("222").Opacity(0.2f))
},
}
};
protected override Drawable CreateContent() => new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
new TopHeaderContainer
{
RelativeSizeAxes = Axes.X,
User = { BindTarget = User },
},
centreHeaderContainer = new CentreHeaderContainer
{
RelativeSizeAxes = Axes.X,
User = { BindTarget = User },
},
detailHeaderContainer = new DetailHeaderContainer
{
RelativeSizeAxes = Axes.X,
User = { BindTarget = User },
},
new MedalHeaderContainer
{
RelativeSizeAxes = Axes.X,
User = { BindTarget = User },
},
new BottomHeaderContainer
{
RelativeSizeAxes = Axes.X,
User = { BindTarget = User },
},
}
};
protected override OverlayTitle CreateTitle() => new ProfileHeaderTitle();
private void updateDisplay(APIUser user) => coverContainer.User = user;
private class ProfileHeaderTitle : OverlayTitle
{
public ProfileHeaderTitle()
{
Title = PageTitleStrings.MainUsersControllerDefault;
IconTexture = "Icons/Hexacons/profile";
}
}
private class ProfileCoverBackground : UserCoverBackground
{
protected override double LoadDelay => 0;
}
}
}
| 35.663717 | 157 | 0.545658 | [
"MIT"
] | Azyyyyyy/osu | osu.Game/Overlays/Profile/ProfileHeader.cs | 3,920 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Alocha.WebUi.Helpers;
using Alocha.WebUi.Models;
using Microsoft.AspNetCore.Mvc;
namespace Alocha.WebUi.Controllers
{
public class MessageController : Controller
{
public IActionResult Index(IdMessage message)
{
MessageVM model = new MessageVM();
if (message == IdMessage.AccountLock)
{
model.Topic = "Blokada";
model.Message = "Twoje konto zostało zablokowane spróbuj ponownie później.";
model.LinkUrl = "/Account/LogIn";
model.LinkName = "Wróć";
}
else
if (message == IdMessage.SendConfirmEmailSucces)
{
model.Topic = "Powodzenie";
model.Message = "Na Adres Email został wysłany link potwierdzajacy konto.";
model.LinkUrl = "/Account/LogIn";
model.LinkName = "Wróć";
}
else
if (message == IdMessage.SendConfirmEmailError)
{
model.Topic = "Błąd";
model.Message = "Niestety nie udało się wysłać maila z potwierdzeniem, skontaktuj się proszę z administratorem.";
model.LinkUrl = "/Account/LogIn";
model.LinkName = "Wróć";
}
else
if (message == IdMessage.EmailConfirmedSucces)
{
model.Topic = "Powodzenie";
model.Message = "Dziękujemy za potwierdzenie konta, zostaniesz przekierowany do ekranu logowania.";
model.LinkUrl = "/Account/LogIn";
model.LinkName = "Wróć";
}
else
if (message == IdMessage.EmailConfirmedError)
{
model.Topic = "Błąd";
model.Message = "Niestety nie udało się potwierdzic konta, skontaktuj się proszę z administartorem.";
model.LinkUrl = "/Account/LogIn";
model.LinkName = "Wróć";
}
else
if (message == IdMessage.ResetPasswordTokenSendSucces)
{
model.Topic = "Powodzenie";
model.Message = "Link do zmiany hasła został wysłany na podany adres Email.";
model.LinkUrl = "/Account/LogIn";
model.LinkName = "Wróć";
}
else
if (message == IdMessage.ResetPasswordTokenSendError)
{
model.Topic = "Błąd";
model.Message = "Niestety nie udało sie wysłać liku do zmiany hasła.";
model.LinkUrl = "/Account/LogIn";
model.LinkName = "Wróć";
}
else
if (message == IdMessage.ResetPasswordSucces)
{
model.Topic = "Powodzenie";
model.Message = "Hasło zostało pomyślnie zresetowane.";
model.LinkUrl = "/Account/LogIn";
model.LinkName = "Wróć";
}
else
if (message == IdMessage.ChangePasswordSucces)
{
model.Topic = "Powodzenie";
model.Message = "Hasło zostało pomyślnie zmienione.";
model.LinkUrl = "/User/Index";
model.LinkName = "Wróć";
}
else
if (message == IdMessage.AddPhoneNumberSucces)
{
model.Topic = "Powodzenie";
model.Message = "Numer wymaga potwierdzenie dlatego został wysłany sms z kodem potwierdzającym.";
model.LinkUrl = "/User/ConfirmPhoneNumber";
model.LinkName = "Potwierdź";
}
else
if (message == IdMessage.AddPhoneNumberError)
{
model.Topic = "Błąd";
model.Message = "Niestety nie udało się dodać numeru telefonu.";
model.LinkUrl = "/User/Index";
model.LinkName = "Wróć";
}
else
if (message == IdMessage.RemovePhoneNumberSucces)
{
model.Topic = "Powodzenie";
model.Message = "Numer telefonu został usunięty pomyślnie.";
model.LinkUrl = "/User/Index";
model.LinkName = "Wróć";
}
else
if (message == IdMessage.RemovePhoneNumberError)
{
model.Topic = "Błąd";
model.Message = "Nie udało się usunąć numeru telefonu.";
model.LinkUrl = "/User/Index";
model.LinkName = "Wróć";
}
else
if (message == IdMessage.ConfirmedPhoneNumberSucces)
{
model.Topic = "Powodzenie";
model.Message = "Numer telefonu został potwierdzony pomyślnie.";
model.LinkUrl = "/User/Index";
model.LinkName = "OK";
}
else
if (message == IdMessage.ConfirmedPhoneNumberError)
{
model.Topic = "Błąd";
model.Message = "Niestety nie udało się potwierdzić numeru telefonu.";
model.LinkUrl = "/User/Index";
model.LinkName = "Wróć";
}
else
if (message == IdMessage.AdminSendConfirmationEmailSucces)
{
model.Topic = "Powodzenie";
model.Message = "Na adres klienta został wysłany link do potwierdzenia adresu Email.";
model.LinkUrl = "/ManagementAdmin/Index";
model.LinkName = "OK";
}
else
if (message == IdMessage.AdminSendConfirmationEmailError)
{
model.Topic = "Błąd";
model.Message = "Niestety nie udało się wysłać potwierdzenia na adres Email.";
model.LinkUrl = "/ManagementAdmin/Index";
model.LinkName = "Wróć";
}
else
if (message == IdMessage.AdminDeleteAccountSucces)
{
model.Topic = "Powodzenie";
model.Message = "Użytkownik został prawidłowo usunięty.";
model.LinkUrl = "/ManagementAdmin/Index";
model.LinkName = "OK";
}
else
if (message == IdMessage.AdminDeleteAccountError)
{
model.Topic = "Błąd";
model.Message = "Niestety nie udało się usunąć użytkownika w logach zostały zawarte szczegóły.";
model.LinkUrl = "/ManagementAdmin/Index";
model.LinkName = "Wróć";
}
else
if (message == IdMessage.UserDeleteAccountSucces)
{
model.Topic = "Powodzenie";
model.Message = "Konto zostało pomyślnie usunięte, dziękujemy za uzytkowanie naszego oprogramowania.";
model.LinkUrl = "/Account/LogIn";
model.LinkName = "OK";
}
else
return RedirectToAction("Index", "Home");
return View(model);
}
}
} | 39.510989 | 129 | 0.509665 | [
"MIT"
] | kamil0508/Alocha.core | Alocha/Controllers/MessageController.cs | 7,310 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using WPF.Tools.BaseClasses;
namespace REPORT.Data.SQLRepository.Agrigates
{
public abstract class LookupBase : ModelsBase
{
private string _LookupGroup;
private int _GroupKey;
private string _GroupDescription;
// Primary Keys
[Key]
public string LookupGroup
{
get
{
return this._LookupGroup;
}
set
{
base.OnPropertyChanged("LookupGroup", ref this._LookupGroup, value);
}
}
[Key]
public int GroupKey
{
get
{
return this._GroupKey;
}
set
{
base.OnPropertyChanged("GroupKey", ref this._GroupKey, value);
}
}
// Foreign Keys
// Columns
public string GroupDescription
{
get
{
return this._GroupDescription;
}
set
{
base.OnPropertyChanged("GroupDescription", ref this._GroupDescription, value);
}
}
}
} | 14.538462 | 82 | 0.673016 | [
"BSD-3-Clause"
] | hansievanstraaten/ERD-Application | ERD SourceCode/REPORT.Data/SQLRepository/Agrigates/Base/LookupBase.cs | 945 | C# |
#nullable enable
using System;
using System.Collections.Generic;
using Content.Shared.Body.Components;
using Content.Shared.Body.Part;
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.ViewVariables;
namespace Content.Shared.Body.Preset
{
/// <summary>
/// Defines the parts used in a body.
/// </summary>
[Prototype("bodyPreset")]
[Serializable, NetSerializable]
public class BodyPresetPrototype : IPrototype
{
[ViewVariables]
[DataField("id", required: true)]
public string ID { get; } = default!;
[DataField("partIDs")]
private Dictionary<string, string> _partIDs = new();
[ViewVariables]
[DataField("name")]
public string Name { get; } = string.Empty;
[ViewVariables]
public Dictionary<string, string> PartIDs => new(_partIDs);
}
}
| 27.085714 | 67 | 0.669831 | [
"MIT"
] | Bright0/space-station-14 | Content.Shared/Body/Preset/BodyPresetPrototype.cs | 950 | C# |
using FikaAmazonAPI.AmazonSpApiSDK.Models.MerchantFulfillment;
using FikaAmazonAPI.Search;
using System;
using System.Collections.Generic;
using System.Text;
namespace FikaAmazonAPI.Services
{
public class MerchantFulfillmentService : RequestService
{
public MerchantFulfillmentService(AmazonCredential amazonCredential) : base(amazonCredential)
{
}
public GetEligibleShipmentServicesResult GetEligibleShipmentServicesOld(GetEligibleShipmentServicesRequest getEligibleShipmentServicesRequest)
{
CreateAuthorizedRequest(MerchantFulfillmentApiUrls.GetEligibleShipmentServicesOld, RestSharp.Method.POST,postJsonObj: getEligibleShipmentServicesRequest);
var response = ExecuteRequest<GetEligibleShipmentServicesResponse>();
if (response != null && response.Payload != null)
return response.Payload;
return null;
}
public GetEligibleShipmentServicesResult GetEligibleShipmentServices(GetEligibleShipmentServicesRequest getEligibleShipmentServicesRequest)
{
CreateAuthorizedRequest(MerchantFulfillmentApiUrls.GetEligibleShipmentServices, RestSharp.Method.POST, postJsonObj: getEligibleShipmentServicesRequest);
var response = ExecuteRequest<GetEligibleShipmentServicesResponse>();
if (response != null && response.Payload != null)
return response.Payload;
return null;
}
public Shipment GetShipment(string shipmentId, IParameterBasedPII ParameterBasedPII = null)
{
CreateAuthorizedRequest(MerchantFulfillmentApiUrls.GetShipment(shipmentId), RestSharp.Method.GET,parameter: ParameterBasedPII);
var response = ExecuteRequest<GetShipmentResponse>();
if (response != null && response.Payload != null)
return response.Payload;
return null;
}
public Shipment CancelShipment(string shipmentId, IParameterBasedPII ParameterBasedPII = null)
{
CreateAuthorizedRequest(MerchantFulfillmentApiUrls.GetShipment(shipmentId), RestSharp.Method.DELETE, parameter: ParameterBasedPII);
var response = ExecuteRequest<GetShipmentResponse>();
if (response != null && response.Payload != null)
return response.Payload;
return null;
}
public Shipment CancelShipmentOld(string shipmentId, IParameterBasedPII ParameterBasedPII = null)
{
CreateAuthorizedRequest(MerchantFulfillmentApiUrls.CancelShipmentOld(shipmentId), RestSharp.Method.PUT, parameter: ParameterBasedPII);
var response = ExecuteRequest<GetShipmentResponse>();
if (response != null && response.Payload != null)
return response.Payload;
return null;
}
public Shipment CreateShipment(CreateShipmentRequest createShipmentRequest, IParameterBasedPII ParameterBasedPII = null)
{
CreateAuthorizedRequest(MerchantFulfillmentApiUrls.CreateShipment, RestSharp.Method.POST,postJsonObj: createShipmentRequest, parameter: ParameterBasedPII);
var response = ExecuteRequest<CreateShipmentResponse>();
if (response != null && response.Payload != null)
return response.Payload;
return null;
}
public GetAdditionalSellerInputsResult GetAdditionalSellerInputsOld(GetAdditionalSellerInputsRequest getAdditionalSellerInputsRequest)
{
CreateAuthorizedRequest(MerchantFulfillmentApiUrls.GetAdditionalSellerInputsOld, RestSharp.Method.POST,postJsonObj: getAdditionalSellerInputsRequest);
var response = ExecuteRequest<GetAdditionalSellerInputsResponse>();
if (response != null && response.Payload != null)
return response.Payload;
return null;
}
public GetAdditionalSellerInputsResult GetAdditionalSellerInputs(GetAdditionalSellerInputsRequest getAdditionalSellerInputsRequest)
{
CreateAuthorizedRequest(MerchantFulfillmentApiUrls.GetAdditionalSellerInputs, RestSharp.Method.POST, postJsonObj: getAdditionalSellerInputsRequest);
var response = ExecuteRequest<GetAdditionalSellerInputsResponse>();
if (response != null && response.Payload != null)
return response.Payload;
return null;
}
}
}
| 46.051546 | 167 | 0.707634 | [
"MIT"
] | IvanMConnex/Amazon-SP-API-CSharp | Source/FikaAmazonAPI/Services/MerchantFulfillmentService.cs | 4,469 | C# |
/*
* Elemental Annotations <https://github.com/takeshik/ElementalAnnotations>
* Copyright © 2015 Takeshi KIRIYA (aka takeshik) <takeshik@tksk.io>
* Licensed under the zlib License; for details, see the website.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
// ReSharper disable CheckNamespace
#if ELEMENTAL_ANNOTATIONS_DEFAULT_NAMESPACE
namespace Elemental.Annotations
#else
namespace BattleInfoPlugin.Annotations
#endif
// ReSharper restore CheckNamespace
{
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
[Conditional("DEBUG")]
public abstract class ElementalAttribute
: Attribute
{
public string Description { get; private set; }
protected ElementalAttribute(string description = null)
{
this.Description = description;
}
}
public static partial class CodeElement
{
private static readonly Lazy<IReadOnlyDictionary<Type, string>> _elements =
new Lazy<IReadOnlyDictionary<Type, string>>(() => typeof(CodeElement).GetTypeInfo().Assembly.DefinedTypes
.Where(x => x.IsSubclassOf(typeof(ElementalAttribute)))
.ToDictionary(x => x.AsType(), x => (string) x.GetDeclaredField("Name").GetValue(null))
);
public static IEnumerable<Type> Types
{
get
{
return _elements.Value.Keys;
}
}
public static IEnumerable<string> Names
{
get
{
return _elements.Value.Values;
}
}
public static ILookup<string, string> GetElements(MemberInfo member, bool inherit = true)
{
return member.GetCustomAttributes(typeof(ElementalAttribute), inherit)
.Cast<ElementalAttribute>()
.MakeLookup();
}
public static ILookup<string, string> GetElements(ParameterInfo parameter, bool inherit = true)
{
return parameter.GetCustomAttributes(typeof(ElementalAttribute), inherit)
.Cast<ElementalAttribute>()
.MakeLookup();
}
public static ILookup<string, string> GetElements(Module module)
{
return module.GetCustomAttributes(typeof(ElementalAttribute))
.Cast<ElementalAttribute>()
.MakeLookup();
}
public static ILookup<string, string> GetElements(Assembly assembly)
{
return assembly.GetCustomAttributes(typeof(ElementalAttribute))
.Cast<ElementalAttribute>()
.MakeLookup();
}
private static ILookup<string, string> MakeLookup(this IEnumerable<ElementalAttribute> attributes)
{
return attributes.ToLookup(x => _elements.Value[x.GetType()], x => x.Description);
}
}
}
| 27 | 108 | 0.741143 | [
"MIT"
] | CirnoV/BattleInfoPlugin | BattleInfoPlugin/Annotations/ElementalAttribute.cs | 2,485 | C# |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace Senai.ShirtStore.WebApi.Domains
{
public partial class ShirtStoreContext : DbContext
{
public ShirtStoreContext()
{
}
public ShirtStoreContext(DbContextOptions<ShirtStoreContext> options)
: base(options)
{
}
public virtual DbSet<Camiseta> Camiseta { get; set; }
public virtual DbSet<Cor> Cor { get; set; }
public virtual DbSet<Estoque> Estoque { get; set; }
public virtual DbSet<Marca> Marca { get; set; }
public virtual DbSet<Perfil> Perfil { get; set; }
public virtual DbSet<Tamanho> Tamanho { get; set; }
public virtual DbSet<Usuario> Usuario { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer("Data Source=.\\SqlExpress;Initial Catalog=T_ShirtStore;User Id=sa;Pwd=132;");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Camiseta>(entity =>
{
entity.HasKey(e => e.IdCamiseta);
entity.Property(e => e.Descricao)
.HasMaxLength(255)
.IsUnicode(false);
entity.HasOne(d => d.IdCorNavigation)
.WithMany(p => p.Camiseta)
.HasForeignKey(d => d.IdCor)
.HasConstraintName("FK__Camiseta__IdCor__628FA481");
entity.HasOne(d => d.IdEstoqueNavigation)
.WithMany(p => p.Camiseta)
.HasForeignKey(d => d.IdEstoque)
.HasConstraintName("FK__Camiseta__IdEsto__656C112C");
entity.HasOne(d => d.IdMarcaNavigation)
.WithMany(p => p.Camiseta)
.HasForeignKey(d => d.IdMarca)
.HasConstraintName("FK__Camiseta__IdMarc__6477ECF3");
entity.HasOne(d => d.IdTamanhoNavigation)
.WithMany(p => p.Camiseta)
.HasForeignKey(d => d.IdTamanho)
.HasConstraintName("FK__Camiseta__IdTama__6383C8BA");
});
modelBuilder.Entity<Cor>(entity =>
{
entity.HasKey(e => e.IdCor);
entity.Property(e => e.Nome)
.HasMaxLength(255)
.IsUnicode(false);
});
modelBuilder.Entity<Estoque>(entity =>
{
entity.HasKey(e => e.IdEstoque);
entity.Property(e => e.Nome)
.HasMaxLength(255)
.IsUnicode(false);
});
modelBuilder.Entity<Marca>(entity =>
{
entity.HasKey(e => e.IdMarca);
entity.HasIndex(e => e.Nome)
.HasName("UQ__Marca__7D8FE3B223408A78")
.IsUnique();
entity.Property(e => e.Nome)
.IsRequired()
.HasMaxLength(255)
.IsUnicode(false);
});
modelBuilder.Entity<Perfil>(entity =>
{
entity.HasKey(e => e.IdPerfil);
entity.HasIndex(e => e.Nome)
.HasName("UQ__Perfil__7D8FE3B26824B936")
.IsUnique();
entity.Property(e => e.Nome)
.IsRequired()
.HasMaxLength(255)
.IsUnicode(false);
});
modelBuilder.Entity<Tamanho>(entity =>
{
entity.HasKey(e => e.IdTamanho);
entity.Property(e => e.Nome)
.HasMaxLength(255)
.IsUnicode(false);
});
modelBuilder.Entity<Usuario>(entity =>
{
entity.HasKey(e => e.IdUsuario);
entity.HasIndex(e => e.Email)
.HasName("UQ__Usuario__A9D105349DA48A09")
.IsUnique();
entity.HasIndex(e => e.Nome)
.HasName("UQ__Usuario__7D8FE3B2C9A2E52E")
.IsUnique();
entity.Property(e => e.Email)
.IsRequired()
.HasMaxLength(255)
.IsUnicode(false);
entity.Property(e => e.Nome)
.IsRequired()
.HasMaxLength(255)
.IsUnicode(false);
entity.Property(e => e.Senha)
.HasMaxLength(255)
.IsUnicode(false);
});
}
}
}
| 33.74 | 213 | 0.497925 | [
"MIT"
] | silvaemiliaborges/ShirtStore | Senai.ShirtStore.WebApi/Senai.ShirtStore.WebApi/Contexts/ShirtStoreContext.cs | 5,063 | C# |
using System.Xml;
namespace DataDynamics.PageFX.Flash.Swf
{
public sealed class SwfFocalGradient : SwfGradient
{
public float FocalPoint { get; set; }
public override void Read(SwfReader reader, bool alpha)
{
base.Read(reader, alpha);
FocalPoint = reader.ReadFixed16();
}
public override void Write(SwfWriter writer, bool alpha)
{
base.Write(writer, alpha);
writer.WriteFixed16(FocalPoint);
}
public override void DumpBody(XmlWriter writer, bool alpha)
{
base.DumpBody(writer, alpha);
writer.WriteElementString("focal-point", FocalPoint.ToString());
}
}
} | 23.185185 | 68 | 0.690096 | [
"MIT"
] | GrapeCity/pagefx | source/libs/Flash/SWF/SwfFocalGradient.cs | 626 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//------------------------------------------------------------------------------
using System.Data.Common;
using System.Diagnostics;
using System.Threading.Tasks;
namespace System.Data.ProviderBase
{
abstract internal class DbConnectionClosed : DbConnectionInternal
{
// Construct an "empty" connection
protected DbConnectionClosed(ConnectionState state, bool hidePassword, bool allowSetConnectionString) : base(state, hidePassword, allowSetConnectionString)
{
}
override public string ServerVersion
{
get
{
throw ADP.ClosedConnectionError();
}
}
override protected void Activate()
{
throw ADP.ClosedConnectionError();
}
override public DbTransaction BeginTransaction(IsolationLevel il)
{
throw ADP.ClosedConnectionError();
}
override public void ChangeDatabase(string database)
{
throw ADP.ClosedConnectionError();
}
internal override void CloseConnection(DbConnection owningObject, DbConnectionFactory connectionFactory)
{
// not much to do here...
}
override protected void Deactivate()
{
throw ADP.ClosedConnectionError();
}
protected override DbReferenceCollection CreateReferenceCollection()
{
throw ADP.ClosedConnectionError();
}
internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, bool isAsync, DbConnectionOptions userOptions, ref TaskCompletionSource<DbConnectionInternal> completionSource)
{
return base.TryOpenConnectionInternal(outerConnection, connectionFactory, isAsync, ref completionSource, userOptions);
}
}
abstract internal class DbConnectionBusy : DbConnectionClosed
{
protected DbConnectionBusy(ConnectionState state) : base(state, true, false)
{
}
internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, bool isAsync, DbConnectionOptions userOptions, ref TaskCompletionSource<DbConnectionInternal> completionSource)
{
throw ADP.ConnectionAlreadyOpen(State);
}
}
sealed internal class DbConnectionClosedBusy : DbConnectionBusy
{
// Closed Connection, Currently Busy - changing connection string
internal static readonly DbConnectionInternal SingletonInstance = new DbConnectionClosedBusy(); // singleton object
private DbConnectionClosedBusy() : base(ConnectionState.Closed)
{
}
}
sealed internal class DbConnectionOpenBusy : DbConnectionBusy
{
// Open Connection, Currently Busy - closing connection
internal static readonly DbConnectionInternal SingletonInstance = new DbConnectionOpenBusy(); // singleton object
private DbConnectionOpenBusy() : base(ConnectionState.Open)
{
}
}
sealed internal class DbConnectionClosedConnecting : DbConnectionBusy
{
// Closed Connection, Currently Connecting
internal static readonly DbConnectionInternal SingletonInstance = new DbConnectionClosedConnecting(); // singleton object
private DbConnectionClosedConnecting() : base(ConnectionState.Connecting)
{
}
internal override void CloseConnection(DbConnection owningObject, DbConnectionFactory connectionFactory)
{
connectionFactory.SetInnerConnectionTo(owningObject, DbConnectionClosedPreviouslyOpened.SingletonInstance);
}
internal override bool TryReplaceConnection(DbConnection outerConnection, bool isAsync, DbConnectionFactory connectionFactory, DbConnectionOptions userOptions, ref TaskCompletionSource<DbConnectionInternal> completionSource)
{
return TryOpenConnection(outerConnection, connectionFactory, isAsync: isAsync, userOptions: userOptions, completionSource: ref completionSource);
}
internal override bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, bool isAsync, DbConnectionOptions userOptions, ref TaskCompletionSource<DbConnectionInternal> completionSource)
{
if (completionSource == null || !completionSource.Task.IsCompleted)
{
// retry is null if this is a synchronous call
// if someone calls Open or OpenAsync while in this state,
// then the retry task will not be completed
throw ADP.ConnectionAlreadyOpen(State);
}
// we are completing an asynchronous open
Debug.Assert(completionSource.Task.Status == TaskStatus.RanToCompletion, "retry task must be completed successfully");
DbConnectionInternal openConnection = completionSource.Task.Result;
if (null == openConnection)
{
connectionFactory.SetInnerConnectionTo(outerConnection, this);
throw ADP.InternalConnectionError(ADP.ConnectionError.GetConnectionReturnsNull);
}
connectionFactory.SetInnerConnectionEvent(outerConnection, openConnection);
return true;
}
}
sealed internal class DbConnectionClosedNeverOpened : DbConnectionClosed
{
// Closed Connection, Has Never Been Opened
internal static readonly DbConnectionInternal SingletonInstance = new DbConnectionClosedNeverOpened(); // singleton object
private DbConnectionClosedNeverOpened() : base(ConnectionState.Closed, false, true)
{
}
}
sealed internal class DbConnectionClosedPreviouslyOpened : DbConnectionClosed
{
// Closed Connection, Has Previously Been Opened
internal static readonly DbConnectionInternal SingletonInstance = new DbConnectionClosedPreviouslyOpened(); // singleton object
private DbConnectionClosedPreviouslyOpened() : base(ConnectionState.Closed, true, true)
{
}
internal override bool TryReplaceConnection(DbConnection outerConnection, bool isAsync, DbConnectionFactory connectionFactory, DbConnectionOptions userOptions, ref TaskCompletionSource<DbConnectionInternal> completionSource)
{
return TryOpenConnection(outerConnection, connectionFactory, isAsync: isAsync, userOptions: userOptions, completionSource: ref completionSource);
}
}
}
| 39.208092 | 232 | 0.692909 | [
"MIT"
] | dpaoliello/SqlClientSlim | src/SqlClientSlim/System/Data/ProviderBase/DbConnectionClosed.cs | 6,783 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using CoreGraphics;
using CoreLocation;
using Foundation;
using MapKit;
using ObjCRuntime;
using TK.CustomMap;
using TK.CustomMap.iOSUnified;
using TK.CustomMap.Interfaces;
using TK.CustomMap.Models;
using TK.CustomMap.Overlays;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using System.Collections;
using Xamarin.iOS.ClusterKit;
// ReSharper disable InconsistentNaming
// ReSharper disable SuspiciousTypeConversion.Global
[assembly: ExportRenderer(typeof(TKCustomMap), typeof(TKCustomMapRenderer))]
namespace TK.CustomMap.iOSUnified
{
/// <summary>
/// iOS Renderer of <see cref="TK.CustomMap.TKCustomMap"/>
/// </summary>
[Preserve(AllMembers = true)]
public class TKCustomMapRenderer : ViewRenderer<TKCustomMap, MKMapView>, IRendererFunctions
{
const double MercatorRadius = 85445659.44705395;
const string AnnotationIdentifier = "TKCustomAnnotation";
const string AnnotationIdentifierDefaultPin = "TKCustomAnnotationDefaultPin";
const string AnnotationIdentifierDefaultClusterPin = "TKDefaultClusterPin";
readonly List<TKRoute> _tempRouteList = new List<TKRoute>();
readonly Dictionary<MKPolyline, TKOverlayItem<TKRoute, MKPolylineRenderer>> _routes = new Dictionary<MKPolyline, TKOverlayItem<TKRoute, MKPolylineRenderer>>();
readonly Dictionary<MKPolyline, TKOverlayItem<TKPolyline, MKPolylineRenderer>> _lines = new Dictionary<MKPolyline, TKOverlayItem<TKPolyline, MKPolylineRenderer>>();
readonly Dictionary<MKCircle, TKOverlayItem<TKCircle, MKCircleRenderer>> _circles = new Dictionary<MKCircle, TKOverlayItem<TKCircle, MKCircleRenderer>>();
readonly Dictionary<MKPolygon, TKOverlayItem<TKPolygon, MKPolygonRenderer>> _polygons = new Dictionary<MKPolygon, TKOverlayItem<TKPolygon, MKPolygonRenderer>>();
bool _isDragging;
bool _disposed;
IMKAnnotation _selectedAnnotation;
MKTileOverlay _tileOverlay;
MKTileOverlayRenderer _tileOverlayRenderer;
UIGestureRecognizer _longPressGestureRecognizer;
UIGestureRecognizer _tapGestureRecognizer;
UIGestureRecognizer _doubleTapGestureRecognizer;
CLLocationManager _locationManager;
TKClusterMap _clusterMap;
private TKOverlayItem<TKPolygon, MKPolygonRenderer> _polygonRenderer;
private TKOverlayItem<TKRoute, MKPolylineRenderer> _routeRenderer;
private TKOverlayItem<TKPolyline, MKPolylineRenderer> _lineRenderer;
private TKOverlayItem<TKCircle, MKCircleRenderer> _circleRenderer;
MKMapView Map => Control as MKMapView;
TKCustomMap FormsMap => Element as TKCustomMap;
IMapFunctions MapFunctions => Element as IMapFunctions;
/// <summary>
/// Gets/Sets if the default pin drop animation is enabled
/// </summary>
public static bool AnimateOnPinDrop { get; set; } = true;
/// <summary>
/// Dummy function to avoid linker.
/// </summary>
[Preserve]
public static void InitMapRenderer()
{
// ReSharper disable once UnusedVariable
var temp = DateTime.Now;
}
/// <inheritdoc/>
protected override void OnElementChanged(ElementChangedEventArgs<TKCustomMap> e)
{
base.OnElementChanged(e);
if (e.OldElement != null && Map != null)
{
e.OldElement.PropertyChanged -= OnMapPropertyChanged;
Map.GetViewForAnnotation = null;
Map.OverlayRenderer = null;
Map.DidSelectAnnotationView -= OnDidSelectAnnotationView;
Map.RegionChanged -= OnMapRegionChanged;
Map.DidUpdateUserLocation -= OnDidUpdateUserLocation;
Map.ChangedDragState -= OnChangedDragState;
Map.CalloutAccessoryControlTapped -= OnMapCalloutAccessoryControlTapped;
UnregisterCollections(e.OldElement);
Map.RemoveGestureRecognizer(_longPressGestureRecognizer);
Map.RemoveGestureRecognizer(_tapGestureRecognizer);
Map.RemoveGestureRecognizer(_doubleTapGestureRecognizer);
_longPressGestureRecognizer.Dispose();
_tapGestureRecognizer.Dispose();
_doubleTapGestureRecognizer.Dispose();
}
if (e.NewElement == null) return;
if (Control == null)
{
var mapView = new MKMapView();
SetNativeControl(mapView);
}
MapFunctions.SetRenderer(this);
if (FormsMap.IsClusteringEnabled)
{
_clusterMap = new TKClusterMap(Map);
}
if (Map == null) return;
Map.GetViewForAnnotation = GetViewForAnnotation;
Map.OverlayRenderer = GetOverlayRenderer;
Map.DidSelectAnnotationView += OnDidSelectAnnotationView;
Map.RegionChanged += OnMapRegionChanged;
Map.DidUpdateUserLocation += OnDidUpdateUserLocation;
Map.ChangedDragState += OnChangedDragState;
Map.CalloutAccessoryControlTapped += OnMapCalloutAccessoryControlTapped;
Map.AddGestureRecognizer((_longPressGestureRecognizer = new UILongPressGestureRecognizer(OnMapLongPress)));
_doubleTapGestureRecognizer = new UITapGestureRecognizer() { NumberOfTapsRequired = 2 };
_tapGestureRecognizer = new UITapGestureRecognizer(OnMapClicked);
_tapGestureRecognizer.RequireGestureRecognizerToFail(_doubleTapGestureRecognizer);
_tapGestureRecognizer.ShouldReceiveTouch = (recognizer, touch) => !(touch.View is MKAnnotationView);
Map.AddGestureRecognizer(_tapGestureRecognizer);
Map.AddGestureRecognizer(_doubleTapGestureRecognizer);
UpdateTileOptions();
UpdatePins();
UpdateRoutes();
UpdateLines();
UpdateCircles();
UpdatePolygons();
UpdateShowTraffic();
UpdateMapRegion();
UpdateMapType();
UpdateIsShowingUser();
UpdateHasScrollEnabled();
UpdateHasZoomEnabled();
FormsMap.PropertyChanged += OnMapPropertyChanged;
MapFunctions.RaiseMapReady();
}
/// <summary>
/// Get the overlay renderer
/// </summary>
/// <param name="mapView">The <see cref="MKMapView"/></param>
/// <param name="overlay">The overlay to render</param>
/// <returns>The overlay renderer</returns>
MKOverlayRenderer GetOverlayRenderer(MKMapView mapView, IMKOverlay overlay)
{
switch (overlay)
{
case MKPolyline polyline when _routes.TryGetValue(polyline, out var route):
{
_routeRenderer = route;
if (_routeRenderer.Renderer == null)
{
_routeRenderer.Renderer = new MKPolylineRenderer(polyline);
}
_routeRenderer.Renderer.FillColor = route.Overlay.Color.ToUIColor();
_routeRenderer.Renderer.LineWidth = route.Overlay.LineWidth;
_routeRenderer.Renderer.StrokeColor = route.Overlay.Color.ToUIColor();
return _routeRenderer.Renderer;
}
case MKPolyline polyline when _lines.TryGetValue(polyline, out var line):
{
_lineRenderer = line;
if (_lineRenderer.Renderer == null)
{
_lineRenderer.Renderer = new MKPolylineRenderer(polyline);
}
_lineRenderer.Renderer.FillColor = _lineRenderer.Overlay.Color.ToUIColor();
_lineRenderer.Renderer.LineWidth = _lineRenderer.Overlay.LineWidth;
_lineRenderer.Renderer.StrokeColor = _lineRenderer.Overlay.Color.ToUIColor();
// return renderer for the line
return _lineRenderer.Renderer;
}
case MKCircle mkCircle:
{
_circleRenderer = _circles[mkCircle];
if (_circleRenderer.Renderer == null)
{
_circleRenderer.Renderer = new MKCircleRenderer(mkCircle);
}
_circleRenderer.Renderer.FillColor = _circleRenderer.Overlay.Color.ToUIColor();
_circleRenderer.Renderer.StrokeColor = _circleRenderer.Overlay.StrokeColor.ToUIColor();
_circleRenderer.Renderer.LineWidth = _circleRenderer.Overlay.StrokeWidth;
return _circleRenderer.Renderer;
}
case MKPolygon mkPolygon:
{
_polygonRenderer = _polygons[mkPolygon];
if (_polygonRenderer.Renderer == null)
{
_polygonRenderer.Renderer = new MKPolygonRenderer(mkPolygon);
}
_polygonRenderer.Renderer.FillColor = _polygonRenderer.Overlay.Color.ToUIColor();
_polygonRenderer.Renderer.StrokeColor = _polygonRenderer.Overlay.StrokeColor.ToUIColor();
_polygonRenderer.Renderer.LineWidth = _polygonRenderer.Overlay.StrokeWidth;
return _polygonRenderer.Renderer;
}
case MKTileOverlay _:
_tileOverlayRenderer?.Dispose();
return (_tileOverlayRenderer = new MKTileOverlayRenderer(_tileOverlay));
default:
return null;
}
}
/// <summary>
/// When the user location changed
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnDidUpdateUserLocation(object sender, MKUserLocationEventArgs e)
{
if (e.UserLocation == null || FormsMap == null || FormsMap.UserLocationChangedCommand == null) return;
var newPosition = e.UserLocation.Location.Coordinate.ToPosition();
MapFunctions.RaiseUserLocationChanged(newPosition);
}
/// <summary>
/// When a property of the forms map changed
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnMapPropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case nameof(TKCustomMap.Pins):
UpdatePins();
break;
case nameof(TKCustomMap.SelectedPin):
SetSelectedPin();
break;
case nameof(TKCustomMap.Polylines):
UpdateLines();
break;
case nameof(TKCustomMap.Circles):
UpdateCircles();
break;
case nameof(TKCustomMap.Polygons):
UpdatePolygons();
break;
case nameof(TKCustomMap.Routes):
UpdateRoutes();
break;
case nameof(TKCustomMap.TilesUrlOptions):
UpdateTileOptions();
break;
case nameof(TKCustomMap.ShowTraffic):
UpdateShowTraffic();
break;
case nameof(TKCustomMap.MapRegion):
UpdateMapRegion();
break;
case nameof(TKCustomMap.IsClusteringEnabled):
UpdateIsClusteringEnabled();
break;
case nameof(TKCustomMap.MapType):
UpdateMapType();
break;
case nameof(TKCustomMap.IsShowingUser):
UpdateIsShowingUser();
break;
case nameof(TKCustomMap.HasScrollEnabled):
UpdateHasScrollEnabled();
break;
case nameof(TKCustomMap.HasZoomEnabled):
UpdateHasZoomEnabled();
break;
}
}
/// <summary>
/// When the collection of pins changed
/// </summary>
/// <param name="sender">Event sender</param>
/// <param name="e">Event arguments</param>
void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (TKCustomMapPin pin in e.NewItems)
{
AddPin(pin);
}
}
else if (e.Action == NotifyCollectionChangedAction.Remove)
{
List<TKCustomMapAnnotation> annotationsToRemove = new List<TKCustomMapAnnotation>();
foreach (TKCustomMapPin pin in e.OldItems)
{
if (!FormsMap.Pins.Contains(pin))
{
if (FormsMap.SelectedPin != null && FormsMap.SelectedPin.Equals(pin))
{
FormsMap.SelectedPin = null;
}
var annotation = GetCustomAnnotation(pin);
if (annotation != null)
{
annotation.CustomPin.PropertyChanged -= OnPinPropertyChanged;
annotationsToRemove.Add(annotation);
}
}
}
if (FormsMap.IsClusteringEnabled)
{
_clusterMap.ClusterManager.RemoveAnnotations(annotationsToRemove.Cast<MKAnnotation>().ToArray());
}
else
{
Map.RemoveAnnotations(annotationsToRemove.Cast<IMKAnnotation>().ToArray());
}
}
else if (e.Action == NotifyCollectionChangedAction.Reset)
{
IEnumerable<IMKAnnotation> annotations = FormsMap.IsClusteringEnabled ? _clusterMap.ClusterManager.Annotations : Map.Annotations;
foreach (var annotation in annotations.OfType<TKCustomMapAnnotation>())
{
annotation.CustomPin.PropertyChanged -= OnPinPropertyChanged;
}
UpdatePins(false);
}
}
/// <summary>
/// When the accessory control of a callout gets tapped
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnMapCalloutAccessoryControlTapped(object sender, MKMapViewAccessoryTappedEventArgs e)
{
MapFunctions.RaiseCalloutClicked(GetPinByAnnotation(e.View.Annotation));
}
/// <summary>
/// When the drag state changed
/// </summary>
/// <param name="sender">Event sender</param>
/// <param name="e">Event Arguments</param>
void OnChangedDragState(object sender, MKMapViewDragStateEventArgs e)
{
var annotation = GetCustomAnnotation(e.AnnotationView);
if (annotation == null) return;
if (e.NewState == MKAnnotationViewDragState.Starting)
{
_isDragging = true;
}
else if (e.NewState == MKAnnotationViewDragState.Dragging)
{
annotation.CustomPin.Position = e.AnnotationView.Annotation.Coordinate.ToPosition();
}
else if (e.NewState == MKAnnotationViewDragState.Ending || e.NewState == MKAnnotationViewDragState.Canceling)
{
if (FormsMap.IsClusteringEnabled)
{
var ckCluster = Runtime.GetNSObject(e.AnnotationView.Annotation.Handle) as CKCluster;
if (!(ckCluster is null))
{
annotation.SetCoordinateInternal(ckCluster.Coordinate, true);
}
}
if (!(e.AnnotationView is MKPinAnnotationView))
e.AnnotationView.DragState = MKAnnotationViewDragState.None;
_isDragging = false;
MapFunctions.RaisePinDragEnd(annotation.CustomPin);
}
}
/// <summary>
/// When the camera region changed
/// </summary>
/// <param name="sender">Event sender</param>
/// <param name="e">Event Arguments</param>
void OnMapRegionChanged(object sender, MKMapViewChangeEventArgs e)
{
FormsMap.MapRegion = Map.GetCurrentMapRegion();
if (FormsMap.IsClusteringEnabled)
{
_clusterMap.ClusterManager.UpdateClustersIfNeeded();
}
}
/// <summary>
/// When an annotation view got selected
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
public virtual void OnDidSelectAnnotationView(object sender, MKAnnotationViewEventArgs e)
{
var pin = GetCustomAnnotation(e.View);
if (pin == null) return;
_selectedAnnotation = e.View.Annotation;
FormsMap.SelectedPin = pin.CustomPin;
MapFunctions.RaisePinSelected(pin.CustomPin);
}
/// <summary>
/// When a tap was perfomed on the map
/// </summary>
/// <param name="recognizer">The gesture recognizer</param>
void OnMapClicked(UITapGestureRecognizer recognizer)
{
if (recognizer.State != UIGestureRecognizerState.Ended) return;
var pixelLocation = recognizer.LocationInView(Map);
var coordinate = Map.ConvertPoint(pixelLocation, Map);
if (FormsMap.Routes != null)
{
if (FormsMap.RouteClickedCommand != null)
{
double maxMeters = MetersFromPixel(22, pixelLocation);
double nearestDistance = double.MaxValue;
TKRoute nearestRoute = null;
foreach (var route in FormsMap.Routes.Where(i => i.Selectable))
{
var internalItem = _routes.Single(i => i.Value.Overlay.Equals(route));
var distance = DistanceOfPoint(MKMapPoint.FromCoordinate(coordinate), internalItem.Key);
if (distance < nearestDistance)
{
nearestDistance = distance;
nearestRoute = internalItem.Value.Overlay;
}
}
if (nearestDistance <= maxMeters)
{
MapFunctions.RaiseRouteClicked(nearestRoute);
return;
}
}
}
MapFunctions.RaiseMapClicked(coordinate.ToPosition());
}
/// <summary>
/// When a long press was performed
/// </summary>
/// <param name="recognizer">The gesture recognizer</param>
void OnMapLongPress(UILongPressGestureRecognizer recognizer)
{
if (recognizer.State != UIGestureRecognizerState.Began) return;
var pixelLocation = recognizer.LocationInView(Map);
var coordinate = Map.ConvertPoint(pixelLocation, Map);
MapFunctions.RaiseMapLongPress(coordinate.ToPosition());
}
/// <summary>
/// Get the view for the annotation
/// </summary>
/// <param name="mapView">The map</param>
/// <param name="annotation">The annotation</param>
/// <returns>The annotation view</returns>
public virtual MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation)
{
var clusterAnnotation = annotation as CKCluster;
var createDefaultClusterAnnotationView = false;
MKAnnotationView annotationView;
TKCustomMapAnnotation customAnnotation = null;
if (clusterAnnotation == null)
{
customAnnotation = annotation as TKCustomMapAnnotation;
}
else
{
if (clusterAnnotation.Count > 1)
{
var clusterPin = FormsMap.GetClusteredPin?.Invoke(null, clusterAnnotation.Annotations.OfType<TKCustomMapAnnotation>().Select(i => i.CustomPin));
if (clusterPin == null)
{
createDefaultClusterAnnotationView = true;
}
else
{
customAnnotation = new TKCustomMapAnnotation(clusterPin);
}
}
else
{
customAnnotation = clusterAnnotation.FirstAnnotation as TKCustomMapAnnotation;
}
}
if (createDefaultClusterAnnotationView)
{
annotationView = mapView.DequeueReusableAnnotation(AnnotationIdentifierDefaultClusterPin);
if (annotationView == null)
{
annotationView = new TKDefaultClusterAnnotationView(clusterAnnotation, AnnotationIdentifierDefaultClusterPin);
}
else
{
annotationView.Annotation = clusterAnnotation;
(annotationView as TKDefaultClusterAnnotationView)?.Configure();
}
}
else
{
if (customAnnotation == null) return null;
if (customAnnotation.CustomPin.Image != null)
{
annotationView = mapView.DequeueReusableAnnotation(AnnotationIdentifier);
}
else
{
annotationView = mapView.DequeueReusableAnnotation(AnnotationIdentifierDefaultPin);
}
if (annotationView == null)
{
if (customAnnotation.CustomPin.Image != null)
{
annotationView = new MKAnnotationView(customAnnotation, AnnotationIdentifier);
annotationView.Layer.AnchorPoint = new CGPoint(customAnnotation.CustomPin.Anchor.X, customAnnotation.CustomPin.Anchor.Y);
}
else
{
annotationView = new MKPinAnnotationView(customAnnotation, AnnotationIdentifierDefaultPin);
}
}
else
{
annotationView.Annotation = customAnnotation;
}
annotationView.CanShowCallout = customAnnotation.CustomPin.ShowCallout;
annotationView.Draggable = customAnnotation.CustomPin.IsDraggable;
annotationView.Selected = _selectedAnnotation != null && customAnnotation.Equals(_selectedAnnotation);
annotationView.Transform = CGAffineTransform.MakeRotation((float)customAnnotation.CustomPin.Rotation.ToRadian());
SetAnnotationViewVisibility(annotationView, customAnnotation.CustomPin);
UpdateImage(annotationView, customAnnotation.CustomPin);
UpdateAccessoryView(customAnnotation.CustomPin, annotationView);
}
return annotationView;
}
/// <summary>
/// Update the callout accessory view
/// </summary>
/// <param name="pin">Custom pin</param>
/// <param name="view">Annotation view</param>
void UpdateAccessoryView(TKCustomMapPin pin, MKAnnotationView view)
{
if (pin.IsCalloutClickable)
{
var button = new UIButton(UIButtonType.InfoLight);
button.Frame = new CGRect(0, 0, 23, 23);
button.HorizontalAlignment = UIControlContentHorizontalAlignment.Center;
button.VerticalAlignment = UIControlContentVerticalAlignment.Center;
view.RightCalloutAccessoryView = button;
}
else
{
view.RightCalloutAccessoryView = null;
}
}
/// <summary>
/// Creates the annotations
/// </summary>
void UpdatePins(bool firstUpdate = true)
{
if (FormsMap.IsClusteringEnabled)
{
_clusterMap.ClusterManager.RemoveAnnotations(_clusterMap.ClusterManager.Annotations);
}
else
{
Map.RemoveAnnotations(Map.Annotations);
}
if (FormsMap.Pins == null) return;
foreach (var i in FormsMap.Pins)
{
i.PropertyChanged -= OnPinPropertyChanged;
AddPin(i);
}
if (firstUpdate)
{
if (FormsMap.Pins is INotifyCollectionChanged observable)
{
observable.CollectionChanged += OnCollectionChanged;
}
}
MapFunctions.RaisePinsReady();
}
/// <summary>
/// Creates the lines
/// </summary>
void UpdateLines(bool firstUpdate = true)
{
if (_lines.Any())
{
foreach (var line in _lines)
{
line.Value.Overlay.PropertyChanged -= OnLinePropertyChanged;
}
Map?.RemoveOverlays(_lines.Select(i => i.Key).Cast<IMKOverlay>().ToArray());
_lines.Clear();
}
if (FormsMap?.Polylines == null) return;
foreach (var line in FormsMap.Polylines)
{
AddLine(line);
}
if (firstUpdate)
{
if (FormsMap.Polylines is INotifyCollectionChanged observable)
{
observable.CollectionChanged += OnLineCollectionChanged;
}
}
}
/// <summary>
/// Create the routes
/// </summary>
/// <param name="firstUpdate">First update of collection or not</param>
void UpdateRoutes(bool firstUpdate = true)
{
_tempRouteList.Clear();
if (_routes.Any())
{
foreach (var r in _routes.Where(i => i.Value != null))
{
r.Value.Overlay.PropertyChanged -= OnRoutePropertyChanged;
}
Map?.RemoveOverlays(_routes.Select(i => i.Key).Cast<IMKOverlay>().ToArray());
_routes.Clear();
}
if (FormsMap == null || FormsMap.Routes == null) return;
foreach (var route in FormsMap.Routes)
{
AddRoute(route);
}
if (!firstUpdate) return;
if (FormsMap.Routes is INotifyCollectionChanged observable)
{
observable.CollectionChanged += OnRouteCollectionChanged;
}
}
/// <summary>
/// When the collection of routes changed
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnRouteCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
{
foreach (TKRoute route in e.NewItems)
{
AddRoute(route);
}
break;
}
case NotifyCollectionChangedAction.Remove:
{
foreach (TKRoute route in e.OldItems)
{
if (FormsMap.Routes.Contains(route)) continue;
route.PropertyChanged -= OnRoutePropertyChanged;
var (key, _) = _routes.SingleOrDefault(i => i.Value.Overlay.Equals(route));
if (key == null) continue;
Map.RemoveOverlay(key);
_routes.Remove(key);
}
break;
}
case NotifyCollectionChangedAction.Reset:
UpdateRoutes(false);
break;
}
}
/// <summary>
/// Creates the circles on the map
/// </summary>
void UpdateCircles(bool firstUpdate = true)
{
if (_circles.Any())
{
foreach (var circle in _circles)
{
circle.Value.Overlay.PropertyChanged -= OnCirclePropertyChanged;
}
Map.RemoveOverlays(_circles.Select(i => i.Key).Cast<IMKOverlay>().ToArray());
_circles.Clear();
}
if (FormsMap.Circles == null) return;
foreach (var circle in FormsMap.Circles)
{
AddCircle(circle);
}
if (!firstUpdate) return;
if (FormsMap.Circles is INotifyCollectionChanged observable)
{
observable.CollectionChanged += OnCirclesCollectionChanged;
}
}
/// <summary>
/// Create the polygons
/// </summary>
/// <param name="firstUpdate">If the collection updates the first time</param>
void UpdatePolygons(bool firstUpdate = true)
{
if (_polygons.Any())
{
foreach (var poly in _polygons)
{
poly.Value.Overlay.PropertyChanged -= OnPolygonPropertyChanged;
}
Map.RemoveOverlays(_polygons.Select(i => i.Key).Cast<IMKOverlay>().ToArray());
_polygons.Clear();
}
if (FormsMap.Polygons == null) return;
foreach (var poly in FormsMap.Polygons)
{
AddPolygon(poly);
}
if (!firstUpdate) return;
if (FormsMap.Polygons is INotifyCollectionChanged observable)
{
observable.CollectionChanged += OnPolygonsCollectionChanged;
}
}
/// <summary>
/// When the collection of polygons changed
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnPolygonsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
{
foreach (TKPolygon poly in e.NewItems)
{
AddPolygon(poly);
}
break;
}
case NotifyCollectionChangedAction.Remove:
{
foreach (TKPolygon poly in e.OldItems)
{
if (FormsMap.Polygons.Contains(poly)) continue;
poly.PropertyChanged -= OnPolygonPropertyChanged;
var (key, _) = _polygons.SingleOrDefault(i => i.Value.Overlay.Equals(poly));
if (key == null) continue;
Map.RemoveOverlay(key);
_polygons.Remove(key);
}
break;
}
case NotifyCollectionChangedAction.Reset:
{
foreach (var poly in _polygons)
{
poly.Value.Overlay.PropertyChanged -= OnPolygonPropertyChanged;
}
UpdatePolygons(false);
break;
}
}
}
/// <summary>
/// Adds a polygon to the map
/// </summary>
/// <param name="polygon">Polygon to add</param>
void AddPolygon(TKPolygon polygon)
{
var mkPolygon = MKPolygon.FromCoordinates(polygon.Coordinates.Select(i => i.ToLocationCoordinate()).ToArray());
_polygons.Add(mkPolygon, new TKOverlayItem<TKPolygon, MKPolygonRenderer>(polygon));
Map.AddOverlay(mkPolygon);
polygon.PropertyChanged += OnPolygonPropertyChanged;
}
/// <summary>
/// When a property of a polygon changed
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnPolygonPropertyChanged(object sender, PropertyChangedEventArgs e)
{
var poly = (TKPolygon)sender;
if (poly == null) return;
var (key, value) = _polygons.SingleOrDefault(i => i.Value.Overlay.Equals(poly));
if (key == null) return;
if (e.PropertyName != nameof(TKPolygon.Coordinates))
{
if (value.Renderer == null) return;
switch (e.PropertyName)
{
case nameof(TKPolygon.StrokeColor):
value.Renderer.StrokeColor = value.Overlay.StrokeColor.ToUIColor();
break;
case nameof(TKPolygon.Color):
value.Renderer.FillColor = value.Overlay.Color.ToUIColor();
break;
case nameof(TKPolygon.StrokeWidth):
value.Renderer.LineWidth = value.Overlay.StrokeWidth;
break;
}
return;
}
Map.RemoveOverlay(key);
_polygons.Remove(key);
var mkPolygon = MKPolygon.FromCoordinates(poly.Coordinates.Select(i => i.ToLocationCoordinate()).ToArray());
_polygons.Add(mkPolygon, new TKOverlayItem<TKPolygon, MKPolygonRenderer>(poly));
Map.AddOverlay(mkPolygon);
}
/// <summary>
/// When the circles collection changed
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnCirclesCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
{
foreach (TKCircle circle in e.NewItems)
{
AddCircle(circle);
}
break;
}
case NotifyCollectionChangedAction.Remove:
{
foreach (TKCircle circle in e.OldItems)
{
if (FormsMap.Circles.Contains(circle)) continue;
circle.PropertyChanged -= OnCirclePropertyChanged;
var (key, _) = _circles.SingleOrDefault(i => i.Value.Overlay.Equals(circle));
if (key == null) continue;
Map.RemoveOverlay(key);
_circles.Remove(key);
}
// var o = new MKLocalSearchRequest();
break;
}
case NotifyCollectionChangedAction.Reset:
UpdateCircles(false);
break;
}
}
/// <summary>
/// When the route collection changed
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnLineCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
{
foreach (TKPolyline line in e.NewItems)
{
AddLine(line);
}
break;
}
case NotifyCollectionChangedAction.Remove:
{
foreach (TKPolyline line in e.OldItems)
{
if (FormsMap.Polylines.Contains(line)) continue;
line.PropertyChanged -= OnLinePropertyChanged;
var (key, _) = _lines.SingleOrDefault(i => i.Value.Overlay.Equals(line));
if (key == null) continue;
Map.RemoveOverlay(key);
_lines.Remove(key);
}
break;
}
case NotifyCollectionChangedAction.Reset:
UpdateLines(false);
break;
}
}
/// <summary>
/// Adds a pin
/// </summary>
/// <param name="pin">The pin to add</param>
void AddPin(TKCustomMapPin pin)
{
var annotation = new TKCustomMapAnnotation(pin);
if (FormsMap.IsClusteringEnabled)
{
_clusterMap.ClusterManager.AddAnnotation(annotation);
}
else
{
Map.AddAnnotation(annotation);
}
pin.PropertyChanged += OnPinPropertyChanged;
}
/// <summary>
/// Adds a route
/// </summary>
/// <param name="line">The route to add</param>
void AddLine(TKPolyline line)
{
var polyLine = MKPolyline.FromCoordinates(line.LineCoordinates.Select(i => i.ToLocationCoordinate()).ToArray());
_lines.Add(polyLine, new TKOverlayItem<TKPolyline, MKPolylineRenderer>(line));
Map.AddOverlay(polyLine);
line.PropertyChanged += OnLinePropertyChanged;
}
/// <summary>
/// Adds a route to the map
/// </summary>
/// <param name="route">The route to add</param>
void AddRoute(TKRoute route)
{
_tempRouteList.Add(route);
var req = new MKDirectionsRequest
{
Source = new MKMapItem(
new MKPlacemark(route.Source.ToLocationCoordinate(),
new MKPlacemarkAddress())),
Destination = new MKMapItem(
new MKPlacemark(route.Destination.ToLocationCoordinate(),
new MKPlacemarkAddress())),
TransportType = route.TravelMode.ToTransportType()
};
var directions = new MKDirections(req);
directions.CalculateDirections((r, e) =>
{
if (FormsMap == null || Map == null || !_tempRouteList.Contains(route)) return;
if (e == null)
{
var nativeRoute = r.Routes.First();
SetRouteData(route, nativeRoute);
_routes.Add(nativeRoute.Polyline, new TKOverlayItem<TKRoute, MKPolylineRenderer>(route));
Map.AddOverlay(nativeRoute.Polyline);
route.PropertyChanged += OnRoutePropertyChanged;
MapFunctions.RaiseRouteCalculationFinished(route);
}
else
{
var routeCalculationError = new TKRouteCalculationError(route, e.ToString());
MapFunctions.RaiseRouteCalculationFailed(routeCalculationError);
}
});
}
/// <summary>
/// When a property of a route changed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void OnRoutePropertyChanged(object sender, PropertyChangedEventArgs e)
{
var route = (TKRoute)sender;
if (route == null) return;
var (key, value) = _routes.SingleOrDefault(i => i.Value.Overlay.Equals(route));
if (key == null) return;
if (e.PropertyName != nameof(TKRoute.TravelMode) &&
e.PropertyName != nameof(TKRoute.Source) &&
e.PropertyName != nameof(TKRoute.Destination))
{
if (value.Renderer == null) return;
switch (e.PropertyName)
{
case nameof(TKRoute.Color):
value.Renderer.FillColor = value.Overlay.Color.ToUIColor();
value.Renderer.StrokeColor = value.Overlay.Color.ToUIColor();
break;
case nameof(TKPolyline.LineWidth):
value.Renderer.LineWidth = value.Overlay.LineWidth;
break;
}
return;
}
value.Overlay.PropertyChanged -= OnRoutePropertyChanged;
Map.RemoveOverlay(key);
_routes.Remove(key);
AddRoute(route);
}
/// <summary>
/// Adds a circle to the map
/// </summary>
/// <param name="circle">The circle to add</param>
void AddCircle(TKCircle circle)
{
var mkCircle = MKCircle.Circle(circle.Center.ToLocationCoordinate(), circle.Radius);
_circles.Add(mkCircle, new TKOverlayItem<TKCircle, MKCircleRenderer>(circle));
Map.AddOverlay(mkCircle);
circle.PropertyChanged += OnCirclePropertyChanged;
}
/// <summary>
/// When a property of a circle changed
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnCirclePropertyChanged(object sender, PropertyChangedEventArgs e)
{
var circle = (TKCircle)sender;
if (circle == null) return;
var (key, value) = _circles.SingleOrDefault(i => i.Value.Overlay.Equals(circle));
if (key == null) return;
if (e.PropertyName != nameof(TKCircle.Center) &&
e.PropertyName != nameof(TKCircle.Radius))
{
if (value.Renderer == null) return;
switch (e.PropertyName)
{
case nameof(TKCircle.Color):
value.Renderer.FillColor = value.Overlay.Color.ToUIColor();
break;
case nameof(TKCircle.StrokeColor):
value.Renderer.StrokeColor = value.Overlay.StrokeColor.ToUIColor();
break;
case nameof(TKCircle.StrokeWidth):
value.Renderer.LineWidth = value.Overlay.StrokeWidth;
break;
}
return;
}
Map.RemoveOverlay(key);
_circles.Remove(key);
var mkCircle = MKCircle.Circle(circle.Center.ToLocationCoordinate(), circle.Radius);
_circles.Add(mkCircle, new TKOverlayItem<TKCircle, MKCircleRenderer>(circle));
Map.AddOverlay(mkCircle);
}
/// <summary>
/// When a property of the route changes, re-add the <see cref="MKPolyline"/>
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnLinePropertyChanged(object sender, PropertyChangedEventArgs e)
{
var line = (TKPolyline)sender;
if (line == null) return;
var (key, value) = _lines.SingleOrDefault(i => i.Value.Overlay.Equals(line));
if (key == null) return;
if (e.PropertyName != nameof(TKPolyline.LineCoordinates))
{
if (value.Renderer == null) return;
switch (e.PropertyName)
{
case nameof(TKOverlay.Color):
value.Renderer.FillColor = value.Overlay.Color.ToUIColor();
value.Renderer.StrokeColor = value.Overlay.Color.ToUIColor();
break;
case nameof(TKPolyline.LineWidth):
value.Renderer.LineWidth = value.Overlay.LineWidth;
break;
}
return;
}
Map.RemoveOverlay(key);
_lines.Remove(key);
var polyLine = MKPolyline.FromCoordinates(line.LineCoordinates.Select(i => i.ToLocationCoordinate()).ToArray());
_lines.Add(polyLine, new TKOverlayItem<TKPolyline, MKPolylineRenderer>(line));
Map.AddOverlay(polyLine);
}
/// <summary>
/// When a property of the pin changed
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnPinPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(TKCustomMapPin.Title) ||
e.PropertyName == nameof(TKCustomMapPin.Subtitle) ||
(e.PropertyName == nameof(TKCustomMapPin.Position) && _isDragging))
return;
var formsPin = (TKCustomMapPin)sender;
var annotation = GetCustomAnnotation(formsPin);
if (annotation == null) return;
var annotationView = GetViewByAnnotation(annotation);
if (annotationView == null) return;
switch (e.PropertyName)
{
case nameof(TKCustomMapPin.Image):
UpdateImage(annotationView, formsPin);
break;
case nameof(TKCustomMapPin.DefaultPinColor):
UpdateImage(annotationView, formsPin);
break;
case nameof(TKCustomMapPin.IsDraggable):
annotationView.Draggable = formsPin.IsDraggable;
break;
case nameof(TKCustomMapPin.IsVisible):
SetAnnotationViewVisibility(annotationView, formsPin);
break;
case nameof(TKCustomMapPin.Position):
annotationView.Annotation.SetCoordinate(formsPin.Position.ToLocationCoordinate());
annotation.SetCoordinateInternal(formsPin.Position.ToLocationCoordinate(), true);
break;
case nameof(TKCustomMapPin.ShowCallout):
annotationView.CanShowCallout = formsPin.ShowCallout;
break;
case nameof(TKCustomMapPin.Anchor):
if (formsPin.Image != null)
{
annotationView.Layer.AnchorPoint = new CGPoint(formsPin.Anchor.X, formsPin.Anchor.Y);
}
break;
case nameof(TKCustomMapPin.Rotation):
annotationView.Transform = CGAffineTransform.MakeRotation((float)formsPin.Rotation);
break;
case nameof(TKCustomMapPin.IsCalloutClickable):
UpdateAccessoryView(formsPin, annotationView);
break;
}
}
/// <summary>
/// Sets the route data
/// </summary>
/// <param name="route">PCL route</param>
/// <param name="nativeRoute">Native route</param>
void SetRouteData(TKRoute route, MKRoute nativeRoute)
{
var routeFunctions = (IRouteFunctions)route;
var steps = new TKRouteStep[nativeRoute.Steps.Count()];
for (var i = 0; i < steps.Length; i++)
{
steps[i] = new TKRouteStep();
var stepFunction = (IRouteStepFunctions)steps[i];
var nativeStep = nativeRoute.Steps.ElementAt(i);
stepFunction.SetInstructions(nativeStep.Instructions);
stepFunction.SetDistance(nativeStep.Distance);
}
routeFunctions.SetSteps(steps);
routeFunctions.SetDistance(nativeRoute.Distance);
routeFunctions.SetTravelTime(nativeRoute.ExpectedTravelTime);
var region = MKCoordinateRegion.FromMapRect(Map.MapRectThatFits(nativeRoute.Polyline.BoundingMapRect, new UIEdgeInsets(25, 25, 25, 25)));
routeFunctions.SetBounds(new MapSpan(region.Center.ToPosition(), region.Span.LatitudeDelta, region.Span.LongitudeDelta));
routeFunctions.SetIsCalculated(true);
}
/// <summary>
/// Set the visibility of an annotation view
/// </summary>
/// <param name="annotationView">The annotation view</param>
/// <param name="pin">The forms pin</param>
void SetAnnotationViewVisibility(MKAnnotationView annotationView, TKCustomMapPin pin)
{
annotationView.Hidden = !pin.IsVisible;
annotationView.UserInteractionEnabled = pin.IsVisible;
annotationView.Enabled = pin.IsVisible;
}
/// <summary>
/// Set the image of the annotation view
/// </summary>
/// <param name="annotationView">The annotation view</param>
/// <param name="pin">The forms pin</param>
async void UpdateImage(MKAnnotationView annotationView, TKCustomMapPin pin)
{
if (pin.Image != null)
{
// If this is the case, we need to get a whole new annotation view.
if (annotationView.GetType() == typeof(MKPinAnnotationView))
{
if (FormsMap.IsClusteringEnabled)
{
_clusterMap.ClusterManager.RemoveAnnotation(GetCustomAnnotation(annotationView));
_clusterMap.ClusterManager.AddAnnotation(new TKCustomMapAnnotation(pin));
}
else
{
Map.RemoveAnnotation(GetCustomAnnotation(annotationView));
Map.AddAnnotation(new TKCustomMapAnnotation(pin));
}
return;
}
var image = await pin.Image.ToImage();
Device.BeginInvokeOnMainThread(() =>
{
annotationView.Image = image;
});
}
else
{
if (annotationView is MKPinAnnotationView pinAnnotationView)
{
pinAnnotationView.AnimatesDrop = AnimateOnPinDrop;
var pinTintColorAvailable = pinAnnotationView.RespondsToSelector(new Selector("pinTintColor"));
if (!pinTintColorAvailable)
{
return;
}
pinAnnotationView.PinTintColor = pin.DefaultPinColor != Color.Default
? pin.DefaultPinColor.ToUIColor()
: UIColor.Red;
}
else
{
if (FormsMap.IsClusteringEnabled)
{
_clusterMap.ClusterManager.RemoveAnnotation(GetCustomAnnotation(annotationView));
_clusterMap.ClusterManager.AddAnnotation(new TKCustomMapAnnotation(pin));
}
else
{
Map.RemoveAnnotation(GetCustomAnnotation(annotationView));
Map.AddAnnotation(new TKCustomMapAnnotation(pin));
}
}
}
}
/// <summary>
/// Updates the tiles and adds or removes the overlay
/// </summary>
void UpdateTileOptions()
{
if (Map == null) return;
if (_tileOverlay != null)
{
Map.RemoveOverlay(_tileOverlay);
_tileOverlay = null;
}
if (FormsMap == null || FormsMap.TilesUrlOptions == null) return;
_tileOverlay = new MKTileOverlay(
FormsMap.TilesUrlOptions.TilesUrl
.Replace("{0}", "{x}")
.Replace("{1}", "{y}")
.Replace("{2}", "{z}"))
{
TileSize = new CGSize(
FormsMap.TilesUrlOptions.TileWidth,
FormsMap.TilesUrlOptions.TileHeight),
MinimumZ = FormsMap.TilesUrlOptions.MinimumZoomLevel,
MaximumZ = FormsMap.TilesUrlOptions.MaximumZoomLevel,
CanReplaceMapContent = true
};
Map.AddOverlay(_tileOverlay);
}
/// <summary>
/// Sets the selected pin
/// </summary>
void SetSelectedPin()
{
if (_selectedAnnotation is TKCustomMapAnnotation customMapAnnotation)
{
if (customMapAnnotation.CustomPin.Equals(FormsMap.SelectedPin)) return;
var annotationView = GetViewByAnnotation(customMapAnnotation);
if (annotationView != null)
{
annotationView.Selected = false;
Map.DeselectAnnotation(annotationView.Annotation, true);
}
_selectedAnnotation = null;
}
if (FormsMap.SelectedPin == null) return;
{
var selectedAnnotation = GetCustomAnnotation(FormsMap.SelectedPin);
if (selectedAnnotation == null) return;
var annotationView = GetViewByAnnotation(selectedAnnotation);
_selectedAnnotation = selectedAnnotation;
if (annotationView != null)
{
Map.SelectAnnotation(annotationView.Annotation, true);
}
MapFunctions.RaisePinSelected(FormsMap.SelectedPin);
}
}
/// <summary>
/// Sets traffic enabled on the map
/// </summary>
void UpdateShowTraffic()
{
if (FormsMap == null || Map == null) return;
var showsTrafficAvailable = Map.RespondsToSelector(new Selector("showsTraffic"));
if (!showsTrafficAvailable) return;
Map.ShowsTraffic = FormsMap.ShowTraffic;
}
/// <summary>
/// Updates the map region when changed
/// </summary>
void UpdateMapRegion()
{
if (FormsMap?.MapRegion == null) return;
if (Map.GetCurrentMapRegion().Equals(FormsMap.MapRegion)) return;
MoveToMapRegion(FormsMap.MapRegion, FormsMap.IsRegionChangeAnimated);
}
/// <summary>
/// Updates clustering
/// </summary>
void UpdateIsClusteringEnabled()
{
if (FormsMap == null || Map == null) return;
if (FormsMap.IsClusteringEnabled)
{
if (_clusterMap == null)
{
_clusterMap = new TKClusterMap(Map);
}
Map.RemoveAnnotations(Map.Annotations);
foreach (var pin in FormsMap.Pins)
{
AddPin(pin);
}
_clusterMap.ClusterManager.UpdateClusters();
}
else
{
_clusterMap.ClusterManager.RemoveAnnotations(_clusterMap.ClusterManager.Annotations);
foreach (var pin in FormsMap.Pins)
{
AddPin(pin);
}
_clusterMap.Dispose();
_clusterMap = null;
}
}
/// <summary>
/// Updates the map type
/// </summary>
void UpdateMapType()
{
if (FormsMap == null || Map == null) return;
switch (FormsMap.MapType)
{
case MapType.Hybrid:
Map.MapType = MKMapType.Hybrid;
break;
case MapType.Satellite:
Map.MapType = MKMapType.Satellite;
break;
case MapType.Street:
Map.MapType = MKMapType.Standard;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Sets whether the user should be shown
/// </summary>
void UpdateIsShowingUser()
{
if (FormsMap == null || Map == null) return;
if (FormsMap.IsShowingUser && UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
{
_locationManager = new CLLocationManager();
_locationManager.RequestWhenInUseAuthorization();
}
Map.ShowsUserLocation = FormsMap.IsShowingUser;
}
/// <summary>
/// Update ScrollEnabled
/// </summary>
void UpdateHasScrollEnabled()
{
if (FormsMap == null || Map == null) return;
Map.ScrollEnabled = FormsMap.HasScrollEnabled;
}
/// <summary>
/// Update ZoomEnabled
/// </summary>
void UpdateHasZoomEnabled()
{
if (FormsMap == null || Map == null) return;
Map.ZoomEnabled = FormsMap.HasZoomEnabled;
}
/// <summary>
/// Calculates the closest distance of a point to a polyline
/// </summary>
/// <param name="pt">The point</param>
/// <param name="poly">The polyline</param>
/// <returns>The closes distance</returns>
double DistanceOfPoint(MKMapPoint pt, MKPolyline poly)
{
double distance = float.MaxValue;
for (var n = 0; n < poly.PointCount - 1; n++)
{
var ptA = poly.Points[n];
var ptB = poly.Points[n + 1];
var xDelta = ptB.X - ptA.X;
var yDelta = ptB.Y - ptA.Y;
if (Math.Abs(xDelta - default(double)) <= 0 && Math.Abs(yDelta - default(double)) <= 0)
{
// Points must not be equal
continue;
}
var u = ((pt.X - ptA.X) * xDelta + (pt.Y - ptA.Y) * yDelta) / (xDelta * xDelta + yDelta * yDelta);
MKMapPoint ptClosest;
if (u < 0.0)
{
ptClosest = ptA;
}
else if (u > 1.0)
{
ptClosest = ptB;
}
else
{
ptClosest = new MKMapPoint(ptA.X + u * xDelta, ptA.Y + u * yDelta);
}
distance = Math.Min(distance, MKGeometry.MetersBetweenMapPoints(ptClosest, pt));
}
return distance;
}
/// <summary>
/// Returns the meters between two points
/// </summary>
/// <param name="px">X in pixels</param>
/// <param name="pt">Position</param>
/// <returns>Distance in meters</returns>
double MetersFromPixel(int px, CGPoint pt)
{
var ptB = new CGPoint(pt.X + px, pt.Y);
var coordA = Map.ConvertPoint(pt, Map);
var coordB = Map.ConvertPoint(ptB, Map);
return MKGeometry.MetersBetweenMapPoints(MKMapPoint.FromCoordinate(coordA), MKMapPoint.FromCoordinate(coordB));
}
/// <summary>
/// Convert a <see cref="MKCoordinateRegion"/> to <see cref="MKMapRect"/>
/// http://stackoverflow.com/questions/9270268/convert-mkcoordinateregion-to-mkmaprect
/// </summary>
/// <param name="region">Region to convert</param>
/// <returns>The map rect</returns>
MKMapRect RegionToRect(MKCoordinateRegion region)
{
var a = MKMapPoint.FromCoordinate(
new CLLocationCoordinate2D(
region.Center.Latitude + region.Span.LatitudeDelta / 2,
region.Center.Longitude - region.Span.LongitudeDelta / 2));
var b = MKMapPoint.FromCoordinate(
new CLLocationCoordinate2D(
region.Center.Latitude - region.Span.LatitudeDelta / 2,
region.Center.Longitude + region.Span.LongitudeDelta / 2));
return new MKMapRect(Math.Min(a.X, b.X), Math.Min(a.Y, b.Y), Math.Abs(a.X - b.X), Math.Abs(a.Y - b.Y));
}
/// <summary>
/// Unregisters all collections
/// </summary>
void UnregisterCollections(TKCustomMap map)
{
UnregisterCollection(map.Pins, OnCollectionChanged, OnPinPropertyChanged);
UnregisterCollection(map.Routes, OnRouteCollectionChanged, OnRoutePropertyChanged);
UnregisterCollection(map.Polylines, OnLineCollectionChanged, OnLinePropertyChanged);
UnregisterCollection(map.Circles, OnCirclesCollectionChanged, OnCirclePropertyChanged);
UnregisterCollection(map.Polygons, OnPolygonsCollectionChanged, OnPolygonPropertyChanged);
}
/// <summary>
/// Unregisters one collection and all of its items
/// </summary>
/// <param name="collection">The collection to unregister</param>
/// <param name="observableHandler">The <see cref="NotifyCollectionChangedEventHandler"/> of the collection</param>
/// <param name="propertyHandler">The <see cref="PropertyChangedEventHandler"/> of the collection items</param>
void UnregisterCollection(
IEnumerable collection,
NotifyCollectionChangedEventHandler observableHandler,
PropertyChangedEventHandler propertyHandler)
{
if (collection is null) return;
if (collection is INotifyCollectionChanged observable)
{
observable.CollectionChanged -= observableHandler;
}
foreach (INotifyPropertyChanged obj in collection)
{
obj.PropertyChanged -= propertyHandler;
}
}
///<inheritdoc/>
public async Task<byte[]> GetSnapshot()
{
UIImage img = null;
await Task.Factory.StartNew(() =>
{
BeginInvokeOnMainThread(() =>
{
UIGraphics.BeginImageContextWithOptions(Frame.Size, false, 0.0f);
Layer.RenderInContext(UIGraphics.GetCurrentContext());
img = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
});
});
return img.AsPNG().ToArray();
}
/// <inheritdoc/>
public void FitMapRegionToPositions(IEnumerable<Position> positions, bool animate = false, int padding = 0)
{
if (Map == null) return;
var zoomRect = positions
.Select(position => MKMapPoint.FromCoordinate(position.ToLocationCoordinate()))
.Select(point => new MKMapRect(point.X, point.Y, 0.1, 0.1))
.Aggregate(MKMapRect.Null, MKMapRect.Union);
Map.SetVisibleMapRect(zoomRect, new UIEdgeInsets(padding, padding, padding, padding), animate);
}
/// <inheritdoc/>
public void MoveToMapRegion(MapSpan region, bool animate)
{
if (Map == null) return;
var coordinateRegion = MKCoordinateRegion.FromDistance(
region.Center.ToLocationCoordinate(),
region.Radius.Meters * 2,
region.Radius.Meters * 2);
Map.SetRegion(coordinateRegion, animate);
}
/// <inheritdoc/>
public void FitToMapRegions(IEnumerable<MapSpan> regions, bool animate = false, int padding = 0)
{
if (Map == null) return;
var rect = regions.Aggregate(MKMapRect.Null,
(current, region) => MKMapRect.Union(current,
RegionToRect(MKCoordinateRegion.FromDistance(region.Center.ToLocationCoordinate(),
region.Radius.Meters * 2,
region.Radius.Meters * 2))));
Map.SetVisibleMapRect(rect, new UIEdgeInsets(padding, padding, padding, padding), animate);
}
/// <inheritdoc/>
public void ShowCallout(TKCustomMapPin pin)
{
if (Map == null) return;
var annotation = GetCustomAnnotation(pin);
if (FormsMap.IsClusteringEnabled)
{
_clusterMap.ClusterManager.SelectAnnotation(annotation, true);
}
else
{
Map.SelectAnnotation(annotation, true);
}
}
/// <inheritdoc/>
public void HideCallout(TKCustomMapPin pin)
{
if (Map == null) return;
var annotation = GetCustomAnnotation(pin);
if (FormsMap.IsClusteringEnabled)
{
_clusterMap.ClusterManager.DeselectAnnotation(annotation, true);
}
else
{
Map.DeselectAnnotation(annotation, true);
}
}
/// <inheritdoc />
public IEnumerable<Position> ScreenLocationsToGeocoordinates(params Point[] screenLocations)
{
if (Map == null)
throw new InvalidOperationException("Map not initialized");
return screenLocations.Select(i => Map.ConvertPoint(i.ToCGPoint(), Map).ToPosition());
}
/// <summary>
/// Returns the <see cref="TKCustomMapPin"/> by the native <see cref="IMKAnnotation"/>
/// </summary>
/// <param name="annotation">The annotation to search with</param>
/// <returns>The forms pin</returns>
protected TKCustomMapPin GetPinByAnnotation(IMKAnnotation annotation)
{
if (!FormsMap.IsClusteringEnabled)
return (annotation as TKCustomMapAnnotation)?.CustomPin;
var customAnnotation = (CKCluster)FromObject(annotation); ;
return customAnnotation.Annotations.Count() > 1
? FormsMap.GetClusteredPin?.Invoke(null, customAnnotation.Annotations.OfType<TKCustomMapAnnotation>().Select(i => i.CustomPin))
: customAnnotation.Annotations.OfType<TKCustomMapAnnotation>().FirstOrDefault()?.CustomPin;
}
/// <summary>
/// Remove all annotations before disposing
/// </summary>
/// <param name="disposing">disposing</param>
protected override void Dispose(bool disposing)
{
if (_disposed) return;
_disposed = true;
if (disposing)
{
DisposeRenderers();
if (Map != null)
{
_clusterMap?.ClusterManager?.RemoveAnnotations(_clusterMap.ClusterManager.Annotations);
Map.RemoveAnnotations(Map.Annotations);
Map.GetViewForAnnotation = null;
Map.OverlayRenderer = null;
Map.DidSelectAnnotationView -= OnDidSelectAnnotationView;
Map.RegionChanged -= OnMapRegionChanged;
Map.DidUpdateUserLocation -= OnDidUpdateUserLocation;
Map.ChangedDragState -= OnChangedDragState;
Map.CalloutAccessoryControlTapped -= OnMapCalloutAccessoryControlTapped;
Map.RemoveGestureRecognizer(_longPressGestureRecognizer);
Map.RemoveGestureRecognizer(_tapGestureRecognizer);
Map.RemoveGestureRecognizer(_doubleTapGestureRecognizer);
_longPressGestureRecognizer.Dispose();
_tapGestureRecognizer.Dispose();
_doubleTapGestureRecognizer.Dispose();
Map.Dispose();
_clusterMap?.Dispose();
}
if (FormsMap != null)
{
FormsMap.PropertyChanged -= OnMapPropertyChanged;
UnregisterCollections(FormsMap);
}
}
base.Dispose(disposing);
void DisposeRenderers()
{
foreach (var route in _routes.Select(x => x.Value))
DisposeTkOverlayItem(route);
foreach (var line in _lines.Select(x => x.Value))
DisposeTkOverlayItem(line);
foreach (var circle in _circles.Select(x => x.Value))
DisposeTkOverlayItem(circle);
foreach (var polygon in _polygons.Select(x => x.Value))
DisposeTkOverlayItem(polygon);
_routes.Clear();
_lines.Clear();
_circles.Clear();
_polygons.Clear();
DisposeTkOverlayItem(_polygonRenderer);
DisposeTkOverlayItem(_lineRenderer);
DisposeTkOverlayItem(_circleRenderer);
DisposeTkOverlayItem(_routeRenderer);
void DisposeTkOverlayItem<TRenderer,TOverlay>(TKOverlayItem<TOverlay,TRenderer> overlay)
where TRenderer: MKOverlayPathRenderer
where TOverlay : TKOverlay
{
if (overlay is null) return;
overlay.Renderer?.Dispose();
overlay.Renderer = null;
overlay.Overlay = null;
}
}
}
TKCustomMapAnnotation GetCustomAnnotation(MKAnnotationView view)
{
if (!FormsMap.IsClusteringEnabled) return view.Annotation as TKCustomMapAnnotation;
var cluster = Runtime.GetNSObject(view.Annotation.Handle) as CKCluster;
if (cluster?.Annotations.Count() != 1) return null;
return cluster.Annotations.First() as TKCustomMapAnnotation;
}
TKCustomMapAnnotation GetCustomAnnotation(TKCustomMapPin pin) =>
FormsMap.IsClusteringEnabled
? _clusterMap.ClusterManager.Annotations.OfType<TKCustomMapAnnotation>().SingleOrDefault(i => i.CustomPin.Equals(pin))
: Map.Annotations.OfType<TKCustomMapAnnotation>().SingleOrDefault(i => i.CustomPin.Equals(pin));
MKAnnotationView GetViewByAnnotation(TKCustomMapAnnotation annotation) =>
FormsMap.IsClusteringEnabled
? Map.ViewForAnnotation(Map.Annotations.GetCluster(annotation))
: Map.ViewForAnnotation(annotation);
}
}
| 39.134468 | 172 | 0.535602 | [
"MIT"
] | TorbenK/TK.CustomMap | Source/TK.CustomMap.iOSUnified/TKCustomMapRenderer.cs | 71,305 | 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.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace NuGet.Services.Search.Client
{
public class ServiceDiscoveryClient
{
private readonly HttpClient _httpClient;
private readonly Uri _serviceDiscoveryEndpoint;
private ServiceIndexDocument _serviceIndexDocument;
private readonly TimeSpan _serviceIndexDocumentExpiration = TimeSpan.FromMinutes(5);
private readonly object _serviceIndexDocumentLock = new object();
private bool _serviceIndexDocumentUpdating;
public ServiceDiscoveryClient(Uri serviceDiscoveryEndpoint)
: this(new HttpClient(), serviceDiscoveryEndpoint)
{
}
public ServiceDiscoveryClient(HttpClient httpClient, Uri serviceDiscoveryEndpoint)
{
_httpClient = httpClient;
_serviceDiscoveryEndpoint = serviceDiscoveryEndpoint;
}
public async Task<IEnumerable<Uri>> GetEndpointsForResourceType(string resourceType)
{
try
{
await DiscoverEndpointsAsync().ConfigureAwait(false);
}
catch (NullReferenceException)
{
// if this happens, we may have received an invalid document
if (_serviceIndexDocument == null)
{
// if we don't have a cached instance, throw (as we can't do anything here)
throw;
}
// if we do have a cached one, keep it for another minute
_serviceIndexDocument = new ServiceIndexDocument(_serviceIndexDocument.Doc, DateTime.UtcNow.AddMinutes(1) - _serviceIndexDocumentExpiration);
}
return _serviceIndexDocument.Doc["resources"]
.Where(j => (j["@type"].Type == JTokenType.Array ? j["@type"].Any(v => (string)v == resourceType) : ((string)j["@type"]) == resourceType))
.Select(o => o["@id"].ToObject<Uri>())
.ToList();
}
public async Task DiscoverEndpointsAsync()
{
// Get out quick if we don't have anything to do.
if (_serviceIndexDocument != null && (_serviceIndexDocumentUpdating || DateTime.UtcNow <= _serviceIndexDocument.UpdateTime + _serviceIndexDocumentExpiration))
{
return;
}
// Lock to make sure that we can only attempt one update at a time.
var performServiceIndexDocumentUpdate = false;
if (!_serviceIndexDocumentUpdating)
{
lock (_serviceIndexDocumentLock)
{
if (!_serviceIndexDocumentUpdating)
{
_serviceIndexDocumentUpdating = true;
performServiceIndexDocumentUpdate = true;
}
}
}
if (performServiceIndexDocumentUpdate)
{
// Fetch the service index document if we're the one to do the update
await DiscoverEndpointsCoreAsync().ConfigureAwait(false);
}
else if (_serviceIndexDocument == null && _serviceIndexDocumentUpdating)
{
// If there is no service index document yet, then someone else is updating it.
// Wait up to 5 seconds to ensure the document is loaded.
int timeWaitedForUpdateInMilliseconds = 0;
int timeToWaitBeforeCheckingInMilliseconds = 200;
while (_serviceIndexDocument == null && _serviceIndexDocumentUpdating && timeWaitedForUpdateInMilliseconds < 5000)
{
await Task.Delay(TimeSpan.FromMilliseconds(timeToWaitBeforeCheckingInMilliseconds)).ConfigureAwait(false);
timeWaitedForUpdateInMilliseconds += timeToWaitBeforeCheckingInMilliseconds;
}
}
}
private async Task DiscoverEndpointsCoreAsync()
{
// Fetch the service index document
await _httpClient.GetStringAsync(_serviceDiscoveryEndpoint)
.ContinueWith(t =>
{
try
{
JObject serviceIndexDocument = JObject.Parse(t.Result);
_serviceIndexDocument = new ServiceIndexDocument(serviceIndexDocument, DateTime.UtcNow);
}
finally
{
_serviceIndexDocumentUpdating = false;
}
}).ConfigureAwait(false);
}
class ServiceIndexDocument
{
public JObject Doc { get; private set; }
public DateTime UpdateTime { get; private set; }
public ServiceIndexDocument(JObject doc, DateTime updateTime)
{
Doc = doc;
UpdateTime = updateTime;
}
}
}
} | 40.045802 | 170 | 0.581777 | [
"Apache-2.0"
] | DevlinSchoonraad/NuGetGallery | src/NuGet.Services.Search.Client/Client/ServiceDiscoveryClient.cs | 5,246 | C# |
using System;
using System.Reflection;
using System.Windows.Input;
using Xamarin.Forms;
namespace Framework.Xamariner
{
// License Url: https://github.com/xamarin/xamarin-forms-samples/
/*
License
The Apache License 2.0 applies to all samples in this repository.
Copyright 2011 Xamarin Inc
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
/// <summary>
/// https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/behaviors/reusable/event-to-command-behavior/
/// </summary>
/// <seealso cref="Framework.Xamariner.BehaviorBase{Xamarin.Forms.View}" />
public class EventToCommandBehavior : BehaviorBase<View>
{
Delegate eventHandler;
public static readonly BindableProperty EventNameProperty = BindableProperty.Create ("EventName", typeof(string), typeof(EventToCommandBehavior), null, propertyChanged: OnEventNameChanged);
public static readonly BindableProperty CommandProperty = BindableProperty.Create ("Command", typeof(ICommand), typeof(EventToCommandBehavior), null);
public static readonly BindableProperty CommandParameterProperty = BindableProperty.Create ("CommandParameter", typeof(object), typeof(EventToCommandBehavior), null);
public static readonly BindableProperty InputConverterProperty = BindableProperty.Create ("Converter", typeof(IValueConverter), typeof(EventToCommandBehavior), null);
public string EventName {
get { return (string)GetValue (EventNameProperty); }
set { SetValue (EventNameProperty, value); }
}
public ICommand Command {
get { return (ICommand)GetValue (CommandProperty); }
set { SetValue (CommandProperty, value); }
}
public object CommandParameter {
get { return GetValue (CommandParameterProperty); }
set { SetValue (CommandParameterProperty, value); }
}
public IValueConverter Converter {
get { return (IValueConverter)GetValue (InputConverterProperty); }
set { SetValue (InputConverterProperty, value); }
}
protected override void OnAttachedTo (View bindable)
{
base.OnAttachedTo (bindable);
RegisterEvent (EventName);
}
protected override void OnDetachingFrom (View bindable)
{
DeregisterEvent (EventName);
base.OnDetachingFrom (bindable);
}
void RegisterEvent (string name)
{
if (string.IsNullOrWhiteSpace (name)) {
return;
}
EventInfo eventInfo = AssociatedObject.GetType ().GetRuntimeEvent (name);
if (eventInfo == null) {
throw new ArgumentException (string.Format ("EventToCommandBehavior: Can't register the '{0}' event.", EventName));
}
MethodInfo methodInfo = typeof(EventToCommandBehavior).GetTypeInfo ().GetDeclaredMethod ("OnEvent");
eventHandler = methodInfo.CreateDelegate (eventInfo.EventHandlerType, this);
eventInfo.AddEventHandler (AssociatedObject, eventHandler);
}
void DeregisterEvent (string name)
{
if (string.IsNullOrWhiteSpace (name)) {
return;
}
if (eventHandler == null) {
return;
}
EventInfo eventInfo = AssociatedObject.GetType ().GetRuntimeEvent (name);
if (eventInfo == null) {
throw new ArgumentException (string.Format ("EventToCommandBehavior: Can't de-register the '{0}' event.", EventName));
}
eventInfo.RemoveEventHandler (AssociatedObject, eventHandler);
eventHandler = null;
}
void OnEvent (object sender, object eventArgs)
{
if (Command == null) {
return;
}
object resolvedParameter;
if (CommandParameter != null) {
resolvedParameter = CommandParameter;
} else if (Converter != null) {
resolvedParameter = Converter.Convert (eventArgs, typeof(object), null, null);
} else {
resolvedParameter = eventArgs;
}
if (Command.CanExecute (resolvedParameter)) {
Command.Execute (resolvedParameter);
}
}
static void OnEventNameChanged (BindableObject bindable, object oldValue, object newValue)
{
var behavior = (EventToCommandBehavior)bindable;
if (behavior.AssociatedObject == null) {
return;
}
string oldEventName = (string)oldValue;
string newEventName = (string)newValue;
behavior.DeregisterEvent (oldEventName);
behavior.RegisterEvent (newEventName);
}
}
}
| 40.171642 | 309 | 0.635891 | [
"MIT"
] | ntierontime/Log4Net | Frameworks.X/Framework.Xamariner.X/Behaviors/EventToCommandBehavior.cs | 5,383 | C# |
using Mklinker.Abstractions;
using System.IO;
using System.Xml.Serialization;
using System.Runtime.Serialization;
namespace Mklinker {
class XMLConfigSerializer : IConfigSerializer {
public string Serialize(IConfig config) {
XmlSerializer serializer = new XmlSerializer(config.GetType());
using (StringWriter writer = new StringWriter()) {
serializer.Serialize(writer, config);
return writer.ToString();
}
}
public IConfig Deserialize(string serializedString) {
if (serializedString.Length == 0)
throw new SerializationException("Serialized string is empty");
// TODO: Fix specific type here later
XmlSerializer serializer = new XmlSerializer(typeof(Config));
using (StringReader reader = new StringReader(serializedString)) {
return (Config) serializer.Deserialize(reader);
}
}
}
}
| 25.764706 | 70 | 0.71347 | [
"MIT"
] | rubenchristoffer/Mklinker | Mklinker/XMLConfigSerializer.cs | 878 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace Rybird.Framework
{
public interface IDialogViewModel
{
double Width { get; }
double Height { get; }
string Title { get; }
string Icon { get; }
bool ShowInTaskbar { get; }
bool? DialogResult { get; set; }
}
}
| 21.368421 | 41 | 0.593596 | [
"MIT"
] | ryanhorath/Rybird.Framework | Core/Framework/ViewModels/IDialogViewModel.cs | 408 | C# |
using System;
namespace StackExchange.DataExplorer.Models
{
public class OpenIdWhiteList
{
public int Id { get; set; }
public string OpenId { get; set; }
public bool Approved { get; set; }
public string IpAddress { get; set; }
public DateTime? CreationDate { get; set; }
}
} | 26.153846 | 52 | 0.591176 | [
"MIT"
] | ASSETEX/Aych.explore | App/StackExchange.DataExplorer/Models/OpenIdWhiteList.cs | 342 | C# |
namespace System
{
public class Just<T> : Maybe<T>, IEquatable<Just<T>>
{
readonly T a;
public Just(T a)
{
this.a = a;
}
public override Maybe<R> Bind<R>(Func<T, Maybe<R>> func)
{
return func(a);
}
public bool Equals(Just<T> other)
{
return other != null && a.Equals(other.a);
}
public override bool Equals(Maybe<T> other)
{
return Equals(other as Just<T>);
}
public override T Return()
{
return a;
}
public override bool Equals(object obj)
{
return Equals(obj as Just<T>);
}
public override int GetHashCode()
{
return a.GetHashCode();
}
public override string ToString()
{
return a.ToString();
}
}
}
| 19.104167 | 64 | 0.453653 | [
"Apache-2.0"
] | rarous/Maybe | Maybe/Just.cs | 917 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Reflection.Metadata.Decoding
{
public interface ISignatureTypeProvider<TType> : IPrimitiveTypeProvider<TType>, ITypeProvider<TType>, IConstructedTypeProvider<TType>
{
/// <summary>
/// Gets the a type symbol for the function pointer type of the given method signature.
/// </summary>
TType GetFunctionPointerType(MethodSignature<TType> signature);
/// <summary>
/// Gets the type symbol for the generic method parameter at the given zero-based index.
/// </summary>
TType GetGenericMethodParameter(int index);
/// <summary>
/// Gets the type symbol for the generic type parameter at the given zero-based index.
/// </summary>
TType GetGenericTypeParameter(int index);
/// <summary>
/// Gets the type symbol for a type with a custom modifier applied.
/// </summary>
/// <param name="reader">The metadata reader that was passed to the <see cref="SignatureDecoder{TType}"/>. It may be null.</param>
/// <param name="isRequired">True if the modifier is required, false if it's optional.</param>
/// <param name="modifierTypeHandle">The modifier type applied. A <see cref="TypeDefinitionHandle"/>, <see cref="TypeReferenceHandle"/>, or <see cref="TypeSpecificationHandle"/>. </param>
/// <param name="unmodifiedType">The type symbol of the underlying type without modifiers applied.</param>
/// <remarks>
/// The modifier type is passed as a handle rather than a decoded <typeparamref name="TType"/>.
///
/// 1. It makes (not uncommon) scenarios that skip modifiers cheaper.
///
/// 2. It is the only valid place where a <see cref="TypeSpecificationHandle"/> can occur within a signature blob.
/// If we were to recurse into the type spec before calling GetModifiedType, it would eliminate scenarios such
/// as caching by TypeSpec or deciphering the structure of a signature without resolving any handles.
/// </remarks>
TType GetModifiedType(MetadataReader reader, bool isRequired, EntityHandle modifierTypeHandle, TType unmodifiedType);
/// <summary>
/// Gets the type symbol for a local variable type that is marked as pinned.
/// </summary>
TType GetPinnedType(TType elementType);
}
}
| 54.276596 | 195 | 0.667973 | [
"MIT"
] | mellinoe/corefx | src/System.Reflection.Metadata/src/System/Reflection/Metadata/Decoding/ISignatureTypeProvider.cs | 2,553 | C# |
using Volo.Abp.Ui.Branding;
using Volo.Abp.DependencyInjection;
namespace CompanyName.ProjectName
{
[Dependency(ReplaceServices = true)]
public class ProjectNameBrandingProvider : DefaultBrandingProvider
{
public override string AppName => "ProjectName";
}
}
| 23.75 | 70 | 0.74386 | [
"MIT"
] | shuangbaojun/abp-vnext-pro | aspnet-core/services/host/CompanyName.ProjectName.IdentityServer/ProjectNameBrandingProvider.cs | 287 | C# |
/*
* nMQTT, a .Net MQTT v3 client implementation.
* http://wiki.github.com/markallanson/nmqtt
*
* Copyright (c) 2009-2010 Mark Allanson (mark@markallanson.net) & Contributors
*
* Licensed under the MIT License. You may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/mit-license.php
*/
using System;
using System.ComponentModel;
namespace nMqtt.SampleApp
{
public abstract class ViewModel
{
}
public abstract class ViewModel<TModel> : ViewModel, INotifyPropertyChanged
where TModel : IModel
{
private TModel model;
public TModel Model
{
get
{
return model;
}
set
{
model = value;
model.PropertyChanged += (sender, e) => OnPropertyChanged(e.PropertyName);
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| 20.576923 | 79 | 0.699065 | [
"MIT"
] | huguoya/nmqtt | nMqttSampleApp/ViewsModels/ViewModel.cs | 1,070 | C# |
using System;
using Huobi.Client.Websocket.Messages.MarketData.Values;
using Xunit;
namespace Huobi.Client.Websocket.ComponentTests.MessagesHandling.MarketData
{
public class MarketDetailsMessagesClientHandlingTests : ClientMessagesHandlingTestsBase
{
[Fact]
public void UpdateMessage_StreamUpdated()
{
// Arrange
var timestamp = DateTimeOffset.UtcNow;
var triggered = false;
var client = InitializeMarketClient();
client.Streams.MarketDetailsUpdateStream.Subscribe(
msg =>
{
triggered = true;
// Assert
Assert.NotNull(msg);
Assert.NotNull(msg.Tick);
Assert.Contains(SubscriptionType.MarketDetails.ToTopicId(), msg.Topic);
Assert.True(!string.IsNullOrEmpty(msg.Topic));
Assert.True(msg.Tick!.Id > 0);
Assert.True(TestUtils.UnixTimesEqual(timestamp, msg.Timestamp));
});
var message = HuobiMessagesFactory.CreateMarketDetailsUpdateMessage(timestamp);
// Act
TriggerMessageReceive(message);
// Assert
VerifyMessageNotUnhandled();
Assert.True(triggered);
}
[Fact]
public void PullMessage_StreamUpdated()
{
// Arrange
var timestamp = DateTimeOffset.UtcNow;
var triggered = false;
var client = InitializeMarketClient();
client.Streams.MarketDetailsPullStream.Subscribe(
msg =>
{
triggered = true;
// Assert
Assert.NotNull(msg);
Assert.NotNull(msg.Data);
Assert.Contains(SubscriptionType.MarketDetails.ToTopicId(), msg.Topic);
Assert.True(!string.IsNullOrEmpty(msg.Topic));
Assert.True(msg.Data!.Id > 0);
Assert.True(TestUtils.UnixTimesEqual(timestamp, msg.Timestamp));
});
var message = HuobiMessagesFactory.CreateMarketDetailsPullResponseMessage(timestamp);
// Act
TriggerMessageReceive(message);
// Assert
VerifyMessageNotUnhandled();
Assert.True(triggered);
}
}
} | 34.197183 | 97 | 0.549835 | [
"Apache-2.0"
] | shaynevanasperen/huobi-client-websocket | test/Huobi.Client.Websocket.ComponentTests/MessagesHandling/MarketData/MarketDetailsMessagesClientHandlingTests.cs | 2,430 | C# |
// The MIT License (MIT)
// Copyright 2015 Siney/Pangweiwei siney@yeah.net
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace SLua
{
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System;
using System.Reflection;
using UnityEditor;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.CompilerServices;
public interface ICustomExportPost { }
public class LuaCodeGen : MonoBehaviour
{
static public string GenPath = SLuaSetting.Instance.UnityEngineGeneratePath;
static public string WrapperName = "sluaWrapper.dll";
public delegate void ExportGenericDelegate(Type t, string ns);
static bool autoRefresh = true;
static bool IsCompiling
{
get
{
if (EditorApplication.isCompiling)
{
Debug.Log("Unity Editor is compiling, please wait.");
}
return EditorApplication.isCompiling;
}
}
[InitializeOnLoad]
public class Startup
{
static bool isPlaying = false;
static Startup()
{
EditorApplication.update += Update;
// use this delegation to ensure dispose luavm at last
EditorApplication.playmodeStateChanged += () =>
{
if (isPlaying == true && EditorApplication.isPlaying == false)
{
if (LuaState.main != null) LuaState.main.Dispose();
}
isPlaying = EditorApplication.isPlaying;
};
}
static void Update()
{
EditorApplication.update -= Update;
Lua3rdMeta.Instance.ReBuildTypes();
// Remind user to generate lua interface code
var remindGenerate = !EditorPrefs.HasKey("SLUA_REMIND_GENERTE_LUA_INTERFACE") || EditorPrefs.GetBool("SLUA_REMIND_GENERTE_LUA_INTERFACE");
bool ok = System.IO.Directory.Exists(GenPath + "Unity") || System.IO.File.Exists(GenPath + WrapperName);
if (!ok && remindGenerate)
{
if (EditorUtility.DisplayDialog("Slua", "Not found lua interface for Unity, generate it now?", "Generate", "No"))
{
GenerateAll();
}
else
{
if (!EditorUtility.DisplayDialog("Slua", "Remind you next time when no lua interface found for Unity?", "OK",
"Don't remind me next time!"))
{
EditorPrefs.SetBool("SLUA_REMIND_GENERTE_LUA_INTERFACE", false);
}
else
{
EditorPrefs.SetBool("SLUA_REMIND_GENERTE_LUA_INTERFACE", true);
}
}
}
}
}
#if UNITY_2017_2_OR_NEWER
public static string[] unityModule = new string[] { "UnityEngine","UnityEngine.CoreModule","UnityEngine.UIModule","UnityEngine.TextRenderingModule","UnityEngine.TextRenderingModule",
"UnityEngine.UnityWebRequestWWWModule","UnityEngine.Physics2DModule","UnityEngine.AnimationModule","UnityEngine.TextRenderingModule","UnityEngine.IMGUIModule","UnityEngine.UnityWebRequestModule",
"UnityEngine.PhysicsModule", "UnityEngine.UI" };
#else
public static string[] unityModule = null;
#endif
[MenuItem("SLua/All/Make")]
static public void GenerateAll()
{
autoRefresh = false;
GenerateModule(unityModule);
GenerateUI();
GenerateAds();
Custom();
Generate3rdDll();
autoRefresh = true;
AssetDatabase.Refresh();
}
static bool filterType(Type t, List<string> noUseList, List<string> uselist)
{
if (t.IsDefined(typeof(CompilerGeneratedAttribute), false))
{
Debug.Log(t.Name + " is filtered out");
return false;
}
// check type in uselist
string fullName = t.FullName;
if (uselist != null && uselist.Count > 0)
{
return uselist.Contains(fullName);
}
else
{
// check type not in nouselist
foreach (string str in noUseList)
{
if (fullName.Contains(str))
{
return false;
}
}
return true;
}
}
static void GenerateModule(string[] target=null) {
#if UNITY_2017_2_OR_NEWER
if (target != null)
{
GenerateFor(target, "Unity/", 0, "BindUnity");
}
else
{
ModuleSelector wnd = EditorWindow.GetWindow<ModuleSelector>("ModuleSelector");
wnd.onExport = (string[] module) =>
{
GenerateFor(module, "Unity/", 0, "BindUnity");
};
}
#else
GenerateFor("UnityEngine", "Unity/", 0, "BindUnity");
#endif
}
#if UNITY_2017_2_OR_NEWER
[MenuItem("SLua/Unity/Make UnityEngine ...")]
#else
[MenuItem("SLua/Unity/Make UnityEngine")]
#endif
static public void Generate()
{
GenerateModule();
}
[MenuItem("SLua/Unity/Make UnityEngine.UI")]
static public void GenerateUI()
{
GenerateFor("UnityEngine.UI", "Unity/", 1, "BindUnityUI");
}
[MenuItem("SLua/Unity/Make UnityEngine.Advertisements")]
static public void GenerateAds()
{
GenerateFor("UnityEngine.Advertisements", "Unity/", 2, "BindUnityAds");
}
static List<Type> GetExportsType(string[] asemblyNames, string genAtPath)
{
List<Type> exports = new List<Type>();
foreach (string asemblyName in asemblyNames)
{
Assembly assembly;
try { assembly = Assembly.Load(asemblyName); }
catch (Exception) { continue; }
Type[] types = assembly.GetExportedTypes();
List<string> uselist;
List<string> noUseList;
CustomExport.OnGetNoUseList(out noUseList);
CustomExport.OnGetUseList(out uselist);
// Get use and nouse list from custom export.
object[] aCustomExport = new object[1];
InvokeEditorMethod<ICustomExportPost>("OnGetUseList", ref aCustomExport);
if (null != aCustomExport[0])
{
if (null != uselist)
{
uselist.AddRange((List<string>)aCustomExport[0]);
}
else
{
uselist = (List<string>)aCustomExport[0];
}
}
aCustomExport[0] = null;
InvokeEditorMethod<ICustomExportPost>("OnGetNoUseList", ref aCustomExport);
if (null != aCustomExport[0])
{
if ((null != noUseList))
{
noUseList.AddRange((List<string>)aCustomExport[0]);
}
else
{
noUseList = (List<string>)aCustomExport[0];
}
}
string path = GenPath + genAtPath;
foreach (Type t in types)
{
if (filterType(t, noUseList, uselist) && Generate(t, path))
exports.Add(t);
}
Debug.Log("Generate interface finished: " + asemblyName);
}
return exports;
}
static public void GenerateFor(string[] asemblyNames, string genAtPath, int genOrder, string bindMethod)
{
if (IsCompiling)
{
return;
}
List<Type> exports = GetExportsType(asemblyNames, genAtPath);
string path = GenPath + genAtPath;
GenerateBind(exports, bindMethod, genOrder, path);
if (autoRefresh)
AssetDatabase.Refresh();
}
static public void GenerateFor(string asemblyName, string genAtPath, int genOrder, string bindMethod)
{
if (IsCompiling)
{
return;
}
List<Type> exports = GetExportsType(new string[] { asemblyName }, genAtPath);
string path = GenPath + genAtPath;
GenerateBind(exports, bindMethod, genOrder, path);
if (autoRefresh)
AssetDatabase.Refresh();
}
static String FixPathName(string path)
{
if (path.EndsWith("\\") || path.EndsWith("/"))
{
return path.Substring(0, path.Length - 1);
}
return path;
}
[MenuItem("SLua/Unity/Clear Unity and UI")]
static public void ClearUnity()
{
clear(new string[] { GenPath + "Unity" });
Debug.Log("Clear Unity & UI complete.");
}
[MenuItem("SLua/Custom/Make")]
static public void Custom()
{
if (IsCompiling)
{
return;
}
List<Type> exports = new List<Type>();
string path = GenPath + "Custom/";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
ExportGenericDelegate fun = (Type t, string ns) =>
{
if (Generate(t, ns, path))
exports.Add(t);
};
HashSet<string> namespaces = CustomExport.OnAddCustomNamespace();
// Add custom namespaces.
object[] aCustomExport = null;
List<object> aCustomNs = LuaCodeGen.InvokeEditorMethod<ICustomExportPost>("OnAddCustomNamespace", ref aCustomExport);
foreach (object cNsSet in aCustomNs)
{
foreach (string strNs in (HashSet<string>)cNsSet)
{
namespaces.Add(strNs);
}
}
Assembly assembly;
Type[] types;
try
{
// export plugin-dll
assembly = Assembly.Load("Assembly-CSharp-firstpass");
types = assembly.GetExportedTypes();
foreach (Type t in types)
{
if (t.IsDefined(typeof(CustomLuaClassAttribute), false) || namespaces.Contains(t.Namespace))
{
fun(t, null);
}
}
}
catch (Exception) { }
// export self-dll
assembly = Assembly.Load("Assembly-CSharp");
types = assembly.GetExportedTypes();
foreach (Type t in types)
{
if (t.IsDefined(typeof(CustomLuaClassAttribute), false) || namespaces.Contains(t.Namespace))
{
fun(t, null);
}
}
CustomExport.OnAddCustomClass(fun);
//detect interface ICustomExportPost,and call OnAddCustomClass
aCustomExport = new object[] { fun };
InvokeEditorMethod<ICustomExportPost>("OnAddCustomClass", ref aCustomExport);
GenerateBind(exports, "BindCustom", 3, path);
if (autoRefresh)
AssetDatabase.Refresh();
Debug.Log("Generate custom interface finished");
}
static public List<object> InvokeEditorMethod<T>(string methodName, ref object[] parameters)
{
List<object> aReturn = new List<object>();
System.Reflection.Assembly editorAssembly = System.Reflection.Assembly.Load("Assembly-CSharp-Editor");
Type[] editorTypes = editorAssembly.GetExportedTypes();
foreach (Type t in editorTypes)
{
if (typeof(T).IsAssignableFrom(t))
{
System.Reflection.MethodInfo method = t.GetMethod(methodName, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
if (method != null)
{
object cRes = method.Invoke(null, parameters);
if (null != cRes)
{
aReturn.Add(cRes);
}
}
}
}
return aReturn;
}
static public List<object> GetEditorField<T>(string strFieldName)
{
List<object> aReturn = new List<object>();
System.Reflection.Assembly cEditorAssembly = System.Reflection.Assembly.Load("Assembly-CSharp-Editor");
Type[] aEditorTypes = cEditorAssembly.GetExportedTypes();
foreach (Type t in aEditorTypes)
{
if (typeof(T).IsAssignableFrom(t))
{
FieldInfo cField = t.GetField(strFieldName, BindingFlags.Static | BindingFlags.Public);
if (null != cField)
{
object cValue = cField.GetValue(t);
if (null != cValue)
{
aReturn.Add(cValue);
}
}
}
}
return aReturn;
}
[MenuItem("SLua/3rdDll/Make")]
static public void Generate3rdDll()
{
if (IsCompiling)
{
return;
}
List<Type> cust = new List<Type>();
List<string> assemblyList = new List<string>();
CustomExport.OnAddCustomAssembly(ref assemblyList);
//detect interface ICustomExportPost,and call OnAddCustomAssembly
object[] aCustomExport = new object[] { assemblyList };
InvokeEditorMethod<ICustomExportPost>("OnAddCustomAssembly", ref aCustomExport);
foreach (string assemblyItem in assemblyList)
{
Assembly assembly = Assembly.Load(assemblyItem);
Type[] types = assembly.GetExportedTypes();
foreach (Type t in types)
{
cust.Add(t);
}
}
if (cust.Count > 0)
{
List<Type> exports = new List<Type>();
string path = GenPath + "Dll/";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
foreach (Type t in cust)
{
if (Generate(t, path))
exports.Add(t);
}
GenerateBind(exports, "BindDll", 2, path);
if (autoRefresh)
AssetDatabase.Refresh();
Debug.Log("Generate 3rdDll interface finished");
}
}
[MenuItem("SLua/3rdDll/Clear")]
static public void Clear3rdDll()
{
clear(new string[] { GenPath + "Dll" });
Debug.Log("Clear AssemblyDll complete.");
}
[MenuItem("SLua/Custom/Clear")]
static public void ClearCustom()
{
clear(new string[] { GenPath + "Custom" });
Debug.Log("Clear custom complete.");
}
[MenuItem("SLua/All/Clear")]
static public void ClearALL()
{
clear(new string[] { Path.GetDirectoryName(GenPath) });
Debug.Log("Clear all complete.");
}
[MenuItem("SLua/Compile LuaObject To DLL")]
static public void CompileDLL()
{
#region scripts
List<string> scripts = new List<string>();
string[] guids = AssetDatabase.FindAssets("t:Script", new string[1] { Path.GetDirectoryName(GenPath) }).Distinct().ToArray();
int guidCount = guids.Length;
for (int i = 0; i < guidCount; i++)
{
// path may contains space
string path = "\"" + AssetDatabase.GUIDToAssetPath(guids[i]) + "\"";
if (!scripts.Contains(path))
scripts.Add(path);
}
if (scripts.Count == 0)
{
Debug.LogError("No Scripts");
return;
}
#endregion
#region libraries
List<string> libraries = new List<string>();
#if UNITY_2017_2_OR_NEWER
string[] referenced = unityModule;
#else
string[] referenced = new string[] { "UnityEngine", "UnityEngine.UI" };
#endif
string projectPath = Path.GetFullPath(Application.dataPath+"/..").Replace("\\", "/");
// http://stackoverflow.com/questions/52797/how-do-i-get-the-path-of-the-assembly-the-code-is-in
foreach (var assem in AppDomain.CurrentDomain.GetAssemblies())
{
UriBuilder uri = new UriBuilder(assem.CodeBase);
string path = Uri.UnescapeDataString(uri.Path).Replace("\\", "/");
string name = Path.GetFileNameWithoutExtension(path);
// ignore dll for Editor
if ((path.StartsWith(projectPath) && !path.Contains("/Editor/") && !path.Contains("CSharp-Editor"))
|| referenced.Contains(name))
{
libraries.Add(path);
}
}
#endregion
//generate AssemblyInfo
string AssemblyInfoFile = Application.dataPath + "/AssemblyInfo.cs";
File.WriteAllText(AssemblyInfoFile, string.Format("[assembly: UnityEngine.UnityAPICompatibilityVersionAttribute(\"{0}\")]", Application.unityVersion));
#region mono compile
string editorData = EditorApplication.applicationContentsPath;
#if UNITY_EDITOR_OSX && !UNITY_5_4_OR_NEWER
editorData += "/Frameworks";
#endif
List<string> arg = new List<string>();
arg.Add("/target:library");
arg.Add("/sdk:2");
arg.Add("/w:0");
arg.Add(string.Format("/out:\"{0}\"", WrapperName));
arg.Add(string.Format("/r:\"{0}\"", string.Join(";", libraries.ToArray())));
arg.AddRange(scripts);
arg.Add(AssemblyInfoFile);
const string ArgumentFile = "LuaCodeGen.txt";
File.WriteAllLines(ArgumentFile, arg.ToArray());
string mcs = editorData + "/MonoBleedingEdge/bin/mcs";
// wrapping since we may have space
#if UNITY_EDITOR_WIN
mcs += ".bat";
#endif
#endregion
#region execute bash
StringBuilder output = new StringBuilder();
StringBuilder error = new StringBuilder();
bool success = false;
try
{
var process = new System.Diagnostics.Process();
process.StartInfo.FileName = mcs;
process.StartInfo.Arguments = "@" + ArgumentFile;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
using (var outputWaitHandle = new System.Threading.AutoResetEvent(false))
using (var errorWaitHandle = new System.Threading.AutoResetEvent(false))
{
process.OutputDataReceived += (sender, e) =>
{
if (e.Data == null)
{
outputWaitHandle.Set();
}
else
{
output.AppendLine(e.Data);
}
};
process.ErrorDataReceived += (sender, e) =>
{
if (e.Data == null)
{
errorWaitHandle.Set();
}
else
{
error.AppendLine(e.Data);
}
};
// http://stackoverflow.com/questions/139593/processstartinfo-hanging-on-waitforexit-why
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
const int timeout = 300;
if (process.WaitForExit(timeout * 1000) &&
outputWaitHandle.WaitOne(timeout * 1000) &&
errorWaitHandle.WaitOne(timeout * 1000))
{
success = (process.ExitCode == 0);
}
}
}
catch (System.Exception ex)
{
Debug.LogError(ex);
}
#endregion
Debug.Log(output.ToString());
if (success)
{
Directory.Delete(GenPath, true);
Directory.CreateDirectory(GenPath);
File.Move (WrapperName, GenPath + WrapperName);
// AssetDatabase.Refresh();
File.Delete(ArgumentFile);
File.Delete(AssemblyInfoFile);
}
else
{
Debug.LogError(error.ToString());
}
}
static void clear(string[] paths)
{
try
{
foreach (string path in paths)
{
System.IO.Directory.Delete(path, true);
AssetDatabase.DeleteAsset(path);
}
}
catch
{
}
AssetDatabase.Refresh();
}
static bool Generate(Type t, string path)
{
return Generate(t, null, path);
}
static bool Generate(Type t, string ns, string path)
{
CodeGenerator cg = new CodeGenerator();
cg.givenNamespace = ns;
cg.path = path;
return cg.Generate(t);
}
static void GenerateBind(List<Type> list, string name, int order,string path)
{
// delete wrapper dll
try
{
System.IO.File.Delete(GenPath + WrapperName);
}
catch {}
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
CodeGenerator cg = new CodeGenerator();
cg.path = path;
cg.GenerateBind(list, name, order);
}
}
class CodeGenerator
{
static List<string> memberFilter = new List<string>
{
"AnimationClip.averageDuration",
"AnimationClip.averageAngularSpeed",
"AnimationClip.averageSpeed",
"AnimationClip.apparentSpeed",
"AnimationClip.isLooping",
"AnimationClip.isAnimatorMotion",
"AnimationClip.isHumanMotion",
"AnimatorOverrideController.PerformOverrideClipListCleanup",
"Caching.SetNoBackupFlag",
"Caching.ResetNoBackupFlag",
"Light.areaSize",
"Security.GetChainOfTrustValue",
"Texture2D.alphaIsTransparency",
"WWW.movie",
"WebCamTexture.MarkNonReadable",
"WebCamTexture.isReadable",
// i don't know why below 2 functions missed in iOS platform
"*.OnRebuildRequested",
// il2cpp not exixts
"Application.ExternalEval",
"GameObject.networkView",
"Component.networkView",
// unity5
"AnimatorControllerParameter.name",
"Input.IsJoystickPreconfigured",
"Resources.LoadAssetAtPath",
#if UNITY_4_6
"Motion.ValidateIfRetargetable",
"Motion.averageDuration",
"Motion.averageAngularSpeed",
"Motion.averageSpeed",
"Motion.apparentSpeed",
"Motion.isLooping",
"Motion.isAnimatorMotion",
"Motion.isHumanMotion",
#endif
"Light.lightmappingMode",
"Light.lightmapBakeType",
"MonoBehaviour.runInEditMode",
"MonoBehaviour.useGUILayout",
"PlayableGraph.CreateScriptPlayable",
};
static void FilterSpecMethods(out Dictionary<Type,List<MethodInfo>> dic, out Dictionary<Type,Type> overloadedClass){
dic = new Dictionary<Type, List<MethodInfo>>();
overloadedClass = new Dictionary<Type, Type> ();
List<string> asems;
CustomExport.OnGetAssemblyToGenerateExtensionMethod(out asems);
// Get list from custom export.
object[] aCustomExport = new object[1];
LuaCodeGen.InvokeEditorMethod<ICustomExportPost>("OnGetAssemblyToGenerateExtensionMethod", ref aCustomExport);
if (null != aCustomExport[0])
{
if (null != asems)
{
asems.AddRange((List<string>)aCustomExport[0]);
}
else
{
asems = (List<string>)aCustomExport[0];
}
}
foreach (string assstr in asems)
{
Assembly assembly = Assembly.Load(assstr);
foreach (Type type in assembly.GetExportedTypes())
{
if (type.IsSealed && !type.IsGenericType && !type.IsNested)
{
MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public);
foreach (MethodInfo _method in methods)
{
MethodInfo method = tryFixGenericMethod(_method);
if (IsExtensionMethod(method))
{
Type extendedType = method.GetParameters()[0].ParameterType;
if (!dic.ContainsKey(extendedType))
{
dic.Add(extendedType, new List<MethodInfo>());
}
dic[extendedType].Add(method);
}
}
}
if (type.IsDefined(typeof(OverloadLuaClassAttribute),false)) {
OverloadLuaClassAttribute olc = type.GetCustomAttributes (typeof(OverloadLuaClassAttribute), false)[0] as OverloadLuaClassAttribute;
if (olc != null) {
if (overloadedClass.ContainsKey (olc.targetType))
throw new Exception ("Can't overload class more than once");
overloadedClass.Add (olc.targetType, type);
}
}
}
}
}
static bool IsExtensionMethod(MethodBase method){
return method.IsDefined(typeof(System.Runtime.CompilerServices.ExtensionAttribute),false);
}
static Dictionary<System.Type,List<MethodInfo>> extensionMethods;
static Dictionary<Type,Type> overloadedClass;
static CodeGenerator(){
FilterSpecMethods(out extensionMethods,out overloadedClass);
}
HashSet<string> funcname = new HashSet<string>();
Dictionary<string, bool> directfunc = new Dictionary<string, bool>();
public string givenNamespace;
public string path;
public bool includeExtension = SLuaSetting.Instance.exportExtensionMethod;
public EOL eol = SLuaSetting.Instance.eol;
class PropPair
{
public string get = "null";
public string set = "null";
public bool isInstance = true;
}
Dictionary<string, PropPair> propname = new Dictionary<string, PropPair>();
int indent = 0;
public void GenerateBind(List<Type> list, string name, int order)
{
HashSet<Type> exported = new HashSet<Type>();
string f = System.IO.Path.Combine(path , name + ".cs");
StreamWriter file = new StreamWriter(f, false, Encoding.UTF8);
file.NewLine = NewLine;
Write(file, "using System;");
Write(file, "using System.Collections.Generic;");
Write(file, "namespace SLua {");
Write(file, "[LuaBinder({0})]", order);
Write(file, "public class {0} {{", name);
Write(file, "public static Action<IntPtr>[] GetBindList() {");
Write(file, "Action<IntPtr>[] list= {");
foreach (Type t in list)
{
WriteBindType(file, t, list, exported);
}
Write(file, "};");
Write(file, "return list;");
Write(file, "}");
Write(file, "}");
Write(file, "}");
file.Close();
}
void WriteBindType(StreamWriter file, Type t, List<Type> exported, HashSet<Type> binded)
{
if (t == null || binded.Contains(t) || !exported.Contains(t))
return;
WriteBindType(file, t.BaseType, exported, binded);
Write(file, "{0}.reg,", ExportName(t), binded);
binded.Add(t);
}
public string DelegateExportFilename(string path, Type t)
{
string f;
if (t.IsGenericType)
{
f = path + string.Format("Lua{0}_{1}.cs", _Name(GenericBaseName(t)), _Name(GenericName(t)));
}
else
{
f = path + "LuaDelegate_" + _Name(t.FullName) + ".cs";
}
return f;
}
public bool Generate(Type t)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (!t.IsGenericTypeDefinition && (!IsObsolete(t) && t != typeof(YieldInstruction) && t != typeof(Coroutine))
|| (t.BaseType != null && t.BaseType == typeof(System.MulticastDelegate)))
{
if (t.IsNested && t.DeclaringType.IsPublic == false)
return false;
if (t.IsEnum)
{
StreamWriter file = Begin(t);
WriteHead(t, file);
RegEnumFunction(t, file);
End(file);
}
else if (t.BaseType == typeof(System.MulticastDelegate))
{
if (t.ContainsGenericParameters)
return false;
string f = DelegateExportFilename(path, t);
StreamWriter file = new StreamWriter(f, false, Encoding.UTF8);
file.NewLine = NewLine;
WriteDelegate(t, file);
file.Close();
return false;
}
else
{
funcname.Clear();
propname.Clear();
directfunc.Clear();
StreamWriter file = Begin(t);
WriteHead(t, file);
WriteConstructor(t, file);
WriteFunction(t, file,false);
WriteFunction(t, file, true);
WriteField(t, file);
RegFunction(t, file);
End(file);
if (t.BaseType != null && t.BaseType.Name.Contains("UnityEvent`"))
{
string basename = "LuaUnityEvent_" + _Name(GenericName(t.BaseType)) + ".cs";
string f = path + basename;
string checkf = LuaCodeGen.GenPath + "Unity/" + basename;
if (!File.Exists(checkf)) // if had exported
{
file = new StreamWriter(f, false, Encoding.UTF8);
file.NewLine = NewLine;
WriteEvent(t, file);
file.Close();
}
}
}
return true;
}
return false;
}
struct ArgMode {
public int index;
public int mode;
public ArgMode(int index,int mode) {
this.index=index;
this.mode=mode;
}
};
void WriteDelegate(Type t, StreamWriter file)
{
string temp = @"
using System;
using System.Collections.Generic;
namespace SLua
{
public partial class LuaDelegation : LuaObject
{
static internal $RET $FN(LuaFunction ld $ARGS) {
IntPtr l = ld.L;
int error = pushTry(l);
";
MethodInfo mi = t.GetMethod("Invoke");
temp = temp.Replace("$TN", t.Name);
temp = temp.Replace("$FN", ExportName(t));
temp = temp.Replace("$RET",
mi.ReturnType != typeof(void)?SimpleType(mi.ReturnType):"void");
string args = ArgsList(mi);
if (args.Length > 0) args = "," + args;
temp = temp.Replace("$ARGS", args);
Write(file, temp);
this.indent = 3;
ParameterInfo[] pis = mi.GetParameters ();
for (int n = 0; n < pis.Length; n++)
{
if (!pis[n].IsOut)
Write(file, "pushValue(l,a{0});", n + 1);
}
int outcount = pis.Count ((ParameterInfo p) => {
return p.ParameterType.IsByRef && p.IsOut;
});
Write(file, "ld.pcall({0}, error);", pis.Length - outcount);
int offset = 0;
if (mi.ReturnType != typeof(void))
{
offset = 1;
WriteValueCheck(file, mi.ReturnType, offset, "ret", "error+");
}
for (int n = 0; n < pis.Length; n++) {
if (pis [n].ParameterType.IsByRef) {
string a = string.Format ("a{0}", n + 1);
WriteCheckType (file, pis[n].ParameterType, ++offset, a, "error+");
}
}
Write(file, "LuaDLL.lua_settop(l, error-1);");
if (mi.ReturnType != typeof(void))
Write(file, "return ret;");
Write(file, "}");
Write(file, "}");
Write(file, "}");
}
string ArgsList(MethodInfo m)
{
string str = "";
ParameterInfo[] pars = m.GetParameters();
for (int n = 0; n < pars.Length; n++)
{
string t = SimpleType(pars[n].ParameterType);
ParameterInfo p = pars[n];
if (p.ParameterType.IsByRef && p.IsOut)
str += string.Format("out {0} a{1}", t, n + 1);
else if (p.ParameterType.IsByRef)
str += string.Format("ref {0} a{1}", t, n + 1);
else
str += string.Format("{0} a{1}", t, n + 1);
if (n < pars.Length - 1)
str += ",";
}
return str;
}
void tryMake(Type t)
{
if (t.BaseType == typeof(System.MulticastDelegate))
{
CodeGenerator cg = new CodeGenerator();
if (File.Exists(cg.DelegateExportFilename(LuaCodeGen.GenPath + "Unity/", t)))
return;
cg.path = this.path;
cg.Generate(t);
}
}
void WriteEvent(Type t, StreamWriter file)
{
string temp = @"
using System;
using System.Collections.Generic;
namespace SLua
{
public class LuaUnityEvent_$CLS : LuaObject
{
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int AddListener(IntPtr l)
{
try
{
UnityEngine.Events.UnityEvent<$GN> self = checkSelf<UnityEngine.Events.UnityEvent<$GN>>(l);
UnityEngine.Events.UnityAction<$GN> a1;
checkType(l, 2, out a1);
self.AddListener(a1);
pushValue(l,true);
return 1;
}
catch (Exception e)
{
return error(l,e);
}
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int RemoveListener(IntPtr l)
{
try
{
UnityEngine.Events.UnityEvent<$GN> self = checkSelf<UnityEngine.Events.UnityEvent<$GN>>(l);
UnityEngine.Events.UnityAction<$GN> a1;
checkType(l, 2, out a1);
self.RemoveListener(a1);
pushValue(l,true);
return 1;
}
catch (Exception e)
{
return error(l,e);
}
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int Invoke(IntPtr l)
{
try
{
UnityEngine.Events.UnityEvent<$GN> self = checkSelf<UnityEngine.Events.UnityEvent<$GN>>(l);
" +
GenericCallDecl(t.BaseType)
+ @"
pushValue(l,true);
return 1;
}
catch (Exception e)
{
return error(l,e);
}
}
static public void reg(IntPtr l)
{
getTypeTable(l, typeof(LuaUnityEvent_$CLS).FullName);
addMember(l, AddListener);
addMember(l, RemoveListener);
addMember(l, Invoke);
createTypeMetatable(l, null, typeof(LuaUnityEvent_$CLS), typeof(UnityEngine.Events.UnityEventBase));
}
static bool checkType(IntPtr l,int p,out UnityEngine.Events.UnityAction<$GN> ua) {
LuaDLL.luaL_checktype(l, p, LuaTypes.LUA_TFUNCTION);
LuaDelegate ld;
checkType(l, p, out ld);
if (ld.d != null)
{
ua = (UnityEngine.Events.UnityAction<$GN>)ld.d;
return true;
}
l = LuaState.get(l).L;
ua = ($ARGS) =>
{
int error = pushTry(l);
$PUSHVALUES
ld.pcall($GENERICCOUNT, error);
LuaDLL.lua_settop(l,error - 1);
};
ld.d = ua;
return true;
}
}
}";
temp = temp.Replace("$CLS", _Name(GenericName(t.BaseType)));
temp = temp.Replace("$FNAME", FullName(t));
temp = temp.Replace("$GN", GenericName(t.BaseType,","));
temp = temp.Replace("$ARGS", ArgsDecl(t.BaseType));
temp = temp.Replace("$PUSHVALUES", PushValues(t.BaseType));
temp = temp.Replace ("$GENERICCOUNT", t.BaseType.GetGenericArguments ().Length.ToString());
Write(file, temp);
}
string GenericCallDecl(Type t) {
try
{
Type[] tt = t.GetGenericArguments();
string ret = "";
string args = "";
for (int n = 0; n < tt.Length; n++)
{
string dt = SimpleType(tt[n]);
ret+=string.Format(" {0} a{1};",dt,n)+NewLine;
//ret+=string.Format(" checkType(l,{0},out a{1});",n+2,n)+NewLine;
ret += " " + GetCheckType(tt[n], n + 2, "a" + n) + NewLine;
args +=("a"+n);
if (n < tt.Length - 1) args += ",";
}
ret+=string.Format(" self.Invoke({0});",args)+NewLine;
return ret;
}
catch (Exception e)
{
Debug.Log(e.ToString());
return "";
}
}
string GetCheckType(Type t, int n, string v = "v", string prefix = "")
{
if (t.IsEnum)
{
return string.Format("checkEnum(l,{2}{0},out {1});", n, v, prefix);
}
else if (t.BaseType == typeof(System.MulticastDelegate))
{
return string.Format("int op=checkDelegate(l,{2}{0},out {1});", n, v, prefix);
}
else if (IsValueType(t))
{
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
return string.Format("checkNullable(l,{2}{0},out {1});", n, v, prefix);
else
return string.Format("checkValueType(l,{2}{0},out {1});", n, v, prefix);
}
else if (t.IsArray)
{
return string.Format("checkArray(l,{2}{0},out {1});", n, v, prefix);
}
else
{
return string.Format("checkType(l,{2}{0},out {1});", n, v, prefix);
}
}
string PushValues(Type t) {
try
{
Type[] tt = t.GetGenericArguments();
string ret = "";
for (int n = 0; n < tt.Length; n++)
{
ret+=("pushValue(l,v"+n+");");
}
return ret;
}
catch (Exception e)
{
Debug.Log(e.ToString());
return "";
}
}
string ArgsDecl(Type t)
{
try
{
Type[] tt = t.GetGenericArguments();
string ret = "";
for (int n = 0; n < tt.Length; n++)
{
string dt = SimpleType(tt[n]);
dt+=(" v"+n);
ret += dt;
if (n < tt.Length - 1)
ret += ",";
}
return ret;
}
catch (Exception e)
{
Debug.Log(e.ToString());
return "";
}
}
void RegEnumFunction(Type t, StreamWriter file)
{
// Write export function
Write(file, "static public void reg(IntPtr l) {");
Write(file, "getEnumTable(l,\"{0}\");", string.IsNullOrEmpty(givenNamespace) ? FullName(t) : givenNamespace);
foreach (string name in Enum.GetNames (t))
{
Write(file, "addMember(l,{0},\"{1}\");", Convert.ToInt32(Enum.Parse(t, name)), name);
}
Write(file, "LuaDLL.lua_pop(l, 1);");
Write(file, "}");
}
StreamWriter Begin(Type t)
{
string clsname = ExportName(t);
string f = path + clsname + ".cs";
StreamWriter file = new StreamWriter(f, false, Encoding.UTF8);
file.NewLine = NewLine;
return file;
}
private void End(StreamWriter file)
{
Write(file, "}");
file.Flush();
file.Close();
}
private void WriteHead(Type t, StreamWriter file)
{
HashSet<string> nsset=new HashSet<string>();
Write(file, "using System;");
Write(file, "using SLua;");
Write(file, "using System.Collections.Generic;");
nsset.Add("System");
nsset.Add("SLua");
nsset.Add("System.Collections.Generic");
WriteExtraNamespace(file,t, nsset);
#if UNITY_5_3_OR_NEWER
Write (file, "[UnityEngine.Scripting.Preserve]");
#endif
Write(file, "public class {0} : LuaObject {{", ExportName(t));
}
// add namespace for extension method
void WriteExtraNamespace(StreamWriter file,Type t, HashSet<string> nsset) {
List<MethodInfo> lstMI;
if(extensionMethods.TryGetValue(t,out lstMI)) {
foreach(MethodInfo m in lstMI) {
// if not writed
if(!string.IsNullOrEmpty(m.ReflectedType.Namespace) && !nsset.Contains(m.ReflectedType.Namespace)) {
Write(file,"using {0};",m.ReflectedType.Namespace);
nsset.Add(m.ReflectedType.Namespace);
}
}
}
}
private void WriteFunction(Type t, StreamWriter file, bool writeStatic = false)
{
BindingFlags bf = BindingFlags.Public | BindingFlags.DeclaredOnly;
if (writeStatic)
bf |= BindingFlags.Static;
else
bf |= BindingFlags.Instance;
MethodInfo[] members = t.GetMethods(bf);
List<MethodInfo> methods = new List<MethodInfo>();
foreach (MethodInfo mi in members)
methods.Add(tryFixGenericMethod(mi));
if (!writeStatic && this.includeExtension){
if(extensionMethods.ContainsKey(t)){
methods.AddRange(extensionMethods[t]);
}
}
foreach (MethodInfo mi in methods)
{
bool instanceFunc;
if (writeStatic && isPInvoke(mi, out instanceFunc))
{
directfunc.Add(t.FullName + "." + mi.Name, instanceFunc);
continue;
}
string fn = writeStatic ? staticName(mi.Name) : mi.Name;
if (mi.MemberType == MemberTypes.Method
&& !IsObsolete(mi)
&& !DontExport(mi)
&& !funcname.Contains(fn)
&& isUsefullMethod(mi)
&& !MemberInFilter(t, mi))
{
WriteFunctionDec(file, fn);
WriteFunctionImpl(file, mi, t, bf);
funcname.Add(fn);
}
}
}
bool isPInvoke(MethodInfo mi, out bool instanceFunc)
{
if (mi.IsDefined(typeof(SLua.MonoPInvokeCallbackAttribute), false))
{
instanceFunc = !mi.IsDefined(typeof(StaticExportAttribute), false);
return true;
}
instanceFunc = true;
return false;
}
string staticName(string name)
{
if (name.StartsWith("op_"))
return name;
return name + "_s";
}
bool MemberInFilter(Type t, MemberInfo mi)
{
return memberFilter.Contains(t.Name + "." + mi.Name) || memberFilter.Contains("*." + mi.Name);
}
bool IsObsolete(MemberInfo t)
{
return t.IsDefined(typeof(ObsoleteAttribute), false);
}
string NewLine{
get{
switch(eol){
case EOL.Native:
return System.Environment.NewLine;
case EOL.CRLF:
return "\r\n";
case EOL.CR:
return "\r";
case EOL.LF:
return "\n";
default:
return "";
}
}
}
bool trygetOverloadedVersion(Type t,ref string f) {
Type ot;
if (overloadedClass.TryGetValue (t, out ot)) {
MethodInfo mi = ot.GetMethod (f, BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
if (mi != null && mi.IsDefined(typeof(SLua.MonoPInvokeCallbackAttribute),false)) {
f = FullName (ot) + "." + f;
return true;
}
}
return false;
}
void RegFunction(Type t, StreamWriter file)
{
#if UNITY_5_3_OR_NEWER
Write (file, "[UnityEngine.Scripting.Preserve]");
#endif
// Write export function
Write(file, "static public void reg(IntPtr l) {");
if (t.BaseType != null && t.BaseType.Name.Contains("UnityEvent`"))
{
Write(file, "LuaUnityEvent_{1}.reg(l);", FullName(t), _Name((GenericName(t.BaseType))));
}
Write(file, "getTypeTable(l,\"{0}\");", string.IsNullOrEmpty(givenNamespace) ? FullName(t) : givenNamespace);
foreach (string i in funcname)
{
string f = i;
trygetOverloadedVersion (t, ref f);
Write (file, "addMember(l,{0});", f);
}
foreach (string f in directfunc.Keys)
{
bool instance = directfunc[f];
Write(file, "addMember(l,{0},{1});", f, instance ? "true" : "false");
}
foreach (string f in propname.Keys)
{
PropPair pp = propname[f];
trygetOverloadedVersion(t, ref pp.get);
trygetOverloadedVersion(t, ref pp.set);
Write(file, "addMember(l,\"{0}\",{1},{2},{3});", f, pp.get, pp.set, pp.isInstance ? "true" : "false");
}
if (t.BaseType != null && !CutBase(t.BaseType))
{
if (t.BaseType.Name.Contains("UnityEvent`"))
Write(file, "createTypeMetatable(l,{2}, typeof({0}),typeof(LuaUnityEvent_{1}));", TypeDecl(t), _Name(GenericName(t.BaseType)), constructorOrNot(t));
else
Write(file, "createTypeMetatable(l,{2}, typeof({0}),typeof({1}));", TypeDecl(t), TypeDecl(t.BaseType), constructorOrNot(t));
}
else
Write(file, "createTypeMetatable(l,{1}, typeof({0}));", TypeDecl(t), constructorOrNot(t));
Write(file, "}");
}
string constructorOrNot(Type t)
{
ConstructorInfo[] cons = GetValidConstructor(t);
if (cons.Length > 0 || t.IsValueType)
return "constructor";
return "null";
}
bool CutBase(Type t)
{
if (t.FullName.StartsWith("System.Object"))
return true;
return false;
}
void WriteSet(StreamWriter file, Type t, string cls, string fn, bool isstatic = false,bool canread = true)
{
if (t.BaseType == typeof(MulticastDelegate))
{
if (isstatic)
{
Write(file, "if(op==0) {0}.{1}=v;", cls, fn);
if(canread){
Write(file, "else if(op==1) {0}.{1}+=v;", cls, fn);
Write(file, "else if(op==2) {0}.{1}-=v;", cls, fn);
}
}
else
{
Write(file, "if(op==0) self.{0}=v;", fn);
if(canread){
Write(file, "else if(op==1) self.{0}+=v;", fn);
Write(file, "else if(op==2) self.{0}-=v;", fn);
}
}
}
else
{
if (isstatic)
{
Write(file, "{0}.{1}=v;", cls, fn);
}
else
{
Write(file, "self.{0}=v;", fn);
}
}
}
readonly static string[] keywords = { "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while" };
static string NormalName(string name)
{
if (Array.BinarySearch<string>(keywords, name) >= 0)
{
return "@" + name;
}
return name;
}
private void WriteField(Type t, StreamWriter file)
{
// Write field set/get
FieldInfo[] fields = t.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (FieldInfo fi in fields)
{
if (DontExport(fi) || IsObsolete(fi))
continue;
PropPair pp = new PropPair();
pp.isInstance = !fi.IsStatic;
if (fi.FieldType.BaseType != typeof(MulticastDelegate))
{
WriteFunctionAttr(file);
Write(file, "static public int get_{0}(IntPtr l) {{", fi.Name);
WriteTry(file);
if (fi.IsStatic)
{
WriteOk(file);
WritePushValue(fi.FieldType, file, string.Format("{0}.{1}", TypeDecl(t), NormalName(fi.Name)));
}
else
{
WriteCheckSelf(file, t);
WriteOk(file);
WritePushValue(fi.FieldType, file, string.Format("self.{0}", NormalName(fi.Name)));
}
Write(file, "return 2;");
WriteCatchExecption(file);
Write(file, "}");
pp.get = "get_" + fi.Name;
}
if (!fi.IsLiteral && !fi.IsInitOnly)
{
WriteFunctionAttr(file);
Write(file, "static public int set_{0}(IntPtr l) {{", fi.Name);
WriteTry(file);
if (fi.IsStatic)
{
Write(file, "{0} v;", TypeDecl(fi.FieldType));
WriteCheckType(file, fi.FieldType, 2);
WriteSet(file, fi.FieldType, TypeDecl(t), NormalName(fi.Name), true);
}
else
{
WriteCheckSelf(file, t);
Write(file, "{0} v;", TypeDecl(fi.FieldType));
WriteCheckType(file, fi.FieldType, 2);
WriteSet(file, fi.FieldType, t.FullName, NormalName(fi.Name));
}
if (t.IsValueType && !fi.IsStatic)
Write(file, "setBack(l,self);");
WriteOk(file);
Write(file, "return 1;");
WriteCatchExecption(file);
Write(file, "}");
pp.set = "set_" + fi.Name;
}
propname.Add(fi.Name, pp);
tryMake(fi.FieldType);
}
//for this[]
List<PropertyInfo> getter = new List<PropertyInfo>();
List<PropertyInfo> setter = new List<PropertyInfo>();
// Write property set/get
PropertyInfo[] props = t.GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (PropertyInfo fi in props)
{
//if (fi.Name == "Item" || IsObsolete(fi) || MemberInFilter(t,fi) || DontExport(fi))
if (IsObsolete(fi) || MemberInFilter(t, fi) || DontExport(fi))
continue;
if (fi.Name == "Item"
|| (t.Name == "String" && fi.Name == "Chars")) // for string[]
{
//for this[]
if (!fi.GetGetMethod().IsStatic && fi.GetIndexParameters().Length == 1)
{
if (fi.CanRead && !IsNotSupport(fi.PropertyType))
getter.Add(fi);
if (fi.CanWrite && fi.GetSetMethod() != null)
setter.Add(fi);
}
continue;
}
PropPair pp = new PropPair();
bool isInstance = true;
if (fi.CanRead && fi.GetGetMethod() != null)
{
if (!IsNotSupport(fi.PropertyType))
{
WriteFunctionAttr(file);
Write(file, "static public int get_{0}(IntPtr l) {{", fi.Name);
WriteTry(file);
if (fi.GetGetMethod().IsStatic)
{
isInstance = false;
WriteOk(file);
WritePushValue(fi.PropertyType, file, string.Format("{0}.{1}", TypeDecl(t), NormalName(fi.Name)));
}
else
{
WriteCheckSelf(file, t);
WriteOk(file);
WritePushValue(fi.PropertyType, file, string.Format("self.{0}", NormalName(fi.Name)));
}
Write(file, "return 2;");
WriteCatchExecption(file);
Write(file, "}");
pp.get = "get_" + fi.Name;
}
}
if (fi.CanWrite && fi.GetSetMethod() != null)
{
WriteFunctionAttr(file);
Write(file, "static public int set_{0}(IntPtr l) {{", fi.Name);
WriteTry(file);
if (fi.GetSetMethod().IsStatic)
{
WriteValueCheck(file, fi.PropertyType, 2);
WriteSet(file, fi.PropertyType, TypeDecl(t), NormalName(fi.Name), true,fi.CanRead);
isInstance = false;
}
else
{
WriteCheckSelf(file, t);
WriteValueCheck(file, fi.PropertyType, 2);
WriteSet(file, fi.PropertyType, TypeDecl(t), NormalName(fi.Name),false,fi.CanRead);
}
if (t.IsValueType)
Write(file, "setBack(l,self);");
WriteOk(file);
Write(file, "return 1;");
WriteCatchExecption(file);
Write(file, "}");
pp.set = "set_" + fi.Name;
}
pp.isInstance = isInstance;
propname.Add(fi.Name, pp);
tryMake(fi.PropertyType);
}
//for this[]
WriteItemFunc(t, file, getter, setter);
}
void WriteItemFunc(Type t, StreamWriter file, List<PropertyInfo> getter, List<PropertyInfo> setter)
{
//Write property this[] set/get
if (getter.Count > 0)
{
//get
bool first_get = true;
WriteFunctionAttr(file);
Write(file, "static public int getItem(IntPtr l) {");
WriteTry(file);
WriteCheckSelf(file, t);
if (getter.Count == 1)
{
PropertyInfo _get = getter[0];
ParameterInfo[] infos = _get.GetIndexParameters();
WriteValueCheck(file, infos[0].ParameterType, 2, "v");
Write(file, "var ret = self[v];");
WriteOk(file);
WritePushValue(_get.PropertyType, file, "ret");
Write(file, "return 2;");
}
else
{
Write(file, "LuaTypes t = LuaDLL.lua_type(l, 2);");
for (int i = 0; i < getter.Count; i++)
{
PropertyInfo fii = getter[i];
ParameterInfo[] infos = fii.GetIndexParameters();
Write(file, "{0}(matchType(l,2,t,typeof({1}))){{", first_get ? "if" : "else if", infos[0].ParameterType);
WriteValueCheck(file, infos[0].ParameterType, 2, "v");
Write(file, "var ret = self[v];");
WriteOk(file);
WritePushValue(fii.PropertyType, file, "ret");
Write(file, "return 2;");
Write(file, "}");
first_get = false;
}
WriteNotMatch (file, "getItem");
}
WriteCatchExecption(file);
Write(file, "}");
funcname.Add("getItem");
}
if (setter.Count > 0)
{
bool first_set = true;
WriteFunctionAttr(file);
Write(file, "static public int setItem(IntPtr l) {");
WriteTry(file);
WriteCheckSelf(file, t);
if (setter.Count == 1)
{
PropertyInfo _set = setter[0];
ParameterInfo[] infos = _set.GetIndexParameters();
WriteValueCheck(file, infos[0].ParameterType, 2);
WriteValueCheck(file, _set.PropertyType, 3, "c");
Write(file, "self[v]=c;");
WriteOk(file);
Write(file, "return 1;");
}
else
{
Write(file, "LuaTypes t = LuaDLL.lua_type(l, 2);");
for (int i = 0; i < setter.Count; i++)
{
PropertyInfo fii = setter[i];
if (t.BaseType != typeof(MulticastDelegate))
{
ParameterInfo[] infos = fii.GetIndexParameters();
Write(file, "{0}(matchType(l,2,t,typeof({1}))){{", first_set ? "if" : "else if", infos[0].ParameterType);
WriteValueCheck(file, infos[0].ParameterType, 2, "v");
WriteValueCheck(file, fii.PropertyType, 3, "c");
Write(file, "self[v]=c;");
WriteOk(file);
Write(file, "return 1;");
Write(file, "}");
first_set = false;
}
if (t.IsValueType)
Write(file, "setBack(l,self);");
}
WriteNotMatch (file, "setItem");
}
WriteCatchExecption(file);
Write(file, "}");
funcname.Add("setItem");
}
}
void WriteTry(StreamWriter file)
{
Write(file, "try {");
}
void WriteCatchExecption(StreamWriter file)
{
Write(file, "}");
Write(file, "catch(Exception e) {");
Write(file, "return error(l,e);");
Write(file, "}");
}
void WriteCheckType(StreamWriter file, Type t, int n, string v = "v", string nprefix = "")
{
if (t.IsEnum)
Write(file, "checkEnum(l,{2}{0},out {1});", n, v, nprefix);
else if (t.BaseType == typeof(System.MulticastDelegate))
Write(file, "int op=checkDelegate(l,{2}{0},out {1});", n, v, nprefix);
else if (IsValueType(t))
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
Write(file, "checkNullable(l,{2}{0},out {1});", n, v, nprefix);
else
Write(file, "checkValueType(l,{2}{0},out {1});", n, v, nprefix);
else if (t.IsArray)
Write(file, "checkArray(l,{2}{0},out {1});", n, v, nprefix);
else
Write(file, "checkType(l,{2}{0},out {1});", n, v, nprefix);
}
void WriteValueCheck(StreamWriter file, Type t, int n, string v = "v", string nprefix = "")
{
Write(file, "{0} {1};", SimpleType(t), v);
WriteCheckType(file, t, n, v, nprefix);
}
private void WriteFunctionAttr(StreamWriter file)
{
Write(file, "[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]");
#if UNITY_5_3_OR_NEWER
Write (file, "[UnityEngine.Scripting.Preserve]");
#endif
}
ConstructorInfo[] GetValidConstructor(Type t)
{
List<ConstructorInfo> ret = new List<ConstructorInfo>();
if (t.GetConstructor(Type.EmptyTypes) == null && t.IsAbstract && t.IsSealed)
return ret.ToArray();
if (t.IsAbstract)
return ret.ToArray();
if (t.BaseType != null && t.BaseType.Name == "MonoBehaviour")
return ret.ToArray();
ConstructorInfo[] cons = t.GetConstructors(BindingFlags.Instance | BindingFlags.Public);
foreach (ConstructorInfo ci in cons)
{
if (!IsObsolete(ci) && !DontExport(ci) && !ContainUnsafe(ci))
ret.Add(ci);
}
return ret.ToArray();
}
bool ContainUnsafe(MethodBase mi)
{
foreach (ParameterInfo p in mi.GetParameters())
{
if (p.ParameterType.FullName.Contains("*"))
return true;
}
return false;
}
bool DontExport(MemberInfo mi)
{
var methodString = string.Format("{0}.{1}", mi.DeclaringType, mi.Name);
if (CustomExport.FunctionFilterList.Contains(methodString))
return true;
// directly ignore any components .ctor
if (mi.DeclaringType.IsSubclassOf(typeof(UnityEngine.Component)))
{
if (mi.MemberType == MemberTypes.Constructor)
{
return true;
}
}
// Check in custom export function filter list.
List<object> aFuncFilterList = LuaCodeGen.GetEditorField<ICustomExportPost>("FunctionFilterList");
foreach (object aFilterList in aFuncFilterList)
{
if (((List<string>)aFilterList).Contains(methodString))
{
return true;
}
}
return mi.IsDefined(typeof(DoNotToLuaAttribute), false);
}
private void WriteConstructor(Type t, StreamWriter file)
{
ConstructorInfo[] cons = GetValidConstructor(t);
if (cons.Length > 0)
{
WriteFunctionAttr(file);
Write(file, "static public int constructor(IntPtr l) {");
WriteTry(file);
if (cons.Length > 1)
Write(file, "int argc = LuaDLL.lua_gettop(l);");
Write(file, "{0} o;", TypeDecl(t));
bool first = true;
for (int n = 0; n < cons.Length; n++)
{
ConstructorInfo ci = cons[n];
ParameterInfo[] pars = ci.GetParameters();
if (cons.Length > 1)
{
if (isUniqueArgsCount(cons, ci))
Write(file, "{0}(argc=={1}){{", first ? "if" : "else if", ci.GetParameters().Length + 1);
else
Write(file, "{0}(matchType(l,argc,2{1})){{", first ? "if" : "else if", TypeDecl(pars));
}
for (int k = 0; k < pars.Length; k++)
{
ParameterInfo p = pars[k];
bool hasParams = p.IsDefined(typeof(ParamArrayAttribute), false);
CheckArgument(file, p.ParameterType, k, 2, p.IsOut, hasParams);
}
Write(file, "o=new {0}({1});", TypeDecl(t), FuncCall(ci));
WriteOk(file);
if (t.Name == "String") // if export system.string, push string as ud not lua string
Write(file, "pushObject(l,o);");
else
Write(file, "pushValue(l,o);");
Write(file, "return 2;");
if (cons.Length == 1)
WriteCatchExecption(file);
Write(file, "}");
first = false;
}
if (cons.Length > 1)
{
if(t.IsValueType)
{
Write(file, "{0}(argc=={1}){{", first ? "if" : "else if", 0);
Write(file, "o=new {0}();", FullName(t));
Write(file, "pushValue(l,true);");
Write(file, "pushObject(l,o);");
Write(file, "return 2;");
Write(file, "}");
}
Write(file, "return error(l,\"New object failed.\");");
WriteCatchExecption(file);
Write(file, "}");
}
}
else if (t.IsValueType) // default constructor
{
WriteFunctionAttr(file);
Write(file, "static public int constructor(IntPtr l) {");
WriteTry(file);
Write(file, "{0} o;", FullName(t));
Write(file, "o=new {0}();", FullName(t));
WriteReturn(file,"o");
WriteCatchExecption(file);
Write(file, "}");
}
}
void WriteOk(StreamWriter file)
{
Write(file, "pushValue(l,true);");
}
void WriteBad(StreamWriter file)
{
Write(file, "pushValue(l,false);");
}
void WriteError(StreamWriter file, string err)
{
WriteBad(file);
Write(file, "LuaDLL.lua_pushstring(l,\"{0}\");",err);
Write(file, "return 2;");
}
void WriteReturn(StreamWriter file, string val)
{
Write(file, "pushValue(l,true);");
Write(file, "pushValue(l,{0});",val);
Write(file, "return 2;");
}
bool IsNotSupport(Type t)
{
if (t.IsSubclassOf(typeof(Delegate)))
return true;
return false;
}
string[] prefix = new string[] { "System.Collections.Generic" };
string RemoveRef(string s, bool removearray = true)
{
if (s.EndsWith("&")) s = s.Substring(0, s.Length - 1);
if (s.EndsWith("[]") && removearray) s = s.Substring(0, s.Length - 2);
if (s.StartsWith(prefix[0])) s = s.Substring(prefix[0].Length + 1, s.Length - prefix[0].Length - 1);
s = s.Replace("+", ".");
if (s.Contains("`"))
{
string regstr = @"`\d";
Regex r = new Regex(regstr, RegexOptions.None);
s = r.Replace(s, "");
s = s.Replace("[", "<");
s = s.Replace("]", ">");
}
return s;
}
string GenericBaseName(Type t)
{
string n = t.FullName;
if (n.IndexOf('[') > 0)
{
n = n.Substring(0, n.IndexOf('['));
}
return n.Replace("+", ".");
}
string GenericName(Type t,string sep="_")
{
try
{
Type[] tt = t.GetGenericArguments();
string ret = "";
for (int n = 0; n < tt.Length; n++)
{
string dt = SimpleType(tt[n]);
ret += dt;
if (n < tt.Length - 1)
ret += sep;
}
return ret;
}
catch (Exception e)
{
Debug.Log(e.ToString());
return "";
}
}
string _Name(string n)
{
string ret = "";
for (int i = 0; i < n.Length; i++)
{
if (char.IsLetterOrDigit(n[i]))
ret += n[i];
else
ret += "_";
}
return ret;
}
string TypeDecl(ParameterInfo[] pars,int paraOffset = 0)
{
string ret = "";
for (int n = paraOffset; n < pars.Length; n++)
{
ret += ",typeof(";
if (pars[n].IsOut)
ret += "LuaOut";
else
ret += SimpleType(pars[n].ParameterType);
ret += ")";
}
return ret;
}
// fill Generic Parameters if needed
string MethodDecl(MethodInfo m)
{
if (m.IsGenericMethod)
{
string parameters = "";
bool first = true;
foreach (Type genericType in m.GetGenericArguments())
{
if (first)
first = false;
else
parameters += ",";
parameters += genericType.ToString();
}
return string.Format("{0}<{1}>", m.Name, parameters);
}
else
return m.Name;
}
// try filling generic parameters
static MethodInfo tryFixGenericMethod(MethodInfo method)
{
if (!method.ContainsGenericParameters)
return method;
try
{
Type[] genericTypes = method.GetGenericArguments();
for (int j = 0; j < genericTypes.Length; j++)
{
Type[] contraints = genericTypes[j].GetGenericParameterConstraints();
if (contraints != null && contraints.Length == 1 && contraints[0] != typeof(ValueType))
genericTypes[j] = contraints[0];
else
return method;
}
// only fixed here
return method.MakeGenericMethod(genericTypes);
}
catch (Exception e)
{
Debug.LogError(e);
}
return method;
}
bool isUsefullMethod(MethodInfo method)
{
if (method.Name != "GetType" && method.Name != "GetHashCode" && method.Name != "Equals" &&
method.Name != "ToString" && method.Name != "Clone" &&
method.Name != "GetEnumerator" && method.Name != "CopyTo" &&
method.Name != "op_Implicit" && method.Name != "op_Explicit" &&
!method.Name.StartsWith("get_", StringComparison.Ordinal) &&
!method.Name.StartsWith("set_", StringComparison.Ordinal) &&
!method.Name.StartsWith("add_", StringComparison.Ordinal) &&
!IsObsolete(method) && !method.ContainsGenericParameters &&
method.ToString() != "Int32 Clamp(Int32, Int32, Int32)" &&
!method.Name.StartsWith("remove_", StringComparison.Ordinal))
{
return true;
}
return false;
}
void WriteFunctionDec(StreamWriter file, string name)
{
WriteFunctionAttr(file);
Write(file, "static public int {0}(IntPtr l) {{", name);
}
MethodBase[] GetMethods(Type t, string name, BindingFlags bf)
{
List<MethodBase> methods = new List<MethodBase>();
if(this.includeExtension && ((bf&BindingFlags.Instance) == BindingFlags.Instance)){
if(extensionMethods.ContainsKey(t)){
foreach(MethodInfo m in extensionMethods[t]){
if(m.Name == name
&& !IsObsolete(m)
&& !DontExport(m)
&& isUsefullMethod(m)){
methods.Add(m);
}
}
}
}
MemberInfo[] cons = t.GetMember(name, bf);
foreach (MemberInfo _m in cons)
{
MemberInfo m = _m;
if (m.MemberType == MemberTypes.Method) m = tryFixGenericMethod((MethodInfo)m);
if (m.MemberType == MemberTypes.Method
&& !IsObsolete(m)
&& !DontExport(m)
&& isUsefullMethod((MethodInfo)m))
methods.Add((MethodBase)m);
}
methods.Sort((a, b) =>
{
return a.GetParameters().Length - b.GetParameters().Length;
});
return methods.ToArray();
}
void WriteNotMatch(StreamWriter file,string fn) {
WriteError(file, string.Format("No matched override function {0} to call",fn));
}
void WriteFunctionImpl(StreamWriter file, MethodInfo m, Type t, BindingFlags bf)
{
WriteTry(file);
MethodBase[] cons = GetMethods(t, m.Name, bf);
Dictionary<string,MethodInfo> overridedMethods = null;
if (cons.Length == 1) // no override function
{
if (isUsefullMethod(m) && !m.ReturnType.ContainsGenericParameters && !m.ContainsGenericParameters) // don't support generic method
WriteFunctionCall(m, file, t,bf);
else
{
WriteNotMatch (file, m.Name);
}
}
else // 2 or more override function
{
Write(file, "int argc = LuaDLL.lua_gettop(l);");
bool first = true;
for (int n = 0; n < cons.Length; n++)
{
if (cons[n].MemberType == MemberTypes.Method)
{
MethodInfo mi = cons[n] as MethodInfo;
if (mi.IsDefined (typeof(LuaOverrideAttribute), false)) {
if (overridedMethods == null)
overridedMethods = new Dictionary<string,MethodInfo> ();
LuaOverrideAttribute attr = mi.GetCustomAttributes (typeof(LuaOverrideAttribute), false)[0] as LuaOverrideAttribute;
string fn = attr.fn;
if(overridedMethods.ContainsKey(fn))
throw new Exception(string.Format("Found function with same name {0}",fn));
overridedMethods.Add (fn,mi);
continue;
}
ParameterInfo[] pars = mi.GetParameters();
if (isUsefullMethod(mi)
&& !mi.ReturnType.ContainsGenericParameters
/*&& !ContainGeneric(pars)*/) // don't support generic method
{
bool isExtension = IsExtensionMethod(mi) && (bf & BindingFlags.Instance) == BindingFlags.Instance;
if (isUniqueArgsCount(cons, mi))
Write(file, "{0}(argc=={1}){{", first ? "if" : "else if", mi.IsStatic ? mi.GetParameters().Length : mi.GetParameters().Length + 1);
else
Write(file, "{0}(matchType(l,argc,{1}{2})){{", first ? "if" : "else if", mi.IsStatic&&!isExtension ? 1 : 2, TypeDecl(pars,isExtension?1:0));
WriteFunctionCall(mi, file, t,bf);
Write(file, "}");
first = false;
}
}
}
WriteNotMatch (file, m.Name);
}
WriteCatchExecption(file);
Write(file, "}");
WriteOverridedMethod (file,overridedMethods,t,bf);
}
void WriteOverridedMethod(StreamWriter file,Dictionary<string,MethodInfo> methods,Type t,BindingFlags bf) {
if (methods == null)
return;
foreach (var pair in methods) {
string fn = pair.Value.IsStatic ? staticName (pair.Key) : pair.Key;
WriteSimpleFunction (file,fn,pair.Value,t,bf);
funcname.Add(fn);
}
}
void WriteSimpleFunction(StreamWriter file,string fn,MethodInfo mi,Type t,BindingFlags bf) {
WriteFunctionDec(file, fn);
WriteTry(file);
WriteFunctionCall (mi, file, t, bf);
WriteCatchExecption(file);
Write(file, "}");
}
int GetMethodArgc(MethodBase mi)
{
bool isExtension = IsExtensionMethod(mi);
if (isExtension)
return mi.GetParameters().Length - 1;
return mi.GetParameters().Length;
}
bool isUniqueArgsCount(MethodBase[] cons, MethodBase mi)
{
int argcLength = GetMethodArgc(mi);
foreach (MethodBase member in cons)
{
MethodBase m = (MethodBase)member;
if (m == mi)
continue;
if (argcLength == GetMethodArgc(m))
return false;
}
return true;
}
void WriteCheckSelf(StreamWriter file, Type t)
{
if (t.IsValueType)
{
Write(file, "{0} self;", TypeDecl(t));
if(IsBaseType(t))
Write(file, "checkType(l,1,out self);");
else
Write(file, "checkValueType(l,1,out self);");
}
else
Write(file, "{0} self=({0})checkSelf(l);", TypeDecl(t));
}
private void WriteFunctionCall(MethodInfo m, StreamWriter file, Type t,BindingFlags bf)
{
bool isExtension = IsExtensionMethod(m) && (bf&BindingFlags.Instance) == BindingFlags.Instance;
bool hasref = false;
ParameterInfo[] pars = m.GetParameters();
int argIndex = 1;
int parOffset = 0;
if (!m.IsStatic )
{
WriteCheckSelf(file, t);
argIndex++;
}
else if(isExtension){
WriteCheckSelf(file, t);
parOffset ++;
}
for (int n = parOffset; n < pars.Length; n++)
{
ParameterInfo p = pars[n];
string pn = p.ParameterType.Name;
if (pn.EndsWith("&"))
{
hasref = true;
}
bool hasParams = p.IsDefined(typeof(ParamArrayAttribute), false);
CheckArgument(file, p.ParameterType, n, argIndex, p.IsOut, hasParams);
}
string ret = "";
if (m.ReturnType != typeof(void))
{
ret = "var ret=";
}
if (m.IsStatic && !isExtension)
{
if (m.Name == "op_Multiply")
Write(file, "{0}a1*a2;", ret);
else if (m.Name == "op_Subtraction")
Write(file, "{0}a1-a2;", ret);
else if (m.Name == "op_Addition")
Write(file, "{0}a1+a2;", ret);
else if (m.Name == "op_Division")
Write(file, "{0}a1/a2;", ret);
else if (m.Name == "op_UnaryNegation")
Write(file, "{0}-a1;", ret);
else if (m.Name == "op_UnaryPlus")
Write(file, "{0}+a1;", ret);
else if (m.Name == "op_Equality")
Write(file, "{0}(a1==a2);", ret);
else if (m.Name == "op_Inequality")
Write(file, "{0}(a1!=a2);", ret);
else if (m.Name == "op_LessThan")
Write(file, "{0}(a1<a2);", ret);
else if (m.Name == "op_GreaterThan")
Write(file, "{0}(a2<a1);", ret);
else if (m.Name == "op_LessThanOrEqual")
Write(file, "{0}(a1<=a2);", ret);
else if (m.Name == "op_GreaterThanOrEqual")
Write(file, "{0}(a2<=a1);", ret);
else{
Write(file, "{3}{2}.{0}({1});", MethodDecl(m), FuncCall(m), TypeDecl(t), ret);
}
}
else{
Write(file, "{2}self.{0}({1});", MethodDecl(m), FuncCall(m,parOffset), ret);
}
WriteOk(file);
int retcount = 1;
if (m.ReturnType != typeof(void))
{
WritePushValue(m.ReturnType, file);
retcount = 2;
}
// push out/ref value for return value
if (hasref)
{
for (int n = 0; n < pars.Length; n++)
{
ParameterInfo p = pars[n];
if (p.ParameterType.IsByRef)
{
WritePushValue(p.ParameterType, file, string.Format("a{0}", n + 1));
retcount++;
}
}
}
if (t.IsValueType && m.ReturnType == typeof(void) && !m.IsStatic)
Write(file, "setBack(l,self);");
Write(file, "return {0};", retcount);
}
string SimpleType(Type t)
{
string tn = t.Name;
switch (tn)
{
case "Single":
return "float";
case "String":
return "string";
case "Double":
return "double";
case "Boolean":
return "bool";
case "Int32":
return "int";
case "Object":
return FullName(t);
default:
tn = TypeDecl(t);
tn = tn.Replace("System.Collections.Generic.", "");
tn = tn.Replace("System.Object", "object");
return tn;
}
}
void WritePushValue(Type t, StreamWriter file)
{
if (t.IsEnum)
Write(file, "pushEnum(l,(int)ret);");
else if (t.IsInterface && t.IsDefined(typeof(CustomLuaClassAttribute), false))
Write(file, "pushInterface(l,ret, typeof({0}));", TypeDecl(t));
else
Write(file, "pushValue(l,ret);");
}
void WritePushValue(Type t, StreamWriter file, string ret)
{
if (t.IsEnum)
Write(file, "pushEnum(l,(int){0});", ret);
else if (t.IsInterface && t.IsDefined(typeof(CustomLuaClassAttribute),false))
Write(file, "pushInterface(l,{0}, typeof({1}));", ret,TypeDecl(t));
else
Write(file, "pushValue(l,{0});", ret);
}
void Write(StreamWriter file, string fmt, params object[] args)
{
fmt = System.Text.RegularExpressions.Regex.Replace(fmt, @"\r\n?|\n|\r", NewLine);
if (fmt.StartsWith("}")) indent--;
for (int n = 0; n < indent; n++)
file.Write("\t");
if (args.Length == 0)
file.WriteLine(fmt);
else
{
string line = string.Format(fmt, args);
file.WriteLine(line);
}
if (fmt.EndsWith("{")) indent++;
}
private void CheckArgument(StreamWriter file, Type t, int n, int argstart, bool isout, bool isparams)
{
Write(file, "{0} a{1};", TypeDecl(t), n + 1);
if (!isout)
{
if (t.IsEnum)
Write(file, "checkEnum(l,{0},out a{1});", n + argstart, n + 1);
else if (t.BaseType == typeof(System.MulticastDelegate))
{
tryMake(t);
Write(file, "checkDelegate(l,{0},out a{1});", n + argstart, n + 1);
}
else if (isparams)
{
if(t.GetElementType().IsValueType && !IsBaseType(t.GetElementType()))
Write(file, "checkValueParams(l,{0},out a{1});", n + argstart, n + 1);
else
Write(file, "checkParams(l,{0},out a{1});", n + argstart, n + 1);
}
else if(t.IsArray)
Write(file, "checkArray(l,{0},out a{1});", n + argstart, n + 1);
else if (IsValueType(t)) {
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
Write(file, "checkNullable(l,{0},out a{1});", n + argstart, n + 1);
else
Write(file, "checkValueType(l,{0},out a{1});", n + argstart, n + 1);
}
else
Write(file, "checkType(l,{0},out a{1});", n + argstart, n + 1);
}
}
bool IsValueType(Type t)
{
return t.BaseType == typeof(ValueType) && !IsBaseType(t);
}
bool IsBaseType(Type t)
{
if (t.IsByRef) {
t = t.GetElementType();
}
return t.IsPrimitive || LuaObject.isImplByLua(t);
}
string FullName(string str)
{
if (str == null)
{
throw new NullReferenceException();
}
return RemoveRef(str.Replace("+", "."));
}
string TypeDecl(Type t)
{
if (t.IsGenericType)
{
string ret = GenericBaseName(t);
string gs = "";
gs += "<";
Type[] types = t.GetGenericArguments();
for (int n = 0; n < types.Length; n++)
{
gs += TypeDecl(types[n]);
if (n < types.Length - 1)
gs += ",";
}
gs += ">";
ret = Regex.Replace(ret, @"`\d", gs);
return ret;
}
if (t.IsArray)
{
return TypeDecl(t.GetElementType()) + "[]";
}
else
return RemoveRef(t.ToString(), false);
}
string ExportName(Type t)
{
if (t.IsGenericType)
{
return string.Format("Lua_{0}_{1}", _Name(GenericBaseName(t)), _Name(GenericName(t)));
}
else
{
string name = RemoveRef(t.FullName, true);
name = "Lua_" + name;
return name.Replace(".", "_");
}
}
string FullName(Type t)
{
if (t.FullName == null)
{
Debug.Log(t.Name);
return t.Name;
}
return FullName(t.FullName);
}
string FuncCall(MethodBase m,int parOffset = 0)
{
string str = "";
ParameterInfo[] pars = m.GetParameters();
for (int n = parOffset; n < pars.Length; n++)
{
ParameterInfo p = pars[n];
if (p.ParameterType.IsByRef && p.IsOut)
str += string.Format("out a{0}", n + 1);
else if (p.ParameterType.IsByRef)
str += string.Format("ref a{0}", n + 1);
else
str += string.Format("a{0}", n + 1);
if (n < pars.Length - 1)
str += ",";
}
return str;
}
}
}
| 29.853584 | 778 | 0.555426 | [
"Apache-2.0"
] | lahmmiley/RhythmMaster | Unity/Assets/Slua/Editor/LuaCodeGen.cs | 77,888 | C# |
using System;
using TODOFilePickerSample.ViewModels;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
namespace TODOFilePickerSample.Views
{
public sealed partial class ToDoEditorContentDialog : ContentDialog
{
public ToDoEditorContentDialog()
{
this.InitializeComponent();
}
protected override void OnGotFocus(RoutedEventArgs e)
{
// NOte, in DP7 (BUILD tools drop), CameraCaptureUI is only in the Desktop extension SDK.
// At RTM, it is planned to be in Mobile extension SDK as well
if (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Media.Capture.CameraCaptureUI"))
{
TakePictureButton.Visibility = Visibility.Collapsed;
}
base.OnGotFocus(e);
}
public event EventHandler<TodoItemViewModel> DeleteTodoItemClicked;
private void DeleteItemClicked(ContentDialog sender, ContentDialogButtonClickEventArgs args)
{
if (DeleteTodoItemClicked != null)
{
DeleteTodoItemClicked(this, (TodoItemViewModel)this.DataContext);
}
}
}
}
| 33.205128 | 115 | 0.657143 | [
"MIT"
] | HydAu/WebDevCamp | Presentation/z102. File Management/Demos/TODOFilePickerSample/TODOFilePickerSample/Views/ToDoEditorContentDialog.xaml.cs | 1,297 | C# |
using System;
using System.IO;
using System.Linq;
namespace AdventOfCode2019.Solutions.Shared
{
internal class IntcodeComputer
{
private int relativeBase = 0;
private int ip = 0;
public IntcodeComputer(long[] memory)
{
// Extend program memory
this.Memory = memory.Concat(new long[1000]).ToArray();
}
public long[] Memory { get; }
public static IntcodeComputer LoadProgramFromString(string input)
{
var program = input.Split(',').Select(long.Parse).ToArray();
return new IntcodeComputer(program);
}
public static IntcodeComputer LoadProgramFromFile(string file)
{
var fileContent = File.ReadAllText(file);
return LoadProgramFromString(fileContent);
}
public void EvaluateProgram(Func<long> getInput = null, Action<long> writeOutput = null)
{
while (true)
{
switch (this.FetchOpcode())
{
case Opcode.Add:
this.Write(3, this.Read(1) + this.Read(2));
this.ip += 4;
break;
case Opcode.Multiply:
this.Write(3, this.Read(1) * this.Read(2));
this.ip += 4;
break;
case Opcode.Input:
this.Write(1, getInput());
this.ip += 2;
break;
case Opcode.Output:
writeOutput(this.Read(1));
this.ip += 2;
break;
case Opcode.JumpIfTrue:
this.ip = this.Read(1) != 0 ? (int)this.Read(2) : this.ip + 3;
break;
case Opcode.JumpIfFalse:
this.ip = this.Read(1) == 0 ? (int)this.Read(2) : this.ip + 3;
break;
case Opcode.LessThan:
this.Write(3, this.Read(1) < this.Read(2) ? 1 : 0);
this.ip += 4;
break;
case Opcode.Equals:
this.Write(3, this.Read(1) == this.Read(2) ? 1 : 0);
this.ip += 4;
break;
case Opcode.AdjustRelativeBase:
this.relativeBase += (int)this.Read(1);
this.ip += 2;
break;
case Opcode.Halt:
return;
}
}
}
private Opcode FetchOpcode() => (Opcode)(this.Memory[this.ip] % 100);
private long Read(int position) => this.Memory[this.GetIndex(position)];
private void Write(int position, long value) => this.Memory[this.GetIndex(position)] = value;
private int GetIndex(int position)
{
var mode = this.GetParameterMode(position);
var index = this.Memory[this.ip + position];
if (mode == 1)
{
index = this.ip + position;
}
else if (mode == 2)
{
index = this.relativeBase + this.Memory[this.ip + position];
}
return (int)index;
}
private int GetParameterMode(int position)
{
var mode = (int)this.Memory[this.ip] / 100;
for (var i = 1; i < position; i++)
mode /= 10;
return mode % 10;
}
private enum Opcode
{
Add = 1,
Multiply = 2,
Input = 3,
Output = 4,
JumpIfTrue = 5,
JumpIfFalse = 6,
LessThan = 7,
Equals = 8,
AdjustRelativeBase = 9,
Halt = 99
}
}
}
| 32.768595 | 101 | 0.433544 | [
"MIT"
] | Speiser/AdventOfCode | 2019/Solutions/Shared/IntcodeComputer.cs | 3,967 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
namespace Lab1Lib.Tests
{
[TestFixture, Description("Покрытие тестами класса квадрата")]
class RectangleTests
{
Rectangle rectangle;
[OneTimeSetUp]
public void Init()
{
rectangle = new Rectangle();
}
[Description("Заданы координаты точек, что не образуют прямоугольника ArgumentException")]
[TestCase(new double[] { -10, -10, 0, 0 }, new double[] { 5, 1, 1, 1 })]
[TestCase(new double[] { -10, 0, 0, 0 }, new double[] { 5, 2, 1, 1 })]
[TestCase(new double[] { 0, 0, 0, 0 }, new double[] { 0, 0, 0, 0 })]
public void SetVertices_NotCorrectRectangle_ArgumentException(double[] x, double[] y)
{
Assert.Throws<ArgumentException>(
() => rectangle.SetVertices(x,y));
}
[Description("Конструктор класса использует метод SetNegative, при отрицательном числе должна вылетать ArgumentException")]
[TestCase(new double[] { -10, -10, 0, 0 }, new double[] { 5, 1, 1, 1 })]
[TestCase(new double[] { -10, 0, 0, 0 }, new double[] { 5, 2, 1, 1 })]
[TestCase(new double[] { 0, 0, 0, 0 }, new double[] { 0, 0, 0, 0})]
public void RectangleConstructor_NotCorrectRectangle_ArgumentException(double[] x, double[] y)
{
Assert.Throws<ArgumentException>(
() => rectangle = new Rectangle(x,y));
}
[Description("Задан существующий прямоугольник, не должно происходить ошибок")]
[TestCase(new double[] { 0, 10, 10, 0 }, new double[] { 0, 0, -10, -10 })]
[TestCase(new double[] { -10, -10, 0, 0 }, new double[] { 5, 1, 1, 5 })]
public void SetVertices_CorrectRectangle_DoesNotThrow(double[] x, double[] y)
{
Assert.DoesNotThrow(() => rectangle.SetVertices(x,y));
}
[Description("На вход идут вершины прямоугольника, а на выход диагональ с погрешностью в 0.001")]
[TestCase(new double[] { 0, 10, 10, 0 }, new double[] { 0, 0, -10, -10 },14.142)]
[TestCase(new double[] { -10, -10, 0, 0 }, new double[] { 5, 1, 1, 5 },10.770)]
public void Diagonal_SetRectangle_DiagonalResulted(double[] x, double[] y,double res)
{
rectangle.SetVertices(x, y);
Assert.AreEqual(rectangle.Diagonal(), res,0.001);
}
}
}
| 41.982759 | 131 | 0.58193 | [
"MIT"
] | GnomGad/NunitTesting | Lab1Lib.Tests/RectangleTests.cs | 2,698 | C# |
#pragma checksum "C:\Users\kobe9\source\repos\Xaml-Controls-Gallery\XamlControlsGallery\ControlPages\TextBoxPage.xaml" "{8829d00f-11b8-4213-878b-770e8597ac16}" "0BB3B989A5DDD6A6CA8A11FCB51EE426FC0C040BFA73D1D5EEE2289839159077"
//------------------------------------------------------------------------------
// <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 AppUIBasics.ControlPages
{
partial class TextBoxPage :
global::Microsoft.UI.Xaml.Controls.Page,
global::Microsoft.UI.Xaml.Markup.IComponentConnector
{
/// <summary>
/// GetWeakRefTarget()
/// </summary>
private static T GetWeakRefTarget<T>(global::System.WeakReference<T> weakRef) where T : class
{
if (weakRef.TryGetTarget(out T weakRefValue))
{
return weakRefValue;
}
else
{
return null;
}
}
/// <summary>
/// Connect()
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.UI.Xaml.Markup.Compiler"," 0.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void Connect(int connectionId, object target)
{
switch(connectionId)
{
case 2: // ControlPages\TextBoxPage.xaml line 17
{
this.Example1 = (AppUIBasics.ControlExample)target;
}
break;
case 3: // ControlPages\TextBoxPage.xaml line 25
{
this.Example2 = (AppUIBasics.ControlExample)target;
}
break;
case 4: // ControlPages\TextBoxPage.xaml line 35
{
this.Example3 = (AppUIBasics.ControlExample)target;
}
break;
case 5: // ControlPages\TextBoxPage.xaml line 48
{
this.Example4 = (AppUIBasics.ControlExample)target;
}
break;
default:
break;
}
this._contentLoaded = true;
}
/// <summary>
/// GetBindingConnector(int connectionId, object target)
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.UI.Xaml.Markup.Compiler"," 0.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public global::Microsoft.UI.Xaml.Markup.IComponentConnector GetBindingConnector(int connectionId, object target)
{
global::Microsoft.UI.Xaml.Markup.IComponentConnector returnValue = null;
return returnValue;
}
}
}
| 37.125 | 227 | 0.538047 | [
"MIT"
] | kobe9936/WinUI_UWP | XamlControlsGallery/obj/XamlControlsGallery/x64/Release/ControlPages/TextBoxPage.g.cs | 2,972 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace AvePoint.Migration.Samples
{
/// <summary>
/// Delete a migration job
/// </summary>
class DeletePSTFileJob : AbstractApplication
{
/// <summary>
/// <see cref="GetPSTFileJob"/>
/// <see cref="FindPSTFileJobByPlan"/>
/// </summary>
private readonly string id = "<job id>";
static void Main(string[] args)
{
new DeletePSTFileJob().RunAsync().Wait();
}
/// <returns>
/// <see cref="AvePoint.Migration.Api.Models.StatusResultModel"/>
/// </returns>
protected override async Task<string> RunAsync(HttpClient client)
{
var response = await client.DeleteAsync($"/api/pstfiles/plans/{id}");
return await response.Content.ReadAsStringAsync();
}
}
}
| 26.135135 | 81 | 0.596691 | [
"MIT"
] | AvePoint/FLY-Migration | WebAPI/CSharp/FLY 4.5/FLY/PSTFile/DeletePSTFileJob.cs | 969 | C# |
using CnGalWebSite.APIServer.Application.WeiXin;
using Microsoft.Extensions.DependencyInjection;
using Senparc.NeuChar.Entities;
using Senparc.Weixin.MP.Entities;
using System.Threading.Tasks;
namespace CnGalWebSite.APIServer.MessageHandlers
{
/// <summary>
/// 自定义MessageHandler
/// </summary>
public partial class CustomMessageHandler
{
public override async Task<IResponseMessageBase> OnTextOrEventRequestAsync(RequestMessageText requestMessage)
{
// 预处理文字或事件类型请求。
// 这个请求是一个比较特殊的请求,通常用于统一处理来自文字或菜单按钮的同一个执行逻辑,
// 会在执行OnTextRequest或OnEventRequest之前触发,具有以下一些特征:
// 1、如果返回null,则继续执行OnTextRequest或OnEventRequest
// 2、如果返回不为null,则终止执行OnTextRequest或OnEventRequest,返回最终ResponseMessage
// 3、如果是事件,则会将RequestMessageEvent自动转为RequestMessageText类型,其中RequestMessageText.Content就是RequestMessageEvent.EventKey
if (requestMessage.Content == "OneClick")
{
var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
strongResponseMessage.Content = "您点击了底部按钮。\r\n为了测试微信软件换行bug的应对措施,这里做了一个——\r\n换行";
return strongResponseMessage;
}
return null;//返回null,则继续执行OnTextRequest或OnEventRequest
}
/// <summary>
/// 点击事件
/// </summary>
/// <param name="requestMessage">请求消息</param>
/// <returns></returns>
public override async Task<IResponseMessageBase> OnEvent_ClickRequestAsync(RequestMessageEvent_Click requestMessage)
{
var reponseMessage = CreateResponseMessage<ResponseMessageText>();
using var scope = ServiceProvider.CreateScope();
var _weiXinService = scope.ServiceProvider.GetRequiredService<IWeiXinService>();
if (requestMessage.EventKey == "Click_Random")
{
reponseMessage.Content = await _weiXinService.GetRandom();
}
else if (requestMessage.EventKey == "Click_Newest_News")
{
reponseMessage.Content = await _weiXinService.GetNewestNews();
}
else if (requestMessage.EventKey == "Click_Newest_PubishGame")
{
reponseMessage.Content = await _weiXinService.GetNewestPublishGames();
}
else if (requestMessage.EventKey == "Click_Newest_UnPublishGame")
{
reponseMessage.Content = await _weiXinService.GetNewestUnPublishGames();
}
else if (requestMessage.EventKey == "Click_Newest_EditGame")
{
reponseMessage.Content = await _weiXinService.GetNewestEditGames();
}
else if (requestMessage.EventKey == "Click_About_Usage")
{
reponseMessage.Content = _weiXinService.GetAboutUsage();
}
return reponseMessage;
}
/// <summary>
/// 进入事件
/// </summary>
/// <param name="requestMessage"></param>
/// <returns></returns>
public override async Task<IResponseMessageBase> OnEvent_EnterRequestAsync(RequestMessageEvent_Enter requestMessage)
{
var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage);
responseMessage.Content = "您刚才发送了ENTER事件请求。";
return responseMessage;
}
/// <summary>
/// 位置事件
/// </summary>
/// <param name="requestMessage"></param>
/// <returns></returns>
public override async Task<IResponseMessageBase> OnEvent_LocationRequestAsync(RequestMessageEvent_Location requestMessage)
{
//这里是微信客户端(通过微信服务器)自动发送过来的位置信息
var responseMessage = CreateResponseMessage<ResponseMessageText>();
responseMessage.Content = "这里写什么都无所谓,比如:上帝爱你!";
return responseMessage;//这里也可以返回null(需要注意写日志时候null的问题)
}
/// <summary>
/// 通过二维码扫描关注扫描事件
/// </summary>
/// <param name="requestMessage"></param>
/// <returns></returns>
public override async Task<IResponseMessageBase> OnEvent_ScanRequestAsync(RequestMessageEvent_Scan requestMessage)
{
//通过扫描关注
var responseMessage = CreateResponseMessage<ResponseMessageText>();
responseMessage.Content = responseMessage.Content ?? string.Format("通过扫描二维码进入,场景值:{0}", requestMessage.EventKey);
return responseMessage;
}
/// <summary>
/// 打开网页事件
/// </summary>
/// <param name="requestMessage"></param>
/// <returns></returns>
public override async Task<IResponseMessageBase> OnEvent_ViewRequestAsync(RequestMessageEvent_View requestMessage)
{
//说明:这条消息只作为接收,下面的responseMessage到达不了客户端,类似OnEvent_UnsubscribeRequest
var responseMessage = CreateResponseMessage<ResponseMessageText>();
responseMessage.Content = "您点击了view按钮,将打开网页:" + requestMessage.EventKey;
return responseMessage;
}
/// <summary>
/// 群发完成事件
/// </summary>
/// <param name="requestMessage"></param>
/// <returns></returns>
public override async Task<IResponseMessageBase> OnEvent_MassSendJobFinishRequestAsync(RequestMessageEvent_MassSendJobFinish requestMessage)
{
var responseMessage = CreateResponseMessage<ResponseMessageText>();
responseMessage.Content = "接收到了群发完成的信息。";
return responseMessage;
}
/// <summary>
/// 订阅(关注)事件
/// </summary>
/// <returns></returns>
public override async Task<IResponseMessageBase> OnEvent_SubscribeRequestAsync(RequestMessageEvent_Subscribe requestMessage)
{
var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage);
responseMessage.Content = GetWelcomeInfo();
if (!string.IsNullOrEmpty(requestMessage.EventKey))
{
responseMessage.Content += "\r\n============\r\n场景值:" + requestMessage.EventKey;
}
return responseMessage;
}
private string GetWelcomeInfo()
{
return "CnGal资料站( cngal.org ) 官方频道。一个非营利性的,立志于收集整理 CnGal 资料的网站";
}
/// <summary>
/// 退订
/// 实际上用户无法收到非订阅账号的消息,所以这里可以随便写。
/// unsubscribe事件的意义在于及时删除网站应用中已经记录的OpenID绑定,消除冗余数据。并且关注用户流失的情况。
/// </summary>
/// <returns></returns>
public override async Task<IResponseMessageBase> OnEvent_UnsubscribeRequestAsync(RequestMessageEvent_Unsubscribe requestMessage)
{
var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
responseMessage.Content = "有空再来";
return responseMessage;
}
/// <summary>
/// 事件之扫码推事件(scancode_push)
/// </summary>
/// <param name="requestMessage"></param>
/// <returns></returns>
public override async Task<IResponseMessageBase> OnEvent_ScancodePushRequestAsync(RequestMessageEvent_Scancode_Push requestMessage)
{
var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
responseMessage.Content = "事件之扫码推事件";
return responseMessage;
}
/// <summary>
/// 事件之扫码推事件且弹出“消息接收中”提示框(scancode_waitmsg)
/// </summary>
/// <param name="requestMessage"></param>
/// <returns></returns>
public override async Task<IResponseMessageBase> OnEvent_ScancodeWaitmsgRequestAsync(RequestMessageEvent_Scancode_Waitmsg requestMessage)
{
var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
responseMessage.Content = "事件之扫码推事件且弹出“消息接收中”提示框";
return responseMessage;
}
/// <summary>
/// 事件之弹出拍照或者相册发图(pic_photo_or_album)
/// </summary>
/// <param name="requestMessage"></param>
/// <returns></returns>
public override async Task<IResponseMessageBase> OnEvent_PicPhotoOrAlbumRequestAsync(RequestMessageEvent_Pic_Photo_Or_Album requestMessage)
{
var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
responseMessage.Content = "事件之弹出拍照或者相册发图";
return responseMessage;
}
/// <summary>
/// 事件之弹出系统拍照发图(pic_sysphoto)
/// 实际测试时发现微信并没有推送RequestMessageEvent_Pic_Sysphoto消息,只能接收到用户在微信中发送的图片消息。
/// </summary>
/// <param name="requestMessage"></param>
/// <returns></returns>
public override async Task<IResponseMessageBase> OnEvent_PicSysphotoRequestAsync(RequestMessageEvent_Pic_Sysphoto requestMessage)
{
var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
responseMessage.Content = "事件之弹出系统拍照发图";
return responseMessage;
}
/// <summary>
/// 事件之弹出微信相册发图器(pic_weixin)
/// </summary>
/// <param name="requestMessage"></param>
/// <returns></returns>
public override async Task<IResponseMessageBase> OnEvent_PicWeixinRequestAsync(RequestMessageEvent_Pic_Weixin requestMessage)
{
var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
responseMessage.Content = "事件之弹出微信相册发图器";
return responseMessage;
}
/// <summary>
/// 事件之弹出地理位置选择器(location_select)
/// </summary>
/// <param name="requestMessage"></param>
/// <returns></returns>
public override async Task<IResponseMessageBase> OnEvent_LocationSelectRequestAsync(RequestMessageEvent_Location_Select requestMessage)
{
var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
responseMessage.Content = "事件之弹出地理位置选择器";
return responseMessage;
}
#region 微信认证事件推送
public override async Task<IResponseMessageBase> OnEvent_QualificationVerifySuccessRequestAsync(RequestMessageEvent_QualificationVerifySuccess requestMessage)
{
//以下方法可以强制定义返回的字符串值
//TextResponseMessage = "your content";
//return null;
return new SuccessResponseMessage();//返回"success"字符串
}
#endregion
}
}
| 40.303846 | 166 | 0.636511 | [
"MIT"
] | LittleFish-233/CnGalWebSite | CnGalWebSite/CnGalWebSite.APIServer/MessageHandlers/CustomMessageHandler_Events.cs | 11,887 | C# |
using System;
namespace RootInsurance.SDK
{
public class ApiManager : Interfaces.IApiManager
{
#region Static Properties
internal static Configuration.Config Config { get; set; }
internal static WebExtensions.WebHelper WebHelper { get; set; }
#endregion
#region Fields
private RootModules.Quote _quote;
private RootModules.PolicyHolder _policyHolder;
#endregion
#region Properties
public RootModules.Quote Quote
{
get
{
if (this._quote == null)
this._quote = new RootModules.Quote();
return this._quote;
}
}
public RootModules.PolicyHolder PolicyHolder
{
get
{
if (this._policyHolder == null)
this._policyHolder = new RootModules.PolicyHolder();
return this._policyHolder;
}
}
#endregion
#region ctor
public ApiManager(Configuration.Config config)
{
if (config == null)
throw new ArgumentNullException("Configuration parameter cannot be null");
ApiManager.Config = config;
ApiManager.WebHelper = new WebExtensions.WebHelper(config);
}
#endregion
}
}
| 26.269231 | 90 | 0.551977 | [
"MIT"
] | TrevorMare/Root_Insurance_Core | RootInsurance/RootInsurance.SDK/ApiManager.cs | 1,368 | C# |
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Bya.BackgroundTasks
{
/// <inheritdoc cref="FactoryHostedService"/>
/// <summary>
/// Implementación de un servicio en segundo plano con capacidad para ejecutar servicio en scoped
/// </summary>
public abstract class ScopedHostedService : FactoryHostedService
{
private readonly IServiceScopeFactory _serviceScopeFactory;
protected ScopedHostedService(IServiceScopeFactory serviceScopeFactory, ILogger<ScopedHostedService> logger, TimeSpan delayBetweenProcess)
: base(logger, delayBetweenProcess)
{
_serviceScopeFactory = serviceScopeFactory;
}
protected override async Task Process(CancellationToken stoppingToken)
{
// Crea una petición scope y ejecuta la tarea, al finalizar, cierra la conexión
using (var scope = _serviceScopeFactory.CreateScope())
{
await ProcessInScope(scope.ServiceProvider, stoppingToken);
}
}
/// <summary>
/// Tarea a implementar en las clases que hereden de esta
/// </summary>
/// <param name="serviceProvider">The service provider.</param>
/// <param name="stoppingToken">The stopping token.</param>
/// <returns></returns>
public abstract Task ProcessInScope(IServiceProvider serviceProvider, CancellationToken stoppingToken);
}
}
| 37.97561 | 146 | 0.685934 | [
"MIT"
] | alca259/Bya-Extensions | src/Bya.BackgroundTasks/ScopedHostedService.cs | 1,562 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using AirProperties.Controls;
using PluginCore.Localization;
namespace AirProperties.Forms
{
public partial class IOSDeviceManager : Form
{
private readonly DeviceClassification[] iOSDevices;
private string _selectedDevices;
public string SelectedDevices { get { return _selectedDevices; } }
public IOSDeviceManager(string[] selectedDevices)
{
InitializeComponent();
this.OKButton.Text = TextHelper.GetString("Label.Ok");
this.CancelButton1.Text = TextHelper.GetString("Label.Cancel");
this.Text = TextHelper.GetString("Title.SelectIOSDevices");
var iPadDevices = new DeviceClassification("iPad", "iPad", new[]
{
new DeviceClassification("iPad", "iPad1", null),
new DeviceClassification("iPad 2/Mini", "iPad2", new[]
{
new DeviceClassification("iPad 2 (WiFi)", "iPad2,1", null),
new DeviceClassification("iPad 2 (GSM)", "iPad2,2", null),
new DeviceClassification("iPad 2 (CDMA)", "iPad2,3", null),
new DeviceClassification("iPad 2 (WiFi Rev A)", "iPad2,4", null),
new DeviceClassification("iPad Mini (WiFi)", "iPad2,5", null),
new DeviceClassification("iPad Mini (GSM)", "iPad2,6", null),
new DeviceClassification("iPad Mini (GSM+CDMA)", "iPad2,7", null)
}),
new DeviceClassification("iPad 3/4", "iPad3", new[]
{
new DeviceClassification("iPad 3 (WiFi)", "iPad3,1", null),
new DeviceClassification("iPad 3 (GSM+CDMA)", "iPad3,2", null),
new DeviceClassification("iPad 3 (GSM)", "iPad3,3", null),
new DeviceClassification("iPad 4 (WiFi)", "iPad3,4", null),
new DeviceClassification("iPad 4 (GSM)", "iPad3,5", null),
new DeviceClassification("iPad 4 (GSM+CDMA)", "iPad3,6", null)
}),
new DeviceClassification("iPad Air/Mini Retina", "iPad4", new[]
{
new DeviceClassification("iPad Air (WiFi)", "iPa43,1", null),
new DeviceClassification("iPad Air (Cellular)", "iPad4,2", null),
new DeviceClassification("iPad Mini 2G (WiFi)", "iPad4,4", null),
new DeviceClassification("iPad Mini 2G (Cellular)", "iPad4,5", null)
})
});
var iPodDevices = new DeviceClassification("iPod", "iPod", new[]
{
new DeviceClassification("iPod Touch 4th Generation", "iPod4,1", null),
new DeviceClassification("iPod Touch 5th Generation", "iPod5,1", null)
});
var iPhoneDevices = new DeviceClassification("iPhone", "iPhone", new[]
{
new DeviceClassification("iPhone 3GS ", "iPhone2,1", null),
new DeviceClassification("iPhone 4", "iPhone3", new[]
{
new DeviceClassification("iPhone 4", "iPhone3,1", null),
new DeviceClassification("iPhone 4 (Rev A)", "iPhone3,2", null),
new DeviceClassification("iPhone 4 (CDMA)", "iPhone3,3", null)
}),
new DeviceClassification("iPhone 4S", "iPhone4", null),
new DeviceClassification("iPhone 5/5C", "iPhone5", new[]
{
new DeviceClassification("iPhone 5 (GSM)", "iPhone5,1", null),
new DeviceClassification("iPhone 5 (GSM+CDMA)", "iPhone5,2", null),
new DeviceClassification("iPhone 5C (GSM)", "iPhone5,3", null),
new DeviceClassification("iPhone 5C (GSM+CDMA)", "iPhone5,4", null)
}),
new DeviceClassification("iPhone 5S", "iPhone6", new[]
{
new DeviceClassification("iPhone 5s (GSM)", "iPhone6,1", null),
new DeviceClassification("iPhone 5s (GSM+CDMA)", "iPhone6,2", null),
})
});
iOSDevices = new[] { iPadDevices, iPhoneDevices, iPodDevices };
IOSDevicesTree.BeginUpdate();
FillTree(iOSDevices, selectedDevices, null);
IOSDevicesTree.EndUpdate();
}
private void FillTree(DeviceClassification[] devices, string[] selected, TreeNode parent)
{
var selectedNodes = new List<TreeNode>(devices.Length);
foreach (var device in devices)
{
TreeNode newNode;
if (parent != null)
{
newNode = parent.Nodes.Add(device.HardwareId, device.Name);
}
else
{
newNode = IOSDevicesTree.Nodes.Add(device.HardwareId, device.Name);
}
// Since we're still populating the tree, we cannot check here.
// We could make SelectedNodes a read/write property, and find the nodes by key after in the setter, but it just came out this way
if (selected != null && Array.IndexOf(selected, device.HardwareId) > -1) selectedNodes.Add(newNode);
if (device.SubClassifications != null && device.SubClassifications.Length > 0)
FillTree(device.SubClassifications, selected, newNode);
}
foreach (var node in selectedNodes) node.Checked = true;
}
private void OKButton_Click(object sender, EventArgs e)
{
StringBuilder deviceBuilder = new StringBuilder();
foreach (TreeNode child in IOSDevicesTree.Nodes)
GetSelectedDevices(child, deviceBuilder);
_selectedDevices = deviceBuilder.ToString();
}
private void GetSelectedDevices(TreeNode node, StringBuilder builder)
{
if (node.StateImageIndex == (int) TriStateTreeView.CheckedState.Checked)
{
if (builder.Length > 0) builder.Append(' ');
builder.Append(node.Name);
}
else if (node.StateImageIndex == (int) TriStateTreeView.CheckedState.Mixed)
{
foreach (TreeNode child in node.Nodes) GetSelectedDevices(child, builder);
}
}
public class DeviceClassification
{
public String Name { get; set; }
public String HardwareId { get; set; }
public DeviceClassification[] SubClassifications { get; set; }
public DeviceClassification(string name, string hardwareId, DeviceClassification[] subClassifications)
{
Name = name;
HardwareId = hardwareId;
SubClassifications = subClassifications;
}
}
}
}
| 46.691824 | 146 | 0.52438 | [
"MIT"
] | Chr0n0AP/flashdevelop | External/Plugins/AirProperties/Forms/IOSDeviceManager.cs | 7,426 | 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 ram-2018-01-04.normal.json service model.
*/
using Amazon.Runtime;
namespace Amazon.RAM.Model
{
/// <summary>
/// Paginator for the ListPermissionVersions operation
///</summary>
public interface IListPermissionVersionsPaginator
{
/// <summary>
/// Enumerable containing all full responses for the operation
/// </summary>
IPaginatedEnumerable<ListPermissionVersionsResponse> Responses { get; }
}
} | 33.272727 | 101 | 0.704918 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/RAM/Generated/Model/_bcl45+netstandard/IListPermissionVersionsPaginator.cs | 1,098 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using CatFactory.CodeFactory.Scaffolding;
using CatFactory.Diagnostics;
namespace CatFactory.EntityFrameworkCore
{
public class EntityFrameworkCoreProjectSettings : IProjectSettings
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private List<string> m_backingFields;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private List<string> m_insertExclusions;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private List<string> m_updateExclusions;
public EntityFrameworkCoreProjectSettings()
{
}
// todo: Add implementation
public ValidationResult Validate()
{
throw new NotImplementedException();
}
public bool ForceOverwrite { get; set; }
public bool SimplifyDataTypes { get; set; } = true;
public bool UseAutomaticPropertiesForEntities { get; set; } = true;
public bool EnableDataBindings { get; set; }
public bool UseDataAnnotations { get; set; }
[Obsolete("Temporarily disabled")]
public bool UseMefForEntitiesMapping { get; set; } = true;
public bool DeclareDbSetPropertiesInDbContext { get; } = true;
public bool PluralizeDbSetPropertyNames { get; set; }
public bool DeclareNavigationProperties { get; set; }
public bool DeclareNavigationPropertiesAsVirtual { get; set; }
public string NavigationPropertyEnumerableNamespace { get; set; } = "System.Collections.ObjectModel";
public string NavigationPropertyEnumerableType { get; set; } = "Collection";
public string ConcurrencyToken { get; set; }
public string EntityInterfaceName { get; set; } = "IEntity";
public AuditEntity AuditEntity { get; set; }
public bool EntitiesWithDataContracts { get; set; }
public bool AddConfigurationForForeignKeysInFluentAPI { get; set; }
public bool AddConfigurationForUniquesInFluentAPI { get; set; } = true;
public bool AddConfigurationForChecksInFluentAPI { get; set; }
public bool AddConfigurationForDefaultsInFluentAPI { get; set; } = true;
public List<string> BackingFields
{
get => m_backingFields ?? (m_backingFields = new List<string>());
set => m_backingFields = value;
}
public List<string> InsertExclusions
{
get => m_insertExclusions ?? (m_insertExclusions = new List<string>());
set => m_insertExclusions = value;
}
public List<string> UpdateExclusions
{
get => m_updateExclusions ?? (m_updateExclusions = new List<string>());
set => m_updateExclusions = value;
}
/// <summary>
/// When true the Database DefaultSchema is also used as a namespace and folder
/// </summary>
public bool DefaultSchemaAsSubdirectory { get; set; }
/// <summary>
/// Navigation Property Enumerable Interface Type
/// Typically ICollection
/// </summary>
public string NavigationPropertyEnumerableInterfaceType { get; set; }
/// <summary>
/// DefaultSchemaAsNamespace
/// default = false;
/// When true use DefaultSchema (dbo) as namespace and class
/// </summary>
public bool DefaultSchemaAsNamespace { get; set; }
}
}
| 32.166667 | 109 | 0.649108 | [
"MIT"
] | JTOne123/CatFactory.EntityFrameworkCore | CatFactory.EntityFrameworkCore/EntityFrameworkCoreProjectSettings.cs | 3,476 | C# |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
singleton TSShapeConstructor(PlayerAnim_Pistol_JumpDAE)
{
baseShape = "./PlayerAnim_Pistol_Jump.dts";
neverImport = "EnvironmentAmbientLight";
loadLights = "0";
};
function PlayerAnim_Pistol_JumpDAE::onLoad(%this)
{
%this.setSequenceCyclic("ambient", "false");
%this.addSequence("ambient", "Jump", "975", "985");
}
| 45.885714 | 79 | 0.680573 | [
"Unlicense"
] | Duion/Uebergame | art/shapes/weapons/Ryder/PlayerAnims/PlayerAnim_Pistol_Jump.cs | 1,606 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.