text stringlengths 13 6.01M |
|---|
using Game;
using TMPro;
using UnityEngine;
namespace UI
{
public class DepthCounter : MonoBehaviour
{
public TextMeshProUGUI DepthText;
private void Awake()
{
Events.Events.OnLevelStart += UpdateDepthCounterText;
}
public void UpdateDepthCounterText()
{
DepthText.text = Stats.NPCurrentDepth.ToString();
}
private void OnDestroy()
{
Events.Events.OnLevelStart -= UpdateDepthCounterText;
}
}
}
|
using DAL.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace DAL.Interfaces
{
public interface IAuthorRepository : IRepositoryBase<Author>
{
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ClientTaskManager
{
static class Configuration
{
static public int MaxRequestPerInterval = 5;
static public int MaxIntervalsPerMinute = 50;
static public int MaxTasksPerRequest = 100000;
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace AssToMouth
{
class MainClass
{
NetSpell.SpellChecker.Dictionary.WordDictionary _wordDict;
NetSpell.SpellChecker.Spelling _spelling;
public static void Main(string[] args)
{
var mc = new MainClass();
}
public MainClass()
{
_wordDict = new NetSpell.SpellChecker.Dictionary.WordDictionary();
_wordDict.Initialize();
_spelling = new NetSpell.SpellChecker.Spelling();
var ass = "head";
var mouth = "tail";
_spelling.Dictionary = _wordDict;
Stopwatch sw = new Stopwatch();
sw.Start();
var set = GetComboAnagrams(ass, mouth);
sw.Stop();
Console.WriteLine($"found {set.Count} words in {sw.ElapsedMilliseconds} mili");
sw.Reset();
sw.Start();
var g = GetNearestWordGraph(set.ToList());
var path = g.shortest_path(ass, mouth);
//add the mouth
path.Add(mouth);
Console.WriteLine($"found {string.Join("-->",path)} in {sw.ElapsedMilliseconds} mili");
int f = 0;
}
Graph GetNearestWordGraph ( List<string> words)
{
var g = new Graph();
for (int i = 0; i < words.Count;i++)
{
var word = words[i];
var edges = words.Where(x => OneDiff(x, word)).ToDictionary((_ => _), (_ => 1));
g.add_vertex(word,edges);
}
return g;
}
bool OneDiff ( string word1 , string word2)
{
bool flg = false;
if ( word1 == word2 )
{
return false;
}
for (int i = 0; i < word1.Length;i++)
{
if ( word1[i] != word2[i] )
{
if (flg)
{
return false;
}
else
{
flg = true;
}
}
}
return true;
}
HashSet<string> GetComboAnagrams ( string word1, string word2)
{
var words = new HashSet<string>();
var combo = word1 + word2;
var targetLen = word1.Length;
for (int i = 0; i < combo.Length;i++)
{
for (int j = 0; j < combo.Length;j++)
{
for (int k = 0; k < combo.Length; k++)
{
for (int l = 0; l < combo.Length; l++)
{
var word = new string(new char[] { combo[i], combo[j], combo[k], combo[l] });
if ( !words.Contains(word) && IsWord(word))
{
words.Add(word);
}
}
}
}
}
return words;
}
private bool IsWord(string wordToCheck)
{
return _spelling.TestWord(wordToCheck);
}
}
class Graph
{
Dictionary<string, Dictionary<string, int>> vertices = new Dictionary<string, Dictionary<string, int>>();
public void add_vertex(string name, Dictionary<string, int> edges)
{
vertices[name] = edges;
}
public List<string> shortest_path(string start, string finish)
{
var previous = new Dictionary<string, string>();
var distances = new Dictionary<string, int>();
var nodes = new List<string>();
List<string> path = null;
foreach (var vertex in vertices)
{
if (vertex.Key == start)
{
distances[vertex.Key] = 0;
}
else
{
distances[vertex.Key] = int.MaxValue;
}
nodes.Add(vertex.Key);
}
while (nodes.Count != 0)
{
nodes.Sort((x, y) => distances[x] - distances[y]);
var smallest = nodes[0];
nodes.Remove(smallest);
if (smallest == finish)
{
path = new List<string>();
while (previous.ContainsKey(smallest))
{
path.Add(smallest);
smallest = previous[smallest];
}
break;
}
if (distances[smallest] == int.MaxValue)
{
break;
}
foreach (var neighbor in vertices[smallest])
{
var alt = distances[smallest] + neighbor.Value;
if (alt < distances[neighbor.Key])
{
distances[neighbor.Key] = alt;
previous[neighbor.Key] = smallest;
}
}
}
return path;
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Xml;
using DataAccessLayer.basis;
using Model.DataEntity;
using Model.DocumentManagement;
using Model.Helper;
using Model.Locale;
using Model.Properties;
using Utility;
using System.Security.Cryptography.Pkcs;
using Uxnet.Com.Security.UseCrypto;
namespace Model.InvoiceManagement
{
public class EIVOPlatformManager
{
public EIVOPlatformManager()
{
}
public void TransmitInvoice()
{
using (InvoiceManager mgr = new InvoiceManager())
{
saveToPlatform(mgr);
}
}
class _key
{
public int? a = (int?)null;
public int? b = (int?)null;
};
public void NotifyToProcess()
{
using (InvoiceManager mgr = new InvoiceManager())
{
var notify = mgr.GetTable<ReplicationNotification>();
var items = notify.ToList();
if (items.Count() > 0)
{
var org = mgr.GetTable<Organization>();
var toIssue = notify.Select(r => r.DocumentReplication.CDS_Document).Where(d => d.CurrentStep == (int)Naming.InvoiceStepDefinition.待開立);
if (toIssue.Count() > 0)
{
var notifyToIssue = toIssue.Select(t => new NotifyToProcessID { MailToID = t.InvoiceItem.InvoiceSeller.SellerID, Seller = t.InvoiceItem.InvoiceSeller.Organization })
.Concat(toIssue.Select(t => new NotifyToProcessID { MailToID = t.DerivedDocument.ParentDocument.InvoiceItem.InvoiceSeller.SellerID, Seller = t.DerivedDocument.ParentDocument.InvoiceItem.InvoiceSeller.Organization }))
.Concat(toIssue.Select(t => new NotifyToProcessID { MailToID = t.InvoiceAllowance.InvoiceAllowanceBuyer.BuyerID, Seller = t.InvoiceAllowance.InvoiceAllowanceSeller.Organization }))
.Concat(toIssue.Select(t => new NotifyToProcessID { MailToID = t.DerivedDocument.ParentDocument.InvoiceAllowance.InvoiceAllowanceBuyer.BuyerID, Seller = t.DerivedDocument.ParentDocument.InvoiceAllowance.InvoiceAllowanceSeller.Organization }))
.Concat(toIssue.Select(t => new NotifyToProcessID { MailToID = (int?)t.ReceiptItem.SellerID, Seller = t.ReceiptItem.Seller }))
.Concat(toIssue.Select(t => new NotifyToProcessID { MailToID = (int?)t.DerivedDocument.ParentDocument.ReceiptItem.SellerID, Seller = t.DerivedDocument.ParentDocument.ReceiptItem.Seller }))
.Distinct();
foreach (var businessID in notifyToIssue)
{
var item = org.Where(o => o.CompanyID == businessID.MailToID).FirstOrDefault();
if (item != null && (item.OrganizationStatus == null || item.OrganizationStatus.Entrusting != true))
{
//EIVOPlatformFactory.NotifyIssuedA0401(this, new EventArgs<NotifyToProcessID> { Argument = businessID });
}
}
}
var toReceive = notify.Select(r => r.DocumentReplication.CDS_Document).Where(d => d.CurrentStep == (int)Naming.InvoiceStepDefinition.待接收);
if (toReceive.Count() > 0)
{
var notifyToReceive = toReceive.Select(t => new NotifyToProcessID { MailToID = t.InvoiceItem.InvoiceBuyer.BuyerID, Seller = t.InvoiceItem.InvoiceSeller.Organization, itemNO = t.InvoiceItem.TrackCode + t.InvoiceItem.No })
.Concat(toReceive.Select(t => new NotifyToProcessID { MailToID = t.DerivedDocument.ParentDocument.InvoiceItem.InvoiceBuyer.BuyerID, Seller = t.DerivedDocument.ParentDocument.InvoiceItem.InvoiceSeller.Organization, itemNO = t.DerivedDocument.ParentDocument.InvoiceItem.TrackCode + t.DerivedDocument.ParentDocument.InvoiceItem.No }))
.Concat(toReceive.Select(t => new NotifyToProcessID { MailToID = t.InvoiceAllowance.InvoiceAllowanceSeller.SellerID, Seller = t.InvoiceAllowance.InvoiceAllowanceSeller.Organization, itemNO = t.InvoiceAllowance.InvoiceItem.TrackCode + t.InvoiceAllowance.InvoiceItem.No }))
.Concat(toReceive.Select(t => new NotifyToProcessID { MailToID = t.DerivedDocument.ParentDocument.InvoiceAllowance.InvoiceAllowanceSeller.SellerID, Seller = t.DerivedDocument.ParentDocument.InvoiceAllowance.InvoiceAllowanceSeller.Organization, itemNO = t.DerivedDocument.ParentDocument.InvoiceAllowance.InvoiceItem.TrackCode + t.DerivedDocument.ParentDocument.InvoiceAllowance.InvoiceItem.No }))
.Concat(toReceive.Select(t => new NotifyToProcessID { MailToID = (int?)t.ReceiptItem.BuyerID, Seller = t.ReceiptItem.Seller, itemNO = t.ReceiptItem.No }))
.Concat(toReceive.Select(t => new NotifyToProcessID { MailToID = (int?)t.DerivedDocument.ParentDocument.ReceiptItem.BuyerID, Seller = t.DerivedDocument.ParentDocument.ReceiptItem.Seller, itemNO = t.DerivedDocument.ParentDocument.ReceiptItem.No }))
.Distinct();
foreach (var businessID in notifyToReceive)
{
var item = org.Where(o => o.CompanyID == businessID.MailToID).FirstOrDefault();
//var InvoiceInfo = new NotifyToProcessID { InvoiceItem = item.InvoiceItem, isMail = false };
if (item != null && (item.OrganizationStatus == null || item.OrganizationStatus.Entrusting != true))
{
//EIVOPlatformFactory.NotifyToReceiveItem(this, new EventArgs<NotifyToProcessID> { Argument = businessID });
}
}
}
foreach (var i in items)
{
mgr.DeleteAny<DocumentDispatch>(d => d.DocID == i.DocID && d.TypeID == i.TypeID);
mgr.DeleteAny<DocumentReplication>(d => d.DocID == i.DocID && d.TypeID == i.TypeID);
}
}
}
}
//public void NotifyCounterpartBusiness()
//{
// using (InvoiceManager mgr = new InvoiceManager())
// {
// var notify = mgr.GetTable<ReplicationNotification>();
// var items = notify.ToList();
// var toIssue = mgr.GetTable<CDS_Document>().Where(d => d.CurrentStep == (int)Naming.B2BInvoiceStepDefinition.待開立);
// var notifyToIssue = toIssue
// .Join(mgr.EntityList, d => d.DocID, i => i.InvoiceID, (d, i) => i)
// .Join(notify, t => t.InvoiceID, s => s.DocID, (t, s) => new _key { a = t.InvoiceSeller.SellerID, b = t.InvoiceBuyer.BuyerID })
// .Join(mgr.GetTable<BusinessRelationship>(), k => k, r => new _key { a = r.RelativeID, b = r.MasterID }, (k, r) => k.a)
// .Concat(toIssue
// .Join(mgr.GetTable<DerivedDocument>(), t => t.DocID, d => d.DocID, (t, d) => d)
// .Join(mgr.EntityList, d => d.SourceID, i => i.InvoiceID, (d, i) => i)
// .Join(notify, t => t.InvoiceID, s => s.DocID, (t, s) => new _key { a = t.InvoiceSeller.SellerID, b = t.InvoiceBuyer.BuyerID })
// .Join(mgr.GetTable<BusinessRelationship>(), k => k, r => new _key { a = r.RelativeID, b = r.MasterID }, (k, r) => k.a))
// .Concat(toIssue
// .Join(mgr.GetTable<InvoiceAllowance>(), d => d.DocID, i => i.AllowanceID, (d, i) => i)
// .Join(notify, t => t.AllowanceID, s => s.DocID, (t, s) => new _key { a = t.InvoiceAllowanceSeller.SellerID, b = t.InvoiceAllowanceBuyer.BuyerID })
// .Join(mgr.GetTable<BusinessRelationship>(), k => k, r => new _key { a = r.MasterID, b = r.RelativeID }, (k, r) => k.b))
// .Concat(toIssue
// .Join(mgr.GetTable<DerivedDocument>(), t => t.DocID, d => d.DocID, (t, d) => d)
// .Join(mgr.GetTable<InvoiceAllowance>(), d => d.SourceID, i => i.AllowanceID, (d, i) => i)
// .Join(notify, t => t.AllowanceID, s => s.DocID, (t, s) => new _key { a = t.InvoiceAllowanceSeller.SellerID, b = t.InvoiceAllowanceBuyer.BuyerID })
// .Join(mgr.GetTable<BusinessRelationship>(), k => k, r => new _key { a = r.MasterID, b = r.RelativeID }, (k, r) => k.b))
// .Concat(toIssue
// .Join(mgr.GetTable<ReceiptItem>(), d => d.DocID, i => i.ReceiptID, (d, i) => i)
// .Join(notify, t => t.ReceiptID, s => s.DocID, (t, s) => new _key { a = t.SellerID, b = t.BuyerID })
// .Join(mgr.GetTable<BusinessRelationship>(), k => k, r => new _key { a = r.RelativeID, b = r.MasterID }, (k, r) => k.a))
// .Concat(toIssue
// .Join(mgr.GetTable<DerivedDocument>(), t => t.DocID, d => d.DocID, (t, d) => d)
// .Join(mgr.GetTable<ReceiptItem>(), d => d.SourceID, i => i.ReceiptID, (d, i) => i)
// .Join(notify, t => t.ReceiptID, s => s.DocID, (t, s) => new _key { a = t.SellerID, b = t.BuyerID })
// .Join(mgr.GetTable<BusinessRelationship>(), k => k, r => new _key { a = r.RelativeID, b = r.MasterID }, (k, r) => k.a))
// .Distinct();
// var toReceive = mgr.GetTable<CDS_Document>().Where(d => d.CurrentStep == (int)Naming.B2BInvoiceStepDefinition.待接收);
// var notifyToReceive = toReceive
// .Join(mgr.EntityList, d => d.DocID, i => i.InvoiceID, (d, i) => i)
// .Join(notify, t => t.InvoiceID, s => s.DocID, (t, s) => new _key { a = t.InvoiceSeller.SellerID, b = t.InvoiceBuyer.BuyerID })
// .Join(mgr.GetTable<BusinessRelationship>(), k => k, r => new _key { a = r.MasterID, b = r.RelativeID }, (k, r) => k.b)
// .Concat(toReceive
// .Join(mgr.GetTable<DerivedDocument>(), t => t.DocID, d => d.DocID, (t, d) => d)
// .Join(mgr.EntityList, d => d.SourceID, i => i.InvoiceID, (d, i) => i)
// .Join(notify, t => t.InvoiceID, s => s.DocID, (t, s) => new _key { a = t.InvoiceSeller.SellerID, b = t.InvoiceBuyer.BuyerID })
// .Join(mgr.GetTable<BusinessRelationship>(), k => k, r => new _key { a = r.MasterID, b = r.RelativeID }, (k, r) => k.b))
// .Concat(toReceive
// .Join(mgr.GetTable<InvoiceAllowance>(), d => d.DocID, i => i.AllowanceID, (d, i) => i)
// .Join(notify, t => t.AllowanceID, s => s.DocID, (t, s) => new _key { a = t.InvoiceAllowanceSeller.SellerID, b = t.InvoiceAllowanceBuyer.BuyerID })
// .Join(mgr.GetTable<BusinessRelationship>(), k => k, r => new _key { a = r.RelativeID, b = r.MasterID }, (k, r) => k.a))
// .Concat(toReceive
// .Join(mgr.GetTable<DerivedDocument>(), t => t.DocID, d => d.DocID, (t, d) => d)
// .Join(mgr.GetTable<InvoiceAllowance>(), d => d.SourceID, i => i.AllowanceID, (d, i) => i)
// .Join(notify, t => t.AllowanceID, s => s.DocID, (t, s) => new _key { a = t.InvoiceAllowanceSeller.SellerID, b = t.InvoiceAllowanceBuyer.BuyerID })
// .Join(mgr.GetTable<BusinessRelationship>(), k => k, r => new _key { a = r.RelativeID, b = r.MasterID }, (k, r) => k.a))
// .Concat(toReceive
// .Join(mgr.GetTable<ReceiptItem>(), d => d.DocID, i => i.ReceiptID, (d, i) => i)
// .Join(notify, t => t.ReceiptID, s => s.DocID, (t, s) => new _key { a = t.SellerID, b = t.BuyerID })
// .Join(mgr.GetTable<BusinessRelationship>(), k => k, r => new _key { a = r.MasterID, b = r.RelativeID }, (k, r) => k.b))
// .Concat(toReceive
// .Join(mgr.GetTable<DerivedDocument>(), t => t.DocID, d => d.DocID, (t, d) => d)
// .Join(mgr.GetTable<ReceiptItem>(), d => d.SourceID, i => i.ReceiptID, (d, i) => i)
// .Join(notify, t => t.ReceiptID, s => s.DocID, (t, s) => new _key { a = t.SellerID, b = t.BuyerID })
// .Join(mgr.GetTable<BusinessRelationship>(), k => k, r => new _key { a = r.MasterID, b = r.RelativeID }, (k, r) => k.b))
// .Distinct();
// var org = mgr.GetTable<Organization>();
// foreach (var businessID in notifyToIssue)
// {
// var item = org.Where(o => o.CompanyID == businessID).FirstOrDefault();
// if (item != null && (item.OrganizationStatus == null || item.OrganizationStatus.Entrusting != true))
// {
// EIVOPlatformFactory.NotifyToIssueItem(this, new EventArgs<Organization> { Argument = item });
// }
// }
// foreach (var businessID in notifyToReceive)
// {
// var item = org.Where(o => o.CompanyID == businessID).FirstOrDefault();
// if (item != null && (item.OrganizationStatus == null || item.OrganizationStatus.Entrusting != true))
// {
// EIVOPlatformFactory.NotifyToReceiveItem(this, new EventArgs<Organization> { Argument = item });
// }
// }
// mgr.ExecuteCommand("delete dbo.DocumentReplication");
// mgr.ExecuteCommand("delete dbo.DocumentDispatch");
// notify.DeleteAllOnSubmit(items);
// mgr.SubmitChanges();
// }
//}
private void saveToPlatform(InvoiceManager mgr)
{
//Settings.Default.A1401Outbound.CheckStoredPath();
//int invoiceCounter = Directory.GetFiles(Settings.Default.A1401Outbound).Length;
//Settings.Default.B1401Outbound.CheckStoredPath();
//int allowanceCounter = Directory.GetFiles(Settings.Default.B1401Outbound).Length;
Settings.Default.A0501Outbound.CheckStoredPath();
int cancellationCounter = Directory.GetFiles(Settings.Default.A0501Outbound).Length;
Settings.Default.B0501Outbound.CheckStoredPath();
int allowanceCancellationCounter = Directory.GetFiles(Settings.Default.B0501Outbound).Length;
var items = mgr.GetTable<CDS_Document>().Where(d => d.CurrentStep == (int)Naming.InvoiceStepDefinition.待傳送);
if (items.Count() > 0)
{
String fileName;
foreach (var item in items)
{
try
{
switch ((Naming.DocumentTypeDefinition)item.DocType.Value)
{
case Naming.DocumentTypeDefinition.E_Invoice:
//if (item.InvoiceItem.InvoiceSeller.Organization.OrganizationStatus != null && item.InvoiceItem.InvoiceSeller.Organization.OrganizationStatus.IronSteelIndustry == true)
//{
// fileName = Path.Combine(Settings.Default.A1401Outbound, String.Format("A1401-{0:yyyyMMddHHmmssf}-{1:00000}.xml", DateTime.Now, invoiceCounter++));
// item.InvoiceItem.CreateA1401().ConvertToXml().Save(fileName);
//}
//else
{
fileName = Path.Combine(Settings.Default.A0401Outbound, $"A0401-{DateTime.Now:yyyyMMddHHmmssf}-{item.InvoiceItem.TrackCode}{item.InvoiceItem.No}.xml");
item.InvoiceItem.CreateA0401().ConvertToXml().Save(fileName);
}
break;
case Naming.DocumentTypeDefinition.E_Allowance:
//if (item.InvoiceAllowance.InvoiceAllowanceSeller.Organization.OrganizationStatus != null && item.InvoiceAllowance.InvoiceAllowanceSeller.Organization.OrganizationStatus.IronSteelIndustry == true)
//{
// fileName = Path.Combine(Settings.Default.B1401Outbound, String.Format("B1401-{0:yyyyMMddHHmmssf}-{1:00000}.xml", DateTime.Now, allowanceCounter++));
// item.InvoiceAllowance.CreateB1401().ConvertToXml().Save(fileName);
//}
//else
{
fileName = Path.Combine(Settings.Default.B0401Outbound, $"B0401-{DateTime.Now:yyyyMMddHHmmssf}-{item.InvoiceAllowance.AllowanceNumber}.xml");
item.InvoiceAllowance.CreateB0401().ConvertToXml().Save(fileName);
}
break;
case Naming.DocumentTypeDefinition.E_InvoiceCancellation:
fileName = Path.Combine(Settings.Default.A0501Outbound, String.Format("A0501-{0:yyyyMMddHHmmssf}-{1:00000}.xml", DateTime.Now, cancellationCounter++));
item.DerivedDocument.ParentDocument.InvoiceItem.CreateA0501().ConvertToXml().Save(fileName);
break;
case Naming.DocumentTypeDefinition.E_AllowanceCancellation:
fileName = Path.Combine(Settings.Default.B0501Outbound, String.Format("B0501-{0:yyyyMMddHHmmssf}-{1:00000}.xml", DateTime.Now, allowanceCancellationCounter++));
item.DerivedDocument.ParentDocument.InvoiceAllowance.CreateB0501().ConvertToXml().Save(fileName);
break;
}
transmit(mgr, item);
}
catch (Exception ex)
{
Logger.Error(ex);
}
}
}
}
public void saveBranchTrackBlankToPlatform(XmlDocument Doc)
{
String fileName;
Settings.Default.E0402Outbound.CheckStoredPath();
int counter = Directory.GetFiles(Settings.Default.E0402Outbound).Length;
fileName = Path.Combine(Settings.Default.E0402Outbound, String.Format("E0402-{0:yyyyMMddHHmmssf}-{1:00000}.xml", DateTime.Now, counter++));
Doc.Save(fileName);
}
public void CommissionedToReceive()
{
using (InvoiceManager mgr = new InvoiceManager())
{
var items = mgr.GetTable<CDS_Document>().Where(d => d.CurrentStep == (int)Naming.InvoiceStepDefinition.待接收);
if (items.Count() > 0)
{
StringBuilder sb = new StringBuilder();
foreach (var item in items)
{
try
{
bool bSigned = false;
switch ((Naming.B2BInvoiceDocumentTypeDefinition)item.DocType.Value)
{
case Naming.B2BInvoiceDocumentTypeDefinition.電子發票:
if (item.InvoiceItem.InvoiceBuyer.Organization.OrganizationStatus.Entrusting == true)
{
sb.Clear();
if (item.InvoiceItem.InvoiceBuyer.Organization.IsEnterpriseGroupMember())
{
var cert = (new B2BInvoiceManager(mgr)).PrepareSignerCertificate(item.InvoiceItem.InvoiceBuyer.Organization);
if (cert != null)
{
bSigned = item.InvoiceItem.SignAndCheckToReceiveInvoiceItem(cert, sb);
}
}
else
{
bSigned = item.InvoiceItem.SignAndCheckToReceiveInvoiceItem(null, sb);
}
if (bSigned)
{
EIVOPlatformFactory.NotifyCommissionedToReceiveA0401(new NotifyToProcessID { DocID = item.DocID });
}
}
break;
case Naming.B2BInvoiceDocumentTypeDefinition.發票折讓:
if (item.InvoiceAllowance.InvoiceAllowanceSeller.Organization.OrganizationStatus.Entrusting == true)
{
sb.Clear();
if (item.InvoiceAllowance.InvoiceAllowanceSeller.Organization.IsEnterpriseGroupMember())
{
var cert = (new B2BInvoiceManager(mgr)).PrepareSignerCertificate(item.InvoiceAllowance.InvoiceAllowanceSeller.Organization);
if (cert != null)
{
bSigned = item.InvoiceAllowance.SignAndCheckToReceiveInvoiceAllowance(cert, sb);
}
}
else
{
bSigned = item.InvoiceAllowance.SignAndCheckToReceiveInvoiceAllowance(null, sb);
}
if (bSigned)
{
var businessID = new NotifyToProcessID
{
MailToID = item.InvoiceAllowance.InvoiceAllowanceBuyer.BuyerID,
Seller = item.InvoiceAllowance.InvoiceAllowanceSeller.Organization,
DocID = item.DocID
};
EIVOPlatformFactory.NotifyCommissionedToReceive(this, new EventArgs<NotifyToProcessID> { Argument = businessID });
}
}
break;
case Naming.B2BInvoiceDocumentTypeDefinition.作廢發票:
if (item.DerivedDocument.ParentDocument.InvoiceItem.InvoiceBuyer.Organization.OrganizationStatus.Entrusting == true)
{
sb.Clear();
if (item.DerivedDocument.ParentDocument.InvoiceItem.InvoiceBuyer.Organization.IsEnterpriseGroupMember())
{
var cert = (new B2BInvoiceManager(mgr)).PrepareSignerCertificate(item.DerivedDocument.ParentDocument.InvoiceItem.InvoiceBuyer.Organization);
if (cert != null)
{
bSigned = item.DerivedDocument.ParentDocument.InvoiceItem.SignAndCheckToReceiveInvoiceCancellation(cert, sb, item.DocID);
}
}
else
{
bSigned = item.DerivedDocument.ParentDocument.InvoiceItem.SignAndCheckToReceiveInvoiceCancellation(null, sb, item.DocID);
}
if (bSigned)
{
var businessID = new NotifyToProcessID
{
DocID = item.DocID
};
EIVOPlatformFactory.NotifyCommissionedToReceiveInvoiceCancellation(this, new EventArgs<NotifyToProcessID> { Argument = businessID });
}
}
break;
case Naming.B2BInvoiceDocumentTypeDefinition.作廢折讓:
if (item.DerivedDocument.ParentDocument.InvoiceAllowance.InvoiceAllowanceSeller.Organization.OrganizationStatus.Entrusting == true)
{
sb.Clear();
if (item.DerivedDocument.ParentDocument.InvoiceAllowance.InvoiceAllowanceSeller.Organization.IsEnterpriseGroupMember())
{
var cert = (new B2BInvoiceManager(mgr)).PrepareSignerCertificate(item.DerivedDocument.ParentDocument.InvoiceAllowance.InvoiceAllowanceSeller.Organization);
if (cert != null)
{
bSigned = item.DerivedDocument.ParentDocument.InvoiceAllowance.SignAndCheckToReceiveAllowanceCancellation(cert, sb, item.DocID);
}
}
else
{
bSigned = item.DerivedDocument.ParentDocument.InvoiceAllowance.SignAndCheckToReceiveAllowanceCancellation(null, sb, item.DocID);
}
if (bSigned)
{
var businessID = new NotifyToProcessID
{
MailToID = item.DerivedDocument.ParentDocument.InvoiceAllowance.InvoiceAllowanceBuyer.BuyerID,
Seller = item.DerivedDocument.ParentDocument.InvoiceAllowance.InvoiceAllowanceSeller.Organization,
DocID = item.DocID
};
EIVOPlatformFactory.NotifyCommissionedToReceive(this, new EventArgs<NotifyToProcessID> { Argument = businessID });
}
}
break;
case Naming.B2BInvoiceDocumentTypeDefinition.收據:
if (item.ReceiptItem != null && item.ReceiptItem.Buyer.OrganizationStatus.Entrusting == true)
{
sb.Clear();
if (item.ReceiptItem.Buyer.IsEnterpriseGroupMember())
{
var cert = (new B2BInvoiceManager(mgr)).PrepareSignerCertificate(item.ReceiptItem.Buyer);
if (cert != null)
{
bSigned = item.ReceiptItem.SignAndCheckToReceiveReceipt(cert, sb);
}
}
else
{
bSigned = item.ReceiptItem.SignAndCheckToReceiveReceipt(null, sb);
}
if (bSigned)
{
var businessID = new NotifyToProcessID
{
MailToID = item.ReceiptItem.BuyerID,
Seller = item.ReceiptItem.Seller,
DocID = item.DocID
};
EIVOPlatformFactory.NotifyCommissionedToReceive(this, new EventArgs<NotifyToProcessID> { Argument = businessID });
}
}
break;
case Naming.B2BInvoiceDocumentTypeDefinition.作廢收據:
if (item.DerivedDocument.ParentDocument.ReceiptItem.Buyer.OrganizationStatus.Entrusting == true)
{
sb.Clear();
if (item.DerivedDocument.ParentDocument.ReceiptItem.Buyer.IsEnterpriseGroupMember())
{
var cert = (new B2BInvoiceManager(mgr)).PrepareSignerCertificate(item.DerivedDocument.ParentDocument.ReceiptItem.Buyer);
if (cert != null)
{
bSigned = item.DerivedDocument.ParentDocument.ReceiptItem.SignAndCheckToReceiveReceiptCancellation(cert, sb, item.DocID);
}
}
else
{
bSigned = item.DerivedDocument.ParentDocument.ReceiptItem.SignAndCheckToReceiveReceiptCancellation(null, sb, item.DocID);
}
if (bSigned)
{
var businessID = new NotifyToProcessID
{
MailToID = item.DerivedDocument.ParentDocument.ReceiptItem.BuyerID,
Seller = item.DerivedDocument.ParentDocument.ReceiptItem.Seller,
DocID = item.DocID
};
EIVOPlatformFactory.NotifyCommissionedToReceive(this, new EventArgs<NotifyToProcessID> { Argument = businessID });
}
}
break;
default:
break;
}
if (bSigned)
{
transmit(mgr, item);
}
}
catch (Exception ex)
{
Logger.Error(ex);
}
}
}
}
}
public void CommissionedToIssue()
{
using (InvoiceManager mgr = new InvoiceManager())
{
var items = mgr.GetTable<CDS_Document>().Where(d => d.CurrentStep == (int)Naming.InvoiceStepDefinition.待開立);
if (items.Count() > 0)
{
StringBuilder sb = new StringBuilder();
foreach (var item in items)
{
try
{
bool bSigned = false;
switch ((Naming.B2BInvoiceDocumentTypeDefinition)item.DocType.Value)
{
case Naming.B2BInvoiceDocumentTypeDefinition.電子發票:
if (item.InvoiceItem.InvoiceSeller.Organization.OrganizationStatus.Entrusting == true)
{
sb.Clear();
if (item.InvoiceItem.InvoiceSeller.Organization.IsEnterpriseGroupMember())
{
var cert = (new B2BInvoiceManager(mgr)).PrepareSignerCertificate(item.InvoiceItem.InvoiceSeller.Organization);
if (cert != null)
{
bSigned = item.InvoiceItem.SignAndCheckToIssueInvoiceItem(cert, sb);
}
}
else
{
bSigned = item.InvoiceItem.SignAndCheckToIssueInvoiceItem(null, sb);
}
}
break;
case Naming.B2BInvoiceDocumentTypeDefinition.發票折讓:
if (item.InvoiceAllowance.InvoiceAllowanceBuyer.Organization.OrganizationStatus.Entrusting == true)
{
sb.Clear();
if (item.InvoiceAllowance.InvoiceAllowanceBuyer.Organization.IsEnterpriseGroupMember())
{
var cert = (new B2BInvoiceManager(mgr)).PrepareSignerCertificate(item.InvoiceAllowance.InvoiceAllowanceBuyer.Organization);
if (cert != null)
{
bSigned = item.InvoiceAllowance.SignAndCheckToIssueInvoiceAllowance(cert, sb);
}
}
else
{
bSigned = item.InvoiceAllowance.SignAndCheckToIssueInvoiceAllowance(null, sb);
}
}
break;
case Naming.B2BInvoiceDocumentTypeDefinition.作廢發票:
if (item.DerivedDocument.ParentDocument.InvoiceItem.InvoiceSeller.Organization.OrganizationStatus.Entrusting == true)
{
sb.Clear();
if (item.DerivedDocument.ParentDocument.InvoiceItem.InvoiceSeller.Organization.IsEnterpriseGroupMember())
{
var cert = (new B2BInvoiceManager(mgr)).PrepareSignerCertificate(item.DerivedDocument.ParentDocument.InvoiceItem.InvoiceSeller.Organization);
if (cert != null)
{
bSigned = item.DerivedDocument.ParentDocument.InvoiceItem.SignAndCheckToIssueInvoiceCancellation(cert, sb, item.DocID);
}
}
else
{
bSigned = item.DerivedDocument.ParentDocument.InvoiceItem.SignAndCheckToIssueInvoiceCancellation(null, sb, item.DocID);
}
}
break;
case Naming.B2BInvoiceDocumentTypeDefinition.作廢折讓:
if (item.DerivedDocument.ParentDocument.InvoiceAllowance.InvoiceAllowanceBuyer.Organization.OrganizationStatus.Entrusting == true)
{
sb.Clear();
if (item.DerivedDocument.ParentDocument.InvoiceAllowance.InvoiceAllowanceBuyer.Organization.IsEnterpriseGroupMember())
{
var cert = (new B2BInvoiceManager(mgr)).PrepareSignerCertificate(item.DerivedDocument.ParentDocument.InvoiceAllowance.InvoiceAllowanceBuyer.Organization);
if (cert != null)
{
bSigned = item.DerivedDocument.ParentDocument.InvoiceAllowance.SignAndCheckToIssueAllowanceCancellation(cert, sb, item.DocID);
}
}
else
{
bSigned = item.DerivedDocument.ParentDocument.InvoiceAllowance.SignAndCheckToIssueAllowanceCancellation(null, sb, item.DocID);
}
}
break;
case Naming.B2BInvoiceDocumentTypeDefinition.收據:
if (item.ReceiptItem.Seller.OrganizationStatus.Entrusting == true)
{
sb.Clear();
if (item.ReceiptItem.Seller.IsEnterpriseGroupMember())
{
var cert = (new B2BInvoiceManager(mgr)).PrepareSignerCertificate(item.ReceiptItem.Seller);
if (cert != null)
{
bSigned = item.ReceiptItem.SignAndCheckToIssueReceipt(cert, sb);
}
}
else
{
bSigned = item.ReceiptItem.SignAndCheckToIssueReceipt(null, sb);
}
}
break;
case Naming.B2BInvoiceDocumentTypeDefinition.作廢收據:
if (item.DerivedDocument.ParentDocument.ReceiptItem.Seller.OrganizationStatus.Entrusting == true)
{
sb.Clear();
if (item.DerivedDocument.ParentDocument.ReceiptItem.Seller.IsEnterpriseGroupMember())
{
var cert = (new B2BInvoiceManager(mgr)).PrepareSignerCertificate(item.DerivedDocument.ParentDocument.ReceiptItem.Seller);
if (cert != null)
{
bSigned = item.DerivedDocument.ParentDocument.ReceiptItem.ReceiptCancellation.SignAndCheckToIssueReceiptCancellation(item.DerivedDocument.ParentDocument.ReceiptItem, cert, sb, item.DocID);
}
}
else
{
bSigned = item.DerivedDocument.ParentDocument.ReceiptItem.ReceiptCancellation.SignAndCheckToIssueReceiptCancellation(item.DerivedDocument.ParentDocument.ReceiptItem, null, sb, item.DocID);
}
}
break;
default:
break;
}
if (bSigned)
{
transmit(mgr, item);
}
}
catch (Exception ex)
{
Logger.Error(ex);
}
}
}
}
}
public void MatchDocumentAttachment()
{
using (InvoiceManager mgr = new InvoiceManager())
{
var invoices = mgr.GetTable<InvoiceItem>();
((EIVOEntityDataContext)invoices.Context).MatchDocumentAttachment();
}
}
private void transmit(GenericManager<EIVOEntityDataContext> mgr, CDS_Document item)
{
item.MoveToNextStep(mgr);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassInheritExercise
{
public class Alumno : Persona, IAlumno
{
public int Matricula { get; set; }
public string Estudios { get; set; }
public List<Asignatura> cursando = new List<Asignatura>();
public Alumno(int matricula, string estudios, List<Asignatura> cursando, string nombre, string apellido, string dni) : base(nombre, apellido, dni)
{
Matricula = matricula;
Estudios = estudios;
this.cursando = cursando;
Nombre = nombre;
Apellido = apellido;
Dni = dni;
}
public Alumno()
{
}
public void EstudiarCosas(IAsignatura a, int tiempoEstudio, IProfesor p, IAlumno f)
{
if (tiempoEstudio > 0)
{
throw new Exception("Ha estudiado " + a.nombre + " " + tiempoEstudio + " horas") ;
}
else
{
p.SuspenderCosas(f, true);
}
}
public bool HacerDeberesDeCosas(bool aproElTiempo)
{
return aproElTiempo;
}
public void MeterseEnDiscord(bool entrar)
{
if (entrar == true)
{
HacerDeberesDeCosas(false);
}
else
{
throw new Exception("Se puede aprobar todavia");
}
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using ZeroFormatter.Comparers;
using ZeroFormatter.Formatters;
using ZeroFormatter.Internal;
using ZeroFormatter.Segments;
using RuntimeUnitTestToolkit;
namespace ZeroFormatter.Tests
{
[TestClass]
public class DictionarySegmentTest
{
DictionarySegment<DefaultResolver, int, string> CreateFresh()
{
ILazyDictionary<int, string> sampleDict = new Dictionary<int, string>()
{
{1234, "aaaa" },
{-1, "mainasu" },
{-42432, "more mainasu" },
{99999, "plus plus" }
}.AsLazyDictionary();
return ZeroFormatter.ZeroFormatterSerializer.Convert(sampleDict) as DictionarySegment<DefaultResolver, int, string>;
}
[TestMethod]
public void DictionarySegment()
{
var dict = CreateFresh();
dict[1234].Is("aaaa");
dict[-1].Is("mainasu");
dict[-42432].Is("more mainasu");
dict[99999].Is("plus plus");
dict.Count.Is(4);
dict.OrderBy(x => x.Key).Select(x => Tuple.Create(x.Key, x.Value)).IsCollection(
Tuple.Create(-42432, "more mainasu"),
Tuple.Create(-1, "mainasu"),
Tuple.Create(1234, "aaaa"),
Tuple.Create(99999, "plus plus"));
dict[1234] = "zzz";
dict[1234].Is("zzz");
dict.Count.Is(4);
dict.OrderBy(x => x.Key).Select(x => Tuple.Create(x.Key, x.Value)).IsCollection(
Tuple.Create(-42432, "more mainasu"),
Tuple.Create(-1, "mainasu"),
Tuple.Create(1234, "zzz"),
Tuple.Create(99999, "plus plus"));
dict.Add(9999, "hogehoge");
dict[9999].Is("hogehoge");
dict.Count.Is(5);
dict.OrderBy(x => x.Key).Select(x => Tuple.Create(x.Key, x.Value)).IsCollection(
Tuple.Create(-42432, "more mainasu"),
Tuple.Create(-1, "mainasu"),
Tuple.Create(1234, "zzz"),
Tuple.Create(9999, "hogehoge"),
Tuple.Create(99999, "plus plus"));
dict.Clear();
dict.Count.Is(0);
dict.ToArray().IsEmpty();
dict.Add(1234, "aaaa");
dict.Add(-1, "mainus one");
dict.Add(9991, "hogehoge one");
dict.ContainsKey(1234).IsTrue();
dict.ContainsKey(-9999).IsFalse();
dict.ContainsValue("aaaa").IsTrue();
dict.ContainsValue("not not").IsFalse();
dict.Remove(1234).IsTrue();
dict.Remove(-30).IsFalse();
dict.ToArray().Length.Is(2); // CopyTo
dict.OrderBy(x => x.Key).Select(x => Tuple.Create(x.Key, x.Value)).IsCollection(
Tuple.Create(-1, "mainus one"),
Tuple.Create(9991, "hogehoge one"));
}
public void ModeLazyAll()
{
ILazyDictionary<int, string> dict = new Dictionary<int, string>
{
{1, "a" },
{2, "b" },
{3, "c" }
}.AsLazyDictionary();
var immediateLazySegment = ZeroFormatterSerializer.Convert(dict);
var segment = immediateLazySegment as IZeroFormatterSegment;
immediateLazySegment[1].Is("a");
immediateLazySegment[2].Is("b");
immediateLazySegment[3].Is("c");
segment.CanDirectCopy().IsTrue();
var moreSerialize = ZeroFormatterSerializer.Convert(immediateLazySegment, true);
(moreSerialize as IZeroFormatterSegment).CanDirectCopy().IsTrue();
moreSerialize.Add(10, "hugahuga");
(moreSerialize as IZeroFormatterSegment).CanDirectCopy().IsFalse();
moreSerialize[10].Is("hugahuga");
var lastSerialize = ZeroFormatterSerializer.Convert(moreSerialize, true);
lastSerialize[1].Is("a");
lastSerialize[2].Is("b");
lastSerialize[3].Is("c");
moreSerialize[10].Is("hugahuga");
}
}
}
|
using Messages;
using Messages.Commands;
using NServiceBus;
using NServiceBus.Logging;
using System.Threading.Tasks;
namespace Billing
{
public class OrderPlacedHandler : IHandleMessages<OrderPlaced>
{
static ILog log = LogManager.GetLogger<OrderPlacedHandler>();
public Task Handle(OrderPlaced message, IMessageHandlerContext context)
{
log.Info($"Received OrderPlaced, OrderId = {message.OrderId} - Charging credit card...");
// This is normally where some business logic would occur
// Create event
var orderBilled = new OrderBilled
{
OrderId = message.OrderId
};
return context.Publish(orderBilled);
// return Task.CompletedTask;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication5
{
interface IPlayable
{
void Play();
void Stop();
void Pause();
}
interface IRecodable
{
void Pause();
void Record();
void Stop();
}
class Player : IPlayable, IRecodable
{
public void Play()
{
Console.WriteLine("Play in IP");
}
void IPlayable.Stop()
{
Console.WriteLine("Stop in IP");
}
void IPlayable.Pause() { Console.WriteLine("Pause in IP"); }
//
void IRecodable.Record()
{
Console.WriteLine("Record in IR");
}
void IRecodable.Stop()
{
Console.WriteLine("Stop in IR");
}
void IRecodable.Pause() { Console.WriteLine("Pause in IR"); }
}
class Progran
{
static void Main()
{
Player pl = new Player();
IPlayable IP = pl as Player;
IP.Play();
Console.ReadKey();
}
}
}
|
using UnityEngine;
using System.Collections;
using HutongGames.PlayMaker;
using Assets.Modules.Utility;
public class ScrollScript : MonoBehaviour {
public GameObject CharacterToFollow;
public float speed = .2f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
// if (CharacterToFollow != null)
// {
renderer.material.mainTextureOffset = new Vector2(FsmVariables.GlobalVariables.GetFsmFloat(GlobalNames.DistanceTraveled).Value * speed/1000, 0f);
// }
}
}
|
// Copyright 2021 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using NtApiDotNet.Win32.Security.Native;
using System;
namespace NtApiDotNet.Win32.Security.Sam
{
/// <summary>
/// The domain password policy.
/// </summary>
public struct SamDomainPasswordInformation
{
/// <summary>
/// Minimum password length.
/// </summary>
public int MinimumLength { get; }
/// <summary>
/// Password history length.
/// </summary>
public int HistoryLength { get; }
/// <summary>
/// Password properties flags.
/// </summary>
public SamDomainPasswordPropertyFlags Properties;
/// <summary>
/// Maximum password age.
/// </summary>
public TimeSpan MaximumAge;
/// <summary>
/// Minimum password age.
/// </summary>
public TimeSpan MinimumAge;
internal SamDomainPasswordInformation(DOMAIN_PASSWORD_INFORMATION info)
{
MinimumLength = info.MinPasswordLength;
HistoryLength = info.PasswordHistoryLength;
Properties = (SamDomainPasswordPropertyFlags)info.PasswordProperties;
MaximumAge = TimeSpan.FromTicks(-info.MaxPasswordAge.QuadPart);
MinimumAge = TimeSpan.FromTicks(-info.MinPasswordAge.QuadPart);
}
}
}
|
using System;
using System.Collections.Generic;
namespace Torshify.Radio.Framework
{
public interface IRadio : ITrackSource
{
event EventHandler CurrentTrackStreamChanged;
event EventHandler<TrackChangedEventArgs> CurrentTrackChanged;
event EventHandler UpcomingTrackChanged;
event EventHandler TrackStreamQueued;
IEnumerable<Lazy<ITrackSource, ITrackSourceMetadata>> TrackSources
{
get;
}
IEnumerable<Lazy<ITrackPlayer, ITrackPlayerMetadata>> TrackPlayers
{
get;
}
ITrackStream CurrentTrackStream
{
get;
}
Track CurrentTrack
{
get;
}
Track UpcomingTrack
{
get;
}
IEnumerable<Track> UpcomingTracks
{
get;
}
IEnumerable<ITrackStream> TrackStreams
{
get;
}
bool CanGoToNextTrack
{
get;
}
bool CanGoToNextTrackStream
{
get;
}
void Play(ITrackStream trackStream);
void Queue(ITrackStream trackStream);
void NextTrack();
void NextTrackStream();
}
} |
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
#region Usings
using Newtonsoft.Json;
#endregion
namespace Dnn.PersonaBar.SiteSettings.Services.Dto
{
public class UpdateLanguageRequest
{
public int? PortalId { get; set; }
public int? LanguageId { get; set; }
public string Code { get; set; }
public string Roles { get; set; }
public bool Enabled { get; set; }
public string Fallback { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Binding.ControlWrappers;
using System.ComponentModel;
using System.Reflection;
using System.Text.RegularExpressions;
using Binding.Services;
using System.Collections;
namespace Binding
{
[Serializable]
public class BindingPath
{
private BindingPath parent;
public BindingPath Parent { get { return parent; } }
private readonly string raw;
public string Raw { get { return raw; } }
private readonly string fullyQualified;
public string FullyQualified
{
get { return fullyQualified; }
}
private readonly string indexed;
public string Indexed { get { return indexed; } }
private readonly PathMode mode;
public PathMode Mode { get { return mode; } }
public BindingPath(string raw)
{
this.raw = raw;
this.indexed = raw;
this.fullyQualified = raw;
}
public BindingPath(string raw, int indexer)
{
this.raw = raw;
if (raw.Contains("."))
{
int lastDotIndex = raw.LastIndexOf('.');
this.indexed = raw.Insert(lastDotIndex, string.Format("[{0}]", indexer.ToString()));
}
else
{
this.indexed = string.Format("[{0}].{1}",indexer.ToString(),raw);
}
this.fullyQualified = this.indexed;
}
public BindingPath(string raw, int indexer, BindingPath parent, PathMode mode)
: this(raw, indexer)
{
this.parent = parent;
if (mode == PathMode.Relative)
this.fullyQualified = GetFullExpression(parent);
}
public BindingPath(string raw, BindingPath parent)
{
this.parent = parent;
this.raw = raw;
this.indexed = raw;
if (mode == PathMode.Relative)
this.fullyQualified = GetFullExpression(parent);
else
this.fullyQualified = this.raw;
}
public BindingPath(string raw, BindingPath parent, PathMode mode)
{
this.parent = parent;
this.mode = mode;
this.raw = raw;
this.indexed = raw;
if (mode == PathMode.Relative)
this.fullyQualified = GetFullExpression(parent);
else
this.fullyQualified = this.raw;
}
public TargetProperty ResolveAsTarget(IBindingTarget container, IControlService controlService)
{
string[] targetExpressionSplit = this.Raw.Split('.');
IBindingTarget control = controlService.FindControlUnique(container, targetExpressionSplit[0]);
object rawControl = controlService.Unwrap(control);
PropertyDescriptor descriptor = TypeDescriptor.GetProperties(rawControl).Find(targetExpressionSplit[1], true);
object value = null;
if (descriptor != null)
value = descriptor.GetValue(rawControl);
return new TargetProperty { Descriptor = descriptor, OwningControlRaw = rawControl, OwningControl= control, Value = value };
}
public TargetEvent ResolveAsTargetEvent(IBindingTarget container, IControlService controlService)
{
string[] targetExpressionSplit = this.Raw.Split('.');
IBindingTarget control = controlService.FindControlUnique(container, targetExpressionSplit[0]);
object rawControl = controlService.Unwrap(control);
EventInfo info = rawControl.GetType().GetEvent(targetExpressionSplit[1]);
return new TargetEvent { OwningControl = rawControl, Descriptor = info };
}
public SourceProperty ResolveAsSource(object container)
{
return GetSourceProperty(this.FullyQualified, container);
}
private string GetFullExpression(BindingPath parent)
{
return GetParentExpression(parent) + this.Indexed;
}
private string GetParentExpression(BindingPath parent)
{
string basic = string.Empty;
if (parent != null)
{
basic = parent.Indexed;
if (parent.Parent != null)
basic = GetParentExpression(parent.Parent) + basic;
}
if (basic.Length > 0 && !this.Indexed.StartsWith("["))
basic = basic + ".";
return basic;
}
private SourceProperty GetSourceProperty(string path, object container)
{
string[] parts = path.Split('.');
string leftMost = parts[0];
string leftMostName = GetName(leftMost);
int leftMostIndexer = 0;
SourceProperty result = new SourceProperty { OwningInstance = container };
if (!string.IsNullOrEmpty(leftMost))
{
PropertyDescriptor pDescriptor = TypeDescriptor.GetProperties(container).Find(leftMostName, true);
if (pDescriptor != null)
{
result.Descriptor = pDescriptor;
object pValue = pDescriptor.GetValue(container);
//this is the dataitem from the viewstate
IEnumerable enumerablePValue = pValue as IEnumerable;
if (enumerablePValue != null && !(pValue is string))
{
if (TryGetIndexer(leftMost, out leftMostIndexer))
{
pValue = enumerablePValue.GetByIndex(leftMostIndexer);
}
}
if (pValue != null)
{
result.Value = pValue;
//remove the current section and retest
path = path.TrimStart(parts[0].ToCharArray());
path = path.TrimStart(new char[] { '.' });
string[] newParts = path.Split('.');
if (newParts[0] != string.Empty)
result = GetSourceProperty(path, pValue);
return result;
}
}
}
return result;
}
private bool TryGetIndexer(string inputString, out int index)
{
bool result = false;
Match match = Regex.Match(inputString, "[[0-9]*]$");
string strResult = match.Value;
strResult = Regex.Match(strResult, "[0-9]").Value;
result = int.TryParse(strResult, out index);
return result;
}
private string GetName(string inputString)
{
Match match = Regex.Match(inputString, "^[A-Za-z]*");
return match.Value;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace KeyConfig
{
/// <summary>
/// An exception that represents an error which occurred in the key config process.
/// </summary>
public class ConfigManagerException : Exception
{
/// <summary>
/// Creates a new instance of ConfigManagerException.
/// </summary>
public ConfigManagerException() { }
/// <summary>
/// Creates a new instance of ConfigManagerException with a specific message.
/// </summary>
/// <param name="message">The messsage to use.</param>
public ConfigManagerException(string message) : base(message) { }
/// <summary>
/// Creates a new instance of ConfigManagerException with a message and inner exception.
/// </summary>
/// <param name="message">The messsage to use.</param>
/// <param name="inner">The inner exception.</param>
public ConfigManagerException(string message, Exception inner) : base(message, inner) { }
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SFP.Persistencia.Dao;
using SFP.Persistencia.Model;
using SFP.SIT.SERV.Model.SNT;
namespace SFP.SIT.SERV.Dao.SNT
{
public class SIT_SNT_MUNICIPIODao : BaseDao
{
public SIT_SNT_MUNICIPIODao(DbConnection cn, DbTransaction transaction, String dataAdapter) : base(cn, transaction, dataAdapter)
{
}
public Object dmlAgregar(SIT_SNT_MUNICIPIO oDatos)
{
String sSQL = " INSERT INTO SIT_SNT_MUNICIPIO( edoclave, paiclave, munfecbaja, mundescripcion, munclave) VALUES ( :P0, :P1, :P2, :P3, :P4) ";
return EjecutaDML ( sSQL, oDatos.edoclave, oDatos.paiclave, oDatos.munfecbaja, oDatos.mundescripcion, oDatos.munclave );
}
public int dmlImportar( List<SIT_SNT_MUNICIPIO> lstDatos)
{
int iTotReg = 0;
String sSQL = " INSERT INTO SIT_SNT_MUNICIPIO( edoclave, paiclave, munfecbaja, mundescripcion, munclave) VALUES ( :P0, :P1, :P2, :P3, :P4) ";
foreach (SIT_SNT_MUNICIPIO oDatos in lstDatos)
{
EjecutaDML ( sSQL, oDatos.edoclave, oDatos.paiclave, oDatos.munfecbaja, oDatos.mundescripcion, oDatos.munclave );
iTotReg++;
}
return iTotReg;
}
public int dmlEditar(SIT_SNT_MUNICIPIO oDatos)
{
String sSQL = " UPDATE SIT_SNT_MUNICIPIO SET edoclave = :P0, paiclave = :P1, munfecbaja = :P2, mundescripcion = :P3 WHERE munclave = :P4 ";
return (int) EjecutaDML ( sSQL, oDatos.edoclave, oDatos.paiclave, oDatos.munfecbaja, oDatos.mundescripcion, oDatos.munclave );
}
public int dmlBorrar(SIT_SNT_MUNICIPIO oDatos)
{
String sSQL = " DELETE FROM SIT_SNT_MUNICIPIO WHERE munclave = :P0 ";
return (int) EjecutaDML ( sSQL, oDatos.munclave );
}
public List<SIT_SNT_MUNICIPIO> dmlSelectTabla( )
{
String sSQL = " SELECT * FROM SIT_SNT_MUNICIPIO ";
return CrearListaMDL<SIT_SNT_MUNICIPIO>(ConsultaDML(sSQL) as DataTable);
}
public List<ComboMdl> dmlSelectCombo( )
{
String sSQL = " SELECT munclave as ID, MUNDESCRIPCION as DESCRIP FROM SIT_SNT_MUNICIPIO";
return CrearListaMDL<ComboMdl> (ConsultaDML (sSQL) as DataTable);
}
public Dictionary<int, string> dmlSelectDiccionario( )
{
String sSQL = " SELECT munclave, MUNDESCRIPCION FROM SIT_SNT_MUNICIPIO";
DataTable dtDatos = (DataTable)ConsultaDML(sSQL);
Dictionary<int, string> dicCatClases = new Dictionary<int, string>();
foreach (DataRow drDatos in dtDatos.Rows)
dicCatClases.Add(Convert.ToInt32(drDatos[0].ToString()), drDatos[1].ToString());
return dicCatClases;
}
public SIT_SNT_MUNICIPIO dmlSelectID(SIT_SNT_MUNICIPIO oDatos )
{
String sSQL = " SELECT * FROM SIT_SNT_MUNICIPIO WHERE munclave = :P0 ";
return CrearListaMDL<SIT_SNT_MUNICIPIO>(ConsultaDML ( sSQL, oDatos.munclave ) as DataTable)[0];
}
public object dmlCRUD( Dictionary<string, object> dicParam )
{
int iOper = (int)dicParam[CMD_OPERACION];
if (iOper == OPE_INSERTAR)
return dmlAgregar(dicParam[CMD_ENTIDAD] as SIT_SNT_MUNICIPIO );
else if (iOper == OPE_EDITAR)
return dmlEditar(dicParam[CMD_ENTIDAD] as SIT_SNT_MUNICIPIO );
else if (iOper == OPE_BORRAR)
return dmlBorrar(dicParam[CMD_ENTIDAD] as SIT_SNT_MUNICIPIO );
else
return 0;
}
/*INICIO*/
public DataTable dmlSelectGrid(BasePagMdl baseMdl)
{
String sqlQuery = " WITH Resultado AS( select COUNT(*) OVER() RESULT_COUNT, rownum recid, a.* from ( " +
"SELECT PAIS.PAICLAVE, PAIS.PAIDESCRIPCION, MUN.MUNDESCRIPCION, EDO.EDOCLAVE, EDO.EDODESCRIPCION, MUN.MUNCLAVE, MUN.MUNFECBAJA" +
" FROM SIT_SNT_MUNICIPIO MUN, SIT_SNT_PAIS PAIS, SIT_SNT_ESTADO EDO WHERE PAIS.PAICLAVE = MUN.PAICLAVE " +
" AND EDO.EDOCLAVE = MUN.EDOCLAVE ORDER BY MUN.MUNCLAVE, MUN.PAICLAVE ) a ) SELECT * from Resultado WHERE recid between :P0 and :P1 ";
return (DataTable)ConsultaDML(sqlQuery, baseMdl.LimInf, baseMdl.LimSup);
}
/*FIN*/
}
}
|
using UnityEditor;
public class BuildCreator
{
private static readonly BuildTarget buildTarget = BuildTarget.StandaloneWindows64;
private static readonly BuildOptions buildOptions = BuildOptions.None;
[MenuItem("Build/Master Server", false, 100)]
public static void BuildMasterServer()
{
var levels = new string[] { "Assets/Scenes/PushyPaddles_MasterServer.unity" };
BuildPipeline.BuildPlayer(levels, "Builds/MasterServer.exe", buildTarget, buildOptions);
}
[MenuItem("Build/Zone Server", false, 100)]
public static void BuildZoneServer()
{
var levels = new string[] { "Assets/Scenes/PushyPaddles_ZoneServer.unity" };
BuildPipeline.BuildPlayer(levels, "Builds/ZoneServer.exe", buildTarget, buildOptions);
}
[MenuItem("Build/Game Server", false, 100)]
public static void BuildGameServer()
{
var levels = new string[]
{
"Assets/Scenes/PushyPaddles_GameServer.unity",
"Assets/Scenes/PushyPaddles.unity",
};
BuildPipeline.BuildPlayer(levels, "Builds/GameServer.exe", buildTarget, buildOptions);
}
[MenuItem("Build/Game Client", false, 100)]
public static void BuildGameClient()
{
var levels = new string[] {
"Assets/Scenes/PushyPaddles_Client.unity",
"Assets/Scenes/PushyPaddles.unity",
};
BuildPipeline.BuildPlayer(levels, "Builds/GameClient.exe", buildTarget, buildOptions);
}
[MenuItem("Build/WebGL Game Client", false, 100)]
public static void BuildWebGLGameClient()
{
var levels = new string[] {
"Assets/Scenes/PushyPaddles_Client.unity",
"Assets/Scenes/PushyPaddles.unity",
};
BuildPipeline.BuildPlayer(levels, "Builds/GameClient", BuildTarget.WebGL, BuildOptions.AutoRunPlayer);
}
[MenuItem("Build/Build All", false, 50)]
public static void BuildAll()
{
BuildMasterServer();
BuildZoneServer();
BuildGameServer();
BuildGameClient();
}
[MenuItem("Build/Build Games", false, 50)]
public static void BuildGame()
{
BuildGameServer();
BuildGameClient();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
public Material Hitmaterial;
[SerializeField] int Bullet;
public Text BulletText;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
BulletText.text = Bullet.ToString("0");
if (Bullet >0)
{
if (Input.GetMouseButtonDown(0))
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitinfo;
if (Physics.Raycast(ray, out hitinfo))
{
var rig = hitinfo.collider.GetComponent<Rigidbody>();
if (rig != null)
{
rig.GetComponent<MeshRenderer>().material = Hitmaterial;
rig.AddForceAtPosition(ray.direction * 50f, hitinfo.point, ForceMode.VelocityChange);
Bullet--;
}
}
}
}
if(Bullet <=0)
{
int ActiveScene = SceneManager.GetActiveScene().buildIndex;
SceneManager.LoadScene(ActiveScene);
}
if(Input.GetKey(KeyCode.Escape))
{
SceneManager.LoadScene("MainMenu");
}
}
}
|
namespace WebMarkupMin.Core
{
using System;
using System.Collections.Generic;
using System.Configuration;
using Configuration;
using Loggers;
using Resources;
using Utilities;
/// <summary>
/// WebMarkupMin context
/// </summary>
public sealed class WebMarkupMinContext
{
/// <summary>
/// Instance of WebMarkupMin context
/// </summary>
private static readonly Lazy<WebMarkupMinContext> _instance =
new Lazy<WebMarkupMinContext>(() => new WebMarkupMinContext());
/// <summary>
/// Configuration settings of core
/// </summary>
private readonly Lazy<CoreConfiguration> _coreConfig =
new Lazy<CoreConfiguration>(() =>
(CoreConfiguration)ConfigurationManager.GetSection("webMarkupMin/core"));
/// <summary>
/// Markup minification context
/// </summary>
private readonly MarkupContext _markupContext;
/// <summary>
/// Code minification context
/// </summary>
private readonly CodeContext _codeContext;
/// <summary>
/// Pool of loggers
/// </summary>
private readonly Dictionary<string, ILogger> _loggersPool = new Dictionary<string, ILogger>();
/// <summary>
/// Synchronizer of loggers pool
/// </summary>
private readonly object _loggersPoolSynchronizer = new object();
/// <summary>
/// Gets instance of WebMarkupMin context
/// </summary>
public static WebMarkupMinContext Current
{
get { return _instance.Value; }
}
/// <summary>
/// Gets a markup minification context
/// </summary>
public MarkupContext Markup
{
get { return _markupContext; }
}
/// <summary>
/// Gets a code minification context
/// </summary>
public CodeContext Code
{
get { return _codeContext; }
}
/// <summary>
/// Private constructor for implementation Singleton pattern
/// </summary>
private WebMarkupMinContext()
{
_markupContext = new MarkupContext(this);
_codeContext = new CodeContext(this);
}
/// <summary>
/// Gets a core configuration settings
/// </summary>
/// <returns>Configuration settings of core</returns>
internal CoreConfiguration GetCoreConfiguration()
{
return _coreConfig.Value;
}
/// <summary>
/// Creates a instance of logger
/// </summary>
/// <param name="name">Logger name</param>
/// <returns>Logger</returns>
public ILogger CreateLoggerInstance(string name)
{
ILogger logger;
LoggerRegistrationList loggerRegistrationList = _coreConfig.Value.Logging.Loggers;
LoggerRegistration loggerRegistration = loggerRegistrationList[name];
if (loggerRegistration != null)
{
logger = Utils.CreateInstanceByFullTypeName<ILogger>(loggerRegistration.Type);
}
else
{
throw new LoggerNotFoundException(
string.Format(Strings.Configuration_LoggerNotRegistered, name));
}
return logger;
}
/// <summary>
/// Creates a instance of default logger based on the settings
/// that specified in configuration files (App.config or Web.config)
/// </summary>
/// <returns>Logger</returns>
public ILogger CreateDefaultLoggerInstance()
{
string defaultLoggerName = _coreConfig.Value.Logging.DefaultLogger;
if (string.IsNullOrWhiteSpace(defaultLoggerName))
{
throw new ConfigurationErrorsException(Strings.Configuration_DefaultLoggerNotSpecified);
}
ILogger logger = CreateLoggerInstance(defaultLoggerName);
return logger;
}
/// <summary>
/// Gets a instance of logger
/// </summary>
/// <param name="name">Logger name</param>
/// <returns>Logger</returns>
public ILogger GetLoggerInstance(string name)
{
ILogger logger;
lock (_loggersPoolSynchronizer)
{
if (_loggersPool.ContainsKey(name))
{
logger = _loggersPool[name];
}
else
{
logger = CreateLoggerInstance(name);
_loggersPool.Add(name, logger);
}
}
return logger;
}
/// <summary>
/// Gets a instance of default logger based on the settings
/// that specified in configuration files (App.config or Web.config)
/// </summary>
/// <returns>Logger</returns>
public ILogger GetDefaultLoggerInstance()
{
string defaultLoggerName = _coreConfig.Value.Logging.DefaultLogger;
if (string.IsNullOrWhiteSpace(defaultLoggerName))
{
throw new ConfigurationErrorsException(Strings.Configuration_DefaultLoggerNotSpecified);
}
ILogger logger = GetLoggerInstance(defaultLoggerName);
return logger;
}
}
} |
namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_08
{
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
SortedDictionary<string, string> sortedDictionary =
new SortedDictionary<string, string>();
int index = 0;
sortedDictionary.Add(index++.ToString(), "object");
sortedDictionary.Add(index++.ToString(), "byte");
sortedDictionary.Add(index++.ToString(), "uint");
sortedDictionary.Add(index++.ToString(), "ulong");
sortedDictionary.Add(index++.ToString(), "float");
sortedDictionary.Add(index++.ToString(), "char");
sortedDictionary.Add(index++.ToString(), "bool");
sortedDictionary.Add(index++.ToString(), "ushort");
sortedDictionary.Add(index++.ToString(), "decimal");
sortedDictionary.Add(index++.ToString(), "int");
sortedDictionary.Add(index++.ToString(), "sbyte");
sortedDictionary.Add(index++.ToString(), "short");
sortedDictionary.Add(index++.ToString(), "long");
sortedDictionary.Add(index++.ToString(), "void");
sortedDictionary.Add(index++.ToString(), "double");
sortedDictionary.Add(index++.ToString(), "string");
Console.WriteLine("Key Value Hashcode");
Console.WriteLine("--- ------- ----------");
foreach (
KeyValuePair<string, string> i in sortedDictionary)
{
Console.WriteLine("{0,-5}{1,-9}{2}",
i.Key, i.Value, i.Key.GetHashCode());
}
}
}
} |
using System.Collections.Generic;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Input;
using Torshify.Radio.Framework;
using Torshify.Radio.Framework.Controls;
namespace Torshify.Radio.EchoNest.Views.Browse.Tabs
{
public partial class ArtistViewSmall : UserControl
{
#region Constructors
public ArtistViewSmall()
{
InitializeComponent();
}
#endregion Constructors
#region Methods
private void SelectionChanged(object sender, SelectionChangedEventArgs e)
{
List<Track> selectedTracks = new List<Track>();
for (int i = 0; i < _albumsTreeView.Items.Count; i++)
{
var container = _albumsTreeView.ItemContainerGenerator.ContainerFromIndex(i);
if (container != null)
{
var parent = container.FindVisualDescendantByType<DataGrid>();
if (parent == null)
{
continue;
}
if (parent != e.Source)
{
if (Keyboard.Modifiers != ModifierKeys.Control)
{
parent.SelectedItem = null;
}
}
selectedTracks.AddRange(parent.SelectedItems.OfType<Track>());
}
}
ArtistViewModel viewModel = DataContext as ArtistViewModel;
if (viewModel != null)
{
viewModel.UpdateCommandBar(selectedTracks);
}
}
private void DataGridKeyDown(object sender, KeyEventArgs e)
{
var dataGrid = ((DataGrid)sender);
if (e.Key == Key.Up)
{
if (dataGrid.SelectedIndex == 0)
{
var parent = dataGrid.FindParent<TreeViewItem>();
if (parent != null)
{
int currentIndex = _albumsTreeView.ItemContainerGenerator.IndexFromContainer(parent) - 1;
if (currentIndex >= 0)
{
var container = _albumsTreeView.ItemContainerGenerator.ContainerFromIndex(currentIndex) as TreeViewItem;
dataGrid.SelectedItem = null;
var previousDatagrid = container.FindVisualDescendantByType<DataGrid>();
if (previousDatagrid != null)
{
previousDatagrid.SelectedIndex = previousDatagrid.Items.Count - 1;
}
Keyboard.Focus(container);
}
}
}
}
else if (e.Key == Key.Down)
{
if (dataGrid.SelectedIndex == dataGrid.Items.Count - 1)
{
var parent = dataGrid.FindParent<TreeViewItem>();
if (parent != null)
{
int currentIndex = _albumsTreeView.ItemContainerGenerator.IndexFromContainer(parent) + 1;
if (currentIndex < _albumsTreeView.Items.Count)
{
var container = _albumsTreeView.ItemContainerGenerator.ContainerFromIndex(currentIndex) as TreeViewItem;
dataGrid.SelectedItem = null;
var nextDatagrid = container.FindVisualDescendantByType<DataGrid>();
if (nextDatagrid != null)
{
nextDatagrid.SelectedIndex = 0;
}
Keyboard.Focus(container);
}
}
}
}
}
#endregion Methods
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ABC_EMS
{
public partial class CustomerDashboard : Form
{
public CustomerDashboard()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
}
private void CustomerDashboard_Load(object sender, EventArgs e)
{
label1.Text = DateTime.Now.ToLongTimeString();
label2.Text = DateTime.Now.ToLongDateString();
}
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = DateTime.Now.ToLongTimeString();
timer1.Start();
}
private void btnLogout_Click(object sender, EventArgs e)
{
Login lg = new Login();
lg.Show();
this.Hide();
}
private void btnSearchusers_Click(object sender, EventArgs e)
{
}
}
}
|
namespace E03_AnimalHierarchy
{
using E03_AnimalHierarchy.Interfaces;
public class Tomcat : Cat, ISound
{
public Tomcat(double age, string name)
: base(age, name, 'M')
{
}
public override string ToString()
{
return base.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using CommonDX;
using GalaSoft.MvvmLight.Messaging;
using SharpDX;
using SumoNinjaMonkey.Framework.Controls.DrawingSurface;
using SumoNinjaMonkey.Framework.Controls.Messages;
using Windows.UI.Xaml;
using System.Linq;
using System.IO;
using System.Threading.Tasks;
using ModernCSApp.Services;
using SharpDX.Toolkit;
using XNATweener;
using System.Reflection;
using ModernCSApp.Views;
namespace ModernCSApp.DxRenderer
{
public partial class BackgroundComposer : BaseRenderer, IRenderer, IBackgroundRenderer
{
private DeviceManager _deviceManager;
private SharpDX.Direct2D1.DeviceContext _d2dContext ;
private bool _doClear { get; set; }
public bool Show { get; set; }
private UIElement _root;
private DependencyObject _rootParent;
private Stopwatch _clock;
private float _appWidth;
private float _appHeight;
//VisualTree to hold UI elements to render
private List<RenderDTO> _renderTree;
private List<HitTestRect> _layoutTree;
private HitTestRect _selectedRect;
public int IndexOfEffectToRender { get; set; }
public int NumberFramesToRender { get; set; }
//NEED TO WORK OUT HOW TO NOT MAKE THIS GLOBAL VARIABLES!!! (used from LoadViaStorageFileAsset)
SharpDX.WIC.FormatConverter _backgroundImageFormatConverter;
Size2 _backgroundImageSize;
private bool _isInertialTranslationStaging { get; set; }
private Vector3 _globalCameraTranslationStaging { get; set; }
private Vector3 _globalCameraTranslation { get; set; }
private Vector3 _globalTranslation { get; set; }
private Vector3 _globalScale { get; set; }
private string _sessionID { get; set; }
private bool _drawDesignerLayout { get; set; }
private LayoutDetail _layoutDetail { get; set; }
private RectangleF _layoutDeviceScreenSize { get; set; }
private RectangleF _layoutViewableArea { get; set; }
SharpDX.Direct3D11.Texture2D _stagingTexture2D;
SharpDX.Direct2D1.Bitmap1 _stagingBitmap;
SharpDX.Direct2D1.Effects.BitmapSource _stagingBitmapSourceEffect;
private bool _useStagingBitmap = false;
RectangleF _debugLine1 = new RectangleF(100, 80, 300, 40);
RectangleF _debugLine2 = new RectangleF(100, 110, 300, 40);
RectangleF _debugLine3 = new RectangleF(100, 140, 300, 40);
RectangleF _debugLine4 = new RectangleF(100, 170, 300, 40);
RectangleF _debugLine5 = new RectangleF(100, 200, 300, 40);
SharpDX.Direct2D1.SolidColorBrush _generalGrayColor ;
SharpDX.Direct2D1.SolidColorBrush _generalRedColor;
SharpDX.Direct2D1.SolidColorBrush _generalLightGrayColor ;
SharpDX.Direct2D1.SolidColorBrush _generalLightWhiteColor;
SharpDX.DirectWrite.TextFormat _generalTextFormat;
SharpDX.DirectWrite.TextFormat _debugTextFormat;
GameTime _gt;
Tweener _tweener;
public BackgroundComposer()
{
_doClear = false;
Show = true;
NumberFramesToRender = 0;
IndexOfEffectToRender = 0;
_globalScale = new Vector3(1f, 1f, 1f);
_globalTranslation = new Vector3(0, 0, 0);
_globalCameraTranslation = new Vector3(0, 0, 0);
_sessionID = AppDatabase.Current.RetrieveInstanceAppState(AppDatabase.AppSystemDataEnums.UserSessionID).Value;
//_effects = new List<EffectDTO>();
_renderTree = new List<RenderDTO>();
_layoutTree = new List<HitTestRect>();
//_clock = new Stopwatch();
//_updateBackgroundTweener(1.0f, 1.0f, 1.2f);
}
public void UpdateState(GlobalState state){
State = state;
}
public void Initialize(CommonDX.DeviceManager deviceManager)
{
_deviceManager = deviceManager;
_d2dContext = deviceManager.ContextDirect2D;
_generalGrayColor = new SharpDX.Direct2D1.SolidColorBrush(_deviceManager.ContextDirect2D, Color.Gray);
_generalRedColor = new SharpDX.Direct2D1.SolidColorBrush(_deviceManager.ContextDirect2D, Color.Red);
_generalLightGrayColor = new SharpDX.Direct2D1.SolidColorBrush(_deviceManager.ContextDirect2D, Color.LightGray);
_generalLightWhiteColor = new SharpDX.Direct2D1.SolidColorBrush(_deviceManager.ContextDirect2D, Color.White);
_generalTextFormat = new SharpDX.DirectWrite.TextFormat(
_deviceManager.FactoryDirectWrite,
"Segoe UI",
SharpDX.DirectWrite.FontWeight.Light,
SharpDX.DirectWrite.FontStyle.Normal,
SharpDX.DirectWrite.FontStretch.Normal,
16f);
_debugTextFormat = new SharpDX.DirectWrite.TextFormat(
_deviceManager.FactoryDirectWrite,
"Segoe UI",
SharpDX.DirectWrite.FontWeight.Light,
SharpDX.DirectWrite.FontStyle.Normal,
SharpDX.DirectWrite.FontStretch.Normal,
20f);
_layoutDetail = new LayoutDetail() { Width = this.State.DrawingSurfaceWidth, Height = this.State.DrawingSurfaceHeight };
_layoutDeviceScreenSize = new RectangleF(0, 0, (float)_layoutDetail.Width, (float)_layoutDetail.Height);
_appWidth = (float)_layoutDetail.Width + 5;
_appHeight = (float)_layoutDetail.Height;
_updateScaleTranslate(1.0f);
////_drawTiles(0);
if (State.DefaultBackgroundUri != string.Empty) {
_clearRenderTree();
_changeBackgroundImpl(1, _appWidth, _appHeight, 0, 0, State.DefaultBackgroundFolder, State.DefaultBackgroundUri, "", Color.White, 0.7f, "", false);
}
//GestureService.OnGestureRaised += (o,a) => {
// CustomGestureArgs gestureArgs = (CustomGestureArgs)a;
// //NumberFramesToRender += 3;
// if (gestureArgs.ManipulationStartedArgs != null)
// {
// _isInertialTranslationStaging = false;
// _globalCameraTranslationStaging = _globalCameraTranslation;
// }
// else if (gestureArgs.ManipulationInertiaStartingArgs != null)
// {
// _isInertialTranslationStaging = true;
// _globalCameraTranslationStaging = _globalCameraTranslation;
// }
// else if (gestureArgs.ManipulationUpdatedArgs != null)
// {
// if(_isInertialTranslationStaging)
// _updateCameraTranslationStaging((float)gestureArgs.ManipulationUpdatedArgs.Velocities.Linear.X);
// else
// _updateCameraTranslationStaging((float)gestureArgs.ManipulationUpdatedArgs.Cumulative.Translation.X);
// }
// else if (gestureArgs.ManipulationCompletedArgs != null)
// {
// if (gestureArgs.ManipulationCompletedArgs.Cumulative.Scale < 1)
// {
// if (_globalScale.X != 0.9f) { _updateBackgroundTweener(1.0f, 0.9f, 1.2f); SendInformationNotification("zoom level at 90%", 3); }
// //_updateScaleTranslate(0.9f);
// }
// else if (gestureArgs.ManipulationCompletedArgs.Cumulative.Scale > 1)
// {
// if (_globalScale.X != 1.0f) { _updateBackgroundTweener(0.9f, 1.0f, 1.2f); SendInformationNotification("zoom level at 100%", 3); }
// //_updateScaleTranslate(1.0f);
// }
// _globalCameraTranslation = _globalCameraTranslation + _globalCameraTranslationStaging;
// _globalCameraTranslationStaging = Vector3.Zero;
// _isInertialTranslationStaging = false;
// }
// else if (gestureArgs.TappedEventArgs != null)
// {
// var x = gestureArgs.TappedEventArgs.Position.X - _globalCameraTranslation.X;
// var y = gestureArgs.TappedEventArgs.Position.Y - _globalCameraTranslation.Y;
// var found = _doTilesHitTest((float)x, (float)y);
// if (found != null && found.Count > 0)
// {
// _selectedRect = found[0];
// }
// else _selectedRect = null;
// }
//};
WindowLayoutService.OnWindowLayoutRaised += WindowLayoutService_OnWindowLayoutRaised;
}
void WindowLayoutService_OnWindowLayoutRaised(object sender, EventArgs e)
{
if (_deviceManager == null) return;
WindowLayoutEventArgs ea = (WindowLayoutEventArgs)e;
_updateDimensions(ea.Size.Width, ea.Size.Height);
_updateScaleTranslate(1.0f);
_drawTiles(0);
}
private List<HitTestRect> _doTilesHitTest(float x, float y)
{
for (int i=0;i< _layoutTree.Count(); i++)
{
var htr = _layoutTree[i];
if (htr.Rectangle.Contains(x, y)) htr.IsHit = true;
else htr.IsHit = false;
}
return _layoutTree.Where(i => i.IsHit).ToList();
}
private void _drawTiles(int selectedTileUniqueId)
{
_clearRenderTree();
//_changeBackgroundImpl(200, 200, 420, 200, string.Empty,"\\Assets\\StartDemo\\Backgrounds\\green1.jpg", "\\Assets\\StartDemo\\Icons\\Playing Cards.png", Color.White, 1.2f, "Games", false);
_changeBackgroundImpl(1, 100, 100, 100, 100, string.Empty, "\\Assets\\StartDemo\\Backgrounds\\blue1.jpg", "\\Assets\\StartDemo\\Icons\\Windows 8.png", Color.White, 0.7f, "Windows 8", selectedTileUniqueId == 1 ? true : false);
_changeBackgroundImpl(2, 100, 100, 210, 100, string.Empty, "\\Assets\\StartDemo\\Backgrounds\\yellow1.jpg", "\\Assets\\StartDemo\\Icons\\Bowl.png", Color.White, 0.7f, "Food", selectedTileUniqueId == 2 ? true : false);
_changeBackgroundImpl(3, 210, 210, 320, 100, string.Empty, "\\Assets\\StartDemo\\Backgrounds\\green1.jpg", "\\Assets\\StartDemo\\Icons\\Playing Cards.png", Color.White, 1.2f, "Games", selectedTileUniqueId == 3 ? true : false);
_changeBackgroundImpl(4, 210, 100, 540, 100, string.Empty, "\\Assets\\StartDemo\\Backgrounds\\white1.jpg", "\\Assets\\StartDemo\\Icons\\Race Car.png", Color.Black, 0.7f, "Car Watcher", selectedTileUniqueId == 4 ? true : false);
_changeBackgroundImpl(5, 100, 100, 760, 100, string.Empty, "\\Assets\\StartDemo\\Backgrounds\\yellow2.jpg", "\\Assets\\StartDemo\\Icons\\Dynamics CRM.png", Color.White, 0.7f, "CRM", selectedTileUniqueId == 5 ? true : false);
_changeBackgroundImpl(6, 210, 210, 100, 210, string.Empty, "\\Assets\\StartDemo\\Backgrounds\\purple1.jpg", "\\Assets\\StartDemo\\Icons\\Internet Explorer.png", Color.White, 1.3f, "Internet Explorer 10", selectedTileUniqueId == 6 ? true : false);
_changeBackgroundImpl(7, 210, 100, 320, 320, string.Empty, "\\Assets\\StartDemo\\Backgrounds\\blue2.jpg", "\\Assets\\StartDemo\\Icons\\Microsoft Office.png", Color.White, 0.7f, "Office 365", selectedTileUniqueId == 7 ? true : false);
_changeBackgroundImpl(8, 100, 100, 540, 210, string.Empty, "\\Assets\\StartDemo\\Backgrounds\\white3.jpg", "\\Assets\\StartDemo\\Icons\\Office 2013.png", Color.White, 0.7f, "Office 2013", selectedTileUniqueId == 8 ? true : false);
_changeBackgroundImpl(9, 100, 100, 540, 320, string.Empty, "\\Assets\\StartDemo\\Backgrounds\\red1.jpg", "\\Assets\\StartDemo\\Icons\\SharePoint.png", Color.White, 0.7f, "Sharepoint", selectedTileUniqueId == 9 ? true : false);
_changeBackgroundImpl(10, 210, 210, 650, 210, string.Empty, "\\Assets\\StartDemo\\Backgrounds\\green2.jpg", "\\Assets\\StartDemo\\Icons\\Visual Studio.png", Color.White, 1.3f, "Visual Studio 2013", selectedTileUniqueId == 10 ? true : false);
_changeBackgroundImpl(11, 100, 100, 100, 430, string.Empty, "\\Assets\\StartDemo\\Backgrounds\\yellow3.jpg", "\\Assets\\StartDemo\\Icons\\Graph2.png", Color.White, 0.7f, "Graphs", selectedTileUniqueId == 11 ? true : false);
_changeBackgroundImpl(12, 210, 100, 210, 430, string.Empty, "\\Assets\\StartDemo\\Backgrounds\\yellow4.jpg", "\\Assets\\StartDemo\\Icons\\Plug.png", Color.White, 0.7f, "Power", selectedTileUniqueId == 12 ? true : false);
_changeBackgroundImpl(13, 210, 100, 430, 430, string.Empty, "\\Assets\\StartDemo\\Backgrounds\\red2.jpg", "\\Assets\\StartDemo\\Icons\\Google Chrome.png", Color.White, 0.7f, "Chrome", selectedTileUniqueId == 13 ? true : false);
_changeBackgroundImpl(14, 100, 100, 650, 430, string.Empty, "\\Assets\\StartDemo\\Backgrounds\\white2.jpg", "\\Assets\\StartDemo\\Icons\\Firefox.png", Color.White, 0.7f, "Firefox", selectedTileUniqueId == 14 ? true : false);
_changeBackgroundImpl(15, 100, 100, 760, 430, string.Empty, "\\Assets\\StartDemo\\Backgrounds\\white3.jpg", "\\Assets\\StartDemo\\Icons\\Cloud-Upload.png", Color.White, 0.7f, "Cloud", selectedTileUniqueId == 15 ? true : false);
}
private void _updateScaleTranslate(float zoomFactor)
{
_globalScale = new Vector3(zoomFactor, zoomFactor, 1f);
_globalTranslation =
new Vector3(
(float)((_appWidth * (1f - zoomFactor)) / 2), //(float)((this.State.DrawingSurfaceWidth * (1f - zoomFactor)) / 2),
(float)((_appHeight * (1f - zoomFactor)) / 2), //(float)((this.State.DrawingSurfaceHeight * (1f - zoomFactor)) / 2),
0
)
+ _globalCameraTranslation
+ _globalCameraTranslationStaging;
}
private void _updateCameraTranslation(float x)
{
_globalCameraTranslation = new Vector3(
_globalCameraTranslation.Y + x,
_globalCameraTranslation.Y,
_globalCameraTranslation.Z);
_updateScaleTranslate(_globalScale.X);
}
private void _updateCameraTranslationStaging(float x)
{
_globalCameraTranslationStaging = new Vector3(
_globalCameraTranslationStaging.Y + x,
_globalCameraTranslationStaging.Y,
_globalCameraTranslationStaging.Z);
_updateScaleTranslate(_globalScale.X);
}
public void InitializeUI(Windows.UI.Xaml.UIElement rootForPointerEvents, Windows.UI.Xaml.UIElement rootOfLayout)
{
_root = rootForPointerEvents;
_rootParent = rootOfLayout;
_updateDimensions(((FrameworkElement)_root).ActualWidth, ((FrameworkElement)_root).ActualHeight);
_pathD2DConverter = new SumoNinjaMonkey.Framework.Lib.PathToD2DPathGeometryConverter();
}
private void _updateDimensions(double width, double height)
{
_appWidth = (float)width + 5;
_appHeight = (float)height;
if (_deviceManager == null) return ;
if (_stagingTexture2D != null) _stagingTexture2D.Dispose();
if (_stagingBitmap != null) _stagingBitmap.Dispose();
if (_stagingBitmapSourceEffect != null) _stagingBitmapSourceEffect.Dispose();
_stagingTexture2D = AllocateTextureReturnSurface((int)_appWidth, (int)_appHeight);
_stagingBitmap = new SharpDX.Direct2D1.Bitmap1(_deviceManager.ContextDirect2D, _stagingTexture2D.QueryInterface<SharpDX.DXGI.Surface>());
_stagingBitmapSourceEffect = new SharpDX.Direct2D1.Effects.BitmapSource(_deviceManager.ContextDirect2D);
}
public void Update(GameTime gameTime)
{
var d2dContext = _d2dContext; //target.DeviceManager.ContextDirect2D;
_gt = gameTime;
if(_tweener!=null) _tweener.Update(gameTime);
}
public void Render(CommonDX.TargetBase target)
{
var d2dContext = _d2dContext; //target.DeviceManager.ContextDirect2D;
var d2dDevice = target.DeviceManager.DeviceDirect2D;
var d3dContext = target.DeviceManager.ContextDirect3D;
var d3dDevice = target.DeviceManager.DeviceDirect3D;
if (NumberFramesToRender > 0)
{
//TurnOffRenderingBecauseThereAreRenderableEffects();
_useStagingBitmap = false;
var _tempTarget = d2dContext.Target;
d2dContext.Target = _stagingBitmap;
d2dContext.BeginDraw();
//if (_doClear) {
//d2dContext.Clear(Color.White);
d2dContext.Clear( new Color4(0, 0, 0, 0));
// _doClear = false;
//}
foreach (var renderTree in _renderTree.OrderBy(x => x.Order))
{
if (renderTree.Type == eRenderType.Effect && renderTree.EffectDTO.IsRenderable && !renderTree.HasLinkedEffects) //effects
{
if (renderTree.EffectDTO.Effect != null)
{
d2dContext.Transform =
//Matrix.Identity
Matrix.Scaling(renderTree.EffectDTO.MainScale)
* Matrix.Translation(renderTree.EffectDTO.MainTranslation)
//* Matrix.Scaling(_globalScale)
//* Matrix.Translation(_globalTranslation)
;
d2dContext.DrawImage(renderTree.EffectDTO.Effect);
}
}
else if (renderTree.Type == eRenderType.Text && renderTree.TextDTO.IsRenderable) //text
{
d2dContext.Transform =
Matrix.Scaling(renderTree.TextDTO.MainScale)
* Matrix.Translation(renderTree.TextDTO.MainTranslation)
//* Matrix.Scaling(_globalScale)
//* Matrix.Translation(_globalTranslation)
;
d2dContext.DrawText(renderTree.TextDTO.Text, renderTree.TextDTO.TextFormat, renderTree.TextDTO.LayoutRect, renderTree.TextDTO.Brush);
}
else if (renderTree.Type == eRenderType.Media && renderTree.MediaDTO.IsRenderable) //video/audio
{
}
else if (renderTree.Type == eRenderType.Shape && renderTree.ShapeDTO.IsRenderable) //Geometry
{
d2dContext.Transform =
//Matrix.Identity
Matrix.Scaling(renderTree.ShapeDTO.MainScale)
* Matrix.Translation(renderTree.ShapeDTO.MainTranslation)
//* Matrix.Scaling(_globalScale)
//* Matrix.Translation(_globalTranslation)
;
if (renderTree.ShapeDTO.Type == 2)
d2dContext.FillGeometry(renderTree.ShapeDTO.Shape, renderTree.ShapeDTO.Brush);
else
d2dContext.DrawGeometry(
renderTree.ShapeDTO.Shape,
renderTree.ShapeDTO.Brush,
renderTree.ShapeDTO.StrokeWidth,
new SharpDX.Direct2D1.StrokeStyle(
_deviceManager.FactoryDirect2D, //target.DeviceManager.FactoryDirect2D,
new SharpDX.Direct2D1.StrokeStyleProperties()
{
DashStyle = (SharpDX.Direct2D1.DashStyle)renderTree.ShapeDTO.DashStyleIndex,
DashOffset = renderTree.ShapeDTO.DashOffset,
StartCap = SharpDX.Direct2D1.CapStyle.Square,
EndCap = SharpDX.Direct2D1.CapStyle.Square,
DashCap = SharpDX.Direct2D1.CapStyle.Square,
MiterLimit = renderTree.ShapeDTO.MiterLimit
}));
}
else if (renderTree.Type == eRenderType.ShapePath && renderTree.ShapePathDTO.IsRenderable) //ShapePath Geometry
{
d2dContext.Transform =
//Matrix.Identity
Matrix.Scaling(renderTree.ShapePathDTO.MainScale)
* Matrix.RotationX(renderTree.ShapePathDTO.MainRotation.X)
* Matrix.RotationY(renderTree.ShapePathDTO.MainRotation.Y)
* Matrix.RotationZ(renderTree.ShapePathDTO.MainRotation.Z)
* Matrix.Translation(renderTree.ShapePathDTO.MainTranslation)
//* Matrix.Scaling(_globalScale)
//* Matrix.Translation(_globalTranslation)
;
d2dContext.DrawGeometry(
renderTree.ShapePathDTO.Shapes[0],
renderTree.ShapePathDTO.Brush,
renderTree.ShapePathDTO.StrokeWidth,
new SharpDX.Direct2D1.StrokeStyle(
_deviceManager.FactoryDirect2D,//target.DeviceManager.FactoryDirect2D,
new SharpDX.Direct2D1.StrokeStyleProperties()
{
DashStyle = (SharpDX.Direct2D1.DashStyle)renderTree.ShapePathDTO.DashStyleIndex,
DashOffset = renderTree.ShapePathDTO.DashOffset,
StartCap = SharpDX.Direct2D1.CapStyle.Square,
EndCap = SharpDX.Direct2D1.CapStyle.Square,
DashCap = SharpDX.Direct2D1.CapStyle.Square,
MiterLimit = renderTree.ShapePathDTO.MiterLimit
}));
}
}
d2dContext.Target = _tempTarget;
d2dContext.EndDraw();
NumberFramesToRender--;
}
else
{
_useStagingBitmap = true;
}
d2dContext.BeginDraw();
d2dContext.Clear(Color.White);
if (_useStagingBitmap)
{
d2dContext.Transform =
Matrix.Scaling(_globalScale)
* Matrix.Translation(_globalTranslation);
d2dContext.DrawImage(_stagingBitmap);
}
//SELECTED TILE
_drawSelectedTile(d2dContext);
//DESIGNER SURFACE REGION
//_drawDesktopOutline(d2dContext);
//DEBUGGING INFO
//_drawDebuggingInfo(d2dContext);
d2dContext.EndDraw();
}
int offsetSelectedDash = 1;
private void _drawSelectedTile(SharpDX.Direct2D1.DeviceContext d2dContext)
{
if (_selectedRect != null)
{
var strokeStyle_dashed = new SharpDX.Direct2D1.StrokeStyle(d2dContext.Factory, new SharpDX.Direct2D1.StrokeStyleProperties() { DashOffset = (offsetSelectedDash / 5), DashStyle = SharpDX.Direct2D1.DashStyle.Dash });
////drown out the shadow of the tile
//d2dContext.DrawRectangle(
// new RectangleF(_selectedRect.Rectangle.X - 2, _selectedRect.Rectangle.Y - 2, _selectedRect.Rectangle.Width + 4, _selectedRect.Rectangle.Height + 4),
// new SharpDX.Direct2D1.SolidColorBrush(d2dContext, Color.White),
// 4
// );
//draw an animated dash around border of tile
d2dContext.DrawRectangle(
new RectangleF(_selectedRect.Rectangle.X - 2, _selectedRect.Rectangle.Y - 2, _selectedRect.Rectangle.Width + 4, _selectedRect.Rectangle.Height + 4),
new SharpDX.Direct2D1.SolidColorBrush(d2dContext, Color.Yellow),
4,
strokeStyle_dashed);
//_drawTiles(_selectedRect.UniqueId);
offsetSelectedDash++;
if (offsetSelectedDash > 100) offsetSelectedDash = 0;
}
}
private void _drawDebuggingInfo(SharpDX.Direct2D1.DeviceContext d2dContext)
{
if (_gt != null)
{
d2dContext.Transform = Matrix.Identity;
d2dContext.DrawText("TotalGameTime (s) : " + _gt.TotalGameTime.TotalSeconds.ToString(), _debugTextFormat, _debugLine1, _generalRedColor);
d2dContext.DrawText("FrameCount : " + _gt.FrameCount.ToString(), _debugTextFormat, _debugLine2, _generalRedColor);
d2dContext.DrawText("ElapsedGameTime (s) : " + _gt.ElapsedGameTime.TotalSeconds.ToString(), _debugTextFormat, _debugLine3, _generalRedColor);
d2dContext.DrawText("IsRunningSlowly : " + _gt.IsRunningSlowly.ToString(), _debugTextFormat, _debugLine4, _generalRedColor);
d2dContext.DrawText("FPS : " + (_gt.FrameCount / _gt.TotalGameTime.TotalSeconds).ToString(), _debugTextFormat, _debugLine5, _generalRedColor);
}
}
private void _drawDesktopOutline( SharpDX.Direct2D1.DeviceContext d2dContext)
{
//BORDER
d2dContext.Transform = Matrix.Translation(_globalTranslation) * Matrix.Scaling(_globalScale);
d2dContext.DrawRectangle(
_layoutDeviceScreenSize,
_generalLightGrayColor,
3
);
//WIDTH
d2dContext.Transform = Matrix.Translation(_globalTranslation) * Matrix.Scaling(_globalScale);
d2dContext.FillRectangle(
new RectangleF(0, -30, 100, 30),
_generalLightGrayColor
);
d2dContext.Transform = Matrix.Translation(10, 0, 0) * Matrix.Translation(_globalTranslation) * Matrix.Scaling(_globalScale);
d2dContext.DrawText(_layoutDetail.Width.ToString(), _generalTextFormat, new RectangleF(0, -30, 100, 30), _generalLightWhiteColor);
////HEIGHT
double angleRadians = 90 * Math.PI / 180; //90 degrees
d2dContext.Transform = Matrix.RotationZ((float)angleRadians) * Matrix.Identity * Matrix.Translation(_globalTranslation) * Matrix.Scaling(_globalScale);
d2dContext.FillRectangle(
new RectangleF(0, 0, 100, 30),
_generalLightGrayColor
);
d2dContext.Transform = Matrix.RotationZ((float)angleRadians) * Matrix.Translation(0, 10, 0) * Matrix.Translation(_globalTranslation) * Matrix.Scaling(_globalScale);
d2dContext.DrawText(_layoutDetail.Height.ToString(), _generalTextFormat, new RectangleF(0, 0, 100, 30), _generalLightWhiteColor);
}
private void _updateBackgroundTweener(float start, float end, float duration)
{
//methodinfo.createdelegate
//http://msdn.microsoft.com/en-us/library/windows/apps/hh194376.aspx
if (_tweener == null)
{
_tweener = new Tweener(start, end, TimeSpan.FromSeconds(duration), (TweeningFunction)Cubic.EaseIn);
_tweener.PositionChanged += (newVal) => { _updateScaleTranslate((float)newVal); };
_tweener.Ended += () => { _tweener.Pause(); };
}
else
{
_tweener.Reset(start, end, duration);
_tweener.Play();
}
}
public async void ChangeBackground(string localUri, string folder)
{
_clearRenderTree();
try
{
//_changeBackgroundImpl(1, _appWidth, _appHeight, 0, 0, string.Empty, "\\Assets\\StartDemo\\Backgrounds\\green1.jpg", "", Color.White, 0.7f, "", false);
await _changeBackgroundImpl(1, _appWidth, _appHeight, 0, 0, folder, localUri, "", Color.White, 0.7f, "", false);
}
catch {
}
}
private async Task _changeBackgroundImpl(int uniqueId, float width, float height, float left, float top,string path, string backgroundUrl, string iconUrl, Color fontColor, float iconScale = 1.0f, string label = "", bool isPressed = false)
{
//===============
//CREATE LAYOUT ITEM USED FOR HITTESTING
//===============
_layoutTree.Add(new HitTestRect() { UniqueId = uniqueId, IsHit = false, Rectangle = new Rectangle((int)left, (int)top, (int)width, (int)height) });
//===============
//TILE
//===============
var _bs = new UIElementState()
{
IsRenderable = false, //is effect rendered/visible
AggregateId = Guid.NewGuid().ToString(),
Grouping1 = string.Empty,
udfString1 = backgroundUrl,
udfString2 = path
};
var _ebs = await CreateRenderItemWithUIElement_Effect(
_bs,
"SharpDX.Direct2D1.Effects.BitmapSourceEffect",
null);
_ebs.EffectDTO.MainTranslation = new Vector3(left, top, 0);
//determine the scale to use to scale the image to the app dimension
double _scaleRatio = 1;
var yRatio = 1.0f / (height / _bs.Height);
var xRatio = 1.0f / (width / _bs.Width);
var xyRatio = Math.Min(xRatio, yRatio);
_scaleRatio = 1.0d / xyRatio;
//create effect - scale
var _escale = await CreateRenderItemWithUIElement_Effect(
new UIElementState()
{
IsRenderable = false, //is effect rendered/visible
AggregateId = Guid.NewGuid().ToString(),
Grouping1 = string.Empty,
udfDouble1 = _scaleRatio, // scale x
udfDouble2 = _scaleRatio, // scale y
udfDouble3 = 0.5f, // centerpoint x
udfDouble4 = 0.5f // centerpoint y
},
"SharpDX.Direct2D1.Effects.Scale",
_ebs //linked parent effect
);
//create effect - crop
var _ecrop = await CreateRenderItemWithUIElement_Effect(
new UIElementState()
{
IsRenderable = true, //is effect rendered/visible
AggregateId = Guid.NewGuid().ToString(),
Grouping1 = string.Empty,
udfDouble1 = 0,
udfDouble2 = 0,
udfDouble3 = width,
udfDouble4 = height
},
"SharpDX.Direct2D1.Effects.Crop",
_escale //linked parent effect
);
_ecrop.Order = 9;
//===============
//INNER GLOW
//===============
var rect_fade = await AddUpdateUIElementState_Rectangle(
new UIElementState()
{
IsRenderable = isPressed ? false : true,
AggregateId = Guid.NewGuid().ToString(),
Grouping1 = string.Empty,
Width = width,
Height = height,
udfInt1 = 2, //not fill = 1, fill = 2
udfString1 = "Rectangle",
udfDouble3 = 0, //stroke width
udfInt2 = 1, // 1 = 2 point gradient, 2= solid
udfString2 = "0|0|0|0", //gradient 1 // white = "255|255|255|0", //gradient 1
udfDouble1 = 70d, // color position 1
udfString3 = "0|0|0|255", //gradient 2
udfDouble2 = 100d, // color position 2
Left = left,
Top = top,
Scale = 1d
},
null);
rect_fade.Order = 10;
//===============
//OUTER SHADOW
//===============
if (!isPressed)
{
var _eshadow = await CreateRenderItemWithUIElement_Effect(
new UIElementState()
{
IsRenderable = true,
AggregateId = Guid.NewGuid().ToString(),
Grouping1 = string.Empty,
udfDouble1 = 5.0d,
},
"SharpDX.Direct2D1.Effects.Shadow",
_ecrop
);
_eshadow.Order = 5;
}
//===============
//ICON
//===============
if (iconUrl.Length > 0)
{
//bitmap source
var _bsicon = new UIElementState()
{
IsRenderable = true,
AggregateId = Guid.NewGuid().ToString(),
Grouping1 = string.Empty,
udfString1 = iconUrl
};
//bitmap effect
var _ebsicon = await CreateRenderItemWithUIElement_Effect(
_bsicon,
"SharpDX.Direct2D1.Effects.BitmapSourceEffect",
null);
double iconX = (width - (_bsicon.Width * iconScale)) / 2;
double iconY = (height - (_bsicon.Height * iconScale)) / 2;
_ebsicon.EffectDTO.MainTranslation = new Vector3(left + (float)iconX, top + (float)iconY, 0);
_ebsicon.EffectDTO.MainScale = new Vector3(iconScale);
_ebsicon.Order = 20;
//outer glow
var _ebsiconshadow = await CreateRenderItemWithUIElement_Effect(
new UIElementState()
{
IsRenderable = isPressed ? false : true,
AggregateId = Guid.NewGuid().ToString(),
Grouping1 = string.Empty,
udfDouble1 = 2.0d,
},
"SharpDX.Direct2D1.Effects.Shadow",
_ebsicon
);
_ebsiconshadow.Order = 19;
}
//===============
//LABEL
//===============
if (label.Length > 0)
{
//outer glow
var _txtLabel = await AddUpdateUIElementState_Text(
new UIElementState()
{
IsRenderable = true,
AggregateId = Guid.NewGuid().ToString(),
Grouping1 = string.Empty,
udfString1 = label,
udfString2 = "Segoe UI",
udfDouble1 = 18d,
Left = left,
Top = top + height - 25,
Scale = 1,
Width = width,
Height = height
}
, null
, fontColor
);
_txtLabel.Order = 25;
}
if (NumberFramesToRender < 1) NumberFramesToRender = 1;
}
private void _clearRenderTree()
{
//clean up the renderTree
foreach (var ri in _renderTree)
{
if (ri.Type == eRenderType.Effect)
{
ri.EffectDTO.Effect.Dispose();
ri.EffectDTO.Effect = null;
ri.EffectDTO = null;
}
}
_renderTree.Clear();
_layoutTree.Clear();
}
/// <summary>
/// Called from parent when it closes to ensure this asset closes properly and leaves
/// not possible memory leaks
/// </summary>
public void Unload()
{
WindowLayoutService.OnWindowLayoutRaised -= WindowLayoutService_OnWindowLayoutRaised;
_root = null;
_rootParent = null;
_clearRenderTree();
ClearAssets();
_clock = null;
_gt = null;
_tweener = null;
_deviceManager = null;
_d2dContext = null;
if (_stagingBitmap != null)
{
_stagingBitmap.Dispose();
_stagingBitmap = null;
}
if (_stagingBitmapSourceEffect != null) {
_stagingBitmapSourceEffect.Dispose();
_stagingBitmapSourceEffect = null;
}
if (_stagingTexture2D != null) {
_stagingTexture2D.Dispose();
_stagingTexture2D = null;
}
_pathD2DConverter = null;
//_graphicsDevice.Dispose();
//_graphicsDevice = null;
}
}
public class HitTestRect
{
public int UniqueId { get; set; }
public Rectangle Rectangle { get; set; }
public bool IsHit { get; set; }
}
}
|
using Clubber.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Clubber.Models
{
public class ClubListItem
{
[Display(Name = "Club Number")]
public int ClubId { get; set; }
public string Title { get; set; }
// public int SponsorId { get; set; }
[Display(Name = "Sponsor")]
public string SponsorName { get; set; }
[Display(Name = "Meeting Day")]
public DayOfWeek MeetingDay { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:H:mm}")]
[Display(Name = "Meeting Time")]
public DateTime MeetingTime { get; set; }
public bool IsMemberOf {get; set;}
[Display(Name = "Club Category")]
public Club_Category ClubType { get; set; }
}
}
|
using System.Data.Entity.ModelConfiguration;
using RMAT3.Models;
namespace RMAT3.Data.Mapping
{
public class ContactPreferenceTypeMap : EntityTypeConfiguration<ContactPreferenceType>
{
public ContactPreferenceTypeMap()
{
// Primary Key
HasKey(t => t.ContactPreferenceTypeId);
// Properties
Property(t => t.AddedByUserId)
.IsRequired()
.HasMaxLength(20);
Property(t => t.UpdatedByUserId)
.IsRequired()
.HasMaxLength(20);
Property(t => t.UpdatedCommentTxt)
.HasMaxLength(500);
Property(t => t.ContactPreferenceTypeCd)
.IsRequired()
.HasMaxLength(50);
Property(t => t.ContactPreferenceTypeTxt)
.HasMaxLength(200);
// Table & Column Mappings
ToTable("ContactPreferenceType", "OLTP");
Property(t => t.ContactPreferenceTypeId).HasColumnName("ContactPreferenceTypeId");
Property(t => t.AddedByUserId).HasColumnName("AddedByUserId");
Property(t => t.AddTs).HasColumnName("AddTs");
Property(t => t.UpdatedByUserId).HasColumnName("UpdatedByUserId");
Property(t => t.UpdatedCommentTxt).HasColumnName("UpdatedCommentTxt");
Property(t => t.UpdatedTs).HasColumnName("UpdatedTs");
Property(t => t.IsActiveInd).HasColumnName("IsActiveInd");
Property(t => t.EffectiveFromDt).HasColumnName("EffectiveFromDt");
Property(t => t.EffectiveToDt).HasColumnName("EffectiveToDt");
Property(t => t.ContactPreferenceTypeCd).HasColumnName("ContactPreferenceTypeCd");
Property(t => t.ContactPreferenceTypeTxt).HasColumnName("ContactPreferenceTypeTxt");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using SubSonic.Extensions;
namespace Pes.Core
{
public partial class VAnswers
{
public static List<VAnswers> GetListAnserForQuestion(int questionID)
{
return All().Where(a=>a.QuestionID==questionID).ToList<VAnswers>();
}
public static VAnswers GetAnswerByID(int id)
{
return VAnswers.Single(id);
}
public static List<VAnswers> GetListAnswers()
{
return All().ToList();
}
public static void InsertAnswer(VAnswers asBO)
{
VAnswers.Add(asBO);
}
public static void DeleteAnswer(VAnswers asBO)
{
VAnswers.Delete(asBO.AnswerID);
}
public static void UpdateAnswer(VAnswers asBo)
{
VAnswers.Update(asBo);
}
public static List<VAnswers> Get(IQueryable<VAnswers> table, int start, int end)
{
if (start <= 0)
start = 1;
List<VAnswers> l = table.Skip(start - 1).Take(end - start + 1).ToList<VAnswers>();
return l;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ERP_Palmeiras_RH.Models
{
public partial class Endereco
{
public override string ToString()
{
return this.Rua + ", " + this.Numero.ToString() + " - " + this.Cidade + "/" + this.Estado;
}
}
} |
namespace Tests
{
using System.Linq;
using System.Reflection;
using FluentAssertions;
using Microsoft.Practices.Unity;
using WebApi.App_Start;
using WebApi.Controllers;
using Xunit;
public class UnityConfigTests
{
[Fact]
public void should_resolve_all_dependencies_from_WebApi_assembly()
{
var container = UnityConfig.GetConfiguredContainer();
//(t.IsAbstract && t.IsSealed) - check for filter static classes because they are IsAbstract and IsSealed
var registeredTypes =
Assembly.GetAssembly(typeof(UsersController))
.Types()
.Where(t => t.Namespace.StartsWith("WebApi") && (t.IsInterface || (t.IsAbstract && !t.IsSealed)));
foreach (var type in registeredTypes.ToArray())
{
container.IsRegistered(type).Should().BeTrue();
}
}
}
} |
namespace Arch.Data.Common.Enums
{
public enum NumericType
{
Int,
Long,
Double
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace UploadFile.Lib
{
public class UploadHistoryModel
{
const string KEY_SQL = "48dc695d5f6203fd54b85c93b022ffe5";
ConnectionDB connectString;
public UploadHistoryModel()
{
connectString = new ConnectionDB("ManamentCMSTools_DB");
}
public void AddUploadHistory(picture pic) {
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 3000;
connectString.conn.Open();
cmd.Connection = connectString.conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_AddUploadHistory";
cmd.Parameters.Add("@FileName", SqlDbType.VarChar, 50);
cmd.Parameters["@FileName"].Value = pic.fileName;
cmd.Parameters.Add("@Url", SqlDbType.VarChar, 250);
cmd.Parameters["@Url"].Value = pic.urlWeb;
cmd.Parameters.Add("@Size", SqlDbType.VarChar, 20);
cmd.Parameters["@Size"].Value = pic.sizeWeb;
cmd.Parameters.Add("@UploadType", SqlDbType.TinyInt);
cmd.Parameters["@UploadType"].Value = pic.uploadType;
cmd.Parameters.Add("@IP", SqlDbType.VarChar, 40);
cmd.Parameters["@IP"].Value = pic.ip;
cmd.Parameters.Add("@Status", SqlDbType.Int);
cmd.Parameters["@Status"].Value = 1;
cmd.Parameters.Add("@UserId", SqlDbType.Int);
cmd.Parameters["@UserId"].Value = pic.userId;
cmd.Parameters.Add("@Key", SqlDbType.VarChar, 100);
cmd.Parameters["@Key"].Value = KEY_SQL;
cmd.Parameters.Add("@Code", SqlDbType.BigInt);
cmd.Parameters["@Code"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
long code = long.Parse(cmd.Parameters["@Code"].Value.ToString());
pic.id = code;
}
catch (Exception ex)
{
Logs.SaveError("ERROR AddUploadHistory: " + ex);
pic.id = -1;
}
finally
{
connectString.conn.Close();
}
}
}
} |
namespace StructureAssertions.Test.TestTypes
{
public class ContainsStringPropertyCallingInitializer
{
string _property;
public string Property
{
get { return _property ?? (_property = StringInitializer.AString()); }
}
}
} |
// --------------------------------------------------------------------------------------------------------------
// <copyright file="LoginInputModel.cs" company="Tiny开源团队">
// Copyright (c) 2017-2018 Tiny. All rights reserved.
// </copyright>
// <site>http://www.lxking.cn</site>
// <last-editor>ArcherTrister</last-editor>
// <last-date>2019/3/15 22:18:33</last-date>
// --------------------------------------------------------------------------------------------------------------
using System.ComponentModel.DataAnnotations;
namespace Tiny.IdentityService.Models.Account
{
public class LoginInputModel
{
[Required]
public string Username { get; set; }
[Required]
public string Password { get; set; }
public bool RememberLogin { get; set; }
public string ReturnUrl { get; set; }
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using OpenGov.Models;
using OpenGov.Scrapers;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace OpenGovTests
{
[TestClass]
public class eInnsynScraper
{
[TestMethod]
public async Task FindNew()
{
string query = JsonConvert.SerializeObject(new { size = 50, aggregations = new { contentTypes = "type", virksomheter = "arkivskaperTransitive" }, appliedFilters = new[] { new { fieldName = "type", fieldValue = new string[] { "Moetemappe" }, type = "termQueryFilter" }, new { fieldName = "type", fieldValue = new string[] { "JournalpostForMøte" }, type = "notQueryFilter" }, new { fieldName = "arkivskaperTransitive", fieldValue = new string[] { "http://data.oslo.kommune.no/virksomhet/osloKommune" }, type = "postQueryFilter" } } });
IScraper scraper = new OpenGov.Scrapers.eInnsyn("https://einnsyn.no/api/result", query);
var meetings = await scraper.GetNewMeetings(new HashSet<string>());
Assert.IsNotNull(meetings);
var meetingsList = new List<Meeting>(meetings);
Assert.IsTrue(meetingsList.Count > 0);
var meeting = meetingsList[0];
//var documents = new List<Document>(await scraper.GetDocuments(meeting));
//Assert.IsTrue(documents.Count > 0);
}
}
}
|
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
namespace OSCGui_Forms.Controls
{
public class Label : Xamarin.Forms.Label, OscTree.IOscObject
{
private OscTree.Object oscObject;
public OscTree.Object OscObject => oscObject;
public Label(JObject obj)
{
OscJsonObject json = new OscJsonObject(obj);
oscObject = new OscTree.Object(new OscTree.Address(json.Name, json.UID), typeof(int));
Text = (string)json.Content;
TextColor = json.Color;
BackgroundColor = json.Background;
FontSize = json.FontSize;
if(json.Bold)
{
if (json.Italic) FontAttributes = Xamarin.Forms.FontAttributes.Bold | Xamarin.Forms.FontAttributes.Italic;
else FontAttributes = Xamarin.Forms.FontAttributes.Bold;
} else if (json.Italic)
{
FontAttributes = Xamarin.Forms.FontAttributes.Italic;
}
HorizontalTextAlignment = json.HAlign;
IsVisible = json.Visible;
oscObject.Endpoints.Add(new OscTree.Endpoint("Text", (args) =>
{
Xamarin.Forms.Device.BeginInvokeOnMainThread(() => { Text = OscParser.ToString(args); });
}));
oscObject.Endpoints.Add(new OscTree.Endpoint("FontSize", (args) =>
{
Xamarin.Forms.Device.BeginInvokeOnMainThread(() => { FontSize = OscParser.ToInt(args); });
}));
oscObject.Endpoints.Add(new OscTree.Endpoint("Visible", (args) =>
{
Xamarin.Forms.Device.BeginInvokeOnMainThread(() => { IsVisible = OscParser.ToBool(args); });
}));
oscObject.Endpoints.Add(new OscTree.Endpoint("TextColor", (args) =>
{
Xamarin.Forms.Device.BeginInvokeOnMainThread(() => { TextColor = OscParser.ToColor(args); });
}));
oscObject.Endpoints.Add(new OscTree.Endpoint("BackgroundColor", (args) =>
{
Xamarin.Forms.Device.BeginInvokeOnMainThread(() => { BackgroundColor = OscParser.ToColor(args); });
}));
}
public void Taint()
{
// not used on client
}
}
}
|
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace BlogMVC4
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
string l4net = Server.MapPath("~/Web.config");
log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(l4net));
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
//注入 Ioc
var container = new UnityContainer();
DependencyRegisterType.Container(ref container);
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
/// <summary>
/// 自定义404页面
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Application_Error(object sender, EventArgs e)
{
//HttpContext currentContext = HttpContext.Current;
//string Url = HttpContext.Current.Request.Url.AbsolutePath;
//string Form = HttpContext.Current.Request.Form.ToString();
//HttpServerUtility server = HttpContext.Current.Server;
//Exception ex = server.GetLastError();
//if (ex is HttpException)
//{
// if (((HttpException)ex).GetHttpCode() == 404)
// //如何指向绝对路径的URL?
// Response.Redirect("/Error/Page404");
//}
//log4net.LogManager.GetLogger("Application_Error").Error(string.Format("在执行 Url:{0} Form:{1}时产生异常;", Url, Form), ex);
}
}
} |
using System;
using RockPaperScissors.Engine;
namespace RockPaperScissors.Contestants
{
public class AlwaysScissors : IAlgorithm
{
public string GetAlgorithName() => "Always Scissors";
public Move GetNextMove() => Move.Scissors;
public void RegisterOponentsMove(Move move)
{
// scissors rules
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NowPlaying.XApplication
{
public static class Define
{
public static string TwitterConsumerKey
{
get { return "lHf2QI9xSFXKcmShszqfmtg85"; }
}
public static string TwitterConsumerSecret
{
get { return "HaDtZs1l5p0PS3o7yDKEp6EUERImSb8hK67Fftan7vcs6m77l1"; }
}
public static string CroudiaConsumerKey
{
get { return "1326cc850376c7de3d9aaf2b569ba9df3b916a0a6f5fc568601b1c6c46910203"; }
}
public static string CroudiaConsumerSecret
{
get { return "be1912ee3abefc02e459d69f76a1a0951b831eed14508d94980a77dcf2676a6c"; }
}
public static string UnavailableText
{
get { return "Mini モードでは、この項目は使用できません。"; }
}
}
}
|
using CarWash.ClassLibrary.Enums;
namespace CarWash.Bot.CognitiveModels
{
internal class ServiceModel : CognitiveModel
{
public ServiceModel(CognitiveModel model)
{
Type = model.Type;
Text = model.Text;
}
public ServiceType Service { get; set; }
}
}
|
using System;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
using NSubstitute;
using NUnit.Framework;
using RestSharp;
using TrafficControl.DAL.RestSharp;
namespace DAL.Test.Unit
{
public class tokenTestDTO
{
public string access_token { get; set; }
public string token_type { get; set; }
public int expires_in { get; set; }
public string userName { get; set; }
public string issued { get; set; }
public string expires { get; set; }
}
/// <summary>
/// test om TCDataConnection op mod en API, intet mocked. (ikke unit test)
/// </summary>
[TestFixture]
public class TCDataConnectionTests
{
private string _username;
private string _password;
private TCDataConnection uut { get; set; }
private TCDataConnection uutWithPosition { get; set; }
[SetUp]
public void Init()
{
uut = new TCDataConnection() {};
uutWithPosition = new TCDataConnection() { ApiDirectory = "api/Position/"};
var fakerequest = Substitute.For<IRestRequest>();
_username = "test@trafficcontrol.dk"; ;
_password = "Phantom-161";
}
[Test]
public void TCDataConnection_AfterInitWithoutSettingApiDirectory_IsEmpty()
{
Assert.That(uut.ApiDirectory,Is.Empty);
}
[Test]
public void Login_WithValidLogin_TokenNotEmpty()
{
TCDataConnection.LogIn(_username, _password);
Assert.That(TCDataConnection.Token, Is.Not.Empty);
}
[Test]
public void Login_WithValidLogin_ReturnTrue()
{
var x = TCDataConnection.LogIn(_username, _password);
Assert.That(x, Is.True);
}
[Test]
public void Login_WithInValidLogin_ReturnsFalse()
{
var mytest = TCDataConnection.LogIn("test", "tester");
Assert.That(mytest, Is.EqualTo(false));
}
[Test]
public void Login_WithInValidLogin_TokenEmpty()
{
TCDataConnection.LogIn("test", "tester");
Assert.That(TCDataConnection.Token, Is.Empty);
}
[Test]
public void TCDataConnection_WithValidLogin_ReturnsTrue()
{
uut.TCAPIconnection(Method.GET);
}
[Test]
public void Login_WithValidLogin_ReturnsTrue()
{
var mytest = TCDataConnection.LogIn(_username, _password);
Assert.That(mytest, Is.EqualTo(true));
}
[Test]
public void TCAPIconnection_GetPositionWithoutToken_ReturnBadStatusCode()
{
TCDataConnection.Token = "";
var mytest = uutWithPosition.TCAPIconnection(Method.GET);
Assert.That(mytest.StatusCode, Is.Not.EqualTo(HttpStatusCode.OK));
}
[Test]
public void TCAPIconnection_GetPositionValidToken_ReturnGoodStatusCode()
{
TCDataConnection.LogIn(_username, _password);
var mytest = uutWithPosition.TCAPIconnection(Method.GET);
Assert.That(mytest.StatusCode, Is.EqualTo(HttpStatusCode.OK));
}
}
}
|
using System;
using Xunit;
using LinkedList.Classes;
using LLKthValue;
namespace LLKthValueTDD
{
public class UnitTest1
{
[Fact]
public void FindingKth()
{
LList testList = new LList();
testList.Insert(58);
testList.Insert(50);
testList.Insert(48);
testList.Insert(40);
Assert.Equal(50, Program.CallKplusAll(1, testList));
}
/*
[Fact]
public void OutsideRangeKth()
{
LList testList = new LList();
testList.Insert(58);
testList.Insert(50);
testList.Insert(48);
testList.Insert(40);
Assert.Equal(System.Exception, Program.CallKplusAll(8, testList));
}
8/
}
}
|
namespace ModelAndroidAppSimples
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
public partial class Documentos
{
public int ID { get; set; }
[Column(TypeName = "date")]
public DateTime? Emissao { get; set; }
[Column(TypeName = "date")]
public DateTime? Vencimento { get; set; }
[StringLength(250)]
public string Titulo { get; set; }
public decimal? ValorEmAberto { get; set; }
public decimal? Valor { get; set; }
public decimal? ValorTotal { get; set; }
public int? IDDocumento { get; set; }
public int? PessoaID { get; set; }
public int? NumeroPedido { get; set; }
public bool? Cobrado { get; set; }
[StringLength(300)]
public string Pessoa { get; set; }
public int? Tipo { get; set; }
public string Detalhe { get; set; }
public int? IDVendedor { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface IDamageable
{
int Hitpoint { get; set; }
int Hit(int damage);
void Dead();
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Dawnfall
{
public static class HexMath
{
public static HexEdgeDir nextEdge(HexEdgeDir edgeDir)
{
return (edgeDir == HexEdgeDir.TL) ? HexEdgeDir.TR : edgeDir + 1;
}
public static HexEdgeDir nextEdge(HexEdgeDir edgeDir, int distance)
{
while (distance > 0)
{
edgeDir = nextEdge(edgeDir);
distance--;
}
return edgeDir;
}
public static HexEdgeDir prevEdge(HexEdgeDir edgeDir)
{
return (edgeDir == HexEdgeDir.TR) ? HexEdgeDir.TL : edgeDir - 1;
}
public static HexEdgeDir prevEdge(HexEdgeDir edgeDir, int distance)
{
while (distance > 0)
{
edgeDir = prevEdge(edgeDir);
distance--;
}
return edgeDir;
}
public static HexCornerDir nextCorner(HexCornerDir cornerDir)
{
return (cornerDir == HexCornerDir.TL) ? HexCornerDir.T : cornerDir + 1;
}
public static HexCornerDir prevCorner(HexCornerDir cornerDir)
{
return (cornerDir == HexCornerDir.T) ? HexCornerDir.TL : cornerDir - 1;
}
public static HexEdgeDir opositeEdge(HexEdgeDir edgeDir)
{
return nextEdge(nextEdge(nextEdge(edgeDir)));
}
public static HexCornerDir opositeCorner(HexCornerDir cornerDir)
{
return nextCorner(nextCorner(nextCorner(cornerDir)));
}
public static HexCornerDir firstCornerOfEdge(HexEdgeDir edgeDir)
{
return (HexCornerDir)edgeDir;
}
public static HexCornerDir secondCornerOfEdge(HexEdgeDir edgeDir)
{
return firstCornerOfEdge(nextEdge(edgeDir));
}
public static HexEdgeDir prevEdgeOfCorner(HexCornerDir cornerDir)
{
return prevEdge((HexEdgeDir)cornerDir);
}
public static HexEdgeDir nextEdgeOfCorner(HexCornerDir cornerDir)
{
return (HexEdgeDir)cornerDir;
}
public static int getCornerClockwiseDistance(HexCornerDir from, HexCornerDir to)
{
if (to >= from)
return to - from;
return 6 + (to - from);
}
public static int getEdgeClockwiseDistance(HexEdgeDir from, HexEdgeDir to)
{
if (to >= from)
return to - from;
return 6 + (to - from);
}
}
public enum HexEdgeDir
{
TR,
R,
BR,
BL,
L,
TL
}
public enum HexCornerDir
{
T,
TR,
BR,
B,
BL,
TL
}
public enum RiverFlowDirection
{
EMPTY,
IN,
OUT
}
} |
using UnityEngine;
using System.Collections;
public class pieceScript : MonoBehaviour {
public bool blue;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter(Collision col){
if (col.gameObject.GetComponent<pieceScript> ().blue != blue) {
print ("hit");
}
}
}
|
using System;
namespace Demo.DynamicCSharp.CommandLine
{
public class LogClient : ILogClient
{
public void Error(string message, params object[] args)
{
var formattedMessage = string.Format(message, args);
var dateString = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
Console.WriteLine($"{dateString} ERROR: {formattedMessage}");
}
}
}
|
using Arcanoid.Context;
using SFML.Graphics;
namespace Arcanoid.GameObjects.Interfaces
{
public interface IGameObject : Drawable
{
void Invoke(GameContext context);
}
} |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GameTimer : MonoBehaviour {
public Text timeText; //残り時間を写すテキスト
public Text endMouthTimeText; //残りの週を写すテキスト
public static int score = 0; //経過時間
public const int MAX_TIME = 60; //残り時間の最大値
public int time = MAX_TIME; //残り時間
public int endMouthTime = 2; //残りの週
[SerializeField]
public bool isTimerStop = true; //タイマーを進めるかどうか
private GameLogic gameLogicScript;
void Awake() {
gameLogicScript = GameObject.Find ("Main Camera").GetComponent<GameLogic> ();
}
void Start (){
timeText.text = "0";
}
void Update (){
//各テキストに文字を入れる
timeText.text = "" + time.ToString();
endMouthTimeText.text = (endMouthTime - 1).ToString();
//タイマーが動いていいなら
if (isTimerStop == false) {
//タイマーを進ませる
score++;
time = MAX_TIME - score / GameLogic.FPS;
}
if (time <= 0) {
time = 0;
}
//残り時間が0になったら
if (time == 0 && gameLogicScript.gameStatus != (int)GameLogic.PLAY_STATUS.CONVERSATION && gameLogicScript.gameStatus != (int)GameLogic.PLAY_STATUS.PRICE_CONFIG) {
SEManager.isSeSound [(int)SEManager.SE_LIST.WEEK_PASS] = true;
endMouthTime -= 1;
if (endMouthTime <= -1) {
endMouthTime = -1;
}
}
}
//デバッグ用 押すとこの週の時間が終わる
public void ClickFinishTime() {
GameTimer.FinishTimer();
}
//タイマーを0に進める
public static void FinishTimer() {
score = 3600;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Console2.From_051_To_75
{
/*
* Given a binary tree
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
* Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
•You may only use constant extra space.
For example,
Given the following binary tree,
1
/ \
2 3
/ \ \
4 5 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL
*/
public class _054_PopulateNextRight
{
public void NextRight(TreeNodeWithNext root)
{
Queue<TreeNodeWithNext> q = new Queue<TreeNodeWithNext>();
q.Enqueue(root);
q.Enqueue(null);
TreeNodeWithNext prev = null;
TreeNodeWithNext tmp = null;
while (q.Count != 0)
{
tmp = q.Dequeue();
if (prev != null)
{
prev.Next = tmp;
}
prev = tmp;
if (tmp == null && q.Count != 0)
{
q.Enqueue(null);
continue;
}
if (tmp != null && tmp.LeftChild != null)
{
q.Enqueue(tmp.LeftChild);
}
if (tmp != null && tmp.RightChild != null)
{
q.Enqueue(tmp.RightChild);
}
}
}
}
public class TreeNodeWithNext
{
public TreeNodeWithNext(int value)
{
Value = value;
}
public int Value { get; set; }
public TreeNodeWithNext LeftChild { get; set; }
public TreeNodeWithNext RightChild { get; set; }
public TreeNodeWithNext Next { get; set; }
}
}
|
namespace AvaloniaDemo.Models.Tools
{
public class Tool4
{
}
}
|
using Kowalski.Common;
using Kowalski.Extensions;
using Kowalski.Models;
using Microsoft.Bot.Connector.DirectLine;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Globalization;
using Windows.Media.SpeechRecognition;
using Windows.Networking.Connectivity;
using Windows.Networking.Sockets;
using Windows.Storage;
namespace Kowalski.Services
{
public static class Assistant
{
private static SpeechRecognizer assistantInvokerSpeechRecognizer;
private static SpeechRecognizer commandSpeechRecognizer;
private static DirectLineClient directLineClient;
private static Conversation conversation;
private static MessageWebSocket webSocketClient;
public static event EventHandler OnStartRecognition;
public static event EventHandler OnCommandReceived;
public static event EventHandler<BotEventArgs> OnResponseReceived;
private static bool isRunning;
public static async void StartService()
{
try
{
if (isRunning)
{
// If the service is already running, exits.
return;
}
isRunning = true;
var isConnected = false;
while (!isConnected)
{
// Be sure to be connected to the Internet.
var profile = NetworkInformation.GetInternetConnectionProfile();
isConnected = profile?.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess;
await Task.Delay(200);
}
if (Settings.Instance == null)
{
await LoadSettingsAsync();
}
if (directLineClient == null)
{
// Obtain a token using the Direct Line secret
var tokenResponse = await new DirectLineClient(Settings.Instance.DirectLineSecret).Tokens.GenerateTokenForNewConversationAsync();
// Use token to create conversation
directLineClient = new DirectLineClient(tokenResponse.Token);
conversation = await directLineClient.Conversations.StartConversationAsync();
// Connect using a WebSocket.
webSocketClient = new MessageWebSocket();
webSocketClient.MessageReceived += WebSocketClient_MessageReceived;
await webSocketClient.ConnectAsync(new Uri(conversation.StreamUrl));
}
if (assistantInvokerSpeechRecognizer == null)
{
// Create an instance of SpeechRecognizer.
assistantInvokerSpeechRecognizer = new SpeechRecognizer(new Language(Settings.Instance.Culture));
assistantInvokerSpeechRecognizer.Timeouts.InitialSilenceTimeout = TimeSpan.MaxValue;
assistantInvokerSpeechRecognizer.Timeouts.BabbleTimeout = TimeSpan.MaxValue;
// Add a list constraint to the recognizer.
var listConstraint = new SpeechRecognitionListConstraint(new string[] { Settings.Instance.AssistantName }, "assistant");
assistantInvokerSpeechRecognizer.Constraints.Add(listConstraint);
await assistantInvokerSpeechRecognizer.CompileConstraintsAsync();
}
if (commandSpeechRecognizer == null)
{
commandSpeechRecognizer = new SpeechRecognizer(new Language(Settings.Instance.Culture));
// Apply the dictation topic constraint to optimize for dictated freeform speech.
var dictationConstraint = new SpeechRecognitionTopicConstraint(SpeechRecognitionScenario.WebSearch, "dictation");
commandSpeechRecognizer.Constraints.Add(dictationConstraint);
await commandSpeechRecognizer.CompileConstraintsAsync();
}
// The assistant is ready to receive input.
SoundPlayer.Instance.Play(Sounds.SpeechActive);
while (isRunning)
{
try
{
var assistantInvocationResult = await assistantInvokerSpeechRecognizer.RecognizeAsync();
if (assistantInvocationResult.Status == SpeechRecognitionResultStatus.Success && assistantInvocationResult.Confidence != SpeechRecognitionConfidence.Rejected)
{
OnStartRecognition?.Invoke(null, EventArgs.Empty);
SoundPlayer.Instance.Play(Sounds.Ready);
// Starts command recognition. It returns when the first utterance has been recognized.
var commandResult = await commandSpeechRecognizer.RecognizeAsync();
if (commandResult.Status == SpeechRecognitionResultStatus.Success && commandResult.Confidence != SpeechRecognitionConfidence.Rejected)
{
var command = commandResult.NormalizeText();
Debug.WriteLine(command);
OnCommandReceived?.Invoke(null, EventArgs.Empty);
// Sends the activity to the Bot. The answer will be received in the WebSocket received event handler.
var userMessage = new Activity
{
From = new ChannelAccount(Settings.Instance.UserName),
Text = command,
Type = ActivityTypes.Message
};
await directLineClient.Conversations.PostActivityAsync(conversation.ConversationId, userMessage);
}
}
}
catch (Exception ex)
{
OnResponseReceived?.Invoke(null, new BotEventArgs(ex.Message));
}
}
// Clean up used resources.
SoundPlayer.Instance.Play(Sounds.SpeechStopped);
}
catch (Exception ex)
{
OnResponseReceived?.Invoke(null, new BotEventArgs(ex.Message));
SoundPlayer.Instance.Play(Sounds.SpeechStopped);
}
assistantInvokerSpeechRecognizer?.Dispose();
commandSpeechRecognizer?.Dispose();
webSocketClient?.Dispose();
directLineClient?.Dispose();
assistantInvokerSpeechRecognizer = null;
commandSpeechRecognizer = null;
webSocketClient = null;
conversation = null;
directLineClient = null;
isRunning = false;
}
private static async void WebSocketClient_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
{
if (args.MessageType == SocketMessageType.Utf8)
{
string jsonOutput = null;
using (var dataReader = args.GetDataReader())
{
dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
jsonOutput = dataReader.ReadString(dataReader.UnconsumedBufferLength);
}
// Occasionally, the Direct Line service sends an empty message as a liveness ping. Ignore these messages.
if (string.IsNullOrWhiteSpace(jsonOutput))
{
return;
}
var activitySet = JsonConvert.DeserializeObject<ActivitySet>(jsonOutput);
var activities = activitySet.Activities.Where(a => a.From.Id == Settings.Instance.BotId);
foreach (var activity in activities)
{
Debug.WriteLine(activity.Text);
OnResponseReceived?.Invoke(null, new BotEventArgs(activity.Text));
// If there is an audio attached to the response, automatically speaks it.
var audioResponseUrl = activity.Attachments?.FirstOrDefault(a => a.ContentType == "audio/mp3")?.ContentUrl;
if (audioResponseUrl != null)
{
await TextToSpeech.SpeakAsync(activity.Speak ?? activity.Text, Settings.Instance.Culture, audioResponseUrl);
}
}
}
}
public static async void StopService()
{
try
{
await assistantInvokerSpeechRecognizer.StopRecognitionAsync();
}
catch
{
}
isRunning = false;
}
private static async Task LoadSettingsAsync()
{
try
{
var storageFolder = KnownFolders.DocumentsLibrary;
var settingsFile = await storageFolder.GetFileAsync("settings.kowalski");
var content = await FileIO.ReadTextAsync(settingsFile);
Settings.Instance = JsonConvert.DeserializeObject<Settings>(content);
}
catch
{
Settings.Instance = new Settings
{
AssistantName = Constants.AssistantName,
BotId = Constants.BotId,
Culture = Constants.Culture,
DirectLineSecret = Constants.DirectLineSecret,
UserName = Constants.UserName,
VoiceGender = Constants.VoiceGender
};
}
}
}
}
|
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double;
using System;
namespace Newton_Raphson
{
class Program
{
static void Main()
{
// initial values, and number of iterations.
solve(DenseVector.OfArray(new double[] { 2, -1, 1 }), 7);
}
static void solve(Vector<double> initial, int iterations)
{
Vector<double> initVector = initial;
Console.WriteLine("┌─────┬──────────────────────┬──────────────┬─────────────────────────┐");
Console.WriteLine("│ k │ X │ f(X) │ grad(X) |");
Console.WriteLine("├─────┼──────────────────────┼──────────────┼─────────────────────────┤");
bool diverge = false;
bool noInverse = false;
for (int i = 0; i <= iterations; i++)
{
// If the function value is large, assume it is diverging.
if (Math.Abs(f(initVector)) > 2000000000000)
{
diverge = true;
break;
}
// the bellow formatting allows me to copy and paste this easily into a latex file! :smile:
string print = string.Format(" {0, -3} & ${1, 20}$ & ${2,12}$ & ${3,23}$ \\\\", i, VectorString(initVector), Math.Round(f(initVector), 8), VectorString(round(initVector, 5)));
Console.WriteLine(print);
Matrix<double> A = hessian(initVector);
if (A.Determinant() == 0)
{
noInverse = true;
break;
}
initVector = initVector - (A.Inverse() * grad(initVector));
}
Console.WriteLine("└─────┴──────────────────────┴──────────────┴─────────────────────────┘");
if (diverge)
Console.WriteLine("This iteration diverged");
if (noInverse)
Console.WriteLine("The hessian matrix had no inverse");
Console.ReadLine();
}
static string VectorString(Vector<double> vector)
{
string returnValue = "< ";
for (int i = 0; i < vector.Count; i++)
if (i < vector.Count - 1)
returnValue += string.Format("{0} ,", Math.Round(vector[i], 6));
else
returnValue += string.Format("{0} >", Math.Round(vector[i], 6));
return returnValue;
}
//Function f(x,y,z)
static double f(Vector<double> v)
{
double x = v[0], y = v[1], z = v[2];
return (sqr(y) * sqr(z) + sqr(z) * sqr(x) + sqr(x) * sqr(z)) + (sqr(x) + sqr(y) + sqr(z)) - 2 * x * y * z - 2 * (z + x - y) - 2 * (y * z + z * x - x * y);
}
//Gradient of f(x,y,z)
static Vector<double> grad(Vector<double> v)
{
double x = v[0], y = v[1], z = v[2];
return DenseVector.OfArray(new double[] {
2*x*sqr(y) + 2*x*sqr(z) + 2*x - 2*y*z + 2*y - 2*z - 2,
2*y*sqr(x) + 2*y*sqr(z) + 2*x - 2*x*z + 2*y - 2*z + 2,
2*z*sqr(x) - 2*x*y - 2*x + 2*sqr(y)*z - 2*y + 2*z - 2
});
}
static Matrix<double> hessian(Vector<double> v)
{
double x = v[0], y = v[1], z = v[2];
return DenseMatrix.OfArray(new double[,]
{
{
2*x*sqr(y) + 2*sqr(z) + 2,
4*x*y - 2*z + 2,
4*x*z - 2*y - 2
},
{
4*x*y - 2*z + 2,
2*sqr(x) + 2*sqr(z) + 2,
-2*x + 4*y*z - 2
},
{
4*x*z - 2*y - 2,
-2*x + 4*y*z - 2,
2*sqr(x) + 2*sqr(y) + 2
},
});
}
// returning the rounded values of the Vector<double>
public static Vector<double> round(Vector<double> v, int decimals) => DenseVector.OfArray(new double[] { Math.Round(v[0], decimals), Math.Round(v[1], decimals), Math.Round(v[2], decimals) });
// this is silly but I like the syntax of this better than math.pow()
static double sqr(double x) => Math.Pow(x, 2);
}
}
/// ┌─────┬──────────────────────┬──────────────┬─────────────────────────┐
/// │ k │ X │ f(X) │ grad(X) |
/// ├─────┼──────────────────────┼──────────────┼─────────────────────────┤
/// | 0 | < 2 ,-1 ,1 > | 5 | < 2 ,-1 ,1 > |
/// | 1 | < -3 ,-5 ,0 > | 60 | < -3 ,-5 ,0 > |
/// | 2 | < -2.51011 ,-1.459683 ,-0.02972 > | 17.91526554 | < -2.51011 ,-1.45968 ,-0.02972 > |
/// | 3 | < -2.119119 ,-0.343131 ,-0.140689 > | 9.60769874 | < -2.11912 ,-0.34313 ,-0.14069 > |
/// | 4 | < -2.397976 ,0.502059 ,-0.317289 > | 9.34589421 | < -2.39798 ,0.50206 ,-0.31729 > |
/// | 5 | < 7.600513 ,-1.21627 ,-0.06305 > | 23.35958861 | < 7.60051 ,-1.21627 ,-0.06305 > |
/// | 6 | < 16.450713 ,3.742723 ,0.77344 > | 587.09322836 | < 16.45071 ,3.74272 ,0.77344 > |
/// | 7 | < 17.332004 ,-0.393847 ,0.056996 > | 252.13824625 | < 17.332 ,-0.39385 ,0.057 > |
/// └─────┴──────────────────────┴──────────────┴─────────────────────────┘ |
using RO;
using System;
using System.IO;
public static class FileEncoder
{
public static byte[] FileToBytes(string file_path)
{
if (!File.Exists(file_path))
{
LoggerUnused.LogWarning(file_path + " no exist.");
return null;
}
return File.ReadAllBytes(file_path);
}
}
|
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Security.Cryptography;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace Samples
{
class IMDSSample
{
const string ImdsServer = "http://169.254.169.254";
const string InstanceEndpoint = ImdsServer + "/metadata/instance";
const string AttestedEndpoint = ImdsServer + "/metadata/attested/document";
const string NonceValue = "123456";
static async Task Main(string[] args)
{
// Query /instance metadata
var result = await QueryInstanceEndpoint();
ParseInstanceResponse(result);
// Make Attested call and parse the response
result = await QueryAttestedEndpoint();
ParseAttestedResponse(result);
}
private static void ParseAttestedResponse(string response)
{
Console.WriteLine("Parsing Attested response");
AttestedDocument document = (AttestedDocument)SerializeObjectFromJsonString(typeof(AttestedDocument), response);
ValidateCertificate(document);
ValidateAttestedData(document);
}
private static void ValidateCertificate(AttestedDocument document)
{
try
{
// Build certificate from response
X509Certificate2 cert = new X509Certificate2(System.Text.Encoding.UTF8.GetBytes(document.Signature));
// Build certificate chain
X509Chain chain = new X509Chain();
chain.Build(cert);
// Print certificate chain information
foreach (X509ChainElement element in chain.ChainElements)
{
Console.WriteLine("Element issuer: {0}", element.Certificate.Issuer);
Console.WriteLine("Element subject: {0}", element.Certificate.Subject);
Console.WriteLine("Element certificate valid until: {0}", element.Certificate.NotAfter);
Console.WriteLine("Element certificate is valid: {0}", element.Certificate.Verify());
Console.WriteLine("Element error status length: {0}", element.ChainElementStatus.Length);
Console.WriteLine("Element information: {0}", element.Information);
Console.WriteLine("Number of element extensions: {0}{1}", element.Certificate.Extensions.Count, Environment.NewLine);
}
}
catch (CryptographicException ex)
{
Console.WriteLine("Exception: {0}", ex);
}
}
private static void ValidateAttestedData(AttestedDocument document)
{
try
{
byte[] blob = Convert.FromBase64String(document.Signature);
SignedCms signedCms = new SignedCms();
signedCms.Decode(blob);
string result = Encoding.UTF8.GetString(signedCms.ContentInfo.Content);
Console.WriteLine("Attested data: {0}", result);
AttestedData data = SerializeObjectFromJsonString(typeof(AttestedData), result) as AttestedData;
if (data.Nonce.Equals(NonceValue))
{
Console.WriteLine("Nonce values match");
}
}
catch (Exception ex)
{
Console.WriteLine("Error checking signature blob: '{0}'", ex);
}
}
private static void ParseInstanceResponse(string response)
{
// Display raw json
Console.WriteLine("Instance response: {0}{1}", response, Environment.NewLine);
}
private static Task<string> QueryInstanceEndpoint()
{
return QueryImds(InstanceEndpoint, "2021-02-01");
}
private static Task<string> QueryAttestedEndpoint()
{
string nonce = "nonce=" + NonceValue;
return QueryImds(AttestedEndpoint, "2021-02-01", nonce);
}
// Query IMDS server and retrieve JSON result
private static Task<string> QueryImds(string path, string apiVersion)
{
return QueryImds(path, apiVersion, "");
}
private static async Task<string> QueryImds(string path, string apiVersion, string otherParams)
{
string imdsUri = path + "?api-version=" + apiVersion;
if (otherParams != null &&
!otherParams.Equals(string.Empty))
{
imdsUri += "&" + otherParams;
}
string jsonResult = string.Empty;
using (var httpClient = new HttpClient())
{
// IMDS requires bypassing proxies.
WebProxy proxy = new WebProxy();
HttpClient.DefaultProxy = proxy;
httpClient.DefaultRequestHeaders.Add("Metadata", "True");
try
{
jsonResult = await httpClient.GetStringAsync(imdsUri);
}
catch (AggregateException ex)
{
// Handle response failures
Console.WriteLine("Request failed: " + ex.GetBaseException());
}
}
return jsonResult;
}
private static object SerializeObjectFromJsonString(Type objectType, string json)
{
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(objectType);
using (MemoryStream memoryStream = new MemoryStream())
using (StreamWriter writer = new StreamWriter(memoryStream))
{
// Prepare stream
writer.Write(json);
memoryStream.Position = 0;
// Serialize object
return jsonSerializer.ReadObject(memoryStream);
}
}
[DataContract]
public class AttestedDocument
{
[DataMember(Name = "encoding")]
public string Encoding { get; set; }
[DataMember(Name = "signature")]
public string Signature { get; set; }
}
[DataContract]
public class AttestedData
{
[DataMember(Name = "nonce")]
public string Nonce { get; set; }
[DataMember(Name = "vmId")]
public string VmId { get; set; }
[DataMember(Name = "subscriptionId")]
public string SubscriptionId { get; set; }
[DataMember(Name = "plan")] public AttestedDataPlanInfo PlanInfo;
[DataMember(Name = "timeStamp")] public AttestedDataTimeStamp TimeStamp;
}
[DataContract]
public class AttestedDataPlanInfo
{
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "product")]
public string Product { get; set; }
[DataMember(Name = "publisher")]
public string Publisher { get; set; }
}
[DataContract]
public class AttestedDataTimeStamp
{
[DataMember(Name = "createdOn")]
public string CreatedDate { get; set; }
[DataMember(Name = "expiresOn")]
public string ExpiryDate { get; set; }
}
}
}
|
using System;
using System.IO;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using UnityEngine.AI;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditorInternal;
#endif
using Object = UnityEngine.Object;
using Random = UnityEngine.Random;
namespace Game
{
public class HideUIElementOperation : MonoBehaviour, Operation.Interface
{
[SerializeField]
protected UIElement target;
public UIElement Target { get { return target; } }
protected virtual void Reset()
{
target = Dependency.Find<UIElement>(gameObject, Dependency.Direction.Up);
}
public virtual void Execute()
{
if (target == null)
throw new NullReferenceException("No target specificed for " + nameof(HideUIElementOperation));
target.Hide();
}
}
} |
using System;
using System.Runtime.Serialization;
using log4net;
using MKModel;
using MKService.Updates;
using ReDefNet;
namespace MKService.Queries
{
[DataContract(Namespace = ServiceConstants.QueryNamespace)]
public class MageKnightQuery : ObservableObject, IUpdatableMageKnight
{
private readonly ILog log = LogManager.GetLogger(nameof(MageKnightQuery));
public MageKnightQuery()
{
this.initialize();
}
private void initialize()
{
this.instantiatedId = Guid.NewGuid();
}
[DataMember]
private Guid id;
[DataMember]
private Guid instantiatedId;
[DataMember]
private string name;
[DataMember]
private int index;
[DataMember]
private int range;
[DataMember]
private int pointValue;
[DataMember]
private int frontArc;
[DataMember]
private int targets;
[DataMember]
private int click;
[DataMember]
private string setName;
[DataMember]
private string faction;
[DataMember]
private string rank;
[DataMember]
private byte[] modelImage;
[DataMember]
private IDial dial;
[DataMember]
private double xCoordinate;
[DataMember]
private double yCoordinate;
public Guid Id { get { return this.id; } set { this.Set(() => this.Id, ref this.id, value); } }
public string Name { get { return this.name; } set { this.Set(() => this.Name, ref this.name, value); } }
public int Index { get { return this.index; } set { this.Set(() => this.Index, ref this.index, value); } }
public int Range { get { return this.range; } set { this.Set(() => this.Range, ref this.range, value); } }
public int PointValue { get { return this.pointValue; } set { this.Set(() => this.PointValue, ref this.pointValue, value); } }
public int FrontArc { get { return this.frontArc; } set { this.Set(() => this.FrontArc, ref this.frontArc, value); } }
public int Targets { get { return this.targets; } set { this.Set(() => this.Targets, ref this.targets, value); } }
public int Click { get { return this.click; } set { this.Set(() => this.Click, ref this.click, value); } }
public string Faction { get { return this.faction; } set { this.Set(() => this.Faction, ref this.faction, value); } }
public string Rank { get { return this.rank; } set { this.Set(() => this.Rank, ref this.rank, value); } }
public string Set { get { return this.setName; } set { this.Set(() => this.Set, ref this.setName, value); } }
public byte[] ModelImage { get { return this.modelImage; } set { this.Set(() => this.ModelImage, ref this.modelImage, value); } }
public IDial Dial { get { return this.dial; } set { this.Set(() => this.Dial, ref this.dial, value); } }
public Guid InstantiatedId { get { return this.instantiatedId; } }
Guid IMageKnightModel.InstantiatedId => this.instantiatedId;
public double XCoordinate { get { return this.xCoordinate; } set { this.Set(() => this.XCoordinate, ref this.xCoordinate, value); } }
public double YCoordinate { get { return this.yCoordinate; } set { this.Set(() => this.YCoordinate, ref this.yCoordinate, value); } }
public void UpdateMageKnightCoordinates(IUserModel user, Guid instantiatedId, double xCoordinate, double yCoordinate)
{
throw new NotImplementedException();
}
}
}
|
using System.Collections.Generic;
namespace JKMServices.DAL.CRM
{
/// Interface Name : IMoveDetails
/// Author : Pratik Soni
/// Creation Date : 13 Dec 2017
/// Purpose : To perform operations on Move entity
/// Revision :
/// </summary>
public interface IMoveDetails
{
DTO.ServiceResponse<DTO.Move> GetMoveData(string moveID);
DTO.ServiceResponse<DTO.Move> GetContactForMove(string moveID);
DTO.ServiceResponse<DTO.Move> GetMoveId(string customerID);
Dictionary<string, string> GetMoveGUID(string moveNumber);
DTO.ServiceResponse<List<DTO.Move>> GetMoveList(string statusReason);
DTO.ServiceResponse<DTO.Move> PutMoveData(string moveID, string jsonFormattedData);
DTO.ServiceResponse<DTO.Move> GetCustomerDetails(string moveID);
}
}
|
using System.Collections.Generic;
using day9a.Models;
namespace day9a.ContactList
{
public class ContactsLists
{
List<Contact> objList;
public ContactsLists()
{
objList=new List<Contact>();
}
public void createContact(Contact objContact)
{
objList.Add(objContact);
}
public List<Contact> DisplayList()
{
return objList;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BPiaoBao.AppServices
{
public abstract class BaseService:IDisposable
{
public virtual void Dispose()
{
}
}
}
|
namespace AtlBot.Models.Slack.Chat
{
public class PostMessageRequest : RequestBase
{
public string Channel { get; set; }
public string Username { get; set; }
public string Text { get; set; }
public string IconUrl { get; set; }
public bool? UnfurlLinks { get; set; }
public bool? AsUser { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class last : MonoBehaviour
{
public GameObject camrea;
public GameObject light;
public GameObject door;
public GameObject panel;
public GameObject body;
public GameObject player;
public GameObject CCTV_View;
private void OnTriggerEnter(Collider other)
{
door.GetComponent<Animator>().SetBool("open", false);
StartCoroutine(End());
}
IEnumerator End()
{
door.GetComponent<Animator>().SetBool("open", false);
yield return new WaitForSeconds(1f);
Manager.soundManager.soundsystem.gun();
yield return new WaitForSeconds(0.5f);
panel.SetActive(true);
camrea.SetActive(true);
Destroy(player);
yield return new WaitForSeconds(1f);
panel.SetActive(false);
body.SetActive(true);
light.SetActive(true);
camrea.GetComponent<Camera>().depth = 3f;
CCTV_View.SetActive(true);
yield return new WaitForSeconds(1f);
Manager.soundManager.soundsystem.last();
}
}
|
using System;
using System.Collections.Generic;
namespace RequestToCash
{
public class RequestData : IEquatable<RequestData>, IComparable<RequestData>
{
Guid id;
int _time;
string _data;
public Guid Id { get => id; }
public int Time
{
get => _time;
set
{
if (value < 0) throw new Exception("Negative time exp");
else
{
_time = value;
}
}
}
public string Data
{
get => _data;
set
{
if (String.IsNullOrEmpty(value)) _data = "empty request";
else _data = value;
}
}
public RequestData(string data, int time)
{
_time = time;
_data = data;
id = Guid.NewGuid();
}
public int CompareTo(RequestData other)
{
if (this.Time > other.Time) return 1;
else if (this.Time < other.Time) return -1;
else return 0;
}
public bool Equals(RequestData other)
{
return (this.Id == other.Id);
}
public bool Equals(RequestData other, IEqualityComparer<RequestData> comperer)
{
return comperer.Equals(this, other);
}
public override string ToString()
{
return $"id = \"{this.id}\" data = \"{this._data}\", time = \"{this._time}\"";
}
public static bool operator <(RequestData a, RequestData b)
{
return (a.Time < b.Time);
}
public static bool operator >(RequestData a, RequestData b)
{
return (a.Time > b.Time);
}
}
}
|
/* Project Prologue
Name: Spencer Carter
Class: CS 1400 Section 003
Lab #16 Dice Game Implementation
Date: 04/08/15
I declare that the following code was written by me, provided
by the instrustor, assisted via the lovely people in the drop
in lab, or provided in the textbook for this project. I also
understand that copying source code from any other sourece
constitutes cheating, and that I will recieve a zero on this
project if I am found in violation of this policy.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/* Psudocode Stuff
Have a menu system that checks if they want to play or not
Have the menu system check for int cases, because that is the easiest to error proof
Call a method to ask for a year to test
error check the input
make sure it is above the first leap year
pass the valid year to a method
The method will check if the passed year value is a year
Then it will pass it back to the method to a console write which will tell the user if it is or is not a leap year
*/
namespace Lab_17
{
/// <summary>
/// Default class for console apps.
/// </summary>
class Program
{
/// <summary>
/// Default method for console apps.
/// </summary>
static void Main()
{
//to hold the console open to make people happy.
Console.ReadKey();
}//End static void Main()
}//End class Program
}//End namespace Lab_17
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Jieshai
{
public static class Enumerable
{
public static IOrderedEnumerable<TSource> OrderBy<TSource>(this IEnumerable<TSource> source, string propertyName)
{
if (propertyName == null)
{
throw new ArgumentNullException("propertyName");
}
PropertyInfo property = typeof(TSource).GetProperty(propertyName);
if (ReflectionHelper.Is<IOrderable>(property.PropertyType))
{
return source.OrderBy(o =>(IOrderable)property.GetValue(o, null));
}
else if (ReflectionHelper.IsIList<IOrderable>(property.PropertyType))
{
return source.OrderBy(o =>(IList)property.GetValue(o, null));
}
return source.OrderBy(o => property.GetValue(o, null));
}
public static IOrderedEnumerable<TSource> OrderByDescending<TSource>(this IEnumerable<TSource> source, string propertyName)
{
if (propertyName == null)
{
throw new ArgumentNullException("propertyName");
}
PropertyInfo property = typeof(TSource).GetProperty(propertyName);
if (ReflectionHelper.Is<IOrderable>(property.PropertyType))
{
return source.OrderByDescending(o =>(IOrderable)property.GetValue(o, null));
}
else if (ReflectionHelper.IsIList<IOrderable>(property.PropertyType))
{
return source.OrderByDescending(o =>(IList)property.GetValue(o, null));
}
return source.OrderByDescending(o => property.GetValue(o, null));
}
public static IOrderedEnumerable<TSource> OrderBy<TSource>(this IEnumerable<TSource> source, Func<TSource, IOrderable> keySelector)
{
return source.OrderBy(o =>
{
IOrderable orderable = keySelector(o);
if (orderable == null)
{
return null;
}
return orderable.GetOrderValue();
});
}
public static IOrderedEnumerable<TSource> OrderBy<TSource>(this IEnumerable<TSource> source, Func<TSource, IList> keySelector)
{
return source.OrderBy(o => GetOrderValue(keySelector(o)));
}
public static IOrderedEnumerable<TSource> OrderByDescending<TSource>(this IEnumerable<TSource> source, Func<TSource, IOrderable> keySelector)
{
return source.OrderByDescending(o =>
{
IOrderable orderable = keySelector(o);
if (orderable == null)
{
return null;
}
return orderable.GetOrderValue();
});
}
public static IOrderedEnumerable<TSource> OrderByDescending<TSource>(this IEnumerable<TSource> source, Func<TSource, IList> keySelector)
{
return source.OrderByDescending(o => GetOrderValue(keySelector(o)));
}
private static string GetOrderValue(IList list)
{
if(list == null)
{
return null;
}
string orderValue = "";
foreach (object obj in list)
{
orderValue += (obj as IOrderable).GetOrderValue();
}
return orderValue;
}
}
}
|
using Godot;
using System;
public class BT_Target : BT_Base
{
private Spatial target;
public override State tick(Node _entity)
{
var entity = (Bot)_entity;
if (target != null) {
var target_normal = (target.Translation - entity.Translation).Normalized();
var forward = entity.Transform.basis.z.Dot(target_normal);
//GD.Print(forward);
if (forward < -0.99) {
return State.Success;
}
var right = entity.Transform.basis.x.Dot(target_normal);
var up = entity.Transform.basis.y.Dot(target_normal);
entity.turn(new Vector3(up, -right, 0));
}
return State.Failure;
}
private void _on_Area_body_entered(object body)
{
if (body is Spatial) {
var node = (Spatial)body;
if (node.Name == "Player") {
this.target = (Spatial)node;
}
}
}
private void _on_Area_body_exited(object body)
{
if (body is Spatial) {
var node = (Spatial)body;
if (node.Name == "Player") {
this.target = null;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.UI.WebControls;
using DataAccessLayer.basis;
using Uxnet.Web.Module.Common;
namespace eIVOGo.Module.Base
{
public abstract partial class EntityItemActionList<T, TEntity> : EntityItemList<T, TEntity>
where T : DataContext, new()
where TEntity : class, new()
{
protected global::Uxnet.Web.Module.Common.ActionHandler doDelete;
protected global::Uxnet.Web.Module.Common.ActionHandler doEdit;
protected global::Uxnet.Web.Module.Common.ActionHandler doCreate;
protected EditEntityItem<T,TEntity> editItem;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
doDelete.DoAction = arg =>
{
delete(arg);
};
doEdit.DoAction = arg =>
{
edit(arg);
};
doCreate.DoAction = arg =>
{
create();
};
editItem.Done += new EventHandler(editItem_Done);
}
void editItem_Done(object sender, EventArgs e)
{
gvEntity.DataBind();
}
protected virtual void create()
{
}
protected virtual void edit(String keyValue)
{
}
protected virtual void delete(String keyValue)
{
}
}
} |
/****************************************************************************************
* Creates an Address object based on GIS requirements for lexington county.
****************************************************************************************/
using AddressParser.Business;
using System;
using System.Globalization;
using System.Text;
namespace AddressParser.Objects
{
public class Address
{
#region fields
#endregion
#region properties
public string Address1 { get; private set; } // street address, apt/lot information
public string Address2 { get; private set; } // city, state zip
public string Address3 { get; private set; } // unit/lot information
public string StreetNumber { get; private set; }
public string StreetNumberSuffix { get; private set; }
public string PrefixDirectional { get; private set; }
public string StreetName { get; private set; }
public string StreetType { get; private set; }
public string SuffixDirectional { get; private set; }
public string UnitType { get; private set; }
public string Unit { get; private set; }
public string City { get; private set; }
public string DefaultCity { get; private set; }
public string State { get; private set; }
public string ZipCode { get; private set; }
public bool isValid { get; private set; }
#endregion
#region constructors
public Address(string address1, string address2, string address3)
{
Address1 = address1;
Address2 = address2;
Address3 = address3;
string[] parsedAddress = ParseAddress.ParseAddressLine1(address1);
StreetNumber = parsedAddress[0];
StreetNumberSuffix = parsedAddress[1];
PrefixDirectional = parsedAddress[2];
StreetName = parsedAddress[3];
StreetType = parsedAddress[4];
SuffixDirectional = parsedAddress[5];
string[] parsedAddress2 = ParseAddress.ParseAddressLine2(address2);
City = parsedAddress2[0];
State = parsedAddress2[1];
ZipCode = parsedAddress2[2];
DefaultCity = GetDefaultCity();
string[] parsedAddress3 = ParseAddress.ParseAddressLine3(address3);
UnitType = parsedAddress3[0];
Unit = parsedAddress3[1];
}
#endregion
#region methods
public string GetAddress()
{
StringBuilder sb = new StringBuilder();
sb.Append(!String.IsNullOrEmpty(StreetNumber) ? ToTitleCase(StreetNumber) : String.Empty);
sb.Append(!String.IsNullOrEmpty(StreetNumberSuffix) ? StreetNumberSuffix : String.Empty);
sb.Append(" ");
sb.Append(!String.IsNullOrEmpty(PrefixDirectional) ? PrefixDirectional.ToUpper() + " " : String.Empty);
sb.Append(!String.IsNullOrEmpty(StreetName) ? ToTitleCase(StreetName) : String.Empty);
sb.Append(!String.IsNullOrEmpty(StreetType) ? " " + ToTitleCase(StreetType) : String.Empty);
sb.Append(!String.IsNullOrEmpty(SuffixDirectional) ? " " + SuffixDirectional.ToUpper() : String.Empty);
sb.Append(", ");
sb.Append(!String.IsNullOrEmpty(UnitType) ? ToTitleCase(UnitType) + " " : String.Empty);
sb.Append(!String.IsNullOrEmpty(Unit) ? Unit + ", " : String.Empty);
sb.Append(!String.IsNullOrEmpty(City) ? ToTitleCase(City) : String.Empty);
sb.Append(", ");
sb.Append(!String.IsNullOrEmpty(State) ? State.ToUpper() : String.Empty);
sb.Append(" ");
sb.Append(!String.IsNullOrEmpty(ZipCode) ? ZipCode : String.Empty);
return sb.ToString();
}
/// <summary>
/// Based on the zip code provided, the default city is returned.
/// </summary>
/// <returns></returns>
/// if this is ever expanded to a wider range of areas, look into USPS web tools to accomplish.
private string GetDefaultCity()
{
if (this.ZipCode.Equals("29006"))
return "Batesburg";
if (this.ZipCode.Equals("29033"))
return "Cayce";
if (this.ZipCode.Equals("29036"))
return "Chapin";
if (this.ZipCode.Equals("29054"))
return "Gaston";
if (this.ZipCode.Equals("29063"))
return "Irmo";
if (this.ZipCode.Equals("29070"))
return "Leesville";
if (this.ZipCode.Equals("29072") || this.ZipCode.Equals("29073"))
return "Lexington";
if (this.ZipCode.Equals("29075"))
return "Little Mountain";
if (this.ZipCode.Equals("29112"))
return "North";
if (this.ZipCode.Equals("29123"))
return "Pelion";
if (this.ZipCode.Equals("29160"))
return "Swansea";
if (this.ZipCode.Equals("29169") || this.ZipCode.Equals("29170") || this.ZipCode.Equals("29172"))
return "West Columbia";
if (this.ZipCode.Equals("29210") || this.ZipCode.Equals("29212"))
return "Columbia";
return String.Empty;
}
private string ToTitleCase(string str)
{
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
}
#endregion
}
}
|
namespace Triton.Game.Mapping
{
using ns26;
using System;
[Attribute38("UberFloaty")]
public class UberFloaty : MonoBehaviour
{
public UberFloaty(IntPtr address) : this(address, "UberFloaty")
{
}
public UberFloaty(IntPtr address, string className) : base(address, className)
{
}
public void Start()
{
base.method_8("Start", Array.Empty<object>());
}
public void Update()
{
base.method_8("Update", Array.Empty<object>());
}
public float frequencyMax
{
get
{
return base.method_2<float>("frequencyMax");
}
}
public float frequencyMaxRot
{
get
{
return base.method_2<float>("frequencyMaxRot");
}
}
public float frequencyMin
{
get
{
return base.method_2<float>("frequencyMin");
}
}
public float frequencyMinRot
{
get
{
return base.method_2<float>("frequencyMinRot");
}
}
public bool localSpace
{
get
{
return base.method_2<bool>("localSpace");
}
}
public Vector3 m_interval
{
get
{
return base.method_2<Vector3>("m_interval");
}
}
public Vector3 m_offset
{
get
{
return base.method_2<Vector3>("m_offset");
}
}
public Vector3 m_rotationInterval
{
get
{
return base.method_2<Vector3>("m_rotationInterval");
}
}
public Vector3 magnitude
{
get
{
return base.method_2<Vector3>("magnitude");
}
}
public Vector3 magnitudeRot
{
get
{
return base.method_2<Vector3>("magnitudeRot");
}
}
}
}
|
using SafetyForAllApp.Model;
using SafetyForAllApp.Service.Interfaces;
using SQLite;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace SafetyForAllApp.MyDatabase
{
public class SQLconn : IDatabase
{
private SQLiteAsyncConnection database;
public SQLconn()
{
string dbPath = GetDbPath();
database = new SQLiteAsyncConnection(dbPath);
database.CreateTableAsync<SignUpDetails>().Wait();
}
private string GetDbPath()
{
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Safety.Db3");
}
public Task<List<SignUpDetails>> GetItemsAsync()
{
return database.Table<SignUpDetails>().ToListAsync();
}
public Task<List<SignUpDetails>> GetItemsNotDoneAsync()
{
return database.QueryAsync<SignUpDetails>("SELECT * FROM [TodoItem] WHERE [Done] = 0");
}
public Task<int> SaveItemAsync(SignUpDetails item)
{
if (item.ID != 0)
{
return database.UpdateAsync(item);
}
else
{
return database.InsertAsync(item);
}
}
public Task<int> DeleteItemAsync(SignUpDetails item)
{
return database.DeleteAsync(item);
}
public async Task<SignUpDetails> GetUserByUserName(string userName)
{
var users = await database.Table<SignUpDetails>().ToListAsync();
return await database.Table<SignUpDetails>().Where(x => x.Username == userName).FirstOrDefaultAsync();
}
}
}
|
using Parser.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace Parser.Handler
{
public class DataHandler
{
public List<Data_Repository> Parser(string Path)
{
//http://data.gov.tw/node/6076 -> 紫外線即時監測資料
List<Data_Repository> ParserResult = new List<Data_Repository>();
Console.WriteLine(@"Loading XML File...");
XElement xml = XElement.Load(Path);
Console.WriteLine("Analyze XML File...\n");
IEnumerable<XElement> StationNode = xml.Descendants("Data");
StationNode.ToList().ForEach(stationNode =>
{
string StationIdentifier = stationNode.Element("SiteName").Value.Trim();
string UV_Value = stationNode.Element("UVI").Value.Trim();
string PublishAgency = stationNode.Element("PublishAgency").Value.Trim();
string County = stationNode.Element("County").Value.Trim();
string WGS84Lon = stationNode.Element("WGS84Lon").Value.Trim();
string WGS84Lat = stationNode.Element("WGS84Lat").Value.Trim();
string RecordTime = stationNode.Element("PublishTime").Value.Trim();
Data_Repository parser_repository = new Data_Repository();
parser_repository._Parser_SiteName = StationIdentifier;
parser_repository._Parser_UVI = UV_Value;
parser_repository._Parser_PublishAgency = PublishAgency;
parser_repository._Parser_County = County;
parser_repository._Parser_WGS84Lon = WGS84Lon;
parser_repository._Parser_WGS84Lat = WGS84Lat;
parser_repository._Parser_PublishTime = RecordTime;
ParserResult.Add(parser_repository);
});
return ParserResult;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ProjectFinder.Manager
{
public class InteractiveManager
{
public static int QueryUserForSelection<T>(IEnumerable<T> collection,Func<T, string> func)
{
var errorInfo = new StringBuilder("Error: Multiple alternatives are matched!\n");
var index = 1;
foreach (var row in collection)
errorInfo.AppendLine($" {index++} - " + func(row));
errorInfo.AppendLine($" 0 - exit\n");
errorInfo.Append("Please input index to continue: ");
Console.Write(errorInfo);
return ReadUserInput(index - 1);
}
private static int ReadUserInput(int upperBound)
{
try
{
var selection = int.Parse(Console.ReadLine());
if (selection < 0 || selection > upperBound) throw new Exception();
return selection;
}
catch
{
System.Console.Write("Invalid input. Please try again: ");
return ReadUserInput(upperBound);
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LoadSceneTest : MonoBehaviour {
private GameObject[,] regions = null;
void Start(){
LoadScene();
}
void LoadScene(){
regions = new GameObject[42, 37];
for (int i = 0; i < 42; i++) {
for (int j = 0; j < 37; j++) {
regions[i, j] = new GameObject();
string url = "scene/scene_10002/" + i + "_" + j;
Texture2D bg = Resources.Load(url) as Texture2D;
Rect rt = new Rect(0, 0, bg.width, bg.height);
Sprite st = Sprite.Create(bg, rt, new Vector2(0f, 0f));
SpriteRenderer sr = regions[i, j].AddComponent<SpriteRenderer>();
sr.sprite = st;
sr.sortingOrder = 1;
float x = 3.2f * i;
float y = 1.8f * (36 - j);
regions[i, j].transform.position = new Vector3(x, y, 0);
regions[i, j].gameObject.name = url;
}
}
}
void DrawGrids() {
for (int i = 0; i < 43; i++) {
Vector3 from = new Vector3(0,0,0);
Vector3 to = new Vector3(0,0,0);
Gizmos.color = new Color(0.3f, 0.7f, 0.5f, 0.5f);
from.x = 3.2f * i;
to.x = 3.2f * i;
to.y = 1.8f * 37;
Gizmos.DrawLine(from, to);
}
for (int i = 0; i < 38; i++)
{
Vector3 from = new Vector3(0, 0, 0);
Vector3 to = new Vector3(0, 0, 0);
Gizmos.color = new Color(0.3f, 0.7f, 0.5f, 0.5f);
from.y = 1.8f * i;
to.x = 3.2f * 42;
to.y = 1.8f * i;
Gizmos.DrawLine(from, to);
}
}
void _DrawGrids()
{
Vector3 from = new Vector3(19.04f, 8.10f, 0);
Vector3 to = new Vector3(22.308f, 9.74f, 0);
Gizmos.color = new Color(1.0f, 0, 0, 0.5f);
Gizmos.DrawLine(from, to);
from = new Vector3(35.125f, 0.046f, 0);
to = new Vector3(0.01f, 17.52f, 0);
Gizmos.color = new Color(1.0f, 0, 0, 0.5f);
Gizmos.DrawLine(from, to);
from = new Vector3(19.436f, 7.876f, 0);
to = new Vector3(22.64f, 9.46f, 0);
Gizmos.color = new Color(1.0f, 0, 0, 0.5f);
Gizmos.DrawLine(from, to);
from = new Vector3(19.493f, 8.35f, 0);
to = new Vector3(19.89f, 8.12f, 0);
Gizmos.color = new Color(1.0f, 0, 0, 0.5f);
Gizmos.DrawLine(from, to);
}
// Update is called once per frame
void Update () {
}
void OnDrawGizmos()
{
DrawGrids();
_DrawGrids();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model
{
public abstract class MovableObject
{
public Tile Spot;
public abstract Direction WayToMove();
public abstract void MakeMove(Direction richting);
public abstract char ToChar();
}
}
|
// Copyright 2020 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using NtApiDotNet.Utilities.ASN1;
using NtApiDotNet.Utilities.Security;
using NtApiDotNet.Utilities.Text;
using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace NtApiDotNet.Win32.Security.Authentication.Kerberos
{
/// <summary>
/// Class to represent Kerberos Encrypted Data.
/// </summary>
public class KerberosEncryptedData
{
/// <summary>
/// Encryption type for the CipherText.
/// </summary>
public KerberosEncryptionType EncryptionType { get; private set; }
/// <summary>
/// Key version number.
/// </summary>
public int? KeyVersion { get; private set; }
/// <summary>
/// Cipher Text.
/// </summary>
public byte[] CipherText { get; private set; }
internal KerberosEncryptedData()
{
CipherText = new byte[0];
}
private protected KerberosEncryptedData(KerberosEncryptionType type,
int? key_version, byte[] cipher_text)
{
EncryptionType = type;
KeyVersion = key_version;
CipherText = cipher_text;
}
internal virtual string Format()
{
StringBuilder builder = new StringBuilder();
builder.AppendLine($"Encryption Type : {EncryptionType}");
if (KeyVersion.HasValue)
{
builder.AppendLine($"Key Version : {KeyVersion}");
}
HexDumpBuilder hex = new HexDumpBuilder(false, true, false, false, 0);
hex.Append(CipherText);
hex.Complete();
builder.AppendLine($"Cipher Text :");
builder.Append(hex);
return builder.ToString();
}
private bool DecryptRC4WithKey(KerberosAuthenticationKey key, KerberosKeyUsage key_usage, out byte[] decrypted)
{
HMACMD5 hmac = new HMACMD5(key.Key);
byte[] key1 = hmac.ComputeHash(BitConverter.GetBytes((int)key_usage));
hmac = new HMACMD5(key1);
byte[] checksum = new byte[16];
Buffer.BlockCopy(CipherText, 0, checksum, 0, checksum.Length);
byte[] key2 = hmac.ComputeHash(checksum);
byte[] result = ARC4.Transform(CipherText, 16, CipherText.Length - 16, key2);
hmac = new HMACMD5(key1);
byte[] calculated_checksum = hmac.ComputeHash(result);
decrypted = new byte[result.Length - 8];
Buffer.BlockCopy(result, 8, decrypted, 0, decrypted.Length);
return NtObjectUtils.EqualByteArray(checksum, calculated_checksum);
}
private const int AES_BLOCK_SIZE = 16;
private const int AES_CHECKSUM_SIZE = 12;
private const int AES_CONFOUNDER_SIZE = 16;
private static void SwapEndBlocks(byte[] cipher_text)
{
if (cipher_text.Length < AES_BLOCK_SIZE*2)
{
return;
}
byte[] block = new byte[AES_BLOCK_SIZE];
Array.Copy(cipher_text, cipher_text.Length - AES_BLOCK_SIZE, block, 0, AES_BLOCK_SIZE);
Array.Copy(cipher_text, cipher_text.Length - (2 * AES_BLOCK_SIZE), cipher_text, cipher_text.Length - AES_BLOCK_SIZE, AES_BLOCK_SIZE);
Array.Copy(block, 0, cipher_text, cipher_text.Length - (2 * AES_BLOCK_SIZE), AES_BLOCK_SIZE);
}
private static int AlignBlock(int size)
{
return (size + (AES_BLOCK_SIZE - 1)) & ~(AES_BLOCK_SIZE - 1);
}
private byte[] DecryptAESBlock(byte[] key, byte[] cipher_text, int offset)
{
AesManaged aes = new AesManaged();
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.None;
aes.Key = key;
aes.IV = new byte[16];
var dec = aes.CreateDecryptor();
byte[] block = new byte[AES_BLOCK_SIZE];
dec.TransformBlock(cipher_text, offset, AES_BLOCK_SIZE, block, 0);
return block;
}
private const byte EncryptionKey = 0xAA;
private const byte VerificationKey = 0x55;
private byte[] DeriveTempKey(KerberosAuthenticationKey key, KerberosKeyUsage key_usage, byte key_type)
{
byte[] r = BitConverter.GetBytes((int)key_usage).Reverse().ToArray();
Array.Resize(ref r, 5);
r[4] = key_type;
return NFold.Compute(r, 16);
}
private bool DecryptAESWithKey(KerberosAuthenticationKey key, KerberosKeyUsage key_usage, out byte[] decrypted)
{
byte[] derive_enc_key = DeriveTempKey(key, key_usage, EncryptionKey);
byte[] derive_mac_key = DeriveTempKey(key, key_usage, VerificationKey);
byte[] new_key = KerberosAuthenticationKey.DeriveAesKey(key.Key, derive_enc_key);
int cipher_text_length = CipherText.Length - AES_CHECKSUM_SIZE;
int remaining = AES_BLOCK_SIZE - (cipher_text_length % AES_BLOCK_SIZE);
decrypted = new byte[AlignBlock(cipher_text_length)];
Array.Copy(CipherText, decrypted, cipher_text_length);
if (remaining > 0)
{
byte[] decrypted_block = DecryptAESBlock(new_key, decrypted, decrypted.Length - (AES_BLOCK_SIZE * 2));
Array.Copy(decrypted_block, AES_BLOCK_SIZE - remaining, decrypted, decrypted.Length - remaining, remaining);
}
SwapEndBlocks(decrypted);
AesManaged aes = new AesManaged();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.None;
aes.Key = new_key;
aes.IV = new byte[16];
var dec = aes.CreateDecryptor();
dec.TransformBlock(decrypted, 0, decrypted.Length, decrypted, 0);
// Obviously not a secure check. This is for information only.
HMACSHA1 hmac = new HMACSHA1(KerberosAuthenticationKey.DeriveAesKey(key.Key, derive_mac_key));
byte[] hash = hmac.ComputeHash(decrypted, 0, cipher_text_length);
for (int i = 0; i < AES_CHECKSUM_SIZE; ++i)
{
if (hash[i] != CipherText[cipher_text_length + i])
return false;
}
Array.Copy(decrypted, AES_CONFOUNDER_SIZE, decrypted, 0, cipher_text_length - AES_CONFOUNDER_SIZE);
Array.Resize(ref decrypted, cipher_text_length - AES_CONFOUNDER_SIZE);
return true;
}
private bool DecryptRC4(KerberosKeySet keyset, string realm, KerberosPrincipalName server_name, KerberosKeyUsage key_usage, out byte[] decrypted)
{
KerberosAuthenticationKey key = keyset.FindKey(EncryptionType, server_name.NameType, server_name.GetPrincipal(realm), KeyVersion ?? 0);
if (key != null)
{
if (DecryptRC4WithKey(key, key_usage, out decrypted))
return true;
}
foreach (var next in keyset.GetKeysForEncryption(EncryptionType))
{
if (DecryptRC4WithKey(next, key_usage, out decrypted))
return true;
}
decrypted = null;
return false;
}
private bool DecryptAES(KerberosKeySet keyset, string realm, KerberosPrincipalName server_name, KerberosKeyUsage key_usage, out byte[] decrypted)
{
KerberosAuthenticationKey key = keyset.FindKey(EncryptionType, server_name.NameType, server_name.GetPrincipal(realm), KeyVersion ?? 0);
if (key != null)
{
if (DecryptAESWithKey(key, key_usage, out decrypted))
return true;
}
foreach (var next in keyset.GetKeysForEncryption(EncryptionType))
{
if (DecryptAESWithKey(next, key_usage, out decrypted))
return true;
}
decrypted = null;
return false;
}
internal bool Decrypt(KerberosKeySet keyset, string realm, KerberosPrincipalName server_name, KerberosKeyUsage key_usage, out byte[] decrypted)
{
if (EncryptionType == KerberosEncryptionType.ARCFOUR_HMAC_MD5)
{
return DecryptRC4(keyset, realm, server_name, key_usage, out decrypted);
}
else if (EncryptionType == KerberosEncryptionType.AES128_CTS_HMAC_SHA1_96
|| EncryptionType == KerberosEncryptionType.AES256_CTS_HMAC_SHA1_96)
{
return DecryptAES(keyset, realm, server_name, key_usage, out decrypted);
}
decrypted = null;
return false;
}
internal static KerberosEncryptedData Parse(DERValue value)
{
if (!value.CheckSequence())
throw new InvalidDataException();
KerberosEncryptedData ret = new KerberosEncryptedData();
foreach (var next in value.Children)
{
if (next.Type != DERTagType.ContextSpecific)
throw new InvalidDataException();
switch (next.Tag)
{
case 0:
ret.EncryptionType = (KerberosEncryptionType)next.ReadChildInteger();
break;
case 1:
ret.KeyVersion = next.ReadChildInteger();
break;
case 2:
ret.CipherText = next.ReadChildOctetString();
break;
default:
throw new InvalidDataException();
}
}
return ret;
}
}
}
|
#region Copyright Syncfusion Inc. 2001-2015.
// Copyright Syncfusion Inc. 2001-2015. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SampleBrowser
{
public class Model
{
public string Name { get; set; }
public DateTime date { get; set; }
public double Value { get; set; }
public double Size { get; set; }
public double High { get; set; }
public double Low { get; set; }
public Model(string name, double value)
{
Name = name;
Value = value;
}
public Model(string name, double value, double size)
{
Name = name;
Value = value;
Size = size;
}
public Model(string name, double high, double low, double open, double close)
{
Name = name;
Value = high;
Size = low;
High = open;
Low = close;
}
public Model(double value, double size)
{
Value = value;
Size = size;
}
public Model(DateTime dateTime, double value)
{
date = dateTime;
Value = value;
}
}
} |
using System.Threading.Tasks;
using CallCenter.Client.ViewModel.Helpers;
namespace CallCenter.Client.ViewModel.ViewModels
{
public abstract class OkCancelViewModel : ViewModelBase
{
protected virtual void OnOkExecuted(object parameter) { }
protected virtual void OnOkExecutedAsync(object parameter) { }
protected virtual void OnCancelExecuted(object parameter) { }
protected virtual void OnCancelExecutedAsync(object parameter) { }
public SimpleCommand OkCommand
{
get
{
return new SimpleCommand(this.Save);
}
}
public SimpleCommand CancelCommand
{
get
{
return new SimpleCommand(this.Cancel);
}
}
private async void Cancel(object parameter)
{
await this.OnCancelExecutedTask(parameter);
this.OnCancelExecuted(parameter);
}
private Task OnOkExecutedTask(object parameter)
{
return Task.Run(() => this.OnOkExecutedAsync(parameter));
}
private Task OnCancelExecutedTask(object parameter)
{
return Task.Run(() => this.OnCancelExecutedAsync(parameter));
}
private async void Save(object parameter)
{
await this.OnOkExecutedTask(parameter);
this.OnOkExecuted(parameter);
}
public OkCancelViewModel(IWindowService windowService) : base(windowService)
{
}
}
} |
using UnityEngine;
using Mirror;
public class PlayerShoot : NetworkBehaviour
{
public PlayerWeapon weapon;
[SerializeField]
private GameObject wand;
[SerializeField]
private LayerMask mask;
void Start()
{
if (wand == null)
{
Debug.LogError("PlayerShoot: No wand referenced!");
this.enabled = false;
}
}
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
RaycastHit _hit;
// We hit something
if (Physics.Raycast(wand.transform.position, wand.transform.up, out _hit, weapon.range, mask))
{
Debug.Log("We hit " + _hit.collider.name);
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Images {
public void CreateChoiceColor(int n) {
if (n == 0)
return;
GameObject instanciateObj = (GameObject)GameObject.Instantiate(Resources.Load("checkcolorcard"));
instanciateObj.transform.SetParent(GameObject.Find("Canvas").transform);
instanciateObj.GetComponent<RectTransform>().localPosition = new Vector3(24, 142, 0);
instanciateObj.transform.GetChild(0).GetComponent<Text>().text = n.ToString();
}
}
|
using System.Collections.Generic;
using HelperLibrary.Models;
namespace ConnectLibrary.SQLRepository.Interfaces
{
public interface IPersonRepository<T> where T : class
{
List<T> GetPersonByName(PeopleTable profession, string lastName, string firstname);
}
} |
namespace D_API.Types.DataKeeper
{
public enum DataOpResult
{
/// <summary>
/// The user tried to perform an operation, but had passed their transfer quota for the upload or download operation
/// </summary>
OverTransferQuota,
/// <summary>
/// The user tried to perform an operation, but had passed their storage quota
/// </summary>
OverStorageQuota,
/// <summary>
/// The user tried to overwrite data they did not specifically request to overwrite
/// </summary>
NoOverwrite,
/// <summary>
/// The user tried to access data that does not exist
/// </summary>
DataDoesNotExist,
/// <summary>
/// The user tried to access data they do not have access to
/// </summary>
DataInaccessible,
/// <summary>
/// The user tried to perform an operation without the proper arguments
/// </summary>
BadArguments,
/// <summary>
/// The operation was succesful
/// </summary>
Success
}
public record DataOperationResults(DataOpResult Result) { }
public record DataOperationResults<T>(DataOpResult Result, T Value) { }
public record DataOperationResults<T1,T2>(DataOpResult Result, T1 FirstValue, T2 SecondValue) { }
public enum UserOperationResult
{
Success,
Failure,
}
public record UserOperationResults(UserOperationResult Result) { }
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using ManageAppleStore_DAO;
using ManageAppleStore_DTO;
namespace ManageAppleStore_BUS
{
public class FrmsBUS
{
public static BindingList<FrmsDTO> loadFrmsBUS()
{
return FrmsDAO.loadListDAO();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BPiaoBao.Common.Enums;
namespace BPiaoBao.AppServices.DataContracts.DomesticTicket
{
public class TicketSuppendRequest
{
public string TicketNumber
{
get;
set;
}
public string Office
{
get;
set;
}
public string BusinessmanCode
{
get;
set;
}
public TicketNumberOpType TicketNumberOpType
{
get;
set;
}
}
public class TicketSuppendResponse
{
public bool Result
{
get;
set;
}
private string _Remark = string.Empty;
public string Remark
{
get { return _Remark; }
set { _Remark = value; }
}
}
}
|
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
namespace XLua.CSObjectWrap
{
using Utils = XLua.Utils;
public class AudioTestWrap
{
public static void __Register(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
System.Type type = typeof(AudioTest);
Utils.BeginObjectRegister(type, L, translator, 0, 0, 7, 7);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "path", _g_get_path);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "files", _g_get_files);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "music", _g_get_music);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "ac", _g_get_ac);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "position", _g_get_position);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "samplerate", _g_get_samplerate);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "frequency", _g_get_frequency);
Utils.RegisterFunc(L, Utils.SETTER_IDX, "path", _s_set_path);
Utils.RegisterFunc(L, Utils.SETTER_IDX, "files", _s_set_files);
Utils.RegisterFunc(L, Utils.SETTER_IDX, "music", _s_set_music);
Utils.RegisterFunc(L, Utils.SETTER_IDX, "ac", _s_set_ac);
Utils.RegisterFunc(L, Utils.SETTER_IDX, "position", _s_set_position);
Utils.RegisterFunc(L, Utils.SETTER_IDX, "samplerate", _s_set_samplerate);
Utils.RegisterFunc(L, Utils.SETTER_IDX, "frequency", _s_set_frequency);
Utils.EndObjectRegister(type, L, translator, null, null,
null, null, null);
Utils.BeginClassRegister(type, L, __CreateInstance, 1, 0, 0);
Utils.EndClassRegister(type, L, translator);
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __CreateInstance(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
if(LuaAPI.lua_gettop(L) == 1)
{
AudioTest gen_ret = new AudioTest();
translator.Push(L, gen_ret);
return 1;
}
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return LuaAPI.luaL_error(L, "invalid arguments to AudioTest constructor!");
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_path(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
AudioTest gen_to_be_invoked = (AudioTest)translator.FastGetCSObj(L, 1);
LuaAPI.lua_pushstring(L, gen_to_be_invoked.path);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_files(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
AudioTest gen_to_be_invoked = (AudioTest)translator.FastGetCSObj(L, 1);
translator.Push(L, gen_to_be_invoked.files);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_music(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
AudioTest gen_to_be_invoked = (AudioTest)translator.FastGetCSObj(L, 1);
translator.Push(L, gen_to_be_invoked.music);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_ac(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
AudioTest gen_to_be_invoked = (AudioTest)translator.FastGetCSObj(L, 1);
translator.Push(L, gen_to_be_invoked.ac);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_position(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
AudioTest gen_to_be_invoked = (AudioTest)translator.FastGetCSObj(L, 1);
LuaAPI.xlua_pushinteger(L, gen_to_be_invoked.position);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_samplerate(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
AudioTest gen_to_be_invoked = (AudioTest)translator.FastGetCSObj(L, 1);
LuaAPI.xlua_pushinteger(L, gen_to_be_invoked.samplerate);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_frequency(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
AudioTest gen_to_be_invoked = (AudioTest)translator.FastGetCSObj(L, 1);
LuaAPI.lua_pushnumber(L, gen_to_be_invoked.frequency);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_path(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
AudioTest gen_to_be_invoked = (AudioTest)translator.FastGetCSObj(L, 1);
gen_to_be_invoked.path = LuaAPI.lua_tostring(L, 2);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_files(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
AudioTest gen_to_be_invoked = (AudioTest)translator.FastGetCSObj(L, 1);
gen_to_be_invoked.files = (string[])translator.GetObject(L, 2, typeof(string[]));
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_music(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
AudioTest gen_to_be_invoked = (AudioTest)translator.FastGetCSObj(L, 1);
gen_to_be_invoked.music = (UnityEngine.AudioSource)translator.GetObject(L, 2, typeof(UnityEngine.AudioSource));
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_ac(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
AudioTest gen_to_be_invoked = (AudioTest)translator.FastGetCSObj(L, 1);
gen_to_be_invoked.ac = (UnityEngine.AudioClip[])translator.GetObject(L, 2, typeof(UnityEngine.AudioClip[]));
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_position(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
AudioTest gen_to_be_invoked = (AudioTest)translator.FastGetCSObj(L, 1);
gen_to_be_invoked.position = LuaAPI.xlua_tointeger(L, 2);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_samplerate(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
AudioTest gen_to_be_invoked = (AudioTest)translator.FastGetCSObj(L, 1);
gen_to_be_invoked.samplerate = LuaAPI.xlua_tointeger(L, 2);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_frequency(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
AudioTest gen_to_be_invoked = (AudioTest)translator.FastGetCSObj(L, 1);
gen_to_be_invoked.frequency = (float)LuaAPI.lua_tonumber(L, 2);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 0;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Archivos
{
static class AdministradorArchivos
{
public static bool Escribir(string path,string texto)
{
StreamWriter sw;
sw = new StreamWriter(path, false);
try
{
sw.WriteLine(texto);
sw.Close();
return true;
}
catch (Exception e)
{
return false;
}
finally
{
sw.Close();
}
}
public static bool Leer(string path, out string texto)
{
StreamReader sw;
sw = new StreamReader(path, false);
try
{
texto=sw.ReadToEnd();
return true;
}
catch (Exception e)
{
texto ="";
return false;
}
finally
{
sw.Close();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Collections;
using System.Text;
namespace MyRESTService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IProductRESTService" in both code and config file together.
[ServiceContract]
public interface IMessageService
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "GetTeste/")]
string GetTeste();
[OperationContract(Name = "SetTeste")]
[WebInvoke(Method = "POST",
UriTemplate = "SetTeste/{data}")]
string SetTeste(String data);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Master.Contract;
using Master.BusinessFactory;
namespace LogiCon.Areas.Master.Controllers
{
[RoutePrefix("api/master/imocode")]
public class IMOCodeController : ApiController
{
[Route("list/{skip?},{take?}"), HttpGet]
public IHttpActionResult List(Int64? skip = null, Int64? take = null)
{
try
{
var list = new IMOCodeBO().GetPageView(skip.Value);
var totalItems = new IMOCodeBO().GetRecordCount();
return Ok(new {
imoCodeList = list,
totalItems = totalItems
});
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
[Route("{code}"), HttpGet]
public IHttpActionResult GetHoldStatus(string code)
{
try
{
var imoCode = new IMOCodeBO().GetIMOCode(new IMOCode { Code = code });
return Ok(imoCode);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
[Route("{code}"), HttpDelete]
public IHttpActionResult DeleteHoldStatus(string code)
{
try
{
var result = new IMOCodeBO().DeleteIMOCode(new IMOCode { Code = code });
return Ok(result ? UTILITY.SUCCESSMSG : UTILITY.FAILEDMSG);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
[Route("save"), HttpPost]
public IHttpActionResult SaveIMOCode(IMOCode imoCode)
{
try
{
imoCode.CreatedBy = UTILITY.DEFAULTUSER;
imoCode.ModifiedBy = UTILITY.DEFAULTUSER;
imoCode.CreatedOn = DateTime.Now;
//imoCode.ModifiedOn = DateTime.Now;
var result = new IMOCodeBO().SaveIMOCode(imoCode);
return Ok(result ? UTILITY.SUCCESSMSG : UTILITY.FAILEDMSG);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
}
}
|
using System.Threading;
using System.Threading.Tasks;
using LubyClocker.Application.BoundedContexts.Users.Commands.SignUp;
using LubyClocker.Application.BoundedContexts.Users.Services;
using LubyClocker.Application.BoundedContexts.Users.ViewModels;
using LubyClocker.CrossCuting.Shared;
using LubyClocker.CrossCuting.Shared.Exceptions;
using LubyClocker.Domain.BoundedContexts.Users;
using MediatR;
using Microsoft.AspNetCore.Identity;
namespace LubyClocker.Application.BoundedContexts.Users.Commands.Login
{
public class LogInCommandHandler : IRequestHandler<LogInCommand, AuthenticationResult>
{
private readonly IAuthService _authService;
private readonly SignInManager<User> _signInManager;
public LogInCommandHandler(SignInManager<User> signInManager, IAuthService authService)
{
_signInManager = signInManager;
_authService = authService;
}
public async Task<AuthenticationResult> Handle(LogInCommand request, CancellationToken cancellationToken)
{
var result = await _signInManager.PasswordSignInAsync(request.Email, request.Password, false, true);
if (!result.Succeeded)
{
throw new InvalidRequestException(MainResource.LoginError);
}
return await _authService.GenerateJwtToken(request.Email);
}
}
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ReferenceNotFoundException.cs" company="CGI">
// Copyright (c) CGI. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
namespace CGI.Reflex.Core.Importers
{
[Serializable]
internal class ReferenceNotFoundException : Exception
{
public ReferenceNotFoundException(string name, string value)
{
Name = name;
Value = value;
}
public string Name { get; private set; }
public string Value { get; private set; }
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Xml.Serialization;
namespace WeatherApp
{
public class ApplicationConfiguration
{
public string BaseAddressAPI { get; set; }
public string ConnectionString { get; set; }
public string Query { get; set; }
public string APIKey { get; set; }
private string Directory { get; set; }
public string AppsEmail { get; set; }
public string AppsMailPassword { get; set; }
/// <summary>
/// Initialize ApplicationConfiguration
/// </summary>
public void Initialize() {
this.BaseAddressAPI = "http://api.openweathermap.org/data/2.5/forecast?q=";
this.Query = "&mode=json&units=metric&APPID=";
this.APIKey = "d49c3a5910fdc77e3a554cd0cd11681d";
this.ConnectionString = "ConnectionString";
this.AppsEmail = "Email that app use for sending confirmation emails";
this.AppsMailPassword = "Password for that email service";
this.Save();
}
/// <summary>
/// Load parameters from xml file
/// </summary>
/// <param name="fileName"></param>
public void Load(string fileName = "ApplicationConfiguration.xml") {
this.Directory = System.AppDomain.CurrentDomain.BaseDirectory;
try
{
if (File.Exists(this.Directory + fileName))
{
using (var stream = File.OpenRead(this.Directory + fileName))
{
var serializer = new XmlSerializer(typeof(ApplicationConfiguration));
ApplicationConfiguration config = serializer.Deserialize(stream) as ApplicationConfiguration;
this.BaseAddressAPI = config.BaseAddressAPI;
this.Query = config.Query;
this.APIKey = config.APIKey;
this.ConnectionString = config.ConnectionString;
this.AppsMailPassword = config.AppsMailPassword;
this.AppsEmail = config.AppsEmail;
stream.Flush();
}
}
else
{
Initialize();
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Save initiaziled params to xml file
/// </summary>
/// <param name="filename"></param>
public void Save(string filename = "ApplicationConfiguration.xml") {
try
{
using (var writer = new StreamWriter( this.Directory + filename))
{
var serializer = new XmlSerializer(typeof(ApplicationConfiguration));
serializer.Serialize(writer, this);
writer.Flush();
}
}
catch (Exception ex)
{
throw ex;
}
}
}
} |
using System.Web.Mvc;
namespace CHSystem.Controllers
{
public class CalendarController : BaseController
{
public ActionResult Calendar()
{
return View();
}
public ActionResult CalendarGoogle()
{
return View();
}
}
} |
using Newtonsoft.Json;
using System;
/// <summary>
/// Scribble.rs ♯ data namespace
/// </summary>
namespace ScribblersSharp.Data
{
/// <summary>
/// A class that describes a base game message
/// </summary>
[JsonObject(MemberSerialization.OptIn)]
public class BaseGameMessageData : IBaseGameMessageData
{
/// <summary>
/// Game message type
/// </summary>
[JsonProperty("type")]
public string MessageType { get; set; }
/// <summary>
/// Is object in a valid state
/// </summary>
public virtual bool IsValid => MessageType != null;
/// <summary>
/// Constructs game message data for serializers
/// </summary>
public BaseGameMessageData()
{
// ...
}
/// <summary>
/// Constructs game message data
/// </summary>
/// <param name="messageType">Game message data</param>
public BaseGameMessageData(string messageType) => MessageType = messageType ?? throw new ArgumentNullException(nameof(messageType));
}
}
|
using Project_NotesDeFrais.Models;
using Project_NotesDeFrais.Models.Reposirery;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Project_NotesDeFrais.Controllers
{
public class CustomerController : Controller
{
[Authorize]
// GET: formulaire to add customer
public ActionResult Index()
{
return View("CostumerFormulaire");
}
// add customer to the database
[Authorize]
public ActionResult createCustomer(CustomersModel customerModel) {
if (!ModelState.IsValidField("Name") || !ModelState.IsValidField("Code")) {
return View("CostumerFormulaire", customerModel);
}
Customers customer = new Customers();
CustomerRepositery costRep = new CustomerRepositery();
customer.Customer_ID = Guid.NewGuid();
customer.Name= Convert.ToString(Request.Form["Name"]);
customer.Code= Convert.ToString(Request.Form["Code"]);
costRep.AddCostumers(customer);
return RedirectToAction("AllCustomer");
}
//Get : edit customer
[Authorize]
public ActionResult Edit(Guid id)
{
CustomerRepositery custRep = new CustomerRepositery();
CustomersModel custModel = new CustomersModel();
Customers customer = custRep.GetById(id);
custModel.Code = customer.Code;
custModel.Customer_ID = customer.Customer_ID;
custModel.Name = customer.Name;
return View("EditCustomer", custModel);
}
// update sutomer after edit
[Authorize]
public ActionResult updateCustomers(Guid id)
{
CustomerRepositery custRep = new CustomerRepositery();
Customers customer = custRep.GetById(id);
if (!ModelState.IsValidField("Name") || !ModelState.IsValidField("Code"))
{
CustomersModel custModel = new CustomersModel();
custModel.Code = customer.Code;
custModel.Customer_ID = customer.Customer_ID;
custModel.Name = customer.Name;
return View("EditCustomer", custModel);
}
String name = Convert.ToString(Request.Form["Name"]);
String code= Convert.ToString(Request.Form["Code"]);
custRep.updateCustomers(customer, name , code);
return RedirectToAction("AllCustomer");
}
//get all custmer in the database
[Authorize]
public ActionResult AllCustomer(int? pageIndex)
{
CustomerRepositery costRep = new CustomerRepositery();
var countElementPage = 10;
var costumers = costRep.allCustomers();
if (costumers.Count() == 0)
{
ViewData["erreurMessage"] = "aucun customer !";
ViewData["element"] = "Customer";
ViewData["create"] = "true";
return View("ErrorEmptyList");
}
List<CustomersModel> customersModel = new List<CustomersModel>();
foreach (var cust in costumers)
{
CustomersModel custModel = new CustomersModel();
custModel.Customer_ID = cust.Customer_ID;
custModel.Code = cust.Code;
custModel.Name = cust.Name;
customersModel.Add(custModel);
}
IQueryable<CustomersModel> listCust = customersModel.AsQueryable();
PaginatedList<CustomersModel> lst = new PaginatedList<CustomersModel>(listCust, pageIndex, countElementPage);
return View("AllCustomers" , lst);
}
// searche some customer in the database by name
[Authorize]
public ActionResult Searche(String query, int? pageIndex)
{
var countElementPage = 10;
CustomerRepositery costRep = new CustomerRepositery();
var customers = costRep.getSerachingCustomers(query);
List<CustomersModel> customersModel = new List<CustomersModel>();
foreach (var cust in customers)
{
CustomersModel custModel = new CustomersModel();
custModel.Customer_ID = cust.Customer_ID;
custModel.Code = cust.Code;
custModel.Name = cust.Name;
customersModel.Add(custModel);
}
IQueryable<CustomersModel> listCust = customersModel.AsQueryable();
PaginatedList<CustomersModel> lst = new PaginatedList<CustomersModel>(listCust, pageIndex, countElementPage);
return View("AllCustomers", lst);
}
//delet customer by id
[Authorize]
public ActionResult Delete(Guid id) {
ProjetController prjtControleur = new ProjetController();
CustomerRepositery cutoRepo = new CustomerRepositery();
Customers cutomer = cutoRepo.GetById(id);
ProjetRepositery prjtRepo = new ProjetRepositery();
List<Projects> projets = prjtRepo.GetByCustomerId(id).ToList();
foreach (var pro in projets) {
prjtControleur.Delete(pro.Project_ID);
}
prjtRepo.Save();
cutoRepo.Delete(cutomer);
cutoRepo.Save();
return RedirectToAction("AllCustomer");
}
//to show popup for cofirm or now delete customer
[Authorize]
public ActionResult confirmDelete(Guid id)
{
ViewData["confirmDelete"] = "/Customer/Delete?id=" + id;
return PartialView("_confirmDelet");
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine. UI;
public class GameManager : MonoBehaviour
{
public GameObject gameOverImage;
//게임오버 됐을 때 화면에 보여줄 이미지
public bool isGameOver;
//게임 오버 유무를 알려주는 변수
public float score;
//점수를 저장하는 변수
public Text ScoreBoard;
//점수를 화면에 표시되는 텍스트 박스
int digit_score=0;//실수로 저자오디는 점수값을
//정수로 별도로 저장해주기 위한 변수
public Image image1000;
public Image image100;
public Image image10;
public Image image1;
// Start is called before the first frame update
void Start()
{
isGameOver = false;
score = 0;
}
public void gameOverFunc()
{
//게임 오버 됐을 때 실행시킬 함수
Time.timeScale = 0;
//timeScale은 게임 상에서 흐르는 시간의 배율을 조절하는 함수
//1보다 크게 주면 게임 상의 시간이 빨리 흐르며
//1보다 작게 주면 게임 상의 시간이 느리게 흐른다.
//0은 멈춘다
gameOverImage.SetActive(true);
isGameOver = true;
}
// Update is called once per frame
void Update()
{
if (isGameOver == true)
{
if (Input.GetKeyDown(KeyCode.R))
{
Time.timeScale = 1;
//타임스케일은 게임 전체에 적용되기 때문에
//다르 씬 으로 전환하더라도 계속 유지가 된다
//따라서 게임이 재시작된다면
//타임스케일을 다시 원래대로 바꿔줘야한다
SceneManager.LoadScene("GameScene");
//TimeScale은 시간의 흐름으 ㄹ멈추는 것이지
//게임 전체를 멈추는 게 아니다
//시간과 관계없는 코드들
//(업데이트 문에서 deltatime이 곱해지지 않은 수치들)
//정상적으로 동작 한다
}
}
score += Time.deltaTime;
//플레이타임만큼 점수를 가산
ScoreBoard.text = "Score:" + (int)score;
//점수값을 int 형으로 바꿔서 점수판에 표시 시킨다
digit_score = (int)score;
int n1000 = digit_score / 1000;//1000의 자리 숫자
int n100 = (digit_score % 1000) / 100;
int n10 = (digit_score % 100) / 10;//10의 자리 숫자
int n1 = digit_score % 10;//1의 자리 숫자
string fileName = "number" + n1000;
image1000.sprite = Resources.Load<Sprite>("Numbers/" + fileName);
fileName = "number" + n100;
image100.sprite = Resources.Load<Sprite>("Numbers/" + fileName);
fileName = "number" + n10;
image10.sprite = Resources.Load<Sprite>("Numbers/" + fileName);
fileName = "number" + n1;
image1.sprite = Resources.Load<Sprite>("Numbers/" + fileName);
//파일명이 규칙성을 가지고 있다는 점을 이용하여 불러올 파일명을
//불러올 파일명을 직접 조합해서 불러오고 있다
image1000.SetNativeSize();
image100.SetNativeSize();
image10.SetNativeSize();
image1.SetNativeSize();
//이미지파일의 원본크기에 맞게 게임오브젝트의 크기를
//변경 시켜주는 함수(에디터의 버튼과 동일한 기능)
}
}
|
namespace JIoffe.PizzaBot.Model
{
public enum PizzaTopping
{
Pepperoni = 1, Mushroom, Sausage, Pineapple, Anchovy, Mozzarella, Bacon, Chicken
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Car.Super.Market.Test.Pages
{
public class SearchResultPage
{
}
}
|
using _2014118187_ENT.Entities;
using _2014118187_ENT.IRepositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _2014118187_PER.Repositories
{
public class CuentaRepository : Repository<Cuenta>, ICuentaRepository
{
public CuentaRepository(_2014118187DbContext context)
: base(context)
{
}
/* private readonly _2014118187DbContext _Context;
public CuentaRepository(_2014118265DbContext context)
{
_Context = context;
}
private CuentaRepository()
{
}*/
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace Calc
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
// apollak: Added action routing for multiple gets
config.Routes.MapHttpRoute(
name: "CalcApi",
routeTemplate: "api/Calc/{action}",
defaults: new { id = RouteParameter.Optional,
Controller = "Calc" }
// Changed to a fix route because otherwise Swagger picks up the GET action in the Values controller which creates
// duplicated operations
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
|
using ProManager.Entities.Base;
using ProManager.Entities.SystemAdmin;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ProManager.Entities.AgentAdmin
{
public class Layout : BaseTenantModel
{
public Layout()
{
RoomTypes = new HashSet<RoomTypes>();
}
ICollection<RoomTypes> RoomTypes { get; set; }
/// <summary>
/// Κάτοψη
/// </summary>
public string FloorPlanUri { get; set; }
/// <summary>
/// Εμβαδόν σε τμ
/// </summary>
public decimal SurfaceArea { get; set; }
/// <summary>
/// Όροφος
/// </summary>
public int Level { get; set; }
public Guid PropertyId { get; set; }
[ForeignKey("PropertyId")]
public virtual Property Property { get; set; }
}
}
|
using System;
using System.Linq;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
var tickets = Console.ReadLine()
.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(ticket => ticket.Trim())
.ToArray();
foreach (var ticket in tickets)
{
var leftSide = string.Join(string.Empty, ticket.Take(10));
var rightSide = string.Join(string.Empty, ticket.Skip(10).Take(10));
if (ticket.Length != 20)
{
Console.WriteLine($"invalid ticket");
}
else if (Regex.IsMatch(ticket, @"(\@{20}|\${20}|\^{20}|\#{20})"))
{
Console.WriteLine($"ticket \"{ticket}\" - 10$ Jackpot!");
}
else if (Regex.IsMatch(leftSide, @"(?<symbol>\^{6,10}|\#{6,10}|\@{6,10}|\${6,10})"))
{
var leftMatch = Regex.Match(leftSide, @"(?<symbol>\^{6,10}|\#{6,10}|\@{6,10}|\${6,10})");
var stringToMatch = leftMatch.Value;
var symbol = stringToMatch.First();
var rightSidePattern = $"\\{symbol}{{6,10}}";
if (Regex.IsMatch(rightSide, rightSidePattern))
{
var leftLen = stringToMatch.Length;
var rightLen = Regex.Match(rightSide, rightSidePattern).Value.Length;
var len = rightLen >= leftLen ? leftLen : rightLen;
Console.WriteLine($"ticket \"{ticket}\" - {len}{stringToMatch.First()}");
}
else
{
Console.WriteLine($"ticket \"{ticket}\" - no match");
}
}
else
{
Console.WriteLine($"ticket \"{ticket}\" - no match");
}
}
}
} |
using UnityEngine;
using UnityEngine.UI;
public class ScoreBoard : MonoBehaviour
{
public static int scoreValue = 0;
Text score;
private void Start()
{
score = GetComponent<Text>();
}
private void Update()
{
score.text = "SCORE: " + scoreValue;
}
}
/*
public int score;
public Text currentDisplay;
public Text highscoreDisplay;
void Start () {
score = 0;
if (currentDisplay != null) {
currentDisplay.text = score.ToString ();
}
if (highscoreDisplay != null)
highscoreDisplay.text = GetScore ().ToString ();
}
public void IncrementScoreBoard(int valUe){
score += valUe;
currentDisplay.text = score.ToString ();
}
public void SaveScore(){
//Check previous score
int oldScore = GetScore();
//if new score is higher than previous score
if(score > oldScore)
PlayerPrefs.SetInt ("HighScore", score);
}
public int GetScore(){
return PlayerPrefs.GetInt ("HighScore");
}
public void OnDisable(){
SaveScore ();
}
}
*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.