text stringlengths 13 6.01M |
|---|
using System;
namespace C__Project
{
class String_Input
{
static void First(string[] args)
{
string greeting = "Hello everyone";
Console.WriteLine(greeting);
string name;
Console.WriteLine("What is your name?");
name = Console.ReadLine();
Console.WriteLine("What's up, " + name );
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CoreTest1.Models
{
public class Contract
{
public int ID { get; set; }
public int CustomerID { get; set; }
public DateTime SignDate { get; set; }
public Customer Customer { get; set; }
public ICollection<PartInContract> PartsInContr { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// 557. Reverse Words in a String III
/// </summary>
namespace leetcodeLocal
{
class ReverseWords
{
public static string ReverseWords(string s)
{
string[] words = s.Split(' ');
StringBuilder sb = new StringBuilder();
foreach (var word in words)
{
sb.Append(Reverse(word));
sb.Append(" ");
}
return sb.ToString().TrimEnd();
}
public static string Reverse(string s)
{
if (s == null) return null;
char[] charArray = s.ToCharArray();
int len = s.Length - 1;
for (int i = 0; i < len; i++, len--)
{
charArray[i] ^= charArray[len];
charArray[len] ^= charArray[i];
charArray[i] ^= charArray[len];
}
return new string(charArray).TrimEnd();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class MainMenu : MonoBehaviour {
public Button BackToGame;
public Button Play;
public Button Highscore;
public Button Quit;
void Update(){
// BackToGame.onClick.AddListener(OpenBackToGame);
Play.onClick.AddListener(PlayGame);
Highscore.onClick.AddListener(OpenHighscore);
Quit.onClick.AddListener(QuitGame);
}
public void OpenBackToGame(){
SceneManager.GetActiveScene();
}
public void PlayGame(){
SceneManager.LoadScene("Scene_1", LoadSceneMode.Single);
}
public void QuitGame(){
Application.Quit();
}
public void OpenHighscore(){
SceneManager.LoadScene("Highscore", LoadSceneMode.Single);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using RPGTALK;
public class DialogManager : MonoBehaviour
{
[SerializeField] RPGTalk RPGTalk;
[SerializeField] GameObject authenticationWindow;
[SerializeField] GameObject answerWindow;
[SerializeField] GameObject eventSystem;
[SerializeField] Player player;
string linePartA = "cutscene";
public int currentDialog = 1;
int currentQuestion = 0;
string linePartBStart = "_start";
string linePartBEnd = "_end";
void Start()
{
eventSystem = GameObject.Find("EventSystem");
Invoke("SetLinesPositions", 1);
RPGTalk.OnMadeChoice += OnMadeChoice;
player.canMove = false;
//RPGTalk.NewTalk(RPGTalk.lineToStart, RPGTalk.lineToBreak);
}
private void Update()
{
if (Input.GetButtonDown("XboxA"))
ApproveAuthentication();
}
void SetLinesPositions()
{
RPGTalk.lineToStart = linePartA + currentDialog.ToString() + linePartBStart;
RPGTalk.lineToBreak = linePartA + currentDialog.ToString() + linePartBEnd;
}
public void ApproveAuthentication()
{
UIManager.Instance.CloseWindow(answerWindow);
UIManager.Instance.CloseWindow(authenticationWindow);
eventSystem.SetActive(true);
RPGTalk.enabled = true;
}
public void ReturnMovement()
{
player.canMove = true;
}
public void OpenAuthenticationWindow()
{
UIManager.Instance.OpenWindow(authenticationWindow);
eventSystem.SetActive(false);
}
public void OpenAnswerWindow()
{
UIManager.Instance.OpenWindow(answerWindow);
RPGTalk.enabled = false;
}
public void HandleDialog()
{
switch (currentDialog)
{
default:
case 1:
BeginNextDialog();
break;
case 2:
OpenAnswerWindow();
break;
case 3:
ReturnMovement();
break;
case 4:
OpenAnswerWindow();
break;
case 5:
ReturnMovement();
break;
case 6:
OpenAnswerWindow();
break;
case 7:
ReturnMovement();
break;
case 8:
//OpenAnswerWindow();
break;
case 9:
//OpenAnswerWindow();
break;
}
}
public void BeginNextDialog()
{
currentDialog++;
SetLinesPositions();
RPGTalk.NewTalk(RPGTalk.lineToStart, RPGTalk.lineToBreak);
player.canMove = false;
}
void OnMadeChoice(string questionId, int choiceID)
{
if (choiceID == 0)
{
Debug.Log("0");
BeginNextDialog();
}
else
{
Debug.Log("1");
LevelManager.Instance.RestartLevel();
}
}
}
|
using System;
namespace MisskeyDotNet
{
[Serializable]
public class MisskeyApiException : Exception
{
public Error Error { get; }
public MisskeyApiException(Error error)
: base($"Misskey API Error: {error.Message}{(error.Info == null ? "" : $"{error.Info.Param}: {error.Info.Reason}")}")
{
Error = error;
}
}
} |
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace KMS.Eleven
{
public class OperationTest
{
var services = new ServiceCollection();
// 默认构造
services.AddSingleton<IOperationSingleton, Operation>();
// 自定义传入Guid空值
services.AddSingleton<IOperationSingleton>(
new Operation(Guid.Empty));
// 自定义传入一个New的Guid
services.AddSingleton<IOperationSingleton>(
new Operation(Guid.NewGuid()));
var provider = services.BuildServiceProvider();
// 输出singletone1的Guid
var singletone1 = provider.GetService<IOperationSingleton>();
Console.WriteLine($"signletone1: {singletone1.OperationId}");
// 输出singletone2的Guid
var singletone2 = provider.GetService<IOperationSingleton>();
Console.WriteLine($"signletone2: {singletone2.OperationId}");
Console.WriteLine($"singletone1 == singletone2 ? : { singletone1 == singletone2 }");
}
public interface IServiceCollection : IList<ServiceDescriptor>
{
private static IServiceCollection Add(
IServiceCollection collection,
Type serviceType,
Type implementationType,
ServiceLifetime lifetime)
{
var descriptor =
new ServiceDescriptor(serviceType, implementationType, lifetime);
collection.Add(descriptor);
return collection;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IRAP.Entity.MES
{
/// <summary>
/// 未结生产工单
/// </summary>
public class OpenProductionWorkOrder
{
/// <summary>
/// 序号
/// </summary>
public int Ordinal { get; set; }
/// <summary>
/// 工单签发事实编号
/// </summary>
public long PWOIssuingFactID { get; set; }
/// <summary>
/// 工单签发事实分区键
/// </summary>
public long TF482PK { get; set; }
/// <summary>
/// 产品叶标识
/// </summary>
public int T102LeafID { get; set; }
/// <summary>
/// 产线叶标识
/// </summary>
public int T134LeafID { get; set; }
/// <summary>
/// 生产工单号
/// </summary>
public string PWONo { get; set; }
/// <summary>
/// 制造订单号
/// </summary>
public string MONumber { get; set; }
/// <summary>
/// 制造订单行号
/// </summary>
public int MOLineNo { get; set; }
/// <summary>
/// 产品编号
/// </summary>
public string ProductNo { get; set; }
/// <summary>
/// 订单数量
/// </summary>
public long OrderQty { get; set; }
/// <summary>
/// 排定生产时间
/// </summary>
public string ScheduledStartTime { get; set; }
/// <summary>
/// 在制品容器号
/// </summary>
public string ContainerNo { get; set; }
/// <summary>
/// 生产工单状态
/// </summary>
public int PWOStatus { get; set; }
public OpenProductionWorkOrder Clone()
{
OpenProductionWorkOrder rlt = MemberwiseClone() as OpenProductionWorkOrder;
return rlt;
}
}
} |
using Alabo.Domains.Repositories;
using Alabo.Industry.Offline.Merchants.Domain.Entities;
using MongoDB.Bson;
namespace Alabo.Industry.Offline.Merchants.Domain.Repositories
{
public interface IMerchantStoreRepository : IRepository<MerchantStore, ObjectId>
{
}
} |
using Newtonsoft.Json;
using System;
using Utilities;
namespace EddiDataDefinitions
{
/// <summary>
/// Presence of a material
/// </summary>
public class MaterialPresence
{
[PublicAPI, JsonProperty("material")]
public string name { get; private set; }
[PublicAPI]
public string category => definition?.category;
[PublicAPI]
public string rarity => definition?.Rarity.localizedName;
[PublicAPI]
public decimal percentage { get; private set; }
// Not intended to be user facing
[JsonIgnore]
public Material definition { get; private set; }
[JsonIgnore, Obsolete("We merged this with MaterialPercentage (which is now gone) but old scripts used different keys for the material's name so put them both here")]
public string material => name;
public MaterialPresence(Material definition, decimal percentage)
{
this.definition = definition;
this.name = definition?.localizedName;
this.percentage = percentage;
}
[JsonConstructor]
public MaterialPresence(string material, decimal percentage)
: this(Material.FromName(material), percentage)
{ }
}
}
|
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace ShopBridgeWeb.Helpers
{
public static class ApiHelper
{
public static async Task<HttpResponseMessage> CallApi(string URL, HttpMethod invokeType, ByteArrayContent body, string bodyId, byte[] file,string fileName)
{
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.BadRequest;
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(URL);
if (invokeType.Method == HttpMethod.Get.ToString())
{
var responseTask = client.GetAsync(URL);
responseTask.Wait();
response = responseTask.Result;
}
else if (invokeType.Method == HttpMethod.Post.ToString())
{
MultipartFormDataContent multiContent = new MultipartFormDataContent();
multiContent.Add(body, bodyId);
//byte[] imageData = null;
//if (formFile != null)
//{
// using (var br = new BinaryReader(formFile.OpenReadStream()))
// {
// imageData = br.ReadBytes((int)formFile.OpenReadStream().Length);
// ByteArrayContent bytes = new ByteArrayContent(imageData);
// multiContent.Add(bytes, "file", formFile.FileName);
// }
//}
if (file != null && file.Length > 0)
{
ByteArrayContent bytes = new ByteArrayContent(file);
multiContent.Add(bytes, "file", fileName);
}
//multiContent.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
var responseTask = client.PostAsync(URL, multiContent);
responseTask.Wait();
response = responseTask.Result;
}
else if (invokeType.Method == HttpMethod.Put.ToString())
{
MultipartFormDataContent multiContent = new MultipartFormDataContent();
//body.Headers.ContentType = new MediaTypeHeaderValue("application/json");
multiContent.Add(body, bodyId);
//byte[] imageData = null;
//if (formFile != null)
//{
// using (var br = new BinaryReader(formFile.OpenReadStream()))
// {
// imageData = br.ReadBytes((int)formFile.OpenReadStream().Length);
// ByteArrayContent bytes = new ByteArrayContent(imageData);
// multiContent.Add(bytes, "file", formFile.FileName);
// }
//}
if (file != null && file.Length > 0)
{
ByteArrayContent bytes = new ByteArrayContent(file);
multiContent.Add(bytes, "file", fileName);
}
//multiContent.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
var responseTask = client.PutAsync(URL, multiContent);
responseTask.Wait();
response = responseTask.Result;
}
else if (invokeType.Method == HttpMethod.Delete.ToString())
{
var responseTask = client.DeleteAsync(URL);
responseTask.Wait();
response = responseTask.Result;
}
response.StatusCode = response.StatusCode;
}
}
catch (Exception ex)
{
response.StatusCode = HttpStatusCode.InternalServerError;
//TODO: Need code to log error somewhere, for example in an error log file
}
return response;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Cinemachine;
public class lickingPussy : MonoBehaviour
{
[SerializeField] SkinnedMeshRenderer girl;
[SerializeField] Image progressBar;
[SerializeField] Image guideLines;
[SerializeField] Transform guidePositions;
[SerializeField] CinemachineVirtualCamera cameraTemp;
[SerializeField] Animator animator;
[SerializeField] AudioSource moaning;
[SerializeField] AudioClip[] moaningSounds;
CinemachinePOV povCamera;
bool activeButton = false;
float orgasm = 0f;
// Start is called before the first frame update
void Start()
{
povCamera = cameraTemp.GetCinemachineComponent<CinemachinePOV>();
animator.transform.position = new Vector3(-24.818f, 24.247f, -24.865f);
animator.transform.eulerAngles = new Vector3(0f, 90f, 0f);
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = true;
moaning.gameObject.SetActive(true);
moaning.clip = moaningSounds[0];
moaning.Play();
}
public void MouseDown(int buttonNumber)
{
activeButton = true;
guideLines.enabled = false;
povCamera.m_HorizontalAxis.m_MaxSpeed = 0;
povCamera.m_VerticalAxis.m_MaxSpeed = 0;
animator.CrossFadeInFixedTime("licking", 0.5f);
moaning.clip = moaningSounds[1];
moaning.Play();
}
public void MouseExit()
{
activeButton = false;
guideLines.enabled = true;
povCamera.m_HorizontalAxis.m_MaxSpeed = 50;
povCamera.m_VerticalAxis.m_MaxSpeed = 50;
animator.CrossFadeInFixedTime("lickyIdle", 0.5f);
moaning.clip = moaningSounds[0];
moaning.Play();
}
// Update is called once per frame
void Update()
{
if(activeButton)
{
orgasm += (Mathf.Abs(Input.GetAxis("Mouse X")) + Mathf.Abs(Input.GetAxis("Mouse Y")))/(1f/Time.deltaTime);
progressBar.fillAmount = orgasm / 100f;
girl.SetBlendShapeWeight(5, Mathf.Clamp((girl.GetBlendShapeWeight(5) + Input.GetAxis("Mouse X")*-1), 0f, 100f));
girl.SetBlendShapeWeight(7, Mathf.Clamp(girl.GetBlendShapeWeight(7) + Input.GetAxis("Mouse Y"), 0f, 100f));
if(orgasm >= 100)
{
activeButton = false;
guideLines.gameObject.SetActive(false);
guidePositions.gameObject.SetActive(false);
progressBar.transform.parent.parent.gameObject.SetActive(false);
povCamera.m_HorizontalAxis.m_MaxSpeed = 50;
povCamera.m_VerticalAxis.m_MaxSpeed = 50;
animator.CrossFadeInFixedTime("cumming", 1f);
moaning.clip = moaningSounds[2];
moaning.Play();
}
}
else
{
guideLines.transform.position = Camera.main.WorldToScreenPoint(guidePositions.position);
}
}
}
|
namespace ForumSystem.Web.Tests.Routes.APIs
{
using ForumSystem.Web.Controllers.APIs;
using MyTested.AspNetCore.Mvc;
using Xunit;
public class CategoriesApiControllerTests
{
[Theory]
[InlineData("/api/categories/search", null)]
[InlineData("/api/categories/search?term=123", "123")]
public void GetSearchContentShouldBeRoutedCorrectly(
string location,
string term)
=> MyRouting
.Configuration()
.ShouldMap(location)
.To<CategoriesApiController>(c => c.Search(term));
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Terraria;
using Terraria.ModLoader;
namespace StarlightRiver.Dimensions
{
/*public class DarkDimension : Subworld
{
public DarkDimension() : base() { }
}*/
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestGame1
{
class GameClass
{
public void input()
{
}
public void tick()
{
}
public void render()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrimeNumber.Model
{
public class BasePrimeCheckResult
{
public bool? IsPrime { get; set; } = false;
public long MinDivisionMaxValue { get; set; } = -1;
public long MinDivisionMinValue { get; set; } = -1;
}
}
|
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
namespace XH.APIs.WebAPI.Models.Shared
{
[DataContract]
public class CustomPropertyRequestModel
{
[DataMember]
[Required]
public string Name { get; set; }
[DataMember]
public string Value { get; set; }
}
} |
using Core.Infrastructure;
using Data;
using EasyCaching.Core;
using EasyCaching.InMemory;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.AspNetCore.Mvc.Versioning;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using MyBlog.WebApi.Framework.Filters;
using MyBlog.WebApi.Framework.GlobalErrorHandling.Extensions;
using MyBlog.WebApi.Framework.Infrastructure.Extensions;
using Serilog;
using Services.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace MyBlog.Web.Framework.Infrastructure
{
/// <summary>
/// Represents object for the configuring common features and middleware on application startup
/// </summary>
public class Startup : Core.Infrastructure.IStartup
{
public int Order => 1;
/// <summary>
/// Add and configure any of the middleware
/// </summary>
/// <param name="services">Collection of service descriptors</param>
/// <param name="typeFinder">Type Finder</param>
/// <param name="configuration">Configuration of the application</param>
public void ConfigureServices(IServiceCollection services, ITypeFinder typeFinder, IConfiguration configuration)
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
services.AddDbContextPool<ApplicationDbContext>(optionsBuilder =>
{
var dbContextOptionsBuilder = optionsBuilder.UseLazyLoadingProxies();
optionsBuilder.UseSqlServer(config.GetConnectionString("DefaultConnection"));
});
//add EF services
services.AddEntityFrameworkSqlServer();
services.AddEntityFrameworkProxies();
//Disable automatic 400 respone
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
//compression
services.AddResponseCompression();
//add Easy caching
services.AddEasyCaching(option =>
{
//use memory cache
option.UseInMemory("MyBlog_memory_cache");
});
//add distributed memory cache
services.AddDistributedMemoryCache();
services.ConfigureCors();
// services.ConfigureIISIntegration();
//add options feature
services.AddOptions();
var appSettingsSection = config.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);
// JWT authentication
var appSettings = appSettingsSection.Get<AppSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddApiVersioning(o => o.ApiVersionReader = new HeaderApiVersionReader("api-version"));
services.AddSwaggerGen((options) =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "My Blog Api",
Description = ".Net Developer Evaluation Project For Digiturk Company",
Contact = new OpenApiContact
{
Name = "Emre Oz",
Email = "emreoz3734@gmail.com",
Url = new Uri("https://github.com/emreoz37")
}
});
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = @"JWT Authorization header using the Bearer scheme. <br>
Enter 'Bearer' [space] and then your token in the text input below. <br>
Example: 'Bearer 12345abcdef'",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header,
},
new List<string>()
}
});
//TODO: Could dynamically find here.
var xmlFile = typeFinder.GetAssemblies().FirstOrDefault(x => x.GetName().Name == "MyBlog.WebApi");
if (xmlFile != null)
{
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile.GetName().Name + ".XML");
options.IncludeXmlComments(xmlPath);
}
});
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(config)
.CreateLogger();
var mvcBuilder = services.AddMvc(options =>
{
options.Filters.Add<ValidationFilter>();
})
.AddJsonOptions(options =>
{
options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
mvcBuilder.AddFluentValidation(cfg =>
{
//register all available validators from project assemblies
var assemblies = mvcBuilder.PartManager.ApplicationParts
.OfType<AssemblyPart>()
.Select(part => part.Assembly);
cfg.RegisterValidatorsFromAssemblies(assemblies);
});
}
/// Configure the using of added middleware
/// </summary>
/// <param name="application">Builder for configuring an application's request pipeline</param>
/// <param name="loggerFactory">Logger Factory</param>
public virtual void Configure(IApplicationBuilder application)
{
var env = StartupEngineContext.Current.Resolve<IHostingEnvironment>();
var loggerFactory = StartupEngineContext.Current.Resolve<ILoggerFactory>();
if (env.IsDevelopment())
{
application.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
application.UseHsts();
}
application.ConfigureCustomExceptionMiddleware();
application.UseResponseCompression();
application.UseStaticFiles();
//easy caching
application.UseEasyCaching();
application.UseCors("CorsPolicy");
application.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.All
});
application.UseAuthentication();
//Swagger
application.UseSwagger();
application.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My Blog Api v1");
});
loggerFactory.AddSerilog();
//app.UseHttpsRedirection();
application.UseMvc();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class move : MonoBehaviour
{
public float speed;
public 게임매니저 manager;
float h;
float v;
bool xMove;
//현재 바라보고있는 방향 값을 가진 변수 백터
Vector3 dirvec;
GameObject scan;
Rigidbody2D rigid;
Animator ani;
private void Awake()
{
scan = GetComponent<GameObject>();
rigid = GetComponent<Rigidbody2D>();
ani = GetComponent<Animator>();
}
void Update()
{
h = manager.isaction ? 0 : Input.GetAxisRaw("Horizontal");
v = manager.isaction ? 0 : Input.GetAxisRaw("Vertical");
bool hDown = manager.isaction ? false : Input.GetButtonDown("Horizontal");
bool vDown = manager.isaction ? false : Input.GetButtonDown("Vertical");
bool hUp = manager.isaction ? true : Input.GetButtonUp("Horizontal");
bool vUp = manager.isaction ? true : Input.GetButtonUp("Vertical");
//대각선 이동 차단
if (hDown)
xMove = true;
else if (vDown)
xMove = false;
else if (hUp || vUp)
xMove = h != 0;
//애니메이션
if (ani.GetInteger("가로이동") != h)
{
ani.SetBool("방향전환", true);
ani.SetInteger("가로이동", (int)h);
}
else if (ani.GetInteger("세로이동") != v)
{
ani.SetBool("방향전환", true);
ani.SetInteger("세로이동", (int)v);
}
else
ani.SetBool("방향전환", false);
//direction(방향)
if (vDown && v == 1)
dirvec = Vector3.up;
if (vDown && v == -1)
dirvec = Vector3.down;
if (hDown && h == 1)
dirvec = Vector3.right;
if (hDown && h == -1)
dirvec = Vector3.left;
//object scan
if (Input.GetButtonDown("Jump") && scan != null)
manager.Action(scan);
}
private void FixedUpdate()
{
//Move
Vector2 moveVec = xMove ? new Vector2(h, 0) : new Vector2(0, v);
rigid.velocity = moveVec * speed;
//Ray
Debug.DrawRay(rigid.position, dirvec * 0.7f, new Color(0, 1, 0));
RaycastHit2D rayhit = Physics2D.Raycast(rigid.position, dirvec, 0.7f, LayerMask.GetMask("object"));
if (rayhit.collider != null)
{
scan = rayhit.collider.gameObject;
}
else
scan = null;
}
}
|
using System;
namespace Training.Framework
{
public class AggregateNotFoundException : Exception
{
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
/*
* Sound controller, Tire Skid Sound
*/
public class TireSkidSoundController : MonoBehaviour {
private float move;
public AudioClip TireSkid;
AudioSource audioSource;
//----------------------------------------------------------
void Start ()
{
audioSource = GetComponent<AudioSource> ();
}
//----------------------------------------------------------
void Update ()
{
//CrossPlatformInputManager return values between -1 to 1 and 0 if no moving
move = CrossPlatformInputManager.GetAxis ("Move");
if (move != 0) {
audioSource.PlayOneShot (TireSkid, 1);
} else {
audioSource.Stop ();
}
}
//----------------------------------------------------------
}
|
namespace SoftUniStore.Client.Api.Common.Providers
{
using System.Collections.Generic;
using System.IO;
using Readers;
using SoftUniStore.Client.Api.Common.Constants;
public static class HtmlsProvider
{
public static readonly Dictionary<string, string> htmls = new Dictionary<string, string>();
public static void Initialize()
{
var allContentHtmls = Directory.GetFiles("../../content");
foreach (var htmlPath in allContentHtmls)
{
var htmlName = htmlPath.Substring(htmlPath.LastIndexOf(@"\") + 1);
htmls.Add(htmlName, HtmlReader.ReadHtml(htmlPath));
}
}
}
} |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SolrDotNet.Models
{
public class ResponseBody<TModel>
{
[JsonProperty("numFound")]
public long NumFound { get; set; }
[JsonProperty("start")]
public long Start { get; set; }
[JsonProperty("docs")]
public List<TModel> Docs { get; set; }
public ResponseBody()
{
Docs = new List<TModel>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace FiiiChain.DTO.Transaction
{
public class TransactionOM
{
public long Id { get; set; }
public string Hash { get; set; }
public string BlockHash { get; set; }
public int Version { get; set; }
public long Timestamp { get; set; }
public long LockTime { get; set; }
public long TotalInput { get; set; }
public long TotalOutput { get; set; }
public int Size { get; set; }
public long Fee { get; set; }
public long ExpiredTime { get; set; }
public bool IsDiscarded { get; set; }
public List<InputsOM> Inputs { get; set; }
public List<OutputsOM> Outputs { get; set; }
public long Confirmations { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace Condor.Tests.Learn.LocalStorage
{
[TestFixture]
[Explicit]
internal class UsingIsolatedStorage
{
[Test]
public void Use_isolated_storage()
{
IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
object stop = null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Net;
/// <summary>
/// Descripción breve de Email
/// </summary>
public class Email
{
private String nombrePerfil; //--variable que recupera el nombre del perfil que se mostrara en el nombre del correo
private String correoPerfil; //--variable que recupera el correo que se utilizara para mandar el correo
private String hostPerfil; //--variable que recupera el servidor de correo saliente
private String puertoPerfil; //--variable que recupera el numero de puerto por el cual sale el correo
private String passPerfil; //--variable que recupera el password del correo
private bool sslPerfil; //--variable que recupera si aplica conexion ssl
private bool credencialesPrefil; //--variable que recupera el nombre del perfil que se mostrara en el nombre del correo
MailMessage _Correo;
Conexion con;
List<String> listaRegistros;
SmtpClient _Smtp;
/// <summary>
/// Contructor
/// </summary>
public Email(bool html,MailPriority prioridad,String subject){
//instancia a objeto Correo
_Correo = new MailMessage();
_Correo.IsBodyHtml = html;
_Correo.Priority = prioridad;
_Correo.Subject = subject;
recuperaInfoCorreo();
}
///metodo para ingresar lista destinos de correos
public void _AddTo(String destinos)
{
///se recupera lista de correos en arreglo
string[] correos = destinos.Split(';');
//--si es mayor se recorreo el arreglo
if (correos.Length > 0)
{
///se recorre lista de correos para agregar el correo
for (int i = 0; i < correos.Length; i++)
{
_Correo.To.Add(new MailAddress(correos[i].ToString()));
}
}
}
//metodo para ingresar destinos en copia
public void _AddCC(String destinos)
{
///se recupera lista de correos en arreglo
string[] correos = destinos.Split(';');
//--si es mayor se recorreo el arreglo
if (correos.Length > 0)
{
///se recorre lista de correos para agregar el correo
for (int i = 0; i < correos.Length; i++)
{
_Correo.CC.Add(new MailAddress(correos[i].ToString()));
}
}
}
//metodo para ingresar destinos con Copia Oculta
public void _AddBCC(String destinos)
{
///se recupera lista de correos en arreglo
string[] correos = destinos.Split(';');
//--si es mayor se recorreo el arreglo
if (correos.Length > 0)
{
///se recorre lista de correos para agregar el correo
for (int i = 0; i < correos.Length; i++)
{
_Correo.Bcc.Add(new MailAddress(correos[i].ToString()));
}
}
}
//Metodo para ingresar el cuerpo del correo
public void _AddBody(String cuerpoCorreo)
{
_Correo.Body = cuerpoCorreo;
}
//Metodo agregar adjunto
public void _AddAttachment(String adjunto)
{
Attachment att = new Attachment(adjunto);
_Correo.Attachments.Add(att);
}
//MEtodo para hacer el envio del correo
public string sendMail() {
try{
_Smtp.Send(_Correo);
_Correo.Dispose();
return "1";
}
catch (Exception ex)
{
return "Error enviando correo electrónico: " + ex.Message;
}
}
/// <summary>
/// recupera informacion del correo
/// </summary>
private void recuperaInfoCorreo()
{
con = new Conexion();
string query = "select top 1sNombrePerfil,sCorreo,sHost,sPuerto,iSSL,iCredenciales,sPass from ct_PerfilesCorreos where iEstado=1";
listaRegistros = con.ejecutarConsultaRegistroMultiples(query);
Security secCorreo, secHost, secPuerto, secPass;
if (listaRegistros.Count > 1)
{
#region contenido
for (int i = 1; i < listaRegistros.Count; i++)
{
if (i == 1)
{
nombrePerfil = listaRegistros[i].ToString();
}
else if (i == 2)
{
secCorreo = new Security(listaRegistros[i]);
correoPerfil = secCorreo.DesEncriptar();
}
else if (i == 3)
{
secHost = new Security(listaRegistros[i]);
hostPerfil = secHost.DesEncriptar();
}
else if (i == 4)
{
secPuerto = new Security(listaRegistros[i]);
puertoPerfil = secPuerto.DesEncriptar();
}
else if (i == 5)
{
sslPerfil = bool.Parse(listaRegistros[i]);
}
else if (i == 6)
{
credencialesPrefil = bool.Parse(listaRegistros[i]);
}
else if (i == 7)
{
secPass = new Security(listaRegistros[i]);
passPerfil = secPass.DesEncriptar();
}
}
#endregion
_Correo.From = new MailAddress(correoPerfil, nombrePerfil);
_Smtp = new SmtpClient();
_Smtp.Host = hostPerfil;
_Smtp.Port = int.Parse(puertoPerfil);
_Smtp.EnableSsl = sslPerfil;
_Smtp.UseDefaultCredentials = credencialesPrefil;
_Smtp.Credentials = new NetworkCredential(correoPerfil, passPerfil);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Matrix
{
class Tree<T>
{
delegate int CompType(T a, T b);
private Node<T> Noeud;
CompType C;
delegate void MapFunction(ref T elt);
MapFunction MF;
public Tree(CompType comp, T value)
{
Node<T> Noeud = new Node<T>(value);
C = comp;
}
public void depth_first_traversal(MapFunction function)
{
if (Noeud.fg != null)
Noeud.fg.depth_first_traversal(function);
function(ref Noeud.val);
if (Noeud.fd != null)
Noeud.fd.depth_first_traversal(function);
}
public void breadth_first_traversal(MapFunction function)
{
Queue<Node<T>> file = new Queue<Node<T>>();
file.Enqueue(Noeud);
while (file.Count != 0)
{
Node<T> n = file.Dequeue();
function(ref n.val);
if (n.fg != null)
file.Enqueue(n.fg.Noeud);
if (n.fd != null)
file.Enqueue(n.fd.Noeud);
}
}
private delegate bool BinFunc(ref Node<T> node, T val);
private bool binary_traversal(ref Node<T> node, T val, BinFunc null_case, BinFunc equal_case)
{
if (C(node.val, val) == 0)
return equal_case(ref Noeud, Noeud.val);
if (node.fg != null || node.fd != null)
{
if (C(node.val, val) < 0)
{
if (node.fg != null)
return binary_traversal(ref node.fg.Noeud, val, null_case, equal_case);
}
else
if (node.fd != null)
return binary_traversal(ref node.fd.Noeud, val, null_case, equal_case);
}
return null_case(ref Noeud, val);
}
public bool find(T val)
{
BinFunc NC = delegate(ref Node<T> n, T v)
{
return false;
};
BinFunc EC = (ref Node<T> n, T v) =>
{
return true;
};
return binary_traversal(ref Noeud, val, NC, EC);
}
public bool insert(T val)
{
BinFunc NC = delegate(ref Node<T> n, T v)
{
n = new Node<T>(v);
return true;
};
BinFunc EC = (ref Node<T> n, T v) =>
{
return false;
};
return binary_traversal(ref Noeud, val, NC, EC);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace GeoSearch.Web
{
public class ResourceType
{
public string Name { get; set; }
public ObservableCollection<ResourceType> Children { get; set; }
public ResourceType Parent { get; set; }
public string ResourceTypeID { get; set; }
public bool isSelected { get; set; }
}
}
|
using Puppeteer.Core.Action;
using Puppeteer.Core.WorldState;
using System.Collections.Generic;
using System.Linq;
namespace Puppeteer.Core.Planning
{
public class PlannerNode<TKey, TValue> : IAStarNode
{
public PlannerNode()
{
}
public void Init(IAction<TKey, TValue> _action)
{
m_Action = _action;
}
public void Reset()
{
m_Action = null;
Priority = 0;
Queue = null;
QueueIndex = 0;
m_PathCost = 0.0f;
m_HeuristicCost = 0.0f;
m_Parent = null;
m_WorldStateAtNode = null;
m_GoalWorldStateAtNode = null;
}
public float Priority { get; set; }
public object Queue { get; set; }
public int QueueIndex { get; set; }
public IAction<TKey, TValue> Action { get => m_Action; set => m_Action = value; }
public float GetCost()
{
return m_PathCost + m_HeuristicCost;
}
public float GetPathCost()
{
return m_PathCost;
}
public float GetHeuristicCost()
{
return m_HeuristicCost;
}
public void CalculateCosts()
{
m_HeuristicCost = (m_Action != null)? 1 / m_Action.GetUtility() : float.MaxValue;
if(m_Parent != null)
{
m_PathCost += m_Parent.GetCost();
}
}
public IAStarNode GetParent()
{
return m_Parent;
}
internal Goal<TKey, TValue> GetGoalWorldStateAtNode()
{
return m_GoalWorldStateAtNode;
}
public void SetParent(IAStarNode _parentNode)
{
m_Parent = _parentNode;
}
internal void CalculateWorldStateAtNode(WorldState<TKey, TValue> _baseWorldState)
{
m_WorldStateAtNode = WorldState<TKey, TValue>.Copy(_baseWorldState);
if (m_Action != null)
{
m_WorldStateAtNode.Apply(m_Action.GetEffects());
}
}
internal void CalculateGoalWorldStateAtNode(Goal<TKey, TValue> _baseGoalWorldState)
{
m_GoalWorldStateAtNode = Goal<TKey,TValue>.Copy(_baseGoalWorldState);
if (m_Action != null)
{
m_GoalWorldStateAtNode.Apply(m_Action.GetPreconditions());
}
}
internal WorldState<TKey, TValue> GetWorldStateAtNode()
{
return m_WorldStateAtNode;
}
public bool Equals(IAStarNode _other)
{
if (_other is PlannerNode<TKey, TValue> sameType)
{
if (!m_WorldStateAtNode.Equals(sameType.m_WorldStateAtNode))
{
return false;
}
if (m_GoalWorldStateAtNode != null)
{
if (sameType.m_GoalWorldStateAtNode == null)
{
return false;
}
if (!m_GoalWorldStateAtNode.Equals(sameType.m_GoalWorldStateAtNode))
{
return false;
}
}else if (sameType.m_GoalWorldStateAtNode != null)
{
return false;
}
if(sameType.m_Action != m_Action)
{
return false;
}
return true;
}
return false;
}
public override string ToString()
{
return string.Format("Action: {0}, WorldStateAtNode: {1}, GoalWorldStateAtNode: {2}, PathCost: {3}",
m_Action != null ? m_Action.GetLabel() : "{}",
m_WorldStateAtNode != null ? m_WorldStateAtNode.ToString() : "{}",
m_GoalWorldStateAtNode != null ? m_GoalWorldStateAtNode.ToString() : "{}",
m_PathCost);
}
public bool ReachesEnd(IAStarNode _end)
{
return m_WorldStateAtNode.ContainsAll(m_GoalWorldStateAtNode);
}
public override int GetHashCode()
{
int hashCode = 2126105136;
hashCode = hashCode * -1521134295 + EqualityComparer<WorldState<TKey, TValue>>.Default.GetHashCode(m_WorldStateAtNode);
hashCode = hashCode * -1521134295 + EqualityComparer<WorldState<TKey, TValue>>.Default.GetHashCode(m_GoalWorldStateAtNode);
hashCode = hashCode * -1521134295 + EqualityComparer<IAction<TKey, TValue>>.Default.GetHashCode(m_Action);
return hashCode;
}
private WorldState<TKey, TValue> m_WorldStateAtNode = null;
private Goal<TKey, TValue> m_GoalWorldStateAtNode = null;
private IAction<TKey, TValue> m_Action = null;
private IAStarNode m_Parent = null;
private float m_PathCost = 0.0f;
private float m_HeuristicCost = 0.0f;
}
} |
using Meteooor.Models;
using Meteooor.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
namespace Meteooor.Controllers
{
public class MarkerController : ApiController
{
public HttpResponseMessage GetMarkers()
{
List<Marker> markers = Markers.GetMarkers().ToList();
string header = "Title,Latitude,Longitude,Diameter,Price,Source,EventID,Version\r\n";
StringBuilder sb = new StringBuilder();
foreach(var marker in markers)
{
sb.AppendFormat("{0},{1},{2},{3},{4},{5},{6},{7}\r\n",
"Marker", marker.Latitude.ToString().Replace(",", "."),
marker.Longitude.ToString().Replace(",", "."), marker.Diameter.Replace(",", "."),
marker.Price
,"1234", "1235", "123456");
}
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent(header + sb.ToString(), Encoding.UTF8, "text/plain");
return resp;
}
}
}
|
using Android.OS;
using Android.Views;
using RayTest.Droid.Adapters;
using System.Linq;
namespace RayTest.Droid.Fragments
{
public class VeggieLoversFragment : BaseFragment
{
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
}
public override void OnActivityCreated(Bundle savedInstanceState)
{
base.OnActivityCreated(savedInstanceState);
base.InitComponents();
base.BindEvents();
HotDogs = base.ActivityHelper.FetchHotDogs().Take(1).ToList();
this.ListView.Adapter = new HotDogListAdapter(this.Activity, this.HotDogs);
this.ListView.FastScrollEnabled = true;
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.Inflate(Resource.Layout.FavoriteHotDogFragment, container, false);
}
}
} |
using System;
using System.Collections.Generic;
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.Shapes;
using ViewModelLib.PropertyViewModels;
namespace ViewLib
{
/// <summary>
/// Logique d'interaction pour EditWindow.xaml
/// </summary>
public partial class EditWindow : Window
{
public static readonly DependencyProperty PropertyViewModelCollectionProperty = DependencyProperty.Register("PropertyViewModelCollection", typeof(IPropertyViewModelCollection), typeof(EditWindow));
public IPropertyViewModelCollection PropertyViewModelCollection
{
get { return (IPropertyViewModelCollection)GetValue(PropertyViewModelCollectionProperty); }
set { SetValue(PropertyViewModelCollectionProperty, value); }
}
public EditWindow()
{
InitializeComponent();
}
private void OKCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = PropertyViewModelCollection?.CanWriteComponents()??false; e.Handled = true;
}
private void OKCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
DialogResult = true;
}
private void CancelCommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;e.Handled = true;
}
private void CancelCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
DialogResult = false;
}
}
}
|
using System;
namespace Demo
{
public static class SystemClock
{
private static Func<DateTime> _now = () => DateTime.UtcNow;
public static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static DateTime UtcNow => _now();
public static IDisposable Freeze()
{
var date = DateTime.UtcNow;
_now = () => date;
return new DisposableAction(Resume);
}
internal static void Resume()
{
_now = () => DateTime.UtcNow;
}
public static IDisposable Set(DateTime date)
{
_now = () => date;
return new DisposableAction(Resume);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusinessLogic
{
public class Class1
{
// Comentarios de Clase
//comentario2
//dasd
}
}
|
using EPI.HashTables;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace EPI.UnitTests.HashTables
{
[TestClass]
public class LineWithMaximumPointsUnitTest
{
[TestMethod]
public void FindLineWithMaxPoints()
{
var line = LineWithMaximumPoints.FindLineWithMostPoints(new[]
{
new LineWithMaximumPoints.Point(0,0),
new LineWithMaximumPoints.Point(1,0),
new LineWithMaximumPoints.Point(0,1),
new LineWithMaximumPoints.Point(1,1),
new LineWithMaximumPoints.Point(2,2),
new LineWithMaximumPoints.Point(2,0),
new LineWithMaximumPoints.Point(3,3)
});
line.Should().Be(new LineWithMaximumPoints.Line(new LineWithMaximumPoints.Point(2, 2), new LineWithMaximumPoints.Point(1,1)));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Threading;
using Szogun1987.EventsAndTasks.Callbacks;
using Szogun1987.EventsAndTasks.Callbacks.NeverCalledback;
using Xunit;
namespace Szogun1987.EventsAndTasks.Tests
{
public class NeverCalledBackTests
{
[Theory]
[MemberData(nameof(TestDataSets))]
public void OperationIsCompleted_EvenIf_GarbageCollector_IsTriggered(
string name,
Func<Func<CallbacksApi>, ITaskAdapter> taskAdapterFactory)
{
// Given
var apiReference = new WeakReference<CallbacksApi>(new CallbacksApi());
var adapter = taskAdapterFactory(() =>
{
CallbacksApi api;
apiReference.TryGetTarget(out api);
return api;
});
// When
var task = adapter.GetNextInt();
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);
CallbacksApi apiFromReference;
if (apiReference.TryGetTarget(out apiFromReference))
{
apiFromReference.Complete(1);
}
else
{
Assert.True(false, $"API for {name} adapter evaporated");
}
// Then
Assert.True(task.IsCompleted);
// This line should prevent worked around adapter failure but it doesn't
Assert.NotNull(adapter);
// Ensure that API is collected when task is completed and it result is no longer used
apiFromReference = null;
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);
Assert.False(apiReference.TryGetTarget(out apiFromReference));
}
public static IEnumerable<object[]> TestDataSets
{
get
{
yield return new object[] { "Broken", new Func<Func<CallbacksApi>, ITaskAdapter>(CreateBroken)};
yield return new object[] { "Worked around", new Func<Func<CallbacksApi>, ITaskAdapter>(CreateWorkedAround) };
yield return new object[] { "Fixed", new Func<Func<CallbacksApi>, ITaskAdapter>(CreateFixed) };
}
}
private static BrokenTaskAdapter CreateBroken(Func<CallbacksApi> callbacksApiFactory)
{
return new BrokenTaskAdapter(callbacksApiFactory);
}
private static WorkedAroundAdapter CreateWorkedAround(Func<CallbacksApi> callbacksApiFactory)
{
return new WorkedAroundAdapter(callbacksApiFactory);
}
private static FixedTaskAdapter CreateFixed(Func<CallbacksApi> callbacksApiFactory)
{
return new FixedTaskAdapter(callbacksApiFactory);
}
}
} |
using System;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
namespace BuildingGame
{
class Cell
{
int x;
int y;
Sprite sprite;
Building building;
Tree tree;
public Cell(int x, int y)
{
this.x = x;
this.y = y;
}
public void Draw(SpriteBatch spriteBatch, Map map)
{
sprite.Draw(spriteBatch, map.CalcWorldToScreen(new Vector2(x,y)));
if (tree != null)
tree.Draw(spriteBatch, map);
if (building != null)
building.Draw(spriteBatch, map);
//spriteBatch.DrawString(Fonts.Standard, X + "," + Y, map.CalcWorldToScreen(new Vector2(x,y)) - new Vector2(10,20), Color.White); // Debug
}
public Vector2 Position
{
get
{
return new Vector2(x, y);
}
}
public Sprite Sprite {
get
{
return sprite;
}
set
{
sprite = value;
}
}
public Building Building
{
get
{
return building;
}
set
{
building = value;
}
}
public Tree Tree
{
get
{
return tree;
}
set
{
tree = value;
}
}
public int X
{
get
{
return x;
}
}
public int Y
{
get
{
return y;
}
}
}
} |
// Copyright (c) 2018 FiiiLab Technology Ltd
// Distributed under the MIT software license, see the accompanying
// file LICENSE or or http://www.opensource.org/licenses/mit-license.php.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace FiiiCoin.Wallet.Win.CustomControls
{
public class PathButton : Button
{
public PathButton()
{
var resourceLoactor = new Uri("pack://application:,,,/FiiiCoin.Wallet.Win;component/CustomControls/PathButton/PathButton.xaml");
ResourceDictionary resource = new ResourceDictionary();
resource.Source = resourceLoactor;
if (!Application.Current.Resources.MergedDictionaries.Any(x => x.Source == resourceLoactor))
Application.Current.Resources.MergedDictionaries.Add(resource);
}
public Geometry PathData
{
get { return (Geometry)GetValue(PathDataProperty); }
set { SetValue(PathDataProperty, value); }
}
public static readonly DependencyProperty PathDataProperty =
DependencyProperty.Register("PathData", typeof(Geometry), typeof(PathButton), new PropertyMetadata(new PathGeometry()));
public Brush DefaultFillBrush
{
get { return (Brush)GetValue(DefaultFillBrushProperty); }
set { SetValue(DefaultFillBrushProperty, value); }
}
public static readonly DependencyProperty DefaultFillBrushProperty =
DependencyProperty.Register("DefaultFillBrush", typeof(Brush), typeof(PathButton), new PropertyMetadata(Brushes.DarkGray));
public Brush MouseOverBrush
{
get { return (Brush)GetValue(MouseOverBrushProperty); }
set { SetValue(MouseOverBrushProperty, value); }
}
public static readonly DependencyProperty MouseOverBrushProperty =
DependencyProperty.Register("MouseOverBrush", typeof(Brush), typeof(PathButton), new PropertyMetadata(Brushes.DeepSkyBlue));
public Brush IsPressedBrush
{
get { return (Brush)GetValue(IsPressedBrushProperty); }
set { SetValue(IsPressedBrushProperty, value); }
}
public static readonly DependencyProperty IsPressedBrushProperty =
DependencyProperty.Register("IsPressedBrush", typeof(Brush), typeof(PathButton), new PropertyMetadata(Brushes.DodgerBlue));
public Brush IsEnabledBrush
{
get { return (Brush)GetValue(IsEnabledBrushProperty); }
set { SetValue(IsEnabledBrushProperty, value); }
}
public static readonly DependencyProperty IsEnabledBrushProperty =
DependencyProperty.Register("IsEnabledBrush", typeof(Brush), typeof(PathButton), new PropertyMetadata(Brushes.LightGray));
public double ImageWidth
{
get { return (double)GetValue(ImageWidthProperty); }
set { SetValue(ImageWidthProperty, value); }
}
public static readonly DependencyProperty ImageWidthProperty =
DependencyProperty.Register("ImageWidth", typeof(double), typeof(PathButton), new PropertyMetadata(16d));
public double ImageHeight
{
get { return (double)GetValue(ImageHeightProperty); }
set { SetValue(ImageHeightProperty, value); }
}
public static readonly DependencyProperty ImageHeightProperty =
DependencyProperty.Register("ImageHeight", typeof(double), typeof(PathButton), new PropertyMetadata(16d));
}
}
|
using System;
using Microsoft.Quantum.Simulation.Core;
using Microsoft.Quantum.Simulation.Simulators;
namespace Test2
{
class Driver
{
static void Main(string[] args)
{
using (var sim = new QuantumSimulator(throwOnReleasingQubitsNotInZeroState: false))
{
string[] array = {"Constant 0", "Constant 1", "Identity", "Negation"};
for (int i = 0; i < 4; i++) {
var blackBox = array[i];
var res = Add.Run(sim, blackBox).Result;
Console.WriteLine($"{blackBox}: {res}");
}
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
namespace LAB2
{
public class DataTableProducts
{
static DataTable dataTableProducts;
public static void AddColumns()
{
dataTableProducts = new DataTable();
dataTableProducts.Columns.Add("Code", typeof(string));
dataTableProducts.Columns.Add("Name", typeof(string));
dataTableProducts.Columns.Add("Price", typeof(string));
dataTableProducts.Columns.Add("Date", typeof(string));
dataTableProducts.Columns.Add("Category", typeof(string));
}
public static DataTable AddRows()
{
AddColumns();
DataRow dataRow1;
dataRow1 = dataTableProducts.NewRow();
dataRow1["Code"] = "SEM42015";
dataRow1["Name"] = "Experia M4 Aqua";
dataRow1["Price"] = "6,490,000";
dataRow1["Date"] = "01/06/2015";
dataRow1["Category"] = "Sony";
dataTableProducts.Rows.Add(dataRow1);
DataRow dataRow7;
dataRow7 = dataTableProducts.NewRow();
dataRow7["Code"] = "SSM42015";
dataRow7["Name"] = "Experia M4 Aqua";
dataRow7["Price"] = "7,490,000";
dataRow7["Date"] = "02/06/2015";
dataRow7["Category"] = "Sony";
dataTableProducts.Rows.Add(dataRow7);
DataRow dataRow2;
dataRow2 = dataTableProducts.NewRow();
dataRow2["Code"] = "SGS62015";
dataRow2["Name"] = "SamSung Galaxy S6";
dataRow2["Price"] = "16,590,000";
dataRow2["Date"] = "01/06/2015";
dataRow2["Category"] = "SamSung";
dataTableProducts.Rows.Add(dataRow2);
DataRow dataRow3;
dataRow3 = dataTableProducts.NewRow();
dataRow3["Code"] = "IP6P64";
dataRow3["Name"] = "IPhone 6 Plus 64GB";
dataRow3["Price"] = "22,190,000";
dataRow3["Date"] = "15/04/2015";
dataRow3["Category"] = "Mobile";
dataTableProducts.Rows.Add(dataRow3);
DataRow dataRow4;
dataRow4 = dataTableProducts.NewRow();
dataRow4["Code"] = "IP6P16";
dataRow4["Name"] = "IPhone 6 Plus 16GB";
dataRow4["Price"] = "19,590,000";
dataRow4["Date"] = "15/04/2015";
dataRow4["Category"] = "Mobile";
dataTableProducts.Rows.Add(dataRow4);
DataRow dataRow5;
dataRow5 = dataTableProducts.NewRow();
dataRow5["Code"] = "32LB552A";
dataRow5["Name"] = "LED LG 32inch HD";
dataRow5["Price"] = "4,590,000";
dataRow5["Date"] = "15/06/2015";
dataRow5["Category"] = "TV";
dataTableProducts.Rows.Add(dataRow5);
DataRow dataRow6;
dataRow6 = dataTableProducts.NewRow();
dataRow6["Code"] = "KDL48R550C";
dataRow6["Name"] = "LED Sony 48inch HD";
dataRow6["Price"] = "14,699,000";
dataRow6["Date"] = "01/06/2015";
dataRow6["Category"] = "TV";
dataTableProducts.Rows.Add(dataRow6);
return dataTableProducts;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using TrashCollector2.Models;
namespace TrashCollector2.Controllers
{
public class CustomersController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: Customers
public ActionResult Index()
{
return View(db.Customers.ToList());
}
public ActionResult CustomerHome()
{
var userId = User.Identity.GetUserId();
var customer = (from c in db.Customers where c.UserId == userId select c).FirstOrDefault();
return View(customer);
}
public ActionResult MoneyOwed()
{
var userId = User.Identity.GetUserId();
var customer = (from c in db.Customers where c.UserId == userId select c).FirstOrDefault();
return View(customer);
}
// GET: Customers/Details/5
public ActionResult Details(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return HttpNotFound();
}
return View(customer);
}
// GET: Customers/Create
public ActionResult Create()
{
return View();
}
// POST: Customers/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,EmailAddress,UserName,Password,FullName,StreetAddress,ZipCode,WeeklyPickupDay")] Customer customer)
{
if (ModelState.IsValid)
{
customer.MoneyOwed = 0;
customer.IsOnHold = false;
customer.UserId = User.Identity.GetUserId();
db.Customers.Add(customer);
db.SaveChanges();
return RedirectToAction("CustomerHome");
}
return View(customer);
}
// GET: Customers/Edit/5
public ActionResult Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return HttpNotFound();
}
return View(customer);
}
// POST: Customers/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,StreetAddress,ZipCode,WeeklyPickupDay")] Customer customer, string id)
{
if (ModelState.IsValid)
{
Customer updatedCustomer = db.Customers.Find(id);
if (updatedCustomer == null)
{
return RedirectToAction("DisplayError", "Employees");
}
updatedCustomer.StreetAddress = customer.StreetAddress;
updatedCustomer.ZipCode = customer.ZipCode;
updatedCustomer.WeeklyPickupDay = customer.WeeklyPickupDay;
db.Entry(updatedCustomer).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("CustomerHome");
}
return View(customer);
}
// GET: Customers/Delete/5
public ActionResult Delete(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return HttpNotFound();
}
return View(customer);
}
// POST: Customers/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(string id)
{
Customer customer = db.Customers.Find(id);
customer.FullName = "Deleted";
db.Entry(customer).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("LogOff", "Account");
}
public ActionResult DelayPickupsForTime()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DelayPickupsForTime([Bind(Include = "StartOfDelayedPickup, EndOfDelayedPickup")] Customer customer)
{
var userId = User.Identity.GetUserId();
var today = DateTime.Now.Date;
var currentCustomer = (from c in db.Customers where userId == c.UserId select c).FirstOrDefault();
if (currentCustomer != null)
{
currentCustomer.StartOfDelayedPickup = customer.StartOfDelayedPickup;
currentCustomer.EndOfDelayedPickup = customer.EndOfDelayedPickup;
if (today >= currentCustomer.StartOfDelayedPickup &&
today <= currentCustomer.EndOfDelayedPickup)
{
currentCustomer.IsOnHold = true;
}
else
{
currentCustomer.IsOnHold = false;
}
db.Entry(currentCustomer).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("CustomerHome");
}
public ActionResult TakePickupsOffHold()
{
var userId = User.Identity.GetUserId();
Customer currentCustomer = (from c in db.Customers where userId == c.UserId select c).First();
currentCustomer.IsOnHold = false;
currentCustomer.StartOfDelayedPickup = null;
currentCustomer.EndOfDelayedPickup = null;
db.Entry(currentCustomer).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("CustomerHome");
}
public ActionResult ChooseNewOneTimePickup()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ChooseNewOneTimePickup([Bind(Include = "OneTimePickupDate")] Customer customer)
{
var userId = User.Identity.GetUserId();
var identityToInt = userId;
var currentCustomer = (from c in db.Customers where userId == c.UserId select c).First();
currentCustomer.OneTimePickupDate = customer.OneTimePickupDate;
db.Entry(currentCustomer).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("CustomerHome");
}
public ActionResult PayForPickups()
{
var userId = User.Identity.GetUserId();
Customer currentCustomer = (from c in db.Customers where userId == c.UserId select c).First();
return View(currentCustomer);
}
public ActionResult PayForPickupsConfirmed(string id)
{
Customer currentCustomer = (from c in db.Customers where c.UserId == id select c).First();
currentCustomer.IsConfirmed = false;
currentCustomer.MoneyOwed = 0;
db.Entry(currentCustomer).State = EntityState.Modified;
db.SaveChanges();
return View(currentCustomer);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
using Microsoft.Reporting.WebForms;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
namespace Report.Site
{
public partial class RelatoriosChannelMonitor : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
populaDropDow();
showReport();
}
}
protected void btnBuscar_Click(object sender, EventArgs e)
{
if (string.Compare(ddlSite.Text, "-1", true) == 0)
{
string msg = "*** SELECIONE O SITE ***";
ClientScript.RegisterStartupScript(typeof(string), string.Empty,
string.Format("window.alert(\"{0}\");", msg), true);
}
else
showReport();
}
public void populaDropDow()
{
ddlSite.DataSource = getDados("sp_GetSites", null);
ddlSite.DataBind();
ListItem listaSite = new ListItem("--Selecione o Site--", "-1");
ddlSite.Items.Insert(0, listaSite);
ListItem listaPlataforma = new ListItem("--Selecione a Plataforma--", "-1");
ddlPlataforma.Items.Insert(0, listaPlataforma);
ListItem listaGravador = new ListItem("--Selecione o Gravador--", "-1");
ddlGravador.Items.Insert(0, listaGravador);
ddlPlataforma.Enabled = false;
ddlGravador.Enabled = false;
}
public DataSet getDados(String sp_name, SqlParameter sp_parameter)
{
DataSet ds = new DataSet();
string connStr = ConfigurationManager.ConnectionStrings["ModelCHM"].ConnectionString;
using (SqlConnection cn = new SqlConnection(connStr))
{
SqlDataAdapter adp = new SqlDataAdapter(sp_name, cn);
adp.SelectCommand.CommandType = CommandType.StoredProcedure;
if (sp_parameter != null)
{
adp.SelectCommand.Parameters.Add(sp_parameter);
}
adp.Fill(ds);
}
return ds;
}
private void showReport()
{
rptChannelMonitor.Reset();
DataTable dt = getData(dwlStatus.Text, ddlSite.Text, ddlPlataforma.Text, ddlGravador.Text);
ReportDataSource rds = new ReportDataSource("ChannelMonitorDataSet", dt);
rptChannelMonitor.LocalReport.DataSources.Add(rds);
rptChannelMonitor.LocalReport.ReportPath = "Reports/ReportChannelMonitor.rdlc";
rptChannelMonitor.LocalReport.Refresh();
}
private DataTable getData(string status, string site, string plataforma, string gravador)
{
DataTable dt = new DataTable();
string connStr = ConfigurationManager.ConnectionStrings["ModelCHM"].ConnectionString;
using (SqlConnection cn = new SqlConnection(connStr))
{
SqlCommand cmd = new SqlCommand("sp_ociosidade", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@status", SqlDbType.VarChar).Value = status;
cmd.Parameters.Add("@site", SqlDbType.VarChar).Value = site;
cmd.Parameters.Add("@plataforma", SqlDbType.VarChar).Value = plataforma;
cmd.Parameters.Add("@gravador", SqlDbType.VarChar).Value = gravador;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
}
return dt;
}
protected void ddlSite_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlSite.SelectedValue == "-1")
{
ddlPlataforma.SelectedIndex = 0;
ddlPlataforma.Enabled = false;
ddlGravador.SelectedIndex = 0;
ddlGravador.Enabled = false;
}
else
{
ddlPlataforma.Enabled = true;
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "@id_site";
parameter.Value = ddlSite.SelectedValue;
ddlPlataforma.DataSource = getDados("sp_GetPlataforma", parameter);
ddlPlataforma.DataBind();
ListItem listaPlataforma = new ListItem("--Selecione a Plataforma--", "-1");
ddlPlataforma.Items.Insert(0, listaPlataforma);
ddlGravador.SelectedIndex = 0;
ddlGravador.Enabled = false;
ddlGravador.Enabled = false;
}
}
protected void ddlPlataforma_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlPlataforma.SelectedValue == "-1")
{
ddlGravador.SelectedIndex = 0;
ddlGravador.Enabled = false;
}
else
{
ddlGravador.Enabled = true;
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "@id_plataforma";
parameter.Value = ddlPlataforma.SelectedValue;
ddlGravador.DataSource = getDados("sp_GetGravador", parameter);
ddlGravador.DataBind();
ListItem listaGravador = new ListItem("--Selecione o Gravador--", "-1");
ddlGravador.Items.Insert(0, listaGravador);
}
}
}
} |
using Codility.PerfectChannel;
using NUnit.Framework;
namespace Codility.Tests.PerfectChannel
{
public class StackStateMachineShould
{
[TestCase("13+62*7+*", ExpectedResult = 76)] //test normal
[TestCase("13++62*7+*", ExpectedResult = -1)] //test double operand
[TestCase("99*9*9*9*9*9*9*9", ExpectedResult = -1)] //test uint12 overflow
[TestCase("88*8*4*", ExpectedResult = 2048)] //test uint12 overflow
[TestCase("88*8*4*1+", ExpectedResult = -1)] //test uint12 overflow
public short Should(string expression)
{
return StackStateMachine.Solve(expression);
}
}
} |
using UnityEngine;
public class Collectible : MonoBehaviour
{
// base components
[HideInInspector] public Transform myTransform;
[HideInInspector] public GameObject myGameObject;
// type
public enum Type { Coin, Tear, Key, Donut };
// settings
[Header("settings")]
public Type myType;
public int value;
public float radius;
// lerpie
float lerpieAdd;
// counter
int canCollectDur, canCollectCounter;
// audio
[Header("audio")]
public float pitchMin;
public float pitchMax;
public float volumeMin;
public float volumeMax;
// state
[HideInInspector] public bool collected;
void Start ()
{
myTransform = transform;
myGameObject = gameObject;
canCollectDur = 16;
if ( myType == Type.Key )
{
canCollectDur = 24;
}
canCollectCounter = 0;
}
void Update ()
{
if ( !SetupManager.instance.inFreeze )
{
if (!collected)
{
if (canCollectCounter < canCollectDur)
{
canCollectCounter++;
}
else
{
Vector3 p0 = myTransform.position;
Vector3 p1 = GameManager.instance.playerFirstPersonDrifter.myTransform.position;
float d0 = Vector3.Distance(p0, p1);
if (d0 <= radius)
{
Collect();
}
}
}
else
{
lerpieAdd += .05f;
Vector3 targetP = GameManager.instance.playerFirstPersonDrifter.myTransform.position + (Vector3.up * .5f);
myTransform.position = Vector3.Lerp(myTransform.position, targetP, (10f + lerpieAdd) * Time.deltaTime);
float d1 = Vector3.Distance(myTransform.position, targetP);
if (d1 <= .25f)
{
Claim();
}
}
}
}
public void Collect ()
{
collected = true;
}
public void Claim ()
{
// audio
AudioClip[] clipsUse = null;
switch (myType)
{
case Type.Coin: GameManager.instance.AddCoinAmount(value); clipsUse = AudioManager.instance.coinCollectClips; GameManager.instance.coinCollected = true; break;
case Type.Tear: GameManager.instance.AddTearAmount(value); clipsUse = AudioManager.instance.tearCollectClips; GameManager.instance.tearCollected = true; break;
case Type.Key: GameManager.instance.PlayerFoundKey(); clipsUse = AudioManager.instance.coinCollectClips; GameManager.instance.keyCollected = true; break;
case Type.Donut: GameManager.instance.AddPlayerHealth(1); clipsUse = AudioManager.instance.donutCollectClips; GameManager.instance.donutCollected = true; break;
}
AudioManager.instance.PlaySoundGlobal(BasicFunctions.PickRandomAudioClipFromArray(clipsUse),pitchMin,pitchMax,volumeMin,volumeMax);
// donut achievement?
if ( myType == Type.Donut && SetupManager.instance.CheckIfBlessingClaimed(BlessingDatabase.Blessing.Hungry) )
{
AchievementHelper.UnlockAchievement("ACHIEVEMENT_SATISFIED");
}
// doeg
Clear();
}
public void Clear ()
{
// particles
PrefabManager.instance.SpawnPrefab(PrefabManager.instance.whiteOrbPrefab, myTransform.position, Quaternion.identity, .5f);
// oke dag toedeledokie
if ( myGameObject != null )
{
Destroy(myGameObject);
}
}
}
|
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using ODL.DomainModel.Adress;
namespace ODL.DataAccess.Mappningar
{
public class AdressMappning : EntityTypeConfiguration<Adress>
{
public AdressMappning()
{
ToTable("Adress.Adress");
HasKey(a => a.Id).Property(m => m.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Ignore(a => a.Ny);
Property(m => m.Adressvariant).HasColumnName("AdressvariantFKId");
HasOptional(e => e.Gatuadress)
.WithRequired(e => e.Adress);
HasOptional(e => e.Epost)
.WithRequired(e => e.Adress);
HasOptional(e => e.OrganisationAdress)
.WithRequired(e => e.Adress);
HasOptional(e => e.PersonAdress)
.WithRequired(e => e.Adress);
HasOptional(e => e.Telefon)
.WithRequired(e => e.Adress);
}
}
} |
using System;
using System.Linq;
using System.Collections.Generic;
using Pe.Stracon.Politicas.Aplicacion.Adapter.General;
using Pe.Stracon.Politicas.Aplicacion.Core.Base;
using Pe.Stracon.Politicas.Aplicacion.Core.ServiceContract;
using Pe.Stracon.Politicas.Aplicacion.Service.Base;
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Request.General;
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General;
using Pe.Stracon.Politicas.Cross.Core;
using Pe.Stracon.Politicas.Infraestructura.Core.QueryContract.General;
using Pe.Stracon.PoliticasCross.Core.Exception;
using Pe.Stracon.Politicas.Infraestructura.Core.CommandContract.General;
using Pe.Stracon.Politicas.Infraestructura.CommandModel.General;
namespace Pe.Stracon.Politicas.Aplicacion.Service.General
{
/// <summary>
/// Implementación base generica de servicios de aplicación
/// </summary>
/// <remarks>
/// Creación: GMD 20150327 <br />
/// Modificación: <br />
/// </remarks>
public class ParametroService : GenericService, IParametroService
{
/// <summary>
/// Repositorio de parametro seccion logic
/// </summary>
public IParametroLogicRepository parametroLogicRepository { get; set; }
/// <summary>
/// Repositorio de parametro entidad
/// </summary>
public IParametroEntityRepository parametroEntityRepository { get; set; }
/// <summary>
/// Realiza la busqueda de Parámetro
/// </summary>
/// <param name="filtro">Filtro de Parametro</param>
/// <returns>Listado de Parametro</returns>
public ProcessResult<List<ParametroResponse>> BuscarParametro(ParametroRequest filtro)
{
ProcessResult<List<ParametroResponse>> resultado = new ProcessResult<List<ParametroResponse>>();
try
{
var listado = parametroLogicRepository.BuscarParametro(
filtro.CodigoParametro,
filtro.IndicadorEmpresa,
(filtro.CodigoEmpresa != null ? new Guid(filtro.CodigoEmpresa) : (Guid?)null),
(filtro.CodigoSistema != null ? new Guid(filtro.CodigoSistema) : (Guid?)null),
filtro.CodigoIdentificador,
filtro.TipoParametro,
filtro.Nombre,
filtro.Descripcion,
filtro.IndicadorPermiteAgregar,
filtro.IndicadorPermiteModificar,
filtro.IndicadorPermiteEliminar,
filtro.EstadoRegistro);
var listaParametro = new List<ParametroResponse>();
foreach(var item in listado)
{
listaParametro.Add(ParametroAdapter.ObtenerParametroResponse(item));
}
resultado.Result = listaParametro;
resultado.IsSuccess = true;
}
catch (Exception e)
{
resultado.Result = new List<ParametroResponse>();
resultado.IsSuccess = false;
resultado.Exception = new ApplicationLayerException<ParametroService>(e);
}
return resultado;
}
/// <summary>
/// Realiza el registro de un Parámetro
/// </summary>
/// <param name="filtro">Parametro a Registrar</param>
/// <returns>Indicador de Error</returns>
public ProcessResult<string> RegistrarParametro(ParametroRequest filtro)
{
string result = "0";
var resultadoProceso = new ProcessResult<string>();
try
{
if (filtro.CodigoParametro == null)
{
var parametroUltimo = BuscarParametro(new ParametroRequest() { EstadoRegistro = null }).Result.OrderByDescending(item => item.CodigoParametro).FirstOrDefault();
filtro.CodigoParametro = parametroUltimo != null ? parametroUltimo.CodigoParametro + 1 : 1;
parametroEntityRepository.Insertar(ParametroAdapter.ObtenerParametroEntity(filtro));
}
else
{
var entity = ParametroAdapter.ObtenerParametroEntity(filtro);
var entityActual = parametroEntityRepository.GetById(filtro.CodigoParametro);
entityActual.IndicadorEmpresa = entity.IndicadorEmpresa;
entityActual.TipoParametro = entity.TipoParametro;
entityActual.CodigoSistema = entity.CodigoSistema;
entityActual.CodigoIdentificador = entity.CodigoIdentificador;
entityActual.Nombre = entity.Nombre;
entityActual.Descripcion = entity.Descripcion;
entityActual.IndicadorPermiteAgregar = entity.IndicadorPermiteAgregar;
entityActual.IndicadorPermiteModificar = entity.IndicadorPermiteModificar;
entityActual.IndicadorPermiteEliminar = entity.IndicadorPermiteEliminar;
parametroEntityRepository.Editar(entityActual);
}
parametroEntityRepository.GuardarCambios();
resultadoProceso.IsSuccess = true;
}
catch (Exception e)
{
result = "-1";
resultadoProceso.Result = result;
resultadoProceso.IsSuccess = false;
resultadoProceso.Exception = new ApplicationLayerException<ParametroValorService>(e);
}
return resultadoProceso;
}
/// <summary>
/// Realiza la eliminación de un Parámetro
/// </summary>
/// <param name="filtro">Parametro Eliminar</param>
/// <returns>Indicador de Error</returns>
public ProcessResult<string> EliminarParametro(ParametroRequest filtro)
{
string result = "0";
var resultadoProceso = new ProcessResult<string>();
try
{
parametroEntityRepository.Eliminar(filtro.CodigoParametro);
parametroEntityRepository.GuardarCambios();
resultadoProceso.IsSuccess = true;
}
catch (Exception e)
{
result = "-1";
resultadoProceso.Result = result;
resultadoProceso.IsSuccess = false;
resultadoProceso.Exception = new ApplicationLayerException<ParametroValorService>(e);
}
return resultadoProceso;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Communication
{
// public enum MessageRole {REGISTER,LOGIN,MESSAGE};
[Serializable]
public class Message
{
private string msg;
private Profile p;
public Message(string msg, Profile p)
{
this.msg = msg;
this.p = p;
}
public string Msg { get => msg; set => msg = value; }
public Profile P { get => p; set => p = value; }
public override string ToString()
{
return msg + " " + p.ToString();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PuzzleDoor : MonoBehaviour
{
public bool[] puzzleTF;
private Animation anim;
private AudioSource audioSource;
void Awake()
{
anim = GetComponent<Animation>();
audioSource = GetComponent<AudioSource>();
}
void Switch(int value)
{
bool test = false;
puzzleTF[value] = true;
foreach(bool tf in puzzleTF)
{
if (tf)
test = true;
else
test = false;
}
foreach(bool tf in puzzleTF)
{
if (!tf)
test = false;
}
if (test)
{
anim.Play();
audioSource.Play();
Destroy(gameObject, 3);
}
}
}
|
using Microsoft.EntityFrameworkCore;
using BuiltCodeAPI.Data;
using BuiltCodeAPI.Models;
using BuiltCodeAPI.Repository.IRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BuiltCodeAPI.Repository
{
public class DoctorRepository : IDoctorRepository
{
private readonly ApplicationDbContext _db;
public DoctorRepository(ApplicationDbContext db)
{
_db = db;
}
public bool CreateDoctor(Doctor doctor)
{
_db.Doctors.Add(doctor);
return Save();
}
public bool DeleteDoctor(Doctor doctor)
{
_db.Doctors.Remove(doctor);
return Save();
}
public Doctor GetDoctor(Guid doctorId)
{
return _db.Doctors.FirstOrDefault(n => n.Id == doctorId);
}
public ICollection<Doctor> GetDoctors()
{
return _db.Doctors.OrderBy(n => n.Name).ToList();
}
public bool CRMEndExists(string crmEnd)
{
bool value = _db.Doctors.Any(n => n.CRMEnd.ToLower().Trim() == crmEnd.ToLower().Trim());
return value;
}
public bool DoctorExists(Guid id)
{
bool value = _db.Doctors.Any(n => n.Id == id);
return value;
}
public bool Save()
{
return _db.SaveChanges() >= 0 ? true : false;
}
public bool UpdateDoctor(Doctor doctor)
{
_db.Doctors.Update(doctor);
return Save();
}
}
} |
using UnityEngine;
using System.Collections;
public class Follow : MonoBehaviour {
public Transform player;
public GameObject enemy;
private bool playerInArea;
public float speed;
private float step;
void Update(){
step = speed * Time.deltaTime;
if(playerInArea == true){
MoveTowardsPlayer();
}
else{
DoNothing();
}
gameObject.GetComponent<Animation>().Play();
}
void OnTriggerEnter(Collider Other){
if(Other.tag == "Player"){
playerInArea = true;
}
}
void OnTriggerExit(Collider Other){
if(Other.tag == "Player"){
playerInArea = false;
}
}
void MoveTowardsPlayer(){
enemy.transform.position = Vector3.MoveTowards(enemy.transform.position, player.position, step);
}
void DoNothing(){
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ExcelinDotNetCoreEPPlus
{
public class UserDetails
{
public string ID { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
}
|
using Cs_Notas.Dominio.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Notas.Dominio.Interfaces.Servicos
{
public interface IServicoComplementos: IServicoBase<Complementos>
{
List<Complementos> ObterComplementosPorIdAto(int idAto);
}
}
|
using System;
using com.Sconit.Entity.SYS;
using System.ComponentModel.DataAnnotations;
//TODO: Add other using statements here
namespace com.Sconit.Entity.MRP.MD
{
public partial class WorkCalendar
{
#region Non O/R Mapping Properties
[CodeDetailDescriptionAttribute(CodeMaster = com.Sconit.CodeMaster.CodeMaster.TimeUnit, ValueField = "DateType")]
[Display(Name = "MrpWorkCalendar_DateType", ResourceType = typeof(Resources.MRP.MrpWorkCalendar))]
public string DateTypeDescription { get; set; }
#endregion
}
} |
using UnityEngine;
namespace UnityAtoms.BaseAtoms
{
/// <summary>
/// Event Instancer of type `Vector2Pair`. Inherits from `AtomEventInstancer<Vector2Pair, Vector2PairEvent>`.
/// </summary>
[EditorIcon("atom-icon-sign-blue")]
[AddComponentMenu("Unity Atoms/Event Instancers/Vector2Pair Event Instancer")]
public class Vector2PairEventInstancer : AtomEventInstancer<Vector2Pair, Vector2PairEvent> { }
}
|
using MinecraftToolsBoxSDK;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace TranslationTools
{
class TreeDataGridItemEntity : TreeDataGridItem
{
public string id;
public string[] uuid;
public TreeDataGridItemEntity(XmlNode item, int index)
{
Type = "实体" + index;
id = item.Attributes["Id"].Value;
foreach (XmlNode node in item.ChildNodes)
{
if (node.Name == "CustomName") Children.Add(new TreeDataGridItem { Type = "名称", Node = node });
else
{
if (node.Name == "Item")
{
TreeDataGridItemItem i = new TreeDataGridItemItem { Type = node.Attributes["Slot"].Value };
foreach (XmlNode data in node.ChildNodes)
i.Children.Add(new TreeDataGridItem { Type = data.Name == "Name" ? "名字" : "说明", Node = data });
Children.Add(i);
}
else
{
TreeDataGridItem i2 = new TreeDataGridItem { Type = "书" };
foreach (XmlNode data in node.ChildNodes)
i2.Children.Add(new TreeDataGridItem { Type = data.Name == "Title" ? "标题" : "内容", Node = data });
Children.Add(i2);
}
}
}
}
}
class TreeDataGridItemItem : TreeDataGridItem
{
public string slot;
}
}
|
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 MetroFramework.Forms;
using ShareCar.Repository;
using ShareCar.Entity;
namespace ShareCar_v2
{
public partial class UserDash : MetroForm
{
CarRequestRepo RequestRepo = new CarRequestRepo();
loginEnt user = new loginEnt();
public UserDash()
{
InitializeComponent();
}
private void PopulatedGridView()
{
user.username = Login.username;
this.userGrid.AutoGenerateColumns = false;
this.userGrid.DataSource = RequestRepo.GetAll(user).ToList();
this.userGrid.ClearSelection();
this.userGrid.Refresh();
}
private void UserDash_Load(object sender, EventArgs e)
{
this.PopulatedGridView();
}
private void metroTile1_Click(object sender, EventArgs e)
{
AddCarRequest addCarRequest = new AddCarRequest();
this.Close();
addCarRequest.Show();
}
}
}
|
using LogicaNegocios;
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.Windows;
using AccesoDatos1;
using Entidades1;
namespace P
{
public partial class Hora : Form
{
Proceso1 proces = new Proceso1();
Citas cita = new Citas();
Cliente clien = new Cliente();
Doctor doctor = new Doctor();
string[,] itemHora;
public Hora()
{
InitializeComponent();
FiltrarListaPersona();
InsertarTabla();
}
void InsertarTabla()
{
DataTable dt = new DataTable();
if ((dt = proces.CitasTabla()) != null)
{
TablaCliente.DataSource = dt;
}
itemHora = new string[3, 5];
for (int i = 0; i < 3; i++)
{
itemHora[i, 0] = "08:00am";
itemHora[i, 1] = "09:00am";
itemHora[i, 2] = "10:00am";
itemHora[i, 3] = "11:00am";
itemHora[i, 4] = "12:00am";
}
if (TablaCliente.Rows.Count > 0)
{
HorasFiltro();
}
Jc_hora.SelectedIndex = -1;
}
void HorasFiltro()
{
for (int i = 0; i < TablaCliente.Rows.Count; i++)
{
string hora = TablaCliente.Rows[i].Cells[3].Value.ToString().Substring(0, 7);
for (int j = 0; j < 3; j++)
{
if (TablaCliente.Rows[i].Cells[1].Value.ToString().Equals(jc_doctor.Items[j]))
{
for (int m = 0; m < 5; m++)
{
if (itemHora[j, m].Equals(hora))
{
itemHora[j, m] = "0";
}
}
}
}
}
}
void DoctorHora(int doc)
{
Jc_hora.Items.Clear();
for (int i = 0; i < 5; i++)
{
if (!itemHora[doc, i].Equals("0"))
{
Jc_hora.Items.Add(itemHora[doc, i]);
}
}
}
void FiltrarListaPersona()
{
List<object> lista;
lista = proces.ReturListaPersona();
foreach (var item in lista)
{
if (item is Cliente)
{
}
else if (item is Doctor)
{
}
}
}
private void Jb_agregarCita_Click(object sender, EventArgs e)
{
try
{
Random random = new Random();
int idcita = random.Next(1, 999);
DateTime date = DateTime.Now;
string fecha = "";
fecha = Jc_hora.Items[Jc_hora.SelectedIndex].ToString() + "-" + Convert.ToString(date.Day) + "/" + Convert.ToString(date.Month) + "/" + Convert.ToString(date.Year);
Citas cita = new Citas(idcita, jc_doctor.Items[jc_doctor.SelectedIndex].ToString(), Jc_Paciente.Items[Jc_Paciente.SelectedIndex].ToString(), jt_desc.Text, fecha);
proces.AgregarCita(cita);
InsertarTabla();
}
catch (Exception ex)
{
Console.WriteLine("El error es: " + ex);
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
int row = e.RowIndex;
jt_cod.Text = TablaCliente.Rows[row].Cells[0].Value.ToString();
}
void filtrarCitas()
{
string[,] itemHoras;
itemHoras = new string[3, 5];
for (int i = 0; i < 2; i++)
{
itemHoras[i, 1] = "08:00a.m";
itemHoras[i, 2] = "09:00a.m";
itemHoras[i, 3] = "10:00a.m";
itemHoras[i, 4] = "11:00a.m";
itemHoras[i, 5] = "12:00a.m";
}
for (int i = 0; i < TablaCliente.Rows.Count; i++)
{
string hora = TablaCliente.Rows[i].Cells[1].Value.ToString().Substring(0, 8);
for (int j = 0; j < 2; i++)
{
if (TablaCliente.Rows[i].Cells[1].Value.ToString().Equals(jc_doctor.Items[j]))
{
for (int k = 0; k < 4; k++)
{
if (itemHoras[j, k].Equals(hora))
{
itemHoras[j, k] = "0";
}
}
}
}
}
if (itemHoras[1, 2].Equals("0"))
{
jc_doctor.Items.Add(itemHoras[1, 2]);
//abrir for
}
}
private void EliminaCita_Click(object sender, EventArgs e)
{
cita.IdCita = int.Parse(jt_cod.Text);
proces.EliminarCita(cita);
InsertarTabla();
}
private void Hora_Load(object sender, EventArgs e)
{
// TODO: esta línea de código carga datos en la tabla 'hospitalDataSet.Citas' Puede moverla o quitarla según sea necesario.
this.citasTableAdapter.Fill(this.hospitalDataSet.Citas);
// TODO: esta línea de código carga datos en la tabla 'hospitalDataSet.Paciente' Puede moverla o quitarla según sea necesario.
this.pacienteTableAdapter.Fill(this.hospitalDataSet.Paciente);
}
private void jc_doctor_SelectedIndexChanged(object sender, EventArgs e)
{
DoctorHora(jc_doctor.SelectedIndex);
}
}
}
|
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using NoSQL.Model;
namespace NoSQL.Extensions {
public static class JsonExtensions {
public static string ToJson(this List<Measurement> measurements) {
string json = "";
using (StringWriter sw = new StringWriter()) {
using (JsonTextWriter writer = new JsonTextWriter(sw)) {
// [
writer.WriteStartArray();
foreach (Measurement measurement in measurements) {
writer.WriteRawValue(measurement.ToJson());
}
// ]
writer.WriteEndArray();
}
json = sw.ToString();
}
return json;
}
public static string ToJson(this Measurement measurement) {
string json = "";
using (StringWriter sw = new StringWriter()) {
using (JsonTextWriter writer = new JsonTextWriter(sw)) {
// {
writer.WriteStartObject();
writer.WritePropertyName("contest_id");
writer.WriteValue(measurement.ContestId);
writer.WritePropertyName("game_id");
writer.WriteValue(measurement.GameId);
writer.WritePropertyName("player_id");
writer.WriteValue(measurement.PlayerId);
writer.WritePropertyName("sensor");
writer.WriteRawValue(measurement.Sensor.ToJson());
writer.WritePropertyName("timestamp");
writer.WriteValue(measurement.Timestamp);
writer.WritePropertyName("coordinate");
writer.WriteRawValue(measurement.Coordinate.ToJson());
// }
writer.WriteEndObject();
}
json = sw.ToString();
}
return json;
}
public static string ToJson(this Sensor sensor) {
string json = "";
using (StringWriter sw = new StringWriter()) {
using (JsonTextWriter writer = new JsonTextWriter(sw)) {
// {
writer.WriteStartObject();
writer.WritePropertyName("hit_type");
writer.WriteValue(sensor.HitType.ToString());
writer.WritePropertyName("top_spin");
writer.WriteValue(sensor.TopSpin);
writer.WritePropertyName("power");
writer.WriteValue(sensor.Power);
writer.WritePropertyName("coordinate");
writer.WriteRawValue(sensor.Coordinate.ToJson());
// }
writer.WriteEndObject();
}
json = sw.ToString();
}
return json;
}
public static string ToJson(this Coordinate coordinate, bool valuesAsString = false) {
string json = "";
using (StringWriter sw = new StringWriter()) {
using (JsonTextWriter writer = new JsonTextWriter(sw)) {
// {
writer.WriteStartObject();
writer.WritePropertyName("latitude");
if (valuesAsString) {
writer.WriteValue(string.Format("{0:0.0000000}", coordinate.Latitude));
} else {
writer.WriteValue(coordinate.Latitude);
}
writer.WritePropertyName("longitude");
if (valuesAsString) {
writer.WriteValue(string.Format("{0:0.0000000}", coordinate.Longitude));
} else {
writer.WriteValue(coordinate.Longitude);
}
// }
writer.WriteEndObject();
}
json = sw.ToString();
}
return json;
}
}
}
|
using WeatherPredictorComponent.aquaintance;
using System;
namespace WeatherPredictorComponent.logic
{
public class ModelFacade : IModelFacade
{
private static ModelFacade instance;
private model model;
private ModelFacade()
{
model = new model();
}
public static ModelFacade getInstance()
{
if (instance == null)
{
instance = new ModelFacade();
}
return instance;
}
[Obsolete]
public string[] CreateArimaModelWithForecast(string[] data, int daysToForecast, int p, int d, int q, string StationId)
{
return model.CreateArimaModelWithForecast(data, daysToForecast, p, d, q, StationId);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Nac.Common.Fuzzy {
[DataContract, Serializable]
public class NacMembershipFunction {}
[DataContract, Serializable]
public class NacTrapezoidalMembershipFunction : NacMembershipFunction {
[DataMember]
public virtual float m1 { get; set; }
[DataMember]
public virtual float m2 { get; set; }
[DataMember]
public virtual float m3 { get; set; }
[DataMember]
public virtual float m4 { get; set; }
[DataMember]
public virtual float min { get; set; }
[DataMember]
public virtual float max { get; set; }
[DataMember]
public virtual int edge { get; set; } //-1 Left, 0 no edge, 1 Right
public NacTrapezoidalMembershipFunction() {
m1 = 10f;
m2 = 30f;
m3 = 50f;
m4 = 90f;
min = 0f;
max = 1f;
edge = 0;
}
}
}
|
using System;
using Apache.Shiro.Aop;
namespace Apache.Shiro.Authz.Aop
{
public abstract class AuthorizingAttributeHandler : AttributeHandler
{
protected AuthorizingAttributeHandler(Type attributeType)
: base(attributeType)
{
}
public abstract void AssertAuthorized(Attribute attribute);
}
} |
using System.Windows;
using System.Windows.Controls;
namespace CODE.Framework.Wpf.Documents
{
/// <summary>
/// TextBlock that can be populated from HTML
/// </summary>
public class HtmlTextBlock : TextBlock
{
/// <summary>HTML string (fragment with limited HTML support)</summary>
public string Html
{
get { return (string) GetValue(HtmlProperty); }
set { SetValue(HtmlProperty, value); }
}
/// <summary>HTML string (fragment with limited HTML support)</summary>
public static readonly DependencyProperty HtmlProperty = DependencyProperty.Register("Html", typeof (string), typeof (HtmlTextBlock), new UIPropertyMetadata("", RepopulateInlines));
/// <summary>Re-creates the actual paragraph inlines based on the HTML as well as leading and trailing inlines</summary>
/// <param name="source">Special Paragraph object</param>
/// <param name="e">Event arguments</param>
private static void RepopulateInlines(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
var textBlock = source as HtmlTextBlock;
if (textBlock == null) return;
textBlock.Inlines.Clear();
textBlock.Inlines.AddRange(textBlock.Html.ToSimplifiedInlines());
}
}
} |
namespace IrsMonkeyApi.Models.Dto
{
public class PaymentResponseDto
{
public TransactionResponse transactionResponse { get; set; }
}
public class TransactionResponse
{
public string responseCode { get; set; }
public string authCode { get; set; }
public string avsResultCode { get; set; }
public string cvvResultCode { get; set; }
public string transID { get; set; }
public string refTransId { get; set; }
public string transHash { get; set; }
public string testRequest { get; set; }
public string accountNumber { get; set; }
public string accountType { get; set; }
public Message[] messages { get; set; }
public string transHashSha2 { get; set; }
public int SupplementalDataQualificationIndicator { get; set; }
}
public class Message
{
public string code { get; set; }
public string description { get; set; }
}
public class Messages
{
public string resultCode { get; set; }
public Message2 message { get; set; }
}
public class Message2
{
public string code { get; set; }
public string text { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Xlns.BusBook.Core.Model
{
public abstract class ModelEntity
{
public virtual int Id { get; set; }
public override bool Equals(object obj)
{
if(obj.GetType() != this.GetType())
return false;
else
return this.Id == ((ModelEntity)obj).Id;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
double widthA = double.Parse(Console.ReadLine());
double heightB = double.Parse(Console.ReadLine());
double wallArea = widthA * (widthA / 2) * 2;
double backWallArea = (widthA / 2) * (widthA / 2) + (widthA / 2) * (heightB - widthA / 2) / 2;
double frontWallArea = backWallArea - (widthA / 5) * (widthA / 5);
double roof = widthA * (widthA / 2) * 2;
double greenColor = (wallArea + backWallArea + frontWallArea) / 3;
double redColor = roof / 5;
Console.WriteLine("{0:f2}", greenColor);
Console.WriteLine("{0:f2}", redColor);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Pun;
public class CreateAndJoinRooms : MonoBehaviourPunCallbacks
{
public InputField createInput;
public InputField joinInput;
// public GameObject waitlobby;
public void CreateRoom()
{
PhotonNetwork.CreateRoom(createInput.text);
}
public void JoinRoom()
{
PhotonNetwork.JoinRoom(joinInput.text);
}
public override void OnJoinedRoom()
{
PhotonNetwork.LoadLevel("Waiting Lobby");
// waitlobby = GameObject.FindGameObjectWithTag("RoomDeets");
// waitlobby.GetComponent<WaitLobby>().players++;
// waitlobby.GetComponent<WaitLobby>().room = "createInput.text";
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Focuswin.SP.Base.Utility;
using Microsoft.SharePoint;
using YFVIC.DMS.Model.Models.Settings;
using YFVIC.DMS.Model.Models.Common;
using YFVIC.DMS.Model.Models.HR;
namespace YFVIC.DMS.Model.Models.Project
{
public class ProjectMgr
{
SysUserMgr usermgr = new SysUserMgr();
/// <summary>
/// 添加项目
/// </summary>
/// <param name="obj">项目实体</param>
/// <returns></returns>
public bool InsertProject(ProjectEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
SPUser user = SPContext.Current.Web.CurrentUser;
string loginname = DMSComm.resolveLogon(user.LoginName);
using (ProjectDataContext db = new ProjectDataContext(setting.DefaultValue))
{
Projectinfo item = new Projectinfo
{
Name = obj.Name,
EPNum=obj.EPNum,
ProjectLine=obj.ProjectLine,
Customer=obj.Customer,
Company = obj.Company,
Depart = obj.Depart,
Creater = loginname,
CreateTime=DateTime.Now.ToString(),
Area=obj.Area,
};
db.Projectinfos.InsertOnSubmit(item);
db.SubmitChanges();
DMSComm.AddGroup(SPContext.Current.Site.Url, obj.EPNum, loginname);
return true;
}
}
/// <summary>
/// 更新项目
/// </summary>
/// <param name="obj">项目实体</param>
/// <returns></returns>
public bool UpdataProject(ProjectEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (ProjectDataContext db = new ProjectDataContext(setting.DefaultValue))
{
Projectinfo item = db.Projectinfos.Where(p => p.Id == obj.Id).FirstOrDefault();
DMSComm.UpdataGroup(SPContext.Current.Site.Url, obj.EPNum, item.EPNum);
item.Name = obj.Name;
item.Customer = obj.Customer;
item.EPNum = obj.EPNum;
item.Depart = obj.Depart;
item.ProjectLine = obj.ProjectLine;
item.Area = obj.Area;
db.SubmitChanges();
return true;
}
}
/// <summary>
/// 删除项目
/// </summary>
/// <param name="id">项目编号</param>
/// <returns></returns>
public bool DelProject(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (ProjectDataContext db = new ProjectDataContext(setting.DefaultValue))
{
Projectinfo item = db.Projectinfos.Where(p => p.Id == Convert.ToInt32(obj.Id)).FirstOrDefault();
DMSComm.RemoveGroup(SPContext.Current.Site.Url, item.EPNum);
db.Projectinfos.DeleteOnSubmit(item);
db.SubmitChanges();
return true;
}
}
/// <summary>
/// 获取项目列表
/// </summary>
/// <param name="obj">页面参数</param>
/// <returns></returns>
public List<ProjectEntity> GetProjectsByCompany(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (ProjectDataContext db = new ProjectDataContext(setting.DefaultValue))
{
List<Projectinfo> items = new List<Projectinfo>();
SPUser currentUser = SPContext.Current.Web.CurrentUser;
string loginname = DMSComm.resolveLogon(currentUser.LoginName);
if (DMSComm.IsAdmin(loginname)||obj.CanGetProject=="true")
{
items = db.Projectinfos.Where(p => p.Company == obj.Id ).Where( p=>p.EPNum.Contains(obj.Search)).Skip(obj.LimitRows * (obj.TakeCount - 1)).Take(obj.LimitRows).ToList();
}
else
{
items = db.Projectinfos.Where(p => p.Company == obj.Id && p.Creater== loginname).Where(p => p.EPNum.Contains(obj.Search)).Skip(obj.LimitRows * (obj.TakeCount - 1)).Take(obj.LimitRows).ToList();
}
List<ProjectEntity> listitems = new List<ProjectEntity>();
foreach (Projectinfo item in items)
{
ProjectEntity pitem = new ProjectEntity();
pitem.Id = item.Id;
pitem.Name = item.Name;
pitem.Company = item.Company;
pitem.Customer = item.Customer;
pitem.Depart = item.Depart;
pitem.EPNum = item.EPNum;
pitem.ProjectLine = item.ProjectLine;
SysUserEntity user = usermgr.GetSysUserBySid(item.Creater);
pitem.Creater = item.Creater;
pitem.CreaterName = user.ChineseName;
pitem.CreateTime = item.CreateTime;
pitem.Area = item.Area;
listitems.Add(pitem);
}
return listitems;
}
}
/// <summary>
/// 获取公司项目总数
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public int GetProjectsCount(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (ProjectDataContext db = new ProjectDataContext(setting.DefaultValue))
{
SPUser user = SPContext.Current.Web.CurrentUser;
string loginname = DMSComm.resolveLogon(user.LoginName);
List<Projectinfo> items = new List<Projectinfo>();
if (DMSComm.IsAdmin(loginname))
{
items = db.Projectinfos.Where(p => p.Company == obj.Id).Where(p => p.EPNum.Contains(obj.Search)).ToList();
}
else
{
items = db.Projectinfos.Where(p => p.Company == obj.Id && p.Creater == loginname).Where(p => p.EPNum.Contains(obj.Search)).ToList();
}
return items.Count;
}
}
/// <summary>
/// 检查名称是否存在
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public bool CheckName(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (ProjectDataContext db = new ProjectDataContext(setting.DefaultValue))
{
List<Projectinfo> items = db.Projectinfos.Where(p => p.Name == obj.Name&&p.EPNum==obj.EPNum).ToList();
if (items.Count == 0)
{
return true;
}
else
{
return false;
}
}
}
/// <summary>
/// 根据项目id获取项目信息
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public ProjectEntity GetProjectById(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (ProjectDataContext db = new ProjectDataContext(setting.DefaultValue))
{
Projectinfo item = db.Projectinfos.Where(p => p.Id== Convert.ToInt32(obj.Id)).FirstOrDefault();
ProjectEntity pitem = new ProjectEntity();
pitem.Id = item.Id;
pitem.Name = item.Name;
pitem.Company = item.Company;
pitem.Customer = item.Customer;
pitem.Depart = item.Depart;
pitem.EPNum = item.EPNum;
pitem.ProjectLine = item.ProjectLine;
SysUserEntity user = usermgr.GetSysUserBySid(item.Creater);
pitem.Creater = item.Creater;
pitem.CreaterName = user.ChineseName;
pitem.CreateTime = item.CreateTime;
pitem.Area = item.Area;
return pitem;
}
}
/// <summary>
/// 根据EPNum获取项目信息
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public ProjectEntity GetProjectByEPNum(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (ProjectDataContext db = new ProjectDataContext(setting.DefaultValue))
{
Projectinfo item = db.Projectinfos.Where(p => p.EPNum == obj.EPNum).FirstOrDefault();
ProjectEntity pitem = new ProjectEntity();
pitem.Id = item.Id;
pitem.Name = item.Name;
pitem.Company = item.Company;
pitem.Customer = item.Customer;
pitem.Depart = item.Depart;
pitem.EPNum = item.EPNum;
pitem.ProjectLine = item.ProjectLine;
SysUserEntity user = usermgr.GetSysUserBySid(item.Creater);
pitem.Creater = item.Creater;
pitem.CreaterName = user.ChineseName;
pitem.CreateTime = item.CreateTime;
pitem.Area = item.Area;
return pitem;
}
}
/// <summary>
/// 获取当前登录人创建的项目
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public List<ProjectEntity> GetProjectByCreater(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
SPUser user = SPContext.Current.Web.CurrentUser;
string loginname = DMSComm.resolveLogon(user.LoginName);
using (ProjectDataContext db = new ProjectDataContext(setting.DefaultValue))
{
List<Projectinfo> items = new List<Projectinfo>();
if (DMSComm.IsAdmin(loginname))
{
items = db.Projectinfos.Skip(obj.LimitRows * (obj.TakeCount - 1)).Take(obj.LimitRows).ToList();
}
else
{
items = db.Projectinfos.Where(p => p.Creater == loginname).Skip(obj.LimitRows * (obj.TakeCount - 1)).Take(obj.LimitRows).ToList();
}
List<ProjectEntity> result = new List<ProjectEntity>();
foreach (Projectinfo item in items)
{
ProjectEntity pitem = new ProjectEntity();
pitem.Id = item.Id;
pitem.Name = item.Name;
pitem.Company = item.Company;
pitem.Customer = item.Customer;
pitem.Depart = item.Depart;
pitem.EPNum = item.EPNum;
pitem.ProjectLine = item.ProjectLine;
SysUserEntity user1 = usermgr.GetSysUserBySid(item.Creater);
pitem.Creater = item.Creater;
pitem.CreaterName = user1.ChineseName;
pitem.CreateTime = item.CreateTime;
pitem.Area = item.Area;
result.Add(pitem);
}
return result;
}
}
/// <summary>
/// 获取当前登录人所创建的项目数
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public int GetProjectCountByCreater(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
SPUser user = SPContext.Current.Web.CurrentUser;
string loginname = DMSComm.resolveLogon(user.LoginName);
using (ProjectDataContext db = new ProjectDataContext(setting.DefaultValue))
{
List<Projectinfo> items = new List<Projectinfo>();
if (DMSComm.IsAdmin(loginname))
{
items = db.Projectinfos.Skip(obj.LimitRows * (obj.TakeCount - 1)).Take(obj.LimitRows).ToList();
}
else
{
items = db.Projectinfos.Where(p => p.Creater == loginname).Skip(obj.LimitRows * (obj.TakeCount - 1)).Take(obj.LimitRows).ToList();
}
return items.Count();
}
}
/// <summary>
/// 更新项目创建者
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public bool UpdataProjectCreater(ProjectEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (ProjectDataContext db = new ProjectDataContext(setting.DefaultValue))
{
Projectinfo item = db.Projectinfos.Where(p => p.Id == obj.Id).FirstOrDefault();
item.Creater = obj.Creater;
db.SubmitChanges();
return true;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace LoadNetworkImageRepo
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class ImageBkgrd : Page
{
public ImageBkgrd()
{
this.InitializeComponent();
}
private async void UserButton2_Click(object sender, RoutedEventArgs e)
{
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(@"\\YouPC\Users\SharedContent\media"); // Your Location. you need to share respective location else it will through exception.
StorageFile file = await folder.GetFileAsync("placeholder-sdk.png"); // Your Image.
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read))
{
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(stream);
if (bitmapImage != null)
{
UserImage1.Source = bitmapImage;
}
}
}
private void HomeButton2_Click(object sender, RoutedEventArgs e)
{
if (Frame.CanGoBack)
{
Frame.GoBack();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ASPNETCoreBSON.Model;
using MongoDB.Driver;
namespace ASPNETCoreBSON.Repository
{
public interface IMercuriesRepository
{
Task Add(Mercury mercuryEntry);
Task<IEnumerable<Mercury>> GetAll();
Task<Mercury> Find(string id);
Task<DeleteResult> Remove(string id);
Task<UpdateResult> Update(Mercury mercuryEntry);
}
}
|
using System.Collections.Generic;
using Chess.Data.Entities;
namespace ChessSharp.Web.Models
{
public class HistoricalGamesViewModel
{
public List<CompletedGameViewModel> Games { get; set; }
public HistoricalGamesViewModel()
{
Games = new List<CompletedGameViewModel>();
}
}
} |
namespace Zitadel.Authentication.Credentials
{
/// <summary>
/// A private key for JWT profile authentication.
/// </summary>
public record JwtPrivateKey
{
internal JwtPrivateKey(string? path, string? content) => (Path, Content) = (path, content);
/// <summary>
/// Path to the key file.
/// </summary>
#if NET5_0_OR_GREATER
public string? Path { get; init; }
#elif NETCOREAPP3_1_OR_GREATER
public string? Path { get; set; }
#endif
/// <summary>
/// Direct json content of the jwt key.
/// </summary>
#if NET5_0_OR_GREATER
public string? Content { get; init; }
#elif NETCOREAPP3_1_OR_GREATER
public string? Content { get; set; }
#endif
}
/// <summary>
/// JWT profile key loaded from a file path.
/// </summary>
public record JwtPrivateKeyPath : JwtPrivateKey
{
public JwtPrivateKeyPath(string path)
: base(path, null)
{
}
}
/// <summary>
/// JWT Profile key loaded from json content.
/// </summary>
public record JwtPrivateKeyContent : JwtPrivateKey
{
public JwtPrivateKeyContent(string content)
: base(null, content)
{
}
}
}
|
using System;
using System.Diagnostics;
using System.IO;
namespace idx2dec
{
class Program
{
static void Main(string[] args)
{
if (File.Exists(@"C:\\Perl64\\bin\\perl.exe"))
{
Console.WriteLine("ActivePerl found.\n");
}
else if (File.Exists(@"C:\\Strawberry\\perl\\bin\\perl.exe"))
{
Console.WriteLine("Strawberry Perl found.\n");
}
else
{
Console.WriteLine("An unexpected error has occurred.\nCannot find perl.\nActivePerl or Strawberry Perl must be installed to use this application.\n");
return;
}
if (args.Length != 2)
{
Console.Clear();
Console.WriteLine("idx2dec - IDOLM@STER Deary Stars: Archive decompress utility - CUI Edition\nApplication by: XyLeP.\nPerl script by: mirai-iro\n\nUsage: idx2dec <BIN-Path> <IDX-Path>\n");
Console.WriteLine("<BIN-Path>: Specify the full path of the BIN archive file.\n<IDX-Path>: Specify the full path of the IDX file.\nNote: Both the BIN archive file and the IDX file must reside in the same directory.\n");
return;
}
else
{
Console.Clear();
if (!File.Exists(Path.GetFullPath(args[0])))
{
Console.WriteLine("An unexpected error has occurred.\n");
Console.WriteLine(args[0] + " : No such file or directory.\n");
return;
}
if (!File.Exists(Path.GetFullPath(args[1])))
{
Console.WriteLine("An unexpected error has occurred.\n");
Console.WriteLine(args[1] + " : No such file or directory.\n");
return;
}
if (Path.GetExtension(args[0]) != ".BIN")
{
Console.WriteLine("An unexpected error has occurred.\nArgument 1 is not a BIN archive file.\n");
return;
}
if (Path.GetExtension(args[1]) != ".IDX")
{
Console.WriteLine("An unexpected error has occurred.\nArgument 2 is not a IDX archive file.\n");
return;
}
if (Path.GetFileNameWithoutExtension(args[0]) != Path.GetFileNameWithoutExtension(args[1]))
{
Console.WriteLine("An unexpected error has occurred.\nThe file names of argument 1 and argument 2 are different.\n");
return;
}
Console.WriteLine("Readed BIN: {0}\nReaded IDX: {1}\n", Path.GetFileName(args[0]), Path.GetFileName(args[1]));
byte[] plxFile = Properties.Resources.main;
File.WriteAllBytes(Directory.GetCurrentDirectory() + "\\main.plx", plxFile);
if (Directory.Exists(Directory.GetCurrentDirectory() + "\\" + Path.GetFileNameWithoutExtension(args[0])))
{
Delete(Directory.GetCurrentDirectory() + "\\" + Path.GetFileNameWithoutExtension(args[0]));
}
Console.WriteLine("Decrypting and decompressing...\n----------------------------------");
ProcessStartInfo pInfo = new ProcessStartInfo();
Process process;
pInfo.FileName = "perl";
pInfo.Arguments = @".\\main.plx " + Path.GetFileNameWithoutExtension(args[0]);
pInfo.UseShellExecute = true;
process = Process.Start(pInfo);
process.WaitForExit();
File.Delete(Directory.GetCurrentDirectory() + "\\main.plx");
if (Directory.Exists(Directory.GetCurrentDirectory() + "\\" + Path.GetFileNameWithoutExtension(args[0])))
{
foreach (string file in Directory.GetFiles(Directory.GetCurrentDirectory() + "\\" + Path.GetFileNameWithoutExtension(args[0]), "*.*"))
{
Console.WriteLine(file);
}
DirectoryInfo di = new DirectoryInfo(Directory.GetCurrentDirectory() + "\\" + Path.GetFileNameWithoutExtension(args[0]));
// フォルダサイズ取得
long size = GetFolderSize(di);
Console.WriteLine("\nSize: {0} bytes, OK.\n", size.ToString());
Console.WriteLine("Archive decompression complete.\n");
return;
}
else
{
Console.WriteLine("An unexpected error has occurred.\n");
Console.WriteLine(Directory.GetCurrentDirectory() + "\\" + Path.GetFileNameWithoutExtension(args[0]) + " : No such directory.\n");
return;
}
}
}
static long GetFolderSize(DirectoryInfo di)
{
long size = 0;
foreach (FileInfo f in di.GetFiles())
{
size += f.Length;
}
foreach (DirectoryInfo d in di.GetDirectories())
{
size += GetFolderSize(d);
}
return size;
}
public static void Delete(string targetDirectoryPath)
{
if (!Directory.Exists(targetDirectoryPath))
{
return;
}
string[] filePaths = Directory.GetFiles(targetDirectoryPath);
foreach (string filePath in filePaths)
{
File.SetAttributes(filePath, FileAttributes.Normal);
File.Delete(filePath);
}
string[] directoryPaths = Directory.GetDirectories(targetDirectoryPath);
foreach (string directoryPath in directoryPaths)
{
Delete(directoryPath);
}
Directory.Delete(targetDirectoryPath, false);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace PiwoBack.Data.DTOs
{
public class BreweryPictureDto: BaseIdDto
{
public string PictureName { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace University.UI.Models
{
public class PaymentGatewayVM
{
[Required(ErrorMessage = "Please enter Full Name")]
[StringLength(30, ErrorMessage = "Do not enter more than 30 characters")]
[RegularExpression(@"^[a-zA-Z\s]+$", ErrorMessage = "Special characters and Numbers should not be entered")]
public string CardHolderName { get; set; }
[Required(ErrorMessage = "Please enter Card Number")]
[RegularExpression("([0-9]+)", ErrorMessage = "Only Numbers are Allowed")]
[StringLength(20, ErrorMessage = "Do not enter more than 20 Numbers")]
public string CardNumber { get; set; }
[Required(ErrorMessage = "Please enter Month")]
public int Month { get; set; }
[Required(ErrorMessage = "Please enter Year")]
public int Year { get; set; }
[Required(ErrorMessage = "Please enter CVV")]
[RegularExpression("([0-9]+)", ErrorMessage = "Only Numbers are Allowed")]
[Range(1, 999999, ErrorMessage = "Do not enter more than 6 Numbers")]
public int CVV { get; set; }
public string MonthAndYear
{
get
{
return Month > 9 ? Month.ToString() + Year.ToString() : "0" + Month.ToString() + Year.ToString();
}
}
public string DBCardNumber
{
get
{
return "XXXXXXXXXXXX" + CardNumber.Substring(CardNumber.Length - 4);
//return CardNumber.Substring(CardNumber.Length - 16);
}
}
public decimal Amount { get; set; }
public string CustomerFName { get; set; }
public string ProductName { get; set; }
public string GuidString { get; set; }
public List<CardListVM> cardListVMs { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _3_CriandoVariaveisPontoFlutuante
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Executando projeto 3 Criando Variáveis de Ponto Flutuante");
double salario;
salario = 15.7;
Console.WriteLine(salario);
double idade;
idade = 15 / 2;
Console.WriteLine(idade);
idade = 15.0 / 2; //15 / 2 mesmo idade sendo um double é necessário colocar 15.0 para que ele faça o calculo de double / por Int senão ele faz entre dois numeros inteiros e nesse caso perde o decimal
Console.WriteLine(idade);
Console.WriteLine("A execução acabou. Aperte qualquer tecla em seguida Enter para finalizar a aplicação...");
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using StanbicIBTC.BotServices.Models;
using StanbicIBTC.BotServices.Utility;
namespace StanbicIBTC.BotServices.Controllers
{
public class AccountStatementController : ApiController
{
public IHttpActionResult AccountStatement([FromBody]AccountStatement accountStatement)
{
try
{
//accountStatement.startDate = new DateTime.Now();
if (!ModelState.IsValid)
return BadRequest("Invalid data.");
string accountStatementReq = App.GetRedboxAccountStatementPayload(accountStatement);
string accountStatementRes = App.CallRedbox(accountStatementReq);
LogWorker logworker = new LogWorker("AccountStatementController", "AccountStatement", "Ok");
return Ok(accountStatementRes);
}
catch (Exception ex)
{
LogWorker logworker = new LogWorker("AccountStatementController", "AccountStatement", ex.ToString());
return InternalServerError();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CRL.Business.OnlinePay.Company.ChinaPay.CancelTender
{
/// <summary>
/// 取消投标
/// </summary>
public class Request : RequestBase
{
protected override string Host
{
get
{
return "http://210.22.91.77:8404/channel";
}
}
protected override string InterfacePath
{
get { return "/Business/EasMerchant/" + RequestName; }
}
public override string MessageCode
{
get { return "201834"; }
}
public override string RequestName
{
get { return "C101TenderCancelRq"; }
}
/// <summary>
/// 投标订单号
/// </summary>
public string OrderNo
{
get;
set;
}
/// <summary>
/// 标的号
/// </summary>
public string SubjectNo
{
get;
set;
}
/// <summary>
/// 投资人用户号
/// </summary>
public string PyrUserId
{
get;
set;
}
/// <summary>
/// 借款人用户号
/// </summary>
public string PyeUserId
{
get;
set;
}
/// <summary>
/// 币种
/// </summary>
public string CurCode
{
get;
set;
}
/// <summary>
/// 投标金额
/// </summary>
public string PyrAmt
{
get;
set;
}
/// <summary>
/// 备注
/// </summary>
public string Remark
{
get;
set;
}
/// <summary>
/// 扩展域
/// </summary>
public string Reserved
{
get;
set;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Project3.Models;
namespace Project3.Controllers
{
public class AvailableLaptopsController : Controller
{
private readonly ProjectContext _context;
public AvailableLaptopsController(ProjectContext context)
{
_context = context;
}
// GET: AvailableLaptops
public async Task<IActionResult> Index()
{
var projectContext = _context.AvailableLaptop.Include(a => a.Seller);
return View(await projectContext.ToListAsync());
}
// GET: AvailableLaptops/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var availableLaptop = await _context.AvailableLaptop
.Include(a => a.Seller)
.FirstOrDefaultAsync(m => m.Lid == id);
if (availableLaptop == null)
{
return NotFound();
}
return View(availableLaptop);
}
// GET: AvailableLaptops/Create
public IActionResult Create()
{
ViewData["SellerId"] = new SelectList(_context.TblSeller, "Sid", "Sid");
return View();
}
// POST: AvailableLaptops/Create
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Lid,SellerId,Lname,Lmodel,Lprice")] AvailableLaptop availableLaptop)
{
if (ModelState.IsValid)
{
_context.Add(availableLaptop);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["SellerId"] = new SelectList(_context.TblSeller, "Sid", "Sid", availableLaptop.SellerId);
return View(availableLaptop);
}
// GET: AvailableLaptops/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var availableLaptop = await _context.AvailableLaptop.FindAsync(id);
if (availableLaptop == null)
{
return NotFound();
}
ViewData["SellerId"] = new SelectList(_context.TblSeller, "Sid", "Sid", availableLaptop.SellerId);
return View(availableLaptop);
}
// POST: AvailableLaptops/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Lid,SellerId,Lname,Lmodel,Lprice")] AvailableLaptop availableLaptop)
{
if (id != availableLaptop.Lid)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(availableLaptop);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!AvailableLaptopExists(availableLaptop.Lid))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["SellerId"] = new SelectList(_context.TblSeller, "Sid", "Sid", availableLaptop.SellerId);
return View(availableLaptop);
}
// GET: AvailableLaptops/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var availableLaptop = await _context.AvailableLaptop
.Include(a => a.Seller)
.FirstOrDefaultAsync(m => m.Lid == id);
if (availableLaptop == null)
{
return NotFound();
}
return View(availableLaptop);
}
// POST: AvailableLaptops/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var availableLaptop = await _context.AvailableLaptop.FindAsync(id);
_context.AvailableLaptop.Remove(availableLaptop);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool AvailableLaptopExists(int id)
{
return _context.AvailableLaptop.Any(e => e.Lid == id);
}
}
}
|
using UnityEngine;
public class PlayerBehaviour : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
if (other.tag == "DamageUp")
{
StartCoroutine(GameLogic.instance.DamageBuff());
Destroy(other.gameObject);
}
if (other.tag == "FirerateUp")
{
StartCoroutine(GameLogic.instance.FirerateBuff());
Destroy(other.gameObject);
}
}
}
|
using System;
using System.Collections.Generic;
namespace EPollingApp
{
public class RegistrationUserData
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public int Age { get; set; }
public bool Offence { get; set; }
public string UserPreferredTool { get; set; }
public Guid Id { get; set; }
public string ToolName { get; set; }
}
}
|
namespace NETTRASH.BOT.Telegram.Core
{
public class Result : Core
{
#region Public properties
public bool result { get; set; }
public string description { get; set; }
#endregion
}
}
|
/**
* \file FileIO.cs
* \author Ab-code: Becky Linyan Li, Bowen Zhuang, Sekou Gassama, Tuan Ly
* \date 11-21-2014
* \brief contain the logics of the methods of the FileIO class
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO; /// streamreader/writer
using System.Diagnostics;
using AllEmployees;
namespace Supporting
{
///
/// \class FileIO
/// \brief This class contains the methods necessary to open (for reading or writing) and close Employee DBase files and other files
/// \details try-catch statements are used to detect exceptions, in which cases, user will be notified
///
public class FileIO
{
// private
// TIPs: static won't work here
const string dBaseFileName = "ems.dBase.csv"; ///< \breif the name of database file
const string dBaseFileExtension = "*.csv"; ///< \breif the name of database file extension
const string dBaseFolderName = "DBase"; ///< \breif the name of database folder
const string className = "FileIO";
Logging logger = new Logging(); ///
///
/// \brief Creates specified file and folder if they don't exist
/// \details <b>Details</b>
/// \param fileName - <b>string </b> -the name of the file
/// \param folderName - <b>string </b> -the name of the folder, folder should be under the same directory the executable locates
/// \param fileFilter - <b>string </b> -file's extention, e.g. ".csv" for dBase; ".log" for log
/// \return true <b>bool </b> - if file and folder are created successfully
/// \return false <b>bool </b> - if file and folder are not created
///
public bool CreateFile(string fileName, string folderName, string fileFilter)
{
//create folder if "DBase" doesn't exist
bool isFileExist = false;
string folderPath = Directory.GetCurrentDirectory() + "\\" + folderName + "\\";
try
{
// create the requred folder if it doesn't exist
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
//open and scan folder if it exist
FileInfo[] fileInfo = directoryInfo.GetFiles(fileFilter, SearchOption.AllDirectories);
foreach (FileInfo fileInfoItem in fileInfo)
{
if (fileInfoItem.Name == fileName)
{
isFileExist = true;
}
}
//create the file if it doesn't exist in the DBase folder
if (!isFileExist)
{
// Create a file to write to.
StreamWriter sw = File.CreateText(folderPath + fileName);
sw.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false ;
}
return true;
}
///
/// \brief Creates specified file and folder if they don't exist
/// \details <b>Details</b> Must create file by using CreateFile() before using GetStreamReader()
/// \param fileName - <b>string </b> - specify the name of the file of which the stream reader is returned
/// \param folderName - <b>string </b> -the name of the folder where file is put, folder should be under the same directory the executable locates
/// \param fileFilter - <b>string </b> -the file's extention, e.g. ".csv" for dBase; ".log" for log
/// \return sr <b>StreamReader </b> - when the stream reader of the specified is successfuly achieved
/// \return null if the stream reader is not created
///
private StreamReader GetStreamReader(string fileName, string folderName, string fileFilter)
{
StreamReader sr=null;
//create folder if "DBase" doesn't exist
string folderPath = Directory.GetCurrentDirectory() + "\\" + folderName + "\\";
try
{
sr = new StreamReader(folderPath + fileName);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
return sr;
}
///
/// \brief Creates specified file and folder if they don't exist
/// \details <b>Details</b> Must create file by using CreateFile() before using GetStreamWriter()
/// \param fileName - <b>string </b> - specify the name of the file of which the stream writer is returned
/// \param folderName - <b>string </b> -the name of the folder where file is put, folder should be under the same directory the executable locates
/// \param fileFilter - <b>string </b> -the file's extention, e.g. ".csv" for dBase; ".log" for log
/// \return sr <b>StreamReader </b> - when the stream writer of the specified is successfuly achieved
/// \return null if the stream writer is not achieved
///
public StreamWriter GetStreamWriter(string fileName, string folderName, string fileFilter)
{
StreamWriter sw = null;
string folderPath = Directory.GetCurrentDirectory() + "\\" + folderName + "\\";
try
{
if (folderName=="log")
{
sw = new StreamWriter(folderPath + fileName,true);
}
else
{
sw = new StreamWriter(folderPath + fileName,true);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
return sw;
}
///
/// \brief Read the database file, parse it, and store different types of employees into passed in the passed in data container
/// \details <b>Details</b>
/// \param employees - <b>Dictionary<string, Employee></b> - the data container where data is stored
/// \return true - <b>bool </b> - when the database file was successfully written to the database file
/// \return false - <b>bool </b> - when error occured, the database file was not successfully updated
///
public bool ReadDatabase(ref Dictionary<string, Employee> employees)
{
string line;
UInt32 validCount = 0;
UInt32 invalidCount = 0;
UInt32 totalCount = 0;
const string methodName = "ReadDatabase";
bool ret = false;
try
{
if (employees != null)
{
employees.Clear();
CreateFile(dBaseFileName, dBaseFolderName, dBaseFileExtension);
StreamReader sr = GetStreamReader(dBaseFileName, dBaseFolderName, dBaseFileExtension);
if (sr != null)
{
using (sr)
{
// keep reading line untial the end of the file
while (sr.Peek() >= 0)
{
//read a new line
line = sr.ReadLine();
if (line == "")
{
continue;
}
// start parse
if (line[0] == ';')
{
// isComment, ignore
}
else
{
totalCount++;
// is employee record
// Split string on |
string[] words = line.Split('|');
// put line to employee
if ((words[0] == "F") && (words.Length >= 8))
{
// a fulltime employee record
FulltimeEmployee fEmployee = new FulltimeEmployee();
fEmployee.SetemployeeType(words[0][0]);
fEmployee.SetlastName(words[1]);
fEmployee.SetfirstName(words[2]);
fEmployee.SetsocialInsuranceNumber(words[3]);
fEmployee.SetdateOfBirth(words[4]);
fEmployee.SetdateOfHire(words[5]);
fEmployee.SetdateOfTermination(words[6]);
if (words[7] != "")
{
fEmployee.Setsalary(float.Parse(words[7]));
}
bool validRet = false;
try
{
validRet = fEmployee.Validate();
logger.Log("UIMenu", methodName, "Validate " + fEmployee.GetfirstName() + "-" + fEmployee.GetlastName() + " SIN: " + fEmployee.GetsocialInsuranceNumber(), true);
}
catch(Exception e)
{
logger.Log("UIMenu", methodName, "Validate " + fEmployee.GetfirstName() + "-" + fEmployee.GetlastName() + " SIN: " + fEmployee.GetsocialInsuranceNumber(), false);
Console.WriteLine("Employee with the sin: " + fEmployee.GetsocialInsuranceNumber() + " is not valid - " + e.Message);
}
//if (true)
if (validRet)
{
validCount++;
try
{
// add record to dictionary if it is valide
employees.Add(fEmployee.GetsocialInsuranceNumber(), fEmployee);
//2010-09-01 07:02:00 [FileIO.ParseRecord] Employee - Clarke,Sean (333 333 333)INVALID
logger.Log(className, methodName, "Employee - " + fEmployee.GetlastName() + "," + fEmployee.GetfirstName()
+ " (" + fEmployee.GetsocialInsuranceNumber() + ")", true);
}
catch
{
// catch dictionary.add() exception
logger.Log(className, methodName, "Duplicate or empty SIN for Employee - " + fEmployee.GetlastName() + "," + fEmployee.GetfirstName()
+ " (" + fEmployee.GetsocialInsuranceNumber() + ")", false);
}
}
else
{
// log invalid record
invalidCount++;
logger.Log(className, methodName, "Employee - " + fEmployee.GetlastName() + "," + fEmployee.GetfirstName()
+ " (" + fEmployee.GetsocialInsuranceNumber() + ")", false);
}
}
else if ((words[0] == "P") && (words.Length >= 8))
{
// a part time employee record
ParttimeEmployee pEmployee = new ParttimeEmployee();
pEmployee.SetemployeeType(words[0][0]);
pEmployee.SetlastName(words[1]);
pEmployee.SetfirstName(words[2]);
pEmployee.SetsocialInsuranceNumber(words[3]);
pEmployee.SetdateOfBirth(words[4]);
pEmployee.SetdateOfHire(words[5]);
pEmployee.SetdateOfTermination(words[6]);
pEmployee.SethourlyRate(float.Parse(words[7]));
bool validRet = false;
try
{
validRet = pEmployee.Validate();
logger.Log("UIMenu", methodName, "Validate " + pEmployee.GetfirstName() + "-" + pEmployee.GetlastName() + " SIN: " + pEmployee.GetsocialInsuranceNumber(), true);
}
catch(Exception e)
{
logger.Log("UIMenu", methodName, "Validate " + pEmployee.GetfirstName() + "-" + pEmployee.GetlastName() + " SIN: " + pEmployee.GetsocialInsuranceNumber(), false);
Console.WriteLine("Employee with the sin: " + pEmployee.GetsocialInsuranceNumber() + " is not valid - " + e.Message);
}
//if (true)
if (validRet)
{
validCount++;
try
{
// add record to dictionary if it is valide
employees.Add(pEmployee.GetsocialInsuranceNumber(), pEmployee);
logger.Log(className, methodName, "Employee - " + pEmployee.GetlastName() + "," + pEmployee.GetfirstName()
+ " (" + pEmployee.GetsocialInsuranceNumber() + ") ", true);
}
catch
{
// catch dictionary.add() exception
logger.Log(className, methodName, "Duplicate or empty SIN for Employee - " + pEmployee.GetlastName() + "," + pEmployee.GetfirstName()
+ " (" + pEmployee.GetsocialInsuranceNumber() + ")", false);
}
}
else
{
invalidCount++;
logger.Log(className, methodName, "Employee - " + pEmployee.GetlastName() + "," + pEmployee.GetfirstName()
+ " (" + pEmployee.GetsocialInsuranceNumber() + ") ", false);
}
}
else if ((words[0] == "C") && (words.Length >= 8))
{
// a contract employee record
ContractEmployee cEmployee = new ContractEmployee();
cEmployee.SetemployeeType(words[0][0]);
cEmployee.SetlastName(words[1]);
cEmployee.SetfirstName(words[2]);
cEmployee.SetsocialInsuranceNumber(words[3]);
cEmployee.SetdateOfBirth(words[4]);
cEmployee.SetcontractStartDate(words[5]);
cEmployee.SetcontractStopDate(words[6]);
cEmployee.SetfixedContractAmount(float.Parse(words[7]));
bool validRet = false;
try
{
validRet = cEmployee.Validate();
logger.Log("UIMenu", methodName, "Validate " + cEmployee.GetfirstName() + "-" + cEmployee.GetlastName() + " SIN: " + cEmployee.GetsocialInsuranceNumber(), true);
}
catch (Exception e)
{
logger.Log("UIMenu", methodName, "Validate " + cEmployee.GetfirstName() + "-" + cEmployee.GetlastName() + " SIN: " + cEmployee.GetsocialInsuranceNumber(), false);
Console.WriteLine("Employee with the sin: " + cEmployee.GetsocialInsuranceNumber() + " is not valid - " + e.Message);
}
//if (true)
if (validRet)
{
validCount++;
try
{
// add record to dictionary if it is valide
employees.Add(cEmployee.GetsocialInsuranceNumber(), cEmployee);
logger.Log(className, methodName, "Employee - " + cEmployee.GetlastName() + "," + cEmployee.GetfirstName()
+ " (" + cEmployee.GetsocialInsuranceNumber() + ") ", true);
}
catch
{
// catch dictionary.add() exception
logger.Log(className, methodName, "Duplicate or empty SIN for Employee - " + cEmployee.GetlastName() + "," + cEmployee.GetfirstName()
+ " (" + cEmployee.GetsocialInsuranceNumber() + ")", false);
}
}
else
{
invalidCount++;
logger.Log(className, methodName, "Employee - " + cEmployee.GetlastName() + "," + cEmployee.GetfirstName()
+ " (" + cEmployee.GetsocialInsuranceNumber() + ") ", false);
}
}
else if ((words[0] == "S") && (words.Length >= 7))
{
// a seasonal employee record
SeasonalEmployee sEmployee = new SeasonalEmployee();
sEmployee.SetemployeeType(words[0][0]);
sEmployee.SetlastName(words[1]);
sEmployee.SetfirstName(words[2]);
sEmployee.SetsocialInsuranceNumber(words[3]);
sEmployee.SetdateOfBirth(words[4]);
sEmployee.Setseason(words[5]);
sEmployee.SetpiecePay(float.Parse(words[6]));
bool validRet = false;
try
{
validRet = sEmployee.Validate();
logger.Log("UIMenu", methodName, "Validate " + sEmployee.GetfirstName() + "-" + sEmployee.GetlastName() + " SIN: " + sEmployee.GetsocialInsuranceNumber(), true);
}
catch (Exception e)
{
logger.Log("UIMenu", methodName, "Validate " + sEmployee.GetfirstName() + "-" + sEmployee.GetlastName() + " SIN: " + sEmployee.GetsocialInsuranceNumber(), false);
Console.WriteLine("Employee with the SIN: " + sEmployee.GetsocialInsuranceNumber() + " is not valid. - " + e.Message);
}
//if (true)
if (validRet)
{
validCount++;
try
{
// add record to dictionary if it is valide
employees.Add(sEmployee.GetsocialInsuranceNumber(), sEmployee);
logger.Log(className, methodName, "Employee - " + sEmployee.GetlastName() + "," + sEmployee.GetfirstName()
+ " (" + sEmployee.GetsocialInsuranceNumber() + ") ", true);
}
catch
{
// catch dictionary.add() exception
logger.Log(className, methodName, "Duplicate or empty SIN for Employee - " + sEmployee.GetlastName() + "," + sEmployee.GetfirstName()
+ " (" + sEmployee.GetsocialInsuranceNumber() + ")", false);
}
}
else
{
invalidCount++;
logger.Log(className, methodName, "Employee - " + sEmployee.GetlastName() + "," + sEmployee.GetfirstName()
+ " (" + sEmployee.GetsocialInsuranceNumber() + ") ", false);
}
}
else
{
// invalid record line
invalidCount++;
logger.Log(className, methodName, "Invalid line - " + line , false);
}
}
}
// log read summary
string sEvent = "Valid Record Count: " + validCount.ToString() + ", Invalid Record Count: " +
invalidCount.ToString() + ", Total Read Count: " + totalCount.ToString();
Console.WriteLine(sEvent);
logger.Log(className, methodName, sEvent, true);
ret = true;
}
}
else
{
Console.WriteLine("Stream reader is null");
logger.Log(className, methodName, "Stream reader is null", false);
ret = false;
}
}
else
{
// null object
Console.WriteLine("Employee containter is null;");
logger.Log(className, methodName, "Employee containter is null;", false);
ret = false;
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
logger.Log(className, methodName, e.ToString(), false);
ret = false;
}
return ret;
}
///
/// \brief Read the data container that got passed in, then store different types of employees into the data base file
/// \details <b>Details</b>
/// \param employees - <b>Dictionary<string, Employee></b> - data container where data is stored
/// \return true - <b>bool </b> - when the data container was successfully written to the data base file, the data base file name and its
/// folder name are specified in the class private attributes: dBaseFileName, dBaseFolderName, dBaseFileExtension.
/// The data base folder located under the same folder of the executable
/// \return false - <b>bool </b> - when error occured, the database file was not successfully updated or created
///
public bool WriteDatabase(Dictionary<string, Employee> employees)
{
string folderPath = Directory.GetCurrentDirectory() + "\\" + dBaseFolderName + "\\";
UInt32 validCount = 0;
UInt32 invalidCount = 0;
UInt32 totalCount = 0;
Employee empTemp = new Employee();
string sEvent;
const string methodName = "WriteDatabase";
bool ret = false;
try
{
if (employees != null)
{
CreateFile(dBaseFileName, dBaseFolderName, dBaseFileExtension);
using (StreamWriter sw = new StreamWriter(folderPath + dBaseFileName))
{
sw.Write("");
}
// get employee one by one from dictionary
foreach (KeyValuePair<string, Employee> entry in employees)
{
empTemp = entry.Value;
// validate employess
// if employee type is contract
if (empTemp.GetemployeeType() == 'C')
{
ContractEmployee cEmployeeTemp = (ContractEmployee)empTemp;
bool validRet = false;
try
{
validRet = cEmployeeTemp.Validate();
logger.Log("UIMenu", "WriteDatabase", "Validate " + cEmployeeTemp.GetfirstName() + "-" + cEmployeeTemp.GetlastName() + " SIN: " + cEmployeeTemp.GetsocialInsuranceNumber(), true);
}
catch (Exception e)
{
logger.Log("UIMenu", "WriteDatabase", "Validate " + cEmployeeTemp.GetfirstName() + "-" + cEmployeeTemp.GetlastName() + " SIN: " + cEmployeeTemp.GetsocialInsuranceNumber(), false);
Console.WriteLine("Employee with the sin: "+cEmployeeTemp.GetsocialInsuranceNumber() + " is not valid - " + e.Message);
}
//if(true)
if (validRet)
{
validCount++;
string empRecord = cEmployeeTemp.GetemployeeType().ToString() + "|" + cEmployeeTemp.GetlastName() + "||" +
cEmployeeTemp.GetsocialInsuranceNumber() + "|" + cEmployeeTemp.GetdateOfBirth() + "|" + cEmployeeTemp.GetcontractStartDate() +
"|" + cEmployeeTemp.GetcontractStopDate() + "|" + cEmployeeTemp.GetfixedContractAmount() + "|";
using (StreamWriter sw = GetStreamWriter(dBaseFileName, dBaseFolderName, dBaseFileExtension))
{
sw.WriteLine(empRecord, true);
}
}
else
{
// not a valid employee
invalidCount++;
}
}
// if employee type is full time
else if (empTemp.GetemployeeType() == 'F')
{
FulltimeEmployee fEmployee = (FulltimeEmployee) empTemp;
bool validRet = false;
try
{
validRet = fEmployee.Validate();
logger.Log("UIMenu", "WriteDatabase", "Validate " + fEmployee.GetfirstName() + "-" + fEmployee.GetlastName() + " SIN: " + fEmployee.GetsocialInsuranceNumber(), validRet);
}
catch (Exception e)
{
Console.WriteLine("Employee with the sin: " + fEmployee.GetsocialInsuranceNumber() + " is not valid - " + e.Message);
logger.Log("UIMenu", "WriteDatabase", "Validate " + fEmployee.GetfirstName() + "-" + fEmployee.GetlastName() + " SIN: " + fEmployee.GetsocialInsuranceNumber(), false);
}
//if (true)
if (validRet)
{
validCount++;
string empRecord = fEmployee.GetemployeeType().ToString() + "|" + fEmployee.GetlastName() + "|" + fEmployee.GetfirstName() + "|" +
fEmployee.GetsocialInsuranceNumber() + "|" + fEmployee.GetdateOfBirth() + "|" + fEmployee.GetdateOfHire() + "|" +
fEmployee.GetdateOfTermination() + "|" + fEmployee.Getsalary() + "|";
using (StreamWriter sw = GetStreamWriter(dBaseFileName, dBaseFolderName, dBaseFileExtension))
{
sw.WriteLine(empRecord,true);
}
}
else
{
// not a valid employee
invalidCount++;
}
}
// employee type is part time
else if (empTemp.GetemployeeType() == 'P')
{
ParttimeEmployee pEmployee = (ParttimeEmployee) empTemp;
bool validRet = false;
try
{
validRet = pEmployee.Validate();
logger.Log("UIMenu", "WriteDatabase", "Validate " + pEmployee.GetfirstName() + "-" + pEmployee.GetlastName() + " SIN: " + pEmployee.GetsocialInsuranceNumber(), validRet);
}
catch (Exception e)
{
logger.Log("UIMenu", "WriteDatabase", "Validate " + pEmployee.GetfirstName() + "-" + pEmployee.GetlastName() + " SIN: " + pEmployee.GetsocialInsuranceNumber(), false);
Console.WriteLine(pEmployee.GetsocialInsuranceNumber() + " - " + e.Message);
}
//if (true)
if (validRet)
{
validCount++;
string empRecord = pEmployee.GetemployeeType().ToString() + "|" + pEmployee.GetlastName() + "|" + pEmployee.GetfirstName() + "|" +
pEmployee.GetsocialInsuranceNumber() + "|" + pEmployee.GetdateOfBirth() +
"|" + pEmployee.GetdateOfHire() + "|" + pEmployee.GetdateOfTermination() + "|" + pEmployee.GethourlyRate().ToString() + "|";
using (StreamWriter sw = GetStreamWriter(dBaseFileName, dBaseFolderName, dBaseFileExtension))
{
sw.WriteLine(empRecord, true);
}
}
else
{
// not a valid employee
invalidCount++;
}
}
// employee type is seasonal employee
else if (empTemp.GetemployeeType() == 'S')
{
SeasonalEmployee sEmployee = (SeasonalEmployee) empTemp;
bool validRet = false;
try
{
validRet = sEmployee.Validate();
logger.Log("UIMenu", "WriteDatabase", "Validate " + sEmployee.GetfirstName() + "-" + sEmployee.GetlastName() + " SIN: " + sEmployee.GetsocialInsuranceNumber(), validRet);
}
catch (Exception e)
{
logger.Log("UIMenu", "WriteDatabase", "Validate " + sEmployee.GetfirstName() + "-" + sEmployee.GetlastName() + " SIN: " + sEmployee.GetsocialInsuranceNumber(), false);
Console.WriteLine("Employee with the SIN: "+sEmployee.GetsocialInsuranceNumber() + " is not valid. - " + e.Message);
}
//if (true)
if (validRet)
{
validCount++;
string empRecord = sEmployee.GetemployeeType().ToString() + "|" + sEmployee.GetlastName() + "|" + sEmployee.GetfirstName() + "|"
+ sEmployee.GetsocialInsuranceNumber() + "|" + sEmployee.GetdateOfBirth() + "|"
+ sEmployee.Getseason() + "|" + sEmployee.GetpiecePay().ToString() + "|";
using (StreamWriter sw = GetStreamWriter(dBaseFileName, dBaseFolderName, dBaseFileExtension))
{
sw.WriteLine(empRecord, true);
}
}
else
{
// not a valid employee
invalidCount++;
}
}
else
{
// not a valid employee type
invalidCount++;
}
totalCount++;
// Write the file.
}
//2010-09-01 07:02:00 [FileIO.WriteDataBase] TotalNumberWritten:12,TotalValidRecord:10, TotalInvalidRecord:2
sEvent = "Valid Record Count: " + validCount.ToString() + ", Invalid Record Count: " +
invalidCount.ToString() + ", Total Write Count: " + totalCount.ToString();
Console.WriteLine(sEvent);
logger.Log(className, methodName, sEvent, ret);
ret = true;
}
else
{
logger.Log(className, methodName, "Data container is null", ret);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
logger.Log(className, methodName, e.ToString(), ret);
ret = false ;
}
return ret;
}
///
/// \brief Writes the creation date of the file and comment placeholder to the file contents
/// \details <b>Details</b>
/// \param none
/// \return true - <b>bool </b> - when the creation date of the file and comment placeholder was successfully written to the data
/// base file
/// \return false - <b>bool </b> - when exception occured
///
private bool WriteDateComment ()
{
bool ret = false;
string dateComment = ";DateCreated: " + DateTime.Now + System.Environment.NewLine + ";Further Comments: " + System.Environment.NewLine;
try
{
using (StreamWriter sw = GetStreamWriter(dBaseFileName, dBaseFolderName, dBaseFileExtension))
{
sw.Write(dateComment);
ret = true;
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
ret = false;
}
return ret;
}
}
}
|
using AutoMapper;
using Library.API.Controllers;
using Library.API.Entities;
using Library.API.Helpers;
using Library.API.Models;
using Library.API.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
using Moq;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
namespace Library.API.Testing
{
/**
* 单元测试(单元测试是指验证代码段(如方法或函数)功能的测试,通常由开发人员编写相应的测试方法,以验证代码执行后与预期结果是否一致)
* 单元测试由开发人员完成,主要用来测试程序中的类以及其中的方法是否能够正确运行。在添加单元测试方法时,应遵循Arrange-Act-Assert模式,使测试方法的代码更加规范
* Arrange:为测试进行准备操作,如设置测试数据、变量和环境等。
* Act:执行要测试的方法,如调用要测试的函数和方法
* Assert:断言测试结果,验证被测试方法的输出是否与预期的结果一致。
*
*
* 系统测试是对整个系统进行全面测试,以确认系统正常运行并符合需求
*/
public class AuthorController_UnitTests
{
private AuthorController _authorController;
private Mock<IDistributedCache> _mockDistributedCache;
private Mock<ILogger<AuthorController>> _mockLogger;
private Mock<IUrlHelper> _mockUrlHelper;
private Mock<IMapper> _mockMapper;
private Mock<IAuthorRepository> _mockAuthorRepository;
public AuthorController_UnitTests()
{
_mockDistributedCache = new Mock<IDistributedCache>();
_mockLogger = new Mock<ILogger<AuthorController>>();
_mockUrlHelper = new Mock<IUrlHelper>();
_mockMapper = new Mock<IMapper>();
_mockAuthorRepository = new Mock<IAuthorRepository>();
_authorController = new AuthorController(_mockMapper.Object, _mockDistributedCache.Object, _mockAuthorRepository.Object);
_authorController.ControllerContext = new ControllerContext
{
// 已实例化的AuthorController的Response属性默认为空
// Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(paginationMetadata));会抛异常
// 因此为AuthorController对象的ControllerContext属性设置了一个ControllerContext对象
HttpContext = new DefaultHttpContext()
};
}
[Fact]
public async Task Tets_GetAllAuthors()
{
// Arrange
var author = new Author
{
Id = Guid.NewGuid(),
Name = "Author Test 1",
Email = "author1@xxx.com",
BirthPlace = "Beijing"
};
var authorDto = new AuthorDto
{
Id = author.Id,
Name = author.Name,
Email = author.Email,
BirthPlace = author.BirthPlace
};
var authorList = new List<Author> { author };
var authorDtoList = new List<AuthorDto> { authorDto };
var parameters = new AuthorResourceParameters();
var authors = new PagedList<Author>(authorList, totalCount: authorList.Count, pageNumber: parameters.PageNumber, pageSize: parameters.PageSize);
_mockAuthorRepository.Setup(m => m.GetAllAsync(It.IsAny<AuthorResourceParameters>())).Returns(Task.FromResult(authors));
_mockMapper.Setup(m => m.Map<IEnumerable<AuthorDto>>(It.IsAny<IEnumerable<Author>>())).Returns(authorDtoList);
_mockUrlHelper.Setup(m => m.Link(It.IsAny<string>(), It.IsAny<object>())).Returns("demo url");
_authorController.Url = _mockUrlHelper.Object;
// Act
var actionResult = await _authorController.GetAuthorsAsync(parameters);
// Assert
ResourceCollect<AuthorDto> resourceCollect = actionResult.Value;
Assert.True(1 == resourceCollect.Items.Count);
Assert.Equal(authorDto, resourceCollect.Items[0]);
Assert.True(_authorController.Response.Headers.ContainsKey("X-Pagination"));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Functional.Maybe;
namespace OrangeApple.WPF.ViewModels
{
public class PivotChooser<T>
{
private readonly IList<T> items;
public PivotChooser(IList<T> items)
{
this.items = items;
}
public Maybe<T> ItemBetween(Maybe<T> x, Maybe<T> y)
{
if (items.Count == 0)
{
return Maybe<T>.Nothing;
}
if (!x.HasValue)
{
return items.First().ToMaybe();
}
if (!y.HasValue)
{
return items.Last().ToMaybe();
}
var xIndex = items.IndexOf(x.Value);
var yIndex = items.IndexOf(y.Value);
if (xIndex < 0)
{
throw new InvalidOperationException($"{x.Value} not found in items");
}
if (yIndex < 0)
{
throw new InvalidOperationException($"{x.Value} not found in items");
}
if (xIndex > yIndex)
{
throw new InvalidOperationException($"{x.Value} should be before {y.Value} in the items list");
}
var distanceBetweenItems = yIndex - xIndex;
if (distanceBetweenItems == 1)
{
// There's nothing between these items
return Maybe<T>.Nothing;
}
// Pick an item half way between x and y in the list
return items[xIndex + (distanceBetweenItems / 2)].ToMaybe();
}
}
} |
using gView.Framework.Data;
using gView.Framework.system.UI;
using gView.Framework.UI;
using System.Threading.Tasks;
namespace gView.Win.DataSources.VectorTileCache.UI.Explorer
{
[gView.Framework.system.RegisterPlugIn("23781302-2B04-4ECF-82A8-246A0C0DCA42")]
public class VectorTileCacheLayerExplorerObject : ExplorerObjectCls, IExplorerSimpleObject, ISerializableExplorerObject
{
private string _fcname = "";
private IExplorerIcon _icon = new Icons.VectorTileCacheDatasetIcon();
private IFeatureClass _fc = null;
private VectorTileCacheDatasetExplorerObject _parent = null;
public VectorTileCacheLayerExplorerObject() : base(null, typeof(FeatureClass), 1) { }
public VectorTileCacheLayerExplorerObject(VectorTileCacheDatasetExplorerObject parent, IDatasetElement element)
: base(parent, typeof(FeatureClass), 1)
{
if (element == null)
{
return;
}
_parent = parent;
_fcname = element.Title;
if (element.Class is IFeatureClass)
{
_fc = (IFeatureClass)element.Class;
}
}
#region IExplorerObject Members
public string Name
{
get { return _fcname; }
}
public string FullName
{
get
{
return _parent.FullName + @"\" + _fcname;
}
}
public string Type
{
get { return "Vector Tile Cache Layer"; }
}
public IExplorerIcon Icon
{
get { return _icon; }
}
public void Dispose()
{
if (_fc != null)
{
_fc = null;
}
}
public Task<object> GetInstanceAsync()
{
return Task.FromResult<object>(_fc);
}
#endregion
#region ISerializableExplorerObject Member
async public Task<IExplorerObject> CreateInstanceByFullName(string FullName, ISerializableExplorerObjectCache cache)
{
if (cache.Contains(FullName))
{
return cache[FullName];
}
FullName = FullName.Replace("/", @"\");
int lastIndex = FullName.LastIndexOf(@"\");
if (lastIndex == -1)
{
return null;
}
string[] parts = FullName.Split('\\');
if (parts.Length != 3)
{
return null;
}
var parent = new VectorTileCacheDatasetExplorerObject();
parent = await parent.CreateInstanceByFullName(parts[0] + @"\" + parts[1], cache) as VectorTileCacheDatasetExplorerObject;
if (parent == null)
{
return null;
}
var childObjects = await parent.ChildObjects();
if (childObjects != null)
{
foreach (IExplorerObject exObject in childObjects)
{
if (exObject.Name == parts[2])
{
cache.Append(exObject);
return exObject;
}
}
}
return null;
}
#endregion
}
}
|
using System;
using System.Linq;
using System.Collections.Generic;
namespace E10
{
class Program
{
static void Main(string[] args)
{
List<Exalumnos> exalumnos = new List<Exalumnos>();
Exalumnos e1 = new Exalumnos(6, 400000, 8);
exalumnos.Add(e1);
Exalumnos e2 = new Exalumnos(2, 400000, 5);
exalumnos.Add(e2);
Exalumnos e3 = new Exalumnos(2, 250000, 6);
exalumnos.Add(e3);
Exalumnos e4 = new Exalumnos(4, 350000, 9);
exalumnos.Add(e4);
Exalumnos e5 = new Exalumnos(2, 250000, 2);
exalumnos.Add(e5);
Exalumnos e6 = new Exalumnos(3, 850000, 3);
exalumnos.Add(e6);
bool fueExitoso = false;
switch(exalumnos.Count(x => x.CantidadDeIdiomasQueHabla > 5)){
case 0:
fueExitoso = false;
break;
default:
if(exalumnos.Count(x => x.CantidadDeIdiomasQueHabla >= 2) == exalumnos.Count()){
switch(exalumnos.Count(x => x.CantidadDePaisesVisitados > 3)){
case 1:
case 2:
case 3:
fueExitoso = false;
break;
default:
switch(exalumnos.Count(x => x.CuantoGana > 200000)){
case 1:
case 2:
case 3:
case 4:
case 5:
fueExitoso = false;
break;
default:
fueExitoso = true;
break;
}
break;
}
break;
}
break;
}
Console.WriteLine("El curso fue exitoso? " + fueExitoso);
}
}
}
|
using StackExchange.Redis.Extensions.Core.Configuration;
using System;
using System.Collections.Generic;
using System.Text;
namespace Shared.ConnectionConfig
{
public class RedisConfig
{
public RedisConfiguration redisConfiguration { get; set; }
public static RedisConfig Instance { get; } = new RedisConfig();
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.DirectoryServices.ActiveDirectory;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml.Linq;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using log4net;
using Microsoft.Build.Utilities;
namespace DotNetNuke.MSBuild.Tasks
{
public class CodePlexUpdate : Task
{
public string TFSServer { get; set; }
public string TFSRoot { get; set; }
public string TFSMappedFolder { get; set; }
public string TFSCommitter { get; set; }
public string CPServer { get; set; }
public string CPRoot { get; set; }
public string TempFolder { get; set; }
public override bool Execute()
{
if (!File.Exists(@"c:\lastrun.txt"))
{
var sw = File.CreateText(@"c:\lastrun.txt");
sw.Write(DateTime.Today.AddDays(-1).Ticks);
sw.Close();
}
long ticks;
var sw2 = File.OpenText(@"c:\lastrun.txt");
long.TryParse(sw2.ReadToEnd(), out ticks);
sw2.Close();
var fromDate = new DateTime(ticks);
#pragma warning disable 612,618
TeamFoundationServer tfs = TeamFoundationServerFactory.GetServer(TFSServer);
#pragma warning restore 612,618
var vcs = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));
string path = TFSRoot;
VersionSpec version = VersionSpec.Latest;
const int deletionId = 0;
const RecursionType recursion = RecursionType.Full;
string user = null;
VersionSpec versionFrom = new DateVersionSpec(fromDate);
VersionSpec versionTo = null;
const int maxCount = 100;
const bool includeChanges = true;
const bool slotMode = true;
const bool includeDownloadInfo = true;
IEnumerable allChangeSets =
vcs.QueryHistory(path,
version,
deletionId,
recursion,
user,
versionFrom,
versionTo,
maxCount,
includeChanges,
slotMode,
includeDownloadInfo);
var changes = new List<Change>();
var comments = new StringBuilder();
foreach (var changeSet in allChangeSets.Cast<Changeset>().Where(changeSet => changeSet != null && changeSet.Committer != TFSCommitter))
{
comments.Append(string.Format("{0}", changeSet.Comment));
changes.AddRange(changeSet.Changes.Where(change => change.Item.ServerItem.Contains("Community") || change.Item.ServerItem.Contains("Website") || change.Item.ServerItem.Contains("packages")));
}
if (Directory.Exists(TempFolder))
{
Directory.Delete(TempFolder,true);
}
Directory.CreateDirectory(TempFolder);
var networkCredential = new NetworkCredential("", "", "snd"); //TODO: need fill the credentials
using (var tfsCodePlex = new TeamFoundationServer(CPServer, networkCredential))
{
var vcsCodePlex = tfsCodePlex.GetService(typeof(VersionControlServer)) as VersionControlServer;
//vcsCodePlex.DeleteWorkspace("CodePlex Temporary Workspace", vcsCodePlex.AuthenticatedUser);
var workspace = vcsCodePlex.CreateWorkspace("CodePlex Temporary Workspace", vcsCodePlex.AuthenticatedUser);
try
{
var workingFolder = new WorkingFolder(CPRoot, TempFolder);
workspace.CreateMapping(workingFolder);
var listDistinctChanges = new List<Change>();
foreach (Change change in changes.OrderByDescending(s => s.Item.CheckinDate))
{
if (listDistinctChanges.Count(s => s.Item.ServerItem == change.Item.ServerItem) == 0)
{
listDistinctChanges.Add(change);
}
}
foreach (Change change in listDistinctChanges)
{
var changedFileName = change.Item.ServerItem.Replace(TFSRoot, TFSMappedFolder);
var destFileName = change.Item.ServerItem.Replace(TFSRoot, TempFolder);
var destSccName = change.Item.ServerItem.Replace(TFSRoot, CPRoot);
var changeSwitch = change.ChangeType.ToString().Trim();
switch (changeSwitch)
{
case "Add, Edit, Encoding":
Directory.CreateDirectory(destFileName.Remove(destFileName.LastIndexOf("/", System.StringComparison.InvariantCulture)));
if (File.Exists(changedFileName))
{
File.Copy(changedFileName, destFileName, true);
workspace.PendAdd(destFileName);
}
break;
case "Edit":
workspace.Get(new GetRequest(destSccName, RecursionType.None, VersionSpec.Latest), GetOptions.Overwrite);
if (File.Exists(changedFileName))
{
workspace.PendEdit(destSccName);
File.Copy(changedFileName, destFileName, true);
}
break;
case "Delete":
workspace.Get(new GetRequest(destSccName, RecursionType.None, VersionSpec.Latest), GetOptions.Overwrite);
workspace.PendDelete(destSccName);
File.Delete(destFileName);
break;
}
Debug.Print(changedFileName);
Debug.Print(destFileName);
}
var pendingChanges = workspace.GetPendingChanges();
if (pendingChanges.Any())
{
workspace.CheckIn(pendingChanges, comments.ToString());
}
}
catch (Exception ex)
{
LogFormat("Error", ex.Message);
}
finally
{
var sw = File.CreateText(@"c:\lastrun.txt");
sw.Write(DateTime.Now.Ticks);
sw.Close();
workspace.Delete();
}
}
return true;
}
private void LogFormat(string level, string message, params object[] args)
{
if (BuildEngine != null)
{
switch (level)
{
case "Message":
Log.LogMessage(message, args);
break;
case "Error":
Log.LogError(message, args);
break;
}
}
else
{
Debug.Print(message, args);
}
}
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace MeterReader.Controllers
{
using System;
using System.Linq;
using FoodDeliveryBot.Repositories;
using MeterReader.Enums;
using MeterReader.Models;
using MeterReader.Services;
using MeterReader.Stubs;
[Route("api/[controller]")]
public class IndicationController : Controller
{
private readonly IndicationService indicationService;
private readonly RateService rateService;
public IndicationController(IndicationService service, RateService rateService)
{
this.indicationService = service;
this.rateService = rateService;
}
/// <summary>
///
/// </summary>
/// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
[HttpGet]
public async Task<IEnumerable<Indication>> GetAll()
{
return (await this.indicationService.GetAll()).OrderBy(e => e.Date);
}
[HttpGet("byType/{type}")]
public async Task<IEnumerable<Indication>> GetByType(MeterType type)
{
return (await this.indicationService.GetAll()).OrderBy(e => e.Date);
}
[HttpGet("{id}")]
public async Task<Indication> Get(int id)
{
return await this.indicationService.Get(id);
}
[HttpPost]
public async Task<Indication> Post([FromBody]Indication entity)
{
return await this.indicationService.Insert(entity);
}
[HttpPut]
public async Task<bool> Put([FromBody]Indication entity)
{
return await this.indicationService.Update(entity);
}
[HttpDelete("{id}")]
public async Task<bool> Delete(int id)
{
return await this.indicationService.Delete(id);
}
/// <summary>
/// Очищает базу и заполняет стабами по типу счетчика.
/// </summary>
/// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
[HttpGet("FillStubs/{type}/{year}")]
public async Task<bool> FillStubs(MeterType type, int year)
{
try
{
await this.rateService.Insert(StubsProvider.GetRate(type));
var old = await this.indicationService.GetByType(type);
foreach (var entity in old)
{
if (entity.Date.Year == year)
{
await this.indicationService.Delete(entity.Id);
}
}
foreach (var indication in StubsProvider.GetIndications(type, StubsProvider.GetRate(type), year))
{
await this.indicationService.Insert(indication);
}
return true;
}
catch (Exception e)
{
return false;
}
}
}
}
|
using Anywhere2Go.Library;
using log4net;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Linq;
using TransferData.Business.Dto;
using TransferData.Business.Interface;
using TransferData.Business.MappingMasterData;
namespace TransferData.Business.Service
{
public class TransferSEICService : ITransferService
{
private static readonly ILog logger = LogManager.GetLogger(typeof(TransferSEICService));
private readonly string apiDomain = Configurator.DomainAPIConfig.SEICAPI;
private readonly string apiEndpointSaveDataToInsurer = "v2/taskintegrate/SaveDataTaskAssignClaimDi";
private readonly string apiEndpointUploadImage = "v2/taskintegrate/upload_image";
private readonly string InsurerID = "IN0048";
private TaskSEICDto taskSEICData;
private TaskBikeDto taskBikeDto;
private MappingProvinceLogic mappingProvinceLogic;
private MappingAmphurLogic mappingAmphurLogic;
private MappingDistrictLogic mappingDistrictLogic;
private MappingCarBrandLogic mappingCarBrandLogic;
private MappingCarModelLogic mappingCarModelLogic;
private MappingCarCapacityLogic mappingCarCapacityLogic;
private MappingDamageLevelLogic mappingDamageLevelLogic;
private MappingDamagePartLogic mappingDamagePartLogic;
private MappingTitleLogic mappingTitleLogic;
private MappingRelationshipLogic mappingrelationshipLogic;
private MappingDriverLicenseTypeLogic mappingDriverLicenseTypeLogic;
private MappingInsurerLogic mappingInsurerLogic;
private MappingAccidentTypeLogic mappingAccidentTypeLogic;
private MappingWoundedTypeLogic mappingWoundedTypeLogic;
private MappingResultCaseLogic mappingResultCaseLogic;
private MappingPictureTypeLogic mappingPictureTypeLogic;
public TransferSEICService()
{
mappingProvinceLogic = new MappingProvinceLogic(InsurerID);
mappingAmphurLogic = new MappingAmphurLogic(InsurerID);
mappingDistrictLogic = new MappingDistrictLogic(InsurerID);
mappingCarBrandLogic = new MappingCarBrandLogic(InsurerID);
mappingCarModelLogic = new MappingCarModelLogic(InsurerID);
mappingCarCapacityLogic = new MappingCarCapacityLogic(InsurerID);
mappingDamageLevelLogic = new MappingDamageLevelLogic(InsurerID);
mappingDamagePartLogic = new MappingDamagePartLogic(InsurerID);
mappingTitleLogic = new MappingTitleLogic(InsurerID);
mappingrelationshipLogic = new MappingRelationshipLogic(InsurerID);
mappingDriverLicenseTypeLogic = new MappingDriverLicenseTypeLogic(InsurerID);
mappingAmphurLogic = new MappingAmphurLogic(InsurerID);
mappingInsurerLogic = new MappingInsurerLogic(InsurerID);
mappingAccidentTypeLogic = new MappingAccidentTypeLogic(InsurerID);
mappingWoundedTypeLogic = new MappingWoundedTypeLogic(InsurerID);
mappingResultCaseLogic = new MappingResultCaseLogic(InsurerID);
mappingPictureTypeLogic = new MappingPictureTypeLogic(InsurerID);
}
public BaseResult<bool> TransferData(TaskBikeDto taskBike)
{
taskBikeDto = taskBike;
this.TransfromData();
var response = this.SendDataToInsurer();
if (response.Result)
{
this.SendImageToInsurer();
}
return response;
}
public void TransfromData()
{
TaskBikeResult taskBikeData = taskBikeDto.Result;
taskSEICData = new TaskSEICDto();
taskSEICData.TaskID = taskBikeData.SEICTaskRef;
TransfromCarInsurer(taskBikeData);
TransfromCarParties(taskBikeData);
TransfromSummaryOfCase(taskBikeData);
TransfromPropertyDamages(taskBikeData);
TransfromWoundeds(taskBikeData);
TransfromSurveyorCharges(taskBikeData);
}
public BaseResult<bool> SendDataToInsurer()
{
BaseResult<bool> apiResponse = new BaseResult<bool>();
ApiHttpProcessor apiProcessor = new ApiHttpProcessor("");
string url = ApiUrlHelper.AppendUrlAsPath(apiDomain, apiEndpointSaveDataToInsurer);
string postBody = JsonConvert.SerializeObject(taskSEICData);
try
{
ApiResponse response = apiProcessor.ExecutePOST(url, new StringContent(postBody, Encoding.UTF8, "application/json"), new MediaTypeWithQualityHeaderValue("application/json"));
string requestData = postBody;
string responseData = JsonConvert.SerializeObject(response);
string taskId = taskBikeDto.Result.TaskId;
string status = "error";
if (response.StatusCode == HttpStatusCode.OK)
{
status = "success";
if (!string.IsNullOrEmpty(response.ResponseContent))
{
apiResponse = JsonConvert.DeserializeObject<BaseResult<bool>>(response.ResponseContent);
}
}
else
{
logger.Error("TaskID : " + taskId);
apiResponse.StatusCode = response.StatusCode.ToString();
apiResponse.MessageBody = response.ResponseContent;
}
log4net.LogicalThreadContext.Properties["taskId"] = taskId;
log4net.LogicalThreadContext.Properties["requestData"] = requestData;
log4net.LogicalThreadContext.Properties["responseData"] = responseData;
log4net.LogicalThreadContext.Properties["status"] = status;
logger.Warn("SendDataToInsurer Success TaskID : " + taskId);
log4net.LogicalThreadContext.Properties.Clear();
}
catch (Exception ex)
{
apiResponse.StatusCode = "500";
apiResponse.MessageBody = ex.Message;
}
return apiResponse;
}
public BaseResult<bool> SendImageToInsurer()
{
BaseResult<bool> sendImages = new BaseResult<bool>();
string taskId = taskSEICData.TaskID;
IList<TaskPicture> taskPictures = taskBikeDto.Result.TaskPictureList;
string url = ApiUrlHelper.AppendUrlAsPath(apiDomain, apiEndpointUploadImage);
if (taskPictures != null && taskPictures.Count > 0)
{
foreach (var item in taskPictures)
{
using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
using (WebClient webClient = new WebClient())
{
byte[] data = webClient.DownloadData(item.PicturePath);
content.Add(CreateFileContent(new MemoryStream(data), "image", "image/jpeg"));
content.Add(new StringContent(taskId), "task_id");
content.Add(new StringContent(mappingPictureTypeLogic.GetByClaimDiKey(item.PictureType.Id)), "picture_type_id");
content.Add(new StringContent(item.PictureDesc), "picture_desc");
content.Add(new StringContent(item.Latitude), "latitude");
content.Add(new StringContent(item.Longitude), "longitude");
content.Add(new StringContent(item.Sequence.ToString()), "sequence");
content.Add(new StringContent(item.DamageLevelCode), "damage_level_code");
content.Add(new StringContent(item.PictureName), "picture_name");
content.Add(new StringContent(item.PictureToken), "picture_token");
using (var message = client.PostAsync(url, content))
{
var input = message.Result.Content.ReadAsStringAsync().Result;
}
}
}
}
}
}
return sendImages;
}
private void TransfromCarInsurer(TaskBikeResult taskBikeData)
{
taskSEICData.CarInsurer = new APICarInsurer();
APICarInformation carInsurerInfoData = new APICarInformation();
var carInsurerInfoBike = taskBikeData.CarInsurer.CarInsurerInfo;
carInsurerInfoData.CarRegis = carInsurerInfoBike.CarRegis;
if (carInsurerInfoBike.CarRegisProvince != null)
{
carInsurerInfoData.CarRegisProvice = new APIProvince();
carInsurerInfoData.CarRegisProvice.provinceCode = mappingProvinceLogic.GetByClaimDiKey(carInsurerInfoBike.CarRegisProvince.Id);
}
carInsurerInfoData.CarChassis = carInsurerInfoBike.CarChassis;
if (carInsurerInfoBike.CarBrand != null)
{
carInsurerInfoData.CarBrand = new APICarBrand
{
carBrandId = mappingCarBrandLogic.GetByClaimDiKey(carInsurerInfoBike.CarBrand.Id)
};
}
if (carInsurerInfoBike.CarModel != null)
{
carInsurerInfoData.CarModel = new APICarModel
{
carModelId = mappingCarModelLogic.GetByClaimDiKey(carInsurerInfoBike.CarModel.Id)
};
}
if (carInsurerInfoBike.CarCapacity != null)
{
int capacityCode;
if (int.TryParse(mappingCarCapacityLogic.GetByClaimDiKey(carInsurerInfoBike.CarCapacity.Id.ToString()), out capacityCode))
{
carInsurerInfoData.CarCapacity = new SyncCarCapacity
{
CapacityCode = capacityCode
};
}
}
taskSEICData.CarInsurer.CarInsurerInfo = carInsurerInfoData;
var carInsurerDriverBike = taskBikeData.CarInsurer.CarInsurerDriver;
if (carInsurerDriverBike != null)
{
APICarDriver carInsurerDriverData = new APICarDriver();
if (carInsurerDriverBike.CarDriverNameInfo != null)
{
carInsurerDriverData.CarDriverNameInfo = new APIPersonInfo
{
FirstName = carInsurerDriverBike.CarDriverNameInfo.FirstName,
LastName = carInsurerDriverBike.CarDriverNameInfo.LastName,
Title = carInsurerDriverBike.CarDriverNameInfo.Title != null ? new SyncTitleName
{
TitleCode = mappingTitleLogic.GetByClaimDiKey(carInsurerDriverBike.CarDriverNameInfo.Title.Id)
} : null
};
}
carInsurerDriverData.CarDriverGender = carInsurerDriverBike.CarDriverGender;
carInsurerDriverData.CarDriverIdCard = carInsurerDriverBike.CarDriverIdcard;
carInsurerDriverData.CarDriverTel = carInsurerDriverBike.CarDriverTel;
if (carInsurerDriverBike.CarDriverRelationship != null)
{
carInsurerDriverData.CarDriverRelationship = new SyncRelationship
{
RelationshipCode = mappingrelationshipLogic.GetByClaimDiKey(carInsurerDriverBike.CarDriverRelationship.Id)
};
}
if (carInsurerDriverBike.CarDriverLocation != null)
{
carInsurerDriverData.CarDriverLocation = new APILocationPlace();
if (carInsurerDriverBike.CarDriverLocation.Province != null)
{
carInsurerDriverData.CarDriverLocation.Province = new SyncProvince
{
ProvinceCode = mappingProvinceLogic.GetByClaimDiKey(carInsurerDriverBike.CarDriverLocation.Province.Id)
};
}
if (carInsurerDriverBike.CarDriverLocation.Aumphur != null)
{
carInsurerDriverData.CarDriverLocation.Amphur = new SyncAmphur
{
AmphurCode = mappingAmphurLogic.GetByClaimDiKey(carInsurerDriverBike.CarDriverLocation.Aumphur.Id)
};
}
if (carInsurerDriverBike.CarDriverLocation.District != null)
{
carInsurerDriverData.CarDriverLocation.District = new SyncDistrict
{
DistrictCode = mappingDistrictLogic.GetByClaimDiKey(carInsurerDriverBike.CarDriverLocation.District.Id)
};
}
carInsurerDriverData.CarDriverLicenseCard = carInsurerDriverBike.CarDriverLicenseCard;
carInsurerDriverData.CarDriverLicenseCardExpireDate = carInsurerDriverBike.CarDriverLicenseCardExpireDate;
carInsurerDriverData.CarDriverLicenseCardIssuedDate = carInsurerDriverBike.CarDriverLicenseCardIssuedDate;
if (carInsurerDriverBike.CarDriverLicenseCardType != null)
{
int carDriverLicenseCardTypeId;
if (int.TryParse(mappingDriverLicenseTypeLogic.GetByClaimDiKey(carInsurerDriverBike.CarDriverLicenseCardType.Id.ToString()), out carDriverLicenseCardTypeId))
{
carInsurerDriverData.CarDriverLicenseCardType = new SyncLicenseCardType
{
SyncLicenseCardTypeId = carDriverLicenseCardTypeId
};
}
}
taskSEICData.CarInsurer.CarInsurerDriver = carInsurerDriverData;
}
if (taskSEICData.Na == null)
{
taskSEICData.Na = new APITaskNA();
}
taskSEICData.CarInsurer.SummaryDamageInsurerCar = taskBikeData.CarInsurer.SummaryDamageInsurerCar;
if (taskBikeData.CarInsurer.CarInsurerDamages != null)
{
taskSEICData.CarInsurer.CarInsurerDamages = new System.Collections.Generic.List<APICarDamage>();
foreach (var item in taskBikeData.CarInsurer.CarInsurerDamages)
{
APICarDamage carDamage = new APICarDamage();
carDamage.DamagePartText = item.CarDamagePartText;
if (item.CarDamageLevel != null)
{
carDamage.DamageLevel = new SyncDamageLevel
{
DamageLevelCode = mappingDamageLevelLogic.GetByClaimDiKey(item.CarDamageLevel.Id)
};
}
if (item.CarDamagePart != null)
{
int damagePartId;
if (int.TryParse(mappingDamagePartLogic.GetByClaimDiKey(item.CarDamagePart.Id.ToString()), out damagePartId))
{
carDamage.DamagePart = new SyncDamagePart
{
PicturePartId = damagePartId
};
}
}
taskSEICData.CarInsurer.CarInsurerDamages.Add(carDamage);
}
}
}
}
private void TransfromCarParties(TaskBikeResult taskBikeData)
{
if (taskBikeData.CarParties != null)
{
taskSEICData.CarParties = new System.Collections.Generic.List<APICarParty>();
foreach (var item in taskBikeData.CarParties)
{
APICarParty carPartyData = new APICarParty();
carPartyData.CarPartyInfo = new APICarInformation();
if (item.CarPartyInfo.CarPolicyInsurer != null)
{
carPartyData.CarPartyInfo.CarPolicyInsurer = new APIInsurer
{
InsurerId = mappingInsurerLogic.GetByClaimDiKey(item.CarPartyInfo.CarPolicyInsurer.Id)
};
}
carPartyData.CarPartyInfo.CarRegis = item.CarPartyInfo.CarRegis;
if (item.CarPartyInfo.CarRegisProvince != null)
{
carPartyData.CarPartyInfo.CarRegisProvice = new APIProvince
{
provinceCode = mappingProvinceLogic.GetByClaimDiKey(item.CarPartyInfo.CarRegisProvince.Id)
};
}
if (item.CarPartyInfo.CarBrand != null)
{
carPartyData.CarPartyInfo.CarBrand = new APICarBrand
{
carBrandId = mappingCarBrandLogic.GetByClaimDiKey(item.CarPartyInfo.CarBrand.Id)
};
}
if (item.CarPartyInfo.CarModel != null)
{
carPartyData.CarPartyInfo.CarModel = new APICarModel
{
carModelId = mappingCarModelLogic.GetByClaimDiKey(item.CarPartyInfo.CarModel.Id)
};
}
if (item.CarPartyInfo.CarCapacity != null)
{
int capacityCode;
if (int.TryParse(mappingCarCapacityLogic.GetByClaimDiKey(item.CarPartyInfo.CarCapacity.Id.ToString()), out capacityCode))
{
carPartyData.CarPartyInfo.CarCapacity = new SyncCarCapacity
{
CapacityCode = capacityCode
};
}
}
if (item.CarPartyDriver != null)
{
carPartyData.CarPartyDriver = new APICarDriver();
if (item.CarPartyDriver.CarDriverNameInfo != null)
{
carPartyData.CarPartyDriver.CarDriverNameInfo = new APIPersonInfo();
carPartyData.CarPartyDriver.CarDriverNameInfo.FirstName = item.CarPartyDriver.CarDriverNameInfo.FirstName;
carPartyData.CarPartyDriver.CarDriverNameInfo.LastName = item.CarPartyDriver.CarDriverNameInfo.LastName;
if (item.CarPartyDriver.CarDriverNameInfo.Title != null)
{
carPartyData.CarPartyDriver.CarDriverNameInfo.Title = new SyncTitleName
{
TitleCode = mappingTitleLogic.GetByClaimDiKey(item.CarPartyDriver.CarDriverNameInfo.Title.Id)
};
}
}
carPartyData.CarPartyDriver.CarDriverGender = item.CarPartyDriver.CarDriverGender;
if (item.CarPartyDriver.CarDriverRelationship != null)
{
carPartyData.CarPartyDriver.CarDriverRelationship = new SyncRelationship
{
RelationshipCode = mappingrelationshipLogic.GetByClaimDiKey(item.CarPartyDriver.CarDriverRelationship.Id)
};
}
if (item.CarPartyDriver.CarDriverLocation != null)
{
carPartyData.CarPartyDriver.CarDriverLocation = new APILocationPlace();
if (item.CarPartyDriver.CarDriverLocation.Province != null)
{
carPartyData.CarPartyDriver.CarDriverLocation.Province = new SyncProvince
{
ProvinceCode = mappingProvinceLogic.GetByClaimDiKey(item.CarPartyDriver.CarDriverLocation.Province.Id)
};
}
if (item.CarPartyDriver.CarDriverLocation.Aumphur != null)
{
carPartyData.CarPartyDriver.CarDriverLocation.Amphur = new SyncAmphur
{
AmphurCode = mappingAmphurLogic.GetByClaimDiKey(item.CarPartyDriver.CarDriverLocation.Aumphur.Id)
};
}
if (item.CarPartyDriver.CarDriverLocation.District != null)
{
carPartyData.CarPartyDriver.CarDriverLocation.District = new SyncDistrict
{
DistrictCode = mappingDistrictLogic.GetByClaimDiKey(item.CarPartyDriver.CarDriverLocation.District.Id)
};
}
}
}
carPartyData.SummaryDamageCar = item.SummaryDamageCar;
if (item.CarPartyDamages != null)
{
carPartyData.CarPartyDamages = new System.Collections.Generic.List<APICarDamage>();
foreach (var carPartyDamage in item.CarPartyDamages)
{
APICarDamage carDamage = new APICarDamage();
carDamage.DamagePartText = carPartyDamage.CarDamagePartText;
if (carPartyDamage.CarDamageLevel != null)
{
carDamage.DamageLevel = new SyncDamageLevel
{
DamageLevelCode = mappingDamageLevelLogic.GetByClaimDiKey(carPartyDamage.CarDamageLevel.Id)
};
}
if (carPartyDamage.CarDamagePart != null)
{
int damagePartId;
if (int.TryParse(mappingDamagePartLogic.GetByClaimDiKey(carPartyDamage.CarDamagePart.Id.ToString()), out damagePartId))
{
carDamage.DamagePart = new SyncDamagePart
{
PicturePartId = damagePartId
};
}
}
carPartyData.CarPartyDamages.Add(carDamage);
}
}
if (item.CarPartyDriver.CarDriverLocation != null)
{
carPartyData.CarPartyDriver.CarDriverLocation = new APILocationPlace();
if (item.CarPartyDriver.CarDriverLocation.Province != null)
{
carPartyData.CarPartyDriver.CarDriverLocation.Province = new SyncProvince
{
ProvinceCode = mappingProvinceLogic.GetByClaimDiKey(item.CarPartyDriver.CarDriverLocation.Province.Id)
};
}
if (item.CarPartyDriver.CarDriverLocation.Aumphur != null)
{
carPartyData.CarPartyDriver.CarDriverLocation.Amphur = new SyncAmphur
{
AmphurCode = mappingAmphurLogic.GetByClaimDiKey(item.CarPartyDriver.CarDriverLocation.Aumphur.Id)
};
}
if (item.CarPartyDriver.CarDriverLocation.District != null)
{
carPartyData.CarPartyDriver.CarDriverLocation.District = new SyncDistrict
{
DistrictCode = mappingDistrictLogic.GetByClaimDiKey(item.CarPartyDriver.CarDriverLocation.District.Id)
};
}
}
taskSEICData.CarParties.Add(carPartyData);
}
}
}
private void TransfromSummaryOfCase(TaskBikeResult taskBikeData)
{
if (taskBikeData.SummaryOfCase != null)
{
taskSEICData.Na = new APITaskNA();
taskSEICData.Na.ResultsCaseId = taskBikeData.SummaryOfCase.ResultCaseId;
var summary = taskBikeData.SummaryOfCase;
taskSEICData.SummaryOfCase = new APISummaryOfCase
{
AccidentDate = summary.AccidentDate,
AccidentDateText = summary.AccidentDateText,
AccidentTimeText = summary.AccidentTimeText,
};
if (summary.AccidentType != null)
{
taskSEICData.SummaryOfCase.AccidentType = new SyncAccidentType();
var result = mappingAccidentTypeLogic.GetByClaimDiKey(taskBikeData.SummaryOfCase.AccidentType.Id.ToString());
taskSEICData.SummaryOfCase.AccidentType.SyncAccidentTypeId = string.IsNullOrEmpty(result) ? 0 : int.Parse(result);
}
if (summary.ResultCaseId != null)
{
taskSEICData.SummaryOfCase.ResultCaseId = mappingResultCaseLogic.GetByClaimDiKey(taskBikeData.SummaryOfCase.ResultCaseId);
}
if (summary.AccidentLocation != null)
{
taskSEICData.SummaryOfCase.AccidentLocation = new APILocationPlace();
taskSEICData.SummaryOfCase.AccidentLocation.Place = summary.AccidentLocation.Place;
if (summary.AccidentLocation.Province != null)
{
taskSEICData.SummaryOfCase.AccidentLocation.Province = new SyncProvince
{
ProvinceCode = mappingProvinceLogic.GetByClaimDiKey(summary.AccidentLocation.Province.Id)
};
}
if (summary.AccidentLocation.Aumphur != null)
{
taskSEICData.SummaryOfCase.AccidentLocation.Amphur = new SyncAmphur
{
AmphurCode = mappingAmphurLogic.GetByClaimDiKey(summary.AccidentLocation.Aumphur.Id)
};
}
if (summary.AccidentLocation.District != null)
{
taskSEICData.SummaryOfCase.AccidentLocation.District = new SyncDistrict
{
DistrictCode = mappingDistrictLogic.GetByClaimDiKey(summary.AccidentLocation.District.Id)
};
}
}
taskSEICData.SummaryOfCase.AccidentDetail = summary.AccidentDetail;
taskSEICData.SummaryOfCase.AccidentResultDetail = summary.AccidentResultDetail;
taskSEICData.SummaryOfCase.CopyDialy = summary.CopyDialy;
}
}
private void TransfromPropertyDamages(TaskBikeResult taskBikeData)
{
if (taskBikeData.PropertyDamages != null)
{
taskSEICData.PropertyDamages = new List<APIPropertyDamage>();
foreach (var item in taskBikeData.PropertyDamages)
{
APIPropertyDamage propData = new APIPropertyDamage();
propData.PropertyDamageType = new SyncWoundedType();
if (item.PropertyDamageType != null)
{
var result = mappingWoundedTypeLogic.GetByClaimDiKey(item.PropertyDamageType.Id.ToString());
propData.PropertyDamageType = new SyncWoundedType
{
SyncWoundedTypeId = string.IsNullOrEmpty(result) ? 0 : int.Parse(result)
};
}
propData.PropertyDamageName = item.PropertyDamageName;
if (item.PropertyDamageOwnerNameInfo != null)
{
propData.PropertyDamageOwnerNameInfo = new APIPersonInfo();
propData.PropertyDamageOwnerNameInfo.FirstName = item.PropertyDamageOwnerNameInfo.FirstName;
propData.PropertyDamageOwnerNameInfo.LastName = item.PropertyDamageOwnerNameInfo.LastName;
if (item.PropertyDamageOwnerNameInfo.Title != null)
{
propData.PropertyDamageOwnerNameInfo.Title = new SyncTitleName
{
TitleCode = mappingTitleLogic.GetByClaimDiKey(item.PropertyDamageOwnerNameInfo.Title.Id)
};
}
}
propData.PropertyDamageAmount = item.PropertyDamageAmount;
if (item.PropertyDamageOwnerLocationPlace != null)
{
propData.PropertyDamageOwnerLocationPlace = new APILocationPlace();
if (item.PropertyDamageOwnerLocationPlace.Province != null)
{
propData.PropertyDamageOwnerLocationPlace.Province = new SyncProvince
{
ProvinceCode = mappingProvinceLogic.GetByClaimDiKey(item.PropertyDamageOwnerLocationPlace.Province.Id)
};
}
if (item.PropertyDamageOwnerLocationPlace.Aumphur != null)
{
propData.PropertyDamageOwnerLocationPlace.Amphur = new SyncAmphur
{
AmphurCode = mappingAmphurLogic.GetByClaimDiKey(item.PropertyDamageOwnerLocationPlace.Aumphur.Id)
};
}
if (item.PropertyDamageOwnerLocationPlace.District != null)
{
propData.PropertyDamageOwnerLocationPlace.District = new SyncDistrict
{
DistrictCode = mappingDistrictLogic.GetByClaimDiKey(item.PropertyDamageOwnerLocationPlace.District.Id)
};
}
}
taskSEICData.PropertyDamages.Add(propData);
}
}
}
private void TransfromWoundeds(TaskBikeResult taskBikeData)
{
if (taskBikeData.Woundeds != null)
{
taskSEICData.Woundeds = new List<APIWounded>();
foreach (var item in taskBikeData.Woundeds)
{
APIWounded woundedData = new APIWounded();
woundedData.WoundedType = new SyncWoundedType();
if (item.WoundedType != null)
{
var result = mappingWoundedTypeLogic.GetByClaimDiKey(item.WoundedType.Id.ToString());
woundedData.WoundedType = new SyncWoundedType
{
SyncWoundedTypeId = string.IsNullOrEmpty(result) ? 0 : int.Parse(result)
};
}
if (item.WoundedNameInfo != null)
{
woundedData.WoundedNameInfo = new APIPersonInfo();
woundedData.WoundedNameInfo.FirstName = item.WoundedNameInfo.FirstName;
woundedData.WoundedNameInfo.LastName = item.WoundedNameInfo.LastName;
if (item.WoundedNameInfo.Title != null)
{
woundedData.WoundedNameInfo.Title = new SyncTitleName
{
TitleCode = mappingTitleLogic.GetByClaimDiKey(item.WoundedNameInfo.Title.Id)
};
}
}
woundedData.WoundedAge = item.WoundedAge;
woundedData.WoundedGender = item.WoundedGender;
woundedData.WoundedAccidentAmount = item.WoundedAccidentAmount;
if (item.WoundedLocationPlace != null)
{
woundedData.WoundedLocationPlace = new APILocationPlace();
if (item.WoundedLocationPlace.Province != null)
{
woundedData.WoundedLocationPlace.Province = new SyncProvince
{
ProvinceCode = mappingProvinceLogic.GetByClaimDiKey(item.WoundedLocationPlace.Province.Id)
};
}
if (item.WoundedLocationPlace.Aumphur != null)
{
woundedData.WoundedLocationPlace.Amphur = new SyncAmphur
{
AmphurCode = mappingAmphurLogic.GetByClaimDiKey(item.WoundedLocationPlace.Aumphur.Id)
};
}
if (item.WoundedLocationPlace.District != null)
{
woundedData.WoundedLocationPlace.District = new SyncDistrict
{
DistrictCode = mappingDistrictLogic.GetByClaimDiKey(item.WoundedLocationPlace.District.Id)
};
}
}
taskSEICData.Woundeds.Add(woundedData);
}
}
}
private void TransfromSurveyorCharges(TaskBikeResult taskBikeData)
{
if (taskBikeData.SurveyorCharges != null)
{
taskSEICData.SurveyorCharges = new List<APISurveyorCharge>();
int serviceTypeCopyID = 7;
int serviceTypeDistanceID = 2;
int serviceTypeTakePictureID = 3;
int serviceTypeClaimRequestID = 6;
if (taskBikeData.TaskPictureList != null && taskBikeData.TaskPictureList.Count > 0)
{
APISurveyorCharge surveyorChargeData = new APISurveyorCharge();
surveyorChargeData.Quantity = taskBikeData.TaskPictureList.Count;
surveyorChargeData.ServiceDesc = "ค่ารูปถ่าย";
surveyorChargeData.ServiceType = new SyncServiceType
{
ServiceTypeId = serviceTypeTakePictureID
};
surveyorChargeData.UnitPrice = 3;
surveyorChargeData.Total = surveyorChargeData.Quantity * surveyorChargeData.UnitPrice;
taskSEICData.SurveyorCharges.Add(surveyorChargeData);
}
List<APISurveyorCharge> surveyorChargeClaimRequest = taskBikeData.SurveyorCharges.Where(t => t.ServiceType.ServiceTypeId == serviceTypeClaimRequestID).ToList();
if (surveyorChargeClaimRequest != null && surveyorChargeClaimRequest.Count > 0)
{
foreach (var item in surveyorChargeClaimRequest)
{
APISurveyorCharge surveyorChargeData = new APISurveyorCharge();
surveyorChargeData.Quantity = 10;
surveyorChargeData.ServiceDesc = item.ServiceDesc;
if (item.ServiceType != null)
{
surveyorChargeData.ServiceType = new SyncServiceType
{
ServiceTypeId = item.ServiceType.ServiceTypeId
};
}
surveyorChargeData.Total = (item.UnitPrice * 10) / 100;
surveyorChargeData.UnitPrice = item.UnitPrice;
taskSEICData.SurveyorCharges.Add(surveyorChargeData);
}
}
List<APISurveyorCharge> surveyorChargeCopy = taskBikeData.SurveyorCharges.Where(t => t.ServiceType.ServiceTypeId == serviceTypeCopyID).ToList();
if (surveyorChargeCopy != null && surveyorChargeCopy.Count > 0)
{
foreach (var item in surveyorChargeCopy)
{
APISurveyorCharge surveyorChargeData = new APISurveyorCharge();
surveyorChargeData.Quantity = 1;
surveyorChargeData.ServiceDesc = item.ServiceDesc;
if (item.ServiceType != null)
{
surveyorChargeData.ServiceType = new SyncServiceType
{
ServiceTypeId = item.ServiceType.ServiceTypeId
};
}
surveyorChargeData.UnitPrice = 100;
surveyorChargeData.Total = surveyorChargeData.Quantity * surveyorChargeData.UnitPrice;
taskSEICData.SurveyorCharges.Add(surveyorChargeData);
}
}
List<APISurveyorCharge> surveyorChargeDistance = taskBikeData.SurveyorCharges.Where(t => t.ServiceType.ServiceTypeId == serviceTypeDistanceID).ToList();
if (surveyorChargeDistance != null && surveyorChargeDistance.Count > 0)
{
APISurveyorCharge surveyorChargeData = new APISurveyorCharge();
surveyorChargeData.Quantity = Math.Round(taskBikeData.ClaimDistanceValue, 0);
surveyorChargeData.ServiceDesc = "ค่าพาหนะต่างจังหวัด";
surveyorChargeData.ServiceType = new SyncServiceType
{
ServiceTypeId = 2
};
surveyorChargeData.UnitPrice = 5;
surveyorChargeData.Total = (Math.Round(taskBikeData.ClaimDistanceValue, 0) * surveyorChargeData.UnitPrice);
taskSEICData.SurveyorCharges.Add(surveyorChargeData);
}
}
}
private StreamContent CreateFileContent(Stream stream, string fileName, string contentType)
{
var fileContent = new StreamContent(stream);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "\"files\"",
FileName = "\"" + fileName + "\""
};
fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
return fileContent;
}
}
}
|
using System.Collections.Generic;
namespace Pathoschild.SlackArchiveSearch.Models
{
/// <summary>Cached Slack archive data.</summary>
public class Cache
{
/// <summary>Metadata about every Slack channel.</summary>
public Dictionary<string, Channel> Channels { get; set; }
/// <summary>Metadata about every Slack user.</summary>
public Dictionary<string, User> Users { get; set; }
/// <summary>Metadata about all Slack message that's been sent.</summary>
public Message[] Messages { get; set; }
}
} |
#if !NET35 && !NET40
namespace Vlc.DotNet.Core
{
using System;
using System.Threading;
using System.Threading.Tasks;
using Vlc.DotNet.Core.Interops.Signatures;
public class LoginResult
{
public string Username { get; set; }
public string Password { get; set; }
public bool StoreCredentials { get; set; }
}
public enum QuestionAction : int
{
Action1 = 1,
Action2
}
/// <summary>
/// The interface that you must implement in your code to handle dialogs
/// </summary>
public interface IVlcDialogManager
{
/// <summary>
/// Displays an error dialog with the specified title and text.
/// </summary>
/// <param name="userdata">The user data, as given to the <see cref="DialogsManagement.UseDialogManager" /> method.</param>
/// <param name="title">The dialog title</param>
/// <param name="text">The dialog message</param>
/// <returns>A task that is completed when the message is acknowledged by the user.</returns>
Task DisplayErrorAsync(IntPtr userdata, string title, string text);
/// <summary>
/// Displays a login dialog.
///
/// There are three ways you can exit from this method:
/// - The user has filled the login dialog and clicked OK. The task completes with a <see cref="LoginResult"/>
/// - The user has cancelled the login dialog. The task completes with a <c>null</c> result
/// - The dialog has been closed by libvlc. The cancellationToken is cancelled. In that case, you must close your dialog and <c>throw new TaskCanceledException</c>
/// </summary>
/// <param name="userdata">The user data, as given to the <see cref="DialogsManagement.UseDialogManager" /> method.</param>
/// <param name="dialogId">The dialog identifier, as given by LibVlc</param>
/// <param name="title">The dialog title</param>
/// <param name="text">The dialog message</param>
/// <param name="username">The default username to be displayed in the login box</param>
/// <param name="askstore">A boolean indicating whether a checkbox "save credentials" should be displayed on the login dialog.</param>
/// <param name="cancellationToken">The token that is cancelled when libvlc asks to cancel the dialog.</param>
/// <exception cref="TaskCanceledException">When the cancellation token has been cancelled, and the dialog has been closed.</exception>
/// <returns>The login information that the user has submitted, or <c>null</c> if (s)he clicked on "cancel"</returns>
Task<LoginResult> DisplayLoginAsync(IntPtr userdata, IntPtr dialogId, string title, string text, string username, bool askstore, CancellationToken cancellationToken);
/// <summary>
/// Displays a question dialog.
///
/// There are three ways you can exit from this method:
/// - The user has clicked on one of the two action buttons. The task completes with a <see cref="QuestionAction"/>
/// - The user has cancelled the question dialog. The task completes with a <c>null</c> result
/// - The dialog has been closed by libvlc. The cancellationToken is cancelled. In that case, you must close your dialog and <c>throw new TaskCanceledException</c>
/// </summary>
/// <param name="userdata">The user data, as given to the <see cref="DialogsManagement.UseDialogManager" /> method.</param>
/// <param name="dialogId">The dialog identifier, as given by LibVlc</param>
/// <param name="title">The dialog title</param>
/// <param name="text">The dialog message</param>
/// <param name="questionType">The kind of question</param>
/// <param name="cancelButton">The text that is displayed on the button that cancels</param>
/// <param name="action1Button">The text that is displayed on the first action button (or <c>null</c> if this button is not displayed)</param>
/// <param name="action2Button">The text that is displayed on the second action button (or <c>null</c> if this button is not displayed)</param>
/// <param name="cancellationToken">The token that is cancelled when libvlc asks to cancel the dialog.</param>
/// <exception cref="TaskCanceledException">When the cancellation token has been cancelled, and the dialog has been closed.</exception>
/// <returns>The action selected by the user, or <c>null</c> if (s)he clicked on "cancel"</returns>
Task<QuestionAction?> DisplayQuestionAsync(IntPtr userdata, IntPtr dialogId, string title, string text,
DialogQuestionType questionType, string cancelButton, string action1Button, string action2Button, CancellationToken cancellationToken);
/// <summary>
/// Displays a progress dialog.
///
/// There are two ways you can exit from this method:
/// - The <see paramref="cancelButton" /> parameter is not <c>null</c> and the user clicked on cancel. The task completes.
/// - The dialog has been closed by libvlc. The cancellationToken is cancelled. In that case, you must close your dialog and <c>throw new TaskCanceledException</c>
/// </summary>
/// <param name="userdata">The user data, as given to the <see cref="DialogsManagement.UseDialogManager" /> method.</param>
/// <param name="dialogId">The dialog identifier, as given by LibVlc. The same identifier will be used in <see cref="UpdateProgress"/></param>
/// <param name="title">The dialog title</param>
/// <param name="text">The dialog message</param>
/// <param name="indeterminate">A boolean indicating whether the progress is indeterminate.</param>
/// <param name="position">The progress position (between 0.0 and 1.0)</param>
/// <param name="cancelButton">The text to display on the "cancel" button, or <c>null</c> if the progress cannot be cancelled.</param>
/// <param name="cancellationToken">The token that is cancelled when libvlc asks to cancel the dialog.</param>
/// <exception cref="TaskCanceledException">When the cancellation token has been cancelled, and the dialog has been closed.</exception>
/// <returns>The task that completes when the user cancels the dialog. Be careful, you cannot cancel the dialog if <see paramref="cancelButton" /> is null.</returns>
Task DisplayProgressAsync(IntPtr userdata, IntPtr dialogId, string title, string text,
bool indeterminate, float position, string cancelButton, CancellationToken cancellationToken);
/// <summary>
/// Updates the previously displayed progress dialog.
/// </summary>
/// <param name="userdata">The user data, as given to the <see cref="DialogsManagement.UseDialogManager" /> method.</param>
/// <param name="dialogId">The dialog identifier, as given by LibVlc. The same identifier was used in <see cref="DisplayProgress"/></param>
/// <param name="position">The progress position (between 0.0 and 1.0)</param>
/// <param name="text">The dialog message</param>
void UpdateProgress(IntPtr userdata, IntPtr dialogId, float position, string text);
}
}
#endif |
namespace SubC.Attachments.ClingyLines {
using UnityEngine;
[System.Serializable]
public class LineRendererDescription {
public UnityEngine.Rendering.ShadowCastingMode shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On;
public bool receiveShadows = true;
public MotionVectorGenerationMode motionVectorGenerationMode = MotionVectorGenerationMode.Camera;
public Material[] materials;
public bool loop;
public bool useWorldSpace = true;
public AnimationCurve widthCurve;
public float widthMultiplier = 1;
public Gradient colorGradient;
public GradientColorKey[] colors;
public GradientAlphaKey[] alphas;
public int cornerVertices = 0;
public int endCapVertices = 0;
public LineAlignment alignment = LineAlignment.View;
public LineTextureMode textureMode = LineTextureMode.Stretch;
public bool generateLightingData;
public int sortingLayerID;
public int sortingOrder;
public UnityEngine.Rendering.LightProbeUsage lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off;
public UnityEngine.Rendering.ReflectionProbeUsage reflectionProbes
= UnityEngine.Rendering.ReflectionProbeUsage.Off;
public LineRendererDescription() {
Reset();
}
public virtual void Reset() {
widthCurve = AnimationCurve.Linear(0, 0.1f, 1, 0.1f);
materials = new Material[1];
}
public void UpdateLineRenderer(LineRenderer lineRenderer, Vector3[] points, Gradient colorGradient = null,
AnimationCurve widthCurve = null) {
lineRenderer.widthMultiplier = widthMultiplier;
lineRenderer.alignment = alignment;
lineRenderer.lightProbeUsage = lightProbeUsage;
lineRenderer.generateLightingData = generateLightingData;
lineRenderer.useWorldSpace = useWorldSpace;
lineRenderer.lightProbeUsage = lightProbeUsage;
lineRenderer.textureMode = textureMode;
lineRenderer.sortingOrder = sortingOrder;
lineRenderer.sortingLayerID = sortingLayerID;
lineRenderer.shadowCastingMode = shadowCastingMode;
lineRenderer.receiveShadows = receiveShadows;
lineRenderer.loop = loop;
lineRenderer.motionVectorGenerationMode = motionVectorGenerationMode;
lineRenderer.colorGradient = colorGradient ?? this.colorGradient;
lineRenderer.materials = materials;
lineRenderer.numCornerVertices = cornerVertices;
lineRenderer.numCapVertices = endCapVertices;
lineRenderer.positionCount = points.Length;
lineRenderer.widthCurve = widthCurve ?? this.widthCurve;
lineRenderer.SetPositions(points);
}
}
// for use when we just have one LineRenderer for the entire strategy and want to put the LineRenderer on a new
// GameObject rather than on one of our AttachObjects
public class LineStrategyState : AttachStrategyState {
public LineState lineState = new LineState();
public AttachObject[] objects;
}
// for use when we want to put the LineRenderer on an AttachObject
public class LineObjectState : AttachObjectState {
public LineState lineState = new LineState();
public AttachObject[] objects;
}
public class LineState {
public LineRenderer lineRenderer;
public Vector3[] points;
public Gradient colorGradient;
public AnimationCurve widthCurve;
}
[System.Serializable]
public abstract class AttachStrategyLineRendererDescription : LineRendererDescription {
public bool perObjectWidth = false;
public bool perObjectColor = false;
public abstract ParamSelector GetPositionParamSelector(AttachObject obj);
public abstract ParamSelector GetWidthParamSelector(AttachObject obj);
public abstract ParamSelector GetColorParamSelector(AttachObject obj);
}
public static class LineAttachStrategyUtility {
public static void RefreshLineRenderer(AttachStrategyLineRendererDescription lineRendererDescription,
LineState state, AttachObject[] objects, AttachObject reference = null,
bool hideLineRendererInInspector = true) {
AttachStrategyLineRendererDescription lrd = lineRendererDescription;
Attachment attachment = objects[0].attachment;
if (state.points == null || state.points.Length != objects.Length)
state.points = new Vector3[objects.Length];
state.widthCurve = new AnimationCurve();
state.colorGradient = new Gradient();
GradientColorKey[] colors = new GradientColorKey[objects.Length];
GradientAlphaKey[] alphas = new GradientAlphaKey[objects.Length];
int i = 0;
foreach (AttachObject obj in objects) {
ParamSelector selector = lrd.GetPositionParamSelector(obj);
state.points[i] = selector.GetWorldPosition(attachment, reference ?? obj);
if (lrd.perObjectWidth) {
selector = lrd.GetWidthParamSelector(obj);
state.widthCurve.AddKey(i / (objects.Length - 1),
selector.GetParam(attachment, reference ?? obj).floatValue);
}
if (lrd.perObjectColor) {
selector = lrd.GetColorParamSelector(obj);
colors[i] = new GradientColorKey(selector.GetParam(attachment, reference ?? obj).colorValue,
i / (objects.Length - 1));
alphas[i] = new GradientAlphaKey(selector.GetParam(attachment, reference ?? obj).colorValue.a,
i / (objects.Length - 1));
}
i ++;
}
if (lrd.perObjectColor)
state.colorGradient.SetKeys(colors, alphas);
lrd.UpdateLineRenderer(state.lineRenderer, state.points, lrd.perObjectColor ? state.colorGradient : null,
lrd.perObjectWidth ? state.widthCurve : null);
state.lineRenderer.hideFlags = hideLineRendererInInspector ? HideFlags.HideInInspector : HideFlags.None;
}
}
} |
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
using System.Xml;
public class InsideOfData : Editor {
[MenuItem("Tools/XML InsideOfData")]
private static void ChangeData()
{
string sourcePath = Application.dataPath + "/StreamingAssets" + "/EndlessMode_Base.xml";
string filePath = Application.dataPath + "/StreamingAssets" + "/WideWallData.xml";
//如果文件存在话开始解析。
if (File.Exists(filePath) && File.Exists(sourcePath))
{
////读取源文档的数据
//SceneData sceneData = new SceneData();
//XmlDocument xmlDoc_Base = new XmlDocument();
//xmlDoc_Base.Load(sourcePath);
//for (int i = 0; i < 285; i++)
//{
// XmlNodeList nodeList_Base =
// xmlDoc_Base.SelectSingleNode("root").SelectSingleNode("scene").SelectNodes("fragment" + i);
// // XmlNodeList nodeList_Base =
// //xmlDoc_Base.SelectSingleNode("root").ChildNodes;
// foreach (XmlElement gameobjects in nodeList_Base)
// {
// Vector3 pos = Vector3.zero;
// Vector3 rot = Vector3.zero;
// Vector3 sca = Vector3.zero;
// string Tag = "";
// int Layer = 0;
// foreach (XmlElement myTransform in gameobjects.SelectSingleNode("gameObject").SelectSingleNode("transform").ChildNodes)
// {
// #region 根据数据赋值参数
// if (gameobjects.SelectSingleNode("gameObject").Attributes[1].InnerText == "Obj_zhangai02")
// {
// if (myTransform.Name == "position")
// {
// foreach (XmlAttribute position in myTransform.Attributes)
// {
// switch (position.Name)
// {
// case "x":
// pos.x = float.Parse(position.InnerText);
// break;
// case "y":
// pos.y = float.Parse(position.InnerText);
// break;
// case "z":
// pos.z = float.Parse(position.InnerText);
// break;
// }
// }
// }
// else if (myTransform.Name == "rotation")
// {
// foreach (XmlAttribute rotation in myTransform.Attributes)
// {
// switch (rotation.Name)
// {
// case "x":
// rot.x = float.Parse(rotation.InnerText);
// break;
// case "y":
// rot.y = float.Parse(rotation.InnerText);
// break;
// case "z":
// rot.z = float.Parse(rotation.InnerText);
// break;
// }
// }
// }
// else if (myTransform.Name == "scale")
// {
// foreach (XmlAttribute scale in myTransform.Attributes)
// {
// switch (scale.Name)
// {
// case "x":
// sca.x = float.Parse(scale.InnerText);
// break;
// case "y":
// sca.y = float.Parse(scale.InnerText);
// break;
// case "z":
// sca.z = float.Parse(scale.InnerText);
// break;
// }
// }
// }
// else if (myTransform.Name == "Tag")
// {
// Tag = myTransform.Attributes[0].InnerText;
// }
// else if (myTransform.Name == "Layer")
// {
// Layer = int.Parse(myTransform.Attributes[0].InnerText);
// }
// if (Tag == "Left")
// {
// sceneData.SaveData(gameobjects.SelectSingleNode("gameObject").Attributes[1].InnerText, pos, rot, sca,
// Layer, Tag);
// }
// }
// #endregion
// }
// }
//}
//Debug.Log(sceneData.GetData(0)._scale);
//修改目标文档的数据
int mark = 0;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filePath);
for (int i = 0; i < 285; i++)
{
XmlNodeList nodeList =
xmlDoc.SelectSingleNode("root").SelectSingleNode("scene").SelectNodes("fragment" + i);
foreach (XmlElement gameobjects in nodeList)
{
if (gameobjects.SelectSingleNode("gameObject") == null)
{
continue;
}
//删除节点
//if (gameobjects.SelectSingleNode("gameObject").SelectSingleNode("transform").SelectSingleNode("Tag").Attributes[0].InnerText == "Right")
//{
// gameobjects.RemoveAll();
//}
//改名
//gameobjects.SelectSingleNode("gameObject").Attributes[1].InnerText = "obj_zhangaila_wujin";
foreach (XmlElement myTransform in
gameobjects.SelectSingleNode("gameObject").SelectSingleNode("transform").ChildNodes)
{
// if (gameobjects.SelectSingleNode("gameObject").Attributes[1].InnerText == "obj_zhangaila_wujin")
// {
//if (myTransform.Name == "scale")
//{
// if (gameobjects.SelectSingleNode("gameObject").SelectSingleNode("transform").SelectSingleNode("position").Attributes[1].InnerText ==
// sceneData.GetData(mark)._position.y.ToString())
// {
// foreach (XmlAttribute scale in myTransform.Attributes)
// {
// switch (scale.Name)
// {
// case "x":
// scale.InnerText = sceneData.GetData(mark)._scale.x.ToString();
// break;
// case "y":
// scale.InnerText = sceneData.GetData(mark)._scale.y.ToString();
// break;
// case "z":
// scale.InnerText = sceneData.GetData(mark)._scale.z.ToString();
// break;
// }
// }
// mark++;
// }
//}
//gameobjects.RemoveAll();
//if (myTransform.Name == "position")
//{
// foreach (XmlAttribute position in myTransform.Attributes)
// {
// switch (position.Name)
// {
// case "x":
// //position.InnerText = sceneData.GetData(mark)._position.x.ToString();
// break;
// case "y":
// position.InnerText = sceneData.GetData(mark)._position.y.ToString();
// break;
// case "z":
// //position.InnerText = sceneData.GetData(mark)._position.z.ToString();
// break;
// }
// }
//}
if (myTransform.Name == "rotation")
{
foreach (XmlAttribute rotation in myTransform.Attributes)
{
switch (rotation.Name)
{
case "x":
rotation.InnerText = "0";
break;
case "y":
rotation.InnerText = "-90";
break;
case "z":
rotation.InnerText = "0";
break;
}
}
}
//if (myTransform.Name == "Tag")
//{
// if (myTransform.Attributes[0].InnerText == "Left")
// {
// gameobjects.SelectSingleNode("gameObject").Attributes[1].InnerText = "Obstacle_zhangai";
// }
// else
// {
// gameobjects.SelectSingleNode("gameObject").Attributes[1].InnerText = "Obstacle_zhangai 1";
// }
//}
// }
}
}
}
xmlDoc.Save(filePath);
Debug.Log("End");
}
else
{
Debug.Log("文件不存在");
}
}
//static void ChangeXML()
//{
// string sourcePath = Application.dataPath + "/StreamingAssets" + "/WideWallData.xml";
// string filePath = Application.dataPath + "/StreamingAssets" + "/EndlessMode.xml";
// if (File.Exists(filePath) && File.Exists(sourcePath))
// {
// XmlDocument baseDocument = new XmlDocument();
// baseDocument.Load(sourcePath);
// XmlDocument childDocument = new XmlDocument();
// XmlDeclaration xmlDeclaration = childDocument.CreateXmlDeclaration("1.0", "us-ascii", null);
// childDocument.AppendChild(xmlDeclaration);
// XmlElement rootXmlElement = childDocument.CreateElement("root");
// XmlNodeList nodeList =
// baseDocument.SelectSingleNode("root").SelectSingleNode("scene").SelectNodes("fragment" + i);
// for (int j = 0; j < nodeList.Count; j++)
// {
// if (nodeList[j].SelectSingleNode("gameObject") == null)
// continue;
// rootXmlElement.AppendChild(childDocument.ImportNode(nodeList[j].SelectSingleNode("gameObject"), true));
// }
// childDocument.AppendChild(rootXmlElement);
// childDocument.Save(path);
// }
//}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using Compiler.BackendPart;
using Compiler.FrontendPart;
using Compiler.FrontendPart.SemanticAnalyzer;
using Compiler.TreeStructure;
namespace Compiler
{
static class EntryPoint
{
static void Main(string[] args)
{
L.LogLevel = 0;
if (args.Length > 0)
{
var cName = args.Length > 1 ? args[1] : null;
var mName = args.Length > 2 ? args[2] : null;
CompileFile(args[0], cName, mName);
}
else
CompileSuite("./../../Tests/Composite");
}
private static void CompileFile(string filename, string entryClass=null, string entryMethod=null)
{
var main = new FrontEndCompiler(filename);
try
{
Compiler.Compile(main.GetClasses(), filename, entryClass, entryMethod);
}
catch (Exception e)
{
L.LogError(e);
}
finally
{
StaticTables.ClassTable = new Dictionary<string, List<Class>>();
}
}
private static void CompileSuite(string folderName)
{
var files = Directory.GetFiles(folderName);
foreach (var filename in files)
{
Console.WriteLine(Path.GetFullPath(filename));
CompileFile(filename);
Console.WriteLine("\n\n");
}
}
}
} |
using System;
using System.Collections;
using System.Linq;
using AppStore.Domain.Common;
using AppStore.Infra.CrossCutting.Encryption.Extension;
using AppStore.Infra.CrossCutting.Serialization;
namespace AppStore.Domain.Users
{
public class AuthenticationService : IAuthenticationService
{
#region Fields
private readonly IUnitOfWork _unitOfWork;
private readonly IUserRepository _userRepository;
private readonly int _sessionTimeout = 60;
private readonly string _tokenName = "AuthToken";
private readonly string[] _publicResources = { "authentication.post", "users.post", "apps.get" };
#endregion
#region Properties
public virtual User User { get; private set; }
public DateTime Expires
{
get
{
return DateTime.Now.AddMinutes(_sessionTimeout);
}
}
public string TokenName
{
get
{
return _tokenName;
}
}
#endregion
#region Constructors
public AuthenticationService(IUnitOfWork unitOfWork, IUserRepository userRepository)
{
_unitOfWork = unitOfWork;
_userRepository = userRepository;
}
#endregion
#region Authenticate
public virtual void Authenticate(string email, string password)
{
User = _userRepository.Get(email);
if (User == null)
throw new UnauthorizedException("Invalid User.");
User.ValidateAccess(password);
_unitOfWork.Commit();
}
#endregion
#region ValidateAccess
public virtual void ValidateAccess(string securityToken, string resource, string action, string method)
{
var expectedResource = resource + (string.IsNullOrEmpty(action) ? "" : "." + action) + "." + method.ToLower();
var isOptionsMethod = method == "OPTIONS";
var isPublic = _publicResources.Contains(expectedResource) || isOptionsMethod;
if (isPublic)
return;
if (securityToken == null)
throw new UnauthorizedException("SecurityToken cannot be empty.");
Hashtable sessionData;
try
{
sessionData = DecryptSecurityToken(securityToken);
}
catch (FormatException)
{
throw new UnauthorizedException("Invalid SecurityToken.");
}
if ((DateTime)sessionData["Expires"] < DateTime.Now.ToUniversalTime())
throw new UnauthorizedException("Session expired.");
User = _userRepository.Get((int)sessionData["UserId"]);
if (User == null)
throw new UnauthorizedException("User not found.");
}
#endregion
#region CreateToken
public virtual string CreateToken()
{
if (User == null)
return null;
var sessionData = new Hashtable();
sessionData["UserId"] = User.UserId;
sessionData["Expires"] = Expires;
string securityToken = EncryptSecurityToken(sessionData);
return securityToken;
}
#endregion
#region Criptography
private static string EncryptSecurityToken(Hashtable securityData)
{
return securityData.Serialize().Encrypt();
}
private static Hashtable DecryptSecurityToken(string securityToken)
{
return securityToken.Decrypt().Deserialize<Hashtable>();
}
#endregion
}
} |
using UnityEngine;
using System.Collections;
public class MenuController : MonoBehaviour {
public static MenuController instance;
[SerializeField]
private GameObject[] planes;
//[SerializeField] enable for debug purposes
private bool isGreenPlaneUnlocked, isBluePlaneUnlocked, isYellowPlaneUnlocked;
void Awake()
{
MakeInstance();
}
void MakeInstance()
{
if (instance == null)
{
instance = this;
}
}
// Use this for initialization
void Start () {
planes[GameController.instance.GetSelectedPlane()].SetActive(true);
CheckUnlockedPlanes();
}
void CheckUnlockedPlanes()
{
if (GameController.instance.IsGreenPlaneUnlocked() == 1)
{
isGreenPlaneUnlocked = true;
}
if (GameController.instance.IsBluePlaneUnlocked() == 1)
{
isBluePlaneUnlocked = true;
}
if (GameController.instance.IsYellowPlaneUnlocked() == 1)
{
isYellowPlaneUnlocked = true;
}
}
public void ConnectOnGooglePlayGames()
{
//LeaderboardsController.instance.ConnectOrDisconnectOnGooglePlayGames();
}
public void OpenLeaderboardsScoreUI()
{
//LeaderboardsController.instance.OpenLeaderboardsScore();
}
public void ChangePlane()
{
//TODO show next available plane because if i unlock blue plane but dont have green plane unlocked i cant
// cycle to it.
if (GameController.instance.GetSelectedPlane() == 0) // red plane selected
{
if (isGreenPlaneUnlocked)
{
planes[0].SetActive(false); // disable red plan
GameController.instance.SetSelectedPlane(1); //select green plan
planes[GameController.instance.GetSelectedPlane()].SetActive(true); //enable green plane
}
}
else if (GameController.instance.GetSelectedPlane() == 1) // green plane selected
{
if (isBluePlaneUnlocked)
{
planes[1].SetActive(false);// disable green plane
GameController.instance.SetSelectedPlane(2); //select blue plane
planes[GameController.instance.GetSelectedPlane()].SetActive(true); //enable blue plane
}
else
{
planes[1].SetActive(false); //disable green plane
GameController.instance.SetSelectedPlane(0); //select red plane
planes[GameController.instance.GetSelectedPlane()].SetActive(true); // enable red plane
}
}
else if (GameController.instance.GetSelectedPlane() == 2) //blue plane selected
{
if (isYellowPlaneUnlocked)
{
planes[2].SetActive(false); //disable blue plane
GameController.instance.SetSelectedPlane(3); //select yellow plane
planes[GameController.instance.GetSelectedPlane()].SetActive(true); //enable yellow plane
}
else
{
planes[2].SetActive(false); //disable blue plane
GameController.instance.SetSelectedPlane(0); //select red plane
planes[GameController.instance.GetSelectedPlane()].SetActive(true); // enable red plane
}
}
else if (GameController.instance.GetSelectedPlane() == 3) // yellow plane selected
{
planes[3].SetActive(false); // disable yellow plane
GameController.instance.SetSelectedPlane(0); //select red plane
planes[GameController.instance.GetSelectedPlane()].SetActive(true); //enable red plane
}
}
public void PlayGame()
{
SceneFader.instance.LoadLevel("Gameplay");
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Escape))
Application.Quit();
}
}
|
using System;
namespace Veiculos
{
class Program
{
static void Main(string[] args)
{
Carro[] carros = new Carro[300];
Caminhao[] caminhoes = new Caminhao[200];
int x, cadastroCarro=0, CadastroCaminhao=0, opcao = 1;
string strProcura;
do
{
Console.Clear();
Console.WriteLine("------------------Gestão de veiculos-------------\n1-Cadastrar Carro\n2-Cadastrar Caminhão\n3-Consulta por Placa\n4-Consulta Camihão " +
"por Modelo\nConsulta Carro por cor \nExibir todos os carros cadastrados\n7Exibir todos os Caminhões cadastrados\n0-Sair");
opcao = int.Parse(Console.ReadLine());
Console.Clear();
switch (opcao)
{
case 1:
Console.WriteLine("Cadastro carro");
if (cadastroCarro < 300)
{
carros[cadastroCarro] = new Carro();
Console.Write("Modelo: ");
carros[cadastroCarro].Modelo = Console.ReadLine();
Console.Write("\nFabricante: ");
carros[cadastroCarro].Fabricante = Console.ReadLine();
Console.Write("\nPlaca: ");
carros[cadastroCarro].Placa = Console.ReadLine();
Console.Write("\nAno");
carros[cadastroCarro].Ano = int.Parse(Console.ReadLine());
Console.Write("\nCor");
carros[cadastroCarro].Cor = Console.ReadLine();
Console.Write("\nQuantidades de Portas: ");
carros[cadastroCarro].Numero_portas = int.Parse(Console.ReadLine());
Console.Write("\nCapacidade porta malas: ");
carros[cadastroCarro].Mala = int.Parse(Console.ReadLine());
Console.Write("\nBagageiro, 1-Sim 2Não: ");
carros[cadastroCarro].Bagageiro = Convert.ToBoolean(int.Parse(Console.ReadLine()));
Console.Write("\nTipo de combustivel: ");
carros[cadastroCarro].Combustivel = Console.ReadLine();
cadastroCarro++;
}
else
{
Console.WriteLine("Banco de Dados Cheio !!!");
Console.ReadKey();
}
break;
case 2:
{
Console.WriteLine("Cadastrar caminhão");
if (CadastroCaminhao < 200)
{
caminhoes[CadastroCaminhao] = new Caminhao();
Console.WriteLine("Modelo: ");
caminhoes[CadastroCaminhao].Modelo = Console.ReadLine();
Console.WriteLine("Fabricante: ");
caminhoes[CadastroCaminhao].Fabricante = Console.ReadLine();
Console.WriteLine("Placa: ");
caminhoes[CadastroCaminhao].Placa = Console.ReadLine();
Console.WriteLine("Ano: ");
caminhoes[CadastroCaminhao].Ano = int.Parse(Console.ReadLine());
Console.WriteLine("Cor: ");
caminhoes[CadastroCaminhao].Cor = Console.ReadLine();
Console.WriteLine("Numero de Portas: ");
caminhoes[CadastroCaminhao].Numero_portas = int.Parse(Console.ReadLine());
Console.WriteLine("Numero de eixos: ");
caminhoes[CadastroCaminhao].Numero_eixos = int.Parse(Console.ReadLine());
Console.WriteLine("Peso maximo de Carga: ");
caminhoes[CadastroCaminhao].Peso = double.Parse(Console.ReadLine());
Console.WriteLine("Tipo de carreta: ");
caminhoes[CadastroCaminhao].Carreta = Console.ReadLine();
cadastroCarro++;
}
else
{
Console.WriteLine("Banco de Dados cheio !!!");
Console.ReadKey();
}
}
break;
case 3:
{
Console.WriteLine("Consulta por placa ");
if(cadastroCarro>0 || CadastroCaminhao > 0)
{
Console.WriteLine("Placa: ");
strProcura = Console.ReadLine();
Console.WriteLine("Modelo Fabricate Placa Ano Cor Portas");
for (x = 0; x < cadastroCarro; x++)
{
if (carros[x].Placa == strProcura)
{
Console.WriteLine("{0,-10} {1,-10} {2,-8} {3,4} {4,-10} {5,6}",
carros[x].Modelo, carros[x].Fabricante, carros[x].Placa, carros[x].Ano, carros[x].Cor, carros[x].Numero_portas);
}
}
for (x=0; x<CadastroCaminhao; x++)
{
if (caminhoes[x].Placa == strProcura)
{
Console.WriteLine("{0,-10} {1,-10} {2,-8} {3,4} {4,-10} {5,6}",
caminhoes[x].Modelo, caminhoes[x].Fabricante, caminhoes[x].Placa, caminhoes[x].Placa, caminhoes[x].Ano, caminhoes[x].Cor, caminhoes[x].Numero_portas);
}
}
Console.ReadKey();
}
}break;
case 4:
{
Console.Write("\nModelo/Marca a procurar: ");
strProcura = Console.ReadLine();
Console.WriteLine("Modelo fabricante placa ano cor portas eixos carga carreta ");
if (CadastroCaminhao > 0)
{
for (x = 0; x < CadastroCaminhao; x++)
{
if (caminhoes[x].Modelo == strProcura || caminhoes[x].Fabricante == strProcura)
{
Console.WriteLine("{0,-10} {1,-10} {2,-8} {3,4} 4,-10} {5,6} {6,5} {7,5} {8}", caminhoes[x].Modelo, caminhoes[x].Fabricante, caminhoes[x].Placa, caminhoes[x].Ano, caminhoes[x].Peso, caminhoes[x].Carreta);
}
Console.ReadKey();
}
}
else
{
Console.WriteLine("Banco de dados vazio !!!");
}
Console.ReadKey();
}break;
case 5:
{
Console.WriteLine("Consulta por cor");
if (cadastroCarro > 0)
{
Console.WriteLine("Cor a procurar: ");
strProcura = Console.ReadLine();
Console.WriteLine("Modelo Fabricante Placa Cor Portas P.malas Bagageiro Combustivel");
for(x=0; x<cadastroCarro; x++)
{
if (carros[x].Cor == strProcura)
{
Console.WriteLine("{0,-10} {1,-10} {2,-8} {3,4} {4,-10} {5,6} {6,7} {7,9} {8}", carros[x].Modelo, carros[x].Fabricante, carros[x].Placa, carros[x].Ano, carros[x].Cor, carros[x].Numero_portas, carros[x].Mala, carros[x].Bagageiro, carros[x].Combustivel);
}
}
Console.ReadKey();
}
else { Console.WriteLine("Banco de dados vazio !!!");
Console.ReadKey();
}
}
break;
case 6:
{
Console.WriteLine("Exibir todos os carros cadastrados ");
if (cadastroCarro > 0)
{
Console.WriteLine("Modelo Fabricante Placa Ano Cor Portas P.malas Bagageiro Combustivel ");
for(x=0; x<cadastroCarro; x++)
{
Console.WriteLine("{0,-10} {1,-10} {2,-8} {3,4} {4,-10} {5,6} {6,7} {7,9} {8}", carros[x].Modelo, carros[x].Fabricante, carros[x].Placa, carros[x].Ano, carros[x].Cor, carros[x].Numero_portas, carros[x].Mala, carros[x].Bagageiro, carros[x].Combustivel);
}Console.ReadKey();
}
else
{
Console.WriteLine("Banco de dados Vazio!!!");
Console.ReadKey();
}
}break;
case 7:
{
Console.WriteLine("exibir todos os caminhões cadastrados ");
if (CadastroCaminhao > 0)
{
Console.WriteLine("Modelo Fabricante Placa Cor Portas Carreta N.eixos Peso de carga ");
for(x=0; x<CadastroCaminhao; x++)
{
Console.WriteLine("{0,-10} {1,-10} {2,-8} {3,4} {4,10} {5,6} {6,5} {7,5} {8}", caminhoes[x].Modelo, caminhoes[x].Fabricante, caminhoes[x].Placa, caminhoes[x].Ano, caminhoes[x].Cor, caminhoes[x].Numero_portas, caminhoes[x].Carreta, caminhoes[x].Numero_eixos, caminhoes[x].Peso) ;
}
Console.ReadKey();
}
else
{
Console.WriteLine("Banco de dados vazio !!!");
Console.ReadKey();
}
}break;
}
} while (opcao != 0);
}
}
}
|
using AlgorithmProblems.Graphs.GraphHelper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgorithmProblems.Graphs
{
/// <summary>
/// Check whether a graph is a tree or not
/// </summary>
class IsGraphATree
{
public IsGraphATree()
{
allVisitedVertices = new Dictionary<GraphVertex, bool>();
}
/// <summary>
/// We will use this Dictionary to check whether all the vertices are connected
/// </summary>
Dictionary<GraphVertex, bool> allVisitedVertices;
/// <summary>
/// A graph is a tree if the following conditions are met
/// 1. No cycles exist in the graph
/// 2. All elements are connected
/// </summary>
/// <param name="graph"></param>
/// <returns></returns>
public bool IsGraphTree(UndirectedGraph graph)
{
if (graph == null || graph.AllVertices.Count==0)
{
throw new ArgumentException("graph is null");
}
return !IsCyclePresent(graph.AllVertices[0], null) && IsAllVerticesConnected(graph);
}
/// <summary>
/// Checks whether a cycle is present in the undirected graph using DFS
/// </summary>
/// <param name="currentNode">current vertex</param>
/// <param name="parentNode">parent of current vertex</param>
/// <returns>whether a cycle is present or not</returns>
private bool IsCyclePresent(GraphVertex currentNode, GraphVertex parentNode)
{
currentNode.IsVisited = true;
bool isCyclePresent = false;
foreach (GraphVertex neighbour in currentNode.NeighbourVertices)
{
if (neighbour.IsVisited && neighbour == parentNode)
{
// this is not a cycle check the other neighbours
continue;
}
else if (!neighbour.IsVisited)
{
isCyclePresent |= IsCyclePresent(neighbour, currentNode);
}
else
{
// We have a cycle in the graph
return true;
}
}
return isCyclePresent;
}
/// <summary>
/// Check whether all vertices in the graph is connected
/// </summary>
/// <param name="graph"></param>
/// <returns>true if all vertices in the graph is connected</returns>
private bool IsAllVerticesConnected(UndirectedGraph graph)
{
foreach(GraphVertex vertex in graph.AllVertices)
{
if(!vertex.IsVisited)
{
return false;
}
}
return true;
}
public static void TestIsGraphATree()
{
IsGraphATree gt = new IsGraphATree();
UndirectedGraph udg = GraphProbHelper.CreateUndirectedGraphWithoutCycleWithoutUnconnectedNodes();
Console.WriteLine("Is the cycle present in the undirected graph: {0}", gt.IsGraphTree(udg));
udg = GraphProbHelper.CreateUndirectedGraphWithoutCycle();
Console.WriteLine("Is the cycle present in the undirected graph: {0}", gt.IsGraphTree(udg));
udg = GraphProbHelper.CreateUndirectedGraphWithCycle();
Console.WriteLine("Is the cycle present in the undirected graph: {0}", gt.IsGraphTree(udg));
}
}
}
|
using DChild.Gameplay.Combat;
using UnityEngine;
namespace DChild.Gameplay.Environment.Obstacles
{
public abstract class Obstacle : MonoBehaviour
{
protected abstract AttackInfo attackInfo { get; }
protected abstract DamageFXType damageFXType { get; }
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.