text stringlengths 13 6.01M |
|---|
using serializacja;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using kolekcje;
using System;
using System.Collections.Generic;
namespace SerializacjaTests
{
[TestClass()]
public class BinConverterTests
{
[TestMethod()]
public void SerializujTest()
{
new BinConverter().Serializuj(new Gra("Pokemon3", "CD Projekt", 2008, 100, 10), "gra3");
new BinConverter().Serializuj(new Gracz("Janek", "Krecina"), "gracz1");
new BinConverter().Serializuj(new Zakup(new Gracz("Janek", "Kowalski"), new Gra("Pokemon", "CD Projekt", 2008, 100, 10)), "zakup1");
Kolekcja k = new Kolekcja();
k.WypelnijZakupy();
new BinConverter().Serializuj(k._gracze, "gracze1");
new BinConverter().Serializuj(k._zakupy, "zakupy1");
new BinConverter().Serializuj(k, "kolekcja1");
}
[TestMethod()]
public void DeSerializujTest()
{
Gra g = new BinConverter().DeSerializuj<Gra>("gra3");
Console.WriteLine(g.ToString());
Gracz gr = new BinConverter().DeSerializuj<Gracz>("gracz1");
Console.WriteLine(gr.ToString());
Zakup zak = new BinConverter().DeSerializuj<Zakup>("zakup1");
Console.WriteLine(zak.ToString());
Kolekcja k = new BinConverter().DeSerializuj<Kolekcja>("kolekcja1");
Console.WriteLine(k.ToString());
var gracze = new BinConverter().DeSerializuj<List<Gracz>>("gracze1");
Console.WriteLine("Lista graczy:");
foreach (var gracz in gracze)
{
Console.WriteLine(gracz.ToString());
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace NewsConcentratorSystem.Models
{
public class Settings
{
[Key]
public int id { get; set; }
[Display(Name = "متن شروع")]
public string StartDescription { get; set; }
[Display(Name = "متن پایان")]
public string EndDescription { get; set; }
}
}
|
using System;
namespace OCP.LDAP
{
/**
* Interface IDeletionFlagSupport
*
* @package OCP\LDAP
* @since 11.0.0
*/
public interface IDeletionFlagSupport
{
/**
* Flag record for deletion.
* @param string uid user id
* @since 11.0.0
*/
void flagRecord(string uid);
/**
* Unflag record for deletion.
* @param string uid user id
* @since 11.0.0
*/
void unflagRecord(string uid);
}
}
|
using System.Data;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using CRVCManager.DataModels;
using CRVCManager.Utilities;
namespace CRVCManager
{
/// <summary>
/// Interaction logic for PrescriptionsListWindow.xaml
/// </summary>
public partial class PrescriptionsListWindow : Window
{
private readonly Client _currentClient;
private readonly Consult _currentConsult;
private readonly User _currentUser;
private readonly int _windowMode;
private Prescription _selectedPrescription;
public PrescriptionsListWindow(User currentUser, Consult currentConsult)
{
InitializeComponent();
_currentUser = currentUser;
_currentConsult = currentConsult;
NewButton.Visibility = Visibility.Visible;
// Get prescriptions by consult
_windowMode = 1;
SetupUi();
}
public PrescriptionsListWindow(User currentUser, Client currentClient)
{
InitializeComponent();
_currentUser = currentUser;
_currentClient = currentClient;
NewButton.Visibility = Visibility.Collapsed;
// Get prescriptions by client
_windowMode = 2;
SetupUi();
}
public PrescriptionsListWindow(User currentUser)
{
InitializeComponent();
_currentUser = currentUser;
NewButton.Visibility = Visibility.Collapsed;
// List all prescriptions
_windowMode = 3;
SetupUi();
}
private void SetupUi()
{
Task.Factory.StartNew(LoadPrescriptionsDataGrid);
}
private async void LoadPrescriptionsDataGrid()
{
DataTable d = null;
switch (_windowMode)
{
case 1:
d = await Prescription.GetAllByConsultFormattedAsync(_currentConsult);
break;
case 2:
d = await Prescription.GetAllByClientFormattedAsync(_currentClient);
break;
case 3:
d = await Prescription.GetAllFormattedAsync();
break;
}
Dispatcher.Invoke(() =>
{
PrescriptionsDataGrid.DataContext = d;
PrescriptionsDataGrid.HideColumn();
PrescriptionsDataGrid.SelectedIndex = -1;
});
}
private void NewButton_OnClick(object sender, RoutedEventArgs e)
{
var prescriptionWindow = new PrescriptionWindow(_currentUser, _currentConsult);
prescriptionWindow.ShowDialog();
SetupUi();
}
private void PrescriptionsDataGrid_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (!PrescriptionsDataGrid.IsEnabled || _selectedPrescription == null)
{
return;
}
var prescriptionWindow = new PrescriptionWindow(_currentUser, _selectedPrescription);
prescriptionWindow.ShowDialog();
SetupUi();
}
private void PrescriptionsDataGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
Prescription selectedPrescription = null;
if (PrescriptionsDataGrid.SelectedIndex != -1)
{
if (PrescriptionsDataGrid.SelectedItem is DataRowView prescriptionRowItem)
{
var prescriptionFromDataGrid = new Prescription(prescriptionRowItem.Row.ItemArray[0].ToString().ParseGuid());
if (prescriptionFromDataGrid.Exists)
{
selectedPrescription = prescriptionFromDataGrid;
}
}
}
_selectedPrescription = selectedPrescription;
}
private void PrescriptionsDataGrid_OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
//Set properties on the columns during auto-generation
switch (e.Column.Header.ToString())
{
case "ID":
e.Column.Visibility = Visibility.Collapsed;
break;
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
//Written by Mason Eastman
public class MainMenuController : MonoBehaviour
{
private SpriteRenderer startButton;
private SpriteRenderer controlsButton;
private SpriteRenderer quitButton;
public Sprite startMain;
public Sprite controlMain;
public Sprite quitMain;
public Sprite startAlt;
public Sprite controlAlt;
public Sprite quitAlt;
private int selectedIndex;
private bool onControls;
public Camera myCamera;
// Start is called before the first frame update
void Start()
{
startButton = GameObject.Find("StartButton").GetComponent<SpriteRenderer>();
controlsButton = GameObject.Find("ControlsButton").GetComponent<SpriteRenderer>();
quitButton = GameObject.Find("QuitButton").GetComponent<SpriteRenderer>();
selectedIndex = 0;
onControls = false;
}
// Update is called once per frame
void Update()
{
//Determines which button is "selected" based on the directional input
//accounts for wrapping
//moving down the menu options
if((Input.GetKeyDown(KeyCode.Joystick1Button5) || Input.GetKeyDown(KeyCode.Joystick2Button5)) || Input.GetKeyDown(KeyCode.RightArrow))
{
selectedIndex++;
if(selectedIndex == 3)
{
selectedIndex = 0;
}
}
//moving up the menu options
else if((Input.GetKeyDown(KeyCode.JoystickButton4) || Input.GetKeyDown(KeyCode.Joystick2Button4)) || Input.GetKeyDown(KeyCode.LeftArrow))
{
selectedIndex--;
if(selectedIndex == -1)
{
selectedIndex = 2;
}
}
//update the sprites correctly based on which one is "selected"
//start button selected
if(selectedIndex == 0)
{
startButton.sprite = startAlt;
controlsButton.sprite = controlMain;
quitButton.sprite = quitMain;
}
//controls button selected
else if(selectedIndex == 1)
{
startButton.sprite = startMain;
controlsButton.sprite = controlAlt;
quitButton.sprite = quitMain;
}
//quit button selected
else
{
startButton.sprite = startMain;
controlsButton.sprite = controlMain;
quitButton.sprite = quitAlt;
}
//If player hits return or presses "A" button on selected option
if ((Input.GetKeyDown(KeyCode.Joystick1Button0) || Input.GetKeyDown(KeyCode.Joystick2Button0)) || Input.GetKeyDown(KeyCode.Return))
{
//on start
if (selectedIndex == 0)
{
//replace with first level scene
SceneManager.LoadScene("Level 1");
}
//on controls
//it is not a separate scene, but a screen displaced from the main menu screen, outside menu camera's bounds
else if (selectedIndex == 1 && !onControls)
{
myCamera.transform.position = new Vector3(myCamera.transform.position.x, myCamera.transform.position.y + 1000, myCamera.transform.position.z);
onControls = true;
}
//on quit
else
{
Application.Quit();
}
}
//if player is on controls screen and presses escape or "B" button, return them to main menu screen
if(((Input.GetKeyDown(KeyCode.Joystick1Button1) || Input.GetKeyDown(KeyCode.Joystick2Button1)) || Input.GetKeyDown(KeyCode.Escape)) && selectedIndex == 1)
{
myCamera.transform.position = new Vector3(myCamera.transform.position.x, myCamera.transform.position.y - 1000, myCamera.transform.position.z);
onControls = false;
}
}
}
|
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MyAppBack.Data.Repos.BasketRepository;
using MyAppBack.Dtos;
using MyAppBack.Models;
namespace MyAppBack.Controllers
{
public class BasketController : BaseApiController
{
private readonly IBasketRepository _basketRepository;
private readonly IMapper _mapper;
public BasketController(IBasketRepository basketRepository, IMapper mapper)
{
_mapper = mapper;
_basketRepository = basketRepository;
}
[HttpGet]
public async Task<ActionResult<Basket>> GetBasketById(string id)
{
var basket = await _basketRepository.GetBasketAsync(id);
return Ok(basket ?? new Basket(id));
}
[HttpPost]
public async Task<ActionResult<Basket>> UpdateBasket(BasketDto basketDto)
{
var basket = _mapper.Map<BasketDto, Basket>(basketDto);
var updatedBasket = await _basketRepository.UpdateBasketAsync(basket);
return Ok(updatedBasket);
}
[HttpDelete]
[AllowAnonymous]
public async Task DeleteBasketAsync(string id)
{
await _basketRepository.DeleteBasketAsync(id);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Master.Contract;
using Master.BusinessFactory;
namespace LogiCon.Areas.Master.Controllers
{
//
[RoutePrefix("api/master/holdstatus")]
public class HoldStatusController : ApiController
{
[Route("list/{skip?},{take?}"), HttpGet]
public IHttpActionResult List(Int64? skip = null, Int64? take = null)
{
try
{
var list = new HoldStatusBO().GetPageView(skip.Value).ToList();
var totalItems = new HoldStatusBO().GetRecordCount();
return Ok(new {
holdStatusList = list,
totalItems = totalItems
});
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
[Route("{code}"), HttpGet]
public IHttpActionResult GetHoldStatus(string code)
{
try
{
var holdStatus = new HoldStatusBO().GetHoldStatus(new HoldStatus { Code = code });
return Ok(holdStatus);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
[Route("{code}"), HttpDelete]
public IHttpActionResult DeleteIMOCode(string code)
{
try
{
var result = new HoldStatusBO().DeleteHoldStatus(new HoldStatus { Code = code });
return Ok(result ? UTILITY.SUCCESSMSG : UTILITY.FAILEDMSG);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
[Route("save"), HttpPost]
public IHttpActionResult SaveHoldStatus(HoldStatus holdStatus)
{
try
{
holdStatus.CreatedBy = UTILITY.DEFAULTUSER;
holdStatus.ModifiedBy = UTILITY.DEFAULTUSER;
holdStatus.CreatedOn = DateTime.Now;
holdStatus.ModifiedOn = DateTime.Now;
var result = new HoldStatusBO().SaveHoldStatus(holdStatus);
return Ok(result ? UTILITY.SUCCESSMSG : UTILITY.FAILEDMSG);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
}
}
|
//------------------------------------------------------------------------------
// 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.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Web;
using NopSolutions.NopCommerce.BusinessLogic.Configuration.Settings;
using NopSolutions.NopCommerce.BusinessLogic.Content.Blog;
using NopSolutions.NopCommerce.BusinessLogic.Content.Forums;
using NopSolutions.NopCommerce.BusinessLogic.Content.NewsManagement;
using NopSolutions.NopCommerce.BusinessLogic.CustomerManagement;
using NopSolutions.NopCommerce.BusinessLogic.Directory;
using NopSolutions.NopCommerce.BusinessLogic.Localization;
using NopSolutions.NopCommerce.BusinessLogic.Orders;
using NopSolutions.NopCommerce.BusinessLogic.Products;
using NopSolutions.NopCommerce.BusinessLogic.Profile;
using NopSolutions.NopCommerce.BusinessLogic.SEO;
using NopSolutions.NopCommerce.BusinessLogic.Shipping;
using NopSolutions.NopCommerce.BusinessLogic.Tax;
using NopSolutions.NopCommerce.Common.Utils.Html;
using NopSolutions.NopCommerce.DataAccess;
using NopSolutions.NopCommerce.DataAccess.Messages;
namespace NopSolutions.NopCommerce.BusinessLogic.Messages
{
/// <summary>
/// Message manager
/// </summary>
public partial class MessageManager
{
#region Utilities
private static MessageTemplateCollection DBMapping(DBMessageTemplateCollection dbCollection)
{
if (dbCollection == null)
return null;
MessageTemplateCollection collection = new MessageTemplateCollection();
foreach (DBMessageTemplate dbItem in dbCollection)
{
MessageTemplate item = DBMapping(dbItem);
collection.Add(item);
}
return collection;
}
private static MessageTemplate DBMapping(DBMessageTemplate dbItem)
{
if (dbItem == null)
return null;
MessageTemplate item = new MessageTemplate();
item.MessageTemplateID = dbItem.MessageTemplateID;
item.Name = dbItem.Name;
return item;
}
private static LocalizedMessageTemplateCollection DBMapping(DBLocalizedMessageTemplateCollection dbCollection)
{
if (dbCollection == null)
return null;
LocalizedMessageTemplateCollection collection = new LocalizedMessageTemplateCollection();
foreach (DBLocalizedMessageTemplate dbItem in dbCollection)
{
LocalizedMessageTemplate item = DBMapping(dbItem);
collection.Add(item);
}
return collection;
}
private static LocalizedMessageTemplate DBMapping(DBLocalizedMessageTemplate dbItem)
{
if (dbItem == null)
return null;
LocalizedMessageTemplate item = new LocalizedMessageTemplate();
item.MessageTemplateLocalizedID = dbItem.MessageTemplateLocalizedID;
item.MessageTemplateID = dbItem.MessageTemplateID;
item.LanguageID = dbItem.LanguageID;
item.Name = dbItem.Name;
item.Subject = dbItem.Subject;
item.Body = dbItem.Body;
return item;
}
private static QueuedEmailCollection DBMapping(DBQueuedEmailCollection dbCollection)
{
if (dbCollection == null)
return null;
QueuedEmailCollection collection = new QueuedEmailCollection();
foreach (DBQueuedEmail dbItem in dbCollection)
{
QueuedEmail item = DBMapping(dbItem);
collection.Add(item);
}
return collection;
}
private static QueuedEmail DBMapping(DBQueuedEmail dbItem)
{
if (dbItem == null)
return null;
QueuedEmail item = new QueuedEmail();
item.QueuedEmailID = dbItem.QueuedEmailID;
item.Priority = dbItem.Priority;
item.From = dbItem.From;
item.FromName = dbItem.FromName;
item.To = dbItem.To;
item.ToName = dbItem.ToName;
item.Cc = dbItem.Cc;
item.Bcc = dbItem.Bcc;
item.Subject = dbItem.Subject;
item.Body = dbItem.Body;
item.CreatedOn = dbItem.CreatedOn;
item.SendTries = dbItem.SendTries;
item.SentOn = dbItem.SentOn;
return item;
}
/// <summary>
/// Convert a collection to a HTML table
/// </summary>
/// <param name="table">Order product variant collection</param>
/// <param name="LanguageID">Language identifier</param>
/// <returns>HTML table of products</returns>
private static string ProductListToHtmlTable(Order order, int LanguageID)
{
string result = string.Empty;
StringBuilder sb = new StringBuilder();
sb.AppendLine("<table class=\"table\" border=\"0\" style=\"border:1px solid grey;padding:2px;border-collapse:collapse;\"><thead><tr>");
sb.AppendLine("<th class=\"header\" style=\"text-align:left;\">" + LocalizationManager.GetLocaleResourceString("Order.ProductsGrid.Name", LanguageID) + "</th>");
sb.AppendLine("<th class=\"header\" style=\"text-align:right;\">" + LocalizationManager.GetLocaleResourceString("Order.ProductsGrid.Price", LanguageID) + "</th>");
sb.AppendLine("<th class=\"header\" style=\"text-align:right;\">" + LocalizationManager.GetLocaleResourceString("Order.ProductsGrid.Quantity", LanguageID) + "</th>");
sb.AppendLine("<th class=\"header\" style=\"text-align:right;\">" + LocalizationManager.GetLocaleResourceString("Order.ProductsGrid.Total", LanguageID) + "</th>");
sb.AppendLine("</tr></thead><tbody>");
Language language = LanguageManager.GetLanguageByID(LanguageID);
if (language == null)
language = NopContext.Current.WorkingLanguage;
#region Products
OrderProductVariantCollection table = order.OrderProductVariants;
for (int i = 0; i <= table.Count - 1; i++)
{
sb.AppendLine("<tr>");
sb.AppendLine("<td class=\"row\">" + HttpUtility.HtmlEncode(table[i].ProductVariant.FullProductName));
if (!String.IsNullOrEmpty(table[i].AttributeDescription))
{
sb.AppendLine("<br />");
sb.AppendLine(table[i].AttributeDescription);
}
sb.AppendLine("</td>");
string unitPriceStr = string.Empty;
switch (order.CustomerTaxDisplayType)
{
case TaxDisplayTypeEnum.ExcludingTax:
unitPriceStr = PriceHelper.FormatPrice(table[i].UnitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, false);
break;
case TaxDisplayTypeEnum.IncludingTax:
unitPriceStr = PriceHelper.FormatPrice(table[i].UnitPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, true);
break;
}
sb.AppendLine("<td class=\"row\">" + unitPriceStr + "</td>");
sb.AppendLine("<td class=\"row\">" + table[i].Quantity + "</td>");
string priceStr = string.Empty;
switch (order.CustomerTaxDisplayType)
{
case TaxDisplayTypeEnum.ExcludingTax:
priceStr = PriceHelper.FormatPrice(table[i].PriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, false);
break;
case TaxDisplayTypeEnum.IncludingTax:
priceStr = PriceHelper.FormatPrice(table[i].PriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, true);
break;
}
sb.AppendLine("<td class=\"row\">" + priceStr + "</td>");
sb.AppendLine("</tr>");
}
#endregion
#region Totals
string CusSubTotal = string.Empty;
string CusShipTotal = string.Empty;
string CusPaymentMethodAdditionalFee = string.Empty;
string CusTaxTotal = string.Empty;
string CusTotal = string.Empty;
//subtotal, shipping, payment method fee
switch (order.CustomerTaxDisplayType)
{
case TaxDisplayTypeEnum.ExcludingTax:
{
CusSubTotal = PriceHelper.FormatPrice(order.OrderSubtotalExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, false);
CusShipTotal = PriceHelper.FormatShippingPrice(order.OrderShippingExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, false);
CusPaymentMethodAdditionalFee = PriceHelper.FormatPaymentMethodAdditionalFee(order.PaymentMethodAdditionalFeeExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, false);
}
break;
case TaxDisplayTypeEnum.IncludingTax:
{
CusSubTotal = PriceHelper.FormatPrice(order.OrderSubtotalInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, true);
CusShipTotal = PriceHelper.FormatShippingPrice(order.OrderShippingInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, true);
CusPaymentMethodAdditionalFee = PriceHelper.FormatPaymentMethodAdditionalFee(order.PaymentMethodAdditionalFeeInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, true);
}
break;
}
//shipping
bool dislayShipping = order.ShippingStatus != ShippingStatusEnum.ShippingNotRequired;
bool displayPaymentMethodFee = true;
if (order.PaymentMethodAdditionalFeeExclTaxInCustomerCurrency == decimal.Zero)
{
displayPaymentMethodFee = false;
}
//tax
bool displayTax = true;
if (TaxManager.HideTaxInOrderSummary && order.CustomerTaxDisplayType == TaxDisplayTypeEnum.IncludingTax)
{
displayTax = false;
}
else
{
if (order.OrderTax == 0 && TaxManager.HideZeroTax)
{
displayTax = false;
}
else
{
string taxStr = PriceHelper.FormatPrice(order.OrderTaxInCustomerCurrency, true, order.CustomerCurrencyCode, false);
CusTaxTotal = taxStr;
}
}
//total
CusTotal = PriceHelper.FormatPrice(order.OrderTotalInCustomerCurrency, true, order.CustomerCurrencyCode, false);
sb.AppendLine("<tr><td style=\"text-align:right;\" colspan=\"2\"></td><td colspan=\"2\">");
sb.AppendLine("<table class=\"table\" style=\"border:0px solid grey;padding:2px;border-collapse:collapse;\">");
sb.AppendLine("<tr><td style=\"text-align:right;\" colspan=\"3\"><strong>" + LocalizationManager.GetLocaleResourceString("Order.Sub-Total", LanguageID) + "</strong></td> <td style=\"text-align:right;\"><strong>" + CusSubTotal + "</strong></td></tr>");
if (dislayShipping)
{
sb.AppendLine("<tr><td style=\"text-align:right;\" colspan=\"3\"><strong>" + LocalizationManager.GetLocaleResourceString("Order.Shipping", LanguageID) + "</strong></td> <td style=\"text-align:right;\"><strong>" + CusShipTotal + "</strong></td></tr>");
}
if (displayPaymentMethodFee)
{
string paymentMethodFeeTitle = LocalizationManager.GetLocaleResourceString("Order.PaymentMethodAdditionalFee", LanguageID);
sb.AppendLine("<tr><td style=\"text-align:right;\" colspan=\"3\"><strong>" + paymentMethodFeeTitle + "</strong></td> <td style=\"text-align:right;\"><strong>" + CusPaymentMethodAdditionalFee + "</strong></td></tr>");
}
if (displayTax)
{
sb.AppendLine("<tr><td style=\"text-align:right;\" colspan=\"3\"><strong>" + LocalizationManager.GetLocaleResourceString("Order.Tax", LanguageID) + "</strong></td> <td style=\"text-align:right;\"><strong>" + CusTaxTotal + "</strong></td></tr>");
}
sb.AppendLine("<tr><td style=\"text-align:right;\" colspan=\"3\"><strong>" + LocalizationManager.GetLocaleResourceString("Order.OrderTotal", LanguageID) + "</strong></td> <td style=\"text-align:right;\"><strong>" + CusTotal + "</strong></td></tr>");
sb.AppendLine("</table>");
sb.AppendLine("</td></tr>");
#endregion
sb.AppendLine("</tbody></table>");
result = sb.ToString();
return result;
}
#endregion
#region Methods
/// <summary>
/// Gets a message template by template identifier
/// </summary>
/// <param name="MessageTemplateID">Message template identifier</param>
/// <returns>Message template</returns>
public static MessageTemplate GetMessageTemplateByID(int MessageTemplateID)
{
if (MessageTemplateID == 0)
return null;
DBMessageTemplate dbItem = DBProviderManager<DBMessageTemplateProvider>.Provider.GetMessageTemplateByID(MessageTemplateID);
MessageTemplate messageTemplate = DBMapping(dbItem);
return messageTemplate;
}
/// <summary>
/// Gets all message templates
/// </summary>
/// <returns>Message template collection</returns>
public static MessageTemplateCollection GetAllMessageTemplates()
{
DBMessageTemplateCollection dbCollection = DBProviderManager<DBMessageTemplateProvider>.Provider.GetAllMessageTemplates();
MessageTemplateCollection collection = DBMapping(dbCollection);
return collection;
}
/// <summary>
/// Gets a localized message template by identifier
/// </summary>
/// <param name="LocalizedMessageTemplateID">Localized message template identifier</param>
/// <returns>Localized message template</returns>
public static LocalizedMessageTemplate GetLocalizedMessageTemplateByID(int LocalizedMessageTemplateID)
{
if (LocalizedMessageTemplateID == 0)
return null;
DBLocalizedMessageTemplate dbItem = DBProviderManager<DBMessageTemplateProvider>.Provider.GetLocalizedMessageTemplateByID(LocalizedMessageTemplateID);
LocalizedMessageTemplate localizedMessageTemplate = DBMapping(dbItem);
return localizedMessageTemplate;
}
/// <summary>
/// Gets a localized message template by name and language identifier
/// </summary>
/// <param name="Name">Message template name</param>
/// <param name="LanguageID">Language identifier</param>
/// <returns>Localized message template</returns>
public static LocalizedMessageTemplate GetLocalizedMessageTemplate(string Name, int LanguageID)
{
DBLocalizedMessageTemplate dbItem = DBProviderManager<DBMessageTemplateProvider>.Provider.GetLocalizedMessageTemplate(Name, LanguageID);
LocalizedMessageTemplate localizedMessageTemplate = DBMapping(dbItem);
return localizedMessageTemplate;
}
/// <summary>
/// Deletes a localized message template
/// </summary>
/// <param name="LocalizedMessageTemplateID">Message template identifier</param>
public static void DeleteLocalizedMessageTemplate(int LocalizedMessageTemplateID)
{
DBProviderManager<DBMessageTemplateProvider>.Provider.DeleteLocalizedMessageTemplate(LocalizedMessageTemplateID);
}
/// <summary>
/// Gets all localized message templates
/// </summary>
/// <param name="MessageTemplatesName">Message template name</param>
/// <returns>Localized message template collection</returns>
public static LocalizedMessageTemplateCollection GetAllLocalizedMessageTemplates(string MessageTemplatesName)
{
DBLocalizedMessageTemplateCollection dbCollection = DBProviderManager<DBMessageTemplateProvider>.Provider.GetAllLocalizedMessageTemplates(MessageTemplatesName);
LocalizedMessageTemplateCollection localizedMessageTemplates = DBMapping(dbCollection);
return localizedMessageTemplates;
}
/// <summary>
/// Inserts a localized message template
/// </summary>
/// <param name="MessageTemplateID">The message template identifier</param>
/// <param name="LanguageID">The language identifier</param>
/// <param name="Subject">The subject</param>
/// <param name="Body">The body</param>
/// <returns>Localized message template</returns>
public static LocalizedMessageTemplate InsertLocalizedMessageTemplate(int MessageTemplateID,
int LanguageID, string Subject, string Body)
{
DBLocalizedMessageTemplate dbItem = DBProviderManager<DBMessageTemplateProvider>.Provider.InsertLocalizedMessageTemplate(MessageTemplateID,
LanguageID, Subject, Body);
LocalizedMessageTemplate localizedMessageTemplate = DBMapping(dbItem);
return localizedMessageTemplate;
}
/// <summary>
/// Updates the localized message template
/// </summary>
/// <param name="MessageTemplateLocalizedID">The localized message template identifier</param>
/// <param name="MessageTemplateID">The message template identifier</param>
/// <param name="LanguageID">The language identifier</param>
/// <param name="Subject">The subject</param>
/// <param name="Body">The body</param>
/// <returns>Localized message template</returns>
public static LocalizedMessageTemplate UpdateLocalizedMessageTemplate(int MessageTemplateLocalizedID,
int MessageTemplateID, int LanguageID,
string Subject, string Body)
{
DBLocalizedMessageTemplate dbItem = DBProviderManager<DBMessageTemplateProvider>.Provider.UpdateLocalizedMessageTemplate(MessageTemplateLocalizedID,
MessageTemplateID, LanguageID, Subject, Body);
LocalizedMessageTemplate localizedMessageTemplate = DBMapping(dbItem);
return localizedMessageTemplate;
}
/// <summary>
/// Gets a queued email by identifier
/// </summary>
/// <param name="QueuedEmailID">Email item identifier</param>
/// <returns>Email item</returns>
public static QueuedEmail GetQueuedEmailByID(int QueuedEmailID)
{
if (QueuedEmailID == 0)
return null;
DBQueuedEmail dbItem = DBProviderManager<DBMessageTemplateProvider>.Provider.GetQueuedEmailByID(QueuedEmailID);
QueuedEmail queuedEmail = DBMapping(dbItem);
return queuedEmail;
}
/// <summary>
/// Deletes a queued email
/// </summary>
/// <param name="QueuedEmailID">Email item identifier</param>
public static void DeleteQueuedEmail(int QueuedEmailID)
{
DBProviderManager<DBMessageTemplateProvider>.Provider.DeleteQueuedEmail(QueuedEmailID);
}
/// <summary>
/// Gets all queued emails
/// </summary>
/// <param name="QueuedEmailCount">Email item count. 0 if you want to get all items</param>
/// <param name="LoadNotSentItemsOnly">A value indicating whether to load only not sent emails</param>
/// <param name="MaxSendTries">Maximum send tries</param>
/// <returns>Email item collection</returns>
public static QueuedEmailCollection GetAllQueuedEmails(int QueuedEmailCount, bool LoadNotSentItemsOnly, int MaxSendTries)
{
return GetAllQueuedEmails(string.Empty, string.Empty, null, null,
QueuedEmailCount, LoadNotSentItemsOnly, MaxSendTries);
}
/// <summary>
/// Gets all queued emails
/// </summary>
/// <param name="FromEmail">From Email</param>
/// <param name="ToEmail">To Email</param>
/// <param name="StartTime">The start time</param>
/// <param name="EndTime">The end time</param>
/// <param name="QueuedEmailCount">Email item count. 0 if you want to get all items</param>
/// <param name="LoadNotSentItemsOnly">A value indicating whether to load only not sent emails</param>
/// <param name="MaxSendTries">Maximum send tries</param>
/// <returns>Email item collection</returns>
public static QueuedEmailCollection GetAllQueuedEmails(string FromEmail,
string ToEmail, DateTime? StartTime, DateTime? EndTime,
int QueuedEmailCount, bool LoadNotSentItemsOnly, int MaxSendTries)
{
if (FromEmail == null)
FromEmail = string.Empty;
FromEmail = FromEmail.Trim();
if (ToEmail == null)
ToEmail = string.Empty;
ToEmail = ToEmail.Trim();
DBQueuedEmailCollection dbCollection = DBProviderManager<DBMessageTemplateProvider>.Provider.GetAllQueuedEmails(FromEmail,
ToEmail, StartTime, EndTime, QueuedEmailCount, LoadNotSentItemsOnly, MaxSendTries);
QueuedEmailCollection queuedEmails = DBMapping(dbCollection);
return queuedEmails;
}
/// <summary>
/// Inserts a queued email
/// </summary>
/// <param name="Priority">The priority</param>
/// <param name="From">From</param>
/// <param name="To">To</param>
/// <param name="Cc">Cc</param>
/// <param name="Bcc">Bcc</param>
/// <param name="Subject">Subject</param>
/// <param name="Body">Body</param>
/// <param name="CreatedOn">The date and time of item creation</param>
/// <param name="SendTries">The send tries</param>
/// <param name="SentOn">The sent date and time. Null if email is not sent yet</param>
/// <returns>Queued email</returns>
public static QueuedEmail InsertQueuedEmail(int Priority, MailAddress From,
MailAddress To, string Cc, string Bcc,
string Subject, string Body, DateTime CreatedOn, int SendTries, DateTime? SentOn)
{
CreatedOn = DateTimeHelper.ConvertToUtcTime(CreatedOn);
if (SentOn.HasValue)
SentOn = DateTimeHelper.ConvertToUtcTime(SentOn.Value);
return InsertQueuedEmail(Priority, From.Address, From.DisplayName,
To.Address, To.DisplayName, Cc, Bcc, Subject, Body, CreatedOn, SendTries, SentOn);
}
/// <summary>
/// Inserts a queued email
/// </summary>
/// <param name="Priority">The priority</param>
/// <param name="From">From</param>
/// <param name="FromName">From name</param>
/// <param name="To">To</param>
/// <param name="ToName">To name</param>
/// <param name="Cc">Cc</param>
/// <param name="Bcc">Bcc</param>
/// <param name="Subject">Subject</param>
/// <param name="Body">Body</param>
/// <param name="CreatedOn">The date and time of item creation</param>
/// <param name="SendTries">The send tries</param>
/// <param name="SentOn">The sent date and time. Null if email is not sent yet</param>
/// <returns>Queued email</returns>
public static QueuedEmail InsertQueuedEmail(int Priority, string From,
string FromName, string To, string ToName, string Cc, string Bcc,
string Subject, string Body, DateTime CreatedOn, int SendTries, DateTime? SentOn)
{
CreatedOn = DateTimeHelper.ConvertToUtcTime(CreatedOn);
if (SentOn.HasValue)
SentOn = DateTimeHelper.ConvertToUtcTime(SentOn.Value);
DBQueuedEmail dbItem = DBProviderManager<DBMessageTemplateProvider>.Provider.InsertQueuedEmail(Priority, From,
FromName, To, ToName, Cc, Bcc, Subject, Body, CreatedOn, SendTries, SentOn);
QueuedEmail queuedEmail = DBMapping(dbItem);
return queuedEmail;
}
/// <summary>
/// Updates a queued email
/// </summary>
/// <param name="QueuedEmailID">Email item identifier</param>
/// <param name="Priority">The priority</param>
/// <param name="From">From</param>
/// <param name="FromName">From name</param>
/// <param name="To">To</param>
/// <param name="ToName">To name</param>
/// <param name="Cc">Cc</param>
/// <param name="Bcc">Bcc</param>
/// <param name="Subject">Subject</param>
/// <param name="Body">Body</param>
/// <param name="CreatedOn">The date and time of item creation</param>
/// <param name="SendTries">The send tries</param>
/// <param name="SentOn">The sent date and time. Null if email is not sent yet</param>
/// <returns>Queued email</returns>
public static QueuedEmail UpdateQueuedEmail(int QueuedEmailID, int Priority, string From,
string FromName, string To, string ToName, string Cc, string Bcc,
string Subject, string Body, DateTime CreatedOn, int SendTries, DateTime? SentOn)
{
CreatedOn = DateTimeHelper.ConvertToUtcTime(CreatedOn);
if (SentOn.HasValue)
SentOn = DateTimeHelper.ConvertToUtcTime(SentOn.Value);
DBQueuedEmail dbItem = DBProviderManager<DBMessageTemplateProvider>.Provider.UpdateQueuedEmail(QueuedEmailID, Priority,
From, FromName, To, ToName, Cc, Bcc, Subject, Body, CreatedOn, SendTries, SentOn);
QueuedEmail queuedEmail = DBMapping(dbItem);
return queuedEmail;
}
/// <summary>
/// Sends an order completed notification to a customer
/// </summary>
/// <param name="order">Order instance</param>
/// <param name="LanguageID">Message language identifier</param>
/// <returns>Queued email identifier</returns>
public static int SendOrderCompletedCustomerNotification(Order order, int LanguageID)
{
if (order == null)
throw new ArgumentNullException("order");
string TemplateName = "OrderCompleted.CustomerNotification";
LocalizedMessageTemplate localizedMessageTemplate = MessageManager.GetLocalizedMessageTemplate(TemplateName, LanguageID);
if (localizedMessageTemplate == null)
return 0;
//throw new NopException(string.Format("Message template ({0}-{1}) couldn't be loaded", TemplateName, LanguageID));
string subject = ReplaceMessageTemplateTokens(order, localizedMessageTemplate.Subject, LanguageID);
string body = ReplaceMessageTemplateTokens(order, localizedMessageTemplate.Body, LanguageID);
MailAddress from = new MailAddress(AdminEmailAddress, AdminEmailDisplayName);
MailAddress to = new MailAddress(order.BillingEmail, order.BillingFullName);
QueuedEmail queuedEmail = InsertQueuedEmail(5, from, to, string.Empty, string.Empty, subject, body, DateTime.Now, 0, null);
return queuedEmail.QueuedEmailID;
}
/// <summary>
/// Sends an order placed notification to a store owner
/// </summary>
/// <param name="order">Order instance</param>
/// <param name="LanguageID">Message language identifier</param>
/// <returns>Queued email identifier</returns>
public static int SendOrderPlacedStoreOwnerNotification(Order order, int LanguageID)
{
if (order == null)
throw new ArgumentNullException("order");
string TemplateName = "OrderPlaced.StoreOwnerNotification";
LocalizedMessageTemplate localizedMessageTemplate = MessageManager.GetLocalizedMessageTemplate(TemplateName, LanguageID);
if (localizedMessageTemplate == null)
return 0;
//throw new NopException(string.Format("Message template ({0}-{1}) couldn't be loaded", TemplateName, LanguageID));
string subject = ReplaceMessageTemplateTokens(order, localizedMessageTemplate.Subject, LanguageID);
string body = ReplaceMessageTemplateTokens(order, localizedMessageTemplate.Body, LanguageID);
MailAddress from = new MailAddress(AdminEmailAddress, AdminEmailDisplayName);
MailAddress to = new MailAddress(AdminEmailAddress, AdminEmailDisplayName);
QueuedEmail queuedEmail = InsertQueuedEmail(5, from, to, string.Empty, string.Empty, subject, body, DateTime.Now, 0, null);
return queuedEmail.QueuedEmailID;
}
/// <summary>
/// Sends a "quantity below" notification to a store owner
/// </summary>
/// <param name="productVariant">Product variant</param>
/// <param name="LanguageID">Message language identifier</param>
/// <returns>Queued email identifier</returns>
public static int SendQuantityBelowStoreOwnerNotification(ProductVariant productVariant, int LanguageID)
{
if (productVariant == null)
throw new ArgumentNullException("productVariant");
string TemplateName = "QuantityBelow.StoreOwnerNotification";
LocalizedMessageTemplate localizedMessageTemplate = MessageManager.GetLocalizedMessageTemplate(TemplateName, LanguageID);
if (localizedMessageTemplate == null)
return 0;
//throw new NopException(string.Format("Message template ({0}-{1}) couldn't be loaded", TemplateName, LanguageID));
string subject = ReplaceMessageTemplateTokens(productVariant, localizedMessageTemplate.Subject, LanguageID);
string body = ReplaceMessageTemplateTokens(productVariant, localizedMessageTemplate.Body, LanguageID);
MailAddress from = new MailAddress(AdminEmailAddress, AdminEmailDisplayName);
MailAddress to = new MailAddress(AdminEmailAddress, AdminEmailDisplayName);
QueuedEmail queuedEmail = InsertQueuedEmail(5, from, to, string.Empty, string.Empty, subject, body, DateTime.Now, 0, null);
return queuedEmail.QueuedEmailID;
}
/// <summary>
/// Sends an order placed notification to a customer
/// </summary>
/// <param name="order">Order instance</param>
/// <param name="LanguageID">Message language identifier</param>
/// <returns>Queued email identifier</returns>
public static int SendOrderPlacedCustomerNotification(Order order, int LanguageID)
{
if (order == null)
throw new ArgumentNullException("order");
string TemplateName = "OrderPlaced.CustomerNotification";
LocalizedMessageTemplate localizedMessageTemplate = MessageManager.GetLocalizedMessageTemplate(TemplateName, LanguageID);
if (localizedMessageTemplate == null)
return 0;
//throw new NopException(string.Format("Message template ({0}-{1}) couldn't be loaded", TemplateName, LanguageID));
string subject = ReplaceMessageTemplateTokens(order, localizedMessageTemplate.Subject, LanguageID);
string body = ReplaceMessageTemplateTokens(order, localizedMessageTemplate.Body, LanguageID);
MailAddress from = new MailAddress(AdminEmailAddress, AdminEmailDisplayName);
MailAddress to = new MailAddress(order.BillingEmail, order.BillingFullName);
QueuedEmail queuedEmail = InsertQueuedEmail(5, from, to, string.Empty, string.Empty, subject, body, DateTime.Now, 0, null);
return queuedEmail.QueuedEmailID;
}
/// <summary>
/// Sends an order shipped notification to a customer
/// </summary>
/// <param name="order">Order instance</param>
/// <param name="LanguageID">Message language identifier</param>
/// <returns>Queued email identifier</returns>
public static int SendOrderShippedCustomerNotification(Order order, int LanguageID)
{
if (order == null)
throw new ArgumentNullException("order");
string TemplateName = "OrderShipped.CustomerNotification";
LocalizedMessageTemplate localizedMessageTemplate = MessageManager.GetLocalizedMessageTemplate(TemplateName, LanguageID);
if (localizedMessageTemplate == null)
return 0;
//throw new NopException(string.Format("Message template ({0}-{1}) couldn't be loaded", TemplateName, LanguageID));
string subject = ReplaceMessageTemplateTokens(order, localizedMessageTemplate.Subject, LanguageID);
string body = ReplaceMessageTemplateTokens(order, localizedMessageTemplate.Body, LanguageID);
MailAddress from = new MailAddress(AdminEmailAddress, AdminEmailDisplayName);
MailAddress to = new MailAddress(order.BillingEmail, order.BillingFullName);
QueuedEmail queuedEmail = InsertQueuedEmail(5, from, to, string.Empty, string.Empty, subject, body, DateTime.Now, 0, null);
return queuedEmail.QueuedEmailID;
}
/// <summary>
/// Sends an order cancelled notification to a customer
/// </summary>
/// <param name="order">Order instance</param>
/// <param name="LanguageID">Message language identifier</param>
/// <returns>Queued email identifier</returns>
public static int SendOrderCancelledCustomerNotification(Order order, int LanguageID)
{
if (order == null)
throw new ArgumentNullException("order");
string TemplateName = "OrderCancelled.CustomerNotification";
LocalizedMessageTemplate localizedMessageTemplate = MessageManager.GetLocalizedMessageTemplate(TemplateName, LanguageID);
if (localizedMessageTemplate == null)
return 0;
//throw new NopException(string.Format("Message template ({0}-{1}) couldn't be loaded", TemplateName, LanguageID));
string subject = ReplaceMessageTemplateTokens(order, localizedMessageTemplate.Subject, LanguageID);
string body = ReplaceMessageTemplateTokens(order, localizedMessageTemplate.Body, LanguageID);
MailAddress from = new MailAddress(AdminEmailAddress, AdminEmailDisplayName);
MailAddress to = new MailAddress(order.BillingEmail, order.BillingFullName);
QueuedEmail queuedEmail = InsertQueuedEmail(5, from, to, string.Empty, string.Empty, subject, body, DateTime.Now, 0, null);
return queuedEmail.QueuedEmailID;
}
/// <summary>
/// Sends a welcome message to a customer
/// </summary>
/// <param name="customer">Customer instance</param>
/// <param name="LanguageID">Message language identifier</param>
/// <returns>Queued email identifier</returns>
public static int SendCustomerWelcomeMessage(Customer customer, int LanguageID)
{
if (customer == null)
throw new ArgumentNullException("customer");
string TemplateName = "Customer.WelcomeMessage";
LocalizedMessageTemplate localizedMessageTemplate = MessageManager.GetLocalizedMessageTemplate(TemplateName, LanguageID);
if (localizedMessageTemplate == null)
return 0;
//throw new NopException(string.Format("Message template ({0}-{1}) couldn't be loaded", TemplateName, LanguageID));
string subject = ReplaceMessageTemplateTokens(customer, localizedMessageTemplate.Subject);
string body = ReplaceMessageTemplateTokens(customer, localizedMessageTemplate.Body);
MailAddress from = new MailAddress(AdminEmailAddress, AdminEmailDisplayName);
MailAddress to = new MailAddress(customer.Email, customer.FullName);
QueuedEmail queuedEmail = InsertQueuedEmail(5, from, to, string.Empty, string.Empty, subject, body, DateTime.Now, 0, null);
return queuedEmail.QueuedEmailID;
}
/// <summary>
/// Sends an email validation message to a customer
/// </summary>
/// <param name="customer">Customer instance</param>
/// <param name="LanguageID">Message language identifier</param>
/// <returns>Queued email identifier</returns>
public static int SendCustomerEmailValidationMessage(Customer customer, int LanguageID)
{
if (customer == null)
throw new ArgumentNullException("customer");
string TemplateName = "Customer.EmailValidationMessage";
LocalizedMessageTemplate localizedMessageTemplate = MessageManager.GetLocalizedMessageTemplate(TemplateName, LanguageID);
if (localizedMessageTemplate == null)
return 0;
//throw new NopException(string.Format("Message template ({0}-{1}) couldn't be loaded", TemplateName, LanguageID));
string subject = ReplaceMessageTemplateTokens(customer, localizedMessageTemplate.Subject);
string body = ReplaceMessageTemplateTokens(customer, localizedMessageTemplate.Body);
MailAddress from = new MailAddress(AdminEmailAddress, AdminEmailDisplayName);
MailAddress to = new MailAddress(customer.Email, customer.FullName);
QueuedEmail queuedEmail = InsertQueuedEmail(5, from, to, string.Empty, string.Empty, subject, body, DateTime.Now, 0, null);
return queuedEmail.QueuedEmailID;
}
/// <summary>
/// Sends password recovery message to a customer
/// </summary>
/// <param name="customer">Customer instance</param>
/// <param name="LanguageID">Message language identifier</param>
/// <returns>Queued email identifier</returns>
public static int SendCustomerPasswordRecoveryMessage(Customer customer, int LanguageID)
{
if (customer == null)
throw new ArgumentNullException("customer");
string TemplateName = "Customer.PasswordRecovery";
LocalizedMessageTemplate localizedMessageTemplate = MessageManager.GetLocalizedMessageTemplate(TemplateName, LanguageID);
if (localizedMessageTemplate == null)
return 0;
//throw new NopException(string.Format("Message template ({0}-{1}) couldn't be loaded", TemplateName, LanguageID));
string subject = ReplaceMessageTemplateTokens(customer, localizedMessageTemplate.Subject);
string body = ReplaceMessageTemplateTokens(customer, localizedMessageTemplate.Body);
MailAddress from = new MailAddress(AdminEmailAddress, AdminEmailDisplayName);
MailAddress to = new MailAddress(customer.Email, customer.FullName);
QueuedEmail queuedEmail = InsertQueuedEmail(5, from, to, string.Empty, string.Empty, subject, body, DateTime.Now, 0, null);
return queuedEmail.QueuedEmailID;
}
/// <summary>
/// Sends "email a friend" message
/// </summary>
/// <param name="customer">Customer instance</param>
/// <param name="LanguageID">Message language identifier</param>
/// <param name="product">Product instance</param>
/// <param name="FriendsEmail">Friend's email</param>
/// <param name="PersonalMessage">Personal message</param>
/// <returns>Queued email identifier</returns>
public static int SendEmailAFriendMessage(Customer customer, int LanguageID, Product product, string FriendsEmail, string PersonalMessage)
{
if (customer == null)
throw new ArgumentNullException("customer");
if (product == null)
throw new ArgumentNullException("product");
string TemplateName = "Service.EmailAFriend";
LocalizedMessageTemplate localizedMessageTemplate = MessageManager.GetLocalizedMessageTemplate(TemplateName, LanguageID);
if (localizedMessageTemplate == null)
return 0;
//throw new NopException(string.Format("Message template ({0}-{1}) couldn't be loaded", TemplateName, LanguageID));
NameValueCollection additinalKeys = new NameValueCollection();
additinalKeys.Add("EmailAFriend.PersonalMessage", PersonalMessage);
string subject = ReplaceMessageTemplateTokens(customer, product, localizedMessageTemplate.Subject, additinalKeys);
string body = ReplaceMessageTemplateTokens(customer, product, localizedMessageTemplate.Body, additinalKeys);
MailAddress from = new MailAddress(AdminEmailAddress, AdminEmailDisplayName);
MailAddress to = new MailAddress(FriendsEmail);
QueuedEmail queuedEmail = InsertQueuedEmail(5, from, to, string.Empty, string.Empty, subject, body, DateTime.Now, 0, null);
return queuedEmail.QueuedEmailID;
}
/// <summary>
/// Sends a forum subscription message to a customer
/// </summary>
/// <param name="customer">Customer instance</param>
/// <param name="forumTopic">Forum Topic</param>
/// <param name="forum">Forum</param>
/// <param name="LanguageID">Message language identifier</param>
/// <returns>Queued email identifier</returns>
public static int SendNewForumTopicMessage(Customer customer, ForumTopic forumTopic, Forum forum, int LanguageID)
{
if (customer == null)
throw new ArgumentNullException("customer");
string TemplateName = "Forums.NewForumTopic";
LocalizedMessageTemplate localizedMessageTemplate = MessageManager.GetLocalizedMessageTemplate(TemplateName, LanguageID);
if (localizedMessageTemplate == null)
return 0;
//throw new NopException(string.Format("Message template ({0}-{1}) couldn't be loaded", TemplateName, LanguageID));
string subject = ReplaceMessageTemplateTokens(customer, forumTopic, forum, localizedMessageTemplate.Subject);
string body = ReplaceMessageTemplateTokens(customer, forumTopic, forum, localizedMessageTemplate.Body);
MailAddress from = new MailAddress(AdminEmailAddress, AdminEmailDisplayName);
MailAddress to = new MailAddress(customer.Email, customer.FullName);
QueuedEmail queuedEmail = InsertQueuedEmail(5, from, to, string.Empty, string.Empty, subject, body, DateTime.Now, 0, null);
return queuedEmail.QueuedEmailID;
}
/// <summary>
/// Sends a forum subscription message to a customer
/// </summary>
/// <param name="customer">Customer instance</param>
/// <param name="forumTopic">Forum Topic</param>
/// <param name="forum">Forum</param>
/// <param name="LanguageID">Message language identifier</param>
/// <returns>Queued email identifier</returns>
public static int SendNewForumPostMessage(Customer customer, ForumTopic forumTopic, Forum forum, int LanguageID)
{
if (customer == null)
throw new ArgumentNullException("customer");
string TemplateName = "Forums.NewForumPost";
LocalizedMessageTemplate localizedMessageTemplate = MessageManager.GetLocalizedMessageTemplate(TemplateName, LanguageID);
if (localizedMessageTemplate == null)
return 0;
//throw new NopException(string.Format("Message template ({0}-{1}) couldn't be loaded", TemplateName, LanguageID));
string subject = ReplaceMessageTemplateTokens(customer, forumTopic, forum, localizedMessageTemplate.Subject);
string body = ReplaceMessageTemplateTokens(customer, forumTopic, forum, localizedMessageTemplate.Body);
MailAddress from = new MailAddress(AdminEmailAddress, AdminEmailDisplayName);
MailAddress to = new MailAddress(customer.Email, customer.FullName);
QueuedEmail queuedEmail = InsertQueuedEmail(5, from, to, string.Empty, string.Empty, subject, body, DateTime.Now, 0, null);
return queuedEmail.QueuedEmailID;
}
/// <summary>
/// Sends a news comment notification message to a store owner
/// </summary>
/// <param name="newsComment">News comment</param>
/// <param name="LanguageID">Message language identifier</param>
/// <returns>Queued email identifier</returns>
public static int SendNewsCommentNotificationMessage(NewsComment newsComment, int LanguageID)
{
if (newsComment == null)
throw new ArgumentNullException("newsComment");
string TemplateName = "News.NewsComment";
LocalizedMessageTemplate localizedMessageTemplate = MessageManager.GetLocalizedMessageTemplate(TemplateName, LanguageID);
if (localizedMessageTemplate == null)
return 0;
//throw new NopException(string.Format("Message template ({0}-{1}) couldn't be loaded", TemplateName, LanguageID));
string subject = ReplaceMessageTemplateTokens(newsComment, localizedMessageTemplate.Subject);
string body = ReplaceMessageTemplateTokens(newsComment, localizedMessageTemplate.Body);
MailAddress from = new MailAddress(AdminEmailAddress, AdminEmailDisplayName);
MailAddress to = new MailAddress(AdminEmailAddress, AdminEmailDisplayName);
QueuedEmail queuedEmail = InsertQueuedEmail(5, from, to, string.Empty, string.Empty, subject, body, DateTime.Now, 0, null);
return queuedEmail.QueuedEmailID;
}
public static int SendQuickOrderMessage(String message)
{
string subject = "Быстрый заказ";
string body = message;
MailAddress from = new MailAddress(AdminEmailAddress, AdminEmailDisplayName);
MailAddress to = new MailAddress(AdminEmailAddress, AdminEmailAddress);
QueuedEmail queuedEmail = InsertQueuedEmail(5, from, to, string.Empty, string.Empty, subject, body, DateTime.Now, 0, null);
return queuedEmail.QueuedEmailID;
}
/// <summary>
/// Sends a blog comment notification message to a store owner
/// </summary>
/// <param name="blogComment">Blog comment</param>
/// <param name="LanguageID">Message language identifier</param>
/// <returns>Queued email identifier</returns>
public static int SendBlogCommentNotificationMessage(BlogComment blogComment, int LanguageID)
{
if (blogComment == null)
throw new ArgumentNullException("blogComment");
string TemplateName = "Blog.BlogComment";
LocalizedMessageTemplate localizedMessageTemplate = MessageManager.GetLocalizedMessageTemplate(TemplateName, LanguageID);
if (localizedMessageTemplate == null)
return 0;
//throw new NopException(string.Format("Message template ({0}-{1}) couldn't be loaded", TemplateName, LanguageID));
string subject = ReplaceMessageTemplateTokens(blogComment, localizedMessageTemplate.Subject);
string body = ReplaceMessageTemplateTokens(blogComment, localizedMessageTemplate.Body);
MailAddress from = new MailAddress(AdminEmailAddress, AdminEmailDisplayName);
MailAddress to = new MailAddress(AdminEmailAddress, AdminEmailDisplayName);
QueuedEmail queuedEmail = InsertQueuedEmail(5, from, to, string.Empty, string.Empty, subject, body, DateTime.Now, 0, null);
return queuedEmail.QueuedEmailID;
}
/// <summary>
/// Sends a product review notification message to a store owner
/// </summary>
/// <param name="productReview">Product review</param>
/// <param name="LanguageID">Message language identifier</param>
/// <returns>Queued email identifier</returns>
public static int SendProductReviewNotificationMessage(ProductReview productReview, int LanguageID)
{
if (productReview == null)
throw new ArgumentNullException("productReview");
string TemplateName = "Product.ProductReview";
LocalizedMessageTemplate localizedMessageTemplate = MessageManager.GetLocalizedMessageTemplate(TemplateName, LanguageID);
if (localizedMessageTemplate == null)
return 0;
//throw new NopException(string.Format("Message template ({0}-{1}) couldn't be loaded", TemplateName, LanguageID));
string subject = ReplaceMessageTemplateTokens(productReview, localizedMessageTemplate.Subject);
string body = ReplaceMessageTemplateTokens(productReview, localizedMessageTemplate.Body);
MailAddress from = new MailAddress(AdminEmailAddress, AdminEmailDisplayName);
MailAddress to = new MailAddress(AdminEmailAddress, AdminEmailDisplayName);
QueuedEmail queuedEmail = InsertQueuedEmail(5, from, to, string.Empty, string.Empty, subject, body, DateTime.Now, 0, null);
return queuedEmail.QueuedEmailID;
}
/// <summary>
/// Sends an email
/// </summary>
/// <param name="Subject">Subject</param>
/// <param name="Body">Body</param>
/// <param name="From">From</param>
/// <param name="To">To</param>
public static void SendEmail(string Subject, string Body, string From, string To)
{
SendEmail(Subject, Body, new MailAddress(From), new MailAddress(To), new List<String>(), new List<String>());
}
/// <summary>
/// Sends an email
/// </summary>
/// <param name="Subject">Subject</param>
/// <param name="Body">Body</param>
/// <param name="From">From</param>
/// <param name="To">To</param>
public static void SendEmail(string Subject, string Body, MailAddress From, MailAddress To)
{
SendEmail(Subject, Body, From, To, new List<String>(), new List<String>());
}
/// <summary>
/// Sends an email
/// </summary>
/// <param name="Subject">Subject</param>
/// <param name="Body">Body</param>
/// <param name="From">From</param>
/// <param name="To">To</param>
/// <param name="bcc">Bcc</param>
/// <param name="cc">Cc</param>
public static void SendEmail(string Subject, string Body, MailAddress From, MailAddress To, List<string> bcc, List<string> cc)
{
MailMessage message = new MailMessage();
message.From = From;
message.To.Add(To);
if (null != bcc)
foreach (string address in bcc)
{
if (!String.IsNullOrEmpty(address))
message.Bcc.Add(address);
}
if (null != cc)
foreach (string address in cc)
{
if (!String.IsNullOrEmpty(address))
message.CC.Add(address);
}
message.Subject = Subject;
message.Body = Body;
message.IsBodyHtml = true;
SmtpClient smtpClient = new SmtpClient();
smtpClient.UseDefaultCredentials = AdminEmailUseDefaultCredentials;
smtpClient.Host = AdminEmailHost;
smtpClient.Port = AdminEmailPort;
smtpClient.EnableSsl = AdminEmailEnableSsl;
if (AdminEmailUseDefaultCredentials)
smtpClient.Credentials = CredentialCache.DefaultNetworkCredentials;
else
smtpClient.Credentials = new NetworkCredential(AdminEmailUser, AdminEmailPassword);
smtpClient.Send(message);
}
/// <summary>
/// Gets list of allowed (supported) message tokens
/// </summary>
/// <returns></returns>
public static string[] GetListOfAllowedTokens()
{
List<string> allowedTokens = new List<string>();
allowedTokens.Add("%Store.Name%");
allowedTokens.Add("%Store.URL%");
allowedTokens.Add("%Store.Email%");
allowedTokens.Add("%Order.OrderNumber%");
allowedTokens.Add("%Order.CustomerFullName%");
allowedTokens.Add("%Order.CustomerEmail%");
allowedTokens.Add("%Order.BillingFirstName%");
allowedTokens.Add("%Order.BillingLastName%");
allowedTokens.Add("%Order.BillingPhoneNumber%");
allowedTokens.Add("%Order.BillingEmail%");
allowedTokens.Add("%Order.BillingFaxNumber%");
allowedTokens.Add("%Order.BillingCompany%");
allowedTokens.Add("%Order.BillingAddress1%");
allowedTokens.Add("%Order.BillingAddress2%");
allowedTokens.Add("%Order.BillingCity%");
allowedTokens.Add("%Order.BillingStateProvince%");
allowedTokens.Add("%Order.BillingZipPostalCode%");
allowedTokens.Add("%Order.BillingCountry%");
allowedTokens.Add("%Order.ShippingMethod%");
allowedTokens.Add("%Order.ShippingFirstName%");
allowedTokens.Add("%Order.ShippingLastName%");
allowedTokens.Add("%Order.ShippingPhoneNumber%");
allowedTokens.Add("%Order.ShippingEmail%");
allowedTokens.Add("%Order.ShippingFaxNumber%");
allowedTokens.Add("%Order.ShippingCompany%");
allowedTokens.Add("%Order.ShippingAddress1%");
allowedTokens.Add("%Order.ShippingAddress2%");
allowedTokens.Add("%Order.ShippingCity%");
allowedTokens.Add("%Order.ShippingStateProvince%");
allowedTokens.Add("%Order.ShippingZipPostalCode%");
allowedTokens.Add("%Order.ShippingCountry%");
allowedTokens.Add("%Order.Product(s)%");
allowedTokens.Add("%Order.CreatedOn%");
allowedTokens.Add("%Order.OrderURLForCustomer%");
allowedTokens.Add("%Customer.Email%");
allowedTokens.Add("%Customer.PasswordRecoveryURL%");
allowedTokens.Add("%Customer.AccountActivationURL%");
allowedTokens.Add("%Customer.FullName%");
allowedTokens.Add("%Product.Name%");
allowedTokens.Add("%Product.ShortDescription%");
allowedTokens.Add("%Product.ProductURLForCustomer%");
allowedTokens.Add("%ProductVariant.FullProductName%");
allowedTokens.Add("%ProductVariant.StockQuantity%");
allowedTokens.Add("%NewsComment.NewsTitle%");
allowedTokens.Add("%BlogComment.BlogPostTitle%");
allowedTokens.Add("%ProductReview.ProductName%");
return allowedTokens.ToArray();
}
/// <summary>
/// Gets list of allowed (supported) message tokens for campaigns
/// </summary>
/// <returns></returns>
public static string[] GetListOfCampaignAllowedTokens()
{
List<string> allowedTokens = new List<string>();
allowedTokens.Add("%Store.Name%");
allowedTokens.Add("%Store.URL%");
allowedTokens.Add("%Store.Email%");
allowedTokens.Add("%Customer.Email%");
allowedTokens.Add("%Customer.FullName%");
return allowedTokens.ToArray();
}
/// <summary>
/// Replaces a message template tokens
/// </summary>
/// <param name="order">Order instance</param>
/// <param name="Template">Template</param>
/// <param name="LanguageID">Language identifier</param>
/// <returns>New template</returns>
public static string ReplaceMessageTemplateTokens(Order order, string Template, int LanguageID)
{
NameValueCollection tokens = new NameValueCollection();
tokens.Add("Store.Name", SettingManager.StoreName);
tokens.Add("Store.URL", SettingManager.StoreURL);
tokens.Add("Store.Email", AdminEmailAddress);
tokens.Add("Order.OrderNumber", order.OrderID.ToString());
//tokens.Add("Order.CustomerFullName", order.Customer.FullName);
//tokens.Add("Order.CustomerEmail", order.Customer.Email);
tokens.Add("Order.CustomerFullName", HttpUtility.HtmlEncode(order.BillingFullName));
tokens.Add("Order.CustomerEmail", HttpUtility.HtmlEncode(order.BillingEmail));
tokens.Add("Order.BillingFirstName", HttpUtility.HtmlEncode(order.BillingFirstName));
tokens.Add("Order.BillingLastName", HttpUtility.HtmlEncode(order.BillingLastName));
tokens.Add("Order.BillingPhoneNumber", HttpUtility.HtmlEncode(order.BillingPhoneNumber));
tokens.Add("Order.BillingEmail", HttpUtility.HtmlEncode(order.BillingEmail.ToString()));
tokens.Add("Order.BillingFaxNumber", HttpUtility.HtmlEncode(order.BillingFaxNumber));
tokens.Add("Order.BillingCompany", HttpUtility.HtmlEncode(order.BillingCompany));
tokens.Add("Order.BillingAddress1", HttpUtility.HtmlEncode(order.BillingAddress1));
tokens.Add("Order.BillingAddress2", HttpUtility.HtmlEncode(order.BillingAddress2));
tokens.Add("Order.BillingCity", HttpUtility.HtmlEncode(order.BillingCity));
tokens.Add("Order.BillingStateProvince", HttpUtility.HtmlEncode(order.BillingStateProvince));
tokens.Add("Order.BillingZipPostalCode", HttpUtility.HtmlEncode(order.BillingZipPostalCode));
tokens.Add("Order.BillingCountry", HttpUtility.HtmlEncode(order.BillingCountry));
tokens.Add("Order.ShippingMethod", HttpUtility.HtmlEncode(order.ShippingMethod));
tokens.Add("Order.ShippingFirstName", HttpUtility.HtmlEncode(order.ShippingFirstName));
tokens.Add("Order.ShippingLastName", HttpUtility.HtmlEncode(order.ShippingLastName));
tokens.Add("Order.ShippingPhoneNumber", HttpUtility.HtmlEncode(order.ShippingPhoneNumber));
tokens.Add("Order.ShippingEmail", HttpUtility.HtmlEncode(order.ShippingEmail.ToString()));
tokens.Add("Order.ShippingFaxNumber", HttpUtility.HtmlEncode(order.ShippingFaxNumber));
tokens.Add("Order.ShippingCompany", HttpUtility.HtmlEncode(order.ShippingCompany));
tokens.Add("Order.ShippingAddress1", HttpUtility.HtmlEncode(order.ShippingAddress1));
tokens.Add("Order.ShippingAddress2", HttpUtility.HtmlEncode(order.ShippingAddress2));
tokens.Add("Order.ShippingCity", HttpUtility.HtmlEncode(order.ShippingCity));
tokens.Add("Order.ShippingStateProvince", HttpUtility.HtmlEncode(order.ShippingStateProvince));
tokens.Add("Order.ShippingZipPostalCode", HttpUtility.HtmlEncode(order.ShippingZipPostalCode));
tokens.Add("Order.ShippingCountry", HttpUtility.HtmlEncode(order.ShippingCountry));
tokens.Add("Order.Product(s)", ProductListToHtmlTable(order, LanguageID));
Language language = LanguageManager.GetLanguageByID(LanguageID);
//UNDONE use time zone
//1. Add new token for store owner
//2. Convert the date and time according to time zone
if (language != null && !String.IsNullOrEmpty(language.LanguageCulture))
{
tokens.Add("Order.CreatedOn", order.CreatedOn.ToString("D", new CultureInfo(language.LanguageCulture)));
}
else
{
tokens.Add("Order.CreatedOn", order.CreatedOn.ToString("D"));
}
//TODO add "Order.OrderTotal" token
//tokens.Add("Order.OrderTotal", String.Format("{0} ({1})", order.OrderTotalInCustomerCurrency.ToString("N", new CultureInfo("en-us")), order.CustomerCurrencyCode));
tokens.Add("Order.OrderURLForCustomer", string.Format("{0}OrderDetails.aspx?OrderID={1}", SettingManager.StoreURL, order.OrderID));
foreach (string token in tokens.Keys)
Template = Template.Replace(string.Format(@"%{0}%", token), tokens[token]);
return Template;
}
/// <summary>
/// Replaces a message template tokens
/// </summary>
/// <param name="customer">Customer instance</param>
/// <param name="Template">Template</param>
/// <returns>New template</returns>
public static string ReplaceMessageTemplateTokens(Customer customer, string Template)
{
NameValueCollection tokens = new NameValueCollection();
tokens.Add("Store.Name", SettingManager.StoreName);
tokens.Add("Store.URL", SettingManager.StoreURL);
tokens.Add("Store.Email", AdminEmailAddress);
tokens.Add("Customer.Email", HttpUtility.HtmlEncode(customer.Email));
tokens.Add("Customer.FullName", HttpUtility.HtmlEncode(customer.FullName));
string passwordRecoveryURL = string.Empty;
passwordRecoveryURL = string.Format("{0}PasswordRecovery.aspx?PRT={1}&Email={2}", SettingManager.StoreURL, customer.PasswordRecoveryToken, customer.Email);
tokens.Add("Customer.PasswordRecoveryURL", passwordRecoveryURL);
string accountActivationURL = string.Empty;
accountActivationURL = string.Format("{0}AccountActivation.aspx?ACT={1}&Email={2}", SettingManager.StoreURL, customer.AccountActivationToken, customer.Email);
tokens.Add("Customer.AccountActivationURL", accountActivationURL);
foreach (string token in tokens.Keys)
Template = Template.Replace(string.Format(@"%{0}%", token), tokens[token]);
return Template;
}
/// <summary>
/// Replaces a message template tokens
/// </summary>
/// <param name="customer">Customer instance</param>
/// <param name="product">Product instance</param>
/// <param name="Template">Template</param>
/// <param name="AdditinalKeys">Additinal keys</param>
/// <returns>New template</returns>
public static string ReplaceMessageTemplateTokens(Customer customer, Product product,
string Template, NameValueCollection AdditinalKeys)
{
NameValueCollection tokens = new NameValueCollection();
tokens.Add("Store.Name", SettingManager.StoreName);
tokens.Add("Store.URL", SettingManager.StoreURL);
tokens.Add("Store.Email", AdminEmailAddress);
tokens.Add("Customer.Email", HttpUtility.HtmlEncode(customer.Email));
tokens.Add("Customer.FullName", HttpUtility.HtmlEncode(customer.FullName));
tokens.Add("Product.Name", HttpUtility.HtmlEncode(product.Name));
tokens.Add("Product.ShortDescription", product.ShortDescription);
tokens.Add("Product.ProductURLForCustomer", SEOHelper.GetProductURL(product));
foreach (string token in tokens.Keys)
Template = Template.Replace(string.Format(@"%{0}%", token), tokens[token]);
foreach (string token in AdditinalKeys.Keys)
Template = Template.Replace(string.Format(@"%{0}%", token), AdditinalKeys[token]);
return Template;
}
/// <summary>
/// Replaces a message template tokens
/// </summary>
/// <param name="customer">Customer instance</param>
/// <param name="forumTopic">Forum Topic</param>
/// <param name="forum">Forum</param>
/// <param name="Template">Template</param>
/// <returns>New template</returns>
public static string ReplaceMessageTemplateTokens(Customer customer,
ForumTopic forumTopic, Forum forum,
string Template)
{
NameValueCollection tokens = new NameValueCollection();
tokens.Add("Store.Name", SettingManager.StoreName);
tokens.Add("Store.URL", SettingManager.StoreURL);
tokens.Add("Store.Email", AdminEmailAddress);
tokens.Add("Customer.Email", HttpUtility.HtmlEncode(customer.Email));
tokens.Add("Customer.FullName", HttpUtility.HtmlEncode(customer.FullName));
tokens.Add("Forums.TopicURL", SEOHelper.GetForumTopicURL(forumTopic.ForumTopicID));
tokens.Add("Forums.TopicName", HttpUtility.HtmlEncode(forumTopic.Subject));
tokens.Add("Forums.ForumURL", SEOHelper.GetForumURL(forum));
tokens.Add("Forums.ForumName", HttpUtility.HtmlEncode(forum.Name));
foreach (string token in tokens.Keys)
Template = Template.Replace(string.Format(@"%{0}%", token), tokens[token]);
return Template;
}
/// <summary>
/// Replaces a message template tokens
/// </summary>
/// <param name="productVariant">Product variant</param>
/// <param name="Template">Template</param>
/// <param name="LanguageID">Language identifier</param>
/// <returns>New template</returns>
public static string ReplaceMessageTemplateTokens(ProductVariant productVariant, string Template, int LanguageID)
{
NameValueCollection tokens = new NameValueCollection();
tokens.Add("Store.Name", SettingManager.StoreName);
tokens.Add("Store.URL", SettingManager.StoreURL);
tokens.Add("Store.Email", AdminEmailAddress);
tokens.Add("ProductVariant.ID", productVariant.ProductVariantID.ToString());
tokens.Add("ProductVariant.FullProductName", HttpUtility.HtmlEncode(productVariant.FullProductName));
tokens.Add("ProductVariant.StockQuantity", productVariant.StockQuantity.ToString());
foreach (string token in tokens.Keys)
Template = Template.Replace(string.Format(@"%{0}%", token), tokens[token]);
return Template;
}
/// <summary>
/// Replaces a message template tokens
/// </summary>
/// <param name="newsComment">News comment</param>
/// <param name="Template">Template</param>
/// <returns>New template</returns>
public static string ReplaceMessageTemplateTokens(NewsComment newsComment, string Template)
{
NameValueCollection tokens = new NameValueCollection();
tokens.Add("Store.Name", SettingManager.StoreName);
tokens.Add("Store.URL", SettingManager.StoreURL);
tokens.Add("Store.Email", AdminEmailAddress);
tokens.Add("NewsComment.NewsTitle", HttpUtility.HtmlEncode(newsComment.News.Title));
foreach (string token in tokens.Keys)
Template = Template.Replace(string.Format(@"%{0}%", token), tokens[token]);
return Template;
}
/// <summary>
/// Replaces a message template tokens
/// </summary>
/// <param name="blogComment">Blog comment</param>
/// <param name="Template">Template</param>
/// <returns>New template</returns>
public static string ReplaceMessageTemplateTokens(BlogComment blogComment, string Template)
{
NameValueCollection tokens = new NameValueCollection();
tokens.Add("Store.Name", SettingManager.StoreName);
tokens.Add("Store.URL", SettingManager.StoreURL);
tokens.Add("Store.Email", AdminEmailAddress);
tokens.Add("BlogComment.BlogPostTitle", HttpUtility.HtmlEncode(blogComment.BlogPost.BlogPostTitle));
foreach (string token in tokens.Keys)
Template = Template.Replace(string.Format(@"%{0}%", token), tokens[token]);
return Template;
}
/// <summary>
/// Replaces a message template tokens
/// </summary>
/// <param name="productReview">Product review</param>
/// <param name="Template">Template</param>
/// <returns>New template</returns>
public static string ReplaceMessageTemplateTokens(ProductReview productReview, string Template)
{
NameValueCollection tokens = new NameValueCollection();
tokens.Add("Store.Name", SettingManager.StoreName);
tokens.Add("Store.URL", SettingManager.StoreURL);
tokens.Add("Store.Email", AdminEmailAddress);
tokens.Add("ProductReview.ProductName", HttpUtility.HtmlEncode(productReview.Product.Name));
foreach (string token in tokens.Keys)
Template = Template.Replace(string.Format(@"%{0}%", token), tokens[token]);
return Template;
}
/// <summary>
/// Formats the contact us form text
/// </summary>
/// <param name="Text">Text</param>
/// <returns>Formatted text</returns>
public static string FormatContactUsFormText(string Text)
{
if (String.IsNullOrEmpty(Text))
return string.Empty;
Text = HtmlHelper.FormatText(Text, false, true, false, false, false, false);
return Text;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets an admin email address
/// </summary>
public static string AdminEmailAddress
{
get
{
return SettingManager.GetSettingValue("Email.AdminEmailAddress");
}
set
{
SettingManager.SetParam("Email.AdminEmailAddress", value.Trim());
}
}
/// <summary>
/// Gets or sets an admin email display name
/// </summary>
public static string AdminEmailDisplayName
{
get
{
return SettingManager.GetSettingValue("Email.AdminEmailDisplayName");
}
set
{
SettingManager.SetParam("Email.AdminEmailDisplayName", value.Trim());
}
}
/// <summary>
/// Gets or sets an admin email host
/// </summary>
public static string AdminEmailHost
{
get
{
return SettingManager.GetSettingValue("Email.AdminEmailHost");
}
set
{
SettingManager.SetParam("Email.AdminEmailHost", value.Trim());
}
}
/// <summary>
/// Gets or sets an admin email port
/// </summary>
public static int AdminEmailPort
{
get
{
return SettingManager.GetSettingValueInteger("Email.AdminEmailPort");
}
set
{
SettingManager.SetParam("Email.AdminEmailPort", value.ToString());
}
}
/// <summary>
/// Gets or sets an admin email user name
/// </summary>
public static string AdminEmailUser
{
get
{
return SettingManager.GetSettingValue("Email.AdminEmailUser");
}
set
{
SettingManager.SetParam("Email.AdminEmailUser", value.Trim());
}
}
/// <summary>
/// Gets or sets an admin email password
/// </summary>
public static string AdminEmailPassword
{
get
{
return SettingManager.GetSettingValue("Email.AdminEmailPassword");
}
set
{
SettingManager.SetParam("Email.AdminEmailPassword", value);
}
}
/// <summary>
/// Gets or sets a value that controls whether the default system credentials of the application are sent with requests.
/// </summary>
public static bool AdminEmailUseDefaultCredentials
{
get
{
return SettingManager.GetSettingValueBoolean("Email.AdminEmailUseDefaultCredentials");
}
set
{
SettingManager.SetParam("Email.AdminEmailUseDefaultCredentials", value.ToString());
}
}
/// <summary>
/// Gets or sets a value that controls whether the SmtpClient uses Secure Sockets Layer (SSL) to encrypt the connection
/// </summary>
public static bool AdminEmailEnableSsl
{
get
{
return SettingManager.GetSettingValueBoolean("Email.AdminEmailEnableSsl");
}
set
{
SettingManager.SetParam("Email.AdminEmailEnableSsl", value.ToString());
}
}
#endregion
}
} |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;
using static JPAssets.Binary.Tests.CommonTestUtility;
namespace JPAssets.Binary.Tests
{
// TODO: Add test method names.
// TODO: Implement tests for all EndiannessUtility methods.
[TestClass()]
public class EndiannessUtilityTests
{
[TestMethod()]
public void TestReverseEndiannessThrowsForNullByteArray()
{
Assert.ThrowsException<ArgumentNullException>(() =>
{
EndiannessUtility.ReverseEndianness((byte[])null);
});
Assert.ThrowsException<ArgumentNullException>(() =>
{
EndiannessUtility.ReverseEndianness((byte[])null, 0, 0);
});
}
[TestMethod()]
public unsafe void TestReverseEndiannessThrowsWhenOffsetOrCountInvalid()
{
const int length = 4;
const int halfLength = length / 2;
// Test negative offset
Assert.ThrowsException<ArgumentOutOfRangeException>(() =>
{
EndiannessUtility.ReverseEndianness(new byte[length], -1, halfLength);
});
// Test negative count
Assert.ThrowsException<ArgumentOutOfRangeException>(() =>
{
EndiannessUtility.ReverseEndianness(new byte[length], 0, -1);
});
Assert.ThrowsException<ArgumentOutOfRangeException>(() =>
{
var bytes = new byte[length];
fixed (byte* ptr = bytes)
EndiannessUtility.ReverseEndianness(ptr, -1);
});
// Test offset >= length
Assert.ThrowsException<ArgumentException>(() =>
{
EndiannessUtility.ReverseEndianness(new byte[length], length, halfLength);
});
Assert.ThrowsException<ArgumentException>(() =>
{
EndiannessUtility.ReverseEndianness(new byte[length], length + 1, halfLength);
});
// Test count overflow
Assert.ThrowsException<ArgumentException>(() =>
{
EndiannessUtility.ReverseEndianness(new byte[length], 0, length + 1);
});
Assert.ThrowsException<ArgumentException>(() =>
{
EndiannessUtility.ReverseEndianness(new byte[length], 1, length);
});
// Test the method does not fail with valid input
EndiannessUtility.ReverseEndianness(new byte[length], 0, 0);
EndiannessUtility.ReverseEndianness(new byte[length], 0, 1);
EndiannessUtility.ReverseEndianness(new byte[length], 0, halfLength);
EndiannessUtility.ReverseEndianness(new byte[length], 0, length);
EndiannessUtility.ReverseEndianness(new byte[length], halfLength, 1);
EndiannessUtility.ReverseEndianness(new byte[length], halfLength, halfLength);
}
[TestMethod()]
public void ReverseEndiannessForByteArray()
{
var random = GetRandomAndLogSeed();
foreach (var length in new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 16, 32, 64 })
{
// Get random bytes
var buffer = new byte[length];
random.NextBytes(buffer);
// Copy original buffer state
var copyBuffer = new byte[length];
Array.Copy(buffer, 0, copyBuffer, 0, length);
// Reverse entire buffer & test
EndiannessUtility.ReverseEndianness(buffer, 0, length);
for (int i = 0; i < length; i++)
Assert.AreEqual<byte>(copyBuffer[i], buffer[length - i - 1]);
// Reverse back to original endianness order & test
EndiannessUtility.ReverseEndianness(buffer, 0, length);
for (int i = 0; i < length; i++)
Assert.AreEqual<byte>(copyBuffer[i], buffer[i]);
}
// TODO: Implement tests for ReverseEndianness(byte[])
// TODO: Implement tests for ReverseEndianness(byte[], int, int)
throw new NotImplementedException();
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using CloneDeploy_Entities;
namespace CloneDeploy_Services
{
public class AuthorizationServices
{
private readonly CloneDeployUserEntity _cloneDeployUser;
private readonly List<string> _currentUserRights;
private readonly string _requiredRight;
private readonly UserServices _userServices;
public AuthorizationServices(int userId, string requiredRight)
{
_userServices = new UserServices();
_cloneDeployUser = _userServices.GetUser(userId);
_currentUserRights = _userServices.GetUserRights(userId).Select(right => right.Right).ToList();
_requiredRight = requiredRight;
}
public bool ComputerManagement(int computerId)
{
if (_cloneDeployUser.Membership == "Administrator") return true;
//All user rights don't have the required right. No need to check group membership.
if (_currentUserRights.All(right => right != _requiredRight)) return false;
if (_cloneDeployUser.GroupManagementEnabled == 1)
{
var computers = new ComputerServices().SearchComputersForUser(_cloneDeployUser.Id, int.MaxValue);
return computers.Any(x => x.Id == computerId);
}
return IsAuthorized();
}
public bool GroupManagement(int groupId)
{
if (_cloneDeployUser.Membership == "Administrator") return true;
//All user rights don't have the required right. No need to check group membership.
if (_currentUserRights.All(right => right != _requiredRight)) return false;
if (_cloneDeployUser.GroupManagementEnabled == 1)
{
return new GroupServices().SearchGroupsForUser(_cloneDeployUser.Id).Any(x => x.Id == groupId);
}
return IsAuthorized();
}
public bool ImageManagement(int imageId)
{
if (_cloneDeployUser.Membership == "Administrator") return true;
//All user rights don't have the required right. No need to check group membership.
if (_currentUserRights.All(right => right != _requiredRight)) return false;
if (_cloneDeployUser.ImageManagementEnabled == 1)
{
return new ImageServices().SearchImagesForUser(_cloneDeployUser.Id).Any(x => x.Id == imageId);
}
return IsAuthorized();
}
public bool IsAuthorized()
{
if (_cloneDeployUser.Membership == "Administrator") return true;
if (_cloneDeployUser.Membership == "Service Account" && _requiredRight == "ServiceAccount") return true;
return _currentUserRights.Any(right => right == _requiredRight);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using MODEL.SYSTEM;
/// <summary>
/// BaseDataHandler 的摘要说明
/// </summary>
public abstract class BaseDataHandler : IHttpHandler, IRequiresSessionState
{
#region 当前登录人
public LoginModel user;
#endregion
public bool IsReusable
{
get
{
return false;
}
}
public void ProcessRequest(HttpContext context)
{
user = Common.CacheHelper.Get<LoginModel>(context.Session["UserID"].ToString());
DealBussiness(context);
}
/// <summary>
/// 处理具体业务逻辑,有派生类重写实现
/// </summary>
/// <param name="context"></param>
public abstract void DealBussiness(HttpContext context);
} |
using System.Collections.Specialized;
using System.Data;
namespace MyWeb
{
public class database
{
private string TABLENAME = "";
public database(string tablename)
{
TABLENAME = tablename;
}
public void dealSearch(string strField, string option, string strInput, ref string strWhere, ref string urlParam)
{
string strFieldValue = MyWeb.Common.GetParam(strInput, "").ToString();
if (!string.IsNullOrEmpty(strFieldValue))
{
if (!string.IsNullOrEmpty(strWhere))
{
strWhere += " And ";
}
if (strInput.StartsWith("int_"))
{
strWhere = strField + "=" + strInput;
}
else
{
if (option == "like")
{
strWhere = strField + " like '%" + strInput + "%'";
}
else
{
strWhere = strField + " = '" + strInput + "'";
}
}
}
}
public DataRow gets(string strWhere)
{
string Sql = "select top 1 * from " + TABLENAME + " where " + strWhere;
DataTable dt = Scaler.DataBase.DataBase.GetRecords(Sql, 0, 0);
if (dt!=null && dt.Rows.Count>0)
{
return dt.Rows[0];
}
return null;
}
public DataRow get(string id)
{
return gets("id=" + id);
}
public bool save(NameValueCollection nv, string primarykey)
{
if (string.IsNullOrEmpty(nv[primarykey].Trim())) //添加
{
nv.Remove(primarykey);
string Sql = MyWeb.MyForm.GetInsertSQL(TABLENAME, nv);
if (Scaler.DataBase.DataBase.ExecuteSql(Sql) > 0)
{
return true;
}
else
{
return false;
}
}
else
{
string primaryvalue = nv[primarykey];
nv.Remove(primarykey);
string Sql = MyWeb.MyForm.GetUpdateSQL(TABLENAME, nv, primarykey + "=" + primaryvalue);
if (Scaler.DataBase.DataBase.ExecuteSql(Sql) > 0)
{
return true;
}
else
{
return false;
}
}
}
public bool dels(string strWhere)
{
string Sql = "delete from " + TABLENAME + " where " + strWhere;
if (Scaler.DataBase.DataBase.ExecuteSql(Sql) > 0)
return true;
return false;
}
public bool del(string id)
{
return dels("id=" + id);
}
public Module.Records list(string Sql, int PageSize)
{
Module.Records record = new Module.Records();
if (PageSize == 0) //显示全部
{
record.list = Scaler.DataBase.DataBase.GetRecords(Sql, 0, 0);
return record;
}
int page = int.Parse(MyWeb.Common.GetParam("page", "1").ToString());
page = page < 1 ? 1 : page;
record.list = Scaler.DataBase.DataBase.GetRecords(Sql, PageSize, page - 1);
int iCount = int.Parse(Scaler.DataBase.DataBase.GetValue(MyWeb.Common.getCountSQL(Sql)).ToString());
record.iCount = iCount;
record.iPage = page;
return record;
}
public Module.Records list(int PageSize, string strOrder)
{
string sql = "select * from " + TABLENAME + strOrder;
return list(sql, PageSize);
}
public Module.Records list(int PageSize)
{
string sql = "select * from " + TABLENAME;
return list(sql, PageSize);
}
public Module.Records list()
{
return list(0, "");
}
}
} |
using System;
namespace ShCore.Caching.CacheType.WebCache
{
/// <summary>
/// Thông báo cho phương thức là thực hiện cache thông thường của dot net
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public class CacheWebMethodInfoAttribute : CacheMethodInfoBaseAttribute
{
}
}
|
using System;
namespace PadawansTask6
{
public static class NumberFinder
{
public static int? NextBiggerThan(int number)
{
if (number <= 0)
{
throw new ArgumentException();
}
else
{
if (number == int.MaxValue)
{
return null;
}
char[] l = number.ToString().ToCharArray();
Array.Sort(l);
char[] lr = new char[l.Length];
lr = (char[])l.Clone();
Array.Reverse(lr);
string g = new string(lr);
int g1 = Convert.ToInt32(g);
checked
{
for (int i = number + 1; i <= g1; i++)
{
char[] ch = i.ToString().ToCharArray();
Array.Sort(ch);
if (CharArrayCompare(l, ch))
{
return i;
}
}
return null;
}
}
}
private static bool CharArrayCompare(char[] charLeft, char[] charRight)
{
if (charLeft.Length != charRight.Length)
return false;
var length = charLeft.Length;
for (int i = 0; i < length; i++)
{
if (charLeft[i] != charRight[i])
return false;
}
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace OMIKAS
{
public partial class MainMenuSliderForm : ContentPage
{
/// <summary>
/// Konstruktor okna z menu glownym aplikacji
/// </summary>
public MainMenuSliderForm()
{
InitializeComponent();
}
/// <summary>
/// Wciskając przycisk, push modal okno z profilem
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void btn_profile_Clicked(object sender, EventArgs e)
{
await Navigation.PushModalAsync(new NavigationPage(new ProfileForm()));
}
/// <summary>
/// Wciskajac przycisk push modal okno z skladnikami stopowymi
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void btn_alloy_Clicked(object sender, EventArgs e)
{
await Navigation.PushModalAsync(new NavigationPage(new AlloyAllForm()));
}
/// <summary>
/// Wciskajac przycisk push modal okno z wytopami
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void btn_smelts_Clicked(object sender, EventArgs e)
{
await Navigation.PushModalAsync(new NavigationPage(new SmeltAllForm()));
}
/// <summary>
/// Wciskajac przycisk push modal okno z ustawieniami
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void btn_settings_Clicked(object sender, EventArgs e)
{
await Navigation.PushModalAsync(new NavigationPage(new SetTabbForm()));
}
/// <summary>
/// Wciskajac przycisk push modal okno do obliczen
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void btn_calc_Clicked(object sender, EventArgs e)
{
await Navigation.PushModalAsync(new NavigationPage(new ProcessChooseForm()));
}
/// <summary>
/// Za kazdym razem kiedy pojawia się ekran sprawdź czy listy stopow i wytopow nie sa puste i dopiero wtedy zezwól na obliczenia
/// </summary>
protected override void OnAppearing()
{
//pobieram z bazy sqlite wszystkie stopy i wytopy do list
App.alloymetals = App.DAUtil.GetAllAlloys();
App.smeltals = App.DAUtil.GetAllSmelts();
//jesli ktoras pusta to zabron obliczen
if(!App.alloymetals.Any() || !App.smeltals.Any())
{
btn_calc.IsEnabled = false;
}
else
btn_calc.IsEnabled = true;
base.OnAppearing();
}
}
}
|
using HCL.Academy.Model;
//using Microsoft.WindowsAzure.Storage;
//using Microsoft.WindowsAzure.Storage.Table;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace HCLAcademy.Util
{
public class AzureStorageTableOperations
{
//CloudStorageAccount storageAccount;
//CloudTableClient tableClient;
private string tableName;
public AzureStorageTableOperations(StorageOperations operation)
{
try
{
var connStr = System.Configuration.ConfigurationManager.AppSettings["StorageConStr"].ToString();
storageAccount = CloudStorageAccount.Parse(connStr);
tableClient = storageAccount.CreateCloudTableClient();
if(operation == StorageOperations.Logging)
{
tableName = AppConstant.StorageTableLogs;
CloudTable table = tableClient.GetTableReference(tableName);
table.CreateIfNotExists();
}
}
catch (Exception ex)
{
//LogHelper.AddLog(new LogEntity(Constants.PARTITION_ERRORLOG, "SYSTEM", ApplicationModules.COMMON_STORAGEDAL, ex.Message, ex.StackTrace));
}
}
public void AddEntity(TableEntity entity, string partitionName)
{
try
{
CloudTable table;
Guid g;
g = Guid.NewGuid();
entity.RowKey = g.ToString();
entity.PartitionKey = partitionName;
table = tableClient.GetTableReference(this.tableName);
TableOperation insertOperation = TableOperation.Insert(entity);
table.Execute(insertOperation);
}
catch (Exception ex)
{
UserManager user = (UserManager)HttpContext.Current.Session["CurrentUser"];
LogHelper.AddLog(new LogEntity(AppConstant.PartitionError, user.EmailID.ToString(), AppConstant.ApplicationName, "Class:Method", ex.Message, ex.StackTrace));
}
}
public void AddEntity(TableEntity entity)
{
// try
// {
CloudTable table;
Random rnd = new Random();
Guid g;
g = Guid.NewGuid();
entity.RowKey = g.ToString();
table = tableClient.GetTableReference(this.tableName);
TableOperation insertOperation = TableOperation.Insert(entity);
table.Execute(insertOperation);
// }
// catch (Exception ex)
// {
// LogHelper.AddLog(new LogEntity(Constants.PARTITION_ERRORLOG, "SYSTEM", ApplicationModules.COMMON_STORAGEDAL, ex.Message, ex.StackTrace));
// }
}
public void EditEntity(TableEntity entity)
{
try
{
CloudTable table = tableClient.GetTableReference(tableName);
TableOperation insertOrReplaceOperation = TableOperation.InsertOrReplace(entity);
table.Execute(insertOrReplaceOperation);
}
catch (Exception ex)
{
//LogHelper.AddLog(new LogEntity(Constants.PARTITION_ERRORLOG, "SYSTEM", ApplicationModules.COMMON_STORAGEDAL, ex.Message, ex.StackTrace));
}
}
public void DeleteEntity(TableEntity entity)
{
try
{
CloudTable table = tableClient.GetTableReference(tableName);
TableOperation deleteOperation = TableOperation.Delete(entity);
table.Execute(deleteOperation);
}
catch (Exception ex)
{
//LogHelper.AddLog(new LogEntity(Constants.PARTITION_ERRORLOG, "SYSTEM", ApplicationModules.COMMON_STORAGEDAL, ex.Message, ex.StackTrace));
}
}
public List<T> GetEntities<T>(string partitionKey, Dictionary<string, string> propertyFilters) where T : TableEntity, new()
{
List<T> results = new List<T>();
try
{
var table = tableClient.GetTableReference(this.tableName);
var pkFilter = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey);
var combinedFilter = pkFilter;
foreach (var properties in propertyFilters)
{
var newFilter = TableQuery.GenerateFilterCondition(properties.Key, QueryComparisons.Equal, properties.Value);
combinedFilter = TableQuery.CombineFilters(combinedFilter, TableOperators.And, newFilter);
}
var query = new TableQuery<T>().Where(combinedFilter);
results = table.ExecuteQuery(query).ToList();
}
catch (Exception ex)
{
//LogHelper.AddLog(new LogEntity(Constants.PARTITION_ERRORLOG, "SYSTEM", ApplicationModules.COMMON_STORAGEDAL, ex.Message, ex.StackTrace));
}
return results;
}
public List<T> GetEntities<T>(string partitionKey) where T : TableEntity, new()
{
List<T> results = new List<T>();
try
{
var table = tableClient.GetTableReference(this.tableName);
var pkFilter = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey);
var query = new TableQuery<T>().Where(pkFilter);
results = table.ExecuteQuery(query).ToList();
}
catch (Exception ex)
{
//LogHelper.AddLog(new LogEntity(Constants.PARTITION_ERRORLOG, "SYSTEM", ApplicationModules.COMMON_STORAGEDAL, ex.Message, ex.StackTrace));
}
return results;
}
//public string GetStorageTable(string partitionKey)
//{
// string tblName = string.Empty;
// /*if (partitionKey == Constants.PARTITION_ERRORLOG || partitionKey == Constants.PARTITION_INFORMATIONLOG || partitionKey == Constants.PARTITION_WARNINGLOG)
// tblName = Constants.LOGTABLENAME;
// else if (partitionKey == Constants.PARTITION_MULTIBRAININFOLOG || partitionKey == Constants.PARTITION_MULTIBRAINERRORLOG)
// tblName = Constants.MULTIBRAINLOGTABLE;
// else*/
// tblName = AppConstant.StorageTableName;
// return tblName;
//}
public object GetEntity<T>(string partitionKey, string rowKey) where T : TableEntity, new()
{
try
{
CloudTable table = tableClient.GetTableReference(this.tableName);
TableOperation tableOperation = null;
tableOperation = TableOperation.Retrieve<T>(partitionKey, rowKey);
return table.Execute(tableOperation).Result;
}
catch (Exception ex)
{
//LogHelper.AddLog(new LogEntity(Constants.PARTITION_ERRORLOG, "SYSTEM", ApplicationModules.COMMON_STORAGEDAL, ex.Message, ex.StackTrace));
return null;
}
}
public List<T> GetEntities<T>(string strFilter, string strFilterValue) where T : TableEntity, new()
{
try
{
//string tblName = AppConstant.StorageTableName;
//if (strFilter == "PartitionKey")
//{
// tblName = GetStorageTable(strFilterValue);
//}
var table = tableClient.GetTableReference(tableName);
var exQuery = new TableQuery<T>().Where(TableQuery.GenerateFilterCondition(strFilter, QueryComparisons.Equal, strFilterValue));
var results = table.ExecuteQuery(exQuery).Select(ent => (T)ent).ToList();
return results;
}
catch (StorageException ex)
{
//LogHelper.AddLog(new LogEntity(Constants.PARTITION_ERRORLOG, "SYSTEM", ApplicationModules.COMMON_STORAGEDAL, ex.Message, ex.StackTrace));
return null;
}
}
public List<T> GetEntities<T>(string partitionValue, string strFilter, string strFilterValue) where T : TableEntity, new()
{
try
{
var table = tableClient.GetTableReference(tableName);
var Q1 = new TableQuery<T>().Where(TableQuery.CombineFilters(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionValue),
TableOperators.And,
TableQuery.GenerateFilterCondition(strFilter, QueryComparisons.Equal, strFilterValue)));
var results = table.ExecuteQuery(Q1).Select(ent => (T)ent).ToList();
return results;
}
catch (StorageException ex)
{
//LogHelper.AddLog(new LogEntity(Constants.PARTITION_ERRORLOG, "SYSTEM", ApplicationModules.COMMON_STORAGEDAL, ex.Message, ex.StackTrace));
return null;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FlashSales.API;
namespace FlashSales.Farmers
{
public partial class NewProduct : System.Web.UI.Page
{
API.FlashSalesServiceClient cliente = new FlashSalesServiceClient();
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack==false)
{
CargarTipos();
CargarUnidades();
}
}
private void CargarTipos()
{
ddlTipo.DataSource = cliente.Tipos();
ddlTipo.DataTextField = "Nombre";
ddlTipo.DataValueField = "ID";
ddlTipo.DataBind();
}
private void CargarUnidades()
{
ddlUnidad.DataSource = cliente.Unidades();
ddlUnidad.DataTextField = "Nombre";
ddlUnidad.DataValueField = "ID";
ddlUnidad.DataBind();
}
}
} |
namespace NDDDSample.Tests.Domain.Model.Voyages
{
#region Usings
using NUnit.Framework;
#endregion
[TestFixture, Category(UnitTestCategories.DomainModel)]
[Ignore("Implement tests for this class")]
public class VoyageTest
{
[Test]
public void TestVoyageNumber()
{
//TODO: Test goes here...
}
[Test]
public void TestSchedule()
{
//TODO: Test goes here...
}
[Test]
public void TestHashCode()
{
//TODO: Test goes here...
}
[Test]
public void TestEquals()
{
//TODO: Test goes here...
}
[Test]
public void TestSameIdentityAs()
{
//TODO: Test goes here...
}
[Test]
public void TestToString()
{
//TODO: Test goes here...
}
[Test]
public void TestAddMovement()
{
//TODO: Test goes here...
}
[Test]
public void TestBuild()
{
//TODO: Test goes here...
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DomainModels.Layer;
namespace Repository.Layer
{
public interface IMarkaNaVoziloRepository
{
void InsertModel(MarkaNaVozilo mv);
void UpdateModel(MarkaNaVozilo mv);
void DeleteModel(int mid);
List<MarkaNaVozilo> GetModels();
List<MarkaNaVozilo> GetModelsByModelId(int ModelId);
}
public class MarkaNaVoziloRepository : IMarkaNaVoziloRepository
{
readonly StoredVehiclesDatabaseDbContext dbcontext;
public MarkaNaVoziloRepository()
{
dbcontext = new StoredVehiclesDatabaseDbContext();
}
public void InsertModel (MarkaNaVozilo mv)
{
dbcontext.MarkaNaVozilo.Add(mv);
dbcontext.SaveChanges();
}
public void UpdateModel (MarkaNaVozilo mv)
{
MarkaNaVozilo mvo = dbcontext.MarkaNaVozilo.Where(m => m.ModelId == m.ModelId).FirstOrDefault();
if(mvo != null)
{
mvo.ModelName = mv.ModelName;
dbcontext.SaveChanges();
}
}
public void DeleteModel (int dim)
{
MarkaNaVozilo mv = dbcontext.MarkaNaVozilo.Where(m => m.ModelId == dim).FirstOrDefault();
if (mv != null)
{
dbcontext.MarkaNaVozilo.Remove(mv);
dbcontext.SaveChanges();
}
}
public List<MarkaNaVozilo> GetModels()
{
List<MarkaNaVozilo> mv = dbcontext.MarkaNaVozilo.ToList();
return mv;
}
public List<MarkaNaVozilo> GetModelsByModelId(int ModelId)
{
List<MarkaNaVozilo> mv = dbcontext.MarkaNaVozilo.Where(m => m.ModelId == ModelId).ToList();
return mv;
}
}
}
|
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Амперия
{
public partial class cal : Form
{
private MySqlDataAdapter dataAdapter = null;
private DataSet dataSet = null;
DB db = new DB();
public cal()
{
InitializeComponent();
}
private void ReolaData()
{
try
{
dataAdapter = new MySqlDataAdapter("SELECT `id_dish` AS `Номер блюда`, `dish_name` AS `Название` FROM `dish`", db.GetConnection());
dataSet = new DataSet();
dataAdapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.Tables[0];
}
//СООБЩЕНИЕ ОБ ОШИБКЕ
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public string id;
private void dataGridView1_Click(object sender, EventArgs e)
{
int i = dataGridView1.CurrentCell.RowIndex;
id = dataGridView1.Rows[i].Cells[0].Value.ToString();
string name = dataGridView1.Rows[i].Cells[1].Value.ToString();
string Sql = ("SELECT product.id_product AS'Номер продукта',product.product_name as 'Состав' ,recipe.amount_per_serving as 'На порцию' FROM product, recipe, dish WHERE recipe.dish_id = dish.id_dish and recipe.product_id = product.id_product AND dish.dish_name = '" + name + "'");
dataAdapter = new MySqlDataAdapter(Sql, db.GetConnection());
dataSet = new DataSet();
dataAdapter.Fill(dataSet);
dataGridView2.DataSource = dataSet.Tables[0];
}
private void cal_Load(object sender, EventArgs e)
{
ReolaData();
}
private void button4_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
int c = Convert.ToInt32(textBox1.Text);
int i = dataGridView1.CurrentCell.RowIndex;
id = dataGridView1.Rows[i].Cells[0].Value.ToString();
string name = dataGridView1.Rows[i].Cells[1].Value.ToString();
string Sql = ("SELECT product.id_product AS'Номер продукта', product.product_name as 'Состав' , (recipe.amount_per_serving *" + c + ") as 'На порцию' FROM product, recipe, dish WHERE recipe.dish_id = dish.id_dish and recipe.product_id = product.id_product AND dish.dish_name = '" + name + "'");
dataAdapter = new MySqlDataAdapter(Sql, db.GetConnection());
dataSet = new DataSet();
dataAdapter.Fill(dataSet);
dataGridView2.DataSource = dataSet.Tables[0];
}
else { MessageBox.Show("Введите количество порций"); }
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
int j= dataGridView1.CurrentCell.RowIndex;
string dish_id = dataGridView1.Rows[j].Cells[0].Value.ToString();
string c = textBox1.Text;
try
{
for (int i = 0; i < dataGridView2.RowCount; i++)
{
string id = dataGridView2.Rows[i].Cells[0].Value.ToString();
string Sql = ("UPDATE product set product.quantity = (product.quantity - (SELECT(recipe.amount_per_serving * " + c + ") FROM recipe WHERE recipe.dish_id=" + dish_id + " AND recipe.product_id = " + id + ")) WHERE product.id_product = " + id);
dataAdapter = new MySqlDataAdapter(Sql, db.GetConnection());
dataSet = new DataSet();
dataAdapter.Fill(dataSet);
}
MessageBox.Show("Продукты списаны со склада", "Успешно!");
}
catch (Exception)
{
MessageBox.Show("Недостаточно продуктов для приготовления", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("Введите количество порций");
}
}
private void button2_Click(object sender, EventArgs e)
{
dataGridView3.ColumnHeadersVisible = false;
dataGridView3.RowHeadersVisible = false;
if (textBox1.Text != "")
{
int i = dataGridView1.CurrentCell.RowIndex;
string dish_id = dataGridView1.Rows[i].Cells[0].Value.ToString();
string c = textBox1.Text;
try
{
string Sql = ("SELECT SUM(recipe.amount_per_serving * product.price)*"+c+" as 'стоимость' FROM recipe,product WHERE recipe.product_id = product.id_product AND recipe.dish_id ="+dish_id);
dataAdapter = new MySqlDataAdapter(Sql, db.GetConnection());
dataSet = new DataSet();
dataAdapter.Fill(dataSet);
dataGridView3.DataSource = dataSet.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("Введите количество порций");
}
}
private void button3_Click(object sender, EventArgs e)
{
dataGridView1.ClearSelection();
if (textBox2.Text != "")
{
//ПРОХОДИТ ПО ВСЕМ ЯЧЕЙКАМ И ИЩЕТ СОВПАДЕНИЕ
for (int i = 0; i < dataGridView1.RowCount; i++)
{
dataGridView1.Rows[i].Selected = false;
for (int j = 0; j < dataGridView1.ColumnCount; j++)
if (dataGridView1.Rows[i].Cells[j].Value != null)
if (dataGridView1.Rows[i].Cells[j].Value.ToString().Contains(textBox2.Text.ToLower()))
{
dataGridView1.Rows[i].Selected = true;
break;
}
}
int rowsCount = dataGridView2.Rows.Count;
for (int j = 0; j < rowsCount; j++)
{
dataGridView2.Rows.Remove(dataGridView2.Rows[0]);
}
}
}
}
}
|
namespace Triton.Game.Mapping
{
using ns25;
using ns26;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Triton.Game;
using Triton.Game.Mono;
[Attribute38("CollectionManager")]
public class CollectionManager : MonoClass
{
public CollectionManager(IntPtr address) : this(address, "CollectionManager")
{
}
public CollectionManager(IntPtr address, string className) : base(address, className)
{
}
public void AddCardReward(CardRewardData cardReward, bool markAsNew)
{
object[] objArray1 = new object[] { cardReward, markAsNew };
base.method_8("AddCardReward", objArray1);
}
public CollectibleCard AddCounts(NetCache.CardStack netStack, EntityDef entityDef)
{
Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.Class, Class272.Enum20.Class };
object[] objArray1 = new object[] { netStack, entityDef };
return base.method_15<CollectibleCard>("AddCounts", enumArray1, objArray1);
}
public CollectibleCard AddCounts(EntityDef entityDef, string cardID, TAG_PREMIUM premium, DateTime insertDate, int count, int numSeen)
{
object[] objArray1 = new object[] { entityDef, cardID, premium, insertDate, count, numSeen };
return base.method_15<CollectibleCard>("AddCounts", new Class272.Enum20[] { Class272.Enum20.Class }, objArray1);
}
public CollectionDeck AddDeck(NetCache.DeckHeader deckHeader)
{
Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.Class };
object[] objArray1 = new object[] { deckHeader };
return base.method_15<CollectionDeck>("AddDeck", enumArray1, objArray1);
}
public CollectionDeck AddDeck(NetCache.DeckHeader deckHeader, bool updateNetCache)
{
Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.Class, Class272.Enum20.Boolean };
object[] objArray1 = new object[] { deckHeader, updateNetCache };
return base.method_15<CollectionDeck>("AddDeck", enumArray1, objArray1);
}
public void AddPreconDeck(TAG_CLASS heroClass, long deckID)
{
object[] objArray1 = new object[] { heroClass, deckID };
base.method_8("AddPreconDeck", objArray1);
}
public void AddPreconDeckFromNotice(NetCache.ProfileNoticePreconDeck preconDeckNotice)
{
object[] objArray1 = new object[] { preconDeckNotice };
base.method_8("AddPreconDeckFromNotice", objArray1);
}
public string AutoGenerateDeckName(TAG_CLASS classTag)
{
object[] objArray1 = new object[] { classTag };
return base.method_13("AutoGenerateDeckName", objArray1);
}
public void ClearTaggedDeck(DeckTag tag)
{
object[] objArray1 = new object[] { tag };
base.method_8("ClearTaggedDeck", objArray1);
}
public void DoneEditing()
{
base.method_8("DoneEditing", Array.Empty<object>());
}
public int EntityDefSortComparison(EntityDef entityDef1, EntityDef entityDef2)
{
object[] objArray1 = new object[] { entityDef1, entityDef2 };
return base.method_11<int>("EntityDefSortComparison", objArray1);
}
public void FireAllDeckContentsEvent()
{
base.method_8("FireAllDeckContentsEvent", Array.Empty<object>());
}
public void FireDeckContentsEvent(long id)
{
object[] objArray1 = new object[] { id };
base.method_8("FireDeckContentsEvent", objArray1);
}
public static CollectionManager Get()
{
return MonoClass.smethod_15<CollectionManager>(TritonHs.MainAssemblyPath, "", "CollectionManager", "Get", Array.Empty<object>());
}
public List<CollectibleCard> GetAllCards()
{
Class267<CollectibleCard> class2 = base.method_14<Class267<CollectibleCard>>("GetAllCards", Array.Empty<object>());
if (class2 != null)
{
return class2.method_25();
}
return null;
}
public CollectionDeck GetBaseDeck(long id)
{
object[] objArray1 = new object[] { id };
return base.method_14<CollectionDeck>("GetBaseDeck", objArray1);
}
public int GetBasicCardsIOwn(TAG_CLASS cardClass)
{
object[] objArray1 = new object[] { cardClass };
return base.method_11<int>("GetBasicCardsIOwn", objArray1);
}
public TAG_PREMIUM GetBestCardPremium(string cardID)
{
object[] objArray1 = new object[] { cardID };
return base.method_11<TAG_PREMIUM>("GetBestCardPremium", objArray1);
}
public List<CollectibleCard> GetBestHeroesIOwn(TAG_CLASS heroClass)
{
object[] objArray1 = new object[] { heroClass };
Class267<CollectibleCard> class2 = base.method_14<Class267<CollectibleCard>>("GetBestHeroesIOwn", objArray1);
if (class2 != null)
{
return class2.method_25();
}
return null;
}
public CollectibleCard GetCard(string cardID, TAG_PREMIUM premium)
{
object[] objArray1 = new object[] { cardID, premium };
return base.method_14<CollectibleCard>("GetCard", objArray1);
}
public int GetCardsToDisenchantCount()
{
return base.method_11<int>("GetCardsToDisenchantCount", Array.Empty<object>());
}
public int GetCardTypeSortOrder(EntityDef entityDef)
{
object[] objArray1 = new object[] { entityDef };
return base.method_11<int>("GetCardTypeSortOrder", objArray1);
}
public CollectionDeck GetDeck(long id)
{
object[] objArray1 = new object[] { id };
return base.method_14<CollectionDeck>("GetDeck", objArray1);
}
public DeckBuilder GetDeckBuilder()
{
return base.method_14<DeckBuilder>("GetDeckBuilder", Array.Empty<object>());
}
public List<CollectionDeck> GetDecks(DeckType deckType)
{
Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.ValueType };
object[] objArray1 = new object[] { deckType };
Class267<CollectionDeck> class2 = base.method_15<Class267<CollectionDeck>>("GetDecks", enumArray1, objArray1);
if (class2 != null)
{
return class2.method_25();
}
return null;
}
public int GetDeckSize()
{
return base.method_11<int>("GetDeckSize", Array.Empty<object>());
}
public List<CollectionDeck> GetDecksWithClass(TAG_CLASS classType, DeckType deckType)
{
object[] objArray1 = new object[] { classType, deckType };
Class267<CollectionDeck> class2 = base.method_14<Class267<CollectionDeck>>("GetDecksWithClass", objArray1);
if (class2 != null)
{
return class2.method_25();
}
return null;
}
public List<TAG_CARD_SET> GetDisplayableCardSets()
{
Class266<TAG_CARD_SET> class2 = base.method_14<Class266<TAG_CARD_SET>>("GetDisplayableCardSets", Array.Empty<object>());
if (class2 != null)
{
return class2.method_25();
}
return null;
}
public CollectionDeck GetEditedDeck()
{
return base.method_14<CollectionDeck>("GetEditedDeck", Array.Empty<object>());
}
public NetCache.CardDefinition GetFavoriteHero(TAG_CLASS heroClass)
{
object[] objArray1 = new object[] { heroClass };
return base.method_14<NetCache.CardDefinition>("GetFavoriteHero", objArray1);
}
public List<CollectibleCard> GetHeroesIOwn(TAG_CLASS heroClass)
{
object[] objArray1 = new object[] { heroClass };
Class267<CollectibleCard> class2 = base.method_14<Class267<CollectibleCard>>("GetHeroesIOwn", objArray1);
if (class2 != null)
{
return class2.method_25();
}
return null;
}
public List<CollectibleCard> GetMassDisenchantCards()
{
Class267<CollectibleCard> class2 = base.method_14<Class267<CollectibleCard>>("GetMassDisenchantCards", Array.Empty<object>());
if (class2 != null)
{
return class2.method_25();
}
return null;
}
public int GetNumCopiesInCollection(string cardID, TAG_PREMIUM premium)
{
object[] objArray1 = new object[] { cardID, premium };
return base.method_11<int>("GetNumCopiesInCollection", objArray1);
}
public List<CollectibleCard> GetOwnedCards()
{
Class267<CollectibleCard> class2 = base.method_14<Class267<CollectibleCard>>("GetOwnedCards", Array.Empty<object>());
if (class2 != null)
{
return class2.method_25();
}
return null;
}
public PreconDeck GetPreconDeck(TAG_CLASS heroClass)
{
object[] objArray1 = new object[] { heroClass };
return base.method_14<PreconDeck>("GetPreconDeck", objArray1);
}
public CollectionDeck GetTaggedDeck(DeckTag tag)
{
object[] objArray1 = new object[] { tag };
return base.method_14<CollectionDeck>("GetTaggedDeck", objArray1);
}
public List<TemplateDeck> GetTemplateDecks(TAG_CLASS classType)
{
object[] objArray1 = new object[] { classType };
Class267<TemplateDeck> class2 = base.method_14<Class267<TemplateDeck>>("GetTemplateDecks", objArray1);
if (class2 != null)
{
return class2.method_25();
}
return null;
}
public string GetVanillaHeroCardID(EntityDef HeroSkinEntityDef)
{
object[] objArray1 = new object[] { HeroSkinEntityDef };
return base.method_13("GetVanillaHeroCardID", objArray1);
}
public string GetVanillaHeroCardIDFromClass(TAG_CLASS heroClass)
{
object[] objArray1 = new object[] { heroClass };
return base.method_13("GetVanillaHeroCardIDFromClass", objArray1);
}
public bool HasVisitedCollection()
{
return base.method_11<bool>("HasVisitedCollection", Array.Empty<object>());
}
public static void Init()
{
MonoClass.smethod_17(TritonHs.MainAssemblyPath, "", "CollectionManager", "Init");
}
public void InitImpl()
{
base.method_8("InitImpl", Array.Empty<object>());
}
public void InsertNewCollectionCard(string cardID, TAG_PREMIUM premium, DateTime insertDate, int count, bool seenBefore)
{
object[] objArray1 = new object[] { cardID, premium, insertDate, count, seenBefore };
base.method_8("InsertNewCollectionCard", objArray1);
}
public bool IsCardInCollection(string cardID, TAG_PREMIUM premium)
{
object[] objArray1 = new object[] { cardID, premium };
return base.method_11<bool>("IsCardInCollection", objArray1);
}
public bool IsDeckNameTaken(string name)
{
object[] objArray1 = new object[] { name };
return base.method_11<bool>("IsDeckNameTaken", objArray1);
}
public bool IsFullyLoaded()
{
return base.method_11<bool>("IsFullyLoaded", Array.Empty<object>());
}
public bool IsInEditMode()
{
return base.method_11<bool>("IsInEditMode", Array.Empty<object>());
}
public bool IsWaitingForBoxTransition()
{
return base.method_11<bool>("IsWaitingForBoxTransition", Array.Empty<object>());
}
public void LoadTemplateDecks()
{
base.method_8("LoadTemplateDecks", Array.Empty<object>());
}
public void MarkAllInstancesAsSeen(string cardID, TAG_PREMIUM premium)
{
object[] objArray1 = new object[] { cardID, premium };
base.method_8("MarkAllInstancesAsSeen", objArray1);
}
public void NetCache_OnDecksReceived()
{
base.method_8("NetCache_OnDecksReceived", Array.Empty<object>());
}
public void NetCache_OnFavoriteHeroesReceived()
{
base.method_8("NetCache_OnFavoriteHeroesReceived", Array.Empty<object>());
}
public void NotifyNetCacheOfNewCards(NetCache.CardDefinition cardDef, long insertDate, int count, bool seenBefore)
{
object[] objArray1 = new object[] { cardDef, insertDate, count, seenBefore };
base.method_8("NotifyNetCacheOfNewCards", objArray1);
}
public void NotifyNetCacheOfRemovedCards(NetCache.CardDefinition cardDef, int count)
{
object[] objArray1 = new object[] { cardDef, count };
base.method_8("NotifyNetCacheOfRemovedCards", objArray1);
}
public void NotifyOfBoxTransitionStart()
{
base.method_8("NotifyOfBoxTransitionStart", Array.Empty<object>());
}
public int NumCardsOwnedInSet(TAG_CARD_SET cardSet)
{
object[] objArray1 = new object[] { cardSet };
return base.method_11<int>("NumCardsOwnedInSet", objArray1);
}
public void OnActiveAchievesUpdated(object userData)
{
object[] objArray1 = new object[] { userData };
base.method_8("OnActiveAchievesUpdated", objArray1);
}
public void OnBoxTransitionFinished(object userData)
{
object[] objArray1 = new object[] { userData };
base.method_8("OnBoxTransitionFinished", objArray1);
}
public void OnCardRewardOpened(string cardID, TAG_PREMIUM premium, int count)
{
object[] objArray1 = new object[] { cardID, premium, count };
base.method_8("OnCardRewardOpened", objArray1);
}
public void OnCardSale()
{
base.method_8("OnCardSale", Array.Empty<object>());
}
public void OnCollectionChanged()
{
base.method_8("OnCollectionChanged", Array.Empty<object>());
}
public void OnDBAction()
{
base.method_8("OnDBAction", Array.Empty<object>());
}
public void OnDeck()
{
base.method_8("OnDeck", Array.Empty<object>());
}
public void OnDeckCreated()
{
base.method_8("OnDeckCreated", Array.Empty<object>());
}
public void OnDeckDeleted()
{
base.method_8("OnDeckDeleted", Array.Empty<object>());
}
public void OnDeckRenamed()
{
base.method_8("OnDeckRenamed", Array.Empty<object>());
}
public void OnDefaultCardBackSet()
{
base.method_8("OnDefaultCardBackSet", Array.Empty<object>());
}
public void OnMassDisenchantResponse()
{
base.method_8("OnMassDisenchantResponse", Array.Empty<object>());
}
public void OnNetCacheReady()
{
base.method_8("OnNetCacheReady", Array.Empty<object>());
}
public void OnSetFavoriteHeroResponse()
{
base.method_8("OnSetFavoriteHeroResponse", Array.Empty<object>());
}
public CollectibleCard RegisterCard(EntityDef entityDef, string cardID, TAG_PREMIUM premium)
{
object[] objArray1 = new object[] { entityDef, cardID, premium };
return base.method_14<CollectibleCard>("RegisterCard", objArray1);
}
public void RegisterCollectionNetHandlers()
{
base.method_8("RegisterCollectionNetHandlers", Array.Empty<object>());
}
public void RemoveCollectionCard(string cardID, TAG_PREMIUM premium, int count)
{
object[] objArray1 = new object[] { cardID, premium, count };
base.method_8("RemoveCollectionCard", objArray1);
}
public void RemoveCollectionNetHandlers()
{
base.method_8("RemoveCollectionNetHandlers", Array.Empty<object>());
}
public void RemoveDeck(long id)
{
object[] objArray1 = new object[] { id };
base.method_8("RemoveDeck", objArray1);
}
public void RequestDeckContents(long id)
{
object[] objArray1 = new object[] { id };
base.method_8("RequestDeckContents", objArray1);
}
public void SendCreateDeck(DeckType deckType, string name, string heroCardID)
{
object[] objArray1 = new object[] { deckType, name, heroCardID };
base.method_8("SendCreateDeck", objArray1);
}
public void SendDeleteDeck(long id)
{
object[] objArray1 = new object[] { id };
base.method_8("SendDeleteDeck", objArray1);
}
public void SetDeckBuilder(DeckBuilder deckBuilder)
{
object[] objArray1 = new object[] { deckBuilder };
base.method_8("SetDeckBuilder", objArray1);
}
public void SetHasVisitedCollection(bool enable)
{
object[] objArray1 = new object[] { enable };
base.method_8("SetHasVisitedCollection", objArray1);
}
public void SetShowDeckTemplatePageForClass(TAG_CLASS classType, bool show)
{
object[] objArray1 = new object[] { classType, show };
base.method_8("SetShowDeckTemplatePageForClass", objArray1);
}
public CollectionDeck SetTaggedDeck(DeckTag tag, long deckId, object callbackData)
{
object[] objArray1 = new object[] { tag, deckId, callbackData };
return base.method_15<CollectionDeck>("SetTaggedDeck", new Class272.Enum20[] { Class272.Enum20.ValueType }, objArray1);
}
public void SetTaggedDeck(DeckTag tag, CollectionDeck deck, object callbackData)
{
object[] objArray1 = new object[] { tag, deck, callbackData };
base.method_9("SetTaggedDeck", new Class272.Enum20[] { Class272.Enum20.ValueType }, objArray1);
}
public bool ShouldShowDeckTemplatePageForClass(TAG_CLASS classType)
{
object[] objArray1 = new object[] { classType };
return base.method_11<bool>("ShouldShowDeckTemplatePageForClass", objArray1);
}
public CollectionDeck StartEditingDeck(DeckTag tag, long deckId, object callbackData)
{
object[] objArray1 = new object[] { tag, deckId, callbackData };
return base.method_14<CollectionDeck>("StartEditingDeck", objArray1);
}
public void UpdateCardCounts(NetCache.NetCacheCollection netCacheCards, NetCache.CardDefinition cardDef, int count, int newCount)
{
object[] objArray1 = new object[] { netCacheCards, cardDef, count, newCount };
base.method_8("UpdateCardCounts", objArray1);
}
public void UpdateCardsWithNetData()
{
base.method_8("UpdateCardsWithNetData", Array.Empty<object>());
}
public void UpdateDeckHeroArt(string heroCardID)
{
object[] objArray1 = new object[] { heroCardID };
base.method_8("UpdateDeckHeroArt", objArray1);
}
public void UpdateFavoriteHero(TAG_CLASS heroClass, string heroCardId, TAG_PREMIUM premium)
{
object[] objArray1 = new object[] { heroClass, heroCardId, premium };
base.method_8("UpdateFavoriteHero", objArray1);
}
public void UpdateShowAdvancedCMOption()
{
base.method_8("UpdateShowAdvancedCMOption", Array.Empty<object>());
}
public void WillReset()
{
base.method_8("WillReset", Array.Empty<object>());
}
public static int DEFAULT_MAX_INSTANCES_PER_DECK
{
get
{
return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "CollectionManager", "DEFAULT_MAX_INSTANCES_PER_DECK");
}
}
public bool m_cardStacksRegistered
{
get
{
return base.method_2<bool>("m_cardStacksRegistered");
}
}
public List<CollectibleCard> m_collectibleCards
{
get
{
Class267<CollectibleCard> class2 = base.method_3<Class267<CollectibleCard>>("m_collectibleCards");
if (class2 != null)
{
return class2.method_25();
}
return null;
}
}
public bool m_collectionLoaded
{
get
{
return base.method_2<bool>("m_collectionLoaded");
}
}
public DeckBuilder m_deckBuilder
{
get
{
return base.method_3<DeckBuilder>("m_deckBuilder");
}
}
public List<TAG_CARD_SET> m_displayableCardSets
{
get
{
Class266<TAG_CARD_SET> class2 = base.method_3<Class266<TAG_CARD_SET>>("m_displayableCardSets");
if (class2 != null)
{
return class2.method_25();
}
return null;
}
}
public bool m_editMode
{
get
{
return base.method_2<bool>("m_editMode");
}
}
public bool m_hasVisitedCollection
{
get
{
return base.method_2<bool>("m_hasVisitedCollection");
}
}
public bool m_unloading
{
get
{
return base.method_2<bool>("m_unloading");
}
}
public bool m_waitingForBoxTransition
{
get
{
return base.method_2<bool>("m_waitingForBoxTransition");
}
}
public static int MAX_DECKS_PER_PLAYER
{
get
{
return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "CollectionManager", "MAX_DECKS_PER_PLAYER");
}
}
public static int MAX_INSTANCES_PER_CARD_ID
{
get
{
return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "CollectionManager", "MAX_INSTANCES_PER_CARD_ID");
}
}
public static int MAX_INSTANCES_PER_ELITE_CARD_ID
{
get
{
return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "CollectionManager", "MAX_INSTANCES_PER_ELITE_CARD_ID");
}
}
public static int MAX_NUM_TEMPLATE_DECKS
{
get
{
return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "CollectionManager", "MAX_NUM_TEMPLATE_DECKS");
}
}
public static int NUM_BASIC_CARDS_PER_CLASS
{
get
{
return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "CollectionManager", "NUM_BASIC_CARDS_PER_CLASS");
}
}
public static int NUM_CARDS_GRANTED_POST_TUTORIAL
{
get
{
return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "CollectionManager", "NUM_CARDS_GRANTED_POST_TUTORIAL");
}
}
public static int NUM_CARDS_TO_UNLOCK_ADVANCED_CM
{
get
{
return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "CollectionManager", "NUM_CARDS_TO_UNLOCK_ADVANCED_CM");
}
}
public static int NUM_CLASS_CARDS_GRANTED_PER_CLASS_UNLOCK
{
get
{
return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "CollectionManager", "NUM_CLASS_CARDS_GRANTED_PER_CLASS_UNLOCK");
}
}
public static int NUM_CLASSES
{
get
{
return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "CollectionManager", "NUM_CLASSES");
}
}
public static int NUM_EXPERT_CARDS_TO_UNLOCK_CRAFTING
{
get
{
return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "CollectionManager", "NUM_EXPERT_CARDS_TO_UNLOCK_CRAFTING");
}
}
public static int NUM_EXPERT_CARDS_TO_UNLOCK_FORGE
{
get
{
return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "CollectionManager", "NUM_EXPERT_CARDS_TO_UNLOCK_FORGE");
}
}
[StructLayout(LayoutKind.Sequential)]
public struct CollectibleCardIndex
{
public string CardId;
public TAG_PREMIUM Premium;
}
[Attribute38("CollectionManager.DeckSort")]
public class DeckSort : MonoClass
{
public DeckSort(IntPtr address) : this(address, "DeckSort")
{
}
public DeckSort(IntPtr address, string className) : base(address, className)
{
}
public int Compare(CollectionDeck a, CollectionDeck b)
{
object[] objArray1 = new object[] { a, b };
return base.method_11<int>("Compare", objArray1);
}
}
public enum DeckTag
{
Editing,
Arena
}
[Attribute38("CollectionManager.PreconDeck")]
public class PreconDeck : MonoClass
{
public PreconDeck(IntPtr address) : this(address, "PreconDeck")
{
}
public PreconDeck(IntPtr address, string className) : base(address, className)
{
}
public long ID
{
get
{
return base.method_11<long>("get_ID", Array.Empty<object>());
}
}
public long m_id
{
get
{
return base.method_2<long>("m_id");
}
}
}
[Attribute38("CollectionManager.TemplateDeck")]
public class TemplateDeck : MonoClass
{
public TemplateDeck(IntPtr address) : this(address, "TemplateDeck")
{
}
public TemplateDeck(IntPtr address, string className) : base(address, className)
{
}
public TAG_CLASS m_class
{
get
{
return base.method_2<TAG_CLASS>("m_class");
}
}
public string m_description
{
get
{
return base.method_4("m_description");
}
}
public string m_displayTexture
{
get
{
return base.method_4("m_displayTexture");
}
}
public int m_id
{
get
{
return base.method_2<int>("m_id");
}
}
public int m_sortOrder
{
get
{
return base.method_2<int>("m_sortOrder");
}
}
public string m_title
{
get
{
return base.method_4("m_title");
}
}
}
}
}
|
namespace SGDE.Domain.Supervisor
{
#region Using
using System;
using System.Collections.Generic;
using Converters;
using Entities;
using SGDE.Domain.Helpers;
using ViewModels;
#endregion
public partial class Supervisor
{
public List<ClientViewModel> GetAllClientWithoutFilter()
{
return ClientConverter.ConvertList(_clientRepository.GetAllWithoutFilter());
}
public QueryResult<ClientViewModel> GetAllClient(int skip = 0, int take = 0, bool allClients = true, string filter = null)
{
var queryResult = _clientRepository.GetAll(skip, take, allClients, filter);
return new QueryResult<ClientViewModel>
{
Data = ClientConverter.ConvertList(queryResult.Data),
Count = queryResult.Count
};
}
public ClientViewModel GetClientById(int id)
{
var clientViewModel = ClientConverter.Convert(_clientRepository.GetById(id));
return clientViewModel;
}
public ClientViewModel AddClient(ClientViewModel newClientViewModel)
{
var client = new Client
{
AddedDate = DateTime.Now,
ModifiedDate = null,
IPAddress = newClientViewModel.iPAddress,
Name = newClientViewModel.name,
Cif = newClientViewModel.cif,
PhoneNumber = newClientViewModel.phoneNumber,
Address = newClientViewModel.address,
WayToPay = newClientViewModel.wayToPay,
ExpirationDays = newClientViewModel.expirationDays,
AccountNumber = newClientViewModel.accountNumber,
Email = newClientViewModel.email,
EmailInvoice = newClientViewModel.emailInvoice,
Active = newClientViewModel.active
};
_clientRepository.Add(client);
return newClientViewModel;
}
public bool UpdateClient(ClientViewModel clientViewModel)
{
if (clientViewModel.id == null)
return false;
var client = _clientRepository.GetById((int)clientViewModel.id);
if (client == null) return false;
client.ModifiedDate = DateTime.Now;
client.IPAddress = clientViewModel.iPAddress;
client.Name = clientViewModel.name;
client.Cif = clientViewModel.cif;
client.PhoneNumber = clientViewModel.phoneNumber;
client.Address = clientViewModel.address;
client.WayToPay = clientViewModel.wayToPay;
client.ExpirationDays = clientViewModel.expirationDays;
client.AccountNumber = clientViewModel.accountNumber;
client.Email = clientViewModel.email;
client.EmailInvoice = clientViewModel.emailInvoice;
client.Active = clientViewModel.active;
return _clientRepository.Update(client);
}
public bool DeleteClient(int id)
{
return _clientRepository.Delete(id);
}
public List<ClientViewModel> GetAllClientLite(string filter = null)
{
return ClientConverter.ConvertList(_clientRepository.GetAllLite(filter));
}
}
}
|
using System;
using System.Collections.Generic;
using UnityEngine;
namespace ProBuilder2.Common
{
[AddComponentMenu(""), ExecuteInEditMode]
public class pb_LineRenderer : MonoBehaviour
{
private HideFlags SceneCameraHideFlags = 13;
[HideInInspector]
private pb_ObjectPool<Mesh> pool = new pb_ObjectPool<Mesh>(1, 8, new Func<Mesh>(pb_LineRenderer.MeshConstructor), null);
[HideInInspector]
public List<Mesh> gizmos = new List<Mesh>();
[HideInInspector]
public Material mat;
private static Mesh MeshConstructor()
{
Mesh mesh = new Mesh();
mesh.set_hideFlags(pb_Constant.EDITOR_OBJECT_HIDE_FLAGS);
return mesh;
}
private void OnEnable()
{
this.mat = new Material(Shader.Find("ProBuilder/UnlitVertexColor"));
this.mat.set_name("pb_LineRenderer_Material");
this.mat.SetColor("_Color", Color.get_white());
this.mat.set_hideFlags(pb_Constant.EDITOR_OBJECT_HIDE_FLAGS);
}
public void AddLineSegments(Vector3[] segments, Color[] colors)
{
Mesh mesh = this.pool.Get();
mesh.Clear();
mesh.set_name("pb_LineRenderer::Mesh_" + mesh.GetInstanceID());
mesh.MarkDynamic();
int num = segments.Length;
int num2 = colors.Length;
mesh.set_vertices(segments);
int[] array = new int[num];
Color[] array2 = new Color[num];
int num3 = 0;
for (int i = 0; i < num; i++)
{
array[i] = i;
array2[i] = colors[num3 % num2];
if (i % 2 == 1)
{
num3++;
}
}
mesh.set_subMeshCount(1);
mesh.SetIndices(array, 3, 0);
mesh.set_uv(new Vector2[mesh.get_vertexCount()]);
mesh.set_colors(array2);
mesh.set_hideFlags(pb_Constant.EDITOR_OBJECT_HIDE_FLAGS);
this.gizmos.Add(mesh);
}
public void Clear()
{
for (int i = 0; i < this.gizmos.get_Count(); i++)
{
this.pool.Put(this.gizmos.get_Item(i));
}
this.gizmos.Clear();
}
private void OnDisable()
{
using (List<Mesh>.Enumerator enumerator = this.gizmos.GetEnumerator())
{
while (enumerator.MoveNext())
{
Mesh current = enumerator.get_Current();
if (current != null)
{
Object.DestroyImmediate(current);
}
}
}
Object.DestroyImmediate(this.mat);
this.pool.Empty();
}
private void OnRenderObject()
{
if ((Camera.get_current().get_gameObject().get_hideFlags() & this.SceneCameraHideFlags) != this.SceneCameraHideFlags || Camera.get_current().get_name() != "SceneCamera")
{
return;
}
this.mat.SetPass(0);
int num = 0;
while (num < this.gizmos.get_Count() && this.gizmos.get_Item(num) != null)
{
Graphics.DrawMeshNow(this.gizmos.get_Item(num), Vector3.get_zero(), Quaternion.get_identity(), 0);
num++;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using System.Web;
using System.Web.Mvc;
using EntityFramework.Extensions;
using SO.Urba.Models.ValueObjects;
using SO.Urba.DbContexts;
using SO.Urba.Managers;
using SO.Urba.Models.ViewModels;
using SO.Utility.Classes;
using SO.Utility.Models.ViewModels;
using SO.Utility;
using SO.Utility.Helpers;
using SO.Utility.Extensions;
namespace SO.Urba.Controllers
{
public class ContactInfoController : Controller
{
private ContactInfoManager contactInfoManager = new ContactInfoManager();
private CompanyManager companyManager = new CompanyManager();
//public ActionResult Index(SO.Urba.Models.ViewModels.ContactInfoSearchFilterVm input = null, Paging paging = null)
//{
// if (input == null) input = new ContactInfoSearchFilterVm();
// input.paging = paging;
// if (this.ModelState.IsValid)
// {
// if (input.submitButton != null)
// input.paging.pageNumber = 1;
// input = contactInfoManager.search(input);
// return View(input);
// }
// return View(input);
//}
public ActionResult Index(SearchFilterVm input = null, Paging paging = null)
{
if (input == null) input = new SearchFilterVm();
input.paging = paging;
if (this.ModelState.IsValid)
{
if (input.submitButton != null)
input.paging.pageNumber = 1;
input = contactInfoManager.search(input);
return View(input);
}
return View(input);
}
public FileResult Export(SearchFilterVm input = null)
{
if (this.ModelState.IsValid)
{
input.paging = null;
input = contactInfoManager.search(input);
var file = ImportExportHelper.exportToCsv(input.result);
return File(file.FullName, "Application/octet-stream", file.Name);
}
return null;
}
#region CRUD
public ActionResult List()
{
var results = contactInfoManager.getAll(null);
return PartialView(results);
}
[HttpPost]
public ActionResult Edit(int id, ContactInfoVo input)
{
if (this.ModelState.IsValid)
{
var res = contactInfoManager.update(input, id);
return RedirectToAction("Index");
}
return View(input);
}
public ActionResult Edit(int id)
{
var result = contactInfoManager.get(id);
return View(result);
}
[HttpPost]
public ActionResult Create(SO.Urba.Models.ViewModels.ContactInfoVm input)
{
if (this.ModelState.IsValid)
{
var res = contactInfoManager.insert(input);
return RedirectToAction("Index");
}
return View(input);
}
public ActionResult Create()
{
//var vo = new ContactInfoVo();
//return View(vo);
var vm = new ContactInfoVm();
vm.contactInfo.created = DateTime.Now;
vm.contactInfo.modified = DateTime.Now;
return View(vm);
}
//[HttpPost]
//public ActionResult Create(ContactInfoVo input, int companyId)
//{
// if (this.ModelState.IsValid)
// {
// if (companyId == null)
// var res = contactInfoManager.insert(input);
// else
// {
// var res = contactInfoManager.insert(input, companyId);
// }
// return RedirectToAction("Index");
// }
// return View(input);
//}
public ActionResult Details(int id)
{
var result = contactInfoManager.get(id);
return View(result);
}
public ActionResult Menu()
{
return PartialView("_Menu");
}
public ActionResult Delete(int id)
{
contactInfoManager.delete(id);
return RedirectToAction("Index");
}
public ActionResult DropDownList(int? id = null, string propertyName = null, Type propertyType = null, string defaultValue = null, int? propertyTypeId = null)
{
//var item = Activator.CreateInstance(modelType);
ViewBag.propertyName = propertyName;
if (defaultValue == null)
defaultValue = "Select One";
ViewBag.defaultValue = defaultValue;
ViewBag.selectedItem = id;
if (propertyType == typeof(CompanyVo))
{
ViewBag.items = companyManager.getAll(true);
ViewBag.idName = "companyId";
}
else if (propertyType == typeof(ContactInfoVo))
{
ViewBag.items = contactInfoManager.getAll(true);
ViewBag.idName = "contactInfoId";
}
return PartialView("_DropDownList");
}
#endregion
}
}
|
using Mccole.Geodesy.Calculator;
namespace Mccole.Geodesy.Extension
{
/// <summary>
/// Extension methods for ICoordinate.
/// </summary>
public static class CoordinateExtension
{
/// <summary>
/// Calculate the (initial) bearing from this point to another.
/// </summary>
/// <param name="this"></param>
/// <param name="point"></param>
/// <returns></returns>
public static double BearingTo(this ICoordinate @this, ICoordinate point)
{
return GeodeticCalculator.Instance.Bearing(@this, point);
}
/// <summary>
/// Calculate the distance between this point and another (using haversine formula) and the average radius of the earth.
/// </summary>
/// <param name="this"></param>
/// <param name="point">The destination point.</param>
/// <returns></returns>
public static double DistanceTo(this ICoordinate @this, ICoordinate point)
{
return DistanceTo(@this, point, Radius.Mean);
}
/// <summary>
/// Calculate the distance between this point and another (using haversine formula).
/// </summary>
/// <param name="this"></param>
/// <param name="point">The destination point.</param>
/// <param name="radius">The radius of the earth.</param>
/// <returns></returns>
public static double DistanceTo(this ICoordinate @this, ICoordinate point, double radius)
{
return GeodeticCalculator.Instance.Distance(@this, point, radius);
}
}
}
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Collections.ObjectModel;
namespace DAGProcessor.Graph
{
/// <summary>
/// Class that encapulates the graph structure fore the request
/// It handles notify the request result and add/remove nodes in the graph onto the machine.
/// </summary>
public class DAG
{
private readonly TaskCompletionSource<RequestResponse> taskSubscriberSource = new TaskCompletionSource<RequestResponse>();
private ConcurrentDictionary<IDagNode, Node.NodeState> nodeStateMap = new ConcurrentDictionary<IDagNode, Node.NodeState>();
private ReadOnlyDictionary<Node, List<Node>> reverseDependencyMap;
private TaskQueue taskQueue;
private long unfinishedNodeCounter;
// 1 is marked as request aborted.
private long aborted = 0;
// number of retry per node.
private int retryPolicy;
public int Id { get; set; }
[XmlArray("Nodes")]
[XmlArrayItem(ElementName = "Node")]
public List<Node> nodes { get; set; }
public Task<RequestResponse> subscribeToGraph()
{
return taskSubscriberSource.Task;
}
// Initial set up once the DAG get assigned a task queue for executing the nodes.
public void setTaskQueue(TaskQueue sharedQueue, int retry)
{
scrubDag();
bool valid = DagValidator.isValidDag(this);
if(!valid)
{
Console.WriteLine("{0} is invalid", Id);
taskSubscriberSource.SetResult(new RequestResponse(-1));
return;
}
taskQueue = sharedQueue;
Dictionary<Node, List<Node>> map = null;
initNodes(out map, retry);
reverseDependencyMap = new ReadOnlyDictionary<Node, List<Node>>(map);
retryPolicy = retry;
// Find the initial sets of node to run.
Node runningNode = null;
foreach (var node in nodes)
{
Node.NodeState currentState = Node.NodeState.Waiting;
if (node.dependencyList.Count == 0 && nodeStateMap.TryGetValue(node, out currentState))
{
if (currentState == Node.NodeState.Waiting)
{
runningNode = node;
kickOffNodeRun(runningNode);
}
}
}
}
// Add the node to taskqueue and attach the node complete call back.
private void kickOffNodeRun(Node runningNode)
{
bool isAborted = Interlocked.Read(ref aborted) == 1;
if (!isAborted && runningNode != null)
{
if (nodeStateMap.TryUpdate(runningNode, Node.NodeState.Queueing, Node.NodeState.Waiting))
{
Task<int> nodeListener = taskQueue.AddNode(runningNode);
Console.WriteLine("{0}:{1} added to task queue", Id, runningNode.Id);
try
{
nodeListener.ContinueWith(t =>
{
int result = t.Result;
nodeCompleted(runningNode, result);
}, TaskContinuationOptions.OnlyOnRanToCompletion);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
// Abort the request if we get a failure in execution.
private void abortRequest()
{
//Only abort once.
if(Interlocked.Read(ref aborted) == 0)
{
Interlocked.Exchange(ref aborted, 1);
Console.WriteLine("DAG {0} aborted", Id);
foreach (var node in nodes)
{
Node.NodeState currentState = Node.NodeState.Waiting;
if (nodeStateMap.TryGetValue(node, out currentState))
{
// If we already put a node in the task queue.
if (currentState == Node.NodeState.Queueing)
{
if (taskQueue.RemoveNode(node))
{
nodeStateMap.TryUpdate(node, Node.NodeState.Cancelled, Node.NodeState.Queueing);
Console.WriteLine("{0}:{1} removed from the queue", Id, node.Id);
}
}
// If the node is has not been queue, just set it to cancel.
else if (currentState == Node.NodeState.Waiting)
{
nodeStateMap.TryUpdate(node, Node.NodeState.Cancelled, Node.NodeState.Waiting);
}
}
}
//Notify the subscribers here or wait till the last node running on the machine is done???
taskSubscriberSource.SetResult(new RequestResponse(-1));
}
}
// Helper method to update mappings once the node work is completed.
private void nodeCompleted(Node node, int result)
{
Console.WriteLine("{0}:{1} result {2}", Id, node.Id, result);
if (result != 0)
{
if(node.retryCounter == 0)
{
//Update the node state to complete
nodeStateMap.TryUpdate(node, Node.NodeState.Completed, Node.NodeState.Queueing);
abortRequest();
return;
}
else
{
node.retryCounter = node.retryCounter - 1;
//Update the node state to complete
nodeStateMap.TryUpdate(node, Node.NodeState.Waiting, Node.NodeState.Queueing);
Console.WriteLine("{0}:{1} Retry: {2}", Id, node.Id, retryPolicy - node.retryCounter);
kickOffNodeRun(node);
return;
}
}
//Update and check the indegree number of nodes which depends on its completion to kick off;
Interlocked.Decrement(ref unfinishedNodeCounter);
if (Interlocked.Read(ref unfinishedNodeCounter) == 0)
{
taskSubscriberSource.SetResult(new RequestResponse(0));
}
else
{
List<Node> childNodes;
if (reverseDependencyMap.TryGetValue(node, out childNodes))
{
foreach(var child in childNodes)
{
child.DecrementDependencyCounter();
if(child.isReadyToQueue())
{
kickOffNodeRun(child);
}
}
}
}
}
// Helper method to update the dependency list in Node to use same object.
private void scrubDag()
{
foreach (var node in nodes)
{
List<Node> mappedNode = new List<Node>();
foreach (var dependency in node.dependencyList)
{
Node resultNode = null;
if (getNode(dependency.Id, out resultNode))
{
mappedNode.Add(resultNode);
}
}
node.dependencyList = mappedNode;
}
}
// Helper method.
private bool getNode(int id, out Node resultNode)
{
foreach (var node in nodes)
{
if (node.Id == id)
{
resultNode = node;
return true;
}
}
resultNode = null;
return false;
}
// Initialize the mappings the class to track node, and assign the retry policy.
private void initNodes(out Dictionary<Node, List<Node>> map, int retry)
{
Interlocked.Exchange(ref unfinishedNodeCounter, nodes.Count);
map = new Dictionary<Node, List<Node>>();
foreach (var node in nodes)
{
nodeStateMap.TryAdd(node, Node.NodeState.Waiting);
map.Add(node, new List<Node>());
node.retryCounter = retry;
}
foreach (var node in nodes)
{
node.SetDependencyCounter();
foreach (var dependent in node.dependencyList)
{
List<Node> list;
if (map.TryGetValue(dependent, out list))
{
list.Add(node);
}
}
}
}
}
}
|
using Autofac;
using KekManager.Api.Interfaces;
using KekManager.Data.Contexts;
using KekManager.Data.Repositories;
using KekManager.Database;
using KekManager.Database.Data;
using KekManager.Logic;
using KekManager.Logic.Interfaces;
using KekManager.Security.Data.Contexts;
namespace KekManager.DependancyRegistration
{
class KekManagerModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<DbInitializer>().As<IDbInitializer>();
builder.RegisterType<LearningProgramBl>().As<ILearningProgramBl>();
builder.RegisterType<LearningProgramRepository>().As<ILearningProgramRepository>();
builder.RegisterType<ResearchFellowBl>().As<IResearchFellowBl>();
builder.RegisterType<ResearchFellowRepository>().As<IResearchFellowRepository>();
builder.RegisterType<SubjectBl>().As<ISubjectBl>();
builder.RegisterType<SubjectRepository>().As<ISubjectRepository>();
builder.RegisterType<FullDatabaseContext>().As<IMainDbContext, ISecurityDbContext>();
}
}
} |
using System;
using System.Collections.Generic;
using YoctoScheduler.Core.Database;
using YoctoScheduler.Core;
using System.Data.SqlClient;
namespace YoctoScheduler.WebAPI.Controllers
{
[Attributes.GetAllSupported]
[Attributes.GetByIDSupported]
[Attributes.DeleteSupported]
public class ServersController : ControllerBase<Server, int>
{
}
}
|
using System;
using NUnit.Framework;
using Paralect.Schematra.Exceptions;
namespace Paralect.Schematra.Test.Tests
{
[TestFixture]
public class BuilderTest
{
[Test]
public void record_type_without_fields_and_namespace()
{
var context = new TypeContext();
var tag = Guid.NewGuid();
const string name = "First";
context.DefineRecord(builder => builder
.SetName(name)
.SetTag(tag)
);
context.Build();
var firstType = context.GetRecordType(name);
Assert.That(firstType.FullName, Is.EqualTo(name));
Assert.That(firstType.Name, Is.EqualTo(name));
Assert.That(firstType.Namespace, Is.EqualTo(""));
Assert.That(firstType.Tag, Is.EqualTo(tag));
Assert.That(firstType.BaseType, Is.Null);
Assert.That(firstType.GetFields().Count, Is.EqualTo(0));
}
[Test]
public void record_type_without_fields_and_with_namespace()
{
var context = new TypeContext();
var tag = Guid.NewGuid();
context.DefineRecord(builder => builder
.SetName("SomeNamespace.First")
.SetTag(tag)
);
context.Build();
var firstType = context.GetRecordType("SomeNamespace.First");
Assert.That(firstType.FullName, Is.EqualTo("SomeNamespace.First"));
Assert.That(firstType.Name, Is.EqualTo("First"));
Assert.That(firstType.Namespace, Is.EqualTo("SomeNamespace"));
Assert.That(firstType.Tag, Is.EqualTo(tag));
Assert.That(firstType.BaseType, Is.Null);
Assert.That(firstType.GetFields().Count, Is.EqualTo(0));
}
[Test]
public void record_type_with_self_base_type()
{
var context = new TypeContext();
var tag = Guid.NewGuid();
context.DefineRecord(builder => builder
.SetName("SomeNamespace.First")
.SetTag(tag)
.SetBaseType("SomeNamespace.First")
);
Assert.Throws<CircularDependencyException>(() =>
{
context.Build();
});
}
[Test]
public void record_type_with_fields_having_the_same_index()
{
var context = new TypeContext();
Assert.Throws<DuplicateFieldIndexException>(() =>
{
context.DefineRecord(builder => builder
.SetName("SomeNamespace.First")
.AddField(1, "Name", "SomeNamespace.First", FieldQualifier.Optional, null)
.AddField(1, "Year", "SomeNamespace.First", FieldQualifier.Optional, null)
);
});
}
[Test]
public void record_type_with_fields_having_the_same_name()
{
var context = new TypeContext();
Assert.Throws<DuplicateFieldNameException>(() =>
{
context.DefineRecord(builder => builder
.SetName("SomeNamespace.First")
.AddField(1, "Name", "SomeNamespace.First", FieldQualifier.Optional, null)
.AddField(2, "Name", "SomeNamespace.First", FieldQualifier.Optional, null)
);
});
}
[Test]
public void record_type_with_fields()
{
var context = new TypeContext();
var tag = Guid.NewGuid();
context.DefineRecord(builder => builder
.SetName("SomeNamespace.First")
.SetTag(tag)
.AddField(1, "Name", "SomeNamespace.First", FieldQualifier.Optional, null)
.AddField(2, "Year", "SomeNamespace.First", FieldQualifier.Optional, null)
);
context.Build();
var firstType = context.GetRecordType("SomeNamespace.First");
Assert.That(firstType.FullName, Is.EqualTo("SomeNamespace.First"));
Assert.That(firstType.Name, Is.EqualTo("First"));
Assert.That(firstType.Namespace, Is.EqualTo("SomeNamespace"));
Assert.That(firstType.Tag, Is.EqualTo(tag));
Assert.That(firstType.BaseType, Is.Null);
var fieldInfos = firstType.GetFields();
Assert.That(fieldInfos.Count, Is.EqualTo(2));
var field1 = firstType.GetField(1);
Assert.That(field1.Index, Is.EqualTo(1));
Assert.That(field1.Name, Is.EqualTo("Name"));
Assert.That(field1.Type, Is.EqualTo(firstType));
Assert.That(field1.Type.FullName, Is.EqualTo("SomeNamespace.First"));
var field2 = firstType.GetField(2);
Assert.That(field2.Index, Is.EqualTo(2));
Assert.That(field2.Name, Is.EqualTo("Year"));
Assert.That(field2.Type, Is.EqualTo(firstType));
Assert.That(field2.Type.FullName, Is.EqualTo("SomeNamespace.First"));
}
[Test]
public void two_record_types_with_the_same_full_name()
{
var context = new TypeContext();
var tag1 = Guid.NewGuid();
var tag2 = Guid.NewGuid();
Assert.Throws<DuplicateTypeNameException>(() =>
{
context.DefineRecord(builder => builder
.SetName("SomeNamespace.First")
.SetTag(tag1)
);
context.DefineRecord(builder => builder
.SetName("SomeNamespace.First")
.SetTag(tag2)
);
});
}
[Test]
public void two_record_types_with_the_same_name_but_different_namespaces()
{
var context = new TypeContext();
var tag1 = Guid.NewGuid();
var tag2 = Guid.NewGuid();
context.DefineRecord(builder => builder
.SetName("SomeNamespace1.First")
.SetTag(tag1)
);
context.DefineRecord(builder => builder
.SetName("SomeNamespace2.First")
.SetTag(tag2)
);
var type1 = context.GetRecordType("SomeNamespace1.First");
var type2 = context.GetRecordType("SomeNamespace2.First");
Assert.That(type1, Is.Not.EqualTo(type2));
Assert.That(type1.Name, Is.EqualTo(type2.Name));
Assert.That(type1.FullName, Is.Not.EqualTo(type2.FullName));
}
[Test]
public void two_record_types_with_the_same_tag_name()
{
var context = new TypeContext();
var tag = Guid.NewGuid();
Assert.Throws<DuplicateTypeTagException>(() =>
{
context.DefineRecord(builder => builder
.SetName("SomeNamespace.First1")
.SetTag(tag)
);
context.DefineRecord(builder => builder
.SetName("SomeNamespace.First2")
.SetTag(tag)
);
});
}
[Test]
public void two_record_types_where_one_extend_another()
{
var context = new TypeContext();
var tag1 = Guid.NewGuid();
var tag2 = Guid.NewGuid();
context.DefineRecord(builder => builder
.SetName("First")
.SetTag(tag1)
.SetBaseType("Second")
);
context.DefineRecord(builder => builder
.SetName("Second")
.SetTag(tag2)
);
context.Build();
var type1 = context.GetRecordType("First");
var type2 = context.GetRecordType("Second");
Assert.That(type1, Is.Not.EqualTo(type2));
Assert.That(type2.BaseType, Is.Null);
Assert.That(type1.BaseType, Is.EqualTo(type2));
}
[Test]
public void one_record_extends_not_existed_type()
{
var context = new TypeContext();
var tag = Guid.NewGuid();
context.DefineRecord(builder => builder
.SetName("First")
.SetTag(tag)
.SetBaseType("NotExistedType")
);
Assert.Throws<TypeNotFoundException>(() =>
{
context.Build();
});
}
[Test]
public void one_record_extends_not_record_type()
{
var context = new TypeContext();
var tag = Guid.NewGuid();
context.DefineRecord(builder => builder
.SetName("First")
.SetTag(tag)
.SetBaseType("Abracadabra")
);
context.DefineEnum(builder => builder
.SetName("Abracadabra")
.AddConstant(1, "First")
.AddConstant(2, "Second")
);
Assert.Throws<TypeMismatchException>(() =>
{
context.Build();
});
}
}
} |
using Microsoft.AspNetCore.Identity;
namespace Infrastructure.Identity.Models
{
public class ApplicationUser : IdentityUser
{
public ApplicationUser(string email, string username)
{
Email = email;
UserName = username;
}
public ApplicationUser()
{
}
}
}
|
using System.Data.Entity.ModelConfiguration;
using SSW.DataOnion.Sample.Entities;
namespace SSW.DataOnion.Sample.Data.Configurations
{
public class SchoolConfigurations : EntityTypeConfiguration<School>
{
public SchoolConfigurations()
{
this.HasKey(m => m.Id);
this.HasMany(m => m.Students).WithRequired().WillCascadeOnDelete(true);
this.HasRequired(m => m.Address).WithMany().WillCascadeOnDelete(true);
}
}
}
|
using Microsoft.EntityFrameworkCore;
using ProjAndParticipants.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ProjAndParticipants
{
public class ProjectContactContext : DbContext
{
public ProjectContactContext(DbContextOptions options) : base(options)
{
}
public ProjectContactContext()
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
//builder.Entity<ProjectContact>()
// .HasKey(pc => new { pc.ContactId, pc.ProjectId });
//builder.Entity<ProjectContact>()
// .HasOne(pc => pc.Project)
// .WithMany(c => c.ProjectContacts)
// .HasForeignKey(pc => pc.ProjectId);
//builder.Entity<ProjectContact>()
// .HasOne(pc => pc.Contact)
// .WithMany(p => p.ProjectContacts)
// .HasForeignKey(pc => pc.ContactId);
}
public DbSet<Project> Projects { get; set; }
public DbSet<Contact> Contacts { get; set; }
public DbSet<ProjectContact> ProjectContacts { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Dynamic;
using Facebook;
using System.Web;
namespace CMSEmergencySystem.Controllers
{
public class NewsFeedController
{
public void UpdateStatustoTwitter(string message)
{
string twitterURL = "https://api.twitter.com/1.1/statuses/update.json";
string oauth_consumer_key = "bZ90ol3pHIWbQudynzhNGOy3S";
string oauth_consumer_secret = "jwuuKARCVj2AORBuEkvPvaw6DyFQTKlwdMmeexTmvbjc2UYASQ";
string oauth_token = "847409682490642432-QNW7iK3wYSsGINN4Oe19gB3Yz7Nvfqk";
string oauth_token_secret = "Ln87plkr89HjiqUG5OIoIEU4g5c0pOg3MNECbbQB03tBF";
string oauth_version = "1.0";
string oauth_signature_method = "HMAC-SHA1";
string oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
System.TimeSpan timeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));
string oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
string baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" + "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&status={6}";
string baseString = string.Format(
baseFormat,
oauth_consumer_key,
oauth_nonce,
oauth_signature_method,
oauth_timestamp, oauth_token,
oauth_version,
Uri.EscapeDataString(message)
);
string oauth_signature = null;
using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(Uri.EscapeDataString(oauth_consumer_secret) + "&" + Uri.EscapeDataString(oauth_token_secret))))
{
oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes("POST&" + Uri.EscapeDataString(twitterURL) + "&" + Uri.EscapeDataString(baseString))));
}
string authorizationFormat = "OAuth oauth_consumer_key=\"{0}\", oauth_nonce=\"{1}\", " + "oauth_signature=\"{2}\", oauth_signature_method=\"{3}\", " + "oauth_timestamp=\"{4}\", oauth_token=\"{5}\", " + "oauth_version=\"{6}\"";
string authorizationHeader = string.Format(
authorizationFormat,
Uri.EscapeDataString(oauth_consumer_key),
Uri.EscapeDataString(oauth_nonce),
Uri.EscapeDataString(oauth_signature),
Uri.EscapeDataString(oauth_signature_method),
Uri.EscapeDataString(oauth_timestamp),
Uri.EscapeDataString(oauth_token),
Uri.EscapeDataString(oauth_version)
);
HttpWebRequest objHttpWebRequest = (HttpWebRequest)WebRequest.Create(twitterURL);
objHttpWebRequest.Headers.Add("Authorization", authorizationHeader);
objHttpWebRequest.Method = "POST";
objHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
using (Stream objStream = objHttpWebRequest.GetRequestStream())
{
byte[] content = ASCIIEncoding.ASCII.GetBytes("status=" + Uri.EscapeDataString(message));
objStream.Write(content, 0, content.Length);
}
var responseResult = "";
try
{
WebResponse objWebResponse = objHttpWebRequest.GetResponse();
StreamReader objStreamReader = new StreamReader(objWebResponse.GetResponseStream());
responseResult = objStreamReader.ReadToEnd().ToString();
}
catch (Exception ex)
{
responseResult = "Twitter Post Error: " + ex.Message.ToString() + ", authHeader: " + authorizationHeader;
}
}
public void UpdateStatustoFB(string message)
{
string app_id = "1677399102562906";
string app_secret = "77b29db9a93f9ed80dcae99b8af74a28";
string scope = "publish_actions,manage_pages";
if (HttpContext.Current.Session["accessToken"] == null){
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
app_id, HttpContext.Current.Request.Url.AbsoluteUri, scope, HttpContext.Current.Request["code"].ToString(), app_secret);
HttpWebRequest request = System.Net.WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split(','))
{
tokens.Add(token.Substring(0, token.IndexOf(":")),
token.Substring(token.IndexOf(":") + 1, token.Length - token.IndexOf(":") - 1));
}
}
string access_token = tokens["{\"access_token\""];
access_token = access_token.Replace("\"", "");
HttpContext.Current.Session.Add("accessToken", access_token);
}
string accessToken = HttpContext.Current.Session["accessToken"].ToString();
var client = new FacebookClient(accessToken);
dynamic parameters = new ExpandoObject();
parameters.message = message;
parameters.access_token = accessToken;
client.Post("/406096709760870/feed", parameters);
}
}
} |
using GeniyIdiot.Common;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace GeniyIdiotWinFormsApp
{
public partial class MainForm : Form
{
private User currentUser;
private Game game;
private int tick;
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
currentUser = new User("Неизвестно");
game = new Game(currentUser);
var getCurrentUserName = new GetCurrentUserName(currentUser);
getCurrentUserName.ShowDialog();
ShowNextQuestion();
}
private void ShowNextQuestion()
{
var currentQuestion = game.PopRandomQuestion();
questionTextLabel.Text = currentQuestion.Text;
questionNumberLabel.Text = game.GetQuestionNumberInfo();
userAnswerTextBox.Clear();
userAnswerTextBox.Focus();
oneQuestionTimer.Start();
tick = 10;
}
private void NextButton_Click(object sender, EventArgs e)
{
var userAnswer = GetUserAnswer();
int userAnswerNumber;
if (userAnswer != "OK")
{
MessageBox.Show(userAnswer, "Неверный формат!");
userAnswerTextBox.Clear();
userAnswerTextBox.Focus();
return;
}
else
{
userAnswerNumber = Convert.ToInt32(userAnswerTextBox.Text);
oneQuestionTimer.Stop();
}
if (tick > 0)
{
game.AcceptAnswer(userAnswerNumber);
}
if (game.End())
{
var diagnosis = game.CalculateDiagnose();
MessageBox.Show(diagnosis, "Поздравляем!");
UserResultsStorage.Append(currentUser);
restartButton.Visible = true;
return;
}
ShowNextQuestion();
}
private string GetUserAnswer()
{
try
{
var input = Convert.ToInt32(userAnswerTextBox.Text);
return "OK";
}
catch (FormatException)
{
return "Пожалуйста, введите число!";
}
catch (OverflowException)
{
return "Пожалуйста, введите число меньше 10^9";
}
}
private void restartButton_Click(object sender, EventArgs e)
{
Application.Restart();
}
private void oneQuestionTimer_Tick(object sender, EventArgs e)
{
oneQuestionTimerLabel.Text = tick.ToString();
tick--;
if(tick == 0)
{
oneQuestionTimerLabel.Text = "Время вышло!";
oneQuestionTimer.Stop();
}
}
}
}
|
using System;
using System.Collections.Generic;
namespace SANTI_WEB.Models
{
public partial class ProductsSeo
{
public int PkProductsSeo { get; set; }
public int? FkProducts { get; set; }
public string Tag { get; set; }
public string Description { get; set; }
public string Language { get; set; }
public Products FkProductsNavigation { get; set; }
}
}
|
namespace Triton.Game.Mapping
{
using ns25;
using ns26;
using System;
using System.Collections.Generic;
using Triton.Game.Mono;
[Attribute38("iTweenCollection")]
public class iTweenCollection : MonoClass
{
public iTweenCollection(IntPtr address) : this(address, "iTweenCollection")
{
}
public iTweenCollection(IntPtr address, string className) : base(address, className)
{
}
public void Add(iTween tween)
{
object[] objArray1 = new object[] { tween };
base.method_8("Add", objArray1);
}
public void CleanUp()
{
base.method_8("CleanUp", Array.Empty<object>());
}
public iTweenIterator GetIterator()
{
return base.method_11<iTweenIterator>("GetIterator", Array.Empty<object>());
}
public void Remove(iTween tween)
{
object[] objArray1 = new object[] { tween };
base.method_8("Remove", objArray1);
}
public int Count
{
get
{
return base.method_2<int>("Count");
}
}
public int DeletedCount
{
get
{
return base.method_2<int>("DeletedCount");
}
}
public int LastIndex
{
get
{
return base.method_2<int>("LastIndex");
}
}
public List<iTween> Tweens
{
get
{
Class247<iTween> class2 = base.method_3<Class247<iTween>>("Tweens");
if (class2 != null)
{
return class2.method_25();
}
return null;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestPartA8
{
public abstract class ChinOfResTraining
{
protected ChinOfResTraining next;
public void SetNext(ChinOfResTraining next)
{
this.next = next;
}
public abstract void Handle();
}
}
|
using System;
using UnityEngine;
public class SurferController : MonoBehaviour
{
#region Public Variables
public Boundaries boundaries;
public float speed;
public Animator spriteAnimator;
public GameObject bulletPrefab;
public Transform bulletSpawn;
#endregion
#region Private Variables
private bool _isShooting = false;
private int _shootHash;
#endregion
#region Private Methods
private void Start()
{
_shootHash = Animator.StringToHash("Shooting");
}
private void Update()
{
float horz = Input.GetAxis("Horizontal");
float vert = Input.GetAxis("Vertical");
Vector3 newPos = new Vector3(
Mathf.Clamp(transform.position.x + horz * Time.deltaTime * speed, boundaries.minX, boundaries.maxX),
Mathf.Clamp(transform.position.y + vert * Time.deltaTime * speed, boundaries.minY, boundaries.maxY), 0.0f);
transform.position = newPos;
if (Input.GetButton("Fire1") && !_isShooting)
{
_isShooting = true;
spriteAnimator.SetTrigger("Shoot");
}
else if (_isShooting)
{
// Check whether we almost finished with the shooting animation
if (spriteAnimator.GetCurrentAnimatorStateInfo(0).shortNameHash == _shootHash &&
spriteAnimator.GetCurrentAnimatorStateInfo(0).normalizedTime > 0.9)
{
GameObject bullet = Instantiate(bulletPrefab, bulletSpawn);
bullet.transform.localPosition = Vector3.zero;
_isShooting = false;
}
}
}
#endregion
}
[Serializable]
public class Boundaries
{
public float minX;
public float minY;
public float maxX;
public float maxY;
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using Model.DataEntity;
using Model.Locale;
using Model.UploadManagement;
using Utility;
using eIVOGo.Properties;
using DataAccessLayer.basis;
namespace eIVOGo.Helper
{
public class BranchBusinessCounterpartUploadManager : CsvUploadManager<EIVOEntityDataContext, OrganizationBranch, ItemUpload<OrganizationBranch>>
{
public BranchBusinessCounterpartUploadManager() : base() {
}
public BranchBusinessCounterpartUploadManager(GenericManager<EIVOEntityDataContext> manager)
: base(manager)
{
}
public Naming.InvoiceCenterBusinessType BusinessType { get; set; }
private int? _masterID;
private List<UserProfile> _userList;
public int? MasterID
{
get
{
return _masterID;
}
set
{
_masterID = value;
}
}
public override void ParseData(Model.Security.MembershipManagement.UserProfileMember userProfile, string fileName, System.Text.Encoding encoding)
{
_userProfile = userProfile;
if (!_masterID.HasValue)
_masterID = _userProfile.CurrentUserRole.OrganizationCategory.CompanyID;
base.ParseData(userProfile, fileName, encoding);
}
protected override void initialize()
{
__COLUMN_COUNT = 6;
_userList = new List<UserProfile>();
}
protected override void doSave()
{
this.SubmitChanges();
var enterprise = this.GetTable<Organization>().Where(o => o.CompanyID == _masterID)
.FirstOrDefault().EnterpriseGroupMember.FirstOrDefault();
String subject = (enterprise != null ? enterprise.EnterpriseGroup.EnterpriseName : "") + " 會員啟用認證信";
ThreadPool.QueueUserWorkItem(p =>
{
foreach (var u in _userList)
{
try
{
u.NotifyToActivate();
}
catch (Exception ex)
{
Logger.Warn("[" + subject + "]傳送失敗,原因 => " + ex.Message);
Logger.Error(ex);
}
}
});
}
protected override bool validate(ItemUpload<OrganizationBranch> item)
{
String[] column = item.Columns;
if (string.IsNullOrEmpty(column[0]))
{
item.Status = String.Join("、", item.Status, "營業人名稱格式錯誤");
_bResult = false;
}
if (column[1].Length > 8 || !ValueValidity.ValidateString(column[1], 20))
{
item.Status = String.Join("、", item.Status, "統編格式錯誤");
_bResult = false;
}
else if (column[1].Length == 0)
{
column[1] = "0000000000";
}
else if (column[1].Length < 8)
{
column[1] = ("0000000" + column[1]).Right(8);
}
//if (string.IsNullOrEmpty(column[2]) || !ValueValidity.ValidateString(column[2], 16))
//{
// item.Status = String.Join("、", item.Status, "聯絡人電子郵件格式錯誤");
// _bResult = false;
//}
//if (string.IsNullOrEmpty(column[3]))
//{
// item.Status = String.Join("、", item.Status, "地址格式錯誤");
// _bResult = false;
//}
//if (string.IsNullOrEmpty(column[4]))
//{
// item.Status = String.Join("、", item.Status, "電話格式錯誤");
// _bResult = false;
//}
if (string.IsNullOrEmpty(column[5]))
{
item.Status = String.Join("、", item.Status, "店號錯誤");
_bResult = false;
}
item.Entity = this.EntityList.Where(o => o.BranchNo == column[5]).FirstOrDefault();
if (item.Entity != null)
{
if (item.Entity.Organization.ReceiptNo != column[1])
{
if (item.Entity.Organization.OrganizationBranch.Count == 1)
{
int relativeID = item.Entity.CompanyID;
this.DeleteAllOnSubmit<BusinessRelationship>(r => r.MasterID == _masterID && r.RelativeID == relativeID);
}
int branchID = item.Entity.BranchID;
this.DeleteAllOnSubmit<OrganizationBranch>(b => b.BranchID == branchID);
item.Entity = null;
}
}
if(item.Entity == null) //新的分店
{
item.Entity = new OrganizationBranch
{
BranchNo = column[5]
};
this.GetTable<OrganizationBranch>().InsertOnSubmit(item.Entity);
var orgItem = _items.Where(i => i.Entity.Organization.ReceiptNo == column[1])
.Select(i => i.Entity.Organization).FirstOrDefault();
if (orgItem == null)
{
orgItem = this.GetTable<Organization>().Where(o => o.ReceiptNo == column[1]).FirstOrDefault();
}
if(orgItem==null) //新的相對營業人
{
orgItem = new Organization
{
OrganizationStatus = new OrganizationStatus
{
CurrentLevel = (int)Naming.MemberStatusDefinition.Checked
},
OrganizationExtension = new OrganizationExtension { }
};
this.GetTable<Organization>().InsertOnSubmit(orgItem);
var relationship = new BusinessRelationship
{
Counterpart = orgItem,
BusinessID = (int)BusinessType,
MasterID = _masterID.Value,
CurrentLevel = (int)Naming.MemberStatusDefinition.Checked
};
orgItem.RelativeRelation.Add(relationship);
var orgaCate = new OrganizationCategory
{
Organization = orgItem,
CategoryID = (int)Naming.CategoryID.COMP_E_INVOICE_B2C_BUYER
};
orgItem.OrganizationCategory.Add(orgaCate);
orgItem.OrganizationBranch.Add(item.Entity);
item.Entity.Organization = orgItem;
checkUser(column, orgaCate, column[5]);
}
else
{
if(!orgItem.RelativeRelation.ToList().Any(r=>r.MasterID==_masterID))
{
var relation = new BusinessRelationship
{
Counterpart = orgItem,
BusinessID = (int)BusinessType,
MasterID = _masterID.Value,
CurrentLevel = (int)Naming.MemberStatusDefinition.Checked
};
this.GetTable<BusinessRelationship>().InsertOnSubmit(relation);
orgItem.RelativeRelation.Add(relation);
}
var orgaCate = orgItem.OrganizationCategory.ToList()
.Where(c => c.CategoryID == (int)Naming.CategoryID.COMP_E_INVOICE_B2C_BUYER).FirstOrDefault();
if (orgaCate == null)
{
orgaCate = new OrganizationCategory
{
CategoryID = (int)Naming.CategoryID.COMP_E_INVOICE_B2C_BUYER,
Organization = orgItem
};
this.GetTable<OrganizationCategory>().InsertOnSubmit(orgaCate);
orgItem.OrganizationCategory.Add(orgaCate);
}
//var currentUser = checkUser(column, orgaCate, column[5].GetEfficientString() ?? column[1]);
//currentUser.Phone = column[4];
//currentUser.EMail = column[2];
//currentUser.Address = column[3];
orgItem.OrganizationBranch.Add(item.Entity);
item.Entity.Organization = orgItem;
checkUser(column, orgaCate, column[5]);
}
}
item.Entity.BranchName = column[0];
item.Entity.ContactEmail = column[2];
item.Entity.Addr = column[3];
item.Entity.Phone = column[4];
item.Entity.Organization.CompanyName = column[0];
item.Entity.Organization.ReceiptNo = column[1];
item.Entity.Organization.ContactEmail = column[2];
item.Entity.Organization.Addr = column[3];
item.Entity.Organization.Phone = column[4];
if (item.Entity.Organization.OrganizationExtension == null)
{
item.Entity.Organization.OrganizationExtension = new OrganizationExtension { };
}
item.Entity.Organization.OrganizationExtension.CustomerNo = column[5];
return _bResult;
}
private UserProfile checkUser(string[] column, OrganizationCategory orgaCate,String pid)
{
var userProfile = this.GetTable<UserProfile>().Where(u => u.PID == pid).FirstOrDefault();
if (userProfile == null)
{
userProfile = new UserProfile
{
PID = pid,
Phone = column[4],
EMail = column[2],
Address = column[3],
Password2 = ValueValidity.MakePassword(pid),
UserProfileExtension = new UserProfileExtension
{
IDNo = column[1]
},
UserProfileStatus = new UserProfileStatus
{
CurrentLevel = (int)Naming.MemberStatusDefinition.Wait_For_Check
}
};
userProfile.MailID = userProfile.EMail.GetEfficientString()?
.Split(';', ',', ',')?[0];
_userList.Add(userProfile);
}
else
{
this.DeleteAllOnSubmit<UserRole>(r => r.UID == userProfile.UID);
}
this.GetTable<UserRole>().InsertOnSubmit(new UserRole
{
RoleID = (int)Naming.RoleID.分店相對營業人,
UserProfile = userProfile,
OrganizationCategory = orgaCate
});
return userProfile;
}
}
} |
using System;
using Android.App;
using ScreenLock.Droid;
using Xamarin.Forms;
[assembly: Xamarin.Forms.Dependency(typeof(CloseApplication))]
namespace ScreenLock.Droid
{
public class CloseApplication : ICloseApplication
{
public void Exit()
{
int pid = Android.OS.Process.MyPid();
var activity = (Activity)Forms.Context;
activity.FinishAffinity();
Android.OS.Process.KillProcess(pid);
}
}
} |
using BLL;
using Entidades;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProyectoFinal.UI
{
public partial class rCliente : Form
{
private int IdUsuario;
public rCliente(int IdUsuario)
{
InitializeComponent();
this.IdUsuario = IdUsuario;
}
private void Guardarbutton_Click(object sender, EventArgs e)
{
if (!Validar())
return;
Clientes cliente = LlenarClase();
RepositorioBase<Clientes> db = new RepositorioBase<Clientes>();
try
{
if(IdnumericUpDown.Value == 0)
{
if(db.Guardar(cliente))
{
MessageBox.Show("Guardado Existosamente","Atencion!!",MessageBoxButtons.OK,MessageBoxIcon.Information);
Limpiar();
}
else
{
MessageBox.Show("No se pudo guardar", "Atencion!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
else
{
if (db.Modificar(cliente))
{
MessageBox.Show("Modificado Existosamente", "Atencion!!", MessageBoxButtons.OK, MessageBoxIcon.Information);
Limpiar();
}
else
{
MessageBox.Show("No se pudo Modificar", "Atencion!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}catch(Exception)
{
MessageBox.Show("Hubo un error!!", "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private bool Validar()
{
bool paso = true;
errorProvider.Clear();
if(string.IsNullOrWhiteSpace(NombretextBox.Text))
{
paso = false;
errorProvider.SetError(NombretextBox,"Este campo no puede estar vacio");
}
if (string.IsNullOrWhiteSpace(CedulatextBox.Text))
{
paso = false;
errorProvider.SetError(CedulatextBox, "Este campo no puede estar vacio");
}
if (string.IsNullOrWhiteSpace(DirecciontextBox.Text))
{
paso = false;
errorProvider.SetError(DirecciontextBox, "Este campo no puede estar vacio");
}
if (string.IsNullOrWhiteSpace(TelefonotextBox.Text))
{
paso = false;
errorProvider.SetError(TelefonotextBox, "Este campo no puede estar vacio");
}
if (FechadateTimePicker.Value > DateTime.Now)
{
paso = false;
errorProvider.SetError(FechadateTimePicker,"La fecha no puede ser mayor que la de hoy");
}
if (FechaNacimientodateTimePicker.Value > DateTime.Now)
{
paso = false;
errorProvider.SetError(FechadateTimePicker, "La fecha no puede ser mayor que la de hoy");
}
if (LimiteCreditonumericUpDown.Value == 0)
{
paso = false;
errorProvider.SetError(LimiteCreditonumericUpDown,"Debe fijar un limite de credito");
}
if (LimiteVentasnumericUpDown.Value == 0)
{
paso = false;
errorProvider.SetError(LimiteVentasnumericUpDown, "Debe fijar un limite de credito");
}
if(!Clientes.ValidarCedula(CedulatextBox.Text.Trim()))
{
paso = false;
errorProvider.SetError(CedulatextBox,"Esta cedula no es valida");
}
return paso;
}
private Clientes LlenarClase()
{
Clientes cliente = new Clientes();
cliente.IdCliente = (int)IdnumericUpDown.Value;
cliente.Nombre = NombretextBox.Text;
cliente.Cedula = CedulatextBox.Text;
cliente.Direccion = DirecciontextBox.Text;
cliente.Telefono = TelefonotextBox.Text;
cliente.Celular = CelulartextBox.Text;
cliente.FechaCreacion = FechadateTimePicker.Value;
cliente.FechaNacimiento = FechaNacimientodateTimePicker.Value;
cliente.LimiteCredito = LimiteCreditonumericUpDown.Value ;
cliente.LimiteVenta = LimiteVentasnumericUpDown.Value;
cliente.IdUsuario = IdUsuario;
return cliente;
}
private void Nuevobutton_Click(object sender, EventArgs e)
{
Limpiar();
}
private void Limpiar()
{
IdnumericUpDown.Value = 0;
NombretextBox.Text = string.Empty;
CedulatextBox.Text = string.Empty;
DirecciontextBox.Text = string.Empty;
TelefonotextBox.Text = string.Empty;
CelulartextBox.Text = string.Empty;
FechadateTimePicker.Value = DateTime.Now;
FechaNacimientodateTimePicker.Value = DateTime.Now;
LimiteCreditonumericUpDown.Value = 0;
LimiteVentasnumericUpDown.Value = 0;
BalancetextBox.Text = "0.0";
}
private void Eliminarbutton_Click(object sender, EventArgs e)
{
RepositorioBase<Clientes> db = new RepositorioBase<Clientes>();
errorProvider.Clear();
try
{
if (IdnumericUpDown.Value == 0)
{
errorProvider.SetError(IdnumericUpDown, "Este campo no puede ser cero al eliminar");
}
else
{
if(db.Elimimar((int)IdnumericUpDown.Value))
{
MessageBox.Show("Eliminado Existosamente", "Atencion!!", MessageBoxButtons.OK, MessageBoxIcon.Information);
Limpiar();
}
else
{
MessageBox.Show("No se pudo guardar", "Atencion!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
catch(Exception)
{
MessageBox.Show("Hubo un error!!", "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Buscarbutton_Click(object sender, EventArgs e)
{
RepositorioBase<Clientes> db = new RepositorioBase<Clientes>();
Clientes cliente;
try
{
if((cliente = db.Buscar((int)IdnumericUpDown.Value)) is null)
{
MessageBox.Show("No se pudo encontrar", "Atencion!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
LlenarCampos(cliente);
}
}catch(Exception)
{
MessageBox.Show("Hubo un error!!", "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LlenarCampos(Clientes cliente)
{
Limpiar();
IdnumericUpDown.Value = cliente.IdCliente;
NombretextBox.Text = cliente.Nombre;
CedulatextBox.Text = cliente.Cedula;
DirecciontextBox.Text = cliente.Direccion;
TelefonotextBox.Text = cliente.Telefono;
CelulartextBox.Text = cliente.Celular;
FechadateTimePicker.Value = cliente.FechaCreacion;
FechaNacimientodateTimePicker.Value = cliente.FechaNacimiento;
LimiteCreditonumericUpDown.Value = cliente.LimiteCredito;
LimiteVentasnumericUpDown.Value = cliente.LimiteVenta;
BalancetextBox.Text = cliente.Balance.ToString();
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class FirstGridScript : GridScript {
string[] gridString = new string[]{ //an array of strings
"ww--|-rw-|----|------------", //ToCharArray is used to look at our string (which is also basically an array of characters) and get the position of a character
"-ww-|-wr-rrrr-|---rrrr-----", //down in line 42, we are using x to find a position in gridString[y]
"-ww-|----r----|------r--www",
"-ww-|----r----|------r--ww-",
"-ww-|----rrrrrrrrrrrr--dww-",
"-wwwwwwww|----|-------dww--", //there will be an area in the script assigning values to the materials, like a difficulty level for each one
"-wwwwwwwwww---|------d-----", //we will be using the x, y to find the value of the spot
"----|---www---|-----dd-----",
"----|---www---|----dd------",
"--ddd----w--www---dd-------",
"--drd----wwww-w--dd--------",
"--drd----|----wwdd---------",
"--ddd----|----|wdd---------",
"----dddddd----|------------",
"----|----d----|------------",
};
// Use this for initialization
void Start () {
gridWidth = gridString[0].Length;
gridHeight = gridString.Length;
}
// Update is called once per frame
void Update () {
}
public override float GetMovementCost(GameObject go){
return base.GetMovementCost(go);
}
protected override Material GetMaterial(int x, int y){ //getting the x and y from 2D grid array in GridScript, and using quad's x y
char c = gridString[y].ToCharArray()[x]; //y is quad's space in 2D array (not literaly Unity transform position). //we are running a fucntion ToCharArray()[x] ON gridString[y]
Material mat;
switch(c){
case 'd':
mat = mats[1];
break;
case 'w':
mat = mats[2];
break;
case 'r':
mat = mats[3];
break;
default:
mat = mats[0];
break;
}
return mat;
}
}
|
using System;
namespace NameSearch.Models.Domain
{
/// <summary>
/// Person in Export Format
/// </summary>
public class Person : IEquatable<Person>
{
/// <summary>
/// Gets or sets the address1.
/// </summary>
/// <value>
/// The address1.
/// </value>
public string Address1 { get; set; }
/// <summary>
/// Gets or sets the address2.
/// </summary>
/// <value>
/// The address2.
/// </value>
public string Address2 { get; set; }
/// <summary>
/// Gets or sets the age range.
/// </summary>
/// <value>
/// The age range.
/// </value>
public string AgeRange { get; set; }
/// <summary>
/// Gets or sets the city.
/// </summary>
/// <value>
/// The city.
/// </value>
public string City { get; set; }
/// <summary>
/// Gets or sets the country.
/// </summary>
/// <value>
/// The country.
/// </value>
public string Country { 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>
public string LastName { get; set; }
/// <summary>
/// Gets or sets the lattitude.
/// </summary>
/// <value>
/// The lattitude.
/// </value>
public double? Latitude { get; set; }
/// <summary>
/// Gets or sets the longitude.
/// </summary>
/// <value>
/// The longitude.
/// </value>
public double? Longitude { get; set; }
/// <summary>
/// Gets or sets the phone number.
/// </summary>
/// <value>
/// The phone number.
/// </value>
public string Phone { get; set; }
/// <summary>
/// Gets or sets the plus4.
/// </summary>
/// <value>
/// The plus4.
/// </value>
public string Plus4 { get; set; }
/// <summary>
/// Gets or sets the state.
/// </summary>
/// <value>
/// The state.
/// </value>
public string State { get; set; }
/// <summary>
/// Gets or sets the zip.
/// </summary>
/// <value>
/// The zip.
/// </value>
public string Zip { get; set; }
#region Equality
/// <summary>
/// See http://www.aaronstannard.com/overriding-equality-in-dotnet/
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(Person other)
{
if (other == null) return false;
return string.Equals(FirstName, other.FirstName, StringComparison.InvariantCultureIgnoreCase) &&
string.Equals(LastName, other.LastName, StringComparison.InvariantCultureIgnoreCase) &&
string.Equals(Phone, other.Phone, StringComparison.CurrentCultureIgnoreCase) &&
string.Equals(Address1, other.Address1, StringComparison.CurrentCultureIgnoreCase) &&
string.Equals(Address2, other.Address2, StringComparison.CurrentCultureIgnoreCase) &&
string.Equals(City, other.City, StringComparison.CurrentCultureIgnoreCase) &&
string.Equals(State, other.State, StringComparison.CurrentCultureIgnoreCase) &&
string.Equals(Zip, other.Zip, StringComparison.CurrentCultureIgnoreCase) &&
string.Equals(Plus4, other.Plus4, StringComparison.CurrentCultureIgnoreCase) &&
string.Equals(Country, other.Country, StringComparison.CurrentCultureIgnoreCase) &&
double.Equals(Latitude, other.Latitude) &&
double.Equals(Longitude, other.Longitude);
}
/// <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;
using Newtonsoft.Json;
namespace TdLib
{
/// <summary>
/// Autogenerated TDLib APIs
/// </summary>
public static partial class TdApi
{
/// <summary>
/// Describes a group call
/// </summary>
public partial class GroupCall : Object
{
/// <summary>
/// Data type for serialization
/// </summary>
[JsonProperty("@type")]
public override string DataType { get; set; } = "groupCall";
/// <summary>
/// Extra data attached to the object
/// </summary>
[JsonProperty("@extra")]
public override string Extra { get; set; }
/// <summary>
/// Group call identifier
/// </summary>
[JsonConverter(typeof(Converter))]
[JsonProperty("id")]
public int Id { get; set; }
/// <summary>
/// True, if the call is active
/// </summary>
[JsonConverter(typeof(Converter))]
[JsonProperty("is_active")]
public bool IsActive { get; set; }
/// <summary>
/// True, if the call is joined
/// </summary>
[JsonConverter(typeof(Converter))]
[JsonProperty("is_joined")]
public bool IsJoined { get; set; }
/// <summary>
/// True, if user was kicked from the call because of network loss and the call needs to be rejoined
/// </summary>
[JsonConverter(typeof(Converter))]
[JsonProperty("need_rejoin")]
public bool NeedRejoin { get; set; }
/// <summary>
/// True, if the current user can unmute themself
/// </summary>
[JsonConverter(typeof(Converter))]
[JsonProperty("can_unmute_self")]
public bool CanUnmuteSelf { get; set; }
/// <summary>
/// True, if the current user can manage the group call
/// </summary>
[JsonConverter(typeof(Converter))]
[JsonProperty("can_be_managed")]
public bool CanBeManaged { get; set; }
/// <summary>
/// Number of participants in the group call
/// </summary>
[JsonConverter(typeof(Converter))]
[JsonProperty("participant_count")]
public int ParticipantCount { get; set; }
/// <summary>
/// True, if all group call participants are loaded
/// </summary>
[JsonConverter(typeof(Converter))]
[JsonProperty("loaded_all_participants")]
public bool LoadedAllParticipants { get; set; }
/// <summary>
/// Recently speaking users in the group call
/// </summary>
[JsonConverter(typeof(Converter))]
[JsonProperty("recent_speakers")]
public GroupCallRecentSpeaker[] RecentSpeakers { get; set; }
/// <summary>
/// True, if only group call administrators can unmute new participants
/// </summary>
[JsonConverter(typeof(Converter))]
[JsonProperty("mute_new_participants")]
public bool MuteNewParticipants { get; set; }
/// <summary>
/// True, if group call administrators can enable or disable mute_new_participants setting
/// </summary>
[JsonConverter(typeof(Converter))]
[JsonProperty("allowed_change_mute_new_participants")]
public bool AllowedChangeMuteNewParticipants { get; set; }
/// <summary>
/// Call duration; for ended calls only
/// </summary>
[JsonConverter(typeof(Converter))]
[JsonProperty("duration")]
public int Duration { get; set; }
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Patterns.StatePattern.Classes
{
class GumballMonitor
{
GumballMachine _gumballMachine;
public GumballMonitor(GumballMachine gumballMachine)
{
this._gumballMachine = gumballMachine;
}
public void Report()
{
Console.WriteLine("Gumball Machine: " + _gumballMachine.GetLocation());
Console.WriteLine("Current inventory: " + _gumballMachine.GetCount() + " gumballs");
Console.WriteLine("Current state: " + _gumballMachine.GetState());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Kers.Models.Repositories;
using System.Threading.Tasks;
using Kers.Models;
using Kers.Models.Data;
using Kers.Models.Contexts;
using Kers.Models.Abstract;
using Kers.Models.Entities.KERScore;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using Kers.Models.Entities;
using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Caching.Memory;
namespace Kers.Models.Repositories
{
public class SnapCommitmentRepository : SnapBaseRepository, ISnapCommitmentRepository
{
private KERScoreContext context;
private IDistributedCache _cache;
public SnapCommitmentRepository(KERScoreContext context, IDistributedCache _cache, IMemoryCache _memoryCache)
: base(context, _cache, _memoryCache)
{
this.context = context;
this._cache = _cache;
}
public async Task<string> CommitmentSummary(FiscalYear fiscalYear, bool refreshCache = false){
string result;
var cacheKey = CacheKeys.SnapCommitmentSummary + fiscalYear.Name;
var cacheString = await _cache.GetStringAsync(cacheKey);
if (!string.IsNullOrEmpty(cacheString) && !refreshCache ){
result = cacheString;
}else{
var keys = new List<string>();
keys.Add("FY");
keys.Add("District");
keys.Add("PlanningUnit");
keys.Add("Name");
keys.Add("Title");
keys.Add("Program(s)");
keys.Add("HoursReportedLastFY");
keys.Add("HoursCommittedLastFY");
keys.Add("HoursCommittedThisFY");
result = string.Join(",", keys.ToArray()) + "\n";
var previousFiscalYear = await this.context.FiscalYear
.Where( f => f.Start < fiscalYear.Start && f.Type == FiscalYearType.SnapEd)
.OrderByDescending( f => f.Start)
.FirstOrDefaultAsync();
if(previousFiscalYear == null){
throw new Exception("No Previous Fiscal Year Found in Commitment Summary Report.");
}
var byUser = SnapData(previousFiscalYear)
.GroupBy( d=> d.User.Id)
.Select(
k => new {
Revisions = k.Select( a => a.Revision),
User = k.Select( a => a.User).First()
}
);
var Rows = new List<CommitmentSummaryViewModel>();
var userIds = new List<int>();
foreach( var usr in byUser){
userIds.Add(usr.User.Id);
var rowData = new CommitmentSummaryViewModel();
rowData.FY = fiscalYear.Name;
if(usr.User.RprtngProfile.PlanningUnit.District != null){
rowData.District = usr.User.RprtngProfile.PlanningUnit.District.Name;
}else{
rowData.District = "";
}
rowData.PlanningUnit = usr.User.RprtngProfile.PlanningUnit.Name;
rowData.Name = usr.User.RprtngProfile.Name;
rowData.Title = usr.User.ExtensionPosition.Code;
var spclt = "";
foreach( var s in usr.User.Specialties){
spclt += " " + (s.Specialty.Code.Substring( 0, 4) == "prog" ? s.Specialty.Code.Substring(4) : s.Specialty.Code);
}
rowData.Programs = spclt;
var reported = usr.Revisions.Sum( s => s.Hours ).ToString();
rowData.HoursReportedLastFY = (reported == "" ? "0" :reported);
var prev = context.SnapEd_Commitment
.Where( c => c.KersUserId1 == usr.User.Id
&&
c.FiscalYear == previousFiscalYear
&&
c.SnapEd_ActivityType.Measurement == "Hour");
var previous = prev.Sum( s => s.Amount).ToString();
rowData.HoursCommittedLastFY = (previous == ""? "0" : previous );
var curnt = context.SnapEd_Commitment
.Where( c => c.KersUserId1 == usr.User.Id
&&
c.FiscalYear == fiscalYear
&&
c.SnapEd_ActivityType.Measurement == "Hour");
var current = curnt.Sum( s => s.Amount).ToString();
rowData.HoursCommittedThisFY = (current == "" ? "0" : current);
Rows.Add(rowData);
}
// Find people with commitment but no reported hours
var restList = context.SnapEd_Commitment.Where(
c =>
!userIds.Contains(c.KersUserId1??0)
&&
c.FiscalYear == fiscalYear
&&
c.SnapEd_ActivityType.Measurement == "Hour"
&&
c.KersUser.RprtngProfile.Institution.Code == "21000-1862"
)
.Include( c => c.KersUser)
.ToList();
var rest = restList.GroupBy( d=> d.KersUser.Id)
.Select(
k => new {
Commitments = k.Select( a => a),
User = k.Select( a => a.KersUser).First()
}
);
foreach( var usr in rest){
var userData = await context.KersUser.Where( u => u.Id == usr.User.Id )
.Include( u => u.RprtngProfile).ThenInclude( r => r.PlanningUnit ).ThenInclude( u => u.District)
.Include( u => u.Specialties ).ThenInclude( s => s.Specialty)
.Include( u => u.ExtensionPosition)
.FirstOrDefaultAsync();
var rowData = new CommitmentSummaryViewModel();
rowData.FY = fiscalYear.Name;
if(userData.RprtngProfile.PlanningUnit.District != null){
rowData.District = userData.RprtngProfile.PlanningUnit.District.Name;
}else{
rowData.District = "";
}
rowData.PlanningUnit = userData.RprtngProfile.PlanningUnit.Name;
rowData.Name = userData.RprtngProfile.Name;
rowData.Title = userData.ExtensionPosition.Code;
var spclt = "";
foreach( var s in userData.Specialties){
spclt += " " + (s.Specialty.Code.Substring( 0, 4) == "prog" ? s.Specialty.Code.Substring(4) : s.Specialty.Code);
}
rowData.Programs = spclt;
rowData.HoursReportedLastFY = "0";
var prev = context.SnapEd_Commitment
.Where( c => c.KersUserId1 == usr.User.Id
&&
c.FiscalYear == previousFiscalYear
&&
c.SnapEd_ActivityType.Measurement == "Hour");
var previous = prev.Sum( s => s.Amount).ToString();
rowData.HoursCommittedLastFY = (previous == ""? "0" : previous );
rowData.HoursCommittedThisFY = usr.Commitments.Sum( c => c.Amount).ToString();
Rows.Add(rowData);
}
foreach( var Row in Rows.OrderBy( r => r.District).ThenBy( r => r.PlanningUnit).ThenBy( r => r.Name )){
var textRow = "";
textRow += Row.FY + ",";
textRow += Row.District + ",";
textRow += Row.PlanningUnit + ",";
textRow += string.Concat( "\"", Row.Name, "\"") + ",";
textRow += string.Concat( "\"", Row.Title, "\"") + ",";
textRow += string.Concat( "\"", Row.Programs, "\"") + ",";
textRow += Row.HoursReportedLastFY + ",";
textRow += Row.HoursCommittedLastFY + ",";
textRow += Row.HoursCommittedThisFY;
result += textRow + "\n";
}
await _cache.SetStringAsync(cacheKey, result, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays( this.getCacheSpan(fiscalYear) )
});
}
return result;
}
public async Task<string> CommitmentHoursDetail(FiscalYear fiscalYear, bool refreshCache = false){
string result;
var cacheKey = CacheKeys.SnapCommitmentHoursDetail + fiscalYear.Name;
var cacheString = await _cache.GetStringAsync(cacheKey);
if (!string.IsNullOrEmpty(cacheString) && !refreshCache ){
result = cacheString;
}else{
var keys = new List<string>();
keys.Add("FY");
keys.Add("Area");
keys.Add("PlanningUnit");
keys.Add("Name");
keys.Add("Title");
keys.Add("Program(s)");
var projects = await context.SnapEd_ProjectType.Where(t => t.FiscalYear == fiscalYear).ToListAsync();
var activitiesPerProject = await context.SnapEd_ActivityType.Where( p => p.PerProject == 1 && p.FiscalYear == fiscalYear).ToListAsync();
foreach( var project in projects){
foreach( var type in activitiesPerProject){
keys.Add( string.Concat( "\"", project.Name + type.Name, "\"") );
}
}
var activitiesNotPerProject = context.SnapEd_ActivityType.Where( p => p.PerProject != 1 && p.FiscalYear == fiscalYear);
foreach( var type in activitiesNotPerProject){
keys.Add( string.Concat( "\"", type.Name, "\""));
}
keys.Add( "TotalCommitmentHours" );
result = string.Join(",", keys.ToArray()) + "\n";
var commitmentList = await context.SnapEd_Commitment
.Where( c =>
c.FiscalYear == fiscalYear
&&
c.KersUser.RprtngProfile.Institution.Code == "21000-1862"
)
.Include( c => c.KersUser)
.ToListAsync();
var commitment = commitmentList.GroupBy( c => c.KersUser)
.Select( c => new {
User = c.Key,
commitments = c.Select( s => s )
}).ToList();
foreach( var usr in commitment){
var user = await context.KersUser.Where( u => u.Id == usr.User.Id)
.Include( u => u.RprtngProfile ).ThenInclude( r => r.PlanningUnit ).ThenInclude( u => u.ExtensionArea)
.Include( u => u.ExtensionPosition)
.Include( u => u.Specialties).ThenInclude( s => s.Specialty)
.FirstOrDefaultAsync();
var row = fiscalYear.Name + ",";
if(user.RprtngProfile.PlanningUnit.ExtensionArea != null){
row += user.RprtngProfile.PlanningUnit.ExtensionArea.Name + ",";
}else{
row += ",";
}
row += user.RprtngProfile.PlanningUnit.Name + ",";
row += string.Concat( "\"", user.RprtngProfile.Name, "\"") + ",";
if(this.context.zEmpProfileRole.Where( r => r.User.Id == user.Id && r.zEmpRoleType.shortTitle == "CNTMNGR" ).Any()){
row += string.Concat( "\"", user.ExtensionPosition.Code, ", CNTMNGR\"") + ",";
}else{
row += string.Concat( "\"", user.ExtensionPosition.Code, "\"") + ",";
}
var spclt = "";
if(user.Specialties != null){
foreach( var s in user.Specialties){
spclt += " " + (s.Specialty.Code.Substring( 0, 4) == "prog" ? s.Specialty.Code.Substring(4) : s.Specialty.Code);
}
}
row += string.Concat( "\"", spclt, "\"") + ",";
var sumHours = 0;
foreach( var project in projects){
foreach( var type in activitiesPerProject){
var cmtm = usr.commitments
.Where( c => c.SnapEd_ProjectTypeId == project.Id && c.SnapEd_ActivityTypeId == type.Id )
.FirstOrDefault();
if( cmtm != null){
if( type.Measurement == "Hour"){
sumHours += cmtm.Amount??0;
}
row += cmtm.Amount.ToString() + ",";
}else{
row += "0,";
}
}
}
foreach( var type in activitiesNotPerProject){
var cmtm = usr.commitments
.Where( c => c.SnapEd_ActivityTypeId == type.Id )
.FirstOrDefault();
if( cmtm != null){
if( type.Measurement == "Hour"){
sumHours += cmtm.Amount??0;
}
row += cmtm.Amount.ToString() + ",";
}else{
row += "0,";
}
}
row += sumHours.ToString() + ",";
result += row + "\n";
}
await _cache.SetStringAsync(cacheKey, result, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays( this.getCacheSpan(fiscalYear) )
});
}
return result;
}
public async Task<string> AgentsWithoutCommitment(FiscalYear fiscalYear, bool refreshCache = false){
string result;
var cacheKey = CacheKeys.SnapAgentsWithoutCommitment + fiscalYear.Name;
var cacheString = await _cache.GetStringAsync(cacheKey);
if (!string.IsNullOrEmpty(cacheString) && !refreshCache ){
result = cacheString;
}else{
var keys = new List<string>();
keys.Add("Area");
keys.Add("PlanningUnit");
keys.Add("Name");
keys.Add("Title");
keys.Add("Program(s)");
result = string.Join(",", keys.ToArray()) + "\n";
var agents = await context.KersUser
.Where( u =>
u.RprtngProfile.enabled
&&
u.ExtensionPosition.Code == "AGENT"
&&
u.RprtngProfile.Institution.Code == "21000-1862"
&&
context.SnapEd_Commitment.Where( c => c.FiscalYear == fiscalYear && c.KersUser == u).Count() == 0
)
.Include( u => u.RprtngProfile ).ThenInclude( r => r.PlanningUnit ).ThenInclude( u => u.ExtensionArea)
.Include( u => u.ExtensionPosition)
.Include( u => u.Specialties).ThenInclude( s => s.Specialty)
.ToListAsync();
foreach( var user in agents){
var row = "";
if(user.RprtngProfile.PlanningUnit.ExtensionArea != null){
row += user.RprtngProfile.PlanningUnit.ExtensionArea.Name + ",";
}else{
row += ",";
}
row += user.RprtngProfile.PlanningUnit.Name + ",";
row += string.Concat( "\"", user.RprtngProfile.Name, "\"") + ",";
if(this.context.zEmpProfileRole.Where( r => r.User.Id == user.Id && r.zEmpRoleType.shortTitle == "CNTMNGR" ).Any()){
row += string.Concat( "\"", user.ExtensionPosition.Code, ", CNTMNGR\"") + ",";
}else{
row += string.Concat( "\"", user.ExtensionPosition.Code, "\"") + ",";
}
var spclt = "";
if(user.Specialties != null){
foreach( var s in user.Specialties){
spclt += " " + (s.Specialty.Code.Substring( 0, 4) == "prog" ? s.Specialty.Code.Substring(4) : s.Specialty.Code);
}
}
row += string.Concat( "\"", spclt, "\"") + ",";
result += row + "\n";
}
await _cache.SetStringAsync(cacheKey, result, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays( this.getCacheSpan(fiscalYear) )
});
}
return result;
}
public async Task<string> SummaryByPlanningUnit(FiscalYear fiscalYear, bool refreshCache = false){
string result;
var cacheKey = CacheKeys.SnapCommitmentSummaryByPlanningUnit + fiscalYear.Name;
var cacheString = await _cache.GetStringAsync(cacheKey);
if (!string.IsNullOrEmpty(cacheString) && !refreshCache ){
result = cacheString;
}else{
var keys = new List<string>();
keys.Add("FY");
keys.Add("PlanningUnit");
var projects = await context.SnapEd_ProjectType.Where(t => t.FiscalYear == fiscalYear).ToListAsync();
var activitiesPerProject = await context.SnapEd_ActivityType.Where( p => p.PerProject == 1 && p.FiscalYear == fiscalYear).ToListAsync();
foreach( var project in projects){
foreach( var type in activitiesPerProject){
keys.Add( string.Concat( "\"", project.Name + type.Name, "\"") );
}
}
var activitiesNotPerProject = context.SnapEd_ActivityType.Where( p => p.PerProject != 1 && p.FiscalYear == fiscalYear);
foreach( var type in activitiesNotPerProject){
keys.Add( string.Concat( "\"", type.Name, "\""));
}
keys.Add( "TotalCommitmentHours" );
result = string.Join(",", keys.ToArray()) + "\n";
var commitmentList = await context.SnapEd_Commitment
.Where( c =>
c.FiscalYear == fiscalYear
&&
c.KersUser.RprtngProfile.Institution.Code == "21000-1862"
)
.Include( c => c.KersUser ).ThenInclude( u => u.RprtngProfile ).ThenInclude( p => p.PlanningUnit)
.ToListAsync();
var commitment = commitmentList.GroupBy( c => c.KersUser.RprtngProfile.PlanningUnit)
.Select( c => new {
Unit = c.Key,
commitments = c.Select( s => s )
})
.OrderBy(s => s.Unit.Name)
.ToList();
foreach( var unit in commitment){
var row = fiscalYear.Name + ",";
row += unit.Unit.Name + ",";
var sumHours = 0;
foreach( var project in projects){
foreach( var type in activitiesPerProject){
var cmtm = unit.commitments
.Where( c => c.SnapEd_ProjectTypeId == project.Id && c.SnapEd_ActivityTypeId == type.Id );
if( cmtm != null){
if( type.Measurement == "Hour"){
sumHours += cmtm.Sum( s => s.Amount)??0;
}
row += cmtm.Sum( s => s.Amount).ToString() + ",";
}else{
row += "0,";
}
}
}
foreach( var type in activitiesNotPerProject){
var cmtm = unit.commitments
.Where( c => c.SnapEd_ActivityTypeId == type.Id );
if( cmtm != null){
if( type.Measurement == "Hour"){
sumHours += cmtm.Sum( s => s.Amount)??0;
}
row += cmtm.Sum( s => s.Amount).ToString() + ",";
}else{
row += "0,";
}
}
row += sumHours.ToString() + ",";
result += row + "\n";
}
await _cache.SetStringAsync(cacheKey, result, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays( this.getCacheSpan(fiscalYear) )
});
}
return result;
}
public async Task<string> SummaryByPlanningUnitNotNEPAssistants(FiscalYear fiscalYear, bool refreshCache = false){
string result;
var cacheKey = CacheKeys.SnapCommitmentSummaryByPlanningUnit + fiscalYear.Name;
var cacheString = await _cache.GetStringAsync(cacheKey);
if (!string.IsNullOrEmpty(cacheString) && !refreshCache ){
result = cacheString;
}else{
var keys = new List<string>();
keys.Add("FY");
keys.Add("PlanningUnit");
var projects = await context.SnapEd_ProjectType.Where(t => t.FiscalYear == fiscalYear).ToListAsync();
var activitiesPerProject = await context.SnapEd_ActivityType.Where( p => p.PerProject == 1 && p.FiscalYear == fiscalYear).ToListAsync();
foreach( var project in projects){
foreach( var type in activitiesPerProject){
keys.Add( string.Concat( "\"", project.Name + type.Name, "\"") );
}
}
var activitiesNotPerProject = context.SnapEd_ActivityType.Where( p => p.PerProject != 1 && p.FiscalYear == fiscalYear);
foreach( var type in activitiesNotPerProject){
keys.Add( string.Concat( "\"", type.Name, "\""));
}
keys.Add( "TotalCommitmentHours" );
result = string.Join(",", keys.ToArray()) + "\n";
var commitment = await context.SnapEd_Commitment
.Where( c =>
c.FiscalYear == fiscalYear
&&
c.KersUser.RprtngProfile.Institution.Code == "21000-1862"
&&
c.KersUser.Specialties.Where( s =>
s.Specialty.Name == "Expanded Food and Nutrition Education Program"
||
s.Specialty.Name == "Supplemental Nutrition Assistance Program Education"
).Count() == 0
)
.GroupBy( c => c.KersUser.RprtngProfile.PlanningUnit )
.Select( c => new {
Unit = c.Key,
commitments = c.Select( s => s )
})
.OrderBy(s => s.Unit.Name)
.ToListAsync();
foreach( var unit in commitment){
var row = fiscalYear.Name + ",";
row += unit.Unit.Name + ",";
var sumHours = 0;
foreach( var project in projects){
foreach( var type in activitiesPerProject){
var cmtm = unit.commitments
.Where( c => c.SnapEd_ProjectTypeId == project.Id && c.SnapEd_ActivityTypeId == type.Id );
if( cmtm != null){
if( type.Measurement == "Hour"){
sumHours += cmtm.Sum( s => s.Amount)??0;
}
row += cmtm.Sum( s => s.Amount).ToString() + ",";
}else{
row += "0,";
}
}
}
foreach( var type in activitiesNotPerProject){
var cmtm = unit.commitments
.Where( c => c.SnapEd_ActivityTypeId == type.Id );
if( cmtm != null){
if( type.Measurement == "Hour"){
sumHours += cmtm.Sum( s => s.Amount)??0;
}
row += cmtm.Sum( s => s.Amount).ToString() + ",";
}else{
row += "0,";
}
}
row += sumHours.ToString() + ",";
result += row + "\n";
}
await _cache.SetStringAsync(cacheKey, result, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays( this.getCacheSpan(fiscalYear) )
});
}
return result;
}
public async Task<string> ReinforcementItems(FiscalYear fiscalYear, bool refreshCache = false){
string result;
var cacheKey = CacheKeys.SnapCommitmentReinforcementItems + fiscalYear.Name;
var cacheString = await _cache.GetStringAsync(cacheKey);
if (!string.IsNullOrEmpty(cacheString) && !refreshCache ){
result = cacheString;
}else{
var keys = new List<string>();
keys.Add("ItemName");
keys.Add("ItemCount");
result = string.Join(",", keys.ToArray()) + "\n";
var items = context.SnapEd_ReinforcementItemChoice
.Where( i =>
i.FiscalYear == fiscalYear
&&
i.KersUser.RprtngProfile.Institution.Code == "21000-1862"
)
.GroupBy( i => i.SnapEd_ReinforcementItem )
.Select( i => new {
item = i.Key,
amount = i.Select( s => s).Count()
})
.OrderBy( i => i.item.Name);
foreach( var item in items){
var row = item.item.Name + ",";
row += item.amount.ToString();
result += row + "\n";
}
await _cache.SetStringAsync(cacheKey, result, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays( this.getCacheSpan(fiscalYear) )
});
}
return result;
}
public async Task<string> ReinforcementItemsPerCounty(FiscalYear fiscalYear, bool refreshCache = false){
string result;
var cacheKey = CacheKeys.SnapCommitmentReinforcementItemsPerCounty + fiscalYear.Name;
var cacheString = await _cache.GetStringAsync(cacheKey);
if (!string.IsNullOrEmpty(cacheString) && !refreshCache ){
result = cacheString;
}else{
var keys = new List<string>();
keys.Add("District");
keys.Add("PlanningUnit");
var ReinforcementItems = context.SnapEd_ReinforcementItem.Where( a => a.FiscalYear == fiscalYear);
foreach( var item in ReinforcementItems){
keys.Add( string.Concat( "\"", item.Name, "\"") );
}
result = string.Join(",", keys.ToArray()) + "\n";
var counties = context.PlanningUnit.Where( p => p.District != null && p.Name.Substring(p.Name.Count() - 3) == "CES").Include(p => p.District).OrderBy( p => p.Name );
foreach( var county in counties){
var row = county.District.Name + ",";
row += county.Name + ",";
foreach( var item in ReinforcementItems){
var areItemsSelected = context.SnapEd_ReinforcementItemChoice
.Where( c =>
c.KersUser.RprtngProfile.PlanningUnit == county
&&
c.SnapEd_ReinforcementItem == item
&&
c.KersUser.RprtngProfile.Institution.Code == "21000-1862"
)
.Any();
if( areItemsSelected ){
row += "x" + ",";
}else{
row += ",";
}
}
result += row + "\n";
}
await _cache.SetStringAsync(cacheKey, result, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays( this.getCacheSpan(fiscalYear) )
});
}
return result;
}
public async Task<string> SuggestedIncentiveItems(FiscalYear fiscalYear, bool refreshCache = false){
string result;
var cacheKey = CacheKeys.SnapCommitmentSuggestedIncentiveItems + fiscalYear.Name;
var cacheString = await _cache.GetStringAsync(cacheKey);
if (!string.IsNullOrEmpty(cacheString) && !refreshCache ){
result = cacheString;
}else{
var keys = new List<string>();
keys.Add("District");
keys.Add("PlanningUnit");
keys.Add("Name");
keys.Add("Title");
keys.Add("Program(s)");
keys.Add("SuggestedIncentiveItems");
result = string.Join(",", keys.ToArray()) + "\n";
var suggestions = await context.SnapEd_ReinforcementItemSuggestion
.Where( u =>
u.FiscalYear == fiscalYear
&&
u.Suggestion != ""
&&
u.KersUser.RprtngProfile.Institution.Code == "21000-1862"
)
.Include( u => u.KersUser.RprtngProfile ).ThenInclude( r => r.PlanningUnit ).ThenInclude( u => u.District)
.Include( u => u.KersUser.ExtensionPosition)
.Include( u => u.KersUser.Specialties).ThenInclude( s => s.Specialty)
.ToListAsync();
foreach( var suggestion in suggestions){
var row = "";
if(suggestion.KersUser.RprtngProfile.PlanningUnit.District != null){
row += suggestion.KersUser.RprtngProfile.PlanningUnit.District.Name + ",";
}else{
row += ",";
}
row += suggestion.KersUser.RprtngProfile.PlanningUnit.Name + ",";
row += string.Concat( "\"", suggestion.KersUser.RprtngProfile.Name, "\"") + ",";
row += suggestion.KersUser.ExtensionPosition.Code + ",";
var spclt = "";
if(suggestion.KersUser.Specialties != null){
foreach( var s in suggestion.KersUser.Specialties){
spclt += " " + (s.Specialty.Code.Substring( 0, 4) == "prog" ? s.Specialty.Code.Substring(4) : s.Specialty.Code);
}
}
row += string.Concat( "\"", spclt, "\"") + ",";
row += string.Concat( "\"", suggestion.Suggestion, "\"") + ",";
result += row + "\n";
}
await _cache.SetStringAsync(cacheKey, result, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays( this.getCacheSpan(fiscalYear) )
});
}
return result;
}
}
public class CommitmentSummaryViewModel{
public string FY;
public string District;
public string PlanningUnit;
public string Name;
public string Title;
public string Programs;
public string HoursReportedLastFY;
public string HoursCommittedLastFY;
public string HoursCommittedThisFY;
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityStandardAssets._2D;
public class Projectile : NetworkBehaviour
{
private Rigidbody2D rb;
public float velocity;
public float direction;
private float fuseTime;
private float startTime;
public GameObject fragment;
// Use this for initialization
void Start()
{
rb = gameObject.GetComponent<Rigidbody2D>();
fuseTime = 1.5f;
startTime = Time.time;
//initial velocity of projectile will be specified from the Platformer2DUserControl
}
// Update is called once per frame
[ServerCallback]
void Update()
{
//the bomb explodes if 1.5 seconds has passed since it was thrown
gameObject.transform.Rotate(0,0,-120*Time.deltaTime);
if (Time.time - startTime >= fuseTime) {
explode();
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
//bomb also explodes if it comes into contact with another object
explode();
}
public void setStartTime(float startTime) { this.startTime = startTime; }
private void explode() {
//this bomb explodes into 8 fragments, which fly in all directions
for(float i = 0; i < 360; i+=360f/8f)
{
GameObject newfragment = Instantiate(fragment, new Vector2(transform.position.x + 2*Mathf.Sin((i*Mathf.PI)/180f), transform.position.y + 2 * Mathf.Cos((i * Mathf.PI) / 180f)), Quaternion.identity);
newfragment.GetComponent<Rigidbody2D>().velocity = new Vector2(50 * Mathf.Sin((i * Mathf.PI) / 180f), 50 * Mathf.Cos((i * Mathf.PI) / 180f));
NetworkServer.Spawn(newfragment);
}
//interrupts movement of players within 5 units radius and applies a 0.4 second stun to them
Collider2D[] inRange = Physics2D.OverlapCircleAll(transform.position, 5);
foreach (Collider2D cd in inRange)
{
GameObject other = cd.gameObject;
Platformer2DUserControl robot = other.GetComponent<Platformer2DUserControl>();
if (robot != null)
{
robot.applyStun(0.4f);
other.GetComponent<Rigidbody2D>().velocity = new Vector2(0, 0);
}
}
NetworkServer.Destroy(gameObject);
Destroy(gameObject);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CardGame
{
class Player
{
public int Index { get; init; }
public Player LeftNeighbor { get; set; }
public Player RightNeighbor { get; set; }
public List<Card> Cards { get; } = new List<Card>();
public List<Card> Base { get; } = new List<Card>();
public int Score { get; set; }
private List<Card> _newCards = new List<Card>();
private void TakeCards(IEnumerable<Card> newCards)
{
_newCards.AddRange(newCards);
}
public void SelectCard(int index)
{
if (index >= Cards.Count)
throw new ArgumentOutOfRangeException(nameof(index));
Base.Add(Cards[index]);
Cards.RemoveAt(index);
}
public void GiveAwayCards()
{
LeftNeighbor.TakeCards(Cards.Where(c => c.Direction == TransmissionDirection.Left));
RightNeighbor.TakeCards(Cards.Where(c => c.Direction == TransmissionDirection.Right));
}
public void CompleteExchange()
{
Cards.Clear();
Cards.AddRange(_newCards);
_newCards.Clear();
if (Cards.Count == 2 && Cards.Count(c => c.Direction == TransmissionDirection.Left) == 1)
{
Base.AddRange(Cards);
Cards.Clear();
}
}
public void Scoring()
{
int leftCard = Base.Count(c => c.Direction == TransmissionDirection.Left);
Score = Math.Min(Base.Count - leftCard, leftCard);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder($"Player {Index} Score {Score} ");
sb.AppendJoin(" ", Cards);
return sb.ToString();
}
}
} |
using System;
using UnityEngine;
using System.Collections.Generic;
using System.Threading;
using PurificationPioneer.Scriptable;
using ReadyGamerOne.Common;
using ReadyGamerOne.Network;
using ReadyGamerOne.Utility;
using UnityEngine.Assertions;
namespace PurificationPioneer.Network
{
public class NetworkMgr:GlobalMonoSingleton<NetworkMgr>
{
#region 网络事件处理_监听于分发
//事件监听委托
public delegate void ReceiveCmdPackageCallback(CmdPackageProtocol.CmdPackage package);
//事件队列
private Queue<CmdPackageProtocol.CmdPackage> msgQueue = new Queue<CmdPackageProtocol.CmdPackage>();
private object queueLock=new object();
//监听者字典
private Dictionary<int, ReceiveCmdPackageCallback> msgListeners =
new Dictionary<int, ReceiveCmdPackageCallback>();
/// <summary>
/// 添加监听者
/// </summary>
/// <param name="sType"></param>
/// <param name="func"></param>
public void AddNetMsgListener(int sType, ReceiveCmdPackageCallback func)
{
if (this.msgListeners.ContainsKey(sType))
this.msgListeners[sType] += func;
else
this.msgListeners.Add(sType, func);
}
/// <summary>
/// 移除监听者
/// </summary>
/// <param name="sType"></param>
/// <param name="func"></param>
public void RemoveNetMsgListener(int sType, ReceiveCmdPackageCallback func)
{
if (!msgListeners.ContainsKey(sType))
return;
msgListeners[sType] -= func;
if (msgListeners[sType] == null)
msgListeners.Remove(sType);
}
protected override void Update()
{
base.Update();
lock (this.queueLock)
{
while (this.msgQueue.Count > 0)
{// 有事件,广播消息
var pk = msgQueue.Dequeue();
if (msgListeners.ContainsKey(pk.serviceType))
{
msgListeners[pk.serviceType]?.Invoke(pk);
}
}
}
}
#endregion
private TcpHelper tcp;
private UdpHelper udp;
private bool errorInside = false;
/// <summary>
/// 建立Udp服务
/// </summary>
/// <param name="onFinishSetup"></param>
public void SetupUdp(Action<bool> onFinishSetup=null)
{
GameSettings.Instance.SetUdpLocalPort(NetUtil.GetUdpPort());
udp = new UdpHelper(
GameSettings.Instance.UdpServerIp,
GameSettings.Instance.UdpServerPort,
GameSettings.Instance.UdpLocalPort,
OnError,
OnRecvCmd,
GameSettings.Instance.MaxUdpPackageSize,
() => GameSettings.Instance.EnableSocketLog,
() =>
{
GameSettings.Instance.SetUdpLocalIp(udp.LocalIp);
#if DebugMode
if (GameSettings.Instance.EnableProtoLog)
{
Debug.Log($"UdpServer[{GameSettings.Instance.UdpServerIp}:{GameSettings.Instance.UdpServerPort}, " +
$"Local[{GameSettings.Instance.UdpLocalIp}:{GameSettings.Instance.UdpLocalPort}]");
}
#endif
onFinishSetup?.Invoke(!errorInside);
});
}
/// <summary>
/// 建立Tcp服务
/// </summary>
private void SetupTcp()
{
tcp=new TcpHelper(
GameSettings.Instance.GatewayIp,
GameSettings.Instance.GatewayPort,
OnError,
OnRecvCmd,
GameSettings.Instance.MaxTcpPackageSize,
GameSettings.Instance.MaxWaitTime,
()=>GameSettings.Instance.EnableSocketLog);
}
#region 发送数据
public void UdpSendProtobuf(int serviceType, int cmdType, ProtoBuf.IExtensible body = null)
{
if (udp == null)
{
Debug.LogError("Udp is null");
return;
}
if (!udp.IsValid)
{
Debug.LogError($"Udp状态异常");
return;
}
var cmdPackage = CmdPackageProtocol.PackageProtobuf(serviceType, cmdType, body);
if (cmdPackage == null)
return;
this.udp.Send(cmdPackage);
}
public void TcpSendJson(int serviceType, int cmdType, string jsonStr)
{
if (tcp == null || !tcp.IsValid)
{
Debug.LogError("tcp 状态异常,无法使用");
return;
}
var cmdPackage = CmdPackageProtocol.PackageJson(serviceType, cmdType, jsonStr);
if (cmdPackage == null)
return;
var tcpPackage = TcpProtocol.Pack(cmdPackage);
if (tcpPackage == null)
return;
tcp.Send(tcpPackage);
}
public void TcpSendProtobuf(int serviceType, int cmdType, ProtoBuf.IExtensible body=null)
{
if (tcp == null || !tcp.IsValid)
{
Debug.LogError("tcp 状态异常,无法使用");
return;
}
var cmdPackage = CmdPackageProtocol.PackageProtobuf(serviceType, cmdType, body);
Assert.IsNotNull(cmdPackage);
var tcpPackage = TcpProtocol.Pack(cmdPackage);
Assert.IsNotNull(tcpPackage);
tcp.Send(tcpPackage);
}
#endregion
#region Private
/// <summary>
/// 初始化
/// </summary>
protected override void OnStateIsNull()
{
base.OnStateIsNull();
SetupTcp();
Application.quitting += Disconnect;
}
protected override void OnDestroy()
{
base.OnDestroy();
if (GameSettings.Instance.EnableSocketLog)
{
Debug.Log("OnDestroy_关闭链接");
}
this.Disconnect();
}
/// <summary>
/// 断开链接
/// </summary>
public void Disconnect()
{
tcp?.CloseReceiver();
tcp = null;
udp?.CloseReceiver();
udp = null;
}
/// <summary>
/// 任何异常都调用
/// </summary>
/// <param name="o"></param>
private void OnError(object o)
{
this.errorInside = true;
if (!(o is ThreadAbortException))
{
Debug.Log(o);
}
if (GameSettings.Instance.CloseSocketOnAnyException)
{
Disconnect();
}
}
/// <summary>
/// 接收到命令
/// </summary>
/// <param name="pkgData"></param>
/// <param name="rawDataStart"></param>
/// <param name="rawDataLen"></param>
private void OnRecvCmd(byte[] pkgData, int rawDataStart, int rawDataLen)
{
CmdPackageProtocol.CmdPackage msg;
//解析
if (!CmdPackageProtocol.UnpackProtobuf(pkgData, rawDataStart, rawDataLen, out msg))
return;
if (null == msg)
return;
#if DebugMode
if (GameSettings.Instance.EnableSocketLog)
{
Debug.Log($"收到CmdPackage:{{sType-{msg.serviceType},cType-{msg.cmdType}}}");
}
#endif
//将收到消息放到事件队列
lock (queueLock)
{
this.msgQueue.Enqueue(msg);
}
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Drawing;
using Client.UI.Base.Enums;
namespace Client.UI.Base.Controls
{
public class CmSysButton
{
private Rectangle bounds;
private ControlBoxState boxState;
private Point location;
private string name;
private Forms.FormBase ownerForm;
private System.Drawing.Size size;
private Image sysButtonDown;
private Image sysButtonMouse;
private Image sysButtonNorml;
private string toolTip;
private bool visibale;
public CmSysButton()
{
this.location = new Point(0, 0);
this.size = new System.Drawing.Size(0x1c, 20);
this.visibale = true;
}
public CmSysButton Clone()
{
return new CmSysButton { Bounds = this.Bounds, Location = this.Location, size = this.Size, ToolTip = this.ToolTip, SysButtonNorml = this.SysButtonNorml, SysButtonMouse = this.SysButtonMouse, SysButtonDown = this.SysButtonDown, OwnerForm = this.OwnerForm, Name = this.Name };
}
[Browsable(false)]
public Rectangle Bounds
{
get
{
if (this.bounds == Rectangle.Empty)
{
this.bounds = new Rectangle();
}
this.bounds.Location = this.Location;
this.bounds.Size = this.Size;
return this.bounds;
}
set
{
this.bounds = value;
this.Location = this.bounds.Location;
this.Size = this.bounds.Size;
}
}
[Browsable(false)]
public ControlBoxState BoxState
{
get
{
return this.boxState;
}
set
{
if (this.boxState != value)
{
this.boxState = value;
if (this.OwnerForm != null)
{
this.OwnerForm.Invalidate(this.Bounds);
}
}
}
}
[Browsable(false), Category("按钮的位置")]
public Point Location
{
get
{
return this.location;
}
set
{
if (this.location != value)
{
this.location = value;
}
}
}
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}
[Browsable(false)]
public Forms.FormBase OwnerForm
{
get
{
return this.ownerForm;
}
set
{
this.ownerForm = value;
}
}
[DefaultValue(typeof(System.Drawing.Size), "28, 20"), Description("设置或获取自定义系统按钮的大小"), Category("按钮大小")]
public System.Drawing.Size Size
{
get
{
return this.size;
}
set
{
if (this.size != value)
{
this.size = value;
}
}
}
[Description("自定义系统按钮点击时"), Category("按钮图像")]
public Image SysButtonDown
{
get
{
return this.sysButtonDown;
}
set
{
if (this.sysButtonDown != value)
{
this.sysButtonDown = value;
}
}
}
[Category("按钮图像"), Description("自定义系统按钮悬浮时")]
public Image SysButtonMouse
{
get
{
return this.sysButtonMouse;
}
set
{
if (this.sysButtonMouse != value)
{
this.sysButtonMouse = value;
}
}
}
[Category("按钮图像"), Description("自定义系统按钮初始时")]
public Image SysButtonNorml
{
get
{
return this.sysButtonNorml;
}
set
{
if (this.sysButtonNorml != value)
{
this.sysButtonNorml = value;
}
}
}
[Category("悬浮提示"), Description("自定义系统按钮悬浮提示")]
public string ToolTip
{
get
{
return this.toolTip;
}
set
{
if (this.toolTip != value)
{
this.toolTip = value;
}
}
}
[Description("自定义系统按钮是否显示"), DefaultValue(typeof(bool), "true"), Category("是否显示")]
public bool Visibale
{
get
{
return this.visibale;
}
set
{
if (this.visibale != value)
{
this.visibale = value;
}
}
}
}
}
|
using Zenject;
namespace Lonely
{
public static class GameCommands
{
public class EnemyTurn : Command { }
public class PlayerTurn : Command { }
public class Escape : Command { }
public class Die : Command { }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Circle_Of_Trust : MonoBehaviour
{
public InputField ICircumference;
public InputField IDiameter;
public Text p;
public Text r;
float d;
float c;
float radius = 0;
float points = 0;
float total = 0;
// Use this for initialization
void Start ()
{
Randomize();
}
// Update is called once per frame
void Update ()
{
}
float CalculateCircumference()
{
float ans = 2 * 3.14f * radius;
return ans;
}
float CalculateDiameter()
{
return radius * 2;
}
void Solve()
{
d = CalculateDiameter();
c = CalculateCircumference();
Debug.Log("Circumference:\t" + c + "\n");
Debug.Log("Diameter:\t" + d + "\n");
}
public void CheckAns()
{
if (IDiameter.text == d.ToString())
{
points++;
total++;
Debug.Log("Correct Diameter\n");
}
else
total++;
if (ICircumference.text == c.ToString())
{
points++;
total++;
Debug.Log("Correct Circumference\n");
}
else
total++;
Debug.Log("Points\t" + points);
p.text = "Points:\t" + points + "/" + total + "\nGrade:\t" + (int)((points / total) * 100) + "%";
Randomize();
}
public void Randomize()
{
ICircumference.text = "";
IDiameter.text = "";
int[] numbers = new int[121];
for (int i = 0; i < 121; i++)
{
numbers[i] = i;
}
radius = UnityEngine.Random.Range(1, numbers.Length);
r.text = radius.ToString() + " m";
Solve();
}
}
|
using System.Collections.Generic;
using System.Windows;
namespace ShearCell_Data.Model
{
public class MetamaterialModel
{
public List<Vertex> Vertices { get; }
public List<Edge> Edges { get; }
public List<Cell> Cells { get; }
public Dictionary<Vertex, List<Vector>> InputMotion { get; }
public Dictionary<Vertex, List<Vector>> OutputMotion { get; }
public List<List<Edge>> ConstraintsGraph { get; private set; }
public List<List<List<Edge>>> ConnectedComponents { get; private set; }
//public Vertex InputVertex { get; set; }
//public List<Vector> InputPath { get; set; }
//public Vertex OutputVertex { get; set; }
//public List<Vector> OutputPath { get; set; }
public MetamaterialModel()
{
Vertices = new List<Vertex>();
Edges = new List<Edge>();
Cells = new List<Cell>();
InputMotion = new Dictionary<Vertex, List<Vector>>();
OutputMotion = new Dictionary<Vertex, List<Vector>>();
//InputPath = new List<Vector>();
//OutputPath = new List<Vector>();
}
public void Clear()
{
Reset();
Cells.Clear();
Vertices.Clear();
Edges.Clear();
}
public void Reset()
{
ResetDeformation();
ResetInput();
}
public void ResetDeformation()
{
foreach (var vertex in Vertices)
vertex.ResetDeformation();
}
public void ResetInput()
{
InputMotion.Clear();
OutputMotion.Clear();
//InputPath.Clear();
//InputVertex = null;
//OutputPath.Clear();
//OutputVertex = null;
}
public List<Vertex> GetAnchors()
{
return Vertices.FindAll(cell => cell.IsAnchor);
}
public void AddCell(Cell cell, Vector indexPosition, Size size)
{
var existingCell = Cells.Find(c => c.IndexVertex.Equals(indexPosition));
if (existingCell != null)
DeleteCell(indexPosition);
var vertices = ContstructNewCellVertices(indexPosition, size);
AddCellFromVertices(cell, vertices);
}
public void AddCellFromVertices(Cell cell, List<Vertex> vertices)
{
AddVertices(vertices, cell);
AddEdges(vertices, cell);
Cells.Add(cell);
//LinkAdjacentVertices(vertices);
}
internal void DeleteCell(Vector indexPosition)
{
var cellToDelete = Cells.Find(cell => cell.IndexVertex.Equals(indexPosition));
if(cellToDelete == null)
return;
foreach (var cellVertex in cellToDelete.CellVertices)
{
if (cellVertex.ContainingCells.Count <= 1)
{
Vertices.Remove(cellVertex);
Edges.RemoveAll(edge => edge.Contains(cellVertex));
}
cellVertex.ContainingCells.Remove(cellToDelete);
}
Cells.Remove(cellToDelete);
}
public void AddAnchor(Vector gridPosition)
{
//var vertex = new Vertex(CoordinateConverter.ConvertScreenToGlobalCellCoordinates(ellipseScreenPosition));
var vertex = new Vertex(gridPosition);
var existingVertex = Vertices.Find(x => x.Equals(vertex));
if (existingVertex == null)
return;
existingVertex.IsAnchor = !existingVertex.IsAnchor;
//if(existingVertex.IsAnchor)
PropagateAnchors(existingVertex);
}
public int GetDegreesOfFreedom()
{
BuildConstraintsGraph();
GetConnectedComponents();
return ConnectedComponents.Count;
}
private void PropagateAnchors(Vertex anchor)
{
var newAnchors = new List<Vertex>();
foreach (var cell in anchor.ContainingCells)
{
if (cell.CanMove())
continue;
foreach (var vertex in cell.CellVertices)
{
if(vertex.IsAnchor)
continue;
vertex.IsAnchor = true;
newAnchors.Add(vertex);
}
}
PropagateAnchors(newAnchors);
}
private void PropagateAnchors(List<Vertex> newAnchors)
{
foreach (var anchor in newAnchors)
{
foreach (var cell in anchor.ContainingCells)
{
if (cell.CanMove())
continue;
foreach (var vertex in cell.CellVertices)
{
if (vertex.IsAnchor)
continue;
vertex.IsAnchor = true;
}
}
}
}
private List<Vertex> ContstructNewCellVertices(Vector indexPosition, Size size)
{
var vertices = new List<Vertex>
{
new Vertex(indexPosition), //bottom left
new Vertex(new Vector(indexPosition.X + size.Width, indexPosition.Y)), //bottom right
new Vertex(new Vector(indexPosition.X + size.Width, indexPosition.Y + size.Height)), //top right
new Vertex(new Vector(indexPosition.X, indexPosition.Y + size.Height)) //top left
};
return vertices;
}
private void AddVertices(List<Vertex> vertices, Cell cell)
{
for (var i = 0; i < vertices.Count; i++)
{
var vertex = vertices[i];
if (!Vertices.Contains(vertex))
AddNewVertex(vertex, cell, i == 0);
else
LinkExistingVertex(vertex, cell, i == 0);
}
}
private void AddEdges(List<Vertex> vertices, Cell cell)
{
Edge edge;
for (var i = 1; i < vertices.Count; i++)
{
edge = new Edge(vertices[i - 1], vertices[i]);
if (Edges.Contains(edge))
{
var existingEdge = Edges.Find(e => e.Equals(edge));
cell.CellEdges.Add(existingEdge);
}
else
{
cell.CellEdges.Add(edge);
Edges.Add(edge);
}
}
edge = new Edge(vertices[vertices.Count - 1], vertices[0]);
if (Edges.Contains(edge))
{
var existingEdge = Edges.Find(e => e.Equals(edge));
cell.CellEdges.Add(existingEdge);
}
else
{
cell.CellEdges.Add(edge);
Edges.Add(edge);
}
}
private void AddNewVertex(Vertex vertex, Cell cell, bool isFirst)
{
vertex.ContainingCells.Add(cell);
if (isFirst)
cell.IndexVertex = vertex;
cell.CellVertices.Add(vertex);
Vertices.Add(vertex);
}
private void LinkExistingVertex(Vertex vertex, Cell cell, bool isFirst)
{
var existingVertex = Vertices.Find(x => x.Equals(vertex));
existingVertex.ContainingCells.Add(cell);
if (isFirst)
cell.IndexVertex = existingVertex;
cell.CellVertices.Add(existingVertex);
}
private void BuildConstraintsGraph()
{
ConstraintsGraph = new List<List<Edge>>();
foreach (var cell in Cells)
{
ConstraintsGraph.AddRange(cell.GetConstraintGraphRepresentation());
//if (cell is RigidCell)
//{
// ConstraintsGraph.Add(cell.CellEdges);
//}
//else
//{
// //horizontal
// ConstraintsGraph.Add(new List<Edge> { cell.CellEdges[1], cell.CellEdges[3] });
// //vertical
// ConstraintsGraph.Add(new List<Edge> { cell.CellEdges[0], cell.CellEdges[2] });
//}
}
}
private void GetConnectedComponents()
{
ConnectedComponents = new List<List<List<Edge>>>();
var toVisit = new List<List<Edge>>(ConstraintsGraph);
var edgesToVisit = new List<Edge>();
var visitedEdges = new List<Edge>();
while (toVisit.Count > 0)
{
var subcomponent = toVisit[0];
toVisit.RemoveAt(0);
var component = new List<List<Edge>> {subcomponent};
edgesToVisit.AddRange(subcomponent);
while (edgesToVisit.Count > 0)
{
var edge = edgesToVisit[0];
edgesToVisit.RemoveAt(0);
if (visitedEdges.Contains(edge))
continue;
visitedEdges.Add(edge);
var componentIndex = FindConnectedComponent(edge, toVisit);
if (componentIndex == -1)
continue;
var containingComponent = toVisit[componentIndex];
component.Add(containingComponent);
toVisit.RemoveAt(componentIndex);
edgesToVisit.AddRange(containingComponent);
}
ConnectedComponents.Add(component);
}
}
private int FindConnectedComponent(Edge edge, List<List<Edge>> components)
{
foreach (var component in components)
{
if (component.Contains(edge))
return components.IndexOf(component);
}
return -1;
}
//private void LinkAdjacentVertices(List<Vertex> vertices)
//{
// for (var i = 0; i < vertices.Count; i++)
// {
// var currentVertex = Vertices.Find(x => x.Equals(vertices[i]));
// var previousVertex = Vertices.Find(x => x.Equals(vertices[(i - 1 + vertices.Count) % vertices.Count]));
// var nextVertex = Vertices.Find(x => x.Equals(vertices[(i + 1 + vertices.Count) % vertices.Count]));
// if (!currentVertex.AdjacentVertices.Contains(previousVertex))
// currentVertex.AdjacentVertices.Add(previousVertex);
// if (!currentVertex.AdjacentVertices.Contains(nextVertex))
// currentVertex.AdjacentVertices.Add(nextVertex);
// }
//}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomerFinderWorkerRole.CognitiveServices.TextAnalytics.KeyPhrases.Response
{
public class DetectKeyPhrasesResponse
{
public Document[] documents { get; set; }
public Error[] errors { get; set; }
}
public class Document
{
public string[] keyPhrases { get; set; }
public string id { get; set; }
}
public class Error
{
public string id { get; set; }
public string message { get; set; }
}
}
|
/*
* DialMyCalls API
*
* The DialMyCalls API
*
* OpenAPI spec version: 2.0.1
* Contact: support@dialmycalls.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace IO.DialMyCalls.Model
{
/// <summary>
/// Callerid
/// </summary>
[DataContract]
public partial class Callerid : IEquatable<Callerid>
{
/// <summary>
/// Initializes a new instance of the <see cref="Callerid" /> class.
/// </summary>
/// <param name="Id">Unique identifier for this caller ID..</param>
/// <param name="Name">The name of the caller ID..</param>
/// <param name="Phone">The caller ID phone number..</param>
/// <param name="Approved">Whether this caller ID is approved for use..</param>
/// <param name="CreatedAt">When the caller id was created..</param>
/// <param name="UpdatedAt">When the caller id was last updated..</param>
public Callerid(Guid? Id = null, string Name = null, string Phone = null, bool? Approved = null, string CreatedAt = null, string UpdatedAt = null)
{
this.Id = Id;
this.Name = Name;
this.Phone = Phone;
this.Approved = Approved;
this.CreatedAt = CreatedAt;
this.UpdatedAt = UpdatedAt;
}
/// <summary>
/// Unique identifier for this caller ID.
/// </summary>
/// <value>Unique identifier for this caller ID.</value>
[DataMember(Name="id", EmitDefaultValue=false)]
public Guid? Id { get; set; }
/// <summary>
/// The name of the caller ID.
/// </summary>
/// <value>The name of the caller ID.</value>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// The caller ID phone number.
/// </summary>
/// <value>The caller ID phone number.</value>
[DataMember(Name="phone", EmitDefaultValue=false)]
public string Phone { get; set; }
/// <summary>
/// Whether this caller ID is approved for use.
/// </summary>
/// <value>Whether this caller ID is approved for use.</value>
[DataMember(Name="approved", EmitDefaultValue=false)]
public bool? Approved { get; set; }
/// <summary>
/// When the caller id was created.
/// </summary>
/// <value>When the caller id was created.</value>
[DataMember(Name="created_at", EmitDefaultValue=false)]
public string CreatedAt { get; set; }
/// <summary>
/// When the caller id was last updated.
/// </summary>
/// <value>When the caller id was last updated.</value>
[DataMember(Name="updated_at", EmitDefaultValue=false)]
public string UpdatedAt { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class Callerid {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Phone: ").Append(Phone).Append("\n");
sb.Append(" Approved: ").Append(Approved).Append("\n");
sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n");
sb.Append(" UpdatedAt: ").Append(UpdatedAt).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as Callerid);
}
/// <summary>
/// Returns true if Callerid instances are equal
/// </summary>
/// <param name="other">Instance of Callerid to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Callerid other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Phone == other.Phone ||
this.Phone != null &&
this.Phone.Equals(other.Phone)
) &&
(
this.Approved == other.Approved ||
this.Approved != null &&
this.Approved.Equals(other.Approved)
) &&
(
this.CreatedAt == other.CreatedAt ||
this.CreatedAt != null &&
this.CreatedAt.Equals(other.CreatedAt)
) &&
(
this.UpdatedAt == other.UpdatedAt ||
this.UpdatedAt != null &&
this.UpdatedAt.Equals(other.UpdatedAt)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.Phone != null)
hash = hash * 59 + this.Phone.GetHashCode();
if (this.Approved != null)
hash = hash * 59 + this.Approved.GetHashCode();
if (this.CreatedAt != null)
hash = hash * 59 + this.CreatedAt.GetHashCode();
if (this.UpdatedAt != null)
hash = hash * 59 + this.UpdatedAt.GetHashCode();
return hash;
}
}
}
}
|
//=======================================================================
// ClassName : MsgMotion
// 概要 : モーションメッセージ
//
//
// LiplisLive2D
// Copyright(c) 2017-2017 sachin. All Rights Reserved.
//=======================================================================
namespace Assets.Scripts.LiplisSystem.Msg
{
public class MsgMotion
{
public string GROUP_NAME;
public int NO;
public MsgMotion(string GROUP_NAME, int NO)
{
this.GROUP_NAME = GROUP_NAME;
this.NO = NO;
}
}
}
|
using UnityEngine;
using System;
public class Error
{
public static ushort OUT_STOP = 510; // 停服踢人
public static ushort MAP_NULL = 1510; // 场景为空
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NuevasEntidades;
namespace practicaFormClase8
{
public partial class Form2 : Form
{
private tempera _miTempera;
public Form2()
{
InitializeComponent();
foreach(ConsoleColor color in Enum.GetValues(typeof(ConsoleColor)))
{
this.comboBox1.Items.Add(color);
}
this.comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
this.comboBox1.SelectedItem = ConsoleColor.Red;
}
public tempera MiTempera {
get { return this._miTempera; }
}
private void button1_Click(object sender, EventArgs e)
{
string marca = this.textBox1.Text;
sbyte cantidad = sbyte.Parse(this.textBox2.Text);
System.ConsoleColor color = (System.ConsoleColor)this.comboBox1.SelectedItem;
this._miTempera = new tempera(cantidad,color,marca);
this.DialogResult= DialogResult.OK;
}
private void button2_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HZGZDL.YZFJKGZXFXY.Model {
class SystemMsgCollect {
}
}
|
using System;
using System.Linq;
using System.Collections.Generic;
using RipplerES.CommandHandler;
namespace RipplerES.EFCoreRepository
{
public class EfCoreEventRepository : IEventRepository, IDisposable
{
private readonly EventContext _db;
public EfCoreEventRepository(EventContext db)
{
_db = db;
}
public IEnumerable<AggregateEventData> GetEvents(Guid id)
{
return _db.Events.Where(c => c.AggregateId == id).Select(e => new AggregateEventData
{
Type = e.Type,
Data = e.Data
});
}
public int Save(Guid id, int expectedVersion, AggregateEventData aggregateEvent)
{
var last = _db.Events.Where(c => c.AggregateId == id)
.OrderByDescending(c => c.Version)
.FirstOrDefault();
if (last != null && expectedVersion != last.Version) throw new Exception("Wrong version");
if (last == null && expectedVersion != -1) throw new Exception("Not found");
_db.Events.Add(
new Event
{
AggregateId = id,
Version = NextVersion(expectedVersion),
Type = aggregateEvent.Type,
Data = aggregateEvent.Data,
MetaData = aggregateEvent.MetaData
});
_db.SaveChanges();
return NextVersion(expectedVersion);
}
private static int NextVersion(int expectedVersion)
{
return expectedVersion == -1 ? 1 : expectedVersion + 1;
}
public void Dispose()
{
throw new NotImplementedException();
}
}
}
|
using System;
namespace UserService.Models
{
public class Relationship
{
public Guid Id { get; set; }
public Guid Requestor { get; set; }
public Guid Requestee { get; set; }
public string RelationshipType { get; set; }
public string Status { get; set; }
}
} |
namespace SchoolClasses
{
public class Comments
{
private string comment;
public virtual string Comment
{
get { return this.comment; }
set { this.comment = value; }
}
}
}
|
using LuaInterface;
using SLua;
using System;
using UnityEngine;
public class Lua_UnityEngine_WheelHit : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int constructor(IntPtr l)
{
int result;
try
{
WheelHit wheelHit = default(WheelHit);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, wheelHit);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_collider(IntPtr l)
{
int result;
try
{
WheelHit wheelHit;
LuaObject.checkValueType<WheelHit>(l, 1, out wheelHit);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, wheelHit.get_collider());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_collider(IntPtr l)
{
int result;
try
{
WheelHit wheelHit;
LuaObject.checkValueType<WheelHit>(l, 1, out wheelHit);
Collider collider;
LuaObject.checkType<Collider>(l, 2, out collider);
wheelHit.set_collider(collider);
LuaObject.setBack(l, wheelHit);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_point(IntPtr l)
{
int result;
try
{
WheelHit wheelHit;
LuaObject.checkValueType<WheelHit>(l, 1, out wheelHit);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, wheelHit.get_point());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_point(IntPtr l)
{
int result;
try
{
WheelHit wheelHit;
LuaObject.checkValueType<WheelHit>(l, 1, out wheelHit);
Vector3 point;
LuaObject.checkType(l, 2, out point);
wheelHit.set_point(point);
LuaObject.setBack(l, wheelHit);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_normal(IntPtr l)
{
int result;
try
{
WheelHit wheelHit;
LuaObject.checkValueType<WheelHit>(l, 1, out wheelHit);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, wheelHit.get_normal());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_normal(IntPtr l)
{
int result;
try
{
WheelHit wheelHit;
LuaObject.checkValueType<WheelHit>(l, 1, out wheelHit);
Vector3 normal;
LuaObject.checkType(l, 2, out normal);
wheelHit.set_normal(normal);
LuaObject.setBack(l, wheelHit);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_forwardDir(IntPtr l)
{
int result;
try
{
WheelHit wheelHit;
LuaObject.checkValueType<WheelHit>(l, 1, out wheelHit);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, wheelHit.get_forwardDir());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_forwardDir(IntPtr l)
{
int result;
try
{
WheelHit wheelHit;
LuaObject.checkValueType<WheelHit>(l, 1, out wheelHit);
Vector3 forwardDir;
LuaObject.checkType(l, 2, out forwardDir);
wheelHit.set_forwardDir(forwardDir);
LuaObject.setBack(l, wheelHit);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_sidewaysDir(IntPtr l)
{
int result;
try
{
WheelHit wheelHit;
LuaObject.checkValueType<WheelHit>(l, 1, out wheelHit);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, wheelHit.get_sidewaysDir());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_sidewaysDir(IntPtr l)
{
int result;
try
{
WheelHit wheelHit;
LuaObject.checkValueType<WheelHit>(l, 1, out wheelHit);
Vector3 sidewaysDir;
LuaObject.checkType(l, 2, out sidewaysDir);
wheelHit.set_sidewaysDir(sidewaysDir);
LuaObject.setBack(l, wheelHit);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_force(IntPtr l)
{
int result;
try
{
WheelHit wheelHit;
LuaObject.checkValueType<WheelHit>(l, 1, out wheelHit);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, wheelHit.get_force());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_force(IntPtr l)
{
int result;
try
{
WheelHit wheelHit;
LuaObject.checkValueType<WheelHit>(l, 1, out wheelHit);
float force;
LuaObject.checkType(l, 2, out force);
wheelHit.set_force(force);
LuaObject.setBack(l, wheelHit);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_forwardSlip(IntPtr l)
{
int result;
try
{
WheelHit wheelHit;
LuaObject.checkValueType<WheelHit>(l, 1, out wheelHit);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, wheelHit.get_forwardSlip());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_forwardSlip(IntPtr l)
{
int result;
try
{
WheelHit wheelHit;
LuaObject.checkValueType<WheelHit>(l, 1, out wheelHit);
float forwardSlip;
LuaObject.checkType(l, 2, out forwardSlip);
wheelHit.set_forwardSlip(forwardSlip);
LuaObject.setBack(l, wheelHit);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_sidewaysSlip(IntPtr l)
{
int result;
try
{
WheelHit wheelHit;
LuaObject.checkValueType<WheelHit>(l, 1, out wheelHit);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, wheelHit.get_sidewaysSlip());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_sidewaysSlip(IntPtr l)
{
int result;
try
{
WheelHit wheelHit;
LuaObject.checkValueType<WheelHit>(l, 1, out wheelHit);
float sidewaysSlip;
LuaObject.checkType(l, 2, out sidewaysSlip);
wheelHit.set_sidewaysSlip(sidewaysSlip);
LuaObject.setBack(l, wheelHit);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
public static void reg(IntPtr l)
{
LuaObject.getTypeTable(l, "UnityEngine.WheelHit");
LuaObject.addMember(l, "collider", new LuaCSFunction(Lua_UnityEngine_WheelHit.get_collider), new LuaCSFunction(Lua_UnityEngine_WheelHit.set_collider), true);
LuaObject.addMember(l, "point", new LuaCSFunction(Lua_UnityEngine_WheelHit.get_point), new LuaCSFunction(Lua_UnityEngine_WheelHit.set_point), true);
LuaObject.addMember(l, "normal", new LuaCSFunction(Lua_UnityEngine_WheelHit.get_normal), new LuaCSFunction(Lua_UnityEngine_WheelHit.set_normal), true);
LuaObject.addMember(l, "forwardDir", new LuaCSFunction(Lua_UnityEngine_WheelHit.get_forwardDir), new LuaCSFunction(Lua_UnityEngine_WheelHit.set_forwardDir), true);
LuaObject.addMember(l, "sidewaysDir", new LuaCSFunction(Lua_UnityEngine_WheelHit.get_sidewaysDir), new LuaCSFunction(Lua_UnityEngine_WheelHit.set_sidewaysDir), true);
LuaObject.addMember(l, "force", new LuaCSFunction(Lua_UnityEngine_WheelHit.get_force), new LuaCSFunction(Lua_UnityEngine_WheelHit.set_force), true);
LuaObject.addMember(l, "forwardSlip", new LuaCSFunction(Lua_UnityEngine_WheelHit.get_forwardSlip), new LuaCSFunction(Lua_UnityEngine_WheelHit.set_forwardSlip), true);
LuaObject.addMember(l, "sidewaysSlip", new LuaCSFunction(Lua_UnityEngine_WheelHit.get_sidewaysSlip), new LuaCSFunction(Lua_UnityEngine_WheelHit.set_sidewaysSlip), true);
LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_WheelHit.constructor), typeof(WheelHit), typeof(ValueType));
}
}
|
using System.ComponentModel.DataAnnotations;
namespace Project33.Models
{
public class EditViewModel
{
[Required(ErrorMessage ="Не указан логин")]
public string Login { get; set; }
[Required(ErrorMessage ="Не указан возраст")]
public int Age { get; set; }
public string NewPassword { get; set; }
public string OldPassword { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using quanlinhahang_offical.classs;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
namespace quanlinhahang_offical.classs
{
class login
{
connect cn = new connect();
public bool isLogin(string username , string password )
{
bool kp = false;
if (cn.isConnect())
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = @"checkaccount";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = cn.cnt;
cmd.Parameters.AddWithValue("@user", username);
cmd.Parameters.AddWithValue("@pass", password);
//int i = cmd. ExecuteNonQuery();
int i = Convert.ToInt32(cmd.ExecuteScalar());
if (i > 0)
{
kp = true;
}
else
{
kp = false;
}
}
return kp;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class shootingScript : MonoBehaviour
{
[SerializeField] int damageDealt = 20;
[SerializeField]
LayerMask layermask;
Animator anim;
void Start()
{
anim = GetComponent<Animator>();
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
layermask |= Physics.IgnoreRaycastLayer;
layermask = ~layermask;
}
public GameObject losePanel;
void Update()
{
if (Input.GetKey(KeyCode.Escape))
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
if (Input.GetButtonDown ("Fire1"))
{
//Make a raycast with the line starting from center of camera
if(!losePanel.activeInHierarchy)
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
Ray mouseRay = GetComponentInChildren<Camera>().ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
RaycastHit hitInfo;
//Send the raycast and if the raycast hits something, print out the name to console
if (Physics.Raycast (mouseRay, out hitInfo, 100, layermask))
{
print(hitInfo.transform);
Debug.DrawLine(transform.position, hitInfo.point, Color.red, 5.0f);
HealthScript enemyHealth = hitInfo.transform.GetComponent<HealthScript>();
if (enemyHealth != null)
{
enemyHealth.Damage(damageDealt); //If enemy gets hit it takes damage
}
}
}
}
}
|
using Dapper;
using MySql.Data.MySqlClient;
using QualificationExaming.Entity;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QualificationExaming.Services
{
using IServices;
public class MultimediaService:IMultimediaService
{
/// <summary>
/// 多媒体题目表显示
/// </summary>
/// <returns></returns>
public List<Multimedia> GetDuoMei()
{
using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["connString"].ConnectionString))
{
//DynamicParameters parameters = new DynamicParameters();
//parameters.Add("p_knowledgePointID", knowledgePointID);
var questionlist = conn.Query<Multimedia>("select * from duomeiti", null);
if (questionlist != null)
{
return questionlist.ToList();
}
return null;
}
}
}
}
|
using System;
using System.Collections.Generic;
namespace TableTool
{
public class Equip_equip : LocalBean
{
protected override bool ReadImpl()
{
this.Id = base.readInt();
this.Name = base.readLocalString();
this.PropType = base.readInt();
this.Overlying = base.readInt();
this.Position = base.readInt();
this.Type = base.readInt();
this.EquipIcon = base.readInt();
this.Quality = base.readInt();
this.Attributes = base.readArraystring();
this.AttributesUp = base.readArrayint();
this.Skills = base.readArrayint();
this.SkillsUp = base.readArraystring();
this.AdditionSkills = base.readArraystring();
this.UnlockCondition = base.readArrayint();
this.InitialPower = base.readLocalString();
this.AddPower = base.readLocalString();
this.Powerratio = base.readLocalString();
this.SuperID = base.readArrayint();
this.BreakNeed = base.readInt();
this.MaxLevel = base.readInt();
this.UpgradeNeed = base.readInt();
this.Score = base.readInt();
this.SellPrice = base.readInt();
this.CritSellProb = base.readArraystring();
this.SellDiamond = base.readArrayfloat();
this.CardCost = base.readArrayint();
this.CoinCost = base.readArrayint();
return true;
}
public int Id { get; private set; }
public string Name { get; private set; }
public int PropType { get; private set; }
public int Overlying { get; private set; }
public int Position { get; private set; }
public int Type { get; private set; }
public int EquipIcon { get; private set; }
public int Quality { get; private set; }
public string[] Attributes { get; private set; }
public int[] AttributesUp { get; private set; }
public int[] Skills { get; private set; }
public string[] SkillsUp { get; private set; }
public string[] AdditionSkills { get; private set; }
public int[] UnlockCondition { get; private set; }
public string InitialPower { get; private set; }
public string AddPower { get; private set; }
public string Powerratio { get; private set; }
public int[] SuperID { get; private set; }
public int BreakNeed { get; private set; }
public int MaxLevel { get; private set; }
public int UpgradeNeed { get; private set; }
public int Score { get; private set; }
public int SellPrice { get; private set; }
public string[] CritSellProb { get; private set; }
public float[] SellDiamond { get; private set; }
public int[] CardCost { get; private set; }
public int[] CoinCost { get; private set; }
public override string ToString()
{
System.Reflection.PropertyInfo[] properties = typeof(Equip_equip).GetProperties();
List<string> strs = new List<string>();
foreach (System.Reflection.PropertyInfo info in properties)
{
var val = info.GetValue(this);
Type t = val.GetType();
string str = string.Empty;
if (t.IsArray)
{
Array arr = val as Array;
object[] strList = new object[arr.Length];
for (int i = 0; i < arr.Length; i++)
{
strList[i] = arr.GetValue(i);
}
str = string.Format(info.Name + ":{0}\n", string.Join(",", strList));
}
else
{
str = string.Format(info.Name + ":{0}\n", val);
}
strs.Add(str);
}
return string.Join(" ", strs.ToArray());
}
}
}
|
using System.Collections.Specialized;
using UnityEngine;
[CreateAssetMenu(menuName = "Data/FloatAxis")]
public class FloatInputAxis : FloatData
{
public string InputType;
public override float Value
{
get { return Input.GetAxis(InputType) * value; }
}
}
|
namespace JCFruit.WeebChat.Server.ChatEvents
{
public class UserJoined
{
public string Username { get; set; }
}
}
|
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
namespace Common.SourceGenerators
{
[Generator]
public class SourceGenerator : ISourceGenerator
{
public void Initialize(GeneratorInitializationContext context)
{
context.RegisterForSyntaxNotifications(() => new SyntaxReceiver());
}
public void Execute(GeneratorExecutionContext context)
{
if (context.SyntaxReceiver is not SyntaxReceiver receiver) return;
var types = receiver.CandidateTypes
.Select(x => context.Compilation.GetSemanticModel(x.SyntaxTree).GetDeclaredSymbol(x)!)
.ToImmutableList();
AddAutoCloneableClasses(context, types);
}
private static void AddAutoCloneableClasses(GeneratorExecutionContext context, ImmutableList<INamedTypeSymbol> types)
{
foreach (var type in types)
{
addSource($"{type.Name}.AutoCloneable.g", AutoCloneablePartialClassBuilder.Build(type));
//NOTE: If this addition is disabled, the crashes to the Roslyn Analyzer process do not occur.
// What is it about these static extensions that causes the process to crash?
addSource($"{type.Name}.AutoCloneableExtensions.g", AutoCloneableExtensionsClassBuilder.Build(type));
void addSource(string sourceFileName, string sourceCode)
{
var sourceText = CSharpSyntaxTree
.ParseText(SourceText.From(sourceCode, Encoding.UTF8))
.GetRoot().NormalizeWhitespace()
.GetText(Encoding.UTF8);
context.AddSource(sourceFileName, sourceText);
}
}
}
internal class SyntaxReceiver : ISyntaxReceiver
{
private static readonly string attributeName = nameof(AutoCloneableAttribute).Replace("Attribute", "");
public List<TypeDeclarationSyntax> CandidateTypes { get; } = new List<TypeDeclarationSyntax>();
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
if (syntaxNode is not TypeDeclarationSyntax typeDeclarationSyntax) return;
var hasAutoCloneableAttribute = typeDeclarationSyntax.AttributeLists
.SelectMany(attributeList => attributeList.Attributes, (_, attribute) => attribute.Name.ToString())
.Any(a => a == attributeName);
if (hasAutoCloneableAttribute) CandidateTypes.Add(typeDeclarationSyntax);
}
}
}
}
|
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour
{
// Use this for class variables.
public int newShip;
public AudioClip newShipClip;
private int score;
private int highScore;
private int nextNewShip;
// Use this for initialization when scene loads.
private void Awake()
{
newShip = 10000;
nextNewShip = newShip;
}
// Use this for initialization when game starts.
private void Start()
{
}
// Update is called once per frame.
private void Update()
{
}
// Update is called by physics.
private void FixedUpdate()
{
}
// When Collider is triggered by other.
private void OnTriggerEnter(Collider other)
{
}
// When object other leaves Collider.
private void OnTriggerExit(Collider other)
{
}
private void OnTriggerStay(Collider other)
{
}
public void AddScore(int Points)
{
score += Points;
Text scroeText = gameObject.GetComponent<Text>();
scroeText.text = "Score: " + score + " Arrow keys to move and rotate, Left CTRL to fire.";
if (score > highScore)
highScore = score;
if (score > nextNewShip)
{
nextNewShip = score + newShip;
gameObject.GetComponent<Game>().AddPlayerShip();
GetComponent<AudioSource>().clip = newShipClip;
GetComponent<AudioSource>().Play();
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
namespace AutoBazar
{
public class FindInDBCar : MenuProperties
{
public static List<DataCar> car = new List<DataCar>();
public static int selectMotorType = 0;
public static int maxMotorType = 2;
public static int selectColorType = 0;
public static int maxColorType = 9;
public static int selectGearBoxType = 0;
public static int maxGearBoxType = 9;
public static int selectTypeCar = 0;
public static int maxTypeCar = 13;
public static int selectFuelType = 0;
public static int maxFuelType = 5;
public FindInDBCar()
{
Console.Clear();
//select find
//in car,cargo,bus,...
FindInCarDB();
}
public static void FindInCarDB()
{
Console.Clear();
string jsonCar = File.ReadAllText(Environment.ExpandEnvironmentVariables("%AppData%\\MyProjects\\SaveCar.txt"));
List<DataCar> deserializedCar = JsonConvert.DeserializeObject<List<DataCar>>(jsonCar);
car = deserializedCar;
if (car == null)
{
//car = new List<DataCar>();
WriteTextWithCursorPosition("Nelze vyhledavat v prazdnem seznamu", 1);
Console.ReadKey();
return;
}
int selectItemID = 0;
string name = string.Empty;
string textPref = string.Empty;
string fuel = string.Empty;
int minPower = 0;
int maxPower = 0;
int minValueInCm = 0;
int maxValueInCm = 0;
int height = Console.WindowHeight;
do
{
if (selectMotorType > maxMotorType)
{
selectMotorType = maxMotorType;
}
if (selectColorType > maxColorType)
{
selectColorType = maxColorType;
}
if (selectGearBoxType > maxGearBoxType)
{
selectGearBoxType = maxGearBoxType;
}
if (selectTypeCar > maxTypeCar)
{
selectTypeCar = maxTypeCar;
}
if (selectFuelType > maxFuelType)
{
selectFuelType = maxFuelType;
}
Console.Clear();
WriteTextWithCursorPosition("Osobní auta", 1, ConsoleColor.White, ConsoleColor.Black);
WriteButton("Jméno - " + name, 0, 0, selectItemID);
//WriteButton("typ karoserie - " + typeCar, 1, 1, selectItemID);
//WriteButton("Síla motoru - " + minPower + "-" + maxPower, 2, 2, selectItemID);
//WriteButton("Objem motoru v cm - " + minValueInCm + "-" + maxValueInCm, 3, 3, selectItemID);
//WriteButton("Převodovka - " + gearBoxType, 4, 4, selectItemID);
//WriteButton("Barva - " + colorType, 5, 5, selectItemID);
//WriteButton("typ motoru - " + motorType, 6, 6, selectItemID);
//WriteButton("typ motoru - " + fuelType, 7, 7, selectItemID);
WriteButton("Najít", 8, 8, selectItemID, ConsoleColor.Red, ConsoleColor.DarkRed);
WriteButton("Odejít", 9, 9, selectItemID, ConsoleColor.Red, ConsoleColor.DarkRed);
ConsoleKeyInfo ans = Console.ReadKey(true);
ConsoleTextSelect(0, 9, ans, ref selectItemID);
ConsoleTypeSelect(0, maxMotorType, ans, ref selectMotorType, 6, selectItemID);
ConsoleTypeSelect(0, maxColorType, ans, ref selectColorType, 5, selectItemID);
ConsoleTypeSelect(0, maxGearBoxType, ans, ref selectGearBoxType, 4, selectItemID);
ConsoleTypeSelect(0, maxTypeCar, ans, ref selectTypeCar, 1, selectItemID);
ConsoleTypeSelect(0, maxFuelType, ans, ref selectTypeCar, 7, selectItemID);
if (ans.Key == ConsoleKey.Enter)
{
switch (selectItemID)
{
case 0:
WriteToButton(0, "Jméno - ");
name = Console.ReadLine();
break;
case 2:
WriteToButton(2, "Síla motoru - ");
minPower = int.Parse(Console.ReadLine());
maxPower = int.Parse(Console.ReadLine());
break;
case 3:
WriteToButton(3, "Objem motoru v cm - ");
minValueInCm = int.Parse(Console.ReadLine());
maxValueInCm = int.Parse(Console.ReadLine());
break;
case 8:
Console.Clear();
//WriteFindedCar(typeCar, minPower, maxPower, minValueInCm, maxValueInCm, gearBoxType, colorType, motorType, fuelType);
break;
case 9:
Console.Clear();
return;
default:
break;
}
}
} while (true);
}
//public static void WriteFindedCar(string typeCar, int minPower, int maxPower, int minValueInCm,
// int maxValueInCm, string gearBoxType, string colorType, string motorType, string fuelType)
//{
// Console.Clear();
// List<DataCar> typeCarList = car.FindAll(item => item.TypeCarString == typeCar);
// List<DataCar> powerCarList = car.FindAll(item => item.MotorPowerInKW >= minPower && item.MotorPowerInKW <= maxPower);
// List<DataCar> valueInCmCarList = car.FindAll(item => item.MotorValueInCm >= minValueInCm && item.MotorValueInCm <= maxValueInCm);
// List<DataCar> gearBoxTypeCarList = car.FindAll(item => item.GearBoxString == gearBoxType);
// List<DataCar> colorCarList = car.FindAll(item => item.ColorString == colorType);
// List<DataCar> motorCarList = car.FindAll(item => item.MotorTypeString == motorType);
// List<DataCar> fuelCarList = car.FindAll(item => item.FuelTypeString == fuelType);
// List<DataCar> CarList = new List<DataCar>();
// if (typeCarList.Count > 0 || powerCarList.Count > 0 || valueInCmCarList.Count > 0 ||
// gearBoxTypeCarList.Count > 0 || colorCarList.Count > 0 || motorCarList.Count > 0 ||
// fuelCarList.Count > 0)
// {
// if (typeCarList.Count > 0)
// {
// }
// }
// else
// {
// WriteTextWithCursorPosition("is empty", 1);
// }
// Console.ReadKey();
//}
}
}
|
using Mccole.Geodesy.Extension;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Mccole.Geodesy.Calculator
{
/// <summary>
/// Provides a series of Geodetic functions that can be used measure the earth's surface.
/// </summary>
public class GeodeticCalculator : CalculatorBase, IGeodeticCalculator
{
private static Lazy<IGeodeticCalculator> _instance = new Lazy<IGeodeticCalculator>(() => { return new GeodeticCalculator(); });
private GeodeticCalculator()
{
}
/// <summary>
/// Singleton instance of IGeodeticCalculator.
/// </summary>
public static IGeodeticCalculator Instance
{
get
{
return _instance.Value;
}
}
/// <summary>
/// Determine if a polygon encloses pole.
/// Sum of course deltas around pole is 0° rather than normal ±360°.
/// </summary>
/// <param name="polygon"></param>
/// <returns>True if the polygon encloses a pole.</returns>
private static bool IsPoleEnclosedBy(IEnumerable<ICoordinate> polygon)
{
// http://blog.element84.com/determining-if-a-spherical-polygon-contains-a-pole.html
// Chris Veness: any better test than this?
var ΣΔ = 0D;
var prevBrng = GeodeticCalculator.Instance.Bearing(polygon.First(), polygon.ElementAt(1));
for (var v = 0; v < polygon.Count() - 1; v++)
{
var bearing = GeodeticCalculator.Instance.Bearing(polygon.ElementAt(v), polygon.ElementAt(v + 1));
var finalBearing = GeodeticCalculator.Instance.FinalBearing(polygon.ElementAt(v), polygon.ElementAt(v + 1));
ΣΔ += (bearing - prevBrng + 540) % 360 - 180;
ΣΔ += (finalBearing - bearing + 540) % 360 - 180;
prevBrng = finalBearing;
}
var initialBearing = GeodeticCalculator.Instance.Bearing(polygon.First(), polygon.ElementAt(1));
ΣΔ += (initialBearing - prevBrng + 540) % 360 - 180;
// Chris Veness: fix (intermittent) edge crossing pole - eg (85,90), (85,0), (85,-90)
// 0°-ISH.
var enclosed = Math.Abs(ΣΔ) < 90;
return enclosed;
}
/// <summary>
/// Calculate how far the point is along a track from the start-point, heading towards the end-point.
/// <para>That is, if a perpendicular is drawn from the point to the (great circle) path, the along-track distance is the distance from the start point to where the perpendicular crosses the path.</para>
/// <para>Uses the mean radius of the Earth.</para>
/// </summary>
/// <param name="pointA">The point to calculate the distance from.</param>
/// <param name="startPoint">Start point of great circle path.</param>
/// <param name="endPoint">End point of great circle path.</param>
/// <returns>The distance along great circle to point nearest point A in metres.</returns>
public double AlongTrackDistance(ICoordinate pointA, ICoordinate startPoint, ICoordinate endPoint)
{
return AlongTrackDistance(pointA, startPoint, endPoint, Radius.Mean);
}
/// <summary>
/// Calculate how far the point is along a track from the start-point, heading towards the end-point.
/// <para>That is, if a perpendicular is drawn from the point to the (great circle) path, the along-track distance is the distance from the start point to where the perpendicular crosses the path.</para>
/// </summary>
/// <param name="pointA">The point to calculate the distance from.</param>
/// <param name="startPoint">Start point of great circle path.</param>
/// <param name="endPoint">End point of great circle path.</param>
/// <param name="radius">Radius of earth.</param>
/// <returns>The distance along great circle to point nearest point A in the same units as the radius.</returns>
public double AlongTrackDistance(ICoordinate pointA, ICoordinate startPoint, ICoordinate endPoint, double radius)
{
if (pointA == null)
{
throw new ArgumentNullException(nameof(pointA), "The argument cannot be null.");
}
if (startPoint == null)
{
throw new ArgumentNullException(nameof(startPoint), "The argument cannot be null.");
}
if (endPoint == null)
{
throw new ArgumentNullException(nameof(endPoint), "The argument cannot be null.");
}
ValidateRadius(radius);
var δ13 = startPoint.DistanceTo(pointA, radius) / radius;
var θ13 = startPoint.BearingTo(pointA).ToRadians();
var θ12 = startPoint.BearingTo(endPoint).ToRadians();
var δxt = Math.Asin(Math.Sin(δ13) * Math.Sin(θ13 - θ12));
var δat = Math.Acos(Math.Cos(δ13) / Math.Abs(Math.Cos(δxt)));
var result = δat * Math.Sign(Math.Cos(θ12 - θ13)) * radius;
return result;
}
/// <summary>
/// Calculate the area of a spherical polygon where the sides of the polygon are great circle arcs joining the vertices.
/// <para>Uses the mean radius of the Earth.</para>
/// </summary>
/// <param name="polygon">Array of points defining vertices of the polygon.</param>
/// <returns>The area of the polygon, in the same units as radius.</returns>
public double AreaOf(IEnumerable<ICoordinate> polygon)
{
return AreaOf(polygon, Radius.Mean);
}
/// <summary>
/// Calculate the area of a spherical polygon where the sides of the polygon are great circle arcs joining the vertices.
/// </summary>
/// <param name="polygon">Array of points defining vertices of the polygon.</param>
/// <param name="radius">Radius of earth.</param>
/// <returns>The area of the polygon, in the same units as radius.</returns>
public double AreaOf(IEnumerable<ICoordinate> polygon, double radius)
{
/*
* Uses method due to Karney - http://osgeo-org.1560.x6.nabble.com/Area-of-a-spherical-polygon-td3841625.html
* For each edge of the polygon, tan(E/2) = tan(Δλ/2)·(tan(φ1/2) + tan(φ2/2)) / (1 + tan(φ1/2)·tan(φ2/2))
* Where E is the spherical excess of the trapezium obtained by extending the edge to the equator
*/
ValidateRadius(radius);
List<ICoordinate> shape = new List<ICoordinate>(polygon);
// Close polygon so that last point equals first point.
var closed = shape.First().Equals(shape.Last());
if (!closed)
{
shape.Add(shape.First());
}
// Spherical excess in steradians.
var s = 0D;
var vertices = shape.Count - 1;
for (var v = 0; v < vertices; v++)
{
var φ1 = shape.ElementAt(v).Latitude.ToRadians();
var φ2 = shape.ElementAt(v + 1).Latitude.ToRadians();
var Δλ = (shape.ElementAt(v + 1).Longitude - shape.ElementAt(v).Longitude).ToRadians();
var E = 2 * Math.Atan2(Math.Tan(Δλ / 2) * (Math.Tan(φ1 / 2) + Math.Tan(φ2 / 2)), 1 + Math.Tan(φ1 / 2) * Math.Tan(φ2 / 2));
s += E;
}
if (IsPoleEnclosedBy(shape))
{
s = Math.Abs(s) - 2 * Math.PI;
}
// Area in units of radius.
var result = Math.Abs(s * radius * radius);
return result;
}
/// <summary>
/// Calculate the (initial) bearing from point A to point B.
/// </summary>
/// <param name="pointA">The start point.</param>
/// <param name="pointB">The end point.</param>
/// <returns>Initial bearing in degrees from north.</returns>
public double Bearing(ICoordinate pointA, ICoordinate pointB)
{
if (pointA == null)
{
throw new ArgumentNullException(nameof(pointA), "The argument cannot be null.");
}
if (pointB == null)
{
throw new ArgumentNullException(nameof(pointB), "The argument cannot be null.");
}
var φ1 = pointA.Latitude.ToRadians();
var φ2 = pointB.Latitude.ToRadians();
var Δλ = (pointB.Longitude - pointA.Longitude).ToRadians();
var y = Math.Sin(Δλ) * Math.Cos(φ2);
var x = Math.Cos(φ1) * Math.Sin(φ2) -
Math.Sin(φ1) * Math.Cos(φ2) * Math.Cos(Δλ);
var θ = Math.Atan2(y, x);
var result = (θ.ToDegrees() + 360) % 360;
return result;
}
/// <summary>
/// Calculate the pair of meridians at which a great circle defined by two points crosses the given latitude.
/// <para>If the great circle doesn't reach the given latitude, null is returned.</para>
/// </summary>
/// <param name="point1">First point defining great circle.</param>
/// <param name="point2">Second point defining great circle.</param>
/// <param name="latitude">Latitude crossings are to be determined for.</param>
/// <returns>Object containing { Longitude1, Longitude2 } or null if given latitude not reached.</returns>
public Tuple<double, double> CrossingParallels(ICoordinate point1, ICoordinate point2, double latitude)
{
if (point1 == null)
{
throw new ArgumentNullException(nameof(point1), "The argument cannot be null.");
}
if (point2 == null)
{
throw new ArgumentNullException(nameof(point2), "The argument cannot be null.");
}
if (latitude < -180 || latitude > 180)
{
throw new ArgumentOutOfRangeException(nameof(latitude), latitude, "The argument must be between -180 and 180.");
}
var φ = latitude.ToRadians();
var φ1 = point1.Latitude.ToRadians();
var λ1 = point1.Longitude.ToRadians();
var φ2 = point2.Latitude.ToRadians();
var λ2 = point2.Longitude.ToRadians();
var Δλ = λ2 - λ1;
var x = Math.Sin(φ1) * Math.Cos(φ2) * Math.Cos(φ) * Math.Sin(Δλ);
var y = Math.Sin(φ1) * Math.Cos(φ2) * Math.Cos(φ) * Math.Cos(Δλ) - Math.Cos(φ1) * Math.Sin(φ2) * Math.Cos(φ);
var z = Math.Cos(φ1) * Math.Cos(φ2) * Math.Sin(φ) * Math.Sin(Δλ);
// Great circle doesn't reach latitude.
if (z * z > x * x + y * y)
{
return null;
}
// Longitude at maximum latitude.
var λm = Math.Atan2(-y, x);
// Δλ from λm to intersection points.
var Δλi = Math.Acos(z / Math.Sqrt(x * x + y * y));
var λi1 = λ1 + λm - Δλi;
var λi2 = λ1 + λm + Δλi;
// Normalise to −180..+180°
var result = new Tuple<double, double>((λi1.ToDegrees() + 540) % 360 - 180, (λi2.ToDegrees() + 540) % 360 - 180);
return result;
}
/// <summary>
/// Calculate the (signed) distance from point A to great circle defined by start-point and end-point.
/// <para>Uses the mean radius of the Earth.</para>
/// <para>Also known as Cross Track Error.</para>
/// </summary>
/// <param name="pointA">The point to calculate the distance from.</param>
/// <param name="startPoint">Start point of great circle path.</param>
/// <param name="endPoint">End point of great circle path.</param>
/// <returns>Distance to great circle (negative if to left, positive if to right of path) in metres.</returns>
public double CrossTrackDistance(ICoordinate pointA, ICoordinate startPoint, ICoordinate endPoint)
{
return CrossTrackDistance(pointA, startPoint, endPoint, Radius.Mean);
}
/// <summary>
/// Calculate the (signed) distance from point A to great circle defined by start-point and end-point.
/// <para>Also known as Cross Track Error.</para>
/// </summary>
/// <param name="pointA">The point to calculate the distance from.</param>
/// <param name="startPoint">Start point of great circle path.</param>
/// <param name="endPoint">End point of great circle path.</param>
/// <param name="radius">Radius of earth.</param>
/// <returns>Distance to great circle (negative if to left, positive if to right of path) in the same units as the radius.</returns>
public double CrossTrackDistance(ICoordinate pointA, ICoordinate startPoint, ICoordinate endPoint, double radius)
{
if (pointA == null)
{
throw new ArgumentNullException(nameof(pointA), "The argument cannot be null.");
}
if (startPoint == null)
{
throw new ArgumentNullException(nameof(startPoint), "The argument cannot be null.");
}
if (endPoint == null)
{
throw new ArgumentNullException(nameof(endPoint), "The argument cannot be null.");
}
ValidateRadius(radius);
var δ13 = startPoint.DistanceTo(pointA, radius) / radius;
var θ13 = startPoint.BearingTo(pointA).ToRadians();
var θ12 = startPoint.BearingTo(endPoint).ToRadians();
var δxt = Math.Asin(Math.Sin(δ13) * Math.Sin(θ13 - θ12));
var result = δxt * radius;
return result;
}
/// <summary>
/// Calculate the destination point from point A having travelled the given distance on the given initial bearing.
/// <para>Bearing normally varies around path followed.</para>
/// <para>Uses the mean radius of the Earth in metres.</para>
/// </summary>
/// <param name="pointA">The start point.</param>
/// <param name="distance">Distance travelled, in same units as the earth's radius (metres).</param>
/// <param name="bearing">Initial bearing in degrees from north.</param>
/// <returns>The destination point.</returns>
public ICoordinate Destination(ICoordinate pointA, double distance, double bearing)
{
return Destination(pointA, distance, bearing, Radius.Mean);
}
/// <summary>
/// Calculate the destination point from point A having travelled the given distance on the given initial bearing.
/// <para>Bearing normally varies around path followed.</para>
/// </summary>
/// <param name="pointA">The start point.</param>
/// <param name="distance">Distance travelled, in same units as the earth's radius.</param>
/// <param name="bearing">Initial bearing in degrees from north.</param>
/// <param name="radius">Radius of earth.</param>
/// <returns>The destination point.</returns>
public ICoordinate Destination(ICoordinate pointA, double distance, double bearing, double radius)
{
/*
* sinφ2 = sinφ1⋅cosδ + cosφ1⋅sinδ⋅cosθ
* tanΔλ = sinθ⋅sinδ⋅cosφ1 / cosδ−sinφ1⋅sinφ2
* See http://mathforum.org/library/drmath/view/52049.html for derivation.
*/
if (pointA == null)
{
throw new ArgumentNullException(nameof(pointA), "The argument cannot be null.");
}
if (distance < 0)
{
throw new ArgumentOutOfRangeException(nameof(distance), "Must not be a negative number.");
}
ValidateBearing(bearing);
ValidateRadius(radius);
// Angular distance in radians.
var δ = distance / radius;
var θ = bearing.ToRadians();
var φ1 = pointA.Latitude.ToRadians();
var λ1 = pointA.Longitude.ToRadians();
var sinφ1 = Math.Sin(φ1);
var cosφ1 = Math.Cos(φ1);
var sinδ = Math.Sin(δ);
var cosδ = Math.Cos(δ);
var sinθ = Math.Sin(θ);
var cosθ = Math.Cos(θ);
var sinφ2 = sinφ1 * cosδ + cosφ1 * sinδ * cosθ;
var φ2 = Math.Asin(sinφ2);
var y = sinθ * sinδ * cosφ1;
var x = cosδ - sinφ1 * sinφ2;
var λ2 = λ1 + Math.Atan2(y, x);
// Normalise to −180..+180°.
var result = base.NewCoordinate(φ2.ToDegrees(), (λ2.ToDegrees() + 540) % 360 - 180);
return result;
}
/// <summary>
/// Calculate the distance between 2 points (using haversine formula).
/// <para>Uses the mean radius of the Earth.</para>
/// </summary>
/// <param name="pointA">The start point.</param>
/// <param name="pointB">The end point.</param>
/// <returns>Distance between this point and destination point, in same units as radius.</returns>
public double Distance(ICoordinate pointA, ICoordinate pointB)
{
return Distance(pointA, pointB, Radius.Mean);
}
/// <summary>
/// Calculate the distance between 2 points (using haversine formula).
/// </summary>
/// <param name="pointA">The start point.</param>
/// <param name="pointB">The end point.</param>
/// <param name="radius">Radius of earth.</param>
/// <returns>Distance between this point and destination point, in same units as radius.</returns>
public double Distance(ICoordinate pointA, ICoordinate pointB, double radius)
{
if (pointA == null)
{
throw new ArgumentNullException(nameof(pointA), "The argument cannot be null.");
}
if (pointB == null)
{
throw new ArgumentNullException(nameof(pointB), "The argument cannot be null.");
}
ValidateRadius(radius);
/*
* a = sin²(Δφ/2) + cos(φ1)⋅cos(φ2)⋅sin²(Δλ/2)
* tanδ = √(a) / √(1−a)
* See http://mathforum.org/library/drmath/view/51879.html for derivation.
*/
var φ1 = pointA.Latitude.ToRadians();
var λ1 = pointA.Longitude.ToRadians();
var φ2 = pointB.Latitude.ToRadians();
var λ2 = pointB.Longitude.ToRadians();
var Δφ = φ2 - φ1;
var Δλ = λ2 - λ1;
var a = Math.Sin(Δφ / 2) * Math.Sin(Δφ / 2)
+ Math.Cos(φ1) * Math.Cos(φ2)
* Math.Sin(Δλ / 2) * Math.Sin(Δλ / 2);
var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
var d = radius * c;
return d;
}
/// <summary>
/// Using the line A->B calculate the shortest distance from point C that line.
/// <para>If point C is outside the bounds of A or B (a perpendicular line cannot be made to A or B) then -1 is returned.</para>
/// <para>Uses the mean radius of the Earth.</para>
/// </summary>
/// <param name="pointA">The start point of a line.</param>
/// <param name="pointB">The end point of a line.</param>
/// <param name="pointC">The point from which to find the perpendicular on the plane A->B.</param>
/// <returns>The distance in the same units as the radius, unless C extends past the line A->B in which case -1.</returns>
public double DistanceToLine(ICoordinate pointA, ICoordinate pointB, ICoordinate pointC)
{
return DistanceToLine(pointA, pointB, pointC, Radius.Mean);
}
/// <summary>
/// Using the line A->B calculate the shortest distance from point C that line.
/// <para>If point C is outside the bounds of A or B (a perpendicular line cannot be made to A or B) then -1 is returned.</para>
/// </summary>
/// <param name="pointA">The start point of a line.</param>
/// <param name="pointB">The end point of a line.</param>
/// <param name="pointC">The point from which to find the perpendicular on the plane A->B.</param>
/// <param name="radius">The radius of the earth.</param>
/// <returns>The distance in the same units as the radius, unless C extends past the line A->B in which case -1.</returns>
public double DistanceToLine(ICoordinate pointA, ICoordinate pointB, ICoordinate pointC, double radius)
{
ICoordinate pointX;
return DistanceToLine(pointA, pointB, pointC, radius, out pointX);
}
/// <summary>
/// Using the line A->B calculate the shortest distance from point C that line.
/// <para>If point C is outside the bounds of A or B (a perpendicular line cannot be made to A or B) then -1 is returned.</para>
/// <para>Uses the mean radius of the Earth.</para>
/// </summary>
/// <param name="pointA">The start point of a line.</param>
/// <param name="pointB">The end point of a line.</param>
/// <param name="pointC">The point from which to find the perpendicular on the plane A->B.</param>
/// <param name="pointX">Out, the point on the line (A->B) that is perpendicular to point C.</param>
/// <returns>The distance in the same units as the radius, unless C extends past the line A->B in which case -1.</returns>
public double DistanceToLine(ICoordinate pointA, ICoordinate pointB, ICoordinate pointC, out ICoordinate pointX)
{
return DistanceToLine(pointA, pointB, pointC, Radius.Mean, out pointX);
}
/// <summary>
/// Using the line A->B calculate the shortest distance from point C that line.
/// <para>If point C is outside the bounds of A or B (a perpendicular line cannot be made to A or B) then -1 is returned.</para>
/// </summary>
/// <param name="pointA">The start point of a line.</param>
/// <param name="pointB">The end point of a line.</param>
/// <param name="pointC">The point from which to find the perpendicular on the plane A->B.</param>
/// <param name="radius">The radius of the earth.</param>
/// <param name="pointX">Out, the point on the line (A->B) that is perpendicular to point C.</param>
/// <returns>The distance in the same units as the radius, unless C extends past the line A->B in which case -1.</returns>
public double DistanceToLine(ICoordinate pointA, ICoordinate pointB, ICoordinate pointC, double radius, out ICoordinate pointX)
{
pointX = default(ICoordinate);
if (pointA == null)
{
throw new ArgumentNullException(nameof(pointA), "The argument cannot be null.");
}
if (pointB == null)
{
throw new ArgumentNullException(nameof(pointB), "The argument cannot be null.");
}
if (pointC == null)
{
throw new ArgumentNullException(nameof(pointC), "The argument cannot be null.");
}
ValidateRadius(radius);
pointX = PerpendicularPoint(pointA, pointB, pointC);
if (pointX == null)
{
return -1;
}
else
{
var d = GeodeticCalculator.Instance.Distance(pointC, pointX);
return d;
}
}
/// <summary>
/// Using a virtual line on the same plane as the line A->B calculate the shortest distance from point C that line.
/// <para>Uses the mean radius of the Earth.</para>
/// </summary>
/// <param name="pointA">The start point of a line.</param>
/// <param name="pointB">The end point of a line.</param>
/// <param name="pointC">The point from which to find the perpendicular on the plane A->B.</param>
/// <returns>The distance in the same units as the radius.</returns>
public double DistanceToPlane(ICoordinate pointA, ICoordinate pointB, ICoordinate pointC)
{
return DistanceToPlane(pointA, pointB, pointC, Radius.Mean);
}
/// <summary>
/// Using a virtual line on the same plane as the line A->B calculate the shortest distance from point C that line.
/// </summary>
/// <param name="pointA">The start point of a line.</param>
/// <param name="pointB">The end point of a line.</param>
/// <param name="pointC">The point from which to find the perpendicular on the plane A->B.</param>
/// <param name="radius">The radius of the earth.</param>
/// <returns>The distance in the same units as the radius.</returns>
public double DistanceToPlane(ICoordinate pointA, ICoordinate pointB, ICoordinate pointC, double radius)
{
ICoordinate pointX;
return DistanceToPlane(pointA, pointB, pointC, radius, out pointX);
}
/// <summary>
/// Using a virtual line on the same plane as the line A->B calculate the shortest distance from point C that line.
/// <para>Uses the mean radius of the Earth.</para>
/// </summary>
/// <param name="pointA">The start point of a line.</param>
/// <param name="pointB">The end point of a line.</param>
/// <param name="pointC">The point from which to find the perpendicular on the plane A->B.</param>
/// <param name="pointX">Out, the point on the plane (A->B) that is perpendicular to point C.</param>
/// <returns>The distance in the same units as the radius.</returns>
public double DistanceToPlane(ICoordinate pointA, ICoordinate pointB, ICoordinate pointC, out ICoordinate pointX)
{
return DistanceToPlane(pointA, pointB, pointC, Radius.Mean, out pointX);
}
/// <summary>
/// Using a virtual line on the same plane as the line A->B calculate the shortest distance from point C that line.
/// </summary>
/// <param name="pointA">The start point of a line.</param>
/// <param name="pointB">The end point of a line.</param>
/// <param name="pointC">The point from which to find the perpendicular on the plane A->B.</param>
/// <param name="radius">The radius of the earth.</param>
/// <param name="pointX">Out, the point on the plane (A->B) that is perpendicular to point C.</param>
/// <returns>The distance in the same units as the radius.</returns>
public double DistanceToPlane(ICoordinate pointA, ICoordinate pointB, ICoordinate pointC, double radius, out ICoordinate pointX)
{
pointX = default(ICoordinate);
if (pointA == null)
{
throw new ArgumentNullException(nameof(pointA), "The argument cannot be null.");
}
if (pointB == null)
{
throw new ArgumentNullException(nameof(pointB), "The argument cannot be null.");
}
if (pointC == null)
{
throw new ArgumentNullException(nameof(pointC), "The argument cannot be null.");
}
ValidateRadius(radius);
// To accommodate where the line A->B does not extend far enough that a perpendicular line could be drawn from
// it to pointC we extend the A->B line by the greatest of the 2 distances, A->B and A->C.
var abDistance = GeodeticCalculator.Instance.Distance(pointA, pointB);
var acDistance = GeodeticCalculator.Instance.Distance(pointA, pointC);
var distanceMax = abDistance > acDistance ? abDistance : acDistance;
ICoordinate extendedPointA = GeodeticCalculator.Instance.Destination(pointA, distanceMax, GeodeticCalculator.Instance.Bearing(pointA, pointB));
ICoordinate extendedPointB = GeodeticCalculator.Instance.Destination(pointB, distanceMax, GeodeticCalculator.Instance.Bearing(pointB, pointA));
pointX = PerpendicularPoint(extendedPointA, extendedPointB, pointC);
var d = GeodeticCalculator.Instance.Distance(pointC, pointX);
return d;
}
/// <summary>
/// Calculate final bearing arriving at destination point from point A.
/// <para>The final bearing will differ from the initial bearing by varying degrees according to distance and latitude.</para>
/// </summary>
/// <param name="pointA">The start point.</param>
/// <param name="pointB">The end point.</param>
/// <returns>Final bearing in degrees from north.</returns>
public double FinalBearing(ICoordinate pointA, ICoordinate pointB)
{
if (pointA == null)
{
throw new ArgumentNullException(nameof(pointA), "The argument cannot be null.");
}
if (pointB == null)
{
throw new ArgumentNullException(nameof(pointB), "The argument cannot be null.");
}
// Get initial bearing from destination point to this point & reverse it by adding 180°.
var result = (pointB.BearingTo(pointA) + 180) % 360;
return result;
}
/// <summary>
/// Calculate the point at a given fraction along the track between point A and point B.
/// </summary>
/// <param name="pointA">The start point.</param>
/// <param name="pointB">The end point.</param>
/// <param name="fraction">Fraction between the two points (0 = this point, 1 = specified point).</param>
/// <returns>The intermediate point between this point and destination point.</returns>
public ICoordinate IntermediatePoint(ICoordinate pointA, ICoordinate pointB, double fraction)
{
if (pointA == null)
{
throw new ArgumentNullException(nameof(pointA), "The argument cannot be null.");
}
if (pointB == null)
{
throw new ArgumentNullException(nameof(pointB), "The argument cannot be null.");
}
if (fraction < 0 || fraction > 1)
{
throw new ArgumentOutOfRangeException(nameof(fraction), fraction, "The argument cannot be less than zero or greater than one.");
}
var φ1 = pointA.Latitude.ToRadians();
var λ1 = pointA.Longitude.ToRadians();
var φ2 = pointB.Latitude.ToRadians();
var λ2 = pointB.Longitude.ToRadians();
var sinφ1 = Math.Sin(φ1);
var cosφ1 = Math.Cos(φ1);
var sinλ1 = Math.Sin(λ1);
var cosλ1 = Math.Cos(λ1);
var sinφ2 = Math.Sin(φ2);
var cosφ2 = Math.Cos(φ2);
var sinλ2 = Math.Sin(λ2);
var cosλ2 = Math.Cos(λ2);
// Distance between points.
var Δφ = φ2 - φ1;
var Δλ = λ2 - λ1;
var a = Math.Sin(Δφ / 2) * Math.Sin(Δφ / 2)
+ Math.Cos(φ1) * Math.Cos(φ2) * Math.Sin(Δλ / 2) * Math.Sin(Δλ / 2);
var δ = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
var A = Math.Sin((1 - fraction) * δ) / Math.Sin(δ);
var B = Math.Sin(fraction * δ) / Math.Sin(δ);
var x = A * cosφ1 * cosλ1 + B * cosφ2 * cosλ2;
var y = A * cosφ1 * sinλ1 + B * cosφ2 * sinλ2;
var z = A * sinφ1 + B * sinφ2;
var φ3 = Math.Atan2(z, Math.Sqrt(x * x + y * y));
var λ3 = Math.Atan2(y, x);
// Normalise to −180..+180°.
var result = base.NewCoordinate(φ3.ToDegrees(), (λ3.ToDegrees() + 540) % 360 - 180);
return result;
}
/// <summary>
/// Calculate the point of intersection of two paths defined by points and bearings.
/// </summary>
/// <param name="point1">First point.</param>
/// <param name="bearing1">Initial bearing from first point.</param>
/// <param name="point2">Second point.</param>
/// <param name="bearing2">Initial bearing from second point.</param>
/// <returns>Destination point (null if no unique intersection defined).</returns>
public ICoordinate Intersection(ICoordinate point1, double bearing1, ICoordinate point2, double bearing2)
{
if (point1 == null)
{
throw new ArgumentNullException(nameof(point1), "The argument cannot be null.");
}
if (point2 == null)
{
throw new ArgumentNullException(nameof(point2), "The argument cannot be null.");
}
ValidateBearing(bearing1, nameof(bearing1));
ValidateBearing(bearing2, nameof(bearing2));
// See http://edwilliams.org/avform.htm#Intersection
var φ1 = point1.Latitude.ToRadians();
var λ1 = point1.Longitude.ToRadians();
var φ2 = point2.Latitude.ToRadians();
var λ2 = point2.Longitude.ToRadians();
var θ13 = bearing1.ToRadians();
var θ23 = bearing2.ToRadians();
var Δφ = φ2 - φ1;
var Δλ = λ2 - λ1;
// Angular distance p1-p2.
var δ12 = 2 * Math.Asin(Math.Sqrt(Math.Sin(Δφ / 2) * Math.Sin(Δφ / 2)
+ Math.Cos(φ1) * Math.Cos(φ2) * Math.Sin(Δλ / 2) * Math.Sin(Δλ / 2)));
if (δ12.WithinTolerance(0))
{
return null;
}
// Initial/final bearings between points
var θa = Math.Acos((Math.Sin(φ2) - Math.Sin(φ1) * Math.Cos(δ12)) / (Math.Sin(δ12) * Math.Cos(φ1)));
if (double.IsNaN(θa))
{
// Protect against rounding.
θa = 0;
}
var θb = Math.Acos((Math.Sin(φ1) - Math.Sin(φ2) * Math.Cos(δ12)) / (Math.Sin(δ12) * Math.Cos(φ2)));
var θ12 = Math.Sin(λ2 - λ1) > 0 ? θa : 2 * Math.PI - θa;
var θ21 = Math.Sin(λ2 - λ1) > 0 ? 2 * Math.PI - θb : θb;
var α1 = θ13 - θ12; // angle 2-1-3
var α2 = θ21 - θ23; // angle 1-2-3
// Infinite intersections.
if (Math.Sin(α1).WithinTolerance(0) && Math.Sin(α2).WithinTolerance(0))
{
return null;
}
// Ambiguous intersection.
if (Math.Sin(α1) * Math.Sin(α2) < 0)
{
return null;
}
var α3 = Math.Acos(-Math.Cos(α1) * Math.Cos(α2) + Math.Sin(α1) * Math.Sin(α2) * Math.Cos(δ12));
var δ13 = Math.Atan2(Math.Sin(δ12) * Math.Sin(α1) * Math.Sin(α2), Math.Cos(α2) + Math.Cos(α1) * Math.Cos(α3));
var φ3 = Math.Asin(Math.Sin(φ1) * Math.Cos(δ13) + Math.Cos(φ1) * Math.Sin(δ13) * Math.Cos(θ13));
var Δλ13 = Math.Atan2(Math.Sin(θ13) * Math.Sin(δ13) * Math.Cos(φ1), Math.Cos(δ13) - Math.Sin(φ1) * Math.Sin(φ3));
var λ3 = λ1 + Δλ13;
// Normalise to −180..+180°.
var result = base.NewCoordinate(φ3.ToDegrees(), (λ3.ToDegrees() + 540) % 360 - 180);
return result;
}
/// <summary>
/// Calculate the maximum latitude reached when travelling on a great circle on given bearing from this point ('Clairaut's formula').
/// <para>Negate the result for the minimum latitude (in the Southern hemisphere).</para>
/// <para>The maximum latitude is independent of longitude; it will be the same for all points on a given latitude.</para>
/// </summary>
/// <param name="pointA">The start point.</param>
/// <param name="bearing">Initial bearing.</param>
/// <returns>The maximum latitude.</returns>
public double MaximumLatitude(ICoordinate pointA, double bearing)
{
if (pointA == null)
{
throw new ArgumentNullException(nameof(pointA), "The argument cannot be null.");
}
ValidateBearing(bearing);
var θ = bearing.ToRadians();
var φ = pointA.Latitude.ToRadians();
var φMax = Math.Acos(Math.Abs(Math.Sin(θ) * Math.Cos(φ)));
var result = φMax.ToDegrees();
return result;
}
/// <summary>
/// Calculate the midpoint between point A and point B.
/// </summary>
/// <param name="pointA">The start point.</param>
/// <param name="pointB">The end point.</param>
/// <returns>Midpoint between this point and the supplied point.</returns>
public ICoordinate Midpoint(ICoordinate pointA, ICoordinate pointB)
{
if (pointA == null)
{
throw new ArgumentNullException(nameof(pointA), "The argument cannot be null.");
}
if (pointB == null)
{
throw new ArgumentNullException(nameof(pointB), "The argument cannot be null.");
}
/*
* φm = atan2( sinφ1 + sinφ2, √( (cosφ1 + cosφ2⋅cosΔλ) ⋅ (cosφ1 + cosφ2⋅cosΔλ) ) + cos²φ2⋅sin²Δλ )
* λm = λ1 + atan2(cosφ2⋅sinΔλ, cosφ1 + cosφ2⋅cosΔλ)
* See http://mathforum.org/library/drmath/view/51822.html for derivation.
*/
var φ1 = pointA.Latitude.ToRadians();
var λ1 = pointA.Longitude.ToRadians();
var φ2 = pointB.Latitude.ToRadians();
var Δλ = (pointB.Longitude - pointA.Longitude).ToRadians();
var Bx = Math.Cos(φ2) * Math.Cos(Δλ);
var By = Math.Cos(φ2) * Math.Sin(Δλ);
var x = Math.Sqrt((Math.Cos(φ1) + Bx) * (Math.Cos(φ1) + Bx) + By * By);
var y = Math.Sin(φ1) + Math.Sin(φ2);
var φ3 = Math.Atan2(y, x);
var λ3 = λ1 + Math.Atan2(By, Math.Cos(φ1) + Bx);
// Normalise to −180..+180°.
var result = base.NewCoordinate(φ3.ToDegrees(), (λ3.ToDegrees() + 540) % 360 - 180);
return result;
}
/// <summary>
/// Calculate the point on the line A->B that is perpendicular from the line to point C.
/// </summary>
/// <param name="pointA">The start point of a line.</param>
/// <param name="pointB">The end point of a line.</param>
/// <param name="pointC">The point from which to find the perpendicular on the line A->B.</param>
/// <returns>Null if pointC extends past the line A->B.</returns>
public ICoordinate PerpendicularPoint(ICoordinate pointA, ICoordinate pointB, ICoordinate pointC)
{
if (pointA == null)
{
throw new ArgumentNullException(nameof(pointA), "The argument cannot be null.");
}
if (pointB == null)
{
throw new ArgumentNullException(nameof(pointB), "The argument cannot be null.");
}
if (pointC == null)
{
throw new ArgumentNullException(nameof(pointC), "The argument cannot be null.");
}
// http://csharphelper.com/blog/2016/09/find-the-shortest-distance-between-a-point-and-a-line-segment-in-c/
double dx = pointB.Longitude - pointA.Longitude;
double dy = pointB.Latitude - pointA.Latitude;
if (dx.WithinTolerance(0) && dy.WithinTolerance(0))
{
// The point (pointC) is not perpendicular to the line A->B.
return default(ICoordinate);
}
else
{
// Calculate the t that minimizes the distance.
double t = ((pointC.Longitude - pointA.Longitude) * dx + (pointC.Latitude - pointA.Latitude) * dy) / (dx * dx + dy * dy);
// See if this represents one of the segment's end points or a point in the middle.
if (t < 0)
{
return NewCoordinate(pointA.Latitude, pointA.Longitude);
}
else if (t > 1)
{
return NewCoordinate(pointB.Latitude, pointB.Longitude);
}
else
{
return NewCoordinate(pointA.Latitude + t * dy, pointA.Longitude + t * dx);
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Beamore.Contracts.DataTransferObjects
{
public class EventDTO
{
public int EventID { get; set; }
public string EventName { get; set; }
/// <summary>
/// This email is creatimg automathicly Ex: iztech@beamore.tech
/// </summary>
public string EventEmail { get; set; }
public DateTime EventDate { get; set; }
public DateTime EventStartTime { get; set; }
public string LogoUrl { get; set; }
public LocationDTO Location { get; set; }
}
}
|
using LuaInterface;
using SLua;
using System;
public class Lua_UnityEngine_AudioClipLoadType : LuaObject
{
public static void reg(IntPtr l)
{
LuaObject.getEnumTable(l, "UnityEngine.AudioClipLoadType");
LuaObject.addMember(l, 0, "DecompressOnLoad");
LuaObject.addMember(l, 1, "CompressedInMemory");
LuaObject.addMember(l, 2, "Streaming");
LuaDLL.lua_pop(l, 1);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using ext;
using Microsoft.EntityFrameworkCore;
using model;
using OCP;
using OCP.Files.Cache;
using Pchp.Library.Spl;
namespace OC.Files.Cache
{
/**
* Propagate etags and mtimes within the storage
*/
class Propagator : IPropagator {
private bool inBatch = false;
private IList<string> batch = new List<string>();
/**
* @var \OC\Files\Storage\Storage
*/
protected OC.Files.Storage.Storage storage;
/**
* @var IDBConnection
*/
private IDBConnection connection;
/**
* @var array
*/
private IList<string> ignores = new List<string>();
public Propagator(Files.Storage.Storage storage, IDBConnection connection, IList<string> ignores)
{
this.storage = storage;
this.connection = connection;
this.ignores = ignores;
}
/**
* @param string internalPath
* @param int time
* @param int sizeDifference number of bytes the file has grown
* @suppress SqlInjectionChecker
*/
public void propagateChange(string internalPath, int time,int sizeDifference = 0) {
// Do not propogate changes in ignored paths
foreach (var ignore in this.ignores) {
if (internalPath.IndexOf(ignore, StringComparison.Ordinal) == 0)
{
return;
}
// if (strpos(internalPath, ignore) == 0) {
// return;
// }
}
var storageId = (int)this.storage.getStorageCache().getNumericId();
var parents = this.getParents(internalPath);
if (this.inBatch) {
foreach (var parent in parents) {
this.addToBatch(parent, time, sizeDifference);
}
return;
}
var parentHashes = parents.Select(o => o.MD5ext());
var etag = Guid.NewGuid().ToString("N"); // since we give all folders the same etag we don't ask the storage for the etag
using (var context = new NCContext())
{
// using (var transaction = context.Database.BeginTransaction())
// {
//
// }
var record = context.FileCaches.Single(o => o.storage == storageId && parentHashes.Contains(o.path_hash));
record.mtime = time; // builder.createFunction('GREATEST(' . builder.getColumnName('mtime') . ', ' . builder.createNamedParameter((int)time, IQueryBuilder::PARAM_INT) . ')'))
record.etag = etag;
context.Update(record);
}
if (sizeDifference !== 0) {
// we need to do size separably so we can ignore entries with uncalculated size
builder = this.connection.getQueryBuilder();
builder.update('filecache')
.set('size', builder.func().add('size', builder.createNamedParameter(sizeDifference)))
.where(builder.expr().eq('storage', builder.createNamedParameter(storageId, IQueryBuilder::PARAM_INT)))
.andWhere(builder.expr().in('path_hash', hashParams))
.andWhere(builder.expr().gt('size', builder.expr().literal(-1, IQueryBuilder::PARAM_INT)));
builder.execute();
}
}
protected IList<string> getParents(string path)
{
var parts = path.Split("/");
var parent = "";
var parents = new List<string>();
foreach (var part in parts)
{
parent = parent.Trim() + "/" + part + "/";
parents.Add(parent);
}
return parents;
}
/**
* Mark the beginning of a propagation batch
*
* Note that not all cache setups support propagation in which case this will be a noop
*
* Batching for cache setups that do support it has to be explicit since the cache state is not fully consistent
* before the batch is committed.
*/
public void beginBatch() {
this.inBatch = true;
}
private void addToBatch(string internalPath,int time,int sizeDifference) {
if (!isset(this.batch[internalPath])) {
this.batch[internalPath] = [
'hash' => md5(internalPath),
'time' => time,
'size' => sizeDifference
];
} else {
this.batch[internalPath]['size'] += sizeDifference;
if (time > this.batch[internalPath]['time']) {
this.batch[internalPath]['time'] = time;
}
}
}
/**
* Commit the active propagation batch
* @suppress SqlInjectionChecker
*/
public void commitBatch() {
if (!this.inBatch) {
throw new BadMethodCallException("Not in batch");
}
this.inBatch = false;
this.connection.beginTransaction();
query = this.connection.getQueryBuilder();
var storageId = (int)this.storage.getStorageCache().getNumericId();
query.update('filecache')
.set('mtime', query.createFunction('GREATEST(' . query.getColumnName('mtime') . ', ' . query.createParameter('time') . ')'))
.set('etag', query.expr().literal(uniqid()))
.where(query.expr().eq('storage', query.expr().literal(storageId, IQueryBuilder::PARAM_INT)))
.andWhere(query.expr().eq('path_hash', query.createParameter('hash')));
sizeQuery = this.connection.getQueryBuilder();
sizeQuery.update('filecache')
.set('size', sizeQuery.func().add('size', sizeQuery.createParameter('size')))
.where(query.expr().eq('storage', query.expr().literal(storageId, IQueryBuilder::PARAM_INT)))
.andWhere(query.expr().eq('path_hash', query.createParameter('hash')))
.andWhere(sizeQuery.expr().gt('size', sizeQuery.expr().literal(-1, IQueryBuilder::PARAM_INT)));
foreach (this.batch as item) {
query.setParameter('time', item['time'], IQueryBuilder::PARAM_INT);
query.setParameter('hash', item['hash']);
query.execute();
if (item['size']) {
sizeQuery.setParameter('size', item['size'], IQueryBuilder::PARAM_INT);
sizeQuery.setParameter('hash', item['hash']);
sizeQuery.execute();
}
}
this.batch = [];
this.connection.commit();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NutritionalResearchBusiness.Dtos
{
public class InvestigationRecordQueryConditions
{
/// <summary>
/// 队列编号
/// </summary>
public string QueueId { get; set; }
/// <summary>
/// 围产保健手册编号
/// </summary>
public string HealthBookId { get; set; }
/// <summary>
/// 孕妇姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 查询开始时间
/// </summary>
public DateTime? QueryStartTime { get; set; }
/// <summary>
/// 查询结束时间
/// </summary>
public DateTime? QueryEndTime { get; set; }
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.Linq;
using Dnn.PersonaBar.Library.Data;
using Dnn.PersonaBar.Library.Model;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Users;
using DotNetNuke.Framework;
namespace Dnn.PersonaBar.Library.Repository
{
public class PersonaBarExtensionRepository : ServiceLocator<IPersonaBarExtensionRepository, PersonaBarExtensionRepository>,
IPersonaBarExtensionRepository
{
#region Fields
private readonly IDataService _dataService = new DataService();
private const string PersonaBarExtensionsCacheKey = "PersonaBarExtensions";
private static readonly object ThreadLocker = new object();
#endregion
private void ClearCache()
{
DataCache.RemoveCache(PersonaBarExtensionsCacheKey);
}
protected override Func<IPersonaBarExtensionRepository> GetFactory()
{
return () => new PersonaBarExtensionRepository();
}
public void SaveExtension(PersonaBarExtension extension)
{
_dataService.SavePersonaBarExtension(
extension.Identifier,
extension.MenuId,
extension.FolderName,
extension.Controller,
extension.Container,
extension.Path,
extension.Order,
extension.Enabled,
UserController.Instance.GetCurrentUserInfo().UserID
);
ClearCache();
}
public void DeleteExtension(PersonaBarExtension extension)
{
DeleteExtension(extension.Identifier);
}
public void DeleteExtension(string identifier)
{
_dataService.DeletePersonaBarExtension(identifier);
ClearCache();
}
public IList<PersonaBarExtension> GetExtensions()
{
var extensions = DataCache.GetCache<IList<PersonaBarExtension>>(PersonaBarExtensionsCacheKey);
if (extensions == null)
{
lock (ThreadLocker)
{
extensions = DataCache.GetCache<IList<PersonaBarExtension>>(PersonaBarExtensionsCacheKey);
if (extensions == null)
{
extensions = CBO.FillCollection<PersonaBarExtension>(_dataService.GetPersonaBarExtensions())
.OrderBy(e => e.Order).ToList();
DataCache.SetCache(PersonaBarExtensionsCacheKey, extensions);
}
}
}
return extensions;
}
public IList<PersonaBarExtension> GetExtensions(int menuId)
{
return GetExtensions().Where(t => t.MenuId == menuId).ToList();
}
}
}
|
using System;
namespace Maths
{
class Program
{
public static int Addition(int a,int b)
{
int c = a + b;
return c;
}
public static void Main(String []args)
{
Func<int, int,int> add = Addition;
int a;
a=add(10, 20);
Console.WriteLine(a);
Func<int, int, int, int> mul = (a, b, c) => a * b * c;
int b=mul(10, 20, 30);
Console.WriteLine(b);
Action<String> show = (s) => Console.WriteLine($"My Name is-{s}");
show("Malli");
Predicate<int> Check = (age) => age >18;
bool agecheck = Check(19);
Console.WriteLine(agecheck);
agecheck = Check(12);
Console.WriteLine(agecheck);
}
}
}
|
using UnityEngine;
using System.Collections;
public class SceneManager : MonoBehaviour
{
[SerializeField] private GameObject _titleScene;
[SerializeField] private GameObject _creditScene;
public void showTitleScene()
{
_titleScene.SetActive(true);
_creditScene.SetActive(false);
}
public void showCreditScene()
{
_titleScene.SetActive(false);
_creditScene.SetActive(true);
}
public void showGameScene()
{
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.ServiceModel;
using ServiceMtk_P1_066;
namespace Server_ConfigureForm_P5_066
{
public partial class Form1 : Form
{
private ServiceHost Host;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Host = new ServiceHost(typeof(Matematika));
label3.Text = "Server ON";
label2.Text = "Klik OFF untuk Mematikan Server";
Host.Open();
button1.Enabled = false;
button2.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
button1.Enabled = true;
button2.Enabled = false;
Host.Close();
label2.Text = "Klik ON untuk Menjalankan Server";
label3.Text = "Server OFF";
}
private void label1_Click(object sender, EventArgs e)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MtgSecretSantaNotifier
{
public class Attribute
{
public string Name { get; }
public int Index { get; }
public string Value { get; }
public Attribute(string name, int row, string value = null) { this.Name = name; this.Index = row; this.Value = value; }
}
}
|
using Prism.Commands;
using Prism.Navigation;
using Viaticos.common.Services;
namespace Viaticos.prism.ViewModels
{
public class LoginPageViewModel : ViewModelBase
{
private readonly INavigationService _navigationService;
private readonly IApiService _apiService;
private string _password;
private bool _isRunning;
private bool _isEnabled;
private DelegateCommand _loginCommand;
private DelegateCommand _registerCommand;
private DelegateCommand _forgotPasswordCommand;
public LoginPageViewModel(INavigationService navigationService, IApiService apiService) : base(navigationService)
{
_navigationService = navigationService;
_apiService = apiService;
Title = "Viaticos - Login";
IsEnabled = true;
IsRemember = true;
IsRunning = false;
}
public DelegateCommand ForgotPasswordCommand => _forgotPasswordCommand ?? (_forgotPasswordCommand = new DelegateCommand(ForgotPassword));
private void ForgotPassword()
{
//throw new NotImplementedException();
}
public DelegateCommand LoginCommand => _loginCommand ?? (_loginCommand = new DelegateCommand(Login));
private void Login()
{
//throw new NotImplementedException();
}
public DelegateCommand RegisterCommand => _registerCommand ?? (_registerCommand = new DelegateCommand(Register));
private void Register()
{
//throw new NotImplementedException();
}
public bool IsRemember { get; set; }
public string Email { get; set; }
public string Password
{
get => _password;
set => SetProperty(ref _password, value);
}
public bool IsRunning
{
get => _isRunning;
set => SetProperty(ref _isRunning, value);
}
public bool IsEnabled
{
get => _isEnabled;
set => SetProperty(ref _isEnabled, value);
}
}
}
|
namespace Requestrr.WebApi.RequestrrBot.Movies
{
public class MoviesSettingsProvider
{
public MoviesSettings Provide()
{
dynamic settings = SettingsFile.Read();
return new MoviesSettings
{
Client = settings.Movies.Client,
};
}
}
} |
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
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 System.Xml.Linq;
using AgentStoryComponents;
namespace AgentStoryHTTP
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//while waiting for Sausalito Ferry
string url = config.startEditor;
url += "?StoryID=";
url += config.startStoryID;
url += "&PageCursor=";
url += config.startStoryPage;
url += "&toolBR=";
url += config.startStoryToolBR;
Response.Redirect(url);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Threading.Tasks;
using DingleTheBotReboot.Data;
using DingleTheBotReboot.Extensions;
using DingleTheBotReboot.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
namespace DingleTheBotReboot.Services.DbContext;
public class DbContextService : IDbContextService
{
private readonly DingleDbContext _dingleDbContext;
private readonly IDistributedCache _distributedCache;
private readonly ILogger<DbContextService> _logger;
public DbContextService(DingleDbContext dingleDbContext, ILogger<DbContextService> logger, Random rnd,
IDistributedCache distributedCache)
{
_dingleDbContext = dingleDbContext;
_logger = logger;
_distributedCache = distributedCache;
}
public async Task<bool> UpdateVerificationRoleAsync(ulong guildId, ulong verificationRoleId)
{
try
{
var guild = await GetGuildAsync(guildId);
if (guild is null)
{
await _dingleDbContext.Guilds.AddAsync(new Guild
{
GuildId = guildId,
VerificationRoleId = verificationRoleId
});
}
else
{
guild.VerificationRoleId = verificationRoleId;
_dingleDbContext.Update(guild);
}
var rows = await _dingleDbContext.SaveChangesAsync();
return rows != 0;
}
catch (Exception e)
{
_logger.LogCritical("Exception when setting verification role: {Message}", e.Message);
return false;
}
}
public async Task<bool> UpdateAnimeChannelAsync(ulong guildId, ulong animeChannelId)
{
try
{
var guild = await GetGuildAsync(guildId);
if (guild is null)
{
await _dingleDbContext.Guilds.AddAsync(new Guild
{
GuildId = guildId,
AnimeRemindersChannelId = animeChannelId
});
}
else
{
guild.AnimeRemindersChannelId = animeChannelId;
_dingleDbContext.Update(guild);
}
var rows = await _dingleDbContext.SaveChangesAsync();
return rows != 0;
}
catch (Exception e)
{
_logger.LogCritical("Exception when setting anime channel id: {Message}", e.Message);
return false;
}
}
public async Task<Guild> GetGuildAsync(ulong guildId)
{
try
{
var guild = await _distributedCache.GetRecordAsync<Guild>(guildId.ToString());
if (guild is not null) return guild;
guild = await _dingleDbContext.Guilds.Where(x => x.GuildId == guildId).FirstOrDefaultAsync();
if (guild is not null) await CacheModelAsync(guildId, guild, TimeSpan.FromMinutes(10));
return guild;
}
catch (Exception e)
{
_logger.LogCritical("Exception when getting guild: {Message}", e.Message);
return null;
}
}
public async Task<User> GetUserAsync(ulong discordId)
{
try
{
var user = await _distributedCache.GetRecordAsync<User>(discordId.ToString());
if (user is not null) return user;
user = await _dingleDbContext.Users.Where(x => x.DiscordId == discordId).FirstOrDefaultAsync();
await CacheModelAsync(discordId, user, TimeSpan.FromMinutes(10));
return user;
}
catch (Exception e)
{
_logger.LogCritical("Exception when getting user: {Message}", e.Message);
return null;
}
}
public async Task<int> AddCoinsAsync(ulong discordId,
int coins = 0, int fromInclusive = 100, int toExclusive = 201)
{
try
{
var amount = coins == 0 ? RandomNumberGenerator.GetInt32(fromInclusive, toExclusive) : coins;
var user = await GetUserAsync(discordId);
if (user is null)
{
await _dingleDbContext.Users.AddAsync(new User
{
DiscordId = discordId,
Coins = 0
});
}
else
{
user.Coins += amount;
await CacheModelAsync(discordId, user, TimeSpan.FromMinutes(10));
_dingleDbContext.Update(user);
}
var rows = await _dingleDbContext.SaveChangesAsync();
return rows != 0 ? amount : 0;
}
catch (Exception e)
{
_logger.LogCritical("Exception when giving coins to user: {Message}", e.Message);
return 0;
}
}
public async Task<HashSet<Guild>> GetAllGuildsAsync()
{
try
{
var guilds = await _distributedCache.GetRecordAsync<HashSet<Guild>>("ALL_GUILDS");
if (guilds is not null) return guilds;
guilds = _dingleDbContext.Guilds.ToHashSet();
await CacheModelAsync("ALL_GUILDS", guilds, TimeSpan.FromMinutes(10));
return guilds;
}
catch (Exception e)
{
_logger.LogCritical("Exception when getting all guilds: {Message}", e.Message);
return null;
}
}
private async Task CacheModelAsync<TK, T>(TK key, T item, TimeSpan timeSpan)
{
await _distributedCache.SetRecordAsync(key.ToString(), item, timeSpan);
}
} |
using System.Collections.Generic;
using System.Net;
namespace MailerQ.RestApi
{
/// <summary>
/// A generic MailerQ Rest API response
/// </summary>
/// <typeparam name="T">Model type that return the endpoint</typeparam>
public class RestApiResponse<T> : IRestApiResponse<T> where T : IRestApiModel
{
/// <inheritdoc />
public HttpStatusCode HttpStatusCode { get; }
/// <inheritdoc />
public ICollection<T> Content { get; }
/// <summary>
/// Initializes a new instance of generic MailerQ Rest API response
/// </summary>
/// <param name="httpStatusCode">The HTTP status code of the response</param>
/// <param name="content">Collection of object deserialized from the response content</param>
public RestApiResponse(HttpStatusCode httpStatusCode, ICollection<T> content = default)
{
HttpStatusCode = httpStatusCode;
Content = content;
}
}
}
|
using UnityEngine;
public abstract class AEntity : MonoBehaviour
{
#region Behaviour Methods
protected abstract void EndureDamage(float enduredDamage);
#endregion
} |
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
using InsertionSort;
using DataStructures;
namespace CodeChallengeTests
{
public class InsertionSortTests
{
[Fact]
public void Tests_That_Output_In_Correct_Order()
{
int[] arr = new int[] { 8, 4, 23, 43, 16, 15 };
int[] expected = new int[] { 4, 8, 15, 16, 23, 43 };
int[] result = InsertionSort(arr);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LibraryManagement.Admin.dsAdminTableAdapters;
/**
*
* Author: Leonardo Stifano
*
*/
namespace LibraryManagement.Admin
{
public partial class ManagePublishers : System.Web.UI.Page
{
PublishersAdapter adpPublishers = new PublishersAdapter();
BooksTableAdapter adpBooks = new BooksTableAdapter();
dsAdmin.PublishersDataTable tblPublishers = new dsAdmin.PublishersDataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
RefreshList();
}
private void RefreshList()
{
tblPublishers = adpPublishers.GetPublishers();
lstPublishers.DataSource = tblPublishers;
lstPublishers.DataValueField = tblPublishers.PublisherColumn.ColumnName;
lstPublishers.DataTextField = tblPublishers.PublisherColumn.ColumnName;
lstPublishers.DataBind();
}
protected void btnChange_Click(object sender, EventArgs e)
{
string publisher = txtNew.Text;
if (publisher.Trim().Equals(""))
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Please fill in the Publisher field";
return;
}
int result = adpBooks.UpdatePublisher(publisher, lstPublishers.Text);
if (result > 0)
{
lblMessage.Text = "Publisher updated successfully";
lblMessage.ForeColor = System.Drawing.Color.Green;
RefreshList();
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Publisher not updated";
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
string Publisher = lstPublishers.Text;
int result = adpBooks.DeletePublisher(Publisher);
if (result == 1)
{
lblMessage.Text = "Publisher deleted successfully";
lblMessage.ForeColor = System.Drawing.Color.Green;
RefreshList();
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Publisher not deleted";
}
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class PlayerController : MovingObject
{
private const int DEFAULTCANDLENUM = 3;
private bool m_isAxisInUse = false;
private BoxCollider2D candle;
[HideInInspector] public int candleAmount = DEFAULTCANDLENUM;
[HideInInspector] public bool movementControl;
[SerializeField] AudioClip walkingSound;
[SerializeField] [Range(0, 1)] float walkingSoundVolume = 1f;
[SerializeField] AudioClip candleSound;
[SerializeField] [Range(0, 1)] float candleSoundVolume = 1f;
protected override void Start()
{
enabled = true;
candle = GameObject.Find("CandleTrigger").GetComponent<BoxCollider2D>();
movementControl = true;
base.Start();
}
void Update()
{
if (!GameManager.instance.playersTurn)
{
return;
}
int horizontal = 0;
int vertical = 0;
if (movementControl && (Input.GetAxisRaw("Horizontal") != 0 || Input.GetAxisRaw("Vertical") != 0))
{
if(m_isAxisInUse == false)
{
horizontal = (int)(Input.GetAxisRaw("Horizontal"));
vertical = (int)(Input.GetAxisRaw("Vertical"));
m_isAxisInUse = true;
}
}
if( Input.GetAxisRaw("Horizontal") == 0 && Input.GetAxisRaw("Vertical") == 0)
{
m_isAxisInUse = false;
}
//Check if moving horizontally, if so set vertical to zero.
if (horizontal != 0)
{
vertical = 0;
}
if (horizontal != 0 || vertical != 0)
{
GameManager.instance.playersTurn = false;
Move(horizontal, vertical);
}
if (movementControl && Input.GetKeyDown(KeyCode.Space) && candleAmount > 0) {
//candle.enabled = true;
FindObjectOfType<Candles>().removeCandle();
AudioSource.PlayClipAtPoint(candleSound, transform.position, candleSoundVolume);
foreach (GameObject go in GameObject.FindGameObjectsWithTag("Fog"))
{
if (go.GetComponent<Fog>().preToDie) {
go.SetActive(false);
}
}
candleAmount -= 1;
}
}
protected override void Move(int x, int y)
{
//candle.enabled = false;
GameManager.instance.playersTurn = false;
base.Move(x, y);
AudioSource.PlayClipAtPoint(walkingSound, transform.position, walkingSoundVolume);
}
public void SetMovementControl(bool controlBool) {
movementControl = controlBool;
}
}
|
using System.Collections.Generic;
using ComponentKit;
namespace Calcifer.Engine.Components
{
public interface IService
{
void Synchronize(IEnumerable<IComponent> components);
}
} |
using System;
using System.IO;
using System.Net;
using System.Xml.Linq;
using System.Threading;
using System.Collections;
using System.Security.Cryptography;
namespace rotten
{
class MainClass
{
private static String baseDirectory = "//home//john//movieTest";
private static String logFile = "//home//john//log.txt";
private static GetInfo dataFetcher;
private static DataParser dataParser;
private static GetIMDBInfo imdbDataFetcher;
private static IMDBDataParser imdbDataParser;
private static OutputWriter outputWriter;
private static Logger logger;
private static ArrayList failedMovies = new ArrayList();
public static void Main (string[] args)
{
logger = new Logger(logFile);
dataFetcher = new GetInfo();
dataParser = new DataParser();
imdbDataFetcher = new GetIMDBInfo();
imdbDataParser = new IMDBDataParser();
outputWriter = new OutputWriter();
String[] movieDirectory = GetMovieNames();
logger.log("Fetched [" + movieDirectory.Length.ToString() + "] movies");
foreach (String moviePath in movieDirectory) {
logger.flush();
String movieName = moviePath.Replace(baseDirectory + "/", "");
logger.log("Processing [" + movieName + "]");
//Split out the directory name to get title and year
DataFromFile dataFromFile = new DataFromFile(movieName);
logger.log ("Split directory name to name [" + dataFromFile.getName() + "] and year [" + dataFromFile.getYear() + "]");
//Grab rotten tomatoes data
String rottenJson = dataFetcher.getData(movieName);
rottenJson = rottenJson.Trim();
MovieInfo rottenParsed = dataParser.getParsedData(rottenJson);
if (rottenParsed == null) {
failedMovies.Add(movieName);
logger.log("Failed to get rottentomatoes data for movie [" + movieName + "]");
continue;
}
processMovieInfo(rottenParsed.Movies[0], dataFromFile, moviePath, failedMovies);
}
logger.closeLog();
}
private static void processMovieInfo(Movie info, DataFromFile dataFromFile, String fullPath, ArrayList failedMovies)
{
//Check release year
if (!dataFromFile.getYear().Equals(info.Year)) {
failedMovies.Add(dataFromFile.getName());
logger.log("Error - directory year " + dataFromFile.getYear() + " does not equal retrieved year " + info.Year);
return;
}
//Grab full cast data
String fullCastUrl = null;
FullCast fullCast = new FullCast();
info.Links.TryGetValue("cast", out fullCastUrl);
if (fullCastUrl == null) {
logger.log("Error - full cast url for " + dataFromFile.getName() + " was null");
} else {
String rottenCastJson = dataFetcher.getCastData(fullCastUrl);
fullCast = dataParser.getCastParsedData(rottenCastJson);
}
//Get IMDB data for synopsis
String imdbNumber = null;
String imdbJson = null;
info.Alternate_IDs.TryGetValue("imdb", out imdbNumber);
if (imdbNumber == null) {
logger.log("Error - IMDB number for " + dataFromFile.getName() + " was null");
} else {
imdbJson = imdbDataFetcher.getData(imdbNumber);
}
//Download the movie poster
String posterUrl = null;
info.Posters.TryGetValue("original", out posterUrl);
if (posterUrl == null) {
logger.log("Error - Poster url for movie " + dataFromFile.getName() + " was null");
} else {
saveCover(posterUrl, fullPath, failedMovies, dataFromFile.getName());
}
outputWriter.WriteOutput(fullPath + "//Info.xml", info, dataFromFile, fullCast);
}
//Get all subdirectories of the movie directory
private static String[] GetMovieNames()
{
String[] movies;
try {
movies = Directory.GetDirectories(baseDirectory);
} catch (IOException e) {
movies = new String[]{};
logger.log(e.ToString());
}
return movies;
}
private static void saveCover(String url, String destination, ArrayList failedMovies, String movieName)
{
WebClient client = new WebClient();
String tempFile = System.IO.Path.GetTempFileName();
logger.log(tempFile);
client.DownloadFile(new Uri(url), tempFile);
if (File.Exists(destination + "//Folder.jpg")) {
SHA512 sha = SHA512.Create();
Byte[] hash = sha.ComputeHash(new StreamReader(tempFile).BaseStream);
Byte[] existingImageHash = sha.ComputeHash(new StreamReader(destination + "//Folder.jpg").BaseStream);
Boolean hashMatch = false;
hashMatch = existingImageHash.Equals(hash);
if (!hashMatch) {
logger.log("Existing file hash does not match downloaded for movie [" + movieName + "]");
failedMovies.Add(movieName);
} else {
logger.log("Identical image for [" + movieName + "]");
}
} else {
logger.log("No image yet, saving to [" + destination + "]");
File.Copy(tempFile, destination + "//Folder.jpg");
}
}
}
} |
using System;
namespace GaleService.DomainLayer.Managers.Exceptions
{
[Serializable]
public class GaleBaseException : Exception
{
public GaleBaseException()
{
}
public GaleBaseException(string message) : base(message)
{
}
public GaleBaseException(string message, Exception inner) : base(message, inner)
{
}
protected GaleBaseException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CAPA_NEGO;
using SEGU_ENTI;
using SEGU_ENTI.Entidades;
using SEGU_ENTI.Interfaz;
using System.Data;
using SEGU_JC.Utilitario;
namespace SEGU_JC.Models
{
public class M_SEGU_ROLE : IEN_SEGU_ROLE
{
clsNEGOCIO oclsNEGOCIO = new clsNEGOCIO();
public List<clsEN_SEGU_ROLE> fn_MOST_ROLE()
{
List<clsEN_SEGU_ROLE> lSEGU_ROLE = new List<clsEN_SEGU_ROLE>();
DataTable dt = oclsNEGOCIO.fn_MOST_ROLE();
if (dt!= null)
{
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
lSEGU_ROLE.Add(new clsEN_SEGU_ROLE()
{
CO_ROLE = dt.Rows[i]["CO_ROLE"].ToString(),
DE_ROLE = dt.Rows[i]["DE_ROLE"].ToString(),
ES_ROLE = dt.Rows[i]["ES_ROLE"].ToString(),
ID_ROLE = int.Parse(dt.Rows[i]["ID_ROLE"].ToString()),
NO_ROLE = dt.Rows[i]["NO_ROLE"].ToString(),
});
}
}
}
return lSEGU_ROLE;
}
public List<clsEN_SEGU_ROLE_DETA> fn_GRIL_PERF_SIST(int nID_ROLE)
{
List<clsEN_SEGU_ROLE_DETA> lSEGU_ROLE_DETA = new List<clsEN_SEGU_ROLE_DETA>();
DataTable dt = oclsNEGOCIO.fn_GRIL_PERF_SIST(nID_ROLE);
if (dt != null)
{
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
lSEGU_ROLE_DETA.Add(new clsEN_SEGU_ROLE_DETA() {
ID_SIST = int.Parse(dt.Rows[i]["ID_SIST"].ToString()),
ID_ROLE_DETA = int.Parse(dt.Rows[i]["ID_ROLE_DETA"].ToString()),
ID_ROLE = int.Parse(dt.Rows[i]["ID_ROLE"].ToString()),
DE_SELE_01 = bool.Parse(dt.Rows[i]["DE_SELE_01"].ToString()),
SEGU_SIST = fn_SEGU_SIST(clsUTILITARIO.ParseNullableInt(dt.Rows[i]["ID_SIST_SUPE"] == null ? "" : dt.Rows[i]["ID_SIST_SUPE"].ToString()), dt.Rows[i]["CO_SIST"].ToString(), dt.Rows[i]["DE_SIST"].ToString())
});
}
}
}
return lSEGU_ROLE_DETA;
}
public List<clsSEGU_SIST> fn_SEGU_SIST(int? nID_SIST_SUPE, string sCO_SIST, string sDE_SIST)
{
List<clsSEGU_SIST> lSEGU_SIST = new List<clsSEGU_SIST>();
lSEGU_SIST.Add(new clsSEGU_SIST() {
ID_SIST_SUPE = nID_SIST_SUPE,
CO_SIST = sCO_SIST,
DE_SIST = sDE_SIST
});
return lSEGU_SIST;
}
public List<clsEN_SEGU_ROLE> fn_ENCO_ROLE(string sCO_ROLE, string sNO_ROLE)
{
List<clsEN_SEGU_ROLE> lSEGU_ROLE = new List<clsEN_SEGU_ROLE>();
DataTable dt = oclsNEGOCIO.fn_ENCO_ROLE(sCO_ROLE, sNO_ROLE);
if (dt != null)
{
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
lSEGU_ROLE.Add(new clsEN_SEGU_ROLE()
{
ID_ROLE = int.Parse(dt.Rows[i]["ID_ROLE"].ToString()),
CO_ROLE = dt.Rows[i]["CO_ROLE"].ToString(),
NO_ROLE = dt.Rows[i]["NO_ROLE"].ToString(),
DE_ROLE = dt.Rows[i]["DE_ROLE"].ToString()
});
}
}
}
return lSEGU_ROLE;
}
}
} |
/*
* Copyright 2017 University of Zurich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using JetBrains.Application.DataContext;
using JetBrains.Application.UI.Actions;
using JetBrains.Application.UI.Actions.ActionManager;
using JetBrains.Application.UI.ActionsRevised.Menu;
namespace KaVE.VS.FeedbackGenerator.Menu
{
public abstract class MenuActionHandlerBase<T> : IExecutableAction where T : IExecutableAction
{
protected MenuActionHandlerBase(IActionManager am)
{
var actId = am.Defs.GetActionDef<T>();
am.Handlers.AddHandler(actId, this);
}
public virtual bool Update(IDataContext context, ActionPresentation presentation, DelegateUpdate nextUpdate)
{
return true;
}
public abstract void Execute(IDataContext context, DelegateExecute nextExecute);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
namespace HlsView
{
public partial class Page1 : PhoneApplicationPage
{
public Page1()
{
InitializeComponent();
BuildLocalizedApplicationBar();
gameDate.Value = DateTime.Now.Date;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
NavigationService.RemoveBackEntry();
}
private void btnGo_Click(object sender, RoutedEventArgs e)
{
int year = gameDate.Value.Value.Year;
int month = gameDate.Value.Value.Month;
int day = gameDate.Value.Value.Day;
string dateString = year.ToString() + month.ToString("00") + day.ToString("00");
NavigationService.Navigate(new Uri("/GameList.xaml?date=" + dateString, UriKind.Relative));
}
// Sample code for building a localized ApplicationBar
private void BuildLocalizedApplicationBar()
{
// Set the page's ApplicationBar to a new instance of ApplicationBar.
ApplicationBar = new ApplicationBar();
// Create a new menu item with the localized string from AppResources.
ApplicationBarMenuItem appbarmenuitem = new ApplicationBarMenuItem("Settings...");
ApplicationBarMenuItem appbarmenuitem2 = new ApplicationBarMenuItem("About");
ApplicationBar.MenuItems.Add(appbarmenuitem);
ApplicationBar.MenuItems.Add(appbarmenuitem2);
appbarmenuitem.Click += appbarmenuitem_Click;
appbarmenuitem2.Click += appbarmenuitem2_Click;
}
void appbarmenuitem2_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/About.xaml", UriKind.Relative));
}
void appbarmenuitem_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.Relative));
}
private void gameDate_ValueChanged(object sender, DateTimeValueChangedEventArgs e)
{
if (gameDate.Value.Value.Date > DateTime.Now.Date)
{
gameDate.Value = DateTime.Now.Date;
MessageBox.Show("You can only look up games on past or current days.");
}
}
}
} |
using ReadyGamerOne.Global;
using ReadyGamerOne.Utility;
using UnityEditor;
using UnityEngine;
namespace PurificationPioneer
{
public class SceneTools
#if UNITY_EDITOR
:IEditorTools
#endif
{
#pragma warning disable 414
#if UNITY_EDITOR
private static string Title = "场景工具";
private static GameObject root;
private static GameObject cube;
private static float floorDepth = -2;
private static Vector2Int floorSize;
private static void OnToolsGUI(string rootNs, string viewNs, string constNs, string dataNs, string autoDir,
string scriptDir)
{
root = EditorGUILayout.ObjectField("Root", root, typeof(GameObject), true)
as GameObject;
cube = EditorGUILayout.ObjectField("Cube", cube, typeof(GameObject), true)
as GameObject;
floorDepth = EditorGUILayout.Slider("深度", floorDepth, -10, 10);
floorSize = EditorGUILayout.Vector2IntField("大小", floorSize);
if (GUILayout.Button("生成地板",
GUILayout.Height(2 * EditorGUIUtility.singleLineHeight)))
{
if (null == root || cube==null)
{
Debug.LogError("Params is error");
return;
}
var floorRoot = root.transform.Find("floorRoot");
if (floorRoot == null)
{
var obj = new GameObject("floorRoot");
obj.transform.SetParent(root.transform);
obj.transform.localPosition=Vector3.zero;
obj.transform.localScale = Vector3.one;
floorRoot = obj.transform;
}
else
{
floorRoot.DestroyChildrenImmediate();
}
var cubeSize = cube.transform.lossyScale;
var startPos=new Vector3(
-(cubeSize.x*floorSize.x/2),
floorDepth,
-(cubeSize.z*floorSize.y/2));
for (var i = 0; i < floorSize.x; i++)
{
for (var j = 0; j < floorSize.y; j++)
{
var pos = startPos + new Vector3(
i * cubeSize.x,
0,
j * cubeSize.z);
var obj = Object.Instantiate(cube, pos, Quaternion.identity, floorRoot);
obj.name = $"Floor_{i}_{j}";
}
}
}
}
#endif
}
} |
using ProConstructionsManagment.Desktop.Commands;
using ProConstructionsManagment.Desktop.Enums;
using ProConstructionsManagment.Desktop.Messages;
using ProConstructionsManagment.Desktop.Services;
using ProConstructionsManagment.Desktop.Views.Base;
using System.Threading.Tasks;
using System.Windows.Input;
namespace ProConstructionsManagment.Desktop.Views.ProjectRecruitment
{
public class ProjectRecruitmentNavigationViewModel : ViewModelBase
{
private readonly IProjectsService _projectsService;
private readonly IMessengerService _messengerService;
private string _projectId;
private string _projectRecruitmentId;
public ProjectRecruitmentNavigationViewModel(IProjectsService projectsService, IMessengerService messengerService)
{
_projectsService = projectsService;
_messengerService = messengerService;
messengerService.Register<ProjectIdMessage>(this, msg => ProjectId = msg.ProjectId);
messengerService.Register<ProjectRecruitmentIdMessage>(this, msg => ProjectRecruitmentId = msg.ProjectRecruitmentId);
}
public string ProjectId
{
get => _projectId;
set => Set(ref _projectId, value);
}
public string ProjectRecruitmentId
{
get => _projectRecruitmentId;
set => Set(ref _projectRecruitmentId, value);
}
public ICommand NavigateToProjectRecruitmentsViewCommand => new AsyncRelayCommand(NavigateToProjectRecruitmentsView);
private async Task NavigateToProjectRecruitmentsView()
{
_messengerService.Send(new ChangeViewMessage(ViewTypes.ProjectRecruitments));
_messengerService.Send(new ChangeViewMessage(ViewTypes.ProjectRecruitmentsNavigation));
_messengerService.Send(new ProjectIdMessage(ProjectId));
_messengerService.Send(new ProjectRecruitmentIdMessage(ProjectRecruitmentId));
}
public ICommand NavigateToMainViewCommand => new AsyncRelayCommand(NavigateToMainView);
private async Task NavigateToMainView()
{
_messengerService.Send(new ChangeViewMessage(ViewTypes.Main));
_messengerService.Send(new ChangeViewMessage(ViewTypes.MainNavigation));
}
public ICommand NavigateToRecruitedEmployeesViewCommand => new AsyncRelayCommand(NavigateToRecruitedEmployeesView);
private async Task NavigateToRecruitedEmployeesView()
{
var projectRecruitment = await _projectsService.GetProjectRecruitmentById(ProjectRecruitmentId);
_messengerService.Send(new ChangeViewMessage(ViewTypes.RecruitedEmployeesWithPosition));
_messengerService.Send(new ProjectIdMessage(ProjectId));
_messengerService.Send(new ProjectRecruitmentIdMessage(ProjectRecruitmentId));
_messengerService.Send(new PositionIdMessage(projectRecruitment.PositionId));
}
public ICommand NavigateToAddEmployeesToProjectRecruitmentViewCommand => new AsyncRelayCommand(NavigateToAddEmployeesToProjectRecruitmentView);
private async Task NavigateToAddEmployeesToProjectRecruitmentView()
{
var projectRecruitment = await _projectsService.GetProjectRecruitmentById(ProjectRecruitmentId);
_messengerService.Send(new ChangeViewMessage(ViewTypes.AddEmployeesToProjectRecruitment));
// _messengerService.Send(new ChangeViewMessage(ViewTypes.AddEmployeesToProjectRecruitmentNavigation));
_messengerService.Send(new ProjectIdMessage(ProjectId));
_messengerService.Send(new ProjectRecruitmentIdMessage(ProjectRecruitmentId));
_messengerService.Send(new PositionIdMessage(projectRecruitment.PositionId));
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.