text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Web; namespace GameStore.WebUI.Helper { public class CreditAuthorizationClient { /* *pSecretValue - the secret key issued when you registered at the Credit Gateway *pAppId - the appid issued to you when you registered at the credit gateway *pTransId - the transaction id your system issues to identify the purchase *pTransAmount - the value you are charging for this transaction */ public static String GenerateClientRequestHash(String pSecretValue, String pAppId, String pTransId, String pTransAmount) { try { String secretPartA = pSecretValue.Substring(0, 5); String secretPartB = pSecretValue.Substring(5, 5); String val = secretPartA + "-" + pAppId + "-" + pTransId + "-" + pTransAmount + "-" + secretPartB; var pwdBytes = Encoding.UTF8.GetBytes(val); SHA256 hashAlg = new SHA256Managed(); hashAlg.Initialize(); var hashedBytes = hashAlg.ComputeHash(pwdBytes); var hash = Convert.ToBase64String(hashedBytes); return hash; } catch (Exception e) { return null; } } /* *pHash - is the Hash Returned from the Credit Service. You need to URLDecode the value before passing it in. *pSecretValue - the secret key issued when you registered at the Credit Gateway *pAppId - the appid issued to you when you registered at the credit gateway *pTransId - the transaction id your system issues to identify the purchase *pTransAmount - the value you are charging for this transaction *pAppStatus - The status of the credit transaction. Values : A = Accepted, D = Denied */ public static bool VerifyServerResponseHash(String pHash, String pSecretValue, String pAppId, String pTransId, String pTransAmount, String pAppStatus) { String secretPartA = pSecretValue.Substring(0, 5); String secretPartB = pSecretValue.Substring(5, 5); String val = secretPartA + "-" + pAppId + "-" + pTransId + "-" + pTransAmount + "-" + pAppStatus + "-" + secretPartB; var pwdBytes = Encoding.UTF8.GetBytes(val); SHA256 hashAlg = new SHA256Managed(); hashAlg.Initialize(); var hashedBytes = hashAlg.ComputeHash(pwdBytes); var hash = Convert.ToBase64String(hashedBytes); if (hash == pHash) return true; else return false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WPFTestProject.Domain; namespace WPFTestProject.Service { public interface ICustomerService { List<Customer> GetCustomers(); int GetCountOfNames(string name); Customer AddCustomer(Customer c); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DungeonGame { class Program { static void Main(string[] args) { Game game = new Game(); game.setup(); } // Place setup methods here? Then pass parameters into StartGame() that need to be passed to the character or monsters. } }
using Contoso.Parameters.Expressions; using LogicBuilder.Attributes; namespace Contoso.Forms.Parameters { public class DropDownTemplateParameters { public DropDownTemplateParameters ( [Comments("XAML template for the picker.")] [NameValue(AttributeNames.DEFAULTVALUE, "PickerTemplate")] string templateName, [Comments("Title text.")] [NameValue(AttributeNames.DEFAULTVALUE, "Select (Entity)")] string titleText, [ParameterEditorControl(ParameterControlType.ParameterSourcedPropertyInput)] [NameValue(AttributeNames.PROPERTYSOURCEPARAMETER, "fieldTypeSource")] [Comments("Update fieldTypeSource first. Property name for the text field.")] string textField, [ParameterEditorControl(ParameterControlType.ParameterSourcedPropertyInput)] [NameValue(AttributeNames.PROPERTYSOURCEPARAMETER, "fieldTypeSource")] [Comments("Update fieldTypeSource first. Property name for the value field.")] string valueField, [Comments("Loading text is useful when the cache has expired and the items source is being retrieved.")] [NameValue(AttributeNames.DEFAULTVALUE, "Loading ...")] string loadingIndicatorText, [Comments("Single object used for defining the selector lambda expression e.g. q => q.OrderBy(s => s.FullName).Select(a => new InstructorModel() {ID = a.ID, FullName = a.FullName})")] SelectorLambdaOperatorParameters textAndValueSelector, [Comments("Includes the source URL. May specify model and data types if we use the URL for multiple types.")] RequestDetailsParameters requestDetails, [Comments("Used the dropdown or multiselect items change conditionally at runtime. Add a flow module to define a new selector (SelectorLambdaOperatorParameters) at run time. Set reloadItemsFlowName to the flow name.")] string reloadItemsFlowName = null, [ParameterEditorControl(ParameterControlType.ParameterSourceOnly)] [Comments("Fully qualified class name for the model type.")] string fieldTypeSource = "Contoso.Domain.Entities" ) { TemplateName = templateName; TitleText = titleText; TextField = textField; ValueField = valueField; LoadingIndicatorText = loadingIndicatorText; TextAndValueSelector = textAndValueSelector; RequestDetails = requestDetails; ReloadItemsFlowName = reloadItemsFlowName; } public string TemplateName { get; set; } public string TitleText { get; set; } public string TextField { get; set; } public string ValueField { get; set; } public string LoadingIndicatorText { get; set; } public SelectorLambdaOperatorParameters TextAndValueSelector { get; set; } public RequestDetailsParameters RequestDetails { get; set; } public string ReloadItemsFlowName { get; set; } } }
using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace NetFabric.Hyperlinq { public static partial class ArrayExtensions { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Option<TSource> ElementAt<TSource>(this ReadOnlySpan<TSource> source, int index) => index < 0 || index >= source.Length ? Option.None : Option.Some(source[index]); static Option<TSource> ElementAt<TSource, TPredicate>(this ReadOnlySpan<TSource> source, int index, TPredicate predicate) where TPredicate : struct, IFunction<TSource, bool> { if (index >= 0) { foreach (var item in source) { if (predicate.Invoke(item) && index-- is 0) return Option.Some(item); } } return Option.None; } static Option<TSource> ElementAtAt<TSource, TPredicate>(this ReadOnlySpan<TSource> source, int index, TPredicate predicate) where TPredicate : struct, IFunction<TSource, int, bool> { if (index >= 0) { for (var sourceIndex = 0; sourceIndex < source.Length; sourceIndex++) { var item = source[sourceIndex]; if (predicate.Invoke(item, sourceIndex) && index-- is 0) return Option.Some(item); } } return Option.None; } static Option<TResult> ElementAt<TSource, TResult, TSelector>(this ReadOnlySpan<TSource> source, int index, TSelector selector) where TSelector : struct, IFunction<TSource, TResult> => index < 0 || index >= source.Length ? Option.None : Option.Some(selector.Invoke(source[index])); static Option<TResult> ElementAtAt<TSource, TResult, TSelector>(this ReadOnlySpan<TSource> source, int index, TSelector selector) where TSelector : struct, IFunction<TSource, int, TResult> => index < 0 || index >= source.Length ? Option.None : Option.Some(selector.Invoke(source[index], index)); static Option<TResult> ElementAt<TSource, TResult, TPredicate, TSelector>(this ReadOnlySpan<TSource> source, int index, TPredicate predicate, TSelector selector) where TPredicate : struct, IFunction<TSource, bool> where TSelector : struct, IFunction<TSource, TResult> { if (index >= 0) { foreach (var item in source) { if (predicate.Invoke(item) && index-- is 0) return Option.Some(selector.Invoke(item)); } } return Option.None; } } }
using System; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using Microsoft.AspNetCore.Mvc; using Microsoft.IdentityModel.Tokens; using Sesi.WebsiteDaSaude.WebApi.Interfaces; using Sesi.WebsiteDaSaude.WebApi.Repositories; using Sesi.WebsiteDaSaude.WebApi.ViewModels; namespace Sesi.WebsiteDaSaude.WebApi.Controllers { [ApiController] [Route ("api/[controller]")] [Produces ("application/json")] public class LoginController : ControllerBase { private IUsuarioRepository UsuarioRepository { get; set; } public LoginController () { UsuarioRepository = new UsuarioRepository (); } [HttpPost] public IActionResult FazerLogin (LoginViewModel login) { try { var usuario = UsuarioRepository.BuscarPorEmailESenha(login); if (usuario == null) { return NotFound(new { Erro = true, Mensagem = "Email ou senha incorretos." }); } var claims = new [] { new Claim (JwtRegisteredClaimNames.Email, usuario.Email), new Claim (JwtRegisteredClaimNames.Jti, usuario.IdUsuario.ToString()), new Claim (ClaimTypes.Role, usuario.IdPermissaoNavigation.NomePermissao.ToUpper()), new Claim ("permissao", usuario.IdPermissaoNavigation.NomePermissao.ToUpper()), new Claim ("nomeUsuario", usuario.NomeUsuario) }; var key = new SymmetricSecurityKey (System.Text.Encoding.UTF8.GetBytes ("websiteDaSaude-chave-autenticacao")); var creds = new SigningCredentials (key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken ( issuer: "WebsiteDaSaude.WebApi", audience: "WebsiteDaSaude.WebApi", claims : claims, expires : DateTime.Now.AddDays(15), signingCredentials : creds ); return Ok(new { token = new JwtSecurityTokenHandler ().WriteToken (token) }); } catch (Exception e) { return BadRequest(new { Erro = true, Mensagem = e.Message }); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using Alpaca.Markets; using Microsoft.Extensions.DependencyInjection; using LunarTrader.Interfaces; using LunarTrader.Services; using LunarTrader.Utils; using CommandService = LunarTrader.Services.CommandService; namespace LunarTrader { public static class Core { private static Settings _settings; public static CommandService CommandService; public static IServiceProvider ServiceProvider; public static ILoggerService Logger; public static async Task Main(string[] args) { //Load Settings var loader = new FileLoader(); _settings = loader.ReadSettings(); try { ServiceProvider = buildServiceProvider().Result; var core = ServiceProvider.GetService<ICoreService>(); await core.Run(); } catch (Exception e) { var logger = new LoggerService(_settings); logger.LogFatal($"Initialization failed with exception: {e}"); Console.ReadKey(); } Console.ReadKey(); } private static async Task<IServiceProvider> buildServiceProvider() { var client = Environments.Paper.GetAlpacaTradingClient(new SecretKey(_settings.KeyId, _settings.SecretKey)); var streamingClient = Environments.Paper.GetAlpacaStreamingClient(new SecretKey(_settings.KeyId, _settings.SecretKey)); Logger = new LoggerService(_settings); CommandService = new CommandService(Logger); IServiceCollection services = new ServiceCollection(); services.AddSingleton(_settings); services.AddSingleton<ILoggerService>(Logger); services.AddSingleton<ICommandService>(CommandService); services.AddSingleton<IDateTimeService, DateTimeService>(); services.AddSingleton(client); services.AddSingleton(streamingClient); services.AddSingleton<IClock>(await client.GetClockAsync()); services.AddSingleton<IAccountService, AccountService>(); services.AddSingleton<ICoreService, CoreService>(); return services.BuildServiceProvider(); } } }
using Hybrid.AspNetCore.Mvc.Models; namespace Hybrid.Quartz.Dashboard.Models.Dtos { public class JobHistoryViewModel { public JobHistoryViewModel(PageResult<JobHistoryEntryDto> entries, string errorMessage) { HistoryEntries = entries; ErrorMessage = errorMessage; } public PageResult<JobHistoryEntryDto> HistoryEntries { get; } public string ErrorMessage { get; } } }
using System.ComponentModel; using System.IO; using System.Runtime.CompilerServices; using CopyByExif.Core.Properties; namespace CopyByExif.Core { public class CopySettings : INotifyPropertyChanged { public string DirectoryStructure { get => Settings.Default.DirectoryStructure; set { if (Settings.Default.DirectoryStructure != value) { Settings.Default.DirectoryStructure = value; Settings.Default.Save(); NotifyPropertyChanged(); } } } public DirectoryInfo FromDirectory { get => new DirectoryInfo(FromDirectoryPath); } public string FromDirectoryPath { get => Settings.Default.FromDirectory; set { if (Settings.Default.FromDirectory != value) { Settings.Default.FromDirectory = value; Settings.Default.Save(); NotifyPropertyChanged(); } } } public DirectoryInfo ToDirectory { get => new DirectoryInfo(ToDirectoryPath); } public string ToDirectoryPath { get => Settings.Default.ToDirectory; set { if (Settings.Default.ToDirectory != value) { Settings.Default.ToDirectory = value; Settings.Default.Save(); NotifyPropertyChanged(); } } } #region INotifyPropertyChanged private void NotifyPropertyChanged([CallerMemberName]string propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion } }
using System; namespace Vaccination.Models { public class VaccinationRecord { public VaccinationRecord() { } public VaccinationRecord(int id, DateTime date, Person person, VaccineBatch vaccineBatch, VaccinationPoint vaccinationPoint, int dose, bool vaccinationDoneStatus) { Id = id; Date = date; Person = person; VaccineBatch = vaccineBatch; VaccinationPoint = vaccinationPoint; Dose = dose; VaccinationDoneStatus = vaccinationDoneStatus; } public int Id { get; set; } public DateTime Date { get; set; } public Person Person { get; set; } public VaccineBatch VaccineBatch { get; set; } public VaccinationPoint VaccinationPoint { get; set; } public int Dose { get; set; } public bool VaccinationDoneStatus { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HackerrankSolutionConsole { class encryption : Challenge { public override void Main(string[] args) { string s = Console.ReadLine(); int L = s.Length; int floor = (int)Math.Floor(Math.Sqrt(L)); int ceiling = (int)Math.Ceiling(Math.Sqrt(L)); int rows, columns; if (floor * floor >= L) { rows = floor; columns = floor; } else if (floor * ceiling >= L) { columns = ceiling; rows = floor; } else { rows = ceiling; columns = ceiling; } char[,] grid = new char[columns, rows]; int x = 0; int y = 0; foreach (char c in s) { grid[x, y] = c; x++; if (x == columns) { x = 0; y++; } } string sentence = string.Empty; for (int i = 0; i < columns; i++) { string word = ""; for (int j = 0; j < rows; j++) { if (Char.IsLetter(grid[i, j]) && grid[i, j] < 128) word += grid[i, j]; } sentence += word + " "; } Console.WriteLine(sentence.Trim()); } public encryption() { Name = "Encryption"; Path = "encryption"; Difficulty = Difficulty.Medium; Domain = Domain.Algorithms; Subdomain = Subdomain.Implementation; } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; //JaJuan Webster //Professor Cascioli //Asteroids! //ABOVE AND BEYOND: Background Music & Game States namespace Webster_HW_Project2_Asteroids { class Circle { //Fields private SpriteBatch spriteBatch; private Texture2D pixel; private float x; private float y; private float radius; //Get Set Properties for X, Y, and Radius public float X { get { return x; } set { x = value; } } public float Y { get { return y; } set { y = value; } } public float Radius { get { return radius; } set { radius = value; } } //Constructor public Circle(SpriteBatch sb, GraphicsDevice gd) { this.spriteBatch = sb; // Set up the texture also pixel = new Texture2D(gd, 1, 1); pixel.SetData<Color>(new Color[] { Color.White }); } public void DrawLine(int x0, int y0, int x1, int y1, int thickness, Color color) { // Calculate the distance between the points float dist = Vector2.Distance(new Vector2(x0, y0), new Vector2(x1, y1)); // Get the angle of the line float angleOfLine = (float)Math.Atan2(y1 - y0, x1 - x0); // Create an axis aligned rectangle of the correct size Rectangle rect = new Rectangle(x0, y0, (int)Math.Ceiling(dist), thickness); // Draw spriteBatch.Draw(pixel, rect, null, color, angleOfLine, new Vector2(0, 0.5f), SpriteEffects.None, 0.0f); } public void DrawCircle(int x, int y, int radius, int segments, Color color) { // Verify valid params if (segments <= 0) return; // Starting point float currentX = x + radius; float currentY = y; // Angle per segment float step = MathHelper.TwoPi / segments; float currentAngle = step; // Loop through the requested number of segments for (int i = 0; i < segments; i++) { // Calc new point on unit circle float newX = (float)Math.Cos(currentAngle); float newY = (float)Math.Sin(currentAngle); // Move to desired location newX = newX * radius + x; newY = newY * radius + y; // Draw from current to new DrawLine((int)currentX, (int)currentY, (int)newX, (int)newY, 1, color); // Save values currentX = newX; currentY = newY; // Adjust angle currentAngle += step; } } } }
using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NetPro.Core.Infrastructure; using NetPro.Sign; using NetPro.TypeFinder; namespace Leon.XXX.Api { public class ApiStartup : INetProStartup { public int Order => 900; public static IFreeSql Fsql { get; private set; } public void ConfigureServices(IServiceCollection services, IConfiguration configuration = null, ITypeFinder typeFinder = null) { var option = configuration.GetSection(nameof(VerifySignOption)).Get<VerifySignOption>(); //覆盖请求签名组件 services.AddVerifySign(s => { //自定义签名摘要逻辑 s.OperationFilter<VerifySignCustomer>(); }); var connectionString = configuration.GetValue<string>("ConnectionStrings:MysqlConnection"); Fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.MySql, connectionString) .UseAutoSyncStructure(false) //自动同步实体结构到数据库 .Build(); //请务必定义成 Singleton 单例模式 services.AddSingleton<IFreeSql>(Fsql); services.AddFreeRepository(null, this.GetType().Assembly);//批量注入Repository } public void Configure(IApplicationBuilder application) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ZeroFormatter; namespace Sandbox.Shared { [ZeroFormattable] public class InheritBase { [Index(0)] public virtual int MyProperty0 { get; set; } } [ZeroFormattable] public class Inherit : InheritBase { [Index(1)] public virtual int MyProperty1 { get; set; } [Index(2)] public virtual TypeCode MyProperty2 { get; set; } } [ZeroFormattable] public class FooBarBaz { [Index(0)] public virtual IList<byte[]> HugaHuga { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Bookstore.Models { public class EpayRequest { public EpayRequest() { } public EpayRequest(string encoded, Func<EpayRequest, string> checksumFuction) { Encoded = encoded; Checksum = checksumFuction(this); } public string Encoded { get; set; } public string Checksum { get; set; } } }
//Problem 9. Trapezoids // Write an expression that calculates trapezoid's area by given sides a and b and height h . using System; namespace Problem09Trapezoids { class Trapezoids { static void Main() { Single a, b, height; try { Console.Write("Enter A:"); a = Single.Parse(Console.ReadLine()); Console.Write("Enter B:"); b = Single.Parse(Console.ReadLine()); Console.Write("Enter height:"); height = Single.Parse(Console.ReadLine()); Console.WriteLine("Perimeter = {0}", ((a + b) / 2) * height); } catch (FormatException) { // Wrong format is entered. Handle exception Console.WriteLine("Format of entered data is not correct"); } } } }
using System; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Micro.Net.Abstractions; using Micro.Net.Abstractions.Sagas; using Micro.Net.Exceptions; using Micro.Net.Handling; using Micro.Net.Receive; using Microsoft.Extensions.DependencyInjection; namespace Micro.Net.Sagas { public static class SagaShell { //TODO: Cache branching internal static async Task HandleSaga<TSagaMessage>(ReceiveContext<TSagaMessage, ValueTuple> request, IServiceProvider provider, CancellationToken cancellationToken) where TSagaMessage : ISagaContract { ISagaStepHandler<TSagaMessage> _svc = provider.GetService<ISagaStepHandler<TSagaMessage>>(); if (_svc == null) { //TODO: Better exception here request.SetFault(new MicroHostException()); return; } Type sagaDataType; if(SagaCache._sagaDataMessageMapCache.TryGetValue(typeof(TSagaMessage), out Type _sagaDataType)) { sagaDataType = _sagaDataType; } else { //Seek saga data type Type svcType = _svc.GetType(); while ((svcType.IsGenericType ? svcType.GetGenericTypeDefinition() : svcType) != typeof(Saga<>)) { svcType = svcType.BaseType; } sagaDataType = SagaCache._sagaDataMessageMapCache[typeof(TSagaMessage)] = svcType.GetGenericArguments()[0]; } MethodInfo slSagaHandleMethod; if (SagaCache._slSagaHandleCache.TryGetValue(typeof(TSagaMessage), out MethodInfo _slSagaHandleMethod)) { slSagaHandleMethod = _slSagaHandleMethod; } else { slSagaHandleMethod = SagaCache._slSagaHandleCache[typeof(TSagaMessage)] = MethodBase.GetCurrentMethod() .DeclaringType.GetMethod(nameof(HandleSagaData), BindingFlags.Static | BindingFlags.NonPublic) .MakeGenericMethod(typeof(TSagaMessage), sagaDataType); } await (Task)slSagaHandleMethod.Invoke(null, new object[] { request, provider, _svc, cancellationToken }); } internal static async Task HandleSagaData<TSagaMessage, TSagaData>(ReceiveContext<TSagaMessage, ValueTuple> request, IServiceProvider provider, ISagaStepHandler<TSagaMessage> stepHandler, CancellationToken cancellationToken) where TSagaMessage : ISagaContract where TSagaData : class, ISagaData { SagaFinderContext finderContext = new SagaFinderContext(); TSagaData data = default; Func<object, SagaFinderContext, object> finderFunc = null; if (SagaCache._slSagaDataFindCache.TryGetValue((typeof(TSagaMessage), typeof(TSagaData)), out Func<object, SagaFinderContext, object> _finderFunc)) { finderFunc = _finderFunc; } else { { ISagaFinder<TSagaData>.IFor<TSagaMessage> finder = provider.GetService<ISagaFinder<TSagaData>.IFor<TSagaMessage>>(); if (finder != null) { data = await finder.Find(request.Request.Payload, finderContext); } } if (data == default) { IDefaultSagaFinder<TSagaData> finder = provider.GetService<IDefaultSagaFinder<TSagaData>>(); if (finder != null) { data = await finder.Find(request.Request.Payload, finderContext); } } if (data == default) { IDefaultSagaFinder finder = provider.GetService<IDefaultSagaFinder>(); if (finder != null) { data = await finder.Find<TSagaData, TSagaMessage>(request.Request.Payload, finderContext); } } } if (finderFunc == null) { //TODO: Set better exception request.SetFault(new MicroException()); return; } data = (TSagaData) finderFunc.Invoke(request.Request.Payload, finderContext); if (data == default && !(stepHandler is ISagaStartHandler<TSagaMessage>)) { //TODO: Set better exception request.SetFault(new MicroException()); return; } if (data == default) { Func<object> slSagaStart = null; if (SagaCache._slSagaStartCache.TryGetValue(typeof(TSagaData), out Func<object> _slSagaStart)) { slSagaStart = _slSagaStart; } else { if (typeof(TSagaData).GetConstructor(Type.EmptyTypes) == null) { slSagaStart = SagaCache._slSagaStartCache[typeof(TSagaData)] = () => Activator.CreateInstance<TSagaData>(); } else { IFactory<TSagaData> factory = provider.GetService<IFactory<TSagaData>>(); if (factory != null) { slSagaStart = SagaCache._slSagaStartCache[typeof(TSagaData)] = () => factory.Create(); } } } if (slSagaStart == null) { //TODO: Set better exception request.SetFault(new MicroException()); return; } data = (TSagaData)slSagaStart.Invoke(); } ISagaContext sagaContext = new SagaContext(); if (stepHandler is Saga<TSagaData> saga) { saga.Data = data; await stepHandler.Handle(request.Request.Payload, sagaContext); if (sagaContext.TryGetFault(out Exception ex)) { ISagaFaultHandler faultHandler = provider.GetService<ISagaFaultHandler>(); if (faultHandler != null) { SagaFaultContext context = new SagaFaultContext(); await faultHandler.HandleFault(request.Request.Payload, data, context); } request.SetFault(ex); } //TODO: Set up terminate handler and resolve handler } else { //TODO: Set better exception request.SetFault(new MicroException()); return; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace UtahPlanners2.Domain.Contract { public interface IPersistentRepository<T> where T : Aggregate { T Get(Guid id); List<T> FindAll(); List<T> Find(Func<T, bool> predicate); bool Save(T aggregate); bool Delete(Guid id); } }
using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.Logging; using Rinsen.IdentityProvider.Contracts.v1; using System; using System.Security.Authentication; using System.Security.Cryptography; using System.Threading.Tasks; namespace Rinsen.IdentityProvider.ExternalApplications { public class ExternalApplicationService : IExternalApplicationService { private readonly IExternalApplicationStorage _externalApplicationStorage; private readonly IExternalSessionStorage _externalSessionStorage; private readonly ITokenStorage _tokenStorage; private readonly ILogger<ExternalApplicationService> _log; private static readonly RandomNumberGenerator CryptoRandom = RandomNumberGenerator.Create(); public ExternalApplicationService(IExternalApplicationStorage externalApplicationStorage, IExternalSessionStorage externalSessionStorage, ITokenStorage tokenStorage, ILogger<ExternalApplicationService> log) { _externalApplicationStorage = externalApplicationStorage; _externalSessionStorage = externalSessionStorage; _tokenStorage = tokenStorage; _log = log; } public async Task<Token> GetTokenAsync(string tokenId, string applicationKey) { if (string.IsNullOrEmpty(tokenId)) { throw new ArgumentException("TokenId is required", nameof(tokenId)); } if (string.IsNullOrEmpty(applicationKey)) { throw new ArgumentException("Application key is required", nameof(applicationKey)); } var token = await _tokenStorage.GetAndDeleteAsync(tokenId); var externalApplication = await _externalApplicationStorage.GetFromApplicationKeyAsync(applicationKey); if (externalApplication.Active && externalApplication.ExternalApplicationId == token.ExternalApplicationId && token.Created.AddSeconds(15) >= DateTimeOffset.Now) { return token; } throw new AuthenticationException($"Authentication failed for token id {tokenId} and application key {applicationKey}"); } public async Task<ValidationResult> GetTokenForValidHostAsync(string applicationName, string host, Guid identityId, Guid correlationId, bool rememberMe) { if (string.IsNullOrEmpty(host)) return ValidationResult.Failure(); var externalApplication = await _externalApplicationStorage.GetFromApplicationNameAndHostAsync(applicationName, host); if (externalApplication == default(ExternalApplication)) { return ValidationResult.Failure(); } var bytes = new byte[32]; CryptoRandom.GetBytes(bytes); var tokenId = Base64UrlTextEncoder.Encode(bytes); var token = new Token { TokenId = tokenId, Created = DateTimeOffset.Now, ExternalApplicationId = externalApplication.ExternalApplicationId, IdentityId = identityId, Expiration = rememberMe, CorrelationId = correlationId }; await _tokenStorage.CreateAsync(token); return ValidationResult.Success(token.TokenId); } public Task LogExportedExternalIdentity(ExternalIdentity externalIdentity, Guid externalApplicationId) { var externalSession = new ExternalSession { CorrelationId = externalIdentity.CorrelationId, Created = DateTimeOffset.Now, ExternalApplicationId = externalApplicationId, IdentityId = externalIdentity.IdentityId }; return _externalSessionStorage.Create(externalSession); } } }
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace DAL.Migrations { public partial class Initial : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Activities", columns: table => new { Id = table.Column<Guid>(nullable: false), Name = table.Column<string>(nullable: true), Latitude = table.Column<float>(nullable: false), Longitude = table.Column<float>(nullable: false), Address = table.Column<string>(nullable: true), PostalCode = table.Column<string>(nullable: true), City = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Activities", x => x.Id); }); migrationBuilder.CreateTable( name: "People", columns: table => new { Id = table.Column<Guid>(nullable: false), Name = table.Column<string>(nullable: true), FirstName = table.Column<string>(nullable: true), BirthDate = table.Column<DateTime>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_People", x => x.Id); }); migrationBuilder.CreateTable( name: "Excursions", columns: table => new { Id = table.Column<Guid>(nullable: false), Name = table.Column<string>(nullable: true), Date = table.Column<DateTime>(nullable: false), NbPlaces = table.Column<int>(nullable: false), ActivityId = table.Column<Guid>(nullable: true), CreatorId = table.Column<Guid>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Excursions", x => x.Id); table.ForeignKey( name: "FK_Excursions_Activities_ActivityId", column: x => x.ActivityId, principalTable: "Activities", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Excursions_People_CreatorId", column: x => x.CreatorId, principalTable: "People", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "PersonsExcursions", columns: table => new { PersonId = table.Column<Guid>(nullable: false), ExcursionId = table.Column<Guid>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_PersonsExcursions", x => new { x.ExcursionId, x.PersonId }); table.ForeignKey( name: "FK_PersonsExcursions_Excursions_ExcursionId", column: x => x.ExcursionId, principalTable: "Excursions", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_PersonsExcursions_People_PersonId", column: x => x.PersonId, principalTable: "People", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Weathers", columns: table => new { Id = table.Column<Guid>(nullable: false), Temperature = table.Column<float>(nullable: false), WindSpeed = table.Column<float>(nullable: false), Pression = table.Column<int>(nullable: false), Humidity = table.Column<int>(nullable: false), Description = table.Column<string>(nullable: true), Icon = table.Column<string>(nullable: true), Sunrise = table.Column<DateTime>(nullable: false), Sunset = table.Column<DateTime>(nullable: false), ExcursionId = table.Column<Guid>(nullable: false), ExcursionId1 = table.Column<Guid>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Weathers", x => x.Id); table.ForeignKey( name: "FK_Weathers_Excursions_ExcursionId", column: x => x.ExcursionId, principalTable: "Excursions", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Weathers_Excursions_ExcursionId1", column: x => x.ExcursionId1, principalTable: "Excursions", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( name: "IX_Excursions_ActivityId", table: "Excursions", column: "ActivityId"); migrationBuilder.CreateIndex( name: "IX_Excursions_CreatorId", table: "Excursions", column: "CreatorId"); migrationBuilder.CreateIndex( name: "IX_PersonsExcursions_PersonId", table: "PersonsExcursions", column: "PersonId"); migrationBuilder.CreateIndex( name: "IX_Weathers_ExcursionId", table: "Weathers", column: "ExcursionId", unique: true); migrationBuilder.CreateIndex( name: "IX_Weathers_ExcursionId1", table: "Weathers", column: "ExcursionId1"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "PersonsExcursions"); migrationBuilder.DropTable( name: "Weathers"); migrationBuilder.DropTable( name: "Excursions"); migrationBuilder.DropTable( name: "Activities"); migrationBuilder.DropTable( name: "People"); } } }
namespace Words { using System; public class Program { public static int count; static void Main() { var pattern = Console.ReadLine(); var text = Console.ReadLine(); var count = 0; for (int i = 0; i < pattern.Length; i++) { var preffix = (pattern.Substring(0, i)); var suffix = (pattern.Substring(i, (pattern.Length - i))); count += CountStringOccurrences(text, suffix, preffix); } Console.WriteLine(count); } public static int CountStringOccurrences(string text, string prefix, string suffix) { var currentCount = 0; var preffixCount = 0; var sufficCound = 0; int i = 0; int j = 0; if (suffix == string.Empty) { sufficCound = 1; } else { while ((i = text.IndexOf(suffix, i)) != -1) { i += suffix.Length; sufficCound++; } } if (prefix == string.Empty) { preffixCount = 1; } else { while ((j = text.IndexOf(prefix, j)) != -1) { j += prefix.Length; preffixCount++; } } currentCount = preffixCount * sufficCound; return currentCount; } } }
using System; using System.Runtime.Serialization.Formatters.Binary; using System.Xml.Serialization; using System.Collections.Generic; using System.Text; using System.IO; using System.Globalization; namespace WF.SDK.Common { public static class JSONSerializerHelper { public static List<Newtonsoft.Json.JsonConverter> SerializeConverters { get; set; } public static List<Newtonsoft.Json.JsonConverter> DeserializeConverters { get; set; } static JSONSerializerHelper() { JSONSerializerHelper.SerializeConverters = new List<Newtonsoft.Json.JsonConverter>(); JSONSerializerHelper.DeserializeConverters = new List<Newtonsoft.Json.JsonConverter>(); } public static T Deserialize<T>(string item, bool errorOnMissingMember = true) { if (item == null || item.Length == 0) { return default(T); } T ret = default(T); try { var ser = new Newtonsoft.Json.JsonSerializer(); if (!errorOnMissingMember) { ser.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore; } //Add the needed converters JSONSerializerHelper.DeserializeConverters.ForEach(i => ser.Converters.Add(i)); //Make a reader var sr = new StringReader(item); var reader = new Newtonsoft.Json.JsonTextReader(sr); ret = (T)ser.Deserialize(reader, typeof(T)); } catch (Exception e) { Exception ex = new Exception("Deserialize Failed.", e); throw ex; } return ret; } public static string SerializeToString<T>(T item) { return JSONSerializerHelper.SerializeToString<T>(item, ""); } public static string SerializeToString<T>(T item, string defaultIfNull) { if (item == null) { return defaultIfNull; } string ret = ""; try { Newtonsoft.Json.JsonSerializer ser = new Newtonsoft.Json.JsonSerializer(); //Add the needed converters JSONSerializerHelper.SerializeConverters.ForEach(i => ser.Converters.Add(i)); //Make a writer var sw = new StringWriter(); ser.Serialize(sw, item); ret = sw.GetStringBuilder().ToString(); } catch (Exception e) { Exception ex = new Exception("Serialize Failed.", e); throw ex; } return ret; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Combination { public partial class 发货通知检核表 : Form { public 发货通知检核表() { InitializeComponent(); } Sql sql = new Sql(); private void btnSeek_Click(object sender, EventArgs e) { Cursor = Cursors.WaitCursor; dataGridView1.Rows.Clear(); string query = @"select a.FFetchDate as 交貨日期,a.FSourceBillNo as 來源單號,a.FModel as 品名,a.FNumber as 物料長代碼,a.FAuxQty as 需求量,isnull(b.Qty,0) as 庫存量,case when a.FAuxQty > b.Qty then a.FAuxQty - b.Qty else '0' end as 差額,a.FCUUnitName 單位 from (select isnull(a.FFetchDate,'') as FFetchDate,isnull(a.FSourceBillNo,'') as FSourceBillNo,isnull(a.FModel,'') as FModel,isnull(a.FNumber,'') as FNumber, isnull(a.FCUUnitName,'小计') as FCUUnitName,isnull(a.FitemID,'') as FitemID, isnull(a.FDefaultLoc,'') as FDefaultLoc,a.FAuxQty from ( select a.FFetchDate,c.FModel,c.FNumber,b.FCUUnitName,c.FitemID,c.FDefaultLoc,b.FSourceBillNo,SUM(a.FAuxQty) as FAuxQty from [" + sql.CYDB + "].[dbo].[SEOutStockEntry] a, " + "["+ sql.CYDB +"].[dbo].[vwICBill_34] b, " + "["+ sql.CYDB +"].[dbo].[t_ICItem] " + "c " + "where a.FInterID = b.FinterID and a.FEntryID = b.FEntryID and a.FitemID = c.FitemID and a.FFetchDate = '" + dateTimePicker1.Value.ToString("yyyyMMdd") + "' " + "group by a.FFetchDate,c.FModel,c.FNumber,b.FCUUnitName,c.FitemID,c.FDefaultLoc,b.FSourceBillNo with rollup) a " + "where a.FDefaultLoc is not null or(a.FNumber is not null and a.FCUUnitName is null)) a left join " + "(select b.FItemID, b.Fmodel, b.Fnumber, d.Fname as unit, a.Qty/d.Fcoefficient as Qty, isnull(h.ww,0) as Uprice,a.FStockID from " + "(select FitemID, FstockID, sum(FQty) as Qty from ["+ sql.CYDB +"].[dbo].[ICinventory] where (FstockID = '810' or FstockID = '20421') group by FitemID,FstockID) a left join " + "(select c.FitemID, c.FNumber, SUM(a.FPrice* b.Fexchangerate)/ count(c.FNumber) as ww from " + "["+ sql.CYDB +"].[dbo].[ICPrcPlyEntry] a, " + "["+ sql.CYDB +"].[dbo].[t_Currency] b, " + "["+ sql.CYDB +"].[dbo].[t_icitem] c, " + "["+ sql.CYDB +"].[dbo].[t_organization] " + "d " + "where a.FitemID = c.FitemID and a.FCuryID = b.FCurrencyID " + "and d.Fdeleted = '0' and a.Fchecked = '1' and c.Fdeleted = '0' " + "and c.FNumber like '14%' group by c.FitemID, c.FNumber) h on a.FitemID = h.FitemID, " + "["+ sql.CYDB +"].[dbo].[t_icitem] b, " + "["+ sql.CYDB +"].[dbo].[t_stock] c, " + "["+ sql.CYDB +"].[dbo].[t_measureunit] " + "d " + "where a.FitemID = b.FitemID and a.FstockID = c.FitemID " + "and(b.FstoreUnitID = d.FMeasureUnitID and b.FUnitGroupID = d.FunitGroupID) " + "and b.Fdeleted = '0' and b.Fnumber like '14.%' " + "and (c.Fnumber = '03' or c.Fnumber = '04')) b on a.FitemID = b.FiteMID and a.FDefaultLoc = b.FStockID"; DataTable dt = new DataTable(); dt = sql.getQuery(query); foreach (DataRow item in dt.Rows) { int n = dataGridView1.Rows.Add(); dataGridView1.Rows[n].Cells[0].Value = Convert.ToDateTime(item["交貨日期"]).ToString("yyyy/MM/dd"); dataGridView1.Rows[n].Cells[1].Value = item["來源單號"].ToString(); dataGridView1.Rows[n].Cells[2].Value = item["品名"].ToString(); dataGridView1.Rows[n].Cells[3].Value = item["物料長代碼"].ToString(); dataGridView1.Rows[n].Cells[4].Value = Convert.ToDecimal(item["需求量"]).ToString("N0"); if (item["庫存量"] != System.DBNull.Value) { dataGridView1.Rows[n].Cells[5].Value = Convert.ToDecimal(item["庫存量"]).ToString("N0"); } dataGridView1.Rows[n].Cells[6].Value = Convert.ToDecimal(item["差額"]).ToString("N0"); dataGridView1.Rows[n].Cells[7].Value = item["單位"].ToString(); } Cursor = Cursors.Default; if (dataGridView1.Rows.Count == 0) { MessageBox.Show("查无信息"); } } private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (e.RowIndex > -1) { string execute = Convert.ToString(this.dataGridView1.Rows[e.RowIndex].Cells["Column8"].Value); if (Convert.ToDecimal(execute) > 0) { dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow; } } } } }
#region Copyright Syncfusion Inc. 2001-2015. // Copyright Syncfusion Inc. 2001-2015. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // licensing@syncfusion.com. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Views; using Com.Syncfusion.Charts; namespace SampleBrowser { public class Candle : SamplePage { public override View GetSampleContent(Context context) { var chart = new SfChart(context);; chart.SetBackgroundColor(Color.White); chart.PrimaryAxis = new CategoryAxis(); chart.SecondaryAxis = new NumericalAxis(); chart.Series.Add(new CandleSeries { DataSource = MainPage.GetFinancialData(), }); return chart; } } }
using System; using System.ComponentModel.DataAnnotations; using Amesc.Dominio.Pessoas; namespace Amesc.WebApp.ViewModels { public class PessoaParaCadastroViewModel { public int Id { get; set; } [Required(ErrorMessage = "Nome é obrigatório")] public string Nome { get; set; } [Required(ErrorMessage = "CPF é obrigatório")] public string Cpf { get; set; } [Required(ErrorMessage = "Telefone é obrigatório")] public string Telefone { get; set; } [Required(ErrorMessage = "Número é obrigatório")] public string Numero { get; set; } [Required(ErrorMessage = "Logradouro é obrigatório")] public string Logradouro { get; set; } [Required(ErrorMessage = "CEP é obrigatório")] public string Cep { get; set; } [Required(ErrorMessage = "Bairro é obrigatório")] public string Bairro { get; set; } public string Complemento { get; set; } [Required(ErrorMessage = "Cidade é obrigatório")] public string Cidade { get; set; } [Required(ErrorMessage = "Estado é obrigatório")] public string Estado { get; set; } [Required(ErrorMessage = "Tipo de publico é obrigatório")] public string TipoDePublico { get; set; } [Required(ErrorMessage = "Orgăo emissor do RG é obrigatório")] public string OrgaoEmissorDoRg { get; set; } [Required(ErrorMessage = "RG é obrigatório")] public string Rg { get; set; } [Required(ErrorMessage = "Data de nascimento é obrigatório")] public string DataDeNascimento { get; set; } public string RegistroProfissional { get; set; } public string MidiaSocial { get; set; } public string Especialidade { get; set; } public PessoaParaCadastroViewModel() { } public PessoaParaCadastroViewModel(Pessoa entidade) { Id = entidade.Id; Nome = entidade.Nome; Cpf = entidade.Cpf; OrgaoEmissorDoRg = entidade.OrgaoEmissorDoRg; Rg = entidade.Rg; DataDeNascimento = entidade.DataDeNascimento.ToString("dd/MM/yyyy"); RegistroProfissional = entidade.RegistroProfissional; TipoDePublico = entidade.TipoDePublico; Especialidade = entidade.Especialidade; Telefone = entidade.Telefone; Numero = entidade.Endereco.Numero; Logradouro = entidade.Endereco.Logradouro; Bairro = entidade.Endereco.Bairro; Complemento = entidade.Endereco.Complemento; Cidade = entidade.Endereco.Cidade; Estado = entidade.Endereco.Estado; Cep = entidade.Endereco.Cep; MidiaSocial = entidade.MidiaSocial; } } }
using System; using System.Text.Json.Serialization; namespace Crt.Model.Dtos.District { public class DistrictDto { [JsonPropertyName("id")] public decimal DistrictId { get; set; } public decimal DistrictNumber { get; set; } public string DistrictName { get; set; } public DateTime? EndDate { get; set; } [JsonPropertyName("name")] public string Description { get => $"{DistrictNumber}-{DistrictName}"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using SKT.WMS.WMSReport.Model; using SKT.WMS.WMSReport.BLL; namespace SKT.MES.Web.WMSReport { public partial class WMSMaterialCardStandingBook : BasePage { protected void Page_Load(object sender, EventArgs e) { if (this.IsPostBack) { Boolean hasSearchSettings = false; hasSearchSettings = (this.txtCInvCode.Text.Trim() != "") ? true : false; if (hasSearchSettings) { this.Master.SetSearchSettings = true; this.Master.PageGridView = this.GridView1; this.GridView1.DataSourceID = this.ObjectDataSource1.ID; this.Master.PageObjectDataSource = this.ObjectDataSource1; this.Master.RecordIDField = "ID"; this.Master.DefaultSortExpression = "dDate"; this.Master.DefaultSortDirection = SortDirection.Descending; SKT.MES.Model.SearchSettings searchSettings = new SKT.MES.Model.SearchSettings(); searchSettings.AddCondition("cInvCode", this.txtCInvCode.Text.Trim()); searchSettings.AddCondition("cWhCode", this.txtCWhCode.Text.Trim()); this.Master.SearchSettings = searchSettings; this.GridView1.PageIndex = 0; WMSRdRecordInfo model = new WMSRdRecord().GetInfoMCSB(this.txtCInvCode.Text.Trim()); if (model != null) { PageData = model; } } else { this.Master.SetSearchSettings = false; } } } /// <summary> /// 设置页面上的数据。 /// </summary> private WMSRdRecordInfo PageData { set { this.lblInvCCode.InnerText = value.InvCCode; this.lblCInvCode.InnerText = value.CInvCode; this.lblCInvName.InnerText = value.CInvName; this.lblInvAddCode.InnerText = value.InvAddCode; this.lblPackingType.InnerText = value.PackingType; this.lblComUnitCode.InnerText = value.ComUnitCode; this.lblSafeNum.InnerText = value.SafeNum.ToString(); this.lblTopSum.InnerText = value.TopSum.ToString(); this.lblLowSum.InnerText = value.LowSum.ToString(); } } } }
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Zillow.Core.Constant; using Zillow.Data.DbEntity; namespace Zillow.Data.Constrains { public class CategoryConstrains : IEntityTypeConfiguration<CategoryDbEntity> { public void Configure(EntityTypeBuilder<CategoryDbEntity> builder) { builder.Property(x => x.Name).IsRequired() .HasMaxLength(100); builder.Property(x => x.Description) .HasMaxLength(500); builder.HasMany(x => x.RealEstates) .WithOne(x => x.Category) .OnDelete(DeleteBehavior.Restrict); builder.HasQueryFilter(x => !x.IsDelete); builder.ToTable(DbTablesName.CategoryTable); } } }
using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; using System.Collections; using POLIMIGameCollective; public class MenuManager : Singleton<MenuManager> { public GameObject m_splashscreen; public GameObject m_mainmenu; public GameObject m_tutorial; public GameObject m_score; public GameObject m_settings; public GameObject m_about; public GameObject m_log_screen; public GameObject m_playlevel; public enum eMenuScreen { SplashScreen = 0, MainMenu = 1, Tutorial = 2, Score = 3, Settings = 4, About = 5, PlayLevel = 6} ; [Header ("Start with Splashscreen?")] public bool m_start_with_splashscreen = true; private static bool m_has_shown_splashscreen = false; // Use this for initialization void Start () { if (!m_has_shown_splashscreen && m_start_with_splashscreen) { SwitchMenuTo (eMenuScreen.SplashScreen); m_has_shown_splashscreen = true; } else { SwitchMenuTo (eMenuScreen.MainMenu); } MusicManager.Instance.StopAll (); MusicManager.Instance.PlayMusic ("MenuMusic"); } /// <summary> /// Switch the current screen to the target one /// </summary> /// <param name="screen">Screen.</param> public void SwitchMenuTo (eMenuScreen screen) { ClearScreens (); switch (screen) { case eMenuScreen.SplashScreen: if (m_splashscreen != null) m_splashscreen.SetActive (true); break; case eMenuScreen.MainMenu: if (m_mainmenu != null) m_mainmenu.SetActive (true); break; case eMenuScreen.Tutorial: if (m_tutorial != null) m_tutorial.SetActive (true); break; case eMenuScreen.Score: if (m_score != null) m_score.SetActive (true); break; case eMenuScreen.Settings: if (m_settings != null) m_settings.SetActive (true); break; case eMenuScreen.About: if (m_about != null) m_about.SetActive (true); break; } } /// <summary> /// Clear all the screens /// </summary> void ClearScreens () { if (m_splashscreen != null) m_splashscreen.SetActive (false); if (m_mainmenu != null) m_mainmenu.SetActive (false); if (m_tutorial != null) m_tutorial.SetActive (false); if (m_score != null) m_score.SetActive (false); if (m_settings != null) m_settings.SetActive (false); if (m_about != null) m_about.SetActive (false); if (m_log_screen != null) m_log_screen.SetActive (false); if (m_playlevel != null) m_playlevel.SetActive (false); } /// <summary> /// Returns to the main screen /// </summary> public void SwitchToMainMenu () { SwitchMenuTo (eMenuScreen.MainMenu); } /// <summary> /// Switch to the tutorial screen /// </summary> public void SwitchToTutorial () { SwitchMenuTo (eMenuScreen.Tutorial); } /// <summary> /// Switch to the tutorial score screen /// </summary> public void SwitchToScore () { SwitchMenuTo (eMenuScreen.Score); } public void SwitchToAbout () { SwitchMenuTo (eMenuScreen.About); } public void SwitchToSettings () { SwitchMenuTo (eMenuScreen.Settings); } public void Play () { MusicManager.Instance.StopAll (); MusicManager.Instance.PlayMusic ("GameplayMusic"); SceneManager.LoadSceneAsync ("DropGame"); } }
using System; using System.ComponentModel.DataAnnotations.Schema; using System.Collections.Generic; using System.Text; namespace Hotel.Data.Models { public class Feedback { public int Id { get; set; } public string Sadrzaj { set; get; } // jedan check in public int CheckINId { get; set; } [ForeignKey(nameof(CheckINId))] public virtual CheckIN CheckIN { get; set; } // jedan gost public int GostId { get; set; } [ForeignKey(nameof(GostId))] public virtual Gost Gost { get; set; } } }
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using TailorIT.API.Models; namespace TailorIT.API.Data.Context { public class Context : DbContext { public Context() { } public DbSet<Usuario> Usuario { get; set; } public DbSet<Sexo> Sexo { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(@"Server=localhost;Database=tailorit;User=SA;Password=D!scador2000; MultipleActiveResultSets=true"); } public override int SaveChanges() { return base.SaveChanges(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace otobus2 { class Musteri { } }
using Logic.GameClasses; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; namespace _4XGame.Serialization { //TODO: Descriptive name public static class GameSaveLoad { public static void Save(Game game, string path) { if (game == null) { throw new System.ArgumentNullException(nameof(game)); } if (path == null) { throw new System.ArgumentNullException(nameof(path)); } using (Stream s = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write)) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(s, game); } } public static Game Load(string path) { if (path == null) { throw new System.ArgumentNullException(nameof(path)); } Game loadedGame = new Game(); try { using (Stream s = new FileStream(path, FileMode.Open, FileAccess.Read)) { BinaryFormatter formatter = new BinaryFormatter(); loadedGame = (Game)formatter.Deserialize(s); } } catch (FileNotFoundException) { throw new SaveFileException("Cannot load game: Path incorrect"); } catch (SerializationException) { throw new SaveFileException("Cannot load game: File format incorrect"); } return loadedGame; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SteeringFOV : MonoBehaviour { [SerializeField] private float speedHoriz = 2.0f; [SerializeField] private float speedVerti = 2.0f; [SerializeField] private float pitch = 0.0f; [SerializeField] private float yaw = 0.0f; private void Update() { yaw += speedHoriz * Input.GetAxis("Mouse X") * Time.deltaTime; pitch += speedVerti * Input.GetAxis("Mouse Y") * Time.deltaTime; transform.eulerAngles = new Vector3(pitch, yaw, 0.0f); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Text.RegularExpressions; using System.Diagnostics; namespace RegExTutorial { public partial class Form1 : Form { // Note: Use Static Regex methods as much as possible // In this tool, Regex instance is instantiated primarily to retrieve group names. // See video on group name for details Regex _regex = null; Match _match = null; RegexOptions _regexOptions = RegexOptions.None; public Form1() { InitializeComponent(); } private void btnMatch_Click(object sender, EventArgs e) { try { _regex = null; _match = null; txtResult.Text = string.Empty; /****************** // // Note: Use Static Regex methods as much as possible // In this tool, Regex instance is instantiated primarily to retrieve group names. // Instantiating Regex instance for every click is a bad idea! Do not use this approach for production code :-) // Since this is an interactive tool with pattern possibly changing between // every execution, Regex instance is created for every call. *******************/ Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); _regex = new Regex(txtPattern.Text, _regexOptions); _match = _regex.Match(txtData.Text); stopWatch.Stop(); highLightMatch(stopWatch.Elapsed); } catch(Exception ex) { MessageBox.Show("Exception: " + ex.ToString()); } } private void btnNextMatch_Click(object sender, EventArgs e) { if (_regex != null && _match != null) { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); _match = _match.NextMatch(); stopWatch.Stop(); highLightMatch(stopWatch.Elapsed); } } private void highLightMatch(TimeSpan elapsed) { if (_regex != null && _match != null && _match.Success) { txtData.Focus(); txtData.Select(_match.Index, _match.Length); StringBuilder sb = new StringBuilder(); sb.AppendFormat("Match Found: {0}, Substring: {1}, Index: {2}, Length: {3}, Elapsed Time (ms): {4}{5}", _match.Success, _match.Value, _match.Index, _match.Length, elapsed.TotalMilliseconds, Environment.NewLine); // Group 0 is default group that matches the complete expression if (_match.Groups.Count > 1) { for (int i = 0; i < _match.Groups.Count; i++) { sb.AppendFormat(" Group Index:{0}, Name:{1}, Value:{2}", i, _regex.GroupNameFromNumber(i), _match.Groups[i].Value); sb.AppendLine(); } } txtResult.Text += sb.ToString(); } else { txtResult.Text += string.Format("END. Elapsed Time (ms): {0}{1}", elapsed.TotalMilliseconds, Environment.NewLine); } } private void textBox1_TextChanged(object sender, EventArgs e) { } private void btnReplace_Click(object sender, EventArgs e) { txtResult.Text = string.Empty; try { txtResult.Text = Regex.Replace(txtData.Text, txtPattern.Text, txtReplacementPattern.Text, _regexOptions); } catch (Exception ex) { MessageBox.Show("Exception: " + ex.ToString()); } } private void btnSplit_Click(object sender, EventArgs e) { txtResult.Text = string.Empty; try { string[] split = Regex.Split(txtData.Text, txtPattern.Text, _regexOptions); StringBuilder sb = new StringBuilder(); foreach (string s in split) { sb.Append(s); sb.Append(Environment.NewLine); } txtResult.Text = sb.ToString(); } catch (Exception ex) { MessageBox.Show("Exception: " + ex.ToString()); } } private void chkRightToLeft_CheckedChanged(object sender, EventArgs e) { if (chkRightToLeft.Checked) _regexOptions = RegexOptions.RightToLeft; else _regexOptions = RegexOptions.None; } } }
using UnityEngine; using System.Collections; public class SpriteAnimInstruct : MonoBehaviour { //DECLARE NEW ANIMATOR REFERENCE Animator animator; // Use this for initialization void Start () { //INITIALIZING ANIMATOR animator = GetComponent<Animator>(); } // Update is called once per frame void Update () { } public void MoveAnim() { animator.SetTrigger ("triggerMove"); } public void AttackAnim() { animator.SetTrigger ("triggerAttack"); } public void StopAnim() { animator.SetTrigger ("triggerStop"); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using WebsiteBanHang.Models; using WebsiteBanHang.ViewModels; namespace WebsiteBanHang.Controllers { [Route("api")] [ApiController] public class ProductCategoriesController : ControllerBase { private readonly SaleDBContext _context; private readonly IMapper _mapper; public ProductCategoriesController(SaleDBContext context, IMapper mapper) { _context = context; _mapper = mapper; } // GET: api/ProductCategories [Authorize(Roles = "admin,employee")] [HttpGet("admin/category/select-full")] public async Task<IActionResult> GetCategorySelectAll() { var category = await _context.ProductCategories.Select(p => new CategorySelectViewModel { CategoryId = p.CategoryId, CategoryName = p.CategoryName, isLast = false }).ToListAsync(); var listChildren = await _context.ProductCategories.Where(p => p.CategoryChildrens.Count() == 0) .Select(p => p.CategoryId).ToListAsync(); category.ForEach(e => { if (listChildren.Contains(e.CategoryId)) { e.isLast = true; } }); if (!category.Any()) { return Ok(new Response { IsError = true, Status = 404, Message = "không tìm thấy dữ liệu" }); } return Ok(new Response { Module = category, Status = 200 }); } //[HttpGet("admin/category/select-full")] //public async Task<IActionResult> GetCategorySelectAll() //{ // var category = await _context.ProductCategories.Select(p => new CategorySelectViewModel // { // CategoryId = p.CategoryId, // CategoryName = p.CategoryName // }).ToListAsync(); // if (!category.Any()) // { // return Ok(new Response // { // IsError = true, // Status = 404, // Message = "không tìm thấy dữ liệu" // }); // } // return Ok(new Response // { // Module = category, // Status = 200 // }); //} [Authorize(Roles = "admin,employee")] [HttpGet("admin/category/select-product")] public async Task<IActionResult> GetCategorySelectProduct() { var category = await _context.ProductCategories.Where(p => p.CategoryChildrens.Count() == 0) .Select(p => new { p.CategoryId, p.CategoryName }).AsNoTracking().ToListAsync(); if (!category.Any()) return Ok(new Response { IsError = true, Status = 404, Message = "không tìm thấy dữ liệu" }); return Ok(new Response { Status = 200, Module = category }); } [Authorize(Roles = "admin,employee")] [HttpGet("admin/category/check-url/{url}")] public async Task<IActionResult> CheckUrl(string url) { if (!ModelState.IsValid) { return Ok(new Response { IsError = true, Status = 400, Message = "Sai dữ liệu đầu vào" }); } var category = await _context.ProductCategories.Where(p => p.Url == url).FirstOrDefaultAsync(); if (category == null) return Ok(new Response { Status = 204 }); return Ok(new Response { Status = 406 }); } [AllowAnonymous] [HttpGet("menu/category")] public async Task<IActionResult> GetMenu() { var allCategory = await _context.ProductCategories.Include(p => p.CategoryChildrens).ThenInclude(d => d.CategoryChildrens).AsNoTracking().Where(p => p.ParentId == null).ToListAsync(); if (!allCategory.Any()) { return Ok(new Response { IsError = true, Status = 404, Message = "không tìm thấy dữ liệu" }); } var menu = _mapper.Map<List<Menu>>(allCategory); return Ok(new Response { Status = 200, Module = menu }); } [AllowAnonymous] [HttpGet("category/{url}")] public async Task<IActionResult> GetProductCategoriesByUrl([FromRoute] string url, [FromQuery] int page, [FromQuery] string order) { if (!ModelState.IsValid) { return Ok(new Response { IsError = true, Status = 400, Message = "Sai dữ liệu đầu vào" }); } int size = 12; var ctg = await _context.ProductCategories.Include(p => p.Products).ThenInclude(i => i.ProductImages) .Include(p => p.CategoryChildrens) .ThenInclude(d => d.CategoryChildrens) .Include(p => p.CategoryChildrens) .ThenInclude(d => d.Products).ThenInclude(i => i.ProductImages) .Include(p => p.CategoryChildrens) .ThenInclude(d => d.CategoryChildrens) .ThenInclude(c => c.Products).ThenInclude(i => i.ProductImages) .Include(p => p.Products).ThenInclude(r => r.EvaluationQuestions) .Include(p => p.CategoryChildrens) .ThenInclude(d => d.Products).ThenInclude(r => r.EvaluationQuestions) .Include(p => p.CategoryChildrens) .ThenInclude(d => d.CategoryChildrens) .ThenInclude(c => c.Products).ThenInclude(r => r.EvaluationQuestions) .Where(p => p.Url == url).SingleOrDefaultAsync(); if(ctg == null) { return Ok(new Response { IsError = true, Status = 404, Message = "không tìm thấy dữ liệu" }); } List<Products> pd = new List<Products>(); if (ctg.Products.Count != 0) { pd.AddRange(ctg.Products); } foreach (ProductCategories categories in ctg.CategoryChildrens) { if (categories.Products.Count != 0) { pd.AddRange(categories.Products); } foreach (ProductCategories categories1 in categories.CategoryChildrens) { if (categories1.Products.Count != 0) { pd.AddRange(categories1.Products); } } } var category_map = new ProductCategoryViewModel(); if(ctg.ParentId != null) { var categoryParent = await _context.ProductCategories.Where(p => p.CategoryId == ctg.ParentId).Select(p => new ProductCategories { CategoryName = p.CategoryName, Url = p.Url, CategoryId = p.CategoryId, CategoryChildrens = p.CategoryChildrens.Select(q => new ProductCategories { CategoryId = q.CategoryId, CategoryName = q.CategoryName, Url = q.Url, CategoryChildrens = q.CategoryChildrens.Where(a => a.ParentId == ctg.CategoryId).ToList() }).OrderByDescending(m => m.CategoryId == ctg.CategoryId).ToList() }).FirstOrDefaultAsync(); category_map = _mapper.Map<ProductCategoryViewModel>(categoryParent); } else { var categoryNoParent = await _context.ProductCategories.Include(p => p.CategoryChildrens).AsNoTracking().SingleOrDefaultAsync(p => p.CategoryId == ctg.CategoryId); category_map = _mapper.Map<ProductCategoryViewModel>(categoryNoParent); } List<ProductCategories> parentCategory = new List<ProductCategories>(); int? breadId = ctg.CategoryId; do { var bread = _context.ProductCategories.Where(p => p.CategoryId == breadId).SingleOrDefault(); breadId = bread.ParentId; parentCategory.Add(bread); } while (breadId != null); var breadcrumb = _mapper.Map<List<Breadcrumbs>>(parentCategory); breadcrumb.Reverse(); List<ProductShowcaseViewModel> productShowcase = new List<ProductShowcaseViewModel>(); foreach (var products in pd) { if(products.Stock != 0 && !products.Discontinued) { float star = 0; int totalStar; var evaluation = products.EvaluationQuestions.Where(e => e.Rate != null && e.ProductId == products.ProductId).ToList(); for (int i = 1; i <= 5; i++) { star += i * evaluation.Where(e => e.Rate == i).Count(); } totalStar = evaluation.Count(); if (totalStar > 0) star = star / totalStar; else star = 0; productShowcase.Add(new ProductShowcaseViewModel { ProductId = products.ProductId, Discount = products.Discount, ProductName = products.ProductName, UnitPrice = products.UnitPrice, Rate = star, TotalRate = totalStar, Image = products.ProductImages.FirstOrDefault()?.Url }); } } switch (order) { case "newest": productShowcase = productShowcase.OrderByDescending(p => p.ProductId).ToList(); break; case "discount": productShowcase = productShowcase.OrderByDescending(p => p.Discount).ToList(); break; case "priceasc": productShowcase = productShowcase.OrderBy(p => p.UnitPrice).ToList(); break; case "pricedesc": productShowcase = productShowcase.OrderByDescending(p => p.UnitPrice).ToList(); break; } int totalProducts = productShowcase.Count(); int totalPages = (int)Math.Ceiling(totalProducts / (float)size); page = (page < 1) ? 1 : ((page > totalPages) ? totalPages : page); var product = productShowcase.Skip(size * (page - 1)).Take(size).ToList(); var outputModel = new CategoryOutputViewModel { Paging = new Paging(totalProducts, page, size, totalPages), Products = product, Categories = category_map, Breadcrumbs = breadcrumb }; return Ok(new Response { Status = 200, Module = outputModel }); } // GET: api/ProductCategories/5 //[HttpGet("category/{id}")] //public async Task<IActionResult> GetProductCategories([FromRoute] int id) //{ // if (!ModelState.IsValid) // { // return BadRequest(ModelState); // } // var productCategories = await _context.ProductCategories.FindAsync(id); // if (productCategories == null) // { // return NotFound(); // } // return Ok(productCategories); //} // PUT: api/ProductCategories/5 [Authorize(Roles = "admin,employee")] [HttpPut("category/{id}")] public async Task<IActionResult> PutProductCategories([FromRoute] int id, [FromBody] ProductCategories productCategories) { if (!ModelState.IsValid) { return Ok(new Response { IsError = true, Status = 400, Message = "Sai dữ liệu đầu vào" }); } if (id != productCategories.CategoryId) { return Ok(new Response { IsError = true, Status = 400, Message = "Sai dữ liệu đầu vào" }); } _context.Entry(productCategories).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ProductCategoriesExists(id)) { return Ok(new Response { IsError = true, Status = 404, Message = "Không tìm thấy dữ liệu" }); } else { return Ok(new Response { IsError = true, Status = 409, Message = "Không thể lưu dữ liệu" }); throw; } } return Ok(new Response { Status = 204 }); } // POST: api/ProductCategories [Authorize(Roles = "admin,employee")] [HttpPost("admin/category")] public async Task<IActionResult> PostProductCategories([FromBody] ProductCategories productCategories) { if (!ModelState.IsValid) { return Ok(new Response { IsError = true, Status = 400, Message = "Sai dữ liệu đầu vào" }); } _context.ProductCategories.Add(productCategories); await _context.SaveChangesAsync(); return Ok(new Response { Status = 201, Module = productCategories.CategoryId }); } // DELETE: api/ProductCategories/5 [Authorize(Roles = "admin,employee")] [HttpDelete("category/{id}")] public async Task<IActionResult> DeleteProductCategories([FromRoute] int id) { if (!ModelState.IsValid) { return Ok(new Response { IsError = true, Status = 400, Message = "Sai dữ liệu đầu vào" }); } var productCategories = await _context.ProductCategories.FindAsync(id); if (productCategories == null) { return Ok(new Response { IsError = true, Status = 404, Message = "Không tìm thấy dữ liệu" }); } _context.ProductCategories.Remove(productCategories); await _context.SaveChangesAsync(); return Ok(new Response { Status = 204 }); } private bool ProductCategoriesExists(int id) { return _context.ProductCategories.Any(e => e.CategoryId == id); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public abstract class AbstractLevelManager : MonoBehaviour { [SerializeField] protected string name = "Scene"; [SerializeField] protected uint id = 0; public uint ID { get { return id; } } [SerializeField] protected Material skybox; [SerializeField] protected GameObject startPoint; [SerializeField] protected GameObject endPoint; [SerializeField] protected GameObject decor; [SerializeField] protected List<AudioClip> backgroundSounds; [SerializeField] protected List<GameObject> objectsToActivate; protected bool playing = false; public void Init() { Debug.Log("Welcome to " + name + " Level!"); RenderSettings.skybox = this.skybox; GameManager.Instance.CurrentLevelManager = this; } public void InitSound() { for (int i = 0; i < this.backgroundSounds.Count; i++) { SoundManager.Instance.AddSound(this.backgroundSounds[i]); } } public void ShowEnvironment() { for (int i = 0; i < objectsToActivate.Count; i++) objectsToActivate[i].SetActive(true); } public abstract IEnumerator BeginExperience(); public void StartExperience() { if (this.playing == false) { this.playing = true; this.startPoint.active = false; this.StartCoroutine(this.BeginExperience()); } } public abstract IEnumerator EndExperience(bool loose = false); public void StopExperience(bool loose = false) { if (this.playing == true) { this.StartCoroutine(this.EndExperience(loose)); SoundManager.Instance.StopPlaying(); this.playing = false; } } }
using ServiceDesk.Api.Systems.Common.Interfaces.Dto; using ServiceDesk.Api.Systems.Common.Interfaces.DtoBuilder; namespace ServiceDesk.Api.Systems.DirectorySystem.DtoBuilders.Software { public interface ISoftwareDtoBuilder<TDto> : IDtoBuilder<Core.Entities.DirectorySystem.Software, TDto> where TDto : class, IDto { } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace FeedBackPlatformWeb.Models.Surveys { public class OverviewModel { public List<SurveyItem> Surveys { get; set; } public List<SelectListItem> SurveyCategories { get; set; } public OverviewModel() { this.Surveys = new List<SurveyItem>(); this.SurveyCategories = new List<SelectListItem>(); } } }
using Airfield_Simulator.Core.FlightRoutes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Airfield_Simulator.Core.Models; using System.Collections; using NUnit.Framework; namespace Airfield_Simulator.Core.FlightRoutes.Tests { [TestFixture] public class RouteTests { private Route _route; GeoPoint _testpoint; GeoPoint _testpoint1; [SetUp] public void Initialize() { _route = new Route(); _testpoint = new GeoPoint(1000, 1000); _testpoint1 = new GeoPoint(2000, 2000); } [Test] public void AddTest() { _route.Add(_testpoint); if (_route[0] == _testpoint) { Assert.IsTrue(true); } else { Assert.Fail(); } } [Test] public void ClearTest() { _route.Add(_testpoint); if (_route[0] == _testpoint) { _route.Clear(); Assert.IsTrue(_route.Count() == 0); } else { Assert.Fail(); } } [Test] public void ContainsTest() { _route.Add(_testpoint); if (_route[0] == _testpoint) { Assert.IsTrue(_route.Contains(_testpoint)); } else { Assert.Fail(); } } [Test] public void CopyToTest() { _route.Add(_testpoint); _route.Add(_testpoint); if (_route[0] == _testpoint) { GeoPoint[] array = new GeoPoint[5]; _route.CopyTo(array, 2); Assert.That(array[0], Is.Null); Assert.That(array[1], Is.Null); Assert.That(array[4], Is.Null); Assert.That(array[2].Y, Is.EqualTo(1000)); Assert.That(array[3].Y, Is.EqualTo(1000)); } else { Assert.Fail(); } } [Test] public void GetEnumeratorTest() { _route.Add(_testpoint); _route.Add(_testpoint1); IEnumerator enm = _route.GetEnumerator(); Assert.That(enm, Is.Not.Null); enm.MoveNext(); Assert.That(enm.Current, Is.EqualTo(_testpoint)); enm.MoveNext(); Assert.That(enm.Current, Is.EqualTo(_testpoint1)); enm.Reset(); Assert.Throws<InvalidOperationException>(delegate { object o = enm.Current; }); } [Test] public void IndexOfTest() { _route.Add(_testpoint); _route.Add(_testpoint1); Assert.That(_route.IndexOf(_testpoint1), Is.EqualTo(1)); } [Test] public void InsertTest() { _route.Add(_testpoint); _route.Add(_testpoint); _route.Add(_testpoint); _route.Add(_testpoint); _route.Add(_testpoint); _route.Insert(3, _testpoint1); Assert.IsTrue(_route[3] == _testpoint1); } [Test] public void RemoveTest() { _route.Add(_testpoint); if (_route[0] == _testpoint) { _route.Remove(_testpoint); Assert.That(_route.Count, Is.EqualTo(0)); } else { Assert.Fail(); } } [Test] public void RemoveAtTest() { _route.Add(_testpoint1); _route.Add(_testpoint1); _route.Add(_testpoint1); _route.Add(_testpoint1); _route.Add(_testpoint1); _route.RemoveAt(3); Assert.That(_route.Count, Is.EqualTo(4)); } [Test] public void TargetNextWaypointTest() { _route.Add(_testpoint); _route.Add(_testpoint1); _route.TargetNextWaypoint(); Assert.That(_route.CurrentWaypoint, Is.EqualTo(_testpoint1)); } } }
// // Weather Maker for Unity // (c) 2016 Digital Ruby, LLC // Source code may be used for personal or commercial projects. // Source code may NOT be redistributed or sold. // // *** A NOTE ABOUT PIRACY *** // // If you got this asset from a pirate site, please consider buying it from the Unity asset store at https://assetstore.unity.com/packages/slug/60955?aid=1011lGnL. This asset is only legally available from the Unity Asset Store. // // I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. // // Thank you. // // *** END NOTE ABOUT PIRACY *** // using System.Collections; using System.Collections.Generic; using UnityEngine; namespace DigitalRuby.WeatherMaker { /// <summary> /// Types of clouds /// </summary> public enum WeatherMakerCloudType { /// <summary> /// None /// </summary> None = 0, /// <summary> /// Light /// </summary> Light = 10, /// <summary> /// LightScattered /// </summary> LightScattered = 15, /// <summary> /// LightMedium /// </summary> LightMedium = 20, /// <summary> /// LightMediumScattered /// </summary> LightMediumScattered = 25, /// <summary> /// Medium /// </summary> Medium = 30, /// <summary> /// MediumScattered /// </summary> MediumScattered = 35, /// <summary> /// MediumHeavy /// </summary> MediumHeavy = 40, /// <summary> /// MediumHeavyScattered /// </summary> MediumHeavyScattered = 45, /// <summary> /// MediumHeavyScatteredStormy /// </summary> MediumHeavyScatteredStormy = 47, /// <summary> /// HeavyDark /// </summary> HeavyDark = 50, /// <summary> /// HeavyScattered /// </summary> HeavyScattered = 55, /// <summary> /// HeavyBright /// </summary> HeavyBright = 60, /// <summary> /// Storm /// </summary> Storm = 70, /// <summary> /// Custom /// </summary> Custom = 250, /// <summary> /// Overcast /// </summary> Overcast = 48 } /// <summary> /// Weather maker cloud profile script, contains flat and volumetric layers /// </summary> [CreateAssetMenu(fileName = "WeatherMakerCloudProfile", menuName = "WeatherMaker/Cloud Profile", order = 40)] [System.Serializable] public class WeatherMakerCloudProfileScript : ScriptableObject { /// <summary>The first, and lowest cloud layer, null for none</summary> [Header("Layers")] [Tooltip("The first, and lowest cloud layer, null for none")] public WeatherMakerCloudLayerProfileScript CloudLayer1; /// <summary>The second, and second lowest cloud layer, null for none</summary> [Tooltip("The second, and second lowest cloud layer, null for none")] public WeatherMakerCloudLayerProfileScript CloudLayer2; /// <summary>The third, and third lowest cloud layer, null for none</summary> [Tooltip("The third, and third lowest cloud layer, null for none")] public WeatherMakerCloudLayerProfileScript CloudLayer3; /// <summary>The fourth, and highest cloud layer, null for none</summary> [Tooltip("The fourth, and highest cloud layer, null for none")] public WeatherMakerCloudLayerProfileScript CloudLayer4; /// <summary>Allow a single layer of volumetric clouds. In the future, more volumetric layers might be supported</summary> [Tooltip("Allow a single layer of volumetric clouds. In the future, more volumetric layers might be supported")] public WeatherMakerCloudVolumetricProfileScript CloudLayerVolumetric1; /// <summary>How much to multiply directional light intensities by when clouds are showing. Ignored for volumetric clouds.</summary> [Header("Lighting - intensity")] [Tooltip("How much to multiply directional light intensities by when clouds are showing. Ignored for volumetric clouds.")] [Range(0.0f, 1.0f)] public float DirectionalLightIntensityMultiplier = 1.0f; /// <summary>How much the clouds reduce directional light scattering. Affects fog and other volumetric effects.</summary> [Tooltip("How much the clouds reduce directional light scattering. Affects fog and other volumetric effects.")] [Range(0.0f, 1.0f)] public float DirectionalLightScatterMultiplier = 1.0f; /// <summary>How much clouds affect directional light intensity, lower values ensure no reduction. Ignored for volumetric clouds.</summary> [Tooltip("How much clouds affect directional light intensity, lower values ensure no reduction. Ignored for volumetric clouds.")] [Range(0.0f, 3.0f)] public float CloudLightStrength = 1.0f; /// <summary>Set a custom weather map texture, bypassing the auto-generated weather map</summary> [Header("Weather map (volumetric only)")] [Tooltip("Set a custom weather map texture, bypassing the auto-generated weather map")] public Texture WeatherMapRenderTextureOverride; /// <summary>Set a custom weather map texture mask, this will mask out all areas of the weather map based on lower alpha values.</summary> [Tooltip("Set a custom weather map texture mask, this will mask out all areas of the weather map based on lower alpha values.")] public Texture WeatherMapRenderTextureMask; /// <summary>Velocity of weather map mask in uv coordinates (0 - 1)</summary> [Tooltip("Velocity of weather map mask in uv coordinates (0 - 1)")] public Vector2 WeatherMapRenderTextureMaskVelocity; /// <summary>Offset of weather map mask (0 - 1). Velocity is applied automatically but you can set manually as well.</summary> [Tooltip("Offset of weather map mask (0 - 1). Velocity is applied automatically but you can set manually as well.")] public Vector2 WeatherMapRenderTextureMaskOffset; /// <summary>Clamp for weather map mask offset to ensure that it does not go too far out of bounds.</summary> [Tooltip("Clamp for weather map mask offset to ensure that it does not go too far out of bounds.")] public Vector2 WeatherMapRenderTextureMaskOffsetClamp = new Vector2(-1.1f, 1.1f); /// <summary>World scale.</summary> [Tooltip("World scale.")] [Range(0.000001f, 0.001f)] public float WorldScale = 0.00001f; /// <summary>Noise scale (x).</summary> [SingleLine("Noise scale (x).")] public RangeOfFloats NoiseScaleX = new RangeOfFloats(1.0f, 1.0f); /// <summary>Noise scale (y).</summary> [SingleLine("Noise scale (y).")] public RangeOfFloats NoiseScaleY = new RangeOfFloats(1.0f, 1.0f); /// <summary>Weather map cloud coverage velocity.</summary> [Tooltip("Weather map cloud coverage velocity.")] [Header("Coverage")] public Vector3 WeatherMapCloudCoverageVelocity = new Vector3(11.0f, 15.0f, 0.0f); /// <summary>Amount of noise to apply to weather map cloud coverage. 0 = all perlin, 1 = all worley.</summary> [MinMaxSlider(0.0f, 1.0f, "Amount of noise to apply to weather map cloud coverage. 0 = all perlin, 1 = all worley.")] public RangeOfFloats WeatherMapCloudCoverageNoiseType = new RangeOfFloats(0.0f, 0.0f); /// <summary>Scale of cloud coverage. Higher values produce smaller clouds.</summary> [MinMaxSlider(0.01f, 100.0f, "Scale of cloud coverage. Higher values produce smaller clouds.")] public RangeOfFloats WeatherMapCloudCoverageScale = new RangeOfFloats(4.0f, 16.0f); /// <summary>Rotation of cloud coverage. Rotates coverage map around center of weather map.</summary> [MinMaxSlider(-360.0f, 360.0f, "Rotation of cloud coverage. Rotates coverage map around center of weather map.")] public RangeOfFloats WeatherMapCloudCoverageRotation = new RangeOfFloats(-30.0f, 30.0f); /// <summary>Cloud coverage adder. Higher values create more cloud coverage.</summary> [MinMaxSlider(-1.0f, 1.0f, "Cloud coverage adder. Higher values create more cloud coverage.")] public RangeOfFloats WeatherMapCloudCoverageAdder = new RangeOfFloats { Minimum = 0.0f, Maximum = 0.0f }; /// <summary>Cloud coverage power. Higher values create more firm cloud coverage edges.</summary> [MinMaxSlider(0.0f, 16.0f, "Cloud coverage power. Higher values create more firm cloud coverage edges.")] public RangeOfFloats WeatherMapCloudCoveragePower = new RangeOfFloats { Minimum = 1.0f, Maximum = 1.0f }; /// <summary>Weather map cloud coverage warp, min values. X = warp noise scale x, Y = warp noise scale y, Z = warp noise scale x influence (0-1), W = warp noise scale y influence (0-1).</summary> [SingleLine("Weather map cloud coverage warp, min values. X = warp noise scale x, Y = warp noise scale y, Z = warp noise scale x influence (0-1), W = warp noise scale y influence (0-1).")] public Vector4 WeatherMapCloudCoverageWarpMin = Vector4.zero; [System.NonSerialized] internal Vector4 weatherMapCloudCoverageWarpMinPrev = Vector4.zero; /// <summary>Weather map cloud coverage warp, max values. X = warp noise scale x, Y = warp noise scale y, Z = warp noise scale x influence (0-1), W = warp noise scale y influence (0-1).</summary> [SingleLine("Weather map cloud coverage warp, max values. X = warp noise scale x, Y = warp noise scale y, Z = warp noise scale x influence (0-1), W = warp noise scale y influence (0-1).")] public Vector4 WeatherMapCloudCoverageWarpMax = Vector4.zero; [System.NonSerialized] internal Vector4 weatherMapCloudCoverageWarpMaxPrev = Vector4.zero; [System.NonSerialized] private Vector4? weatherMapCloudCoverageWarp; internal Vector4 WeatherMapCloudCoverageWarp { get { if (weatherMapCloudCoverageWarp == null) { float l1 = Mathf.Pow(UnityEngine.Random.value, 2.0f); float l2 = Mathf.Pow(UnityEngine.Random.value, 2.0f); weatherMapCloudCoverageWarp = new Vector4 ( UnityEngine.Random.Range(WeatherMapCloudCoverageWarpMin.x, WeatherMapCloudCoverageWarpMax.x), UnityEngine.Random.Range(WeatherMapCloudCoverageWarpMin.y, WeatherMapCloudCoverageWarpMax.y), Mathf.Lerp(WeatherMapCloudCoverageWarpMin.z, WeatherMapCloudCoverageWarpMax.z, l1), Mathf.Lerp(WeatherMapCloudCoverageWarpMin.w, WeatherMapCloudCoverageWarpMax.w, l2) ); weatherMapCloudCoverageWarpMinPrev = WeatherMapCloudCoverageWarpMin; weatherMapCloudCoverageWarpMaxPrev = WeatherMapCloudCoverageWarpMax; } return weatherMapCloudCoverageWarp.Value; } set { weatherMapCloudCoverageWarp = value; weatherMapCloudCoverageWarpMinPrev = WeatherMapCloudCoverageWarpMin; weatherMapCloudCoverageWarpMaxPrev = WeatherMapCloudCoverageWarpMax; } } /// <summary>Weather map cloud coverage negation velocity, xy units per second, z change per second</summary> [Tooltip("Weather map cloud coverage negation velocity, xy units per second, z change per second")] [Header("Coverage Negation")] public Vector3 WeatherMapCloudCoverageNegationVelocity = new Vector3(0.0f, 0.0f, 0.0f); /// <summary>Scale of cloud coverage negation. 0 for none. Higher values produce smaller negation areas.</summary> [MinMaxSlider(0.0f, 100.0f, "Scale of cloud coverage negation . Higher values produce smaller negation areas.")] public RangeOfFloats WeatherMapCloudCoverageNegationScale = new RangeOfFloats(1.0f, 1.0f); /// <summary>Rotation of cloud coverage negation. Rotates coverage negation map around center of weather map.</summary> [MinMaxSlider(-360.0f, 360.0f, "Rotation of cloud coverage negation. Rotates coverage negation map around center of weather map.")] public RangeOfFloats WeatherMapCloudCoverageNegationRotation = new RangeOfFloats(-30.0f, 30.0f); /// <summary>Cloud coverage negation adder. Higher values create more cloud coverage negation.</summary> [MinMaxSlider(-1.0f, 1.0f, "Cloud coverage negation adder. Higher values create more cloud coverage negation.")] public RangeOfFloats WeatherMapCloudCoverageNegationAdder = new RangeOfFloats { Minimum = -1.0f, Maximum = -1.0f }; /// <summary>Cloud coverage negation power. Higher values create more firm cloud coverage negation edges.</summary> [MinMaxSlider(0.0f, 16.0f, "Cloud coverage negation power. Higher values create more firm cloud coverage negation edges.")] public RangeOfFloats WeatherMapCloudCoverageNegationPower = new RangeOfFloats { Minimum = 1.0f, Maximum = 1.0f }; /// <summary>Max cloud coverage negation offset. Moves the negation noise around.</summary> //[SingleLine("Cloud coverage negation adder. Higher values create more cloud coverage negation.")] //public Vector2 WeatherMapCloudCoverageNegationOffset = new Vector2(5000.0f, 50000.0f); //[System.NonSerialized] //internal Vector2 weatherMapCloudCoverageNegationOffsetCalculated; /// <summary>Weather map cloud coverage negation warp, min values. X = warp noise scale x, Y = warp noise scale y, Z = warp noise scale x influence (0-1), W = warp noise scale y influence (0-1).</summary> [SingleLine("Weather map cloud coverage negation warp, min values. X = warp noise scale x, Y = warp noise scale y, Z = warp noise scale x influence (0-1), W = warp noise scale y influence (0-1).")] public Vector4 WeatherMapCloudCoverageNegationWarpMin = Vector4.zero; [System.NonSerialized] internal Vector4 weatherMapCloudCoverageNegationWarpMinPrev = Vector4.zero; /// <summary>Weather map cloud coverage negation warp, max values. X = warp noise scale x, Y = warp noise scale y, Z = warp noise scale x influence (0-1), W = warp noise scale y influence (0-1).</summary> [SingleLine("Weather map cloud coverage negation warp, max values. X = warp noise scale x, Y = warp noise scale y, Z = warp noise scale x influence (0-1), W = warp noise scale y influence (0-1).")] public Vector4 WeatherMapCloudCoverageNegationWarpMax = Vector4.zero; [System.NonSerialized] internal Vector4 weatherMapCloudCoverageNegationWarpMaxPrev = Vector4.zero; [System.NonSerialized] private Vector4? weatherMapCloudCoverageNegationWarp; internal Vector4 WeatherMapCloudCoverageNegationWarp { get { if (weatherMapCloudCoverageNegationWarp == null) { float l1 = Mathf.Pow(UnityEngine.Random.value, 2.0f); float l2 = Mathf.Pow(UnityEngine.Random.value, 2.0f); weatherMapCloudCoverageNegationWarp = new Vector4 ( UnityEngine.Random.Range(WeatherMapCloudCoverageNegationWarpMin.x, WeatherMapCloudCoverageNegationWarpMax.x), UnityEngine.Random.Range(WeatherMapCloudCoverageNegationWarpMin.y, WeatherMapCloudCoverageNegationWarpMax.y), Mathf.Lerp(WeatherMapCloudCoverageNegationWarpMin.z, WeatherMapCloudCoverageNegationWarpMax.z, l1), Mathf.Lerp(WeatherMapCloudCoverageNegationWarpMin.w, WeatherMapCloudCoverageNegationWarpMax.w, l2) ); weatherMapCloudCoverageNegationWarpMinPrev = WeatherMapCloudCoverageNegationWarpMin; weatherMapCloudCoverageNegationWarpMaxPrev = WeatherMapCloudCoverageNegationWarpMax; } return weatherMapCloudCoverageNegationWarp.Value; } set { weatherMapCloudCoverageNegationWarp = value; weatherMapCloudCoverageNegationWarpMinPrev = WeatherMapCloudCoverageNegationWarpMin; weatherMapCloudCoverageNegationWarpMaxPrev = WeatherMapCloudCoverageNegationWarpMax; } } /// <summary>Weather map cloud Density velocity, xy units per second, z change per second</summary> [Tooltip("Weather map cloud density velocity, xy units per second, z change per second")] [Header("Density")] public Vector3 WeatherMapCloudDensityVelocity = new Vector3(11.0f, 15.0f, 0.0f); /// <summary>Amount of noise to apply to weather map cloud Density. 0 = all perlin, 1 = all worley.</summary> [MinMaxSlider(0.0f, 1.0f, "Amount of noise to apply to weather map cloud Density. 0 = all perlin, 1 = all worley.")] public RangeOfFloats WeatherMapCloudDensityNoiseType = new RangeOfFloats(1.0f, 1.0f); /// <summary>Scale of cloud Density. Higher values produce smaller clouds.</summary> [MinMaxSlider(0.01f, 100.0f, "Scale of cloud Density. Higher values produce smaller clouds.")] public RangeOfFloats WeatherMapCloudDensityScale = new RangeOfFloats(4.0f, 16.0f); /// <summary>Rotation of cloud Density. Rotates Density map around center of weather map.</summary> [MinMaxSlider(-360.0f, 360.0f, "Rotation of cloud Density. Rotates Density map around center of weather map.")] public RangeOfFloats WeatherMapCloudDensityRotation = new RangeOfFloats(-30.0f, 30.0f); /// <summary>Cloud Density adder. Higher values create more cloud Density.</summary> [MinMaxSlider(-1.0f, 1.0f, "Cloud Density adder. Higher values create more cloud Density.")] public RangeOfFloats WeatherMapCloudDensityAdder = new RangeOfFloats { Minimum = 0.0f, Maximum = 0.0f }; /// <summary>Cloud Density power. Higher values create more firm cloud Density edges.</summary> [MinMaxSlider(0.0f, 16.0f, "Cloud Density power. Higher values create more firm cloud Density edges.")] public RangeOfFloats WeatherMapCloudDensityPower = new RangeOfFloats { Minimum = 1.0f, Maximum = 1.0f }; /// <summary>Weather map cloud Density warp, min values. X = warp noise scale x, Y = warp noise scale y, Z = warp noise scale x influence (0-1), W = warp noise scale y influence (0-1).</summary> [SingleLine("Weather map cloud Density warp, min values. X = warp noise scale x, Y = warp noise scale y, Z = warp noise scale x influence (0-1), W = warp noise scale y influence (0-1).")] public Vector4 WeatherMapCloudDensityWarpMin = Vector4.zero; [System.NonSerialized] internal Vector4 weatherMapCloudDensityWarpMinPrev = Vector4.zero; /// <summary>Weather map cloud Density warp, max values. X = warp noise scale x, Y = warp noise scale y, Z = warp noise scale x influence (0-1), W = warp noise scale y influence (0-1).</summary> [SingleLine("Weather map cloud Density warp, max values. X = warp noise scale x, Y = warp noise scale y, Z = warp noise scale x influence (0-1), W = warp noise scale y influence (0-1).")] public Vector4 WeatherMapCloudDensityWarpMax = Vector4.zero; [System.NonSerialized] internal Vector4 weatherMapCloudDensityWarpMaxPrev = Vector4.zero; [System.NonSerialized] private Vector4? weatherMapCloudDensityWarp; internal Vector4 WeatherMapCloudDensityWarp { get { if (weatherMapCloudDensityWarp == null) { float l1 = Mathf.Pow(UnityEngine.Random.value, 2.0f); float l2 = Mathf.Pow(UnityEngine.Random.value, 2.0f); weatherMapCloudDensityWarp = new Vector4 ( UnityEngine.Random.Range(WeatherMapCloudDensityWarpMin.x, WeatherMapCloudDensityWarpMax.x), UnityEngine.Random.Range(WeatherMapCloudDensityWarpMin.y, WeatherMapCloudDensityWarpMax.y), Mathf.Lerp(WeatherMapCloudDensityWarpMin.z, WeatherMapCloudDensityWarpMax.z, l1), Mathf.Lerp(WeatherMapCloudDensityWarpMin.w, WeatherMapCloudDensityWarpMax.w, l2) ); weatherMapCloudDensityWarpMinPrev = WeatherMapCloudDensityWarpMin; weatherMapCloudDensityWarpMaxPrev = WeatherMapCloudDensityWarpMax; } return weatherMapCloudDensityWarp.Value; } set { weatherMapCloudDensityWarp = value; weatherMapCloudDensityWarpMinPrev = WeatherMapCloudDensityWarpMin; weatherMapCloudDensityWarpMaxPrev = WeatherMapCloudDensityWarpMax; } } /// <summary>Weather map cloud Density negation velocity, xy units per second, z change per second</summary> [Tooltip("Weather map cloud Density negation velocity, xy units per second, z change per second")] [Header("Density Negation")] public Vector3 WeatherMapCloudDensityNegationVelocity = new Vector3(0.0f, 0.0f, 0.0f); /// <summary>Scale of cloud Density negation. 0 for none. Higher values produce smaller negation areas.</summary> [MinMaxSlider(0.0f, 100.0f, "Scale of cloud Density negation . Higher values produce smaller negation areas.")] public RangeOfFloats WeatherMapCloudDensityNegationScale = new RangeOfFloats(1.0f, 1.0f); /// <summary>Rotation of cloud Density negation. Rotates Density negation map around center of weather map.</summary> [MinMaxSlider(-360.0f, 360.0f, "Rotation of cloud Density negation. Rotates Density negation map around center of weather map.")] public RangeOfFloats WeatherMapCloudDensityNegationRotation = new RangeOfFloats(-30.0f, 30.0f); /// <summary>Cloud Density negation adder. Higher values create more cloud Density negation.</summary> [MinMaxSlider(-1.0f, 1.0f, "Cloud Density negation adder. Higher values create more cloud Density negation.")] public RangeOfFloats WeatherMapCloudDensityNegationAdder = new RangeOfFloats { Minimum = -1.0f, Maximum = -1.0f }; /// <summary>Cloud Density negation power. Higher values create more firm cloud Density negation edges.</summary> [MinMaxSlider(0.0f, 16.0f, "Cloud Density negation power. Higher values create more firm cloud Density negation edges.")] public RangeOfFloats WeatherMapCloudDensityNegationPower = new RangeOfFloats { Minimum = 1.0f, Maximum = 1.0f }; /// <summary>Max cloud Density negation offset. Moves the negation noise around.</summary> //[SingleLine("Cloud Density negation adder. Higher values create more cloud Density negation.")] //public Vector2 WeatherMapCloudDensityNegationOffset = new Vector2(5000.0f, 50000.0f); //[System.NonSerialized] //internal Vector2 weatherMapCloudDensityNegationOffsetCalculated; /// <summary>Weather map cloud Density negation warp, min values. X = warp noise scale x, Y = warp noise scale y, Z = warp noise scale x influence (0-1), W = warp noise scale y influence (0-1).</summary> [SingleLine("Weather map cloud Density negation warp, min values. X = warp noise scale x, Y = warp noise scale y, Z = warp noise scale x influence (0-1), W = warp noise scale y influence (0-1).")] public Vector4 WeatherMapCloudDensityNegationWarpMin = Vector4.zero; [System.NonSerialized] internal Vector4 weatherMapCloudDensityNegationWarpMinPrev = Vector4.zero; /// <summary>Weather map cloud Density negation warp, max values. X = warp noise scale x, Y = warp noise scale y, Z = warp noise scale x influence (0-1), W = warp noise scale y influence (0-1).</summary> [SingleLine("Weather map cloud Density negation warp, max values. X = warp noise scale x, Y = warp noise scale y, Z = warp noise scale x influence (0-1), W = warp noise scale y influence (0-1).")] public Vector4 WeatherMapCloudDensityNegationWarpMax = Vector4.zero; [System.NonSerialized] internal Vector4 weatherMapCloudDensityNegationWarpMaxPrev = Vector4.zero; [System.NonSerialized] private Vector4? weatherMapCloudDensityNegationWarp; internal Vector4 WeatherMapCloudDensityNegationWarp { get { if (weatherMapCloudDensityNegationWarp == null) { float l1 = Mathf.Pow(UnityEngine.Random.value, 2.0f); float l2 = Mathf.Pow(UnityEngine.Random.value, 2.0f); weatherMapCloudDensityNegationWarp = new Vector4 ( UnityEngine.Random.Range(WeatherMapCloudDensityNegationWarpMin.x, WeatherMapCloudDensityNegationWarpMax.x), UnityEngine.Random.Range(WeatherMapCloudDensityNegationWarpMin.y, WeatherMapCloudDensityNegationWarpMax.y), Mathf.Lerp(WeatherMapCloudDensityNegationWarpMin.z, WeatherMapCloudDensityNegationWarpMax.z, l1), Mathf.Lerp(WeatherMapCloudDensityNegationWarpMin.w, WeatherMapCloudDensityNegationWarpMax.w, l2) ); weatherMapCloudDensityNegationWarpMinPrev = WeatherMapCloudDensityNegationWarpMin; weatherMapCloudDensityNegationWarpMaxPrev = WeatherMapCloudDensityNegationWarpMax; } return weatherMapCloudDensityNegationWarp.Value; } set { weatherMapCloudDensityNegationWarp = value; weatherMapCloudDensityNegationWarpMinPrev = WeatherMapCloudDensityNegationWarpMin; weatherMapCloudDensityNegationWarpMaxPrev = WeatherMapCloudDensityNegationWarpMax; } } /// <summary>Weather map cloud type velocity, xy units per second, z change per second</summary> [Tooltip("Weather map cloud type velocity, xy units per second, z change per second")] [Header("Type")] public Vector3 WeatherMapCloudTypeVelocity = new Vector3(17.0f, 10.0f, 0.0f); /// <summary>Amount of noise to apply to weather map cloud type. 0 = all perlin, 1 = all worley.</summary> [MinMaxSlider(0.0f, 1.0f, "Amount of noise to apply to weather map cloud type. 0 = all perlin, 1 = all worley.")] public RangeOfFloats WeatherMapCloudTypeNoiseType = new RangeOfFloats(0.0f, 0.0f); /// <summary>Scale of cloud types. Higher values produce more jagged clouds.</summary> [MinMaxSlider(0.01f, 100.0f, "Scale of cloud types. Higher values produce more jagged clouds.")] public RangeOfFloats WeatherMapCloudTypeScale = new RangeOfFloats(2.0f, 8.0f); /// <summary>Rotation of cloud type. Rotates cloud type map around center of weather map.</summary> [MinMaxSlider(-360.0f, 360.0f, "Rotation of cloud type. Rotates cloud type map around center of weather map.")] public RangeOfFloats WeatherMapCloudTypeRotation; /// <summary>Cloud type adder. Higher values create more cloud type.</summary> [MinMaxSlider(-1.0f, 1.0f, "Cloud type adder. Higher values create more cloud type.")] public RangeOfFloats WeatherMapCloudTypeAdder = new RangeOfFloats { Minimum = 0.0f, Maximum = 0.0f }; /// <summary>Cloud type power. Higher values create more firm cloud type edges.</summary> [MinMaxSlider(0.0f, 16.0f, "Cloud type power. Higher values create more firm cloud type edges.")] public RangeOfFloats WeatherMapCloudTypePower = new RangeOfFloats { Minimum = 1.0f, Maximum = 1.0f }; /// <summary>Weather map cloud type warp, min values. X = warp noise scale x, Y = warp noise scale y, Z = warp noise scale x influence (0-1), W = warp noise scale y influence (0-1).</summary> [SingleLine("Weather map cloud type warp, min values. X = warp noise scale x, Y = warp noise scale y, Z = warp noise scale x influence (0-1), W = warp noise scale y influence (0-1).")] public Vector4 WeatherMapCloudTypeWarpMin = Vector4.zero; [System.NonSerialized] internal Vector4 weatherMapCloudTypeWarpMinPrev = Vector4.zero; /// <summary>Weather map cloud type warp, max values. X = warp noise scale x, Y = warp noise scale y, Z = warp noise scale x influence (0-1), W = warp noise scale y influence (0-1).</summary> [SingleLine("Weather map cloud type warp, max values. X = warp noise scale x, Y = warp noise scale y, Z = warp noise scale x influence (0-1), W = warp noise scale y influence (0-1).")] public Vector4 WeatherMapCloudTypeWarpMax = Vector4.zero; [System.NonSerialized] internal Vector4 weatherMapCloudTypeWarpMaxPrev = Vector4.zero; [System.NonSerialized] private Vector4? weatherMapCloudTypeWarp; internal Vector4 WeatherMapCloudTypeWarp { get { if (weatherMapCloudTypeWarp == null) { float l1 = Mathf.Pow(UnityEngine.Random.value, 2.0f); float l2 = Mathf.Pow(UnityEngine.Random.value, 2.0f); weatherMapCloudTypeWarp = new Vector4 ( UnityEngine.Random.Range(WeatherMapCloudTypeWarpMin.x, WeatherMapCloudTypeWarpMax.x), UnityEngine.Random.Range(WeatherMapCloudTypeWarpMin.y, WeatherMapCloudTypeWarpMax.y), Mathf.Lerp(WeatherMapCloudTypeWarpMin.z, WeatherMapCloudTypeWarpMax.z, l1), Mathf.Lerp(WeatherMapCloudTypeWarpMin.w, WeatherMapCloudTypeWarpMax.w, l2) ); weatherMapCloudTypeWarpMinPrev = WeatherMapCloudTypeWarpMin; weatherMapCloudTypeWarpMaxPrev = WeatherMapCloudTypeWarpMax; } return weatherMapCloudTypeWarp.Value; } set { weatherMapCloudTypeWarp = value; weatherMapCloudTypeWarpMinPrev = WeatherMapCloudTypeWarpMin; weatherMapCloudTypeWarpMaxPrev = WeatherMapCloudTypeWarpMax; } } /// <summary>Weather map cloud type negation velocity, xy units per second, z change per second</summary> [Tooltip("Weather map cloud type negation velocity, xy units per second, z change per second")] [Header("Type Negation")] public Vector3 WeatherMapCloudTypeNegationVelocity = new Vector3(0.0f, 0.0f, 0.0f); /// <summary>Scale of cloud type negation. 0 for none. Higher values produce smaller negation areas.</summary> [MinMaxSlider(0.0f, 100.0f, "Scale of cloud type negation . Higher values produce smaller negation areas.")] public RangeOfFloats WeatherMapCloudTypeNegationScale = new RangeOfFloats(1.0f, 1.0f); /// <summary>Rotation of cloud type negation. Rotates type negation map around center of weather map.</summary> [MinMaxSlider(-360.0f, 360.0f, "Rotation of cloud type negation. Rotates type negation map around center of weather map.")] public RangeOfFloats WeatherMapCloudTypeNegationRotation = new RangeOfFloats(-30.0f, 30.0f); /// <summary>Cloud type negation adder. Higher values create more cloud type negation.</summary> [MinMaxSlider(-1.0f, 1.0f, "Cloud type negation adder. Higher values create more cloud type negation.")] public RangeOfFloats WeatherMapCloudTypeNegationAdder = new RangeOfFloats { Minimum = -1.0f, Maximum = -1.0f }; /// <summary>Cloud type negation power. Higher values create more firm cloud type negation edges.</summary> [MinMaxSlider(0.0f, 16.0f, "Cloud type negation power. Higher values create more firm cloud type negation edges.")] public RangeOfFloats WeatherMapCloudTypeNegationPower = new RangeOfFloats { Minimum = 1.0f, Maximum = 1.0f }; /// <summary>Max cloud type negation offset. Moves the negation noise around.</summary> //[SingleLine("Cloud type negation adder. Higher values create more cloud type negation.")] //public Vector2 WeatherMapCloudTypeNegationOffset = new Vector2(5000.0f, 50000.0f); //[System.NonSerialized] //internal Vector2 weatherMapCloudTypeNegationOffsetCalculated; /// <summary>Weather map cloud type negation warp, min values. X = warp noise scale x, Y = warp noise scale y, Z = warp noise scale x influence (0-1), W = warp noise scale y influence (0-1).</summary> [SingleLine("Weather map cloud type negation warp, min values. X = warp noise scale x, Y = warp noise scale y, Z = warp noise scale x influence (0-1), W = warp noise scale y influence (0-1).")] public Vector4 WeatherMapCloudTypeNegationWarpMin = Vector4.zero; [System.NonSerialized] internal Vector4 weatherMapCloudTypeNegationWarpMinPrev = Vector4.zero; /// <summary>Weather map cloud type negation warp, max values. X = warp noise scale x, Y = warp noise scale y, Z = warp noise scale x influence (0-1), W = warp noise scale y influence (0-1).</summary> [SingleLine("Weather map cloud type negation warp, max values. X = warp noise scale x, Y = warp noise scale y, Z = warp noise scale x influence (0-1), W = warp noise scale y influence (0-1).")] public Vector4 WeatherMapCloudTypeNegationWarpMax = Vector4.zero; [System.NonSerialized] internal Vector4 weatherMapCloudTypeNegationWarpMaxPrev = Vector4.zero; [System.NonSerialized] private Vector4? weatherMapCloudTypeNegationWarp; internal Vector4 WeatherMapCloudTypeNegationWarp { get { if (weatherMapCloudTypeNegationWarp == null) { float l1 = Mathf.Pow(UnityEngine.Random.value, 2.0f); float l2 = Mathf.Pow(UnityEngine.Random.value, 2.0f); weatherMapCloudTypeNegationWarp = new Vector4 ( UnityEngine.Random.Range(WeatherMapCloudTypeNegationWarpMin.x, WeatherMapCloudTypeNegationWarpMax.x), UnityEngine.Random.Range(WeatherMapCloudTypeNegationWarpMin.y, WeatherMapCloudTypeNegationWarpMax.y), Mathf.Lerp(WeatherMapCloudTypeNegationWarpMin.z, WeatherMapCloudTypeNegationWarpMax.z, l1), Mathf.Lerp(WeatherMapCloudTypeNegationWarpMin.w, WeatherMapCloudTypeNegationWarpMax.w, l2) ); weatherMapCloudTypeNegationWarpMinPrev = WeatherMapCloudTypeNegationWarpMin; weatherMapCloudTypeNegationWarpMaxPrev = WeatherMapCloudTypeNegationWarpMax; } return weatherMapCloudTypeNegationWarp.Value; } set { weatherMapCloudTypeNegationWarp = value; weatherMapCloudTypeNegationWarpMinPrev = WeatherMapCloudTypeNegationWarpMin; weatherMapCloudTypeNegationWarpMaxPrev = WeatherMapCloudTypeNegationWarpMax; } } /// <summary>Cloud height.</summary> [Header("Planet (volumetric only)")] [SingleLine("Cloud height.")] public RangeOfFloats CloudHeight = new RangeOfFloats { Minimum = 1500, Maximum = 2000 }; /// <summary>Cloud height top - clouds extend from CloudHeight to this value.</summary> [SingleLine("Cloud height top - clouds extend from CloudHeight to this value.")] public RangeOfFloats CloudHeightTop = new RangeOfFloats { Minimum = 4000, Maximum = 5000 }; /// <summary>Planet radius for sphere cloud mapping. 1200000.0 seems to work well.</summary> [Tooltip("Planet radius for sphere cloud mapping. 1200000.0 seems to work well.")] public float CloudPlanetRadius = 1200000.0f; /// <summary> /// Checks whether clouds are enabled /// </summary> public bool CloudsEnabled { get; private set; } /// <summary> /// Sum of cloud cover, max of 1 /// </summary> public float CloudCoverTotal { get; private set; } /// <summary> /// Sum of cloud density, max of 1 /// </summary> public float CloudDensityTotal { get; private set; } /// <summary> /// Sum of cloud light absorption, max of 1 /// </summary> public float CloudLightAbsorptionTotal { get; private set; } /// <summary> /// Aurora profile /// </summary> public WeatherMakerAuroraProfileScript AuroraProfile { get; set; } /// <summary> /// Atmosphere profile /// </summary> public WeatherMakerAtmosphereProfileScript AtmosphereProfile { get; set; } /// <summary> /// Directional light block /// </summary> public float CloudDirectionalLightDirectBlock { get; private set; } private Vector3 cloudNoiseVelocityAccum1; private Vector3 cloudNoiseVelocityAccum2; private Vector3 cloudNoiseVelocityAccum3; private Vector3 cloudNoiseVelocityAccum4; private Vector3 velocityAccumCoverage; private Vector3 velocityAccumDensity; private Vector3 velocityAccumType; private Vector3 velocityAccumCoverageNegation; private Vector3 velocityAccumDensityNegation; private Vector3 velocityAccumTypeNegation; internal bool isAnimating; //unused currently //internal Vector3 cloudCoverageOffset; //internal Vector3 cloudCoverageNegationOffset; //internal Vector3 cloudTypeOffset; //internal Vector3 cloudTypeNegationOffset; private readonly WeatherMakerShaderPropertiesScript shaderProps = new WeatherMakerShaderPropertiesScript(); private void SetShaderVolumetricCloudShaderProperties(WeatherMakerShaderPropertiesScript props, Texture weatherMap, WeatherMakerCelestialObjectScript sun, Camera camera) { float sunLookup = sun.GetGradientLookup(); float ambientMultiplier = (WeatherMakerFullScreenCloudsScript.Instance == null || WeatherMakerFullScreenCloudsScript.Instance.GlobalAmbientMultiplierGradient == null || WeatherMakerFullScreenCloudsScript.Instance.GlobalAmbientMultiplierGradient.alphaKeys.Length == 0 ? 1.0f : WeatherMakerFullScreenCloudsScript.Instance.GlobalAmbientMultiplierGradient.Evaluate(sunLookup).a); props.SetTexture(WMS._WeatherMakerWeatherMapTexture, weatherMap); props.SetVector(WMS._WeatherMakerWeatherMapScale, new Vector4(NoiseScaleX.LastValue, NoiseScaleY.LastValue, WorldScale, (1.0f / WorldScale) / (float)weatherMap.width)); props.SetFloat(WMS._CloudInvFade, 20.0f * (1.0f / camera.farClipPlane)); props.SetFloat(WMS._CloudCoverVolumetricMinimumForCloud, CloudLayerVolumetric1.CloudCoverMinimum); props.SetFloat(WMS._CloudCoverVolumetric, CloudLayerVolumetric1.CloudCover.LastValue); props.SetFloat(WMS._CloudCoverSecondaryVolumetric, CloudLayerVolumetric1.CloudCoverSecondary.LastValue); props.SetFloat(WMS._CloudDensityVolumetric, CloudLayerVolumetric1.CloudDensity.LastValue); props.SetFloat(WMS._CloudDensitySecondaryVolumetric, CloudLayerVolumetric1.CloudDensitySecondary.LastValue); props.SetFloat(WMS._CloudTypeVolumetric, CloudLayerVolumetric1.CloudType.LastValue); props.SetFloat(WMS._CloudTypeSecondaryVolumetric, CloudLayerVolumetric1.CloudTypeSecondary.LastValue); props.SetFloat(WMS._CloudNoiseScalarVolumetric, CloudLayerVolumetric1.CloudNoiseShapeScalar.LastValue * WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudNoiseMultiplier); props.SetVector(WMS._CloudWeights, CloudLayerVolumetric1.CloudNoiseShapeWeights); props.SetInt(WMS._CloudDirLightRaySampleCount, WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudDirLightRaySampleCount); props.SetFloat(WMS._CloudPlanetRadiusVolumetric, CloudPlanetRadius); props.SetTexture(WMS._CloudNoiseShapeVolumetric, CloudLayerVolumetric1.CloudNoiseShape); props.SetTexture(WMS._CloudNoiseDetailVolumetric, CloudLayerVolumetric1.CloudNoiseDetail); props.SetTexture(WMS._CloudNoiseCurlVolumetric, CloudLayerVolumetric1.CloudNoiseCurl); props.SetVector(WMS._CloudShapeAnimationVelocity, CloudLayerVolumetric1.CloudShapeAnimationVelocity); props.SetVector(WMS._CloudDetailAnimationVelocity, CloudLayerVolumetric1.CloudDetailAnimationVelocity); Vector4 cloudNoiseScale = new Vector4(CloudLayerVolumetric1.CloudNoiseShapeScale.LastValue, CloudLayerVolumetric1.CloudNoiseDetailScale.LastValue, CloudLayerVolumetric1.CloudNoiseDetailCurlScale.LastValue, CloudLayerVolumetric1.CloudNoiseDetailCurlIntensity.LastValue); props.SetVector(WMS._CloudNoiseScaleVolumetric, cloudNoiseScale); props.SetFloat(WMS._CloudNoiseDetailPowerVolumetric, CloudLayerVolumetric1.CloudNoiseDetailPower.LastValue); props.SetFloat(WMS._CloudNoiseDetailHeightMultiplier, CloudLayerVolumetric1.CloudNoiseDetailHeightMultiplier.LastValue); // cloud shaping props.SetFloat(WMS._CloudBottomFade, CloudLayerVolumetric1.CloudBottomFade.LastValue); props.SetFloat(WMS._CloudTopFade, CloudLayerVolumetric1.CloudTopFade.LastValue); props.SetFloat(WMS._CloudRoundnessVolumetric, CloudLayerVolumetric1.CloudRoundness.LastValue); props.SetFloat(WMS._CloudRoundnessVolumetricInv, 1.0f - CloudLayerVolumetric1.CloudRoundness.LastValue); if (WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudAllowAnvils) { props.SetFloat(WMS._CloudAnvilStrength, CloudLayerVolumetric1.CloudAnvilStrength.LastValue); props.SetFloat(WMS._CloudAnvilStart, CloudLayerVolumetric1.CloudAnvilStart.LastValue); } else { props.SetFloat(WMS._CloudAnvilStrength, 0.0f); props.SetFloat(WMS._CloudAnvilStart, 1.0f); } // lower cloud level sphere // assign global shader so shadow map can see them props.SetFloat(WMS._CloudStartVolumetric, CloudHeight.LastValue); props.SetFloat(WMS._CloudStartInverseVolumetric, 1.0f / CloudHeight.LastValue); props.SetFloat(WMS._CloudStartSquaredVolumetric, CloudHeight.LastValue * CloudHeight.LastValue); props.SetFloat(WMS._CloudPlanetStartVolumetric, CloudHeight.LastValue + CloudPlanetRadius); props.SetFloat(WMS._CloudPlanetStartSquaredVolumetric, Mathf.Pow(CloudHeight.LastValue + CloudPlanetRadius, 2.0f)); // height of top minus bottom cloud layer float height = CloudHeightTop.LastValue - CloudHeight.LastValue; props.SetFloat(WMS._CloudHeightVolumetric, height); props.SetFloat(WMS._CloudHeightInverseVolumetric, 1.0f / height); height *= height; props.SetFloat(WMS._CloudHeightSquaredVolumetric, height); props.SetFloat(WMS._CloudHeightSquaredInverseVolumetric, 1.0f / height); // upper cloud level sphere props.SetFloat(WMS._CloudEndVolumetric, CloudHeightTop.LastValue); props.SetFloat(WMS._CloudEndInverseVolumetric, CloudHeightTop.LastValue); height = CloudHeightTop.LastValue * CloudHeightTop.LastValue; props.SetFloat(WMS._CloudEndSquaredVolumetric, height); props.SetFloat(WMS._CloudEndSquaredInverseVolumetric, 1.0f / height); props.SetFloat(WMS._CloudPlanetEndVolumetric, CloudHeightTop.LastValue + CloudPlanetRadius); props.SetFloat(WMS._CloudPlanetEndSquaredVolumetric, Mathf.Pow(CloudHeightTop.LastValue + CloudPlanetRadius, 2.0f)); props.SetFloat(WMS._CloudPlanetRadiusNegativeVolumetric, -CloudPlanetRadius); props.SetFloat(WMS._CloudPlanetRadiusSquaredVolumetric, CloudPlanetRadius * CloudPlanetRadius); props.SetVector(WMS._CloudHenyeyGreensteinPhaseVolumetric, CloudLayerVolumetric1.CloudHenyeyGreensteinPhase); props.SetFloat(WMS._CloudRayOffsetVolumetric, CloudLayerVolumetric1.CloudRayOffset + (WeatherMakerFullScreenCloudsScript.Instance == null ? 0.0f : WeatherMakerFullScreenCloudsScript.Instance.CloudRayOffset)); props.SetVector(WMS._CloudGradientStratus, CloudLayerVolumetric1.CloudGradientStratusVector); props.SetVector(WMS._CloudGradientStratoCumulus, CloudLayerVolumetric1.CloudGradientStratoCumulusVector); props.SetVector(WMS._CloudGradientCumulus, CloudLayerVolumetric1.CloudGradientCumulusVector); props.SetVector(WMS._CloudNoiseSampleCountVolumetric, WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudSampleCount.ToVector2()); props.SetFloat(WMS._CloudRaymarchMaybeInCloudStepMultiplier, WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudRaymarchMaybeInCloudStepMultiplier); props.SetFloat(WMS._CloudRaymarchInCloudStepMultiplier, WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudRaymarchInCloudStepMultiplier); props.SetFloat(WMS._CloudNoiseLod, WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudFlatLayerLod); props.SetVector(WMS._CloudNoiseLodVolumetric, WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudLod.ToVector2()); props.SetColor(WMS._CloudColorVolumetric, CloudLayerVolumetric1.CloudColor); props.SetColor(WMS._CloudDirColorVolumetric, CloudLayerVolumetric1.CloudDirLightGradientColorColor); props.SetColor(WMS._CloudEmissionColorVolumetric, CloudLayerVolumetric1.CloudEmissionGradientColorColor); props.SetFloat(WMS._CloudDirLightMultiplierVolumetric, CloudLayerVolumetric1.CloudDirLightMultiplier); props.SetFloat(WMS._WeatherMakerDirectionalLightScatterMultiplier, DirectionalLightScatterMultiplier); props.SetFloat(WMS._CloudLightDitherLevel, CloudLayerVolumetric1.CloudLightDitherLevel); props.SetFloat(WMS._CloudPointSpotLightMultiplierVolumetric, CloudLayerVolumetric1.CloudPointSpotLightMultiplier); props.SetFloat(WMS._CloudAmbientGroundIntensityVolumetric, CloudLayerVolumetric1.CloudAmbientGroundIntensity * ambientMultiplier); props.SetFloat(WMS._CloudAmbientSkyIntensityVolumetric, CloudLayerVolumetric1.CloudAmbientSkyIntensity * ambientMultiplier); float backgroundSkyStyle = (WeatherMakerSkySphereScript.Instance == null || WeatherMakerSkySphereScript.Instance.SkySphereProfile == null || WeatherMakerSkySphereScript.Instance.SkySphereProfile.SkyMode == WeatherMakeSkyMode.ProceduralUnityStyle || WeatherMakerSkySphereScript.Instance.SkySphereProfile.SkyMode == WeatherMakeSkyMode.ProceduralTexturedUnityStyle ? 0.0f : 1.0f); props.SetFloat(WMS._CloudAmbientSkyHeightMultiplierVolumetric, CloudLayerVolumetric1.CloudAmbientSkyHeightMultiplier); props.SetFloat(WMS._CloudAmbientGroundHeightMultiplierVolumetric, CloudLayerVolumetric1.CloudAmbientGroundHeightMultiplier * ambientMultiplier); props.SetFloat(WMS._CloudAmbientShadowVolumetric, CloudLayerVolumetric1.CloudAmbientShadow * 0.333f); props.SetFloat(WMS._CloudLightAbsorptionVolumetric, CloudLayerVolumetric1.CloudLightAbsorption * WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudAbsorptionMultiplier); props.SetFloat(WMS._CloudDirLightIndirectMultiplierVolumetric, CloudLayerVolumetric1.CloudDirLightIndirectMultiplier); props.SetFloat(WMS._CloudPowderMultiplierVolumetric, CloudLayerVolumetric1.CloudPowderMultiplier.LastValue); props.SetFloat(WMS._CloudOpticalDistanceMultiplierVolumetric, CloudLayerVolumetric1.CloudOpticalDistanceMultiplier); props.SetFloat(WMS._CloudDirLightSampleCount, WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudDirLightSampleCount); props.SetFloat(WMS._CloudLightStepMultiplierVolumetric, WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudDirLightStepMultiplier); Vector4 fade = CloudLayerVolumetric1.CloudHorizonFade; const float horizonDawnDuskMultiplier = 0.5f; const float horizonNightMultiplier = 0.0f; float horizonDawnDusk = WeatherMakerDayNightCycleManagerScript.Instance.DawnDuskMultiplier * horizonDawnDuskMultiplier; float horizonNight = WeatherMakerDayNightCycleManagerScript.Instance.NightMultiplier * horizonNightMultiplier; float horizonTotal = 1.0f - Mathf.Min(1.0f, horizonDawnDusk + horizonNight); fade.x = Mathf.Clamp(fade.x, 0.0f, 16.0f); fade.y = Mathf.Clamp(fade.y, 0.1f, 16.0f); fade.z = Mathf.Clamp(fade.z, 0.1f, 16.0f); fade.w = Mathf.Clamp(fade.w * horizonTotal, 0.0f, 1.0f); props.SetVector(WMS._CloudHorizonFadeVolumetric, fade); // increase light steps as light goes to horizon for more realistic lighting WeatherMakerCelestialObjectScript primaryLight = WeatherMakerLightManagerScript.Instance.PrimaryDirectionalLight; float lightGradient = (primaryLight == null ? 1.0f : Mathf.Min(1.0f, 4.0f * Mathf.Abs(primaryLight.transform.forward.y))); lightGradient *= lightGradient; lightGradient *= lightGradient; int stepCount = WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudDirLightSampleCount; float stepCountMultiplier = WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudDirLightHorizonMultiplier; float lightStepCountMultiplier = Mathf.Lerp(stepCountMultiplier, 1.0f, lightGradient); int maxStepCount = Mathf.Min(16, Mathf.RoundToInt((float)stepCount * lightStepCountMultiplier)); props.SetFloat(WMS._CloudDirLightSampleCount, maxStepCount); props.SetFloat(WMS._CloudLightStepMultiplierVolumetric, WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudDirLightStepMultiplier); props.SetFloat(WMS._CloudLightRadiusMultiplierVolumetric, WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudDirLightRadiusMultiplier); props.SetFloat(WMS._CloudLightDistantMultiplierVolumetric, WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudLightDistantMultiplier); props.SetFloat(WMS._CloudRayDitherVolumetric, WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudRayDither * CloudLayerVolumetric1.CloudDitherMultiplier.LastValue); props.SetFloat(WMS._CloudRaymarchMultiplierVolumetric, WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudRaymarchMultiplier); props.SetVector(WMS._CloudRayMarchParameters, CloudLayerVolumetric1.CloudRayMarchParameters); // sample details for dir light ray march if max lod is small props.SetFloat(WMS._CloudDirLightLod, WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudDirLightLod); props.SetInt(WMS._CloudRaymarchSampleDetailsForDirLight, WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudDirLightSampleDetails ? 1 : 0); props.SetFloat(WMS._WeatherMakerCloudShadowSampleShadowMap, WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudShadowMapMinPower); // flat clouds float cloudCover1 = 0.0f; float cloudCover2 = 0.0f; float cloudCover3 = 0.0f; float cloudCover4 = 0.0f; if (isAnimating || CloudLayerVolumetric1 == null || CloudLayerVolumetric1.CloudCover.Maximum == 0.0f || !WeatherMakerScript.Instance.PerformanceProfile.EnableVolumetricClouds || (CloudLayerVolumetric1.FlatLayerMask & WeatherMakerVolumetricCloudsFlatLayerMask.One) == WeatherMakerVolumetricCloudsFlatLayerMask.One) { cloudCover1 = CloudLayer1.CloudCover.LastValue; } if (isAnimating || CloudLayerVolumetric1 == null || CloudLayerVolumetric1.CloudCover.Maximum == 0.0f || !WeatherMakerScript.Instance.PerformanceProfile.EnableVolumetricClouds || (CloudLayerVolumetric1.FlatLayerMask & WeatherMakerVolumetricCloudsFlatLayerMask.Two) == WeatherMakerVolumetricCloudsFlatLayerMask.Two) { cloudCover2 = CloudLayer2.CloudCover.LastValue; } if (isAnimating || CloudLayerVolumetric1 == null || CloudLayerVolumetric1.CloudCover.Maximum == 0.0f || !WeatherMakerScript.Instance.PerformanceProfile.EnableVolumetricClouds || (CloudLayerVolumetric1.FlatLayerMask & WeatherMakerVolumetricCloudsFlatLayerMask.Three) == WeatherMakerVolumetricCloudsFlatLayerMask.Three) { cloudCover3 = CloudLayer3.CloudCover.LastValue; } if (isAnimating || CloudLayerVolumetric1 == null || CloudLayerVolumetric1.CloudCover.Maximum == 0.0f || !WeatherMakerScript.Instance.PerformanceProfile.EnableVolumetricClouds || (CloudLayerVolumetric1.FlatLayerMask & WeatherMakerVolumetricCloudsFlatLayerMask.Four) == WeatherMakerVolumetricCloudsFlatLayerMask.Four) { cloudCover4 = CloudLayer4.CloudCover.LastValue; } props.SetTexture(WMS._CloudNoise1, CloudLayer1.CloudNoise ?? Texture2D.blackTexture); props.SetTexture(WMS._CloudNoise2, CloudLayer2.CloudNoise ?? Texture2D.blackTexture); props.SetTexture(WMS._CloudNoise3, CloudLayer3.CloudNoise ?? Texture2D.blackTexture); props.SetTexture(WMS._CloudNoise4, CloudLayer4.CloudNoise ?? Texture2D.blackTexture); Vector4 scaleReducer = new Vector4(1.0f / Mathf.Max(1.0f, CloudLayer1.CloudHeight.LastValue), 1.0f / Mathf.Max(1.0f, CloudLayer2.CloudHeight.LastValue), 1.0f / Mathf.Max(1.0f, CloudLayer3.CloudHeight.LastValue), 1.0f / Mathf.Max(1.0f, CloudLayer4.CloudHeight.LastValue)); props.SetVector(WMS._CloudNoiseScale, new Vector4(CloudLayer1.CloudNoiseScale.LastValue * scaleReducer.x, CloudLayer2.CloudNoiseScale.LastValue * scaleReducer.y, CloudLayer3.CloudNoiseScale.LastValue * scaleReducer.z, CloudLayer4.CloudNoiseScale.LastValue * scaleReducer.w)); props.SetVector(WMS._CloudNoiseMultiplier, new Vector4(CloudLayer1.CloudNoiseMultiplier.LastValue, CloudLayer2.CloudNoiseMultiplier.LastValue, CloudLayer3.CloudNoiseMultiplier.LastValue, CloudLayer4.CloudNoiseMultiplier.LastValue)); props.SetVector(WMS._CloudNoiseAdder, new Vector4(CloudLayer1.CloudNoiseAdder.LastValue, CloudLayer2.CloudNoiseAdder.LastValue, CloudLayer3.CloudNoiseAdder.LastValue, CloudLayer4.CloudNoiseAdder.LastValue)); props.SetVector(WMS._CloudNoiseDither, new Vector4(CloudLayer1.CloudNoiseDither.LastValue, CloudLayer2.CloudNoiseDither.LastValue, CloudLayer3.CloudNoiseDither.LastValue, CloudLayer4.CloudNoiseDither.LastValue)); props.SetVectorArray(WMS._CloudNoiseVelocity, cloudNoiseVelocityAccum1, cloudNoiseVelocityAccum2, cloudNoiseVelocityAccum3, cloudNoiseVelocityAccum4); props.SetFloatArrayRotation(WMS._CloudNoiseRotation, CloudLayer1.CloudNoiseRotation.LastValue, CloudLayer2.CloudNoiseRotation.LastValue, CloudLayer3.CloudNoiseRotation.LastValue, CloudLayer4.CloudNoiseRotation.LastValue); props.SetVector(WMS._CloudHeight, new Vector4(CloudLayer1.CloudHeight.LastValue, CloudLayer2.CloudHeight.LastValue, CloudLayer3.CloudHeight.LastValue, CloudLayer4.CloudHeight.LastValue)); props.SetVector(WMS._CloudCover, new Vector4(cloudCover1, cloudCover2, cloudCover3, cloudCover4)); props.SetFloatArray(WMS._CloudRayOffset, CloudLayer1.CloudRayOffset, CloudLayer2.CloudRayOffset, CloudLayer3.CloudRayOffset, CloudLayer4.CloudRayOffset); props.SetColorArray(WMS._CloudColor, CloudLayer1.CloudColor * sun.GetGradientColor(CloudLayer1.CloudGradientColor), CloudLayer2.CloudColor * sun.GetGradientColor(CloudLayer2.CloudGradientColor), CloudLayer3.CloudColor * sun.GetGradientColor(CloudLayer3.CloudGradientColor), CloudLayer4.CloudColor * sun.GetGradientColor(CloudLayer4.CloudGradientColor)); props.SetColorArray(WMS._CloudEmissionColor, CloudLayer1.CloudEmissionColor, CloudLayer2.CloudEmissionColor, CloudLayer3.CloudEmissionColor, CloudLayer4.CloudEmissionColor); props.SetFloatArray(WMS._CloudAmbientGroundMultiplier, CloudLayer1.CloudAmbientGroundMultiplier.LastValue * ambientMultiplier, CloudLayer2.CloudAmbientGroundMultiplier.LastValue * ambientMultiplier, CloudLayer3.CloudAmbientGroundMultiplier.LastValue * ambientMultiplier, CloudLayer4.CloudAmbientGroundMultiplier.LastValue * ambientMultiplier); props.SetFloatArray(WMS._CloudAmbientSkyMultiplier, CloudLayer1.CloudAmbientSkyMultiplier.LastValue * ambientMultiplier, CloudLayer2.CloudAmbientSkyMultiplier.LastValue * ambientMultiplier, CloudLayer3.CloudAmbientSkyMultiplier.LastValue * ambientMultiplier, CloudLayer4.CloudAmbientSkyMultiplier.LastValue * ambientMultiplier); props.SetVectorArray(WMS._CloudScatterMultiplier, CloudLayer1.CloudScatterMultiplier, CloudLayer2.CloudScatterMultiplier, CloudLayer3.CloudScatterMultiplier, CloudLayer4.CloudScatterMultiplier); /* if (CloudLayer1.CloudNoiseMask != null || CloudLayer2.CloudNoiseMask != null || CloudLayer3.CloudNoiseMask != null || CloudLayer4.CloudNoiseMask != null) { cloudMaterial.SetTexture(WMS._CloudNoiseMask1, CloudLayer1.CloudNoiseMask ?? Texture2D.whiteTexture); cloudMaterial.SetTexture(WMS._CloudNoiseMask2, CloudLayer2.CloudNoiseMask ?? Texture2D.whiteTexture); cloudMaterial.SetTexture(WMS._CloudNoiseMask3, CloudLayer3.CloudNoiseMask ?? Texture2D.whiteTexture); cloudMaterial.SetTexture(WMS._CloudNoiseMask4, CloudLayer4.CloudNoiseMask ?? Texture2D.whiteTexture); WeatherMakerShaderIds.SetVectorArray(cloudMaterial, "_CloudNoiseMaskOffset", CloudLayer1.CloudNoiseMaskOffset, CloudLayer2.CloudNoiseMaskOffset, CloudLayer3.CloudNoiseMaskOffset, CloudLayer4.CloudNoiseMaskOffset); WeatherMakerShaderIds.SetVectorArray(cloudMaterial, "_CloudNoiseMaskVelocity", cloudNoiseMaskVelocityAccum1, cloudNoiseMaskVelocityAccum2, cloudNoiseMaskVelocityAccum3, cloudNoiseMaskVelocityAccum4); WeatherMakerShaderIds.SetFloatArray(cloudMaterial, "_CloudNoiseMaskScale", (CloudLayer1.CloudNoiseMask == null ? 0.0f : CloudLayer1.CloudNoiseMaskScale * scaleReducer), (CloudLayer2.CloudNoiseMask == null ? 0.0f : CloudLayer2.CloudNoiseMaskScale * scaleReducer), (CloudLayer3.CloudNoiseMask == null ? 0.0f : CloudLayer3.CloudNoiseMaskScale * scaleReducer), (CloudLayer4.CloudNoiseMask == null ? 0.0f : CloudLayer4.CloudNoiseMaskScale * scaleReducer)); WeatherMakerShaderIds.SetFloatArrayRotation(cloudMaterial, "_CloudNoiseMaskRotation", CloudLayer1.CloudNoiseMaskRotation.LastValue, CloudLayer2.CloudNoiseMaskRotation.LastValue, CloudLayer3.CloudNoiseMaskRotation.LastValue, CloudLayer4.CloudNoiseMaskRotation.LastValue); } */ props.SetVector(WMS._CloudLightAbsorption, new Vector4( CloudLayer1.CloudLightAbsorption.LastValue, CloudLayer2.CloudLightAbsorption.LastValue, CloudLayer3.CloudLightAbsorption.LastValue, CloudLayer4.CloudLightAbsorption.LastValue)); if (WeatherMakerCommandBufferManagerScript.Instance != null) { WeatherMakerCommandBufferManagerScript.Instance.UpdateShaderPropertiesForCamera(props, camera); } } /// <summary> /// Set shader cloud values /// </summary> /// <param name="cloudMaterial">Cloud material</param> /// <param name="cloudProbe">Cloud probe shader</param> /// <param name="camera">Camera</param> /// <param name="weatherMap">Weather map texture</param> public void SetShaderCloudParameters(Material cloudMaterial, ComputeShader cloudProbe, Camera camera, Texture weatherMap) { if (WeatherMakerScript.Instance == null || WeatherMakerScript.Instance.PerformanceProfile == null || WeatherMakerDayNightCycleManagerScript.Instance == null || WeatherMakerLightManagerScript.Instance == null) { return; } WeatherMakerCelestialObjectScript sun = (camera == null || !camera.orthographic ? WeatherMakerLightManagerScript.Instance.SunPerspective : WeatherMakerLightManagerScript.Instance.SunOrthographic); if (sun == null) { return; } if (!isAnimating) { CloudLayerVolumetric1.CloudDirLightGradientColorColor = sun.GetGradientColor(CloudLayerVolumetric1.CloudDirLightGradientColor); CloudLayerVolumetric1.CloudEmissionGradientColorColor = sun.GetGradientColor(CloudLayerVolumetric1.CloudEmissionGradientColor); CloudLayerVolumetric1.CloudGradientStratusVector = WeatherMakerCloudVolumetricProfileScript.CloudHeightGradientToVector4(CloudLayerVolumetric1.CloudGradientStratus); CloudLayerVolumetric1.CloudGradientStratoCumulusVector = WeatherMakerCloudVolumetricProfileScript.CloudHeightGradientToVector4(CloudLayerVolumetric1.CloudGradientStratoCumulus); CloudLayerVolumetric1.CloudGradientCumulusVector = WeatherMakerCloudVolumetricProfileScript.CloudHeightGradientToVector4(CloudLayerVolumetric1.CloudGradientCumulus); } // update global shader values shaderProps.Update(null); SetShaderVolumetricCloudShaderProperties(shaderProps, weatherMap, sun, camera); // update compute shader values if (cloudProbe != null) { shaderProps.Update(cloudProbe); SetShaderVolumetricCloudShaderProperties(shaderProps, weatherMap, sun, camera); } Shader.SetGlobalInt(WMS._WeatherMakerCloudVolumetricShadowSampleCount, WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudShadowSampleCount); Shader.SetGlobalInt(WMS._WeatherMakerCloudVolumetricShadowLod, WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudShadowLod); if (CloudsEnabled) { float cover = Mathf.Min(1.0f, CloudCoverTotal * (1.5f - CloudLightAbsorptionTotal)); float sunIntensityMultiplier = Mathf.Clamp(1.0f - (cover * CloudLightStrength), 0.2f, 1.0f); float sunIntensityMultiplierWithoutLightStrength = Mathf.Clamp(1.0f - (cover * cover * 0.85f), 0.2f, 1.0f); float cloudShadowReducer = sunIntensityMultiplierWithoutLightStrength; float dirLightMultiplier = sunIntensityMultiplier * Mathf.Lerp(1.0f, DirectionalLightIntensityMultiplier, cover); Shader.SetGlobalFloat(WMS._WeatherMakerCloudGlobalShadow2, cloudShadowReducer); CloudGlobalShadow = cloudShadowReducer = Mathf.Min(cloudShadowReducer, Shader.GetGlobalFloat(WMS._WeatherMakerCloudGlobalShadow)); CloudDirectionalLightDirectBlock = dirLightMultiplier; // if we have shadows turned on, use screen space shadows if (QualitySettings.shadows != ShadowQuality.Disable && WeatherMakerLightManagerScript.ScreenSpaceShadowMode != UnityEngine.Rendering.BuiltinShaderMode.Disabled && WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudShadowDownsampleScale != WeatherMakerDownsampleScale.Disabled && WeatherMakerScript.Instance.PerformanceProfile.VolumetricCloudShadowSampleCount > 0) { // do not reduce light intensity or shadows, screen space shadows are being used WeatherMakerLightManagerScript.Instance.DirectionalLightIntensityMultipliers.Remove("WeatherMakerFullScreenCloudsScript"); Shader.SetGlobalFloat(WMS._WeatherMakerDirLightMultiplier, 1.0f); Shader.SetGlobalFloat(WMS._WeatherMakerCloudGlobalShadow, 1.0f); } else { // save dir light multiplier so flat clouds can adjust to the dimmed light Shader.SetGlobalFloat(WMS._WeatherMakerDirLightMultiplier, 1.0f / Mathf.Max(0.0001f, dirLightMultiplier)); Shader.SetGlobalFloat(WMS._WeatherMakerCloudGlobalShadow, cloudShadowReducer); // brighten up on orthographic, looks better if (WeatherMakerScript.Instance.MainCamera != null && WeatherMakerScript.Instance.MainCamera.orthographic) { sunIntensityMultiplier = Mathf.Min(1.0f, sunIntensityMultiplier * 2.0f); } // we rely on sun intensity reduction to fake shadows WeatherMakerLightManagerScript.Instance.DirectionalLightIntensityMultipliers["WeatherMakerFullScreenCloudsScript"] = dirLightMultiplier; } } else { WeatherMakerLightManagerScript.Instance.DirectionalLightIntensityMultipliers.Remove("WeatherMakerFullScreenCloudsScript"); WeatherMakerLightManagerScript.Instance.DirectionalLightShadowIntensityMultipliers.Remove("WeatherMakerFullScreenCloudsScript"); } } private void LoadDefaultLayerIfNeeded(ref WeatherMakerCloudLayerProfileScript script) { if (script == null && WeatherMakerScript.Instance != null) { script = WeatherMakerScript.Instance.LoadResource<WeatherMakerCloudLayerProfileScript>("WeatherMakerCloudLayerProfile_None"); } } private void LoadDefaultLayerIfNeeded(ref WeatherMakerCloudVolumetricProfileScript script) { if (script == null && WeatherMakerScript.Instance != null) { script = WeatherMakerScript.Instance.LoadResource<WeatherMakerCloudVolumetricProfileScript>("WeatherMakerCloudLayerProfileVolumetric_None"); } } private void CheckWarpChange() { // support editor changes for warping if (weatherMapCloudCoverageWarpMinPrev != WeatherMapCloudCoverageWarpMin || weatherMapCloudCoverageWarpMaxPrev != WeatherMapCloudCoverageWarpMax) { weatherMapCloudCoverageWarpMinPrev = WeatherMapCloudCoverageWarpMin; weatherMapCloudCoverageWarpMaxPrev = WeatherMapCloudCoverageWarpMax; weatherMapCloudCoverageWarp = null; } if (weatherMapCloudCoverageNegationWarpMinPrev != WeatherMapCloudCoverageNegationWarpMin || weatherMapCloudCoverageNegationWarpMaxPrev != WeatherMapCloudCoverageNegationWarpMax) { weatherMapCloudCoverageNegationWarpMinPrev = WeatherMapCloudCoverageNegationWarpMin; weatherMapCloudCoverageNegationWarpMaxPrev = WeatherMapCloudCoverageNegationWarpMax; weatherMapCloudCoverageNegationWarp = null; } if (weatherMapCloudTypeWarpMinPrev != WeatherMapCloudTypeWarpMin || weatherMapCloudTypeWarpMaxPrev != WeatherMapCloudTypeWarpMax) { weatherMapCloudTypeWarpMinPrev = WeatherMapCloudTypeWarpMin; weatherMapCloudTypeWarpMaxPrev = WeatherMapCloudTypeWarpMax; weatherMapCloudTypeWarp = null; } if (weatherMapCloudTypeNegationWarpMinPrev != WeatherMapCloudTypeNegationWarpMin || weatherMapCloudTypeNegationWarpMaxPrev != WeatherMapCloudTypeNegationWarpMax) { weatherMapCloudTypeNegationWarpMinPrev = WeatherMapCloudTypeNegationWarpMin; weatherMapCloudTypeNegationWarpMaxPrev = WeatherMapCloudTypeNegationWarpMax; weatherMapCloudTypeNegationWarp = null; } } private void UpdateWeatherMap(WeatherMakerFullScreenCloudsScript script, WeatherMakerShaderPropertiesScript props, Texture weatherMap, float weatherMapSeed, Camera camera) { props.SetTexture(WMS._WeatherMakerWeatherMapTexture, weatherMap); props.SetVector(WMS._WeatherMakerWeatherMapScale, new Vector4(NoiseScaleX.LastValue, NoiseScaleY.LastValue, WorldScale, 1.0f / WorldScale)); props.SetFloat(WMS._CloudCoverageNoiseType, WeatherMapCloudCoverageNoiseType.LastValue); props.SetFloat(WMS._CloudDensityNoiseType, WeatherMapCloudDensityNoiseType.LastValue); props.SetFloat(WMS._CloudTypeNoiseType, WeatherMapCloudTypeNoiseType.LastValue); props.SetFloat(WMS._CloudCoverageNoiseTypeInv, 1.0f - WeatherMapCloudCoverageNoiseType.LastValue); props.SetFloat(WMS._CloudDensityNoiseTypeInv, 1.0f - WeatherMapCloudDensityNoiseType.LastValue); props.SetFloat(WMS._CloudTypeNoiseTypeInv, 1.0f - WeatherMapCloudTypeNoiseType.LastValue); props.SetFloat(WMS._CloudCoverVolumetric, CloudLayerVolumetric1.CloudCover.LastValue); props.SetFloat(WMS._CloudDensityVolumetric, CloudLayerVolumetric1.CloudDensity.LastValue); props.SetFloat(WMS._CloudTypeVolumetric, CloudLayerVolumetric1.CloudType.LastValue); props.SetFloat(WMS._CloudCoverSecondaryVolumetric, CloudLayerVolumetric1.CloudCoverSecondary.LastValue); props.SetFloat(WMS._CloudDensitySecondaryVolumetric, CloudLayerVolumetric1.CloudDensitySecondary.LastValue); props.SetFloat(WMS._CloudTypeSecondaryVolumetric, CloudLayerVolumetric1.CloudTypeSecondary.LastValue); props.SetVector(WMS._CloudVelocity, new Vector3(WeatherMapCloudCoverageVelocity.x, WeatherMapCloudCoverageVelocity.z, WeatherMapCloudCoverageVelocity.y)); props.SetVector(WMS._CloudCoverageVelocity, velocityAccumCoverage); props.SetVector(WMS._CloudDensityVelocity, velocityAccumDensity); props.SetVector(WMS._CloudTypeVelocity, velocityAccumType); props.SetVector(WMS._CloudCoverageNegationVelocity, velocityAccumCoverageNegation); props.SetVector(WMS._CloudDensityNegationVelocity, velocityAccumDensityNegation); props.SetVector(WMS._CloudTypeNegationVelocity, velocityAccumTypeNegation); props.SetFloat(WMS._CloudCoverageFrequency, WeatherMapCloudCoverageScale.LastValue); props.SetFloat(WMS._CloudDensityFrequency, WeatherMapCloudDensityScale.LastValue); props.SetFloat(WMS._CloudTypeFrequency, WeatherMapCloudTypeScale.LastValue); props.SetFloat(WMS._CloudCoverageNegationFrequency, WeatherMapCloudCoverageNegationScale.LastValue); props.SetFloat(WMS._CloudDensityNegationFrequency, WeatherMapCloudDensityNegationScale.LastValue); props.SetFloat(WMS._CloudTypeNegationFrequency, WeatherMapCloudTypeNegationScale.LastValue); float r = WeatherMapCloudCoverageRotation.LastValue * Mathf.Deg2Rad; props.SetVector(WMS._CloudCoverageRotation, new Vector2(Mathf.Sin(r), Mathf.Cos(r))); r = WeatherMapCloudDensityNegationRotation.LastValue * Mathf.Deg2Rad; props.SetVector(WMS._CloudDensityRotation, new Vector2(Mathf.Sin(r), Mathf.Cos(r))); r = WeatherMapCloudTypeNegationRotation.LastValue * Mathf.Deg2Rad; props.SetVector(WMS._CloudTypeRotation, new Vector2(Mathf.Sin(r), Mathf.Cos(r))); r = WeatherMapCloudCoverageNegationRotation.LastValue * Mathf.Deg2Rad; props.SetVector(WMS._CloudCoverageNegationRotation, new Vector2(Mathf.Sin(r), Mathf.Cos(r))); r = WeatherMapCloudDensityNegationRotation.LastValue * Mathf.Deg2Rad; props.SetVector(WMS._CloudDensityNegationRotation, new Vector2(Mathf.Sin(r), Mathf.Cos(r))); r = WeatherMapCloudTypeRotation.LastValue * Mathf.Deg2Rad; props.SetVector(WMS._CloudTypeNegationRotation, new Vector2(Mathf.Sin(r), Mathf.Cos(r))); props.SetFloat(WMS._CloudCoverageAdder, WeatherMapCloudCoverageAdder.LastValue); props.SetFloat(WMS._CloudDensityAdder, WeatherMapCloudDensityAdder.LastValue); props.SetFloat(WMS._CloudTypeAdder, WeatherMapCloudTypeAdder.LastValue); props.SetFloat(WMS._CloudCoverageNegationAdder, WeatherMapCloudCoverageNegationAdder.LastValue); props.SetFloat(WMS._CloudDensityNegationAdder, WeatherMapCloudDensityNegationAdder.LastValue); props.SetFloat(WMS._CloudTypeNegationAdder, WeatherMapCloudTypeNegationAdder.LastValue); //props.SetVector(WMS._CloudCoverageOffset, cloudCoverageOffset); //props.SetVector(WMS._CloudDensityOffset, cloudDensityOffset); //props.SetVector(WMS._CloudTypeOffset, cloudTypeOffset); //props.SetVector(WMS._CloudCoverageNegationOffset, weatherMapCloudCoverageNegationOffsetCalculated); //props.SetVector(WMS._CloudDensityNegationOffset, weatherMapCloudDensityNegationOffsetCalculated); //props.SetVector(WMS._CloudTypeNegationOffset, weatherMapCloudTypeNegationOffsetCalculated); props.SetFloat(WMS._CloudCoveragePower, WeatherMapCloudCoveragePower.LastValue); props.SetFloat(WMS._CloudDensityPower, WeatherMapCloudDensityPower.LastValue); props.SetFloat(WMS._CloudTypePower, WeatherMapCloudTypePower.LastValue); props.SetFloat(WMS._CloudCoverageNegationPower, WeatherMapCloudCoverageNegationPower.LastValue); props.SetFloat(WMS._CloudDensityNegationPower, WeatherMapCloudDensityNegationPower.LastValue); props.SetFloat(WMS._CloudTypeNegationPower, WeatherMapCloudTypeNegationPower.LastValue); props.SetVector(WMS._CloudCoverageWarpScale, WeatherMapCloudCoverageWarp); props.SetVector(WMS._CloudDensityWarpScale, WeatherMapCloudDensityWarp); props.SetVector(WMS._CloudTypeWarpScale, WeatherMapCloudTypeWarp); props.SetVector(WMS._CloudCoverageNegationWarpScale, WeatherMapCloudCoverageNegationWarp); props.SetVector(WMS._CloudDensityNegationWarpScale, WeatherMapCloudDensityNegationWarp); props.SetVector(WMS._CloudTypeNegationWarpScale, WeatherMapCloudTypeNegationWarp); props.SetVector(WMS._MaskOffset, WeatherMapRenderTextureMaskOffset); props.SetFloat(WMS._WeatherMakerWeatherMapSeed, weatherMapSeed); if (WeatherMakerCommandBufferManagerScript.Instance != null) { WeatherMakerCommandBufferManagerScript.Instance.UpdateShaderPropertiesForCamera(props, camera); } if (script.VolumetricCloudBoxRemap == null) { props.SetVector(WMS._WeatherMakerCloudVolumetricWeatherMapRemapBoxMin, Vector4.zero); props.SetVector(WMS._WeatherMakerCloudVolumetricWeatherMapRemapBoxMax, Vector4.zero); } else { Vector4 min = script.VolumetricCloudBoxRemap.bounds.min; Vector4 max = script.VolumetricCloudBoxRemap.bounds.max; min.w = max.y - min.y; max.w = (min.w > 0.0f ? 1.0f / min.w : 0.0f); props.SetVector(WMS._WeatherMakerCloudVolumetricWeatherMapRemapBoxMin, min); props.SetVector(WMS._WeatherMakerCloudVolumetricWeatherMapRemapBoxMax, max); } } /// <summary> /// Update the weather map /// </summary> /// <param name="script">Script</param> /// <param name="weatherMapMaterial">Weather map material</param> /// <param name="camera">Camera</param> /// <param name="cloudProbeShader">Cloud probe shader</param> /// <param name="weatherMap">Weather map render texture</param> /// <param name="weatherMapSeed">Weather map seed</param> public void UpdateWeatherMap(WeatherMakerFullScreenCloudsScript script, Material weatherMapMaterial, Camera camera, ComputeShader cloudProbeShader, RenderTexture weatherMap, float weatherMapSeed) { if (CloudLayerVolumetric1 == null) { return; } if (camera == null) { camera = Camera.main; if (camera == null) { return; } } shaderProps.Update(null); UpdateWeatherMap(script, shaderProps, weatherMap, weatherMapSeed, camera); shaderProps.Update(weatherMapMaterial); UpdateWeatherMap(script, shaderProps, weatherMap, weatherMapSeed, camera); if (cloudProbeShader != null) { shaderProps.Update(cloudProbeShader); UpdateWeatherMap(script, shaderProps, weatherMap, weatherMapSeed, camera); } } /// <summary> /// Ensure all layers have profiles /// </summary> public void EnsureNonNullLayers() { LoadDefaultLayerIfNeeded(ref CloudLayer1); LoadDefaultLayerIfNeeded(ref CloudLayer2); LoadDefaultLayerIfNeeded(ref CloudLayer3); LoadDefaultLayerIfNeeded(ref CloudLayer4); LoadDefaultLayerIfNeeded(ref CloudLayerVolumetric1); } /// <summary> /// Deep clone the entire profile /// </summary> /// <returns></returns> public WeatherMakerCloudProfileScript Clone() { WeatherMakerCloudProfileScript clone = ScriptableObject.Instantiate(this); clone.EnsureNonNullLayers(); clone.CloudLayer1 = ScriptableObject.Instantiate(clone.CloudLayer1); clone.CloudLayer2 = ScriptableObject.Instantiate(clone.CloudLayer2); clone.CloudLayer3 = ScriptableObject.Instantiate(clone.CloudLayer3); clone.CloudLayer4 = ScriptableObject.Instantiate(clone.CloudLayer4); clone.CloudLayerVolumetric1 = ScriptableObject.Instantiate(clone.CloudLayerVolumetric1); CopyStateTo(clone); return clone; } /// <summary> /// Update /// </summary> public void Update() { EnsureNonNullLayers(); CheckWarpChange(); CloudsEnabled = ( (CloudLayerVolumetric1.CloudColor.a > 0.0f && CloudLayerVolumetric1.CloudCover.LastValue > 0.001f) || (CloudLayer1.CloudNoise != null && CloudLayer1.CloudColor.a > 0.0f && CloudLayer1.CloudCover.LastValue > 0.0f) || (CloudLayer2.CloudNoise != null && CloudLayer2.CloudColor.a > 0.0f && CloudLayer2.CloudCover.LastValue > 0.0f) || (CloudLayer3.CloudNoise != null && CloudLayer3.CloudColor.a > 0.0f && CloudLayer3.CloudCover.LastValue > 0.0f) || (CloudLayer4.CloudNoise != null && CloudLayer4.CloudColor.a > 0.0f && CloudLayer4.CloudCover.LastValue > 0.0f) || (AuroraProfile != null && AuroraProfile.AuroraEnabled) ); bool enableVol = WeatherMakerScript.Instance.PerformanceProfile.EnableVolumetricClouds; float volCover = (enableVol ? CloudLayerVolumetric1.CloudCover.LastValue : 0.0f); float volAbsorption = (enableVol ? Mathf.Min(1.0f, (Mathf.Clamp(1.0f - (CloudLayerVolumetric1.CloudCover.LastValue), 0.0f, 1.0f))) : 0.0f); //float volAbsorption = (enableVol ? Mathf.Min(1.0f, (Mathf.Clamp(1.0f - (CloudLayerVolumetric1.CloudCover.LastValue), 0.0f, 1.0f))) : 0.0f); CloudCoverTotal = Mathf.Min(1.0f, (CloudLayer1.CloudCover.LastValue + CloudLayer2.CloudCover.LastValue + CloudLayer3.CloudCover.LastValue + CloudLayer4.CloudCover.LastValue + volCover)); CloudDensityTotal = Mathf.Min(1.0f, volCover); CloudLightAbsorptionTotal = volAbsorption + (CloudLayer1.CloudCover.LastValue * CloudLayer1.CloudLightAbsorption.LastValue) + (CloudLayer2.CloudCover.LastValue * CloudLayer2.CloudLightAbsorption.LastValue) + (CloudLayer3.CloudCover.LastValue * CloudLayer3.CloudLightAbsorption.LastValue) + (CloudLayer4.CloudCover.LastValue * CloudLayer4.CloudLightAbsorption.LastValue); float velocityScaleFlat = Time.deltaTime; //cloudNoiseMaskVelocityAccum1 += (CloudLayer1.CloudNoiseMaskVelocity * velocityScaleFlat); //cloudNoiseMaskVelocityAccum2 += (CloudLayer2.CloudNoiseMaskVelocity * velocityScaleFlat); //cloudNoiseMaskVelocityAccum3 += (CloudLayer3.CloudNoiseMaskVelocity * velocityScaleFlat); //cloudNoiseMaskVelocityAccum4 += (CloudLayer4.CloudNoiseMaskVelocity * velocityScaleFlat); cloudNoiseVelocityAccum1 += (CloudLayer1.CloudNoiseVelocity * velocityScaleFlat); cloudNoiseVelocityAccum2 += (CloudLayer2.CloudNoiseVelocity * velocityScaleFlat); cloudNoiseVelocityAccum3 += (CloudLayer3.CloudNoiseVelocity * velocityScaleFlat); cloudNoiseVelocityAccum4 += (CloudLayer4.CloudNoiseVelocity * velocityScaleFlat); float velocityScaleVolumetric = Time.deltaTime * 10.0f * WorldScale; velocityAccumCoverage += (WeatherMapCloudCoverageVelocity * velocityScaleVolumetric); velocityAccumDensity += (WeatherMapCloudDensityVelocity * velocityScaleVolumetric); velocityAccumType += (WeatherMapCloudTypeVelocity * velocityScaleVolumetric); velocityAccumCoverageNegation += (WeatherMapCloudCoverageNegationVelocity * velocityScaleVolumetric); velocityAccumDensityNegation += (WeatherMapCloudDensityNegationVelocity * velocityScaleVolumetric); velocityAccumTypeNegation += (WeatherMapCloudTypeNegationVelocity * velocityScaleVolumetric); WeatherMapRenderTextureMaskOffset += (WeatherMapRenderTextureMaskVelocity * Time.deltaTime); // ensure mask offset does not go to far out of bounds WeatherMapRenderTextureMaskOffset.x = Mathf.Clamp(WeatherMapRenderTextureMaskOffset.x, WeatherMapRenderTextureMaskOffsetClamp.x, WeatherMapRenderTextureMaskOffsetClamp.y); WeatherMapRenderTextureMaskOffset.y = Mathf.Clamp(WeatherMapRenderTextureMaskOffset.y, WeatherMapRenderTextureMaskOffsetClamp.x, WeatherMapRenderTextureMaskOffsetClamp.y); } /// <summary> /// Copy profile state to another profile /// </summary> /// <param name="other">Other profile</param> public void CopyStateTo(WeatherMakerCloudProfileScript other) { other.velocityAccumCoverage = velocityAccumCoverage; other.velocityAccumDensity = velocityAccumDensity; other.velocityAccumType = velocityAccumType; other.velocityAccumCoverageNegation = velocityAccumCoverageNegation; other.velocityAccumDensityNegation = velocityAccumDensityNegation; other.velocityAccumTypeNegation = velocityAccumTypeNegation; other.weatherMapCloudCoverageWarp = null; other.weatherMapCloudDensityWarp = null; other.weatherMapCloudTypeWarp = null; other.weatherMapCloudCoverageNegationWarp = null; other.weatherMapCloudDensityNegationWarp = null; other.weatherMapCloudTypeNegationWarp = null; other.cloudNoiseVelocityAccum1 = this.cloudNoiseVelocityAccum1; other.cloudNoiseVelocityAccum2 = this.cloudNoiseVelocityAccum2; other.cloudNoiseVelocityAccum3 = this.cloudNoiseVelocityAccum3; other.cloudNoiseVelocityAccum4 = this.cloudNoiseVelocityAccum4; other.CloudCoverTotal = this.CloudCoverTotal; other.CloudDensityTotal = this.CloudDensityTotal; other.CloudLightAbsorptionTotal = this.CloudLightAbsorptionTotal; other.CloudsEnabled = this.CloudsEnabled; other.WeatherMapRenderTextureMaskVelocity = this.WeatherMapRenderTextureMaskVelocity; other.WeatherMapRenderTextureMaskOffset = this.WeatherMapRenderTextureMaskOffset; } /// <summary> /// Cloud global shadow value /// </summary> public float CloudGlobalShadow { get; private set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GenericStackArray { class GenericStack<T> { public int Top { get; set; } public int Size { get; set; } public T[] Stk { get; set; } public GenericStack(int size) { Top = -1; Size = size; Stk = new T[Size]; } public bool Push(T val) { if (Top == Size - 1) return false; Stk[++Top] = val; return true; } public T Pop() { if(Top == -1) return default(T); return Stk[Top--]; } public void Print() { Console.WriteLine("Stack:"); for (int i = 0; i <= Top; i++) Console.WriteLine(Stk[i]); } } class Program { static void Main(string[] args) { Console.WriteLine("Enter size of Stack:"); int size = int.Parse(Console.ReadLine()); GenericStack<string> stack = new GenericStack<string>(size); bool exit = false; int ch; while (!exit) { Console.WriteLine("1. Push"); Console.WriteLine("2. Pop"); Console.WriteLine("3. Print"); Console.WriteLine("4. Exit"); Console.WriteLine("Enter Choice:"); ch = int.Parse(Console.ReadLine()); switch (ch) { case 1: Console.WriteLine("Enter value:"); string val = Console.ReadLine(); if (stack.Push(val)) Console.WriteLine(val + " has been pushed onto stack"); else Console.WriteLine("Stack Overflow"); break; case 2: string topOfStack = stack.Pop(); if (topOfStack == null) Console.WriteLine("Stack Underflow"); else Console.WriteLine(topOfStack + " has been popped out of stack"); break; case 3: stack.Print(); break; case 4: exit = true; break; default: break; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Mediathek_Webfrontend { public partial class MediaSearch : System.Web.UI.Page { /// <summary> /// On page load /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { this.TxtTitle.Text = Request.QueryString["title"]; this.TxtDesc.Text = Request.QueryString["desc"]; } HandleNoData(); } /// <summary> /// Show error text when no data found and hide data grid. /// Else show grid. /// </summary> private void HandleNoData() { if (this.GridViewMedia.Rows.Count > 0) { this.GridViewMedia.Visible = true; this.LblNoData.Visible = false; } else { this.GridViewMedia.Visible = false; this.LblNoData.Visible = true; } } /// <summary> /// Button "search" clicked /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void ButSearch_Click(object sender, EventArgs e) { string srchUrl = string.Format("MediaSearch.aspx?title={0}&desc={1}", this.TxtTitle.Text, this.TxtDesc.Text); Response.Redirect(srchUrl); } /// <summary> /// Selected index changed in GridView "media" /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void GridViewMedia_SelectedIndexChanged(object sender, EventArgs e) { // open detail page for selected mediaId GridViewRow row = GridViewMedia.SelectedRow; if (row != null) { int mediaId; if (Int32.TryParse(row.Cells[0].Text, out mediaId) && mediaId > 0) { Response.Redirect("MediaDetail.aspx?mediaId=" + mediaId.ToString()); } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /** * Copyright (c) blueback * Released under the MIT License * https://github.com/bluebackblue/fee/blob/master/LICENSE.txt * http://bbbproject.sakura.ne.jp/wordpress/mitlicense * @brief フェード。コンフィグ。 */ /** NFade */ namespace NFade { /** Config */ public class Config { /** ログ。 */ public static bool LOG_ENABLE = false; /** アサート。 */ public static bool ASSERT_ENABLE = true; /** デフォルト。アニメ。スピード。 */ public static float DEFAULT_ANIME_SPEED = 0.01f; /** デフォルト。アニメ。色。 */ public static Color DEFAULT_ANIME_COLOR = new Color(0.0f,0.0f,0.0f,0.0f); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Car : MonoBehaviour { public CarController Controller; public NavigationArrow navigation; public SteeringWheel steeringWheel; public AudioClip doorOpening, doorClosing, seatbelt; public AudioSource audioSource; public Passanger currPassanger; private static Car _instance; public static Car Instance { get { return _instance; } } private void Awake() { if (_instance == null) { _instance = this; } GameManager.onGameEvent += GettingInCar; } private void OnDisable() { GameManager.onGameEvent -= GettingInCar; } private void Start() { } private void Update() { } public void SetPassanger(Passanger nPassanger) { currPassanger = nPassanger; if(currPassanger != null) navigation.UpdateDestination(currPassanger.GetDestination()); } public Passanger GetPassanger() { return currPassanger; } void GettingInCar(GameEvents currEvent) { if (currEvent == GameEvents.ENTERING_CAR) { AudioClip[] clipArray = new AudioClip[] { doorOpening, doorClosing, seatbelt, PassangerAudio.Instance.GetDestinationAudio(currPassanger.GetComponentInChildren<PassangerModel>().male, currPassanger.GetFinishingLocation().GetLocationArea()) }; StartCoroutine(PlaySoundArray(clipArray)); } else if (currEvent == GameEvents.PASSANGER_DROPPED_OFF) { AudioClip[] clipArray = new AudioClip[] { seatbelt, doorOpening, doorClosing }; StartCoroutine(PlaySoundArray(clipArray)); } else if (currEvent == GameEvents.GAME_OVER) steeringWheel.active = false; } IEnumerator PlaySoundArray(AudioClip[] clips) { foreach (AudioClip clip in clips) { audioSource.clip = clip; audioSource.Play(); yield return new WaitForSeconds(clip.length); } } }
using System.Data.SqlClient; namespace Insurance.Model.Interfaces { public interface IBaseService { SqlConnection Connection { get; set; } } }
#if UNITY_EDITOR_WIN using System.Collections.Generic; using System.Linq; using System; using System.Collections; using UnityEngine; using UnityEngine.Windows.Speech; public class WhereAmI : MonoBehaviour { private Dictionary<string, Action> keyActs = new Dictionary<string, Action>(); private KeywordRecognizer recognizer; public enum CurrentLocation { Cell, NarrowHallway, CrowdedStudy, IronCorridor, Laboratory, SittingRoom, CurtainedRoom, CurvingHall, CurvingHallSouthEnd, DimShed, MosaicRoom, Atelier, CurvingHallPedestal, CurvingHallWest, NaturalPassage, HarpChamber, GreyChamber, ConfusingPassage, DeadEnd, LedgeInPit, VaultingCavern, DeepInPit, DepthsInPit, Arboretum, DarkJungle, ShoreOfRiver, FarShoreOfRiver, RiverCrawl } public enum MoveDirections { north, east, south, west } MoveDirections Direction; [SerializeField] CurrentLocation roomName; public Animator animator; void Start() { keyActs.Add("east", isEast); keyActs.Add("west", isWest); keyActs.Add("north", isNorth); keyActs.Add("south", isSouth); keyActs.Add("right", isEast); keyActs.Add("left", isWest); keyActs.Add("up", isNorth); keyActs.Add("down", isSouth); keyActs.Add("go right", isEast); keyActs.Add("go left", isWest); keyActs.Add("go up", isNorth); keyActs.Add("go down", isSouth); keyActs.Add("go east", isEast); keyActs.Add("go west", isWest); keyActs.Add("go north", isNorth); keyActs.Add("go south", isSouth); recognizer = new KeywordRecognizer(keyActs.Keys.ToArray()); recognizer.OnPhraseRecognized += OnKeywordsRecognized; recognizer.Start(); } void OnKeywordsRecognized(PhraseRecognizedEventArgs args) { Debug.Log("Command: " + args.text); keyActs[args.text].Invoke(); } public void isEast() { Direction = MoveDirections.east; GoToNextRoom(); } public void isWest() { Direction = MoveDirections.west; GoToNextRoom(); } public void isNorth() { Direction = MoveDirections.north; GoToNextRoom(); } public void isSouth() { Direction = MoveDirections.south; GoToNextRoom(); } public void GoToNextRoom() { switch (roomName) { case CurrentLocation.Cell: switch (Direction) { case MoveDirections.north: Debug.Log("Not possible"); break; case MoveDirections.east: animator.Play("Go_NarrowHallway"); roomName = CurrentLocation.NarrowHallway; break; case MoveDirections.south: Debug.Log("Not possible"); break; case MoveDirections.west: Debug.Log("Not possible"); break; } break; case CurrentLocation.NarrowHallway: switch (Direction) { case MoveDirections.north: Debug.Log("Not possible"); break; case MoveDirections.east: animator.Play("Go_CrowdedStudy"); roomName = CurrentLocation.CrowdedStudy; break; case MoveDirections.south: Debug.Log("Not possible"); break; case MoveDirections.west: animator.Play("Go_Cell"); roomName = CurrentLocation.Cell; break; } break; case CurrentLocation.CrowdedStudy: switch (Direction) { case MoveDirections.north: Debug.Log("Not possible"); break; case MoveDirections.east: Debug.Log("Not possible"); break; case MoveDirections.south: animator.Play("Go_IronCorridor"); roomName = CurrentLocation.IronCorridor; break; case MoveDirections.west: animator.Play("Go_NarrowHallway"); roomName = CurrentLocation.NarrowHallway; break; } break; case CurrentLocation.IronCorridor: switch (Direction) { case MoveDirections.north: animator.Play("Go_CrowdedStudy"); roomName = CurrentLocation.CrowdedStudy; break; case MoveDirections.east: Debug.Log("Not possible"); break; case MoveDirections.south: Debug.Log("Not possible"); break; case MoveDirections.west: Debug.Log("Not possible"); break; } break; } } public void possibleDirections(CurrentLocation north, CurrentLocation east, CurrentLocation south, CurrentLocation west) { switch (Direction) { case MoveDirections.north: animator.Play("Go_"+ north.ToString()); roomName = north; break; case MoveDirections.east: animator.Play("Go_" + east.ToString()); roomName = east; break; case MoveDirections.south: animator.Play("Go_" + south.ToString()); roomName = south; break; case MoveDirections.west: animator.Play("Go_" + west.ToString()); roomName = west; break; } } } #endif
namespace InterfaceSegregationWorkerAfter.Contracts { public interface IEater { void Eat(); } }
using System.Collections.Generic; using System.Threading.Tasks; using Tookan.NET.Core; namespace Tookan.NET.Clients { public interface ITeamsClient { Task<IEnumerable<Team>> GetTeamsAsync(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Collections; using System.Data; using System.Text.RegularExpressions; using System.Configuration; using System.IO; public partial class BillApproval : System.Web.UI.Page { string obj_Authenticated, obj_emailid; PlaceHolder maPlaceHolder; UserControl obj_Tabs; UserControl obj_LoginCtrl; UserControl obj_WelcomCtrl; UserControl obj_Navi; UserControl obj_Navihome; BillingModule obj_class = new BillingModule(); DataTable dt = new DataTable(); DataTable dt_BillNo = new DataTable(); UserControl Esignature; int resp, resp1; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (Session["ClientID"].ToString() == "1135") { LoadProjectName(); // EnabledApproveButton(); //DisableSaveButton(); } else { Response.Redirect("BillMatching1.aspx"); } ChkAuthentication(); } } public void ChkAuthentication() { obj_LoginCtrl = null; obj_WelcomCtrl = null; obj_Navi = null; obj_Navihome = null; if (Session["Authenticated"] == null) { Session["Authenticated"] = "0"; } else { obj_Authenticated = Session["Authenticated"].ToString(); } maPlaceHolder = (PlaceHolder)Master.FindControl("P1"); if (maPlaceHolder != null) { obj_Tabs = (UserControl)maPlaceHolder.FindControl("loginheader1"); if (obj_Tabs != null) { obj_LoginCtrl = (UserControl)obj_Tabs.FindControl("login1"); obj_WelcomCtrl = (UserControl)obj_Tabs.FindControl("welcome1"); // obj_Navi = (UserControl)obj_Tabs.FindControl("Navii"); //obj_Navihome = (UserControl)obj_Tabs.FindControl("Navihome1"); if (obj_LoginCtrl != null & obj_WelcomCtrl != null) { if (obj_Authenticated == "1") { SetVisualON(); } else { SetVisualOFF(); } } } else { } } else { } } public void SetVisualON() { obj_LoginCtrl.Visible = false; obj_WelcomCtrl.Visible = true; //obj_Navi.Visible = true; // obj_Navihome.Visible = true; } public void SetVisualOFF() { obj_LoginCtrl.Visible = true; obj_WelcomCtrl.Visible = false; //obj_Navi.Visible = true; // obj_Navihome.Visible = false; } public void LoadProjectName() { dt = obj_class.Get_BizconnectProjectName(Convert.ToInt32(Session["ClientID"].ToString()),1); ddl_ProjectName.DataSource = dt; ddl_ProjectName.DataTextField = "ProjectName"; ddl_ProjectName.DataValueField = "ProjectName"; ddl_ProjectName.DataBind(); ddl_ProjectName.Items.Insert(0, new ListItem("-Select-", "0")); } protected void ddlBillNo_SelectedIndexChanged(object sender, EventArgs e) { try { DataSet ds = new DataSet(); ds = obj_class.Get_BillDetailsForBillMatching(ddl_ProjectNo .SelectedItem.Text ,ddlBillNo.SelectedValue); if (ds.Tables[0].Rows.Count > 0) { txtfrom.Text = ds.Tables[0].Rows[0].ItemArray[0].ToString(); txtto.Text = ds.Tables[0].Rows[0].ItemArray[1].ToString(); txttrucktype.Text = ds.Tables[0].Rows[0].ItemArray[2].ToString(); txtLRNo.Text = ds.Tables[0].Rows[0].ItemArray[3].ToString(); txtRCDate.Text = ds.Tables[0].Rows[0].ItemArray[4].ToString(); txtdate.Text = ds.Tables[0].Rows[0].ItemArray[7].ToString(); txtLRDate.Text = ds.Tables[0].Rows[0].ItemArray[25].ToString(); //image Session["ImageID"] = ds.Tables[0].Rows[0].ItemArray[9].ToString(); BillImage.ImageUrl = "BillImage.ashx?ImageID=" + ds.Tables[0].Rows[0].ItemArray[9].ToString(); lblBillID.Text = ds.Tables[0].Rows[0].ItemArray[9].ToString(); txtaddress.Text = ds.Tables[0].Rows[0].ItemArray[10].ToString(); txtRemarks.Text = ds.Tables[0].Rows[0].ItemArray[11].ToString(); txtConfirmno.Text = ds.Tables[0].Rows[0].ItemArray[12].ToString(); txtbasicfreight.Text = ds.Tables[0].Rows[0].ItemArray[13].ToString(); txtloadingdetention.Text = ds.Tables[0].Rows[0].ItemArray[14].ToString(); txtunloadingdetention.Text = ds.Tables[0].Rows[0].ItemArray[15].ToString(); txtLoadingCharges.Text = ds.Tables[0].Rows[0].ItemArray[16].ToString(); txtunloadingCharges.Text = ds.Tables[0].Rows[0].ItemArray[17].ToString(); txtoctroid.Text = ds.Tables[0].Rows[0].ItemArray[18].ToString(); txtDimensionDiff.Text = ds.Tables[0].Rows[0].ItemArray[19].ToString(); txtOtherClaims.Text = ds.Tables[0].Rows[0].ItemArray[20].ToString(); //Less txtinsurance.Text = ds.Tables[0].Rows[0].ItemArray[21].ToString(); txtDamages.Text = ds.Tables[0].Rows[0].ItemArray[22].ToString(); txtshortages.Text = ds.Tables[0].Rows[0].ItemArray[23].ToString(); txtOtherCharges.Text = ds.Tables[0].Rows[0].ItemArray[24].ToString(); txtbillvalue.Text = ds.Tables[0].Rows[0].ItemArray[5].ToString(); txtCNLoadingDetention.Text = ds.Tables[0].Rows[0].ItemArray[26].ToString(); txtCNunloadingdetention.Text = ds.Tables[0].Rows[0].ItemArray[27].ToString(); txtCNLoadingCharges.Text = ds.Tables[0].Rows[0].ItemArray[28].ToString(); txtCNUNLoadingCharges.Text = ds.Tables[0].Rows[0].ItemArray[29].ToString(); txtCNOctroid.Text = ds.Tables[0].Rows[0].ItemArray[30].ToString(); txtCNDimensionDiff.Text = ds.Tables[0].Rows[0].ItemArray[31].ToString(); txtCNOtherClaims.Text = ds.Tables[0].Rows[0].ItemArray[32].ToString(); txtCNInsurance.Text = ds.Tables[0].Rows[0].ItemArray[33].ToString(); txtCNDamages.Text = ds.Tables[0].Rows[0].ItemArray[34].ToString(); txtCNShortages.Text = ds.Tables[0].Rows[0].ItemArray[35].ToString(); txtCNOtherCharges.Text = ds.Tables[0].Rows[0].ItemArray[36].ToString(); txt_CliTransporter.Text = ds.Tables[0].Rows[0].ItemArray[37].ToString(); } DataSet ds1 = new DataSet(); ds1 = obj_class.Bizconnect_GetCollectionNoteDetailsForBillApproval(Convert.ToInt32(txtConfirmno.Text)); if (ds1.Tables[0].Rows.Count > 0) { TxtCNconfirmno.Text = ds1.Tables[0].Rows[0].ItemArray[0].ToString(); txtCNNumber.Text = ds1.Tables[0].Rows[0].ItemArray[1].ToString(); txtCNDate.Text = ds1.Tables[0].Rows[0].ItemArray[2].ToString(); txtautonumber.Text = ds1.Tables[0].Rows[0].ItemArray[3].ToString(); txtprojectno.Text = ds1.Tables[0].Rows[0].ItemArray[4].ToString(); txtwbsno.Text = ds1.Tables[0].Rows[0].ItemArray[5].ToString(); txtdescription.Text = ds1.Tables[0].Rows[0].ItemArray[6].ToString(); txtCNTruckType.Text = ds1.Tables[0].Rows[0].ItemArray[7].ToString(); txttransitdays.Text = ds1.Tables[0].Rows[0].ItemArray[8].ToString(); txtLength.Text = ds1.Tables[0].Rows[0].ItemArray[9].ToString(); txtWidth.Text = ds1.Tables[0].Rows[0].ItemArray[10].ToString(); txtHeight.Text = ds1.Tables[0].Rows[0].ItemArray[11].ToString(); txtTotalWeight.Text = ds1.Tables[0].Rows[0].ItemArray[12].ToString(); txtBuyer.Text = ds1.Tables[0].Rows[0].ItemArray[13].ToString(); txtContactPerson.Text = ds1.Tables[0].Rows[0].ItemArray[14].ToString(); txtContactNo.Text = ds1.Tables[0].Rows[0].ItemArray[15].ToString(); txtCNVehiclePlanned.Text = ds1.Tables[0].Rows[0].ItemArray[16].ToString(); txtCNfrom.Text = ds1.Tables[0].Rows[0].ItemArray[17].ToString(); txtCNTO.Text = ds1.Tables[0].Rows[0].ItemArray[18].ToString(); txtApprovedPRice.Text = ds1.Tables[0].Rows[0].ItemArray[23].ToString(); txtCNBascicFreight.Text = ds1.Tables[0].Rows[0].ItemArray[21].ToString(); //Math.Round ((Convert.ToDouble(ds1.Tables[0].Rows[0].ItemArray[20].ToString()) * Convert.ToDouble(ds1.Tables[0].Rows[0].ItemArray[16].ToString())),0).ToString(); txtNetPrice.Text = (Convert.ToDouble(txtApprovedPRice.Text) + Convert.ToDouble(txtCNBascicFreight.Text)).ToString(); //txtCNBillValue.Text = ds1.Tables[0].Rows[0].ItemArray[21].ToString(); txtNetPrice.Text = (Convert.ToDouble(txtApprovedPRice.Text) + Convert.ToDouble(txtCNBascicFreight.Text)).ToString(); //txtCNBillValue.Text = txtNetPrice.Text; double netvalue = (Convert.ToDouble(txtNetPrice.Text)) + (Convert.ToDouble(txtCNLoadingDetention.Text)) + (Convert.ToDouble(txtCNunloadingdetention.Text)) + (Convert.ToDouble(txtCNLoadingCharges.Text)) + (Convert.ToDouble(txtCNUNLoadingCharges.Text)) + (Convert.ToDouble(txtCNOctroid.Text)) + (Convert.ToDouble(txtCNDimensionDiff.Text)) + (Convert.ToDouble(txtCNOtherClaims.Text)); double totalvalue = (Convert.ToDouble(txtCNInsurance.Text)) + Convert.ToDouble(txtCNDamages.Text) + Convert.ToDouble(txtCNShortages.Text) + Convert.ToDouble(txtCNOtherCharges.Text); // txtCNBillValue .Text =(Convert.ToDouble(txtCNBillValue .Text)-(Convert.ToDouble(txtCNInsurance.Text))+Convert.ToDouble(txtCNDamages .Text))+Convert.ToDouble(txtCNShortages.Text)+Convert.ToDouble(txtCNOtherCharges.Text).ToString (); double Totalnetvalue = (netvalue) - (totalvalue); txtCNBillValue.Text = Totalnetvalue.ToString(); txt_Transporter.Text = ds1.Tables[0].Rows[0].ItemArray[22].ToString(); } if (ds.Tables[0].Rows[0][38].ToString() == "") { txt_ActLength.Text = txtLength.Text; txt_ActWidth.Text = txtWidth.Text; txt_ActHeight.Text = txtHeight.Text; txt_ActTotWeight.Text = txtTotalWeight.Text; } else { txt_ActLength.Text = ds.Tables[0].Rows[0][38].ToString(); txt_ActWidth.Text = ds.Tables[0].Rows[0][39].ToString(); txt_ActHeight.Text = ds.Tables[0].Rows[0][40].ToString(); txt_ActTotWeight.Text = ds.Tables[0].Rows[0][41].ToString(); } DisableSaveButton(); } catch (Exception ex) { } } public void DisableSaveButton() { try { dt_BillNo.Clear(); dt_BillNo = obj_class.Bizconnect_CheckBilldetailsExistsorNotForBillApproval(Convert.ToInt32(Session["ClientID"].ToString()), Convert.ToInt32(txtConfirmno.Text)); if (dt_BillNo.Rows.Count > 0) { btn_Save.Enabled = false; } else { btn_Save.Enabled = true; } } catch (Exception ex) { } } protected void LinkHistory_Click(object sender, EventArgs e) { OpenWindow(); } public void OpenWindow() { ClientScript.RegisterStartupScript(this.GetType(), "OpenWin", "<script>window.open('ViewDetails.aspx?CID=" + TxtCNconfirmno.Text + "', 'mynewwin', 'width=1050,height=850,scrollbars=yes,toolbar=1')</script>"); } protected void btn_Approved_Click(object sender, EventArgs e) { try { ContentPlaceHolder contp; contp = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1"); Esignature = (UserControl)contp.FindControl("Esign"); Control image = Esignature.FindControl("SignatureImage"); if (ddlBillNo.SelectedItem.Text != "-Select-") { if (image.Visible == true) { btn_Approved.Enabled = true; Assigning_BillMatchingDetails(); obj_class.BillMatchFlag = 2; if (Convert.ToInt32(Session["ClientID"].ToString()) > 0) { resp = obj_class.Bizconnect_InsertBillValidation(); resp1 = obj_class.Update_scmjunction_BillSubmissionStaus(Convert.ToInt32(Session["ClientID"].ToString()), Convert.ToInt32(txtConfirmno.Text), ddlBillNo.SelectedItem.Text, 2); } else { ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('Session expired bill not approved successfully please Login again');</script>"); } if (resp == 1 && resp1 == 1) { ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('Approved Successfully');</script>"); ClearFields(); txtCNLoadingDetention.Text = ""; txtCNunloadingdetention.Text = ""; txtCNLoadingCharges.Text = ""; txtCNUNLoadingCharges.Text = ""; txtCNOctroid.Text = ""; txtCNDimensionDiff.Text = ""; txtCNOtherClaims.Text = ""; txtCNInsurance.Text = ""; txtCNDamages.Text = ""; txtCNShortages.Text = ""; txtCNOtherCharges.Text = ""; txt_ActLength.Text = ""; txt_ActWidth.Text = ""; txt_ActHeight.Text = ""; txt_ActTotWeight.Text = ""; } DisableSaveButton(); txtConfirmno.Text = ""; } else { ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('Please Enter Your Esignature');</script>"); } } else { ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('Please Select BillNo To Approve');</script>"); } } catch (Exception ex) { } } public void Assigning_BillMatchingDetails() { try { obj_class.ClientID = Convert.ToInt32(Session["ClientID"].ToString()); obj_class.ConfirmNo = Convert.ToInt32(txtConfirmno.Text); obj_class.BillNo = ddlBillNo.SelectedItem.Text; obj_class.BillDate = Convert.ToDateTime(txtdate.Text); obj_class.LRNumber = txtLRNo.Text; obj_class.LRDate = Convert.ToDateTime(txtLRDate.Text); obj_class.VehicleNo = txtRCDate.Text; obj_class.FromLocation = txtfrom.Text; obj_class.ToLocation = txtto.Text; obj_class.SubmissionAddress = txtaddress.Text; obj_class.TransporterPrice = Convert.ToSingle(txtbasicfreight.Text); obj_class.ClientPrice = Convert.ToSingle(txtCNBascicFreight.Text); obj_class.TransLoadingDetentionCharges = Convert.ToSingle(txtloadingdetention.Text); obj_class.ClientLoadingDetentionCharges = Convert.ToSingle(txtCNLoadingDetention.Text); obj_class.TransUnLoadingDetentionCharges = Convert.ToSingle(txtunloadingdetention.Text); obj_class.ClientUnLoadingDetentionCharges = Convert.ToSingle(txtCNunloadingdetention.Text); obj_class.TransLoadingCharges = Convert.ToSingle(txtLoadingCharges.Text); obj_class.ClientLoadingCharges = Convert.ToSingle(txtCNLoadingCharges.Text); obj_class.TransUnLoadingCharges = Convert.ToSingle(txtunloadingCharges.Text); obj_class.ClientUnLoadingCharges = Convert.ToSingle(txtCNUNLoadingCharges.Text); obj_class.TransoctroiCharges = Convert.ToSingle(txtoctroid.Text); obj_class.ClientoctroiCharges = Convert.ToSingle(txtCNOctroid.Text); obj_class.TransoDimentionDiff = Convert.ToSingle(txtDimensionDiff.Text); obj_class.ClientDimentionDiff = Convert.ToSingle(txtCNDimensionDiff.Text); obj_class.TransOtherClaimsCharges = Convert.ToSingle(txtOtherClaims.Text); obj_class.ClientOtherClaimsCharges = Convert.ToSingle(txtCNOtherClaims.Text); obj_class.TransInsurance = Convert.ToSingle(txtinsurance.Text); obj_class.ClientInsurance = Convert.ToSingle(txtCNInsurance.Text); obj_class.TransDamages = Convert.ToSingle(txtDamages.Text); obj_class.ClientDamages = Convert.ToSingle(txtCNDamages.Text); obj_class.TransShortages = Convert.ToSingle(txtshortages.Text); obj_class.ClientShortages = Convert.ToSingle(txtCNShortages.Text); obj_class.TransOtherCharges = Convert.ToSingle(txtOtherCharges.Text); obj_class.ClientOtherCharges = Convert.ToSingle(txtCNOtherCharges.Text); obj_class.TransNetValue = Convert.ToSingle(txtbillvalue.Text); obj_class.ClientNetValue = Convert.ToSingle(txtCNBillValue.Text); obj_class.AARMSRemarks = txtaarmsRemarks.Text; obj_class.CheckedBy = txtcheckedby.Text; obj_class.IncreasePrice = Convert.ToSingle(txtApprovedPRice.Text); obj_class.Length = Convert.ToSingle(txt_ActLength.Text); obj_class.Width = Convert.ToSingle(txt_ActWidth.Text); obj_class.Height = Convert.ToSingle(txt_ActHeight.Text); obj_class.TotalWeight = Convert.ToSingle(txt_ActTotWeight.Text); } catch (Exception ex) { } } protected void ddl_ProjectNo_SelectedIndexChanged(object sender, EventArgs e) { dt_BillNo = obj_class.Bizconnect_GetBillNoByProjecNameAndNoForBillApproval(Convert.ToInt32(Session["ClientID"].ToString()), ddl_ProjectName.SelectedItem.Text, ddl_ProjectNo.SelectedItem.Text,1); ddlBillNo.DataSource = dt_BillNo; ddlBillNo.DataTextField = "BillNo"; ddlBillNo.DataValueField = "BillSubmissionNo"; ddlBillNo.DataBind(); ddlBillNo.Items.Insert(0, new ListItem("-Select-", "0")); ClearFields(); } protected void ddl_ProjectName_SelectedIndexChanged(object sender, EventArgs e) { try { dt.Clear(); dt = obj_class.Get_BizconnectProjectNo(Convert.ToInt32(Session["ClientID"].ToString()), ddl_ProjectName.SelectedItem.Text,1); ddl_ProjectNo.DataSource = dt; ddl_ProjectNo.DataTextField = "ProjectNo"; ddl_ProjectNo.DataValueField = "ProjectNo"; ddl_ProjectNo.DataBind(); ddl_ProjectNo.Items.Insert(0, new ListItem("-Select-", "0")); ClearFields(); } catch (Exception ex) { } } protected void btn_Save_Click(object sender, EventArgs e) { try { if (ddlBillNo.SelectedItem.Text != "-Select-") { Assigning_BillMatchingDetails(); obj_class.BillMatchFlag = 1; if (Convert.ToInt32(Session["ClientID"].ToString()) > 0) { resp = obj_class.Bizconnect_InsertBillValidation(); } else { ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('Session expired bill not saved successfully please Login again');</script>"); } if (resp == 1) { ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('Saved Successfully');</script>"); ClearFields(); txtCNLoadingDetention.Text = ""; txtCNunloadingdetention.Text = ""; txtCNLoadingCharges.Text = ""; txtCNUNLoadingCharges.Text = ""; txtCNOctroid.Text = ""; txtCNDimensionDiff.Text = ""; txtCNOtherClaims.Text = ""; txtCNInsurance.Text = ""; txtCNDamages.Text = ""; txtCNShortages.Text = ""; txtCNOtherCharges.Text = ""; txt_ActLength.Text = ""; txt_ActWidth.Text = ""; txt_ActHeight.Text = ""; txt_ActTotWeight.Text = ""; } DisableSaveButton(); txtConfirmno.Text = ""; } else { ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('Please Select BillNo for Billmatching');</script>"); } } catch (Exception ex) { } } public void ClearFields() { txtaarmsRemarks.Text = ""; txtaddress.Text = ""; txtApprovedPRice.Text = ""; txtautonumber.Text = ""; txtbasicfreight.Text = ""; txtbillvalue.Text = ""; txtBuyer.Text = ""; txtcheckedby.Text = ""; txtCNBascicFreight.Text = ""; txtCNBillValue.Text = ""; TxtCNconfirmno.Text = ""; txtCNDamages.Text = ""; txtCNDate.Text = ""; txtCNDimensionDiff.Text = ""; txtCNfrom.Text = ""; txtCNInsurance.Text = ""; txtCNLoadingCharges.Text = ""; txtCNLoadingDetention.Text = ""; txtCNNumber.Text = ""; txtCNOctroid.Text = ""; txtCNOtherCharges.Text = ""; txtCNOtherClaims.Text = ""; txtCNShortages.Text = ""; txtCNTO.Text = ""; txtCNTruckType.Text = ""; txtCNUNLoadingCharges.Text = ""; txtCNunloadingdetention.Text = ""; txtCNVehiclePlanned.Text = ""; //txtConfirmno.Text = ""; txtContactNo.Text = ""; txtContactPerson.Text = ""; txtDamages.Text = ""; txtdate.Text = ""; txtdescription.Text = ""; txtDimensionDiff.Text = ""; txtfrom.Text = ""; txtHeight.Text = ""; txtinsurance.Text = ""; txtLength.Text = ""; txtLoadingCharges.Text = ""; txtloadingdetention.Text = ""; txtLRDate.Text = ""; txtLRNo.Text = ""; txtNetPrice.Text = ""; txtTotalWeight.Text = ""; txttransitdays.Text = ""; txttrucktype.Text = ""; txtwbsno.Text = ""; txtWidth.Text = ""; txtprojectno.Text = ""; txtRCDate.Text = ""; txtto.Text = ""; txtloadingdetention.Text = ""; txtLoadingCharges.Text = ""; txtoctroid.Text = ""; txtshortages.Text = ""; txtOtherCharges.Text = ""; txtOtherClaims.Text = ""; txtRemarks.Text = ""; txtunloadingdetention.Text = ""; txtunloadingCharges.Text = ""; } }
using NetFabric.Assertive; using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace NetFabric.Hyperlinq.UnitTests.Bindings.System.Collections.Generic { public class ListTests { [Theory] [MemberData(nameof(TestData.Empty), MemberType = typeof(TestData))] [MemberData(nameof(TestData.Single), MemberType = typeof(TestData))] [MemberData(nameof(TestData.Multiple), MemberType = typeof(TestData))] public void Count_With_ValidData_Must_Succeed(int[] source) { // Arrange var list = source.ToList(); var expected = Enumerable .Count(source); // Act var result = list.AsValueEnumerable() .Count(); // Assert _ = result.Must() .BeEqualTo(expected); } [Theory] [MemberData(nameof(TestData.SkipEmpty), MemberType = typeof(TestData))] [MemberData(nameof(TestData.SkipSingle), MemberType = typeof(TestData))] [MemberData(nameof(TestData.SkipMultiple), MemberType = typeof(TestData))] public void Skip_With_ValidData_Must_Succeed(int[] source, int count) { // Arrange var list = source.ToList(); var expected = Enumerable .Skip(source, count); // Act var result = list.AsValueEnumerable() .Skip(count); // Assert _ = result.Must() .BeEqualTo(expected); } [Theory] [MemberData(nameof(TestData.TakeEmpty), MemberType = typeof(TestData))] [MemberData(nameof(TestData.TakeSingle), MemberType = typeof(TestData))] [MemberData(nameof(TestData.TakeMultiple), MemberType = typeof(TestData))] public void Take_With_ValidData_Must_Succeed(int[] source, int count) { // Arrange var list = source.ToList(); var expected = Enumerable .Take(source, count); // Act var result = list.AsValueEnumerable() .Take(count); // Assert _ = result.Must() .BeEqualTo(expected); } [Theory] [MemberData(nameof(TestData.PredicateEmpty), MemberType = typeof(TestData))] [MemberData(nameof(TestData.PredicateSingle), MemberType = typeof(TestData))] [MemberData(nameof(TestData.PredicateMultiple), MemberType = typeof(TestData))] public void All_Predicate_With_ValidData_Must_Succeed(int[] source, Func<int, bool> predicate) { // Arrange var list = source.ToList(); var expected = Enumerable .All(source, predicate); // Act var result = list.AsValueEnumerable() .All(predicate); // Assert _ = result.Must() .BeEqualTo(expected); } [Theory] [MemberData(nameof(TestData.PredicateAtEmpty), MemberType = typeof(TestData))] [MemberData(nameof(TestData.PredicateAtSingle), MemberType = typeof(TestData))] [MemberData(nameof(TestData.PredicateAtMultiple), MemberType = typeof(TestData))] public void All_PredicateAt_With_ValidData_Must_Succeed(int[] source, Func<int, int, bool> predicate) { // Arrange var list = source.ToList(); var expected = Enumerable .Where(source, predicate) .Count() == source.Length; // Act var result = list.AsValueEnumerable() .All(predicate); // Assert _ = result.Must() .BeEqualTo(expected); } [Theory] [MemberData(nameof(TestData.Empty), MemberType = typeof(TestData))] [MemberData(nameof(TestData.Single), MemberType = typeof(TestData))] [MemberData(nameof(TestData.Multiple), MemberType = typeof(TestData))] public void Any_With_ValidData_Must_Succeed(int[] source) { // Arrange var list = source.ToList(); var expected = Enumerable .Any(source); // Act var result = list.AsValueEnumerable() .Any(); // Assert _ = result.Must() .BeEqualTo(expected); } [Theory] [MemberData(nameof(TestData.PredicateEmpty), MemberType = typeof(TestData))] [MemberData(nameof(TestData.PredicateSingle), MemberType = typeof(TestData))] [MemberData(nameof(TestData.PredicateMultiple), MemberType = typeof(TestData))] public void Any_Predicate_With_ValidData_Must_Succeed(int[] source, Func<int, bool> predicate) { // Arrange var list = source.ToList(); var expected = Enumerable .Any(source, predicate); // Act var result = list.AsValueEnumerable() .Any(predicate); // Assert _ = result.Must() .BeEqualTo(expected); } [Theory] [MemberData(nameof(TestData.PredicateAtEmpty), MemberType = typeof(TestData))] [MemberData(nameof(TestData.PredicateAtSingle), MemberType = typeof(TestData))] [MemberData(nameof(TestData.PredicateAtMultiple), MemberType = typeof(TestData))] public void Any_PredicateAt_With_ValidData_Must_Succeed(int[] source, Func<int, int, bool> predicate) { // Arrange var list = source.ToList(); var expected = Enumerable .Where(source, predicate) .Count() != 0; // Act var result = list.AsValueEnumerable() .Any(predicate); // Assert _ = result.Must() .BeEqualTo(expected); } [Theory] [MemberData(nameof(TestData.Empty), MemberType = typeof(TestData))] [MemberData(nameof(TestData.Single), MemberType = typeof(TestData))] [MemberData(nameof(TestData.Multiple), MemberType = typeof(TestData))] public void Contains_With_Null_And_NotContains_Must_ReturnFalse(int[] source) { // Arrange var list = source.ToList(); var value = int.MaxValue; // Act var result = list.AsValueEnumerable() .Contains(value); // Assert _ = result.Must() .BeFalse(); } [Theory] [MemberData(nameof(TestData.Single), MemberType = typeof(TestData))] [MemberData(nameof(TestData.Multiple), MemberType = typeof(TestData))] public void Contains_With_Null_And_Contains_Must_ReturnTrue(int[] source) { // Arrange var list = source.ToList(); var value = source.Last(); // Act var result = list.AsValueEnumerable() .Contains(value); // Assert _ = result.Must() .BeTrue(); } [Theory] [MemberData(nameof(TestData.SelectorEmpty), MemberType = typeof(TestData))] [MemberData(nameof(TestData.SelectorSingle), MemberType = typeof(TestData))] [MemberData(nameof(TestData.SelectorMultiple), MemberType = typeof(TestData))] public void Select_Selector_With_ValidData_Must_Succeed(int[] source, Func<int, string> selector) { // Arrange var list = source.ToList(); var expected = Enumerable .Select(source, selector); // Act var result = list.AsValueEnumerable() .Select(selector); // Assert _ = result.Must() .BeEnumerableOf<string>() .BeEqualTo(expected, testRefStructs: false); _ = result.SequenceEqual(expected).Must().BeTrue(); } [Theory] [MemberData(nameof(TestData.SelectorAtEmpty), MemberType = typeof(TestData))] [MemberData(nameof(TestData.SelectorAtSingle), MemberType = typeof(TestData))] [MemberData(nameof(TestData.SelectorAtMultiple), MemberType = typeof(TestData))] public void Select_SelectorAt_With_ValidData_Must_Succeed(int[] source, Func<int, int, string> selector) { // Arrange var list = source.ToList(); var expected = Enumerable .Select(source, selector); // Act var result = list.AsValueEnumerable() .Select(selector); // Assert _ = result.Must() .BeEnumerableOf<string>() .BeEqualTo(expected, testRefStructs: false); _ = result.SequenceEqual(expected).Must().BeTrue(); } [Theory] [MemberData(nameof(TestData.PredicateEmpty), MemberType = typeof(TestData))] [MemberData(nameof(TestData.PredicateSingle), MemberType = typeof(TestData))] [MemberData(nameof(TestData.PredicateMultiple), MemberType = typeof(TestData))] public void Where_Predicate_With_ValidData_Must_Succeed(int[] source, Func<int, bool> predicate) { // Arrange var list = source.ToList(); var expected = Enumerable .Where(source, predicate); // Act var result = list.AsValueEnumerable() .Where(predicate); // Assert _ = result.Must() .BeEnumerableOf<int>() .BeEqualTo(expected, testRefStructs: false); _ = result.SequenceEqual(expected).Must().BeTrue(); } [Theory] [MemberData(nameof(TestData.PredicateAtEmpty), MemberType = typeof(TestData))] [MemberData(nameof(TestData.PredicateAtSingle), MemberType = typeof(TestData))] [MemberData(nameof(TestData.PredicateAtMultiple), MemberType = typeof(TestData))] public void Where_PredicateAt_With_ValidData_Must_Succeed(int[] source, Func<int, int, bool> predicate) { // Arrange var list = source.ToList(); var expected = Enumerable .Where(source, predicate); // Act var result = list.AsValueEnumerable() .Where(predicate); // Assert _ = result.Must() .BeEnumerableOf<int>() .BeEqualTo(expected, testRefStructs: false); _ = result.SequenceEqual(expected).Must().BeTrue(); } [Theory] [MemberData(nameof(TestData.PredicateEmpty), MemberType = typeof(TestData))] [MemberData(nameof(TestData.PredicateSingle), MemberType = typeof(TestData))] [MemberData(nameof(TestData.PredicateMultiple), MemberType = typeof(TestData))] public void WhereRef_Predicate_With_ValidData_Must_Succeed(int[] source, Func<int, bool> predicate) { // Arrange var list = source.ToList(); var function = Wrap.AsFunctionIn(predicate); var expected = Enumerable .Where(source, predicate); // Act var result = list.AsValueEnumerableRef() .Where(function); // Assert #if NETCOREAPP3_1 || NET5_0 //_ = result.Must() // .BeEnumerableOf<int>() // .BeEqualTo(expected, testRefStructs: false); #else _ = result.Must() .BeEnumerableOf<int>() .BeEqualTo(expected, testRefStructs: false, testRefReturns: false); #endif _ = result.SequenceEqual(expected).Must().BeTrue(); } [Theory] [MemberData(nameof(TestData.PredicateAtEmpty), MemberType = typeof(TestData))] [MemberData(nameof(TestData.PredicateAtSingle), MemberType = typeof(TestData))] [MemberData(nameof(TestData.PredicateAtMultiple), MemberType = typeof(TestData))] public void WhereAtRef_PredicateAt_With_ValidData_Must_Succeed(int[] source, Func<int, int, bool> predicate) { // Arrange var list = source.ToList(); var function = Wrap.AsFunctionIn(predicate); var expected = Enumerable .Where(source, predicate); // Act var result = list.AsValueEnumerableRef() .Where(function); // Assert #if NETCOREAPP3_1 || NET5_0 //_ = result.Must() // .BeEnumerableOf<int>() // .BeEqualTo(expected, testRefStructs: false); #else _ = result.Must() .BeEnumerableOf<int>() .BeEqualTo(expected, testRefStructs: false, testRefReturns: false); #endif _ = result.SequenceEqual(expected).Must().BeTrue(); } [Theory] [MemberData(nameof(TestData.Empty), MemberType = typeof(TestData))] [MemberData(nameof(TestData.Single), MemberType = typeof(TestData))] [MemberData(nameof(TestData.Multiple), MemberType = typeof(TestData))] public void ElementAt_With_OutOfRange_Must_Return_None(int[] source) { // Arrange var list = source.ToList(); // Act var optionTooSmall = list.AsValueEnumerable() .ElementAt(-1); var optionTooLarge = list.AsValueEnumerable() .ElementAt(source.Length); // Assert _ = optionTooSmall.Must() .BeOfType<Option<int>>() .EvaluateTrue(option => option.IsNone); _ = optionTooLarge.Must() .BeOfType<Option<int>>() .EvaluateTrue(option => option.IsNone); } [Theory] [MemberData(nameof(TestData.Single), MemberType = typeof(TestData))] [MemberData(nameof(TestData.Multiple), MemberType = typeof(TestData))] public void ElementAt_With_ValidData_Must_Return_Some(int[] source) { // Arrange var list = source.ToList(); for (var index = 0; index < source.Length; index++) { // Act var result = list.AsValueEnumerable() .ElementAt(index); // Assert _ = result.Match( value => value.Must().BeEqualTo(source[index]), () => throw new Exception()); } } [Theory] [MemberData(nameof(TestData.Empty), MemberType = typeof(TestData))] public void First_With_Empty_Must_Return_None(int[] source) { // Arrange var list = source.ToList(); // Act var result = list.AsValueEnumerable() .First(); // Assert _ = result.Must() .BeOfType<Option<int>>() .EvaluateTrue(option => option.IsNone); } [Theory] [MemberData(nameof(TestData.Single), MemberType = typeof(TestData))] [MemberData(nameof(TestData.Multiple), MemberType = typeof(TestData))] public void First_With_ValidData_Must_Return_Some(int[] source) { // Arrange var list = source.ToList(); var expected = Enumerable .First(source); // Act var result = list.AsValueEnumerable() .First(); // Assert _ = result.Match( value => value.Must().BeEqualTo(expected), () => throw new Exception()); } [Theory] [MemberData(nameof(TestData.Empty), MemberType = typeof(TestData))] public void Single_With_Empty_Must_Return_None(int[] source) { // Arrange var list = source.ToList(); // Act var result = list.AsValueEnumerable() .Single(); // Assert _ = result.Must() .BeOfType<Option<int>>() .EvaluateTrue(option => option.IsNone); } [Theory] [MemberData(nameof(TestData.Single), MemberType = typeof(TestData))] public void Single_With_Single_Must_Return_Some(int[] source) { // Arrange var list = source.ToList(); var expected = Enumerable .Single(source); // Act var result = list.AsValueEnumerable() .Single(); // Assert _ = result.Match( value => value.Must().BeEqualTo(expected), () => throw new Exception()); } [Theory] [MemberData(nameof(TestData.Empty), MemberType = typeof(TestData))] [MemberData(nameof(TestData.Single), MemberType = typeof(TestData))] [MemberData(nameof(TestData.Multiple), MemberType = typeof(TestData))] public void Distinct_With_ValidData_Must_Succeed(int[] source) { // Arrange var list = source.ToList(); var expected = Enumerable .Distinct(source); // Act var result = list.AsValueEnumerable() .Distinct(); // Assert _ = result.Must() .BeEnumerableOf<int>() .BeEqualTo(expected, testRefStructs: false, testRefReturns: false); _ = result.SequenceEqual(expected).Must().BeTrue(); } [Theory] [MemberData(nameof(TestData.Empty), MemberType = typeof(TestData))] [MemberData(nameof(TestData.Single), MemberType = typeof(TestData))] [MemberData(nameof(TestData.Multiple), MemberType = typeof(TestData))] public void AsValueEnumerable_With_ValidData_Must_Succeed(int[] source) { // Arrange var list = source.ToList(); // Act var result = list.AsValueEnumerable(); // Assert _ = result.Must() .BeAssignableTo<IValueReadOnlyList<int, List<int>.Enumerator>>() .BeEnumerableOf<int>() .BeEqualTo(source); } [Theory] [MemberData(nameof(TestData.Empty), MemberType = typeof(TestData))] [MemberData(nameof(TestData.Single), MemberType = typeof(TestData))] [MemberData(nameof(TestData.Multiple), MemberType = typeof(TestData))] public void ToArray_With_ValidData_Must_Succeed(int[] source) { // Arrange var list = source.ToList(); // Act var result = list.AsValueEnumerable() .ToArray(); // Assert _ = result.Must() .BeArrayOf<int>() .BeEqualTo(source); } [Theory] [MemberData(nameof(TestData.Empty), MemberType = typeof(TestData))] [MemberData(nameof(TestData.Single), MemberType = typeof(TestData))] [MemberData(nameof(TestData.Multiple), MemberType = typeof(TestData))] public void ToList_With_ValidData_Must_Succeed(int[] source) { // Arrange var list = source.ToList(); // Act var result = list.AsValueEnumerable() .ToArray(); // Assert _ = result.Must() .BeEnumerableOf<int>() .BeEqualTo(source); } [Theory] [MemberData(nameof(TestData.Empty), MemberType = typeof(TestData))] [MemberData(nameof(TestData.Single), MemberType = typeof(TestData))] [MemberData(nameof(TestData.Multiple), MemberType = typeof(TestData))] public void ToDictionary_KeySelector_With_ValidData_Must_Succeed(int[] source) { // Arrange var list = source.ToList(); var expected = Enumerable .ToDictionary(source, item => item); // Act var result = list.AsValueEnumerable() .ToDictionary(item => item); // Assert _ = result.Must() .BeEnumerableOf<KeyValuePair<int, int>>() .BeEqualTo(expected, testNonGeneric: false); } [Theory] [MemberData(nameof(TestData.Empty), MemberType = typeof(TestData))] [MemberData(nameof(TestData.Single), MemberType = typeof(TestData))] [MemberData(nameof(TestData.Multiple), MemberType = typeof(TestData))] public void ToDictionary_KeySelector_ElementSelector_With_ValidData_Must_Succeed(int[] source) { // Arrange var list = source.ToList(); var expected = Enumerable .ToDictionary(source, item => item, item => item); // Act var result = list.AsValueEnumerable() .ToDictionary(item => item, item => item); // Assert _ = result.Must() .BeEnumerableOf<KeyValuePair<int, int>>() .BeEqualTo(expected, testNonGeneric: false); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /** * Copyright (c) blueback * Released under the MIT License * https://github.com/bluebackblue/fee/blob/master/LICENSE.txt * http://bbbproject.sakura.ne.jp/wordpress/mitlicense * @brief UI。スクロール。ベース。 */ /** NUi */ namespace NUi { /** Scroll_Base */ public abstract class Scroll_Base : NDeleter.DeleteItem_Base , NEventPlate.OnOverCallBack_Base { /** deleter */ protected NDeleter.Deleter deleter; /** 表示位置。 */ protected int view_position; /** アイテム幅。 */ protected int item_length; /** 表示幅。 */ protected int view_length; /** 表示インデックス。 */ protected int viewindex_st; protected int viewindex_en; /** 矩形。 */ protected NRender2D.Rect2D_R<int> rect; /** eventplate */ protected NEventPlate.Item eventplate; /** is_onover */ protected bool is_onover; /** constructor */ public Scroll_Base(NDeleter.Deleter a_deleter,long a_drawpriority,int a_item_length) { //deleter this.deleter = new NDeleter.Deleter(); //表示位置。 this.view_position = 0; //アイテム幅。 this.item_length = a_item_length; //表示幅。 this.view_length = 0; //表示インデックス。 this.viewindex_st = -1; this.viewindex_en = -1; //矩形。 this.rect.Set(0,0,0,0); //eventplate this.eventplate = new NEventPlate.Item(this.deleter,NEventPlate.EventType.View,a_drawpriority); this.eventplate.SetRect(0,0,0,0); this.eventplate.SetOnOverCallBack(this); //is_onover this.is_onover = false; //削除管理。 if(a_deleter != null){ a_deleter.Register(this); } } /** [Scroll_Base]コールバック。リスト数。取得。 */ public abstract int GetListCount(); /** [Scroll_Base]コールバック。リスト数変更。 */ protected abstract void OnChangeListCount(); /** [Scroll_Base]コールバック。矩形変更。 */ protected abstract void OnChangeRect(); /** [Scroll_Base]コールバック。表示位置変更。 */ protected abstract void OnChangeViewPosition(); /** [Scroll_Base]コールバック。アイテム移動。 */ protected abstract void OnMoveItem_FromBase(int a_index); /** [Scroll_Base]コールバック。表示開始。 */ protected abstract void OnViewInItem_FromBase(int a_index); /** [Scroll_Base]コールバック。表示終了。 */ protected abstract void OnViewOutItem_FromBase(int a_index); /** [Scroll_Base]コールバック。矩形変更。 */ protected abstract void OnChangeRect_FromBase(); /** 削除。 */ public void Delete() { this.deleter.DeleteAll(); } /** 全チェック。表示範囲更新。 */ protected void UpdateView_AllCheck() { int t_list_count = this.GetListCount(); //表示中のアイテムの位置を設定。 for(int ii=this.viewindex_st;ii<=this.viewindex_en;ii++){ this.OnMoveItem_FromBase(ii); } for(int ii=0;ii<this.viewindex_st;ii++){ //表示終了。 this.OnViewOutItem_FromBase(ii); } for(int ii=viewindex_en+1;ii<t_list_count;ii++){ //表示終了。 this.OnViewOutItem_FromBase(ii); } for(int ii=this.viewindex_st;ii<=this.viewindex_en;ii++){ //表示開始。 this.OnViewInItem_FromBase(ii); } } /** 表示位置変更後。表示範囲更新。 */ protected void UpdateView_PositionChange() { int t_list_count = this.GetListCount(); int t_st_old = this.viewindex_st; int t_en_old = this.viewindex_en; //表示範囲チェック。 { if(t_list_count <= 0){ this.viewindex_st = -1; this.viewindex_en = -1; }else{ int t_index_st = this.view_position / this.item_length; int t_index_en = (this.view_position + this.view_length) / this.item_length; if(t_index_en > (t_list_count - 1)){ t_index_en = t_list_count - 1; } this.viewindex_st = t_index_st; this.viewindex_en = t_index_en; } } //表示中のアイテムの位置を設定。 for(int ii=this.viewindex_st;ii<=this.viewindex_en;ii++){ this.OnMoveItem_FromBase(ii); } if((t_st_old == this.viewindex_st)&&(t_en_old == this.viewindex_en)){ //変化なし。 }else{ //旧表示空間。 for(int ii=t_st_old;ii<=t_en_old;ii++){ if((ii<this.viewindex_st)||(this.viewindex_en<ii)){ //表示終了。 this.OnViewOutItem_FromBase(ii); } } //新表示空間。 for(int ii=this.viewindex_st;ii<=this.viewindex_en;ii++){ if((ii<t_st_old)||(t_en_old<ii)){ //表示開始。 this.OnViewInItem_FromBase(ii); } } } } /** アイテム追加後。表示範囲更新。 */ protected void UpdateView_Insert(int a_insert_index) { int t_list_count = this.GetListCount(); //表示範囲チェック。 { if(t_list_count <= 0){ this.viewindex_st = -1; this.viewindex_en = -1; }else{ int t_index_st = this.view_position / this.item_length; int t_index_en = (this.view_position + this.view_length) / this.item_length; if(t_index_en > (t_list_count - 1)){ t_index_en = t_list_count - 1; } this.viewindex_st = t_index_st; this.viewindex_en = t_index_en; } } //表示中のアイテムの位置を設定。 for(int ii=this.viewindex_st;ii<=this.viewindex_en;ii++){ this.OnMoveItem_FromBase(ii); } //表示範囲内チェック。 for(int ii=this.viewindex_st;ii<=this.viewindex_en;ii++){ this.OnViewInItem_FromBase(ii); } //表示範囲外チェック。 { this.OnViewOutItem_FromBase(this.viewindex_st - 1); this.OnViewOutItem_FromBase(this.viewindex_en + 1); } } /** アイテム削除後。表示範囲更新。 */ protected void UpdateView_Remove() { int t_list_count = this.GetListCount(); //表示範囲チェック。 { if(t_list_count <= 0){ this.viewindex_st = -1; this.viewindex_en = -1; }else{ if(this.item_length * t_list_count < this.view_length){ if(this.view_position != 0){ this.view_position = 0; this.OnChangeViewPosition(); } }else{ int t_position_max = this.item_length * t_list_count - this.view_length; if(this.view_position > t_position_max){ if(this.view_position != t_position_max){ this.view_position = t_position_max; this.OnChangeViewPosition(); } } } int t_index_st = this.view_position / this.item_length; int t_index_en = (this.view_position + this.view_length) / this.item_length; if(t_index_en > (t_list_count - 1)){ t_index_en = t_list_count - 1; } this.viewindex_st = t_index_st; this.viewindex_en = t_index_en; } } //表示中のアイテムの位置を設定。 for(int ii=this.viewindex_st;ii<=this.viewindex_en;ii++){ this.OnMoveItem_FromBase(ii); } //表示範囲内チェック。 for(int ii=this.viewindex_st;ii<=this.viewindex_en;ii++){ this.OnViewInItem_FromBase(ii); } //表示範囲外チェック。 { this.OnViewOutItem_FromBase(this.viewindex_st - 1); this.OnViewOutItem_FromBase(this.viewindex_en + 1); } } /** 表示位置。設定。 return : 変更あり。 */ public void SetViewPosition(int a_view_position) { int t_view_position = a_view_position; int t_list_count = this.GetListCount(); if(t_view_position < 0){ t_view_position = 0; }else if(this.item_length * t_list_count < this.view_length){ t_view_position = 0; }else{ int t_position_max = this.item_length * t_list_count - this.view_length; if(t_view_position > t_position_max){ t_view_position = t_position_max; } } if(this.view_position != t_view_position){ this.view_position = t_view_position; this.OnChangeViewPosition(); //表示範囲更新。 this.UpdateView_PositionChange(); } } /** 表示位置。取得。 */ public int GetViewPosition() { return this.view_position; } /** 矩形。設定。 */ public void SetRect(int a_x,int a_y,int a_w,int a_h) { //rect this.rect.Set(a_x,a_y,a_w,a_h); //eventplate this.eventplate.SetRect(a_x,a_y,a_w,a_h); //コールバック。矩形変更。 this.OnChangeRect_FromBase(); } /** 矩形。設定。 */ public void SetX(int a_x) { //rect this.rect.x = a_x; //eventplate this.eventplate.SetX(a_x); //コールバック。矩形変更。 this.OnChangeRect_FromBase(); } /** 矩形。設定。 */ public void SetY(int a_y) { //rect this.rect.y = a_y; //eventplate this.eventplate.SetY(a_y); //コールバック。矩形変更。 this.OnChangeRect_FromBase(); } /** 矩形。取得。 */ public int GetX() { return this.rect.x; } /** 矩形。取得。 */ public int GetY() { return this.rect.y; } /** 矩形。取得。 */ public int GetW() { return this.rect.w; } /** 矩形。取得。 */ public int GetH() { return this.rect.h; } /** [NEventPlate.OnOverCallBack_Base]イベントプレートに入場。 */ public void OnOverEnter(int a_value) { this.is_onover = true; } /** [NEventPlate.OnOverCallBack_Base]イベントプレートから退場。 */ public void OnOverLeave(int a_value) { this.is_onover = false; } /** オンオーバー。取得。 */ public bool IsOnOver() { return this.is_onover; } } }
namespace DomainModel { public class tbOne { public int No { get; set; } public string Name { get; set; } public string College { get; set; } public virtual tbTwo tbTwo { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InterviewQuestions { class PrintFrom1ToMaxNBitNum { //if n=3, 1,2,3~999 public static void Print1ToMaxOfNBits(int n) { if (n <= 0) return; var number = new int[n]; for (int i = 0; i < 10; ++i) { number[0] = i + '0'; //初始化设置number[0]是显示数字的最高位n。数字前的0 不显示 Print1ToMaxOfNBitsRecursively(number, 0); //依次递归设置number[1] ~ number[n-1],是显示数字的从高到低的(n-1) ~1位; } } private static void Print1ToMaxOfNBitsRecursively(int[] number, int bitChanging) { //约束条件,数组最右一位number[n-1]设置好了,即数字的最低一位 if (bitChanging == number.Length -1) { PrintNumbers(number); Console.Write(" "); return; } for (int i = 0; i < 10; i++) { number[bitChanging + 1] = i + '0';//设置下一位,依次设置每一位 为 0~9,实际上以0开始的不打印 Print1ToMaxOfNBitsRecursively(number,bitChanging+1); } } private static void PrintNumbers(int[] number) { bool isBegin0 = true; int nLength = number.Length; for (int i = 0; i < nLength; ++i) { if (isBegin0 && number[i] != '0') isBegin0 = false; if(!isBegin0) { Console.Write((char) number[i]); } } } public static void Run() { Print1ToMaxOfNBits(3); } } }
namespace LuaLu { using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using System.Reflection; public class TestClass { /* * for test: * I: int * Z: bool * J: long * B: byte * C: char * S: string * O: object */ public delegate bool DelegateIZ(int num); public int FieldI; public string PropertyS { get; set; } public TestClass() { FieldI = 0x12345678; PropertyS = "hello"; } public bool TestPrimitiveTypes(byte arg0, sbyte arg1, char arg2, bool arg3, short arg4, ushort arg5, int arg6, uint arg7, decimal arg8, long arg9, ulong arg10, float arg11, double arg12) { return arg0 == 100 && arg1 == 100 && arg2 == 100 && arg3 == true && arg4 == 100 && arg5 == 100 && arg6 == 100 && arg7 == 100 && arg8 == 100 && arg9 == 100 && arg10 == 100 && arg11 == 100 && arg12 == 100; } public bool TestValueTruncate(byte arg0, sbyte arg1, char arg2, short arg3, ushort arg4) { return arg0 == 0x78 && arg1 == 0x78 && arg2 == 0x5678 && arg3 == 0x5678 && arg4 == 0x5678; } public bool TestListI(List<int> arg0) { return arg0.Count == 3 && arg0[0] == 100 && arg0[1] == 200 && arg0[2] == 300; } public bool TestListValueTruncate(List<byte> arg0, List<char> arg1) { return arg0.Count == 2 && arg0[0] == 0x78 && arg0[1] == 0x78 && arg1.Count == 2 && arg1[0] == 0x5678 && arg1[1] == 0x5678; } public bool TestDictionaryII(Dictionary<int, int> arg0) { return arg0.Count == 3 && arg0[100] == 101 && arg0[200] == 202 && arg0[300] == 303; } public bool TestDictionarySS(Dictionary<string, string> arg0) { return arg0.Count == 2 && arg0["hello"] == "world" && arg0["test"] == "case"; } public bool TestDelegateIZ(DelegateIZ del) { return del(0x12345678); } public void TestActionS(Action<string> a) { a("hello"); } public int TestFuncSI(Func<string, int> f) { return f("hello"); } public static bool TestStaticMethodIZ(int num) { return num == 0x12345678; } public bool TestGeneric<T>(T t) { return true; } public bool TestGeneric<T>(int i, T t) { return true; } } }
using System.Linq; using NUnit.Framework; namespace AdvancedIoCTechniques { public class Dependency_Injection { public class BetterBlog { private readonly IRepository<Post> _repository; // we inject an interface of something which can save posts public BetterBlog(IRepository<Post> repository) { _repository = repository; } public void Save(Post post) { // when saving, we pass the call into the repository, which can be any implementation // SQL, file, whatever storage mechanism is abstracted away _repository.Save(post); } public Post[] FindAllPosts() { return _repository.FindAll().ToArray(); } } [Test] public void Now_It_Can_Be_Tested_Too() { // now testing is much easier, and there are no surprises var repo = new InMemoryRepository<Post>(); var blog = new BetterBlog(repo); Assert.IsEmpty(blog.FindAllPosts()); blog.Save(new Post()); Assert.IsNotEmpty(blog.FindAllPosts()); } // but don't forget the 'S' in S.O.L.I.D.!!! public class DontForgetAboutSingleReponsibilityPrinciple { public DontForgetAboutSingleReponsibilityPrinciple( Disposable dispo, Foo foo, Bar bar, IFirst0 first0, IFirst1 first1, IFirst2 first2, ISecond0 second0, ISecond1 second1, ISecond2 second2, IThird0 third0, IThird1 third1) { } } } }
using Autofac; using Nancy.Bootstrappers.Autofac; namespace Emanate.Service.Api { public class Bootstrapper : AutofacNancyBootstrapper { private static IContainer _container; public static void SetContainer(IContainer container) { _container = container; } protected override ILifetimeScope GetApplicationContainer() { return _container; } } }
using FoodInstructions.Models; using Microsoft.AspNetCore.Mvc; using MongoDB.Bson; using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FoodInstructions.Controllers { public class IngredientsController : Controller { public IActionResult Index() { var mongoClient = new MongoClient(); var database = mongoClient.GetDatabase("food_instructions"); var collection = database.GetCollection<Ingredient>("ingredients"); List<Ingredient> ingredientsInDb = collection.Find(r => true).ToList(); return View(ingredientsInDb); } /// <summary> /// Create page (form) for a new ingredient /// </summary> /// <returns>Create form view</returns> public IActionResult Create() { return View(); } [HttpPost] public IActionResult Create(Ingredient ingredient) { var mongoClient = new MongoClient(); var database = mongoClient.GetDatabase("food_instructions"); var collection = database.GetCollection<Ingredient>("ingredients"); collection.InsertOne(ingredient); return Redirect("/Ingredients"); } public IActionResult Show(string Id) { ObjectId objId = new ObjectId(Id); var mongoClient = new MongoClient(); var database = mongoClient.GetDatabase("food_instructions"); var collection = database.GetCollection<Ingredient>("ingredients"); Ingredient ingredient = collection.Find(i => i.Id == objId).FirstOrDefault(); return View(ingredient); } public IActionResult Edit(string Id) { ObjectId objId = new ObjectId(Id); MongoClient dbClient = new MongoClient(); var database = dbClient.GetDatabase("food_instructions"); var collection = database.GetCollection<Ingredient>("ingredients"); Ingredient ingredient = collection.Find(i => i.Id == objId).FirstOrDefault(); return View(ingredient); } [HttpPost] public IActionResult Edit(string Id, Ingredient ingredient) { ObjectId objId = new ObjectId(Id); MongoClient dbClient = new MongoClient(); var database = dbClient.GetDatabase("food_instructions"); var collection = database.GetCollection<Ingredient>("ingredients"); ingredient.Id = objId; collection.ReplaceOne(b => b.Id == objId, ingredient); return Redirect("/Ingredients/Show/" + Id); } [HttpPost] public IActionResult Delete(string Id) { ObjectId objId = new ObjectId(Id); MongoClient dbClient = new MongoClient(); var database = dbClient.GetDatabase("food_instructions"); var collection = database.GetCollection<Ingredient>("ingredients"); collection.DeleteOne(i => i.Id == objId); return Redirect("/Ingredients"); } } }
using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace BlazorSerialTerminal.Data { public class ServiceB : BackgroundService, IService { public delegate void ChangeEventHandler(int numberArg); public event ChangeEventHandler OnValueChanged; public int Counter { get; set; } private bool countDirectionDown = true; private const int upperCountLimit = 1000; private const int lowerCountLimit = 0; public ServiceB(ILoggerFactory loggerFactory) { Logger = loggerFactory.CreateLogger<ServiceB>(); Counter = upperCountLimit; } public ILogger Logger { get; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { Logger.LogInformation("ServiceB is starting."); stoppingToken.Register(() => Logger.LogInformation("ServiceB is stopping.")); while (!stoppingToken.IsCancellationRequested) { //Logger.LogInformation($"ServiceB is doing background work. Iterations:{Counter}"); if (Counter == lowerCountLimit) { countDirectionDown = false; } else if (Counter == upperCountLimit) { countDirectionDown = true; } if (countDirectionDown == true) Counter--; else Counter++; OnValueChanged?.Invoke(Counter); await Task.Delay(TimeSpan.FromMilliseconds(250), stoppingToken); } Logger.LogInformation("ServiceB has stopped."); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Common.Repository; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Moq; using SensorService.Controllers; using Xunit; using Environment = Domain.Entities.Environment; namespace SensorServiceTests { public class EnvironmentsControllerTest { [Fact] public async Task Put_WhenCalled_ReturnsOkResult() { var mockedRepo = new Mock<IHomeRepository>(); var environment = new Environment() { Id = Guid.Parse("00000000-0000-0000-0000-000000000000") }; mockedRepo.Setup(repo => repo.EditEnvironment(environment)).ReturnsAsync(true); var controller = new EnvironmentsController(mockedRepo.Object); var result = await controller.Put(environment); var contentResult = (result as OkObjectResult).Value; Assert.NotNull(contentResult); Assert.Equal(contentResult, environment); } [Fact] public async Task GetById_WhenCalled_ReturnsOkResult() { var mockedRepo = new Mock<IHomeRepository>(); var envs = new List<Environment> { new Environment() { Id = Guid.Parse("00000000-0000-0000-0000-000000000001") }, new Environment() { Id = Guid.Parse("00000000-0000-0000-0000-000000000002") } }; mockedRepo.Setup(repo => repo.GetEnvironment(Guid.Parse("00000000-0000-0000-0000-000000000001"))).ReturnsAsync(envs[0]); mockedRepo.Setup(repo => repo.GetEnvironment(Guid.Parse("00000000-0000-0000-0000-000000000002"))).ReturnsAsync(envs[1]); var controller = new EnvironmentsController(mockedRepo.Object); var result = await controller.Get("00000000-0000-0000-0000-000000000001"); var contentResult = (result as OkObjectResult).Value as Environment; Assert.NotNull(contentResult); Assert.Equal(contentResult, envs[0]); result = await controller.Get("00000000-0000-0000-0000-000000000002"); contentResult = (result as OkObjectResult).Value as Environment; Assert.NotNull(result); Assert.Equal(contentResult, envs[1]); } [Fact] public async Task GetById_WhenCalled_UnknownID_ReturnsNotFoundResult() { var mockedRepo = new Mock<IHomeRepository>(); var envs = new List<Environment> { new Environment() { Id = Guid.Parse("00000000-0000-0000-0000-000000000001") }, new Environment() { Id = Guid.Parse("00000000-0000-0000-0000-000000000002") } }; mockedRepo.Setup(repo => repo.GetEnvironment(Guid.Parse("00000000-0000-0000-0000-000000000001"))).ReturnsAsync(envs[0]); mockedRepo.Setup(repo => repo.GetEnvironment(Guid.Parse("00000000-0000-0000-0000-000000000002"))).ReturnsAsync(envs[1]); mockedRepo.Setup(repo => repo.GetEnvironment(Guid.Parse("00000000-0000-0000-0000-000000000003"))).ReturnsAsync((Environment)null); var controller = new EnvironmentsController(mockedRepo.Object); var result = await controller.Get("00000000-0000-0000-0000-000000000003"); var contentResult = result as NotFoundResult; Assert.NotNull(contentResult); } [Fact] public async Task Put_WhenCalled_BadObject_ReturnsBadRequest() { var mockedRepo = new Mock<IHomeRepository>(); var controller = new EnvironmentsController(mockedRepo.Object); var newEnv = new Environment() { Id = Guid.Parse("00000000-0000-0000-0000-000000000003") }; mockedRepo.Setup(repo => repo.EditEnvironment(newEnv)).ReturnsAsync(false); var result = await controller.Put(newEnv); var contentResult = result as BadRequestResult; Assert.NotNull(contentResult); } [Fact] public async Task Delete_WhenCalled_ReturnsOk() { var mockedRepo = new Mock<IHomeRepository>(); var controller = new EnvironmentsController(mockedRepo.Object); var newEnv = new Environment() { Id = Guid.Parse("00000000-0000-0000-0000-000000000003") }; mockedRepo.Setup(repo => repo.GetEnvironment(Guid.Parse("00000000-0000-0000-0000-000000000003"))).ReturnsAsync(newEnv); mockedRepo.Setup(repo => repo.DeleteEnvironment(Guid.Parse("00000000-0000-0000-0000-000000000003"))).ReturnsAsync(true); var result = await controller.Delete("00000000-0000-0000-0000-000000000003"); var contentResult = (result as OkObjectResult).Value; Assert.NotNull(contentResult); Assert.Equal(newEnv, contentResult); } [Fact] public async Task Delete_WhenCalled_UnknownObject_ReturnsNotFound() { var mockedRepo = new Mock<IHomeRepository>(); var controller = new EnvironmentsController(mockedRepo.Object); var newEnv = new Environment() { Id = Guid.Parse("00000000-0000-0000-0000-000000000003") }; mockedRepo.Setup(repo => repo.GetEnvironment(Guid.Parse("00000000-0000-0000-0000-000000000002"))).ReturnsAsync((Environment)null); var result = await controller.Delete("00000000-0000-0000-0000-000000000002"); var contentResult = result as NotFoundResult; Assert.NotNull(contentResult); } [Fact] public async Task Delete_WhenCalled_DeleteFailed_ReturnsServerError() { var mockedRepo = new Mock<IHomeRepository>(); var controller = new EnvironmentsController(mockedRepo.Object); var newEnv = new Environment() { Id = Guid.Parse("00000000-0000-0000-0000-000000000003") }; mockedRepo.Setup(repo => repo.GetEnvironment(Guid.Parse("00000000-0000-0000-0000-000000000003"))).ReturnsAsync(newEnv); mockedRepo.Setup(repo => repo.DeleteEnvironment(Guid.Parse("00000000-0000-0000-0000-000000000003"))).ReturnsAsync(false); var result = await controller.Delete("00000000-0000-0000-0000-000000000003"); var contentResult = result as StatusCodeResult; Assert.NotNull(contentResult); Assert.Equal(StatusCodes.Status500InternalServerError, contentResult.StatusCode); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace SqlServerTestApp { public partial class Form15 : Form { public Form15() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string query = @"SELECT [Название], [ID_Салон], [Кол-во машин], [Адрес] FROM [dbo].[Салон]"; ; var list = DBConnectionService.SendQueryToSqlServer(query); if (list == null || !list.Any()) { return; } dataGridView1.Rows.Clear(); dataGridView1.Columns.Clear(); dataGridView1.Columns.Add("Название", "Название"); dataGridView1.Columns.Add("ID_Салон", "ID_Салон"); dataGridView1.Columns.Add("Кол-во машин", "Кол-во машин"); dataGridView1.Columns.Add("Адрес", "Адрес"); foreach (var row in list) { dataGridView1.Rows.Add(row[0], row[1], row[2], row[3]); } dataGridView1.Refresh(); } private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e) { } private void comboBox1_DropDown(object sender, EventArgs e) { string query = "select [Кол-во машин], [Кол-во машин] from [dbo].[Салон]"; var list = DBConnectionService.SendQueryToSqlServer(query)?.Select(row => new IdentityItem(row[0], row[1])).ToArray(); comboBox1.Items.Clear(); comboBox1.Items.AddRange(list); } private void button2_Click(object sender, EventArgs e) { int? id = Convert.ToInt32(((IdentityItem)comboBox1.SelectedItem)?.Id); string query = "Delete from dbo.Салон where [Кол-во машин]=" + id; int? result = DBConnectionService.SendCommandToSqlServer(query); if (result != null && result > 0) { MessageBox.Show("Удалено"); comboBox1.SelectedItem = null; } } private void Form15_Load(object sender, EventArgs e) { } private void button3_Click(object sender, EventArgs e) { Form10 frm10 = new Form10(); frm10.Show(); this.Hide(); } private void label1_Click(object sender, EventArgs e) { } } }
using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class CatalogueController : MonoBehaviour { public static CatalogueController catalogueController; public GameObject locationInformation, listPlantInformation, questInformation; public GameObject itemPrefab, itemParent; public GameObject info; public GameObject[] item, quest; public string locationName; public int locationIndex; public string[] listLocationName, locationDescription; [System.Serializable] public class ListItem { public string[] itemName; } public ListItem[] listItem; [System.Serializable] public class ListQuest { public string[] questName; } public ListQuest[] listQuest; public bool isLocationShowing, isItemShowing, isMissionShowing, checkList; private void Awake() { if (catalogueController == null) { catalogueController = this; } else if (catalogueController != this) { Destroy(gameObject); } } void Start() { } void Update() { for (int i = 0; i < listLocationName.Length; i++) { if (locationName == listLocationName[i]) { if (listPlantInformation.activeSelf == true && checkList == true) { for (int j = 0; j < listItem[i].itemName.Length; j++) { item[j].gameObject.GetComponent<Text>().text = listItem[i].itemName[j]; } checkList = false; break; } if (questInformation.activeSelf == true && checkList == true) { for (int j = 0; j < listQuest[i].questName.Length; j++) { quest[j].gameObject.GetComponent<Text>().text = listQuest[i].questName[j]; } checkList = false; break; } if (locationInformation.activeSelf == true && checkList == true) { info.gameObject.GetComponent<Text>().text = locationDescription[i]; checkList = false; break; } } } SaveGameFunction(); } public void ButtonInfoFunction() { MapController.mapController.audioButton.Stop(); MapController.mapController.audioButton.clip = MapController.mapController.audioButtonSelect; MapController.mapController.audioButton.Play(); if (locationInformation.activeSelf == false) { locationInformation.SetActive(true); listPlantInformation.SetActive(false); questInformation.SetActive(false); checkList = true; } else { locationInformation.SetActive(false); } } public void ButtonListPlantFunction() { MapController.mapController.audioButton.Stop(); MapController.mapController.audioButton.clip = MapController.mapController.audioButtonSelect; MapController.mapController.audioButton.Play(); if (listPlantInformation.activeSelf == false) { listPlantInformation.SetActive(true); locationInformation.SetActive(false); questInformation.SetActive(false); checkList = true; } else { listPlantInformation.SetActive(false); } } public void ButtonQuestFunction() { MapController.mapController.audioButton.Stop(); MapController.mapController.audioButton.clip = MapController.mapController.audioButtonSelect; MapController.mapController.audioButton.Play(); if (questInformation.activeSelf == false) { questInformation.SetActive(true); listPlantInformation.SetActive(false); locationInformation.SetActive(false); checkList = true; } else { questInformation.SetActive(false); } } public void ButtonChoseLocationFunction() { LoadingController.loadingController.ButtonLoadSceneFunction(2); MapController.mapController.GetComponent<AudioSource>().Stop(); } public void SaveGameFunction() { PlayerPrefs.SetString("Location", locationName); for (int i = 0; i < listLocationName.Length; i++) { if (locationName == listLocationName[i]) { PlayerPrefs.SetInt("IndexLocation", i); break; } } } }
using QuickCollab.Models; using QuickCollab.Session; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Security; namespace QuickCollab.Controllers.MVC { public class LobbyController : Controller { private ISessionInstanceRepository _repo; private RegistrationService _service; public LobbyController(ISessionInstanceRepository repo, RegistrationService service) { _repo = repo; _service = service; } public ActionResult Index() { return View(_repo.ListAllSessions()); } public ActionResult JoinSession(string sessionId) { if (_service.RegisterConnection(User.Identity.Name, sessionId)) return RedirectToAction("Index", "SessionInstance", new { SessionId = sessionId }); // present view to fill in details return RedirectToAction("JoinSecured", new { sessionId = sessionId }); } public ActionResult CreateSession() { return View(); } [HttpPost] public ActionResult CreateSession(StartSettingsViewModel vm) { if (!ModelState.IsValid) return View(vm); try { SessionParameters parameters = new SessionParameters(vm.Public, vm.PersistHistory, vm.ConnectionExpiryInHours); _service.StartNewSession(vm.SessionName, vm.SessionPassword, parameters); } catch (Exception e) { return View(vm); } return RedirectToAction("Index"); } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using test1.Models; namespace ATS.Model.Context { public class TrainingManagementDBContext:DbContext { public DbSet<Trainer> Trainers { get; set; } public DbSet<Trainee> Trainees { get; set; } public DbSet<Institute> Institutes { get; set; } public DbSet<Branch> Branchs { get; set; } } }
using Server.Services; namespace Server { public abstract class ValidateAuth0UserFilterAttribute : BaseActionFilterAttribute { protected readonly IAuth0Service _auth0Service; public ValidateAuth0UserFilterAttribute(IMyCommunityContext dbContext, IAuth0Service auth0Service) : base(dbContext) { this._auth0Service = auth0Service; } } }
using Common.Tasks; using Money.ViewModels.Fronts; using Money.ViewModels.Transactions; using MoneyBack; using MoneyBack.Bankier; using MoneyBack.Currencies; using MoneyBack.Enums; using MoneyBack.Repositories; using MoneyBack.Requests; using MoneyBack.StockPrices; using Ninject; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Money { /// <summary> /// Interaction logic for Front.xaml /// </summary> public partial class FrontView : UserControl { public ObservableCollection<TransactionListItemViewModel> TransactionsViewModel { get; set; } public FrontInformationViewModel FrontInfoViewModel { get; set; } public AddTransactionViewModel AddViewModel { get; set; } private readonly int frontID; private readonly string companySymbol; private StockBroker broker; private StockPriceType stockPriceType; private ICurrency currency; public FrontView(int frontID) { this.frontID = frontID; InitializeComponent(); List<string> transactionTypes = new List<string>(); transactionTypes.Add("Buy"); transactionTypes.Add("Sell"); TransactionTypeCombo.ItemsSource = transactionTypes; var transactionRepository = Global.Kernel.Get<ITransactionRepository>(); var frontRepository = Global.Kernel.Get<IFrontRepository>(); var front = frontRepository.GetById(frontID); companySymbol = front.Company.Symbol; stockPriceType = (StockPriceType)front.Company.StockPriceType; FrontInfoViewModel = new FrontInformationViewModel(front); FrontInformations.DataContext = FrontInfoViewModel; currency = CurrencyProvider.ProvideCurrency((StockBroker)front.Company.Broker); TransactionsViewModel = new ObservableCollection<TransactionListItemViewModel>(transactionRepository.Where(t => t.FrontID == frontID) .OrderBy(t => t.Date) .Select(t => new TransactionListItemViewModel() { Amount = t.Amount, Commision = t.Commision, Price = t.Price, TransactionType = (TransactionTypeEnum)t.TypeID, Profit = t.Total.Value, Date = t.Date }).ToList()); foreach(var t in TransactionsViewModel) { t.Currency = currency; } broker = (StockBroker) front.Company.Broker; TransactionList.ItemsSource = TransactionsViewModel; NewTransaction.DataContext = AddViewModel = new AddTransactionViewModel(broker); GetInformationAboutFront().RunAsync(); } public async Task GetInformationAboutFront() { try { var stockPriceService = Global.Kernel.Get<IAllStockPriceService>(); var price = await stockPriceService.GetStockPrice(stockPriceType, companySymbol); lock (FrontInfoViewModel) { FrontInfoViewModel.HoldedPrice = price; } } catch (Exception) { int a = 5; //:( } } private void Add(object sender, RoutedEventArgs e) { if (AddViewModel.Price.HasValue == false || AddViewModel.Price <= 0 || AddViewModel.Amount.HasValue == false || AddViewModel.Amount <= 0) { MessageBox.Show("Wrong values", "Wrong values"); return; } var transaction = new Transaction() { Amount = AddViewModel.Amount.Value, Commision = AddViewModel.Comission, Date = AddViewModel.Date, FrontID = frontID, Price = (decimal)AddViewModel.Price, TypeID = (int)AddViewModel.TransactionTypeEnum }; var repo = Global.Kernel.Get<ITransactionRepository>(); repo.Add(transaction); repo.SaveChanges(); TransactionsViewModel.Add(new TransactionListItemViewModel() { Amount = transaction.Amount, Commision = transaction.Commision, Price = transaction.Price, TransactionType = (TransactionTypeEnum)transaction.TypeID, Profit = transaction.Total.Value, Currency = currency, Date = transaction.Date }); NewTransaction.DataContext = AddViewModel = new AddTransactionViewModel(broker); } } }
// Accord Statistics Library // The Accord.NET Framework // http://accord-framework.net // // Copyright © César Souza, 2009-2015 // cesarsouza at gmail.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // namespace Accord.Statistics.Kernels.Sparse { using System; /// <summary> /// Sparse Sigmoid Kernel. /// </summary> /// /// <remarks> /// Sigmoid kernels are not positive definite and therefore do not induce /// a reproducing kernel Hilbert space. However, they have been successfully /// used in practice (Schölkopf and Smola, 2002). /// </remarks> /// [Serializable] public sealed class SparseSigmoid : KernelBase, IKernel { private double gamma; private double constant; /// <summary> /// Constructs a Sparse Sigmoid kernel. /// </summary> /// /// <param name="alpha">Alpha parameter.</param> /// <param name="constant">Constant parameter.</param> /// public SparseSigmoid(double alpha, double constant) { this.gamma = alpha; this.constant = constant; } /// <summary> /// Constructs a Sparse Sigmoid kernel. /// </summary> /// public SparseSigmoid() : this(0.01, -Math.E) { } /// <summary> /// Gets or sets the kernel's gamma parameter. /// </summary> /// /// <remarks> /// In a sigmoid kernel, gamma is a inner product /// coefficient for the hyperbolic tangent function. /// </remarks> /// public double Gamma { get { return gamma; } set { gamma = value; } } /// <summary> /// Gets or sets the kernel's constant term. /// </summary> /// public double Constant { get { return constant; } set { constant = value; } } /// <summary> /// Sigmoid kernel function. /// </summary> /// /// <param name="x">Vector <c>x</c> in input space.</param> /// <param name="y">Vector <c>y</c> in input space.</param> /// <returns>Dot product in feature (kernel) space.</returns> /// public override double Function(double[] x, double[] y) { double sum = SparseLinear.Product(x, y); return System.Math.Tanh(Gamma * sum + Constant); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace UsingInterfaces { interface ITalkative { void SayHello(); void SayGoodBye(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace Atelier5.Model { public partial class Orders { public Decimal Amount { get { decimal somme = (from order_details in Order_Details select order_details.Unit_Price).Sum(); if(this.Freight!= 0) return (this.Freight.Value+somme); return this.Freight.Value; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using Kers.Models.Abstract; using Kers.Models.Contexts; using Kers.Models.Entities.KERScore; using Kers.Models.Entities.KERSmain; using Kers.Models.Repositories; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using SkiaSharp; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Caching.Distributed; using System.Text.RegularExpressions; namespace Kers.Controllers { [Route("api/[controller]")] public class PdfTripExpensesController : PdfBaseController { const int width = 792; const int height = 612; int locationLinesCharacterLength_personal = 50; int businessPurposeLinesCharacterLength_personal = 50; int locationLinesCharacterLength_county = 42; int businessPurposeLinesCharacterLength_county = 42; IExpenseRepository expenseRepo; public PdfTripExpensesController( KERScoreContext _context, IKersUserRepository userRepo, IExpenseRepository expenseRepo, KERSmainContext mainContext, IMemoryCache _cache ): base(_context, userRepo, mainContext, _cache){ this.expenseRepo = expenseRepo; } [HttpGet("tripexpenses/{year}/{month}/{userId?}/{overnight?}/{personal?}")] [Authorize] public IActionResult TripExpenses(int year, int month, int userId = 0, Boolean overnight = false, Boolean personal = true) { using (var stream = new SKDynamicMemoryWStream ()) using (var document = SKDocument.CreatePdf (stream, this.metadata( "Kers, Expenses, Reporting, Activity", "Expenses Report", "Mileage Report") )) { KersUser user; if(userId == 0){ user = this.CurrentUser(); }else{ user = this._context.KersUser. Where(u => u.Id == userId). Include(u => u.PersonalProfile). Include(u => u.RprtngProfile).ThenInclude(p => p.PlanningUnit). Include(u => u.ExtensionPosition). FirstOrDefault(); } var expenses = this.expenseRepo.PerMonth(user, year, month, "asc"); if(personal){ expenses = expenses.Where( e => e.VehicleType != 2 && e.isOvernight == overnight && e.Mileage != 0).ToList(); }else{ expenses = expenses.Where( e => e.VehicleType == 2).ToList(); } var dataObjext = new TripExpenses(expenses); dataObjext.SetIsItPersonalVehicle(personal); if( !personal ){ dataObjext.SetBusinessPurposeLinesCharacterLength( businessPurposeLinesCharacterLength_county ); dataObjext.SetLocationLinesCharacterLength( locationLinesCharacterLength_county ); dataObjext.setDivideExpenses( false ); }else{ dataObjext.SetBusinessPurposeLinesCharacterLength( businessPurposeLinesCharacterLength_personal ); dataObjext.SetLocationLinesCharacterLength( locationLinesCharacterLength_personal ); } var pagesData = dataObjext.getData(); var currentPageNumber = 1; foreach( var pg in pagesData){ var pdfCanvas = document.BeginPage(width, height); var runningY = dataObjext.GetPageMargins()/2; AddPageInfo(pdfCanvas, currentPageNumber, pagesData.Count(), user, new DateTime(year, month, 1), "Mileage Log", "landscape"); if(pg.header){ AddUkLogo(pdfCanvas, 16, 31); SummaryLandscapeInfo(pdfCanvas, year, month, user, "Mileage Log", overnight, personal); runningY += dataObjext.GetHeaderHeight(); } foreach( var exp in pg.data){ table(pdfCanvas, exp.expenses, 25, runningY, true, exp.title, exp.total, personal, exp.totalText); runningY += exp.expenses.Sum( e => e.lines) * dataObjext.GetLineHeight() + dataObjext.GetSpaceBetweenTables(); } if( !personal ){ pdfCanvas.RotateDegrees(30); pdfCanvas.DrawText( "Not Reimbursable", 160, 130, getPaint(80.0f, 1, 0x20000000)); pdfCanvas.RotateDegrees(-30); } if(pg.signatures){ Signatures(pdfCanvas, 30, 490); } document.EndPage(); currentPageNumber++; } document.Close(); return File(stream.DetachAsData().AsStream(), "application/pdf", "TripExpensesReport.pdf"); } } private int table(SKCanvas pdfCanvas, List<ExpenseNumLines> expenses, int x, int y, Boolean header = true, string title = "", float total = 0, bool personalVehicle = true, string totalText = "Total:"){ var rowHeight = 15; var beginningY = y; int[] verticalLinesX = { 0, 74, 154, 411, 652, 700, 746 }; if( !personalVehicle ){ verticalLinesX = new int[] { 0, 74, 154, 234, 435, 652, 702, 746 }; } SKPaint thinLinePaint = new SKPaint { Style = SKPaintStyle.Stroke, Color = SKColors.Black, StrokeWidth = 0.5f }; if(title != ""){ pdfCanvas.DrawText( title, x, y, getPaint(10.0f, 1)); y += 5; } if(header){ pdfCanvas.DrawLine(x, y, x + 746, y, thinLinePaint); pdfCanvas.DrawLine(x, y + rowHeight, x + 746, y + rowHeight, thinLinePaint); pdfCanvas.DrawLine(x, y + rowHeight - 0.5f, x + 746, y + rowHeight - 0.5f, thinLinePaint); pdfCanvas.DrawText("Date", x + 4, y + 11, getPaint(9.5f, 1)); if(personalVehicle){ pdfCanvas.DrawText("Starting Location", x + 76, y + 11, getPaint(9.35f, 1)); pdfCanvas.DrawText("Destination(s)", x + 158, y + 11, getPaint(9.5f, 1)); pdfCanvas.DrawText("Business Purpose", x + 415, y + 11, getPaint(9.5f, 1)); }else{ pdfCanvas.DrawText("Vehicle Name", x + 76, y + 11, getPaint(9.35f, 1)); pdfCanvas.DrawText("Starting Location", x + 156, y + 11, getPaint(9.35f, 1)); pdfCanvas.DrawText("Destination(s)", x + 236, y + 11, getPaint(9.5f, 1)); pdfCanvas.DrawText("Business Purpose", x + 437, y + 11, getPaint(9.5f, 1)); } pdfCanvas.DrawText("Program", x + 655, y + 11, getPaint(9.5f, 1)); pdfCanvas.DrawText("Mileage", x + 708, y + 11, getPaint(9.5f, 1)); DrawTableVerticalLines(pdfCanvas, verticalLinesX, x, y, 15); y += rowHeight; }else{ pdfCanvas.DrawLine(x, y, x + 746, y, thinLinePaint); } var i = 0; foreach( var expense in expenses){ var thisRowHeight = 0; var initialY = y; pdfCanvas.DrawText(expense.expense.ExpenseDate.ToString("MM/dd/yyyy") + "(" + expense.expense.ExpenseDate.ToString("ddd").Substring(0,2) + ")", x + 2, y + 11, getPaint(10.0f)); if(!personalVehicle && expense.expense.CountyVehicle != null && expense.expense.CountyVehicle.Name != null ){ pdfCanvas.DrawText(expense.expense.CountyVehicle.Name, x + 76, y + 11, getPaint(10.0f)); } if(expense.expense.ProgramCategory != null){ pdfCanvas.DrawText(expense.expense.ProgramCategory.ShortName, x + 655, y + 11, getPaint(10.0f)); } pdfCanvas.DrawText(Math.Round(expense.expense.Mileage, 2).ToString(), x + 742, y + 11, getPaint(10.0f, 0, 0xFF000000, SKTextAlign.Right)); var startingLocation = "Workplace"; if( expense.expense.StartingLocationType == 2 ){ startingLocation = "Home"; } pdfCanvas.DrawText(startingLocation, x + (personalVehicle ? 77 : 156 ), y + 11, getPaint(10.0f)); var locationLines = SplitLineToMultiline(expense.expense.ExpenseLocation, personalVehicle ? locationLinesCharacterLength_personal : locationLinesCharacterLength_county); var locationLinesY = y; var locationLinesHight = 0; foreach( var line in locationLines){ pdfCanvas.DrawText(line, x + (personalVehicle ? 158 : 237 ), locationLinesY + 11, getPaint(10.0f)); locationLinesY += rowHeight; locationLinesHight += rowHeight; } var businessPurposeLines = SplitLineToMultiline(expense.expense.BusinessPurpose, personalVehicle ? businessPurposeLinesCharacterLength_personal : businessPurposeLinesCharacterLength_county); var purposeLinesY = y; var purposeLineHight = 0; foreach( var line in businessPurposeLines){ pdfCanvas.DrawText(line, x + (personalVehicle ? 415 : 437 ), purposeLinesY + 11, getPaint(10.0f)); purposeLinesY += rowHeight; purposeLineHight += rowHeight; } y = Math.Max(locationLinesY, purposeLinesY); thisRowHeight = Math.Max( locationLinesHight, purposeLineHight); pdfCanvas.DrawLine(x, y, x + 746, y, thinLinePaint); DrawTableVerticalLines(pdfCanvas, verticalLinesX, x, initialY, thisRowHeight); i++; } if(total != 0){ pdfCanvas.DrawText( totalText + " ", x + 4, y + 13, getPaint(10.0f, 1)); pdfCanvas.DrawText(Math.Round(total, 2).ToString("0.00"), x + 742, y + 13, getPaint(10.0f, 1, 0xFF000000, SKTextAlign.Right)); } return i; } private int paintTable(SKCanvas pdfCanvas, IEnumerable<ExpenseRevision> expenses, int x, int y, int space, Boolean header = true, float total = 0){ var rowHeight = 15; var beginningY = y; int[] verticalLinesX = { 0, 74, 360, 650, 700, 746 }; SKPaint thinLinePaint = new SKPaint { Style = SKPaintStyle.Stroke, Color = SKColors.Black, StrokeWidth = 0.5f }; if(header){ pdfCanvas.DrawLine(x, y, x + 746, y, thinLinePaint); pdfCanvas.DrawLine(x, y + rowHeight, x + 746, y + rowHeight, thinLinePaint); pdfCanvas.DrawLine(x, y + rowHeight - 0.5f, x + 746, y + rowHeight - 0.5f, thinLinePaint); pdfCanvas.DrawText("Date", x + 10, y + 11, getPaint(10.0f, 1)); pdfCanvas.DrawText("Destination(s)", x + 78, y + 11, getPaint(10.0f, 1)); pdfCanvas.DrawText("Business Purpose", x + 364, y + 11, getPaint(10.0f, 1)); pdfCanvas.DrawText("Program", x + 652, y + 11, getPaint(10.0f, 1)); pdfCanvas.DrawText("Mileage", x + 704, y + 11, getPaint(10.0f, 1)); DrawTableVerticalLines(pdfCanvas, verticalLinesX, x, y, 15); y += rowHeight; }else{ pdfCanvas.DrawLine(x, y, x + 746, y, thinLinePaint); } var i = 0; foreach( var expense in expenses){ var thisRowHeight = 0; var initialY = y; pdfCanvas.DrawText(expense.ExpenseDate.ToString("MM/dd/yyyy") + "(" + expense.ExpenseDate.ToString("ddd").Substring(0,2) + ")", x + 2, y + 11, getPaint(10.0f)); if(expense.ProgramCategory != null){ pdfCanvas.DrawText(expense.ProgramCategory.ShortName, x + 655, y + 11, getPaint(10.0f)); } pdfCanvas.DrawText(expense.Mileage.ToString(), x + 737, y + 11, getPaint(10.0f, 0, 0xFF000000, SKTextAlign.Right)); var locationLines = SplitLineToMultiline(expense.ExpenseLocation, 52); var locationLinesY = y; var locationLinesHight = 0; foreach( var line in locationLines){ pdfCanvas.DrawText(line, x + 78, locationLinesY + 11, getPaint(10.0f)); locationLinesY += rowHeight; locationLinesHight += rowHeight; } var businessPurposeLines = SplitLineToMultiline(expense.BusinessPurpose, 50); var purposeLinesY = y; var purposeLineHight = 0; foreach( var line in businessPurposeLines){ pdfCanvas.DrawText(line, x + 364, purposeLinesY + 11, getPaint(10.0f)); purposeLinesY += rowHeight; purposeLineHight += rowHeight; } y = Math.Max(locationLinesY, purposeLinesY); thisRowHeight = Math.Max( locationLinesHight, purposeLineHight); pdfCanvas.DrawLine(x, y, x + 746, y, thinLinePaint); DrawTableVerticalLines(pdfCanvas, verticalLinesX, x, initialY, thisRowHeight); i++; if( (y - beginningY) > space ){ break; } } if(total != 0){ pdfCanvas.DrawText("Total: ", x + 4, y + 13, getPaint(10.0f, 1)); pdfCanvas.DrawText(total.ToString("0.00"), x + 737, y + 13, getPaint(10.0f, 1, 0xFF000000, SKTextAlign.Right)); } return i; } private void DrawTableVerticalLines(SKCanvas pdfCanvas, int[] PosiitionsX, int x, int y, int length){ SKPaint thinLinePaint = new SKPaint { Style = SKPaintStyle.Stroke, Color = SKColors.Black, StrokeWidth = 0.5f }; foreach( var pos in PosiitionsX){ pdfCanvas.DrawLine(x + pos, y, x + pos, y + length, thinLinePaint); } } private void Signatures( SKCanvas pdfCanvas, int x, int y){ SKPaint thinLinePaint = new SKPaint { Style = SKPaintStyle.Stroke, Color = SKColors.Black, StrokeWidth = 0.5f }; pdfCanvas.DrawLine(x, y + 60, x + 300, y + 60, thinLinePaint); pdfCanvas.DrawText("Employee Signature & Date", x + 85, y + 72, getPaint(10.0f)); pdfCanvas.DrawLine(x + 400, y, x + 700, y, thinLinePaint); pdfCanvas.DrawText("Authorized Reviewer Printed Name", x + 475, y + 12, getPaint(10.0f)); pdfCanvas.DrawLine(x + 400, y + 60, x + 700, y + 60, thinLinePaint); pdfCanvas.DrawText("Authorized Reviewer Signature & Date", x + 470, y + 72, getPaint(10.0f)); } } public class TripExpenses{ List<ExpenseRevision> _expenses; List<ExpenseNumLines> _expenseLines; List<ExpenseNumLines> _countyExpenses; List<ExpenseNumLines> _proffesionalDevelopmentExpenses; List<ExpenseNumLines> _nonCountyExpenses; bool divideExpanses = true; bool isItPersonalVehicle = true; List<ExpenseMileageLogPageData> pages = new List<ExpenseMileageLogPageData>(); string[] nonCountySourceNames = new string[]{"State", "Federal"}; string[] professionalDevelopmentNames = new string[]{"Professional Improvement (Reimbursed to Employee)"}; int locationLinesCharacterLength = 52; int businessPurposeLinesCharacterLength = 50; //********************************/ // Dimensions definition // //********************************/ int headerHeight = 130; int lineHeight = 15; int signaturesHeight = 160; int pageHeight = 612; int pageMargins = 92; int spaceBetweenTables = 80; public TripExpenses( List<ExpenseRevision> _expenses ){ this._expenses = _expenses; } /************************/ // Getters /************************/ public int GetHeaderHeight(){ return headerHeight; } public int GetLineHeight(){ return lineHeight; } public int GetSignaturesHeight(){ return signaturesHeight; } public int GetSpaceBetweenTables(){ return spaceBetweenTables; } public int getLinesCounty(){ return getLinesCount(_countyExpenses); } public int getLinesNotCounty(){ return getLinesCount(_nonCountyExpenses); } public int GetPageMargins(){ return pageMargins; } public List<ExpenseNumLines> getCountyExpenses(){ return _countyExpenses; } public List<ExpenseNumLines> getNonCountyExpenses(){ return _nonCountyExpenses; } public List<ExpenseMileageLogPageData> getData(){ getLines(); DivideExpenses(); CalculatePageData(); return pages; } private int getLinesCount(List<ExpenseNumLines> exp){ return exp.Sum( e => e.lines); } private void getLines(){ _expenseLines = new List<ExpenseNumLines>(); foreach( var expense in _expenses){ var ln = new ExpenseNumLines(); ln.expense = expense; var locLines = PdfBaseController.SplitLineToMultiline(expense.ExpenseLocation, locationLinesCharacterLength); ln.locationLines = locLines; var busnLines = PdfBaseController.SplitLineToMultiline(expense.BusinessPurpose, businessPurposeLinesCharacterLength); ln.purposeLines = busnLines; ln.lines = Math.Max(locLines.Count(), busnLines.Count()); _expenseLines.Add(ln); } } public void CalculatePageData(){ var pageSpace = pageHeight - pageMargins; var countyRemaining = _countyExpenses.Count();; var professionalDevelopmentRemaining = _proffesionalDevelopmentExpenses.Count(); var nonCountyRemaining = _nonCountyExpenses.Count(); var signaturesAdded = false; var currentPage = 1; do{ var spaceRemaining = pageSpace; var pg = new ExpenseMileageLogPageData(); if(currentPage == 1){ pg.header = true; spaceRemaining -= headerHeight; } //County Funded Travel if(countyRemaining > 0){ var tbl = new ExpenseMileageLogTableData(); if(countyRemaining < _countyExpenses.Count()){ tbl.title = ""; }else{ if(!this.isItPersonalVehicle){ tbl.title = "County Vehicle Mileage (Not Reimbursed):"; tbl.totalText = "Total County Vehicle Mileage (Not Reimbursed):"; } } var rmnng = _countyExpenses.Skip(_countyExpenses.Count() - countyRemaining); foreach( var exp in rmnng){ if(exp.lines * lineHeight < spaceRemaining){ tbl.expenses.Add(exp); countyRemaining--; spaceRemaining -= exp.lines * lineHeight; }else{ break; } } if(tbl.expenses.Count() > 0){ if(countyRemaining <= 0){ tbl.total = _countyExpenses.Sum( e => e.expense.Mileage); spaceRemaining -= lineHeight; } pg.data.Add(tbl); } } //Professional Development Travel if( countyRemaining <= 0 && professionalDevelopmentRemaining > 0 ){ var tbl = new ExpenseMileageLogTableData(); var rmnng = _proffesionalDevelopmentExpenses.Skip(_proffesionalDevelopmentExpenses.Count() - professionalDevelopmentRemaining); if( countyRemaining == 0 && professionalDevelopmentRemaining == _proffesionalDevelopmentExpenses.Count()){ spaceRemaining -= spaceBetweenTables; spaceRemaining -= lineHeight; tbl.title = "Professional Improvement Travel:"; }else{ tbl.title = ""; } tbl.totalText = "Total Professional Improvement Travel (separate travel report required):"; foreach( var exp in rmnng){ if(exp.lines * lineHeight < spaceRemaining){ tbl.expenses.Add(exp); professionalDevelopmentRemaining--; spaceRemaining -= exp.lines * lineHeight; }else{ break; } } if(tbl.expenses.Count() > 0){ if(professionalDevelopmentRemaining <= 0){ tbl.total = _proffesionalDevelopmentExpenses.Sum( e => e.expense.Mileage); spaceRemaining -= lineHeight; } pg.data.Add(tbl); } } //UK Funded Travel if( countyRemaining <= 0 && professionalDevelopmentRemaining <= 0 && nonCountyRemaining > 0){ var tbl = new ExpenseMileageLogTableData(); var rmnng = _nonCountyExpenses.Skip(_nonCountyExpenses.Count() - nonCountyRemaining - professionalDevelopmentRemaining); if( countyRemaining == 0 && professionalDevelopmentRemaining == 0 && nonCountyRemaining == _nonCountyExpenses.Count()){ spaceRemaining -= spaceBetweenTables; spaceRemaining -= lineHeight; tbl.title = "UK Funded Travel:"; }else{ tbl.title = ""; } tbl.totalText = "Total UK Funded Travel (separate travel report required):"; foreach( var exp in rmnng){ if(exp.lines * lineHeight < spaceRemaining){ tbl.expenses.Add(exp); nonCountyRemaining--; spaceRemaining -= exp.lines * lineHeight; }else{ break; } } if(tbl.expenses.Count() > 0){ if(nonCountyRemaining <= 0){ tbl.total = _nonCountyExpenses.Sum( e => e.expense.Mileage); spaceRemaining -= lineHeight; } pg.data.Add(tbl); } } if(countyRemaining <= 0 && nonCountyRemaining <= 0 && professionalDevelopmentRemaining <= 0 && spaceRemaining >= signaturesHeight){ signaturesAdded = true; pg.signatures = true; } currentPage++; pages.Add(pg); }while( !signaturesAdded); } /************************/ // Setters /************************/ public void SetLocationLinesCharacterLength(int length){ locationLinesCharacterLength = length; } public void SetBusinessPurposeLinesCharacterLength(int length){ businessPurposeLinesCharacterLength = length; } public void setPageHeight(int height){ this.pageHeight = height; } public void setDivideExpenses( bool divide ){ this.divideExpanses = divide; } public void SetIsItPersonalVehicle( bool personal ){ this.isItPersonalVehicle = personal; } private void DivideExpenses(){ if( this.divideExpanses ){ this._nonCountyExpenses = _expenseLines.Where( e => nonCountySourceNames.Contains( e.expense.FundingSourceMileage != null ? e.expense.FundingSourceMileage.Name : "" ) ).ToList(); var remaining = _expenseLines.Except( this._nonCountyExpenses ).ToList(); this._proffesionalDevelopmentExpenses = remaining.Where( e => professionalDevelopmentNames.Contains( e.expense.FundingSourceMileage != null ? e.expense.FundingSourceMileage.Name : "")).ToList(); this._countyExpenses = remaining.Except( this._proffesionalDevelopmentExpenses ).ToList(); }else{ this._countyExpenses = _expenseLines; this._nonCountyExpenses = new List<ExpenseNumLines>(); this._proffesionalDevelopmentExpenses = new List<ExpenseNumLines>(); } } } public class ExpenseNumLines{ public int lines; public ExpenseRevision expense; public List<string> locationLines; public List<string> purposeLines; } public class ExpenseMileageLogPageData{ public bool header = false; public bool signatures = false; public List<ExpenseMileageLogTableData> data = new List<ExpenseMileageLogTableData>(); } public class ExpenseMileageLogTableData{ public bool header = true; public string title = "County Funded Travel:"; public string totalText = "Total County Funded Travel (separate travel report required):"; public float total = 0; public List<ExpenseNumLines> expenses = new List<ExpenseNumLines>(); } }
// The file has been modified by Victor Alexiev (some properties added) using System; using SharpPcap.Packets.Util; namespace SharpPcap.Packets { public class IPv4Packet : EthernetPacket { public const int HeaderMinimumLength = 20; /// <summary> Type of service code constants for IP. Type of service describes /// how a packet should be handled. /// <p> /// TOS is an 8-bit record in an IP header which contains a 3-bit /// precendence field, 4 TOS bit fields and a 0 bit. /// </p> /// <p> /// The following constants are bit masks which can be logically and'ed /// with the 8-bit IP TOS field to determine what type of service is set. /// </p> /// <p> /// Taken from TCP/IP Illustrated V1 by Richard Stevens, p34. /// </p> /// </summary> public struct TypesOfService_Fields { public readonly static int MINIMIZE_DELAY = 0x10; public readonly static int MAXIMIZE_THROUGHPUT = 0x08; public readonly static int MAXIMIZE_RELIABILITY = 0x04; public readonly static int MINIMIZE_MONETARY_COST = 0x02; public readonly static int UNUSED = 0x01; } public struct Flags_Fields { public readonly static int RESERVED = 0x04; public readonly static int DONT_FRAGMENT = 0x02; public readonly static int MORE_FRAGMENTS = 0x041; } public static int ipVersion = 4; /// <summary> /// should be overriden by upper classes /// </summary> public override void OnOffsetChanged() { base.OnOffsetChanged(); _ipOffset = _ethPayloadOffset + IPHeaderLength; } /// <summary> Get the IP version code.</summary> public virtual int Version { get { return IPVersion; } set { IPVersion = value; } } /// <summary> Get the IP version code.</summary> virtual public int IPVersion { get { return (ArrayHelper.extractInteger(Bytes, _ethPayloadOffset + IPv4Fields_Fields.IP_VER_POS, IPv4Fields_Fields.IP_VER_LEN) >> 4) & 0xF; } set { Bytes[_ethPayloadOffset + IPv4Fields_Fields.IP_VER_POS] &= (byte)(0x0F); Bytes[_ethPayloadOffset + IPv4Fields_Fields.IP_VER_POS] |= (byte)(((value << 4) & 0xF0)); } } /// <summary> Fetch the IP header length in bytes. </summary> /// <summary> Sets the IP header length field. At most, this can be a /// four-bit value. The high order bits beyond the fourth bit /// will be ignored. /// /// </summary> virtual public int IPHeaderLength { get { return (ArrayHelper.extractInteger(Bytes, _ethPayloadOffset + IPv4Fields_Fields.IP_VER_POS, IPv4Fields_Fields.IP_VER_LEN) & 0xF) * 4; } set { value /= 4; // Clear low order bits and then set Bytes[_ethPayloadOffset + IPv4Fields_Fields.IP_VER_POS] &= (byte)(0xF0); Bytes[_ethPayloadOffset + IPv4Fields_Fields.IP_VER_POS] |= (byte)(value & 0x0F); // set offset into _bytes of previous layers _ipOffset = _ethPayloadOffset + IPHeaderLength; } } /// <summary> Fetch the packet IP header length.</summary> override public int HeaderLength { get { return IPHeaderLength; } } /// <summary> Fetch the unique ID of this IP datagram. The ID normally /// increments by one each time a datagram is sent by a host. /// </summary> /// <summary> Sets the IP identification header value. /// /// </summary> virtual public int Id { get { return ArrayHelper.extractInteger(Bytes, _ethPayloadOffset + IPv4Fields_Fields.IP_ID_POS, IPv4Fields_Fields.IP_ID_LEN); } set { ArrayHelper.insertLong(Bytes, value, _ethPayloadOffset + IPv4Fields_Fields.IP_ID_POS, IPv4Fields_Fields.IP_ID_LEN); } } /// <summary> Fetch fragment offset.</summary> /// <summary> Sets the fragment offset header value. The offset specifies a /// number of octets (i.e., bytes). /// /// </summary> virtual public int FragmentOffset { get { return ArrayHelper.extractInteger(Bytes, _ethPayloadOffset + IPv4Fields_Fields.IP_FRAG_POS, IPv4Fields_Fields.IP_FRAG_LEN) & 0x1FFF; } set { Bytes[_ethPayloadOffset + IPv4Fields_Fields.IP_FRAG_POS] &= (byte)(0xE0); Bytes[_ethPayloadOffset + IPv4Fields_Fields.IP_FRAG_POS] |= (byte)(((value >> 8) & 0x1F)); Bytes[_ethPayloadOffset + IPv4Fields_Fields.IP_FRAG_POS + 1] = (byte)(value & 0xFF); } } /// <summary> Fetch the IP address of the host where the packet originated from.</summary> virtual public System.Net.IPAddress SourceAddress { get { return IPPacket.GetIPAddress(System.Net.Sockets.AddressFamily.InterNetwork, _ethPayloadOffset + IPv4Fields_Fields.IP_SRC_POS, Bytes); } set { byte[] address = value.GetAddressBytes(); System.Array.Copy(address, 0, Bytes, _ethPayloadOffset + IPv4Fields_Fields.IP_SRC_POS, address.Length); } } /// <summary> Fetch the IP address of the host where the packet is destined.</summary> virtual public System.Net.IPAddress DestinationAddress { get { return IPPacket.GetIPAddress(System.Net.Sockets.AddressFamily.InterNetwork, _ethPayloadOffset + IPv4Fields_Fields.IP_DST_POS, Bytes); } set { byte[] address = value.GetAddressBytes(); System.Array.Copy(address, 0, Bytes, _ethPayloadOffset + IPv4Fields_Fields.IP_DST_POS, address.Length); } } /// <summary> Fetch the IP header a byte array.</summary> virtual public byte[] IPHeader { get { return PacketEncoding.extractHeader(_ethPayloadOffset, IPHeaderLength, Bytes); } set // NB! added by Victor Alexiev { Array.Copy(value, 0, Bytes, _ethPayloadOffset, IPHeaderLength); } } /// <summary> Fetch the IP header as a byte array.</summary> override public byte[] Header { get { return IPHeader; } } /// <summary> Fetch the IP data as a byte array.</summary> virtual public byte[] IPData { get { return PacketEncoding.extractData(_ethPayloadOffset, IPHeaderLength, Bytes, IPPayloadLength); } set { // retrieve the current payload length int currentIPPayloadLength = IPPayloadLength; // compute the difference between the current and the // requested payload lengths int changeInLength = value.Length - currentIPPayloadLength; // create a new buffer for the entire packet byte[] newByteArray = new Byte[Bytes.Length + changeInLength]; // copy the old contents over to the new buffer Array.Copy(Bytes, newByteArray, Bytes.Length - currentIPPayloadLength); // copy the new payload into place Array.Copy(value, 0, newByteArray, Bytes.Length - currentIPPayloadLength, value.Length); // update the Bytes to the new byte array Bytes = newByteArray; // update the IP length IPPayloadLength = value.Length; } } /// <summary> Fetch the header checksum.</summary> virtual public int IPChecksum { get { return ArrayHelper.extractInteger(Bytes, _ethPayloadOffset + IPv4Fields_Fields.IP_CSUM_POS, IPv4Fields_Fields.IP_CSUM_LEN); } set { SetChecksum(value, _ethPayloadOffset + IPv4Fields_Fields.IP_CSUM_POS); } } /// <summary> Check if the IP packet is valid, checksum-wise.</summary> virtual public bool ValidChecksum { get { return ValidIPChecksum; } } /// <summary> Check if the IP packet is valid, checksum-wise.</summary> virtual public bool ValidIPChecksum { get { // first validate other information about the packet. if this stuff // is not true, the packet (and therefore the checksum) is invalid // - ip_hl >= 5 (ip_hl is the length in 4-byte words) if (IPHeaderLength < IPv4Fields_Fields.IP_HEADER_LEN) { return false; } else { return (ChecksumUtils.OnesSum(Bytes, _ethPayloadOffset, IPHeaderLength) == 0xFFFF); } } } /// <summary> Fetch ascii escape sequence of the color associated with this packet type.</summary> override public System.String Color { get { return AnsiEscapeSequences_Fields.WHITE; } } // offset from beginning of byte array where IP header ends (i.e., // size of ethernet frame header and IP header protected internal int _ipOffset; /// <summary> Create a new IP packet. </summary> public IPv4Packet(int lLen, byte[] bytes) : base(lLen, bytes) { _ipOffset = _ethPayloadOffset + IPHeaderLength; } /// <summary> Create a new IP packet.</summary> public IPv4Packet(int lLen, byte[] bytes, Timeval tv) : this(lLen, bytes) { this._timeval = tv; } /// <summary> Fetch the type of service.</summary> public virtual int TypeOfService { get { return ArrayHelper.extractInteger(Bytes, _ethPayloadOffset + IPv4Fields_Fields.IP_TOS_POS, IPv4Fields_Fields.IP_TOS_LEN); } set { Bytes[_ethPayloadOffset + IPv4Fields_Fields.IP_TOS_POS] = (byte)(value & 0xFF); } } public virtual int Precedence { get { return (TypeOfService & 0xE0) >> 5; } } public virtual bool MinimizeDelay { get { return (TypeOfService & TypesOfService_Fields.MINIMIZE_DELAY) != 0; } } public virtual bool MaximizeThroughput { get { return (TypeOfService & TypesOfService_Fields.MAXIMIZE_THROUGHPUT) != 0; } } public virtual bool MaximizeReliability { get { return (TypeOfService & TypesOfService_Fields.MAXIMIZE_RELIABILITY) != 0; } } public virtual bool MinimizeMonetaryCost { get { return (TypeOfService & TypesOfService_Fields.MINIMIZE_MONETARY_COST) != 0; } } /// <summary> Fetch the IP length in bytes.</summary> public virtual int Length { get { return IPTotalLength; } set { IPTotalLength = value; } } /// <summary> Fetch the IP length in bytes.</summary> public virtual int IPTotalLength { get { return ArrayHelper.extractInteger(Bytes, _ethPayloadOffset + IPv4Fields_Fields.IP_LEN_POS, IPv4Fields_Fields.IP_LEN_LEN); } set { ArrayHelper.insertLong(Bytes, value, _ethPayloadOffset + IPv4Fields_Fields.IP_LEN_POS, IPv4Fields_Fields.IP_LEN_LEN); } } public virtual int IPPayloadLength { get { return IPTotalLength - IPv4Fields_Fields.IP_HEADER_LEN; } set { IPTotalLength = value + IPv4Fields_Fields.IP_HEADER_LEN; } } /// <summary> Fetch fragmentation flags.</summary> public virtual int FragmentFlags { get { // fragment flags are the high 3 bits return (ArrayHelper.extractInteger(Bytes, _ethPayloadOffset + IPv4Fields_Fields.IP_FRAG_POS, IPv4Fields_Fields.IP_FRAG_LEN) >> 13) & 0x7; } set { Bytes[_ethPayloadOffset + IPv4Fields_Fields.IP_FRAG_POS] &= (byte)(0x1F); Bytes[_ethPayloadOffset + IPv4Fields_Fields.IP_FRAG_POS] |= (byte)(((value << 5) & 0xE0)); } } public virtual bool ReservedFlag { get { return (FragmentFlags & Flags_Fields.RESERVED) != 0; } } public virtual bool DontFragment { get { return (FragmentFlags & Flags_Fields.DONT_FRAGMENT) != 0; } } public virtual bool MoreFragments { get { return (FragmentFlags & Flags_Fields.MORE_FRAGMENTS) != 0; } } /// <summary> Fetch the time to live. TTL sets the upper limit on the number of /// routers through which this IP datagram is allowed to pass. /// Originally intended to be the number of seconds the packet lives it is now decremented /// by one each time a router passes the packet on /// /// 8-bit value /// </summary> public virtual int TimeToLive { get { return ArrayHelper.extractInteger(Bytes, _ethPayloadOffset + IPv4Fields_Fields.IP_TTL_POS, IPv4Fields_Fields.IP_TTL_LEN); } set { Bytes[_ethPayloadOffset + IPv4Fields_Fields.IP_TTL_POS] = (byte)value; } } /// <summary> Fetch the code indicating the type of protocol embedded in the IP</summary> public virtual IPProtocol.IPProtocolType IPProtocol { get { return (IPProtocol.IPProtocolType)ArrayHelper.extractInteger(Bytes, _ethPayloadOffset + IPv4Fields_Fields.IP_CODE_POS, IPv4Fields_Fields.IP_CODE_LEN); } set { Bytes[_ethPayloadOffset + IPv4Fields_Fields.IP_CODE_POS] = (byte)value; } } /// <summary> Fetch the IP data as a byte array.</summary> public override byte[] Data { get { return IPData; } } /// <summary> Fetch the IP header checksum.</summary> public virtual int Checksum { get { return IPChecksum; } set { IPChecksum = value; } } /// <summary> Sets the IP header checksum.</summary> protected internal virtual void SetChecksum(int cs, int checkSumOffset) { ArrayHelper.insertLong(Bytes, cs, checkSumOffset, 2); } protected internal virtual void SetTransportLayerChecksum(int cs, int csPos) { SetChecksum(cs, _ipOffset + csPos); } /// <summary> Computes the IP checksum, optionally updating the IP checksum header. /// /// </summary> /// <param name="update">Specifies whether or not to update the IP checksum /// header after computing the checksum. A value of true indicates /// the header should be updated, a value of false indicates it /// should not be updated. /// </param> /// <returns> The computed IP checksum. /// </returns> public int ComputeIPChecksum(bool update) { //copy the ip header byte[] ip = ArrayHelper.copy(Bytes, _ethPayloadOffset, IPHeaderLength); //reset the checksum field (checksum is calculated when this field is zeroed) ArrayHelper.insertLong(ip, 0, IPv4Fields_Fields.IP_CSUM_POS, 2); //compute the one's complement sum of the ip header int cs = ChecksumUtils.OnesComplementSum(ip, 0, ip.Length); if (update) { IPChecksum = cs; } return cs; } /// <summary> Same as <code>computeIPChecksum(true);</code> /// /// </summary> /// <returns> The computed IP checksum value. /// </returns> public int ComputeIPChecksum() { return ComputeIPChecksum(true); } // Prepend to the given byte[] origHeader the portion of the IPv6 header used for // generating an tcp checksum // // http://en.wikipedia.org/wiki/Transmission_Control_Protocol#TCP_checksum_using_IPv4 // http://tools.ietf.org/html/rfc793 protected internal virtual byte[] AttachPseudoIPHeader(byte[] origHeader) { bool odd = origHeader.Length % 2 != 0; int numberOfBytesFromIPHeaderUsedToGenerateChecksum = 12; int headerSize = numberOfBytesFromIPHeaderUsedToGenerateChecksum + origHeader.Length; if (odd) headerSize++; byte[] headerForChecksum = new byte[headerSize]; // 0-7: ip src+dest addr Array.Copy(Bytes, _ethPayloadOffset + IPv4Fields_Fields.IP_SRC_POS, headerForChecksum, 0, 8); // 8: always zero headerForChecksum[8] = 0; // 9: ip protocol headerForChecksum[9] = (byte)IPProtocol; // 10-11: header+data length ArrayHelper.insertLong(headerForChecksum, origHeader.Length, 10, 2); // prefix the pseudoHeader to the header+data Array.Copy(origHeader, 0, headerForChecksum, numberOfBytesFromIPHeaderUsedToGenerateChecksum, origHeader.Length); //if not even length, pad with a zero if (odd) headerForChecksum[headerForChecksum.Length - 1] = 0; return headerForChecksum; } public override bool IsValid(out string errorString) { errorString = string.Empty; // validate the base class(es) bool baseValid = base.IsValid(out errorString); // perform some quick validation if (IPTotalLength < IPHeaderLength) { errorString += string.Format("IPTotalLength {0} < IPHeaderLength {1}", IPTotalLength, IPHeaderLength); return false; } return baseValid; } public virtual bool IsValidTransportLayerChecksum(bool pseudoIPHeader) { byte[] upperLayer = IPData; if (pseudoIPHeader) upperLayer = AttachPseudoIPHeader(upperLayer); int onesSum = ChecksumUtils.OnesSum(upperLayer); return (onesSum == 0xFFFF); } /// <summary> Convert this IP packet to a readable string.</summary> public override System.String ToString() { return ToColoredString(false); } /// <summary> Generate string with contents describing this IP packet.</summary> /// <param name="colored">whether or not the string should contain ansi /// color escape sequences. /// </param> public override System.String ToColoredString(bool colored) { System.Text.StringBuilder buffer = new System.Text.StringBuilder(); buffer.Append('['); if (colored) buffer.Append(Color); buffer.Append("IPv4Packet"); if (colored) buffer.Append(AnsiEscapeSequences_Fields.RESET); buffer.Append(": "); buffer.Append(SourceAddress + " -> " + DestinationAddress); buffer.Append(" proto=" + IPProtocol); buffer.Append(" l=" + IPHeaderLength + "," + Length); buffer.Append(']'); // append the base class output buffer.Append(base.ToColoredString(colored)); return buffer.ToString(); } /// <summary> Convert this IP packet to a more verbose string.</summary> public override System.String ToColoredVerboseString(bool colored) { System.Text.StringBuilder buffer = new System.Text.StringBuilder(); buffer.Append('['); if (colored) buffer.Append(Color); buffer.Append("IPv4Packet"); if (colored) buffer.Append(AnsiEscapeSequences_Fields.RESET); buffer.Append(": "); buffer.Append("version=" + Version + ", "); buffer.Append("hlen=" + HeaderLength + ", "); buffer.Append("tos=" + TypeOfService + ", "); buffer.Append("length=" + Length + ", "); buffer.Append("id=" + Id + ", "); buffer.Append("flags=0x" + System.Convert.ToString(FragmentFlags, 16) + ", "); buffer.Append("offset=" + FragmentOffset + ", "); buffer.Append("ttl=" + TimeToLive + ", "); buffer.Append("proto=" + IPProtocol + ", "); buffer.Append("sum=0x" + System.Convert.ToString(Checksum, 16)); if (this.ValidChecksum) buffer.Append(" (correct), "); else buffer.Append(" (incorrect, should be " + ComputeIPChecksum(false) + "), "); buffer.Append("src=" + SourceAddress + ", "); buffer.Append("dest=" + DestinationAddress); buffer.Append(']'); // append the base class output buffer.Append(base.ToColoredVerboseString(colored)); return buffer.ToString(); } /// <summary> This inner class provides access to private methods for unit testing.</summary> public class TestProbe { public TestProbe(IPv4Packet enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(IPv4Packet enclosingInstance) { this.enclosingInstance = enclosingInstance; } private IPv4Packet enclosingInstance; virtual public int ComputedReceiverIPChecksum { get { return ChecksumUtils.OnesSum(Enclosing_Instance.Bytes, Enclosing_Instance._ethPayloadOffset, Enclosing_Instance.IPHeaderLength); } } virtual public int ComputedSenderIPChecksum() { return Enclosing_Instance.ComputeIPChecksum(false); } public IPv4Packet Enclosing_Instance { get { return enclosingInstance; } } } } }
using Prism.Commands; using Prism.Mvvm; using Prism.Navigation; using System; using System.Collections.Generic; using System.Linq; namespace SafetyForAllApp.ViewModels { public class EmergencyDirectoryViewModel : ViewModelBase { public EmergencyDirectoryViewModel(INavigationService navigationService) :base(navigationService) { } } }
using System; using dubble = System.Double; namespace NeuralNetwork { public class NeuralNetwork { public Layer[] Layers; public ActivationFunc Activation; public double Fitness { get; set; } = 1; public (dubble[], dubble)[] Tests; public NeuralNetwork(ActivationFunc activation, int inputs, (dubble[], dubble)[] tests, params int[] neuronsCount){ Activation = activation; Layers = new Layer[neuronsCount.Length]; Layers[0] = new Layer(neuronsCount[0], inputs); Tests = tests; for (int i = 1; i < Layers.Length; i++){ Layers[i] = new Layer(neuronsCount[i], Layers[i - 1].Neurons.Length); } } public Layer OutputLayer { get { return Layers[Layers.Length - 1]; } } public Layer InputLayer { get { return Layers[0]; } } public void Randomize(Random randy){ for (int i = 0; i < Layers.Length; i++) { Layers[i].Randomize(randy); } } public double[] Compute(double[] inputs){ Layers[0].Compute(inputs, Activation.activation); for (int i = 1; i < Layers.Length; i++){ Layers[i].Compute(Layers[i - 1].Outputs, Activation.activation); } return Layers[Layers.Length - 1].Outputs; } public void Mutate(double rate, Random randy){ foreach (var layer in Layers) { foreach (var neuron in layer.Neurons) { if(randy.NextDouble() < rate){ neuron.Bias += randy.NextDouble(-1, 1); } for (int i = 0; i < neuron.Weights.Length; i++){ if(randy.NextDouble() < rate){ neuron.Weights[i] += randy.NextDouble(-1, 1); } } } } } public void Crossover(NeuralNetwork other, Random randy) { for (int i = 0; i < Layers.Length; i++) { int greatWall = randy.Next(0, Layers[i].Neurons.Length); bool primary = randy.Next(2) == 0; for (int n = (primary ? greatWall : 0); n < (primary ? Layers[i].Neurons.Length : greatWall); n++) { other.Layers[i].Neurons[n].Weights.CopyTo(Layers[i].Neurons[n].Weights, 0); Layers[i].Neurons[n].Bias = other.Layers[i].Neurons[n].Bias; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using UnityEngine.Events; namespace COM3D2.SimpleUI { public interface IAutoLayout: IControlContainer, ILayout { IBox Box(Vector2 size, string content); IButton Button(Vector2 size, string content, UnityAction onClick = null); ILabel Label(Vector2 size, string content); ITextField TextField(Vector2 size, string initial, UnityAction<string> onChange = null); ITextArea TextArea(Vector2 size, string initial, UnityAction<string> onChange = null); IToggle Toggle(Vector2 size, string content, bool initial, UnityAction<bool> onChange = null); IToolbar Toolbar(Vector2 size, int initial, string[] toolbarStrings, UnityAction<int> onChange = null); ISelectionGrid SelectionGrid(Vector2 size, int initial, string[] selectionStrings, int columns, UnityAction<int> onChange = null); ISlider HorizontalSlider(Vector2 size, float initial, float minimum, float maximum, UnityAction<float> onChange = null); ISlider VerticalSlider(Vector2 size, float initial, float minimum, float maximum, UnityAction<float> onChange = null); IDropdown Dropdown(Vector2 size, string content, string initial, IEnumerable<string> choices, UnityAction<string> onChange = null); IGenericDropdown GenericDropdown(Vector2 size, string content, UnityAction<object> onChange = null); IScrollView ScrollView(Vector2 size, Vector2 inner); IFixedLayout Group(Vector2 size); IAutoLayout Area(Vector2 size, IAutoLayoutOptions options); } }
using System.Windows.Forms; namespace Wc3Engine { public partial class NameSuffixDialog : Form { public NameSuffixDialog() { InitializeComponent(); } private void OnLoad(object sender, System.EventArgs e) { Name_textBox.Text = Wc3Engine.This.SelectedAbility.Name; Suffix_textBox.Text = Wc3Engine.This.SelectedAbility.Suffix; } private void Ok_button_Click(object sender, System.EventArgs e) { Ability ability = Wc3Engine.This.SelectedAbility; ability.Name = Name_textBox.Text; ability.Suffix = Suffix_textBox.Text; ability.Model.Name = "(" + ability.CodeId + ") " + Name_textBox.Text; ability.Model.Suffix = Suffix_textBox.Text; Wc3Engine.This.LTVCustomAbilities.RefreshObject(Wc3Engine.This.SelectedAbility.Model); Close(); } } }
using System; using System.Collections.Generic; using System.Web; using System.Security.Cryptography; using System.Text; using System.Data; using System.Data.SqlClient; using System.Net; using System.IO; using System.Web.Script.Serialization; namespace Assignment_1 { public partial class Login : System.Web.UI.Page { string MYDBConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MYDBConnection"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { } public class MyObject { public string success { get; set; } public List<string> ErrorMessage { get; set; } } protected void btn_login_Click(object sender, EventArgs e) { string pwd = tb_password.Text.ToString().Trim(); string userid = tb_emailAddress.Text.ToString().Trim(); DateTime dateTimeNow = DateTime.Now; DateTime maxPasswordAge = Convert.ToDateTime(getMaxPasswordAge(userid)); int maxDuration = DateTime.Compare(dateTimeNow, maxPasswordAge); SHA512Managed hashing = new SHA512Managed(); string dbHash = getDBHash(userid); string dbSalt = getDBSalt(userid); if (maxDuration <= 0) { try { if (ValidateCaptcha()) { if (dbSalt != null && dbSalt.Length > 0 && dbHash != null && dbHash.Length > 0 && tb_emailAddress.Text.Trim().Equals(userid) && tb_password.Text.Trim().Equals(pwd)) { string pwdWithSalt = pwd + dbSalt; byte[] hashWithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt)); string userHash = Convert.ToBase64String(hashWithSalt); if (userHash.Equals(dbHash)) { Session["LoggedIn"] = tb_emailAddress.Text.Trim(); // Create a new GUID and save into the session string guid = Guid.NewGuid().ToString(); Session["AuthToken"] = guid; // Now create a new cookie with this guid value Response.Cookies.Add(new HttpCookie("AuthToken", guid)); Session["UserID"] = userid; Response.Redirect("Success.aspx", false); } else { lbl_errorMsg.ForeColor = System.Drawing.Color.Red; Session["LoginCount"] = Convert.ToInt32(Session["LoginCount"]) + 1; if (Convert.ToInt32(Session["LoginCount"]) >= 3) { lbl_errorMsg.Text = DeactivateLoginAccount(); btn_login.Enabled = false; } else { lbl_errorMsg.Text = "Userid or password is not valid. Please try again."; lbl_errorMsg.ForeColor = System.Drawing.Color.Red; } //Response.Redirect("Login.aspx", false); } } else { lbl_error_message.Text = "Wrong username or password."; lbl_error_message.ForeColor = System.Drawing.Color.Red; } } } catch (Exception ex) { throw new Exception(ex.ToString()); } } else { lbl_error_message.Text = "Must change password after 5 mins."; lbl_error_message.ForeColor = System.Drawing.Color.Red; btn_resetPassword.Visible = true; } } protected void btn_reset_password_Click(object sender, EventArgs e) { string email = tb_emailAddress.Text.Trim(); Session["SSEmail"] = email; Response.Redirect("EmailRequestResetPassword.aspx", false); } protected string DeactivateLoginAccount() { DataSet ds = new DataSet(); SqlConnection con = new SqlConnection(MYDBConnectionString); string query = "select * from Account Where emailAddress='" + tb_emailAddress.Text + "';Update Account set Status=0 Where emailAddress='" + tb_emailAddress.Text + "';"; con.Open(); SqlDataAdapter da = new SqlDataAdapter(query, con); da.Fill(ds); if (ds.Tables[0].Rows.Count > 0) { return "Your Account is Locked. Please contact to admin."; } else { return "Enter email address does not exist in the application."; } con.Close(); } //protected void btn_login_Click(object sender, EventArgs e) //{ // string pwd = tb_password.Text.ToString().Trim(); // string userid = tb_emailAddress.Text.ToString().Trim(); // SHA512Managed hashing = new SHA512Managed(); // string dbHash = getDBHash(userid); // string dbSalt = getDBSalt(userid); // try // { // if (dbSalt != null && dbSalt.Length > 0 && dbHash != null && dbHash.Length > 0) // { // string pwdWithSalt = pwd + dbSalt; // byte[] hashWithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt)); // string userHash = Convert.ToBase64String(hashWithSalt); // if (userHash.Equals(dbHash)) // { // Session["UserID"] = userid; // Response.Redirect("Success.aspx", false); // } // else // { // lbl_errorMsg.Text = "Userid or password is not valid. Please try again."; // //Response.Redirect("Login.aspx", false); // } // } // else // { // lbl_error_message.Text = "Wrong username or password12221"; // lbl_error_message.ForeColor = System.Drawing.Color.Red; // } // } // catch (Exception ex) // { // throw new Exception(ex.ToString()); // } // finally // { // //if (ValidateCaptcha()) // //{ // // Check for username and password // //if (tb_emailAddress.Text.Trim().Equals("test1") && tb_password.Text.Trim().Equals("test2")) // if (tb_emailAddress.Text.Trim().Equals(userid) && tb_password.Text.Trim().Equals(pwd)) // { // Session["LoggedIn"] = tb_emailAddress.Text.Trim(); // // Create a new GUID and save into the session // string guid = Guid.NewGuid().ToString(); // Session["AuthToken"] = guid; // // Now create a new cookie with this guid value // Response.Cookies.Add(new HttpCookie("AuthToken", guid)); // Response.Redirect("Success.aspx", false); // } // else // { // lbl_error_message.Text = "Wrong username or password111"; // lbl_error_message.ForeColor = System.Drawing.Color.Red; // } // //} // } //} protected string getDBHash(string userid) { string h = null; SqlConnection connection = new SqlConnection(MYDBConnectionString); string sql = "select PasswordHash FROM Account WHERE emailAddress=@emailAddress"; SqlCommand command = new SqlCommand(sql, connection); command.Parameters.AddWithValue("@emailAddress", userid); try { connection.Open(); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { if (reader["PasswordHash"] != null) { if (reader["PasswordHash"] != DBNull.Value) { h = reader["PasswordHash"].ToString(); } } } } } catch (Exception ex) { throw new Exception(ex.ToString()); } finally { connection.Close(); } return h; } protected string getDBSalt(string userid) { string s = null; SqlConnection connection = new SqlConnection(MYDBConnectionString); string sql = "select PASSWORDSALT FROM ACCOUNT WHERE emailAddress=@emailAddress"; SqlCommand command = new SqlCommand(sql, connection); command.Parameters.AddWithValue("@emailAddress", userid); try { connection.Open(); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { if (reader["PASSWORDSALT"] != null) { if (reader["PASSWORDSALT"] != DBNull.Value) { s = reader["PASSWORDSALT"].ToString(); } } } } } catch (Exception ex) { throw new Exception(ex.ToString()); } finally { connection.Close(); } return s; } protected string getMaxPasswordAge(string userid) { string s = null; SqlConnection connection = new SqlConnection(MYDBConnectionString); string sql = "Select MaxPasswordAge FROM Account WHERE emailAddress=@emailAddress"; SqlCommand command = new SqlCommand(sql, connection); command.Parameters.AddWithValue("@emailAddress", userid); try { connection.Open(); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { if (reader["MaxPasswordAge"] != null) { if (reader["MaxPasswordAge"] != DBNull.Value) { s = reader["MaxPasswordAge"].ToString(); } } } } } catch (Exception ex) { throw new Exception(ex.ToString()); } finally { connection.Close(); } return s; } public bool ValidateCaptcha() { bool result = true; //When user submits recaptcha form, the user gets a response POST parameter. //captchaResponse consist of the user click pattern. Behaviour analytics! AI :) string captchaResponse = Request.Form["g-recaptcha-response"]; //To send a GET request to Google along with the response and Secret Key. HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?secret=6LfOZRcaAAAAALd7evSqK-VTIA5IGywYPM3QGn99 &response=" + captchaResponse); try { //Codes to receive the Reponse in JSON format from Google Server using (WebResponse wResponse = req.GetResponse()) { using (StreamReader readStream = new StreamReader(wResponse.GetResponseStream())) { //The response in JSON format string jsonResponse = readStream.ReadToEnd(); //To show the JSON response string for learning purpose //lbl_gScore.Text = jsonResponse.ToString(); JavaScriptSerializer js = new JavaScriptSerializer(); //Create jsonObject to handle the response e.g success or Error //Deserialise Json MyObject jsonObject = js.Deserialize<MyObject>(jsonResponse); //Convert the string "False" to bool false or "True" to bool true result = Convert.ToBoolean(jsonObject.success); } } return result; } catch (WebException ex) { throw ex; } } } }
using Contoso.XPlatform.Validators; namespace Contoso.XPlatform.Directives { public class ValidateIf<T> : ConditionBase<T> { public ValidateIf() { /*Properties will be created through inline initialization*/ Validator = null!; } public IValidationRule Validator { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Dalle : MonoBehaviour { private SpriteRenderer sprite; [SerializeField] private GameObject groundTileMap; // Start is called before the first frame update void Start() { sprite = this.GetComponent<SpriteRenderer>(); } // Update is called once per frame void Update() { } private void OnTriggerEnter2D(Collider2D other) { Debug.Log("Collision"); if (other.gameObject.tag == "Player") { gameObject.transform.position = new Vector2 (gameObject.transform.position.x, gameObject.transform.position.y - 0.12f); transform.GetChild(0).gameObject.SetActive(true); } } private void OnTriggerExit2D(Collider2D other) { if (other.gameObject.tag == "Player") { gameObject.transform.position = new Vector2(gameObject.transform.position.x, gameObject.transform.position.y + 0.12f); transform.GetChild(0).gameObject.SetActive(false); } } }
namespace Middleware.Core { public interface IResolver : IResolverBase { IScopedResolver BeginScope(); } }
var input = File.ReadLines("15.txt"); var cost = new Dictionary<(int x, int y), int> { [(0,0)] = 1, [(1,0)] = 1, [(0,1)] = 2, [(1,1)] = 1, }; var maxX = cost.Keys.MaxBy(k => k.x).x; var maxY = cost.Keys.MaxBy(k => k.y).y; var dist = cost.Keys.ToDictionary(k => k, _ => int.MaxValue); var prev = cost.Keys.ToDictionary(k => k, _ => ((int,int)?) null); dist[(0,0)] = 0; var q = new PriorityQueue<(int x, int y), int>(); q.Enqueue((0,0), 0); var neighboursDelta = new List<(int x, int y)> { (-1,1),(0,1),(1, 1), (-1,0), (1, 0), ( 1,1),(1,1),(1,-1), }; while (q.Count > 0) { var u = q.Dequeue(); var neighbours = neighboursDelta .Select(nd => (x: u.x + nd.x, y: u.y + nd.y)) .Where(n => n.x >= 0 && n.x <= maxX && n.y >= 0 && n.y <= maxY) .ToList(); foreach (var v in neighbours) { var alt = dist[u] + cost[v]; if (alt < dist[v]) { dist[v] = alt; prev[v] = u; if (!q.Contains(v)) } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class LH_Health : MonoBehaviour { private int mHealthPoints = 100; private int mHealthCoefficient = 100; private int mSecondsCounter = 0; private int mMaxSeconds = 10; LH_Attack mAttack; void Start() { mAttack = this.GetComponent<LH_Attack>(); } private void changeHealth(int changeAmt) { if(mAttack.mIsInvincible==false) { if ( (changeAmt + mHealthPoints) <= 100) /*checks to make sure hp stays under 100 */ { mHealthPoints += changeAmt; } else if ( (changeAmt + mHealthPoints) >= 100) { mHealthPoints = 100; } if(mHealthPoints < 0) { Debug.Log("LH_Health: Player died."); mHealthPoints = 100; } } Debug.Log("LH_Health: HP changed to: " + mHealthPoints); } public void doDamage(uint dmgAmt) /*must call with a positive amount for damage */ { int a = Convert.ToInt32(dmgAmt); //play sound changeHealth( (-a*mHealthCoefficient)/100 ); } public void Heal(int healAmt) { changeHealth( (healAmt*mHealthCoefficient)/100 ); //play sound } public void changeArmor(int percent) { mHealthCoefficient = (mHealthCoefficient * percent)/100; mSecondsCounter = 0; } public void makeInvincible(int seconds) { mAttack.setInvincible(seconds); } public int getHP() { return mHealthPoints; } // Use this for initialization // Update is called once per frame void Update () { } }
using System; namespace NameSearch.Models.Entities.Interfaces { /// <summary> /// Entity Interface /// </summary> public interface IEntity<TEntity> : IEquatable<TEntity> { /// <summary> /// Gets or sets a value indicating whether this instance is active. /// </summary> /// <value> /// <c>true</c> if this instance is active; otherwise, <c>false</c>. /// </value> bool IsActive { get; set; } /// <summary> /// Gets or sets the created date time. /// </summary> /// <value> /// The created date time. /// </value> DateTime CreatedDateTime { get; set; } /// <summary> /// Gets or sets the modified date time. /// </summary> /// <value> /// The modified date time. /// </value> DateTime? ModifiedDateTime { get; set; } } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> public interface IEntity<TEntity, TIdentifier> : IEntity<TEntity> { /// <summary> /// Gets or sets the identifier. /// </summary> /// <value> /// The identifier. /// </value> TIdentifier Id { get; set; } } }
using Android.Content; using Application = Android.App.Application; using Net = Android.Net; using Provider = Android.Provider; namespace Kit.MAUI.Services { public class NativeSettingsService : INativeSettingsService { public void OpenAppSettings() { string package_name = AppInfo.PackageName; var intent = new Intent(Provider.Settings.ActionApplicationDetailsSettings); intent.AddFlags(ActivityFlags.NewTask); var uri = Net.Uri.FromParts("package", package_name, null); intent.SetData(uri); Application.Context.StartActivity(intent); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace NapierBank.Models { /* The parent Message class. This class is the parent class for each of the message types. */ class Message { public string Header { get; set; } public string Sender { get; set; } public string Body { get; set; } // Outputs each message to the appropriate JSON file depending on the header public void OutputJson() { string file = ""; if(this.Header.StartsWith("S")) { DirectoryInfo di = Directory.CreateDirectory("sms"); file = "sms\\sms.json"; } else if (this.Header.StartsWith("T")) { DirectoryInfo di = Directory.CreateDirectory("tweets"); file = "tweets\\tweets.json"; } else if (this.Header.StartsWith("E")) { DirectoryInfo di = Directory.CreateDirectory("emails"); file = "emails\\emails.json"; } string json = JsonConvert.SerializeObject(this, Formatting.Indented); if (!File.Exists(file)) { File.WriteAllText(file, json + '-'); } else { File.AppendAllText(file, json + '-'); } } // Checks the header follows the correct format public static bool HeaderOk(string header) { bool headerOk = true; if(header.Length != 10) { headerOk = false; } foreach (char letter in header.Skip(1)) { if (!char.IsDigit(letter)) { headerOk = false; } } return headerOk; } } }
using SQLite; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WinForm.Model { public class AssetsInformation { [PrimaryKey, AutoIncrement] public int id { get; set; } /// <summary> /// 资产名称 /// </summary> public string AssetName { get; set; } /// <summary> /// 资产编码 /// </summary> public string AssetCode { get; set; } /// <summary> /// 资产型号 /// </summary> public string AssetModel { get; set; } /// <summary> /// 管理部门 /// </summary> public string ManagementDepartment { get; set; } /// <summary> /// 使用部门 /// </summary> public string UseDepartment { get; set; } /// <summary> /// 使用状态 /// </summary> public string UseState { get; set; } /// <summary> /// 使用年限 /// </summary> public string UseDate { get; set; } /// <summary> /// 使用地点 /// </summary> public string UsePlace { get;set; } /// <summary> /// 安装日期 /// </summary> public string InstallationDate { get; set; } /// <summary> /// 二维码地址 /// </summary> public string QdPath { get; set; } } }
using System; namespace console_b { public class newFile { int x, y; } }
using RevolutionCAD.Tracing; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RevolutionCAD.Layering { public class StepLayeringLog { /// <summary> /// Представляет дискретное рабочее поле, каждая ячейка представлена классом Cell /// у неё есть вес и состояние /// </summary> public List<List<Matrix<Cell>>> BoardsLayersDRPs { get; set; } // имеем список узлов, в каждом элементе списка хранится список слоёв дрп, в каждом элементе списка хранится список слоёв проводов для каждого слоя public string Message { get; set; } public StepLayeringLog(List<List<List<Matrix<Cell>>>> boardsLayers, string msg) { // способ для получения копий списков, потому что иначе мы получим тупо ссылки на них BoardsLayersDRPs = new List<List<Matrix<Cell>>>(); // а вот матрицы в списке остались ссылочные и соотвественно ячейки в них тоже // нужно скопируваты for (int boardNum = 0; boardNum < boardsLayers.Count; boardNum++) { var boardLayers = new List<Matrix<Cell>>(); for (int layerNumber = 0; layerNumber < boardsLayers[boardNum].Count; layerNumber++) { var matr = ApplicationData.MergeLayersDRPs(boardsLayers[boardNum][layerNumber]); boardLayers.Add(matr); } BoardsLayersDRPs.Add(boardLayers); } Message = msg; } } }
using PDV.DAO.Atributos; namespace PDV.DAO.Entidades.Financeiro { public class Banco { [CampoTabela("IDBANCO")] public decimal IDBanco { get; set; } [CampoTabela("CODBACEN")] public decimal? CodBacen { get; set; } [CampoTabela("NOME")] public string Nome { get; set; } [CampoTabela("SITE")] public string Site { get; set; } public Banco() { } } }
/* * Copyright (c) 2016 Billy Wolfington * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * https://github.com/Bwolfing/Bootstrap.AspNetCore.Mvc.TagHelpers * */ using Microsoft.AspNetCore.Razor.TagHelpers; namespace Bootstrap.AspNetCore.Mvc.TagHelpers { [HtmlTargetElement(Global.PREFIX + "container-fluid")] public class ContainerFluid : Container { public override string CssClass { get { return "container-fluid"; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ProjectRestaurant.Controllers.Inputs { public class RestaurantInput { public string RestaurantName { get; set; } public int Kitchen { get; set; } public string Street { get; set; } public string Number { get; set; } public string City { get; set; } public string UF { get; set; } public string Cep { get; set; } } }
using FastSQL.Sync.Core.Enums; using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace FastSQL.Sync.Core.Models { [Table("core_options")] public class OptionModel { [Key] public Guid Id { get; set; } public string EntityId { get; set; } public EntityType EntityType { get; set; } [MaxLength(255)] public string Key { get; set; } [MaxLength(4000)] public string Value { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; public partial class Analysis : System.Web.UI.Page { string obj_Authenticated; PlaceHolder maPlaceHolder; UserControl obj_Tabs; UserControl obj_LoginCtrl; UserControl obj_WelcomCtrl; UserControl obj_Navi; UserControl obj_Navihome; BizConnectDealProcess obj_Class = new BizConnectDealProcess(); DataSet ds = new DataSet(); DataSet ds_capacity = new DataSet(); DataSet ds_Lowquote = new DataSet(); DataTable dt = new DataTable(); DataTable dt_Bind = new DataTable(); DataSet ds_Analysis = new DataSet(); DataTable dt_AnaSearh = new DataTable(); int Capacity, FConversion; double Length, Breadth, Height, CubicFeet, NfBoxes, Loadingboxes; double VolLength, VolBreadth, VolHeight, VolCubicFeet, VolNfBoxes, VolLoadingboxes; double NoofCartons, TotalCFTs, TotalFTL, TotalTarus, Total32saTot, Total32maTot,TotalWeight; double Len=0,bred=0,hei=0; int FTLSop, TaurusSop, SaSop, MaSop; double FTLDesWei, TaurusDesWei, SaDesWei, MaDesWei; double FTLNoOFTrucks, TaurusNoOFTrucks, SaNoOFTrucks, MaNoOFTrucks, NoOfFTLCartons, NoOfTaurusCartons, NoOfSaCartons, NoOfMaCartons, FtlCost, TaurusCost, SaCost, MaCost; string TravelDate; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //GridBind(); BindAnalysisGrid(); // Load_FromLoc(); Load_ToLoc(); Session["TaurusQuote"] = 0; Session["32ftsaQuote"] = 0; Session["32ftmaQuote"] = 0; Session["FTlQuote"] = 0; ChkAuthentication(); } } public void ChkAuthentication() { obj_LoginCtrl = null; obj_WelcomCtrl = null; obj_Navi = null; obj_Navihome = null; if (Session["Authenticated"] == null) { Session["Authenticated"] = "0"; } else { obj_Authenticated = Session["Authenticated"].ToString(); } maPlaceHolder = (PlaceHolder)Master.FindControl("P1"); if (maPlaceHolder != null) { obj_Tabs = (UserControl)maPlaceHolder.FindControl("loginheader1"); if (obj_Tabs != null) { obj_LoginCtrl = (UserControl)obj_Tabs.FindControl("login1"); obj_WelcomCtrl = (UserControl)obj_Tabs.FindControl("welcome1"); // obj_Navi = (UserControl)obj_Tabs.FindControl("Navii"); //obj_Navihome = (UserControl)obj_Tabs.FindControl("Navihome1"); if (obj_LoginCtrl != null & obj_WelcomCtrl != null) { if (obj_Authenticated == "1") { SetVisualON(); } else { SetVisualOFF(); } } } else { } } else { } } public void SetVisualON() { obj_LoginCtrl.Visible = false; obj_WelcomCtrl.Visible = true; } public void SetVisualOFF() { obj_LoginCtrl.Visible = true; obj_WelcomCtrl.Visible = false; } //public void Load_FromLoc() //{ // ds = obj_Class.bizconnect_Get_Fromlocation(Convert.ToInt32(Session["ClientID"].ToString())); // ddl_FromLoc.DataSource = ds; // ddl_FromLoc.DataTextField = "FromLocation"; // ddl_FromLoc.DataBind(); // ddl_FromLoc.Items.Insert(0, new ListItem("--Select--", "0")); //} public void Load_ToLoc() { ds = obj_Class.bizconnect_Get_ToLocation(Convert.ToInt32(Session["ClientID"].ToString())); ddl_ToLoc.DataSource = ds; ddl_ToLoc.DataTextField = "ToLocation"; ddl_ToLoc.DataBind(); ddl_ToLoc.Items.Insert(0, new ListItem("--Select--", "0")); } public void GridBind() { ds = obj_Class.Get_OptimizationDetails(Convert.ToInt32(Session["ClientID"].ToString())); grd_Analysis.DataSource = ds; grd_Analysis.DataBind(); } public void BindAnalysisGrid() { //load weight Analysis ds_Analysis = obj_Class.Bizconnect_Get_OptimizationAnalysis(Convert.ToInt32(Session["ClientID"].ToString())); grd_WeightAnalysis.DataSource = ds_Analysis; grd_WeightAnalysis.DataBind(); //load space Analysis // ds_Analysis = obj_Class.Bizconnect_Get_OptimizationAnalysis(Convert.ToInt32(Session["ClientID"].ToString())); grd_VolumeAnalysis.DataSource = ds_Analysis; grd_VolumeAnalysis.DataBind(); } protected void btn_Analysis_Click(object sender, EventArgs e) { if (ddl_FromLoc.SelectedValue.ToString() == "0" || ddl_ToLoc.SelectedValue.ToString() == "0") { ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('Please Select Both From and To Location For Analysis!');</script>"); } else { ds_capacity = obj_Class.Bizconnet_Get_CapacityCubicfeet(); try { TextBox FTLCost = (TextBox)grd_Analysis.HeaderRow.FindControl("txt_Ftl"); TextBox TaurusCost = (TextBox)grd_Analysis.HeaderRow.FindControl("txt_Tauras"); TextBox SingleAxleCost = (TextBox)grd_Analysis.HeaderRow.FindControl("txt_32ftsa"); TextBox MultiAxleCost = (TextBox)grd_Analysis.HeaderRow.FindControl("txt_32ftma"); for (int i = 0; i < grd_Analysis.Rows.Count; i++) { Label lblL1 = (Label)grd_Analysis.Rows[i].FindControl("lbl_Length"); Label lblB1 = (Label)grd_Analysis.Rows[i].FindControl("lbl_Breadth"); Label lblH1 = (Label)grd_Analysis.Rows[i].FindControl("lbl_Height"); TextBox l1 = (TextBox)grd_Analysis.Rows[i].FindControl("txt_Length"); TextBox B1 = (TextBox)grd_Analysis.Rows[i].FindControl("txt_Breadth"); TextBox H1 = (TextBox)grd_Analysis.Rows[i].FindControl("txt_Height"); TextBox W1 = (TextBox)grd_Analysis.Rows[i].FindControl("txt_Weight"); Label FeetConv = (Label)grd_Analysis.Rows[i].FindControl("lbl_FeetCon"); Label costforFTL = (Label)grd_Analysis.Rows[i].FindControl("lbl_CostforFTL"); Label costforTaurus = (Label)grd_Analysis.Rows[i].FindControl("lbl_CostforTaurus"); Label costfor32ftsa = (Label)grd_Analysis.Rows[i].FindControl("lbl_Costfor32ftsa"); Label costfor32ftma = (Label)grd_Analysis.Rows[i].FindControl("lbl_Costfor32ftma"); FConversion = Convert.ToInt32(FeetConv.Text); Label length1 = (Label)grd_Analysis.Rows[i].FindControl("lbl_OPTLength"); Label Breadth1 = (Label)grd_Analysis.Rows[i].FindControl("lbl_OPTBreadth"); Label Height1 = (Label)grd_Analysis.Rows[i].FindControl("lbl_OPTHeight"); Label Cft1 = (Label)grd_Analysis.Rows[i].FindControl("lbl_OPTCFT"); Label LoadBoxes = (Label)grd_Analysis.Rows[i].FindControl("lbl_OPTLoadBoxes"); Label NoOfBoxesInFtl = (Label)grd_Analysis.Rows[i].FindControl("lbl_NoofBoxesFtl"); Label NoOfBoxesInTaurus = (Label)grd_Analysis.Rows[i].FindControl("lbl_NoofBoxesTaurus"); Label NoOfBoxesIn32ftsa = (Label)grd_Analysis.Rows[i].FindControl("lbl_NoofBoxes32sa"); Label NoOfBoxesIn32ftma = (Label)grd_Analysis.Rows[i].FindControl("lbl_NoofBoxes32ma"); Label LoadBoxesInFTL = (Label)grd_Analysis.Rows[i].FindControl("lbl_LoadBoxesFTL"); Label LoadBoxesInTaurus = (Label)grd_Analysis.Rows[i].FindControl("lbl_LoadBoxesTaurus"); Label LoadBoxesIn32ftsa = (Label)grd_Analysis.Rows[i].FindControl("lbl_LoadBoxes32ftsa"); Label LoadBoxesIn32ftma = (Label)grd_Analysis.Rows[i].FindControl("lbl_LoadBoxes32ftma"); Length = Math.Round(Convert.ToDouble(lblL1.Text) / FConversion, 2); Breadth = Math.Round(Convert.ToDouble(lblB1.Text) / FConversion, 2); Height = Math.Round(Convert.ToDouble(lblH1.Text) / FConversion, 2); CubicFeet = Math.Round(Convert.ToDouble(Length) * Convert.ToDouble(Breadth) * Convert.ToDouble(Height), 2); length1.Text = Length.ToString(); Breadth1.Text = Breadth.ToString(); Height1.Text = Height.ToString(); Cft1.Text = CubicFeet.ToString(); NoOfBoxesInFtl.Text = Math.Round(Convert.ToInt32(ds_capacity.Tables[0].Rows[3][2].ToString()) / CubicFeet, 0).ToString(); NoOfBoxesInTaurus.Text = Math.Round(Convert.ToInt32(ds_capacity.Tables[0].Rows[0][2].ToString()) / CubicFeet, 0).ToString(); NoOfBoxesIn32ftsa.Text = Math.Round(Convert.ToInt32(ds_capacity.Tables[0].Rows[1][2].ToString()) / CubicFeet, 0).ToString(); NoOfBoxesIn32ftma.Text = Math.Round(Convert.ToInt32(ds_capacity.Tables[0].Rows[2][2].ToString()) / CubicFeet, 0).ToString(); LoadBoxesInFTL.Text = Math.Round(Convert.ToInt32(ds_capacity.Tables[0].Rows[3][3].ToString()) / Convert.ToDouble(W1.Text), 0).ToString(); LoadBoxesInTaurus.Text = Math.Round(Convert.ToInt32(ds_capacity.Tables[0].Rows[0][3].ToString()) / Convert.ToDouble(W1.Text), 0).ToString(); LoadBoxesIn32ftsa.Text = Math.Round(Convert.ToInt32(ds_capacity.Tables[0].Rows[1][3].ToString()) / Convert.ToDouble(W1.Text), 0).ToString(); LoadBoxesIn32ftma.Text = Math.Round(Convert.ToInt32(ds_capacity.Tables[0].Rows[2][3].ToString()) / Convert.ToDouble(W1.Text), 0).ToString(); if (Convert.ToDouble(NoOfBoxesInFtl.Text) < Convert.ToDouble(LoadBoxesInFTL.Text)) { costforFTL.Text = Math.Round(Convert.ToDouble(FTLCost.Text) / Convert.ToDouble(NoOfBoxesInFtl.Text), 2).ToString(); } else { costforFTL.Text = Math.Round(Convert.ToDouble(FTLCost.Text) / Convert.ToDouble(LoadBoxesInFTL.Text), 2).ToString(); } if (Convert.ToDouble(NoOfBoxesInTaurus.Text) < Convert.ToDouble(LoadBoxesInTaurus.Text)) { costforTaurus.Text = Math.Round(Convert.ToDouble(TaurusCost.Text) / Convert.ToDouble(NoOfBoxesInTaurus.Text), 2).ToString(); } else { costforTaurus.Text = Math.Round(Convert.ToDouble(TaurusCost.Text) / Convert.ToDouble(LoadBoxesInTaurus.Text), 2).ToString(); } if (Convert.ToDouble(NoOfBoxesIn32ftsa.Text) < Convert.ToDouble(LoadBoxesIn32ftsa.Text)) { costfor32ftsa.Text = Math.Round(Convert.ToDouble(SingleAxleCost.Text) / Convert.ToDouble(NoOfBoxesIn32ftsa.Text), 2).ToString(); } else { costfor32ftsa.Text = Math.Round(Convert.ToDouble(SingleAxleCost.Text) / Convert.ToDouble(LoadBoxesIn32ftsa.Text), 2).ToString(); } if (Convert.ToDouble(NoOfBoxesIn32ftma.Text) < Convert.ToDouble(LoadBoxesIn32ftma.Text)) { costfor32ftma.Text = Math.Round(Convert.ToDouble(MultiAxleCost.Text) / Convert.ToDouble(NoOfBoxesIn32ftma.Text), 2).ToString(); } else { costfor32ftma.Text = Math.Round(Convert.ToDouble(MultiAxleCost.Text) / Convert.ToDouble(LoadBoxesIn32ftma.Text), 2).ToString(); } } } catch (Exception ex) { } } } protected void ddl_ToLoc_SelectedIndexChanged(object sender, EventArgs e) { try { grd_Summary.Visible = false; grd_WeightAnalysis.Visible = false; grd_VolumeAnalysis.Visible = false; //ds_Lowquote = obj_Class.Bizconnect_Get_LowestQuoteBasedOnTruck(ddl_FromLoc.SelectedValue.ToString(), ddl_ToLoc.SelectedValue.ToString()); //if (ds_Lowquote.Tables[0].Rows.Count > 0) //{ // Session["TaurusQuote"] = ds_Lowquote.Tables[0].Rows[0][0]; //} //else //{ // Session["TaurusQuote"] = 0; //} //if (ds_Lowquote.Tables[1].Rows.Count > 0) //{ // Session["32ftsaQuote"] = ds_Lowquote.Tables[1].Rows[0][0]; //} //else //{ // Session["32ftsaQuote"] = 0; //} //if (ds_Lowquote.Tables[2].Rows.Count > 0) //{ // Session["32ftmaQuote"] = ds_Lowquote.Tables[2].Rows[0][0]; //} //else //{ // Session["32ftmaQuote"] = 0; //} //if (ds_Lowquote.Tables[3].Rows.Count > 0) //{ // Session["FTlQuote"] = ds_Lowquote.Tables[3].Rows[0][0]; //} //else //{ // Session["FTlQuote"] = 0; //} //TextBox FtlQuote = (TextBox)grd_Analysis.HeaderRow.FindControl("txt_Ftl"); //TextBox TaurusQuote = (TextBox)grd_Analysis.HeaderRow.FindControl("txt_Tauras"); //TextBox SaQuote = (TextBox)grd_Analysis.HeaderRow.FindControl("txt_32ftsa"); //TextBox MaQuote = (TextBox)grd_Analysis.HeaderRow.FindControl("txt_32ftma"); //FtlQuote.Text = Session["FTlQuote"].ToString(); //TaurusQuote.Text = Session["TaurusQuote"].ToString(); //SaQuote.Text = Session["32ftsaQuote"].ToString(); //MaQuote.Text = Session["32ftmaQuote"].ToString(); ds = obj_Class.bizconnect_Get_Fromlocation(Convert.ToInt32(Session["ClientID"].ToString()), ddl_ToLoc.SelectedItem.Text); ddl_FromLoc.DataSource = ds; ddl_FromLoc.DataTextField = "FromLocation"; ddl_FromLoc.DataBind(); ddl_FromLoc.Items.Insert(0, new ListItem("--Select--", "0")); dt = obj_Class.Bizconnet_Get_DespatchPlanNoByTolocation(Convert.ToInt32(Session["ClientID"].ToString()), ddl_ToLoc.SelectedItem.Text); ddl_PlanNo.DataSource = dt; ddl_PlanNo.DataTextField = "PlanNo"; ddl_PlanNo.DataBind(); ddl_PlanNo.Items.Insert(0, new ListItem("--Select--", "0")); //dt_Bind = obj_Class.Bizconnect_SearchDespatchplanByPlannoAndTolocation(Convert.ToInt32(Session["ClientID"].ToString()), ddl_ToLoc.SelectedItem.Text, string.Empty); //grd_Analysis.DataSource = dt_Bind; //grd_Analysis.DataBind(); //dt_AnaSearh = obj_Class.Bizconnect_SearchDespatchplanAnalysisByPlannoAndTolocation(Convert.ToInt32(Session["ClientID"].ToString()), ddl_ToLoc.SelectedItem.Text, string.Empty); dt_AnaSearh = obj_Class.Bizconnect_SearchDespatchVolumeAnalysisbyTolocationandPlanno(Convert.ToInt32(Session["ClientID"].ToString()), ddl_ToLoc.SelectedItem.Text, string.Empty); grd_WeightAnalysis.DataSource = dt_AnaSearh; grd_WeightAnalysis.DataBind(); dt_Bind.Clear(); dt_Bind = obj_Class.Bizconnect_SearchDespatchVolumeAnalysisbyTolocationandPlanno(Convert.ToInt32(Session["ClientID"].ToString()), ddl_ToLoc.SelectedItem.Text, string.Empty); grd_VolumeAnalysis.DataSource = dt_Bind; grd_VolumeAnalysis.DataBind(); } catch (Exception ex) { } } protected void btn_ExportToExcel_Click(object sender, EventArgs e) { ExportGrid(grd_Analysis, "Analysis.xls"); } public static void ExportGrid(GridView oGrid, string exportFile) { //Clear the response, and set the content type and mark as attachment HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + exportFile + "\""); //Clear the character set HttpContext.Current.Response.Charset = ""; //Create a string and Html writer needed for output System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); //Clear the controls from the pased grid //Show grid lines oGrid.GridLines = GridLines.Both; //Color header oGrid.HeaderStyle.BackColor = System.Drawing.Color.LightGray; //Render the grid to the writer oGrid.RenderControl(oHtmlTextWriter); //Write out the response (file), then end the response HttpContext.Current.Response.Write(oStringWriter.ToString()); HttpContext.Current.Response.End(); } public override void VerifyRenderingInServerForm(Control control) { } protected void btn_Despatchplan_Click(object sender, EventArgs e) { Response.Redirect("~/OptDispatchPlan.aspx"); } protected void ddl_PlanNo_SelectedIndexChanged(object sender, EventArgs e) { try { grd_Summary.Visible = false; grd_WeightAnalysis.Visible = false; grd_VolumeAnalysis.Visible = false; if (ddl_PlanNo.SelectedItem.Text != "--Select--") { //dt_Bind.Clear(); //dt_Bind = obj_Class.Bizconnect_SearchDespatchplanByPlannoAndTolocation(Convert.ToInt32(Session["ClientID"].ToString()), ddl_ToLoc.SelectedItem.Text, ddl_PlanNo.SelectedItem.Text); //grd_Analysis.DataSource = dt_Bind; //grd_Analysis.DataBind(); dt_AnaSearh.Clear(); //dt_AnaSearh = obj_Class.Bizconnect_SearchDespatchplanAnalysisByPlannoAndTolocation(Convert.ToInt32(Session["ClientID"].ToString()), ddl_ToLoc.SelectedItem.Text, ddl_PlanNo.SelectedItem.Text); dt_AnaSearh = obj_Class.Bizconnect_SearchDespatchVolumeAnalysisbyTolocationandPlanno(Convert.ToInt32(Session["ClientID"].ToString()), ddl_ToLoc.SelectedItem.Text, ddl_PlanNo.SelectedItem.Text); grd_WeightAnalysis.DataSource = dt_AnaSearh; grd_WeightAnalysis.DataBind(); dt_Bind.Clear(); dt_Bind = obj_Class.Bizconnect_SearchDespatchVolumeAnalysisbyTolocationandPlanno(Convert.ToInt32(Session["ClientID"].ToString()), ddl_ToLoc.SelectedItem.Text, ddl_PlanNo.SelectedItem.Text); grd_VolumeAnalysis.DataSource = dt_Bind; grd_VolumeAnalysis.DataBind(); } else { ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('Please Select Plan No For search despatch plan details!');</script>"); } } catch (Exception ex) { } } protected void Button1_Click(object sender, EventArgs e) { grd_Summary.Visible = false; pnl_Summary.Visible = false ; pnl_OptSummary.Visible = false; if (ddl_FromLoc.SelectedValue.ToString() == "0" || ddl_ToLoc.SelectedValue.ToString() == "0") { ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('Please Select Both From and To Location For Analysis!');</script>"); } else { dt_AnaSearh.Clear(); dt_AnaSearh = obj_Class.Bizconnect_SearchDespatchVolumeAnalysisbyTolocationandPlanno(Convert.ToInt32(Session["ClientID"].ToString()), ddl_ToLoc.SelectedItem.Text, string.Empty); grd_WeightAnalysis.DataSource = dt_AnaSearh; grd_WeightAnalysis.DataBind(); //dt_Bind = obj_Class.Bizconnect_SearchDespatchVolumeAnalysisbyTolocationandPlanno(Convert.ToInt32(Session["ClientID"].ToString()), ddl_ToLoc.SelectedItem.Text, string.Empty); grd_VolumeAnalysis.DataSource = dt_AnaSearh; grd_VolumeAnalysis.DataBind(); if (ddl_PlanNo.SelectedItem.Text != "--Select--") { dt_AnaSearh.Clear(); //dt_AnaSearh = obj_Class.Bizconnect_SearchDespatchplanAnalysisByPlannoAndTolocation(Convert.ToInt32(Session["ClientID"].ToString()), ddl_ToLoc.SelectedItem.Text, ddl_PlanNo.SelectedItem.Text); dt_AnaSearh = obj_Class.Bizconnect_SearchDespatchVolumeAnalysisbyTolocationandPlanno(Convert.ToInt32(Session["ClientID"].ToString()), ddl_ToLoc.SelectedItem.Text, ddl_PlanNo.SelectedItem.Text); grd_WeightAnalysis.DataSource = dt_AnaSearh; grd_WeightAnalysis.DataBind(); dt_Bind.Clear(); dt_Bind = obj_Class.Bizconnect_SearchDespatchVolumeAnalysisbyTolocationandPlanno(Convert.ToInt32(Session["ClientID"].ToString()), ddl_ToLoc.SelectedItem.Text, ddl_PlanNo.SelectedItem.Text); grd_VolumeAnalysis.DataSource = dt_Bind; grd_VolumeAnalysis.DataBind(); } if (rdb_Weight.Checked == true) { grd_WeightAnalysis.Visible = true ; grd_VolumeAnalysis.Visible = false ; //pnl_OptSummary.Visible = true ; ds_capacity = obj_Class.Bizconnet_Get_CapacityCubicfeet(); try { TextBox FTLCost = (TextBox)grd_WeightAnalysis.HeaderRow.FindControl("txt_Ftl"); TextBox TaurusCost = (TextBox)grd_WeightAnalysis.HeaderRow.FindControl("txt_Tauras"); TextBox SingleAxleCost = (TextBox)grd_WeightAnalysis.HeaderRow.FindControl("txt_32ftsa"); TextBox MultiAxleCost = (TextBox)grd_WeightAnalysis.HeaderRow.FindControl("txt_32ftma"); for (int i = 0; i < grd_WeightAnalysis.Rows.Count; i++) { Label lblL1 = (Label)grd_WeightAnalysis.Rows[i].FindControl("lbl_Length"); Label lblB1 = (Label)grd_WeightAnalysis.Rows[i].FindControl("lbl_Breadth"); Label lblH1 = (Label)grd_WeightAnalysis.Rows[i].FindControl("lbl_Height"); Label lblWei = (Label)grd_WeightAnalysis.Rows[i].FindControl("lbl_Weight"); Label lblCode = (Label)grd_WeightAnalysis.Rows[i].FindControl("lbl_Code"); Label TotalCFT = (Label)grd_WeightAnalysis.Rows[i].FindControl("lbl_TotalCFT"); TextBox l1 = (TextBox)grd_WeightAnalysis.Rows[i].FindControl("txt_Length"); TextBox B1 = (TextBox)grd_WeightAnalysis.Rows[i].FindControl("txt_Breadth"); TextBox H1 = (TextBox)grd_WeightAnalysis.Rows[i].FindControl("txt_Height"); TextBox W1 = (TextBox)grd_WeightAnalysis.Rows[i].FindControl("txt_TotalWeight"); Label FeetConv = (Label)grd_WeightAnalysis.Rows[i].FindControl("lbl_FeetCon"); Label costforFTL = (Label)grd_WeightAnalysis.Rows[i].FindControl("lbl_CostforFTL"); Label costforTaurus = (Label)grd_WeightAnalysis.Rows[i].FindControl("lbl_CostforTaurus"); Label costfor32ftsa = (Label)grd_WeightAnalysis.Rows[i].FindControl("lbl_Costfor32ftsa"); Label costfor32ftma = (Label)grd_WeightAnalysis.Rows[i].FindControl("lbl_Costfor32ftma"); Label Product = (Label)grd_WeightAnalysis.Rows[i].FindControl("lbl_Product"); Label NumberofCartons = (Label)grd_WeightAnalysis.Rows[i].FindControl("lbl_NumberofCartons"); FConversion = Convert.ToInt32(FeetConv.Text); Label length1 = (Label)grd_WeightAnalysis.Rows[i].FindControl("lbl_OPTLength"); Label Breadth1 = (Label)grd_WeightAnalysis.Rows[i].FindControl("lbl_OPTBreadth"); Label Height1 = (Label)grd_WeightAnalysis.Rows[i].FindControl("lbl_OPTHeight"); Label Cft1 = (Label)grd_WeightAnalysis.Rows[i].FindControl("lbl_OPTCFT"); Label LoadBoxes = (Label)grd_WeightAnalysis.Rows[i].FindControl("lbl_OPTLoadBoxes"); Label LoadBoxesInFTL = (Label)grd_WeightAnalysis.Rows[i].FindControl("lbl_LoadBoxesFTL"); Label LoadBoxesInTaurus = (Label)grd_WeightAnalysis.Rows[i].FindControl("lbl_LoadBoxesTaurus"); Label LoadBoxesIn32ftsa = (Label)grd_WeightAnalysis.Rows[i].FindControl("lbl_LoadBoxes32ftsa"); Label LoadBoxesIn32ftma = (Label)grd_WeightAnalysis.Rows[i].FindControl("lbl_LoadBoxes32ftma"); Length = Math.Round(Convert.ToDouble(lblL1.Text) / FConversion, 2); Breadth = Math.Round(Convert.ToDouble(lblB1.Text) / FConversion, 2); Height = Math.Round(Convert.ToDouble(lblH1.Text) / FConversion, 2); CubicFeet = Math.Round(Convert.ToDouble(Length) * Convert.ToDouble(Breadth) * Convert.ToDouble(Height) * Convert.ToDouble(NumberofCartons.Text), 2); //assigned 1000 as CubicFeet // CubicFeet1 = 1000; // length1.Text = Length.ToString(); Breadth1.Text = Breadth.ToString(); Height1.Text = Height.ToString(); Cft1.Text = CubicFeet.ToString(); Session["WeiProduct"] = Product.Text; Product.Text = Session["WeiProduct"] + "(Code :" + lblCode.Text + ")" + "<br />" + "( L :" + Length + " )" + "<br /> " + " ( B :" + Breadth + " )" + " <br />" + "( H :" + Height + ")" + " <br />" + "( W :" + lblWei.Text + ")"; // Product .Text +=Product.Text +"B :"+ Breadth ; //Product.Text = Product.Text + "H :" + Height; /////start calculating weight constraint double BoxesInFTL = Math.Round(Convert.ToDouble(ds_capacity.Tables[0].Rows[3][3].ToString()), 0); LoadBoxesInTaurus.Text = Math.Round(Convert.ToDouble(ds_capacity.Tables[0].Rows[0][3].ToString()), 0).ToString(); LoadBoxesIn32ftsa.Text = Math.Round(Convert.ToDouble(ds_capacity.Tables[0].Rows[1][3].ToString()), 0).ToString(); LoadBoxesIn32ftma.Text = Math.Round(Convert.ToDouble(ds_capacity.Tables[0].Rows[2][3].ToString()), 0).ToString(); TotalCFT.Text = CubicFeet.ToString(); LoadBoxesInFTL.Text = Math.Round((Convert.ToDouble(W1.Text) / Convert.ToDouble(BoxesInFTL)), 2).ToString(); LoadBoxesInTaurus.Text = Math.Round((Convert.ToDouble(W1.Text) / Convert.ToDouble(LoadBoxesInTaurus.Text)), 2).ToString(); LoadBoxesIn32ftsa.Text = Math.Round((Convert.ToDouble(W1.Text) / Convert.ToDouble(LoadBoxesIn32ftsa.Text)), 2).ToString(); LoadBoxesIn32ftma.Text = Math.Round((Convert.ToDouble(W1.Text) / Convert.ToDouble(LoadBoxesIn32ftma.Text)), 2).ToString(); //end Label NoofCartonstotal = (Label)grd_WeightAnalysis.FooterRow.FindControl("lbl_NoofCartonsTotal"); Label Totalweight = (Label)grd_WeightAnalysis.FooterRow.FindControl("lbl_TotalWeight"); Label FtlTotal = (Label)grd_WeightAnalysis.FooterRow.FindControl("lbl_FtlTotal"); Label TarusTotal = (Label)grd_WeightAnalysis.FooterRow.FindControl("lbl_TarusTotal"); Label Total32sa = (Label)grd_WeightAnalysis.FooterRow.FindControl("lbl_32saTotal"); Label Total32ma = (Label)grd_WeightAnalysis.FooterRow.FindControl("lbl_32MaTotal"); NoofCartons += Convert.ToDouble(NumberofCartons.Text); TotalCFTs += Convert.ToDouble(W1.Text); TotalFTL += Convert.ToDouble(LoadBoxesInFTL.Text); TotalTarus += Convert.ToDouble(LoadBoxesInTaurus.Text); Total32saTot += Convert.ToDouble(LoadBoxesIn32ftsa.Text); Total32maTot += Convert.ToDouble(LoadBoxesIn32ftma.Text); //Session["TotalCFT"] = Convert.ToDouble(TotalCFTs); NoofCartonstotal.Text = NoofCartons.ToString(); Totalweight.Text = TotalCFTs.ToString(); FtlTotal.Text = TotalFTL.ToString(); TarusTotal.Text = TotalTarus.ToString(); Total32sa.Text = Total32saTot.ToString(); Total32ma.Text = Total32maTot.ToString(); } } catch (Exception ex) { } } if (rdb_Volume.Checked == true) { grd_VolumeAnalysis.Visible = true; grd_WeightAnalysis .Visible = false; pnl_OptSummary.Visible = false; Session["Productname"] = ""; ds_capacity = obj_Class.Bizconnet_Get_CapacityCubicfeet(); try { TextBox FTLCost = (TextBox)grd_VolumeAnalysis.HeaderRow.FindControl("txt_Ftl"); TextBox TaurusCost = (TextBox)grd_VolumeAnalysis.HeaderRow.FindControl("txt_Tauras"); TextBox SingleAxleCost = (TextBox)grd_VolumeAnalysis.HeaderRow.FindControl("txt_32ftsa"); TextBox MultiAxleCost = (TextBox)grd_VolumeAnalysis.HeaderRow.FindControl("txt_32ftma"); Session["Product"] = ""; Session["Productname"] = ""; Len = 0; bred = 0; hei = 0; for (int i = 0; i < grd_VolumeAnalysis.Rows.Count; i++) { Label VollblL1 = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_Length"); Label VollblB1 = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_Breadth"); Label VollblH1 = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_Height"); Label lblWei = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_Weight"); Label lblCode = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_Code"); Label TotalCFT = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_TotalCFT"); TextBox l1 = (TextBox)grd_VolumeAnalysis.Rows[i].FindControl("txt_Length"); TextBox B1 = (TextBox)grd_VolumeAnalysis.Rows[i].FindControl("txt_Breadth"); TextBox H1 = (TextBox)grd_VolumeAnalysis.Rows[i].FindControl("txt_Height"); Label FeetConv = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_FeetCon"); Label costforFTL = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_CostforFTL"); Label costforTaurus = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_CostforTaurus"); Label costfor32ftsa = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_Costfor32ftsa"); Label costfor32ftma = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_Costfor32ftma"); Label Productname = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_Product"); Label NumberofCartons = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_NumberofCartons"); FConversion = Convert.ToInt32(FeetConv.Text); Label length1 = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_OPTLength"); Label Breadth1 = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_OPTBreadth"); Label Height1 = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_OPTHeight"); Label Cft1 = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_OPTCFT"); Label LoadBoxes = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_OPTLoadBoxes"); Label NoOfBoxesInFtl = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_NoofBoxesFtl"); Label NoOfBoxesInTaurus = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_NoofBoxesTaurus"); Label NoOfBoxesIn32ftsa = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_NoofBoxes32sa"); Label NoOfBoxesIn32ftma = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_NoofBoxes32ma"); Label LoadBoxesInFTL = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_LoadBoxesFTL"); Label LoadBoxesInTaurus = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_LoadBoxesTaurus"); Label LoadBoxesIn32ftsa = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_LoadBoxes32ftsa"); Label LoadBoxesIn32ftma = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_LoadBoxes32ftma"); VolLength = Math.Round(Convert.ToDouble(VollblL1.Text) / FConversion, 2); VolBreadth = Math.Round(Convert.ToDouble(VollblB1.Text) / FConversion, 2); VolHeight = Math.Round(Convert.ToDouble(VollblH1.Text) / FConversion, 2); VolCubicFeet = Math.Round(Convert.ToDouble(VolLength) * Convert.ToDouble(VolBreadth) * Convert.ToDouble(VolHeight) * Convert.ToDouble(NumberofCartons.Text), 2); Len = VolLength; bred = VolBreadth; hei = VolHeight; //assigned 1000 as CubicFeet // CubicFeet1 = 1000; // //Productname.Text = ""; Session["Product"] = Productname.Text; length1.Text = VolLength.ToString(); Breadth1.Text = VolBreadth.ToString(); Height1.Text = VolHeight.ToString(); Cft1.Text = CubicFeet.ToString(); Session["Productname"] = Session["Product"] + "(Code :" + lblCode.Text + ")" + "<br />" + "( L :" + Len + " )" + "<br /> " + " ( B :" + bred + " )" + " <br />" + "( H :" + hei + ")" + " <br />" + "( W :" + lblWei.Text + ")"; Productname.Text = Session["Productname"].ToString (); // Productname.Text = Productname.Text + "--" + "(" + Math.Round(Convert.ToDouble(Length) * Convert.ToDouble(Breadth) * Convert.ToDouble(Height), 2) + ")".ToString(); ; // Product .Text +=Product.Text +"B :"+ Breadth ; //Product.Text = Product.Text + "H :" + Height; TotalCFT.Text = VolCubicFeet.ToString(); ///start calculating space constraint NoOfBoxesInFtl.Text = Math.Round(VolCubicFeet / Convert.ToInt32(ds_capacity.Tables[0].Rows[3][2].ToString()), 2).ToString(); NoOfBoxesInTaurus.Text = Math.Round(VolCubicFeet / Convert.ToInt32(ds_capacity.Tables[0].Rows[0][2].ToString()), 2).ToString(); NoOfBoxesIn32ftsa.Text = Math.Round(VolCubicFeet / Convert.ToInt32(ds_capacity.Tables[0].Rows[1][2].ToString()), 2).ToString(); NoOfBoxesIn32ftma.Text = Math.Round(VolCubicFeet / Convert.ToInt32(ds_capacity.Tables[0].Rows[2][2].ToString()), 2).ToString(); double NoofFTL = (Convert.ToDouble(NoOfBoxesInFtl.Text)); NoOfBoxesInFtl.Text = NoofFTL.ToString(); NoOfBoxesInTaurus.Text = Convert.ToDouble(NoOfBoxesInTaurus.Text).ToString(); NoOfBoxesIn32ftsa.Text = Convert.ToDouble(NoOfBoxesIn32ftsa.Text).ToString(); NoOfBoxesIn32ftma.Text = Convert.ToDouble(NoOfBoxesIn32ftma.Text).ToString(); ////end Label NoofCartonstotal = (Label)grd_VolumeAnalysis.FooterRow.FindControl("lbl_NoofCartonsTotal"); Label TotalCFTtotal = (Label)grd_VolumeAnalysis.FooterRow.FindControl("lbl_TotalCFTtotal"); Label FtlTotal = (Label)grd_VolumeAnalysis.FooterRow.FindControl("lbl_FtlTotal"); Label TarusTotal = (Label)grd_VolumeAnalysis.FooterRow.FindControl("lbl_TarusTotal"); Label Total32sa = (Label)grd_VolumeAnalysis.FooterRow.FindControl("lbl_32saTotal"); Label Total32ma = (Label)grd_VolumeAnalysis.FooterRow.FindControl("lbl_32MaTotal"); NoofCartons += Convert.ToDouble(NumberofCartons.Text); TotalCFTs += Convert.ToDouble(TotalCFT.Text); TotalFTL += Convert.ToDouble(NoOfBoxesInFtl.Text); TotalTarus += Convert.ToDouble(NoOfBoxesInTaurus.Text); Total32saTot += Convert.ToDouble(NoOfBoxesIn32ftsa.Text); Total32maTot += Convert.ToDouble(NoOfBoxesIn32ftma.Text); NoofCartonstotal.Text = NoofCartons.ToString(); TotalCFTtotal.Text = TotalCFTs.ToString(); FtlTotal.Text = TotalFTL.ToString(); TarusTotal.Text = TotalTarus.ToString(); Total32sa.Text = Total32saTot.ToString(); Total32ma.Text = Total32maTot.ToString(); Len = 0; bred = 0; hei = 0; } } catch (Exception ex) { } } } } protected void btn_Summary_Click(object sender, EventArgs e) { try { rdb_Volume.Checked = false; rdb_Weight.Checked = false; pnl_Summary.Visible = true; grd_Summary.Visible = true; grd_VolumeAnalysis.Visible = false; grd_WeightAnalysis.Visible = false; for (int i = 0; i < grd_WeightAnalysis .Rows.Count; i++) { //Total weight TextBox MaxWeight = (TextBox)grd_WeightAnalysis.Rows[i].FindControl("txt_TotalWeight"); TotalWeight += Convert.ToDouble(MaxWeight.Text); //Session["MaxWeight"] = Convert.ToDouble(MaxWeight.Text); } Session["MaxWeight"] = TotalWeight; for (int i = 0; i < grd_VolumeAnalysis.Rows.Count; i++) { Label TotalCFT = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_TotalCFT"); Label lblL1 = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_Length"); Label lblB1 = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_Breadth"); Label lblH1 = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_Height"); Label NumberofCartons = (Label)grd_VolumeAnalysis.Rows[i].FindControl("lbl_NumberofCartons"); Length = Math.Round(Convert.ToDouble(lblL1.Text) / 328, 2); Breadth = Math.Round(Convert.ToDouble(lblB1.Text) / 328, 2); Height = Math.Round(Convert.ToDouble(lblH1.Text) / 328, 2); CubicFeet = Math.Round(Convert.ToDouble(Length) * Convert.ToDouble(Breadth) * Convert.ToDouble(Height) * Convert.ToDouble(NumberofCartons.Text), 2); TotalCFT.Text = CubicFeet.ToString(); TotalCFTs += Convert.ToDouble(TotalCFT.Text); //TotalCFTtotal.Text = TotalCFTs.ToString(); } //Label TotalCFTtotal = (Label)grd_VolumeAnalysis.FooterRow.FindControl("lbl_TotalCFTtotal"); Session["TotalCFT"] = Convert.ToDouble(TotalCFTs); DataTable dt = new DataTable(); DataRow dr; dt.Columns.Add("Optimization"); dt.Columns.Add("FTL"); dt.Columns.Add("Taurus"); dt.Columns.Add("32Ft Single Axle"); dt.Columns.Add("32Ft Double Axle"); dr = dt.NewRow(); dr[0] = "Maxium volume"; dr[1] = 882; dr[2] = 1078; dr[3] = 2048; dr[4] = 2048; dt.Rows.Add(dr); //2nd row dr = dt.NewRow(); dr[0] = "Despatch volume"; //dr[1] = FTLAnalysisTotal.ToString (); dr[1] = Session["TotalCFT"]; dr[2] = Session["TotalCFT"]; dr[3] = Session["TotalCFT"]; dr[4] = Session["TotalCFT"]; dt.Rows.Add(dr); //2nd row FTLSop = txt_FTLSop.Text == "" ? 0 : Convert.ToInt32(txt_FTLSop.Text); double volFtlTrucksReq = FTLSop != 0 ? Math.Round((Convert.ToDouble(Session["TotalCFT"])) / (18 * 7 * FTLSop), 3) : Math.Round(Convert.ToDouble(Session["TotalCFT"]) / 882, 3); TaurusSop = txt_TaurusSop.Text == "" ? 0 : Convert.ToInt32(txt_TaurusSop.Text); double volTaurusTrucksReq = TaurusSop != 0 ? Math.Round((Convert.ToDouble(Session["TotalCFT"])) / (22 * 7 * TaurusSop), 3) : Math.Round(Convert.ToDouble(Session["TotalCFT"]) / 1078, 3); SaSop = txt_32ftsaSop.Text == "" ? 0 : Convert.ToInt32(txt_32ftsaSop.Text); double vol32ftsaTrucksReq = SaSop != 0 ? Math.Round((Convert.ToDouble(Session["TotalCFT"])) / (32 * 8 * SaSop), 3) : Math.Round(Convert.ToDouble(Session["TotalCFT"]) / 2048, 3); MaSop = txt_32ftmaSop.Text == "" ? 0 : Convert.ToInt32(txt_32ftmaSop.Text); double vol32ftmaTrucksReq = MaSop != 0 ? Math.Round((Convert.ToDouble(Session["TotalCFT"])) / (32 * 8 * MaSop), 3) : Math.Round(Convert.ToDouble(Session["TotalCFT"]) / 2048, 3); dr = dt.NewRow(); dr[0] = "Trucks required"; //dr[1] = FTLAnalysisTotal.ToString (); dr[1] = volFtlTrucksReq; dr[2] = volTaurusTrucksReq; dr[3] =vol32ftsaTrucksReq; dr[4] = vol32ftmaTrucksReq; dt.Rows.Add(dr); dr = dt.NewRow(); dr[0] = "Total cost"; txt_FTL.Text = txt_FTL.Text == "" ? "0" : txt_FTL.Text; dr[1] = Math.Round(volFtlTrucksReq * Convert.ToDouble(txt_FTL.Text), 2); txt_Taurus.Text = txt_Taurus.Text == "" ? "0" : txt_Taurus.Text; dr[2] = Math.Round(volTaurusTrucksReq * Convert.ToDouble(txt_Taurus.Text), 2); txt_32ftsa.Text = txt_32ftsa.Text == "" ? "0" : txt_32ftsa.Text; dr[3] = Math.Round(vol32ftsaTrucksReq * Convert.ToDouble(txt_32ftsa.Text), 2); txt_32ftma.Text = txt_32ftma.Text == "" ? "0" : txt_32ftma.Text; dr[4] = Math.Round(vol32ftsaTrucksReq * Convert.ToDouble(txt_32ftma.Text), 2); dt.Rows.Add(dr); // 3rd row dr = dt.NewRow(); dr[0] = "Maximum weight"; dr[1] = 9000 +" "+ "(KGS)"; dr[2] = 15000 + " " + "(KGS)"; dr[3] = 7000 + " " + "(KGS)"; dr[4] = 15000 + " " + "(KGS)"; dt.Rows.Add(dr); // 4th row dr = dt.NewRow(); dr[0] = "Despatch weight"; dr[1] = Session["MaxWeight"] + " " + "(KGS)"; dr[2] = Session["MaxWeight"] + " " + "(KGS)"; dr[3] = Session["MaxWeight"] + " " + "(KGS)"; dr[4] = Session["MaxWeight"] + " " + "(KGS)"; dt.Rows.Add(dr); //5th row double WeiFtlTrucksReq = Math.Round(Convert.ToDouble(Session["MaxWeight"]) / 9000, 3); double WeiTaurusTrucksReq = Math.Round(Convert.ToDouble(Session["MaxWeight"]) / 16000, 3); double Wei32ftsaTrucksReq = Math.Round(Convert.ToDouble(Session["MaxWeight"]) / 7000, 3); double Wei32ftmaTrucksReq = Math.Round(Convert.ToDouble(Session["MaxWeight"]) / 15000, 3); dr = dt.NewRow(); dr[0] = "Trucks required"; dr[1] = WeiFtlTrucksReq; dr[2] = WeiTaurusTrucksReq; dr[3] = Wei32ftsaTrucksReq; dr[4] = Wei32ftmaTrucksReq; dt.Rows.Add(dr); // 6th row dr = dt.NewRow(); dr[0] = "Total cost"; dr[1] = Math.Round(WeiFtlTrucksReq * Convert.ToDouble(txt_FTL.Text), 2); dr[2] = Math.Round(WeiTaurusTrucksReq * Convert.ToDouble(txt_Taurus.Text), 2); dr[3] = Math.Round(Wei32ftsaTrucksReq * Convert.ToDouble(txt_32ftsa.Text), 2); dr[4] = Math.Round(Wei32ftmaTrucksReq * Convert.ToDouble(txt_32ftma.Text), 2); dt.Rows.Add(dr); // 6th row grd_Summary.DataSource = dt; grd_Summary.DataBind(); } catch (Exception ex) { } } protected void btn_TrucksSummary_Click(object sender, EventArgs e) { try { for (int i = 0; i < grd_WeightAnalysis.Rows.Count; i++) { TextBox MaxWeight = (TextBox)grd_WeightAnalysis.Rows[i].FindControl("txt_TotalWeight"); TextBox NoofCartons = (TextBox)grd_WeightAnalysis.Rows[i].FindControl("txt_Lotsize"); Label Traveldate = (Label)grd_WeightAnalysis.Rows[i].FindControl("lbl_TravelDate"); DropDownList ddlTruck = (DropDownList)grd_WeightAnalysis.Rows[i].FindControl("ddl_Truck"); FTLDesWei += ddlTruck.SelectedItem.Text == "FTL" ? Convert.ToDouble(MaxWeight.Text) : 0; TaurusDesWei += ddlTruck.SelectedItem.Text == "Taurus" ? Convert.ToDouble(MaxWeight.Text) : 0; SaDesWei += ddlTruck.SelectedItem.Text == "32ftsa" ? Convert.ToDouble(MaxWeight.Text) : 0; MaDesWei += ddlTruck.SelectedItem.Text == "32ftma" ? Convert.ToDouble(MaxWeight.Text) : 0; TravelDate = Traveldate.Text; NoOfFTLCartons += ddlTruck.SelectedItem.Text == "FTL" ? Convert.ToDouble(NoofCartons.Text) : 0; NoOfTaurusCartons += ddlTruck.SelectedItem.Text == "Taurus" ? Convert.ToDouble(NoofCartons.Text) : 0; NoOfSaCartons += ddlTruck.SelectedItem.Text == "32ftsa" ? Convert.ToDouble(NoofCartons.Text) : 0; NoOfMaCartons += ddlTruck.SelectedItem.Text == "32ftma" ? Convert.ToDouble(NoofCartons.Text) : 0; } //despatch weight lbl_FtlWeight.Text = FTLDesWei.ToString(); lbl_TaurusWeight.Text = TaurusDesWei.ToString(); lbl_32saWeight.Text = SaDesWei.ToString(); lbl_32maWeight.Text = MaDesWei.ToString(); lbl_FTLNoofCartons.Text = NoOfFTLCartons.ToString(); lbl_TaurusNoofCartons.Text = NoOfTaurusCartons.ToString(); lbl_SaNoofCartons.Text = NoOfSaCartons.ToString(); lbl_MaNoofCartons.Text = NoOfMaCartons.ToString(); FTLNoOFTrucks = Math.Round((FTLDesWei / 9000), 2); TaurusNoOFTrucks = Math.Round((TaurusDesWei / 15000), 2); SaNoOFTrucks = Math.Round((SaDesWei / 7000), 2); MaNoOFTrucks = Math.Round((MaDesWei / 15000), 2); //noof trucks lbl_FtlTrucksReq.Text = FTLNoOFTrucks.ToString(); lbl_TaurusTrucksReq.Text = TaurusNoOFTrucks.ToString(); lbl_32saTrucksReq.Text = SaNoOFTrucks.ToString(); lbl_32maTrucksReq.Text = MaNoOFTrucks.ToString(); FtlCost = txt_FtlCost.Text == "" ? 0 : Convert.ToDouble(txt_FtlCost.Text); TaurusCost = txt_TaurusCost.Text == "" ? 0 : Convert.ToDouble(txt_TaurusCost.Text); SaCost = txt_SaCost.Text == "" ? 0 : Convert.ToDouble(txt_SaCost.Text); MaCost = txt_MaCost.Text == "" ? 0 : Convert.ToDouble(txt_MaCost.Text); lbl_FtlTotCost.Text = Math.Round((FTLNoOFTrucks * FtlCost), 2).ToString(); lbl_TaurusTotCost.Text = Math.Round((TaurusNoOFTrucks * TaurusCost), 2).ToString(); lbl_SaTotCost.Text = Math.Round((SaNoOFTrucks * SaCost), 2).ToString(); lbl_MaTotCost.Text = Math.Round((MaNoOFTrucks * MaCost), 2).ToString(); lbl_PlanID.Text = ddl_PlanNo.SelectedItem.Text; lbl_FroLoc.Text = ddl_FromLoc.SelectedItem.Text; lbl_ToLoc.Text = ddl_ToLoc.SelectedItem.Text; lbl_Traveldate.Text = TravelDate; pnl_OptSummary.Visible = true ; lbl_FTLCostPerCarton.Text = Math.Round((Convert.ToDouble(lbl_FtlTotCost.Text) / NoOfFTLCartons), 2).ToString(); lbl_TaurusCostPerCarton.Text = Math.Round((Convert.ToDouble(lbl_TaurusTotCost.Text) / NoOfTaurusCartons), 2).ToString(); lbl_SaCostPerCarton.Text = Math.Round((Convert.ToDouble(lbl_SaTotCost.Text) / NoOfSaCartons), 2).ToString(); lbl_MaCostPerCarton.Text = Math.Round((Convert.ToDouble(lbl_MaTotCost.Text) / NoOfMaCartons), 2).ToString(); lbl_FTLCostPerton.Text = Math.Round((Convert.ToDouble(lbl_FtlTotCost.Text) / FTLDesWei), 2).ToString(); lbl_TaurusCostPerton.Text = Math.Round((Convert.ToDouble(lbl_TaurusTotCost.Text) / TaurusDesWei), 2).ToString(); lbl_SaCostPerton.Text = Math.Round((Convert.ToDouble(lbl_SaTotCost.Text) / SaDesWei), 2).ToString(); lbl_MaCostPerton.Text = Math.Round((Convert.ToDouble(lbl_MaTotCost.Text) / MaDesWei), 2).ToString(); } catch (Exception ex) { } } protected void btn_GtnOptimization_Click(object sender, EventArgs e) { Response.Redirect("OptDispatchPlan.aspx"); } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; namespace SharedLibrary { /// <summary> /// http://hamidmosalla.com/2018/06/24/what-is-synchronizationcontext/ /// https://devblogs.microsoft.com/pfxteam/should-i-expose-synchronous-wrappers-for-asynchronous-methods/ /// </summary> public class RemoteHelper { readonly HttpClient httpClient; readonly BaseLog log; public RemoteHelper(BaseLog log) { httpClient = new HttpClient(); this.log = log; } public HttpResponseMessage GetResponse() { var task = Task.Run(() => { log.Write("RemoteHelper.GetResponse.AnonymousFunction"); return GetResponseAsync(); }); log.Write("RemoteHelper.GetResponse"); var response = task.GetAwaiter().GetResult(); log.Write("RemoteHelper.GetResponse"); return response; } public HttpResponseMessage GetResponseDeadlock() { log.Write("RemoteHelper.GetResponseDeadlock"); var response = GetResponseAsync().GetAwaiter().GetResult(); log.Write("RemoteHelper.GetResponseDeadlock"); return response; } public async Task<HttpResponseMessage> GetResponseAsync() { log.Write("RemoteHelper.GetResponseAsync"); var resp = await httpClient.GetAsync("http://localhost:51265/api/Default"); log.Write("RemoteHelper.GetResponseAsync"); return resp; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using Stundenplan.Models; using Stundenplan.Services; using Xamarin.Forms; namespace Stundenplan.ViewModels { public class BaseViewModel : INotifyPropertyChanged { private string caption = string.Empty; private DateTime date = DateTime.Now; private string day = string.Empty; private bool isBusy; private string title = string.Empty; public IDataStore<Lesson> DataStore => DependencyService.Get<IDataStore<Lesson>>() ?? new MockDataStore(this.date); public bool IsBusy { get => this.isBusy; set => this.SetProperty(ref this.isBusy, value); } public string Title { get => this.title; set => this.SetProperty(ref this.title, value); } public string Day { get => this.day; set => this.SetProperty(ref this.day, value); } public string Caption { get => this.day; set => this.SetProperty(ref this.caption, value); } public DateTime Date { get => this.date; set => this.SetProperty(ref this.date, value); } protected bool SetProperty<T>(ref T backingStore, T value, [CallerMemberName] string propertyName = "", Action onChanged = null) { if (EqualityComparer<T>.Default.Equals(backingStore, value)) return false; backingStore = value; onChanged?.Invoke(); this.OnPropertyChanged(propertyName); return true; } #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string propertyName = "") { var changed = this.PropertyChanged; if (changed == null) return; changed.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion } }
using UnityEngine; using UnityEditor; using System.IO; using System.Collections; using System.Collections.Generic; public class DoAssetBundle : EditorWindow { [MenuItem("EditorTools/DoAssetBundle")] private static void _mShowAssetBuddle() { DoAssetBundle _DoAssetBundleScript = (DoAssetBundle)EditorWindow.GetWindow(typeof(DoAssetBundle)); _DoAssetBundleScript.Show(); } void OnGUI() { GUILayout.Label("Nope", EditorStyles.boldLabel); } }
using System; using System.ComponentModel; using System.Windows; using CopyByExif.Core; namespace CopyByExif { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { BackgroundWorker copyWorker; public CopySettings CopySettings { get => (CopySettings)DataContext; set => DataContext = value; } public MainWindow() { InitializeComponent(); InitializeCopyWorker(); CopySettings = new CopySettings(); } private void Btn_BrowseFrom_Click(object sender, RoutedEventArgs e) { var fd = new Ookii.Dialogs.Wpf.VistaFolderBrowserDialog { Description = Properties.Resources.Lbl_FromDirectory, UseDescriptionForTitle = true }; if (fd.ShowDialog().GetValueOrDefault()) CopySettings.FromDirectoryPath = fd.SelectedPath; } private void Btn_BrowseTo_Click(object sender, RoutedEventArgs e) { var fd = new Ookii.Dialogs.Wpf.VistaFolderBrowserDialog { Description = Properties.Resources.Lbl_ToDirectory, UseDescriptionForTitle = true }; if (fd.ShowDialog().GetValueOrDefault()) CopySettings.ToDirectoryPath = fd.SelectedPath; } private void Btn_ControlCopy_Click(object sender, RoutedEventArgs e) { if (!copyWorker.IsBusy) { btn_ControlCopy.Content = Properties.Resources.CancelCopy; copyWorker.RunWorkerAsync(CopySettings); } else { copyWorker.CancelAsync(); btn_ControlCopy.Content = Properties.Resources.StartCopy; } } private void CopyWorker_DoWork(object sender, DoWorkEventArgs e) { try { CopyPhotos.Copy(e.Argument as CopySettings, sender as BackgroundWorker); } catch (Exception exc) { MessageBox.Show(exc.Message, Properties.Resources.ErrorCopyingFiles, MessageBoxButton.OK, MessageBoxImage.Error); } } private void InitializeCopyWorker() { if (copyWorker != null) copyWorker.Dispose(); copyWorker = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = true }; copyWorker.DoWork += CopyWorker_DoWork; copyWorker.ProgressChanged += (_, pcea) => progressBar.Value = pcea.ProgressPercentage; copyWorker.RunWorkerCompleted += (_, rwcea) => btn_ControlCopy.Content = Properties.Resources.StartCopy; } } }
using System; using System.Collections.Generic; using cn.bmob.api; using cn.bmob.response; using System.Collections; using System.Text; using System.IO; using cn.bmob.tools; using cn.bmob.io; using cn.bmob.json; using cn.bmob.Extensions; using cn.bmob.config; using cn.bmob.exception; namespace cn.bmob.http { /// <summary> /// 请求回调函数 /// /// <para>Bmob服务器请求到数据后调用该委托实现。 /// </para> /// </summary> /// <typeparam name="T">返回类型</typeparam> /// <param name="response">请求返回数据</param> /// <param name="exception">调用过程中发生的异常,包括调用执行过程中的校验和服务端返回状态非200情况。</param> public delegate void BmobCallback<T>(T response, BmobException exception); internal class BmobCommand<T> { private BmobInteractObject receiver; public BmobCommand(BmobInteractObject mReceiver) { this.receiver = mReceiver; } internal BmobInteractObject getReceiver() { return receiver; } protected virtual IDictionary<String, String> getHeaders() { if (receiver.AppKey == null || receiver.RestKey == null) { throw new BmobException("applicationid and restkey must be set!!! please invoke Bmob#initialize first. "); } IDictionary<String, String> headers = new Dictionary<String, String>(); headers.Add("X-Bmob-Application-Id", receiver.AppKey); headers.Add("X-Bmob-REST-API-Key", receiver.RestKey); if (receiver.MasterKey != null) { headers.Add("X-Bmob-Master-Key", receiver.MasterKey); } // 如果是用户表修改的请求需要检查是否设置了sessiontoken if (receiver.SessionToken != null) headers.Add("X-Bmob-Session-Token", receiver.SessionToken); // XXX 默认Unity WWW已经添加了压缩标志; WindowsPhone8默认不支持GzipStream,暂时不添加压缩! // headers.Add("Accept-Encoding", "gzip,deflate"); return headers; } /// <typeparam name="R">操作返回值类型</typeparam> /// <param name="request">参数对应为: url, contenttype, requestData, headers, callback(请求服务器数据返回值回调函数)</param> /// <param name="fCallback">返回结果回调函数</param> /// <returns>操作返回值</returns> public virtual R execute<R>(Func<String, String, String, Byte[], IDictionary<String, String>, Action<String, Status, BmobException>, R> request, BmobCallback<T> fCallback) { var url = receiver.Url; var contentType = receiver.ContentType; var postData = getPostData(); var headers = getHeaders(); return Execute(request, url, contentType, postData, headers, fCallback); } protected R Execute<R>(Func<String, String, String, Byte[], IDictionary<String, String>, Action<String, Status, BmobException>, R> request, String url, String contentType, Byte[] postData, IDictionary<String, String> headers, BmobCallback<T> fCallback) { BmobDebug.T("\r\n\t请求的URL : " + url + "\r\n\t交互对象(以请求的数据为准): " + JsonAdapter.JSON.ToRawString(receiver) + "\r\n\t请求的数据: " + JsonAdapter.JSON.ToJsonString(receiver.Data)); return request.Invoke(url, receiver.Method, contentType, postData, headers, (resp, status, ex) => { if (BmobDebug.Debug) { BmobDebug.D("返回数据内容为: " + resp); } else { var rp = resp.Length > 400 ? resp.Substring(0, 200) + " ... ... ... ... ... ... " + resp.Substring(resp.Length - 200) : resp; BmobDebug.I("返回数据内容为: " + rp); } onPostExecute(resp, status, ex, fCallback); }); } protected virtual byte[] getPostData() { if (receiver.Data == null || receiver.Method.Equals("GET")) { return null; } var data = JsonAdapter.JSON.ToJsonString(receiver.Data); return data.GetBytes(); } protected void onPostExecute(String result, Status status, BmobException exception, BmobCallback<T> fCallback) { T data; BmobException ex; if (exception != null) { data = default(T); if (result == null) ex = exception; else ex = new BmobException(exception.Message + ", and response content is " + result, exception.InnerException); } else { BmobResponseParser<T> parser = getResponseParser(status); parser.parse(result); data = parser.data; ex = parser.exception; } if (ex != null) { BmobDebug.T("[ BmobCommand ] after parse response, error: '" + ex.Message + "'"); } fCallback(data, ex); } protected virtual BmobResponseParser<T> getResponseParser(Status status) { return new BmobResponseParser<T>(status); } } internal class BmobFileCommand<T> : BmobCommand<T> { public BmobFileCommand(BmobInteractObject mReceiver) : base(mReceiver) { } protected override byte[] getPostData() { var data = getReceiver().Data as BmobLocalFile; return data.Content(); } } }
using Newtonsoft.Json; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using UnityEngine; using UnityEngine.UI; using Random = UnityEngine.Random; public class Graph : MonoBehaviour { public List<Vertex> vertices; public List<Edge> edges; public GameObject vertexPrefab; public GameObject edgePrefab; private List<Step> steps; private int stepNum; private Colors colors; public Button AddVertexButton; public Button ColorEdgesButton; public Button BackToDrawingButton; public Button PreviousButton; public Button NextButton; public Text infoText; public Text DeltaText; // Start is called before the first frame update void Start() { stepNum = 0; steps = new List<Step>(); colors = new Colors(); BackToDrawingButton.interactable = false; PreviousButton.interactable = false; NextButton.interactable = false; infoText.text = ""; ReCalculateDelta(); } // Update is called once per frame void Update() { } public bool CanEditGraph() { return !BackToDrawingButton.IsInteractable(); } public void AddVertex() { Vector3 newPos = new Vector3(transform.position.x, transform.position.y, -2); GameObject newVertex = GameObject.Instantiate(vertexPrefab, newPos, Quaternion.identity); var v = newVertex.GetComponent<Vertex>(); v.id = vertices.Count; vertices.Add(v); } public void RemoveVertex(int index) { var v = vertices[index]; vertices.RemoveAt(index); ReCalculateDelta(); Destroy(v.gameObject); ReNumberVertices(); } public void AddEdge(Vertex v1, Vertex v2) { Vector3 newPos = new Vector3(transform.position.x, transform.position.y, transform.position.z); GameObject newEdge = GameObject.Instantiate(edgePrefab, newPos, Quaternion.identity); var e = newEdge.GetComponent<Edge>(); e.v1 = v1; e.v2 = v2; e.v1.degree++; e.v2.degree++; ReCalculateDelta(); e.id = edges.Count; edges.Add(e); } public void RemoveEdge(int index) { var e = edges[index]; edges.RemoveAt(index); e.v1.degree--; e.v2.degree--; ReCalculateDelta(); Destroy(e.gameObject); } public void ReCalculateDelta() { int maxDegree = 0; foreach(var vertex in vertices) { if(vertex.degree > maxDegree) { maxDegree = vertex.degree; } } int maxColor = 0; foreach (var edge in edges) { if (edge.colorId > maxColor) { maxColor = edge.colorId; } } DeltaText.text = "Delta: " + maxDegree.ToString() + "\nColors Used: " + maxColor.ToString(); } public void ReNumberVertices() { for(int i = 0; i < vertices.Count; i++) { vertices[i].id = i; } } public void ClearEdges(Vertex v) { for (int i = 0; i < edges.Count; i++) { if (edges[i].v1 == v || edges[i].v2 == v) { RemoveEdge(i); i--; } } } public void ColorEdges() { List<int> numList = new List<int>(); numList.Add(vertices.Count); numList.Add(edges.Count); for(int i = 0; i < edges.Count; i++) { numList.Add(edges[i].v1.id + 1); numList.Add(edges[i].v2.id + 1); } int[] temp = numList.ToArray(); getGraphColorJson(temp, temp.Length); var json = System.IO.File.ReadAllText("edge colors.json"); var stepsinfo = JsonConvert.DeserializeObject<List<List<List<int>>>>(json); foreach (var stepinfo in stepsinfo) { var step = new Step(stepinfo[0][0], stepinfo[0][1]); steps.Add(step); for (int i = 1; i < stepinfo.Count; i++) { step.changes.Add(new Change(stepinfo[i][0], stepinfo[i][1], stepinfo[i][2], stepinfo[i][3])); } } PreviousButton.interactable = false; NextButton.interactable = true; BackToDrawingButton.interactable = true; ColorEdgesButton.interactable = false; AddVertexButton.interactable = false; } public void ChangeToDrawing() { stepNum = 0; steps = new List<Step>(); colors = new Colors(); ReCalculateDelta(); PreviousButton.interactable = false; NextButton.interactable = false; BackToDrawingButton.interactable = false; ColorEdgesButton.interactable = true; AddVertexButton.interactable = true; foreach(var edge in edges) { edge.ReColor(colors.GetColor(0), 0); } } public void NextStep() { stepNum++; var step = steps[stepNum - 1]; UpdateInfo(step); foreach (var change in step.changes) { Edge e = null; for(int i = 0; i < edges.Count; i++) { var edge = edges[i]; if ((change.changedV1 - 1 == edge.v1.id && change.changedV2 - 1 == edge.v2.id) || (change.changedV1 - 1 == edge.v2.id && change.changedV2 - 1 == edge.v1.id)) { e = edge; } } e.ReColor(colors.GetColor(change.changedNewColor), change.changedNewColor); } PreviousButton.interactable = true; if (stepNum >= steps.Count) { NextButton.interactable = false; } ReCalculateDelta(); } public void PreviousStep() { var step = steps[stepNum - 1]; stepNum--; if (stepNum <= 0) infoText.text = ""; else UpdateInfo(steps[stepNum - 1]); for (int j = step.changes.Count - 1; j >= 0; j--) { var change = step.changes[j]; Edge e = null; for (int i = 0; i < edges.Count; i++) { var edge = edges[i]; if ((change.changedV1 - 1 == edge.v1.id && change.changedV2 - 1 == edge.v2.id) || (change.changedV1 - 1 == edge.v2.id && change.changedV2 - 1 == edge.v1.id)) { e = edge; } } e.ReColor(colors.GetColor(change.changedOldColor), change.changedOldColor); } NextButton.interactable = true; if(stepNum <= 0) { PreviousButton.interactable = false; } ReCalculateDelta(); } public void UpdateInfo(Step step) { var result = ""; result += "Coloring edge " + step.coloredV1.ToString() + "," + step.coloredV2.ToString() + "\n"; foreach(var change in step.changes) { result += "Edge " + change.changedV1.ToString() + "," + change.changedV2.ToString() + " is recolored from " + change.changedOldColor.ToString() + " to " + change.changedNewColor.ToString() + "\n"; } infoText.text = result; } [DllImport("Vizing's Algorithm.dll", CallingConvention = CallingConvention.Cdecl)] private extern static void getGraphColorJson(int[] input, int size); public class Step { public int coloredV1; public int coloredV2; public List<Change> changes; public Step(int coloredV1, int coloredV2) { this.coloredV1 = coloredV1; this.coloredV2 = coloredV2; changes = new List<Change>(); } } public class Change { public int changedV1; public int changedV2; public int changedOldColor; public int changedNewColor; public Change(int changedV1, int changedV2, int changedOldColor, int changedNewColor) { this.changedV1 = changedV1; this.changedV2 = changedV2; this.changedOldColor = changedOldColor; this.changedNewColor = changedNewColor; } } public class Colors { public List<Color> colors; public Colors() { colors = new List<Color>() { new Color(1, 1, 1), new Color(1, 0, 0), new Color(0, 1, 0), new Color(0, 0, 1), new Color(1, 1, 0), new Color(1, 0, 1), new Color(0, 1, 1) }; } public Color GetColor(int i) { if(i < colors.Count) { return colors[i]; } //Need more colors. Autogenerate one var newColor = new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f)); colors.Add(newColor); return newColor; } } }
using System; using MyResources; using TeaseAI_CE.Scripting.VType; namespace TeaseAI_CE.Scripting { public static class CoreFunctions { public static void AddTo(VM vm) { // if statements vm.AddFunction(@if); vm.AddFunction(elseif); vm.AddFunction(@else); vm.AddFunction(isSet); vm.AddFunction(@goto); // date time vm.AddFunction(date); vm.AddFunction(time); vm.AddFunction("x", (Context sender, Variable[] args) => { return new Variable(); }); } #region if statements private static Variable @if(Context sender, Variable[] args) { sender.ExitLine = false; foreach (var arg in args) { if (arg.IsSet == false) sender.ExitLine = true; else if (arg.Value is bool == false) { sender.Root.Log.ErrorF(StringsScripting.Formatted_Function_invalid_type, "If", arg.Value.GetType().Name, typeof(bool).Name); sender.ExitLine = true; } else if ((bool)arg.Value == false) sender.ExitLine = true; } sender.LastIf = !sender.ExitLine; return new Variable(sender.LastIf); } private static Variable elseif(Context sender, Variable[] args) { if (sender.LastIf == true) return new Variable(false); return @if(sender, args); } private static Variable @else(Context sender, Variable[] args) { if (args.Length != 0) sender.Root.Log.ErrorF(StringsScripting.Formatted_Function_arguments_not_empty, "Else"); sender.ExitLine = sender.LastIf; sender.LastIf = !sender.ExitLine; return new Variable(sender.LastIf); } #endregion #region goto, isSet private static Variable isSet(Context sender, Variable[] args) { if (args.Length == 0) { sender.Root.Log.WarningF(StringsScripting.Formatted_Function_arguments_empty, "IsSet"); return new Variable(false); } foreach (var arg in args) { if (!arg.IsSet) return new Variable(false); } return new Variable(true); } private static Variable @goto(Context sender, Variable[] args) { if (args.Length == 0) { sender.Root.Log.ErrorF(StringsScripting.Formatted_Function_arguments_empty, "GoTo"); return null; } int i = -1; foreach (var arg in args) { ++i; if (!arg.IsSet) continue; BlockBase script = null; object value = arg.Value; if (value is BlockBase) script = (BlockBase)value; else if (value is VType.Query) script = sender.Controller.VM.QueryScript((VType.Query)value, sender.Root.Log); else if (value is string) // string can be a single query key. script = sender.Controller.VM.QueryScript((string)value, sender.Root.Log); else sender.Root.Log.ErrorF(StringsScripting.Formatted_Function_invalid_type, "GoTo", arg.Value.GetType().Name, typeof(Script).Name); if (script != null) { if (ReferenceEquals(script, sender.Root)) sender.Root.Log.Error(StringsScripting.FunctionGoTo_cannot_goto_self); else if (sender.Root.Valid != BlockBase.Validation.Running) sender.Controller.Add(script); } } return null; } #endregion #region date time private static Variable date(Context sender, Variable[] args) { if (args.Length == 0) return new Variable(new Date(DateTime.Now)); if (args.Length == 1) { if (!args[0].IsSet) sender.Root.Log.ErrorF(StringsScripting.Formatted_Function_argument_unset, "Date", ""); else if (args[0].Value is string) { DateTime result; try { if (DateTime.TryParse((string)args[0].Value, out result)) return new Variable(new Date(result)); else sender.Root.Log.ErrorF(StringsScripting.Formatted_Unable_to_parse, "Date", (string)args[0].Value, typeof(DateTime).Name); } catch (ArgumentOutOfRangeException ex) { sender.Root.Log.Error(ex.Message); } } else sender.Root.Log.ErrorF(StringsScripting.Formatted_Function_invalid_type, "Date", args[0].Value.GetType().Name, typeof(string).Name); return new Variable(new Date(DateTime.Now)); } else sender.Root.Log.WarningF(StringsScripting.Formatted_Function_arguments_less_than_two, "Date"); return new Variable(new Date(DateTime.Now)); } private static Variable time(Context sender, Variable[] args) { if (args.Length == 0) return new Variable(new TimeFrame(TimeSpan.Zero)); if (args.Length == 1) { if (!args[0].IsSet) sender.Root.Log.ErrorF(StringsScripting.Formatted_Function_argument_unset, "Time", ""); else if (args[0].Value is string) { TimeSpan result; if (TimeSpan.TryParse((string)args[0].Value, out result)) return new Variable(new TimeFrame(result)); else sender.Root.Log.ErrorF(StringsScripting.Formatted_Unable_to_parse, "Time", (string)args[0].Value, typeof(TimeSpan).Name); } else sender.Root.Log.ErrorF(StringsScripting.Formatted_Function_invalid_type, "Time", args[0].Value.GetType().Name, typeof(string).Name); return new Variable(new TimeFrame(TimeSpan.Zero)); } else sender.Root.Log.WarningF(StringsScripting.Formatted_Function_arguments_less_than_two, "Time"); return new Variable(new TimeFrame(TimeSpan.Zero)); } #endregion } }