text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Euler_Logic.Problems {
public interface IProblem {
bool RequiresInputFile { get; }
string ProblemName { get; }
string GetAnswer();
string GetAnswer2();
void UploadInputFile(string fileName);
void DownloadOutputFile();
bool HasAnswer2 { get; }
}
public abstract class ProblemBase : IProblem {
public abstract string ProblemName { get; }
public abstract string GetAnswer();
public virtual string GetAnswer2() {
return "";
}
public virtual void UploadInputFile(string fileName) { }
public virtual void DownloadOutputFile() { }
public virtual bool RequiresInputFile {
get { return false; }
}
public virtual bool HasAnswer2 => false;
}
}
|
using GraphQL.Types;
using GraphQL;
using System.Linq;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text.Json;
namespace Microsoft
{
public class Response
{
public List<Planet> results { get; set; }
}
public class HttpHelper
{
public static async ValueTask<T> Get<T>(string url)
{
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
};
HttpClient client = new HttpClient();
var streamTask = client.GetStreamAsync(url);
var response = await System.Text.Json.JsonSerializer.DeserializeAsync<T>(await streamTask, options);
return response;
}
}
public class Query
{
[GraphQLMetadata("hello")]
public string GetHello()
{
return "World";
}
[GraphQLMetadata("products")]
public async Task<List<Product>> GetProducts()
{
return await HttpHelper.Get<List<Product>>("http://localhost:8000");
}
[GraphQLMetadata("product")]
public Product GetProductById(int id)
{
return Data.Products.SingleOrDefault(p => p.Id == id);
}
[GraphQLMetadata("reviews")]
public async Task<List<Review>> GetReviews()
{
return await HttpHelper.Get<List<Review>>("http://localhost:8001");
}
[GraphQLMetadata("planets")]
public async Task<List<Planet>> GetPlanets()
{
var response = await HttpHelper.Get<Response>("https://swapi.co/api/planets");
return response.results;
}
}
[GraphQLMetadata("Review", IsTypeOf = typeof(Review))]
public class ReviewResolver
{
public string Title(Review review) => review.Title;
public string Description(Review review) => review.Description;
public int Grade(Review review) => review.Grade;
public async Task<Product> Product(ResolveFieldContext context, Review review)
{
var products = await HttpHelper.Get<List<Product>>("http://localhost:8000");
return products.SingleOrDefault(p => p.Id == review.Product);
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//Carlos Salas G.
//Jhonatan Araya Valverde
namespace TorresdeHanoi
{
public partial class frmDificultad : Form
{
public int demo = 0;
public frmDificultad()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)// boton aceptar
{
this.Hide();//esconde el formulario
torresHanoi juego1 = new torresHanoi();//llama al formulario del juego
// condicional para seleccionar la dificultad
if (rbtnFacil.Checked == true)// si facil esta marcado
{
juego1.NumAnillos = 3; //seran 3 discos
}
if (rbtnNormal.Checked == true)// si normal esta marcado
{
juego1.NumAnillos = 6; //seran 6 discos
}
if (rbtnUltraViolencia.Checked == true) //si dificil esta marcado
{
juego1.NumAnillos = 8;//seran 8 discos
}
juego1.demo = demo;
juego1.Show(); // muestra el formulario
}
private void Form4_Load(object sender, EventArgs e)
{
rbtnNormal.Checked = true;// al cargar el formulario marca por defento normal
}
}
}
|
using System;
using System.Linq;
using System.Threading.Tasks;
namespace ExcelToJsonExtractor
{
class ExcelToJsonExtractor
{
static async Task Main(string[] args)
{
if (args.Count() == 0 || args[0].Contains("help"))
{
Console.WriteLine("\nNo file given\n");
Console.WriteLine("Usage: ExcelToJsonExtractor.exe some_excel_file.xls\n");
return;
}
var excelFileReader = new ExcelFileReader();
if (args.Count() == 1 && args[0].EndsWith(".xls"))
{
excelFileReader.ExcelFile = args[0];
}
excelFileReader.Run();
var trades = excelFileReader.GetTradeCollection();
if (trades.Count() == 0)
{
Console.WriteLine("No trades could be generated\n");
return;
}
var dataWriter = new JsonDataWriter();
await dataWriter.WriteDataToFile(trades);
if (args.Count() > 0 && args.Contains("write"))
{
var writer = new WriteDataToConsole();
writer.CreateConsoleTable(trades);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using Framework.Core.Config;
using Framework.Core.Drivers;
using Framework.Core.Helpers.Data;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
using Keys = OpenQA.Selenium.Keys;
namespace Framework.Core.Common
{
public class Driver: IDisposable
{
public delegate Driver Factory(Browser browser);
#region Driver
public readonly IWebDriver _driver;
/// <summary>
/// starts default browser instance
/// </summary>
public Driver()
{
_driver = BrowserFactory.Start();
SetDefaultTimeOuts();
}
/// <summary>
/// starts browser instance based on browser string, list of browsers found in AvailableBrowsers class
/// </summary>
public Driver(Browser browser)
{
_driver = BrowserFactory.Start(browser);
SetDefaultTimeOuts();
}
#endregion
#region timeouts
public static int DefaultWait = 10;
public static int DefaultMaxAttempts = 4;
public static int DefaultTimeOut = 30;
public static int DefaultPageTimeOut = 90;
public void SetDefaultTimeOuts()
{
_driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(DefaultTimeOut));
_driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(DefaultPageTimeOut));
}
public int GetDefaultWait()
{
return DefaultWait;
}
public int GetDefaultTimeOut()
{
return DefaultTimeOut;
}
public int GetDefaultPageTimeOut()
{
return DefaultPageTimeOut;
}
#endregion
public void TakeScreenshotOutputException(Exception ex, string output)
{
TakeScreenshot(ex.Message);
Console.WriteLine(ex.Message + " exception " + output);
}
#region Move
/// <summary>
/// moves focus to element
/// </summary>
public void MoveToElement(IWebElement element)
{
Actions action = new Actions(_driver);
//action.SendKeys(Keys.End);
try
{
action.MoveToElement(element).Build().Perform();
}
catch (Exception ex)
{
TakeScreenshotOutputException(ex, "moving element ");
throw;
}
}
/// <summary>
/// Scroll the browser to the element's Y position
/// </summary>
public void MoveToElementYPosition(IWebElement element)
{
var js = _driver as IJavaScriptExecutor;
if (js != null)
{
try
{
js.ExecuteScript(string.Format("window.scrollTo(0," + element.Location.Y + ")"));
}
catch (Exception ex)
{
TakeScreenshotOutputException(ex, "moving element to element Y position ");
throw;
}
}
}
public void MoveToPlace(int x, int y)
{
Actions action = new Actions(_driver);
try
{
action.MoveByOffset(x, y).Click().Perform();
}
catch (Exception ex)
{
TakeScreenshotOutputException(ex, "move by offest X,Y " + x + ", " + y);
throw;
}
}
public void MoveFromElementToPlace(IWebElement element,int x, int y)
{
Actions action = new Actions(_driver);
action.DragAndDropToOffset(element, x, y).Perform();
}
public void PhysicalMoveToElement(IWebElement startElement, IWebElement endElement)
{
Actions action = new Actions(_driver);
try
{
action.DragAndDrop(startElement, endElement).Perform();
}
catch (Exception ex)
{
TakeScreenshotOutputException(ex, "moving element from start element " + startElement + " to end element " + endElement);
throw;
}
}
public void Movetooffset(int startx, int starty, int endx, int endy)
{
Actions action = new Actions(_driver);
try
{
action.MoveByOffset(startx, starty).ClickAndHold().MoveByOffset(endx, endy).Release().Build().Perform();
}
catch (Exception ex)
{
TakeScreenshotOutputException(ex, "clicking and holding, moving by offest x " + endx + " y " + endy);
throw;
}
}
#endregion
#region scroll
/// <summary>
/// scrolls into view of element
/// </summary>
public void ScrollIntoView(IWebElement element)
{
var js = _driver as IJavaScriptExecutor;
if (js != null)
{
try
{
js.ExecuteScript("arguments[0].scrollIntoView(true);", element);
}
catch (Exception ex)
{
TakeScreenshotOutputException(ex, "scrolling into view " + element);
throw;
}
}
}
public void ScrollToBottomOfPage()
{
var js = _driver as IJavaScriptExecutor;
if (js != null)
{
try
{
js.ExecuteScript("window.scrollTo(0, document.body.scrollHeight);");
}
catch (Exception ex)
{
TakeScreenshotOutputException(ex, "scrolling to bottom of page");
throw;
}
}
}
#endregion
#region Browser
/// <summary>
/// returns driver navigate
/// </summary>
/// <returns></returns>
public INavigation Navigate()
{
return _driver.Navigate();
}
/// <summary>
/// refreshes page
/// </summary>
public void RefreshPage()
{
Navigate().Refresh();
}
/// <summary>
/// navigates to previous pag, waits for url to change
/// </summary>
public void GoToPreviousPage()
{
string currentUrl = GetUrl();
Navigate().Back();
//Actions action = new Actions(_driver);
//action.Click();
//action.SendKeys(Keys.Backspace).Perform();
while (UrlContains(currentUrl)) Thread.Sleep(1000);
}
/// <summary>
/// navigates to next page, waits for url to change
/// </summary>
public void GoToNextPage()
{
string currentUrl = GetUrl();
Navigate().Forward();
//Actions action = new Actions(_driver);
//action.Click();
//action.KeyDown(Keys.Shift).SendKeys(Keys.Backspace).KeyUp(Keys.Shift).Perform();
while (UrlContains(currentUrl)) Thread.Sleep(1000);
}
//move page down
public void Movetobottom(IWebElement element)
{
Actions action = new Actions(_driver);
while (!IsElementPresent(element))
{
try
{
action.SendKeys(Keys.PageDown).Perform();
}
catch (Exception ex)
{
TakeScreenshotOutputException(ex, "paging down ");
throw;
}
}
}
// move page up
public void Movetotop(IWebElement element)
{
Actions action = new Actions(_driver);
while (!IsElementPresent(element))
{
try
{
action.SendKeys(Keys.PageUp).Perform();
}
catch (Exception ex)
{
TakeScreenshotOutputException(ex, "paging up ");
throw;
}
}
}
#endregion
#region Manage
public IOptions Manage()
{
// TODO: Encapsulate this better?
return _driver.Manage();
}
#endregion
#region SetTimeouts
/// <summary>
/// sets wait times for elements in seconds
/// </summary>
/// <param name="seconds"></param>
public void SetImplicitWaitTimeout(int seconds)
{
Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(seconds));
}
/// <summary>
/// resets wait time for elements back to default timeout
/// </summary>
public void ResetImplicitWaitTimout()
{
Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(GetDefaultTimeOut()));
}
/// <summary>
/// sets page load timeout in seconds
/// </summary>
/// <param name="seconds"></param>
public void SetPageLoadTimout(int seconds)
{
Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(seconds));
}
/// <summary>
/// sets page load timeout in seconds
/// </summary>
/// <param name="seconds"></param>
public void ResetPageLoadTimout(int seconds)
{
Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(DefaultPageTimeOut));
}
#endregion
#region Attribute
/// <summary>
/// sets element attribute by value
/// </summary>
public void SetAttribute(IWebElement element, string attribute, string value)
{
var js = _driver as IJavaScriptExecutor;
try
{
js.ExecuteScript("arguments[0].setAttribute('" + attribute + "', '" + value + "')", element);
}
catch (Exception ex)
{
TakeScreenshotOutputException(ex, "setting element attribute " + attribute + " to value " + value);
throw;
}
}
/// <summary>
/// get element value by attribute
/// </summary>
public string GetAttribute(IWebElement element, string attribute)
{
try
{
return element.GetAttribute(attribute);
}
catch (Exception ex)
{
TakeScreenshotOutputException(ex, "getting element attribute " + attribute);
throw;
}
}
#endregion
#region Element
/// <summary>
/// returns list of element options
/// </summary>
public IList<IWebElement> Options(IWebElement element)
{
var xselectElement = new SelectElement(element);
try
{
return xselectElement.Options;
}
catch (Exception ex)
{
TakeScreenshotOutputException(ex, "returning element options");
throw;
}
}
/// <summary>
/// returns list of child nodes
/// </summary>
public List<string> GetChildNodes(IWebElement element, string nodes)
{
var list = new List<string>();
List<IWebElement> children;
try
{
children = new List<IWebElement>(element.FindElements(By.TagName(nodes)));
}
catch (Exception ex)
{
TakeScreenshotOutputException(ex, "returning element nodes " + nodes);
throw;
}
foreach (IWebElement child in children)
{
list.Add(child.Text);
}
return list;
}
/// <summary>
/// returns element enabled state
/// </summary>
public bool IsEnabled(IWebElement element)
{
return element.Enabled;
}
/// <summary>
/// returns element selected state
/// </summary>
public bool IsSelected(IWebElement element)
{
return element.Selected;
}
/// <summary>
/// returns element text
/// </summary>
public string Text(IWebElement element)
{
return element.Text;
}
#endregion
#region Browser
/// <summary>
/// quits browser
/// </summary>
public void BrowserQuit()
{
_driver.Quit();
}
public void BrowserQuit(string name)
{
//TakeScreenshot(name);
_driver.Quit();
}
public void TakeScreenshot(string name)
{
name = name.Split('\n')[0];
name = Regex.Replace(name, @"[^0-9a-zA-Z\._.]", "_");
name = name.Trim(' ');
name = name.Split('\n')[0];
DateTime dt = DateTime.Parse(DateTime.Now.ToString());
string ssDir = "Screenshots";
//var environmentDir = new DirectoryInfo(Environment.CurrentDirectory);
var baseDir = AppDomain.CurrentDomain.BaseDirectory;
var environmentDir = new DirectoryInfo(baseDir);
environmentDir.CreateSubdirectory(ssDir);
string dirPath = environmentDir.ToString() + "\\" + ssDir + "\\";
ITakesScreenshot screenshotDriver = _driver as ITakesScreenshot;
Screenshot screenshot = screenshotDriver.GetScreenshot();
string filename = dirPath + name + DateTime.Now.ToString("yyyyMMdd") + dt.ToString("HHmmss") + ".png";
screenshot.SaveAsFile(filename, ImageFormat.Png);
Console.WriteLine("screenshot has been recorded: " + filename);
}
/// <summary>
/// closes browser
/// </summary>
public void BrowserClose()
{
_driver.Close();
}
/// <summary>
/// returns browser name
/// </summary>
public string BrowserName()
{
return ((RemoteWebDriver)_driver).Capabilities.BrowserName;
}
/// <summary>
/// returns true of browser name contains firefox
/// </summary>
public bool Firefox()
{
return BrowserName().Contains("firefox");
}
public string FirefoxVersion()
{
return ((RemoteWebDriver)_driver).Capabilities.Version;
}
/// <summary>
/// returns true of browser name contains internet explorer
/// </summary>
public bool InternetExplorer()
{
return BrowserName().Contains("internet explorer");
}
/// <summary>
/// returns true of browser name contains chrome
/// </summary>
public bool Chrome()
{
return BrowserName().Contains("chrome");
}
#endregion
#region Click
/// <summary>
/// clicks element by xpath string
/// </summary>
public void Click(By by)
{
Click(_driver.FindElement(by));
}
/// <summary>
/// waits for element present, then clicks elements via javascript
/// </summary>
public void JavascriptClick(IWebElement element)
{
var js = _driver as IJavaScriptExecutor;
if (js != null)
{
try
{
js.ExecuteScript("arguments[0].click();", element);
}
catch (Exception ex)
{
TakeScreenshotOutputException(ex, "executing javascript click on element ");
throw;
}
}
}
/// <summary>
/// clicks the elements via javascript, does not wait for element
/// </summary>
/// <param name="element"></param>
public void JavascriptClickNoWait(IWebElement element)
{
JavascriptClick(element);
}
/// <summary>
/// clicks element using webdriver click for firefox, if ie or chrome, uses javascript exectuer to click
/// </summary>
public void Click(IWebElement element)
{
WebDriverClick(element);
}
public void MoveToElementWithOffsetAndClick(IWebElement element, int x, int y)
{
Actions action = new Actions(_driver);
try
{
action.MoveToElement(element, x, y).Click().Perform();
}
catch (Exception ex)
{
TakeScreenshotOutputException(ex, "moving to element with offset and click at x " + x + ",y " + y);
throw;
}
}
public void MoveToElementWithOffsetAndClick(IWebElement element)
{
MoveToElementWithOffsetAndClick(element, 0, 20);
}
/// <summary>
/// clicks element by webdriver click
/// </summary>
/// <param name="element"></param>
public void WebDriverClick(IWebElement element)
{
if (Chrome())
{
int x = element.Location.X;
int y = element.Location.Y;
int height = element.Size.Height;
int width = element.Size.Width;
int halfHeight = height/2;
int halfWidth = width/2;
MoveToElementWithOffsetAndClick(element, halfWidth, halfHeight);
}
else
{
try
{
element.Click();
}
catch (Exception ex)
{
TakeScreenshotOutputException(ex, "clicking element ");
throw;
}
}
}
#endregion
#region Check and Uncheck
/// <summary>
/// Checks a checkbox or selects a radio button if it is not selected.
/// </summary>
/// <param name="elementToSelect"></param>
public void Check(IWebElement elementToSelect)
{
if (elementToSelect.Selected) return;
Click(elementToSelect);
}
/// <summary>
/// Unchecks a checkbox if it is selected
/// </summary>
/// <param name="checkboxElement"></param>
public void Uncheck(IWebElement checkboxElement)
{
if (!checkboxElement.Selected) return;
Click(checkboxElement);
}
/// <summary>
/// Checks a checkbox element if passed boolean is true, unchecks if passed boolean is false
/// </summary>
/// <param name="check"></param>
/// <param name="checkboxElement"></param>
public void CheckOrUncheck(IWebElement checkboxElement, bool check)
{
if (check)
Check(checkboxElement);
else
Uncheck(checkboxElement);
}
/// <summary>
/// Selects a radio button element if the passed boolean is true
/// </summary>
/// <param name="radioButtonElement"></param>
/// <param name="select"></param>
public void SelectRadioButton(IWebElement radioButtonElement, bool select)
{
if (select)
Check(radioButtonElement);
}
#endregion
#region Javascript Alerts
public bool IsAlertPresent()
{
try
{
_driver.SwitchTo().Alert();
return true;
} // try
catch (NoAlertPresentException )
{
return false;
} // catch
} // isAlertPresent()
/// <summary>
/// clicks accept on the javascript alert
/// </summary>
public void JavascriptAlertClickAccept()
{
if (IsAlertPresent())
{
IAlert alert = _driver.SwitchTo().Alert();
Thread.Sleep(1000);
alert.Accept();
// return alert.Text.ToString();
}
// return null;
}
/// <summary>
/// clicks dismiss on the javascript alert
/// </summary>
public void JavascriptAlertClickDismiss()
{
if (IsAlertPresent())
{
IAlert alert = _driver.SwitchTo().Alert();
Thread.Sleep(1000);
alert.Dismiss();
// return alert.Text.ToString();
}
// return null;
}
#endregion
#region Keys
/// <summary>
/// sets attribute of element
/// </summary>
public void JavaScriptSetValue(IWebElement element, string text)
{
var js = _driver as IJavaScriptExecutor;
try
{
js.ExecuteScript("arguments[0].setAttribute('value', " + text + " )");
}
catch (Exception ex)
{
TakeScreenshotOutputException(ex, "setting element attribute value text to " + text);
throw;
}
}
/// <summary>
/// send tab command to element
/// </summary>
/// <param name="element"></param>
public void Tab(IWebElement element)
{
SendKeys(element, Keys.Tab);
}
/// <summary>
/// types keys into element
/// </summary>
public void SendKeys(IWebElement element, string text)
{
try
{
element.SendKeys(text);
}
catch (Exception ex)
{
TakeScreenshotOutputException(ex, "sending " + text + " to element");
throw;
}
}
/// <summary>
/// types keys into element and hits enter for select2, includes selecting found element
/// </summary>
public void SendKeysHitEnter(IWebElement element, string text)
{
SendKeys(element, text);
SendKeys(element, Keys.ArrowDown);
SendKeys(element, Keys.Enter);
}
/// <summary>
/// selects list of strings in select 2 element
/// </summary>
/// <param name="select2MultiSelectElement"></param>
/// <param name="itemList"></param>
public void SendKeysToSelect2MultiSelectIfListNotNullOrEmpty(IWebElement select2MultiSelectElement, List<string> itemList)
{
if (itemList == null || itemList.Count < 1) return;
var select2Choices = new List<IWebElement>(_driver.FindElements(_select2Choice));
foreach (var select2Choice in select2Choices)
{
SendKeys(select2MultiSelectElement, Keys.Backspace);
SendKeys(select2MultiSelectElement, Keys.Backspace);
}
foreach (var item in itemList)
{
List<IWebElement> searchResultsMatch;
SendKeys(select2MultiSelectElement, item);
do
{
searchResultsMatch = new List<IWebElement>(_driver.FindElements(By.CssSelector(".select2-match")));
} while (searchResultsMatch.Count > 1);
Click(searchResultsMatch[0]);
}
}
/// <summary>
/// Clears the select2MultiSelectElement
/// </summary>
/// <param name="select2MultiSelectElement"></param>
public void ClearSelect2MultiSelect(IWebElement select2MultiSelectElement)
{
HighlightElement(select2MultiSelectElement);
var webElementList = new List<IWebElement>(_driver.FindElements(_select2ChoiceClose));
if (webElementList.Count < 1) return;
while (webElementList.Count > 0)
{
var webElement = webElementList.First();
Click(webElement);
webElementList.Remove(webElement);
SetImplicitWaitTimeout(1);
if (webElementList.Count < 1)
break;
webElementList = new List<IWebElement>(_driver.FindElements(_select2ChoiceClose));
}
//Click(select2MultiSelectElement);
}
/// <summary>
/// clears select 2 and selects list of strings in select 2 element
/// </summary>
/// <param name="select2MultiSelectElement"></param>
/// <param name="itemList"></param>
public void ClearAndSendKeysToSelect2MultiSelectIfListNotNullOrEmpty(IWebElement select2MultiSelectElement, List<string> itemList)
{
ClearSelect2MultiSelect(select2MultiSelectElement);
if (itemList == null || itemList.Count < 1) return;
foreach (var item in itemList)
{
SendKeys(select2MultiSelectElement, item);
WebDriverClick(_driver.FindElement(_select2Match));
}
}
/// <summary>
/// clears element input field
/// </summary>
public void ClearAndTab(IWebElement element)
{
SendKeys(element, Keys.Control + "a");
SendKeys(element,Keys.Delete);
SendKeys(element, Keys.Tab);
}
/// <summary>
/// clears element input field
/// </summary>
public void ClearOnly(IWebElement element)
{
SendKeys(element, Keys.Control + "a");
SendKeys(element, Keys.Delete);
}
public void WaitElementEnabledandClick(IWebElement element)
{
int count = 1;
while (true)
{
if (element.Enabled&&element.Displayed)
{
Click(element);
break;
}
Thread.Sleep(100);
count++;
if (count > DefaultTimeOut)
{
Console.WriteLine("times out");
break;
}
}
}
/// <summary>
/// Clears element input field, then types keys into element
/// </summary>
/// <param name="element"></param>
/// <param name="text"></param>
public void ClearAndSendKeys(IWebElement element, string text)
{
ClearOnly(element);
SendKeys(element, text);
}
/// <summary>
/// Clears and fills the input field with the passed text if the text is neither null nor empty
/// </summary>
/// <param name="inputFieldElement"></param>
/// <param name="text"></param>
public void ClearAndSendKeysIfStringNotNullOrEmpty(IWebElement inputFieldElement, string text)
{
if (!String.IsNullOrEmpty(text))
ClearAndSendKeys(inputFieldElement, text);
}
#endregion
#region Is Present
/// <summary>
/// returns true if element displays
/// </summary>
public bool Exists(IWebElement element)
{
try
{
if (element.Displayed)
return true;
}
catch (Exception)
{
return false;
//throw;
}
return true;
}
/// <summary>
/// returns true if text is present in body
/// </summary>
public bool IsTextPresent(string textToFind)
{
return _driver.FindElement(By.TagName("body")).Text.Contains(textToFind);
}
/// <summary>
/// returns true if element is present, waits implicit
/// </summary>
public bool IsElementPresentImplicitWait(By by)
{
try
{
FindElementByImplicitWait(by, 0);
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex + " exception found during implicit wait");
return false;
}
}
/// <summary>
/// returns true if element is present, waits explicit
/// </summary>
public bool IsElementPresentExplicitWait(By by)
{
try
{
ExplicitWait(by, 0);
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex + " exception found during explicit wait");
return false;
}
}
/// <summary>
/// returns true if element is present, waits fluently
/// </summary>
public bool IsElementPresentFluentWait(By by)
{
try
{
FindElementByFluentWait(by, 0);
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex + " exception found during fluent wait");
return false;
}
}
/// <summary>
/// returns true if element is present
/// </summary>
public bool IsElementPresentBy(By by)
{
SetImplicitWaitTimeout(0);
try
{
_driver.FindElement(by);
return true;
}
catch (NoSuchElementException )
{
return false;
}
}
/// <summary>
/// returns true if element is present in the element provided
/// </summary>
public bool IsElementPresentBy(By by, IWebElement element)
{
SetImplicitWaitTimeout(0);
try
{
element.FindElement(by);
return true;
}
catch (NoSuchElementException)
{
return false;
}
}
/// <summary>
/// returns true if element is present, doesn't throw exception
/// </summary>
public bool IsElementPresent(By by)
{
return IsElementPresent(FindElement(by), 0);
}
/// <summary>
/// returns true if element is present, doesn't throw exception
/// </summary>
public bool IsElementPresent(IWebElement element)
{
return (IsElementPresent(element, 0));
}
/// <summary>
/// returns true if element displays, doesn't throw exception, doesn't wait
/// </summary>
public bool IsElementPresent(IWebElement element,int seconds)
{
int count = 0;
do
{
try
{
if (element.Displayed)
return true;
count++;
}
catch (Exception)
{
if (count == DefaultTimeOut || count==seconds)
{
break;
}
Thread.Sleep(1000);
count++;
}
} while (count <= seconds+1);
return false;
}
/// <summary>
/// Validates if a Select2 MultiSelect control has a list of strings selected as values
/// </summary>
/// <param name="select2MultiSelectElement"></param>
/// <param name="itemList"></param>
/// <returns>True if the list of passed strings match the selected items in the Select2 MultiSelect</returns>
public bool ValidateSelect2MultiSelectFieldIsCorrect(IWebElement select2MultiSelectElement,
List<String> itemList)
{
var cssSelectorString = String.Format("#{0} li.select2-search-choice",
select2MultiSelectElement.GetAttribute("id"));
var webElementList = _driver.FindElements(By.CssSelector(cssSelectorString));
// TODO: Keep better track of errors
var errorCount = 0;
foreach (var item in itemList)
{
var found = webElementList.Any(webElement => webElement.Text.Equals(item));
if (found)
{
//Console.WriteLine("Found {0} in the list of {1} Select2 MultiSelect elements", item, select2MultiSelectElement);
continue;
}
errorCount++;
//Console.WriteLine("Unable to find {0} in the list of {1} Select2 MultiSelect elements", item, select2MultiSelectElement);
}
return errorCount < 1;
}
#endregion
#region Waits
public void WaitForElementToDisplayBy(By by)
{
WaitForElementToDisplayBy(by, DefaultMaxAttempts, false);
}
public void WaitForElementToDisplayBy(By by, bool throwError)
{
WaitForElementToDisplayBy(by, DefaultMaxAttempts, throwError);
}
public void WaitForElementToDisplayBy(By by, int maxAttempts, bool throwError)
{
int count = 1;
int timeout;
do
{
timeout = GetDefaultTimeOut() * count;
if (FindElementByFluentWait(by) != null) break;
count++;
} while (count <= maxAttempts);
try
{
FindElement(by, 0, true);
}
catch (Exception ex )
{
TakeScreenshotOutputException(ex, "element did not load in " + timeout + " second(s)" + by.ToString());
throw;
}
}
/// <summary>
/// waits until element style does not display (style : none) - usually used for "Loading..." text and the like
/// </summary>
public void WaitUntilElementStyleDoesNotDisplay(By by)
{
try
{
while (!_driver.FindElement(by).GetAttribute("style").Contains("none")) { }
}
catch (Exception )
{
}
}
public IWebElement WaitUntilElementVisible(By by)
{
return WaitUntilElementVisible(by, TimeSpan.FromSeconds(DefaultTimeOut));
}
/// <summary>
/// waits until element is visible by timeout
/// </summary>
public IWebElement WaitUntilElementVisible(By by, TimeSpan timeout)
{
WebDriverWait wait = new WebDriverWait(_driver, timeout);
return wait.Until<IWebElement>(ExpectedConditions.ElementIsVisible(by));
}
public IWebElement WaitUntilElementExists(By by, TimeSpan timeout)
{
return WaitUntilElementExists(by, timeout, false);
}
/// <summary>
/// waits until element exists
/// </summary>
public IWebElement WaitUntilElementExists(By by, TimeSpan timeout, bool ignoreException)
{
IWebElement element;
WebDriverWait wait = new WebDriverWait(_driver, timeout);
if (ignoreException) wait.IgnoreExceptionTypes(typeof(Exception));
wait.Until(ExpectedConditions.ElementExists(by));
element = wait.Until<IWebElement>((d) =>
{
return d.FindElement(by);
});
return element;
}
/// <summary>
/// waits until element does not display
/// </summary>
public void WaitUntilNotDisplayed(By searchBy, int seconds)
{
try
{
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(seconds));
wait.Until(driver => !_driver.FindElement(searchBy).Displayed);
}
catch (Exception )
{
}
}
/// <summary>
/// Explicit waits default timeout is applied only for particular specified element
/// </summary>
public IWebElement ExplicitWait(By by)
{
return ExplicitWait(by, DefaultTimeOut);
}
/// <summary>
/// Explicit wait time is applied only for particular specified element.
/// </summary>
public IWebElement ExplicitWait(By by, int seconds)
{
return WaitUntilElementExists(by, TimeSpan.FromSeconds(seconds));
}
/// <summary>
/// waits until element is not present using by
/// </summary>
public void WaitForNotPresent(By by)
{
const int milliseconds = 1000;
const int mod = 1000 / milliseconds;
int timeout = DefaultTimeOut * mod;
int count = 0;
_driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromMilliseconds(milliseconds));
do
{
IWebElement element;
try
{
element = _driver.FindElement(by);
}
catch (Exception)
{
break;
}
if (IsElementPresent(element))
{
Thread.Sleep(milliseconds);
count++;
}
else
{
break;
}
} while (count <= timeout);
}
#region Implicit
public IWebElement ImplicitWait(By by, int time)
{
SetImplicitWaitTimeout(time);
return _driver.FindElement(by);
}
#endregion
#region FluentWait
public IWebElement FluentWait(By by, int waitInSeconds, int timeOutInSeconds, int pollingInMilliseconds)
{
IWebElement element;
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(waitInSeconds));
wait.Timeout = TimeSpan.FromSeconds(timeOutInSeconds);
wait.PollingInterval = TimeSpan.FromMilliseconds(pollingInMilliseconds);
wait.IgnoreExceptionTypes(typeof(Exception));
element = wait.Until<IWebElement>((d) =>
{
return d.FindElement(by);
});
return element;
}
#endregion
#endregion
#region table
/// <summary>
/// returns true if text displays
/// </summary>
public bool ContainsText(string text)
{
try
{
if (_driver.FindElement(By.XPath("//*[contains(.,'" + text + "')]")) != null)
return true;
}
catch (Exception)
{
return false;
}
return false;
}
/// <summary>
/// returns true if element table cell contains text
/// </summary>
public bool FindTextInTable(IWebElement element, string text)
{
var cells = new List<IWebElement>(element.FindElements(By.TagName("td")));
foreach (IWebElement cell in cells)
{
if (cell.Text.Contains(text))
{
return true;
}
}
return false;
}
/// <summary>
/// returns true if element table cell contains text
/// </summary>
public bool FindTextInTableLastRow(IWebElement element, string text)
{
int match = 0;
Thread.Sleep(1000);
var rows = new List<IWebElement>(element.FindElements(By.TagName("tr")));
foreach (IWebElement row in rows)
{
var cells = new List<IWebElement>(row.FindElements(By.TagName("td")));
foreach (IWebElement cell in cells)
{
// Console.WriteLine("cell-" + cell.Text);
if (cell.Text.Contains(text))
{
match++;
}
}
}
return (match >= 1);
}
/// <summary>
/// this just traverses through all the elements in a table and doesn't actually do any checking, but good for large tables without popup windows
/// </summary>
/// <param name="element">element of the table that you want to traverse</param>
/// <returns></returns>
public void WaitUntilLastRowInTableLoads(IWebElement element)
{
Thread.Sleep(1000);
var rows = new List<IWebElement>(element.FindElements(By.TagName("tr")));
foreach (IWebElement row in rows)
{
var cells = new List<IWebElement>(row.FindElements(By.TagName("td")));
foreach (IWebElement cell in cells)
{
}
}
}
/// <summary>
/// returns row count in table element
/// </summary>
public int GetRowCountInTable(IWebElement element)
{
var rows = new List<IWebElement>(element.FindElements(By.TagName("tr")));
return rows.Count;
}
#endregion
public bool WaitForAttributeToDisplayValue(By by, string attribute, string value)
{
int count = 1;
const int sleep = 100;
const int mod = 1000 / sleep;
while (!GetAttribute(FindElement(by, false), attribute).Contains(value) && count <= GetDefaultTimeOut()*mod)
{
if (Debugger.IsAttached) Console.WriteLine("style display not " + value + ", waiting "+ count + " second(s)");
Thread.Sleep(sleep);
count++;
}
return GetAttribute(FindElement(by, false), attribute).Contains(value);
}
#region Url
/// <summary>
/// navigates browser by url
/// </summary>
public void GoToPage(String url)
{
_driver.Navigate().GoToUrl(url);
//WaitForPageToLoad(url);
}
/// <summary>
/// navigates browser by url, waits x seconds
/// </summary>
public void GoToPageAndWait(String url, int seconds)
{
GoToPage(url);
SetImplicitWaitTimeout(seconds);
}
/// <summary>
/// returns true if url contains url string
/// </summary>
public bool UrlContains(String url)
{
if (_driver.Url.Contains(url)) return true;
else return false;
}
/// <summary>
/// returns browser url
/// </summary>
public string GetUrl()
{
return _driver.Url;
}
#endregion
#region FindElementBy
#region Implicit
public IWebElement FindElementByImplicitWait(By by)
{
return FindElementByImplicitWait(by, DefaultTimeOut);
}
public IWebElement FindElementByImplicitWait(By by, int seconds)
{
IWebElement element = null;
try
{
element = ImplicitWait(by, seconds);
return element;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + " exception while trying to FindElement by " + by);
}
return element;
}
#endregion
#region Explicit
public IWebElement FindElementByExplicitWait(By by)
{
return FindElementByExplicitWait(by, DefaultTimeOut, true);
}
public IWebElement FindElementByExplicitWait(By by, bool throwError)
{
return FindElementByExplicitWait(by, DefaultTimeOut, throwError);
}
public IWebElement FindElementByExplicitWait(By by, int time, bool ignoreException)
{
IWebElement element = null;
try
{
element = WaitUntilElementExists(by, TimeSpan.FromSeconds(time), ignoreException);
}
catch (Exception ex)
{
if (ignoreException) Console.WriteLine(ex.Message + " exception while trying to FindElement by " + by);
}
return element;
}
public IWebElement FindElementByExplicitWaitInMilliseconds(By by, int timeInMilliseconds, bool ignoreException)
{
IWebElement element = null;
try
{
element = WaitUntilElementExists(by, TimeSpan.FromMilliseconds(timeInMilliseconds), ignoreException);
}
catch (Exception ex)
{
if (ignoreException) Console.WriteLine(ex.Message + " exception while trying to FindElement by " + by);
}
return element;
}
#endregion
#region FluentWait
public IWebElement FindElementByFluentWait(By by)
{
return FindElementByFluentWait(by, DefaultTimeOut, 1, 100);
}
public IWebElement FindElementByFluentWait(By by, int waitInSeconds)
{
return FindElementByFluentWait(by, waitInSeconds, 1, 100);
}
public IWebElement FindElementByFluentWait(By by, int waitInSeconds, int timeOutInSeconds, int pollingInMilliseconds)
{
IWebElement element = null;
try
{
element = FluentWait(by, waitInSeconds, timeOutInSeconds, pollingInMilliseconds);
}
catch (Exception )
{
//Console.WriteLine(ex.Message + " exception while trying to FindElement by " + by);
}
return element;
}
#endregion
#region FindElement
public IWebElement FindElement(By by)
{
return FindElement(by, DefaultTimeOut, true);
}
public IWebElement FindElement(By by, bool throwError)
{
return FindElement(by, DefaultTimeOut, throwError);
}
public IWebElement FindElement(By by, int time)
{
return FindElement(by, time, false);
}
/// <summary>
/// find element by and waits for element to display
/// </summary>
public IWebElement FindElement(By by, int time, bool throwError)
{
IWebElement element = null;
SetImplicitWaitTimeout(time);
try
{
element = _driver.FindElement(by);
SetImplicitWaitTimeout(DefaultTimeOut);
}
catch (Exception ex)
{
if (throwError)
{
TakeScreenshotOutputException(ex, "exception while trying to FindElement by " + by.ToString());
throw;
}
}
return element;
}
/// <summary>
/// returns list of elements using by
/// </summary>
public IList<IWebElement> FindElements(By by)
{
try
{
return _driver.FindElements(by);
}
catch (Exception ex)
{
TakeScreenshotOutputException(ex, "exception while trying to FindElements by " + by.ToString());
throw;
}
}
#endregion
#endregion
#region SelectOptionBy
/// <summary>
/// select option by text
/// </summary>
public void SelectOptionByText(IWebElement element, string text)
{
var xselectElement = new SelectElement(element);
try
{
xselectElement.SelectByText(text);
}
catch (Exception ex)
{
TakeScreenshotOutputException(ex, "selecting element by text " + text);
throw;
}
}
/// <summary>
/// select option by index
/// </summary>
public void SelectOptionByIndex(IWebElement element, int index)
{
var xselectElement = new SelectElement(element);
try
{
xselectElement.SelectByIndex(index);
}
catch (Exception ex)
{
TakeScreenshotOutputException(ex, "selecting element by index " + index);
throw;
}
}
/// <summary>
/// select option by value
/// </summary>
public void SelectOptionByValue(IWebElement element, string value)
{
var xselectElement = new SelectElement(element);
try
{
xselectElement.SelectByValue(value);
}
catch (Exception ex)
{
TakeScreenshotOutputException(ex, "selecting element by value " + value);
throw;
}
}
/// <summary>
/// select random option by index
/// </summary>
public void SelectRandomIndex(IWebElement element, int max)
{
var xselectElement = new SelectElement(element);
xselectElement.SelectByIndex(FakeData.RandomNumberInt(1, max));
}
/// <summary>
/// Selects dropdown option by text if the passed string is neither null nor empty
/// </summary>
/// <param name="element"></param>
/// <param name="text"></param>
public void SelectOptionByTextIfStringNotNullOrEmpty(IWebElement element, String text)
{
if (!String.IsNullOrEmpty(text))
SelectOptionByText(element, text);
}
public void SelectOptionByTextIfStringNotNull(IWebElement element, String text)
{
if (text != null)
SelectOptionByText(element, text);
}
#endregion
#region Switch
/// <summary>
/// returns driver switch to
/// </summary>
public ITargetLocator Switch()
{
return _driver.SwitchTo();
}
/// <summary>
/// switches to page by title
/// </summary>
public void SwitchToPopUpByTitle(String title)
{
var windowIterator = _driver.WindowHandles;
foreach (var windowHandle in windowIterator)
{
IWebDriver popup = _driver.SwitchTo().Window(windowHandle);
if (popup.Title == title)
{
break;
}
}
}
/// <summary>
/// switches browser to most recent popup
/// </summary>
public void SwitchToPopUp()
{
String parentWindowHandle = _driver.CurrentWindowHandle;
var windowIterator = _driver.WindowHandles;
foreach (var windowHandle in windowIterator)
{
if (windowHandle != parentWindowHandle)
{
_driver.SwitchTo().Window(windowHandle);
}
}
}
/// <summary>
/// switches to parent browser
/// </summary>
public void SwitchToMainBrowser()
{
//String parentWindowHandle = _driver.CurrentWindowHandle;
var windowIterator = _driver.WindowHandles;
foreach (var windowHandle in windowIterator)
{
//if (windowHandle == parentWindowHandle)
//{
_driver.SwitchTo().Window(windowHandle);
// }
}
}
/// <summary>
/// switches frame
/// </summary>
public void SwitchToFrame(IWebElement element)
{
_driver.SwitchTo().Frame(element);
}
#endregion
#region get text
/// <summary>
/// returns element text
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
public string GetSelectedText(IWebElement element)
{
try
{
return element.Text;
}
catch (Exception ex)
{
TakeScreenshotOutputException(ex, "get selectect text from element ");
throw;
}
}
/// <summary>
/// Select Option text
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
public string GetSelectOptionText(IWebElement element)
{
var xselectElement = new SelectElement(element);
try
{
return xselectElement.SelectedOption.Text.ToString(CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
TakeScreenshotOutputException(ex, "get selected option text from element ");
throw;
}
}
#endregion
#region ImportFile
/// <summary>
/// imports file to file upload dialog box
/// </summary>
/// <param name="file"></param>
public void UploadFile(string file)
{
var environmentDir = new DirectoryInfo(Environment.CurrentDirectory);
var item = "Framework\\bin\\autoit-ie.exe";
if (InternetExplorer()) item = "Framework\\bin\\autoit-ie.exe";
else if (Firefox()) item = "Framework\\bin\\autoit-ff.exe";
else if (Chrome()) item = "Framework\\bin\\autoit-chrome.exe";
var filePath = item.Replace("/", @"\");
var itemPath = new Uri(Path.Combine(environmentDir.Parent.Parent.Parent.FullName, filePath)).LocalPath;
var uploadFile = file.Replace("/", @"\");
var uploadFilePath = new Uri(Path.Combine(environmentDir.Parent.Parent.FullName, uploadFile)).LocalPath;
// Configure open file dialog box
try
{
var process = new Process
{
StartInfo =
{
FileName = itemPath,
Arguments = uploadFilePath,
UseShellExecute = false,
RedirectStandardOutput = true
}
};
process.Start();
process.WaitForExit();
}
catch (IOException )
{ }
}
#endregion
#region highlight
public void HighlightElement(IWebElement element)
{
if (Debugger.IsAttached && AppConfig.DisableElementHighlight!="false")
{
for (int i = 0; i < 2; i++)
{
var js = _driver as IJavaScriptExecutor;
js.ExecuteScript("arguments[0].setAttribute('style', arguments[1]);", element,
"color: red; border: 4px solid red;");
Thread.Sleep(100);
js.ExecuteScript("arguments[0].setAttribute('style', arguments[1]);", element,
"");
}
}
}
#endregion
#region Select2
private readonly By _select2ChoiceClose = By.CssSelector(".select2-choices .select2-search-choice-close");
private readonly By _select2Match = By.CssSelector(".select2-match");
private readonly By _select2Choice = By.CssSelector(".select2-search-choice");
public IWebElement Select2Results()
{
return FindElementByExplicitWait(By.CssSelector("ul.select2-results"));
}
/// <summary>
/// Gets a list of the options in a select2 Multiselect control
/// </summary>
/// <param name="select2MultiSelect"></param>
/// <returns></returns>
public List<string> GetListOfSelect2MultiSelectOptions(IWebElement select2MultiSelect)
{
var optionsList = new List<string>();
Click(select2MultiSelect);
var select2MultiSelectResults = _driver.FindElements(By.CssSelector(".select2-drop.select2-drop-multi.select2-display-none.select2-drop-active .select2-result-label"));
foreach (var select2MultiSelectResult in select2MultiSelectResults)
{
optionsList.Add(select2MultiSelectResult.Text);
}
return optionsList;
}
#endregion
public void Dispose()
{
BrowserQuit();
}
}
}
|
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.Net;
using System.Net.Sockets;
namespace bsClient
{
public partial class Form2 : Form
{
TcpClient client = new TcpClient();
public Form2()
{
InitializeComponent();
}
public void connect()
{
client.Connect("127.0.0.1", 800);
}
public void send()
{
NetworkStream stream = client.GetStream();
string response = textBox1.Text;
byte[] data = System.Text.Encoding.UTF8.GetBytes(response);
stream.Write(data, 0, data.Length);
}
private void Button1_Click(object sender, EventArgs e)
{
connect();
}
private void Button2_Click(object sender, EventArgs e)
{
send();
}
}
}
|
using Contracts.Photos;
using Entity;
using LFP.Common.DataAccess;
using System;
using System.Collections.Generic;
using System.ServiceModel;
namespace Services.Photo
{
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerSession,
AutomaticSessionShutdown = true)]
public class PhotoService : IPhotoService
{
#region Private Fields
private string mConnectionString = String.Empty;
private DataAccess mDataAccess = null;
private string mDepartment = String.Empty;
private string mDirSCC = String.Empty;
private string mUserName = String.Empty;
#endregion
#region Constructors
public PhotoService()
{ }
#endregion
#region Public Methods
public void CreatePhotoMethods(string connectionString, string userName)
{
mConnectionString = connectionString;
mUserName = userName;
mDataAccess = new DataAccess(connectionString, userName);
}
public List<int> GetActorIds(int screenerId)
{
ScreenerActor actor = new ScreenerActor();
try
{
return actor.GetActorIds(mConnectionString, screenerId);
}
finally
{
actor = null;
}
}
public string GetPhotoPath()
{
SystemMediaLocations sml = new SystemMediaLocations();
try
{
return sml.GetPhotoPath(mConnectionString);
}
finally
{
sml = null;
}
}
public List<string> GetPhotos(int actorId)
{
ActorPhoto photo = new ActorPhoto();
try
{
return photo.GetActorPhotos(mConnectionString, actorId);
}
finally
{
photo = null;
}
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OgrenciTakip.Models.Bolumler
{
public class Branch
{
public int BolumId { get; set; }
public string BolumAdi { get; set; }
public string Email { get; set; }
public string Telefon { get; set; }
public string Website { get; set; }
public byte[] BolumResmi { get; set; }
public string AdressLine { get; set; }
public int CityId { get; set; }
public int DistrictId { get; set; }
public string PostCode { get; set; }
public string CreatedBy { get; set; }
}
}
|
using Alabo.Cache;
using Alabo.Runtime;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Alabo.Test.Base.Core.Extensions
{
public static class StartupExtensions
{
public static IServiceCollection AddTestServices(this IServiceCollection services)
{
// Add ZKCloud Services.
// services.AddRuntimeService();
services.AddCacheService();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
return services;
}
public static void AddTestConfigurations(this IConfigurationRoot configuration, IApplicationBuilder app,
IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMvc();
//此处不放出错误,目前版本很难调试
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseStatusCodePages();
}
else
{
app.UseStatusCodePagesWithRedirects("/{0}");
app.UseExceptionHandler("/error");
}
app.UseRuntimeContext();
}
}
} |
using System;
using Microsoft.ApplicationServer.Caching;
namespace Docller.Core.Common
{
public class AzureCache : ICache
{
private readonly DataCache _dataCache;
public AzureCache()
{
_dataCache = new DataCache();
}
#region Implementation of ICache
public object this[string key]
{
get { return _dataCache[key]; }
}
public void AddSlidingExpiration(string key, object value, CacheDurationHours duration)
{
_dataCache.Add(key, value, new TimeSpan(0, (int)duration, 0, 0));
}
public void Remove(string key)
{
_dataCache.Remove(key);
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
namespace Adapter
{
public interface IRtdClient
{
bool GetValue(TimeSpan timeout, out object value, params object[] args);
}
public class RtdClient : IRTDUpdateEvent, IRtdClient
{
readonly Guid ServerId;
int Heartbeat;
static readonly Dictionary<Guid, IRTDServer> servers = new Dictionary<Guid, IRTDServer>();
static readonly Dictionary<Guid, int> topicIds = new Dictionary<Guid, int>();
public RtdClient(Guid serverId, int heartbeat)
{
ServerId = serverId;
Heartbeat = heartbeat;
}
public bool GetValue(TimeSpan timeout, out object value, params object[] args)
{
value = null;
var server = GetRtdServer();
var topicId = GetTopicId();
var sw = Stopwatch.StartNew();
var delay = 100;
try
{
server.ConnectData(topicId, args, true);
while (sw.Elapsed < timeout)
{
Thread.Sleep(delay);
delay *= 2;
var alive = server.Heartbeat();
if (alive != 1)
{
Debug.WriteLine("ERROR!!!!");
return false;
}
var refresh = server.RefreshData(1);
if (refresh.Length > 0)
{
if (refresh[0, 0].ToString() == topicId.ToString())
{
value = refresh[1, 0];
return true;
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
return false;
}
finally
{
server.DisconnectData(topicId);
sw.Stop();
}
return false;
}
public void UpdateNotify()
{
var server = GetRtdServer();
var topicId = GetTopicId();
var refresh = server.RefreshData(1);
if (refresh.Length > 0)
{
for (int i = 0; i < refresh.Length / 2; i++)
{
var id = (int)refresh[0, i];
Debug.WriteLine("update...", i);
//var data = this.topics.Get(id);
//this.queue.Push(new Quote(
// data.Item1,
// data.Item2,
// double.Parse(refresh[1, i].ToString())));
}
}
}
public int HeartbeatInterval
{
get; set;
}
public void Disconnect()
{
//this.queue.Disconnect();
}
IRTDServer GetRtdServer()
{
IRTDServer server;
if (!servers.TryGetValue(ServerId, out server))
{
Type rtd = Type.GetTypeFromCLSID(ServerId);
server = (IRTDServer)Activator.CreateInstance(rtd);
servers[ServerId] = server;
}
return server;
}
int GetTopicId()
{
int topicId = 0;
if (topicIds.TryGetValue(ServerId, out topicId))
{
topicId++;
}
topicIds[ServerId] = topicId;
return topicId;
}
}
} |
using Alabo.Cloud.School.SuccessfulCases.Domains.Entities;
using Alabo.Domains.Repositories;
using MongoDB.Bson;
namespace Alabo.Cloud.School.SuccessfulCases.Domains.Repositories
{
public interface ICasesRepository : IRepository<Cases, ObjectId>
{
}
} |
//==============================================================================
// Copyright (c) 2012-2020 Fiats Inc. All rights reserved.
// https://www.fiats.asia/
//
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Financial.Extensions;
using Financial.Extensions.Trading;
namespace OrderTests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestCreateOrder()
{
var order1a = new MarketPriceOrder<double, double>(TradeSide.Buy, 1.0);
var order1b = new MarketPriceOrder<double, double>(1.0); // buy
var order1c = new MarketPriceOrder<double, double>(-1.0); // sell
var order2a = new LimitPriceOrder<double, double>(TradeSide.Buy, 300000.0, 1.0);
var order2b = new LimitPriceOrder<double, double>(300000.0, 1.0); // buy
var order2c = new LimitPriceOrder<double, double>(300000.0, -1.0); // sell
}
[TestMethod]
public void TestPlaceOrder()
{
var market = new Market<double, double>();
var order = new LimitPriceOrder<double, double>(300000.0, 1.0); // buy
market.PlaceOrder(order);
}
}
}
|
namespace Uintra.Features.Notification.ViewModel
{
public class NotificationListViewModel
{
public string NotificationPageUrl { get; set; }
public NotificationViewModel[] Notifications { get; set; }
}
} |
using System;
using System.Collections.Generic;
using EasyHarmonica.DAL.Entities;
namespace EasyHarmonica.BLL.DTO
{
public class NotificationDTO
{
public int Id { get; set; }
public string Info { get; set; }
public DateTime Date { get; set; }
public virtual ICollection<User> Users { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TableroComando.RangosUserControls;
using Dominio;
namespace TableroComando.Formularios
{
public partial class Form_Meta : Form
{
int posicionX = 100;
int posicionY = 50;
int espacioEntreRangos = 0;
int CantidadRangos = 0;
string codigoLabel;
public Indicador Indicador { get; set; }
public List<Restriccion> _restriccionForms;
public Form_Meta(Indicador indicador)
{
InitializeComponent();
Indicador = indicador;
CargarRestriccionesForms();
}
private void CargarRestriccionesForms()
{
if(Indicador.Restricciones.Count != 0)
{
foreach (Restriccion r in Indicador.Restricciones)
{
switch(r.Tipo)
{
case(TipoRestriccion.Mayor):
AgregarRestriccion(new RestriccionMayorUserControl(this, Indicador.Codigo, r));
break;
case(TipoRestriccion.Menor):
AgregarRestriccion(new RestriccionMenorUserControl(this, Indicador.Codigo, r));
break;
case(TipoRestriccion.Rango):
AgregarRestriccion(new RestriccionRangoUserControl(this, Indicador.Codigo, r));
break;
}
}
}
}
private void Form_Meta_Load(object sender, EventArgs e)
{
Binding binding = DataBindingConverter.BuildBindingDecimalString<Indicador>("Text", Indicador, "ValorEsperado");
ValorEsperadoTxt.DataBindings.Add(binding);
codigoLabel = Indicador.Codigo ?? "Indicador";
MayorBtn.Text = "X < " + codigoLabel;
MenorBtn.Text = codigoLabel + " < X";
RangoBtn.Text = "X < " + codigoLabel + " < Y";
if (Indicador.Restricciones.Count != 0) MenorBtn.Enabled = false;
MayorBtn.Enabled = false;
RangoBtn.Enabled = false;
}
private void MenorBtn_Click(object sender, EventArgs e)
{
MenorBtn.Enabled = false;
RangoBtn.Enabled = true;
AgregarRestriccion(new RestriccionMenorUserControl(this, codigoLabel, Indicador.CrearRestriccion(TipoRestriccion.Menor)));
}
private void RangoBtn_Click(object sender, EventArgs e)
{
CantidadRangos += 1;
if (CantidadRangos == 3) RangoBtn.Enabled = false;
MayorBtn.Enabled = true;
AgregarRestriccion(new RestriccionRangoUserControl(this, codigoLabel, Indicador.CrearRestriccion(TipoRestriccion.Rango)));
}
private void MayorBtn_Click(object sender, EventArgs e)
{
RangoBtn.Enabled = false;
MayorBtn.Enabled = false;
AgregarRestriccion(new RestriccionMayorUserControl(this, codigoLabel, Indicador.CrearRestriccion(TipoRestriccion.Mayor)));
}
private void AgregarRestriccion(UserControl userControl)
{
posicionY += userControl.Height + espacioEntreRangos;
userControl.Location = new Point(posicionX, posicionY);
Controls.Add(userControl);
}
public void EliminarRestriccion(UserControl userControl)
{
posicionY -= userControl.Height - espacioEntreRangos;
Controls.Remove(userControl);
}
private void GuardarBtn_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PADIbookCommonLib
{
[Serializable]
abstract public class Query
{
private DateTime _id;
private List<string> _contactingServerUri;
private List<string> _uris;
private String _name;
public Query() { }
public String Name
{
get { return _name; }
set { _name = value; }
}
public DateTime Id
{
get { return _id; }
set { _id = value; }
}
public List<string> ContactingServerUri
{
get { return _contactingServerUri; }
set { _contactingServerUri = value; }
}
public List<string> Uris
{
get { return _uris; }
set { _uris = value; }
}
public void refreshTimeStamp()
{
_id = DateTime.Now;
}
public Query(List<string> uris, List<string> contactingServerUri,DateTime id)
{
_uris = uris;
_contactingServerUri = contactingServerUri;
_id = id;
_name = "";
}
public Query(String name, List<string> uris, List<string> contactingServerUri,DateTime id)
{
_uris = uris;
_contactingServerUri = contactingServerUri;
_id = id;
_name = name;
}
abstract public bool CompareTo(Query o);
}
}
|
namespace WinAppDriver.WinUserWrapper
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
[SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1201:ElementsMustAppearInTheCorrectOrder", Justification = "Reviewed.")]
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Reviewed.")]
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Reviewed.")]
internal interface IWinUserWrap
{
void mouse_event(int mouseEventFlag, int incrementX, int incrementY, int data, int extraInfo);
void SetCursorPos(int x, int y);
uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);
IntPtr GetMessageExtraInfo();
short VkKeyScan(char ch);
bool SetForegroundWindow(IntPtr hWnd);
}
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Reviewed.")]
[SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1201:ElementsMustAppearInTheCorrectOrder", Justification = "Reviewed.")]
internal static class WinUserConstants
{
public const int INPUT_MOUSE = 0;
public const int INPUT_KEYBOARD = 1;
public const int INPUT_HARDWARE = 2;
}
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1307:AccessibleFieldsMustBeginWithUpperCaseLetter", Justification = "Reviewed.")]
[SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1201:ElementsMustAppearInTheCorrectOrder", Justification = "Reviewed.")]
internal struct INPUT
{
public int type;
public InputUnion u;
}
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1307:AccessibleFieldsMustBeginWithUpperCaseLetter", Justification = "Reviewed.")]
[StructLayout(LayoutKind.Explicit)]
internal struct InputUnion
{
[FieldOffset(0)]
public MOUSEINPUT mi;
[FieldOffset(0)]
public KEYBDINPUT ki;
[FieldOffset(0)]
public HARDWAREINPUT hi;
}
internal enum INPUTTYPE
{
MOUSE = 0,
KEYBOARD = 1,
HARDWARE = 2,
}
[Flags]
internal enum KEYEVENTF : uint
{
KEYDOWN = 0,
EXTENDEDKEY = 0x0001,
KEYUP = 0x0002,
UNICODE = 0x0004,
SCANCODE = 0x0008,
}
[Flags]
internal enum MOUSEEVENTF : uint
{
MOVE = 0x0001,
LEFTDOWN = 0x0002,
LEFTUP = 0x0004,
RIGHTDOWN = 0x0008,
RIGHTUP = 0x0010,
MIDDLEDOWN = 0x0020,
MIDDLEUP = 0x0040,
ABSOLUTE = 0x8000,
}
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Reviewed.")]
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1307:AccessibleFieldsMustBeginWithUpperCaseLetter", Justification = "Reviewed.")]
[StructLayout(LayoutKind.Sequential)]
internal struct MOUSEINPUT
{
public int dx;
public int dy;
public uint mouseData;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Reviewed.")]
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1307:AccessibleFieldsMustBeginWithUpperCaseLetter", Justification = "Reviewed.")]
[StructLayout(LayoutKind.Sequential)]
internal struct KEYBDINPUT
{
public ushort wVk;
public ushort wScan;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Reviewed.")]
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1307:AccessibleFieldsMustBeginWithUpperCaseLetter", Justification = "Reviewed.")]
[StructLayout(LayoutKind.Sequential)]
internal struct HARDWAREINPUT
{
public uint uMsg;
public ushort wParamL;
public ushort wParamH;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FactoryMethod
{
class Resume : Document
{
public override void CreatePages()
{
this.Pages.Add(new SkillPage());
this.Pages.Add(new EducationPage());
this.Pages.Add(new ExperiencePage());
}
}
}
|
using System;
using System.IO;
namespace CourseHunter_69_Constructors
{
public class Program
{
static void Main(string[] args)
{
Character Elf = new Character("Elf");
Console.WriteLine($"{Elf.Race}, {Elf.Armor}");
Character Human = new Character("Human", 15 );
Console.Write(Human.Race);
Console.WriteLine(Human.Armor);
Character Orc = new Character("Orc", 20);
Console.WriteLine($"{Orc.Race}, {Orc.Armor}");
Character Dwarf = new Character("Dwarf", 21, 120);
Console.WriteLine($"{Dwarf.Race}, {Dwarf.Armor}, {Dwarf.Health}");
Console.ReadLine();
Console.WriteLine(new string ('_', 40));
Console.WriteLine($@"{Directory.GetCurrentDirectory()}\");
LocalFileSystemStorage localFileSystemStorage = new LocalFileSystemStorage(1);
Console.WriteLine(localFileSystemStorage.IsFileExistInStorage("1.txt"));
Console.ReadLine();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class TestMyIdeErrors : MonoBehaviour
{
string Tag = "TestMyIdeErrors";
// Update is called once per frame
void Update()
{
}
int a = 1;
int b = 2;
float d = 5;
TextMeshProUGUI TextPro;
// Start is called before the first frame update
void Start()
{
int c = a + b;
Debug.Log("a + b = 3");
Debug.Log(Tag + "- Done ;)");
}
} |
using Sentry.Extensibility;
namespace Sentry.Internal;
internal sealed class ThreadPoolInfo : IJsonSerializable
{
public ThreadPoolInfo(
int minWorkerThreads,
int minCompletionPortThreads,
int maxWorkerThreads,
int maxCompletionPortThreads,
int availableWorkerThreads,
int availableCompletionPortThreads)
{
MinWorkerThreads = minWorkerThreads;
MinCompletionPortThreads = minCompletionPortThreads;
MaxWorkerThreads = maxWorkerThreads;
MaxCompletionPortThreads = maxCompletionPortThreads;
AvailableWorkerThreads = availableWorkerThreads;
AvailableCompletionPortThreads = availableCompletionPortThreads;
}
public int MinWorkerThreads { get; }
public int MinCompletionPortThreads { get; }
public int MaxWorkerThreads { get; }
public int MaxCompletionPortThreads { get; }
public int AvailableWorkerThreads { get; }
public int AvailableCompletionPortThreads { get; }
public void WriteTo(Utf8JsonWriter writer, IDiagnosticLogger? logger)
{
writer.WriteStartObject();
writer.WriteNumber("min_worker_threads", MinWorkerThreads);
writer.WriteNumber("min_completion_port_threads", MinCompletionPortThreads);
writer.WriteNumber("max_worker_threads", MaxWorkerThreads);
writer.WriteNumber("max_completion_port_threads", MaxCompletionPortThreads);
writer.WriteNumber("available_worker_threads", AvailableWorkerThreads);
writer.WriteNumber("available_completion_port_threads", AvailableCompletionPortThreads);
writer.WriteEndObject();
}
}
|
using System;
using System.Linq;
using System.Web.UI.WebControls;
using Sind.BLL;
using Sind.Model;
using Sind.Web.Publico.Code;
using Sind.Web.Publico.Controles;
using Sind.Web.Publico.Helpers;
namespace Sind.Web.Cadastros
{
public partial class DetalheUsuario : System.Web.UI.Page
{
#region [ PROPRIEDADES ]
private AcaoEnum Acao { get { return GetAcao(); } }
#endregion
#region [ EVENTOS ]
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
CarregarPrimeiroAcesso();
}
catch (Exception ex)
{
ExceptionHelper.PresentationErrorTreatment(ex);
}
}
protected void btnSalvar_Click(object sender, EventArgs e)
{
try
{
Salvar();
}
catch (Exception ex)
{
ExceptionHelper.PresentationErrorTreatment(ex);
}
Server.Transfer("ListaUsuario.aspx");
}
protected void btnVoltar_Click(object sender, EventArgs e)
{
Server.Transfer("ListaUsuario.aspx");
}
#endregion
#region [ MÉTODOS ]
private void CarregarPrimeiroAcesso()
{
CarregarComboPerfil();
CarregarComboGrupoVisao();
if (this.Acao == AcaoEnum.Editar)
{
var idUsuario = GetIdUsuario();
Usuario usuario = new ManterUsuario().FindById(idUsuario);
Set(usuario);
}
else
{
chkAtivo.Checked = true;
chkAtivo.Enabled = false;
}
txtUserName.Focus();
}
private void Set(Usuario usuario)
{
txtUserName.Text = usuario.UserName;
ddlPerfil.SelectedIndex = (int)usuario.Perfil;
ddlGrupoVisao.SelectedValue = usuario.GrupoVisao.Id.ToString();
if (usuario.Status)
chkAtivo.Checked = true;
}
private void CarregarComboPerfil()
{
ddlPerfil.Items.Insert(0, new ListItem("Selecione", ""));
ddlPerfil.Items.Insert(1, new ListItem("Gestor Sede", "1"));
ddlPerfil.Items.Insert(2, new ListItem("Gestor Fábrica", "2"));
}
private void CarregarComboGrupoVisao()
{
var listaGrupoVisao = new ManterGrupoVisao().GetAll();
ddlGrupoVisao.DataSource = listaGrupoVisao.OrderBy(l => l.Nome);
ddlGrupoVisao.DataTextField = "Nome";
ddlGrupoVisao.DataValueField = "Id";
ddlGrupoVisao.DataBind();
ddlGrupoVisao.Items.Insert(0, new ListItem("Selecione", ""));
}
private void Salvar()
{
Usuario usuario = Get();
ManterUsuario manterUsuario = new ManterUsuario();
var msgSucesso = "";
if (this.Acao == AcaoEnum.Incluir)
{
manterUsuario.Insert(usuario);
msgSucesso = String.Format("Usuário ({0}) criado com sucesso", usuario.UserName);
}
else if (this.Acao == AcaoEnum.Editar)
{
manterUsuario.Update(usuario);
msgSucesso = String.Format("Usuário ({0}) alterado com sucesso", usuario.UserName);
}
GerenciadorMensagens.IncluirMensagemSucesso(msgSucesso);
}
private int GetIdUsuario()
{
return Request.QueryString["Id"] != null
? Convert.ToInt32(Request.QueryString["Id"])
: 0;
}
private Usuario Get()
{
Usuario usuario = new Usuario();
ManterGrupoVisao manterGrupoVisao = new ManterGrupoVisao();
if (this.Acao == AcaoEnum.Editar)
usuario.Id = GetIdUsuario();
usuario.UserName = txtUserName.Text.Trim();
if (ddlPerfil.SelectedValue.Equals("1"))
usuario.Perfil = PerfilEnum.GestorSede;
else
usuario.Perfil = PerfilEnum.GestorFabrica;
usuario.GrupoVisao = new GrupoVisao();
usuario.GrupoVisao = manterGrupoVisao.FindById(Convert.ToInt32(ddlGrupoVisao.SelectedValue));
if (chkAtivo.Checked)
usuario.Status = true;
else
usuario.Status = false;
return usuario;
}
private AcaoEnum GetAcao()
{
return Request.QueryString["a"] != null
? (AcaoEnum)Convert.ToInt32(Request.QueryString["a"])
: AcaoEnum.Incluir;
}
#endregion
}
} |
using System;
namespace MyfirstClass
{
class Program
{
static void Main()
{
double a,b;
Console.WriteLine("Введите значения a и b");
a=Convert.ToInt32(Console.ReadLine());
b=Convert.ToInt32(Console.ReadLine());
Rectangle Aziz =new Rectangle(a,b);
Aziz.AreaCalculator();
Aziz.PerimetrCalculator();
}
}
class Rectangle
{
public double side1,side2;
public double area { get; set; }
public double perimetr { get; set; }
public Rectangle(double side1,double side2)
{
this.side1=side1;
this.side2=side2;
}
public void AreaCalculator()
{
this.area=this.side1*this.side2;
Console.WriteLine($"Периметр = {this.side1*this.side2}");
}
public void PerimetrCalculator()
{
this.perimetr=2*(this.side1+this.side2);
Console.WriteLine($"Площадь = {2*(this.side1+this.side2)}");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using CreamBell_DMS_WebApps.App_Code;
using Microsoft.Reporting.WebForms;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using Elmah;
namespace CreamBell_DMS_WebApps
{
public partial class frmLoadSheetList : System.Web.UI.Page
{
SqlConnection conn = null;
SqlDataAdapter adp2, adp1;
DataSet ds2 = new DataSet();
DataSet ds1 = new DataSet();
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
public static string ParameterName = string.Empty;
List<byte[]> bytelist = new List<byte[]>();
HashSet<string> h1 = new HashSet<string>();
CreamBell_DMS_WebApps.App_Code.Global obj = new Global();
DataTable dtHeader = null;
DataTable dtLinetest = null;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["USERID"] == null || Session["USERID"].ToString() == string.Empty)
{
Response.Redirect("Login.aspx");
return;
}
if (!Page.IsPostBack)
{
// ContentPlaceHolder myContent = (ContentPlaceHolder)this.Master.FindControl("ContentPage");
// myContent.FindControl("fixedHeaderRow").Visible = false; //this is not working
// ContentPlaceHolder myContent1 = (ContentPlaceHolder)this.Master.FindControl("ContentPage");
// myContent.FindControl("fixedHeaderRow1").Visible = false; //this is not working
GridDetail();
}
}
private void GridDetail()
{
string sitecode1, DataAreaId;
try
{
sitecode1 = Session["SiteCode"].ToString();
CreamBell_DMS_WebApps.App_Code.Global obj = new Global();
conn = obj.GetConnection();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Load_Sheet_List";
cmd.Connection = conn;
cmd.Parameters.AddWithValue("@siteid", sitecode1.ToString());
try
{
GridView1.EmptyDataText = "No Records Found";
GridView1.DataSource = cmd.ExecuteReader() ;
GridView1.DataBind();
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
finally
{
conn.Close();
conn.Dispose();
}
//adp1 = new SqlDataAdapter("Select * from ax.ACXLOADSHEETHEADER where Siteid = '" + sitecode1 + "' "+
//"ORDER BY LOADSHEET_NO desc", conn);
//ds2.Clear();
//adp1.Fill(ds2, "dtl");
//if (ds2.Tables["dtl"].Rows.Count != 0)
//{
// for (int i = 0; i < ds2.Tables["dtl"].Rows.Count; i++)
// {
// GridView1.DataSource = ds2.Tables["dtl"];
// GridView1.DataBind();
// //foreach (GridViewRow grv in GridView1.Rows)
// //{
// // CheckBox chkAll = (CheckBox)grv.Cells[0].FindControl("chklist");
// // chkAll.Checked = true;
// //}
// }
//}
//if (conn.State == ConnectionState.Open)
//{
// conn.Close();
// conn.Dispose();
//}
}
catch(Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
String Indentno = row.Cells[0].Text;
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
/* string sitecode1, DataAreaId;
sitecode1 = Session["SiteCode"].ToString();
ContentPlaceHolder myContent = (ContentPlaceHolder)this.Master.FindControl("ContentPage");
myContent.FindControl("fixedHeaderRow").Visible = true; //this is not working
ContentPlaceHolder myContent1 = (ContentPlaceHolder)this.Master.FindControl("ContentPage");
myContent.FindControl("fixedHeaderRow1").Visible = true; //this is not working
try
{
GridView2.DataSource = null;
GridView2.DataBind();
GridView3.DataSource = null;
GridView3.DataBind();
CreamBell_DMS_WebApps.App_Code.Global obj = new Global();
conn = obj.GetConnection();
GridViewRow gvrow = (GridViewRow)((CheckBox)sender).NamingContainer;
int index = gvrow.RowIndex;
CheckBox chk = sender as CheckBox;
if(chk.Checked==true)
{
adp1 = new SqlDataAdapter("select c.SO_NO,d.customer_code,d.customer_name,d.address1,a.*,b.product_group," +
" b.product_name from ax.ACXLOADSHEETLINE a, ax.ACXProductMaster b,ax.ACXLOADSHEETHEADER c , ax.ACXCUSTMASTER d " +
" where a.loadsheet_no = '" + chk.Text + "' and shiteid = '" + sitecode1 + "' and a.product_code = b.product_code and a.loadsheet_no = c.loadsheet_no " +
" and a.customer_code = d.customer_code ", conn);
}
//adp1.SelectCommand.CommandTimeout = 0;
ds1.Clear();
adp1.Fill(ds1, "dtl");
if (ds1.Tables["dtl"].Rows.Count != 0)
{
for (int i = 0; i < ds1.Tables["dtl"].Rows.Count; i++)
{
GridView2.DataSource = ds1.Tables["dtl"];
GridView2.DataBind();
GridView3.DataSource = ds1.Tables["dtl"];
GridView3.DataBind();
}
}
}
catch
{
}
finally
{
conn.Close();
conn.Dispose();
}*/
}
protected void lnkbtn_Click(object sender, EventArgs e)
{
string sitecode1, DataAreaId;
try
{
sitecode1 = Session["SiteCode"].ToString();
GridView2.DataSource = null;
GridView2.DataBind();
GridView3.DataSource = null;
GridView3.DataBind();
Session["lnk1"] = "";
CreamBell_DMS_WebApps.App_Code.Global obj = new Global();
conn = obj.GetConnection();
GridViewRow gvrow = (GridViewRow)(((LinkButton)sender)).NamingContainer;
LinkButton lnk = sender as LinkButton;
Session["lnk1"] = lnk.Text;
//adp1 = new SqlDataAdapter("select c.SO_NO,d.customer_code,d.customer_name,d.address1,a.*,b.product_group," +
//" b.product_name from ax.ACXLOADSHEETLINE a, ax.inventtable b,ax.ACXLOADSHEETHEADER c , ax.ACXCUSTMASTER d " +
//" where a.loadsheet_no = '" + lnk.Text + "' and shiteid = '" + sitecode1 + "' and a.product_code = b.ITEMID and a.loadsheet_no = c.loadsheet_no " +
//" and a.customer_code = d.customer_code ", conn);
adp1 = new SqlDataAdapter("select c.SO_NO,d.customer_code,d.customer_name,d.address1,a.*,b.product_group,b.product_name " +
" from ax.ACXLOADSHEETLINE a " +
" Inner Join ax.inventtable b on a.product_code = b.ITEMID" +
" Inner Join ax.ACXLOADSHEETHEADER c on c.siteid=a.shiteid and a.loadsheet_no = c.loadsheet_no " +
" Inner JOin ax.ACXCUSTMASTER d on a.customer_code = d.customer_code " +
" where a.loadsheet_no = '" + lnk.Text + "' and shiteid = '" + sitecode1 + "' " +
" ", conn);
//adp1.SelectCommand.CommandTimeout = 0;
ds1.Clear();
adp1.Fill(ds1, "dtl");
if (ds1.Tables["dtl"].Rows.Count != 0)
{
for (int i = 0; i < ds1.Tables["dtl"].Rows.Count; i++)
{
GridView2.DataSource = ds1.Tables["dtl"];
GridView2.DataBind();
GridView3.DataSource = ds1.Tables["dtl"];
GridView3.DataBind();
}
}
}
catch(Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
finally
{
conn.Close();
conn.Dispose();
}
}
protected void btn2_Click(object sender, EventArgs e)
{
GridView3.DataSource = null;
GridView3.DataBind();
string sitecode1, DataAreaId;
sitecode1 = Session["SiteCode"].ToString();
CreamBell_DMS_WebApps.App_Code.Global obj = new Global();
conn = obj.GetConnection();
//if (ddlSearch.Text == "SO Number")
//{
// adp1 = new SqlDataAdapter("select c.SO_NO,d.customer_code,d.customer_name,d.address1,a.*," +
// " b.product_group,b.product_name from ax.ACXLOADSHEETLINE a, ax.inventtable b,ax.ACXLOADSHEETHEADER c , ax.ACXCUSTMASTER d" +
// " where c.SO_NO = '" + txtSerch.Text + "' and shiteid = '" + sitecode1 + "'"+
// " and a.loadsheet_no = '" + Session["lnk1"].ToString() + "' and a.product_code = b.ITEMID and a.loadsheet_no = c.loadsheet_no " +
// " and a.customer_code = d.customer_code", conn);
//}
//else
//{
// adp1 = new SqlDataAdapter("select c.SO_NO,d.customer_code,d.customer_name,d.address1,a.*," +
// " b.product_group,b.product_name from ax.ACXLOADSHEETLINE a, ax.inventtable b,ax.ACXLOADSHEETHEADER c , ax.ACXCUSTMASTER d " +
// " where c.Customer_Code like '%" + txtSerch.Text + "%' and shiteid = '" + sitecode1 + "'"+
// "and a.loadsheet_no = '" + Session["lnk1"].ToString() + "' and a.product_code = b.ITEMID and a.loadsheet_no = c.loadsheet_no " +
// " and a.customer_code = d.customer_code", conn);
//}
string query = string.Empty;
if (txtSerch.Text !=string.Empty)
{
query = "select LoadSheet_No,LoadSheet_Date,Value from ax.ACXLOADSHEETHEADER where siteid = '" + sitecode1 + "' and LOADSHEET_DATE between '" + txtSerch.Text + "' and dateadd(dd,1,'" + txtSerch.Text + "')";
}
else
{
query = "select LoadSheet_No,LoadSheet_Date,Value from ax.ACXLOADSHEETHEADER where siteid = '" + sitecode1 + "' ";
}
//ds2.Clear();
//adp1.Fill(ds2, "dtl");
DataTable dt = new DataTable();
dt = obj.GetData(query);
if (dt.Rows.Count>= 0)
{
GridView1.DataSource =dt;
GridView1.DataBind();
foreach (GridViewRow grv in GridView1.Rows)
{
CheckBox chkAll = (CheckBox)grv.Cells[0].FindControl("chklist");
if (txtSerch.Text != string.Empty)
{
chkAll.Checked = true;
}
else
{
chkAll.Checked = false;
}
}
}
else
{
this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Record not found!');", true);
}
if (conn.State == ConnectionState.Open)
{
conn.Close();
conn.Dispose();
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridDetail();
GridView2.Visible = false;
GridView3.Visible = false;
}
protected void GridView2_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
// GridView2.PageIndex = e.NewPageIndex;
}
protected void GridView3_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//GridView3.PageIndex = e.NewPageIndex;
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
String LoadSheetNo = string.Empty;
String strRetVal2 = "LoadSheet";
LinkButton LnkBtnLSNo;
HyperLink HL;
HL = new HyperLink();
int i = e.Row.RowIndex;
string SaleInvoice = e.Row.Cells[0].Text;
LnkBtnLSNo = (LinkButton)e.Row.FindControl("lnkbtn");
LoadSheetNo = LnkBtnLSNo.Text;
HL = (HyperLink)e.Row.FindControl("HPLinkPrint");
HL.NavigateUrl = "#";
HL.Font.Bold = true;
HL.Attributes.Add("onclick", "window.open('frmReport.aspx?LaodSheetNo=" + LoadSheetNo + "&Type=" + strRetVal2 + "','_newtab');");
}
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void checkAll_CheckedChanged(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
string multipleparameter = string.Empty;
int count = 0;
foreach (GridViewRow grv in GridView1.Rows)
{
CheckBox chklist1 = (CheckBox)grv.Cells[0].FindControl("chklist");
LinkButton lnkBtn = (LinkButton)grv.Cells[0].FindControl("lnkbtn");
if (chklist1.Checked)
{
count += 1;
// ShowReportSaleInvoice(string.Empty, chklist1.Text);
if (multipleparameter == string.Empty)
{
multipleparameter = "'" + lnkBtn.Text + "'";
}
else
{
multipleparameter += ",'" + lnkBtn.Text + "'";
}
}
}
if (count==0)
{
return;
}
string listLoadsheet = "select * from ax.ACXLOADSHEETHEADER where SITEID = '" + Session["SiteCode"].ToString() + "' and LOADSHEET_NO in (" + multipleparameter + ") order by LOADSHEET_NO";
DataTable dtMainHeader1 = new DataTable();
dtMainHeader1 = obj.GetData(listLoadsheet);
for (int i = 0; i < dtMainHeader1.Rows.Count; i++)
{
//==============================
string queryHeader = "select LSH.LOADSHEET_NO, CONVERT(varchar(15),LSH.LOADSHEET_DATE,105) AS LOADSHEET_DATE , " +
" ( SH.CUSTOMER_CODE +'-' + CUS.CUSTOMER_NAME) as CUSTOMER, SH.SO_NO, CONVERT( varchar(15), SH.SO_DATE,105) AS SO_DATE , " +
" cast(round(SH.SO_VALUE,2) as numeric(36,2)) as SO_VALUE, SH.SITEID, USM.User_Name,USM.State from ax.ACXLOADSHEETHEADER LSH " +
" INNER JOIN ax.ACXSALESHEADER SH ON LSH.LOADSHEET_NO = SH.LoadSheet_No and LSH.SITEID= SH.SITEID " +
" INNER JOIN AX.ACXCUSTMASTER CUS ON SH.CUSTOMER_CODE = CUS.CUSTOMER_CODE "+// exclude on 4th Apr 2017 and cus.Site_Code = LSH.SITEID" +
" INNER JOIN AX.ACXUSERMASTER USM ON LSH.SITEID= USM.Site_Code " +
" where LSH.SITEID = '" + Session["SiteCode"].ToString() + "' and LSH.LOADSHEET_NO='" + dtMainHeader1.Rows[i]["LOADSHEET_NO"].ToString() + "' order by LSH.LOADSHEET_NO";
dtHeader = obj.GetData(queryHeader);
string queryLine = " Select ROW_NUMBER() over (ORDER BY LOADSHEET_NO,LSH.PRODUCT_CODE) AS SRNO,LOADSHEET_NO,( LSH.PRODUCT_CODE + '-'+ PM.PRODUCT_NAME) AS PRODUCT, "
+ " LSH.BOXQTY as BOX,LSH.PCSQTY as PCS,isnull(LSH.BOXPCS,0) as TotalBoxPCS,LSH.BOX as TotalQtyConv,LSH.LTR, LSH.STOCKQTY_BOX,LSH.STOCKQTY_LTR from ax.ACXLOADSHEETLINE LSH " +
" Inner Join ax.inventtable PM on LSH.PRODUCT_CODE = PM.ITEMID " +
" where SHITEID = '" + Session["SiteCode"].ToString() + "' and LOADSHEET_NO='" + dtMainHeader1.Rows[i]["LOADSHEET_NO"].ToString() + "'";
dtLinetest = obj.GetData(queryLine);
ShowReportLoadSheet(dtHeader, dtLinetest);
}
murgebytges();
}
public void murgebytges()
{
int size = 0;
for (int i = 0; i < bytelist.Count; i++)
{
if (bytelist.Count == 1)
{
size += bytelist[i].Length + 1;
}
else
{
size += bytelist[i].Length;
}
}
//byte[] newArray = new byte[size];
byte[] newArray = concatAndAddContent(bytelist);
try
{
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=Image.pdf");
Response.ContentType = "application/pdf";
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(newArray);
Response.End();
//Response.Flush();
// }
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
string str = ex.Message;
}
}
public static byte[] concatAndAddContent(List<byte[]> pdf)
{
byte[] all;
using (MemoryStream ms = new MemoryStream())
{
Document doc = new Document();
PdfWriter writer = PdfWriter.GetInstance(doc, ms);
doc.SetPageSize(PageSize.LETTER);
doc.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
PdfReader reader;
foreach (byte[] p in pdf)
{
reader = new PdfReader(p);
int pages = reader.NumberOfPages;
// loop over document pages
for (int i = 1; i <= pages; i++)
{
doc.SetPageSize(PageSize.LETTER);
doc.NewPage();
page = writer.GetImportedPage(reader, i);
cb.AddTemplate(page, 0, 0);
}
}
doc.Close();
all = ms.GetBuffer();
ms.Flush();
ms.Dispose();
}
return all;
}
private void ShowReportLoadSheet(DataTable dtHeader, DataTable dtLinetest)
{
try
{
DataTable dtLine = new DataTable();
CreamBell_DMS_WebApps.App_Code.AmountToWords obj1 = new AmountToWords();
DataTable dtAmountWords = null;
dtLine = dtLinetest;
string query = "Select VALUE from ax.ACXLOADSHEETHEADER where LOADSHEET_NO='" + dtLinetest.Rows[0]["LOADSHEET_NO"].ToString() + "' and SITEID='" + Session["SiteCode"].ToString() + "'";
DataTable dt = obj.GetData(query);
decimal amount = Math.Round(Convert.ToDecimal(dt.Rows[0]["VALUE"].ToString()));
string Words = obj1.words(Convert.ToInt32(amount));
string queryAmountWords = "Select VALUE, '" + Words + "' as AMNTWORDS from ax.ACXLOADSHEETHEADER where LOADSHEET_NO='" + dtLinetest.Rows[0]["LOADSHEET_NO"].ToString() + "' and SITEID='" + Session["SiteCode"].ToString() + "'";
dtAmountWords = obj.GetData(queryAmountWords);
ReportViewer1.ProcessingMode = ProcessingMode.Local;
ReportViewer1.AsyncRendering = true;
ReportDataSource RDS1 = new ReportDataSource("DSetHeader", dtHeader);
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(RDS1);
ReportDataSource RDS2 = new ReportDataSource("DSetLine", dtLine);
ReportViewer1.LocalReport.DataSources.Add(RDS2);
ReportDataSource RDS3 = new ReportDataSource("DSetAmountWords", dtAmountWords);
ReportViewer1.LocalReport.DataSources.Add(RDS3);
ReportViewer1.LocalReport.ReportPath = Server.MapPath("Reports\\LoadSheet.rdl");
ReportViewer1.ShowPrintButton = true;
ReportViewer1.LocalReport.DisplayName = dtLinetest.Rows[0]["LOADSHEET_NO"].ToString();
#region generate PDF of ReportViewer
string savePath = Server.MapPath("Downloads\\" + "LoaSheet" + ".pdf");
byte[] Bytes = ReportViewer1.LocalReport.Render(format: "PDF", deviceInfo: "");
Warning[] warnings;
string[] streamIds;
string mimeType = string.Empty;
string encoding = string.Empty;
string extension = string.Empty;
byte[] bytes = ReportViewer1.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
bytelist.Add(bytes);
#endregion
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using SFA.DAS.CommitmentsV2.Api.Client;
using SFA.DAS.CommitmentsV2.Types;
using SFA.DAS.ProviderCommitments.Extensions;
namespace SFA.DAS.ProviderCommitments.Queries.GetTrainingCourses
{
public sealed class GetTrainingCoursesQueryHandler : IRequestHandler<GetTrainingCoursesQueryRequest, GetTrainingCoursesQueryResponse>
{
private readonly ICommitmentsApiClient _commitmentsApiClient;
public GetTrainingCoursesQueryHandler(ICommitmentsApiClient commitmentsApiClient)
{
_commitmentsApiClient = commitmentsApiClient;
}
public async Task<GetTrainingCoursesQueryResponse> Handle(GetTrainingCoursesQueryRequest message, CancellationToken cancellationToken)
{
var courses = await GetAllRequiredCourses(message.IncludeFrameworks, cancellationToken);
if (message.EffectiveDate.HasValue)
{
courses = courses.Where(x => x.IsActiveOn(message.EffectiveDate.Value));
}
var result = new GetTrainingCoursesQueryResponse
{
TrainingCourses = courses.OrderBy(m => m.Name).ToArray()
};
return result;
}
private Task<IEnumerable<TrainingProgramme>> GetAllRequiredCourses(bool getFramework, CancellationToken cancellationToken)
{
var tasks = new List<Task<IEnumerable<TrainingProgramme>>>
{
getFramework ? GetAll(cancellationToken) : GetStandards(cancellationToken)
};
return Task.WhenAll(tasks)
.ContinueWith(allTasks => allTasks.Result.SelectMany(task => task), cancellationToken);
}
private async Task<IEnumerable<TrainingProgramme>> GetStandards(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
throw new OperationCanceledException();
}
var response = await _commitmentsApiClient.GetAllTrainingProgrammeStandards(cancellationToken);
return response.TrainingProgrammes;
}
private async Task<IEnumerable<TrainingProgramme>> GetAll(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
throw new OperationCanceledException();
}
var response = await _commitmentsApiClient.GetAllTrainingProgrammes(cancellationToken);
return response.TrainingProgrammes;
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KartObjects;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraEditors;
using KartLib;
namespace KartSystem
{
public partial class GoodGroupEditor : XBaseDictionaryEditor
{
public GoodGroupEditor(GoodGroup _entity)
//: base(_entity, presenter)
{
InitializeComponent();
_editableGroup = _entity;
List<GoodGroup> GoodGroupTree = Loader.DbLoad<GoodGroup>("treepath like '%" + _editableGroup.TreePath + "%'") ?? new List<GoodGroup>();
ctlParentGroup.DataSource = KartDataDictionary.sGoodGroups.Where(q => !(GoodGroupTree.Any(q2 => q2.Id == q.Id)));
InitView();
}
public GoodGroup _editableGroup;
public override void InitView()
{
base.InitView();
tbGroupName.Text = _editableGroup.Name;
if (_editableGroup.IdParentGroup.HasValue)
ctlParentGroup.SelectedItemId = _editableGroup.IdParentGroup;
string query = "select count(*) from(select distinct c.denysaletimebegin from v_goods c join v_goodgroups g on g.treepath like '%"
+ _editableGroup.Id + "%' and c.idgoodgroup = g.id group by c.denysaletimebegin)";
int Count = (int)Loader.DataContext.ExecuteScalar(query);
if (Count == 1)
{
query = "select first 1 c.denysaletimebegin from v_goods c join v_goodgroups g on g.treepath like '%"
+ _editableGroup.Id + "%' and c.idgoodgroup = g.id group by c.denysaletimebegin";
teSaleTimeBegin.EditValue = Loader.DataContext.ExecuteScalar(query);
}
query = "select count(*) from(select distinct c.denysaletimeend from v_goods c join v_goodgroups g on g.treepath like '%"
+ _editableGroup.Id + "%' and c.idgoodgroup = g.id group by c.denysaletimeend)";
Count = (int)Loader.DataContext.ExecuteScalar(query);
if (Count == 1)
{
query = "select first 1 c.denysaletimeend from v_goods c join v_goodgroups g on g.treepath like '%"
+ _editableGroup.Id + "%' and c.idgoodgroup = g.id group by c.denysaletimeend";
teSaleTimeEnd.EditValue = Loader.DataContext.ExecuteScalar(query);
}
}
protected override bool CheckForValidation()
{
bool result = true;
if (string.IsNullOrWhiteSpace(tbGroupName.Text) || tbGroupName.Text == "")
{
NotValidDataMessage = "Не задано наименование группы";
return result = false;
}
if (ctlParentGroup.SelectedItemId == null)
{
NotValidDataMessage = "Не задана родительская группа";
return result = false;
}
return result;
}
protected override void SaveData()
{
_editableGroup.Name = tbGroupName.Text;
GoodGroup parentGG = ctlParentGroup.SelectedItem as GoodGroup;
if (parentGG != null)
_editableGroup.IdParentGroup = parentGG.Id;
else _editableGroup.IdParentGroup = null;
Saver.SaveToDb<GoodGroup>(_editableGroup);
string Begin = " null ";
string End = " null";
if (teSaleTimeBegin.EditValue != null)
if (teSaleTimeBegin.EditValue!=Convert.DBNull)
Begin = "'" + teSaleTimeBegin.EditValue.ToString() + "'";
if (teSaleTimeEnd.EditValue != null)
if (teSaleTimeEnd.EditValue!=Convert.DBNull)
End = "'" + teSaleTimeEnd.EditValue.ToString() + "'";
Loader.DataContext.ExecuteNonQuery("execute procedure SP_UPDATE_GOODSTIME(" + Begin + ", " + End + ", " + _editableGroup.Id + ", " + Convert.ToInt32(ceCheck.Checked) + ")");
GC.Collect();
}
}
} |
using System;
using System.IO;
using System.IO.Pipes;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
namespace GrabDriver
{
class Program
{
static void Main(string[] args)
{
Regex stepAcceptRegex = new Regex(@"^\[\d\d Task info \d+]$");
FilePipe pipeServerr = new FilePipe();
pipeServerr.Open("..\\..\\..\\GRAB.181107.163454");
string s = pipeServerr.Read();
while (s != null)
{
if(pipeServerr.Write(s) == false)
{
break;
}
if (stepAcceptRegex.IsMatch(s) == true)
{
Console.WriteLine("Data sent, waiting a second");
Thread.Sleep(1000);
}
s = pipeServerr.Read();
}
pipeServerr.Close();
}
}
}
|
using System.Collections.Generic;
namespace ReactMusicStore.Core.Domain.Entities.EqualityCompare
{
public class ArtistComparer : IEqualityComparer<Artist>
{
// Objects are equal if their unique data are equal.
public bool Equals(Artist x, Artist y)
{
//Check whether the compared objects reference the same data.
if (ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (ReferenceEquals(x, null) || ReferenceEquals(y, null))
return false;
//Check whether the objects' properties are equal.
return x.Name == y.Name;
}
// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.
public int GetHashCode(Artist artist)
{
//Check whether the object is null
if (ReferenceEquals(artist, null)) return 0;
//Get hash code for the field.
var hashArtistName = artist.Name.GetHashCode();
//Calculate the hash code for the object.
return hashArtistName;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using Grasshopper.Kernel;
using Rhino.Geometry;
using PterodactylCharts;
using System.Windows.Forms;
using ShapeDiver.Public.Grasshopper.Parameters.SDMLDoc;
using PterodactylEngine;
using ShapeDiver.Public.Grasshopper.Parameters;
namespace Pterodactyl
{
public class BarChartGH : GH_Component
{
public BarChartGH()
: base("Bar Chart", "Bar Chart",
"Create bar chart, if you want to generate Report Part - set Path",
"Pterodactyl", "Basic Graphs")
{
}
protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager)
{
//pManager.AddBooleanParameter("Show Graph", "Show Graph", "True = show graph, False = hide", GH_ParamAccess.item, false);
pManager.AddTextParameter("Title", "Title", "Title of your chart", GH_ParamAccess.item, "Wingspan comparison (size matters)");
pManager.AddNumberParameter("Values", "Values", "Values for each bar as list",
GH_ParamAccess.list, new List<double> { 0.68, 0.81, 1.00, 1.20, 1.60, 6.00 });
pManager.AddTextParameter("Bar Names", "Bar Names", "Sets bar names as list", GH_ParamAccess.list,
new List<string> {"Pigeon","Duck", "Crow", "Owl", "Peacock", "Pterodactyl"});
pManager.AddTextParameter("Text Format", "Text Format", "Set text format", GH_ParamAccess.item, "{0:0.00[m]}");
pManager.AddColourParameter("Colors", "Colors", "Sets data colors, each color for each bar", GH_ParamAccess.list,
new List<Color>
{
Color.FromArgb(255, 110, 110),
Color.FromArgb(7,173,148),
Color.FromArgb(153,255,0),
Color.FromArgb(255,119,0),
Color.FromArgb(168,45,160),
Color.FromArgb(115,115,115)
});
}
protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager)
{
pManager.AddParameter(new PterodactylGrasshopperBitmapParam(), "Report Part", "Report Part", "Created part of the report (Markdown text with referenced Image)", GH_ParamAccess.item);
}
public override bool IsBakeCapable => false;
protected override void SolveInstance(IGH_DataAccess DA)
{
string title = "";
List<double> values = new List<double>();
List<string> names = new List<string>();
string textFormat = "";
List<Color> colors = new List<Color>();
DA.GetData(0, ref title);
DA.GetDataList(1, values);
DA.GetDataList(2, names);
DA.GetData(3, ref textFormat);
DA.GetDataList(4, colors);
BarChart chartObject = new BarChart();
dialogImage = chartObject;
PterodactylGrasshopperBitmapGoo GH_bmp = new PterodactylGrasshopperBitmapGoo();
chartObject.BarChartData(true, title, values, names, textFormat, colors, GH_bmp.ReferenceTag);
using (Bitmap b = chartObject.ExportBitmap())
{
GH_bmp.Value = b.Clone(new Rectangle(0, 0, b.Width, b.Height), b.PixelFormat);
GH_bmp.ReportPart = chartObject.Create();
DA.SetData(0, GH_bmp);
}
}
private BarChart dialogImage;
public override void AppendAdditionalMenuItems(ToolStripDropDown menu)
{
base.AppendAdditionalMenuItems(menu);
Menu_AppendItem(menu, "Show Chart", ShowChart, this.Icon, (dialogImage != null), false);
}
private void ShowChart(object sender, EventArgs e)
{
if (dialogImage != null) dialogImage.ShowDialog();
}
protected override System.Drawing.Bitmap Icon
{
get
{
return Properties.Resources.PterodactylBarChart;
}
}
public override Guid ComponentGuid
{
get { return new Guid("eecd2d5e-918e-42ee-b7ab-aee8b49b3ecd"); }
}
}
} |
using Newtonsoft.Json;
namespace Mega_Desk
{
public class DeskQuote
{
public Customer customer;
[JsonProperty]
int productionDays;
[JsonProperty]
Desk desk;
public void setDesk(double width, double depth, string material, int numDrawers)
{
desk = new Desk(width, depth, material, numDrawers);
}
public Desk getDesk()
{
return desk;
}
public void setCustomer(string first, string last)
{
customer.firstName = first;
customer.lastName = last;
}
public string getCustomer()
{
return customer.lastName + ", " + customer.firstName;
}
public void setOrderDays(int d)
{
productionDays = d;
}
public int getProductionDays()
{
return productionDays;
}
public double getQuote()
{
double quote = Constants.baseDeskPrice;
double deskSurfaceArea = desk.getSurfaceArea();
if (deskSurfaceArea > Constants.mediumSizeLower)
quote += deskSurfaceArea * Constants.costPerSquareInch;
quote += Constants.costPerDrawer * desk.getNumOfDrawers();
quote += Constants.materialCost[desk.getMaterial()];
if (productionDays < Constants.standardProduction)
{
quote += getRushOrder(deskSurfaceArea);
}
return quote;
}
public double getRushOrder(double deskSurfaceArea)
{
double rushCost;
try
{
int rushIndex = Constants.rushOrderOptions.IndexOf(productionDays);
int sizeIndex;
if (deskSurfaceArea > Constants.mediumSizeUpper)
sizeIndex = 2;
else if (deskSurfaceArea <= Constants.mediumSizeUpper
&& deskSurfaceArea >= Constants.mediumSizeLower)
sizeIndex = 1;
else
sizeIndex = 0;
rushCost = Constants.rushOrderPrices[rushIndex, sizeIndex];
}
catch
{
return 0;
}
return rushCost;
}
}
public struct Customer
{
public string firstName;
public string lastName;
public Customer(string first, string last)
{
firstName = first;
lastName = last;
}
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectBueno.Engine
{
public abstract class MenuHandler : IHandler
{
protected Texture2D background;
public float downscale { get; protected set; }
protected Matrix screenScale;
public abstract void Draw();
public abstract void Update();
public virtual void WindowResize()
{
screenScale = Matrix.CreateScale((float)Main.Viewport.Width / Main.xRatio);
downscale = (float)Main.xRatio / Main.Viewport.Width;
}
public virtual void Initialize()
{
}
public virtual void Deinitialize()
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
namespace MyWebServer.Models
{
public class CookieCollection: IEnumerable<Cookie>
{
public Dictionary<string,Cookie> Cookies { get; set; }
public int Count { get { return this.Cookies.Count; } }
public Cookie this[string cookieName]
{
get { return this.Cookies[cookieName]; }
set
{
if (this.Cookies.ContainsKey(cookieName))
{
this.Cookies[cookieName] = value;
}
else
{
this.Cookies.Add(cookieName,new Cookie(cookieName,null));
}
}
}
public CookieCollection()
{
this.Cookies = new Dictionary<string, Cookie>();
}
public bool Contains(string cookie)
{
return this.Cookies.ContainsKey(cookie);
}
public void Add(Cookie cookie)
{
this.Cookies.Add(cookie.Name,cookie);
}
public IEnumerator<Cookie> GetEnumerator()
{
return this.Cookies.Values.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public override string ToString()
{
return string.Join("; ", this.Cookies.Values);
}
}
} |
using System;
using System.Collections.Generic;
using Substrate.Nbt;
using System.IO;
using Substrate.Core;
namespace Substrate.Data
{
public class BetaDataManager : DataManager, INbtObject<BetaDataManager>
{
private static SchemaNodeCompound _schema = new SchemaNodeCompound()
{
new SchemaNodeScaler("map", TagType.TAG_SHORT),
};
private TagNodeCompound _source;
private NbtWorld _world;
private short _mapId;
private MapManager _maps;
public BetaDataManager (NbtWorld world)
{
_world = world;
_maps = new MapManager(_world);
}
public override int CurrentMapId
{
get { return _mapId; }
set { _mapId = (short)value; }
}
public new MapManager Maps
{
get { return _maps; }
}
protected override IMapManager GetMapManager ()
{
return _maps;
}
public override bool Save ()
{
if (_world == null) {
return false;
}
try {
string path = Path.Combine(_world.Path, _world.DataDirectory);
NBTFile nf = new NBTFile(Path.Combine(path, "idcounts.dat"));
Stream zipstr = nf.GetDataOutputStream(CompressionType.None);
if (zipstr == null) {
NbtIOException nex = new NbtIOException("Failed to initialize uncompressed NBT stream for output");
nex.Data["DataManager"] = this;
throw nex;
}
new NbtTree(BuildTree() as TagNodeCompound).WriteTo(zipstr);
zipstr.Close();
return true;
}
catch (Exception ex) {
Exception lex = new Exception("Could not save idcounts.dat file.", ex);
lex.Data["DataManager"] = this;
throw lex;
}
}
#region INBTObject<DataManager>
public virtual BetaDataManager LoadTree (TagNode tree)
{
TagNodeCompound ctree = tree as TagNodeCompound;
if (ctree == null) {
return null;
}
_mapId = ctree["map"].ToTagShort();
_source = ctree.Copy() as TagNodeCompound;
return this;
}
public virtual BetaDataManager LoadTreeSafe (TagNode tree)
{
if (!ValidateTree(tree)) {
return null;
}
return LoadTree(tree);
}
public virtual TagNode BuildTree ()
{
TagNodeCompound tree = new TagNodeCompound();
tree["map"] = new TagNodeLong(_mapId);
if (_source != null) {
tree.MergeFrom(_source);
}
return tree;
}
public virtual bool ValidateTree (TagNode tree)
{
return new NbtVerifier(tree, _schema).Verify();
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class CameraPoint : MonoBehaviour
{
[SerializeField]
private float
_departSpeed,
_arriveSpeed;
public float DepartSpeed
{
get { return _departSpeed; }
}
public float ArriveSpeed
{
get { return _arriveSpeed; }
}
private void Update()
{
if (Application.isPlaying)
return;
CameraMovement movement = ServiceLocator.Locate<CameraMovement>();
if (movement == null || !movement.transform.hasChanged)
return;
if (movement.CurrentPoint == this)
{
movement.transform.position = transform.position;
movement.transform.rotation = transform.rotation;
}
}
}
|
using Tomelt.ContentManagement.Handlers;
using Tomelt.Core.Navigation.Models;
namespace Tomelt.Core.Navigation.Handlers {
public class MenuWidgetPartHandler : ContentHandler {
public MenuWidgetPartHandler() {
OnInitializing<MenuWidgetPart>((context, part) => { part.StartLevel = 1; });
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GlobalGameDataAccessor : MonoBehaviour
{
public void SetGlobalSeed(int seed)
{
GlobalGameData.instance.SetGlobalSeed(seed);
}
}
|
using Alabo.Dependency;
using Alabo.Extensions;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace Alabo.Helpers {
/// <summary>
/// 容器
/// </summary>
public static class Ioc {
/// <summary>
/// 默认容器
/// </summary>
internal static readonly Container DefaultContainer = new Container();
/// <summary>
/// 创建容器
/// </summary>
/// <param name="configs">依赖配置</param>
public static IContainer CreateContainer(params IConfig[] configs) {
var container = new Container();
container.Register(null, builder => builder.EnableAop(), configs);
return container;
}
/// <summary>
/// 创建集合
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="name">服务名称</param>
public static List<T> ResolveAll<T>(string name = null) {
return DefaultContainer.CreateList<T>(name);
}
/// <summary>
/// 创建集合
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="type">对象类型</param>
/// <param name="name">服务名称</param>
public static List<T> ResolveAll<T>(Type type, string name = null) {
return ((IEnumerable<T>)DefaultContainer.CreateList(type, name)).ToList();
}
/// <summary>
/// 创建实例
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="name">服务名称</param>
public static T Resolve<T>(string name = null) {
var scope = GetScope(CurrentScope);
if (scope != null) {
return scope.Resolve<T>();
}
return DefaultContainer.Create<T>(name);
}
/// <summary>
/// 创建实例
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="type">对象类型</param>
/// <param name="name">服务名称</param>
public static T Resolve<T>(Type type, string name = null) {
return (T)DefaultContainer.Create(type, name);
}
/// <summary>
/// 创建实例
/// </summary>
/// <param name="type">创建实例需为接口</param>
public static object ResolveType(Type type) {
return DefaultContainer.Create(type);
}
/// <summary>
/// 创建实例
/// </summary>
/// <param name="fullName">命名空间</param>
public static object Resolve(string fullName) {
var type = fullName.GetTypeByName();
if (type != null) {
return ResolveType(type);
}
return null;
}
/// <summary>
/// 作用域开始
/// </summary>
public static IScope BeginScope() {
var scope = DefaultContainer.BeginScope();
AddScope(scope.GetHashCode(), scope);
return scope;
}
/// <summary>
/// 注册依赖
/// </summary>
/// <param name="configs">依赖配置</param>
public static void Register(params IConfig[] configs) {
DefaultContainer.Register(null, builder => builder.EnableAop(), configs);
}
/// <summary>
/// 注册依赖
/// </summary>
/// <param name="services">服务集合</param>
/// <param name="configs">依赖配置</param>
public static IServiceProvider Register(IServiceCollection services, params IConfig[] configs) {
return DefaultContainer.Register(services, builder => builder.EnableAop(), configs);
}
/// <summary>
/// 释放容器
/// </summary>
public static void Dispose() {
DefaultContainer.Dispose();
}
#region scope
[ThreadStatic] public static int CurrentScope;
/// <summary>
/// Tenants
/// </summary>
private static readonly ConcurrentDictionary<int, IScope> _scopeDictionaries =
new ConcurrentDictionary<int, IScope>();
/// <summary>
/// Add scope
/// </summary>
/// <param name="hashCode"></param>
/// <param name="scope"></param>
public static void AddScope(int hashCode, IScope scope) {
if (!_scopeDictionaries.ContainsKey(hashCode)) {
_scopeDictionaries.TryAdd(hashCode, scope);
}
}
/// <summary>
/// Get scope
/// </summary>
/// <param name="hashCode"></param>
/// <returns></returns>
private static IScope GetScope(int hashCode) {
if (_scopeDictionaries.ContainsKey(hashCode)) {
return _scopeDictionaries[hashCode];
}
return null;
}
/// <summary>
/// Remove scope
/// </summary>
/// <param name="hashCode"></param>
/// <returns></returns>
public static IScope RemoveScope(int hashCode) {
_scopeDictionaries.TryRemove(hashCode, out var scope);
return scope;
}
#endregion scope
}
} |
namespace _12_Self_Generic
{
public class Bacallies<T, TT> : Product<T, TT>
{
public Bacallies(string name, T volume, TT energy) : base(name, volume, energy)
{
}
}
}
|
namespace DChild.Gameplay.Player
{
public interface IPlayerSkill
{
void EnableSkill(bool value);
bool isEnabled { get; }
}
} |
// <copyright file="SecondTask.cs" company="MyCompany.com">
// Contains the solutions to tasks of the 'Creating types in C#' module.
// </copyright>
// <author>Daryn Akhmetov</author>
namespace Creating_types_in_CSharp
{
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Contains implementation of the given by the task algorithm.
/// </summary>
public class SecondTask
{
/// <summary>
/// A class that implements a specific strategy must inherit this interface.
/// Context class uses this interface to call a specific strategy.
/// </summary>
public interface IStrategy
{
/// <summary>
/// Sorts rows of an array.
/// </summary>
/// <param name="array">Array to be sorted.</param>
/// <returns>Sorted array.</returns>
int[][] SortArrayRows(int[][] array);
}
/// <summary>
/// Sorts rows of an array in the given order using the given rows comparison criteria.
/// </summary>
/// <param name="array">Array to be sorted.</param>
/// <param name="comparisonCriteria">Method that is called for two compared rows to get the comparison criteria.</param>
/// <param name="inAscending">Boolean variable used to specify the order in which the array is sorted.</param>
/// <returns>Sorted using comparisonCriteria array in ascending order if inAscending = true; in descending order otherwise.</returns>
public static int[][] ParameterizedSortArrayRows(int[][] array, Func<IEnumerable<int>, int> comparisonCriteria, bool inAscending)
{
var length = array.Length;
// Bubble sort in order of increasing sums of elements of rows of the matrix.
for (var i = 0; i < length; i++)
{
for (var j = i + 1; j < length; j++)
{
if (comparisonCriteria(array[i]) > comparisonCriteria(array[j]))
{
// Swap rows.
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
if (inAscending)
{
return array;
}
else
{
return array.Reverse().ToArray();
}
}
/// <summary>
/// Contains the implementation of SortArrayRows that sorts array rows in ascending order of the sum of their elements.
/// </summary>
public class IncreasingSumsOfRowElements : IStrategy
{
/// <summary>
/// Sorts array rows in ascending order of the sum of their elements.
/// </summary>
/// <param name="array">Array to be sorted.</param>
/// <returns>Array whose rows are in ascending order of the sum of their elements.</returns>
public int[][] SortArrayRows(int[][] array)
{
return ParameterizedSortArrayRows(array, Enumerable.Sum, true);
}
}
/// <summary>
/// Contains the implementation of SortArrayRows that sorts array rows in descending order of the sum of their elements.
/// </summary>
public class DecreasingSumsOfRowElements : IStrategy
{
/// <summary>
/// Sorts array rows in descending order of the sum of their elements.
/// </summary>
/// <param name="array">Array to be sorted.</param>
/// <returns>Array whose rows are in descending order of the sum of their elements.</returns>
public int[][] SortArrayRows(int[][] array)
{
return ParameterizedSortArrayRows(array, Enumerable.Sum, false);
}
}
/// <summary>
/// Contains the implementation of SortArrayRows that sorts array rows in ascending order of the maximum elements of rows.
/// </summary>
public class IncreasingMaximumElement : IStrategy
{
/// <summary>
/// Sorts array rows in ascending order of the maximum elements of rows.
/// </summary>
/// <param name="array">Array to be sorted.</param>
/// <returns>Array whose rows are in ascending order of the maximum elements of rows.</returns>
public int[][] SortArrayRows(int[][] array)
{
return ParameterizedSortArrayRows(array, Enumerable.Max, true);
}
}
/// <summary>
/// Contains the implementation of SortArrayRows that sorts array rows in descending order of the maximum elements of rows.
/// </summary>
public class DecreasingMaximumElement : IStrategy
{
/// <summary>
/// Sorts array rows in descending order of the maximum elements of rows.
/// </summary>
/// <param name="array">Array to be sorted.</param>
/// <returns>Array whose rows are in descending order of the maximum elements of rows.</returns>
public int[][] SortArrayRows(int[][] array)
{
return ParameterizedSortArrayRows(array, Enumerable.Max, false);
}
}
/// <summary>
/// Contains the implementation of SortArrayRows that sorts array rows in ascending order of the minimum elements of rows.
/// </summary>
public class IncreasingMinimumElement : IStrategy
{
/// <summary>
/// Sorts array rows in ascending order of the minimum elements of rows.
/// </summary>
/// <param name="array">Array to be sorted.</param>
/// <returns>Array whose rows are in ascending order of the minimum elements of rows.</returns>
public int[][] SortArrayRows(int[][] array)
{
return ParameterizedSortArrayRows(array, Enumerable.Min, true);
}
}
/// <summary>
/// Contains the implementation of SortArrayRows that sorts array rows in descending order of the minimum elements of rows.
/// </summary>
public class DecreasingMinimumElement : IStrategy
{
/// <summary>
/// Sorts array rows in descending order of the minimum elements of rows.
/// </summary>
/// <param name="array">Array to be sorted.</param>
/// <returns>Array whose rows are in descending order of the minimum elements of rows.</returns>
public int[][] SortArrayRows(int[][] array)
{
return ParameterizedSortArrayRows(array, Enumerable.Min, false);
}
}
/// <summary>
/// Context that uses a strategy to solve its problem.
/// </summary>
public class Context
{
/// <summary>
/// IStrategy interface reference that allows the program to automatically switch between specific implementations.
/// </summary>
private IStrategy strategy;
/// <summary>
/// Initializes a new instance of the Context class.
/// </summary>
/// <param name="strategy">Chosen strategy (an object that implements IStrategy interface).</param>
public Context(IStrategy strategy)
{
this.strategy = strategy;
}
/// <summary>
/// Sets a strategy that used by Context to solve its problem.
/// </summary>
/// <param name="strategy">Chosen strategy (an object that implements IStrategy interface).</param>
public void SetStrategy(IStrategy strategy)
{
this.strategy = strategy;
}
/// <summary>
/// Sorts rows of an array using chosen strategy.
/// </summary>
/// <param name="array">Array to be sorted.</param>
/// <returns>Sorted array.</returns>
public int[][] SortArrayRows(int[][] array)
{
return this.strategy.SortArrayRows(array);
}
}
}
} |
using UnityEngine;
public class ProjectileController : MonoBehaviour
{
#region Variables
#region Components
private Rigidbody2D m_rigidbody2D;
#endregion
#region Private Variables
[SerializeField] private string m_destroySound;
[SerializeField] private LayerMask m_destroyMask;
[SerializeField] private CustomProjectile m_customProjectileScript;
private float m_currentSpeed;
private float m_addSpeedOverTime;
private AnimationCurve m_moveCurve;
private AudioManager m_audioManager;
#endregion
#endregion
#region BuiltIn Methods
void Start()
{
m_audioManager = GameObject.FindGameObjectWithTag("AudioManager").GetComponent<AudioManager>();
m_rigidbody2D = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
m_currentSpeed += m_addSpeedOverTime * Time.deltaTime;
m_rigidbody2D.velocity = transform.right * m_currentSpeed * Time.deltaTime + transform.up * m_moveCurve.Evaluate(Time.time % m_moveCurve.length);
}
void OnCollisionEnter2D(Collision2D col)
{
if (m_destroyMask == (m_destroyMask | (1 << col.gameObject.layer)))
{
if (m_customProjectileScript)
m_customProjectileScript.Init(transform);
if (m_audioManager)
m_audioManager.Play("SFX", m_destroySound);
Destroy(gameObject);
}
}
#endregion
#region Custom Methods
public void Init(float currentSpeed, float addSpeedOverTime, AnimationCurve moveCurve)
{
m_currentSpeed = currentSpeed;
m_addSpeedOverTime = addSpeedOverTime;
m_moveCurve = moveCurve;
}
public void CustomProjectileStart()
{
if (m_customProjectileScript)
{
m_customProjectileScript.Init(transform);
}
}
#endregion
}
|
namespace LiveTest.Models
{
public class RoleViewModel
{
public string User { get; set; }
public string Role { get; set; }
}
} |
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 Negocio;
namespace AerolineaFrba.Abm_Ciudad
{
public partial class frmCiudades : Form
{
public frmCiudades()
{
InitializeComponent();
}
private void frmCiudades_Load(object sender, EventArgs e)
{
limpiar();
}
private void limpiar()
{
txtNombre.Text = string.Empty;
chkHabilitadas.Checked = false;
actualizarDGV(new Ciudad().obtenerTodasDGV());
}
private void btnLimpiar_Click(object sender, EventArgs e)
{
limpiar();
}
private void actualizarDGV(DataTable fuente)
{
dgvCiudades.DataSource = null;
dgvCiudades.Columns.Clear();
dgvCiudades.DataSource = fuente;
dgvCiudades.Columns[0].Visible = false;
//Creo la columna de modificar
var columnaActualizar = new DataGridViewButtonColumn
{
Text = "Modificar",
UseColumnTextForButtonValue = true,
AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
};
//Creo la columna de borrar
var columnaEliminar = new DataGridViewButtonColumn
{
Text = "Inhabilitar",
UseColumnTextForButtonValue = true,
AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
};
//Agrego las columnas nuevas
dgvCiudades.Columns.Add(columnaActualizar);
dgvCiudades.Columns.Add(columnaEliminar);
}
private void btnVolver_Click(object sender, EventArgs e)
{
Close();
}
private void btnFiltrar_Click(object sender, EventArgs e)
{
try
{
actualizarDGV(new Ciudad().obtenerFiltroDGV(txtNombre.Text.Trim(), chkHabilitadas.Checked));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
private void btnNueva_Click(object sender, EventArgs e)
{
frmAMCiudad amc = new frmAMCiudad(null);
amc.ShowDialog();
limpiar();
}
private void dgvCiudades_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1)
return;
Ciudad cSeleccionada = new Ciudad().obtenerCiudadPorNombre((string)dgvCiudades.Rows[e.RowIndex].Cells[1].Value);
if (cSeleccionada != null)
{
if (e.ColumnIndex == 3)
{
frmAMCiudad amc = new frmAMCiudad(cSeleccionada);
amc.ShowDialog();
limpiar();
}
if (e.ColumnIndex == 4)
{
try
{
var msg = MessageBox.Show("¿Esta seguro que quiere inhabilitar la ciudad seleccionada?", "Atención", MessageBoxButtons.YesNo);
if (msg == DialogResult.Yes)
{
if (new Ciudad().estaEnAlgunaRuta(cSeleccionada))
{
throw new Exception("La ciudad es parte de una ruta aerea, no se puede inhabilitar.");
}
new Ciudad().inhabilitarCiudad(cSeleccionada);
MessageBox.Show("La ciudad ha sido inhabilitada.", "Atención");
limpiar();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class respawn : MonoBehaviour
{
public Holdable itemPrefab;
public float respawnSeconds = 5;
[System.NonSerialized]
public Holdable item;
public void Start()
{
Respawn();
}
public void Consume()
{
if (item != null)
{
item = null;
Invoke("Respawn", respawnSeconds);
}
}
public void Respawn()
{
if (item == null)
{
item = Object.Instantiate(itemPrefab, this.transform);
item.SetSpawner(this);
}
}
public void OnDrawGizmos()
{
Gizmos.color = Color.yellow;
Gizmos.DrawSphere(transform.position, 0.5f);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace Question
{
[Table("tblAnswers")]
public class Answer
{
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestBlackjack;
using Cards;
using Blackjack;
namespace TestBlackjack
{
[TestClass]
public class TestBlackjackHand
{
private Card two, ten, jack, queen, king, ace;
[TestInitialize]
public void Setup()
{
two = CardFactory.GetCard(Card.RankEnum.Two, Card.SuitEnum.Hearts);
ten = CardFactory.GetCard(Card.RankEnum.Ten, Card.SuitEnum.Clubs);
jack = CardFactory.GetCard(Card.RankEnum.Jack, Card.SuitEnum.Diamonds);
queen = CardFactory.GetCard(Card.RankEnum.Queen, Card.SuitEnum.Spades);
king = CardFactory.GetCard(Card.RankEnum.King, Card.SuitEnum.Clubs);
ace = CardFactory.GetCard(Card.RankEnum.Ace, Card.SuitEnum.Hearts);
}
[TestMethod]
public void TestBasics()
{
BlackjackHand hand = new();
Assert.AreEqual(0, hand.Value);
Assert.IsFalse(hand.HasAce);
Assert.AreEqual(0, hand.NumAces);
Assert.IsFalse(hand.IsSoft);
Assert.IsFalse(hand.IsBust);
Assert.IsFalse(hand.IsPair);
Assert.IsFalse(hand.IsBlackjack);
Assert.IsFalse(hand.IsNaturalBlackjack);
Assert.IsFalse(hand.IsSplit);
hand.Add(two);
Assert.AreEqual(2, hand.Value);
Assert.IsFalse(hand.HasAce);
Assert.AreEqual(0, hand.NumAces);
Assert.IsFalse(hand.IsSoft);
Assert.IsFalse(hand.IsBust);
Assert.IsFalse(hand.IsPair);
Assert.IsFalse(hand.IsBlackjack);
Assert.IsFalse(hand.IsNaturalBlackjack);
Assert.IsFalse(hand.IsSplit);
hand.Add(ten);
Assert.AreEqual(12, hand.Value);
Assert.IsFalse(hand.HasAce);
Assert.AreEqual(0, hand.NumAces);
Assert.IsFalse(hand.IsSoft);
Assert.IsFalse(hand.IsBust);
Assert.IsFalse(hand.IsPair);
Assert.IsFalse(hand.IsBlackjack);
Assert.IsFalse(hand.IsNaturalBlackjack);
Assert.IsFalse(hand.IsSplit);
hand.Add(ten);
Assert.AreEqual(22, hand.Value);
Assert.IsFalse(hand.HasAce);
Assert.AreEqual(0, hand.NumAces);
Assert.IsFalse(hand.IsSoft);
Assert.IsTrue(hand.IsBust);
Assert.IsFalse(hand.IsPair);
Assert.IsFalse(hand.IsBlackjack);
Assert.IsFalse(hand.IsNaturalBlackjack);
Assert.IsFalse(hand.IsSplit);
hand = new BlackjackHand(two, jack);
Assert.AreEqual(two, hand[0]);
Assert.AreEqual(jack, hand[1]);
}
[TestMethod]
public void TestBlackjack()
{
BlackjackHand hand = new(jack, ace);
Assert.AreEqual(21, hand.Value);
Assert.IsTrue(hand.HasAce);
Assert.AreEqual(1, hand.NumAces);
Assert.IsTrue(hand.IsSoft);
Assert.IsFalse(hand.IsBust);
Assert.IsFalse(hand.IsPair);
Assert.IsTrue(hand.IsBlackjack);
Assert.IsTrue(hand.IsNaturalBlackjack);
Assert.IsFalse(hand.IsSplit);
hand.Add(queen);
Assert.AreEqual(21, hand.Value);
Assert.IsTrue(hand.HasAce);
Assert.AreEqual(1, hand.NumAces);
Assert.IsFalse(hand.IsSoft);
Assert.IsFalse(hand.IsBust);
Assert.IsFalse(hand.IsPair);
Assert.IsTrue(hand.IsBlackjack);
Assert.IsFalse(hand.IsNaturalBlackjack);
Assert.IsFalse(hand.IsSplit);
}
[TestMethod]
public void TestPairs()
{
BlackjackHand hand = new(king, king);
Assert.AreEqual(20, hand.Value);
Assert.IsFalse(hand.HasAce);
Assert.AreEqual(0, hand.NumAces);
Assert.IsFalse(hand.IsSoft);
Assert.IsFalse(hand.IsBust);
Assert.IsTrue(hand.IsPair);
Assert.IsFalse(hand.IsBlackjack);
Assert.IsFalse(hand.IsNaturalBlackjack);
Assert.IsFalse(hand.IsSplit);
}
[TestMethod]
public void TestMultiAces()
{
Card nine = CardFactory.GetCard(Card.RankEnum.Nine, Card.SuitEnum.Clubs);
BlackjackHand hand = new(ace, nine);
Assert.AreEqual(20, hand.Value);
Assert.IsTrue(hand.HasAce);
Assert.AreEqual(1, hand.NumAces);
Assert.IsTrue(hand.IsSoft);
Assert.IsFalse(hand.IsBust);
Assert.IsFalse(hand.IsPair);
Assert.IsFalse(hand.IsBlackjack);
Assert.IsFalse(hand.IsNaturalBlackjack);
Assert.IsFalse(hand.IsSplit);
hand.Add(ace);
Assert.AreEqual(21, hand.Value);
Assert.IsTrue(hand.HasAce);
Assert.AreEqual(2, hand.NumAces);
Assert.IsTrue(hand.IsSoft);
Assert.IsFalse(hand.IsBust);
Assert.IsFalse(hand.IsPair);
Assert.IsTrue(hand.IsBlackjack);
Assert.IsFalse(hand.IsNaturalBlackjack);
Assert.IsFalse(hand.IsSplit);
hand.Add(ace);
Assert.AreEqual(12, hand.Value);
Assert.IsTrue(hand.HasAce);
Assert.AreEqual(3, hand.NumAces);
Assert.IsFalse(hand.IsSoft);
Assert.IsFalse(hand.IsBust);
Assert.IsFalse(hand.IsPair);
Assert.IsFalse(hand.IsBlackjack);
Assert.IsFalse(hand.IsNaturalBlackjack);
Assert.IsFalse(hand.IsSplit);
hand.Add(nine);
Assert.AreEqual(21, hand.Value);
Assert.IsTrue(hand.HasAce);
Assert.AreEqual(3, hand.NumAces);
Assert.IsFalse(hand.IsSoft);
Assert.IsFalse(hand.IsBust);
Assert.IsFalse(hand.IsPair);
Assert.IsTrue(hand.IsBlackjack);
Assert.IsFalse(hand.IsNaturalBlackjack);
Assert.IsFalse(hand.IsSplit);
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class pausa : MonoBehaviour {
// Use this for initialization
bool pausado=false;
public void Pause() {
if (!pausado) {
Time.timeScale = 0;
pausado = true;
} else {
Time.timeScale = 1;
pausado=false;
}
}
}
|
namespace CameraBazaar.Models.Attributes
{
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
using Constants;
public class CameraModelAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string modelAsStr = value as string;
if (!Regex.IsMatch(modelAsStr, ValidationRegularExpressions.CameraModelRegex))
{
return new ValidationResult(ValidationMessages.CameraModelValidationMessage);
}
return ValidationResult.Success;
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Api
{
class ErrorLogFile
{
private string logFormat = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + "\t";
private string path = @"log/" + DateTime.Now.ToShortDateString() + ".txt";
bool loggingEnabled;
public ErrorLogFile()
{
//Checks if the log directory exists
if (!Directory.Exists(@"log/"))
{
System.IO.Directory.CreateDirectory(@"log/");
}
recreateConfig(configValidationCheck());
//Checks the enable entry of the configfile & sets loggingEnabled
using (StreamReader sr = new StreamReader(@"log/config.txt"))
{
string line = sr.ReadToEnd();
string subStr = line.Substring(line.IndexOf('=') + 1).Trim();
loggingEnabled = Convert.ToBoolean(subStr);
}
}
//Checks the existence and the validity of the config
private bool configValidationCheck()
{
//Check if the configfile exists.
if (!File.Exists(@"log/config.txt"))
{
return true;
}
//Check if the configfile has the right format
using (StreamReader sr = new StreamReader(@"log/config.txt"))
{
string line = sr.ReadLine();
if (line.Equals("enabled = false") || line.Equals("enabled = true"))
{
return false;
}
}
return true;
}
//Recreates the config when true
private void recreateConfig(bool recreate)
{
if (recreate)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"log/config.txt"))
{
file.WriteLine("enabled = false");
}
}
}
//Writes Error errMsg into the LogFile
public void errorLog(string errMsg)
{
if(!loggingEnabled)
{
return;
}
using (System.IO.StreamWriter file = new System.IO.StreamWriter(path, true))
{
file.WriteLine(logFormat + errMsg);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web;
// public class RetureCode
// {
// public int code = 0;
// public string msg = "";
// }
//
// public class CodeData
// {
// public string CountryCode;
// public string PhoneNum;
// public string CodeNum;
// public string Data;
// public DateTime CreateTime = DateTime.Now;
// public bool HasExp()
// {
// return (DateTime.Now - CreateTime).TotalMinutes >= 30;
// }
// }
// public class PhoneCode
// {
// public static PhoneCode GPhoneCode = new PhoneCode();
// public Dictionary<string, CodeData> Codes = new Dictionary<string, CodeData>();
// public void Add(string phone, CodeData code)
// {
// lock (Codes)
// {
// Codes.Remove(phone);
// Codes.Add(phone, code);
// }
// }
// public CodeData CheckCode(string CountryCode, string PhoneNum, string CodeNum)
// {
// lock (Codes)
// {
// if (Codes.ContainsKey(CountryCode + PhoneNum))
// {
// CodeData d = Codes[CountryCode + PhoneNum];
// if (d.CodeNum == CodeNum)
// {
// Codes.Remove(CountryCode + PhoneNum);
// if (!d.HasExp())
// return d;
// }
// }
// return null;
// }
// }
// public CodeData FindCode(string CountryCode, string PhoneNum)
// {
// lock (Codes)
// {
// if (Codes.ContainsKey(CountryCode + PhoneNum))
// {
// CodeData d = Codes[CountryCode + PhoneNum];
// if (!d.HasExp())
// return d;
// }
// return null;
// }
// }
// }
// public class CommonTools
// {
// public static string GetRequest(HttpContext context)
// {
// Stream sm = context.Request.InputStream;
// using (StreamReader inputData = new StreamReader(sm))
// {
// string DataString = inputData.ReadToEnd();
// return DataString;
// }
// }
// public static void SendStringToClient(HttpContext hd, System.Object obj)
// {
// hd.Response.ContentType = "text/plain;charset=UTF-8";
// hd.Response.Write(LitJson.JsonMapper.ToJson(obj));
// }
// public static void SendStringToClient(HttpContext hd, string obj)
// {
// hd.Response.ContentType = "text/plain;charset=UTF-8";
// hd.Response.Write(obj);
// }
// public static void SendStringToClient(HttpContext hd, int codeId, string Msg)
// {
// RetureCode code = new RetureCode();
// code.code = codeId;
// code.msg = Msg;
// SendStringToClient(hd, code);
// }
//
// static Random rd = new Random();
// public static string CreatePassWord(int num)
// {
// string str = "";
// for (int i = 0; i < num; i++)
// {
// str += (char)(((int)'0') + rd.Next(10));
// }
// return str;
// }
// public static string GetMD5Hash(string fileName)
// {
// try
// {
// MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(fileName));
// MD5 md5 = new MD5CryptoServiceProvider();
// byte[] retVal = md5.ComputeHash(ms);
// ms.Close();
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < retVal.Length; i++)
// {
// sb.Append(retVal[i].ToString("x2"));
// }
// return sb.ToString();
// }
// catch (Exception ex)
// {
// throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
// }
// }
// }
public class Debug
{
public static string RootPath = "D:/RYpro/Web/Log/";
public static void Log(string type, string cont, bool bSuss)
{
if (bSuss)
LogSuss(type, cont);
else
LogError(type, cont);
}
public static void Log(string type, string cont)
{
if (RootPath == "")
{
RootPath = System.Environment.CurrentDirectory;
if (!RootPath.EndsWith("/") && !RootPath.EndsWith("\\"))
RootPath += "/";
}
if (!System.IO.Directory.Exists(RootPath + "weblogs/"))
System.IO.Directory.CreateDirectory(RootPath + "weblogs/");
File.AppendAllText( RootPath+"weblogs/"+DateTime.Now.ToString("yyyy-MM-dd") + " .log", DateTime.Now.ToString() + " " + type + ":" + cont.ToString() + "\n");
}
public static void LogError(string type, string cont)
{
Log("Error "+type, cont);
}
public static void LogSuss(string type, string cont)
{
Log("Suss " + type, cont);
}
public static void LogException(Exception type)
{
LogError("Exception", type.Message.ToString()+"\n"+type.StackTrace.ToString());
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MIDIDotNet
{
public class GMOutDevice : IOutDevice, IDisposable
{
IOutDevice outDevice;
public GMOutDevice(IOutDevice outDevice)
{
this.outDevice = outDevice;
}
#region IDisposable
public void Dispose()
{
}
#endregion
#region IOutDevice
public string DeviceName { get { return outDevice.DeviceName; } }
public bool IsOpen { get { return outDevice.IsOpen; } }
public uint Polyphony { get { return outDevice.Polyphony; } }
public uint Voices { get { return outDevice.Voices; } }
public bool[] Channel { get { return outDevice.Channel; } }
public uint DeviceType { get { return outDevice.DeviceType; } }
public void Open() { outDevice.Open(); }
public void Close() { outDevice.Close(); }
public void SendShortMsg(uint msg) { outDevice.SendShortMsg(msg); }
#endregion
public void SendNoteOn(byte channel, byte note, byte velocity)
{
if (channel > 0x0f)
{
throw new MIDIException("Invalid channel", ErrorCode.MDNERR_GM_INVALIDCHANNEL);
}
if (note > 0x7f)
{
throw new MIDIException("Invalid note", ErrorCode.MDNERR_GM_INVALIDNOTE);
}
if (velocity > 0x7f)
{
throw new MIDIException("Invalid velocity", ErrorCode.MDNERR_GM_INVALIDVELOCITY);
}
uint msg = ((uint)0x90 | channel) | ((uint)note << 8) | ((uint)velocity << 16);
SendShortMsg(msg);
}
public void SendNoteOff(byte channel, byte note, byte velocity)
{
if (channel > 0x0f)
{
throw new MIDIException("Invalid channel", ErrorCode.MDNERR_GM_INVALIDCHANNEL);
}
if (note > 0x7f)
{
throw new MIDIException("Invalid note", ErrorCode.MDNERR_GM_INVALIDNOTE);
}
if (velocity > 0x7f)
{
throw new MIDIException("Invalid velocity", ErrorCode.MDNERR_GM_INVALIDVELOCITY);
}
uint msg = ((uint)0x80 | channel) | ((uint)note << 8) | ((uint)velocity << 16);
SendShortMsg(msg);
}
}
}
|
using Com.CurtisRutland.WpfHotkeys;
using HomeServer.Client;
using HomeServer.Enums;
using HomeServer.Objects;
using LogManager;
using NotificationManager;
using RemoteLibrary;
using RemoteLibrary.Enums;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using VideoPlayerRemote.Objects;
namespace VideoPlayerRemote
{
public partial class MainWindow : Window
{
private string previousDirectory;
private string currentDirectory;
bool isInFront = true;
Hotkey hotkeyBringToFront;
Hotkey hotkeyNextFile;
Hotkey hotkeyPreviousFile;
Hotkey hotkeyForward;
Hotkey hotkeyBackward;
Hotkey hotkeyVolumeUp;
Hotkey hotkeyVolumeDown;
BitmapImage playBtnImage;
BitmapImage pauseBtnImage;
public MainWindow()
{
InitializeComponent();
HomeServerClient.Instance.ConnectedToServer += ConnectedToServer;
HomeServerClient.Instance.GotDirectoryFilesAndFolders += Server_GotDirectoryFilesAndFolders;
HomeServerClient.Instance.DeletePath += Server_DeletePath;
HomeServerClient.Instance.Connect(ClientType.Video);
}
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
//if (e.ChangedButton == MouseButton.Left)
// this.DragMove();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var workingArea = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;
var transform = PresentationSource.FromVisual(this).CompositionTarget.TransformFromDevice;
var corner = transform.Transform(new Point(workingArea.Right, workingArea.Bottom));
this.Left = (corner.X / 2) - (this.ActualWidth / 2);
this.Top = corner.Y - this.ActualHeight;
hotkeyBringToFront = new Hotkey(Modifiers.Ctrl | Modifiers.Alt, Keys.V, this, true);
hotkeyBringToFront.HotkeyPressed += HotkeyBringToFrontPressed;
hotkeyNextFile = new Hotkey(Modifiers.Ctrl | Modifiers.Alt, Keys.OemPeriod, this, true);
hotkeyNextFile.HotkeyPressed += HotkeyNextFilePressed;
hotkeyPreviousFile = new Hotkey(Modifiers.Ctrl | Modifiers.Alt, Keys.Oemcomma, this, true);
hotkeyPreviousFile.HotkeyPressed += HotkeyPreviousFilePressed;
hotkeyForward = new Hotkey(Modifiers.Ctrl | Modifiers.Alt, Keys.Oem2, this, true);
hotkeyForward.HotkeyPressed += HotkeyForwardPressed;
hotkeyBackward = new Hotkey(Modifiers.Ctrl | Modifiers.Alt, Keys.M, this, true);
hotkeyBackward.HotkeyPressed += HotkeyBackwardPressed;
hotkeyVolumeDown = new Hotkey(Modifiers.Ctrl | Modifiers.Alt, Keys.Oem1, this, true);
hotkeyVolumeDown.HotkeyPressed += HotkeyVolumeDownPressed;
hotkeyVolumeUp = new Hotkey(Modifiers.Ctrl | Modifiers.Alt, Keys.Oem7, this, true);
hotkeyVolumeUp.HotkeyPressed += HotkeyVolumeUpPressed;
playBtnImage = new BitmapImage(new Uri("pack://application:,,,/VideoPlayerRemote;component/Assets/PlayerIcons/play.png"));
pauseBtnImage = new BitmapImage(new Uri("pack://application:,,,/VideoPlayerRemote;component/Assets/PlayerIcons/pause.png"));
Notifications.InitNotifyIcon(System.Drawing.Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location));
}
private void HotkeyVolumeUpPressed(object sender, HotkeyEventArgs e)
{
Remote.Instance.Volume(true);
}
private void HotkeyVolumeDownPressed(object sender, HotkeyEventArgs e)
{
Remote.Instance.Volume(false);
}
private void HotkeyBackwardPressed(object sender, HotkeyEventArgs e)
{
Remote.Instance.JumpBackward();
}
private void HotkeyForwardPressed(object sender, HotkeyEventArgs e)
{
Remote.Instance.JumpForward();
}
private void HotkeyPreviousFilePressed(object sender, HotkeyEventArgs e)
{
Remote.Instance.PlayPrevious();
}
private void HotkeyNextFilePressed(object sender, HotkeyEventArgs e)
{
Remote.Instance.PlayNext();
}
private void Window_KeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Space:
Remote.Instance.PlayPause();
break;
case Key.Up:
Remote.Instance.Volume(true);
break;
case Key.Down:
Remote.Instance.Volume(false);
break;
case Key.Left:
Remote.Instance.JumpBackward();
break;
case Key.Right:
Remote.Instance.JumpForward();
break;
case Key.PageDown:
Remote.Instance.PlayNext();
break;
case Key.PageUp:
Remote.Instance.PlayPrevious();
break;
case Key.Back:
Browser.Instance.BrowseLocation(previousDirectory);
break;
}
}
private void buttonForward_Click(object sender, RoutedEventArgs e)
{
Remote.Instance.JumpForward();
}
private void buttonNext_Click(object sender, RoutedEventArgs e)
{
Remote.Instance.PlayNext();
}
private void buttonPlayPause_Click(object sender, RoutedEventArgs e)
{
Remote.Instance.PlayPause();
}
private void buttonPrevious_Click(object sender, RoutedEventArgs e)
{
Remote.Instance.PlayPrevious();
}
private void buttonRewind_Click(object sender, RoutedEventArgs e)
{
Remote.Instance.JumpBackward();
}
private void buttonExit_Click(object sender, RoutedEventArgs e)
{
Environment.Exit(0);
}
private void buttonMinimize_Click(object sender, RoutedEventArgs e)
{
WindowState = WindowState.Minimized;
}
private void buttonToggleShutdown_Click(object sender, RoutedEventArgs e)
{
Remote.Instance.ToggleShutdownAfterPlayback();
Brush backColor = (Brush)new BrushConverter().ConvertFrom("#FFF4F4F4");
if (Remote.Instance.ShutDownAfterPlayback)
{
backColor = (Brush)new BrushConverter().ConvertFrom("#FFD44B4B");
}
buttonToggleShutdown.Background = backColor;
}
private void buttonFullscreen_Click(object sender, RoutedEventArgs e)
{
Remote.Instance.FullScreen();
var scope = FocusManager.GetFocusScope(buttonFullscreen);
Keyboard.ClearFocus();
}
private void buttonNextSubs_Click(object sender, RoutedEventArgs e)
{
Remote.Instance.NextSubtitle();
}
private void buttonNextAudio_Click(object sender, RoutedEventArgs e)
{
Remote.Instance.NextAudio();
}
private void buttonRefresh_Click(object sender, RoutedEventArgs e)
{
Browser.Instance.BrowseLocation(currentDirectory);
}
private void buttonBrowseToFile_Click(object sender, RoutedEventArgs e)
{
Browser.Instance.BrowseLocation();
this.mainGrid.Focus();
}
private double SetProgressBarValue(double MousePosition)
{
double ratio = MousePosition / timeBar.ActualWidth;
double ProgressBarValue = ratio * timeBar.Maximum;
return ProgressBarValue;
}
private double SetVolumeBarValue(double MousePosition)
{
double ratio = MousePosition / volumeBar.ActualWidth;
double ProgressBarValue = ratio * volumeBar.Maximum;
return ProgressBarValue;
}
private void TimeBar_MouseDown(object sender, MouseButtonEventArgs e)
{
double MousePosition = e.GetPosition(timeBar).X;
double position = SetProgressBarValue(MousePosition);
string pos = string.Format("{0:00}:{1:00}:{2:00}",
TimeSpan.FromMilliseconds(position).Hours,
TimeSpan.FromMilliseconds(position).Minutes,
TimeSpan.FromMilliseconds(position).Seconds);
Remote.Instance.SetPosition(pos);
}
private void volumeBar_MouseDown(object sender, MouseButtonEventArgs e)
{
double MousePosition = e.GetPosition(volumeBar).X;
double volumeLevel = Math.Round(SetVolumeBarValue(MousePosition));
Remote.Instance.SetVolume((int)volumeLevel);
}
private void ConnectedToServer()
{
Notifications.ShowNotification("Connected to server!");
HomeServerClient.Instance.SendMessage(MessageType.StartVideoPlayer, "");
Recents.Instance.LoadRecents();
PlaylistManager.Instance.PlaylistChanged += PlaylistChanged;
PlaylistManager.Instance.Init();
Remote.Instance.PlayerInfoRefreshed += PlayerInfoRefreshed;
Remote.Instance.Init();
Browser.Instance.BrowserLocationLoaded += BrowserLocationLoaded;
Browser.Instance.BrowseLocation();
Browser.Instance.BrowseLocation(Recents.Instance.RecentFiles.Count > 0 ?
System.IO.Path.GetDirectoryName(Recents.Instance.RecentFiles[0]) : null);
RefreshPlaylistItems();
}
private void PlayerInfoRefreshed()
{
try
{
this.Dispatcher.Invoke((Action)(() =>
{
labelCurrentPosition.Content = Remote.Instance.PlayerInfo.CurrentPosition;
labelDuration.Content = Remote.Instance.PlayerInfo.Duration;
labelTitle.Content = System.IO.Path.GetFileName(Remote.Instance.PlayerInfo.Filename);
volumeBar.Value = Remote.Instance.PlayerInfo.VolumeLevel;
if (Remote.Instance.PlayerInfo.Playing)
{
PlayPauseImage.Source = pauseBtnImage;
PlayPauseImage.Margin = new Thickness(0, 0, 0, 0);
}
else
{
PlayPauseImage.Source = playBtnImage;
PlayPauseImage.Margin = new Thickness(4, 0, 0, 0);
}
if (Remote.Instance.PlayerInfo.DurationMilliseconds != 0)
{
timeBar.Maximum = Remote.Instance.PlayerInfo.DurationMilliseconds;
timeBar.Value = Remote.Instance.PlayerInfo.CurrentPositionMilliseconds;
}
else
{
timeBar.Value = 0;
}
}));
}
catch (Exception ex) { Logger.Log(ex); }
}
private void HotkeyBringToFrontPressed(object sender, HotkeyEventArgs e)
{
isInFront = !isInFront;
if (!isInFront)
{
WindowState = WindowState.Normal;
this.Activate();
}
else
{
WindowState = WindowState.Minimized;
}
}
private void buttonAddToPlaylist_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)e.OriginalSource;
BrowserItem item = (BrowserItem)btn.DataContext;
if (Browser.Instance.IsVideo(item.Filename))
{
PlaylistManager.Instance.AddToPlaylist(item.Filename);
}
else if (Browser.Instance.IsDirectory(item.Filename))
{
HomeServerClient.Instance.SendMessage(MessageType.GetDirectoryFilesAndFolders, item.Filename + "\\");
}
}
private void buttonDeleteFile_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)e.OriginalSource;
BrowserItem item = (BrowserItem)btn.DataContext;
HomeServerClient.Instance.SendMessage(MessageType.DeletePath, item.Filename);
}
private void buttonDelete_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)e.OriginalSource;
PlaylistItem item = (PlaylistItem)btn.DataContext;
PlaylistManager.Instance.RemoveFromPlaylist(item.Filename);
}
private void buttonDown_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)e.OriginalSource;
PlaylistItem item = (PlaylistItem)btn.DataContext;
PlaylistManager.Instance.MovePlaylistItem(item.Filename, false);
}
private void buttonUp_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)e.OriginalSource;
PlaylistItem item = (PlaylistItem)btn.DataContext;
PlaylistManager.Instance.MovePlaylistItem(item.Filename, true);
}
private void listBoxBrowserRecents_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
BrowserItem bi = null;
string controlName = e.OriginalSource.ToString().ToLower();
if (controlName.Contains("border"))
{
Border b = (Border)e.OriginalSource;
bi = (BrowserItem)b.DataContext;
}
else
{
TextBlock t = (TextBlock)e.OriginalSource;
bi = (BrowserItem)t.DataContext;
}
if (bi != null)
{
if (labelRecents.Foreground == Brushes.White)
{
Remote.Instance.PlayFile(bi.Filename);
}
else
{
Browser.Instance.BrowseLocation(bi.Filename);
}
}
}
private void listBoxPlaylist_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
PlaylistItem pi = null;
string controlName = e.OriginalSource.ToString().ToLower();
if (controlName.Contains("border"))
{
Border b = (Border)e.OriginalSource;
pi = (PlaylistItem)b.DataContext;
}
else
{
TextBlock t = (TextBlock)e.OriginalSource;
pi = (PlaylistItem)t.DataContext;
}
if (pi != null)
{
if (pi.Filename != Remote.Instance.PlayerInfo.Filename)
{
Remote.Instance.PlayFile(pi.Filename);
}
}
}
private void listBoxBrowserRecents_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
//ListBox parent = (ListBox)sender;
//ListBox dragSource = parent;
//object data = GetDataFromListBox(dragSource, e.GetPosition(parent));
//if (data != null)
//{
// DragDrop.DoDragDrop(parent, data, DragDropEffects.Move);
//}
}
private void listBoxPlaylist_Drop(object sender, DragEventArgs e)
{
ListBox parent = (ListBox)sender;
var bi = (BrowserItem)e.Data.GetData(typeof(BrowserItem));
if (Browser.Instance.IsVideo(bi.Filename))
{
PlaylistManager.Instance.AddToPlaylist(bi.Filename);
}
else if (Browser.Instance.IsDirectory(bi.Filename))
{
HomeServerClient.Instance.SendMessage(MessageType.GetDirectoryFilesAndFolders, bi.Filename + "\\");
}
}
private void BrowserLocationLoaded(List<string> fileList)
{
this.Dispatcher.Invoke((Action)(() =>
{
listBoxBrowserRecents.Items.Clear();
SetBrowserLabel(true);
}));
previousDirectory = fileList[0];
currentDirectory = System.IO.Path.GetDirectoryName(fileList[1]);
foreach (string file in fileList)
{
var bi = new BrowserItem()
{
Filename = file,
ButtonVisibility = Visibility.Visible
};
if (file == fileList[0])
{
bi.Title = "...";
bi.ButtonVisibility = Visibility.Hidden;
bi.ButtonDeleteVisibility = Visibility.Hidden;
previousDirectory = file;
}
else
{
bi.Title = System.IO.Path.GetFileName(file);
}
if (String.IsNullOrEmpty(bi.Title))
{
bi.Title = file;
}
if (Browser.Instance.IsDirectory(System.IO.Path.GetExtension(file)))
{
bi.Image = "Assets/folder.png";
}
else
{
bi.Image = "Assets/mov.png";
}
this.Dispatcher.Invoke((Action)(() =>
{
listBoxBrowserRecents.Items.Add(bi);
}));
}
}
private void PlaylistChanged()
{
RefreshPlaylistItems();
}
private void Server_GotDirectoryFilesAndFolders(List<string> dirContent)
{
foreach (string f in dirContent)
{
if (!Browser.Instance.IsDirectory(f) && Browser.Instance.IsVideo(f))
{
//this.Dispatcher.Invoke((Action)(() =>
//{
PlaylistManager.Instance.AddToPlaylist(f);
//}));
}
}
}
private void Server_DeletePath()
{
Browser.Instance.BrowseLocation(currentDirectory);
}
private void RefreshPlaylistItems()
{
this.Dispatcher.Invoke((Action)(() =>
{
listBoxPlaylist.Items.Clear();
}));
foreach (string file in PlaylistManager.Instance.Files)
{
var pi = new PlaylistItem()
{
Title = System.IO.Path.GetFileName(file),
Filename = file
};
this.Dispatcher.Invoke((Action)(() =>
{
listBoxPlaylist.Items.Add(pi);
}));
}
}
private void RefreshRecentItems()
{
this.Dispatcher.Invoke((Action)(() =>
{
listBoxBrowserRecents.Items.Clear();
}));
if (Recents.Instance.RecentFiles == null) return;
foreach (string file in Recents.Instance.RecentFiles)
{
var bi = new BrowserItem()
{
Filename = file,
Title = System.IO.Path.GetFileName(file),
Image = "Assets/mov.png",
ButtonDeleteVisibility = Visibility.Hidden
};
this.Dispatcher.Invoke((Action)(() =>
{
listBoxBrowserRecents.Items.Add(bi);
}));
}
}
private void labelRecents_MouseDown(object sender, MouseButtonEventArgs e)
{
SetBrowserLabel(false);
RefreshRecentItems();
}
private void labelBrowser_MouseDown(object sender, MouseButtonEventArgs e)
{
SetBrowserLabel(true);
Browser.Instance.BrowseLocation(currentDirectory);
}
private void mainGrid_KeyDown(object sender, KeyEventArgs e)
{
Console.WriteLine();
}
private static object GetDataFromListBox(ListBox source, Point point)
{
UIElement element = source.InputHitTest(point) as UIElement;
if (element != null)
{
object data = DependencyProperty.UnsetValue;
while (data == DependencyProperty.UnsetValue)
{
data = source.ItemContainerGenerator.ItemFromContainer(element);
if (data == DependencyProperty.UnsetValue)
{
element = VisualTreeHelper.GetParent(element) as UIElement;
}
if (element == source)
{
return null;
}
}
if (data != DependencyProperty.UnsetValue)
{
return data;
}
}
return null;
}
private void SetBrowserLabel(bool showBrowserLabel)
{
if (showBrowserLabel)
{
labelRecents.Foreground = Brushes.Silver;
labelBrowser.Foreground = Brushes.White;
labelRecents.FontSize = 15;
labelBrowser.FontSize = 20;
}
else
{
labelRecents.Foreground = Brushes.White;
labelBrowser.Foreground = Brushes.Silver;
labelRecents.FontSize = 20;
labelBrowser.FontSize = 15;
}
}
}
}
|
// Copyright (c) 2018 FiiiLab Technology Ltd
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
using FiiiChain.Entities;
using System;
using System.Collections.Generic;
using Microsoft.Data.Sqlite;
using System.Text;
using FiiiChain.Framework;
using System.Linq;
using System.Data;
using FiiiChain.Entities.ExtensionModels;
namespace FiiiChain.Data
{
public class BlockDac : DataAccessComponent<BlockDac>
{
public virtual int Save(Block block)
{
int rows = 0;
StringBuilder sql = new StringBuilder("BEGIN TRANSACTION;");
sql.Append("INSERT INTO Blocks " +
"(Hash, Version, Height, PreviousBlockHash, Bits, Nonce, Timestamp, NextBlockHash, TotalAmount, TotalFee, GeneratorId, BlockSignature, PayloadHash, IsDiscarded, IsVerified) " +
$"VALUES ('{block.Hash}', {block.Version}, {block.Height}, '{block.PreviousBlockHash}', {block.Bits}, {block.Nonce}, {block.Timestamp}, null, {block.TotalAmount}, {block.TotalFee}, '{block.GeneratorId}', '{block.BlockSignature}', '{block.PayloadHash}', {Convert.ToInt32(block.IsDiscarded)}, {Convert.ToInt32(block.IsVerified)});");
foreach (var transaction in block.Transactions)
{
sql.Append("INSERT INTO Transactions " +
"(Hash, BlockHash, Version, Timestamp, LockTime, TotalInput, TotalOutput, Fee, Size) " +
$"VALUES ('{transaction.Hash}', '{transaction.BlockHash}', {transaction.Version}, {transaction.Timestamp}, {transaction.LockTime}, {transaction.TotalInput}, {transaction.TotalOutput}, {transaction.Fee}, {transaction.Size});");
foreach (var input in transaction.Inputs)
{
sql.Append("INSERT INTO InputList " +
"(TransactionHash, OutputTransactionHash, OutputIndex, Size, Amount, UnlockScript, AccountId, BlockHash) " +
$"VALUES ('{input.TransactionHash}', '{input.OutputTransactionHash}', {input.OutputIndex}, {input.Size}, {input.Amount}, '{input.UnlockScript}', '{Convert.ToString(input.AccountId)}', '{block.Hash}');");
if (input.OutputTransactionHash != Base16.Encode(HashHelper.EmptyHash()))
{
sql.Append($"UPDATE OutputList SET Spent = 1 WHERE TransactionHash = '{input.OutputTransactionHash}' AND [Index] = {input.OutputIndex};");
}
}
foreach (var output in transaction.Outputs)
{
sql.Append("INSERT INTO OutputList " +
"([Index], TransactionHash, ReceiverId, Amount, Size, LockScript, Spent, BlockHash) " +
$"VALUES ({output.Index}, '{output.TransactionHash}', '{output.ReceiverId}', {output.Amount}, {output.Size}, '{output.LockScript}', {Convert.ToInt32(output.Spent)}, '{block.Hash}'); ");
}
}
sql.Append($"UPDATE Blocks SET NextBlockHash = '{block.Hash}' WHERE Hash = '{block.PreviousBlockHash}';");
sql.Append("END TRANSACTION;");
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(sql.ToString(), con))
{
cmd.Connection.Open();
//con.SynchronousNORMAL();
rows = cmd.ExecuteNonQuery();
}
return rows;
}
internal virtual void UpdateNextBlockHash(string currentHash, string nextHash)
{
const string SQL_STATEMENT =
"UPDATE Blocks " +
"SET NextBlockHash = @NextBlockHash " +
"WHERE Hash = @Hash ";
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@Hash", currentHash);
cmd.Parameters.AddWithValue("@NextBlockHash", nextHash);
cmd.Connection.Open();
//con.SynchronousNORMAL();
cmd.ExecuteNonQuery();
}
}
internal virtual void UpdateBlockStatusToDiscarded(string hash)
{
const string TX_SELECT_SQL_STATEMENT =
"SELECT Hash " +
"FROM Transactions " +
"WHERE BlockHash = @BlockHash " +
"AND IsDiscarded = 0 ";
const string BLOCK_UPDATE_SQL_STATEMENT =
"UPDATE Blocks " +
"SET IsDiscarded = 1 " +
"WHERE Hash = @Hash ";
const string TX_UPDATE_SQL_STATEMENT =
"UPDATE Transactions " +
"SET IsDiscarded = 1 " +
"WHERE BlockHash = @BlockHash ";
const string INPUT_UPDATE_SQL_STATEMENT =
"UPDATE InputList " +
"SET IsDiscarded = 1 " +
"WHERE TransactionHash = @TransactionHash AND BlockHash = @BlockHash";
const string OUTPUT_UPDATE_SQL_STATEMENT =
"UPDATE OutputList " +
"SET IsDiscarded = 1 " +
"WHERE TransactionHash = @TransactionHash AND BlockHash = @BlockHash ";
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
{
con.Open();
//con.SynchronousNORMAL();
var txHashList = new List<string>();
using (SqliteCommand cmd = new SqliteCommand(TX_SELECT_SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@BlockHash", hash);
cmd.Connection.Open();
using (SqliteDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
txHashList.Add(GetDataValue<string>(dr, "Hash"));
}
}
}
using (var scope = new System.Transactions.TransactionScope())
{
using (SqliteCommand cmd = new SqliteCommand(BLOCK_UPDATE_SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@Hash", hash);
cmd.ExecuteNonQuery();
}
using (SqliteCommand cmd = new SqliteCommand(TX_UPDATE_SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@BlockHash", hash);
cmd.ExecuteNonQuery();
}
foreach(var txHash in txHashList)
{
using (SqliteCommand cmd = new SqliteCommand(INPUT_UPDATE_SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@TransactionHash", txHash);
cmd.Parameters.AddWithValue("@BlockHash", hash);
cmd.ExecuteNonQuery();
}
using (SqliteCommand cmd = new SqliteCommand(OUTPUT_UPDATE_SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@TransactionHash", txHash);
cmd.Parameters.AddWithValue("@BlockHash", hash);
cmd.ExecuteNonQuery();
}
}
scope.Complete();
}
}
}
internal virtual void UpdateBlockStatusToConfirmed(string hash)
{
const string SQL_STATEMENT =
"UPDATE Blocks " +
"SET IsVerified = 1 " +
"WHERE Hash = @Hash ";
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@Hash", hash);
cmd.Connection.Open();
//con.SynchronousNORMAL();
cmd.ExecuteNonQuery();
}
}
public virtual Dictionary<long, Block> Select()
{
const string SQL_STATEMENT =
"SELECT * " +
"FROM Blocks " +
"WHERE IsDiscarded = 0";
Dictionary<long, Block> result = null;
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Connection.Open();
//con.SynchronousNORMAL();
using (SqliteDataReader dr = cmd.ExecuteReader())
{
result = new Dictionary<long, Block>();
while (dr.Read())
{
Block block = new Block();
block.Id = GetDataValue<long>(dr, "Id");
block.Hash = GetDataValue<string>(dr, "Hash");
block.Version = GetDataValue<int>(dr, "Version");
block.Height = GetDataValue<long>(dr, "Height");
block.PreviousBlockHash = GetDataValue<string>(dr, "PreviousBlockHash");
block.Bits = GetDataValue<long>(dr, "Bits");
block.Nonce = GetDataValue<long>(dr, "Nonce");
block.Timestamp = GetDataValue<long>(dr, "Timestamp");
block.NextBlockHash = GetDataValue<string>(dr, "NextBlockHash");
block.TotalAmount = GetDataValue<long>(dr, "TotalAmount");
block.TotalFee = GetDataValue<long>(dr, "TotalFee");
block.GeneratorId = GetDataValue<string>(dr, "GeneratorId");
block.BlockSignature = GetDataValue<string>(dr, "BlockSignature");
block.PayloadHash = GetDataValue<string>(dr, "PayloadHash");
block.IsDiscarded = GetDataValue<bool>(dr, "IsDiscarded");
block.IsVerified = GetDataValue<bool>(dr, "IsVerified");
result.Add(block.Id, block);
}
}
}
return result;
}
public virtual Dictionary<long, Block> SelectByHeightRange(long from, long to)
{
const string SQL_STATEMENT =
"SELECT * " +
"FROM Blocks " +
"WHERE Id BETWEEN @FromHeight AND @ToHeight " +
"AND IsDiscarded = 0 ";
Dictionary<long, Block> result = null;
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@FromHeight", from);
cmd.Parameters.AddWithValue("@ToHeight", to);
cmd.Connection.Open();
//con.SynchronousNORMAL();
using (SqliteDataReader dr = cmd.ExecuteReader())
{
result = new Dictionary<long, Block>();
while (dr.Read())
{
Block block = new Block();
block.Id = GetDataValue<long>(dr, "Id");
block.Hash = GetDataValue<string>(dr, "Hash");
block.Version = GetDataValue<int>(dr, "Version");
block.Height = GetDataValue<long>(dr, "Height");
block.PreviousBlockHash = GetDataValue<string>(dr, "PreviousBlockHash");
block.Bits = GetDataValue<long>(dr, "Bits");
block.Nonce = GetDataValue<long>(dr, "Nonce");
block.Timestamp = GetDataValue<long>(dr, "Timestamp");
block.NextBlockHash = GetDataValue<string>(dr, "NextBlockHash");
block.TotalAmount = GetDataValue<long>(dr, "TotalAmount");
block.TotalFee = GetDataValue<long>(dr, "TotalFee");
block.GeneratorId = GetDataValue<string>(dr, "GeneratorId");
block.BlockSignature = GetDataValue<string>(dr, "BlockSignature");
block.PayloadHash = GetDataValue<string>(dr, "PayloadHash");
block.IsDiscarded = GetDataValue<bool>(dr, "IsDiscarded");
block.IsVerified = GetDataValue<bool>(dr, "IsVerified");
result.Add(block.Id, block);
}
}
}
return result;
}
public virtual bool HasBlock(long height)
{
const string SQL_STATEMENT =
"SELECT 1 " +
"FROM Blocks " +
"WHERE IsDiscarded = 0 " +
"AND Height = @Height LIMIT 1 ";
bool hasBlock = false;
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@Height", height);
cmd.Connection.Open();
//con.SynchronousNORMAL();
using (SqliteDataReader dr = cmd.ExecuteReader())
{
hasBlock = dr.HasRows;
}
}
return hasBlock;
}
public virtual Block SelectLast()
{
const string SQL_STATEMENT =
"SELECT * " +
"FROM Blocks " +
"WHERE IsDiscarded = 0 " +
"ORDER BY Height DESC,Timestamp DESC LIMIT 1 ";
Block block = null;
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Connection.Open();
//con.SynchronousNORMAL();
using (SqliteDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
block = new Block();
block.Id = GetDataValue<long>(dr, "Id");
block.Hash = GetDataValue<string>(dr, "Hash");
block.Version = GetDataValue<int>(dr, "Version");
block.Height = GetDataValue<long>(dr, "Height");
block.PreviousBlockHash = GetDataValue<string>(dr, "PreviousBlockHash");
block.Bits = GetDataValue<long>(dr, "Bits");
block.Nonce = GetDataValue<long>(dr, "Nonce");
block.Timestamp = GetDataValue<long>(dr, "Timestamp");
block.NextBlockHash = GetDataValue<string>(dr, "NextBlockHash");
block.TotalAmount = GetDataValue<long>(dr, "TotalAmount");
block.TotalFee = GetDataValue<long>(dr, "TotalFee");
block.GeneratorId = GetDataValue<string>(dr, "GeneratorId");
block.BlockSignature = GetDataValue<string>(dr, "BlockSignature");
block.PayloadHash = GetDataValue<string>(dr, "PayloadHash");
block.IsDiscarded = GetDataValue<bool>(dr, "IsDiscarded");
block.IsVerified = GetDataValue<bool>(dr, "IsVerified");
}
}
}
return block;
}
public virtual Block SelectLastConfirmed()
{
const string SQL_STATEMENT =
"SELECT * " +
"FROM Blocks " +
"WHERE IsDiscarded = 0 AND IsVerified = 1 " +
"ORDER BY Height DESC,Timestamp DESC LIMIT 1 ";
Block block = null;
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Connection.Open();
//con.SynchronousNORMAL();
using (SqliteDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
block = new Block();
block.Id = GetDataValue<long>(dr, "Id");
block.Hash = GetDataValue<string>(dr, "Hash");
block.Version = GetDataValue<int>(dr, "Version");
block.Height = GetDataValue<long>(dr, "Height");
block.PreviousBlockHash = GetDataValue<string>(dr, "PreviousBlockHash");
block.Bits = GetDataValue<long>(dr, "Bits");
block.Nonce = GetDataValue<long>(dr, "Nonce");
block.Timestamp = GetDataValue<long>(dr, "Timestamp");
block.NextBlockHash = GetDataValue<string>(dr, "NextBlockHash");
block.TotalAmount = GetDataValue<long>(dr, "TotalAmount");
block.TotalFee = GetDataValue<long>(dr, "TotalFee");
block.GeneratorId = GetDataValue<string>(dr, "GeneratorId");
block.BlockSignature = GetDataValue<string>(dr, "BlockSignature");
block.PayloadHash = GetDataValue<string>(dr, "PayloadHash");
block.IsDiscarded = GetDataValue<bool>(dr, "IsDiscarded");
block.IsVerified = GetDataValue<bool>(dr, "IsVerified");
}
}
}
return block;
}
public virtual Block SelectById(long id)
{
const string SQL_STATEMENT =
"SELECT * " +
"FROM Blocks " +
"WHERE Id = @Id " +
"AND IsDiscarded = 0 ";
Block block = null;
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@Id", id);
cmd.Connection.Open();
//con.SynchronousNORMAL();
using (SqliteDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
block = new Block();
block.Id = GetDataValue<long>(dr, "Id");
block.Hash = GetDataValue<string>(dr, "Hash");
block.Version = GetDataValue<int>(dr, "Version");
block.Height = GetDataValue<long>(dr, "Height");
block.PreviousBlockHash = GetDataValue<string>(dr, "PreviousBlockHash");
block.Bits = GetDataValue<long>(dr, "Bits");
block.Nonce = GetDataValue<long>(dr, "Nonce");
block.Timestamp = GetDataValue<long>(dr, "Timestamp");
block.NextBlockHash = GetDataValue<string>(dr, "NextBlockHash");
block.TotalAmount = GetDataValue<long>(dr, "TotalAmount");
block.TotalFee = GetDataValue<long>(dr, "TotalFee");
block.GeneratorId = GetDataValue<string>(dr, "GeneratorId");
block.BlockSignature = GetDataValue<string>(dr, "BlockSignature");
block.PayloadHash = GetDataValue<string>(dr, "PayloadHash");
block.IsDiscarded = GetDataValue<bool>(dr, "IsDiscarded");
block.IsVerified = GetDataValue<bool>(dr, "IsVerified");
}
}
}
return block;
}
public virtual List<Block> SelectByHeight(long height)
{
const string SQL_STATEMENT =
"SELECT * " +
"FROM Blocks " +
"WHERE Height = @Height " +
"AND IsDiscarded = 0 ";
var result = new List<Block>();
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@Height", height);
cmd.Connection.Open();
//con.SynchronousNORMAL();
using (SqliteDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
var block = new Block();
block.Id = GetDataValue<long>(dr, "Id");
block.Hash = GetDataValue<string>(dr, "Hash");
block.Version = GetDataValue<int>(dr, "Version");
block.Height = GetDataValue<long>(dr, "Height");
block.PreviousBlockHash = GetDataValue<string>(dr, "PreviousBlockHash");
block.Bits = GetDataValue<long>(dr, "Bits");
block.Nonce = GetDataValue<long>(dr, "Nonce");
block.Timestamp = GetDataValue<long>(dr, "Timestamp");
block.NextBlockHash = GetDataValue<string>(dr, "NextBlockHash");
block.TotalAmount = GetDataValue<long>(dr, "TotalAmount");
block.TotalFee = GetDataValue<long>(dr, "TotalFee");
block.GeneratorId = GetDataValue<string>(dr, "GeneratorId");
block.BlockSignature = GetDataValue<string>(dr, "BlockSignature");
block.PayloadHash = GetDataValue<string>(dr, "PayloadHash");
block.IsDiscarded = GetDataValue<bool>(dr, "IsDiscarded");
block.IsVerified = GetDataValue<bool>(dr, "IsVerified");
result.Add(block);
}
}
}
return result;
}
public virtual List<Block> SelectByHeights(IEnumerable<long> height)
{
var match = $" ({string.Join(",", height)}) ";
string SQL_STATEMENT =
"SELECT * " +
"FROM Blocks " +
"WHERE Height in " + match +
" AND IsDiscarded = 0 ";
var result = new List<Block>();
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Connection.Open();
//con.SynchronousNORMAL();
using (SqliteDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
var block = new Block();
block.Id = GetDataValue<long>(dr, "Id");
block.Hash = GetDataValue<string>(dr, "Hash");
block.Version = GetDataValue<int>(dr, "Version");
block.Height = GetDataValue<long>(dr, "Height");
block.PreviousBlockHash = GetDataValue<string>(dr, "PreviousBlockHash");
block.Bits = GetDataValue<long>(dr, "Bits");
block.Nonce = GetDataValue<long>(dr, "Nonce");
block.Timestamp = GetDataValue<long>(dr, "Timestamp");
block.NextBlockHash = GetDataValue<string>(dr, "NextBlockHash");
block.TotalAmount = GetDataValue<long>(dr, "TotalAmount");
block.TotalFee = GetDataValue<long>(dr, "TotalFee");
block.GeneratorId = GetDataValue<string>(dr, "GeneratorId");
block.BlockSignature = GetDataValue<string>(dr, "BlockSignature");
block.PayloadHash = GetDataValue<string>(dr, "PayloadHash");
block.IsDiscarded = GetDataValue<bool>(dr, "IsDiscarded");
block.IsVerified = GetDataValue<bool>(dr, "IsVerified");
result.Add(block);
}
}
}
return result;
}
public virtual Block SelectByHash(string hash)
{
const string SQL_STATEMENT =
"SELECT * " +
"FROM Blocks " +
"WHERE Hash = @Hash " +
"AND IsDiscarded = 0 ";
Block block = null;
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@Hash", hash);
cmd.Connection.Open();
//con.SynchronousNORMAL();
using (SqliteDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
block = new Block();
block.Id = GetDataValue<long>(dr, "Id");
block.Hash = GetDataValue<string>(dr, "Hash");
block.Version = GetDataValue<int>(dr, "Version");
block.Height = GetDataValue<long>(dr, "Height");
block.PreviousBlockHash = GetDataValue<string>(dr, "PreviousBlockHash");
block.Bits = GetDataValue<long>(dr, "Bits");
block.Nonce = GetDataValue<long>(dr, "Nonce");
block.Timestamp = GetDataValue<long>(dr, "Timestamp");
block.NextBlockHash = GetDataValue<string>(dr, "NextBlockHash");
block.TotalAmount = GetDataValue<long>(dr, "TotalAmount");
block.TotalFee = GetDataValue<long>(dr, "TotalFee");
block.GeneratorId = GetDataValue<string>(dr, "GeneratorId");
block.BlockSignature = GetDataValue<string>(dr, "BlockSignature");
block.PayloadHash = GetDataValue<string>(dr, "PayloadHash");
block.IsDiscarded = GetDataValue<bool>(dr, "IsDiscarded");
block.IsVerified = GetDataValue<bool>(dr, "IsVerified");
}
}
}
return block;
}
public virtual bool BlockHashExist(string hash)
{
const string SQL_STATEMENT =
"SELECT Hash " +
"FROM Blocks " +
"WHERE Hash = @Hash " +
"AND IsDiscarded = 0 Limit 1";
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@Hash", hash);
cmd.Connection.Open();
//con.SynchronousNORMAL();
using (SqliteDataReader dr = cmd.ExecuteReader())
{
return dr.HasRows;
}
}
}
public virtual List<Block> SelectByPreviousHash(string prevHash)
{
const string SQL_STATEMENT =
"SELECT * " +
"FROM Blocks " +
"WHERE PreviousBlockHash = @PreviousBlockHash " +
"AND IsDiscarded = 0 ";
var result = new List<Block>();
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@PreviousBlockHash", prevHash);
cmd.Connection.Open();
//con.SynchronousNORMAL();
using (SqliteDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
var block = new Block();
block.Id = GetDataValue<long>(dr, "Id");
block.Hash = GetDataValue<string>(dr, "Hash");
block.Version = GetDataValue<int>(dr, "Version");
block.Height = GetDataValue<long>(dr, "Height");
block.PreviousBlockHash = GetDataValue<string>(dr, "PreviousBlockHash");
block.Bits = GetDataValue<long>(dr, "Bits");
block.Nonce = GetDataValue<long>(dr, "Nonce");
block.Timestamp = GetDataValue<long>(dr, "Timestamp");
block.NextBlockHash = GetDataValue<string>(dr, "NextBlockHash");
block.TotalAmount = GetDataValue<long>(dr, "TotalAmount");
block.TotalFee = GetDataValue<long>(dr, "TotalFee");
block.GeneratorId = GetDataValue<string>(dr, "GeneratorId");
block.BlockSignature = GetDataValue<string>(dr, "BlockSignature");
block.PayloadHash = GetDataValue<string>(dr, "PayloadHash");
block.IsDiscarded = GetDataValue<bool>(dr, "IsDiscarded");
block.IsVerified = GetDataValue<bool>(dr, "IsVerified");
result.Add(block);
}
}
}
return result;
}
public virtual List<Block> SelectTipBlocks()
{
const string SQL_STATEMENT =
"SELECT * " +
"FROM Blocks " +
"WHERE NextBlockHash IS NULL AND IsDiscarded = 0";
var result = new List<Block>();
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Connection.Open();
//con.SynchronousNORMAL();
using (SqliteDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
var block = new Block();
block.Id = GetDataValue<long>(dr, "Id");
block.Hash = GetDataValue<string>(dr, "Hash");
block.Version = GetDataValue<int>(dr, "Version");
block.Height = GetDataValue<long>(dr, "Height");
block.PreviousBlockHash = GetDataValue<string>(dr, "PreviousBlockHash");
block.Bits = GetDataValue<long>(dr, "Bits");
block.Nonce = GetDataValue<long>(dr, "Nonce");
block.Timestamp = GetDataValue<long>(dr, "Timestamp");
block.NextBlockHash = GetDataValue<string>(dr, "NextBlockHash");
block.TotalAmount = GetDataValue<long>(dr, "TotalAmount");
block.TotalFee = GetDataValue<long>(dr, "TotalFee");
block.GeneratorId = GetDataValue<string>(dr, "GeneratorId");
block.BlockSignature = GetDataValue<string>(dr, "BlockSignature");
block.PayloadHash = GetDataValue<string>(dr, "PayloadHash");
block.IsDiscarded = GetDataValue<bool>(dr, "IsDiscarded");
block.IsVerified = GetDataValue<bool>(dr, "IsVerified");
result.Add(block);
}
}
}
return result;
}
public virtual long CountBranchLength(string blockHash)
{
const string SQL_STATEMENT =
"WITH RECURSIVE down(Hash, PreviousBlockHash, NextBlockHash) AS " +
"( " +
" SELECT Hash, PreviousBlockHash, NextBlockHash " +
" FROM Blocks " +
" WHERE Hash = @Hash " +
" UNION " +
" SELECT a.Hash, a.PreviousBlockHash, a.NextBlockHash " +
" FROM Blocks a, down b " +
" WHERE b.Hash = a.NextBlockHash AND " +
" (SELECT COUNT(0) FROM Blocks WHERE PreviousBlockHash = b.Hash) <= 1 " +
") SELECT count(0) FROM down WHERE Hash != @Hash ";
long result = 0;
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@Hash", blockHash);
cmd.Connection.Open();
//con.SynchronousNORMAL();
result = Convert.ToInt64(cmd.ExecuteScalar());
}
return result;
}
public virtual long CountOfDescendants(string hash)
{
const string SQL_STATEMENT =
"WITH RECURSIVE down(Hash, PreviousBlockHash, NextBlockHash) AS " +
"( " +
" SELECT Hash, PreviousBlockHash, NextBlockHash " +
" FROM Blocks " +
" WHERE Hash = @Hash " +
" UNION " +
" SELECT a.Hash, a.PreviousBlockHash, a.NextBlockHash " +
" FROM Blocks a, down b " +
" WHERE b.Hash = a.PreviousBlockHash " +
") SELECT COUNT(0) - 1 FROM down ;";
long result = 0;
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@Hash", hash);
cmd.Connection.Open();
//con.SynchronousNORMAL();
result = Convert.ToInt64(cmd.ExecuteScalar());
}
return result;
}
public virtual List<string> SelectHashesOfDescendants(string hash)
{
const string SQL_STATEMENT =
"WITH RECURSIVE down(Hash) AS " +
"( " +
" SELECT Hash " +
" FROM Blocks " +
" WHERE Hash = @Hash " +
" UNION " +
" SELECT a.Hash " +
" FROM Blocks a, down b " +
" WHERE b.Hash = a.PreviousBlockHash " +
") SELECT Hash FROM down WHERE Hash != @Hash ";
var result = new List<string>();
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@Hash", hash);
cmd.Connection.Open();
//con.SynchronousNORMAL();
using (SqliteDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
result.Add(GetDataValue<string>(dr, "Hash"));
}
}
}
return result;
}
public virtual List<Block> SelectPreviousBlocks(long lastHeight, int blockCount)
{
const string SQL_STATEMENT =
"WITH RECURSIVE down(Id, Hash, Version, Height, PreviousBlockHash, Bits, Nonce, Timestamp, NextBlockHash, TotalAmount, TotalFee, GeneratorId, BlockSignature, PayloadHash, IsDiscarded, IsVerified, num) AS " +
"( " +
" SELECT Id, Hash, Version, Height, PreviousBlockHash, Bits, Nonce, Timestamp, NextBlockHash, TotalAmount, TotalFee, GeneratorId, BlockSignature, PayloadHash, IsDiscarded, IsVerified, 1 as num " +
" FROM Blocks " +
" WHERE Height = @LastHeight " +
" UNION " +
" SELECT a.Id, a.Hash, a.Version, a.Height, a.PreviousBlockHash, a.Bits, a.Nonce, a.Timestamp, a.NextBlockHash, a.TotalAmount, a.TotalFee, a.GeneratorId, a.BlockSignature, a.PayloadHash, a.IsDiscarded, a.IsVerified, b.num + 1 as num " +
" FROM Blocks a, down b " +
" WHERE b.PreviousBlockHash = a.Hash and b.num < @BlockCount " +
") SELECT Id, Hash, Version, Height, PreviousBlockHash, Bits, Nonce, Timestamp, NextBlockHash, TotalAmount, TotalFee, GeneratorId, BlockSignature, PayloadHash, IsDiscarded, IsVerified FROM down; ";
var result = new List<Block>();
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@LastHeight", lastHeight);
cmd.Parameters.AddWithValue("@BlockCount", blockCount);
cmd.Connection.Open();
//con.SynchronousNORMAL();
using (SqliteDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
var block = new Block();
block.Id = GetDataValue<long>(dr, "Id");
block.Hash = GetDataValue<string>(dr, "Hash");
block.Version = GetDataValue<int>(dr, "Version");
block.Height = GetDataValue<long>(dr, "Height");
block.PreviousBlockHash = GetDataValue<string>(dr, "PreviousBlockHash");
block.Bits = GetDataValue<long>(dr, "Bits");
block.Nonce = GetDataValue<long>(dr, "Nonce");
block.Timestamp = GetDataValue<long>(dr, "Timestamp");
block.NextBlockHash = GetDataValue<string>(dr, "NextBlockHash");
block.TotalAmount = GetDataValue<long>(dr, "TotalAmount");
block.TotalFee = GetDataValue<long>(dr, "TotalFee");
block.GeneratorId = GetDataValue<string>(dr, "GeneratorId");
block.BlockSignature = GetDataValue<string>(dr, "BlockSignature");
block.PayloadHash = GetDataValue<string>(dr, "PayloadHash");
block.IsDiscarded = GetDataValue<bool>(dr, "IsDiscarded");
block.IsVerified = GetDataValue<bool>(dr, "IsVerified");
result.Add(block);
}
}
}
return result;
}
public virtual List<Block> SelectPreviousBlocks(string blockHash, int blockCount)
{
const string SQL_STATEMENT =
"WITH RECURSIVE down(Id, Hash, Version, Height, PreviousBlockHash, Bits, Nonce, Timestamp, NextBlockHash, TotalAmount, TotalFee, GeneratorId, BlockSignature, PayloadHash, IsDiscarded, IsVerified, num) AS " +
"( " +
" SELECT Id, Hash, Version, Height, PreviousBlockHash, Bits, Nonce, Timestamp, NextBlockHash, TotalAmount, TotalFee, GeneratorId, BlockSignature, PayloadHash, IsDiscarded, IsVerified, 1 as num " +
" FROM Blocks " +
" WHERE Hash = @BlockHash " +
" UNION " +
" SELECT a.Id, a.Hash, a.Version, a.Height, a.PreviousBlockHash, a.Bits, a.Nonce, a.Timestamp, a.NextBlockHash, a.TotalAmount, a.TotalFee, a.GeneratorId, a.BlockSignature, a.PayloadHash, a.IsDiscarded, a.IsVerified, b.num + 1 as num " +
" FROM Blocks a, down b " +
" WHERE b.PreviousBlockHash = a.Hash and b.num < @BlockCount " +
") SELECT Id, Hash, Version, Height, PreviousBlockHash, Bits, Nonce, Timestamp, NextBlockHash, TotalAmount, TotalFee, GeneratorId, BlockSignature, PayloadHash, IsDiscarded, IsVerified FROM down; ";
var result = new List<Block>();
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@BlockHash", blockHash);
cmd.Parameters.AddWithValue("@BlockCount", blockCount);
cmd.Connection.Open();
//con.SynchronousNORMAL();
using (SqliteDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
var block = new Block();
block.Id = GetDataValue<long>(dr, "Id");
block.Hash = GetDataValue<string>(dr, "Hash");
block.Version = GetDataValue<int>(dr, "Version");
block.Height = GetDataValue<long>(dr, "Height");
block.PreviousBlockHash = GetDataValue<string>(dr, "PreviousBlockHash");
block.Bits = GetDataValue<long>(dr, "Bits");
block.Nonce = GetDataValue<long>(dr, "Nonce");
block.Timestamp = GetDataValue<long>(dr, "Timestamp");
block.NextBlockHash = GetDataValue<string>(dr, "NextBlockHash");
block.TotalAmount = GetDataValue<long>(dr, "TotalAmount");
block.TotalFee = GetDataValue<long>(dr, "TotalFee");
block.GeneratorId = GetDataValue<string>(dr, "GeneratorId");
block.BlockSignature = GetDataValue<string>(dr, "BlockSignature");
block.PayloadHash = GetDataValue<string>(dr, "PayloadHash");
block.IsDiscarded = GetDataValue<bool>(dr, "IsDiscarded");
block.IsVerified = GetDataValue<bool>(dr, "IsVerified");
result.Add(block);
}
}
}
return result;
}
public virtual long SelectIdByHeight(long height)
{
const string SQL_STATEMENT =
"SELECT Id " +
"FROM Blocks " +
"WHERE Height = @Height " +
"AND IsDiscarded = 0 ";
long blockId = 0;
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@Height", height);
cmd.Connection.Open();
//con.SynchronousNORMAL();
blockId = (long)cmd.ExecuteScalar();
}
return blockId;
}
public virtual List<long> SelectIdByLimit(long blockId, int limit)
{
const string SQL_STATEMENT =
"SELECT Id " +
"FROM Blocks " +
"WHERE Id > @Id " +
"AND IsDiscarded = 0 " +
"LIMIT @Id, @Limit";
List<long> result = null;
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@Id", blockId);
cmd.Parameters.AddWithValue("@Limit", limit);
cmd.Connection.Open();
//con.SynchronousNORMAL();
using (SqliteDataReader dr = cmd.ExecuteReader())
{
result = new List<long>();
while (dr.Read())
{
Block block = new Block();
long id = GetDataValue<long>(dr, "Id");
result.Add(id);
}
}
}
return result;
}
public virtual Dictionary<long, Block> SelectByLimit(long blockId, int limit)
{
const string SQL_STATEMENT =
"SELECT * " +
"FROM Blocks " +
"WHERE Id > @Id " +
"AND IsDiscarded = 0 " +
"LIMIT @Id, @Limit ";
Dictionary<long, Block> result = null;
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@Id", blockId);
cmd.Parameters.AddWithValue("@Limit", limit);
cmd.Connection.Open();
//con.SynchronousNORMAL();
using (SqliteDataReader dr = cmd.ExecuteReader())
{
result = new Dictionary<long, Block>();
while (dr.Read())
{
Block block = new Block();
block.Id = GetDataValue<long>(dr, "Id");
block.Hash = GetDataValue<string>(dr, "Hash");
block.Version = GetDataValue<int>(dr, "Version");
block.Height = GetDataValue<long>(dr, "Height");
block.PreviousBlockHash = GetDataValue<string>(dr, "PreviousBlockHash");
block.Bits = GetDataValue<long>(dr, "Bits");
block.Nonce = GetDataValue<long>(dr, "Nonce");
block.Timestamp = GetDataValue<long>(dr, "Timestamp");
block.NextBlockHash = GetDataValue<string>(dr, "NextBlockHash");
block.TotalAmount = GetDataValue<long>(dr, "TotalAmount");
block.TotalFee = GetDataValue<long>(dr, "TotalFee");
block.GeneratorId = GetDataValue<string>(dr, "GeneratorId");
block.IsDiscarded = GetDataValue<bool>(dr, "IsDiscarded");
block.IsVerified = GetDataValue<bool>(dr, "IsVerified");
result.Add(block.Id, block);
}
}
}
return result;
}
public virtual List<Block> DistinguishBlockVerifiedByHashes(List<string> hashes)
{
string SQL_STATEMENT = $"SELECT * FROM Blocks WHERE Hash IN('{string.Join("','", hashes.ToArray())}');";
List<Block> result = null;
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Connection.Open();
//con.SynchronousNORMAL();
using (SqliteDataReader dr = cmd.ExecuteReader())
{
result = new List<Block>();
while (dr.Read())
{
Block block = new Block();
block.Id = GetDataValue<long>(dr, "Id");
block.Hash = GetDataValue<string>(dr, "Hash");
block.Version = GetDataValue<int>(dr, "Version");
block.Height = GetDataValue<long>(dr, "Height");
block.PreviousBlockHash = GetDataValue<string>(dr, "PreviousBlockHash");
block.Bits = GetDataValue<long>(dr, "Bits");
block.Nonce = GetDataValue<long>(dr, "Nonce");
block.Timestamp = GetDataValue<long>(dr, "Timestamp");
block.NextBlockHash = GetDataValue<string>(dr, "NextBlockHash");
block.TotalAmount = GetDataValue<long>(dr, "TotalAmount");
block.TotalFee = GetDataValue<long>(dr, "TotalFee");
block.GeneratorId = GetDataValue<string>(dr, "GeneratorId");
block.IsDiscarded = GetDataValue<bool>(dr, "IsDiscarded");
block.IsVerified = GetDataValue<bool>(dr, "IsVerified");
result.Add(block);
}
}
}
return result;
}
/// <summary>
/// 确认次数
/// </summary>
/// <param name="blockHash"></param>
/// <param name="height"></param>
/// <param name="confirmations"></param>
/// <returns></returns>
public virtual ListSinceBlock GetSinceBlock(string blockHash, long height, long confirmations)
{
string SQL_STATEMENT =
"SELECT t1.TransactionHash, t1.'Index', t2.IsDiscarded, t1.amount, t4.id AS Address, t4.Tag, t2.TotalInput, t2.Fee, t2.Timestamp, t3.Hash as BlockHash, t3.Timestamp as BlockTime, (@Height - t3.Height + 1) as Confirmations, t1.Spent, t2.LockTime "
+ "FROM OutputList t1 JOIN Transactions t2 ON t1.TransactionHash = t2.Hash "
+ "JOIN Blocks t3 ON t2.BlockHash = t3.Hash "
+ "JOIN Accounts t4 ON t1.ReceiverId = t4.Id "
+ "WHERE t1.IsDiscarded = 0 AND t3.IsDiscarded = 0 AND t3.height > (SELECT Height FROM Blocks WHERE Hash = @Hash);";
if (string.IsNullOrEmpty(blockHash))
{
SQL_STATEMENT =
"SELECT t1.TransactionHash, t1.'Index', t2.IsDiscarded, t1.amount, t4.id AS Address, t4.Tag, t2.TotalInput, t2.Fee, t2.Timestamp, t3.Hash as BlockHash, t3.Timestamp as BlockTime, (@Height - t3.Height + 1) as Confirmations, t1.Spent, t2.LockTime "
+ "FROM OutputList t1 JOIN Transactions t2 ON t1.TransactionHash = t2.Hash "
+ "JOIN Blocks t3 ON t2.BlockHash = t3.Hash "
+ "JOIN Accounts t4 ON t1.ReceiverId = t4.Id "
+ "WHERE t1.IsDiscarded = 0 AND t3.IsDiscarded = 0;";
}
List<SinceBlock> sinceBlock = null;
string lastestBlockHash = string.Empty;
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
{
con.Open();
//con.SynchronousNORMAL();
SqliteTransaction transaction = con.BeginTransaction();
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@Hash", blockHash);
cmd.Parameters.AddWithValue("@Height", height);
cmd.Parameters.AddWithValue("@Confirmations", confirmations);
cmd.Connection.Open();
SqliteDataReader dataReader = cmd.ExecuteReader();
sinceBlock = (
from IDataRecord x in dataReader
where (long)x["IsDiscarded"] == 0
select new SinceBlock
{
Account = "",
Address = (string)x["Address"],
amount = (long)x["Amount"],
Confirmations = (long)x["Confirmations"],
Category = ((long)x["TotalInput"] == 0 && (long)x["Fee"] == 0 && (long)x["Confirmations"] >= 100) ? "generate" : ((long)x["TotalInput"] == 0 && (long)x["Fee"] == 0) ? "immature" : "receive",
Vout = (long)x["Index"],
Fee = (long)x["Fee"],
LockTime = (long)x["LockTime"],
BlockHash = (string)x["BlockHash"],
BlockTime = (long)x["BlockTime"],
Label = x["Tag"].Equals(DBNull.Value) ? "" : (string)x["Tag"],
TxId = (string)x["TransactionHash"],
IsSpent = (long)x["Spent"] == 0 ? false : true
}).ToList();
}
}
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
{
con.Open();
//获取lastestBlock
long lastestBlockHeight = height - confirmations + 1;
if (lastestBlockHeight < 0)
{
return new ListSinceBlock { LastBlock = null, Transactions = sinceBlock?.ToArray() };
}
const string BLOCKSQL_STATEMENT =
"SELECT Hash " +
"FROM Blocks " +
"WHERE Height = @Height " +
"AND IsDiscarded = 0 limit 1; ";
using (SqliteCommand cmd = new SqliteCommand(BLOCKSQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@Height", lastestBlockHeight);
cmd.Connection.Open();
using (SqliteDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
lastestBlockHash = GetDataValue<string>(dr, "Hash");
}
}
}
}
return new ListSinceBlock { LastBlock = lastestBlockHash, Transactions = sinceBlock?.ToArray() };
}
/// <summary>
///
/// </summary>
/// <param name="blockHash">当前的BlockHash</param>
/// <param name="height"></param>
/// <param name="confirmations">确认次数</param>
/// <param name="currentPage">当前页</param>
/// <param name="pageSize">每页显示数</param>
/// <returns></returns>
public virtual ListSinceBlock GetPageSinceBlock(string blockHash, long height, long confirmations, int currentPage, int pageSize)
{
string SQL_STATEMENT =
"SELECT t1.TransactionHash, t1.'Index', t2.IsDiscarded, t1.amount, t4.id AS Address, t4.Tag, t2.TotalInput, t2.Fee, t2.Timestamp, t3.Hash as BlockHash, t3.Timestamp as BlockTime, (@Height - t3.Height + 1) as Confirmations, t1.Spent, t2.LockTime "
+ "FROM OutputList t1 JOIN Transactions t2 ON t1.TransactionHash = t2.Hash "
+ "JOIN Blocks t3 ON t2.BlockHash = t3.Hash "
+ "JOIN Accounts t4 ON t1.ReceiverId = t4.Id "
+ "WHERE t1.IsDiscarded = 0 AND t3.IsDiscarded = 0 AND t3.height >= (SELECT Height FROM Blocks WHERE Hash = @Hash)"
+ " LIMIT (@CurrentPage - 1) * @PageSize, @PageSize;";
if (string.IsNullOrEmpty(blockHash))
{
SQL_STATEMENT =
"SELECT t1.TransactionHash, t1.'Index', t2.IsDiscarded, t1.amount, t4.id AS Address, t4.Tag, t2.TotalInput, t2.Fee, t2.Timestamp, t3.Hash as BlockHash, t3.Timestamp as BlockTime, (@Height - t3.Height + 1) as Confirmations, t1.Spent, t2.LockTime "
+ "FROM OutputList t1 JOIN Transactions t2 ON t1.TransactionHash = t2.Hash "
+ "JOIN Blocks t3 ON t2.BlockHash = t3.Hash "
+ "JOIN Accounts t4 ON t1.ReceiverId = t4.Id "
+ "WHERE t1.IsDiscarded = 0 AND t3.IsDiscarded = 0;"
+ " LIMIT (@CurrentPage - 1) * @PageSize, @PageSize;";
}
List<SinceBlock> sinceBlock = null;
string lastestBlockHash = string.Empty;
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
{
con.Open();
//con.SynchronousNORMAL();
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@Hash", blockHash);
cmd.Parameters.AddWithValue("@Height", height);
cmd.Parameters.AddWithValue("@CurrentPage", currentPage);
cmd.Parameters.AddWithValue("@PageSize", pageSize);
cmd.Connection.Open();
SqliteDataReader dataReader = cmd.ExecuteReader();
sinceBlock = (
from IDataRecord x in dataReader
where (long)x["IsDiscarded"] == 0
select new SinceBlock
{
Account = "",
Address = (string)x["Address"],
amount = (long)x["Amount"],
Confirmations = (long)x["Confirmations"],
Category = ((long)x["TotalInput"] == 0 && (long)x["Fee"] == 0 && (long)x["Confirmations"] >= 100) ? "generate" : ((long)x["TotalInput"] == 0 && (long)x["Fee"] == 0) ? "immature" : "receive",
Vout = (long)x["Index"],
Fee = (long)x["Fee"],
LockTime = (long)x["LockTime"],
BlockHash = (string)x["BlockHash"],
BlockTime = (long)x["BlockTime"],
Label = x["Tag"].Equals(DBNull.Value) ? "" : (string)x["Tag"],
TxId = (string)x["TransactionHash"],
IsSpent = (long)x["Spent"] == 0 ? false : true
}).ToList();
}
}
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
{
//获取lastestBlock
long lastestBlockHeight = height - confirmations + 1;
if (lastestBlockHeight < 0)
{
return new ListSinceBlock { LastBlock = null, Transactions = sinceBlock?.ToArray() };
}
const string BLOCKSQL_STATEMENT =
"SELECT Hash " +
"FROM Blocks " +
"WHERE Height = @Height " +
"AND IsDiscarded = 0 limit 1; ";
con.Open();
using (SqliteCommand cmd = new SqliteCommand(BLOCKSQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@Height", lastestBlockHeight);
cmd.Connection.Open();
using (SqliteDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
lastestBlockHash = GetDataValue<string>(dr, "Hash");
}
}
}
}
return new ListSinceBlock { LastBlock = lastestBlockHash, Transactions = sinceBlock?.ToArray() };
}
public virtual long GetBlockReward(string blockHash)
{
/*
const string SQL_STATEMENT =
"SELECT t1.TransactionHash, t1.'Index', t1.amount, t4.id AS Address, t4.Tag, t2.TotalInput, t2.Fee, t2.Timestamp, t3.Hash as BlockHash, t3.Timestamp as BlockTime, (@Height - t3.Height) as Confirmations "
+ "FROM OutputList t1 JOIN Transactions t2 ON t1.TransactionHash = t2.Hash "
+ "JOIN Blocks t3 ON t2.BlockHash = t3.Hash "
+ "JOIN Accounts t4 ON t1.ReceiverId = t4.Id "
+ "WHERE t1.IsDiscarded = 0 AND t2.IsDiscarded = 0 AND t3.IsDiscarded = 0 AND t3.height > (SELECT Height FROM Blocks WHERE Hash = @Hash) AND t3.height < @Height;";
List<SinceBlock> sinceBlock = null;
string lastestBlock = "";
long blockTime = 0;
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Parameters.AddWithValue("@Hash", blockHash);
cmd.Parameters.AddWithValue("@Height", height);
cmd.Connection.Open();
using (SqliteDataReader dr = cmd.ExecuteReader())
{
sinceBlock = new List<SinceBlock>();
while (dr.Read())
{
SinceBlock block = new SinceBlock();
block.Account = "";
block.Address = GetDataValue<string>(dr, "Address");
block.amount = GetDataValue<long>(dr, "Amount");
block.Category = (GetDataValue<long>(dr, "TotalInput") == 0 && GetDataValue<long>(dr, "Fee") == 0 && GetDataValue<long>(dr, "Confirmations") > 100) ? "generate"
: (GetDataValue<long>(dr, "TotalInput") == 0 && GetDataValue<long>(dr, "Fee") == 0 && GetDataValue<long>(dr, "Confirmations") < 100) ? "immature" : "receive";
block.Vout = GetDataValue<long>(dr, "Index");
block.Fee = GetDataValue<long>(dr, "Fee");
block.Confirmations = GetDataValue<long>(dr, "Confirmations");
block.BlockHash = GetDataValue<string>(dr, "BlockHash");
block.BlockTime = GetDataValue<long>(dr, "BlockTime");
block.Label = GetDataValue<string>(dr, "Tag") ?? "";
block.TxId = GetDataValue<string>(dr, "TransactionHash");
if (block.BlockTime > blockTime)
{
lastestBlock = block.BlockHash;
}
sinceBlock.Add(block);
}
}
}
if (sinceBlock == null && sinceBlock.Count == 0)
{
return null;
}
else
{
return new ListSinceBlock { LastBlock = lastestBlock, Transactions = sinceBlock.ToArray() };
}
*/
return 0;
}
public virtual List<BlockTrans> GetBlocksByTxHash(List<string> hashes)
{
if (hashes == null || !hashes.Any())
return new List<BlockTrans>();
string SQL_STATEMENT = $"select a.Hash as BlockHash,a.Height,a.[timestamp],b.Hash as TxHash from blocks as a inner join transactions as b on a.Hash = b.BlockHash and b.hash IN( '{string.Join("','", hashes.ToArray())}');";
List<BlockTrans> result = null;
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Connection.Open();
//con.SynchronousNORMAL();
using (SqliteDataReader dr = cmd.ExecuteReader())
{
result = new List<BlockTrans>();
while (dr.Read())
{
BlockTrans bt = new BlockTrans();
bt.BlockHash = GetDataValue<string>(dr, "BlockHash");
bt.Height = GetDataValue<long>(dr, "Height");
bt.Timestamp = GetDataValue<long>(dr, "Timestamp");
bt.TransHash = GetDataValue<string>(dr, "TxHash");
result.Add(bt);
}
}
}
return result;
}
public virtual List<BlockConstraint> GetConstraintsByBlockHashs(IEnumerable<string> hashs)
{
List<BlockConstraint> result= new List<BlockConstraint>();
var condition= $"('{string.Join("','", hashs)}')";
//string SQL_PREV_TRANSACTIONS = $"UPDATE Transactions SET HASH = REPLACE(HASH,' ','') WHERE REPLACE(HASH,' ','') IN {condition};";
//string SQL_PREV_OUTPUTS = $"UPDATE outputList SET Transactionhash = REPLACE(Transactionhash,' ','') WHERE REPLACE(Transactionhash, ' ', '') IN {condition};";
string SQL_MAIN = $"select outputList.TransactionHash,Blocks.Height,Transactions.LockTime," +
$"(select count(1) from inputlist where OutputTransactionHash = '0000000000000000000000000000000000000000000000000000000000000000' and outputList.transactionHash = inputlist.transactionHash) as IsCoinBase " +
$"from outputList " +
$"join Transactions on outputList.transactionHash = Transactions.Hash " +
$"join Blocks on outputList.BlockHash = Blocks.Hash and blocks.IsDiscarded = 0 " +
$"where transactionHash in {condition};" ;
string SQL_STATEMENT = SQL_MAIN;// SQL_PREV_TRANSACTIONS +SQL_PREV_OUTPUTS + SQL_MAIN;
using (SqliteConnection con = new SqliteConnection(base.CacheConnectionString))
using (SqliteCommand cmd = new SqliteCommand(SQL_STATEMENT, con))
{
cmd.Connection.Open();
//con.SynchronousNORMAL();
using (SqliteDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
BlockConstraint constraint = new BlockConstraint();
constraint.Height = GetDataValue<long>(dr, "Height");
constraint.TransactionHash = GetDataValue<string>(dr, "TransactionHash");
constraint.LockTime = GetDataValue<long>(dr, "LockTime");
constraint.IsCoinBase = GetDataValue<bool>(dr, "IsCoinBase");
result.Add(constraint);
}
}
}
return result;
}
}
}
|
using Cs_Gerencial.Aplicacao.Interfaces;
using Cs_Gerencial.Dominio.Entities;
using Cs_Gerencial.Dominio.Interfaces.Servicos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Gerencial.Aplicacao.ServicosApp
{
public class AppServicoLogSistema: AppServicoBase<LogSistema>, IAppServicoLogSistema
{
private readonly IServicoLogSistema _servicoLogSistema;
public AppServicoLogSistema(IServicoLogSistema servicoLogSistema)
: base(servicoLogSistema)
{
_servicoLogSistema = servicoLogSistema;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Welic.Dominio.Eventos;
namespace Registrators
{
public class ManipuladorNotificacaoDominio : IManipulador<NotificacaoDominio>
{
private List<NotificacaoDominio> _notifications;
public ManipuladorNotificacaoDominio()
{
_notifications = new List<NotificacaoDominio>();
}
public void Manipular(NotificacaoDominio args)
{
_notifications.Add(args);
}
public IEnumerable<NotificacaoDominio> Notificar()
{
return ObterValor();
}
private List<NotificacaoDominio> ObterValor()
{
return _notifications;
}
public bool PossuiNotificacoes()
{
return ObterValor().Count > 0;
}
public void Dispose()
{
_notifications = new List<NotificacaoDominio>();
}
}
}
|
namespace YouOpine2.DataAccess
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
public partial class yodbModel : DbContext
{
public yodbModel()
: base("name=yodbEntitie")
{
}
public virtual DbSet<IronManOp> IronManOp { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<IronManOp>()
.Property(e => e.Comentario)
.IsUnicode(false);
}
}
}
|
using Microsoft.WindowsAzure.Commands.ServiceManagement.Model;
using Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests.PowershellCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests.IaasCmdletInfo.Extensions.Common
{
public class GetAzureVMExtensionCmdletInfo : CmdletsInfo
{
public GetAzureVMExtensionCmdletInfo(IPersistentVM vm,string extensionName=null, string publisher=null, string version = null, string referenceName = null,
string publicConfiguration = null, string privateConfiguration = null, bool disable= false)
{
cmdletName = Utilities.GetAzureVMExtensionCmdletName;
cmdletParams.Add(new CmdletParam("VM", vm));
if (!string.IsNullOrEmpty(extensionName))
{
cmdletParams.Add(new CmdletParam("ExtensionName", extensionName));
}
if (!string.IsNullOrEmpty(publisher))
{
cmdletParams.Add(new CmdletParam("Publisher", publisher));
}
if (!string.IsNullOrEmpty(version))
{
cmdletParams.Add(new CmdletParam("Version", version));
}
if (!string.IsNullOrEmpty(referenceName))
{
cmdletParams.Add(new CmdletParam("ReferenceName", referenceName));
}
if (!string.IsNullOrEmpty(publicConfiguration))
{
cmdletParams.Add(new CmdletParam("PublicConfiguration", publicConfiguration));
}
if (!string.IsNullOrEmpty(privateConfiguration))
{
cmdletParams.Add(new CmdletParam("PrivateConfiguration", privateConfiguration));
}
if (disable)
{
cmdletParams.Add(new CmdletParam("Disable"));
}
}
}
}
|
using System.Collections;
using UnityEngine;
[System.Serializable]
public class Questionn
{
public string fact;
public bool isTrue;
public GameObject obj;
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PokerEnumLibrary
{
public static class PokerUtilities
{
public static List<Card> AllCards()
{
List<Card> allCards = new List<Card> { };
foreach (Suits suit in Enum.GetValues(typeof(Suits)))
{
foreach (CardValues value in Enum.GetValues(typeof(CardValues)))
{
allCards.Add(new Card(value, suit));
}
}
return allCards;
}
public static Card NameToCard(this string name)
{
Dictionary<char, int> cards = new Dictionary<char, int> { {'T', 10}, { 'J', 11 } , { 'Q', 12 } , { 'K', 13 } };
Dictionary<char, Suits> suits =
new Dictionary<char, Suits> { { 'D', Suits.Diamonds }, { 'H', Suits.Hearts }, { 'S', Suits.Spades }, { 'C', Suits.Clubs } };
bool isInt = int.TryParse(name[0].ToString(), out int num);
if(isInt)
return new Card((CardValues)(1 << num - 1), suits[name[1]]);
return new Card((CardValues)(1 << (cards[name[0]] - 1)), suits[name[1]]);
}
public static List<Card> ShuffledCards(List<Card> allCards)
{
List<Card> shuffled = new List<Card> { };
List<int> random = new List<int> { };
Random rd = new Random();
for (int i = 1; i <= 52; ++i)
{
int randint = rd.Next(0, 52);
while (random.Contains(randint)) //while the number is not already generated
{
randint = rd.Next(0, 52);
}
random.Add(randint);
}
foreach (int randint in random)
{
shuffled.Add(allCards[randint]);
}
return shuffled;
}
public static List<Card> RandomHand(this List<Card> shuffled, int n)
{
return shuffled.Take(n).ToList();
}
public static List<CardValues> FindLongestRun(int cardsBinary)
{
List<CardValues> longestRun = new List<CardValues> { };
int count = 0, start = 0;
for (int i = 14; i >= 0; --i)
{
if (cardsBinary % 2 == 1) //if a 1 is detected
count += 1;
else
{
if (count > longestRun.Count())
{
longestRun.Clear();
for (int j = 0; j < count; ++j)
{
if (start + j == 13)
longestRun.Add(CardValues.Ace); //if ace as high is included in longestRun
else
longestRun.Add((CardValues)(1 << start + j)); //add corresponding CardValue to longestRun
}
}
start += count + 1; //reset start and count
count = 0;
}
cardsBinary = cardsBinary >> 1;// go to next bit
}
return longestRun;
}
public static List<CardValues> LongestRun2(this List<Card> hand)
{
int cardsBinary = 0;
foreach (Card card in hand)
cardsBinary = cardsBinary | (int)card.Value; //bitwise or all the values to get a string of 1s and 0s
if (cardsBinary % 2 == 1)
{
cardsBinary = cardsBinary + (1 << 13); //when Ace counts as high, add Ace as a 14th card
}
return FindLongestRun(cardsBinary);
}
}
}
|
using UnityEngine;
using System.Threading.Tasks;
using Grpc.Core;
using static NetworkService.NetworkService;
using NetworkService;
using System;
public class CallbackServiceServer {
class CallbackService : ComServiceParent {
public override Task<GameStateUpdateReply> GameStateUpdate(GameStateUpdateRequest request, ServerCallContext context) {
GameStateUpdateReply rep = new GameStateUpdateReply();
return Task.FromResult(rep);
}
}
private int servicePort;
private Server serviceServer = null;
private CallbackService service = null;
private bool running = false;
public void StartService(string port = "50052") {
servicePort = Int32.Parse(port);
service = new CallbackService();
serviceServer = new Server {
Services = { BindService(new CallbackService()) },
Ports = { new ServerPort("localhost", servicePort, ServerCredentials.Insecure) }
};
serviceServer.Start();
running = true;
Debug.Log("CallbackService server listening on port " + servicePort);
}
public void StopService() {
if (service != null) {
Debug.Log("Stopping the CallbackService...");
serviceServer.ShutdownAsync().Wait();
serviceServer = null;
}
Debug.Log("CallbackService stopped.");
}
public bool IsRunning() {
return running;
}
}
|
using Harmony;
using MiniMantaVehicle.Core;
using MiniMantaVehicle.Utilities;
using System.Reflection;
namespace MiniMantaVehicle
{
/**
* Entry point into our Mini Manta Vehicle
*/
public class EntryPoint
{
public static string QMODS_FOLDER_LOCATION { get; private set; }
public static string MOD_FOLDER_NAME { get; private set; }
public static readonly string ASSET_FOLDER_NAME = "Assets/";
public static HarmonyInstance HarmonyInstance { get; private set; }
public static void Entry()
{
HarmonyInstance = HarmonyInstance.Create("taylor.brett.MiniMantaVehicle.mod");
HarmonyInstance.PatchAll(Assembly.GetExecutingAssembly());
MiniMantaVehicleAssetLoader.LoadAssets();
MiniMantaVehicleMod miniMantaVehicle = new MiniMantaVehicleMod();
miniMantaVehicle.Patch();
}
public static void SetModFolderDirectory(string qmodsFolderLocation, string modFolderName)
{
QMODS_FOLDER_LOCATION = qmodsFolderLocation;
MOD_FOLDER_NAME = modFolderName;
}
}
}
|
using ScheduleService.DTO;
namespace ScheduleService.Services.AdvancedSearchStrategy
{
public interface IAdvancedSearchStrategy
{
BasicSearchDTO GetSearchParameters();
}
}
|
using UnrealBuildTool;
public class ToolExampleEditor : ModuleRules
{
public ToolExampleEditor(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
PublicDependencyModuleNames.AddRange(new string[]
{
"Core",
"Engine",
"CoreUObject",
"InputCore",
"LevelEditor",
"Slate",
"EditorStyle",
"AssetTools",
"EditorWidgets",
"UnrealEd",
"BlueprintGraph",
"AnimGraph",
"ComponentVisualizers",
"ToolExample",
"PropertyEditor",
"CinematicCamera"
});
PrivateDependencyModuleNames.AddRange(new string[]
{
"Core",
"CoreUObject",
"Engine",
"AppFramework",
"SlateCore",
"AnimGraph",
"UnrealEd",
"KismetWidgets",
"MainFrame",
"PropertyEditor",
"ComponentVisualizers",
"ToolExample",
"CinematicCamera"
});
// Uncomment if you are using Slate UI
// PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });
// Uncomment if you are using online features
// PrivateDependencyModuleNames.Add("OnlineSubsystem");
// To include OnlineSubsystemSteam, add it to the plugins section in your uproject file with the Enabled attribute set to true
}
} |
using Comun.EntityFramework;
using Datos.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Datos.Repositorio
{
internal class DispositivoRepositorio : IDispositivo
{
public object Guardar(object Parametro)
{
try
{
using (Hogar2Entities contexto = new Hogar2Entities())
{
Dispositivos dispositivos = (Dispositivos)Parametro;
Dispositivos resultado = new Dispositivos();
resultado = contexto.Dispositivos.Where(item => item.id == dispositivos.id).FirstOrDefault();
if (resultado == null)
{
contexto.Dispositivos.Add(dispositivos);
contexto.SaveChanges();
return true;
}
else
{
resultado.Descripcion = dispositivos.Descripcion;
resultado.Nombre = dispositivos.Nombre;
contexto.SaveChanges();
return true;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Docller.Core.Models;
namespace Docller.Core.Repository
{
public interface IUserSubscriptionRepository: IRepository
{
void UpdateUser(User user);
}
}
|
using Common;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace FunctionRegression
{
static partial class FunctionRegression
{
static RegressionTaskV0 task = new RegressionTaskV1();
static Form form;
static Series computedFunction;
static HistoryChart history;
static void UpdateCharts()
{
computedFunction.Points.Clear();
for (int i = 0; i < task.Inputs.Length; i++)
computedFunction.Points.Add(new DataPoint(task.Inputs[i][0], task.Outputs[i]));
history.AddRange(task.Errors);
double error;
while (task.Errors.TryDequeue(out error)) ;
}
[STAThread]
static void Main()
{
task.Prepare();
var targetFunction = new Series()
{
ChartType = SeriesChartType.Line,
Color = Color.Red,
BorderWidth = 2
};
for (int i = 0; i < task.Inputs.Length; i++)
targetFunction.Points.Add(new DataPoint(task.Inputs[i][0], task.Answers[i][0]));
computedFunction = new Series()
{
ChartType = SeriesChartType.Line,
Color = Color.Green,
BorderWidth = 2
};
history = new HistoryChart
{
Max = task.MaxError,
DotsCount=200,
Lines =
{
new HistoryChartValueLine
{
DataFunction = { Color = Color.Blue }
}
},
Dock = DockStyle.Bottom
};
form = new Form()
{
Text = task.GetType().Name,
Size = new Size(800, 600),
FormBorderStyle = FormBorderStyle.FixedDialog,
Controls =
{
new Chart
{
ChartAreas =
{
new ChartArea
{
AxisX=
{
Minimum = task.Inputs.Min(z=>z[0]),
Maximum = task.Inputs.Max(z=>z[0])
},
AxisY=
{
Minimum = Math.Min(-1.5,task.Answers.Min(z=>z[0])),
Maximum = Math.Max(1.5, task.Answers.Max(z=>z[0]))
}
}
},
Series = { targetFunction, computedFunction },
Dock= DockStyle.Top
},
history
}
};
task.UpdateCharts += (s, a) => form.BeginInvoke(new Action(UpdateCharts));
new Action(task.Learn).BeginInvoke(null, null);
Application.Run(form);
}
}
}
|
using System;
using ReactMusicStore.Core.Domain.Interfaces.Specification;
namespace ReactMusicStore.Core.Domain.Entities.Specifications.OrderSpecs
{
public class OrderEmailIsRequiredSpec : ISpecification<Order>
{
public bool IsSatisfiedBy(Order order)
{
return !String.IsNullOrEmpty(order.Email) && !String.IsNullOrWhiteSpace(order.Email);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class NewCustomer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string con = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Travels;Integrated Security=True;Pooling=False";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = con;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Customers(username,password,name,email,phone,gender) values(@username,@password,@name,@email,@phone,@gender)", conn);
cmd.Parameters.AddWithValue("@username", TextBox1.Text);
cmd.Parameters.AddWithValue("@password", TextBox2.Text);
cmd.Parameters.AddWithValue("@name", TextBox3.Text);
cmd.Parameters.AddWithValue("@email", TextBox4.Text);
cmd.Parameters.AddWithValue("@phone", TextBox5.Text);
cmd.Parameters.AddWithValue("@gender", DropDownList1.SelectedItem.Text);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
Response.Redirect("~/CustomerLogin.aspx");
}
} |
using System;
using MassTransit;
namespace Meetup.PubSub.Sender
{
using Meetup.PubSub.Messages;
class Program
{
static void Main(string[] args)
{
IBusControl bus = Bus.Factory.CreateUsingRabbitMq(
configurator =>
{
var rabbitMqHost = configurator.Host(
new Uri("rabbitmq://localhost"),
hostConfigurator =>
{
hostConfigurator.Username("server");
hostConfigurator.Password("server");
});
});
bus.Start();
Console.WriteLine("Bus started, enter smth to send command");
var line = Console.ReadLine();
bus.Publish(new SayHiEvent(line));
Console.WriteLine("Published message!");
}
}
public class SayHiEvent : SayHi
{
public SayHiEvent(string name)
{
this.Name = name;
}
public string Name { get; }
}
}
|
namespace iPhoneController.Utils
{
using System;
using System.Net;
public static class NetUtils
{
public static string Get(string url)
{
using (var wc = new WebClient())
{
wc.Proxy = null;
return wc.DownloadString(url);
}
}
}
} |
using System;
using System.Collections.Generic;
using FrontDesk.Core.Aggregates;
using PluralsightDdd.SharedKernel;
using Xunit;
namespace UnitTests.Core.AggregatesEntities.ScheduleTests
{
public class Schedule_Constructor
{
private readonly Guid _scheduleId = Guid.Parse("4a17e702-c20e-4b87-b95b-f915c5a794f7");
private readonly DateTime _startTime = new DateTime(2021, 01, 01, 10, 00, 00);
private readonly DateTime _endTime = new DateTime(2021, 01, 01, 11, 00, 00);
private readonly DateTimeRange _dateRange;
private readonly int _clinicId = 1;
public Schedule_Constructor()
{
_dateRange = new DateTimeRange(_startTime, _endTime);
}
[Fact]
public void CreateConstructor()
{
var appointments = new List<Appointment>();
var schedule = new Schedule(_scheduleId, _dateRange, _clinicId, appointments);
Assert.Equal(_scheduleId, schedule.Id);
Assert.Equal(_startTime, schedule.DateRange.Start);
Assert.Equal(_endTime, schedule.DateRange.End);
Assert.Equal(_clinicId, schedule.ClinicId);
Assert.Equal(appointments, schedule.Appointments);
}
}
}
|
// @9 Dynamic Programming
public class Solution {
public IList<int> LargestDivisibleSubset(int[] nums) {
if (nums.Length == 0) {
return new List<int>();
}
Array.Sort(nums);
List<int> pre = new List<int>();
List<int> sizes = new List<int>();
for (int i = 0; i < nums.Length; i++) {
pre.Add(-1);
sizes.Add(1);
}
for (int i = 0; i < nums.Length; i++) {
int size = sizes[i];
for (int j = 0; j < i; j ++) {
if (nums[i] % nums[j] == 0 && size < sizes[j] + 1) {
size = sizes[j] + 1;
pre[i] = j;
}
}
sizes[i] = size;
}
int max = sizes.Max();
int cursor = sizes.IndexOf(max);
IList<int> res = new List<int>();
while (cursor != -1) {
res.Add(nums[cursor]);
cursor = pre[cursor];
}
// There is no need to reverse. If there is, declare it as a List<int> in line 27.
//res.Reverse();
return res;
}
} |
using Model.Manager;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Clinic_Health.Model
{
public class Soba : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
private int _sifra;
private DateTime _pocetak;
private DateTime _kraj;
private int _kapacitet;
private TypeOfUsage _tip;
private int _zauzetost;
public TypeOfUsage Tip
{
get
{
return _tip;
}
set
{
if (value != _tip)
{
_tip = value;
OnPropertyChanged("Tip");
}
}
}
public int Sifra
{
get
{
return _sifra;
}
set
{
if (value != _sifra)
{
_sifra = value;
OnPropertyChanged("Sifra");
}
}
}
/* public bool Renoviranje
{
get
{
return _renoviranje;
}
set
{
if (value != _renoviranje)
{
_renoviranje = value;
OnPropertyChanged("Renoviranje");
}
}
}*/
public DateTime Pocetak
{
get
{
return _pocetak;
}
set
{
if (value != _pocetak)
{
_pocetak = value;
OnPropertyChanged("Pocetak");
}
}
}
public DateTime Kraj
{
get
{
return _kraj;
}
set
{
if (value != _kraj)
{
_kraj = value;
OnPropertyChanged("Kraj");
}
}
}
public int Kapacitet
{
get
{
return _kapacitet;
}
set
{
if (value != _kapacitet)
{
_kapacitet = value;
OnPropertyChanged("Kapacitet");
}
}
}
public int Zauzetost
{
get
{
return _zauzetost;
}
set
{
if (value != _zauzetost)
{
_zauzetost = value;
OnPropertyChanged("Zauzetost");
}
}
}
}
}
|
using System;
using System.Linq;
using Uintra.Core.Member.Abstractions;
using Uintra.Core.Member.Entities;
using Uintra.Core.Member.Services;
using Uintra.Features.Notification.Entities;
using Uintra.Features.Notification.Entities.Base;
using Uintra.Features.Notification.Models;
using Uintra.Features.Notification.Models.NotifierTemplates;
using Uintra.Features.Notification.Services;
using Uintra.Infrastructure.Extensions;
using static Uintra.Features.Notification.Constants.TokensConstants;
namespace Uintra.Features.Notification
{
public class UiNotificationModelMapper : INotificationModelMapper<UiNotifierTemplate, UiNotificationMessage>
{
private readonly IIntranetMemberService<IntranetMember> _intranetMemberService;
public UiNotificationModelMapper(IIntranetMemberService<IntranetMember> intranetMemberService)
{
_intranetMemberService = intranetMemberService;
}
public UiNotificationMessage Map(INotifierDataValue notifierData, UiNotifierTemplate template, IIntranetMember receiver)
{
var message = new UiNotificationMessage
{
ReceiverId = receiver.Id,
IsPinned = notifierData.IsPinned,
IsPinActual = notifierData.IsPinActual,
//IsDesktopNotificationEnabled = template.IsDesktopNotificationEnabled
};
(string, string)[] tokens;
switch (notifierData)
{
case ActivityNotifierDataModel model:
message.NotificationType = model.NotificationType;
message.Url = model.Url;
message.NotifierId = model.NotifierId;
tokens = new[]
{
(ActivityTitle, model.Title),
(ActivityType, model.ActivityType.ToString()),
(FullName, _intranetMemberService.Get(model.NotifierId).DisplayedName),
(NotifierFullName, receiver.DisplayedName),
(NotificationType, model.NotificationType.ToString().SplitOnUpperCaseLetters())
};
break;
case ActivityReminderDataModel model:
message.NotificationType = model.NotificationType;
message.Url = model.Url;
tokens = new[]
{
(ActivityTitle, model.Title),
(ActivityType, model.ActivityType.ToString()),
(StartDate, model.StartDate.ToShortDateString()),
(FullName, receiver.DisplayedName),
(NotificationType, model.NotificationType.ToString().SplitOnUpperCaseLetters())
};
break;
case CommentNotifierDataModel model:
message.NotificationType = model.NotificationType;
message.Url = model.Url;
message.NotifierId = model.NotifierId;
tokens = new[]
{
(ActivityTitle, model.Title),
(FullName, _intranetMemberService.Get(model.NotifierId).DisplayedName),
(NotificationType, model.NotificationType.ToString().SplitOnUpperCaseLetters())
};
break;
case LikesNotifierDataModel model:
message.NotificationType = model.NotificationType;
message.Url = model.Url;
message.NotifierId = model.NotifierId;
tokens = new[]
{
(ActivityTitle, model.Title),
(ActivityType, model.ActivityType.ToString()),
(FullName, _intranetMemberService.Get(model.NotifierId).DisplayedName),
(CreatedDate, model.CreatedDate.ToShortDateString()),
(NotificationType, model.NotificationType.ToString().SplitOnUpperCaseLetters())
};
break;
case UserMentionNotifierDataModel model:
message.NotificationType = model.NotificationType;
message.Url = model.Url;
message.NotifierId = model.NotifierId;
tokens = new[]
{
(ActivityTitle, model.Title),
(FullName, _intranetMemberService.Get(model.ReceiverId).DisplayedName),
(TaggedBy, _intranetMemberService.Get(model.NotifierId).DisplayedName),
(NotificationType, model.NotificationType.ToString().SplitOnUpperCaseLetters())
};
break;
case GroupInvitationDataModel model:
message.NotificationType = model.NotificationType;
message.Url = model.Url;
message.NotifierId = model.NotifierId;
tokens = new[]
{
(ActivityTitle, model.Title),
(FullName, _intranetMemberService.Get(model.ReceiverId).DisplayedName),
(Url, model.Url.ToString()),
(Title, model.Title),
(TaggedBy, _intranetMemberService.Get(model.NotifierId).DisplayedName),
(NotificationType, model.NotificationType.ToString().SplitOnUpperCaseLetters())
};
break;
default:
throw new IndexOutOfRangeException();
}
message.Message = ReplaceTokens(template.Message, tokens);
return message;
}
//public async Task<UiNotificationMessage> MapAsync(INotifierDataValue notifierData, UiNotifierTemplate template, IIntranetMember receiver)
//{
// var message = new UiNotificationMessage
// {
// ReceiverId = receiver.Id,
// IsPinned = notifierData.IsPinned,
// IsPinActual = notifierData.IsPinActual,
// //IsDesktopNotificationEnabled = template.IsDesktopNotificationEnabled
// };
// (string, string)[] tokens;
// switch (notifierData)
// {
// case ActivityNotifierDataModel model:
// message.NotificationType = model.NotificationType;
// message.Url = model.Url;
// message.NotifierId = model.NotifierId;
// tokens = new[]
// {
// (ActivityTitle, model.Title),
// (ActivityType, model.ActivityType.ToString()),
// (FullName, (await _intranetMemberService.GetAsync(model.NotifierId)).DisplayedName),
// (NotifierFullName, receiver.DisplayedName),
// (NotificationType, model.NotificationType.ToString().SplitOnUpperCaseLetters())
// };
// break;
// case ActivityReminderDataModel model:
// message.NotificationType = model.NotificationType;
// message.Url = model.Url;
// tokens = new[]
// {
// (ActivityTitle, model.Title),
// (ActivityType, model.ActivityType.ToString()),
// (StartDate, model.StartDate.ToShortDateString()),
// (FullName, receiver.DisplayedName),
// (NotificationType, model.NotificationType.ToString().SplitOnUpperCaseLetters())
// };
// break;
// case CommentNotifierDataModel model:
// message.NotificationType = model.NotificationType;
// message.Url = model.Url;
// message.NotifierId = model.NotifierId;
// tokens = new[]
// {
// (ActivityTitle, model.Title),
// (FullName, (await _intranetMemberService.GetAsync(model.NotifierId)).DisplayedName),
// (NotificationType, model.NotificationType.ToString().SplitOnUpperCaseLetters())
// };
// break;
// case LikesNotifierDataModel model:
// message.NotificationType = model.NotificationType;
// message.Url = model.Url;
// message.NotifierId = model.NotifierId;
// tokens = new[]
// {
// (ActivityTitle, model.Title),
// (ActivityType, model.ActivityType.ToString()),
// (FullName, (await _intranetMemberService.GetAsync(model.NotifierId)).DisplayedName),
// (CreatedDate, model.CreatedDate.ToShortDateString()),
// (NotificationType, model.NotificationType.ToString().SplitOnUpperCaseLetters())
// };
// break;
// case UserMentionNotifierDataModel model:
// message.NotificationType = model.NotificationType;
// message.Url = model.Url;
// message.NotifierId = model.NotifierId;
// tokens = new[]
// {
// (ActivityTitle, model.Title),
// (FullName, (await _intranetMemberService.GetAsync(model.ReceiverId)).DisplayedName),
// (TaggedBy, (await _intranetMemberService.GetAsync(model.NotifierId)).DisplayedName),
// (NotificationType, model.NotificationType.ToString().SplitOnUpperCaseLetters())
// };
// break;
// case GroupInvitationDataModel model:
// message.NotificationType = model.NotificationType;
// message.Url = model.Url;
// message.NotifierId = model.NotifierId;
// tokens = new[]
// {
// (ActivityTitle, model.Title),
// (FullName, (await _intranetMemberService.GetAsync(model.ReceiverId)).DisplayedName),
// (Url, model.Url),
// (Title, model.Title),
// (TaggedBy, (await _intranetMemberService.GetAsync(model.NotifierId)).DisplayedName),
// (NotificationType, model.NotificationType.ToString().SplitOnUpperCaseLetters())
// };
// break;
// default:
// throw new IndexOutOfRangeException();
// }
// message.Message = ReplaceTokens(template.Message, tokens);
// return message;
//}
private string ReplaceTokens(string source, params (string token, string value)[] replacePairs) =>
replacePairs
.Aggregate(source ?? string.Empty, (acc, pair) => acc.Replace(pair.token, pair.value));
}
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Breeze;
using Breeze.AssetTypes;
using Breeze.Screens;
using Microsoft.Xna.Framework;
namespace BreezeDemo.Screens.Demo1
{
public class Demo1Screen : BaseScreen
{
private Demo1VirtualizedContext vm;
public override async Task Initialise()
{
await base.Initialise();
LoadXAML();
this.RootAsset.FixBinds();
vm = new Demo1VirtualizedContext();
this.RootContext = vm;
this.RootContext.Screen = this;
this.IsFullScreen = true;
UpdateAllAssets();
Update(new GameTime());
// SetBindings();
}
public void TestButtonClick(ButtonClickEventArgs args)
{
ButtonAsset button = args.Sender as ButtonAsset;
Demo1VirtualizedContext context = (Demo1VirtualizedContext)button.VirtualizedDataContext;
Debug.WriteLine("OH HAI THERE!");
context.TestText = context.TestText + "!";
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Boid : MonoBehaviour
{
public static List<Boid> allBoids = new List<Boid>();
BoidBehavior[] boidBehaviors;
public float speed = 10f;
public Rigidbody2D rigid;
public Vector2 dir;
public float smoothingTime = 0.3f;
Vector2 velSmoothing;
public float boidRange = 20;
public List<Boid> closestBoids = new List<Boid>();
public Color debugColor;
public bool handleDirection = true;
private void Start() {
rigid = GetComponent<Rigidbody2D>();
boidBehaviors = GetComponentsInChildren<BoidBehavior>();
}
private void OnEnable() {
allBoids.Add(this);
StartCoroutine(FindClosestBoids());
}
private void OnDisable() {
allBoids.Remove(this);
}
private void OnDestroy() {
allBoids.Remove(this);
}
private void FixedUpdate() {
dir = AverageDir();
Debug.DrawRay(transform.position,dir,debugColor,0.3f);
Vector2 velocity = rigid.velocity;
Vector2 goalVelocity = dir * speed;
velocity.x = Mathf.SmoothDamp(velocity.x,goalVelocity.x,ref velSmoothing.x,smoothingTime);
velocity.y = Mathf.SmoothDamp(velocity.y,goalVelocity.y,ref velSmoothing.y,smoothingTime);
rigid.velocity = velocity;
if(handleDirection)
transform.up = dir;
}
public Vector2 AverageDir(){
Vector2 totalDir = Vector2.zero;
float totalWeight = 0;
for(int i=0;i<boidBehaviors.Length;i++){
BoidBehavior boidBehavior = boidBehaviors[i];
if(!boidBehavior.enabled)
continue;
if(!boidBehavior.UpdateDirection())
continue;
Debug.DrawRay(transform.position,boidBehavior.dir,boidBehavior.debugColor,0.3f);
Vector2 weightedDir = boidBehavior.dir * boidBehavior.weight;
totalDir += weightedDir;
totalWeight += boidBehavior.weight;
}
if((totalWeight) ==0)
return totalDir;
return totalDir / totalWeight;
}
private void OnDrawGizmos() {
Gizmos.color= debugColor;
Gizmos.DrawRay(transform.position,dir);
Gizmos.DrawWireSphere(transform.position,boidRange);
}
public IEnumerator FindClosestBoids()
{
while(true)
{
closestBoids = new List<Boid>();
foreach(Boid boid in allBoids){
if(boid == this)
continue;
Vector2 difference = (boid.transform.position - transform.position);
float distance = difference.magnitude;
if(distance < boidRange){
closestBoids.Add(boid);
}
}
yield return new WaitForSecondsRealtime(0.5f);
}
}
}
|
using RetenionApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace RetenionApp.Services
{
public interface IRollingRetentionProvider : IStatisticsProvider
{
RollingRetention GetRollingRetention(IEnumerable<User> users);
}
}
|
using System.Collections.Generic;
namespace DFC.ServiceTaxonomy.GraphVisualiser.Models.Owl
{
public partial class Filter
{
public List<CheckBox> CheckBox { get; set; } = new List<CheckBox>();
public string? DegreeSliderValue { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ComplejoDeCines.Models
{
public class Sede
{
public int IdSede { get; set; }
public string Nombre { get; set; }
public string Direccion { get; set; }
public decimal PrecioGeneral { get; set; }
}
} |
namespace Docller.Core.Images
{
public class NullImageConverter : IImageConverter
{
public void Convert(string inputFile, string outputPngfile)
{
//do nothing
}
public string Extension { get { return string.Empty; } }
}
} |
using System;
using System.Collections;
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System.Windows.Forms;
using System.Text;
using System.Diagnostics;
using System.Linq;
using System.Collections.Generic;
using System.Runtime.ExceptionServices;
namespace Kingdee.CAPP.Solidworks.RoutingPlugIn
{
public class DocumentEventHandler
{
protected ISldWorks iSwApp;
protected ModelDoc2 document;
protected SwAddin userAddin;
protected Hashtable openModelViews;
public DocumentEventHandler(ModelDoc2 modDoc, SwAddin addin)
{
document = modDoc;
userAddin = addin;
iSwApp = (ISldWorks)userAddin.SwApp;
openModelViews = new Hashtable();
}
virtual public bool AttachEventHandlers()
{
return true;
}
virtual public bool DetachEventHandlers()
{
return true;
}
public bool ConnectModelViews()
{
IModelView mView;
mView = (IModelView)document.GetFirstModelView();
while (mView != null)
{
if (!openModelViews.Contains(mView))
{
DocView dView = new DocView(userAddin, mView, this);
dView.AttachEventHandlers();
openModelViews.Add(mView, dView);
}
mView = (IModelView)mView.GetNext();
}
return true;
}
public bool DisconnectModelViews()
{
//Close events on all currently open docs
DocView dView;
int numKeys;
numKeys = openModelViews.Count;
if (numKeys == 0)
{
return false;
}
object[] keys = new object[numKeys];
//Remove all ModelView event handlers
openModelViews.Keys.CopyTo(keys, 0);
foreach (ModelView key in keys)
{
dView = (DocView)openModelViews[key];
dView.DetachEventHandlers();
openModelViews.Remove(key);
dView = null;
}
return true;
}
public bool DetachModelViewEventHandler(ModelView mView)
{
DocView dView;
if (openModelViews.Contains(mView))
{
dView = (DocView)openModelViews[mView];
openModelViews.Remove(mView);
mView = null;
dView = null;
}
return true;
}
}
public class PartEventHandler : DocumentEventHandler
{
PartDoc doc;
bool isRelation = false;
string partName = string.Empty;
List<string> routingIdList = new List<string>();
ProcessFileRoutingContext pfr = null;
public PartEventHandler(ModelDoc2 modDoc, SwAddin addin)
: base(modDoc, addin)
{
doc = (PartDoc)document;
string partName = modDoc.GetPathName().Substring(
modDoc.GetPathName().LastIndexOf('\\') + 1);
GlobalCache.Instance.ComponetName = partName;
this.partName = partName;
pfr = new ProcessFileRoutingContext(DbConfig.Connection);
List<ProcessFileRouting> qlist = null;
try
{
qlist = (from p in pfr.ProcessFileRoutings
where p.ProcessFileName == partName
select p).ToList<ProcessFileRouting>();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
Dictionary<string, bool> featureDic = new Dictionary<string, bool>();
Feature feature = modDoc.FirstFeature();
ModelDocExtension swModelExt = modDoc.Extension;
while (feature != null)
{
string featureTypeName = feature.GetTypeName();
string featureName = feature.Name;
if (featureTypeName == "ProfileFeature")
{
if (!featureDic.ContainsKey(featureName))
{
featureDic.Add(featureName,false);
}
}
feature = (Feature)feature.GetNextFeature();
}
GlobalCache.Instance.SketchStatusDic = featureDic;
List<string> routingIdList = new List<string>();
foreach (var q in qlist)
{
routingIdList.Add(q.RoutingId);
}
this.routingIdList = routingIdList;
if (routingIdList.Count > 0)
{
///Exist the correlation component to routing
Routing(modDoc, iSwApp, routingIdList);
}
}
ProcessLine frm;
/// <summary>
/// Add form to taskpanel
/// </summary>
public void Routing(IModelDoc2 doc,ISldWorks swApp, List<string> routingIds)
{
ITaskpaneView pTaskPanView = null;
if (GlobalCache.Instance.PTaskPanView == null)
{
pTaskPanView = iSwApp.CreateTaskpaneView2("", "关联工艺路线");
GlobalCache.Instance.PTaskPanView = pTaskPanView;
}
else
{
pTaskPanView = GlobalCache.Instance.PTaskPanView;
}
frm = new ProcessLine(doc, swApp, routingIds);
pTaskPanView.DisplayWindowFromHandle(frm.Handle.ToInt32());
}
override public bool AttachEventHandlers()
{
doc.DestroyNotify += new DPartDocEvents_DestroyNotifyEventHandler(OnDestroy);
doc.NewSelectionNotify += new DPartDocEvents_NewSelectionNotifyEventHandler(OnNewSelection);
ConnectModelViews();
return true;
}
override public bool DetachEventHandlers()
{
doc.DestroyNotify -= new DPartDocEvents_DestroyNotifyEventHandler(OnDestroy);
doc.NewSelectionNotify -= new DPartDocEvents_NewSelectionNotifyEventHandler(OnNewSelection);
DisconnectModelViews();
userAddin.DetachModelEventHandler(document);
return true;
}
//Event Handlers
public int OnDestroy()
{
GlobalCache.Instance.OperId = string.Empty;
ProcessLine.CurrentProcessLine = null;
if (frm != null)
{
frm.Dispose();
frm = null;
}
DetachEventHandlers();
return 0;
}
[HandleProcessCorruptedStateExceptions]
public int OnNewSelection()
{
//ModelDoc2 swDoc = null;
//Feature swFeature;
//swDoc = iSwApp.ActiveDoc;
//SelectionMgr swSelMgr;
//swSelMgr = (SelectionMgr)swDoc.SelectionManager;
//Feature feature = swDoc.FirstFeature();
//Feature nextFeature = null;
//bool reValue = false;
//bool isSuppressSet = false;
////long suppressState = 0;
//string featType = string.Empty;
//Feature swFeat = default(Feature);
//ModelDocExtension swModDocExt = default(ModelDocExtension);
//Component2 swComp = default(Component2);
//object vModelPathName = null;
//int selObjType = 0;
//int nRefCount = 0;
//selObjType = swSelMgr.GetSelectedObjectType3(1, -1); ;
//if (selObjType == (int)swSelectType_e.swSelBODYFEATURES)
//{
// swFeature = swSelMgr.GetSelectedObject6(1, -1);
// if (swFeature == null) return 0;
// //MessageBox.Show(swFeature.Name);
//}
//else if (selObjType == (int)swSelectType_e.swSelCOMPONENTS)
//{
// swComp = (Component2)swSelMgr.GetSelectedObject6(1, -1);
// if (swComp == null) return 0;
// //MessageBox.Show(swComp.GetPathName());
// swFeat = swComp.FirstFeature();
// EventHelper eh = EventHelper.GetInstance();
// SelectedEventArgs arg = new SelectedEventArgs();
// arg.ComponentName = swComp.Name;
// eh.RasieTesting(arg);
//}
//else if (selObjType == (int)swSelectType_e.swSelSKETCHES)
//{
// swFeat = (Feature)swSelMgr.GetSelectedObject6(1, -1);
// if (swFeat == null) return 0;
// //if (!isRelation)
// //{
// // ///First relate component with process routing
// // ///Then relate sketch with process
// // DialogResult result = MessageBox.Show("该零件还没有和工艺路线进行关联,是否现在关联?",
// // "关联工艺路线和零件",
// // MessageBoxButtons.YesNoCancel,
// // MessageBoxIcon.Exclamation);
// // if (result == DialogResult.Yes)
// // {
// // /// relate component with process routing
// // PartRelProcessLing newPartRelProcessLing = new PartRelProcessLing(partName, swDoc);
// // newPartRelProcessLing.Show();
// // }
// //}
// //else
// //{
// // /// relate sketch with process
// // var qlist = from p in pfr.SketchFileProcesses
// // where routingIdList.Contains(p.RoutingId) && p.SketchName == swFeat.Name
// // select p;
// // if(qlist.Count() <= 0)
// // {
// // //如果没有找到就提示进行关联
// // DialogResult result = MessageBox.Show("该草图还没有和工序进行关联,是否现在关联?",
// // "关联工序和草图",
// // MessageBoxButtons.YesNoCancel,
// // MessageBoxIcon.Exclamation);
// // if (result == DialogResult.Yes)
// // {
// // /// relate component with process routing
// // SketchRefProcess sketchRefProcess = new SketchRefProcess(
// // routingIdList.FirstOrDefault().ToString(),
// // swFeat.Name,
// // partName);
// // sketchRefProcess.ShowDialog();
// // }
// // }
// // else
// // {
// // /// 如果找到就显示
// // /// 事件传递参数
// // SelectedEventArgs e = new SelectedEventArgs();
// // e.SketchName = swFeat.Name;
// // e.ComponentName = partName;
// // ProcessLine.CurrentProcessLine.SeletedProcessByComponentName(e);
// // }
// //}
// nRefCount = swFeat.ListExternalFileReferencesCount();
//}
return 0;
}
}
public class AssemblyEventHandler : DocumentEventHandler
{
AssemblyDoc doc;
SwAddin swAddin;
public AssemblyEventHandler(ModelDoc2 modDoc, SwAddin addin)
: base(modDoc, addin)
{
doc = (AssemblyDoc)document;
swAddin = addin;
}
override public bool AttachEventHandlers()
{
doc.DestroyNotify += new DAssemblyDocEvents_DestroyNotifyEventHandler(OnDestroy);
doc.NewSelectionNotify += new DAssemblyDocEvents_NewSelectionNotifyEventHandler(OnNewSelection);
doc.ComponentStateChangeNotify2 += new DAssemblyDocEvents_ComponentStateChangeNotify2EventHandler(ComponentStateChangeNotify2);
doc.ComponentStateChangeNotify += new DAssemblyDocEvents_ComponentStateChangeNotifyEventHandler(ComponentStateChangeNotify);
doc.ComponentVisualPropertiesChangeNotify += new DAssemblyDocEvents_ComponentVisualPropertiesChangeNotifyEventHandler(ComponentVisualPropertiesChangeNotify);
doc.ComponentDisplayStateChangeNotify += new DAssemblyDocEvents_ComponentDisplayStateChangeNotifyEventHandler(ComponentDisplayStateChangeNotify);
ConnectModelViews();
return true;
}
override public bool DetachEventHandlers()
{
doc.DestroyNotify -= new DAssemblyDocEvents_DestroyNotifyEventHandler(OnDestroy);
doc.NewSelectionNotify -= new DAssemblyDocEvents_NewSelectionNotifyEventHandler(OnNewSelection);
doc.ComponentStateChangeNotify2 -= new DAssemblyDocEvents_ComponentStateChangeNotify2EventHandler(ComponentStateChangeNotify2);
doc.ComponentStateChangeNotify -= new DAssemblyDocEvents_ComponentStateChangeNotifyEventHandler(ComponentStateChangeNotify);
doc.ComponentVisualPropertiesChangeNotify -= new DAssemblyDocEvents_ComponentVisualPropertiesChangeNotifyEventHandler(ComponentVisualPropertiesChangeNotify);
doc.ComponentDisplayStateChangeNotify -= new DAssemblyDocEvents_ComponentDisplayStateChangeNotifyEventHandler(ComponentDisplayStateChangeNotify);
DisconnectModelViews();
userAddin.DetachModelEventHandler(document);
return true;
}
//Event Handlers
public int OnDestroy()
{
DetachEventHandlers();
return 0;
}
public int OnNewSelection()
{
//var swSelMgr = document.SelectionManager;
//var f = swSelMgr.GetSelectedObject6(1, 0);
ModelDoc2 swDoc = null;
Feature swFeature;
swDoc = iSwApp.ActiveDoc;
SelectionMgr swSelMgr;
swSelMgr = (SelectionMgr)swDoc.SelectionManager;
Feature swFeat = default(Feature);
ModelDocExtension swModDocExt = default(ModelDocExtension);
Component2 swComp = default(Component2);
object vModelPathName = null;
int selObjType = 0;
int nRefCount = 0;
selObjType = swSelMgr.GetSelectedObjectType3(1, -1); ;
if (selObjType == (int)swSelectType_e.swSelBODYFEATURES)
{
swFeature = swSelMgr.GetSelectedObject6(1, 1);
}
else if (selObjType == (int)swSelectType_e.swSelCOMPONENTS)
{
swComp = (Component2)swSelMgr.GetSelectedObjectsComponent3(1, -1);
if (swComp == null) return 0;
//MessageBox.Show(swComp.GetPathName());
swFeat = swComp.FirstFeature();
EventHelper eh = EventHelper.GetInstance();
SelectedEventArgs arg = new SelectedEventArgs();
arg.ComponentName = swComp.GetPathName();
eh.RasieTesting(arg);
//display feature's sensor
//MessageBox.Show(swFeat.Name);
}
else if (selObjType == (int)swSelectType_e.swSelSKETCHES)
{
swFeat = (Feature)swSelMgr.GetSelectedObject6(1, -1);
nRefCount = swFeat.ListExternalFileReferencesCount();
}
//Component2 swComp = null;
//swComp = (Component2)swDwgComp.Component;
//ModelDoc2 swCompModDoc = null;
//swCompModDoc = (ModelDoc2)swComp.GetModelDoc2();
//Debug.Print("dsfasdf");
//var swSelMgr = modelDoc2.SelectionManager;
//var swCompEnt = swSelMgr.GetSelectedObject6(1, 0);
#region 递归输出Feature.Name
//StringBuilder sb = new StringBuilder();
//Feature feature = modelDoc2.FirstFeature();
//Feature nextFeature = null;
//sb.Append("名称:" + feature.Name + "----类型:" + feature.GetTypeName());
//while (feature != null)
//{
// nextFeature = (Feature)feature.GetNextFeature();
// if (nextFeature == null) { break; }
// sb.Append("名称:" + nextFeature.Name + "----类型:" + feature.GetTypeName());
// feature = null;
// feature = nextFeature;
// nextFeature = null;
//}
#endregion
#region 类型转换出错
//ModelDocExtension swModelDocExt = default(ModelDocExtension);
//SelectionMgr swSelMgr = default(SelectionMgr);
//Feature swFeat = default(Feature);
//string featName = null;
//string featType = null;
//swSelMgr = (SelectionMgr)document.SelectionManager;
//swModelDocExt = (ModelDocExtension)document.Extension;
//// Get the selected feature
//swFeat = (Feature)swSelMgr.GetSelectedObject6(1, -1);
//document.ClearSelection2(true);
//// Get the feature's type and name
//featName = swFeat.GetNameForSelection(out featType);
//swModelDocExt.SelectByID2(featName, featType, 0, 0, 0, true, 0, null, 0);
//MessageBox.Show(featName + "" + featType);
#endregion
return 0;
}
//attach events to a component if it becomes resolved
protected int ComponentStateChange(object componentModel, short newCompState)
{
ModelDoc2 modDoc = (ModelDoc2)componentModel;
swComponentSuppressionState_e newState = (swComponentSuppressionState_e)newCompState;
switch (newState)
{
case swComponentSuppressionState_e.swComponentFullyResolved:
{
if ((modDoc != null) & !this.swAddin.OpenDocs.Contains(modDoc))
{
this.swAddin.AttachModelDocEventHandler(modDoc);
}
break;
}
case swComponentSuppressionState_e.swComponentResolved:
{
if ((modDoc != null) & !this.swAddin.OpenDocs.Contains(modDoc))
{
this.swAddin.AttachModelDocEventHandler(modDoc);
}
break;
}
}
return 0;
}
protected int ComponentStateChange(object componentModel)
{
ComponentStateChange(componentModel, (short)swComponentSuppressionState_e.swComponentResolved);
return 0;
}
public int ComponentStateChangeNotify2(object componentModel, string CompName, short oldCompState, short newCompState)
{
return ComponentStateChange(componentModel, newCompState);
}
int ComponentStateChangeNotify(object componentModel, short oldCompState, short newCompState)
{
return ComponentStateChange(componentModel, newCompState);
}
int ComponentDisplayStateChangeNotify(object swObject)
{
Component2 component = (Component2)swObject;
ModelDoc2 modDoc = (ModelDoc2)component.GetModelDoc();
//StringBuilder sb = new StringBuilder();
//sb.Append(modDoc.SceneName + "----" + modDoc.SceneUserName);
return ComponentStateChange(modDoc);
}
int ComponentVisualPropertiesChangeNotify(object swObject)
{
Component2 component = (Component2)swObject;
ModelDoc2 modDoc = (ModelDoc2)component.GetModelDoc();
return ComponentStateChange(modDoc);
}
}
public class DrawingEventHandler : DocumentEventHandler
{
DrawingDoc doc;
public DrawingEventHandler(ModelDoc2 modDoc, SwAddin addin)
: base(modDoc, addin)
{
doc = (DrawingDoc)document;
}
override public bool AttachEventHandlers()
{
doc.DestroyNotify += new DDrawingDocEvents_DestroyNotifyEventHandler(OnDestroy);
doc.NewSelectionNotify += new DDrawingDocEvents_NewSelectionNotifyEventHandler(OnNewSelection);
ConnectModelViews();
return true;
}
override public bool DetachEventHandlers()
{
doc.DestroyNotify -= new DDrawingDocEvents_DestroyNotifyEventHandler(OnDestroy);
doc.NewSelectionNotify -= new DDrawingDocEvents_NewSelectionNotifyEventHandler(OnNewSelection);
DisconnectModelViews();
userAddin.DetachModelEventHandler(document);
return true;
}
//Event Handlers
public int OnDestroy()
{
DetachEventHandlers();
return 0;
}
public int OnNewSelection()
{
return 0;
}
}
public class DocView
{
ISldWorks iSwApp;
SwAddin userAddin;
ModelView mView;
DocumentEventHandler parent;
public DocView(SwAddin addin, IModelView mv, DocumentEventHandler doc)
{
userAddin = addin;
mView = (ModelView)mv;
iSwApp = (ISldWorks)userAddin.SwApp;
parent = doc;
}
public bool AttachEventHandlers()
{
mView.DestroyNotify2 += new DModelViewEvents_DestroyNotify2EventHandler(OnDestroy);
mView.RepaintNotify += new DModelViewEvents_RepaintNotifyEventHandler(OnRepaint);
return true;
}
public bool DetachEventHandlers()
{
mView.DestroyNotify2 -= new DModelViewEvents_DestroyNotify2EventHandler(OnDestroy);
mView.RepaintNotify -= new DModelViewEvents_RepaintNotifyEventHandler(OnRepaint);
parent.DetachModelViewEventHandler(mView);
return true;
}
//EventHandlers
public int OnDestroy(int destroyType)
{
switch (destroyType)
{
case (int)swDestroyNotifyType_e.swDestroyNotifyHidden:
return 0;
case (int)swDestroyNotifyType_e.swDestroyNotifyDestroy:
return 0;
}
return 0;
}
public int OnRepaint(int repaintType)
{
//单击每个目录触发的
//MessageBox.Show("123123");
return 0;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Checkout : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["CartLength"] == null)
{
// Error message
setuperror();
}
else
{
// Database Context
ShopNowDataContext db = new ShopNowDataContext();
// Initial variables
Checkout_info.Text = "";
double total = 0;
Guid guid = Guid.NewGuid();
// Cycle through whole cart
for (int i = 1; i <= Convert.ToInt32(Session["CartLength"]); i++)
{
// Get current cart items
string[] cartitems = (string[])Session["CartItem" + i];
// Pull corresponding row given the selected value
O OS = db.Os.FirstOrDefault(row => row.ID.Equals(cartitems[0]));
CPU cPU = db.CPUs.FirstOrDefault(row => row.ID.Equals(cartitems[1]));
RAM rAM = db.RAMs.FirstOrDefault(row => row.ID.Equals(cartitems[2]));
HardDrive hardDrive = db.HardDrives.FirstOrDefault(row => row.ID.Equals(cartitems[3]));
Monitor monitor = db.Monitors.FirstOrDefault(row => row.ID.Equals(cartitems[4]));
SoundCard soundCard = db.SoundCards.FirstOrDefault(row => row.ID.Equals(cartitems[5]));
// Format correctly
Checkout_info.Text += "<br />PC #" + i + "<br /> " +
OS.Name + "<br /> " +
cPU.Name + "<br /> " +
rAM.Name + "<br /> " +
hardDrive.Name + "<br /> " +
monitor.Name + "<br /> " +
soundCard.Name + "<br /> " +
cartitems[6] + "<br />";
// Find total
total += Convert.ToDouble(cartitems[6].Substring(2, cartitems[6].Length - 2));
// Create order item for the info to be inserted
Guid internal_guid = Guid.NewGuid();
Order order = new Order();
order.Order_ID = guid;
order.InternalComp_ID = internal_guid;
order.OS_ID = OS.ID;
order.CPU_ID = cPU.ID;
order.RAM_ID = rAM.ID;
order.HardDrive_ID = hardDrive.ID;
order.Monitor_ID = monitor.ID;
order.SoundCard_ID = soundCard.ID;
order.Cost = cartitems[6].Substring(2, cartitems[6].Length - 2);
// Check if Guest or logged in
if (Session["Username"] == null)
{
order.Username = "";
}
else
{
order.Username = Session["Username"].ToString();
}
// Insert row
db.Orders.InsertOnSubmit(order);
}
// Formatting
Checkout_info.Text += "<br />";
Checkout_info.Text += "Total: " + total;
Checkout_Label.Text = "Thank you for your purchase!";
// Reset Session data and submit database changes
Session["CartLength"] = null;
db.SubmitChanges();
}
}
protected void setuperror()
{
// Hide info and Error message
Checkout_Label.Text = "Please go through the proper channels to obtain this page";
Checkout_info.Visible = false;
}
} |
using System;
using System.Collections;
using System.Configuration;
using System.Data;
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 CIPMSBC;
using CIPMSBC.Eligibility;
public partial class NLIntermediate : System.Web.UI.Page
{
CamperApplication CamperAppl = new CamperApplication();
protected void Page_Init(object sender, EventArgs e)
{
btnSaveandExit.Click += new EventHandler(btnSaveandExit_Click);
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnPrevious_Click(object sender, EventArgs e)
{
Response.Redirect("~/Enrollment/Step1_NL.aspx");
}
protected void btnReturnAdmin_Click(object sender, EventArgs e)
{
string strRedirURL;
try
{
strRedirURL = ConfigurationManager.AppSettings["AdminRedirURL"].ToString();
Response.Redirect(strRedirURL);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
void btnSaveandExit_Click(object sender, EventArgs e)
{
try
{
string strRedirURL;
strRedirURL = Master.SaveandExitURL;
if (Master.IsCamperUser == "Yes")
{
General oGen = new General();
if (oGen.IsApplicationSubmitted(Session["FJCID"].ToString()))
{
Response.Redirect(strRedirURL);
}
else
{
string strScript = "<script language=javascript>openThis(); window.location='" + strRedirURL + "';</script>";
if (!ClientScript.IsStartupScriptRegistered("clientScript"))
{
ClientScript.RegisterStartupScript(Page.GetType(), "clientScript", strScript);
}
}
}
else
{
Response.Redirect(strRedirURL);
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
protected void btnNext_Click(object sender, EventArgs e)
{
string url = (string)Session["nxtUrl"];
Response.Redirect(url);
}
}
|
using System;
using CC.Mobile.Services.Common;
using Android.Content;
using Android.Widget;
using Android.App;
namespace CC.Mobile.Services
{
public class ShareService : IShareService
{
Context context;
public ShareService (Context context)
{
this.context = context;
}
public void Share (string subject, string text)
{
var shareInent = new Intent (Android.Content.Intent.ActionSend);
shareInent.SetType ("text/plain");
shareInent.AddFlags (ActivityFlags.ClearWhenTaskReset);
shareInent.PutExtra (Intent.ExtraSubject, subject);
shareInent.PutExtra (Intent.ExtraText, text);
context.StartActivity (Intent.CreateChooser (shareInent, "Share app!"));
}
public void Email (string email, string subject, string text){
Email (email, String.Empty, subject, text);
}
public void Email (string email, string cc, string subject, string text){
var parts = Android.Net.Uri.FromParts ("mailto", string.Empty, null);
Intent emailIntent = new Intent (Intent.ActionSendto, parts);
emailIntent.PutExtra (Intent.ExtraEmail, new string[]{ email });
if (!string.IsNullOrEmpty (cc)) {
emailIntent.PutExtra (Intent.ExtraCc, cc);
}
emailIntent.PutExtra (Intent.ExtraSubject, subject);
emailIntent.PutExtra (Intent.ExtraText, text);
try {
var intent = Intent.CreateChooser (emailIntent, "Send mail...");
intent.AddFlags (ActivityFlags.NewTask);
context.StartActivity (intent);
} catch (Android.Content.ActivityNotFoundException) {
Toast.MakeText (context, "There is no email client installed.", ToastLength.Long).Show ();
}
}
public void Sms (string phone, string message)
{
Intent smsIntent = new Intent (Intent.ActionView);
smsIntent.PutExtra ("sms_body", "default content");
smsIntent.PutExtra ("address", new String[]{ phone });
smsIntent.SetType ("vnd.android-dir/mms-sms");
smsIntent.AddFlags (ActivityFlags.NewTask);
context.StartActivity (smsIntent);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace St.Eg.M1.Ex1.OOP.Model4
{
public class OrderItem : EntityBase
{
public Product Product { get; set; }
public int Quantity { get; set; }
public double PriceAtPurchase { get; set; }
public override void Validate()
{
base.Validate();
if (Product == null) throw new Exception("OrderItem needs a Product");
if (Quantity == 0) throw new Exception("OrderItem needs a quantitiy > 0");
}
public override void Save()
{
throw new NotImplementedException();
}
public override void Retrieve(string ID)
{
throw new NotImplementedException();
}
}
}
|
using EddiDataDefinitions;
using System;
using Utilities;
namespace EddiEvents
{
[PublicAPI]
public class SearchAndRescueEvent : Event
{
public const string NAME = "Search and rescue";
public const string DESCRIPTION = "Triggered when delivering items to a Search and Rescue contact";
public const string SAMPLE = "{ \"timestamp\":\"2017-08-26T01:58:24Z\", \"event\":\"SearchAndRescue\", \"MarketID\": 128666762, \"Name\":\"occupiedcryopod\", \"Count\":2, \"Reward\":5310 }";
[PublicAPI("The amount of the item recovered")]
public int? amount { get; }
[PublicAPI("The monetary reward for completing the search and rescue")]
public long reward { get; }
[PublicAPI("The localized name of the commodity recovered")]
public string localizedcommodityname => commodity.localizedName;
[PublicAPI("The commodity (object) recovered")]
public CommodityDefinition commodity { get; }
// Not intended to be user facing
public long marketId { get; private set; }
public SearchAndRescueEvent(DateTime timestamp, CommodityDefinition commodity, int? amount, long reward, long marketId) : base(timestamp, NAME)
{
this.amount = amount;
this.reward = reward;
this.commodity = commodity;
this.marketId = marketId;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace KartObjects
{
public enum AxlErrors
{
[EnumDescription("Ошибок нет")]
eNone = 0,
[EnumDescription("Карта не найдена")]
eCardNotFound = 1,
[EnumDescription("Карта просрочена")]
eCardExpired = 2,
[EnumDescription("Карта заблокирована")]
eCardBlocked = 3,
[EnumDescription("Не верный тип карты")]
eWrongCardType = 4,
[EnumDescription("Ошибка БД")]
eQueryError = 10,
}
}
|
using Likja.DataAccess.Common;
namespace Likja.Conthread
{
public interface IConthreadRepository<T> : IBaseRepository<T>
where T : Conthread
{
}
}
|
namespace MastermindGame
{
class Program
{
static void Main()
{
// TODO: Eger birden fazla oyun ekleyecek olursak, implementasyonu degistirip DI eklememiz grekiyor .
IGame game = new MastermindGame();
game.Start();
game.Play();
game.End();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Modelos;
using Servicos;
namespace WEBTeste.Controllers
{
public class UnidadeController : Controller
{
UnidadeServico serv = new UnidadeServico();
// GET: Unidade
public ActionResult Index(int? pagina)
{
int linhas = 5;
int qtCat = serv.ObterQuantidadeUnidade();
if (qtCat <= linhas)
ViewBag.Pages = 1;
else
ViewBag.Pages = Convert.ToInt32(qtCat / linhas) + 1;
ViewBag.Page = pagina.GetValueOrDefault(1);
return View(serv.ObterUnidades(pagina.GetValueOrDefault(1), linhas));
}
// GET: Unidade/Details/5
public ActionResult Details(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Unidade unidade = serv.ObterUnidade(id);
if (unidade == null)
{
return HttpNotFound();
}
return View(unidade);
}
// GET: Unidade/Create
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "SgUnidade,DsUnidade")] Unidade unidade)
{
if (ModelState.IsValid)
{
serv.IncluirUnidade(unidade);
return RedirectToAction("Index");
}
return View(unidade);
}
// GET: Unidade/Edit/5
public ActionResult Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Unidade unidade = serv.ObterUnidade(id);
if (unidade == null)
{
return HttpNotFound();
}
return View(unidade);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "SgUnidade,DsUnidade")] Unidade unidade)
{
if (ModelState.IsValid)
{
serv.AtualizarUnidade(unidade);
return RedirectToAction("Index");
}
return View(unidade);
}
// GET: Unidade/Delete/5
public ActionResult Delete(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Unidade unidade = serv.ObterUnidade(id);
if (unidade == null)
{
return HttpNotFound();
}
return View(unidade);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(string id)
{
Unidade unidade = serv.ObterUnidade(id);
serv.ExcluirUnidade(unidade);
return RedirectToAction("Index");
}
}
}
|
using NetDDD.Core.Contracts;
using System;
using System.Threading.Tasks;
namespace NetDDD.Core.Bases
{
public abstract class DomainEventHandler<T> : IDomainEventHandler
where T : IDomainEvent
{
public string Name { get; private set; }
protected DomainEventHandler(string name)
{
Name = name;
}
public bool CanHandle(Type eventType )
{
return eventType == typeof(T);
}
public async Task Handle(IDomainEvent @event)
{
var castedEvent = (T)@event;
await Handle(castedEvent);
}
/// <summary>
/// Handles the specific domain event asynchronously.
/// </summary>
/// <param name="event">Domain event.</param>
/// <returns>Task to run the operation asynchronously.</returns>
public abstract Task Handle(T @event);
}
}
|
using ColossalFramework;
using ColossalFramework.UI;
using ICities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace AutobulldozeMod
{
public class AutobulldozeMod : IUserMod
{
public static GameObject modObject;
public string Name {
get { return "Automatic Bulldoze"; }
}
public string Description {
get { return "Automatically destroys abandoned and burned buildings"; }
}
}
public class ThreadingTestMod : ThreadingExtensionBase
{
public static AudioGroup nullAudioGroup;
bool m_initialized = false;
public bool init()
{
if (m_initialized == true) return true;
UIComponent bullBar = UIView.Find("BulldozerBar");
if (bullBar == null) return false;
GameObject obDemolishAbandoned = new GameObject();
UIButton checkDemolishAbandoned = obDemolishAbandoned.AddComponent<UIButton>();
checkDemolishAbandoned.transform.parent = bullBar.transform;
checkDemolishAbandoned.transformPosition = new Vector3(-1.0f, 0.0f);
checkDemolishAbandoned.text = "Abandoned";
nullAudioGroup = new AudioGroup(0, new SavedFloat("NOTEXISTINGELEMENT", Settings.gameSettingsFile, 0, false));
UnityEngine.Debug.LogWarning("Autobulldoze initialized.");
m_initialized = true;
return true;
}
public override void OnCreated(IThreading threading)
{
m_initialized = false;
BulldozerPanelInterface.initialized = false;
}
public override void OnUpdate(float realTimeDelta, float simulationTimeDelta)
{
init();
BulldozerPanelInterface.init();
}
/*
private void demolishNowButtonClick(UIComponent component, UIMouseEventParameter eventParam)
{
BuildingManager buildManager = Singleton<BuildingManager>.instance;
for (ushort i = 0; i < buildManager.m_buildings.m_buffer.Length; i++)
{
demolishBuilding(i, false);
}
}
*/
private int GetBuildingRefundAmount(ushort building)
{
BuildingManager instance = Singleton<BuildingManager>.instance;
if (Singleton<SimulationManager>.instance.IsRecentBuildIndex(instance.m_buildings.m_buffer[(int) building].m_buildIndex))
return instance.m_buildings.m_buffer[(int) building].Info.m_buildingAI.GetRefundAmount(building, ref instance.m_buildings.m_buffer[(int) building]);
else
return 0;
}
public static void DispatchAutobulldozeEffect(BuildingInfo info, Vector3 pos, float angle, int length)
{
EffectInfo effect = Singleton<BuildingManager>.instance.m_properties.m_bulldozeEffect;
if (effect == null) return;
InstanceID instance = new InstanceID();
EffectInfo.SpawnArea spawnArea = new EffectInfo.SpawnArea(Matrix4x4.TRS(Building.CalculateMeshPosition(info, pos, angle, length), Building.CalculateMeshRotation(angle), Vector3.one), info.m_lodMeshData);
Singleton<EffectManager>.instance.DispatchEffect(effect, instance, spawnArea, Vector3.zero, 0.0f, 1f, nullAudioGroup);
}
private void DeleteBuildingImpl(ushort building, bool showEffect)
{
if (Singleton<BuildingManager>.instance.m_buildings.m_buffer[(int) building].m_flags != Building.Flags.None)
{
BuildingManager instance = Singleton<BuildingManager>.instance;
BuildingInfo info = instance.m_buildings.m_buffer[(int) building].Info;
if (info.m_buildingAI.CheckBulldozing(building, ref instance.m_buildings.m_buffer[(int) building]) == ToolBase.ToolErrors.None)
{
if (info.m_placementStyle == ItemClass.Placement.Automatic)
{
//this.m_bulldozingMode = BulldozeTool.Mode.Building;
//this.m_bulldozingService = info.m_class.m_service;
//this.m_deleteTimer = 0.1f;
}
int buildingRefundAmount = this.GetBuildingRefundAmount(building);
if (buildingRefundAmount != 0)
Singleton<EconomyManager>.instance.AddResource(EconomyManager.Resource.RefundAmount, buildingRefundAmount, info.m_class);
Vector3 pos = instance.m_buildings.m_buffer[(int) building].m_position;
float angle = instance.m_buildings.m_buffer[(int) building].m_angle;
int length = instance.m_buildings.m_buffer[(int) building].Length;
instance.ReleaseBuilding(building);
if (info.m_class.m_service > ItemClass.Service.Office)
Singleton<CoverageManager>.instance.CoverageUpdated(info.m_class.m_service, info.m_class.m_subService, info.m_class.m_level);
if (showEffect) DispatchAutobulldozeEffect(info, pos, angle, length);
}
}
//if ((int) building == (int) this.m_hoverInstance.Building)
// this.m_hoverInstance.Building = (ushort) 0;
//if ((int) building != (int) this.m_lastInstance.Building)
// return;
//this.m_lastInstance.Building = (ushort) 0;
}
public void demolishBuilding(ushort index, bool isAuto)
{
SimulationManager simManager = Singleton<SimulationManager>.instance;
BuildingManager buildManager = Singleton<BuildingManager>.instance;
//if (!BulldozerPanelInterface.b_demolishAutomatically && isAuto) return;
if (index >= buildManager.m_buildings.m_buffer.Length)
{
UnityEngine.Debug.LogWarning("Autodemolish: building "+index+" not exists.");
return;
}
Building build = buildManager.m_buildings.m_buffer[index];
bool needToDemolish = false;
if (BulldozerPanelInterface.b_demolishAbandoned && ((build.m_flags & Building.Flags.Abandoned) != Building.Flags.None)) needToDemolish = true;
if (BulldozerPanelInterface.b_demolishBurned && ((build.m_flags & Building.Flags.BurnedDown) != Building.Flags.None)) needToDemolish = true;
if (needToDemolish)
{
// UnityEngine.Debug.LogWarning("Autobulldozed #" + index);
DeleteBuildingImpl(index,true);
return;
}
}
public override void OnAfterSimulationTick()
{
//NetManager netManager = Singleton<NetManager>.instance;
//PathManager pathManager = Singleton<PathManager>.instance;
SimulationManager simManager = Singleton<SimulationManager>.instance;
//VehicleManager vehManager = Singleton<VehicleManager>.instance;
BuildingManager buildManager = Singleton<BuildingManager>.instance;
// if ((simManager.m_currentTickIndex % 100) != 0) return;
//uint frame = Singleton<SimulationManager>.instance.m_currentFrameIndex;
for (ushort i = (ushort)(simManager.m_currentTickIndex%1000); i < buildManager.m_buildings.m_buffer.Length; i+=1000)
{
demolishBuilding(i, true);
Building build = buildManager.m_buildings.m_buffer[i];
}
}
}
}
|
using System;
namespace iSukces.Code.AutoCode
{
public class UnableToFindConstructorException : Exception
{
public UnableToFindConstructorException(Type type, string message, Exception innerException = null)
: base($"Unable to find constructor for type {type}. {message}", innerException) =>
Type = type;
public Type Type { get; }
}
} |
using gView.Framework.Data;
using gView.Framework.Geometry;
using gView.Framework.Symbology;
using gView.Framework.system;
using System;
using System.Collections.Generic;
using System.Drawing;
namespace gView.Framework.Carto
{
internal class LabelEngine2 : ILabelEngine, IDisposable
{
private enum OverlapMethod { Pixel = 1, Geometry = 0 };
private OverlapMethod _method = OverlapMethod.Geometry;
private GraphicsEngine.Abstraction.IBitmap _bitmap;
//private Display _display;
private GraphicsEngine.Abstraction.ICanvas _canvas = null;
private GraphicsEngine.ArgbColor _back;
private bool _first = true, _directDraw = false;
private GridArray<List<IAnnotationPolygonCollision>> _gridArrayPolygons = null;
public LabelEngine2()
{
//_display = new Display(false);
}
public void Dispose()
{
if (_canvas != null)
{
_canvas.Dispose();
_canvas = null;
}
if (_bitmap != null)
{
_bitmap.Dispose();
_bitmap = null;
}
_gridArrayPolygons = null;
}
#region ILabelEngine Member
public void Init(IDisplay display, bool directDraw)
{
try
{
if (display == null)
{
return;
}
//if (_bm != null && (_bm.Width != display.iWidth || _bm.Height != display.iHeight))
{
Dispose();
}
if (_bitmap == null)
{
_bitmap = GraphicsEngine.Current.Engine.CreateBitmap(display.iWidth, display.iHeight, GraphicsEngine.PixelFormat.Rgba32);
}
_canvas = _bitmap.CreateCanvas();
//using (var brush = GraphicsEngine.Current.Engine.CreateSolidBrush(GraphicsEngine.ArgbColor.Transparent))
//{
// _canvas.FillRectangle(brush, new GraphicsEngine.CanvasRectangle(0, 0, _bitmap.Width, _bitmap.Height));
//}
_bitmap.MakeTransparent();
_back = _bitmap.GetPixel(0, 0);
_first = true;
_directDraw = directDraw;
//_bm.MakeTransparent(Color.White);
_gridArrayPolygons = new GridArray<List<IAnnotationPolygonCollision>>(
new Envelope(0.0, 0.0, display.iWidth, display.iHeight),
new int[] { 50, 25, 18, 10, 5, 2 },
new int[] { 50, 25, 18, 10, 5, 2 });
}
catch
{
Dispose();
}
}
public LabelAppendResult _TryAppend(IDisplay display, ITextSymbol symbol, IGeometry geometry, bool checkForOverlap)
{
if (symbol == null || !(display is Display))
{
return LabelAppendResult.WrongArguments;
}
IAnnotationPolygonCollision labelPolyon = null;
if (display.GeometricTransformer != null && !(geometry is IDisplayPath))
{
geometry = display.GeometricTransformer.Transform2D(geometry) as IGeometry;
if (geometry == null)
{
return LabelAppendResult.WrongArguments;
}
}
IEnvelope labelPolyonEnvelope = null;
if (symbol is ILabel)
{
foreach (var symbolAlignment in LabelAlignments((ILabel)symbol))
{
List<IAnnotationPolygonCollision> aPolygons = ((ILabel)symbol).AnnotationPolygon(display, geometry, symbolAlignment);
bool outside = true;
if (aPolygons != null)
{
#region Check Outside
foreach (IAnnotationPolygonCollision polyCollision in aPolygons)
{
AnnotationPolygonEnvelope env = polyCollision.Envelope;
if (env.MinX < 0 || env.MinY < 0 || env.MaxX > _bitmap.Width || env.MaxY > _bitmap.Height)
{
return LabelAppendResult.Outside;
}
}
#endregion
foreach (IAnnotationPolygonCollision polyCollision in aPolygons)
{
AnnotationPolygonEnvelope env = polyCollision.Envelope;
//int minx = (int)Math.Max(0, env.MinX);
//int maxx = (int)Math.Min(_bm.Width - 1, env.MaxX);
//int miny = (int)Math.Max(0, env.MinY);
//int maxy = (int)Math.Min(_bm.Height, env.MaxY);
//if (minx > _bm.Width || maxx <= 0 || miny > _bm.Height || maxy <= 0) continue; // liegt außerhalb!!
int minx = (int)env.MinX, miny = (int)env.MinX, maxx = (int)env.MaxX, maxy = (int)env.MaxY;
outside = false;
if (!_first && checkForOverlap)
{
if (_method == OverlapMethod.Pixel)
{
#region Pixel Methode
for (int x = minx; x < maxx; x++)
{
for (int y = miny; y < maxy; y++)
{
//if (x < 0 || x >= _bm.Width || y < 0 || y >= _bm.Height) continue;
if (polyCollision.Contains(x, y))
{
//_bm.SetPixel(x, y, Color.Yellow);
if (!_back.Equals(_bitmap.GetPixel(x, y)))
{
return LabelAppendResult.Overlap;
}
}
}
}
#endregion
}
else
{
#region Geometrie Methode
labelPolyon = polyCollision;
foreach (List<IAnnotationPolygonCollision> indexedPolygons in _gridArrayPolygons.Collect(new Envelope(env.MinX, env.MinY, env.MaxX, env.MaxY)))
{
foreach (IAnnotationPolygonCollision lp in indexedPolygons)
{
if (lp.CheckCollision(polyCollision) == true)
{
return LabelAppendResult.Overlap;
}
}
}
#endregion
}
}
else
{
_first = false;
if (_method == OverlapMethod.Geometry)
{
#region Geometrie Methode
labelPolyon = polyCollision;
#endregion
}
}
labelPolyonEnvelope = new Envelope(env.MinX, env.MinY, env.MaxX, env.MaxY);
}
}
if (outside)
{
return LabelAppendResult.Outside;
}
}
}
if (labelPolyon != null)
{
List<IAnnotationPolygonCollision> indexedPolygons = _gridArrayPolygons[labelPolyonEnvelope];
indexedPolygons.Add(labelPolyon);
//using (System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath())
//{
// path.StartFigure();
// path.AddLine(labelPolyon[0], labelPolyon[1]);
// path.AddLine(labelPolyon[1], labelPolyon[2]);
// path.AddLine(labelPolyon[2], labelPolyon[3]);
// path.CloseFigure();
// _graphics.FillPath(Brushes.Aqua, path);
//}
}
var originalCanvas = display.Canvas;
((Display)display).Canvas = _canvas;
symbol.Draw(display, geometry);
((Display)display).Canvas = originalCanvas;
if (_directDraw)
{
symbol.Draw(display, geometry);
}
return LabelAppendResult.Succeeded;
}
public LabelAppendResult TryAppend(IDisplay display, ITextSymbol symbol, IGeometry geometry, bool checkForOverlap)
{
if (symbol == null || !(display is Display))
{
return LabelAppendResult.WrongArguments;
}
if (display.GeometricTransformer != null && !(geometry is IDisplayPath))
{
geometry = display.GeometricTransformer.Transform2D(geometry) as IGeometry;
if (geometry == null)
{
return LabelAppendResult.WrongArguments;
}
}
var labelApendResult = LabelAppendResult.Succeeded;
if (symbol is ILabel)
{
foreach (var symbolAlignment in LabelAlignments((ILabel)symbol))
{
labelApendResult = LabelAppendResult.Succeeded;
List<IAnnotationPolygonCollision> aPolygons = ((ILabel)symbol).AnnotationPolygon(display, geometry, symbolAlignment);
labelApendResult = TryAppend(display, symbol, geometry, aPolygons, checkForOverlap, symbolAlignment);
if (labelApendResult == LabelAppendResult.Succeeded)
{
break;
}
}
}
return labelApendResult;
}
public LabelAppendResult TryAppend(IDisplay display, List<IAnnotationPolygonCollision> aPolygons, IGeometry geometry, bool checkForOverlap)
{
bool outside = true;
IAnnotationPolygonCollision labelPolyon = null;
IEnvelope labelPolyonEnvelope = null;
if (aPolygons != null)
{
foreach (IAnnotationPolygonCollision polyCollision in aPolygons)
{
AnnotationPolygonEnvelope env = polyCollision.Envelope;
int minx = (int)Math.Max(0, env.MinX);
int maxx = (int)Math.Min(_bitmap.Width - 1, env.MaxX);
int miny = (int)Math.Max(0, env.MinY);
int maxy = (int)Math.Min(_bitmap.Height, env.MaxY);
if (minx > _bitmap.Width || maxx <= 0 || miny > _bitmap.Height || maxy <= 0)
{
continue; // liegt außerhalb!!
}
outside = false;
if (!_first && checkForOverlap)
{
if (_method == OverlapMethod.Pixel)
{
#region Pixel Methode
for (int x = minx; x < maxx; x++)
{
for (int y = miny; y < maxy; y++)
{
//if (x < 0 || x >= _bm.Width || y < 0 || y >= _bm.Height) continue;
if (polyCollision.Contains(x, y))
{
//_bm.SetPixel(x, y, Color.Yellow);
if (!_back.Equals(_bitmap.GetPixel(x, y)))
{
return LabelAppendResult.Overlap;
}
}
}
}
#endregion
}
else
{
#region Geometrie Methode
labelPolyon = polyCollision;
foreach (List<IAnnotationPolygonCollision> indexedPolygons in _gridArrayPolygons.Collect(new Envelope(env.MinX, env.MinY, env.MaxX, env.MaxY)))
{
foreach (IAnnotationPolygonCollision lp in indexedPolygons)
{
if (lp.CheckCollision(polyCollision) == true)
{
return LabelAppendResult.Overlap;
}
}
}
#endregion
}
}
else
{
_first = false;
if (_method == OverlapMethod.Geometry)
{
#region Geometrie Methode
labelPolyon = polyCollision;
#endregion
}
}
labelPolyonEnvelope = new Envelope(env.MinX, env.MinY, env.MaxX, env.MaxY);
}
if (outside)
{
return LabelAppendResult.Outside;
}
}
if (labelPolyon != null)
{
List<IAnnotationPolygonCollision> indexedPolygons = _gridArrayPolygons[labelPolyonEnvelope];
indexedPolygons.Add(labelPolyon);
}
return LabelAppendResult.Succeeded;
}
public void Draw(IDisplay display, ICancelTracker cancelTracker)
{
try
{
display.Canvas.DrawBitmap(_bitmap, new GraphicsEngine.CanvasPoint(0, 0));
//_bm.Save(@"c:\temp\label.png", System.Drawing.Imaging.ImageFormat.Png);
}
catch { }
}
public void Release()
{
Dispose();
}
public GraphicsEngine.Abstraction.ICanvas LabelCanvas
{
get { return _canvas; }
}
#endregion
#region Helper
private LabelAppendResult TryAppend(IDisplay display, ITextSymbol symbol, IGeometry geometry, List<IAnnotationPolygonCollision> aPolygons, bool checkForOverlap, TextSymbolAlignment symbolAlignment)
{
IAnnotationPolygonCollision labelPolyon = null;
IEnvelope labelPolyonEnvelope = null;
bool outside = true;
if (aPolygons != null)
{
#region Check Outside
foreach (IAnnotationPolygonCollision polyCollision in aPolygons)
{
AnnotationPolygonEnvelope env = polyCollision.Envelope;
if (env.MinX < 0 || env.MinY < 0 || env.MaxX > _bitmap.Width || env.MaxY > _bitmap.Height)
{
return LabelAppendResult.Outside;
}
}
#endregion
foreach (IAnnotationPolygonCollision polyCollision in aPolygons)
{
AnnotationPolygonEnvelope env = polyCollision.Envelope;
//int minx = (int)Math.Max(0, env.MinX);
//int maxx = (int)Math.Min(_bm.Width - 1, env.MaxX);
//int miny = (int)Math.Max(0, env.MinY);
//int maxy = (int)Math.Min(_bm.Height, env.MaxY);
//if (minx > _bm.Width || maxx <= 0 || miny > _bm.Height || maxy <= 0) continue; // liegt außerhalb!!
int minx = (int)env.MinX, miny = (int)env.MinX, maxx = (int)env.MaxX, maxy = (int)env.MaxY;
outside = false;
if (!_first && checkForOverlap)
{
if (_method == OverlapMethod.Pixel)
{
#region Pixel Methode
for (int x = minx; x < maxx; x++)
{
for (int y = miny; y < maxy; y++)
{
//if (x < 0 || x >= _bm.Width || y < 0 || y >= _bm.Height) continue;
if (polyCollision.Contains(x, y))
{
//_bm.SetPixel(x, y, Color.Yellow);
if (!_back.Equals(_bitmap.GetPixel(x, y)))
{
return LabelAppendResult.Overlap;
}
}
}
}
#endregion
}
else
{
#region Geometrie Methode
labelPolyon = polyCollision;
foreach (List<IAnnotationPolygonCollision> indexedPolygons in _gridArrayPolygons.Collect(new Envelope(env.MinX, env.MinY, env.MaxX, env.MaxY)))
{
foreach (IAnnotationPolygonCollision lp in indexedPolygons)
{
if (lp.CheckCollision(polyCollision) == true)
{
return LabelAppendResult.Overlap;
}
}
}
#endregion
}
}
else
{
_first = false;
if (_method == OverlapMethod.Geometry)
{
#region Geometrie Methode
labelPolyon = polyCollision;
#endregion
}
}
labelPolyonEnvelope = new Envelope(env.MinX, env.MinY, env.MaxX, env.MaxY);
}
}
if (outside)
{
return LabelAppendResult.Outside;
}
if (labelPolyon != null)
{
List<IAnnotationPolygonCollision> indexedPolygons = _gridArrayPolygons[labelPolyonEnvelope];
indexedPolygons.Add(labelPolyon);
//using (System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath())
//{
// path.StartFigure();
// path.AddLine(labelPolyon[0], labelPolyon[1]);
// path.AddLine(labelPolyon[1], labelPolyon[2]);
// path.AddLine(labelPolyon[2], labelPolyon[3]);
// path.CloseFigure();
// _graphics.FillPath(Brushes.Aqua, path);
//}
}
var originalCanvas = display.Canvas;
((Display)display).Canvas = _canvas;
symbol.Draw(display, geometry, symbolAlignment);
((Display)display).Canvas = originalCanvas;
if (_directDraw)
{
symbol.Draw(display, geometry, symbolAlignment);
}
return LabelAppendResult.Succeeded;
}
private TextSymbolAlignment[] LabelAlignments(ILabel label)
{
return label.SecondaryTextSymbolAlignments != null && label.SecondaryTextSymbolAlignments.Length > 0 ?
label.SecondaryTextSymbolAlignments :
new TextSymbolAlignment[] { label.TextSymbolAlignment };
}
#endregion
#region Helper Classes
private class LabelPolygon
{
PointF[] _points;
public LabelPolygon(PointF[] points)
{
_points = points;
}
public bool CheckCollision(LabelPolygon lp)
{
if (HasSeperateLine(this, lp))
{
return false;
}
if (HasSeperateLine(lp, this))
{
return false;
}
return true;
}
public PointF this[int index]
{
get
{
if (index < 0 || index >= _points.Length)
{
return _points[0];
}
return _points[index];
}
}
private static bool HasSeperateLine(LabelPolygon tester, LabelPolygon cand)
{
for (int i = 1; i <= tester._points.Length; i++)
{
PointF p1 = tester[i];
Vector2dF ortho = new Vector2dF(p1, tester._points[i - 1]);
ortho.ToOrtho();
ortho.Normalize();
float t_min = 0f, t_max = 0f, c_min = 0f, c_max = 0f;
MinMaxAreaForOrhtoSepLine(p1, ortho, tester, ref t_min, ref t_max);
MinMaxAreaForOrhtoSepLine(p1, ortho, cand, ref c_min, ref c_max);
if ((t_min <= c_max && t_max <= c_min) ||
(c_min <= t_max && c_max <= t_min))
{
return true;
}
}
return false;
}
private static void MinMaxAreaForOrhtoSepLine(PointF p1, Vector2dF ortho, LabelPolygon lp, ref float min, ref float max)
{
for (int j = 0; j < lp._points.Length; j++)
{
Vector2dF rc = new Vector2dF(lp[j], p1);
float prod = ortho.DotProduct(rc);
if (j == 0)
{
min = max = prod;
}
else
{
min = Math.Min(min, prod);
max = Math.Max(max, prod);
}
}
}
public IEnvelope Envelope
{
get
{
double
minx = _points[0].X,
miny = _points[0].Y,
maxx = _points[0].X,
maxy = _points[0].Y;
for (int i = 1; i < _points.Length; i++)
{
minx = Math.Min(minx, _points[i].X);
miny = Math.Min(miny, _points[i].Y);
maxx = Math.Max(maxx, _points[i].X);
maxy = Math.Max(maxy, _points[i].Y);
}
return new Envelope(minx, miny, maxx, maxy);
}
}
#region Helper Classes
private class Vector2dF
{
float _x, _y;
public Vector2dF(PointF p1, PointF p0)
{
_x = p1.X - p0.X;
_y = p1.Y - p0.Y;
}
public void ToOrtho()
{
float x = _x;
_x = -_y;
_y = x;
}
public void Normalize()
{
float l = (float)Math.Sqrt(_x * _x + _y * _y);
_x /= l;
_y /= l;
}
public float DotProduct(Vector2dF v)
{
return _x * v._x + _y * v._y;
}
}
#endregion
}
#endregion
}
#region Old Label Engines
/*
internal class LabelEngine : ILabelEngine
{
List<Font> _fonts = new List<Font>();
List<Label> _labels = new List<Label>();
List<ITextSymbol> _symbols = new List<ITextSymbol>();
private bool _directDraw = false;
#region ILabelEngine Member
public void Init(IDisplay display, bool directDraw)
{
_directDraw = directDraw;
}
public LabelAppendResult TryAppend(IDisplay display, ITextSymbol symbol, IGeometry geometry, bool chechForOverlap)
{
if (symbol == null || geometry == null || display == null || symbol.Text.Trim() == String.Empty) return LabelAppendResult.WrongArguments;
if (!_fonts.Contains(symbol.Font))
_fonts.Add((Font)symbol.Font.Clone());
if (!_symbols.Contains(symbol))
_symbols.Add(symbol);
_labels.Add(new Label(_symbols.IndexOf(symbol), _fonts.IndexOf(symbol.Font), geometry, symbol.Text));
return LabelAppendResult.Succeeded;
}
public void Draw(IDisplay display, ICancelTracker cancelTracker)
{
foreach (Label label in _labels)
{
if (cancelTracker != null && !cancelTracker.Continue) return;
ITextSymbol txtSymbol = _symbols[label.SymbolID];
txtSymbol.Text = label.Text;
txtSymbol.Font = _fonts[label.FontID];
txtSymbol.Draw(display, label.Geometry);
}
}
public void Release()
{
_labels.Clear();
ReleaseTextSymbols();
ReleaseFonts();
//GC.Collect();
}
#endregion
private void ReleaseTextSymbols()
{
foreach (ITextSymbol txtSymbol in _symbols)
{
txtSymbol.Release();
}
_symbols.Clear();
}
private void ReleaseFonts()
{
foreach (Font font in _fonts)
{
if (font == null) continue;
font.Dispose();
}
_fonts.Clear();
}
}
internal class Label
{
public int SymbolID, FontID;
public IGeometry Geometry;
public string Text;
public Label(int symbolID, int fontID, IGeometry geometry, string text)
{
FontID = fontID;
SymbolID = symbolID;
Geometry = geometry;
Text = text;
}
}
*/
#endregion
}
|
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using VoxelSpace.Graphics;
namespace VoxelSpace.UI {
public abstract partial class UI {
public Matrix ProjMat => _projMat;
Matrix _projMat;
public float Width { get; private set; }
public float Height { get; private set; }
public Anchors Anchors { get; private set; }
public Skin Skin;
BlendState _lastBlendState;
DepthStencilState _lastDepthStencilState;
static readonly RasterizerState SCISSORSTATE = new RasterizerState() {
ScissorTestEnable = true
};
public static void Initialize(GameWindow window) {
}
public UI(float height, Skin skin) {
Primitives.Initialize();
Input = new Input.InputHandle();
Skin = skin;
G.Game.Window.TextInput += OnCharTyped;
SetHeight(height);
}
~UI() {
// NOTE: this is a workaround that wont be necessary when listening to this event is moved to the input system.
// for now, we have each ui subscribe to this event for its text inputs
G.Game.Window.TextInput -= OnCharTyped;
}
void OnCharTyped(object sender, TextInputEventArgs e) {
TextBoxState.OnCharTyped(this, e);
}
public void SetHeight(float height) {
var aspect = G.Graphics.Viewport.AspectRatio;
Width = height * aspect;
Height = height;
onSizeChanged();
}
public void SetWidth(float width) {
var aspect = G.Graphics.Viewport.AspectRatio;
Width = width;
Height = width / aspect;
onSizeChanged();
}
void onSizeChanged() {
setProjectionMatrix();
Anchors = new Anchors(Width, Height);
}
void setProjectionMatrix() {
_projMat = Matrix.CreateOrthographic(Width, Height, -1000, 1000) * Matrix.CreateScale(1, -1, 1);
}
void StartDraw() {
var graphics = G.Graphics;
graphics.Clear(ClearOptions.DepthBuffer, Color.White, float.MinValue, 0);
_lastBlendState = graphics.BlendState;
_lastDepthStencilState = graphics.DepthStencilState;
graphics.BlendState = BlendState.AlphaBlend;
graphics.DepthStencilState = DepthStencilState.None;
}
void EndDraw() {
var graphics = G.Graphics;
graphics.BlendState = _lastBlendState;
graphics.DepthStencilState = _lastDepthStencilState;
}
/// <summary>
/// Draw the ui
/// </summary>
public void Draw() {
StartDraw();
DrawUI();
EndDraw();
}
protected abstract void DrawUI();
public void Draw(IDrawable drawable, Rect rect)
=> Draw(drawable, rect, Color.White);
public void Draw(IDrawable drawable, Rect rect, Color color) {
rect.Position.Floor();
rect.Size.Floor();
drawable.DrawUI(this, _projMat, rect, color);
}
public void DrawString(TileFont font, Vector2 position, string text, HorizontalAlign halign = HorizontalAlign.Left, VerticalAlign valign = VerticalAlign.Top)
=> DrawString(font, position, text, Color.White, halign, valign);
public void DrawString(TileFont font, Vector2 position, string text, Color color, HorizontalAlign halign = HorizontalAlign.Left, VerticalAlign valign = VerticalAlign.Top) {
font.DrawString(this, _projMat, position, text, color, halign, valign);
}
public Vector2 ScreenToCanvasPoint(Vector2 point) {
var scale = Width / G.Graphics.Viewport.Width;
point *= scale;
point.X -= Width / 2;
point.Y -= Height / 2;
return point;
}
public Vector2 CanvasToScreenPoint(Vector2 point) {
var scale = Width / G.Graphics.Viewport.Width;
point.X += Width / 2;
point.Y += Height / 2;
point /= scale;
return point;
}
public Rect CanvasToScreenRect(Rect rect) {
var scale = Width / G.Graphics.Viewport.Width;
rect.Position = CanvasToScreenPoint(rect.Position);
rect.Size /= scale;
return rect;
}
}
public struct Anchors {
public readonly Vector2
TopLeft, TopCenter, TopRight,
MidLeft, MidCenter, MidRight,
BottomLeft, BottomCenter, BottomRight;
public readonly float Width;
public readonly float Height;
public Anchors(float w, float h) {
Width = w;
Height = h;
TopLeft = Vector2.Floor(new Vector2(-w, -h) / 2);
TopCenter = Vector2.Floor(new Vector2( 0, -h) / 2);
TopRight = Vector2.Floor(new Vector2(+w, -h) / 2);
MidLeft = Vector2.Floor(new Vector2(-w, 0) / 2);
MidCenter = Vector2.Floor(new Vector2( 0, 0) / 2);
MidRight = Vector2.Floor(new Vector2(+w, 0) / 2);
BottomLeft = Vector2.Floor(new Vector2(-w, +h) / 2);
BottomCenter = Vector2.Floor(new Vector2( 0, +h) / 2);
BottomRight = Vector2.Floor(new Vector2(+w, +h) / 2);
}
}
} |
using System;
using System.Linq;
namespace Asp_webform_sinav
{
public partial class Filmler : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (EntityModel Database = new EntityModel())
{
Tekrar1.DataSource = Database.Movie.ToList();
Tekrar1.DataBind();
}
if (!IsPostBack)
{
if (Request.QueryString["ID"] != null)
{
int id = int.Parse(Request.QueryString["ID"]);
using (EntityModel database = new EntityModel())
{
var deger = database.Movie.Find(id);
database.Movie.Remove(deger);
database.SaveChanges();
Response.Redirect("Filmler.aspx");
}
}
if (Request.QueryString["GID"] != null)
{
int gid = int.Parse(Request.QueryString["GID"]);
using (EntityModel database = new EntityModel())
{
var deger = database.Movie.Find(gid);
txtFilmAdi.Text = deger.FilmAdi;
txtFilmYili.Text = Convert.ToString(deger.FilmYili);
txtFilmTuru.Text = deger.FilmTuru;
//txtFilmYönetmen.Text = yonetmen.YonetmenAdi;
//txtFilmAktor.Text = aktor.AktorAdi;
}
}
}
}
protected void butonKaydet_Click(object sender, EventArgs e)
{
if (txtFilmAdi.Text != "" && txtFilmYili.Text != "" && txtFilmTuru.Text != "" && txtFilmYönetmen.Text != "" && txtFilmAktor.Text != "")
{
using (EntityModel database = new EntityModel())
{
Models.Movie film = new Models.Movie();
Models.Actor aktor = new Models.Actor();
Models.Director yonetmen = new Models.Director();
film.FilmAdi = txtFilmAdi.Text;
film.FilmYili = txtFilmYili.Text;
film.FilmTuru = txtFilmTuru.Text;
yonetmen.YonetmenAdi = txtFilmYönetmen.Text;
aktor.AktorAdi = txtFilmAktor.Text;
database.Movie.Add(film);
database.Actor.Add(aktor);
database.Director.Add(yonetmen);
database.SaveChanges();
}
Response.Redirect("Filmler.aspx");
}
}
protected void butonGuncelle_Click(object sender, EventArgs e)
{
if (Request.QueryString["GID"] != null)
{
using (EntityModel database = new EntityModel())
{
int gid = int.Parse(Request.QueryString["GID"]);
var deger = database.Movie.Find(gid);
txtFilmAdi.Text = deger.FilmAdi;
txtFilmYili.Text = Convert.ToString(deger.FilmYili);
txtFilmTuru.Text = deger.FilmTuru;
//txtFilmYönetmen.Text = Convert.ToString(deger.YonetmenNo);
//txtFilmAktor.Text = Convert.ToString(deger.AktorNo);
database.SaveChanges();
}
Response.Redirect("Filmler.aspx");
}
}
}
} |
using ODL.DomainModel.Common;
namespace ODL.DomainModel.Organisation
{
public class Resultatenhet
{
public Resultatenhet()
{
}
public Resultatenhet(string kstNr, Kostnadsstalletyp typ)
{
KstNr = kstNr;
Typ = typ;
}
public int OrganisationId { get; private set; }
public string KstNr { get; private set; }
public Kostnadsstalletyp Typ
{
get => KostnadsstalletypString.TillEnum<Kostnadsstalletyp>();
private set => KostnadsstalletypString = value.ToString();
}
public string KostnadsstalletypString { get; private set; }
public virtual Organisation Organisation { get; private set; }
public bool Ny => OrganisationId == default(int);
}
}
|
/*
* Created by SharpDevelop.
* User: User
* Date: 8/18/2016
* Time: 6:11 PM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Robot
{
/// <summary>
/// Description of frmChooseGroupStartAuto.
/// </summary>
public partial class frmChooseGroupStartAuto : Form
{
public frmChooseGroupStartAuto()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
this.ResizeChildrenText();
}
void FrmChooseGroupStartAutoClientSizeChanged(object sender, EventArgs e)
{
this.ResizeChildrenText();
}
void BtnSortirClick(object sender, EventArgs e)
{
this.Close();
}
void BtnStartClick(object sender, EventArgs e)
{
StartAutomaticMode();
}
void StartAutomaticMode()
{
if(GR.Instance.BalanceSerialPort.SerialPortActive)
{
bool fillingCompleted;
using(var frm = new frmAutomaticMode(this.ctrlGroupSelect1.SelectedGroup))
{
frm.ShowDialog();
fillingCompleted = frm.FillingCompleted;
}
if(fillingCompleted)
{
using(var frm2 = new frmWaitingTime())
{
frm2.ShowDialog();
}
}
}
else
{
MessageBox.Show("Serial port not connected");
}
}
void FrmChooseGroupStartAutoKeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter)
{
StartAutomaticMode();
}
// if(e.KeyCode == Keys.Back)
// {
// this.Close();
// }
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class GameOver : MonoBehaviour
{
public TextMeshProUGUI textscore1;
public TextMeshProUGUI textscore2;
public TextMeshProUGUI textscoreTotal;
int score1;
int score2;
// Start is called before the first frame update
void Start()
{
score1 = PlayerPrefs.GetInt("ActualScore1");
score2 = PlayerPrefs.GetInt("ActualScore2");
textscore1.text = score1.ToString();
textscore2.text = score2.ToString();
PlayerPrefs.SetInt("ActualScore1", 0);
PlayerPrefs.SetInt("ActualScore2", 0);
int total = score1 + score2;
textscoreTotal.text = "TOTAL SCORE\n" + total.ToString();
}
// Update is called once per frame
void Update()
{
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.