text stringlengths 13 6.01M |
|---|
//------------------------------------------------------------------------------
// The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.nopCommerce.com/License.aspx.
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
// See the License for the specific language governing rights and limitations under the License.
//
// The Original Code is nopCommerce.
// The Initial Developer of the Original Code is NopSolutions.
// All Rights Reserved.
//
// Contributor(s): _______.
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using NopSolutions.NopCommerce.BusinessLogic;
using NopSolutions.NopCommerce.BusinessLogic.Audit;
using NopSolutions.NopCommerce.BusinessLogic.Configuration.Settings;
using NopSolutions.NopCommerce.BusinessLogic.Localization;
using NopSolutions.NopCommerce.BusinessLogic.Media;
using NopSolutions.NopCommerce.BusinessLogic.Orders;
using NopSolutions.NopCommerce.BusinessLogic.Products;
using NopSolutions.NopCommerce.Common.Utils;
namespace NopSolutions.NopCommerce.Web.Modules
{
public partial class ProductVariantsInGridControl : BaseNopUserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindData();
}
protected void BindData()
{
Product product = ProductManager.GetProductByID(ProductID);
if (product != null)
{
ProductVariantCollection productVariants = product.ProductVariants;
if (productVariants.Count > 0)
{
rptVariants.DataSource = productVariants;
rptVariants.DataBind();
}
else
this.Visible = false;
}
else
this.Visible = false;
}
protected void rptVariants_OnItemCommand(Object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "AddToCart" || e.CommandName == "AddToWishlist")
{
NumericTextBox txtQuantity = e.Item.FindControl("txtQuantity") as NumericTextBox;
Label productVariantID = e.Item.FindControl("ProductVariantID") as Label;
ProductAttributesControl ctrlProductAttributes = e.Item.FindControl("ctrlProductAttributes") as ProductAttributesControl;
Label lblError = e.Item.FindControl("lblError") as Label;
try
{
if (e.CommandName == "AddToCart")
{
List<string> addToCartWarnings = ShoppingCartManager.AddToCart(ShoppingCartTypeEnum.ShoppingCart,
Convert.ToInt32(productVariantID.Text),
ctrlProductAttributes.SelectedAttributes,
txtQuantity.Value);
if (addToCartWarnings.Count == 0)
{
Response.Redirect("~/ShoppingCart.aspx");
}
else
{
StringBuilder addToCartWarningsSb = new StringBuilder();
for (int i = 0; i < addToCartWarnings.Count; i++)
{
addToCartWarningsSb.Append(Server.HtmlEncode(addToCartWarnings[i]));
if (i != addToCartWarnings.Count - 1)
{
addToCartWarningsSb.Append("<br />");
}
}
lblError.Text = addToCartWarningsSb.ToString();
}
}
if (e.CommandName == "AddToWishlist")
{
List<string> addToCartWarnings = ShoppingCartManager.AddToCart(ShoppingCartTypeEnum.Wishlist,
Convert.ToInt32(productVariantID.Text),
ctrlProductAttributes.SelectedAttributes,
txtQuantity.Value);
if (addToCartWarnings.Count == 0)
{
Response.Redirect("~/Wishlist.aspx");
}
else
{
StringBuilder addToCartWarningsSb = new StringBuilder();
for (int i = 0; i < addToCartWarnings.Count; i++)
{
addToCartWarningsSb.Append(Server.HtmlEncode(addToCartWarnings[i]));
if (i != addToCartWarnings.Count - 1)
{
addToCartWarningsSb.Append("<br />");
}
}
lblError.Text = addToCartWarningsSb.ToString();
}
}
}
catch (Exception exc)
{
LogManager.InsertLog(LogTypeEnum.CustomerError, exc.Message, exc);
lblError.Text = Server.HtmlEncode(exc.Message);
}
}
}
protected void rptVariants_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
ProductVariant productVariant = e.Item.DataItem as ProductVariant;
Panel pnlDownloadSample = e.Item.FindControl("pnlDownloadSample") as Panel;
HyperLink hlDownloadSample = e.Item.FindControl("hlDownloadSample") as HyperLink;
Image iProductVariantPicture = e.Item.FindControl("iProductVariantPicture") as Image;
NumericTextBox txtQuantity = e.Item.FindControl("txtQuantity") as NumericTextBox;
Button btnAddToCart = e.Item.FindControl("btnAddToCart") as Button;
Button btnAddToWishlist = e.Item.FindControl("btnAddToWishlist") as Button;
if (iProductVariantPicture != null)
{
Picture productVariantPicture = productVariant.Picture;
string pictureUrl = PictureManager.GetPictureUrl(productVariantPicture, SettingManager.GetSettingValueInteger("Media.Product.VariantImageSize", 125), false);
if (String.IsNullOrEmpty(pictureUrl))
iProductVariantPicture.Visible = false;
else
iProductVariantPicture.ImageUrl = pictureUrl;
iProductVariantPicture.ToolTip = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), productVariant.Name);
iProductVariantPicture.AlternateText = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), productVariant.Name);
}
btnAddToWishlist.Visible = SettingManager.GetSettingValueBoolean("Common.EnableWishlist");
if (!productVariant.DisableBuyButton)
{
txtQuantity.ValidationGroup = string.Format("ProductVariant{0}", productVariant.ProductVariantID);
btnAddToCart.ValidationGroup = string.Format("ProductVariant{0}", productVariant.ProductVariantID);
btnAddToWishlist.ValidationGroup = string.Format("ProductVariant{0}", productVariant.ProductVariantID);
txtQuantity.Value = productVariant.OrderMinimumQuantity;
}
else
{
txtQuantity.Visible = false;
btnAddToCart.Visible = false;
btnAddToWishlist.Visible = false;
}
if (pnlDownloadSample != null && hlDownloadSample != null)
{
if (productVariant.IsDownload && productVariant.HasSampleDownload)
{
pnlDownloadSample.Visible = true;
hlDownloadSample.NavigateUrl = DownloadManager.GetSampleDownloadUrl(productVariant);
}
else
{
pnlDownloadSample.Visible = false;
}
}
}
}
public int ProductID
{
get
{
return CommonHelper.QueryStringInt("ProductID");
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.UI;
public class navMeshDestination : MonoBehaviour
{
public NavMeshAgent TargetAgent;
public bool moveOnClick = true;
Animator animator;
//PATROLLING
public bool isPatrolling;
private Vector3 targetPoint;
private bool onDestination = true;
private float timer;
public Vector4 MovementRandomPointRange = new Vector4(25, -25, 25, -25);
public LayerMask groundLayer;
//Chasing
public bool isChasingPlayer;
GameObject prey;
Vector3 lastPreyLocation;
//Debug
public Text debug1;
public Text debug2;
public Text debug3;
//STAY UPWARD
float turnSmoothVelocity;
float turnSmoothTime = 0.1f;
// AI sensor
[HideInInspector] public AiSensor sensor;
float distanceToAttack = 1f;
void Start()
{
animator = GetComponent<Animator>();
sensor = GetComponent<AiSensor>();
}
void Update()
{
if (moveOnClick)
{
if (Input.GetMouseButtonDown(0))
{
MoveOnClick();
}
}
if (isPatrolling) Patrolling();
if(TargetAgent.velocity.magnitude > 0.5f)
{
animator.SetBool("isWalking", true);
}
else
{
animator.SetBool("isWalking", false);
}
//stayUpward TODO
RaycastHit hit;
if (Physics.Raycast(transform.position + Vector3.up, Vector3.down, out hit, 3, groundLayer))
{
//aligner le perso a la surface de collision
Vector3 targetDirection = -hit.normal;
float targetAngle = Mathf.Atan2(targetDirection.x, targetDirection.z) * Mathf.Rad2Deg;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
//transform.rotation = Quaternion.AngleAxis(angle,);
}
// CHASE
if (prey == null)
{
prey = FindPrey();
isPatrolling = true;
isChasingPlayer = false;
}
else
{
ChasePrey();
isPatrolling = false;
isChasingPlayer = true;
}
}
GameObject FindPrey()
{
if (sensor.Objects.Count > 0)
{
return sensor.Objects[0];
}
return null;
}
private void ChasePrey()
{
NavMeshHit navMeshHit;
if (NavMesh.SamplePosition(prey.transform.position, out navMeshHit, 2, 1))
{
targetPoint = navMeshHit.position;
lastPreyLocation = targetPoint;
TargetAgent.SetDestination(navMeshHit.position);
onDestination = false;
if ((prey.transform.position - transform.position).magnitude < distanceToAttack)
{
animator.SetTrigger("Attack");
Debug.Log("ATTACK");
}
}
if (!sensor.Objects.Contains(prey))
{
prey = null;
isChasingPlayer = false;
isPatrolling = true;
timer = 3f;
onDestination = false;
targetPoint = lastPreyLocation;
}
}
private void Patrolling()
{
if (onDestination)
{
timer -= Time.deltaTime;
if (timer < 0f) ChooseNewDestination();
}
else
{
if (Vector3.Distance(transform.position, targetPoint) < 2f)
{
ReachDestination();
}
}
}
private void ChooseNewDestination()
{
targetPoint = new Vector3(Random.Range(MovementRandomPointRange.x, MovementRandomPointRange.y), 0f, Random.Range(MovementRandomPointRange.z, MovementRandomPointRange.w));
RaycastHit hit;
if(Physics.Raycast(targetPoint + Vector3.up * 1000f, Vector3.down, out hit, Mathf.Infinity, groundLayer))
{
NavMeshHit navMeshHit;
if (NavMesh.SamplePosition(hit.point, out navMeshHit, 2, 1))
{
targetPoint = navMeshHit.position;
TargetAgent.SetDestination(navMeshHit.position);
onDestination = false;
}
else
{
Debug.Log("pas trouvé");
TargetAgent.SetDestination(hit.point);
}
}
}
private void ReachDestination()
{
timer = Random.Range(1f, 5f);
onDestination = true;
}
private void MoveOnClick()
{
if (TargetAgent)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray.origin, ray.direction, out hit))
{
NavMeshHit navMeshHit;
if (NavMesh.SamplePosition(hit.point, out navMeshHit, 1, 1))
{
TargetAgent.SetDestination(navMeshHit.position);
}
}
}
}
}
|
using BPiaoBao.DomesticTicket.Domain.Models.Orders;
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
namespace BPiaoBao.DomesticTicket.EFRepository.OrdersMap
{
public class CoordinationLogMap : EntityTypeConfiguration<CoordinationLog>
{
public CoordinationLogMap()
{
this.HasKey(t => t.Id);
this.Property(t => t.Content).HasMaxLength(500);
this.Property(t => t.OperationPerson).HasMaxLength(50);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ORMHandsOn;
using Test.ORM.Infrastructure;
namespace Test.ORM.Exercises
{
[TestClass]
public class WhenRetrievingAStudent : WithFreshDatabaseForEveryTest
{
[TestInitialize]
public void SetUp()
{
(new TestDataSeeder()).SeedDatabaseWithStudentEnrolledInCourses(1, "Paulien", 3);
}
[TestMethod]
public void AlsoRetrievesCoursesSheIsEnrolledIn()
{
var coursesPaulienIsEnrolledIn = FindCoursesStudentIsEnrolledIn("Paulien");
Assert.IsNotNull(coursesPaulienIsEnrolledIn);
Assert.AreEqual(3, coursesPaulienIsEnrolledIn.Count, "Paulien should be enrolled in 3 courses");
}
private ICollection<Course> FindCoursesStudentIsEnrolledIn(string studentName)
{
throw new NotImplementedException("Write logic to retrieve all Paulien's courses here.");
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using HtmlAgilityPack;
using Newtonsoft.Json;
namespace QuotesDb
{
public class Quote
{
public int Id { get; set; }
public string Text { get; set; }
public string Author { get; set; }
public Quote(int id, string text, string author)
{
Id = id;
Author = author;
Text = text;
}
}
class Program
{
static void Main(string[] args)
{
// Initialize variables
string dir = Environment.CurrentDirectory;
Directory.CreateDirectory(dir + "/data");
string jsonPath = dir + "/data/" + "quotes.json";
List<Quote> quotes = new List<Quote>();
int id = 0;
// Download data from web. Then save it as HTML.
WebClient webClient = new WebClient();
for (int i = 1; i < 12; i++)
{
webClient.DownloadFile(
"https://www.successories.com/iquote/category/50/motivational-quotes/" + i,
dir + "/data/" + i + ".html"
);
}
// Make operations on every saved file.
for (int i = 1; i < 12; i++)
{
string path = dir + "/data/" + i + ".html";
HtmlDocument doc = new HtmlDocument();
doc.Load(path);
// Get all divs elements in the file.
HtmlNodeCollection allDivs = doc.DocumentNode.SelectNodes("//div");
List<HtmlNode> nodesList = new List<HtmlNode>();
// Search for divs with class "quotebox". Then save them to the list.
foreach (HtmlNode item in allDivs)
{
if (item.HasClass("quotebox"))
{
nodesList.Add(item);
}
}
// For each div in the list search for elements with class "quote" and "aboutquote". Then get important data and save them to the list.
foreach (HtmlNode item in nodesList)
{
HtmlNodeCollection childNodes = item.ChildNodes;
string text = "", author = "";
foreach (HtmlNode node in childNodes)
{
if (node.HasClass("quote"))
{
text = node.InnerText.Replace('"', ' ').Trim();
}
if ((node.HasClass("aboutquote")))
{
string inner = node.ChildNodes.FindFirst("span").InnerHtml;
author = inner.Split('/')[6];
var name = author.Split('-');
author = name[0] + " " + name[1];
Quote quote = new Quote(id, text, author);
quotes.Add(quote);
id++;
}
}
}
}
// Save quotes to JSON file.
using (StreamWriter file = File.AppendText(jsonPath))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, quotes);
}
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using IBAN;
using System.Diagnostics;
namespace IBANTest
{
[TestClass]
public class UnitTest1
{
/// <summary>
/// In diesem Beispiel wird die Zeichenlänge überprüft und ein "true" ausgegeben , wenn die Bedingung erfüllt ist.
/// </summary>
[TestMethod]
public void IsValidDE()
{
//ich instanziiere hier eine Klasse und übergebe die einer neuen Klasse
String Pruefsumme;
Pruefsumme = "DE10550604170000082716";
bool result;
result = IBANnumber.IsValid(Pruefsumme);
Assert.IsTrue(result);
}
[TestMethod]
public void IsValidPL()
{
//ich instanziiere hier eine Klasse und übergebe die einer neuen Klasse
String Pruefsumme;
Pruefsumme = "PL65109017370000000967";
bool result;
result = IBANnumber.IsValid(Pruefsumme);
Assert.IsFalse(result);
}
[TestMethod]
public void IsValidDK()
{
//ich instanziiere hier eine Klasse und übergebe die einer neuen Klasse
String Pruefsumme;
Pruefsumme = "DK3456789012345678";
bool result;
result = IBANnumber.IsValid(Pruefsumme);
Assert.IsFalse(result);
}
[TestMethod]
public void TestGetDEBLZ()
{
//ich instanziiere hier eine Klasse und übergebe die einer neuen Klasse
String iban;
iban = "DE10550604170000082716";
String result;
result = IBANnumber.GetBLZ(iban);
Assert.AreEqual(result, "55060417");
}
[TestMethod]
public void TestGetDEBLZNOT()
{
//ich instanziiere hier eine Klasse und übergebe die einer neuen Klasse
String iban;
iban = "DE1055060417000023213213082716";
String result;
result = IBANnumber.GetBLZ(iban);
Assert.AreNotEqual(result, "55060417");
}
[TestMethod]
public void TestGetDEKonto()
{
//ich instanziiere hier eine Klasse und übergebe die einer neuen Klasse
String iban;
iban = "DE10550604170000082716";
String result;
result = IBANnumber.GetKonto(iban);
Assert.AreEqual(result, "0000082716");
}
[TestMethod]
public void TestGetDEKontoNot()
{
//ich instanziiere hier eine Klasse und übergebe die einer neuen Klasse
String iban;
iban = "DE1055060417000023213213082716";
String result;
result = IBANnumber.GetKonto(iban);
Assert.AreNotEqual(result, "82716");
}
[TestMethod]
public void TestGetPLBLZ()
{
//ich instanziiere hier eine Klasse und übergebe die einer neuen Klasse
String iban;
iban = "PL37109024020000000610000434";
String result;
result = IBANnumber.GetBLZ(iban);
Assert.AreEqual(result, "10902402");
}
[TestMethod]
public void TestGetNotPLBLZ()
{
//ich instanziiere hier eine Klasse und übergebe die einer neuen Klasse
String iban;
iban = "PL37109024020655000000610000434";
String result;
result = IBANnumber.GetBLZ(iban);
Assert.AreNotEqual(result, "10902402");
}
[TestMethod]
public void TestGetPLKonto()
{
//ich instanziiere hier eine Klasse und übergebe die einer neuen Klasse
String iban;
iban = "PL37109024020000000610000434";
String result;
result = IBANnumber.GetKonto(iban);
Assert.AreEqual(result,"0000000610000434");
}
[TestMethod]
public void TestGetCZBLZ()
{
//ich instanziiere hier eine Klasse und übergebe die einer neuen Klasse
String iban;
iban = "CZ6508000000192000145399";
String result;
result = IBANnumber.GetBLZ(iban);
Assert.AreEqual(result, "0800");
}
[TestMethod]
public void TestGetNoTCZBLZ()
{
//ich instanziiere hier eine Klasse und übergebe die einer neuen Klasse
String iban;
iban = "CZ65034253458000000192000145399";
String result;
result = IBANnumber.GetBLZ(iban);
Assert.AreNotEqual(result, "0800");
}
[TestMethod]
public void TestGetCZKonto()
{
//ich instanziiere hier eine Klasse und übergebe die einer neuen Klasse
String iban;
iban = "CZ6508000000192000145399";
String result;
result = IBANnumber.GetKonto(iban);
Assert.AreEqual(result, "00192000145399");
}
[TestMethod]
public void TestGetNotKonto()
{
//ich instanziiere hier eine Klasse und übergebe die einer neuen Klasse
String iban;
iban = "CZ650342534580sadasda00000192000145399";
String result;
result = IBANnumber.GetKonto(iban);
Assert.AreNotEqual(result,"0000192000145399");
}
[TestMethod]
public void TestGenerateGermanIban()
{
String expectedIban ="DE10550604170000082716";
String givenBlz ="55060417";
String givenKtoNr="82716";
String result;
result = IBANnumber.GenerateDeIban(givenBlz, givenKtoNr);
Assert.AreEqual(result, expectedIban);
}
}
}
|
using System;
namespace Web.Models
{
public class Message
{
public int Id { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public DateTime MessageDate { get; set; }
//[RegularExpression("^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,4})$", ErrorMessage = "Not a valid email address")]
public string FromAddress { get; set; }
public string ToAddress { get; set; }
public string AdminUserName { get; set; }
public int RespondId { get; set; }
public bool Incoming { get; set; }
public bool Waiting { get; set; }
public string MessageTypeCode { get; set; }
public string WriterUserId { get; set; }
}
}
|
using System;
using System.Linq;
public class Program
{
public static void Main()
{
var inputList = Console.ReadLine().Split().Select(int.Parse).ToList();
Console.WriteLine($"Min = {inputList.Min()}");
Console.WriteLine($"Max = {inputList.Max()}");
Console.WriteLine($"Sum = {inputList.Sum()}");
Console.WriteLine($"Average = {inputList.Average()}");
}
} |
using Autofac;
namespace BusinessLogic.Core.DI
{
public class CoreModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterAssemblyTypes(ThisAssembly)
.AsImplementedInterfaces();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bat : MonoBehaviour
{
public int hp;
public bool ishurt = false;
public Animator anime;
public GameObject damageuiprefab;
// Start is called before the first frame update
void Start()
{
anime = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.transform.tag == "attackarea" && !ishurt)
{
int damage = 0;
GameObject damageui = Instantiate(damageuiprefab);
damageui.transform.localPosition = transform.position;
damage = PlayerManager.TakeAttack();
damageui.GetComponent<DamageUIControl>().SetText(damage);
hp -= damage;
ishurt = true;
StartCoroutine(hurt());
if (hp <= 0)
{
anime.SetTrigger("dead");
if (transform.parent.GetComponent<BatterControl>())
{
transform.parent.GetComponent<BatterControl>().whenenemyddead();
}
}
}
if (other.transform.tag == "summon1" && !ishurt)
{
int damage = 20;
GameObject damageui = Instantiate(damageuiprefab);
damageui.transform.localPosition = transform.position;
hp -= damage;
damageui.GetComponent<DamageUIControl>().SetText(damage);
ishurt = true;
StartCoroutine(hurt());
if (hp <= 0)
{
anime.SetTrigger("dead");
if (transform.parent.GetComponent<BatterControl>())
{
transform.parent.GetComponent<BatterControl>().whenenemyddead();
}
}
}
}
IEnumerator hurt()
{
yield return new WaitForSeconds(0.5f);
ishurt = false;
}
private void dead()
{
Destroy(this.gameObject);
}
}
|
using System;
using IdentityServer4.Configuration;
using IdentityServer4.Services.Default;
using IdentityServer4.Stores;
using IdentityServer4.Stores.InMemory;
using IdsvrMultiTenant.Services;
using IdsvrMultiTenant.Services.IdSvr;
using IdsvrMultiTenant.Services.MultiTenancy;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace IdsvrMultiTenant
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Saaskit multitenant applications
services.AddMultitenancy<IdsvrTenant, IdsvrTenantResolver>();
var identityServerBuilder = services.AddIdentityServer();
// ----------------------------------------------------------------------------------------------
// standard IdSvr services that we need to define because we don't use AddDeveloperIdentityServer
//
// this is a required service by IdSvr4 - no need for a tenant specific version
identityServerBuilder.Services.AddSingleton<IPersistedGrantStore, InMemoryPersistedGrantStore>();
// scopes are not tenant specific, we can use 1 store for all tenants
identityServerBuilder.Services.AddSingleton<IScopeStore>(_ => new InMemoryScopeStore(Scopes.Get()));
// just a development cert, remember it's best to restart your clients when you restart the server
identityServerBuilder.SetTemporarySigningCredential();
// ---------------------------------------------------------------------------------------------
// tenant specific services
//
// we replace the default IdentityServerOptions with a custom one that returns tenant specific
// IdentityServerOptions
identityServerBuilder.Services.AddTransient<IdentityServerOptions, TenantSpecificIdentityServerOptions>();
// clients are tenant specific
identityServerBuilder.Services.AddScoped<IClientStore, ClientStoreResolver>();
// extraction of the IdSvr4 host example InMemoryLoginService so that we can resolve
// this per tenant
identityServerBuilder.Services.AddScoped<IUserLoginService, UserLoginResolver>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseStaticFiles();
// multitenant aware Idsvr is mounted on "/tenants/<tenant>/" via this construction
app.Map("/tenants", multiTenantIdsvrMountPoint =>
{
// Saaskit.Multitenancy
multiTenantIdsvrMountPoint.UseMultitenancy<IdsvrTenant>();
multiTenantIdsvrMountPoint.UsePerTenant<IdsvrTenant>((ctx, builder) =>
{
var mountPath = "/" + ctx.Tenant.Name.ToLowerInvariant();
// we mount the tenant specific IdSvr4 app under /tenants/<tenant>/
builder.Map(mountPath, idsvrForTenantApp =>
{
var identityServerOptions = idsvrForTenantApp.ApplicationServices.GetRequiredService<IdentityServerOptions>();
// we use our own cookie middleware because Idsvr4 expects it to be included in the
// pipeline as we have changed the default authentication scheme
idsvrForTenantApp.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = identityServerOptions.AuthenticationOptions.AuthenticationScheme,
CookieName = identityServerOptions.AuthenticationOptions.AuthenticationScheme,
AutomaticAuthenticate = true,
SlidingExpiration = false,
ExpireTimeSpan = TimeSpan.FromHours(10)
});
idsvrForTenantApp.UseIdentityServer();
idsvrForTenantApp.UseMvc(routes =>
{
routes.MapRoute(name: "Account",
template: "account/{action=Index}",
defaults: new {controller = "Account"});
});
});
});
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
|
namespace Game.ConsoleUI
{
using System;
using Infrastructure.Helpers;
using Interfaces;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
class Program
{
static void Main()
{
ConfigureServices();
AddUnhandledErrorListener();
Run();
}
private static void Run()
{
var app = ServiceLocator.Provider.GetRequiredService<IGameApplication>();
app.Run();
}
private static void AddUnhandledErrorListener()
{
AppDomain.CurrentDomain.UnhandledException += (s, e) =>
{
var logger = ServiceLocator.Provider.GetRequiredService<ILogger>();
logger.Error(e.ExceptionObject as Exception, "Unhandled error occured");
};
}
private static void ConfigureServices()
{
IConfiguration configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile("appsettings.Development.json", true)
.Build();
ServiceLocator.Provider = new ServiceCollection()
.AddSerilogLogging(configuration)
.AddServices(configuration)
.BuildServiceProvider();
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ChartControl
{
public class SeriesPointCollection : List<SeriesPoint>
{
#region Variables
//List<SeriesPoint> points;
#endregion
#region Constructors
//public SeriesPointCollection()
//{
// points = new List<SeriesPoint>();
//}
#endregion
#region Methods
//public void Add(SeriesPoint Point)
//{
// points.Add(Point);
//}
//public void AddRange(SeriesPoint[] Points)
//{
// points.AddRange(points);
//}
//public void Clear()
//{
// points.Clear();
//}
//public void RemoveAt(int Index)
//{
// points.RemoveAt(Index);
//}
//public void Remove(SeriesPoint Item)
//{
// points.Remove(Item);
//}
public double MaxPointValue()
{
return this.Max<SeriesPoint>(t => t.Value);
}
private static int SortCompare(SeriesPoint Arg1, SeriesPoint Arg2)
{
if (Arg1.Value < Arg2.Value)
return -1;
else if (Arg1.Value > Arg2.Value)
return 1;
else
return 0;
}
#endregion
}
}
|
/*
Copyright (c) 2010, Direct Project
All rights reserved.
Authors:
Umesh Madan umeshma@microsoft.com
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of The Direct Project (directproject.org) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Security.Cryptography.X509Certificates;
using Health.Direct.Common.Certificates;
using Health.Direct.Common.Container;
namespace Health.Direct.Agent.Config
{
/// <summary>
/// A plugin resolver is a CUSTOM certificate resolver. It is arbitrary Type (Assembly + Type) that implements
/// ICertificateResolver.
///
/// You use this object to define the plugin which will be loaded and plugged into the Agent's Certificate
/// resolution pipeline.
///
/// The plugin definition uses Health.Direct.Common.Container.PluginDefinition
/// If your resolver ALSO implements IPlugin, then you will be called to initialize yourself
/// with settings (see below)
///
/// Also see Health.Direct.Agent.Tests.MachineResolverProxy for sample code
/// </summary>
/*
<PluginResolver>
<Definition>
<TypeName>Type Name, Assembly Name</TypeName>
<Settings>
<!-- Your OPTIONAL Xml settings....
If your plugin ALSO implements IPlugin:
When your plugin is loaded, we will invoke IPlugin:Init(pluginDefinition)
The pluginDefinition object has an XmlNode on it containing your settings
-->
</Settings>
</Definition>
</PluginResolver>
* Example:
<PrivateCerts>
<PluginResolver>
<Definition>
<TypeName>Health.Direct.Agent.Tests.MachineResolverProxy, Health.Direct.Agent.Tests</TypeName>
<Settings>
<Name>NHINDPrivate</Name>
</Settings>
</Definition>
</PluginResolver>
</PrivateCerts>
*/
public class PluginCertResolverSettings : CertResolverSettings
{
/// <summary>
/// Create a new PluginCertResolverSettings
/// </summary>
public PluginCertResolverSettings()
{
}
/// <summary>
/// Resolver Type information
/// <see cref="PluginDefinition"/>
/// </summary>
[XmlElement("Definition")]
public PluginDefinition ResolverDefinition
{
get;
set;
}
/// <summary>
/// Validate settings
/// </summary>
public override void Validate()
{
if (this.ResolverDefinition == null)
{
throw new AgentConfigException(AgentConfigError.MissingPluginResolverDefinition);
}
if (!this.ResolverDefinition.HasTypeName)
{
throw new AgentConfigException(AgentConfigError.MissingPluginResolverType);
}
}
/// <summary>
/// Create a new plugin resolver from settings
/// </summary>
/// <returns>Certificate Resolver <see cref="ICertificateResolver"/></returns>
public override ICertificateResolver CreateResolver()
{
return this.ResolverDefinition.Create<ICertificateResolver>();
}
}
}
|
/////////////////////////////////////////////
// FuelCalculator.cs //
// Created by: Markus Lidrot, 2015-10-24 //
/////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment3
{
/// <summary>
/// This class is used to do calculations regarding
/// fuelconsumtion. Five diffrent values are possible do
/// get depending on what values the instancevaribles are
/// set to through the "set"-metohds.
/// </summary>
class FuelCalculator
{
//Declars instance variables
private double currReading;
private double fuelAmount;
private double prevReading;
private double unitPrice;
/// <summary>
/// This method calculates and returns the value of
/// the fuelconsumtion kilometer per liter
/// </summary>
/// <returns>A double</returns>
public double CalcConsumtionKilometerPerLiter()
{
double km = currReading - prevReading;
return (km / fuelAmount);
}
/// <summary>
/// This method calculates and returns the value of
/// the fuelconsumtion per metric mile
/// </summary>
/// <returns>A double</returns>
public double CalcConsumtionPerMetric()
{
const double kmToMileFactor = 0.621371192;
return ((fuelAmount / (currReading - prevReading))/ kmToMileFactor);
}
/// <summary>
/// This method calculates and returns the value of
/// the fuelconsumtion the cost per kilometer
/// </summary>
/// <returns>A double</returns>
public double CalcCostPerKm()
{
return ((fuelAmount / (currReading - prevReading))* unitPrice);
}
/// <summary>
/// This method calculates and returns the value of
/// the fuelconsumtion per liter every kilometer
/// </summary>
/// <returns>A double</returns>
public double CalcFuelConsumtionPerKm()
{
return (fuelAmount / (currReading - prevReading));
}
/// <summary>
/// This method calculates and returns the value of
/// the fuelconsumtion per every swedish mile
/// </summary>
/// <returns>A double</returns>
public double CalcFuelConsumtionPerSweMile()
{
return ((fuelAmount / (currReading - prevReading)) * 10);
}
/// <summary>
/// Metohd that returns the value of currReading
/// </summary>
/// <returns>A double</returns>
public double GetCurrentReading()
{
return currReading;
}
/// <summary>
/// Metohd that returns the value of prevReading
/// </summary>
/// <returns>A double</returns>
private double GetPreviousReading()
{
return prevReading;
}
/// <summary>
/// Metohd that returns the value of fuelAmount
/// </summary>
/// <returns>A double</returns>
public double GetFuelAmount()
{
return fuelAmount;
}
/// <summary>
/// Metohd that returns the value of unirPrice
/// </summary>
/// <returns>A double</returns>
public double GetUnitPrice()
{
return unitPrice;
}
/// <summary>
/// Method that updates the value of currReading variable
/// </summary>
/// <param name="inValue"></param>
public void SetCurrentReading(double newValue)
{
currReading = newValue;
}
/// <summary>
/// Method that updates the value of fuelAmount variable
/// </summary>
/// <param name="inValue"></param>
public void SetFuelAmount(double newValue)
{
fuelAmount = newValue;
}
/// <summary>
/// Method that updates the value of prevReading variable
/// </summary>
/// <param name="inValue"></param>
public void SetPreviousReading(double newValue)
{
prevReading = newValue;
}
/// <summary>
/// Method that updates the value of unitPrice variable
/// </summary>
/// <param name="inValue"></param>
public void SetUnitPrice(double newValue)
{
unitPrice = newValue;
}
/// <summary>
/// Method that checks if current reading is bigger than previous reading.
/// </summary>
/// <returns>A boolean</returns>
public bool ValidateOdometerValue()
{
if(currReading > prevReading)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// Method that checks that no values are negative
/// fuelAmount must be postive for the method
/// CalcConsumtionKilometerPerLiter to work.
/// </summary>
/// <returns>A boolean</returns>
public bool noNegativeValues()
{
if (currReading < 0 || prevReading < 0 || fuelAmount <= 0 || unitPrice < 0)
{
return false;
}
else
{
return true;
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//responsible for the logic on the button expressing an agreement
public class AgreeSelector : MonoBehaviour
{
//inidicate if button is should be available for pushing and triggering actions
private bool isColliding = false;
private bool isAgreeOn = false;
//material to show if button is active or not
public Material onMaterial;
public Material offMaterial;
private void Awake()
{
AnimationEventSystem.OnResetAgreeAnimations += AnimationEventSystem_OnResetAgreeAnimations;
}
private void OnDestroy()
{
AnimationEventSystem.OnResetAgreeAnimations -= AnimationEventSystem_OnResetAgreeAnimations;
}
private void AnimationEventSystem_OnResetAgreeAnimations()
{
isAgreeOn = false;
SwitchMode(isAgreeOn);
}
private void OnTriggerEnter(Collider other)
{
//do not execute if button shouldn't be available again
if (isColliding) return;
isColliding = true;
//start coroutine to delay availability of button
StartCoroutine(Reset());
//do not continue if animationmanager is not existing
AnimationManager animationManager = other.gameObject.GetComponentInParent<AnimationManager>();
if (animationManager == null)
{
return;
}
//ensure no other animations are active
AnimationEventSystem.ResetIdeaAnimations();
//update internal status of animation
isAgreeOn = !isAgreeOn;
SwitchMode(isAgreeOn);
//activate animation if it should be on
if (isAgreeOn)
{
animationManager.SetAgreeAnimation();
return;
}
//reset animation if it should be off
animationManager.SetDefaultAnimation();
}
//responsible to update shown material to player
private void SwitchMode(bool on)
{
//if active, apply "on" material. if not apply "off" material
MeshRenderer meshRenderer = transform.parent.GetComponent<MeshRenderer>();
if (on)
{
meshRenderer.material = onMaterial;
return;
}
meshRenderer.material = offMaterial;
}
//responsible for delaying the availability of the button
IEnumerator Reset()
{
//wait until availability is activated again
yield return new WaitForSeconds(1);
isColliding = false;
}
}
|
namespace Assets.Scripts.Weapons.Interfaces {
public interface IDamaging {
int Damage { get; set; }
}
} |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Xrm.Sdk;
using XrmMoq;
namespace XrmMoqTestPlugin2016.Tests
{
[TestClass]
public class ExamplePlugin2Tests
{
[TestMethod]
[TestCategory("ExampleUnit")]
public void Test_plugin_2016_trace_configurations()
{
//Arrange
//Create the plug-in mock and set the unsecure & secure configurations
CrmPluginMock pluginMock = new CrmPluginMock
{
UnsecureConfiguration = "Hello World",
SecureConfiguration = "Testing 1234"
};
//Act
//Execute the plug-in
pluginMock.Execute<ExamplePlugin2>();
//Assert
//Review the test Output to see the configuration values
Assert.IsNotNull(1);
}
[TestMethod]
[TestCategory("ExampleUnit")]
public void Test_plugin_2016_multiple_retrievemultiple_method_using_orgservice()
{
//Arrange
//Create the plug-in mock
CrmPluginMock pluginMock = new CrmPluginMock();
//Define the result of the first query - type QueryExpressions
EntityCollection accounts = new EntityCollection
{
Entities =
{
new Entity("account") {Id = Guid.NewGuid(), ["name"] = "test1", ["telephone1"] = "555-555-5555"},
new Entity("account") {Id = Guid.NewGuid(), ["name"] = "test2", ["telephone1"] = "333-333-3333"}
}
};
//Define the result of the first query - type FetchExpression
EntityCollection contacts = new EntityCollection
{
Entities =
{
new Entity("contact") {Id = Guid.NewGuid(), ["fullname"] = "Joe Smith", ["telephone1"] = "444-444-4444"},
new Entity("contact") {Id = Guid.NewGuid(), ["fullname"] = "Bob Smith", ["telephone1"] = "777-777-7777"}
}
};
//Set the RetrieveMultiple responses
pluginMock.SetMockRetrieveMultiples(accounts, contacts);
//Act
//Execute the plug-in
ExamplePlugin2 examplePlugin2 = new ExamplePlugin2(String.Empty, String.Empty);
int count = examplePlugin2.GetAccountAndContactCount(pluginMock.FakeOrganizationService);
//Assert
//Review the test Output to see the configuration values
Assert.AreEqual(count, 4);
}
}
} |
using System.Collections.Generic;
using UnityEngine;
using System;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace HT.Framework
{
/// <summary>
/// 任务内容基类
/// </summary>
public abstract class TaskContentBase : ScriptableObject
{
/// <summary>
/// 任务ID
/// </summary>
public string GUID;
/// <summary>
/// 任务名称
/// </summary>
public string Name;
/// <summary>
/// 任务详细介绍
/// </summary>
public string Details;
/// <summary>
/// 任务目标
/// </summary>
public TaskGameObject Target;
/// <summary>
/// 所有任务点
/// </summary>
public List<TaskPointBase> Points = new List<TaskPointBase>();
/// <summary>
/// 所有任务依赖
/// </summary>
public List<TaskDepend> Depends = new List<TaskDepend>();
/// <summary>
/// 是否完成
/// </summary>
public bool IsComplete { get; private set; } = false;
/// <summary>
/// 当前所有未完成的任务点数量
/// </summary>
public int AllUncompletePointCount
{
get
{
int count = 0;
for (int i = 0; i < Points.Count; i++)
{
if (!Points[i].IsComplete)
{
count += 1;
}
}
return count;
}
}
public TaskContentBase()
{
GUID = "";
Name = "";
Details = "";
}
/// <summary>
/// 任务内容开始
/// </summary>
public virtual void OnStart()
{
}
/// <summary>
/// 任务内容开始后,帧刷新
/// </summary>
protected virtual void OnUpdate()
{
}
/// <summary>
/// 任务内容完成
/// </summary>
public virtual void OnComplete()
{
}
internal void OnAutoComplete()
{
if (!IsComplete)
{
List<TaskPointBase> uncompletePoints = new List<TaskPointBase>();
List<int> uncompletePointIndexs = new List<int>();
for (int i = 0; i < Points.Count; i++)
{
if (!Points[i].IsComplete)
{
uncompletePoints.Add(Points[i]);
uncompletePointIndexs.Add(i);
}
}
while (uncompletePoints.Count > 0)
{
for (int i = 0; i < uncompletePoints.Count; i++)
{
if (IsDependComplete(uncompletePointIndexs[i]))
{
uncompletePoints[i].OnAutoComplete();
uncompletePoints.RemoveAt(i);
uncompletePointIndexs.RemoveAt(i);
i -= 1;
}
}
}
IsComplete = true;
}
}
internal void OnMonitor()
{
OnUpdate();
bool isComplete = true;
for (int i = 0; i < Points.Count; i++)
{
if (Points[i].IsEnable && !Points[i].IsComplete)
{
isComplete = false;
if (IsDependComplete(i))
{
Points[i].OnMonitor();
}
}
}
IsComplete = isComplete;
}
internal void ReSet()
{
IsComplete = false;
}
internal bool IsDependComplete(int taskPointIndex)
{
for (int i = 0; i < Depends.Count; i++)
{
if (Depends[i].OriginalPoint == taskPointIndex)
{
int depend = Depends[i].DependPoint;
if (Points[depend].IsEnable && !Points[depend].IsComplete)
{
return false;
}
}
}
return true;
}
#if UNITY_EDITOR
private static readonly int _width = 200;
private int _height = 0;
internal void OnEditorGUI()
{
GUILayout.BeginVertical("ChannelStripBg", GUILayout.Width(_width), GUILayout.Height(_height));
GUILayout.BeginHorizontal();
GUILayout.Label("Task Property:");
GUILayout.EndHorizontal();
GUILayout.Space(5);
_height = 20;
_height += OnPropertyGUI();
GUILayout.EndVertical();
}
public virtual int OnPropertyGUI()
{
int height = 0;
GUILayout.BeginHorizontal();
GUILayout.Label("ID:", GUILayout.Width(50));
GUID = EditorGUILayout.TextField(GUID);
GUILayout.EndHorizontal();
height += 20;
GUILayout.BeginHorizontal();
GUILayout.Label("Name:", GUILayout.Width(50));
Name = EditorGUILayout.TextField(Name);
GUILayout.EndHorizontal();
height += 20;
GUILayout.BeginHorizontal();
GUILayout.Label("Details:", GUILayout.Width(50));
Details = EditorGUILayout.TextField(Details);
GUILayout.EndHorizontal();
height += 20;
GUILayout.BeginHorizontal();
GUILayout.Label("Points:", GUILayout.Width(50));
GUILayout.Label(Points.Count.ToString());
GUILayout.EndHorizontal();
height += 20;
TaskGameObjectField(ref Target, "Target:", 50);
height += 20;
return height;
}
public bool IsExistDepend(int originalPoint, int dependPoint)
{
for (int i = 0; i < Depends.Count; i++)
{
if (Depends[i].OriginalPoint == originalPoint && Depends[i].DependPoint == dependPoint)
{
return true;
}
}
return false;
}
public void DisconnectDepend(int originalPoint, int dependPoint)
{
for (int i = 0; i < Depends.Count; i++)
{
if (Depends[i].OriginalPoint == originalPoint && Depends[i].DependPoint == dependPoint)
{
Depends.RemoveAt(i);
i -= 1;
}
}
}
public void ConnectDepend(int originalPoint, int dependPoint)
{
Depends.Add(new TaskDepend(originalPoint, dependPoint));
}
protected void TaskGameObjectField(ref TaskGameObject taskGameObject, string name, float nameWidth)
{
if (taskGameObject == null)
{
taskGameObject = new TaskGameObject();
}
GUILayout.BeginHorizontal();
GUIContent gUIContent = new GUIContent(name);
gUIContent.tooltip = "GUID: " + taskGameObject.GUID;
GUILayout.Label(gUIContent, GUILayout.Width(nameWidth));
GUI.color = taskGameObject.AgentEntity ? Color.white : Color.gray;
GameObject newEntity = EditorGUILayout.ObjectField(taskGameObject.AgentEntity, typeof(GameObject), true, GUILayout.Width(_width - nameWidth - 35)) as GameObject;
if (newEntity != taskGameObject.AgentEntity)
{
if (newEntity != null)
{
TaskTarget target = newEntity.GetComponent<TaskTarget>();
if (!target)
{
target = newEntity.AddComponent<TaskTarget>();
}
if (target.GUID == "<None>")
{
target.GUID = Guid.NewGuid().ToString();
}
taskGameObject.AgentEntity = newEntity;
taskGameObject.GUID = target.GUID;
taskGameObject.Path = newEntity.transform.FullName();
}
}
GUI.color = Color.white;
if (taskGameObject.AgentEntity == null && taskGameObject.GUID != "<None>")
{
taskGameObject.AgentEntity = GameObject.Find(taskGameObject.Path);
if (taskGameObject.AgentEntity == null)
{
TaskTarget[] targets = FindObjectsOfType<TaskTarget>();
foreach (TaskTarget target in targets)
{
if (taskGameObject.GUID == target.GUID)
{
taskGameObject.AgentEntity = target.gameObject;
taskGameObject.Path = target.transform.FullName();
break;
}
}
}
else
{
TaskTarget target = taskGameObject.AgentEntity.GetComponent<TaskTarget>();
if (!target)
{
target = taskGameObject.AgentEntity.AddComponent<TaskTarget>();
target.GUID = taskGameObject.GUID;
}
}
}
gUIContent = EditorGUIUtility.IconContent("TreeEditor.Trash");
gUIContent.tooltip = "Delete";
GUI.enabled = taskGameObject.GUID != "<None>";
if (GUILayout.Button(gUIContent, "InvisibleButton", GUILayout.Width(20), GUILayout.Height(20)))
{
taskGameObject.AgentEntity = null;
taskGameObject.GUID = "<None>";
taskGameObject.Path = "";
}
GUI.enabled = true;
GUILayout.EndHorizontal();
}
internal static void GenerateSerializeSubObject(UnityEngine.Object obj, UnityEngine.Object mainAsset)
{
obj.hideFlags = HideFlags.HideInHierarchy;
AssetDatabase.AddObjectToAsset(obj, mainAsset);
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(mainAsset));
}
internal static void DestroySerializeSubObject(UnityEngine.Object obj, UnityEngine.Object mainAsset)
{
AssetDatabase.RemoveObjectFromAsset(obj);
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(mainAsset));
}
#endif
}
} |
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityStandardAssets.CrossPlatformInput;
public class PlayerController : MonoBehaviour
{
[Header("General")]
[SerializeField] float ControlSpeed = 60f;
[SerializeField] float ySpeed = 60f;
[SerializeField] float yRange = 35f;
[SerializeField] float xRange = 24f;
[SerializeField] GameObject[] guns;
[Header("Screen-position based")]
[SerializeField] float positionPitchFactor = -5f;
[SerializeField] float controlPitchFactor = -5f;
float xThrow = 0f;
float yThrow = 0f;
[Header("Control-throw based")]
[SerializeField] float positionYawFactor;
[SerializeField] float controlRollFactor;
[SerializeField] bool isControlEnabled = true;
void Start()
{
}
void Update()
{
if (isControlEnabled)//Checks to see if the ship has collided with anything (AKA Died)
{
ProcessTranslation();//allows the ship to fly up down left and right
ProcessRotation();//rotates the ship as necessary
ProcessFiring();//Shoot guns
}
}
void ProcessRotation()//This whole function calculates the rotation required depending on the position of ship on screen
{
float pitchDueToPosition = transform.localPosition.y * positionPitchFactor;
float pitchDueToControlThrow = yThrow * controlPitchFactor;
float pitch = pitchDueToPosition + pitchDueToControlThrow;
float yaw = transform.localPosition.x * positionYawFactor;
float roll = xThrow * controlRollFactor;
transform.localRotation = Quaternion.Euler(pitch, yaw, roll);
}
void ProcessTranslation()//This function just moves the ship based on the calculations of the other functions
{
transform.localPosition = new Vector3(ProcessedXInput(), ProcessedYInput(), transform.localPosition.z);
}
float ProcessedXInput()//Process how fast and how far the ship will go on the X Axis
{
xThrow = CrossPlatformInputManager.GetAxis("Horizontal");
float xOffset = xThrow * ControlSpeed * Time.deltaTime;
float rawXPos = transform.localPosition.x + xOffset;
float clampedXPos = Mathf.Clamp(rawXPos, -xRange, xRange);//Keeps the ship from going off screen
return clampedXPos;
}
float ProcessedYInput()//Process how fast and how far the ship will go on the Y Axis
{
yThrow = CrossPlatformInputManager.GetAxis("Vertical");
float yOffset = yThrow * ySpeed * Time.deltaTime;
float rawYPos = transform.localPosition.y + yOffset;
float clampedYPos = Mathf.Clamp(rawYPos, -yRange, yRange);//Keeps the ship from going off screen
return clampedYPos;
}
void ProcessFiring()//Turns the guns on and off by activating and deactiving the gameobject
{
if (CrossPlatformInputManager.GetButton("Fire"))
{
SetGunsActive(true);
}
else
{
SetGunsActive(false);
}
}
private void SetGunsActive(bool isActive)// Turn on the gun object
{
foreach (GameObject gun in guns)
{
var emissionModule = gun.GetComponent<ParticleSystem>().emission;
emissionModule.enabled = isActive;
}
}
void OnPlayerDeath()//Small function for the collider script to call, when the ship collides it disables the controls
{
isControlEnabled = false;
}
void OnCollisionEnter(Collision col) //This does nothing but debug for collisions
{
print("Player Collided With Something");
}
void Reload()//Reloads the scene AKA Level
{
SceneManager.LoadScene(1);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using SampleApplication.App_Base;
using AppactsPlugin.Data.Model.Enum;
namespace SampleApplication
{
public partial class PageFeedback : PhoneApplicationPageBase
{
#region //Private Properties
private string pageNameNavigateFrom;
#endregion
#region //Constructor
/// <summary>
/// Initializes a new instance of the <see cref="PageFeedback"/> class.
/// </summary>
public PageFeedback()
: base("Feedback")
{
InitializeComponent();
this.Loaded += this.PageFeedback_Loaded;
}
/// <summary>
/// Handles the Loaded event of the PageFeedback control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
public void PageFeedback_Loaded(object sender, RoutedEventArgs e)
{
this.pageNameNavigateFrom = NavigationContext.QueryString["pageName"];
this.txtUserMessage.Text = string.Format(this.txtUserMessage.Text, this.pageNameNavigateFrom);
}
#endregion
#region //Private Properties
/// <summary>
/// Handles the Click event of the btnSend control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
private void btnSend_Click(object sender, RoutedEventArgs e)
{
RatingType? ratingType = null;
ListBoxItem listBoxItemRating = this.lstRating.SelectedItem as ListBoxItem;
if (listBoxItemRating != null)
{
ratingType = (RatingType)int.Parse((string)listBoxItemRating.Content);
}
try
{
AppactsPlugin.AnalyticsSingleton.GetInstance().LogFeedback(this.pageNameNavigateFrom, ratingType.Value, this.txtFeedback.Text);
}
catch (AppactsPlugin.Data.Model.ExceptionDatabaseLayer)
{
//todo: handle the error
}
NavigationService.GoBack();
}
/// <summary>
/// Handles the Click event of the btnCancel control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
NavigationService.GoBack();
}
#endregion
}
} |
namespace OmniSharp.Extensions.LanguageServer.Protocol.Server
{
public interface IWorkspaceLanguageServer : ILanguageServerProxy
{
}
}
|
using crud.Data;
using crud.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace crud.Controllers
{
public class UserController : Controller
{
private readonly MySQLContext _db;
public UserController(MySQLContext db)
{
_db = db;
}
public IActionResult List(string _txtSearch)
{
List<TBL_USER> LstUser = new List<TBL_USER>();
if (!string.IsNullOrEmpty(_txtSearch)) // ช่อง search ไม่เท่ากับ null หรือ ค่าว่าง ให้ where ค้นหาด้วย
{
// select * from TBL_USER where FirstName like '%_txtSearch%' or LastName like '%_txtSearh%'
LstUser = _db.TBL_USER.Where(o => o.FirstName.Contains(_txtSearch) || o.LastName.Contains(_txtSearch)).ToList(); // Contains คือ where like บน sql
}
else
{
// select * from TBL_USER
LstUser = _db.TBL_USER.ToList();
}
return View(LstUser);
}
public IActionResult Edit(int UserId)// UserId ส่งมาจาก View ปุ่ม Edit (asp-route-UserId)
{
TBL_USER User = new TBL_USER();
// select * from TBL_USER where UserId = UserId
User = _db.TBL_USER.FirstOrDefault(o => o.UserId == UserId);
return View(User);//ส่งข้อมูลที่ View/User/Edit
}
public IActionResult Update(TBL_USER _user)
{
TBL_USER User = new TBL_USER();
User = _db.TBL_USER.FirstOrDefault(o => o.UserId == _user.UserId);
if (User != null)
{
//เอาข้อมูลใหม่แทนที่ข้อมูลเดิม
User.FirstName = _user.FirstName;
User.LastName = _user.LastName;
User.IsActive = _user.IsActive;
_db.SaveChanges();// Save ลง database
}
return RedirectToAction("List");
}
public IActionResult Create()
{
TBL_USER NewUser = new TBL_USER();
return View(NewUser);
}
public IActionResult Insert(TBL_USER _user)
{
_db.TBL_USER.Add(new TBL_USER
{
FirstName = _user.FirstName,
LastName = _user.LastName,
IsActive = _user.IsActive
});
_db.SaveChanges();
return RedirectToAction("List");
}
public IActionResult Delete(int UserId)
{
TBL_USER User = new TBL_USER();
User = _db.TBL_USER.FirstOrDefault(o => o.UserId == UserId);
_db.TBL_USER.Remove(User);
_db.SaveChanges();
return RedirectToAction("List");
}
}
}
|
namespace akka_microservices_proj.Messages
{
public class GetProductsMessage
{
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace Traslator
{
class Program
{
static void Main(string[] args)
{
string text = "Hello World!";
Console.WriteLine("Original Text: " + text);
Console.WriteLine();
Console.WriteLine("---------------------------------------");
Console.WriteLine("Translated Text: " + Util.TraslateText(text));
Console.ReadKey();
}
}
public class Util
{
public static string TraslateText(string text)
{
string url = String.Format
("https://translate.googleapis.com/translate_a/single?client=gtx&sl={0}&tl={1}&dt=t&q={2}",
"en", "pt-BR", Uri.EscapeUriString(text));
HttpClient httpClient = new HttpClient();
string result = httpClient.GetStringAsync(url).Result;
var jsonData = JsonConvert.DeserializeObject<List<dynamic>>(result);
var translationItems = jsonData[0];
string translation = "";
foreach (object item in translationItems)
{
IEnumerable translationLineObject = item as IEnumerable;
IEnumerator translationLineString = translationLineObject.GetEnumerator();
translationLineString.MoveNext();
translation += string.Format(" {0}", Convert.ToString(translationLineString.Current));
}
if (translation.Length > 1) { translation = translation.Substring(1); };
return translation;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
using Jokedst.GetOpt;
using System.Text;
using WindowsFormsAppPaint;
namespace WindowsFormsAppPaint
{
class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string [] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// For the sake of this example, we're just printing the arguments to the console.
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine("args[{0}] == {1}", i, args[i]);
}
string paramFileName = string.Empty;
bool paramAll = false;
var opt = new GetOpt("Chuong trinh ky ten",
new[] {
new CommandLineOption('s', "save", "Luu file voi ten da duoc quy uoc", ParameterType.String, o => paramFileName = (string)o),
new CommandLineOption('a', "all", "Tai ve tat ca cac file", ParameterType.None, o => paramAll = true),
});
try
{
opt.ParseOptions(args);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return;
}
Form1 myForm = new Form1();
myForm.DestinationFileName = paramFileName;
// Tim hieu va phan tich bang GetOpt
Application.Run(myForm);
}
}
}
|
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Web.Models
{
public class Recording
{
//There's a one-to-zero-or-one relationship between the Meeting and the Recording entities.
//A Recording only exists in relation to the Meeting it's assigned to,
//and therefore its primary key is also its foreign key to the Meeting entity.
//http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-a-more-complex-data-model-for-an-asp-net-mvc-application
[Key]
[ForeignKey("Meeting")]
public int MeetingId { get; set; }
public int Size { get; set; }
public string RecordingUrl { get; set; }
public virtual Meeting Meeting { get; set; }
}
} |
using System;
namespace FelixTheCat.BlackHole
{
class BlackHoleGenerator
{
public static string[,] GetBlackHoleSymbols()
{
string[,] symbols =
{
{"░░▒▒▓▓███████████████████████████████████████████████████████████████████████████████▓▓▒▒░░"},
{" ░░▒▒▓▓███████████████████████████████████████████████████████████████████████████▓▓▒▒░░ "},
{" ░░▒▒▓▓███████████████████████████████████████████████████████████████████████▓▓▒▒░░ "},
{" ░░▒▒▓▓███████████████████████████████████████████████████████████████████▓▓▒▒░░ "},
//{" ░░▒▒▓▓███████████████████████████████████████████████████████████████▓▓▒▒░░ "},
};
return symbols;
}
public static BlackHole GenerateBlackHole(int windowHeight, int windowWidth)
{
ConsoleColor color = ConsoleColor.DarkRed;
BlackHole blackHole = new BlackHole(GetBlackHoleSymbols(), color, 0, 0);
int startX = (windowWidth - blackHole.Width) / 2;
int startY = (windowHeight - blackHole.Height) / 2;
blackHole.StartX = startX;
blackHole.StartY = startY;
return blackHole;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TQ.SaveFilesExplorer.Components
{
internal enum CopyKeysType
{
KeysOnly,
KeysType,
KeysTypeData,
DistinctKeys,
DistinctKeysType,
DistinctKeysTypeData,
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using AjaxPro;
using SKT.MES.User.Model;
using SKT.MES.User.BLL;
using System.Text;
using SKT.MES.Utility;
namespace SKT.MES.Web.AjaxServices.User
{
/// <summary>
/// 系统Ajax类
/// </summary>
public class AjaxServiceUser
{
/// <summary>
/// 编辑用户
/// </summary>
/// <param name="entity"></param>
/// <param name="hiredDate"></param>
/// <param name="termination"></param>
[AjaxMethod]
public void UserEdit(UsersInfo entity, String hiredDate, String termination)
{
try
{
Users bll = new Users();
entity.HiredDate = (hiredDate == "") ? Convert.ToDateTime("9999-12-31") : Convert.ToDateTime(hiredDate);
entity.TerminationDate = (termination == "") ? Convert.ToDateTime("9999-12-31") : Convert.ToDateTime(termination);
bll.Edit(entity);
}
catch (Exception ex)
{
WebHelper.HandleException(ex);
}
}
/// <summary>
/// 编辑角色
/// </summary>
/// <param name="entity"></param>
[AjaxMethod]
public void RoleEdit(RoleInfo entity)
{
try
{
Role bll = new Role();
bll.Edit(entity);
}
catch (Exception ex)
{
WebHelper.HandleException(ex);
}
}
/// <summary>
/// 分配权限给角色
/// </summary>
/// <param name="roleId"></param>
/// <param name="popedomString"></param>
[AjaxMethod]
public void AssignPopodomToRole(Int32 roleId, String popedomString)
{
try
{
Role role = new Role();
role.AssignPopedomToRole(roleId, popedomString);
}
catch (Exception ex)
{
WebHelper.HandleException(ex);
}
}
/// <summary>
/// 从用户中移除角色
/// </summary>
/// <param name="userId"></param>
/// <param name="roleIdString"></param>
/// <param name="userName"></param>
[AjaxMethod]
public void RemoveRolesFromUser(Int32 userId, String roleIdString, String userName)
{
try
{
(new Role()).RemoveRolesFromUser(userId, roleIdString, userName);
}
catch (Exception ex)
{
WebHelper.HandleException(ex);
}
}
/// <summary>
/// 分配角色给用户
/// </summary>
/// <param name="userId"></param>
/// <param name="roleIdString"></param>
[AjaxMethod]
public void AssignRolesToUser(Int32 userId, String roleIdString)
{
try
{
(new Role()).AssignRolesToUser(userId, roleIdString);
}
catch (Exception ex)
{
WebHelper.HandleException(ex);
}
}
/// <summary>
/// 导出权限用户
/// </summary>
/// <param name="popedom"></param>
/// <returns></returns>
[AjaxMethod]
public String[] ExportPopedomUser(Int32 popedom)
{
String[] reportSource = new String[3];
StringBuilder sb = new StringBuilder();
List<UsersInfo> list = null;
try
{
sb.Append(Resources.lang.RoleName);
sb.Append("\t");
sb.Append(Resources.lang.DefaultUserName);
sb.Append("\n");
list = (new Users()).GetPopedomUsers(0, -1, popedom);
foreach (UsersInfo entity in list)
{
sb.Append(entity.RoleName);
sb.Append("\t");
sb.Append(entity.LoginID);
sb.Append("\n");
}
}
catch (Exception ex)
{
WebHelper.HandleException(ex);
}
reportSource[0] = sb.ToString();
reportSource[1] = (list.Count + 1).ToString();
reportSource[2] = "2";
return reportSource;
}
/// <summary>
/// 修改密码
/// </summary>
/// <param name="oldpwd"></param>
/// <param name="newpwd"></param>
/// <returns></returns>
[AjaxMethod]
public string ChangePwd(string oldpwd, string newpwd)
{
string result = "";
try
{
int re = (new Users()).ChangeUserPassword(AccountController.GetCurrentUser().UserID, oldpwd, newpwd);
if (re == 0)
{
result = Resources.Messages.InvalidOldPassword;
}
else if (re == -1)
{
result = Resources.Messages.InvalidMembership;
}
}
catch (Exception ex)
{
WebHelper.HandleException(ex);
}
return result;
}
/// <summary>
/// 重置密码
/// </summary>
/// <param name="userIdStr"></param>
[AjaxMethod]
public void ResetPwd(string userIdStr)
{
try
{
(new Users()).ResetPwd(userIdStr);
}
catch (Exception ex)
{
WebHelper.HandleException(ex);
}
}
/// <summary>
/// 解锁用户
/// </summary>
/// <param name="userIdStr"></param>
[AjaxMethod]
public void UnlockUser(string userIdStr)
{
try
{
(new Users()).UnlockUser(userIdStr);
}
catch (Exception ex)
{
WebHelper.HandleException(ex);
}
}
/// <summary>
/// 注销用户
/// </summary>
/// <param name="userId"></param>
[AjaxMethod]
public void LogoffUser(int userId)
{
try
{
(new Users()).LogoffUser(userId);
}
catch (Exception ex)
{
WebHelper.HandleException(ex);
}
}
[AjaxMethod]
public List<RoleInfo> GetAllRole()
{
List<RoleInfo> list = null;
try
{
list = (new Role()).GetAll(0, -1, "RoleName", null);
}
catch (Exception ex)
{
WebHelper.HandleException(ex);
}
return list;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Timers;
using System.Web;
using DAL.Interface;
using Microsoft.AspNetCore.SignalR;
namespace DrawingGame.Hubs
{
public class RoomHub : Hub
{
private readonly IAnswer _answers;
private readonly IRoomConnection _roomConnections;
private readonly IRoom _rooms;
public RoomHub(IAnswer answers, IRoomConnection roomConnections, IRoom rooms)
{
_answers = answers;
_roomConnections = roomConnections;
_rooms = rooms;
}
public async Task AddToGroup(string groupName, string userName)
{
var connectionId = Context.ConnectionId;
await Groups.AddToGroupAsync(connectionId, groupName); //todo move to confirm player login - to add to group only once confirmed
_roomConnections.AddToRoom(groupName, connectionId, userName);
await Clients.Group(groupName).SendAsync("RecieveNewPlayerMaster", connectionId, userName);
}
public override async Task OnDisconnectedAsync(Exception exception)
{
var roomConnection = _roomConnections.GetForConnection(Context.ConnectionId);
var room = roomConnection.Room;
await Groups.RemoveFromGroupAsync(Context.ConnectionId, room.KeyCode);
var masterConnectionId = _roomConnections.GetMaster(room.KeyCode).ConnectionId;
if (masterConnectionId == Context.ConnectionId)
{
_rooms.SetGameEnded(room);
}
else
{
await Clients.Client(masterConnectionId).SendAsync("PlayerDisconnected", Context.ConnectionId);
}
}
public async Task ConfirmPlayerLogin(string connectionId, string lightColor, string darkColor)
{
await Clients.Client(connectionId).SendAsync("ConfirmPlayerJoin", lightColor, darkColor);
}
public async Task CreateNewGroup(string groupName)
{
await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
_roomConnections.AddToRoom(groupName, Context.ConnectionId, "master", true);
await Clients.Group(groupName).SendAsync("RoomStarted", groupName);
}
public async Task StartRound(string groupName)
{
await Clients.Group(groupName).SendAsync("StartRound");
}
public async Task RequestAnswer()
{
var a = _answers.GetRandomAnswer(false).Text;
await Clients.Client(Context.ConnectionId).SendAsync("RecieveAnswer", a);
}
public async Task ReadyDrawing(string groupName, string userName)
{
await Clients.Group(groupName).SendAsync("ReadyDrawing", Context.ConnectionId, userName);
}
public async Task GetDrawing(string connectionId)
{
await Clients.Client(connectionId).SendAsync("GetDrawing", Context.ConnectionId);
}
public async Task SendDrawing(string connectionId, string answer, int[] clickX, int[] clickY, bool[] clickDrag, bool[] colorToggle, float canvasWidth, float canvasHeight)
{
await Clients.Client(connectionId).SendAsync("RecieveDrawing", Context.ConnectionId, answer, clickX, clickY, clickDrag, colorToggle, canvasWidth, canvasHeight);
}
public async Task StartVoting(string groupName)
{
await Clients.Group(groupName).SendAsync("StartVoting", Context.ConnectionId);
}
public async Task SubmitAnswer(string connectionId, string userName, string answer)
{
await Clients.Client(connectionId).SendAsync("GetAnswer", Context.ConnectionId, userName, answer);
}
public async Task GuessCorrectAnswer(string groupName, string[] answers)
{
await Clients.Group(groupName).SendAsync("GuessCorrectAnswer", answers);
}
public async Task VoteAnswer(string connectionId, string userName, int buttonId)
{
await Clients.Client(connectionId).SendAsync("GetVote", Context.ConnectionId, userName, buttonId);
}
public async Task FinishVoting(string groupName)
{
await Clients.Group(groupName).SendAsync("VotingFinished");
}
public async Task FinishAnswering(string groupName)
{
await Clients.Group(groupName).SendAsync("AnsweringFinished");
}
}
}
|
using System;
using System.Windows;
using System.Windows.Input;
using BPiaoBao.Client.DomesticTicket.ViewModel;
using GalaSoft.MvvmLight.Messaging;
using JoveZhao.Framework;
namespace BPiaoBao.Client.DomesticTicket.View
{
/// <summary>
/// ChoosePolicyWindow.xaml 的交互逻辑
/// </summary>
public partial class ChoosePolicyWindow
{
public ChoosePolicyWindow()
{
InitializeComponent();
KeyDown += ChoosePolicyWindow_KeyDown;
Messenger.Default.Register<bool>(this, "close_choose_policy_window", p =>
{
if (!p) return;
try
{
Messenger.Default.Unregister<bool>(this, "close_choose_policy_window");
Close();
}
catch (Exception ex)
{
Logger.WriteLog(LogType.ERROR, "",ex);
}
});
dg.Columns[0].Visibility = LocalUIManager.DefaultShowhiddenColumn ? Visibility.Visible : Visibility.Collapsed;
}
void ChoosePolicyWindow_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.F7) return;
if (dg.Columns[0].Visibility == Visibility.Visible)
{
dg.Columns[0].Visibility = Visibility.Collapsed;
dg.Columns[5].Visibility = Visibility.Collapsed;
LocalUIManager.DefaultShowhiddenColumn = false;
}
else
{
dg.Columns[0].Visibility = Visibility.Visible;
dg.Columns[5].Visibility = Visibility.Visible;
LocalUIManager.DefaultShowhiddenColumn = true;
}
if (Messenger.Default != null)
{
Messenger.Default.Send(dg.Columns[0].Visibility,
ChoosePolicyViewModel.ChoosePolicyToTicketBookingQueryViewMessage_Commission);
Messenger.Default.Send(dg.Columns[0].Visibility,
ChoosePolicyViewModel.ChoosePolicyToPnrViewMessage_Commission);
}
var main = DataContext as ChoosePolicyViewModel;
if (main == null) return;
main.IsShowCommissionColumn = dg.Columns[0].Visibility;
}
}
}
|
using System;
namespace NetworkToolkit.Connections
{
/// <summary>
/// A read-only collection of connection properties.
/// </summary>
public interface IConnectionProperties
{
/// <summary>
/// Gets a property.
/// </summary>
/// <param name="type">The type of the property to retrieve.</param>
/// <param name="value">The value of the property retrieved.</param>
/// <returns>
/// If a property for the given <paramref name="type"/> was found, true.
/// Otherwise, false.
/// </returns>
bool TryGetProperty(Type type, out object? value);
}
}
|
using System;
using System.Threading.Tasks;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Realeyes.Application.DTOs;
using Realeyes.Application.Sessions.Commands;
namespace Realeyes.Api.Controllers
{
[ApiController]
[Route("api/sessions")]
public class SessionController : ControllerBase
{
private readonly IMediator mediator;
public SessionController(IMediator mediator)
{
this.mediator = mediator;
}
[HttpPost]
public async Task<ActionResult<SessionDTO>> Create([FromBody] Guid? surveyId = null)
{
SessionDTO result = await mediator.Send(new CreateSessionCommand(surveyId));
if (result == null)
{
return BadRequest();
}
return Ok(result);
}
[HttpPut("{id}/start")]
public async Task<ActionResult<SessionDTO>> Start(Guid id)
{
SessionDTO result = await mediator.Send(new StartSessionCommand(id));
return Ok(result);
}
[HttpPut("{id}/complete")]
public async Task<ActionResult<SessionDTO>> Complete( Guid id)
{
SessionDTO result = await mediator.Send(new CompleteSessionCommand(id));
return Ok(result);
}
}
}
|
namespace OmniGui.Geometry
{
public struct Point
{
public Point(double x, double y)
{
X = x;
Y = y;
}
public double X { get; }
public double Y { get; }
public static Point Zero => new Point(0, 0);
public Point Offset(Point offset)
{
return new Point(offset.X + X, offset.Y + Y);
}
public override string ToString()
{
return $"{nameof(X)}: {X}, {nameof(Y)}: {Y}";
}
public static Point operator +(Point point, Vector vector)
{
return new Point(point.X + vector.X, point.Y + vector.Y);
}
public static Point operator -(Point point, Vector vector)
{
return new Point(point.X - vector.X, point.Y - vector.Y);
}
public static Point operator -(Point point)
{
return new Point(-point.X, -point.Y);
}
public static explicit operator Vector(Point a)
{
return new Vector(a.X, a.Y);
}
}
} |
/*
* Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
* If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.
*
* For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284.
* The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
*
* Evaluate the sum of all the amicable numbers under 10000.
*/
var lookup = new Dictionary<int, int>();
for (var i = 1; i < 10000; i++)
{
var factors = GetFactors(i);
var divisorSum = 0;
foreach (var factor in factors)
if (factor != i)
divisorSum += factor;
lookup.Add(i, divisorSum);
}
var sum = 0;
for (var i = 1; i < 10000; i++)
if (lookup.TryGetValue(lookup[i], out var value) && i != lookup[i] && i == value)
sum += i;
Console.WriteLine(sum);
private static IEnumerable<int> GetFactors(int n)
{
var factors = new List<int>();
for (int i = 1; i <= Math.Sqrt(n); i++)
{
if (n % i == 0)
{
factors.Add(i);
if (n / i != i)
factors.Add(n / i);
}
}
factors.Sort();
return factors;
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QualificationExaming.Entity
{
/// <summary>
/// 成绩表
/// </summary>
public class Score
{
/// <summary>
/// 成绩主键
/// </summary>
public int ScoreID { get; set; }
/// <summary>
/// 成绩
/// </summary>
public string Scores { get; set; }
/// <summary>
/// 试卷id
/// </summary>
public int ExamID { get; set; }
/// <summary>
/// 试卷名称
/// </summary>
public string ExamName { get; set; }
/// <summary>
/// 交卷时间
/// </summary>
public DateTime CreateTime { get; set; }
/// <summary>
/// 是否随机
/// </summary>
public bool isRandom { get; set; }
/// <summary>
/// 用户id
/// </summary>
public int UserID { get; set; }
}
}
|
using System;
using static yocto.Preconditions;
namespace yocto
{
public static class AsSingletonExtension
{
public static IRegistration AsSingleton(this IRegistration registration, bool eagerLoad = false)
{
CheckIsNotNull(nameof(registration), registration);
return registration.Register(Instancing.SingletonInstance, eagerLoad);
}
public static IRegistration RegisterSingleton<T, V>(this IContainer container) where V : class, T where T : class
{
CheckIsNotNull(nameof(container), container);
return container.Register<T,V>().AsSingleton();
}
public static IRegistration RegisterSingleton<T, V>(this IContainer container, bool eagerLoad) where V : class, T where T : class
{
CheckIsNotNull(nameof(container), container);
return container.Register<T, V>().AsSingleton(eagerLoad);
}
public static IRegistration RegisterSingleton<T>(this IContainer container, Func<T> factory) where T : class
{
CheckIsNotNull(nameof(container), container);
CheckIsNotNull(nameof(factory), factory);
return container.Register(factory).AsSingleton();
}
public static IRegistration RegisterSingleton<T>(this IContainer container, Func<T> factory, bool eagerLoad) where T : class
{
CheckIsNotNull(nameof(container), container);
CheckIsNotNull(nameof(factory), factory);
return container.Register(factory).AsSingleton(eagerLoad);
}
}
}
|
namespace Tennis
{
public class TennisGame2 : ITennisGame
{
private int p1point;
private int p2point;
private string p1res = "";
private string p2res = "";
private string player1Name;
private string player2Name;
public TennisGame2(string player1Name, string player2Name)
{
this.player1Name = player1Name;
p1point = 0;
this.player2Name = player2Name;
}
private string ScoreBelow4(int point)
{
var score = "";
switch(point)
{
case 0:
score = "Love";
break;
case 1:
score = "Fifteen";
break;
case 2:
score = "Thirty";
break;
case 3:
score = "Forty";
break;
}
return score;
}
private bool isPlayerWinner(int p1, int p2)
{
if (p1>= 4 && p2>= 0 && (p1- p2) >= 2) return true;
else { return false; }
}
private bool isPlayerAdvantage(int p1, int p2)
{
if (p1 > p2 && p2 >= 3) return true;
else { return false;}
}
private bool isScoreAll()
{
if (p1point == p2point && p1point < 3) return true;
else { return false; }
}
private bool isScoreDeuce()
{
if (p1point == p2point && p1point > 2) return true;
else { return false; }
}
private bool isBelow4()
{
if (p1point <= 3 && p2point <= 3 && p1point != p2point) return true;
else { return false; }
}
public string GetScore()
{
if (isPlayerWinner(p1point, p2point))
{
return "Win for player1";
}
else if (isPlayerWinner(p2point, p1point))
{
return "Win for player2";
}
else if (isScoreAll())
{
var s = ScoreBelow4(p1point);
return s += "-All";
}
else if (isScoreDeuce())
{
return "Deuce";
}
else if (isBelow4())
{
return ScoreBelow4(p1point) + "-" + ScoreBelow4(p2point);
}
else if (isPlayerAdvantage(p1point, p2point))
{
return "Advantage player1";
}
else if (isPlayerAdvantage(p2point, p1point))
{
return "Advantage player2";
}
else
{
throw new System.Exception("Invalid score");
}
}
private void P1Score()
{
p1point++;
}
private void P2Score()
{
p2point++;
}
public void WonPoint(string player)
{
if (player == "player1")
P1Score();
else
P2Score();
}
}
}
|
using System.Collections.Generic;
using System.ServiceModel;
using CallCenter.Server.Helper;
namespace CallCenter.ServiceContracts.Services
{
[ServiceContract]
[ServiceKnownType("GetKnownTypes", typeof(KnownTypesHelper))]
public interface IReopsitoryServiceBase<T>
{
[OperationContract]
void DeleteById(int id);
[OperationContract]
IEnumerable<T> GetAll();
[OperationContract]
T GetById(int id);
[OperationContract]
IEnumerable<T> GetByName(string entityName);
[OperationContract]
int Insert(T entity);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AbstractClasses
{
abstract class myBaseClass
{
public abstract int myMethod(int arg1, int arg2);
}
}
|
//
// commercio.sdk - Sdk for Commercio Network
//
// Riccardo Costacurta
// Dec. 30, 2019
// BlockIt s.r.l.
//
//
using System;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics;
using commercio.sacco.lib;
namespace commercio.sdk
{
public class MsgShareDocument : StdMsg
{
#region Properties
public CommercioDoc document { get; private set; }
// The override of the value getter is mandatory to obtain a correct codified Json
public override Dictionary<String, Object> value
{
get
{
return _toJson();
}
}
#endregion
#region Constructors
/// Public constructor.
public MsgShareDocument(CommercioDoc document)
{
Trace.Assert(document != null);
// Assigns the properties
this.document = document;
base.setProperties("commercio/MsgShareDocument", _toJson());
}
#endregion
#region Public Methods
#endregion
#region Helpers
private Dictionary<String, Object> _toJson()
{
Dictionary<String, Object> wk = this.document.toJson();
return wk;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AirCaddy.Domain.ViewModels.Privileges
{
public class PrivilegeRequestViewModel
{
public string CourseName { get; set; }
public string CourseAddress { get; set; }
public string City { get; set; }
public string StateCode { get; set; }
public string Zip { get; set; }
public string CoursePhoneNumber { get; set; }
public string CourseType { get; set; }
public string Reason { get; set; }
}
}
|
// -----------------------------------------------------------------------
// <file>World.cs</file>
// <copyright></copyright>
// <author>Aleksandar Jeremic</author>
// <summary>Projekat Grafika 12.1</summary>
// -----------------------------------------------------------------------
using System;
using Assimp;
using System.IO;
using System.Reflection;
using SharpGL.SceneGraph;
using SharpGL.SceneGraph.Primitives;
using SharpGL.SceneGraph.Quadrics;
using SharpGL.SceneGraph.Core;
using SharpGL;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Threading;
namespace AssimpSample
{
/// <summary>
/// Klasa enkapsulira OpenGL kod i omogucava njegovo iscrtavanje i azuriranje.
/// </summary>
public class World : IDisposable
{
#region Atributi
/// <summary>
/// Scena koja se prikazuje.
/// </summary>
private AssimpScene m_scene_motor;
private AssimpScene m_scene_semafor;
/// <summary>
/// Ugao rotacije sveta oko X ose.
/// </summary>
private float m_xRotation = 0.0f;
/// <summary>
/// Ugao rotacije sveta oko Y ose.
/// </summary>
private float m_yRotation = 0.0f;
/// <summary>
/// Menjanje visine bandere preko slajdera
/// </summary>
private double skaliranje_bandere = 1;
/// <summary>
/// Menjanej ambinetalne komponente tackastog izvora svetlosti
/// </summary>
private float m_ambient_R= 1.0f;
private float m_ambient_G = 1.0f;
private float m_ambient_B= 0.7f;
private float m_ambient_Alpha = 1.0f;
/// <summary>
/// Atributi za animaciju.
/// </summary>
public static bool startAnimation = false;
public static DispatcherTimer timer;
private static float x=0.0f;
private static float z=3500.0f;
private static float rotate=0.0f;
public static bool endAnimation=false;
public static bool disapper = false;
/// <summary>
/// Pomeranje brzine motora
/// </summary>
public static float brzina_motora = 100.0f;
/// <summary>
/// Udaljenost scene od kamere.
/// </summary>
private float m_sceneDistance = 12000.0f;
/// <summary>
/// Sirina OpenGL kontrole u pikselima.
/// </summary>
private int m_width;
/// <summary>
/// Visina OpenGL kontrole u pikselima.
/// </summary>
private int m_height;
/// <summary>
/// Identifikatori tekstura za jednostavniji pristup teksturama
/// </summary>
private enum TextureObjects { Road = 0, Wood, Building };
private readonly int m_textureCount = Enum.GetNames(typeof(TextureObjects)).Length;
/// <summary>
/// Identifikatori OpenGL tekstura
/// </summary>
private uint[] m_textures = null;
/// <summary>
/// Putanje do slika koje se koriste za teksture
/// </summary>
private string[] m_textureFiles = { "..//..//Texture//road.jpg", "..//..//Texture//wood.jpg", "..//..//Texture//building.jpg" };
#endregion Atributi
#region Properties
/// <summary>
/// Scena koja se prikazuje.
/// </summary>
public AssimpScene Motor_Scene
{
get { return m_scene_motor; }
set { m_scene_motor = value; }
}
public AssimpScene Semafor_Scene
{
get { return m_scene_semafor; }
set { m_scene_semafor = value; }
}
/// <summary>
/// Ugao rotacije sveta oko X ose.
/// </summary>
public float RotationX
{
get { return m_xRotation; }
set { m_xRotation = value; }
}
/// <summary>
/// Pocetak Animacije
/// </summary>
//public bool StartAnimation
//{
// get { return startAnimation; }
// set { startAnimation = value; }
//}
/// <summary>
/// Ugao rotacije sveta oko Y ose.
/// </summary>
public float RotationY
{
get { return m_yRotation; }
set { m_yRotation = value; }
}
/// <summary>
/// Udaljenost scene od kamere.
/// </summary>
public float SceneDistance
{
get { return m_sceneDistance; }
set { m_sceneDistance = value; }
}
/// <summary>
/// Sirina OpenGL kontrole u pikselima.
/// </summary>
public int Width
{
get { return m_width; }
set { m_width = value; }
}
public double Skaliranje_bandere
{
get { return skaliranje_bandere; }
set { skaliranje_bandere = value; }
}
public float Ambient_R {
get { return m_ambient_R; }
set { m_ambient_R = value; }
}
public float Ambient_G
{
get { return m_ambient_G; }
set { m_ambient_G = value; }
}
public float Ambient_B
{
get { return m_ambient_B; }
set { m_ambient_B = value; }
}
public float Ambient_Alpha
{
get { return m_ambient_Alpha; }
set { m_ambient_Alpha = value;
}
}
/// <summary>
/// Visina OpenGL kontrole u pikselima.
/// </summary>
public int Height
{
get { return m_height; }
set { m_height = value; }
}
#endregion Properties
#region Konstruktori
/// <summary>
/// Konstruktor klase World.
/// </summary>
public World(String scenePath, String sceneFileName, String scenePath2, String sceneFileName2, int width, int height, OpenGL gl)
{
this.m_scene_motor = new AssimpScene(scenePath, sceneFileName, gl);
this.m_scene_semafor = new AssimpScene(scenePath2, sceneFileName2, gl);
this.m_width = width;
this.m_height = height;
m_textures = new uint[m_textureCount];
}
/// <summary>
/// Destruktor klase World.
/// </summary>
~World()
{
this.Dispose(false);
}
#endregion Konstruktori
#region Metode
/// <summary>
/// Korisnicka inicijalizacija i podesavanje OpenGL parametara.
/// </summary>
public void Initialize(OpenGL gl)
{
gl.ClearColor(0.0f, 0.0f, 0.0f, 1.0f);
gl.Color(1f, 0f, 0f);
gl.ShadeModel(OpenGL.GL_FLAT);
gl.Enable(OpenGL.GL_DEPTH_TEST);
gl.Enable(OpenGL.GL_CULL_FACE);
gl.Enable(OpenGL.GL_NORMALIZE);
//STAVKA 1
gl.Enable(OpenGL.GL_COLOR_MATERIAL);
gl.ColorMaterial(OpenGL.GL_FRONT, OpenGL.GL_AMBIENT);
gl.ColorMaterial(OpenGL.GL_BACK, OpenGL.GL_DIFFUSE);
Tekstura(gl);
m_scene_motor.LoadScene();
m_scene_motor.Initialize();
m_scene_semafor.LoadScene();
m_scene_semafor.Initialize();
}
//STAVKA 3
/// <summary>
/// Podesavanje teksture
/// </summary>
private void Tekstura(OpenGL gl)
{
// Teksture se primenjuju sa parametrom add
gl.Enable(OpenGL.GL_TEXTURE_2D);
gl.TexEnv(OpenGL.GL_TEXTURE_ENV, OpenGL.GL_TEXTURE_ENV_MODE, OpenGL.GL_ADD);
// Ucitaj slike i kreiraj teksture
gl.GenTextures(m_textureCount, m_textures);
for (int i = 0; i < m_textureCount; ++i)
{
// Pridruzi teksturu odgovarajucem identifikatoru
gl.BindTexture(OpenGL.GL_TEXTURE_2D, m_textures[i]);
// Ucitaj sliku i podesi parametre teksture
Bitmap image = new Bitmap(m_textureFiles[i]);
// rotiramo sliku zbog koordinantog sistema opengl-a
image.RotateFlip(RotateFlipType.RotateNoneFlipY);
Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);
// RGBA format (dozvoljena providnost slike tj. alfa kanal)
BitmapData imageData = image.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
gl.Build2DMipmaps(OpenGL.GL_TEXTURE_2D, (int)OpenGL.GL_RGBA8, image.Width, image.Height, OpenGL.GL_BGRA, OpenGL.GL_UNSIGNED_BYTE, imageData.Scan0);
gl.TexParameter(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_MIN_FILTER, OpenGL.GL_NEAREST); // Najblizi sused filtriranja
gl.TexParameter(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_MAG_FILTER, OpenGL.GL_NEAREST); // Najblizi sused filtriranja
gl.TexParameter(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_WRAP_S, OpenGL.GL_REPEAT); //Podesen wrapping na repeat
gl.TexParameter(OpenGL.GL_TEXTURE_2D, OpenGL.GL_TEXTURE_WRAP_T, OpenGL.GL_REPEAT);
gl.TexEnv(OpenGL.GL_TEXTURE_ENV, OpenGL.GL_TEXTURE_ENV_MODE, OpenGL.GL_ADD); //Nacin stapanja teksture sa materijalom
image.UnlockBits(imageData);
image.Dispose();
}
}
//STAVKA 2
/// <summary>
/// Definisanje tackastog izvora svetlosti. STAVKA 2
/// </summary>
private void SvetloIzvor(OpenGL gl,float r,float g,float b,float a) {
float[] light0pos = new float[] { 10000.0f, 500.0f, 10000, 1.0f };
float[] light0ambient= { r, g, b, a };
float[] light0diffuse = { r, g, b, a };
// Pridruži komponente svetlosnom izvoru 0
gl.Light(OpenGL.GL_LIGHT0, OpenGL.GL_POSITION, light0pos);
gl.Light(OpenGL.GL_LIGHT0, OpenGL.GL_AMBIENT, light0ambient);
gl.Light(OpenGL.GL_LIGHT0, OpenGL.GL_SPOT_CUTOFF, 180.0f);
gl.Light(OpenGL.GL_LIGHT0, OpenGL.GL_DIFFUSE, light0diffuse);
// Podesi parametre tackastog svetlosnog izvora
gl.Enable(OpenGL.GL_LIGHTING);
gl.Enable(OpenGL.GL_LIGHT0);
}
/// <summary>
/// Stavka 9 svetlo usmereno ka motoru
/// </summary>
/// <param name="gl"></param>
private void crvenoSvetlo(OpenGL gl)
{
float[] light1pos = new float[] { -2400.0f, 500.0f, 1000, 1.0f };
//float[] ambijentalnaKomponenta1 = { 1f, 0f, 0f, 1f };
float[] difuznaKomponenta1 = { 1.0f, 0f, 0f, 1.0f };
float[] light_dir = { 1f, -0.5f, 0.8f };
// Pridruži komponente svetlosnom izvoru 1
gl.Light(OpenGL.GL_LIGHT1, OpenGL.GL_DIFFUSE,difuznaKomponenta1);
// Podesi parametre tackastog svetlosnog izvora
gl.Light(OpenGL.GL_LIGHT1, OpenGL.GL_SPOT_DIRECTION, light_dir);
gl.Light(OpenGL.GL_LIGHT1, OpenGL.GL_SPOT_CUTOFF, 40.0f);
gl.Light(OpenGL.GL_LIGHT1, OpenGL.GL_POSITION, light1pos);
gl.Enable(OpenGL.GL_LIGHTING);
gl.Enable(OpenGL.GL_LIGHT1);
}
/// <summary>
/// Iscrtavanje OpenGL kontrole.
/// </summary>
public void Draw(OpenGL gl)
{
gl.Clear(OpenGL.GL_COLOR_BUFFER_BIT | OpenGL.GL_DEPTH_BUFFER_BIT);
gl.LoadIdentity();
gl.Viewport(0, 0, m_width, m_height);
gl.PushMatrix();
gl.Translate(0.0f, 0.0f, -m_sceneDistance);
gl.Rotate(m_xRotation, 1.0f, 0.0f, 0.0f);
gl.Rotate(m_yRotation, 0.0f, 1.0f, 0.0f);
// stavka 6 pozicioniranje kamere iza i iznad motora usmerena ka putu
gl.LookAt(0, 1500, 0, 0, 0, -m_sceneDistance, 0, 1, 0);
gl.PushMatrix();
SvetloIzvor(gl,m_ambient_R,m_ambient_G,m_ambient_B,m_ambient_Alpha);
crvenoSvetlo(gl);
DrawSemafor(gl);
DrawMotor(gl);
gl.PopMatrix();
DrawPodloga(gl);
DrawZgrada1(gl);
DrawZgrada2(gl);
DrawBandera1(gl);
gl.PushMatrix();
gl.Scale(1, skaliranje_bandere, 1);
DrawBandera2(gl);
gl.PopMatrix();
DrawText(gl);
gl.PopMatrix();
// Oznaci kraj iscrtavanja
gl.Flush();
}
/// <summary>
/// Podesava viewport i projekciju za OpenGL kontrolu.
/// </summary>
public void Resize(OpenGL gl, int width, int height)
{
m_width = width;
m_height = height;
gl.MatrixMode(OpenGL.GL_PROJECTION); // selektuj Projection Matrix
gl.LoadIdentity();
gl.Perspective(45f, (double)width / height, 0.5f, 30000f);
gl.Viewport(0, 0, m_width, m_height);
gl.MatrixMode(OpenGL.GL_MODELVIEW);
gl.LoadIdentity(); // resetuj ModelView Matrix
}
public void DrawMotor(OpenGL gl)
{
gl.PushMatrix();
gl.Translate(x, -500.0f, z);
gl.Rotate(90, 180, rotate);
gl.Color(1.0f, 1.0f, 1.0f);
gl.Scale(2, 2, 2);
gl.TexEnv(OpenGL.GL_TEXTURE_ENV, OpenGL.GL_TEXTURE_ENV_MODE, OpenGL.GL_MODULATE); // Nacin stapanja teksture motora
m_scene_motor.Draw();
gl.PopMatrix();
gl.TexEnv(OpenGL.GL_TEXTURE_ENV, OpenGL.GL_TEXTURE_ENV_MODE, OpenGL.GL_ADD);
}
public void DrawSemafor(OpenGL gl)
{
gl.PushMatrix();
gl.Translate(800.0f, 1500.0f, 2200.0f);
gl.Color(0.5f, 0.5f, 0.5f, 1.0f);
//gl.Rotate(0, 0, 0);
gl.Scale(8, 8, 8);
gl.TexEnv(OpenGL.GL_TEXTURE_ENV, OpenGL.GL_TEXTURE_ENV_MODE, OpenGL.GL_MODULATE); // Nacin stapanja teksture semafora
m_scene_semafor.Draw();
gl.PopMatrix();
gl.TexEnv(OpenGL.GL_TEXTURE_ENV, OpenGL.GL_TEXTURE_ENV_MODE, OpenGL.GL_ADD);
}
private void DrawPodloga(OpenGL gl)
{
//STAVKA 5 Podloga tekstura betona
gl.MatrixMode(OpenGL.GL_TEXTURE);
gl.LoadIdentity();
gl.Scale(100.0f, 100.0f, 100.0f); // skaliranje teksture podloge
gl.MatrixMode(OpenGL.GL_MODELVIEW);
gl.Color(0.1, 0.1, 0.1);
gl.TexEnv(OpenGL.GL_TEXTURE_ENV, OpenGL.GL_TEXTURE_ENV_MODE, OpenGL.GL_ADD);
gl.BindTexture(OpenGL.GL_TEXTURE_2D, m_textures[(int)TextureObjects.Road]);
gl.PushMatrix();
gl.Translate(0, -500f, 0);
gl.Scale(30, 15, 30);
gl.Begin(OpenGL.GL_QUADS);
gl.TexCoord(0, 0);
gl.Vertex(300, 0, 200);
gl.TexCoord(1, 0);
gl.Vertex(300, 0, -200);
gl.TexCoord(1, 1);
gl.Vertex(-300, 0, -200);
gl.TexCoord(0, 1);
gl.Vertex(-300, 0, 200);
gl.End();
gl.MatrixMode(OpenGL.GL_TEXTURE); // vracanje na pocetnu matricu za teksture
gl.LoadIdentity();
gl.MatrixMode(OpenGL.GL_MODELVIEW);
gl.PopMatrix();
}
private void DrawZgrada1(OpenGL gl)
{
gl.PushMatrix();
gl.MatrixMode(OpenGL.GL_TEXTURE_MATRIX);
gl.BindTexture(OpenGL.GL_TEXTURE_2D, m_textures[(int)TextureObjects.Building]);
gl.Scale(2000, 3000, 3000);
gl.Translate(-3f, 0.84f, 0f);
//gl.Color(0.57f, 0.28f, 0.0f);
Cube zgrada1 = new Cube();
zgrada1.Render(gl, SharpGL.SceneGraph.Core.RenderMode.Render);
gl.PopMatrix();
}
private void DrawZgrada2(OpenGL gl)
{
gl.PushMatrix();
gl.MatrixMode(OpenGL.GL_TEXTURE_MATRIX);
gl.BindTexture(OpenGL.GL_TEXTURE_2D, m_textures[(int)TextureObjects.Building]);
gl.Scale(2000, 3000, 3000);
gl.Translate(3f, 0.84f, 0f);
//gl.Color(0.57f, 0.28f, 0.0f);
Cube zgrada2 = new Cube();
zgrada2.Render(gl, SharpGL.SceneGraph.Core.RenderMode.Render);
gl.PopMatrix();
}
private void DrawBandera1(OpenGL gl)
{
gl.PushMatrix();
gl.MatrixMode(OpenGL.GL_TEXTURE_MATRIX);
//BANDERA TEKSUTRA DRVETA STAVKA 4
gl.BindTexture(OpenGL.GL_TEXTURE_2D, m_textures[(int)TextureObjects.Wood]);
gl.Translate(-3000.0f, -485.0f, 0.0f);
gl.Rotate(-90f, 0f, 0f);
Cylinder stub = new Cylinder();
stub.TopRadius = 50f;
stub.BaseRadius = 50f;
stub.Height = 2500f;
stub.CreateInContext(gl);
stub.Render(gl, SharpGL.SceneGraph.Core.RenderMode.Render);
gl.PopMatrix();
gl.PushMatrix();
gl.MatrixMode(OpenGL.GL_TEXTURE_MATRIX);
gl.BindTexture(OpenGL.GL_TEXTURE_2D, m_textures[(int)TextureObjects.Wood]);
gl.Translate(-3000.0f, 2200.0f, 0.0f);
gl.Scale(300f, 300f, 300f);
Cube svetlo = new Cube();
svetlo.Render(gl, SharpGL.SceneGraph.Core.RenderMode.Render);
gl.PopMatrix();
}
private void DrawBandera2(OpenGL gl)
{
gl.PushMatrix();
//BANDERA TEKSUTRA DRVETA STAVKA 4
gl.MatrixMode(OpenGL.GL_TEXTURE_MATRIX);
gl.BindTexture(OpenGL.GL_TEXTURE_2D, m_textures[(int)TextureObjects.Wood]);
gl.Translate(3000.0f, -485.0f, 0.0f);
gl.Rotate(-90f, 0f, 0f);
Cylinder stub = new Cylinder();
stub.TopRadius = 50f;
stub.BaseRadius = 50f;
stub.Height = 2500f;
stub.CreateInContext(gl);
stub.Render(gl, SharpGL.SceneGraph.Core.RenderMode.Render);
gl.PopMatrix();
gl.PushMatrix();
gl.MatrixMode(OpenGL.GL_TEXTURE_MATRIX);
gl.BindTexture(OpenGL.GL_TEXTURE_2D, m_textures[(int)TextureObjects.Wood]);
//gl.Color(0.45f, 0.47f, 0.44f);
gl.Translate(3000.0f, 2200.0f, 0.0f);
gl.Scale(300f, 300f, 300f);
Cube svetlo = new Cube();
svetlo.Render(gl, SharpGL.SceneGraph.Core.RenderMode.Render);
gl.PopMatrix();
}
private void DrawText(OpenGL gl)
{
gl.PushMatrix();
gl.Viewport(m_width / 2, 0, m_width / 2, m_height / 2);
gl.Color(0f, 0f, 1f);
gl.DrawText(m_width - 400, 140, 0f, 0f, 1f, "", 10, "");
gl.DrawText(m_width - 400, 140, 0f, 0f, 1f, "Arial Italic", 10, "Predmet : Racunarska grafika");
gl.DrawText(m_width - 400, 110, 0f, 0f, 1f, "Arial Italic", 10, "Sk. god: 2018/19");
gl.DrawText(m_width - 400, 80, 0f, 0f, 1f, "Arial Italic", 10, "Ime: Aleksandar");
gl.DrawText(m_width - 400, 50, 0f, 0f, 1f, "Arial Italic", 10, "Prezime: Jeremic");
gl.DrawText(m_width - 400, 20, 0f, 0f, 1f, "Arial Italic", 10, "Sifra zad: 12.1");
gl.Viewport(0, 0, m_width, m_height);
gl.PopMatrix();
}
/// <summary>
/// Stavka 11 Animacija klikom na dugme V
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public static void Animacija(object sender, EventArgs e)
{
if (z == 3500.0f)
{
timer.Start();
z -= brzina_motora;
}else if(z<3500 && z > -4000)
{
z -= brzina_motora;
}else if (z<= -4000 && z>=-4300)
{
if (x == 0)
{
rotate = -90;
x += brzina_motora;
}else if (x>0 && x < 10000)
{
x += brzina_motora;
}else if (x >= 10000 && x<=10400)
{
disapper = true;
x += brzina_motora;
}else if (x>10000 && x < 11000)
{
x += brzina_motora;
}else if (x >= 11000)
{
startAnimation = false;
endAnimation = true;
z = 3500.0f;
x = 0.0f;
rotate = 0;
disapper = false;
timer.Stop();
}
}
}
/// <summary>
/// Implementacija IDisposable interfejsa.
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
m_scene_motor.Dispose();
m_scene_semafor.Dispose();
}
}
#endregion Metode
#region IDisposable metode
/// <summary>
/// Dispose metoda.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
#endregion IDisposable metode
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BreakAway.Domain;
using BreakAway.Models;
using BreakAway.Models.Customer;
using ITCloud.Web.Routing;
using Studentum.Infrastructure.Repository;
using Studentum.Infrastructure.Repository.Specifications;
namespace BreakAway.Web.Controllers
{
public class CustomerController : Controller
{
[UrlRoute(Path = "customer")]
public ActionResult Index(IndexViewModel.Form filter = null, string sortExpression = null, int page = 1, string message = null)
{
CustomerRepository repository = RepositoryFactory.GetReadOnlyRepository<CustomerRepository>();
filter = filter ?? new IndexViewModel.Form();
if (!string.IsNullOrWhiteSpace(message))
ViewBag.Message = message;
int pageSize = 25;
int skipIndex = (page - 1)*pageSize;
IQueryable<Customer> customers = repository.Items;
if (!string.IsNullOrWhiteSpace(filter.FirstName))
customers = customers.Where(c => c.FirstName.StartsWith(filter.FirstName));
if (!string.IsNullOrWhiteSpace(filter.LastName))
customers = customers.Where(c => c.LastName.StartsWith(filter.LastName));
if (filter.CustomerType.HasValue)
{
int customerTypeId = (int)filter.CustomerType.Value;
customers = customers.Where(c => c.CustomerTypeId == customerTypeId);
}
int totalItems = customers.Count();
customers = customers.OrderBy(c => c.LastName).ThenBy(c => c.FirstName);
customers = customers.Skip(skipIndex).Take(pageSize);
var items = customers.Select(c => new IndexViewModel.CustomerItem
{
Id = c.Id,
FirstName = c.FirstName.Trim(),
LastName = c.LastName.Trim(),
Type = (CustomerType)c.CustomerTypeId,
PrimaryActivity = c.PrimaryActivity.Name,
SecondaryActivity = c.SecondaryActivity.Name
});
IndexViewModel viewModel = new IndexViewModel {Paging = new PagingInfo(page, totalItems, pageSize), Filter = filter, Customers = items.ToArray()};
return View(viewModel);
}
}
}
|
using System;
namespace Arch.Data.Orm.FastInvoker
{
public interface IDynamicConstructorInfo
{
Object Invoke(Object[] parameters);
}
}
|
namespace Task02_Products
{
using System;
public class Product : IComparable
{
public Product(string name, double price)
{
this.Name = name;
this.Price = price;
}
public string Name { get; set; }
public double Price { get; set; }
public int CompareTo(object obj)
{
var product = obj as Product;
if (product != null)
{
return (int)(this.Price - product.Price);
}
return -1;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.Security.Cryptography.X509Certificates;
namespace ZiZhuJY.ServiceModel
{
/// <summary>
/// A class that derive from the ServiceHost system class to automatically set the
/// server certificate used for service authentication.
/// This class set the Credentials.ServiceCertificate.Certificate property override any certificate configuration.
/// Consider anyway that you must correctly configure the binding security.
/// </summary>
public class CertificateServiceHost : ServiceHost
{
public CertificateServiceHost(Type serviceType, Uri[] baseAddresses)
: base(serviceType, baseAddresses)
{
}
protected override void ApplyConfiguration()
{
try
{
//Check if there is a valid configuration section
Configuration.Section section = Configuration.Section.GetSection();
if (section == null || section.Services == null)
{
//System.IO.File.WriteAllText(@"test.txt", string.Format("section is null"));
return;
}
//Check if there is a valid configuration for this service
Configuration.ServiceElement element = section.Services.GetElementByKey(Description.ConfigurationName);
if (element == null)
{
//StringBuilder sb = new StringBuilder();
//foreach (Configuration.ServiceElement service in section.Services)
//{
// sb.AppendLine(service.Name);
//}
//System.IO.File.WriteAllText(@"test2.txt", string.Format("element is null, Description.Name: {0}\r\nAll services list:{1}", Description.ConfigurationName, sb.ToString()));
return;
}
X509Certificate2 serverCertificate = element.GetServerCertificate();
//Set the server certificate
if (serverCertificate != null)
{
this.Credentials.ServiceCertificate.Certificate = serverCertificate;
}
else
{
//System.IO.File.WriteAllText(@"test3.txt", string.Format("serverCertificate is null"));
}
//Set the userNameAuthentication
Configuration.UserNameAuthenticationElement userNameAuthElement = section.UserNameAuthentication;
if (userNameAuthElement != null)
{
this.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = userNameAuthElement.UserNamePasswordValidationMode;
// Don't know how to configure the MembershipProvider from conig files, currently use default membership provider
//this.Credentials.UserNameAuthentication.MembershipProvider = userNameAuthElement.MembershipProviderName;
}
base.ApplyConfiguration();
//Set the client certificates and the validator
if (string.IsNullOrEmpty(element.ClientCertificates) == false)
{
X509ClientCertificateAuthentication authentication =
this.Credentials.ClientCertificate.Authentication;
authentication.CertificateValidationMode =
System.ServiceModel.Security.X509CertificateValidationMode.Custom;
authentication.CustomCertificateValidator =
new CustomCertificateValidator(element.GetClientCertificates());
}
}
catch(Exception ex)
{
//throw;
System.IO.File.WriteAllText(System.Web.Hosting.HostingEnvironment.MapPath("~/Exception2.txt"), string.Format("Error occurred: {0}\r\n{1}\r\n{2}", ex.Message, ex.Source, ex.StackTrace));
}
finally
{
}
}
}
}
|
using System.Text;
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using System.Net.Http;
using System.Drawing;
using System.Collections.ObjectModel;
using System.Xml;
using System.ComponentModel;
using System.Reflection;
namespace LinnworksAPI
{
public static class WarehouseTransferMethods
{
private static JsonSerializerSettings serializerSettings = new JsonSerializerSettings() { DateFormatString = "yyyy-MM-ddTHH:mm:ss.ffZ"};
public static WarehouseTransferItem AddItemToTransfer(Guid fkTransferId,Guid pkStockItemId,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<WarehouseTransferItem>(Factory.GetResponse("WarehouseTransfer/AddItemToTransfer", "fkTransferId=" + fkTransferId + "&pkStockItemId=" + pkStockItemId + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static Guid AddTransferBinNote(Guid fkTransferBinId,String note,Guid fkTransferId,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<Guid>(Factory.GetResponse("WarehouseTransfer/AddTransferBinNote", "fkTransferBinId=" + fkTransferBinId + "¬e=" + note + "&fkTransferId=" + fkTransferId + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static Guid AddTransferItemNote(Guid fkTransferId,Guid fkTransferItemId,String note,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<Guid>(Factory.GetResponse("WarehouseTransfer/AddTransferItemNote", "fkTransferId=" + fkTransferId + "&fkTransferItemId=" + fkTransferItemId + "¬e=" + note + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static Guid AddTransferNote(Guid pkTransferId,String note,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<Guid>(Factory.GetResponse("WarehouseTransfer/AddTransferNote", "pkTransferId=" + pkTransferId + "¬e=" + note + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static Guid AddTransferProperty(Guid fkTransferId,String propertyName,String propertyValue,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<Guid>(Factory.GetResponse("WarehouseTransfer/AddTransferProperty", "fkTransferId=" + fkTransferId + "&propertyName=" + propertyName + "&propertyValue=" + propertyValue + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static Int32 AllocateItemToBin(Guid pkSrcBinId,Guid pkDstBinId,Guid pkTransferItemId,Int32 quantity,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<Int32>(Factory.GetResponse("WarehouseTransfer/AllocateItemToBin", "pkSrcBinId=" + pkSrcBinId + "&pkDstBinId=" + pkDstBinId + "&pkTransferItemId=" + pkTransferItemId + "&quantity=" + quantity + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static void ChangeBinDetails(Guid pkTransferId,Guid pkBinId,String BinName,String BinReference,String BinBarcode,Guid ApiToken, String ApiServer)
{
Factory.GetResponse("WarehouseTransfer/ChangeBinDetails", "pkTransferId=" + pkTransferId + "&pkBinId=" + pkBinId + "&BinName=" + BinName + "&BinReference=" + BinReference + "&BinBarcode=" + BinBarcode + "", ApiToken, ApiServer);
}
public static void ChangeTransferFromLocation(Guid pkTransferId,Guid newLocationId,Guid ApiToken, String ApiServer)
{
Factory.GetResponse("WarehouseTransfer/ChangeTransferFromLocation", "pkTransferId=" + pkTransferId + "&newLocationId=" + newLocationId + "", ApiToken, ApiServer);
}
public static void ChangeTransferItemReceivedQuantity(Guid pkTransferId,Guid pkBinId,Guid pkTransferItemId,Int32? Quantity,Guid ApiToken, String ApiServer)
{
Factory.GetResponse("WarehouseTransfer/ChangeTransferItemReceivedQuantity", "pkTransferId=" + pkTransferId + "&pkBinId=" + pkBinId + "&pkTransferItemId=" + pkTransferItemId + "&Quantity=" + Newtonsoft.Json.JsonConvert.SerializeObject(Quantity, serializerSettings) + "", ApiToken, ApiServer);
}
public static void ChangeTransferItemRequestQuantity(Guid pkTransferId,Guid pkTransferItemId,Int32 Quantity,Guid ApiToken, String ApiServer)
{
Factory.GetResponse("WarehouseTransfer/ChangeTransferItemRequestQuantity", "pkTransferId=" + pkTransferId + "&pkTransferItemId=" + pkTransferItemId + "&Quantity=" + Quantity + "", ApiToken, ApiServer);
}
public static WarehouseTransferItem ChangeTransferItemSentQuantity(Guid pkTransferId,Guid pkBinId,Guid pkTransferItemId,Int32 Quantity,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<WarehouseTransferItem>(Factory.GetResponse("WarehouseTransfer/ChangeTransferItemSentQuantity", "pkTransferId=" + pkTransferId + "&pkBinId=" + pkBinId + "&pkTransferItemId=" + pkTransferItemId + "&Quantity=" + Quantity + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static void ChangeTransferLocations(Guid pkTransferId,Guid fromLocationId,Guid toLocationId,Guid ApiToken, String ApiServer)
{
Factory.GetResponse("WarehouseTransfer/ChangeTransferLocations", "pkTransferId=" + pkTransferId + "&fromLocationId=" + fromLocationId + "&toLocationId=" + toLocationId + "", ApiToken, ApiServer);
}
public static void ChangeTransferProperty(Guid pkTransferId,Guid pkTransferPropertyId,String newValue,Guid ApiToken, String ApiServer)
{
Factory.GetResponse("WarehouseTransfer/ChangeTransferProperty", "pkTransferId=" + pkTransferId + "&pkTransferPropertyId=" + pkTransferPropertyId + "&newValue=" + newValue + "", ApiToken, ApiServer);
}
public static void ChangeTransferStatus(Guid pkTransferId,TransferStatus newStatus,Guid ApiToken, String ApiServer)
{
Factory.GetResponse("WarehouseTransfer/ChangeTransferStatus", "pkTransferId=" + pkTransferId + "&newStatus=" + newStatus + "", ApiToken, ApiServer);
}
public static void ChangeTransferToLocation(Guid pkTransferId,Guid newLocationId,Guid ApiToken, String ApiServer)
{
Factory.GetResponse("WarehouseTransfer/ChangeTransferToLocation", "pkTransferId=" + pkTransferId + "&newLocationId=" + newLocationId + "", ApiToken, ApiServer);
}
public static Guid CheckForDraftTransfer(Guid toLocationId,Guid fromLocationId,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<Guid>(Factory.GetResponse("WarehouseTransfer/CheckForDraftTransfer", "toLocationId=" + toLocationId + "&fromLocationId=" + fromLocationId + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static WarehouseTransferBin CreateNewBin(Guid pkTransferId,String barcode,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<WarehouseTransferBin>(Factory.GetResponse("WarehouseTransfer/CreateNewBin", "pkTransferId=" + pkTransferId + "&barcode=" + barcode + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static WarehouseTransfer CreateTransferFromDescrepancies(Guid pkTransferId,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<WarehouseTransfer>(Factory.GetResponse("WarehouseTransfer/CreateTransferFromDescrepancies", "pkTransferId=" + pkTransferId + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static WarehouseTransfer CreateTransferRequestWithReturn(Guid fromLocationId,Guid toLocationId,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<WarehouseTransfer>(Factory.GetResponse("WarehouseTransfer/CreateTransferRequestWithReturn", "fromLocationId=" + fromLocationId + "&toLocationId=" + toLocationId + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static void DeleteEmptyDraftTransfer(Guid pkTransferId,Guid ApiToken, String ApiServer)
{
Factory.GetResponse("WarehouseTransfer/DeleteEmptyDraftTransfer", "pkTransferId=" + pkTransferId + "", ApiToken, ApiServer);
}
public static void DeleteTransfer(Guid pkTransferId,String DeleteReason,Guid ApiToken, String ApiServer)
{
Factory.GetResponse("WarehouseTransfer/DeleteTransfer", "pkTransferId=" + pkTransferId + "&DeleteReason=" + DeleteReason + "", ApiToken, ApiServer);
}
public static void DeleteTransferProperty(Guid pkTransferId,Guid pkTransferPropertyId,Guid ApiToken, String ApiServer)
{
Factory.GetResponse("WarehouseTransfer/DeleteTransferProperty", "pkTransferId=" + pkTransferId + "&pkTransferPropertyId=" + pkTransferPropertyId + "", ApiToken, ApiServer);
}
public static List<WarehouseTransfer> GetActiveTransfersAllLocations(Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<List<WarehouseTransfer>>(Factory.GetResponse("WarehouseTransfer/GetActiveTransfersAllLocations", "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static List<WarehouseTransfer> GetActiveTransfersForLocation(Guid locationId,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<List<WarehouseTransfer>>(Factory.GetResponse("WarehouseTransfer/GetActiveTransfersForLocation", "locationId=" + locationId + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static GenericPagedResult<WarehouseTransfer> GetArchivedTransfers(Int32 pageNumber,Int32 entriesPerPage,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<GenericPagedResult<WarehouseTransfer>>(Factory.GetResponse("WarehouseTransfer/GetArchivedTransfers", "pageNumber=" + pageNumber + "&entriesPerPage=" + entriesPerPage + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static GenericPagedResult<WarehouseTransfer> GetArchivedTransfersBetweenDates(DateTime start,DateTime end,Int32 pageNumber,Int32 entriesPerPage,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<GenericPagedResult<WarehouseTransfer>>(Factory.GetResponse("WarehouseTransfer/GetArchivedTransfersBetweenDates", "start=" + Newtonsoft.Json.JsonConvert.SerializeObject(start, serializerSettings) + "&end=" + Newtonsoft.Json.JsonConvert.SerializeObject(end, serializerSettings) + "&pageNumber=" + pageNumber + "&entriesPerPage=" + entriesPerPage + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static GenericPagedResult<WarehouseTransfer> GetArchivedTransfersFiltered(SearchType searchType,String filter,Int32 pageNumber,Int32 entriesPerPage,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<GenericPagedResult<WarehouseTransfer>>(Factory.GetResponse("WarehouseTransfer/GetArchivedTransfersFiltered", "searchType=" + searchType + "&filter=" + filter + "&pageNumber=" + pageNumber + "&entriesPerPage=" + entriesPerPage + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static List<WarehouseTransferItem> GetDiscrepancyItems(Guid pkTransferId,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<List<WarehouseTransferItem>>(Factory.GetResponse("WarehouseTransfer/GetDiscrepancyItems", "pkTransferId=" + pkTransferId + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static List<WarehouseTransfer> GetListTransfers(List<Guid> ids,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<List<WarehouseTransfer>>(Factory.GetResponse("WarehouseTransfer/GetListTransfers", "ids=" + Newtonsoft.Json.JsonConvert.SerializeObject(ids, serializerSettings) + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static List<WarehouseTransfer> GetModifiedBasic(DateTime updateDate,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<List<WarehouseTransfer>>(Factory.GetResponse("WarehouseTransfer/GetModifiedBasic", "updateDate=" + Newtonsoft.Json.JsonConvert.SerializeObject(updateDate, serializerSettings) + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static DateTime GetServerTime(Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<DateTime>(Factory.GetResponse("WarehouseTransfer/GetServerTime", "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static List<StockAvailability> GetStockAvailability(Guid pkTransferItemId,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<List<StockAvailability>>(Factory.GetResponse("WarehouseTransfer/GetStockAvailability", "pkTransferItemId=" + pkTransferItemId + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static List<WarehouseTransferAudit> GetTransferAudit(Guid pkTransferId,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<List<WarehouseTransferAudit>>(Factory.GetResponse("WarehouseTransfer/GetTransferAudit", "pkTransferId=" + pkTransferId + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static List<WarehouseTransferBinNote> GetTransferBinNotes(Guid pkBinId,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<List<WarehouseTransferBinNote>>(Factory.GetResponse("WarehouseTransfer/GetTransferBinNotes", "pkBinId=" + pkBinId + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static List<WarehouseTransferItemNote> GetTransferItemNotes(Guid pkTransferId,Guid pkTransferItemId,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<List<WarehouseTransferItemNote>>(Factory.GetResponse("WarehouseTransfer/GetTransferItemNotes", "pkTransferId=" + pkTransferId + "&pkTransferItemId=" + pkTransferItemId + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static List<WarehouseTransferItem> GetTransferItems(Guid pkTransferId,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<List<WarehouseTransferItem>>(Factory.GetResponse("WarehouseTransfer/GetTransferItems", "pkTransferId=" + pkTransferId + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static List<WarehouseTransferNote> GetTransferNotes(Guid pkTransferId,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<List<WarehouseTransferNote>>(Factory.GetResponse("WarehouseTransfer/GetTransferNotes", "pkTransferId=" + pkTransferId + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static List<WarehouseTransferProperty> GetTransferProperties(Guid pkTransferId,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<List<WarehouseTransferProperty>>(Factory.GetResponse("WarehouseTransfer/GetTransferProperties", "pkTransferId=" + pkTransferId + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static WarehouseTransfer GetTransferWithItems(Guid pkTransferId,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<WarehouseTransfer>(Factory.GetResponse("WarehouseTransfer/GetTransferWithItems", "pkTransferId=" + pkTransferId + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static WarehouseTransfer GetTransferWithNotes(Guid pkTransferId,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<WarehouseTransfer>(Factory.GetResponse("WarehouseTransfer/GetTransferWithNotes", "pkTransferId=" + pkTransferId + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static Boolean IsDraftTransferChanged(Guid pkTransferId,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<Boolean>(Factory.GetResponse("WarehouseTransfer/IsDraftTransferChanged", "pkTransferId=" + pkTransferId + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static String PrintTransfer(Guid pkTransferId,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<String>(Factory.GetResponse("WarehouseTransfer/PrintTransfer", "pkTransferId=" + pkTransferId + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static void RemoveAllEmptyBins(Guid ApiToken, String ApiServer)
{
Factory.GetResponse("WarehouseTransfer/RemoveAllEmptyBins", "", ApiToken, ApiServer);
}
public static void RemoveItemFromTransfer(Guid pkTransferId,Guid pkTransferItemId,Guid ApiToken, String ApiServer)
{
Factory.GetResponse("WarehouseTransfer/RemoveItemFromTransfer", "pkTransferId=" + pkTransferId + "&pkTransferItemId=" + pkTransferItemId + "", ApiToken, ApiServer);
}
public static List<Guid> SearchTransfersAllLocations(SearchType searchType,String searchText,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<List<Guid>>(Factory.GetResponse("WarehouseTransfer/SearchTransfersAllLocations", "searchType=" + searchType + "&searchText=" + searchText + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static List<Guid> SearchTransfersByLocation(SearchType searchType,String searchText,Guid locationID,Guid ApiToken, String ApiServer)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<List<Guid>>(Factory.GetResponse("WarehouseTransfer/SearchTransfersByLocation", "searchType=" + searchType + "&searchText=" + searchText + "&locationID=" + locationID + "", ApiToken, ApiServer), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
}
public static void SetReferenceNumber(Guid pkTransferId,String ReferenceNumber,Guid ApiToken, String ApiServer)
{
Factory.GetResponse("WarehouseTransfer/SetReferenceNumber", "pkTransferId=" + pkTransferId + "&ReferenceNumber=" + ReferenceNumber + "", ApiToken, ApiServer);
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text.Json.Serialization;
#nullable disable
namespace dk.via.ftc.dataTier_v2_C
{
[Table("vendor_admin", Schema = "SEP3")]
public partial class VendorAdmin
{
[JsonPropertyName("username"), Key]
public string Username { get; set; }
[JsonPropertyName("vendor_id")]
public string VendorId { get; set; }
[ForeignKey(nameof(VendorId))]
[JsonPropertyName("pass")]
public string Pass { get; set; }
[JsonPropertyName("email")]
public string Email { get; set; }
[JsonPropertyName("first_name")]
public string FirstName { get; set; }
[JsonPropertyName("last_name")]
public string LastName { get; set; }
[JsonPropertyName("phone")]
public string Phone { get; set; }
public virtual Vendor Vendor { get; set; }
}
}
|
using System.Threading.Tasks;
namespace ScripterTestCmd
{
public interface IVariablesRepository
{
ITreeNode GetVariable(string parent, string name);
Task<ITreeNode> GetFolderTree();
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Quest_manager: MonoBehaviour
{
public Quest_object[] quests;
public bool[] quest_completed;
public Dialogue_manager the_DM;
public string item_collected;
public string enemy_killed;
// Start is called before the first frame update
void Start()
{
quest_completed = new bool[quests.Length];
}
// Update is called once per frame
void Update()
{
}
public void Show_quest_text(string quest_text)
{
the_DM.dialog_lines = new string[1];
the_DM.dialog_lines[0] = quest_text;
the_DM.current_line = 0;
the_DM.ShowDialogue();
}
}
|
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace UnityExtensions.UI.Components
{
[RequireComponent(typeof(ScrollRect))]
public class ScrollList : MonoBehaviour
{
#region Attributes
[SerializeField]
private bool m_static;
private RectTransform m_contentTransform;
[Space(10)]
[SerializeField]
private RectTransform m_focusTransform;
private List<GameObject> m_content;
#endregion Attributes
#region Methods
#region Accessors and Mutators
//_____________________________________________________________________ ACCESSORS AND MUTATORS _____________________________________________________________________
public bool isStatic
{
get { return m_static; }
}
public GameObject value { get; private set; }
public int count
{
get { return m_content.Count; }
}
#endregion Accessors and Mutators
#region Inherited Methods
//_______________________________________________________________________ INHERITED METHODS _______________________________________________________________________
private void Start()
{
m_content = new List<GameObject>();
m_contentTransform = GetComponent<ScrollRect>().content;
if (m_static)
{
/*foreach (Transform itemTransform in m_contentTransform)
{
GameObject copy = Instantiate(itemTransform.gameObject);
m_content.Add(copy);
}*/
}
else
{
Refresh();
}
//Refresh();
}
private void Update()
{
if (value != null)
{
FocusOn(value);
}
}
#endregion Inherited Methods
#region Events
//_____________________________________________________________________________ EVENTS _____________________________________________________________________________
public void OnSelectionChanged(GameObject content)
{
value = content;
FocusOn(content);
}
#endregion Events
#region Other Methods
//__________________________________________________________________________ OTHER METHODS _________________________________________________________________________
public void Add(GameObject content)
{
m_content.Add(content);
}
public void Clear()
{
m_content = new List<GameObject>();
value = null;
Purge();
}
private void Purge()
{
foreach (Transform listItemTransform in m_contentTransform)
{
Destroy(listItemTransform.gameObject);
}
}
public void Refresh()
{
Purge();
foreach (var content in m_content)
{
var contentTransform = Instantiate(content).transform;
contentTransform.SetParent(m_contentTransform);
var contentRectTransform = contentTransform.GetComponent<RectTransform>();
contentRectTransform.localPosition = Vector3.zero;
contentRectTransform.localRotation = Quaternion.identity;
contentRectTransform.localScale = Vector3.one;
}
value = m_content.Count > 0 ? m_content[0] : value;
}
private void FocusOn(GameObject content)
{
var contentTransform = content.GetComponent<RectTransform>();
m_focusTransform.position = contentTransform.position;
m_focusTransform.rotation = contentTransform.rotation;
m_focusTransform.sizeDelta = contentTransform.sizeDelta;
}
#endregion Other Methods
#endregion Methods
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace DynamicsExtensions.Extensions
{
public static class MvcExtensions
{
public static string[] ReadAllLines(this HttpPostedFileBase httpPostedFileBase)
{
List<string> lines = new List<string>();
using (var sr = new StreamReader(httpPostedFileBase.InputStream))
{
string line;
while((line = sr.ReadLine()) != null)
{
lines.Add(line);
}
}
return lines.ToArray();
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace NBXplorer
{
public class WellknownMetadataKeys
{
public const string ImportAddressToRPC = nameof(ImportAddressToRPC);
public const string Mnemonic = nameof(Mnemonic);
public const string MasterExtKey = nameof(MasterExtKey);
public const string AccountExtKey = nameof(AccountExtKey);
public const string AccountKeyPath = nameof(AccountKeyPath);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using NameSearch.Models.Entities.Abstracts;
namespace NameSearch.Models.Entities
{
/// <summary>
/// Person Entity
/// </summary>
/// <seealso cref="NameSearch.Models.Entities.Abstracts.EntityBase{NameSearch.Models.Entities.Person}" />
/// <inheritdoc />
public class Person : EntityBase<Person>
{
/// <summary>
/// Gets or sets the person search result identifier.
/// </summary>
/// <value>
/// The person search result identifier.
/// </value>
[ForeignKey("PersonSearchForeignKey")]
public long PersonSearchId { get; set; }
/// <summary>
/// Gets or sets the first name.
/// </summary>
/// <value>
/// The first name.
/// </value>
public string FirstName { get; set; }
/// <summary>
/// Gets or sets the last name.
/// </summary>
/// <value>
/// The last name.
/// </value>
[Required]
public string LastName { get; set; }
/// <summary>
/// Gets or sets the alias.
/// </summary>
/// <value>
/// The alias.
/// </value>
public string Alias { get; set; }
/// <summary>
/// Gets or sets the age.
/// </summary>
/// <value>
/// The age.
/// </value>
public string AgeRange { get; set; }
/// <summary>
/// Gets or sets the addresses.
/// </summary>
/// <value>
/// The addresses.
/// </value>
public List<Address> Addresses { get; set; }
/// <summary>
/// Gets or sets the phones.
/// </summary>
/// <value>
/// The phones.
/// </value>
public List<Phone> Phones { get; set; }
/// <summary>
/// Gets or sets the associates.
/// </summary>
/// <value>
/// The associates.
/// </value>
public List<Associate> Associates { get; set; }
#region Equality
/// <summary>
/// See http://www.aaronstannard.com/overriding-equality-in-dotnet/
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public override bool Equals(Person other)
{
if (other == null) return false;
return PersonSearchId == other.PersonSearchId &&
string.Equals(FirstName, other.FirstName, StringComparison.InvariantCultureIgnoreCase) &&
string.Equals(LastName, other.LastName, StringComparison.InvariantCultureIgnoreCase) &&
string.Equals(Alias, other.Alias, StringComparison.InvariantCultureIgnoreCase) &&
AgeRange == other.AgeRange &&
(Addresses ?? new List<Address>()).Equals(other.Addresses) &&
(Phones ?? new List<Phone>()).Equals(other.Phones) &&
(Associates ?? new List<Associate>()).Equals(other.Associates);
}
/// <summary>
/// Determines whether the specified <see cref="System.Object" />, is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
if (obj is null) return false;
if (this is null) return false;
if (obj.GetType() != GetType()) return false;
return Equals(obj as Person);
}
/// <summary>
/// Return Base Implementation.
/// "You should only override GetHashCode if your objects are immutable."
/// See also http://www.aaronstannard.com/overriding-equality-in-dotnet/
/// See also https://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode/263416#263416
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode() => base.GetHashCode();
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AnimationSE : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void PlayElectronSE()
{
AudioManager.Instance.PlaySE("magic-electron2", 0.1f);
}
public void PlayCountDown()
{
AudioManager.Instance.PlaySE("CountDown", 0.1f);
}
public void PlayBomb()
{
AudioManager.Instance.PlaySE("Fire", 0.1f);
}
public void PlayTitleCoal()
{
AudioManager.Instance.PlayExVoice("TitleCoal");
}
public void PlayKamisibaiAppear()
{
AudioManager.Instance.PlaySE("wood_impact", 0.1f);
}
public void PlayKamisibaiNext()
{
AudioManager.Instance.PlaySE("wood_swing", 0.1f);
}
}
|
using System.Collections.Generic;
namespace FlipLeaf.Core
{
public interface IInputSource
{
IEnumerable<IInput> Get(IStaticSite ctx);
}
}
|
using Firebase.Database;
using Firebase.Database.Query;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelertApp.Models;
namespace TravelertApp.Services
{
public class EntrepreneurApiServices
{
private JsonSerializer _serializer = new JsonSerializer();
private static EntrepreneurApiServices _ServiceClientInstance;
public static EntrepreneurApiServices ServiceClientInstance
{
get
{
if (_ServiceClientInstance == null)
_ServiceClientInstance = new EntrepreneurApiServices();
return _ServiceClientInstance;
}
}
FirebaseClient firebase;
public EntrepreneurApiServices()
{
//replace this with your firebase realtimedatabase end point.
firebase = new FirebaseClient("https://travelertappdb-default-rtdb.firebaseio.com/");
}
#region ClientSection
//[Pushing Single table to the Database]
public async Task<bool> RegisterUser(string fullname, int age, string businesstype, string email, string password)
{
var result = await firebase
.Child("Entrepreneurs")
.PostAsync(new Entrepreneur()
{
FullName = fullname,
Age = age,
BusinessType = businesstype,
EntrepreneurUID = Guid.NewGuid(),
Email = email,
Password = password
});
if (result.Object != null)
{
return true;
}
else
{
return false;
}
}
//Login with clients credentials.
public async Task<Entrepreneur> LoginUser(string email, string password)
{
var getEntrepreneur = (await firebase
.Child("Entrepreneurs")
.OnceAsync<Entrepreneur>()).Where(a => a.Object.Email == email).Where(b => b.Object.Password == password).FirstOrDefault();
if (getEntrepreneur != null)
{
var content = getEntrepreneur.Object as Entrepreneur;
return content;
}
else
{
return null;
}
}
//Getting all entrepreneurs (gagamitin para sa GetEntrepreneur) ??
public async Task<List<Entrepreneur>> GetAllEntrepreneurs()
{
var GetClients = (await firebase
.Child("Entrepreneurs")
.OnceAsync<Entrepreneur>()).Select(item => new Entrepreneur
{
FullName = item.Object.FullName,
Age = item.Object.Age,
BusinessType = item.Object.BusinessType,
EntrepreneurUID = item.Object.EntrepreneurUID,
Email = item.Object.Email,
Password = item.Object.Password
}).ToList();
return GetClients;
}
//Getting the entrepreneur??
public async Task<Entrepreneur> GetEntrepreneur(string entrepreneurUID)
{
var AllClients = await GetAllEntrepreneurs();
await firebase
.Child("Entrepreneurs")
.OnceAsync<Entrepreneur>();
return AllClients.Where(a => a.EntrepreneurUID.ToString() == entrepreneurUID).FirstOrDefault();
}
//Logout the entrepreneur?? sa mismong page.cs nalang
#endregion ClientSection
}
}
|
using System.Linq;
using System;
public static class Kata
{
public static bool XO (string inp)
{
int o = 0;
int x = 0;
int xo = 0;
String input = inp.ToLower();
for(int i=0; i<input.Length; i++){
if(input[i] == 'o'){
o++;
}else if(input[i] == 'x'){
x++;
}
}
foreach(char n in input){
if(!(n !='o' && n !='x')){
xo++;
}
}
if(x == o){
return true;
}
if(xo == 0){
return true;
}
if(x != o){
return false;
}
return false;
}
}
/*
Check to see if a string has the same amount of 'x's and 'o's. The method must return a boolean and be case insensitive. The string can contain any char.
Examples input/output:
XO("ooxx") => true
XO("xooxx") => false
XO("ooxXm") => true
XO("zpzpzpp") => true // when no 'x' and 'o' is present should return true
XO("zzoo") => false
*/
|
namespace Tensor.Test.BubbleGame
{
/// <summary>
/// Точки
/// </summary>
public class Seed : GameUnit
{
public Seed(double x, double y, double Vx, double Vy)
: base(x, y)
{
VelocityX = Vx;
VelocityY = Vy;
}
public double VelocityX { get; set; }
public double VelocityY { get; set; }
/// <summary>
/// Готовит данные для визуализатора
/// </summary>
/// <returns></returns>
public override string Render()
{
return string.Format("seed {4} x: {0:F2}, y: {1:F2}, Vx: {2:F2}, Vy: {3:F2}", X, Y, VelocityX, VelocityY, UnitStatus);
}
public override void Evolute(double period)
{
if (UnitStatus != Status.Active) return;
X += VelocityX * period;
Y += VelocityY * period;
}
/// <summary>
/// Столкновение с границами игрового поля
/// </summary>
/// <param name="gameUnit"></param>
/// <param name="gameField"></param>
public override bool Collision(GameUnit gameUnit, GameField gameField)
{
if (X < 0)
{
X = -X;
VelocityX = -VelocityX;
}
if (X > gameField.Width)
{
X = gameField.Width;
VelocityX = -VelocityX;
}
if (Y < 0)
{
Y = 0;
VelocityY = -VelocityY;
}
if (Y > gameField.Width)
{
Y = gameField.Width;
VelocityY = -VelocityY;
}
return false;
}
}
}
|
using FastSQL.Core;
using FastSQL.Sync.Core;
using FastSQL.Sync.Core.Mapper;
using FastSQL.Sync.Core.Processors;
using FastSQL.Sync.Core.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FastSQL.Magento1.Integration.Mappers
{
public class SubCategoryMapper : BaseMapper
{
public SubCategoryMapper(
SubCategoryProcessor processor,
SubCategoryMapperOptionManager optionManager,
FastAdapter adapter) : base(processor, optionManager, adapter)
{
}
public override MapResult Pull(object lastToken = null)
{
throw new NotImplementedException();
}
}
}
|
using UnityEngine;
public class GateCollisionController : MonoBehaviour
{
private GameObject _player;
private PlayerController _playerController;
private GameObject _bossGate;
void Start()
{
_bossGate = GameObject.Find("BossGate");
_player = GameObject.Find("Player");
_playerController = _player.GetComponent<PlayerController>();
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject == _player && _playerController.HasKey)
{
_bossGate.GetComponent<BossGateController>().OpenGate();
}
}
}
|
using Beamore.API.BusinessLogics.Notification;
using Beamore.API.BusinessLogics.UnitOfWorks;
using Beamore.API.Models;
using Beamore.Contracts.DataTransferObjects;
using Beamore.DAL.Contents.Models;
using Beamore.DAL.Repositories;
using Microsoft.Azure.NotificationHubs;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Beamore.API.Controllers
{
[RoutePrefix("api")]
public class NotificationController : ApiController
{
SentNotificationRepo _sentNotificationRepo = new SentNotificationRepo();
[HttpPost]
[Authorize(Roles ="Manager")]
[Route("notification")]
public void Notificaiton(NotificationDTO model)
{
var xx = new NotificationModel
{
data = new Data
{
message = model.EventId + "% " + model.Message
}
};
SendNotificationAsync(xx);
var mdl = new SentNotification
{
EventId = model.EventId,
NotificationHeader = "Beamore",
NotificationMessage = model.Message
};
_sentNotificationRepo.add(mdl);
_sentNotificationRepo.Save();
}
[HttpGet]
[Authorize(Roles ="endUser, Manager")]
[Route("getnotification")]
public List<SentNotification> getNotification(int EventId)
{
var result = _sentNotificationRepo.FindByExxpression(p=>p.EventId == EventId);
if (result != null)
{
return result;
}
return null;
}
public async void SendNotificationAsync(NotificationModel msg)
{
var json = JsonConvert.SerializeObject(msg);
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("key", "hubName");
await hub.SendGcmNativeNotificationAsync(json);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Dependencies;
using Unity;
namespace WebApplication.App_Start
{
public class UnityDependencyScope : IDependencyScope
{
protected IUnityContainer Container { get; set; }
public UnityDependencyScope(IUnityContainer container)
{
Container = container;
}
public void Dispose()
{
Container.Dispose();
}
public object GetService(Type serviceType)
{
return Container.IsRegistered(serviceType)
? Container.Resolve(serviceType)
: null;
}
public IEnumerable<object> GetServices(Type serviceType)
{
return Container.ResolveAll(serviceType);
}
}
} |
using FLS.Business;
using FuelSupervisorSetting.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
namespace FuelSupervisorSetting.ViewModel
{
class MqttServerViewModel : ViewModelBase
{
private readonly RelayCommand _saveCommand;
string _serveraddress;
int _serverport;
string _userid;
string _status;
//string _confirmpwd;
public MqttServerViewModel()
{
BusinessHelper.InitConnection();
_serverport = 1883;
_saveCommand = new RelayCommand(DoSaveCommand, CanSave);
}
public RelayCommand SaveCommand
{
get { return _saveCommand;}
}
public String ServerAddress
{
get { return _serveraddress; }
set { SetProperty(ref _serveraddress, value); SaveCommand.RaiseCanExecuteChanged(); }
}
public int ServerPort
{
get { return _serverport; }
set { SetProperty(ref _serverport, value); SaveCommand.RaiseCanExecuteChanged(); }
}
public String UserId
{
get { return _userid; }
set { SetProperty(ref _userid, value); SaveCommand.RaiseCanExecuteChanged(); }
}
public String Status
{
get { return _status; }
set { SetProperty(ref _status, value); }
}
//public String ConfirmPassword
//{
// get { return _confirmpwd; }
// set { SetProperty(ref _confirmpwd, value); }
//}
private void DoSaveCommand(object parameter)
{
var values = (object[])parameter;
PasswordBox pwdBox = values[0] as PasswordBox;
string clearPassword = pwdBox.Password;
string clearConfirmPwd = (values[1] as PasswordBox).Password;
if (!clearPassword.Equals(clearConfirmPwd))
{
Status = string.Format("Password not equal!!");
return;
}
BusinessHelper.AddMqttServer(ServerAddress, ServerPort, UserId, FLS.Helper.CryptorEngine.Encrypt(clearPassword, true));
Status = string.Format("Add server success!!");
ServerAddress = string.Empty;
ServerPort = 1883;
UserId = string.Empty;
values = null;
}
private bool CanSave(object parameter)
{
if (string.IsNullOrEmpty(ServerAddress) || (_serverport<0) || (_serverport>65535)
|| string.IsNullOrEmpty(_userid)
//|| string.IsNullOrEmpty(_password)||string.IsNullOrEmpty(_confirmpwd)
)
return false;
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OPC_UA_Library
{
public enum SecurityPolicy
{
None = 0,
Basic128,
Basic256
}
public enum MessageSecurity
{
None,
Sign,
SignAndEncrypt
}
}
|
using System;
using System.Collections.Generic;
using Braspag.Domain.Entities;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
namespace Braspag.Domain.Update
{
public static class AdquirentesUpdate
{
public static UpdateDocument UpDateAdquirentes(this Adquirentes adquirente)
{
var update = new UpdateDocument();
if (adquirente.adquirentes != null)
update.Set("adquirentes", adquirente.adquirentes);
if (adquirente.visa != 0)
update.Set("visa", adquirente.visa.ToString().Replace(",","."));
if (adquirente.master != 0)
update.Set("master", adquirente.master.ToString().Replace(",", "."));
if (adquirente.elo != 0)
update.Set("elo", adquirente.elo.ToString().Replace(",", "."));
return update;
}
}
}
|
namespace BitArray
{
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
// Console.WindowWidth = Console.BufferWidth = 120;
var numbers = new List<BitArray64> {
new BitArray64(5),
new BitArray64(254),
new BitArray64(4611686018427387904) };
foreach (var num in numbers)
{
Console.WriteLine("NUMBER IN DECIMAL REPRESENTATION: {0}", num.DecimalRepresentation);
Console.WriteLine("{0}({1}) = {2}", num.GetType().Name, num.DecimalRepresentation, num);
Console.WriteLine(new string('-', Console.WindowWidth-1));
}
for (int ind = 0; ind < numbers.Count-1; ind++)
{
Console.WriteLine("{0,10} == {1} : {2}",
numbers[ind],
numbers[ind+1],
numbers[ind] == numbers[ind+1]);
Console.WriteLine("{0,10} != {1} : {2}",
numbers[ind],
numbers[ind + 1],
numbers[ind] != numbers[ind + 1]);
Console.WriteLine("{0,10}.Equals({1}) : {2}",
numbers[ind],
numbers[ind + 1],
numbers[ind].Equals(numbers[ind + 1]));
Console.WriteLine();
}
Console.WriteLine("TESTING IEnumerator, foreaching BitArray64(5):");
foreach (var digit in new BitArray64(5))
{
Console.Write((char)digit + " ");
}
Console.WriteLine();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Animations;
public class Player : MonoBehaviour
{
public AudioClip leaveBox;
public AudioClip pickUpBox;
public AudioClip pickUpHeavyBox;
public PlayerUI playerUI;
public RuntimeAnimatorController controller;
public RuntimeAnimatorController controllerBox;
public GameObject grabberPos;
public float grabberOffsetX = 0.15f;
public float grabberOffsetY = 0.1f;
private PickUpTruck truck;
private Animator animator;
public float movementSpeed;
private PickUpableObject objectToPickUp;
private PlayerPickUpTrigger pickUpTrigger;
private Vector2 movement;
private bool canPickUp;
private Rigidbody2D rb;
public enum PlayerState
{
NOT_HOLDING_ITEM,
HOLDING_ITEM,
PICKING_UP
}
private PlayerState state;
void Start ()
{
truck = FindObjectOfType<PickUpTruck>();
grabberPos.transform.localPosition = new Vector2(0, grabberOffsetY * -1);
animator = GetComponent<Animator>();
animator.runtimeAnimatorController = controller;
objectToPickUp = null;
pickUpTrigger = GetComponentInChildren<PlayerPickUpTrigger>();
movement = transform.position;
canPickUp = pickUpTrigger.CanPickUpObj;
rb = GetComponent<Rigidbody2D>();
// Set default state
state = PlayerState.NOT_HOLDING_ITEM;
}
void FixedUpdate ()
{
UpdatePlayerState();
}
private void UpdatePlayerState()
{
switch(state)
{
case PlayerState.NOT_HOLDING_ITEM:
Movement(1);
if (Input.GetButton("Action") && pickUpTrigger.CanPickUpObj)
{
state = PlayerState.PICKING_UP;
}
break;
case PlayerState.HOLDING_ITEM:
Movement(objectToPickUp.weight);// <------------ Change by the object weight
DropItem();
break;
case PlayerState.PICKING_UP:
PickUp();
break;
}
}
private void DropItem()
{
if (pickUpTrigger.CanDropOnTruck)
{
if (Input.GetButtonDown("Action"))
{
Debug.Log("Item dropped on truck");
GameManager.GetInstance().PlayEffectSound(leaveBox);
// push item into truck
truck.AddItem(objectToPickUp);
objectToPickUp = null;
state = PlayerState.NOT_HOLDING_ITEM;
animator.runtimeAnimatorController = controller;
}
}
}
private void PickUp()
{
canPickUp = pickUpTrigger.CanPickUpObj;
if (Input.GetButton("Action") && pickUpTrigger.CanPickUpObj)
{
Debug.Log("Pick up button");
// ------ New pick up mechanic------ //
objectToPickUp = pickUpTrigger.objToPickUp;
if (!objectToPickUp.BeingPickedUp)
{
playerUI.EnableLoadingCircle();
//objectToPickUp.BeingPickedUp = true;
// disable item
if (objectToPickUp.GetPickedUp())
{
GameManager.GetInstance().PlayEffectSound(pickUpBox);
playerUI.ResetTimer();
objectToPickUp.gameObject.SetActive(false);
canPickUp = false;
state = PlayerState.HOLDING_ITEM;
pickUpTrigger.HideObjectInfo();
Debug.Log("Culo2");
animator.runtimeAnimatorController = controllerBox;
}
}
}
else if (Input.GetButtonUp("Action"))
{
if (objectToPickUp != null)
{
state = PlayerState.NOT_HOLDING_ITEM;
objectToPickUp.BeingPickedUp = false;
playerUI.ResetTimer();
}
}
}
private void Movement(float weight)
{
if (Input.GetAxis("Vertical") != 0)
{
animator.SetFloat("Vertical", Input.GetAxis("Vertical"));
animator.SetFloat("Horizontal", 0);
if (Input.GetAxis("Vertical") < 0)
{
grabberPos.transform.localPosition = new Vector2(0, grabberOffsetY * -1);
}
else
{
grabberPos.transform.localPosition = new Vector2(0, grabberOffsetY + .2f);
}
}
if (Input.GetAxis("Horizontal") != 0)
{
animator.SetFloat("Horizontal", Input.GetAxis("Horizontal"));
animator.SetFloat("Vertical", 0);
if (Input.GetAxis("Horizontal") < 0)
{
grabberPos.transform.localPosition = new Vector2(grabberOffsetX * -1, .1f);
}
else
{
grabberPos.transform.localPosition = new Vector2(grabberOffsetX, .1f);
}
}
if (Input.GetAxis("Horizontal") == 0 && Input.GetAxis("Vertical") == 0)
{
animator.SetBool("NoMovement", true);
animator.SetFloat("Vertical", Input.GetAxis("Vertical"));
animator.SetFloat("Horizontal", Input.GetAxis("Horizontal"));
}
else
{
animator.SetBool("NoMovement", false);
}
float x = Input.GetAxis("Horizontal");
float y = Input.GetAxis("Vertical");
Vector2 movement = new Vector2(x, y);
if (movement.magnitude > 1.0f)
{
movement.Normalize();
}
rb.velocity = (movement * movementSpeed * Time.fixedDeltaTime) / weight;
/* if (Mathf.Abs(Input.GetAxis("RightHorizontal")) < Mathf.Abs(Input.GetAxis("RightVertical")))
{
if (Input.GetAxis("RightVertical") < 0)
{
Debug.Log("up");
animator.SetFloat("Vertical", Input.GetAxis("RightVertical"));
}
else if (Input.GetAxis("RightVertical") > 0)
{
Debug.Log("Down");
animator.SetFloat("Vertical", Input.GetAxis("RightVertical"));
}
}
else if (Input.GetAxis("RightHorizontal") > 0)
{
Debug.Log("right");
animator.SetFloat("Horizontal", Input.GetAxis("RightHorizontal"));
}
else if (Input.GetAxis("RightHorizontal") < 0)
{
Debug.Log("left");
animator.SetFloat("Horizontal", Input.GetAxis("RightHorizontal"));
}*/
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Umbraco.Core;
using Umbraco.Core.Configuration.Dashboard;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Services;
namespace Umbraco.Web.Editors
{
/// <summary>
/// A utility class for determine dashboard security
/// </summary>
internal class DashboardSecurity
{
//TODO: Unit test all this!!! :/
public static bool AuthorizeAccess(ISection dashboardSection, IUser user, ISectionService sectionService)
{
return CheckUserAccessByRules(user, sectionService, dashboardSection.AccessRights.Rules);
}
public static bool AuthorizeAccess(IDashboardTab dashboardTab, IUser user, ISectionService sectionService)
{
return CheckUserAccessByRules(user, sectionService, dashboardTab.AccessRights.Rules);
}
public static bool AuthorizeAccess(IDashboardControl dashboardControl, IUser user, ISectionService sectionService)
{
return CheckUserAccessByRules(user, sectionService, dashboardControl.AccessRights.Rules);
}
private static (IAccessRule[], IAccessRule[], IAccessRule[]) GroupRules(IEnumerable<IAccessRule> rules)
{
IAccessRule[] denyRules = null, grantRules = null, grantBySectionRules = null;
var groupedRules = rules.GroupBy(x => x.Type);
foreach (var group in groupedRules)
{
var a = group.ToArray();
switch (group.Key)
{
case AccessRuleType.Deny:
denyRules = a;
break;
case AccessRuleType.Grant:
grantRules = a;
break;
case AccessRuleType.GrantBySection:
grantBySectionRules = a;
break;
default:
throw new Exception("panic");
}
}
return (denyRules ?? Array.Empty<IAccessRule>(), grantRules ?? Array.Empty<IAccessRule>(), grantBySectionRules ?? Array.Empty<IAccessRule>());
}
public static bool CheckUserAccessByRules(IUser user, ISectionService sectionService, IEnumerable<IAccessRule> rules)
{
if (user.Id == Constants.Security.SuperUserId)
return true;
var (denyRules, grantRules, grantBySectionRules) = GroupRules(rules);
var hasAccess = true;
string[] assignedUserGroups = null;
// if there are no grant rules, then access is granted by default, unless denied
// otherwise, grant rules determine if access can be granted at all
if (grantBySectionRules.Length > 0 || grantRules.Length > 0)
{
hasAccess = false;
// check if this item has any grant-by-section arguments.
// if so check if the user has access to any of the sections approved, if so they will be allowed to see it (so far)
if (grantBySectionRules.Length > 0)
{
var allowedSections = sectionService.GetAllowedSections(user.Id).Select(x => x.Alias).ToArray();
var wantedSections = grantBySectionRules.SelectMany(g => g.Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)).ToArray();
if (wantedSections.Intersect(allowedSections).Any())
hasAccess = true;
}
// if not already granted access, check if this item as any grant arguments.
// if so check if the user is in one of the user groups approved, if so they will be allowed to see it (so far)
if (hasAccess == false && grantRules.Any())
{
assignedUserGroups = user.Groups.Select(x => x.Alias).ToArray();
var wantedUserGroups = grantRules.SelectMany(g => g.Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)).ToArray();
if (wantedUserGroups.Intersect(assignedUserGroups).Any())
hasAccess = true;
}
}
if (!hasAccess || denyRules.Length == 0)
return false;
// check if this item has any deny arguments, if so check if the user is in one of the denied user groups, if so they will
// be denied to see it no matter what
assignedUserGroups = assignedUserGroups ?? user.Groups.Select(x => x.Alias).ToArray();
var deniedUserGroups = denyRules.SelectMany(g => g.Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)).ToArray();
if (deniedUserGroups.Intersect(assignedUserGroups).Any())
hasAccess = false;
return hasAccess;
}
}
}
|
using System;
namespace SparamTestLib
{
public class SparamBandwith : SparamTestCase.TestCaseAbstract
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SFP.SIT.SERV.Model.RESP
{
public class SIT_RESP_HABILITAR
{
public int? rtpclave { set; get; }
public int? araclave { set; get; }
public long? solclave { set; get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BlazorJsFastDataExchangerDemo
{
public static class LocalFunctions
{
public static string GetShortenedItem(string item)
{
if (!string.IsNullOrEmpty(item))
{
if (item.Length > 100)
{
return item.Substring(0, 100);
}
else
{
return item;
}
}
else
{
return "empty";
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine;
public class Connected : MainApplicationReference
{
MainApplication application;
bool joining = false;
public override void Init(MainApplication application)
{
this.application = application;
MD5 md5Hasher = MD5.Create();
var hashed = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(PhotonNetwork.LocalPlayer.UserId));
var ivalue = BitConverter.ToInt32(hashed, 0);
ShufflingExtension.Init(ivalue);
}
public override void OnJoinedRoom()
{
application.UpdateState(MainApplication.State.kEnteredRoom);
}
public override void OnJoinRandomFailed(short returnCode, string message)
{
PhotonNetwork.CreateRoom(null, new RoomOptions { MaxPlayers = MainApplication.kMaxPlayersPerRoom });
}
void OnGUI()
{
int y = 10;
if (joining)
{
GUI.Label(new Rect(10, y += 25, 200, 20), "Finding opponent...");
}
else
{
GUI.Label(new Rect(10, y += 25, 200, 20), "Connected!");
GUI.Label(new Rect(10, y += 25, 200, 20), "Welcome! " + PhotonNetwork.NickName);
GUI.enabled = !joining;
if (GUI.Button(new Rect(10, y += 25, 200, 20), "Quick play"))
{
PhotonNetwork.JoinRandomRoom();
joining = true;
}
GUI.enabled = true;
}
}
}
|
using CommandLine;
using Opbot.Core;
using Opbot.Services;
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading;
namespace Opbot
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(string.Join(";", args));
var options = new Options();
if (Parser.Default.ParseArguments(args, options))
{
//post apply settings
options.Since = options.Since ?? TimeSpan.FromDays(365 * 3);
options.WorkingFolder = string.IsNullOrEmpty(options.WorkingFolder) ? Path.Combine(Environment.CurrentDirectory, DateTime.UtcNow.Ticks.ToString()) : options.WorkingFolder;
var logger = new LogService(options);
logger.Info("Started ...");
ServicePointManager.DefaultConnectionLimit = 128;
int cpuw = 0, iow = 0;
ThreadPool.GetMinThreads(out cpuw, out iow);
ThreadPool.SetMinThreads(Math.Min(128, cpuw), Math.Min(128, iow));
Optimizer pipeline = new Optimizer(options, logger);
pipeline.Scan(options.RemoteFolder);
pipeline.Complete().Wait();
}
if (Debugger.IsAttached)
{
Console.WriteLine("Press any key to exit ...");
Console.ReadKey();
}
}
}
}
|
namespace WMaper.Meta.Store
{
/// <summary>
/// 图层尺寸信息类
/// </summary>
public sealed class Nature
{
#region 变量
// Canvas横轴原点偏移量l
private double l;
// Canvas纵轴原点偏移量t
private double t;
// 图层范围宽度
private double w;
// 图层范围高度
private double h;
// Canvas原点像素横坐标x
private double x;
// Canvas原点像素纵坐标y
private double y;
#endregion
#region 属性方法
public double L
{
get { return this.l; }
set { this.l = value; }
}
public double T
{
get { return this.t; }
set { this.t = value; }
}
public double W
{
get { return this.w; }
set { this.w = value; }
}
public double H
{
get { return this.h; }
set { this.h = value; }
}
public double X
{
get { return this.x; }
set { this.x = value; }
}
public double Y
{
get { return this.y; }
set { this.y = value; }
}
#endregion
#region 构造函数
public Nature()
: this(0.0, 0.0)
{ }
public Nature(double l, double t)
{
this.l = l;
this.t = t;
}
public Nature(double l, double t, double w, double h, double x, double y)
{
this.l = l;
this.t = t;
this.w = w;
this.h = h;
this.x = x;
this.y = y;
}
#endregion
}
} |
using System;
using System.Web;
using System.Web.UI;
using System.Web.Configuration;
namespace CurrencyConverter
{
public partial class ShowSettings : System.Web.UI.Page
{
protected void Page_Load(Object sender, EventArgs args)
{
if (this.IsPostBack == false)
{
AppName.InnerText = WebConfigurationManager.AppSettings["appName"];
AppAuthor.InnerText = WebConfigurationManager.AppSettings["appAuthor"];
}
}
}
}
|
using MKService.Messages;
using MKService.ModelFactories;
using MKService.Updates;
using System.Linq;
using MKService.DefaultModel;
namespace MKService.ModelUpdaters
{
internal class GameJoinedUpdater : ModelUpdaterBase<IUpdatableGame, GameJoined>
{
public GameJoinedUpdater(
IModelFactoryResolver modelFactoryResolver, IDefaultModel defaultMode)
: base(modelFactoryResolver, defaultMode)
{
}
protected override bool UpdateInternal(IUpdatableGame model, GameJoined message)
{
model.User2Id = ServiceTypeProvider.Instance.UserCollection.Users.FirstOrDefault(x => x.Id == message.User2Id).Id;
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TXTextControl;
using TXTextControl.DocumentServer.Fields;
namespace tx_inject_html
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void mergeToolStripMenuItem_Click(object sender, EventArgs e)
{
// create a new DataSet and load the XML file
DataSet ds = new DataSet();
ds.ReadXml("data.xml");
// start the merge process
mailMerge1.Merge(ds.Tables[0]);
}
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
// load the template
TXTextControl.LoadSettings ls = new TXTextControl.LoadSettings();
ls.ApplicationFieldFormat = TXTextControl.ApplicationFieldFormat.MSWord;
textControl1.Load(TXTextControl.StreamType.WordprocessingML, ls);
}
private void mailMerge1_FieldMerged(object sender, TXTextControl.DocumentServer.MailMerge.FieldMergedEventArgs e)
{
// check whether the field is a MergeField
if(e.MailMergeFieldAdapter.TypeName != "MERGEFIELD")
return;
MergeField field = e.MailMergeFieldAdapter as MergeField;
// if switch "Preserve formatting during updates" is set
// load HTML data into temporary ServerTextControl and return
// formatted text
if (field.PreserveFormatting == true)
{
byte[] data;
using (ServerTextControl tx = new ServerTextControl())
{
tx.Create();
tx.Load(field.Text, StringStreamType.HTMLFormat);
tx.Save(out data, BinaryStreamType.InternalUnicodeFormat);
}
e.MergedField = data;
}
}
}
}
|
// ************************************************************************
// Copyright (C) 2001, Patrick Charles and Jonas Lehmann *
// Distributed under the Mozilla Public License *
// http://www.mozilla.org/NPL/MPL-1.1.txt *
// *************************************************************************
using SharpPcap.Packets.Util;
using System.Collections;
namespace SharpPcap.Packets
{
/// <summary> IPProtocol utility class.
///
/// </summary>
public class IPProtocol
{
public enum IPProtocolType
{
/// <summary> IPv6 Hop-by-Hop option. </summary>
HOPOPT = 0,
/// <summary> Internet Control Message Protocol. </summary>
ICMP = 1,
/// <summary> Internet Group Management Protocol.</summary>
IGMP = 2,
/// <summary> IP in IP (encapsulation). </summary>
IP = 4,
/// <summary> Transmission Control Protocol. </summary>
TCP = 6,
/// <summary> Exterior Gateway Protocol. </summary>
EGP = 8,
/// <summary> Xerox PUP. </summary>
PUP = 12,
/// <summary> User Datagram Protocol. </summary>
UDP = 17,
/// <summary> XEROX NS IDP. </summary>
XNS_IDP = 22,
/// <summary> ISO Transport Protocol Class 4. </summary>
ISO_TP4 = 29,
/// <summary> IPv6. </summary>
IPv6 = 41,
/// <summary> Routing Header for IPv6. </summary>
IPv6_Route = 43,
/// <summary> Fragment Header for IPv6. </summary>
IPv6_Frag = 44,
/// <summary> Resource Reservation Protocol. </summary>
RSVP = 46,
/// <summary> Generic Routing Encapsulation. </summary>
GRE = 47,
/// <summary> Encapsulating Security Payload. </summary>
ESP = 50,
/// <summary> Authentication Header. </summary>
AH = 51,
/// <summary> ICMP for IPv6. </summary>
IPv6_ICMP = 58,
/// <summary> No Next Header for IPv6. </summary>
IPv6_NoNxt = 59,
/// <summary> Destination Options for IPv6. </summary>
IPv6_Opts = 60,
/// <summary> EIGRP. </summary>
EIGRP = 88,
/// <summary> Open Shortest Path First. </summary>
OSPF = 89,
/// <summary> Multicast Transport Protocol. </summary>
MTP = 92,
/// <summary> Encapsulation Header. </summary>
ENCAP = 98,
/// <summary> Protocol Independent Multicast. </summary>
PIM = 103,
/// <summary> IP Payload Compression Protocol. </summary>
IPComp = 108,
/// <summary> Unrecognized IP protocol.
/// WARNING: this only works because the int storage for the protocol
/// code has more bits than the field in the IP header where it is stored.
/// </summary>
INVALID = -1,
/// <summary> IP protocol mask.</summary>
MASK = 0xFF
}
/// <summary> Fetch a protocol description.</summary>
/// <param name="code">the code associated with the message.
/// </param>
/// <returns> a message describing the significance of the IP protocol.
/// </returns>
public static string getDescription(IPProtocolType protocolType)
{
if (messages.ContainsKey(protocolType))
{
return messages[protocolType].ToString();
}
else
{
return "unknown";
}
}
/// <summary> 'Human-readable' IP protocol descriptions.</summary>
private static Hashtable messages = new Hashtable();
public static Hashtable Messages
{
get { return messages; }
}
/// <summary> Extract the protocol code from packet data. The packet data
/// must contain an IP datagram.
/// The protocol code specifies what kind of information is contained in the
/// data block of the ip datagram.
///
/// </summary>
/// <param name="lLen">the length of the link-level header.
/// </param>
/// <param name="packetBytes">packet bytes, including the link-layer header.
/// </param>
/// <returns> the IP protocol code. i.e. 0x06 signifies TCP protocol.
/// </returns>
public static int extractProtocol(int lLen, byte[] packetBytes)
{
IPPacket.IPVersions ipVer = ExtractVersion(lLen, packetBytes);
int protoOffset;
switch (ipVer)
{
case IPPacket.IPVersions.IPv4:
protoOffset = IPv4Fields_Fields.IP_CODE_POS;
break;
case IPPacket.IPVersions.IPv6:
protoOffset = IPv6Fields_Fields.NEXT_HEADER_POS;
break;
default:
return -1;//unknown ip version
}
return packetBytes[lLen + protoOffset];
}
public static IPPacket.IPVersions ExtractVersion(int lLen, byte[] packetBytes)
{
return (IPPacket.IPVersions)((ArrayHelper.extractInteger(packetBytes,
lLen + IPv4Fields_Fields.IP_VER_POS,
IPv4Fields_Fields.IP_VER_LEN) >> 4) & 0xF);
}
static IPProtocol()
{
{
messages[IPProtocolType.HOPOPT] = "IPv6 Hop-by-Hop Option";
messages[IPProtocolType.ICMP] = "Internet Control Message Protocol";
messages[IPProtocolType.IGMP] = "Internet Group Management Protocol";
messages[IPProtocolType.IP] = "IP in IP (encapsulation)";
messages[IPProtocolType.TCP] = "Transmission Control Protocol";
messages[IPProtocolType.EGP] = "Exterior Gateway Protocol";
messages[IPProtocolType.PUP] = "Xerox PUP";
messages[IPProtocolType.UDP] = "User Datagram Protocol";
messages[IPProtocolType.XNS_IDP] = "XEROX NS IDP";
messages[IPProtocolType.ISO_TP4] = "ISO Transport Protocol Class 4";
messages[IPProtocolType.IPv6] = "IPv6";
messages[IPProtocolType.IPv6_Route] = "Routing Header for IPv6";
messages[IPProtocolType.IPv6_Frag] = "Fragment Header for IPv6";
messages[IPProtocolType.RSVP] = "Resource Reservation Protocol";
messages[IPProtocolType.GRE] = "Generic Routing Encapsulation";
messages[IPProtocolType.ESP] = "Encapsulating Security Payload";
messages[IPProtocolType.AH] = "Authentication Header";
messages[IPProtocolType.IPv6_ICMP] = "ICMP for IPv6";
messages[IPProtocolType.IPv6_NoNxt] = "No Next Header for IPv6";
messages[IPProtocolType.IPv6_Opts] = "Destination Options for IPv6";
messages[IPProtocolType.EIGRP] = "EIGRP";
messages[IPProtocolType.OSPF] = "Open Shortest Path First";
messages[IPProtocolType.MTP] = "Multicast Transport Protocol";
messages[IPProtocolType.ENCAP] = "Encapsulation Header";
messages[IPProtocolType.PIM] = "Protocol Independent Multicast";
messages[IPProtocolType.IPComp] = "IP Payload Compression Protocol";
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.OleDb;
namespace Proje
{
public class Giris:Client
{
private int kontrol = 0;
OleDbConnection baglanti;
OleDbCommand komut;
OleDbDataReader dr;
private int KullaniciKontrol()
{
//Veritabanında girilen kullanıcı adı var mı diye kontrol et varsa 1 yoksa 0 döndür
baglanti = new OleDbConnection("Provider=Microsoft.ACE.Oledb.12.0;Data Source=C:/Users/marsl/OneDrive/Masaüstü/Dönem Projesi/YazılımProje.accdb");
komut = new OleDbCommand();
komut.Connection = baglanti;
baglanti.Open();
komut.CommandText = "SELECT KullaniciAd,Sifre FROM Kullanici where KullaniciAd='" + Kulad + "' AND Sifre=" + Sifre + "";
dr = komut.ExecuteReader();
if (dr.Read())
kontrol = 1;
baglanti.Close();
dr.Close();
return kontrol;
}
public void GirisYap()
{
//Veritabanı bağlantısı kurup giriş işlemlerini yap.
if (Kulad=="admin" && Sifre==123)
{
AdminOnay ao = new AdminOnay();
ao.Show();
}
else
{
if (KullaniciKontrol() == 1)//Kullanıcı kayıtlı ise giriş yap
{
System.Windows.Forms.MessageBox.Show("Girdiğiniz Bilgiler Sistemde Kayıtlı Programa Girişiniz Yapılıyor.");
AliciveSaticiBilgiGiris asbg = new AliciveSaticiBilgiGiris();
asbg.KullaniciAd = Kulad;
asbg.Show();
}
else//kullanici kayıtlı değil ise
{
System.Windows.Forms.MessageBox.Show("Bilgileriniz Sistemde Bulunmuyor Lütfen Tekrar Deneyiniz.Hesabınız Yoksa Lütfen Kayıt Olunuz.");
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;
using System.Drawing;
/// <summary>
/// 该类用于导出经对比、合并等操作后的Excel文件及报告文件
/// </summary>
public class ExportExcelFileHelper
{
/// <summary>
/// 对比新旧两张Excel母表,返回旧表中含有但新表中已删除的Key所在旧表中的数据索引、新表中新增Key所在新表中的数据索引、新表中的主语言翻译相对旧表变动的Key所在新表中的数据索引(下标均从0开始)
/// </summary>
public static void CompareExcelFile(LangExcelInfo langExcelInfo, LangExcelInfo oldLangExcelInfo, out List<int> delectedKeyIndex, out List<int> newKeyIndex, out List<int> translationChangedIndex)
{
delectedKeyIndex = new List<int>();
newKeyIndex = new List<int>();
translationChangedIndex = new List<int>();
List<LanguageInfo> languageInfoList = langExcelInfo.GetAllLanguageInfoList();
List<LanguageInfo> oldLanguageInfoList = oldLangExcelInfo.GetAllLanguageInfoList();
// 查找新表中已删除的Key
List<string> keys = langExcelInfo.Keys;
List<string> oldKeys = oldLangExcelInfo.Keys;
int oldKeyCount = oldKeys.Count;
for (int i = 0; i < oldKeyCount; ++i)
{
string oldKey = oldKeys[i];
if (oldKey != null && !keys.Contains(oldKey))
delectedKeyIndex.Add(i);
}
// 查找新增Key、主语言翻译变动
int keyCount = keys.Count;
List<string> defaultLanguageDataList = langExcelInfo.DefaultLanguageInfo.Data;
List<string> oldDefaultLanguageDataList = oldLangExcelInfo.DefaultLanguageInfo.Data;
for (int i = 0; i < keyCount; ++i)
{
string key = keys[i];
if (key == null)
continue;
else if (!oldKeys.Contains(key))
newKeyIndex.Add(i);
else
{
string data = defaultLanguageDataList[i];
if (data == null)
continue;
else
{
int dataIndexInOldLanguageFile = oldLangExcelInfo.KeyToDataIndex[key];
string oldData = oldDefaultLanguageDataList[dataIndexInOldLanguageFile];
if (!data.Equals(oldData))
translationChangedIndex.Add(i);
}
}
}
}
/// <summary>
/// 导出新版母表相对旧版新增Key、主语言翻译变动所在行信息到新建的Excel文件中。返回true表示生成了Excel文件,反之表示无需生成或存在错误
/// </summary>
public static bool ExportNeedTranslateExcelFile(string savePath, out string errorString, out string promptMessage)
{
promptMessage = null;
errorString = null;
// 旧表中含有但新表中已删除的Key所在旧表中的数据索引(下标从0开始)
List<int> delectedKeyIndex = new List<int>();
// 新表中新增Key所在新表中的数据索引(下标从0开始)
List<int> newKeyIndex = new List<int>();
// 新表中的主语言翻译相对旧表变动的Key所在新表中的数据索引(下标从0开始)
List<int> translationChangedIndex = new List<int>();
List<LanguageInfo> languageInfoList = AppValues.LangExcelInfo.GetAllLanguageInfoList();
List<LanguageInfo> oldLanguageInfoList = AppValues.OldLangExcelInfo.GetAllLanguageInfoList();
List<string> keys = AppValues.LangExcelInfo.Keys;
List<string> oldKeys = AppValues.OldLangExcelInfo.Keys;
List<string> defaultLanguageDataList = AppValues.LangExcelInfo.DefaultLanguageInfo.Data;
List<string> oldDefaultLanguageDataList = AppValues.OldLangExcelInfo.DefaultLanguageInfo.Data;
// 进行新旧母表对比
CompareExcelFile(AppValues.LangExcelInfo, AppValues.OldLangExcelInfo, out delectedKeyIndex, out newKeyIndex, out translationChangedIndex);
if (delectedKeyIndex.Count == 0 && newKeyIndex.Count == 0 && translationChangedIndex.Count == 0)
{
promptMessage = "新旧母表经对比未发现需要更新翻译的内容";
return false;
}
// 新版母表中已删除的Key信息写入新建文本文件中,路径与选择导出的新建Excel文件相同
if (delectedKeyIndex.Count > 0)
{
StringBuilder delectedKeyInfoBuilder = new StringBuilder();
for (int i = 0; i < delectedKeyIndex.Count; ++i)
{
int dataIndex = delectedKeyIndex[i];
delectedKeyInfoBuilder.AppendFormat("第{0}行,Key为\"{1}\",主语言译文为\"{2}\"", dataIndex + AppValues.EXCEL_DATA_START_INDEX, oldKeys[dataIndex], oldDefaultLanguageDataList[dataIndex]).AppendLine();
}
string txtFileName = string.Format("新版母表相对于旧版已删除Key信息 {0:yyyy年MM月dd日 HH时mm分ss秒}.txt", DateTime.Now);
string txtFileSavePath = Utils.CombinePath(Path.GetDirectoryName(savePath), txtFileName);
if (Utils.SaveFile(txtFileSavePath, delectedKeyInfoBuilder.ToString(), out errorString) == true)
promptMessage = string.Format("发现新版母表相对于旧版存在已删除的Key,相关信息已保存到{0}", txtFileSavePath);
else
promptMessage = string.Format("发现以下新版母表相对于旧版存在已删除的Key信息:\n{0}", delectedKeyInfoBuilder.ToString());
}
// 新增Key、主语言翻译变动信息需写入新建Excel文件中
if (newKeyIndex.Count > 0 || translationChangedIndex.Count > 0)
{
// 导出待翻译内容到指定的新建Excel文件中
Excel.Application application = new Excel.Application();
// 不显示Excel窗口
application.Visible = false;
// 不显示警告对话框
application.DisplayAlerts = false;
// 禁止屏幕刷新
application.ScreenUpdating = false;
// 编辑非空单元格时不进行警告提示
application.AlertBeforeOverwriting = false;
// 新建Excel工作簿
Excel.Workbook workbook = application.Workbooks.Add();
// 在名为data的Sheet表中填充数据
Excel.Worksheet dataWorksheet = workbook.Sheets[1] as Excel.Worksheet;
dataWorksheet.Name = AppValues.EXCEL_DATA_SHEET_NAME.Replace("$", "");
// 设置表格中所有单元格均为文本格式
dataWorksheet.Cells.NumberFormatLocal = "@";
// 写入待翻译的内容,列自左向右分别为Key、新版主语言译文、旧版主语言译文、旧版各语种译文(注意Excel中左上角单元格下标为[1,1])
// 定义各功能列在Excel的列号(从1开始计)
const int EXCEL_KEY_COLUMN_INDEX = 1;
const int EXCEL_DEFAULT_LANGUAGE_COLUMN_INDEX = 2;
const int EXCEL_OLD_DEFAULT_LANGUAGE_COLUMN_INDEX = 3;
const int EXCEL_OLD_OTHER_LANGUAGE_START_COLUMN_INDEX = 4;
// 写入语种描述信息、名称
dataWorksheet.Cells[AppValues.EXCEL_DESC_ROW_INDEX, EXCEL_KEY_COLUMN_INDEX] = "新增或主语言翻译变动的Key";
dataWorksheet.Cells[AppValues.EXCEL_DESC_ROW_INDEX, EXCEL_DEFAULT_LANGUAGE_COLUMN_INDEX] = "新版母表中主语言译文";
dataWorksheet.Cells[AppValues.EXCEL_NAME_ROW_INDEX, EXCEL_DEFAULT_LANGUAGE_COLUMN_INDEX] = languageInfoList[0].Name;
dataWorksheet.Cells[AppValues.EXCEL_DESC_ROW_INDEX, EXCEL_OLD_DEFAULT_LANGUAGE_COLUMN_INDEX] = "旧版母表中主语言译文";
int languageCount = languageInfoList.Count;
int otherLanguageCount = languageCount - 1;
for (int i = 1; i < languageCount; ++i)
{
string languageName = oldLanguageInfoList[i].Name;
dataWorksheet.Cells[AppValues.EXCEL_DESC_ROW_INDEX, i + EXCEL_OLD_DEFAULT_LANGUAGE_COLUMN_INDEX] = string.Format("旧版{0}语种的译文", languageName);
dataWorksheet.Cells[AppValues.EXCEL_NAME_ROW_INDEX, i + EXCEL_OLD_DEFAULT_LANGUAGE_COLUMN_INDEX] = languageName;
}
// 先将新版中主语言翻译变动内容写入新建的Excel文件
int translationChangedCount = translationChangedIndex.Count;
for (int i = 0; i < translationChangedCount; ++i)
{
int rowIndex = i + AppValues.EXCEL_DATA_START_INDEX;
int excelDataIndex = translationChangedIndex[i];
string key = keys[excelDataIndex];
int oldExcelDataIndex = AppValues.OldLangExcelInfo.KeyToDataIndex[key];
// Key
dataWorksheet.Cells[rowIndex, EXCEL_KEY_COLUMN_INDEX] = key;
// 新版主语言译文
dataWorksheet.Cells[rowIndex, EXCEL_DEFAULT_LANGUAGE_COLUMN_INDEX] = defaultLanguageDataList[excelDataIndex];
// 旧版主语言译文
dataWorksheet.Cells[rowIndex, EXCEL_OLD_DEFAULT_LANGUAGE_COLUMN_INDEX] = oldDefaultLanguageDataList[oldExcelDataIndex];
// 旧版各语种的译文
for (int j = 1; j < otherLanguageCount + 1; ++j)
{
int columnIndex = EXCEL_OLD_OTHER_LANGUAGE_START_COLUMN_INDEX + j - 1;
string data = oldLanguageInfoList[j].Data[oldExcelDataIndex];
dataWorksheet.Cells[rowIndex, columnIndex] = data;
}
}
// 空出3行后,将新版母表中新增Key内容写入新建的Excel文件,只需写入Key和新版母表中的主语言译文
const int SPACE_LINE_COUNT = 3;
int newKeyDataStartRowIndex = AppValues.EXCEL_DATA_START_INDEX + translationChangedCount + SPACE_LINE_COUNT;
if (translationChangedCount == 0)
newKeyDataStartRowIndex = AppValues.EXCEL_DATA_START_INDEX;
int newKeyCount = newKeyIndex.Count;
for (int i = 0; i < newKeyCount; ++i)
{
int excelDataIndex = newKeyIndex[i];
int rowIndex = i + newKeyDataStartRowIndex;
// Key
dataWorksheet.Cells[rowIndex, EXCEL_KEY_COLUMN_INDEX] = keys[excelDataIndex];
// 新版主语言译文
dataWorksheet.Cells[rowIndex, EXCEL_DEFAULT_LANGUAGE_COLUMN_INDEX] = defaultLanguageDataList[excelDataIndex];
}
// 对前2行配置行执行窗口冻结
Excel.Range excelRange = dataWorksheet.get_Range(dataWorksheet.Cells[AppValues.EXCEL_DATA_START_INDEX, 1], dataWorksheet.Cells[AppValues.EXCEL_DATA_START_INDEX + 1, 1]);
excelRange.Select();
application.ActiveWindow.FreezePanes = true;
// 美化生成的Excel文件
int lastColumnIndex = EXCEL_OLD_OTHER_LANGUAGE_START_COLUMN_INDEX + otherLanguageCount - 1;
_BeautifyExcelWorksheet(dataWorksheet, 30, lastColumnIndex);
// 保存Excel
dataWorksheet.SaveAs(savePath);
workbook.SaveAs(savePath);
// 关闭Excel
workbook.Close(false);
application.Workbooks.Close();
application.Quit();
Utils.KillExcelProcess(application);
return true;
}
return false;
}
/// <summary>
/// 复制最新母表,并将新增Key、主语言翻译变动所在行信息用指定颜色突出标注。返回true表示生成了Excel文件,反之表示无需生成或存在错误
/// </summary>
public static bool ExportComparedExcelFile(Color colorForAdd, Color colorForChange, string fillNullCellText, string savePath, out string errorString, out string promptMessage)
{
promptMessage = null;
errorString = null;
// 旧表中含有但新表中已删除的Key所在旧表中的数据索引(下标从0开始)
List<int> delectedKeyIndex = new List<int>();
// 新表中新增Key所在新表中的数据索引(下标从0开始)
List<int> newKeyIndex = new List<int>();
// 新表中的主语言翻译相对旧表变动的Key所在新表中的数据索引(下标从0开始)
List<int> translationChangedIndex = new List<int>();
List<string> oldKeys = AppValues.OldLangExcelInfo.Keys;
List<string> oldDefaultLanguageDataList = AppValues.OldLangExcelInfo.DefaultLanguageInfo.Data;
// 找到所有外语语种所在Excel文件中的列号(从1开始计)
List<int> otherLanguageColumnIndex = new List<int>();
foreach (LanguageInfo info in AppValues.LangExcelInfo.OtherLanguageInfo.Values)
otherLanguageColumnIndex.Add(info.ColumnIndex);
// 进行新旧母表对比
CompareExcelFile(AppValues.LangExcelInfo, AppValues.OldLangExcelInfo, out delectedKeyIndex, out newKeyIndex, out translationChangedIndex);
if (delectedKeyIndex.Count == 0 && newKeyIndex.Count == 0 && translationChangedIndex.Count == 0)
{
promptMessage = "新旧母表经对比未发现需要更新翻译的内容";
return false;
}
// 新版母表中已删除的Key信息写入新建文本文件中,路径与选择导出的新建Excel文件相同
if (delectedKeyIndex.Count > 0)
{
StringBuilder delectedKeyInfoBuilder = new StringBuilder();
for (int i = 0; i < delectedKeyIndex.Count; ++i)
{
int dataIndex = delectedKeyIndex[i];
delectedKeyInfoBuilder.AppendFormat("第{0}行,Key为\"{1}\",主语言译文为\"{2}\"", dataIndex + AppValues.EXCEL_DATA_START_INDEX, oldKeys[dataIndex], oldDefaultLanguageDataList[dataIndex]).AppendLine();
}
string txtFileName = string.Format("新版母表相对于旧版已删除Key信息 {0:yyyy年MM月dd日 HH时mm分ss秒}.txt", DateTime.Now);
string txtFileSavePath = Utils.CombinePath(Path.GetDirectoryName(savePath), txtFileName);
if (Utils.SaveFile(txtFileSavePath, delectedKeyInfoBuilder.ToString(), out errorString) == true)
promptMessage = string.Format("发现新版母表相对于旧版存在已删除的Key,相关信息已保存到{0}", txtFileSavePath);
else
promptMessage = string.Format("发现以下新版母表相对于旧版存在已删除的Key信息:\n{0}", delectedKeyInfoBuilder.ToString());
}
// 新增Key、主语言翻译变动所在行需在复制的新版母表中用指定背景色进行标注
if (newKeyIndex.Count > 0 || translationChangedIndex.Count > 0)
{
// 复制新版母表
FileState fileState = Utils.GetFileState(AppValues.ExcelFullPath);
if (fileState == FileState.Inexist)
{
errorString = string.Format("新版母表所在路径({0})已不存在,请勿在使用本工具过程中对母表文件进行操作,导出操作被迫中止", AppValues.ExcelFullPath);
return false;
}
try
{
File.Copy(AppValues.ExcelFullPath, savePath, true);
}
catch (Exception exception)
{
errorString = string.Format("复制新版母表({0})至指定路径({1})失败:{2},导出操作被迫中止", AppValues.ExcelFullPath, savePath, exception.Message);
return false;
}
// 打开复制后的母表
// 导出待翻译内容到指定的新建Excel文件中
Excel.Application application = new Excel.Application();
// 不显示Excel窗口
application.Visible = false;
// 不显示警告对话框
application.DisplayAlerts = false;
// 禁止屏幕刷新
application.ScreenUpdating = false;
// 编辑非空单元格时不进行警告提示
application.AlertBeforeOverwriting = false;
// 打开Excel工作簿
Excel.Workbook workbook = application.Workbooks.Open(savePath);
// 找到名为data的Sheet表
Excel.Worksheet dataWorksheet = null;
int sheetCount = workbook.Sheets.Count;
string DATA_SHEET_NAME = AppValues.EXCEL_DATA_SHEET_NAME.Replace("$", "");
for (int i = 1; i <= sheetCount; ++i)
{
Excel.Worksheet sheet = workbook.Sheets[i] as Excel.Worksheet;
if (sheet.Name.Equals(DATA_SHEET_NAME))
{
dataWorksheet = sheet;
break;
}
}
if (dataWorksheet == null)
{
errorString = string.Format("新版母表({0})找不到Sheet名为{1}的数据表,请勿在使用本工具过程中对母表文件进行操作,导出操作被迫中止", AppValues.ExcelFullPath, DATA_SHEET_NAME);
return false;
}
// 先将所有行的背景色清除
dataWorksheet.Cells.Interior.ColorIndex = 0;
// 将新增Key所在行背景色调为指定颜色并将对应译文部分统一填充为指定的字符串
int newKeyCount = newKeyIndex.Count;
for (int i = 0; i < newKeyCount; ++i)
{
int excelDataIndex = newKeyIndex[i];
int rowIndex = excelDataIndex + AppValues.EXCEL_DATA_START_INDEX;
// 调整背景色
dataWorksheet.get_Range(string.Concat("A", rowIndex)).EntireRow.Interior.Color = ColorTranslator.ToOle(colorForAdd);
// 新增Key所在行的外语单元格填充为指定的字符串
foreach (int columnIndex in otherLanguageColumnIndex)
dataWorksheet.Cells[rowIndex, columnIndex] = fillNullCellText;
}
// 将翻译变动Key所在行背景色调为指定颜色,保留新版母表中储存的旧版外语译文
int translationChangedCount = translationChangedIndex.Count;
for (int i = 0; i < translationChangedCount; ++i)
{
int excelDataIndex = translationChangedIndex[i];
int rowIndex = excelDataIndex + AppValues.EXCEL_DATA_START_INDEX;
// 调整背景色
dataWorksheet.get_Range(string.Concat("A", rowIndex)).EntireRow.Interior.Color = ColorTranslator.ToOle(colorForChange);
}
// 保存Excel
dataWorksheet.SaveAs(savePath);
workbook.SaveAs(savePath);
// 关闭Excel
workbook.Close(false);
application.Workbooks.Close();
application.Quit();
Utils.KillExcelProcess(application);
return true;
}
return false;
}
/// <summary>
/// 复制最新母表,将翻译完的Excel文件内容与之合并,并将合并结果报告写入新建的Excel文件中
/// </summary>
public static bool ExportMergedExcelFile(string mergedExcelSavePath, string reportExcelSavePath, LangExcelInfo langExcelInfo, LangExcelInfo translatedLangExcelInfo, List<string> mergeLanguageNames, out string errorString)
{
int languageCount = mergeLanguageNames.Count;
// 记录合并翻译时发现的新版母表与翻译完的Excel文件中Key相同但主语言翻译不同信息
List<MergedResultDifferentDefaultLanguageInfo> differentDefaultLanguageInfo = new List<MergedResultDifferentDefaultLanguageInfo>();
// 记录合并翻译时发现的新版母表与翻译完的Excel文件中Key不同信息
List<MergedResultDifferentKeyInfo> differentKeyInfo = new List<MergedResultDifferentKeyInfo>();
// 记录各个报告部分起始行行号
List<int> partStartRowIndexList = new List<int>();
partStartRowIndexList.Add(1);
// 复制新版母表
FileState fileState = Utils.GetFileState(AppValues.ExcelFullPath);
if (fileState == FileState.Inexist)
{
errorString = string.Format("新版母表所在路径({0})已不存在,请勿在使用本工具过程中对母表文件进行操作,合并操作被迫中止", AppValues.ExcelFullPath);
return false;
}
try
{
File.Copy(AppValues.ExcelFullPath, mergedExcelSavePath, true);
}
catch (Exception exception)
{
errorString = string.Format("复制新版母表({0})至指定路径({1})失败:{2},合并操作被迫中止", AppValues.ExcelFullPath, mergedExcelSavePath, exception.Message);
return false;
}
// 打开复制后的母表,将翻译完的Excel文件中的内容与之合并
Excel.Application mergedApplication = new Excel.Application();
// 不显示Excel窗口
mergedApplication.Visible = false;
// 不显示警告对话框
mergedApplication.DisplayAlerts = false;
// 禁止屏幕刷新
mergedApplication.ScreenUpdating = false;
// 编辑非空单元格时不进行警告提示
mergedApplication.AlertBeforeOverwriting = false;
// 打开Excel工作簿
Excel.Workbook mergedWorkbook = mergedApplication.Workbooks.Open(mergedExcelSavePath);
// 找到名为data的Sheet表
Excel.Worksheet mergedDataWorksheet = null;
int sheetCount = mergedWorkbook.Sheets.Count;
string DATA_SHEET_NAME = AppValues.EXCEL_DATA_SHEET_NAME.Replace("$", "");
for (int i = 1; i <= sheetCount; ++i)
{
Excel.Worksheet sheet = mergedWorkbook.Sheets[i] as Excel.Worksheet;
if (sheet.Name.Equals(DATA_SHEET_NAME))
{
mergedDataWorksheet = sheet;
break;
}
}
if (mergedDataWorksheet == null)
{
errorString = string.Format("新版母表({0})找不到Sheet名为{1}的数据表,请勿在使用本工具过程中对母表文件进行操作,导出操作被迫中止", AppValues.ExcelFullPath, DATA_SHEET_NAME);
return false;
}
// 还要新建一张新表,保存合并报告
Excel.Application reportApplication = new Excel.Application();
reportApplication.Visible = false;
reportApplication.DisplayAlerts = false;
reportApplication.ScreenUpdating = false;
reportApplication.AlertBeforeOverwriting = false;
// 新建Excel工作簿
Excel.Workbook reportWorkbook = reportApplication.Workbooks.Add();
// 在名为合并报告的Sheet表中填充数据
Excel.Worksheet reportWorksheet = reportWorkbook.Sheets[1] as Excel.Worksheet;
reportWorksheet.Name = "合并报告";
// 设置表格中所有单元格均为文本格式
reportWorksheet.Cells.NumberFormatLocal = "@";
// 报告Excel文件中依次按Key与主语言译文均相同、Key相同但主语言译文不同、母表不存在指定Key分成三部分进行报告
// 不同部分之间隔开的行数
const int SPACE_LINE_COUNT = 3;
// Key与主语言译文相同的报告部分,列依次为Key名、母表行号、翻译完的Excel文件中的行号、主语言译文、各外语译文,其中用无色背景标识两表译文相同的单元格,用绿色背景标识母表未翻译而翻译完的Excel文件中新增译文的单元格,用黄色背景标识译文不同的单元格(并以批注形式写入母表中旧的译文)
const int ALL_SAME_KEY_COLUMN_INDEX = 1;
const int ALL_SAME_FILE_LINE_NUM_COLUMN_INDEX = 2;
const int ALL_SAME_TRANSLATED_FILE_LINE_NUM_COLUMN_INDEX = 3;
const int ALL_SAME_DEFAULT_LANGUAGE_VALUE_COLUMN_INDEX = 4;
const int ALL_SAME_OTHER_LANGUAGE_START_COLUMN_INDEX = 5;
// 每个部分首行写入说明文字
reportWorksheet.Cells[1, 1] = "以下为已合并的译文报告,其中用无色背景标识两表译文相同的单元格,用绿色背景标识母表未翻译而翻译完的Excel文件中新增译文的单元格,用黄色背景标识译文不同的单元格(并以批注形式写入母表中旧的译文)";
// 写入Key与主语言译文均相同部分的列标题说明
reportWorksheet.Cells[2, ALL_SAME_KEY_COLUMN_INDEX] = "Key名";
reportWorksheet.Cells[2, ALL_SAME_FILE_LINE_NUM_COLUMN_INDEX] = "母表中的行号";
reportWorksheet.Cells[2, ALL_SAME_TRANSLATED_FILE_LINE_NUM_COLUMN_INDEX] = "翻译完的Excel表中的行号";
reportWorksheet.Cells[2, ALL_SAME_DEFAULT_LANGUAGE_VALUE_COLUMN_INDEX] = "主语言译文";
for (int i = 0; i < languageCount; ++i)
{
int columnIndex = ALL_SAME_OTHER_LANGUAGE_START_COLUMN_INDEX + i;
reportWorksheet.Cells[2, columnIndex] = mergeLanguageNames[i];
}
// 当前报告Excel表中下一个可用空行的行号(从1开始计)
int nextCellLineNum = 3;
// 逐行读取翻译完的Excel表中的内容并与最新母表比较,若Key相同主语言翻译相同,直接将翻译完的Excel表中对应的外语译文合并到母表,若Key相同但主语言翻译不同或者翻译完的Excel表中存在母表中已没有的Key则不合并且记入报告
int translatedExcelDataCount = translatedLangExcelInfo.Keys.Count;
for (int i = 0; i < translatedExcelDataCount; ++i)
{
string mergedExcelKey = translatedLangExcelInfo.Keys[i];
if (mergedExcelKey == null)
continue;
// 判断母表中是否存在指定Key
if (langExcelInfo.Keys.Contains(mergedExcelKey))
{
// 判断母表与翻译完的Excel文件中该Key对应的主语言译文是否相同
// 母表中该Key所在行的数据索引
int excelDataIndex = langExcelInfo.KeyToDataIndex[mergedExcelKey];
string excelDefaultLanguageValue = langExcelInfo.DefaultLanguageInfo.Data[excelDataIndex];
string translatedExcelDefaultLanguageValue = translatedLangExcelInfo.DefaultLanguageInfo.Data[i];
if (excelDefaultLanguageValue.Equals(translatedExcelDefaultLanguageValue))
{
// 如果该行外语的翻译均相同,则无需合并且不需要记入报告
bool isAllSame = true;
foreach (string languageName in mergeLanguageNames)
{
string excelLanguageValue = langExcelInfo.OtherLanguageInfo[languageName].Data[excelDataIndex];
string translatedLanguageValue = translatedLangExcelInfo.OtherLanguageInfo[languageName].Data[i];
if (!excelLanguageValue.Equals(translatedLanguageValue))
{
isAllSame = false;
break;
}
}
// 存在不同的译文,则要合并到母表中并记入报告
if (isAllSame == false)
{
reportWorksheet.Cells[nextCellLineNum, ALL_SAME_KEY_COLUMN_INDEX] = mergedExcelKey;
reportWorksheet.Cells[nextCellLineNum, ALL_SAME_FILE_LINE_NUM_COLUMN_INDEX] = excelDataIndex + AppValues.EXCEL_DATA_START_INDEX;
reportWorksheet.Cells[nextCellLineNum, ALL_SAME_TRANSLATED_FILE_LINE_NUM_COLUMN_INDEX] = i + AppValues.EXCEL_DATA_START_INDEX;
reportWorksheet.Cells[nextCellLineNum, ALL_SAME_TRANSLATED_FILE_LINE_NUM_COLUMN_INDEX] = i + AppValues.EXCEL_DATA_START_INDEX;
reportWorksheet.Cells[nextCellLineNum, ALL_SAME_DEFAULT_LANGUAGE_VALUE_COLUMN_INDEX] = translatedExcelDefaultLanguageValue;
for (int j = 0; j < languageCount; ++j)
{
string languageName = mergeLanguageNames[j];
string excelLanguageValue = langExcelInfo.OtherLanguageInfo[languageName].Data[excelDataIndex];
string translatedLanguageValue = translatedLangExcelInfo.OtherLanguageInfo[languageName].Data[i];
int columnIndex = ALL_SAME_OTHER_LANGUAGE_START_COLUMN_INDEX + j;
// 报告中外语列单元格都要写入翻译完的Excel文件中对应的译文
reportWorksheet.Cells[nextCellLineNum, columnIndex] = translatedLanguageValue;
if (!excelLanguageValue.Equals(translatedLanguageValue))
{
int mergedExcelRowIndex = excelDataIndex + AppValues.EXCEL_DATA_START_INDEX;
int mergedExcelColumnIndex = langExcelInfo.OtherLanguageInfo[languageName].ColumnIndex;
if (string.IsNullOrEmpty(excelLanguageValue))
{
// 母表中原来没有译文,则将报告Excel表中对应单元格背景色设为绿色
reportWorksheet.get_Range(reportWorksheet.Cells[nextCellLineNum, columnIndex], reportWorksheet.Cells[nextCellLineNum, columnIndex]).Interior.ColorIndex = 4;
}
else
{
// 母表中和翻译完的Excel表中译文不同,则用黄色背景标识译文不同的单元格(并以批注形式写入母表中旧的译文)
reportWorksheet.get_Range(reportWorksheet.Cells[nextCellLineNum, columnIndex], reportWorksheet.Cells[nextCellLineNum, columnIndex]).Interior.ColorIndex = 6;
reportWorksheet.get_Range(reportWorksheet.Cells[nextCellLineNum, columnIndex], reportWorksheet.Cells[nextCellLineNum, columnIndex]).AddComment(string.Concat("母表中旧的译文:", System.Environment.NewLine, excelLanguageValue));
}
// 将翻译完的Excel表中的译文写入母表
mergedDataWorksheet.Cells[mergedExcelRowIndex, mergedExcelColumnIndex] = translatedLanguageValue;
}
}
++nextCellLineNum;
}
}
else
{
// Key相同,主语言译文不同则不合并且记入报告
MergedResultDifferentDefaultLanguageInfo info = new MergedResultDifferentDefaultLanguageInfo();
info.ExcelLineNum = excelDataIndex + AppValues.EXCEL_DATA_START_INDEX;
info.TranslatedExcelLineNum = i + AppValues.EXCEL_DATA_START_INDEX;
info.Key = mergedExcelKey;
info.ExcelDefaultLanguageValue = excelDefaultLanguageValue;
info.TranslatedExcelDefaultLanguageValue = translatedExcelDefaultLanguageValue;
differentDefaultLanguageInfo.Add(info);
}
}
else
{
// 翻译完的Excel表中存在母表中已没有的Key则不合并且记入报告
MergedResultDifferentKeyInfo info = new MergedResultDifferentKeyInfo();
info.TranslatedExcelLineNum = i + AppValues.EXCEL_DATA_START_INDEX;
info.Key = mergedExcelKey;
info.TranslatedExcelDefaultLanguageValue = translatedLangExcelInfo.DefaultLanguageInfo.Data[i];
differentKeyInfo.Add(info);
}
}
// 设置框线及标题行格式
_FormatPart(reportWorksheet, 1, nextCellLineNum - 1, ALL_SAME_OTHER_LANGUAGE_START_COLUMN_INDEX + languageCount - 1);
// Key相同但主语言译文不同的报告部分,列依次为Key名、母表行号、翻译完的Excel文件中的行号、母表中主语言译文、翻译完的Excel文件中主语言译文
const int KEY_SAME_KEY_COLUMN_INDEX = 1;
const int KEY_SAME_FILE_LINE_NUM_COLUMN_INDEX = 2;
const int KEY_SAME_TRANSLATED_FILE_LINE_NUM_COLUMN_INDEX = 3;
const int KEY_SAME_EXCEL_DEFAULT_LANGUAGE_VALUE_COLUMN_INDEX = 4;
const int KEY_SAME_TRANSLATED_DEFAULT_LANGUAGE_VALUE_COLUMN_INDEX = 5;
if (differentDefaultLanguageInfo.Count > 0)
{
nextCellLineNum = nextCellLineNum + SPACE_LINE_COUNT;
partStartRowIndexList.Add(nextCellLineNum);
// 每个部分首行写入说明文字
reportWorksheet.Cells[nextCellLineNum, 1] = "以下为母表与翻译完的Excel表中Key相同但主语言译文不同,无法进行合并的信息";
++nextCellLineNum;
// 写入Key相同但主语言译文不同部分的列标题说明
reportWorksheet.Cells[nextCellLineNum, KEY_SAME_KEY_COLUMN_INDEX] = "Key名";
reportWorksheet.Cells[nextCellLineNum, KEY_SAME_FILE_LINE_NUM_COLUMN_INDEX] = "母表中的行号";
reportWorksheet.Cells[nextCellLineNum, KEY_SAME_TRANSLATED_FILE_LINE_NUM_COLUMN_INDEX] = "翻译完的Excel表中的行号";
reportWorksheet.Cells[nextCellLineNum, KEY_SAME_EXCEL_DEFAULT_LANGUAGE_VALUE_COLUMN_INDEX] = "母表中主语言译文";
reportWorksheet.Cells[nextCellLineNum, KEY_SAME_TRANSLATED_DEFAULT_LANGUAGE_VALUE_COLUMN_INDEX] = "翻译完的Excel文件中主语言译文";
++nextCellLineNum;
// 将所有Key相同但主语言译文不同信息写入报告
foreach (MergedResultDifferentDefaultLanguageInfo info in differentDefaultLanguageInfo)
{
reportWorksheet.Cells[nextCellLineNum, KEY_SAME_KEY_COLUMN_INDEX] = info.Key;
reportWorksheet.Cells[nextCellLineNum, KEY_SAME_FILE_LINE_NUM_COLUMN_INDEX] = info.ExcelLineNum;
reportWorksheet.Cells[nextCellLineNum, KEY_SAME_TRANSLATED_FILE_LINE_NUM_COLUMN_INDEX] = info.TranslatedExcelLineNum;
reportWorksheet.Cells[nextCellLineNum, KEY_SAME_EXCEL_DEFAULT_LANGUAGE_VALUE_COLUMN_INDEX] = info.ExcelDefaultLanguageValue;
reportWorksheet.Cells[nextCellLineNum, KEY_SAME_TRANSLATED_DEFAULT_LANGUAGE_VALUE_COLUMN_INDEX] = info.TranslatedExcelDefaultLanguageValue;
++nextCellLineNum;
}
}
// 设置框线及标题行格式
_FormatPart(reportWorksheet, partStartRowIndexList[1], nextCellLineNum - 1, KEY_SAME_TRANSLATED_DEFAULT_LANGUAGE_VALUE_COLUMN_INDEX);
// 母表不存在指定Key的报告部分,列依次为Key名、翻译完的Excel文件中的行号以及主语言译文
const int KEY_DIFFERENT_KEY_COLUMN_INDEX = 1;
const int KEY_DIFFERENT_TRANSLATED_FILE_LINE_NUM_COLUMN_INDEX = 2;
const int KEY_DIFFERENT_TRANSLATED_DEFAULT_LANGUAGE_VALUE_COLUMN_INDEX = 3;
if (differentKeyInfo.Count > 0)
{
nextCellLineNum = nextCellLineNum + SPACE_LINE_COUNT;
partStartRowIndexList.Add(nextCellLineNum);
// 每个部分首行写入说明文字
reportWorksheet.Cells[nextCellLineNum, 1] = "以下为翻译完的Excel文件含有但母表已经没有的Key,无法进行合并的信息";
++nextCellLineNum;
// 写入母表中已没有的Key部分的列标题说明
reportWorksheet.Cells[nextCellLineNum, KEY_DIFFERENT_KEY_COLUMN_INDEX] = "Key名";
reportWorksheet.Cells[nextCellLineNum, KEY_DIFFERENT_TRANSLATED_FILE_LINE_NUM_COLUMN_INDEX] = "翻译完的Excel表中的行号";
reportWorksheet.Cells[nextCellLineNum, KEY_DIFFERENT_TRANSLATED_DEFAULT_LANGUAGE_VALUE_COLUMN_INDEX] = "翻译完的Excel文件中主语言译文";
++nextCellLineNum;
// 将所有母表中已没有的Key信息写入报告
foreach (MergedResultDifferentKeyInfo info in differentKeyInfo)
{
reportWorksheet.Cells[nextCellLineNum, KEY_DIFFERENT_KEY_COLUMN_INDEX] = info.Key;
reportWorksheet.Cells[nextCellLineNum, KEY_DIFFERENT_TRANSLATED_FILE_LINE_NUM_COLUMN_INDEX] = info.TranslatedExcelLineNum;
reportWorksheet.Cells[nextCellLineNum, KEY_DIFFERENT_TRANSLATED_DEFAULT_LANGUAGE_VALUE_COLUMN_INDEX] = info.TranslatedExcelDefaultLanguageValue;
++nextCellLineNum;
}
}
// 设置框线及标题行格式
_FormatPart(reportWorksheet, partStartRowIndexList[2], nextCellLineNum - 1, KEY_DIFFERENT_TRANSLATED_DEFAULT_LANGUAGE_VALUE_COLUMN_INDEX);
// 美化生成的Excel文件
_BeautifyExcelWorksheet(reportWorksheet, 40, nextCellLineNum - 1);
// 因为Excel中执行过合并的单元格即便设置了自动换行也无法实现效果,故为了防止每个部分首行的描述文字不完全可见,手工修改其行高
for (int i = 0; i < partStartRowIndexList.Count; ++i)
{
int partStartRowIndex = partStartRowIndexList[i];
reportWorksheet.get_Range("A" + partStartRowIndex).EntireRow.RowHeight = 80;
}
// 保存报告Excel文件
reportWorksheet.SaveAs(reportExcelSavePath);
reportWorkbook.SaveAs(reportExcelSavePath);
// 关闭Excel
reportWorkbook.Close(false);
reportApplication.Workbooks.Close();
reportApplication.Quit();
Utils.KillExcelProcess(reportApplication);
// 保存合并后的Excel文件
mergedDataWorksheet.SaveAs(mergedExcelSavePath);
mergedWorkbook.SaveAs(mergedExcelSavePath);
// 关闭Excel
mergedWorkbook.Close(false);
mergedApplication.Workbooks.Close();
mergedApplication.Quit();
Utils.KillExcelProcess(mergedApplication);
errorString = null;
return true;
}
/// <summary>
/// 格式化每个报告部分的报告内容,将每个部分设置粗实线外边框,首行(部分描述行)字体设为16号加粗并合并单元格,第二行(列字段说明行)设为细实线内外边框绿色背景、字体加粗
/// </summary>
public static void _FormatPart(Worksheet worksheet, int startRowIndex, int endRowIndex, int columnCount)
{
// 首行(部分描述行)字体设为16号加粗并合并单元格
worksheet.get_Range(worksheet.Cells[startRowIndex, 1], worksheet.Cells[startRowIndex, columnCount]).Font.Bold = true;
worksheet.get_Range(worksheet.Cells[startRowIndex, 1], worksheet.Cells[startRowIndex, columnCount]).Font.Size = 16;
worksheet.get_Range(worksheet.Cells[startRowIndex, 1], worksheet.Cells[startRowIndex, columnCount]).Merge();
// 第二行(列字段说明行)设为细实线内外边框绿色背景、字体加粗
int secondLineIndex = startRowIndex + 1;
worksheet.get_Range(worksheet.Cells[secondLineIndex, 1], worksheet.Cells[secondLineIndex, columnCount]).Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThin;
worksheet.get_Range(worksheet.Cells[secondLineIndex, 1], worksheet.Cells[secondLineIndex, columnCount]).Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThin;
worksheet.get_Range(worksheet.Cells[secondLineIndex, 1], worksheet.Cells[secondLineIndex, columnCount]).Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThin;
worksheet.get_Range(worksheet.Cells[secondLineIndex, 1], worksheet.Cells[secondLineIndex, columnCount]).Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThin;
worksheet.get_Range(worksheet.Cells[secondLineIndex, 1], worksheet.Cells[secondLineIndex, columnCount]).Borders[XlBordersIndex.xlInsideHorizontal].Weight = XlBorderWeight.xlThin;
worksheet.get_Range(worksheet.Cells[secondLineIndex, 1], worksheet.Cells[secondLineIndex, columnCount]).Borders[XlBordersIndex.xlInsideVertical].Weight = XlBorderWeight.xlThin;
worksheet.get_Range(worksheet.Cells[secondLineIndex, 1], worksheet.Cells[secondLineIndex, columnCount]).Interior.ColorIndex = 35;
worksheet.get_Range(worksheet.Cells[secondLineIndex, 1], worksheet.Cells[secondLineIndex, columnCount]).Font.Bold = true;
// 每个部分设置粗实线外边框
worksheet.get_Range(worksheet.Cells[startRowIndex, 1], worksheet.Cells[endRowIndex, columnCount]).Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick;
worksheet.get_Range(worksheet.Cells[startRowIndex, 1], worksheet.Cells[endRowIndex, columnCount]).Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;
worksheet.get_Range(worksheet.Cells[startRowIndex, 1], worksheet.Cells[endRowIndex, columnCount]).Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThick;
worksheet.get_Range(worksheet.Cells[startRowIndex, 1], worksheet.Cells[endRowIndex, columnCount]).Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;
}
/// <summary>
/// 美化Excel文件中指定工作簿,设置单元格自动列宽(使得列宽根据内容自动调整,每个单元格在一行中可显示完整内容)。然后对于因内容过多而通过自动列宽后超过指定最大列宽的单元格,强制缩小列宽到所允许的最大宽度。最后设置单元格内容自动换行,使得单元格自动扩大高度以显示所有内容
/// 注意执行本操作需在插入完所有数据后进行,否则插入数据前设置自动列宽无效
/// </summary>
public static void _BeautifyExcelWorksheet(Worksheet worksheet, int excelColumnMaxWidth, int lastColumnIndex)
{
// 设置表格中所有单元格均自动列宽
worksheet.Columns.AutoFit();
// 对于因内容过多而通过自动列宽后超过配置文件中配置的最大列宽的单元格,强制缩小列宽到所允许的最大宽度
for (int columnIndex = 1; columnIndex <= lastColumnIndex; ++columnIndex)
{
double columnWidth = Convert.ToDouble(worksheet.get_Range(Utils.GetExcelColumnName(columnIndex) + "1").EntireColumn.ColumnWidth);
if (columnWidth > excelColumnMaxWidth)
worksheet.get_Range(Utils.GetExcelColumnName(columnIndex) + "1").EntireColumn.ColumnWidth = excelColumnMaxWidth;
}
// 设置表格中所有单元格均自动换行
worksheet.Cells.WrapText = true;
}
}
/// <summary>
/// 用于记录一条合并翻译时发现的新版母表与翻译完的Excel文件中Key相同但主语言翻译不同信息
/// </summary>
public struct MergedResultDifferentDefaultLanguageInfo
{
// 母表中的行号
public int ExcelLineNum;
// 翻译完的Excel文件中的行号
public int TranslatedExcelLineNum;
// Key名
public string Key;
// 母表中的主语言译文
public string ExcelDefaultLanguageValue;
// 翻译完的Excel文件中的主语言译文
public string TranslatedExcelDefaultLanguageValue;
}
/// <summary>
/// 用于记录一条合并翻译时发现的新版母表与翻译完的Excel文件中Key不同信息
/// </summary>
public struct MergedResultDifferentKeyInfo
{
// 翻译完的Excel文件中的行号
public int TranslatedExcelLineNum;
// Key名
public string Key;
// 翻译完的Excel文件中的主语言译文
public string TranslatedExcelDefaultLanguageValue;
}
|
using System;
using System.Collections.Generic;
namespace SheMediaConverterClean.Infra.Data.Models
{
public partial class VArchivlagerort
{
public int ArchivId { get; set; }
public string Bezeichnung { get; set; }
public Guid? ArchivGuid { get; set; }
public int? HausId { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Maverick.Xrm.DI.CustomAttributes
{
public class DisplayAttribute : Attribute
{
internal DisplayAttribute(string displayName)
{
this.Name = displayName;
}
public string Name { get; private set; }
}
}
|
using Android.App;
using Android.Content;
using Android.OS;
using Android.Preferences;
using Android.Support.V7.App;
using Android.Views;
using Android.Webkit;
using Android.Widget;
using JKMAndroidApp.Common;
using JKMPCL.Model;
using JKMPCL.Services;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace JKMAndroidApp.activity
{
[Activity(Label = "PrivacyPolicyActivity", Theme = "@style/MyTheme", ScreenOrientation = Android.Content.PM.ScreenOrientation.Portrait, WindowSoftInputMode = SoftInput.AdjustResize)]
public class PrivacyPolicyActivity : AppCompatActivity
{
ProgressDialog progressDialog;
TextView tvTitleMsg;
Button btnAgree;
Button btnDisagee;
Login login;
Android.App.AlertDialog.Builder dialog;
Android.App.AlertDialog alert;
private ISharedPreferences sharedPreference;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
login = new Login();
sharedPreference = PreferenceManager.GetDefaultSharedPreferences(this);
// Create your application here
SetContentView(Resource.Layout.PrivacyPolicy);
//Find Control
UIReference();
btnDisagee.Click += BtnDisagee_Click;
btnAgree.Click += BtnAgree_Click;
}
// <summary>
/// Event Name : UIReference
/// Author : Sanket Prajapati
/// Creation Date : 15 Dec 2017
/// Purpose : For find all control
/// Revision :
/// </summary>
private void UIReference()
{
tvTitleMsg = FindViewById<TextView>(Resource.Id.tvTitleMsg);
btnAgree = FindViewById<Button>(Resource.Id.btnAgree);
btnDisagee = FindViewById<Button>(Resource.Id.btnDisagree);
WebView webview; webview = FindViewById<WebView>(Resource.Id.webView1);
webview.LoadUrl(StringResource.PrivacyPolicyUrl);
}
/// <summary>
/// Event Name : BtnDisagee_Click
/// Author : Sanket Prajapati
/// Creation Date : 2 Dec 2017
/// Purpose : Open deshboard screen
/// Revision :
/// </summary>
private async void BtnDisagee_Click(object sender, EventArgs e)
{
Intent intent = new Intent(this, typeof(ContactusActivity));
intent.PutExtra(StringResource.msgFromActvity, StringResource.msgPrivacyPolicyActivity);
StartActivity(intent);
}
/// <summary>
/// Event Name : BtnAgree_Click
/// Author : Sanket Prajapati
/// Creation Date : 2 Dec 2017
/// Purpose : Open contactus screen
/// Revision :
/// </summary>
private async void BtnAgree_Click(object sender, EventArgs e)
{
await CallPrivacyPolicyService(true);
}
/// <summary>
/// Method Name : CallPrivacyPolicyService
/// Author : Sanket Prajapati
/// Creation Date : 14 Dec 2017
/// Purpose : check agree or disagree & move next activity
/// Revision :
/// </summary>
private async Task CallPrivacyPolicyService(bool IsAgree)
{
string errorMessage = string.Empty;
try
{
progressDialog = UIHelper.SetProgressDailoge(this);
ServiceResponse serviceResponse = await login.PrivacyPolicyService(IsAgree);
if (serviceResponse != null)
{
if (string.IsNullOrEmpty(serviceResponse.Message))
{
await SetRedirectActivityAsync(serviceResponse, IsAgree);
}
else
{
errorMessage = serviceResponse.Message;
}
}
}
catch (Exception error)
{
errorMessage = error.Message;
}
finally
{
progressDialog.Dismiss();
if (!string.IsNullOrEmpty(errorMessage))
{
AlertMessage(errorMessage);
}
}
}
/// <summary>
/// Method Name : SetRedirectActivity
/// Author : Sanket Prajapati
/// Creation Date : 2 Dec 2017
/// Purpose :To Redirect Activity
/// Revision :
/// </summary>
private async Task SetRedirectActivityAsync(ServiceResponse serviceResponse,bool IsAgree)
{
if (serviceResponse.Status)
{
SetSharedPreference();
if (IsAgree)
{
await DTOConsumer.BindMoveDataAsync();
SetMoveActivity();
}
}
else
{
Intent intent = new Intent(this, typeof(ContactusActivity));
intent.PutExtra(StringResource.msgFromActvity, StringResource.msgPrivacyPolicyActivity);
StartActivity(intent);
}
}
///// <summary>
///// Event Name : BindgDataAsync
///// Author : Sanket Prajapati
///// Creation Date : 23 jan 2018
///// Purpose : Use for set condition ways flow
///// Revision :
///// </summary>
private void SetMoveActivity()
{
if (DTOConsumer.dtoEstimateData != null && DTOConsumer.dtoEstimateData.Count != 0)
{
if (DTOConsumer.dtoEstimateData.Count == 1)
{
UIHelper.SelectedMoveNumber = DTOConsumer.dtoEstimateData.FirstOrDefault().MoveNumber;
Intent intent = new Intent(this, typeof(ActivityEstimateViewPager));
StartActivity(intent);
}
else
{
UIHelper.SelectedMoveNumber = string.Empty;
Intent intent = new Intent(this, typeof(MultipleEstimatedActivity));
StartActivity(intent);
}
}
else
{
Intent intent = new Intent(this, typeof(MainActivity));
StartActivity(intent);
}
}
/// <summary>
/// Method Name : SetSharedPreference
/// Author : Sanket Prajapati
/// Creation Date : 23 jan 2018
/// Purpose : Set Customer Id in Shared perfence
/// Revision :
/// </summary>
private void SetSharedPreference()
{
string customerId;
customerId = sharedPreference.GetString(StringResource.keyCustomerID, string.Empty);
if (customerId != UtilityPCL.LoginCustomerData.CustomerId)
{
sharedPreference.Edit().PutString(StringResource.keyCustomerID, UtilityPCL.LoginCustomerData.CustomerId).Apply();
sharedPreference.Edit().PutString(StringResource.keyLastLoginDate, DateTime.Now.ToString()).Apply();
sharedPreference.Edit().PutBoolean(UtilityPCL.LoginCustomerData.CustomerId, true).Apply();
}
}
/// <summary>
/// Method Name : AlertMessage
/// Author : Sanket Prajapati
/// Creation Date : 14 Dec 2017
/// Purpose : Show Alert message
/// Revision :
/// </summary>
public void AlertMessage(String StrErrorMessage)
{
dialog = new Android.App.AlertDialog.Builder(new ContextThemeWrapper(this, Resource.Style.AlertDialogCustom));
alert = dialog.Create();
alert.SetMessage(StrErrorMessage);
alert.SetButton(StringResource.msgOK, (c, ev) =>
{
alert.Dispose();
});
alert.Show();
}
/// <summary>
/// Method Name : ApplyFont
/// Author : Sanket Prajapati
/// Creation Date : 14 Dec 2017
/// Purpose : Apply font all control
/// Revision :
/// </summary>
public void ApplyFont()
{
UIHelper.SetTextViewFont(tvTitleMsg, (int)UIHelper.LinotteFont.LinotteBold, Assets);
UIHelper.SetButtonFont(btnAgree, (int)UIHelper.LinotteFont.LinotteSemiBold, Assets);
UIHelper.SetButtonFont(btnDisagee, (int)UIHelper.LinotteFont.LinotteSemiBold, Assets);
}
/// <summary>
/// Event Name : OnBackPressed
/// Author : Sanket Prajapati
/// Creation Date : 2 Dec 2017
/// Purpose : backup button avoid Create password and customer password screen
/// Revision :
/// </summary>
public override void OnBackPressed()
{
dialog = new Android.App.AlertDialog.Builder(new ContextThemeWrapper(this, Resource.Style.AlertDialogCustom));
alert = dialog.Create();
alert.SetMessage(StringResource.msgBackButtonDisable);
alert.SetButton(StringResource.msgOK, (c, ev) =>
{
alert.Dispose();
});
alert.Show();
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace kolok2_2018_grpB
{
class VozniPark<T> where T : Vozilo, new()
{
private List<T> vozila;
private int maxBrojVozila;
private double dozvoljenaEmisija;
public VozniPark()
{
vozila = new List<T>();
maxBrojVozila = 0;
}
public double DozvoljenaEmisija
{
get { return dozvoljenaEmisija; }
set { dozvoljenaEmisija = value; }
}
public void dodajVozilo(T vozilo)
{
if (vozila.Count == maxBrojVozila) throw new Exception("Park je popunjen");
vozila.Add(vozilo);
}
public void upisiTxt(string path)
{
using(StreamWriter sw = new StreamWriter(new FileStream(path, FileMode.Create)))
{
sw.WriteLine(maxBrojVozila);
sw.WriteLine(dozvoljenaEmisija);
sw.WriteLine(vozila.Count); // trenutni broj vozila u parku
foreach(T vozilo in vozila)
{
vozilo.upisiTxt(sw);
}
}
}
public void citajTxt(string path)
{
using(StreamReader sr = new StreamReader(new FileStream(path, FileMode.Open)))
{
maxBrojVozila = int.Parse(sr.ReadLine());
dozvoljenaEmisija = double.Parse(sr.ReadLine());
int brojVozila = int.Parse(sr.ReadLine());
for(int i = 0; i < brojVozila; i++)
{
T vozilo = new T();
vozilo.citajTxt(sr);
vozila.Add(vozilo);
}
}
}
public void izbaciLosaVozila()
{
for(int i = 0; i < vozila.Count; i++)
{
if(vozila[i].RezultatTestaEmisije > DozvoljenaEmisija)
{
vozila.RemoveAt(i--);
}
}
}
public void sortirajVozila()
{
for(int i = 1; i < vozila.Count; i++)
{
int j;
T temp = vozila[i];
for(j = i; j > 0 && temp.boljiOd(vozila[j - 1]); j--)
{
vozila[j] = vozila[j - 1];
}
vozila[j] = temp;
}
}
}
}
|
using PMA.Store_Framework.Commands;
namespace PMA.Store_Domain.Categories.Commands
{
public class AddCategoryCommand : ICommand
{
public string Name { get; set; }
public long? ParentId { get; set; }
public string PhotoUrl { get; set; }
public int PhotoSize { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using Cinemachine;
using UnityEngine;
public class playerMovementController : MonoBehaviour
{
public Camera cam;
public float movementSpeed;
public float speedLimit;
public float lookSpeed;
private CharacterController cc;
private Vector3 forwardVector;
private Vector3 horizontalVector;
private float verticalMovement;
private float horizontalMovement;
private Vector3 moveDirection = Vector3.zero;
private playerAttackController attackScript;
private playerHealth healthScript;
private touchInputController inputScript;
private gameManager managerScript;
// Start is called before the first frame update
void Start()
{
cam = Camera.main;
cc = GetComponent<CharacterController>();
attackScript = GetComponent<playerAttackController>();
healthScript = GetComponent<playerHealth>();
inputScript = GameObject.FindGameObjectWithTag("touchInputController").GetComponent<touchInputController>();
managerScript = GameObject.FindGameObjectWithTag("gameManager").GetComponent<gameManager>();
CinemachineCore.GetInputAxis = AxisOverride;
}
public float AxisOverride(string axisName)
{
if (!managerScript.isPaused) {
if (Application.isMobilePlatform || managerScript.mobileTesting) {
if (axisName == "Mouse X") {
return inputScript.GetRotationY();
} else if (axisName == "Mouse Y") {
return inputScript.GetRotationX();
}
} else {
if (axisName == "Mouse X") {
return Input.GetAxis("Mouse X");
} else if (axisName == "Mouse Y") {
return Input.GetAxis("Mouse Y");
}
}
}
return 0;
}
// Update is called once per frame
void Update()
{
if (!managerScript.isPaused) {
// If you want to pause the player when attacking
// if (attackScript.isAttacking) {
// moveDirection = Vector3.zero;
// }
if (cc.isGrounded && !attackScript.isAttacking && healthScript.isAlive)
{
var camera = Camera.main;
var forward = cam.transform.forward;
var right = cam.transform.right;
forward.y = 0f;
right.y = 0f;
forward.Normalize();
right.Normalize();
if (Application.isMobilePlatform || managerScript.mobileTesting) {
verticalMovement = Mathf.Clamp(inputScript.GetVerticalMovement(), -speedLimit, speedLimit);
horizontalMovement = Mathf.Clamp(inputScript.GetHorizontalMovement(), -speedLimit, speedLimit);
} else {
verticalMovement = Input.GetAxis("Vertical") * speedLimit;
horizontalMovement = Input.GetAxis("Horizontal") * speedLimit;
}
forwardVector = forward * movementSpeed * verticalMovement;
horizontalVector = right * movementSpeed * horizontalMovement;
moveDirection = forwardVector + horizontalVector;
transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation (forward), lookSpeed);
// Just in case you wanna use jump
// if (Input.GetButton("Jump"))
// {
// moveDirection.y = 5;
// }
}
// Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below
// when the moveDirection is multiplied by deltaTime). This is because gravity should be applied
// as an acceleration (ms^-2)
moveDirection.y += Physics.gravity.y * Time.deltaTime;
// Move the controller
// Can't use simple move because for some reason gravity breaks and you don't fall
cc.Move(moveDirection * Time.deltaTime);
}
}
}
|
namespace GetLabourManager.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class ContributionSummary : DbMigration
{
public override void Up()
{
CreateStoredProcedure("ConstributionSummaryProc",
@"SELECT datepart(year,I.ProccessdOn) as Years,i.Invoice,
I.ProccessdOn,DATENAME(month,I.ProccessdOn)+'-'+Convert(varchar(5),datepart(year,I.ProccessdOn))
as MonthAndYear, (E.FirstName+' '+Isnull(e.MiddleName,'')+' '+e.LastName) as FullName,P.CasualCode,sum(p.[Basic]) as [Basic],
sum(p.Welfare) as Welfare ,sum(p.SSF) as SSF,sum(p.UnionDues) AS UnionDues,sum(p.PF) AS PF
FROM ProcessedSheetCasuals p
INNER JOIN ProcessedInvoices I
ON P.InvoiceCode=I.Invoice
inner join Employees E on E.Code=p.CasualCode
where p.SheetKind=1
group by datepart(year,I.ProccessdOn),i.Invoice,
I.ProccessdOn,DATENAME(month,I.ProccessdOn)+'-'+Convert(varchar(5),datepart(year,I.ProccessdOn))
, (E.FirstName+' '+Isnull(e.MiddleName,'')+' '+e.LastName),P.CasualCode
order by Years asc"
);
}
public override void Down()
{
DropStoredProcedure("ConstributionSummaryProc");
}
}
}
|
using System.Text;
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using System.Net.Http;
using System.Drawing;
using System.Collections.ObjectModel;
using System.Xml;
using System.ComponentModel;
using System.Reflection;
namespace LinnworksAPI
{
public class ConditionHeaderBasic
{
public Int32 pkConditionId;
public Int32? fkParentConditionId;
public Int32 fkRuleId;
public String ConditionName;
public Boolean Enabled;
public List<ConditionItemBasic> Conditions;
}
} |
namespace KRF.Core.Entities.ValueList
{
public class FleetStatus : ValueList
{
public int FleetStatusID { get; set; }
public string StatusName { get; set; }
public bool Active { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
public class PlayerController : MonoBehaviour
{
[Header("Move Positions")]
public float[] movePositionsX;
public float sideMoveTime;
[Header("Jump")]
public float jumpPeak;
public float jumpTime;
public float floorPos;
[Header("Down or Slide")]
public float downTime;
public float slideTime;
[Header("Game Controller")]
public GameObject GameController;
//other private variables
private bool isUp;
void Start()
{
floorPos = transform.position.y;
isUp = false;
Utils.isSliding = false;
}
public void movePlayerSide(int pos)
{
transform.DOMoveX(movePositionsX[pos], sideMoveTime).SetEase(Ease.OutCirc);
}
public void jump(){
if(!isUp){
isUp = true;
transform.DOMoveY(jumpPeak, jumpTime).SetEase(Ease.OutSine).OnComplete(()=>{
transform.DOMoveY(floorPos, jumpTime).SetEase(Ease.InSine).OnComplete(()=>{
isUp = false;
});
});
}
}
Coroutine slide_routine;
public void downOrSlide(){
if(isUp){
//remove the current jumping animation
transform.DOKill(true);
transform.DOMoveY(floorPos, downTime).OnComplete(()=>{
isUp = false;
});
}else if(!Utils.isSliding){
//Slide animation or slide down bool
if(slide_routine!=null){
StopCoroutine(slide_routine);
}
slide_routine = StartCoroutine(slideRouting());
}
}
IEnumerator slideRouting(){
Utils.isSliding = true;
yield return new WaitForSeconds(slideTime);
Utils.isSliding = false;
yield return null;
}
//COLLISIONS
void OnTriggerEnter(Collider other){
if(other.tag == Utils.ITEM_TAG){
//pass collider object to game comtroller
GameController.GetComponent<GameplayController>().hitItems(other.gameObject);
}else if (other.tag == Utils.POWERUP_TAG){
GameController.GetComponent<GameplayController>().hitPowerUp(other.gameObject);
}
}
}
|
//--------------------------------
// Skinned Metaball Builder
// Copyright © 2015 JunkGames
//--------------------------------
using UnityEngine;
using System.Collections;
public class SphereGun : Weapon
{
public ParticleSystem hitPS;
protected override void DoShoot(DungeonControl2 dungeon, Vector3 from, Vector3 to)
{
weaponBody.transform.position = to;
dungeon.Attack(brush);
Instantiate(hitPS.gameObject, to, Quaternion.identity);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Requestrr.WebApi.RequestrrBot.Notifications.Movies
{
public class MovieNotificationsRepository
{
private class Notification
{
public string UserId { get; }
public int MovieId { get; }
public Notification(string userId, int movieId)
{
UserId = userId;
MovieId = movieId;
}
public override bool Equals(object obj)
{
return obj is Notification notification &&
UserId == notification.UserId &&
MovieId == notification.MovieId;
}
public override int GetHashCode()
{
return HashCode.Combine(UserId, MovieId);
}
}
private HashSet<Notification> _notifications = new HashSet<Notification>();
private object _lock = new object();
public MovieNotificationsRepository()
{
foreach (var notif in NotificationsFile.Read().Movies)
{
foreach (var movieId in notif.MovieIds)
{
_notifications.Add(new Notification(notif.UserId.ToString(), (int)movieId));
}
}
}
public void AddNotification(string userId, int movieId)
{
lock (_lock)
{
if (_notifications.Add(new Notification(userId, movieId)))
{
NotificationsFile.WriteMovies(_notifications.GroupBy(x => x.UserId).ToDictionary(x => x.Key, x => x.Select(n => n.MovieId).ToArray()));
}
}
}
public void RemoveNotification(string userId, int movieId)
{
lock (_lock)
{
if (_notifications.Remove(new Notification(userId, movieId)))
{
NotificationsFile.WriteMovies(_notifications.GroupBy(x => x.UserId).ToDictionary(x => x.Key, x => x.Select(n => n.MovieId).ToArray()));
}
}
}
public Dictionary<int, HashSet<string>> GetAllMovieNotifications()
{
lock (_lock)
{
return _notifications
.GroupBy(x => x.MovieId)
.ToDictionary(x => x.Key, x => new HashSet<string>(x.Select(r => r.UserId)));
}
}
public bool HasNotification(string userId, int movieId)
{
var hasRequest = false;
lock (_lock)
{
hasRequest = _notifications.Contains(new Notification(userId, movieId));
}
return hasRequest;
}
}
} |
using System.Collections.Generic;
using System.Linq;
namespace W3ChampionsStatisticService.Matches
{
public class Team
{
public List<PlayerOverviewMatches> Players { get; set; } = new List<PlayerOverviewMatches>();
public bool Won => Players?.Any(x => x.Won) ?? false;
}
} |
using System;
using System.Collections.Generic;
namespace Templates.Framework
{
public enum Privacy
{
Public,
Protected,
Private
}
public interface IClass : IComponent
{
IEnumerable<IConstructor> Constructors { get; }
IEnumerable<IInterface> Implements { get; }
IClass InheritsFrom { get; set; }
bool IsAbstract { get; set; }
bool IsPartial { get; set; }
string Name { get; }
INamespace Namespace { get; }
IEnumerable<IProperty> Properties { get; }
IEnumerable<IRegion> Regions { get; }
string Signature { get; }
string Summary { get; set; }
IEnumerable<ITag> Tags { get; }
string Type { get; }
void Add(IConstructor IConstructor);
void Add(IFunction codeFunction);
void Add(IProperty property);
void Add(IVariable variable);
void Add(IVariable variable, bool canGet, bool canSet);
void Add(bool isNew, IVariable variable, bool canGet, bool canSet);
void Inherits(IClass classToInherit);
void NewRegion();
void NewRegion(string name);
void WillImplement(IInterface interfaceToImplement);
void Tag(string tag);
}
}
|
using Dao.Seguridad;
using Dao.Mercadeo;
using Ninject.Modules;
using Dao.Solicitud;
namespace BLO
{
public class NinjectBlo : NinjectModule
{
public override void Load()
{
//Seguridad
Bind<IParametroDao>().To<ParametroDao>();
Bind<IUsuarioDao>().To<UsuarioDao>();
Bind<IOpcionDao>().To<OpcionDao>();
Bind<IEmpresaDao>().To<EmpresaDao>();
Bind<ISucursalDao>().To<SucursalDao>();
Bind<IPeriodoDao>().To<PeriodoDao>();
Bind<IAccesoUsuarioDao>().To<AccesoUsuarioDao>();
//Mercadeo
Bind<IPreciosDetDao>().To<PreciosDetDao>();
Bind<IExistenciasDao>().To<ExistenciasDao>();
Bind<IClaseDao>().To<ClaseDao>();
Bind<IMarcaDao>().To<MarcaDao>();
Bind<IProductosDao>().To<ProductosDao>();
Bind<ICampaniaDao>().To<CampaniaDao>();
Bind<ICampaniaColorProductoDao>().To<CampaniaColorProductoDao>();
Bind<ICampaniaProdRegaliaDao>().To<CampaniaProdRegaliaDao>();
Bind<ICampaniaProductoDao>().To<CampaniaProductoDao>();
Bind<ICampaniaSucursalDao>().To<CampaniaSucursalDao>();
Bind<ITipoVentaDao>().To<TipoVentaDao>();
Bind<IEstadoProductoDao>().To<EstadoProductoDao>();
Bind<INivelPrecioDao>().To<NivelPrecioDao>();
Bind<IColorDao>().To<ColorDao>();
Bind<ICampaniaProdPartesDao>().To<CampaniaProdPartesDao>();
Bind<IOportunidadDao>().To<OportunidadDao>();
Bind<ITipoMedioDao>().To<TipoMedioDao>();
Bind<IMedioContactoDao>().To<MedioContactoDao>();
Bind<IEmpleadoDao>().To<EmpleadoDao>();
//Solicitud
Bind<IContactoDao>().To<ContactoDao>();
Bind<ITipoViviendaDao>().To<TipoViviendaDao>();
Bind<ICiudadDao>().To<CiudadDao>();
Bind<INivelEducacionDao>().To<NivelEducacionDao>();
Bind<IProfesionDao>().To<ProfesionDao>();
Bind<IEstadoCivilDao>().To<EstadoCivilDao>();
Bind<IContactoDireccionDao>().To<ContactoDireccionDao>();
Bind<IContactoInformacionEcoDao>().To<ContactoInformacionEcoDao>();
Bind<IContactoReferenciaDao>().To<ContactoReferenciaDao>();
Bind<ITipoReferenciaDao>().To<TipoReferenciaDao>();
Bind<ITipoPropiedadDao>().To<TipoPropiedadDao>();
Bind<IDepartamentoDao>().To<DepartamentoDao>();
Bind<ICondicionPagoDao>().To<CondicionPagoDao>();
Bind<ITasaInteresDao>().To<TasaInteresDao>();
Bind<IContactoArchivosDao>().To<ContactoArchivosDao>();
Bind<ITipoDireccionDao>().To<TipoDireccionDao>();
}
}
} |
using Paint.Model.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Paint.Data.Interface
{
public interface IManufacturerRepository
{
IEnumerable<Manufacturer> GetAll();
}
}
|
using System.Collections.Generic;
using UnityEngine;
namespace ObjectPooling
{
public static class PoolManager
{
private static readonly int _DEFAULT_POOL_SIZE = 10;
private static Dictionary<int, List<PoolableObject>> _Pools = new Dictionary<int, List<PoolableObject>>();
private static Dictionary<int, int> _Indexes = new Dictionary<int, int>();
private static PoolableObject AddObjectToPool(PoolableObject prefab, int poolId)
{
var clone = GameObject.Instantiate(prefab);
clone.gameObject.SetActive(false);
_Pools[poolId].Add(clone);
return clone;
}
public static void CreatePool(PoolableObject prefab, int poolSize)
{
var poolId = prefab.GetInstanceID();
_Pools[poolId] = new List<PoolableObject>(poolSize);
_Indexes[poolId] = -1;
for (int i = 0; i < poolSize; i++)
{
AddObjectToPool(prefab, poolId);
}
}
public static PoolableObject GetNext(PoolableObject prefab, Vector3 pos, Quaternion rot, bool active = true)
{
var clone = GetNext(prefab);
clone.transform.position = pos;
clone.transform.rotation = rot;
clone.gameObject.SetActive(active);
return clone;
}
public static PoolableObject GetNext(PoolableObject prefab)
{
var poolId = prefab.GetInstanceID();
if(_Pools.ContainsKey(poolId) == false)
{
CreatePool(prefab, _DEFAULT_POOL_SIZE);
}
var currentPoolableObjectsList = _Pools[poolId];
for (int i = 0; i < currentPoolableObjectsList.Count; i++)
{
_Indexes[poolId] = (_Indexes[poolId] + 1) % _Pools[poolId].Count;
var checkIndex = _Indexes[poolId];
if(currentPoolableObjectsList[checkIndex].gameObject.activeInHierarchy == false)
{
return currentPoolableObjectsList[checkIndex];
}
}
return AddObjectToPool(prefab, poolId);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.