text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// config 的摘要说明
/// </summary>
public class config
{
public config()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
// 应用ID,您的APPID
public static string app_id = "2018071060547790";
// 支付宝网关
public static string gatewayUrl = "https://openapi.alipay.com/gateway.do";
// 商户私钥,您的原始格式RSA私钥
public static string private_key = @"MIIEowIBAAKCAQEAzVfroSuD1KMmitOOQ0R6tTsh/AMQuul2eooRRXwk+/aw50+w
MuOsjpM6+zBH468pI0HOq3LXMscGAmp9WYXYon7Naa6kvuw3zkmi9nLD220FAI8v
O5ol+pLMz/hFauohSL6gS0z1oeTpXQicKLLcMIwgUwtcGCq3i3v4dSbXaBi5thGV
MHDWNsn9mtC2pY6fe9MVJcLhCk5z9d2sl+ODWoWm/XbebopjENI6NiHnfWKeRXNe
Oa/MOymNzBvHZA8ZvMbekBoyb2/b2SpuTdW/9t9k5KL3Ryws04brSowov9x54ocS
9zCJ4qVmikE0yInl1OBUgrx19yPn1R6poL+B9QIDAQABAoIBADbM6fNfO5V53QVb
pDHLirvnBhDNeJ+JQrc9NZLHqM8dbOSuXaWXISwDmtACeI0I5/+ixlb3FPtWJgJr
DPzhPYlQMd2sYAcb32DMQhNnWWGr3JPjooVThCM1Hje6WDxKM4vIY9r0tPD5uFW9
wH8UDLNgEhhXhcJlVAqDkTEipoX+6C0019ZDGgNEePPAbgcLKB4RTvGTfgzN1247
3pOHuHeSf6Z3zvmiYSReTUOWVEdVMxsUWXCAPn2UIFihU4ab5HjCqUKe7SY7wWaT
7B0gAgkqBYWsNrJLuzaukZkw+LPWcdek1s0ZCrC8GQ739W9AHTyPerT8s4U3HoP7
QgioOVkCgYEA/yVG/WJIRMhQj1URmgQDmVyp9SAwsIeCc5OV95iROI2d9QKENeV6
CMAiGZ7sRGMtDg7ZMbDMFD88nkh8DneO4Xr+uya+LfgxmMQPV6GWItYWbJm1ry/1
NkJnLU4MZmGtyFFgThmG2/ELKrVxl8/tV55PgdxBBpn6dCNSKwrpbocCgYEAzgfz
TDQ5BBeGGmZHYot0BuTp/u3pUGLF2b3FbSsF4y5m9csuTCA+XCYDzCMdhHUkOg5j
TqBXr++1lG6cLY1IDoC7udTKtI93/tcVmq7DprZ2JOGadd4YWZCopuSLcOqIqCs1
uLBZYmQjvHHwMGfq2yKPqaF8KNCq0S3dYqFHTqMCgYBGtxo52CeXiL1rPHSobzxg
ISKp4cYc5zHsvpbuDMcTGY0R/ySNm5B7JGVPHJD3U1WFc/AWqZ2mbvBqHkTj7ZcY
P3KihFZpf0SfxpdJ/msSNKv6ZY/Jgk1AQJ9AG0Wsip4TyxoaC1EpXGFv8OIO5X4u
rp3yrA0Ju1uDHNcFPvz7uQKBgE092c8F/SI1l4cqNTUSxysWg0uZ8lC61yYs6Wlm
KczkRqF7zR2pMPfnIKFVwOk56Z0Ca+S8ZGOHYPIHDfJd91fIl5ix2FUdPIWEKYtW
Xe+QlHZ7RidOXp6lhzUaldR9eUJjAL7/DmO+2075AG2FaB1DtcyIyD2dDY1ivo8N
m+g1AoGBAMHLgR+MZAX9rqlniMsGD4T9YZ+jEMfKBYIZqZN3LCxE7B/kryI9eaoy
BmRGY7n/eVIib7VQfYgFj7wAKo3d45lE0lE6pTxScTHgwGqm/ObyKCAuECOeqtdc
R8FgbdLW10UyURJPBpWBxSZpCHOMaRs/Fld3JpSKjXkeP1vuLk4L";
// 支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
public static string alipay_public_key = @"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzVfroSuD1KMmitOOQ0R6
tTsh/AMQuul2eooRRXwk+/aw50+wMuOsjpM6+zBH468pI0HOq3LXMscGAmp9WYXY
on7Naa6kvuw3zkmi9nLD220FAI8vO5ol+pLMz/hFauohSL6gS0z1oeTpXQicKLLc
MIwgUwtcGCq3i3v4dSbXaBi5thGVMHDWNsn9mtC2pY6fe9MVJcLhCk5z9d2sl+OD
WoWm/XbebopjENI6NiHnfWKeRXNeOa/MOymNzBvHZA8ZvMbekBoyb2/b2SpuTdW/
9t9k5KL3Ryws04brSowov9x54ocS9zCJ4qVmikE0yInl1OBUgrx19yPn1R6poL+B
9QIDAQAB"; // 签名方式
public static string sign_type = "RSA2";
// 编码格式
public static string charset = "UTF-8";
}
public class PayData
{
public string TradeNo;
public DateTime CreateDate;
public float Amount;
public int UserId;
public int Status = 0;
public string PayType;
private static Dictionary<string, PayData> AliPayDatas = new Dictionary<string, PayData>();
public static void Add(string TradeNo, PayData TradeItem)
{
lock (AliPayDatas)
{
var key = string.Format("{0}_{1}", TradeItem.PayType, TradeNo);
AliPayDatas.Add(key, TradeItem);
}
}
public static PayData Find(string TradeNo,string payType)
{
lock (AliPayDatas)
{
var key = string.Format("{0}_{1}", payType, TradeNo);
if (AliPayDatas.ContainsKey(key))
return AliPayDatas[key];
return null;
}
}
// public static AliPayData TryRemove(string TradeNo)
// {
// lock (AliPayDatas)
// {
// if (AliPayDatas.ContainsKey(TradeNo))
// {
// AliPayData _AliPayData = AliPayDatas[TradeNo];
// AliPayDatas.Remove(TradeNo);
// return _AliPayData;
// }
// return null;
// }
// }
} |
using DAL.Models;
using DAL.Repositories.Interfaces;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DAL.Repositories
{
public class StudentRepository :
Repository<StudentRegistrationInfo>, IStudentRepository
{
public StudentRepository(DbContext context) : base(context)
{ }
public override void Add(StudentRegistrationInfo item)
{
_appContext.StudentRegistrationInfo.Add(item);
_appContext.SaveChanges();
}
public IEnumerable<StudentRegistrationInfo> GetStudentRegistrationInfos(string userID)
{
var studentRegistrationInfo = (from p in _appContext.StudentRegistrationInfo
join e in _appContext.MarketingStudentList
on p.Id equals e.StudentId
where e.UserId == userID
select p).ToList();
return studentRegistrationInfo;
}
public IEnumerable<int> GetUnregisteredStudentsID(int toAssignNumber)
{
IEnumerable<int> registeredStudent = (from ep in _appContext.StudentRegistrationInfo
join e in _appContext.MarketingStudentList on ep.Id equals e.StudentId into gj
from x in gj.DefaultIfEmpty()
where x.StudentId == null
select ep.Id
).Take(toAssignNumber);
return registeredStudent;
}
private ApplicationDbContext _appContext => (ApplicationDbContext)_context;
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Windows.Forms;
using DelftTools.Controls.Swf.Charting;
using DelftTools.Controls.Swf.Charting.Series;
using DelftTools.Functions;
using DelftTools.Functions.Binding;
using DelftTools.Functions.Filters;
using DelftTools.Functions.Generic;
using DelftTools.TestUtils;
using DelftTools.Utils;
using NUnit.Framework;
using Chart=DelftTools.Controls.Swf.Charting.Chart;
using Function=DelftTools.Functions.Function;
using HorizontalAxis=DelftTools.Controls.Swf.Charting.HorizontalAxis;
using IChart=DelftTools.Controls.Swf.Charting.IChart;
using VerticalAxis=DelftTools.Controls.Swf.Charting.VerticalAxis;
namespace DelftTools.Tests.Controls.Swf.Charting
{
[TestFixture]
public class ChartViewTest
{
#region Setup/Teardown
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
LogHelper.ConfigureLogging();
}
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
LogHelper.ResetLogging();
}
#endregion
private static DataTable InitTable()
{
var dataTable = new DataTable("ShowTableWithValues");
dataTable.Columns.Add("Y", typeof (double));
dataTable.Columns.Add("Z", typeof (double));
dataTable.Columns.Add("n", typeof (float));
var y = new[] { 0.0, 5.0, 6.0, 7.0, 3.0, 0.0};
var z = new[] { 0.0, 10.0, 15.0, 21.0, 15.0, 0.0};
var n = new []{0.001, 0.001, 0.01, 0.01, 0.01, 0.001};
for (int i = 0; i < 6; i++)
{
var row = dataTable.NewRow();
row["Y"] = y[i];
row["Z"] = z[i];
row["n"] = n[i];
dataTable.Rows.Add(row);
}
return dataTable;
}
[Test]
[Category(TestCategory.WindowsForms)]
public void HidingPointWithZeroY()
{
var view = new ChartView();
var series = ChartSeriesFactory.CreateLineSeries();
series.NoDataValues.Add(1.0);
series.Add(new double?[] { 0.0, 1.0, 3.0, 4.0, 5.0, 7.0, 8.0},
new double?[] { 0.0, 1.0, 0.5, 0.0, 5.0, 3.0, 4.0 });
view.Chart.Series.Add(series);
WindowsFormsTestHelper.ShowModal(view);
}
[Test]
[Category(TestCategory.WindowsForms)]
public void AreaSeriesView()
{
var chartView = new ChartView();
var series = ChartSeriesFactory.CreateLineSeries();
series.DataSource = InitTable();
series.XValuesDataMember = "Y";
series.YValuesDataMember = "Z";
chartView.Chart.Series.Add(series);
WindowsFormsTestHelper.ShowModal(chartView);
}
[Test]
[Category(TestCategory.WindowsForms)]
public void SeriesBandToolView()
{
var chartView = new ChartView();
var dataTable1 = new DataTable();
var dataTable2 = new DataTable();
dataTable1.Columns.AddRange(new []
{
new DataColumn("Y", typeof(double)),
new DataColumn("Z", typeof(double))
});
dataTable2.Columns.AddRange(new[]
{
new DataColumn("Y", typeof(double)),
new DataColumn("Z", typeof(double))
});
var ySeries1 = new[] {0.0, 2.0, 5.0, 10.0, 13.0, 15.0};
var zSeries1 = new[] {0.0, 0.0, -10.0, -10.0, 0.0, 0.0};
var ySeries2 = new[] {0.0, 5.0, 5.0, 10.0, 10.0, 15.0};
var zSeries2 = new[] {1.0, 1.0, -9.0, -9.0, 1.0, 1.0};
for (int i = 0; i < ySeries1.Length; i++)
{
var row = dataTable1.NewRow();
row["Y"] = ySeries1[i];
row["Z"] = zSeries1[i];
dataTable1.Rows.Add(row);
}
for (int i = 0; i < ySeries2.Length; i++)
{
var row = dataTable2.NewRow();
row["Y"] = ySeries2[i];
row["Z"] = zSeries2[i];
dataTable2.Rows.Add(row);
}
var series1 = ChartSeriesFactory.CreateLineSeries();
var series2 = ChartSeriesFactory.CreateLineSeries();
series1.DataSource = dataTable1;
series1.XValuesDataMember = "Y";
series1.YValuesDataMember = "Z";
series2.DataSource = dataTable2;
series2.XValuesDataMember = "Y";
series2.YValuesDataMember = "Z";
chartView.Chart.Series.AddRange(new []{series1, series2});
//tool
var tool = chartView.NewSeriesBandTool(series1, series2, Color.Yellow, HatchStyle.BackwardDiagonal,Color.Red);
chartView.Tools.Add(tool);
WindowsFormsTestHelper.ShowModal(chartView);
}
[Test]
[Category(TestCategory.WindowsForms)]
public void ChangeYMemberSeriesView()
{
var chartView = new ChartView();
var series = ChartSeriesFactory.CreateLineSeries();
series.DataSource = InitTable();
series.XValuesDataMember = "Y";
series.YValuesDataMember = "Z";
chartView.Chart.Series.Add(series);
series.YValuesDataMember = "n";
series.CheckDataSource();
WindowsFormsTestHelper.ShowModal(chartView);
}
[Test]
[Category(TestCategory.WindowsForms)]
public void ChangeYMemberSeriesViewWithFunctionAsDataSource()
{
var function = new Function();
var Y = new Variable<double>("Y");
var Z = new Variable<double>("Z");
var n = new Variable<double>("n");
function.Arguments.Add(Y);
function.Components.Add(Z);
function.Components.Add(n);
Y.SetValues(new[] { 0.0, 3.0 ,5.0, 6.0, 7.0});
Z.SetValues(new[] { 0.0, 10.0, 15.0, 21.0, 15.0 });
n.SetValues(new[] { 0.001, 0.001, 0.01, 0.01, 0.01 });
var chartView = new ChartView();
IChartSeries series = ChartSeriesFactory.CreateLineSeries();
series.XValuesDataMember = Y.DisplayName;
series.YValuesDataMember = Z.DisplayName;
series.DataSource = new FunctionBindingList(function) { SynchronizeInvoke = chartView};
chartView.Chart.Series.Add(series);
WindowsFormsTestHelper.ShowModal(chartView);
}
private static IChart CreateMultipleSeriesChart()
{
IChart chart = new Chart();
var dataTable = new DataTable("sinandcosinus");
dataTable.Columns.Add("X", typeof(double));
dataTable.Columns.Add("sin", typeof(double));
dataTable.Columns.Add("cos", typeof(double));
const double pi2 = Math.PI * 2;
for (int i = 0; i < 100; i++)
{
double angle = i * (pi2 / 100);
DataRow row = dataTable.NewRow();
row["X"] = angle;
row["sin"] = Math.Sin(angle);
row["cos"] = Math.Cos(angle);
dataTable.Rows.Add(row);
}
ILineChartSeries sin = ChartSeriesFactory.CreateLineSeries();
sin.Title = "sinus";
sin.DataSource = dataTable;
sin.XValuesDataMember = "X";
sin.YValuesDataMember = "sin";
chart.Series.Add(sin);
sin.BrushColor = Color.Red;
sin.PointerVisible = false;
ILineChartSeries cos = ChartSeriesFactory.CreateLineSeries();
cos.Title = "cosinus";
cos.DataSource = dataTable;
cos.XValuesDataMember = "X";
cos.YValuesDataMember = "cos";
chart.Series.Add(cos);
cos.BrushColor = Color.Blue;
cos.PointerVisible = false;
chart.Legend.Visible = true;
return chart;
}
[Test]
[Category(TestCategory.WindowsForms)]
public void MultipleSeriesView()
{
WindowsFormsTestHelper.ShowModal(new ChartView
{
Chart = CreateMultipleSeriesChart()
});
}
[Test]
[Category(TestCategory.WindowsForms)]
public void ShowDisabledChartView()
{
WindowsFormsTestHelper.ShowModal(new ChartView
{
Chart = CreateMultipleSeriesChart(),
Enabled = false
});
}
[Test]
[Category(TestCategory.WindowsForms)]
public void MultipleSeriesExtraAxesView()
{
var chart = CreateMultipleSeriesChart();
var chartSeries = chart.Series[0];
chartSeries.HorizAxis = HorizontalAxis.Top;
chartSeries.VertAxis = VerticalAxis.Right;
WindowsFormsTestHelper.ShowModal(new ChartView { Chart = chart });
}
[Test]
[Category(TestCategory.WindowsForms)]
public void MultipleSeriesChartViaImage()
{
WindowsFormsTestHelper.ShowModal(new PictureBox
{
Image = CreateMultipleSeriesChart().Image(300, 300)
});
}
[Test]
[Category(TestCategory.Performance)]
public void RefreshShouldBeFastWhenFunctionDataSourceHasManyChanges()
{
var random = new Random();
IFunction function = new Function
{
Arguments = { new Variable<int>("x") },
Components = { new Variable<int>("f") }
};
int count = 1000;
var componentvalues = Enumerable.Range(1, count).Select(i => random.Next(100)).ToArray();
var argumentvalues = Enumerable.Range(1, count).ToArray();
var chartView = new ChartView();
var lineSeries = ChartSeriesFactory.CreateLineSeries();
var functionBindingList = new FunctionBindingList(function) { SynchronizeInvoke = chartView};
lineSeries.DataSource = functionBindingList;
//don't update on every change...
lineSeries.UpdateASynchronously = true;
lineSeries.XValuesDataMember = function.Arguments[0].DisplayName;
lineSeries.YValuesDataMember = function.Components[0].DisplayName;
chartView.Chart.Series.Add(lineSeries);
lineSeries.PointerVisible = false;
// call one time to make sure that internal HACK TypeUtils.CallGeneric is done, otherwise timing varies a lot
function.SetValues(componentvalues, new VariableValueFilter<int>(function.Arguments[0], argumentvalues));
function.Arguments[0].Clear();
// now do the same when table view is shown
Action<Form> onShown = delegate
{
//the slowdown of chart is absolute minimal
TestHelper.AssertIsFasterThan(50, ()=>
function.SetValues(componentvalues, new VariableValueFilter<int>(function.Arguments[0], argumentvalues)));
};
WindowsFormsTestHelper.ShowModal(chartView, onShown);
}
[Test]
[Category(TestCategory.WindowsForms)]
public void ApplyCustomDateTimeFormatSeconds()
{
var random = new Random();
var chartView = new ChartView();
var startTime = DateTime.Now;
var times = Enumerable.Range(1, 1000).Select(i => startTime.AddSeconds(i)).ToArray();
var y = Enumerable.Range(1000, 1000).Select(i => Convert.ToDouble(random.Next(100))).ToArray();
var pointList = new List<Tuple<DateTime, double>>();
var lineSeries = ChartSeriesFactory.CreateLineSeries();
var chart = chartView.Chart;
chart.Series.Add(lineSeries);
for (int i = 0; i < 1000; i++)
{
pointList.Add(new Tuple<DateTime, double>(times[i], y[i]));
}
lineSeries.DataSource = pointList;
lineSeries.XValuesDataMember = "First";
lineSeries.YValuesDataMember = "Second";
lineSeries.CheckDataSource();
WindowsFormsTestHelper.ShowModal(chartView);
}
[Test]
[Category(TestCategory.WindowsForms)]
public void ApplyCustomDateTimeFormatYears()
{
var random = new Random();
var chartView = new ChartView();
var startTime = DateTime.Now;
var times = Enumerable.Range(1, 1000).Select(startTime.AddYears).ToArray();
var y = Enumerable.Range(1000, 1000).Select(i => Convert.ToDouble(random.Next(100))).ToArray();
var pointList = new List<Utils.Tuple<DateTime, double>>();
var lineSeries = ChartSeriesFactory.CreateLineSeries();
var chart = chartView.Chart;
chart.Series.Add(lineSeries);
chartView.DateTimeLabelFormatProvider = new QuarterNavigatableLabelFormatProvider();
for (int i = 0; i < 1000; i++)
{
pointList.Add(new Tuple<DateTime, double>(times[i], y[i]));
}
lineSeries.DataSource = pointList;
lineSeries.XValuesDataMember = "First";
lineSeries.YValuesDataMember = "Second";
lineSeries.CheckDataSource();
WindowsFormsTestHelper.ShowModal(chartView);
}
}
} |
namespace Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class SaleEnqquiry : DbMigration
{
public override void Up()
{
DropForeignKey("Web.MaterialPlanCancelForSaleOrders", "MaterialPlanForSaleOrderLineId", "Web.MaterialPlanForSaleOrderLines");
DropIndex("Web.MaterialPlanCancelForSaleOrders", new[] { "MaterialPlanForSaleOrderLineId" });
DropIndex("Web.MaterialPlanSettings", new[] { "DocTypePurchaseIndentId" });
DropIndex("Web.MaterialPlanSettings", new[] { "DocTypeProductionOrderId" });
CreateTable(
"Web.SaleEnquiryHeaders",
c => new
{
SaleEnquiryHeaderId = c.Int(nullable: false, identity: true),
DocTypeId = c.Int(nullable: false),
DocDate = c.DateTime(nullable: false),
DocNo = c.String(maxLength: 20),
DivisionId = c.Int(nullable: false),
SiteId = c.Int(nullable: false),
BuyerEnquiryNo = c.String(maxLength: 20),
DueDate = c.DateTime(nullable: false),
ActualDueDate = c.DateTime(nullable: false),
SaleToBuyerId = c.Int(nullable: false),
BillToBuyerId = c.Int(nullable: false),
CurrencyId = c.Int(nullable: false),
Priority = c.Int(nullable: false),
ShipMethodId = c.Int(nullable: false),
ShipAddress = c.String(maxLength: 250),
DeliveryTermsId = c.Int(nullable: false),
TermsAndConditions = c.String(),
CreditDays = c.Int(nullable: false),
LedgerHeaderId = c.Int(),
StockHeaderId = c.Int(),
Status = c.Int(nullable: false),
UnitConversionForId = c.Byte(nullable: false),
Advance = c.Decimal(precision: 18, scale: 4),
Remark = c.String(),
LockReason = c.String(),
ReviewCount = c.Int(),
ReviewBy = c.String(),
CreatedBy = c.String(),
CreatedDate = c.DateTime(nullable: false),
ModifiedBy = c.String(),
ModifiedDate = c.DateTime(nullable: false),
OMSId = c.String(maxLength: 50),
})
.PrimaryKey(t => t.SaleEnquiryHeaderId)
.ForeignKey("Web.Buyers", t => t.BillToBuyerId)
.ForeignKey("Web.Currencies", t => t.CurrencyId)
.ForeignKey("Web.DeliveryTerms", t => t.DeliveryTermsId)
.ForeignKey("Web.Divisions", t => t.DivisionId)
.ForeignKey("Web.DocumentTypes", t => t.DocTypeId)
.ForeignKey("Web.LedgerHeaders", t => t.LedgerHeaderId)
.ForeignKey("Web.People", t => t.SaleToBuyerId)
.ForeignKey("Web.ShipMethods", t => t.ShipMethodId)
.ForeignKey("Web.Sites", t => t.SiteId)
.ForeignKey("Web.StockHeaders", t => t.StockHeaderId)
.ForeignKey("Web.UnitConversionFors", t => t.UnitConversionForId)
.Index(t => t.DocTypeId)
.Index(t => t.DivisionId)
.Index(t => t.SiteId)
.Index(t => t.SaleToBuyerId)
.Index(t => t.BillToBuyerId)
.Index(t => t.CurrencyId)
.Index(t => t.ShipMethodId)
.Index(t => t.DeliveryTermsId)
.Index(t => t.LedgerHeaderId)
.Index(t => t.StockHeaderId)
.Index(t => t.UnitConversionForId);
CreateTable(
"Web.SaleEnquiryLines",
c => new
{
SaleEnquiryLineId = c.Int(nullable: false, identity: true),
SaleEnquiryHeaderId = c.Int(nullable: false),
ProductId = c.Int(nullable: false),
Dimension1Id = c.Int(),
Dimension2Id = c.Int(),
Specification = c.String(maxLength: 50),
Qty = c.Decimal(nullable: false, precision: 18, scale: 4),
DueDate = c.DateTime(),
DealUnitId = c.String(maxLength: 3),
DealQty = c.Decimal(nullable: false, precision: 18, scale: 4),
UnitConversionMultiplier = c.Decimal(precision: 18, scale: 4),
Rate = c.Decimal(nullable: false, precision: 18, scale: 4),
Amount = c.Decimal(nullable: false, precision: 18, scale: 4),
DiscountPer = c.Decimal(precision: 18, scale: 4),
ReferenceDocTypeId = c.Int(),
ReferenceDocLineId = c.Int(),
Remark = c.String(),
LockReason = c.String(),
CreatedBy = c.String(),
ModifiedBy = c.String(),
CreatedDate = c.DateTime(nullable: false),
ModifiedDate = c.DateTime(nullable: false),
OMSId = c.String(maxLength: 50),
})
.PrimaryKey(t => t.SaleEnquiryLineId)
.ForeignKey("Web.Units", t => t.DealUnitId)
.ForeignKey("Web.Dimension1", t => t.Dimension1Id)
.ForeignKey("Web.Dimension2", t => t.Dimension2Id)
.ForeignKey("Web.Products", t => t.ProductId)
.ForeignKey("Web.DocumentTypes", t => t.ReferenceDocTypeId)
.ForeignKey("Web.SaleEnquiryHeaders", t => t.SaleEnquiryHeaderId)
.Index(t => new { t.SaleEnquiryHeaderId, t.ProductId, t.DueDate }, unique: true, name: "IX_SaleEnquiryLine_SaleOrdeHeaderProductDueDate")
.Index(t => t.Dimension1Id)
.Index(t => t.Dimension2Id)
.Index(t => t.DealUnitId)
.Index(t => t.ReferenceDocTypeId);
CreateTable(
"Web.SaleEnquiryLineExtendeds",
c => new
{
SaleEnquiryLineId = c.Int(nullable: false),
ProductGroup = c.String(),
Size = c.String(),
ProductQuality = c.String(),
Colour = c.String(),
})
.PrimaryKey(t => t.SaleEnquiryLineId)
.ForeignKey("Web.JobOrderHeaders", t => t.SaleEnquiryLineId)
.Index(t => t.SaleEnquiryLineId);
CreateTable(
"Web.ViewMaterialPlanForProdOrderBalance",
c => new
{
MaterialPlanForProdOrderId = c.Int(nullable: false, identity: true),
MaterialPlanHeaderId = c.Int(nullable: false),
ProdOrderLineId = c.Int(nullable: false),
BalanceQty = c.Decimal(nullable: false, precision: 18, scale: 4),
})
.PrimaryKey(t => t.MaterialPlanForProdOrderId);
CreateTable(
"Web.ViewMaterialPlanForProdOrderLineBalance",
c => new
{
MaterialPlanForProdOrderLineId = c.Int(nullable: false, identity: true),
MaterialPlanForProdOrderId = c.Int(nullable: false),
ProductId = c.Int(nullable: false),
Dimension1Id = c.Int(),
Dimension2Id = c.Int(),
BalanceQty = c.Decimal(nullable: false, precision: 18, scale: 4),
ProcessId = c.Int(),
MaterialPlanLineId = c.Int(),
})
.PrimaryKey(t => t.MaterialPlanForProdOrderLineId);
CreateTable(
"Web.ViewMaterialPlanForSaleOrderBalance",
c => new
{
MaterialPlanForSaleOrderId = c.Int(nullable: false, identity: true),
MaterialPlanHeaderId = c.Int(nullable: false),
SaleOrderLineId = c.Int(nullable: false),
BalanceQty = c.Decimal(nullable: false, precision: 18, scale: 4),
MaterialPlanLineId = c.Int(),
})
.PrimaryKey(t => t.MaterialPlanForSaleOrderId);
CreateTable(
"Web.ViewSaleEnquiryBalance",
c => new
{
SaleEnquiryLineId = c.Int(nullable: false, identity: true),
BalanceQty = c.Decimal(nullable: false, precision: 18, scale: 4),
Rate = c.Decimal(nullable: false, precision: 18, scale: 4),
BalanceAmount = c.Decimal(nullable: false, precision: 18, scale: 4),
SaleEnquiryHeaderId = c.Int(nullable: false),
Dimension1Id = c.Int(),
Dimension2Id = c.Int(),
SiteId = c.Int(nullable: false),
DivisionId = c.Int(nullable: false),
SaleEnquiryNo = c.String(),
ProductId = c.Int(nullable: false),
BuyerId = c.Int(nullable: false),
OrderDate = c.DateTime(nullable: false),
})
.PrimaryKey(t => t.SaleEnquiryLineId)
.ForeignKey("Web.Dimension1", t => t.Dimension1Id)
.ForeignKey("Web.Dimension2", t => t.Dimension2Id)
.ForeignKey("Web.Products", t => t.ProductId)
.Index(t => t.Dimension1Id)
.Index(t => t.Dimension2Id)
.Index(t => t.ProductId);
AddColumn("Web.PackingLines", "SaleEnquiryLine_SaleEnquiryLineId", c => c.Int());
AddColumn("Web.Stocks", "StockStatus", c => c.String(maxLength: 20));
AddColumn("Web.SaleOrderHeaders", "StockHeaderId", c => c.Int());
AddColumn("Web.JobReceiveQAHeaders", "StockHeaderId", c => c.Int());
AddColumn("Web.JobReceiveQASettings", "isPostedInStock", c => c.Boolean());
AddColumn("Web.MaterialPlanCancelForSaleOrders", "MaterialPlanForSaleOrderId", c => c.Int(nullable: false));
AlterColumn("Web.ProductGroups", "Sr", c => c.Decimal(precision: 18, scale: 4));
AlterColumn("Web.MaterialPlanSettings", "DocTypePurchaseIndentId", c => c.Int());
AlterColumn("Web.MaterialPlanSettings", "DocTypeProductionOrderId", c => c.Int());
CreateIndex("Web.PackingLines", "SaleEnquiryLine_SaleEnquiryLineId");
CreateIndex("Web.SaleOrderHeaders", "StockHeaderId");
CreateIndex("Web.JobReceiveQAHeaders", "StockHeaderId");
CreateIndex("Web.MaterialPlanCancelForSaleOrders", "MaterialPlanForSaleOrderId");
CreateIndex("Web.MaterialPlanSettings", "DocTypePurchaseIndentId");
CreateIndex("Web.MaterialPlanSettings", "DocTypeProductionOrderId");
AddForeignKey("Web.SaleOrderHeaders", "StockHeaderId", "Web.StockHeaders", "StockHeaderId");
AddForeignKey("Web.JobReceiveQAHeaders", "StockHeaderId", "Web.StockHeaders", "StockHeaderId");
AddForeignKey("Web.MaterialPlanCancelForSaleOrders", "MaterialPlanForSaleOrderId", "Web.MaterialPlanForSaleOrders", "MaterialPlanForSaleOrderId");
AddForeignKey("Web.PackingLines", "SaleEnquiryLine_SaleEnquiryLineId", "Web.SaleEnquiryLines", "SaleEnquiryLineId");
DropColumn("Web.MaterialPlanCancelForSaleOrders", "MaterialPlanForSaleOrderLineId");
DropColumn("Web.ViewMaterialPlanBalance", "DocTypeName");
}
public override void Down()
{
AddColumn("Web.ViewMaterialPlanBalance", "DocTypeName", c => c.String());
AddColumn("Web.MaterialPlanCancelForSaleOrders", "MaterialPlanForSaleOrderLineId", c => c.Int(nullable: false));
DropForeignKey("Web.ViewSaleEnquiryBalance", "ProductId", "Web.Products");
DropForeignKey("Web.ViewSaleEnquiryBalance", "Dimension2Id", "Web.Dimension2");
DropForeignKey("Web.ViewSaleEnquiryBalance", "Dimension1Id", "Web.Dimension1");
DropForeignKey("Web.SaleEnquiryLineExtendeds", "SaleEnquiryLineId", "Web.JobOrderHeaders");
DropForeignKey("Web.SaleEnquiryHeaders", "UnitConversionForId", "Web.UnitConversionFors");
DropForeignKey("Web.SaleEnquiryHeaders", "StockHeaderId", "Web.StockHeaders");
DropForeignKey("Web.SaleEnquiryHeaders", "SiteId", "Web.Sites");
DropForeignKey("Web.SaleEnquiryHeaders", "ShipMethodId", "Web.ShipMethods");
DropForeignKey("Web.SaleEnquiryHeaders", "SaleToBuyerId", "Web.People");
DropForeignKey("Web.SaleEnquiryLines", "SaleEnquiryHeaderId", "Web.SaleEnquiryHeaders");
DropForeignKey("Web.SaleEnquiryLines", "ReferenceDocTypeId", "Web.DocumentTypes");
DropForeignKey("Web.SaleEnquiryLines", "ProductId", "Web.Products");
DropForeignKey("Web.PackingLines", "SaleEnquiryLine_SaleEnquiryLineId", "Web.SaleEnquiryLines");
DropForeignKey("Web.SaleEnquiryLines", "Dimension2Id", "Web.Dimension2");
DropForeignKey("Web.SaleEnquiryLines", "Dimension1Id", "Web.Dimension1");
DropForeignKey("Web.SaleEnquiryLines", "DealUnitId", "Web.Units");
DropForeignKey("Web.SaleEnquiryHeaders", "LedgerHeaderId", "Web.LedgerHeaders");
DropForeignKey("Web.SaleEnquiryHeaders", "DocTypeId", "Web.DocumentTypes");
DropForeignKey("Web.SaleEnquiryHeaders", "DivisionId", "Web.Divisions");
DropForeignKey("Web.SaleEnquiryHeaders", "DeliveryTermsId", "Web.DeliveryTerms");
DropForeignKey("Web.SaleEnquiryHeaders", "CurrencyId", "Web.Currencies");
DropForeignKey("Web.SaleEnquiryHeaders", "BillToBuyerId", "Web.Buyers");
DropForeignKey("Web.MaterialPlanCancelForSaleOrders", "MaterialPlanForSaleOrderId", "Web.MaterialPlanForSaleOrders");
DropForeignKey("Web.JobReceiveQAHeaders", "StockHeaderId", "Web.StockHeaders");
DropForeignKey("Web.SaleOrderHeaders", "StockHeaderId", "Web.StockHeaders");
DropIndex("Web.ViewSaleEnquiryBalance", new[] { "ProductId" });
DropIndex("Web.ViewSaleEnquiryBalance", new[] { "Dimension2Id" });
DropIndex("Web.ViewSaleEnquiryBalance", new[] { "Dimension1Id" });
DropIndex("Web.SaleEnquiryLineExtendeds", new[] { "SaleEnquiryLineId" });
DropIndex("Web.SaleEnquiryLines", new[] { "ReferenceDocTypeId" });
DropIndex("Web.SaleEnquiryLines", new[] { "DealUnitId" });
DropIndex("Web.SaleEnquiryLines", new[] { "Dimension2Id" });
DropIndex("Web.SaleEnquiryLines", new[] { "Dimension1Id" });
DropIndex("Web.SaleEnquiryLines", "IX_SaleEnquiryLine_SaleOrdeHeaderProductDueDate");
DropIndex("Web.SaleEnquiryHeaders", new[] { "UnitConversionForId" });
DropIndex("Web.SaleEnquiryHeaders", new[] { "StockHeaderId" });
DropIndex("Web.SaleEnquiryHeaders", new[] { "LedgerHeaderId" });
DropIndex("Web.SaleEnquiryHeaders", new[] { "DeliveryTermsId" });
DropIndex("Web.SaleEnquiryHeaders", new[] { "ShipMethodId" });
DropIndex("Web.SaleEnquiryHeaders", new[] { "CurrencyId" });
DropIndex("Web.SaleEnquiryHeaders", new[] { "BillToBuyerId" });
DropIndex("Web.SaleEnquiryHeaders", new[] { "SaleToBuyerId" });
DropIndex("Web.SaleEnquiryHeaders", new[] { "SiteId" });
DropIndex("Web.SaleEnquiryHeaders", new[] { "DivisionId" });
DropIndex("Web.SaleEnquiryHeaders", new[] { "DocTypeId" });
DropIndex("Web.MaterialPlanSettings", new[] { "DocTypeProductionOrderId" });
DropIndex("Web.MaterialPlanSettings", new[] { "DocTypePurchaseIndentId" });
DropIndex("Web.MaterialPlanCancelForSaleOrders", new[] { "MaterialPlanForSaleOrderId" });
DropIndex("Web.JobReceiveQAHeaders", new[] { "StockHeaderId" });
DropIndex("Web.SaleOrderHeaders", new[] { "StockHeaderId" });
DropIndex("Web.PackingLines", new[] { "SaleEnquiryLine_SaleEnquiryLineId" });
AlterColumn("Web.MaterialPlanSettings", "DocTypeProductionOrderId", c => c.Int(nullable: false));
AlterColumn("Web.MaterialPlanSettings", "DocTypePurchaseIndentId", c => c.Int(nullable: false));
AlterColumn("Web.ProductGroups", "Sr", c => c.Decimal(nullable: false, precision: 18, scale: 4));
DropColumn("Web.MaterialPlanCancelForSaleOrders", "MaterialPlanForSaleOrderId");
DropColumn("Web.JobReceiveQASettings", "isPostedInStock");
DropColumn("Web.JobReceiveQAHeaders", "StockHeaderId");
DropColumn("Web.SaleOrderHeaders", "StockHeaderId");
DropColumn("Web.Stocks", "StockStatus");
DropColumn("Web.PackingLines", "SaleEnquiryLine_SaleEnquiryLineId");
DropTable("Web.ViewSaleEnquiryBalance");
DropTable("Web.ViewMaterialPlanForSaleOrderBalance");
DropTable("Web.ViewMaterialPlanForProdOrderLineBalance");
DropTable("Web.ViewMaterialPlanForProdOrderBalance");
DropTable("Web.SaleEnquiryLineExtendeds");
DropTable("Web.SaleEnquiryLines");
DropTable("Web.SaleEnquiryHeaders");
CreateIndex("Web.MaterialPlanSettings", "DocTypeProductionOrderId");
CreateIndex("Web.MaterialPlanSettings", "DocTypePurchaseIndentId");
CreateIndex("Web.MaterialPlanCancelForSaleOrders", "MaterialPlanForSaleOrderLineId");
AddForeignKey("Web.MaterialPlanCancelForSaleOrders", "MaterialPlanForSaleOrderLineId", "Web.MaterialPlanForSaleOrderLines", "MaterialPlanForSaleOrderLineId");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ApiWrapper
{
public static class Keyboard
{
public static void TypeMe(this string message)
{
TypeThisString(message);
}
public static void TypeThisString(string strMessage)
{
char[] cs = strMessage.ToCharArray();
foreach (char c in cs)
{
bool up = false;
char t = MappingKeyCode(c, ref up);
if (up)
Api.keybd_event(16, 0, Api.KeyEventFlag.KEYEVENTF_KEYDOWN, 0);
Api.keybd_event(t, 0, Api.KeyEventFlag.KEYEVENTF_KEYDOWN, 0);
Api.keybd_event(t, 0, Api.KeyEventFlag.KEYEVENTF_KEYUP, 0);
if (up)
Api.keybd_event(16, 0, Api.KeyEventFlag.KEYEVENTF_KEYUP, 0);
}
}
private static char MappingKeyCode(char o, ref bool isUpper)
{
//Capital letters
if (o <= 90 && o >= 65)
{
isUpper = true;
return o;
}
if (o >= 48 && o <= 57)
return (char)(o + 48);
if (o >= 97 && o <= 122)
return (char)(o - 32);
if (o == '-')
{
return (char)109;
}
if (o == '@')
{
isUpper = true;
return (char)50;
}
if (o == '!')
{
isUpper = true;
return (char)49;
}
if (o == '#')
{
isUpper = true;
return (char)51;
}
if (o == '$')
{
isUpper = true;
return (char)52;
}
if (o == '%')
{
isUpper = true;
return (char)53;
}
if (o == '^')
{
isUpper = true;
return (char)54;
}
if (o == '_')
{
isUpper = true;
return (char) 189;
}
if (o == '"')
{
isUpper = true;
return (char) 222;
}
if (o == ':')
{
isUpper = true;
return (char)186;
}
if (o == '.')
{
return (char) 190;
}
if (o == ' ')
{
return (char) 32;
}
return (char)0;
}
public static void Tap(Keys key, Keys assicts = Keys.None)
{
if (assicts.HasFlag(Keys.Alt))
{
Api.keybd_event(18, 0, Api.KeyEventFlag.KEYEVENTF_KEYDOWN, 0);
}
if (assicts.HasFlag(Keys.Control))
{
Api.keybd_event(17, 0, Api.KeyEventFlag.KEYEVENTF_KEYDOWN, 0);
}
Api.keybd_event((int)key, 0, Api.KeyEventFlag.KEYEVENTF_KEYDOWN, 0);
Thread.Sleep(20);
Api.keybd_event((int)key, 0, Api.KeyEventFlag.KEYEVENTF_KEYUP, 0);
if (assicts.HasFlag(Keys.Alt))
{
Api.keybd_event(18, 0, Api.KeyEventFlag.KEYEVENTF_KEYUP, 0);
}
if (assicts.HasFlag(Keys.Control))
{
Api.keybd_event(17, 0, Api.KeyEventFlag.KEYEVENTF_KEYUP, 0);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace _042
{
class Program
{
private static bool IsTriangleNumber(int n)
{
var temp = Math.Floor(Math.Sqrt(n << 1));
return temp * (temp + 1) == (n << 1);
}
private static bool IsTriangleWord(string word)
{
return IsTriangleNumber(WordSum(word));
}
private static IEnumerable<string> GetWords(string filename)
{
string[] words;
using (var reader = new StreamReader(filename))
{
words = reader.ReadToEnd().Split(',');
}
return words.Select(x => x.Trim('"'));
}
private static int WordSum(string word)
{
int sum = 0;
foreach (var c in word)
{
sum += (c - 'A') + 1;
}
return sum;
}
static void Main(string[] args)
{
var stopwatch = new System.Diagnostics.Stopwatch();
#region General solution
stopwatch.Start();
int count = GetWords("words.txt").Count(IsTriangleWord);
stopwatch.Stop();
Console.WriteLine("{0} triange words. {1} ms", count, stopwatch.ElapsedMilliseconds);
#endregion
#region Using LINQ expressions
stopwatch.Restart();
int countLinq = (from s in File.OpenText("words.txt").ReadToEnd().Split(',')
select s.Trim('"')).Count(IsTriangleWord);
stopwatch.Stop();
Console.WriteLine("{0} triange words. {1} ms", countLinq, stopwatch.ElapsedMilliseconds);
#endregion
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class Cell : MonoBehaviour, IPointerClickHandler {
static GameManager GameManager { get; set; }
GameObject piece;
public GameObject Piece {
get { return piece; }
set {
/*
if (piece != null && value != null && piece != value) {
piece.GetComponent<Piece> ().Destroy ();
}
*/
piece = value;
if (value != null) {
piece.SetActive (true);
piece.GetComponent<Piece> ().Coordinate = Coordinates;
}
}
}
public Vector3 Coordinates { get; set; }
public bool IsEmpty {
get { return Piece == null; }
}
CellAppearanceController _cac;
void Awake () {
GameManager = GameObject.FindGameObjectWithTag ("GameController").GetComponent<GameManager> ();
_cac = GetComponent<CellAppearanceController> ();
}
public Cell() {
piece = null;
}
/*
public void OnMouseDown () {
if (IsEmpty) {
GameManager.CellClicked (Coordinates, null);
} else {
GameManager.CellClicked (Coordinates, Piece.GetComponent<Piece> ());
}
}
*/
#region IPointerClickHandler implementation
public void OnPointerClick (PointerEventData eventData)
{
var player = GameManager.ActivePlayer;
if (player != null && player.PlayerType == PlayerType.HUMAN) {
var hp = player as HumanPlayer;
if (IsEmpty) {
hp.CellClicked (Coordinates, null);
} else {
hp.CellClicked (Coordinates, Piece.GetComponent<Piece> ());
}
}
}
#endregion
public void HighlightSelect () {
_cac.State = CellState.SELECTED;
}
public void HighlightMove () {
_cac.State = CellState.MOVE;
}
public void HighlightCapture () {
_cac.State = CellState.CAPTURE;
}
public void HighlightClear () {
_cac.State = CellState.IDLE;
}
public void Destroy () {
if (piece != null) {
GameObject.Destroy (piece);
}
GameObject.Destroy (gameObject);
}
}
|
using System.Collections.Generic;
using Docller.Core.Models;
namespace Docller.Core.Services
{
public class TransmittalCreationInfo
{
public IssueSheet IssueSheetData { get; set; }
public TransmittalServiceStatus Status { get; set; }
public Transmittal Transmittal { get; set; }
}
} |
using Microsoft.AspNetCore.Mvc;
namespace AKCore.Controllers
{
public class ErrorController : Controller
{
public override NotFoundResult NotFound()
{
return new NotFoundResult();
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.SocialPlatforms.Impl;
using UnityEngine.UI;
namespace Sarah
{
public class PlayerController : MonoBehaviour
{
public static PlayerController instance;
// Outlets - sibling components (Transform, SpriteRenderer)
Rigidbody2D _rigidbody2D;
private SpriteRenderer sprite;
private Animator _animator;
public Transform[] itemSpawners;
public GameObject itemPrefab;
public Image healthBarImage;
public Text bottleScoreText;
// Configuration - settings (max health, speed)
public float speed;
public float maxHealth;
// State Tracking - current state of things (health, current weapon)
public bool itemAvailable;
private int status;
public float health;
public int bottleScore;
public bool isPaused;
// Methods
private void Awake()
{
instance = this;
}
void Start()
{
_rigidbody2D = GetComponent<Rigidbody2D>();
sprite = GetComponent<SpriteRenderer>();
_animator = GetComponent<Animator>();
SpawnItem();
itemAvailable = true;
status = 0;
health = maxHealth;
bottleScore = 0;
isPaused = false;
}
private void FixedUpdate()
{
if (isPaused)
{
return;
}
_animator.SetInteger("PrevStatus", status);
CheckVelocity();
_animator.SetInteger("Status", status);
}
void Update()
{
if (isPaused)
{
return;
}
// In future, add something to indicate loss
if (health <= 0)
{
Die();
}
// Move Player Left
if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))
{
//happens over time, so we need delta time to account for lag
_rigidbody2D.AddForce(Vector2.left * speed * Time.deltaTime, ForceMode2D.Impulse);
sprite.flipX = true;
}
// Move Player Right
if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D))
{
_rigidbody2D.AddForce(Vector2.right * speed * Time.deltaTime, ForceMode2D.Impulse);
sprite.flipX = false;
}
// Move Player Up
if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W))
{
_rigidbody2D.AddForce(Vector2.up * speed * Time.deltaTime, ForceMode2D.Impulse);
}
// Move Player Down
if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S))
{
_rigidbody2D.AddForce(Vector2.down * speed * Time.deltaTime, ForceMode2D.Impulse);
}
// Show menu
if (Input.GetKey(KeyCode.P))
{
MenuController.instance.Show();
}
if (!itemAvailable)
{
SpawnItem();
}
_animator.SetInteger("PrevStatus", status);
CheckVelocity();
_animator.SetInteger("Status", status);
}
private void SpawnItem()
{
Transform randomSpawner = itemSpawners[UnityEngine.Random.Range(0, itemSpawners.Length)];
// Spawn a new item
Instantiate(itemPrefab, randomSpawner.position, Quaternion.identity);
itemAvailable = true;
}
void CheckVelocity()
{
Vector2 velocity = _rigidbody2D.velocity;
float x = velocity.x;
float y = velocity.y;
if (velocity.sqrMagnitude > 0.1f)
{
if (y > 0 && y > Math.Abs(x))
{
status = 1;
}
else if (y < 0 && Math.Abs(y) > Math.Abs(x))
{
status = 3;
}
else
{
status = 2;
}
}
else
{
status = 0;
}
}
public void TakeDamage(float damageAmount)
{
health -= damageAmount;
UpdateHealthBar();
if (health <= 0)
{
Die();
}
}
public void RegenHealth(float amount)
{
health = Math.Min(health + amount, maxHealth);
UpdateHealthBar();
UpdateBottleScore();
}
private void UpdateHealthBar()
{
healthBarImage.fillAmount = health / maxHealth;
}
void UpdateBottleScore()
{
++bottleScore;
bottleScoreText.text = ": " + bottleScore;
}
void Die()
{
GameOverScript.instance.Show();
}
}
}
|
using Erlang.NET;
using Spring.Util;
namespace Spring.Erlang.Connection
{
/// <summary>
/// Encapsulate properties to create a OtpConnection
/// </summary>
/// <remarks></remarks>
/// <author>Mark Pollack</author>
/// <author>Joe Fitzgerald</author>
public class ConnectionParameters
{
/// <summary>
/// The otp self.
/// </summary>
private OtpSelf otpSelf;
/// <summary>
/// The otp peer.
/// </summary>
private OtpPeer otpPeer;
/// <summary>
/// Initializes a new instance of the <see cref="ConnectionParameters"/> class.
/// </summary>
/// <param name="otpSelf">The otp self.</param>
/// <param name="otpPeer">The otp peer.</param>
/// <remarks></remarks>
public ConnectionParameters(OtpSelf otpSelf, OtpPeer otpPeer)
{
AssertUtils.ArgumentNotNull(otpSelf, "OtpSelf must be non-null");
AssertUtils.ArgumentNotNull(otpPeer, "OtpPeer must be non-null");
this.otpSelf = otpSelf;
this.otpPeer = otpPeer;
}
/// <summary>
/// Gets the otp self.
/// </summary>
/// <returns>The otp self.</returns>
/// <remarks></remarks>
public OtpSelf GetOtpSelf()
{
return this.otpSelf;
}
/// <summary>
/// Gets the otp peer.
/// </summary>
/// <returns>The otp peer.</returns>
/// <remarks></remarks>
public OtpPeer GetOtpPeer()
{
return this.otpPeer;
}
}
}
|
using Plotter.Models;
using Plotter.Tweet.Processing;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Plotter.Tests.WinForms
{
public partial class RenderingTest : Form
{
public RenderingTest()
{
InitializeComponent();
Redraw();
}
private double _maxMilliseconds = 0;
private double _maxY = 0;
private void Redraw()
{
var maxMs = Math.Max(_maxMilliseconds, 500);
var startTime = DateTime.Now;
var midTime = DateTime.Now.AddMilliseconds(maxMs / 2);
var maxTime = DateTime.Now.AddMilliseconds(maxMs);
var maxY = (decimal)Math.Max(_maxY, 1);
var midY = (decimal)(maxY / 2);
var points = new Models.Point[]
{
new Models.Point(){ X = startTime, Y = 1 },
new Models.Point(){ X = midTime, Y = midY },
new Models.Point(){ X = maxTime, Y = maxY }
};
Rendering r = new Rendering(new Chart() { Title = "Test chart - adjust X and Y axes" }, points);
byte[] result = r.RenderPng();
MemoryStream ms = new MemoryStream(result);
ms.Write(result, 0, result.Length);
ms.Position = 0;
pictureBox1.Image = Image.FromStream(ms);
}
//Y Axis
private void trackBar1_Scroll(object sender, EventArgs e)
{
double sliderVal = (double)trackBar1.Value / 100.0; //0 to 1, linear
double exponentialVal = Math.Pow(sliderVal, 10); //0 to 1, rising exponentially
_maxY = exponentialVal * 1000000000; //0 to 1bn
Redraw();
label5.Text = "0 to " + _maxY;
}
//X Axis
private void trackBar2_Scroll(object sender, EventArgs e)
{
double sliderVal = (double)trackBar2.Value / 100.0; //0 to 1, linear
double exponentialVal = Math.Pow(sliderVal, 10); //0 to 1, rising exponentially
_maxMilliseconds = exponentialVal * 1577846298735; //0 to 50 years (in milliseconds)
Redraw();
label6.Text = TimeSpan.FromMilliseconds(_maxMilliseconds).ToString("g");
}
private void button1_Click(object sender, EventArgs e)
{
new IOTest().Show(this);
}
}
}
|
/***********************************************************************
* Module: NotificationController.cs
* Author: Sladjana Savkovic
* Purpose: Definition of the Class Controller.NotificationController
***********************************************************************/
using Service.NotificationSurveyAnddFeedback;
using System;
using System.Collections.Generic;
namespace Controller.NotificationSurveyAndFeedback
{
public class NotificationController
{
public NotificationService notificationService = new NotificationService();
public void SendNotification(Model.Users.Notification notification)
{
notificationService.SendNotification(notification);
}
public List<Model.Users.Notification> ViewNotificationByJmbg(string jmbg)
{
return notificationService.ViewNotificationByJmbg(jmbg);
}
public void DeleteNotification(int id)
{
notificationService.DeleteNotification(id);
}
public int getLastId()
{
return notificationService.getLastId();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XH.Domain.Shared;
using XH.Infrastructure.Domain.Models;
namespace XH.Domain.Catalogs
{
public class Region : FullAuditableEntity, IAggregateRoot
{
private string _administrativeId;
public virtual string AdministrativeId
{
get
{
return _administrativeId;
}
set
{
_administrativeId = value;
Id = value;
}
}
public virtual string Name { get; set; }
public virtual string ShortName { get; set; }
public virtual string ParentId { get; set; }
public virtual string ZipCode { get; set; }
public virtual string PinYin { get; set; }
public virtual string ShortPinYin { get; set; }
public virtual Coordinate Coordinate { get; set; }
public virtual RegionType RegionType { get; set; }
public virtual int Level { get; set; }
public virtual int DisplayOrder { get; set; }
}
}
|
using System;
namespace ProctorCreekGreenwayApp
{
/**
* Interface to retrieve the location of the SQLite Database for each OS
*/
public interface IDBFileHelper
{
string GetLocalFilePath(string filename);
}
}
|
using System;
using UsersLib.DbControllers;
using UsersLib.Entity;
using UsersLib.Service.Resolvers;
namespace UsersLib.Service.Finders
{
internal class SiteSecureDataFinder : ISiteSecureDataFinder
{
private readonly IDbSiteController _dbSiteController;
private readonly ISecureSiteDataResolver _secureSiteDataResolver;
public SiteSecureDataFinder(IDbSiteController dbSiteController, ISecureSiteDataResolver secureSiteDataResolver)
{
_dbSiteController = dbSiteController;
_secureSiteDataResolver = secureSiteDataResolver;
}
public SecureSiteData FindeSiteSecureData(string storageId)
{
if (String.IsNullOrEmpty(storageId))
{
return null;
}
Site foundSite = _dbSiteController.GetSite(storageId);
if (foundSite == null)
{
return null;
}
return _secureSiteDataResolver.ResolveSiteData(foundSite.SiteId);
}
}
} |
using System;
using System.Collections.Generic;
using FIMMonitoring.Domain.ViewModels.WCF;
using System.ServiceModel;
namespace FIMMonitoring.WebService
{
[ServiceContract]
public interface IFIMWebService
{
[OperationContract]
List<Guid> SendErrorPack(ErrorPack errors);
}
}
|
using System;
using System.Linq;
namespace DependencyKata.Tests
{
public static class Helper
{
public static bool AreAllSpecifiedJobsCompletedOnce(string results, string expected)
{
try
{
foreach (var result in results)
{
expected.Single(job => job.Equals(result));
}
}
catch (InvalidOperationException e)
{
return false;
}
return true;
}
}
}
|
using System;
using Properties.Core.Objects;
// ReSharper disable InconsistentNaming
namespace Properties.Infrastructure.Rightmove.Objects
{
public class RmrtdfPropertyAddress
{
private const int _address_field_max_length = 60;
private const int _postcode_1_max_length = 4;
private const int _postcode_2_max_length = 3;
private const int _display_address_max_length = 120;
private readonly string _house_name_number;
public string house_name_number => _house_name_number.Substring(0, Math.Min(_address_field_max_length, _house_name_number.Length));
private readonly string _address_2;
public string address_2 => _address_2.Substring(0, Math.Min(_address_field_max_length, _address_2.Length));
private readonly string _address_3;
public string address_3 => _address_3.Substring(0, Math.Min(_address_field_max_length, _address_3.Length));
private readonly string _address_4;
public string address_4 => _address_4.Substring(0, Math.Min(_address_field_max_length, _address_4.Length));
private readonly string _town;
public string town => _town.Substring(0, Math.Min(_address_field_max_length, _town.Length));
private readonly string _postcode_1;
public string postcode_1 => _postcode_1.Substring(0, Math.Min(_postcode_1_max_length, _postcode_1.Length));
private readonly string _postcode_2;
public string postcode_2 => _postcode_2.Substring(0, Math.Min(_postcode_2_max_length, _postcode_2.Length));
private readonly string _display_address;
public string display_address => _display_address.Substring(0, Math.Min(_display_address_max_length, _display_address.Length));
public RmrtdfPropertyAddress(Property property)
{
_house_name_number = string.IsNullOrEmpty(property.AddressLine1) ? "" : property.AddressLine1.Trim();
_address_2 = string.IsNullOrEmpty(property.AddressLine2) ? "" : property.AddressLine2.Trim();
_address_3 = string.IsNullOrEmpty(property.AddressLine3) ? "" : property.AddressLine3.Trim();
_address_4 = string.IsNullOrEmpty(property.AddressLine4) ? "" : property.AddressLine4.Trim();
_town = (char.ToUpper(property.AddressLine4[0]) + property.AddressLine4.Substring(1).ToLower()).Trim();
_postcode_1 = property.Postcode.Remove(property.Postcode.Length - 3).Trim();
_postcode_2 = property.Postcode.Substring(property.Postcode.Length - 3).Trim();
_display_address = $"{address_2} {town} {postcode_1}";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// 500. Keyboard Row
/// </summary>
namespace LeetCode
{
class KeyboardRow
{
public static string[] FindWords(string[] words)
{
var w = words.ToList().ConvertAll(wd => wd.ToLower());
List<string> ans = new List<string>();
HashSet<char> row1 = new HashSet<char>(){ 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p' };
HashSet<char> row2 = new HashSet<char>(){ 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l' };
HashSet<char> row3 = new HashSet<char>() { 'z', 'x', 'c', 'v', 'b', 'n', 'm' };
int check1=0, check2 =0, check3 = 0, index =-1;
int checksum = 0;
foreach (var word in w)
{
index++;
check1 = check2 = check3 = 0;
foreach (var letter in word)
{
if (row1.Contains(letter))
check1 = 1;
if (row2.Contains(letter))
check2 = 1;
if (row3.Contains(letter))
check3 = 1;
checksum = check1 + check2 + check3;
if (check1 + check2 + check3 > 1)
break;
}
if(checksum == 1)
ans.Add(words[index]);
}
return ans.ToArray();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EBS.Query.DTO
{
public class SearchAdjustStorePrice
{
public string Code { get; set; }
public string ProductCodeOrBarCode { get; set; }
public int Status { get; set; }
/// <summary>
/// 查询门店,多个门店逗号分隔
/// </summary>
public string StoreId { get; set; }
public DateTime? CreatedOn { get; set; }
}
}
|
namespace SlackBot
{
public class SlackCommand
{
public string Text { get; set; }
public string ChannelName { get; set; }
public string UserId { get; set; }
public string UserName { get; set; }
}
}
|
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace QL_DatBao.Class
{
class XL_BANG : DataTable
{
//
public static string connectionString;
//
public SqlConnection con;
public SqlDataAdapter da;
public DataTable dt;
public SqlCommand cmd;
//
protected string sql;
public string tableName;
#region Set Get thuộc tính
//public string Sql
//{
// get { return sql; }
// set { sql = value; }
//}
//public string TableName
//{
// get { return tableName; }
// set { tableName = value; }
//}
public int Count
{
get { return this.DefaultView.Count; }
}
#endregion
#region Phương thức khởi tạo
public XL_BANG() : base()
{
this.tableName = this.sql = "";
con = new SqlConnection(XL_BANG.connectionString);
}
public XL_BANG(string tableName) : base()
{
this.tableName = tableName;
this.sql = "";
con = new SqlConnection(XL_BANG.connectionString);
Read();
}
public XL_BANG(string tableName, string sql) : base()
{
this.tableName = tableName;
this.sql = sql;
con = new SqlConnection(XL_BANG.connectionString);
Read();
}
#endregion
#region Hàm xử lý truy vấn
public void close()
{
if (con.State == ConnectionState.Closed)
con.Open();
}
public SqlCommand getCMD(string sql)
{
if (con.State == ConnectionState.Closed)
con.Open();
cmd = new SqlCommand(sql, con);
return cmd;
}
public DataTable ExecuteQuery(string sql)
{
try
{
if (con.State == ConnectionState.Closed)
con.Open();
da = new SqlDataAdapter(sql, con);
dt = new DataTable();
da.Fill(dt);
return dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return null;
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
}
public int ExecuteNonQuery(string strSQL)
{
try
{
if (con.State == ConnectionState.Closed)
con.Open();
SqlCommand cmd = new SqlCommand(strSQL, con);
return cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return -1;
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
}
public Object ExecuteScalar(string function)
{
try
{
if (con.State == ConnectionState.Closed)
con.Open();
SqlCommand cmd = new SqlCommand(function, con);
Object result = cmd.ExecuteScalar();
return result;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return null;
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
}
#endregion
#region Các phương thức xử lý, thao tác trên bảng: đọc, ghi, lọc, cập nhật
// Đọc Dữ Liệu
public void Read()
{
try
{
if (con.State == ConnectionState.Closed)
con.Open();
if (sql == "")
sql = "SELECT * FROM " + tableName;
da = new SqlDataAdapter(sql, con);
da.FillSchema(this, SchemaType.Mapped);
da.Fill(this);
da.RowUpdated += new SqlRowUpdatedEventHandler(SqlRowUpdatedEventHandler_RowUpdated);
SqlCommandBuilder builder = new SqlCommandBuilder(da);
}
catch (SqlException e)
{
MessageBox.Show(e.Message);
}
}
// Ghi Dữ Liệu
public bool Write()
{
try
{
da.Update(this);
this.AcceptChanges();
return true;
}
catch (SqlException ex)
{
this.RejectChanges();
MessageBox.Show(ex.Message);
}
return false;
}
//Lọc Dữ Liệu
public void Filter(string dieu_kien)
{
try
{
this.DefaultView.RowFilter = dieu_kien;
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
#endregion
#region Xử lý xự kiện
// Xử lý sự kiện Rowupdated đối với trường khóa chính có kiểu Autonumber
private void SqlRowUpdatedEventHandler_RowUpdated(Object sender, SqlRowUpdatedEventArgs e)
{
if (this.PrimaryKey[0].AutoIncrement)
{
if ((e.Status == UpdateStatus.Continue) && (e.StatementType == StatementType.Insert))
{
SqlCommand cmd = new SqlCommand("Select @@IDENTITY ", con);
e.Row.ItemArray[0] = cmd.ExecuteScalar();
e.Row.AcceptChanges();
}
}
}
#endregion
}
}
|
using gView.Framework.Geometry;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace gView.Framework.FDB
{
public interface ISpatialTreeInfo
{
string type { get; }
IEnvelope Bounds { get; }
double SpatialRatio { get; }
int MaxFeaturesPerNode { get; }
Task<List<SpatialIndexNode>> SpatialIndexNodes();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KartLib;
using KartObjects;
namespace KartSystem
{
public interface IDiscountReasonView:IAxiTradeView
{
IList<DiscountReason> DiscountReasons { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SolutionsAssembly
{
public class NumberLetterCounts: ISolutionsContract
{
public string ProblemName => "Number Letter Count";
public string ProblemDescription => @"If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of 'and' when writing out numbers is in compliance with British usage.";
public int ProblemNumber => 17;
private static int[] SubTen => new int []{ 3, 3, 5, 4, 4, 3, 5, 5, 4}; //zero, one,two,three,four,five,six,seven,eight,nine
private static int[] SubTwenty => new int[] { 3, 6, 6, 8, 8, 7, 7, 9, 8, 8 };//ten, eleven,twelve,thirteen,fourteen,fifteen,sixteen,seventeen,eighteen,nineteen
private static int[] SubHundred=> new int[] { 6, 6, 5, 5, 5, 7, 6, 6 };//twenty,thirty,forty,fifty,sixty,seventy,eighty,ninety
private static int[] HunThou => new int[] { 7, 8 }; //hundred, thousand
public string Solution()
{
return ProblemSolution().ToString();
//return NumberToWordCount(90).ToString();
}
private int ProblemSolution()
{
var answer = 0;
for (int i = 1; i < 1001; i++)
{
answer += NumberToWordCount(i);
}
return answer;
}
private int NumberToWordCount(int vocalizeNumber)
{
var wordPos = 0;
var sumWordCount = 0;
//handle thousand
if ((vocalizeNumber / 1000) > 0)
{
sumWordCount += SubTen[vocalizeNumber/1000 -1]; //one
sumWordCount += HunThou[1]; // thousand...
}
vocalizeNumber %= 1000;
wordPos = (vocalizeNumber / 100);
//handle hundreds
if (wordPos > 0)
{
sumWordCount += SubTen[(vocalizeNumber/100) -1];
sumWordCount += HunThou[0];
sumWordCount += (vocalizeNumber % 100) > 0 ? 3: 0; //and
}
vocalizeNumber %= 100;
//handle sub 100
if (vocalizeNumber == 0)
return sumWordCount;
if (vocalizeNumber % 10 ==0 && vocalizeNumber >10) //more then 10 and no remainders
return sumWordCount += SubHundred[(vocalizeNumber / 10) - 2];
else if (vocalizeNumber < 10) // less then 10
return sumWordCount += SubTen[vocalizeNumber%10 -1];
else if (vocalizeNumber > 9 && vocalizeNumber < 20) // between 9 and 20
return sumWordCount += SubTwenty[(vocalizeNumber - 10) % 10];
else //has a 10 and a digit
{
sumWordCount += SubHundred[(vocalizeNumber / 10)-2 ];
return sumWordCount += SubTen[(vocalizeNumber % 10)-1];
}
}
}
}
|
using System;
namespace ScriptKit
{
public class JsBoolean:JsValue
{
public JsBoolean(bool value)
{
IntPtr booleanValue = IntPtr.Zero;
JsErrorCode jsErrorCode = NativeMethods.JsBoolToBoolean(value, out booleanValue);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
}
internal JsBoolean(IntPtr value)
{
this.Value = value;
}
public bool ToBoolean()
{
bool value = false;
JsErrorCode jsErrorCode = NativeMethods.JsBooleanToBool(this.Value, out value);
JsRuntimeException.VerifyErrorCode(jsErrorCode);
return value;
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class TeamGrid : MonoBehaviour
{
public Tile[] tiles;
private BattleManager battleManager;
// Use this for initialization
void Start ()
{
battleManager = (BattleManager) GameObject.FindObjectOfType (typeof(BattleManager));
}
public Tile GetTile(int row, int column)
{
for (int index = 0; index < tiles.Length; ++index)
{
Tile tile = tiles [index];
if (tile.row == row && tile.column == column) {
return tile;
}
}
return null;
}
public bool IsValidTile(int row, int column)
{
return (GetTile (row, column) != null);
}
public bool CanMoveToTile(Tile startTile, int row, int column)
{
Tile endTile = GetTile (row, column);
return CanMoveToTile (startTile, endTile);
}
public bool CanMoveToTile(Tile startTile, Tile endTile)
{
if (endTile == null)
{
return false;
}
int rowDelta = Mathf.Abs (startTile.row - endTile.row);
int columnDelta = Mathf.Abs (startTile.column - endTile.column);
if (rowDelta == 0 && columnDelta == 0)
{
return true;
}
else if (endTile.character != null)
{
return false;
}
if (!battleManager.canMoveDiagonal)
{
return (rowDelta + columnDelta <= battleManager.moveRange);
}
else
{
int moveRadius = Mathf.Max(rowDelta, columnDelta);
return (moveRadius <= battleManager.moveRange);
}
}
// Update is called once per frame
void Update ()
{
}
}
|
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Tools;
namespace _357
{
class Program
{
public const int UPPER_LIMIT = 1000000000;
public static HashSet<int> Primes;
public static void Main(string[] args)
{
Decorators.Benchmark(Solve, argument: UPPER_LIMIT);
}
public static long Solve(int limit)
{
NumUtils.ResetPrimesCache();
Primes = NumUtils.EratospheneSeive(limit + 1);
long s = 0;
#if DEBUG
foreach (var prime in Primes)
{
if (IsPrimeGenerating(prime - 1))
{
Console.WriteLine(prime - 1);
s += prime - 1;
}
}
#else
Parallel.ForEach(Primes, prime => {
if ((prime - 1) % 4 == 2 && IsPrimeGenerating(prime - 1))
{
Interlocked.Add(ref s, prime - 1);
}
});
#endif
return s + 1;
}
public static bool IsPrimeGenerating(int num)
{
var upper = NumUtils.SqrtUpper(num);
for (int i = 2; i <= upper; i++)
{
if (num % i == 0 && !Primes.Contains(i + num / i))
{
return false;
}
}
return true;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Opções : MonoBehaviour {
private Vector2 touchStartPos;
private Vector2 touchDirection;
private Narration narrator;
void Start()
{
narrator = GameObject.Find ("Narrator").GetComponent<Narration> ();
narrator.StartNarration ("Opcoes");
}
void Update()
{
if (Input.touchCount == 1) {
Touch touch = Input.GetTouch (0);
switch (touch.phase)
{
case TouchPhase.Began:
touchStartPos = touch.position;
break;
case TouchPhase.Moved:
touchDirection = touch.position - touchStartPos;
break;
case TouchPhase.Ended:
ChooseInput ();
break;
}
}
}
void ChooseInput()
{
if (touchDirection.magnitude > 100)
{
var normTouchDirection = touchDirection.normalized;
float absoluteDirection = Mathf.Abs (Vector2.Dot (normTouchDirection, Vector2.right));
if ( absoluteDirection< .3) {
if (normTouchDirection.y < 0)
{
ToogleNarration ();
}
else if(normTouchDirection.y > 0)
{
}
}
else if (absoluteDirection > .7)
{
if (normTouchDirection.x < 0)
{
narrator.Stop ();
SceneManager.LoadScene ("Menu");
}
else if( normTouchDirection.x > 0)
{
narrator.Stop ();
Debug.Log ("Mudar dificuldade");
}
}
}
}
void ToogleNarration()
{
narrator.Stop ();
narrator.disabled = (narrator.disabled)? false: true;
}
}
|
namespace buildingEnergyLoss.Model
{
public class TemperatureIndoor
{
private static int _idIncrement;
public int Id { get; private set; }
public string Name { get; }
public double Temperature { get; }
public TemperatureIndoor(string name, double temperature)
{
Id = _idIncrement++;
Name = name;
Temperature = temperature;
}
public TemperatureIndoor(int id, string name, double temperature)
{
Id = id;
Name = name;
Temperature = temperature;
}
}
}
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace Algorithms.Lib
{
public static class SystemHelp
{
public static string StrJoin<T>(this IEnumerable<T> src, string separator = ", ") => string.Join(separator, src);
public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<TKey, TValue> factory)
{
if (dictionary.ContainsKey(key)) return dictionary[key];
var value = factory(key);
dictionary.Add(key, value);
return value;
}
public static IEnumerable<TValue> GetListOrEmpty<TKey, TValue>(this IDictionary<TKey, IList<TValue>> edges, TKey node)
=> edges.ContainsKey(node) ? edges[node] : Enumerable.Empty<TValue>();
public static IEnumerable<T> In<T>(this IEnumerable<T> src, HashSet<T> hashSet) => src.Where(e => hashSet.Contains(e));
public static IEnumerable<T> NotIn<T>(this IEnumerable<T> src, HashSet<T> hashSet) => src.Where(e => !hashSet.Contains(e));
public static bool NotIn<T>(this T e, HashSet<T> hashSet) => !hashSet.Contains(e);
public static IEnumerable<T> NotNull<T>(this IEnumerable<T> src) where T : class => src.Where(s => s is not null);
public static T MinElement<T>(this IEnumerable<T> src, Func<T, int> func)
{
var min = (Item: default(T), Value: int.MaxValue);
foreach (var item in src)
{
var value = func(item);
if (min.Value <= value) continue;
min = (item, value);
}
return min.Item;
}
public static IEnumerable<T> Meanwhile<T>(this IEnumerable<T> src, Action<T> action)
{
if (src is null)
{
throw new ArgumentNullException(nameof(src));
}
if (action is null)
{
throw new ArgumentNullException(nameof(action));
}
static IEnumerable<T> Minwhile(IEnumerable<T> src, Action<T> action)
{
foreach (var i in src)
{
action(i);
yield return i;
}
}
return Minwhile(src, action);
}
public static void ForEach<T>(this IEnumerable<T> src, Action<T> action)
{
if (src is null)
{
throw new ArgumentNullException(nameof(src));
}
if (action is null)
{
throw new ArgumentNullException(nameof(action));
}
foreach (var i in src) action(i);
}
public static IEnumerable<T> Transform<T>(this IEnumerable<T> src, Func<T, T> transform)
{
if (src is null)
{
throw new ArgumentNullException(nameof(src));
}
if (transform is null)
{
throw new ArgumentNullException(nameof(transform));
}
static IEnumerable<T> Transform(IEnumerable<T> src, Func<T, T> transform)
{
foreach (var i in src) yield return transform(i);
}
return Transform(src, transform);
}
}
public class EventArgs<T> : EventArgs
{
public T Value { get; }
public EventArgs(T value)
{
Value = value;
}
}
public class Pool<T>
{
public Pool(Func<T> factory, int capacity = 8)
{
_queue = new();
for (int i = 0; i < capacity; i++)
_queue.Enqueue(factory());
}
private readonly ConcurrentQueue<T> _queue;
public int Capacity { get; private set; }
struct PoolObject : IDisposable
{
public T Value { get; }
public void Dispose()
{
throw new NotImplementedException();
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ProjectileScript : MonoBehaviour
{
[SerializeField]
int damage;
[SerializeField]
float velocity = 5f;
Rigidbody2D rigidbody;
public float directionMultiplier;
private void Awake()
{
rigidbody = GetComponent<Rigidbody2D>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.transform.tag == "Player")
{
collision.gameObject.GetComponent<GenericHealth>().RemoveHealth(damage);
}
if(collision.gameObject.transform.tag != "Enemy")
{
Destroy(this.gameObject);
}
}
private void Update()
{
rigidbody.velocity = Vector2.right * velocity * directionMultiplier;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FishSchool : MonoBehaviour {
public GameObject fishPrefab;
public int spawnCount = 6;
public float spawnRadius = 2.0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
|
using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebDriverFrameworkUnitTests
{
public class PageObjectExample
{
public PageObjectExample()
{
PageFactory.InitElements(PropertiesCollection.driver, this);
}
[FindsBy(How=How.ClassName, Using = "group-button")]
public IWebElement Group_ButtonClassName { get; set; }
}
}
|
using System;
namespace StoreModel
{
/// <summary>
/// This data structure models a product and its quantity.
/// </summary>
public class Item
{
private int _quantity;
public Item(Product product, int quantity)
{
this.Product = product;
this.Quantity = quantity;
}
public override string ToString()
{
return String.Format("{0} Quantity: {1}",Product.ToString(), Quantity);
}
public Product Product { get; set; }
public int Quantity
{
get => _quantity;
set
{
if (value < 0){
throw new Exception("You cannot have a negative quantity");
}else{
_quantity = value;
}
}
}
public void ChangeQuantity(int num)
{
this.Quantity = this.Quantity + num;
}
}
} |
<<<<<<< HEAD
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Drawing.Drawing2D;
using Microsoft.Win32;
namespace enem
{
class enemy
{
Random rnd = new Random();
public int myscore;
public int allscore;
public int enemyscore;
public int[] ex = new int[3];
// public enemy(int my, int your, int all) { }
public void getinfo(int my, int your, int all) {
myscore = my;
allscore = all;
enemyscore = your;
}
/* public void myturn(int my, int your, int all)
{
MessageBox.Show(my.ToString());
MessageBox.Show(your.ToString());
MessageBox.Show(all.ToString());
int take;
if (all > 18) {
take = rnd.Next(1, 3);
all = all - take;
my = my + take;
MessageBox.Show(">18");
}
else if((my % 2) == 0)
{
take = 2;
all = all - take;
my = my + take;
}
else if(all == 3)
{
if((my % 2) == 0) {
take = 2;
all = all - take;
my = my + take;
}
else if((my % 2) == 1)
{
take = 3;
all = all - take;
my = my + take;
}
}
else if(all < 3)
{
if((my % 2) == 0)
{
take = 2;
all = all - take;
my = my + take;
}
else if((my % 2) == 1)
{
take = 1;
all = all - take;
my = my + take;
}
}
else {
MessageBox.Show("else");
}
return ex;
}*/
public Tuple<int, int,int> myturn(int my,int your, int all)
{
// MessageBox.Show(my.ToString());
// MessageBox.Show(your.ToString());
// MessageBox.Show(all.ToString());
int take;
if (all > 18)
{
take = rnd.Next(1, 3);
all = all - take;
my = my + take;
MessageBox.Show("5");
// MessageBox.Show(">18");
}
else if (((my % 2) == 0) && (all > 1))
{
take = 2;
all = all - take;
my = my + take;
}
else if (all == 1)
{
take = 1;
all = all - take;
my = my + take;
}
else if (all <= 0)
{
take = 0;
all = all - take;
my = my + take;
}
else if (all == 3)
{
if ((my % 2) == 0)
{
take = 2;
all = all - take;
my = my + take;
}
else if ((my % 2) == 1)
{
take = 3;
all = all - take;
my = my + take;
}
}
else if (all < 3 && all > 0)
{
if (((my % 2 ) == 0) && (all>1))
{
take = 2;
all = all - take;
my = my + take;
}
else if ((my % 2) == 1)
{
take = 1;
all = all - take;
my = my + take;
}
}
else
{
take = rnd.Next(1, 3);
all = all - take;
my = my + take;
}
return Tuple.Create(my,your,all);
}
}
}
=======
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Drawing.Drawing2D;
using Microsoft.Win32;
namespace enem
{
class enemy
{
Random rnd = new Random();
public int myscore;
public int allscore;
public int enemyscore;
public int[] ex = new int[3];
// public enemy(int my, int your, int all) { }
public void getinfo(int my, int your, int all) {
myscore = my;
allscore = all;
enemyscore = your;
}
/* public void myturn(int my, int your, int all)
{
MessageBox.Show(my.ToString());
MessageBox.Show(your.ToString());
MessageBox.Show(all.ToString());
int take;
if (all > 18) {
take = rnd.Next(1, 3);
all = all - take;
my = my + take;
MessageBox.Show(">18");
}
else if((my % 2) == 0)
{
take = 2;
all = all - take;
my = my + take;
}
else if(all == 3)
{
if((my % 2) == 0) {
take = 2;
all = all - take;
my = my + take;
}
else if((my % 2) == 1)
{
take = 3;
all = all - take;
my = my + take;
}
}
else if(all < 3)
{
if((my % 2) == 0)
{
take = 2;
all = all - take;
my = my + take;
}
else if((my % 2) == 1)
{
take = 1;
all = all - take;
my = my + take;
}
}
else {
MessageBox.Show("else");
}
return ex;
}*/
public Tuple<int, int,int> myturn(int my,int your, int all)
{
MessageBox.Show(my.ToString());
MessageBox.Show(your.ToString());
MessageBox.Show(all.ToString());
int take;
if (all > 18)
{
take = rnd.Next(1, 3);
all = all - take;
my = my + take;
MessageBox.Show(">18");
}
else if ((my % 2) == 0)
{
take = 2;
all = all - take;
my = my + take;
}
else if (all == 3)
{
if ((my % 2) == 0)
{
take = 2;
all = all - take;
my = my + take;
}
else if ((my % 2) == 1)
{
take = 3;
all = all - take;
my = my + take;
}
}
else if (all < 3 && all > 0)
{
if ((my % 2) == 0)
{
take = 2;
all = all - take;
my = my + take;
}
else if ((my % 2) == 1)
{
take = 1;
all = all - take;
my = my + take;
}
}
else
{
take = rnd.Next(1, 3);
all = all - take;
my = my + take;
}
return Tuple.Create(my,your,all);
}
}
}
>>>>>>> b30dd1c82299db585f2c0fdacde1c296de9480fe
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Comics.Core.Extensions;
using Comics.Core.Persistence;
using Comics.Core.Presentation;
namespace Comics.Web.Controllers
{
public class FeedController : Controller
{
private readonly IComicsRepository _comics;
public FeedController(IComicsRepository comics)
{
_comics = comics;
}
// GET: Feed
public FileStreamResult Feed(ComicType type)
{
var comics = _comics.GetLatestComics(type);
var feed = new ComicFeed($"{type.ToDisplayName()} Comics", new Uri("http://example.com"));
var xml = feed.Render(comics);
return new FileStreamResult(new MemoryStream(Encoding.UTF8.GetBytes(xml)), "text/xml");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Nac.Common;
using System.IO;
using System.Runtime.Serialization;
using Nac.Engine;
using Nac.Engine.Control;
public class NacEngineEventArgs : EventArgs {
public object OriginalSender;
public EventArgs OriginalArgs;
}
public delegate void NacEngineEventHandler(object sender, NacEngineEventArgs args);
public interface INacEngineContext : INacContext {
NacEngine Engine { get; }
NacEngineField Field { get; }
NacEngineRuntime Runtime(string path);
NacEngineProject Project(string path);
NacEngineDatabase Database(string path);
event NacEngineEventHandler NacEngineEvent;
}
public static class NacEngineGlobal {
public static INacEngineContext G { get { return NacGlobal.G as NacEngineContext; } set { NacGlobal.G = value; } }
}
namespace Nac.Engine {
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using static NacEngineGlobal;
[DataContract]
public class NacEngineContext : INacEngineContext {
private const string contextFileName = "NacEngineContext.Xml";
public static string IP { get; private set; }
private NacEngineContext(NacEngine engine) { Engine = engine; }
#region INacContext
[DataMember]
public NacEngine Engine { get; private set; }
public NacEngineField Field { get; private set; }
public NacEngineProject Project(string path) {
return Engine[NacPath.Parse(path).ProjectPath] as NacEngineProject;
}
public NacEngineDatabase Database(string path) {
return Project(path).Database;
}
public NacEngineRuntime Runtime(string path) {
return Project(path).Runtime;
}
private static NacEngineLogger Logger { get; set; }
public bool Log(params object[] args) {
return Logger.Log(args);
}
#endregion
#region static
private static NacEngineContext Instance { get { return G as NacEngineContext; } set { G = value; } }
public static void Create() {
Logger = new NacEngineLogger();
IP = NacUtils.FindIP(); if (IP == null) IP = NacUtils.cLoopbackIP;
Logger.Log(IP);
try {
Instance = Load() as NacEngineContext;
Instance.Engine.Cleanup();
} catch { Instance = new NacEngineContext(new NacEngine()); }
Logger.NewLogMessage += Instance.Logger_NewLogMessage;
Instance.Field = new NacEngineField(IP);
Instance.Start();
}
public event NacEngineEventHandler NacEngineEvent;
private void Logger_NewLogMessage(object sender, NacEngineLogger.NacEngineLogEventArgs args) {
if (NacEngineEvent != null) {
var newArgs = new NacEngineEventArgs() { OriginalSender = sender, OriginalArgs = args };
NacEngineEvent.Invoke(Instance, newArgs);
}
}
private void Start() { Engine.Start(); }
public static void Destroy() {
Instance.Dispose();
Logger.Dispose();
}
private static void Save() {
Instance.Engine.Cleanup();
string xml = NacSerializer.Serialize(Instance);
File.WriteAllText(contextFileName, xml);
}
private static object Load() {
return NacSerializer.Deserialize(File.ReadAllText(contextFileName), typeof(NacEngineContext)) as NacEngineContext;
}
#endregion
public void Dispose() {
Engine.Dispose();
Save();
}
}
}
|
using Alabo.Datas.UnitOfWorks;
using Alabo.Domains.Repositories.Exception;
using Alabo.Domains.Repositories.SqlServer;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
namespace Alabo.Domains.Repositories.EFCore.Context {
/// <summary>
/// Class EntityFrameworkRepositoryContext.
/// </summary>
public class EfCoreRepositoryContext : IRepositoryContext {
/// <summary>
/// The context
/// </summary>
private readonly DbContext _context;
/// <summary>
/// The transaction
/// </summary>
private IDbContextTransaction _transaction;
/// <summary>
/// The transaction count
/// </summary>
private int _transactionCount;
public UnitOfWorkBase _unitOfWork;
public EfCoreRepositoryContext(UnitOfWorkBase unitOfWork) {
ConnectionString = unitOfWork.ConnectionString;
_unitOfWork = unitOfWork;
_context = _unitOfWork;
}
/// <summary>
/// Gets the database context.
/// </summary>
public object DbContext => _context;
/// <summary>
/// Gets the connection string.
/// </summary>
public string ConnectionString { get; }
/// <summary>
/// Gets a value indicating whether this instance is in transaction.
/// </summary>
public bool IsInTransaction => _transactionCount > 0;
public UnitOfWorkBase UnitOfWork => _unitOfWork;
public IQueryable<T> Query<T>() where T : class {
return Set<T>();
}
/// <summary>
/// Saves the changes.
/// </summary>
public int SaveChanges() {
return _context.SaveChanges();
}
/// <summary>
/// Begins the transaction.
/// </summary>
public void BeginTransaction() {
RaseExceptionIfConnectionIsNotInitialization();
if (_transactionCount <= 0) {
_transaction = _context.Database.BeginTransaction();
} else {
_transactionCount++;
}
}
/// <summary>
/// Begins the transaction.
/// </summary>
/// <param name="isolationLevel">The isolation level.</param>
public void BeginTransaction(IsolationLevel isolationLevel) {
RaseExceptionIfConnectionIsNotInitialization();
if (_transactionCount <= 0) {
_transaction = _context.Database.BeginTransaction(isolationLevel);
} else {
_transactionCount++;
}
}
/// <summary>
/// Commits the transaction.
/// </summary>
public void CommitTransaction() {
RaseExceptionIfConnectionIsNotInitialization();
if (_transactionCount > 0) {
_transactionCount--;
} else {
_transaction.Commit();
}
}
/// <summary>
/// Rollbacks the transaction.
/// </summary>
public void RollbackTransaction() {
RaseExceptionIfConnectionIsNotInitialization();
if (_transactionCount > 0) {
_transactionCount--;
} else {
_transaction.Rollback();
}
}
/// <summary>
/// Disposes the transaction.
/// </summary>
public void DisposeTransaction() {
RaseExceptionIfConnectionIsNotInitialization();
if (_transactionCount > 0) {
_transactionCount--;
} else {
_transaction.Dispose();
_transaction = null;
}
}
/// <summary>
/// 通过SQl方式打开事物
/// </summary>
public IRepositoryTransaction OpenTransaction() {
RaseExceptionIfConnectionIsNotInitialization();
var sqlServerRepositoryContext = new SqlServerRepositoryContext(ConnectionString);
return sqlServerRepositoryContext.OpenTransaction();
}
/// <summary>
/// Transations the specified action.
/// </summary>
/// <param name="action">The action.</param>
public bool Transation(Action action) {
var sqlConnection = new SqlConnection(ConnectionString);
sqlConnection.Open();
var sqlTransaction = sqlConnection.BeginTransaction();
var sqlCommand = new SqlCommand {
Connection = sqlConnection,
Transaction = sqlTransaction
};
try {
action();
sqlTransaction.Commit();
return true;
} catch (System.Exception ex) {
Console.WriteLine(ex.Message);
sqlTransaction.Rollback();
return false;
} finally {
sqlTransaction.Dispose();
sqlCommand.Dispose();
}
}
public void Close() {
}
/// <summary>
/// 更新s the specified predicate.
/// </summary>
/// <param name="predicate">The predicate.</param>
/// <param name="action">The action.</param>
public void Update<T>(Expression<Func<T, bool>> predicate, Action<T> action)
where T : class {
var query = Query<T>();
if (predicate != null) {
query = query.Where(predicate);
}
var source = query.ToList();
foreach (var item in source) {
action(item);
}
SaveChanges();
}
public DbSet<T> Set<T>() where T : class {
return _context.Set<T>();
}
private void RaseExceptionIfConnectionIsNotInitialization() {
if (_context == null) {
throw new RepositoryContextException("sqlite connection is not initialization.");
}
}
}
} |
namespace BattleEngine.Actors
{
public enum DefenseType
{
DEFENSE = DamageType.DAMAGE,
MAGIC_DEFENSE = DamageType.MAGIC_DAMAGE
}
}
|
using System;
using OwnArrayList.Core;
namespace OwnArrayList.ConsoleApp
{
internal class Program
{
private static void Main(string[] args)
{
string headLine = $"{"KatNr",5} | {"Vorname",-20} | {"Nachname",-20} | {"Alter",5}";
Console.WriteLine("Dynamische Schülerliste");
for (int k = 0; k < headLine.Length; k++)
{
Console.Write("=");
}
Console.WriteLine();
//Testdaten
PupilList pupils = new PupilList();
Pupil pupil1 = new Pupil(1, "Simon", "P", 17);
pupils.Add(pupil1);
Pupil pupil2 = new Pupil(2, "Anna", "Lutz", 16);
Pupil pupil3 = new Pupil(3, "Fritz", "Auer", 15);
Pupil pupil4 = new Pupil(6, "Hans", "Huber", 14);
Pupil pupil5 = new Pupil(5, "Moritz", "Maier", 13);
pupils.Add(pupil2);
pupils.Remove(pupil1);
pupils.Add(pupil5);
pupils.Insert(1, pupil4);
pupils.GetAt(1);
pupils.Sort();
pupils.Add(pupil3);
Console.WriteLine(headLine);
for (int k = 0; k < headLine.Length; k++)
{
Console.Write("=");
}
Console.WriteLine();
for (int i = 0; i < pupils.Count; i++)
{
Console.WriteLine($"{pupils.GetAt(i).CatalogNumber,5} | {pupils.GetAt(i).FirstName,-20} | {pupils.GetAt(i).LastName,-20} | {pupils.GetAt(i).Age,5}");
}
}
}
} |
namespace AlienWeatherPrediction
{
public enum Weather
{
Normal,
Drought,
Rain,
Optimum
}
} |
namespace BettingSystem.Application.Games.Matches.Queries.Stadiums
{
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
public class GetMatchStadiumsQuery : IRequest<IEnumerable<GetMatchStadiumsResponseModel>>
{
public class GetMatchStadiumsQueryHandler : IRequestHandler<
GetMatchStadiumsQuery,
IEnumerable<GetMatchStadiumsResponseModel>>
{
private readonly IMatchQueryRepository matchRepository;
public GetMatchStadiumsQueryHandler(IMatchQueryRepository matchRepository)
=> this.matchRepository = matchRepository;
public async Task<IEnumerable<GetMatchStadiumsResponseModel>> Handle(
GetMatchStadiumsQuery request,
CancellationToken cancellationToken)
=> await this.matchRepository.GetStadiumsListing(cancellationToken);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using lsc.Common;
using lsc.Model.Enume;
using lsc.Bll;
using lsc.Model;
using lsc.crm.ViewModel;
namespace lsc.crm.Controllers
{
/// <summary>
/// 企业客户信息
/// </summary>
public class EnterCustomController : BaseController
{
public async Task<IActionResult> Index()
{
DistrictInfoBll dbll = new DistrictInfoBll();
var ProvinceList = await dbll.GetAsync(0);
ViewBag.ProvinceList = ProvinceList;
int pageIndex = 1;
if (Request.Method =="POST")
{
pageIndex = Request.Form["page"].TryToInt(1);
}
int pageSize = 20;
string EnterName = Request.Method == "POST"? Request.Form["EnterName"].TryToString():string.Empty;
ViewBag.EnterName = EnterName;
CustomerTypeEnum? CustomerType = null;
ViewBag.CustomerType = 0;
if (Request.Method == "POST"&& Request.Form["CustomerType"].TryToInt(0) > 0)
{
CustomerType = (CustomerTypeEnum)Request.Form["CustomerType"].TryToInt(0);
ViewBag.CustomerType = Request.Form["CustomerType"].TryToInt(0);
}
RelationshipEnume? Relationship = null;
ViewBag.Relationship = 0;
if (Request.Method == "POST" && Request.Form["Relationship"].TryToInt(0) > 0)
{
Relationship = (RelationshipEnume)Request.Form["Relationship"].TryToInt(0);
ViewBag.Relationship = Request.Form["Relationship"].TryToInt(0);
}
PhaseEnume? Phase = null;
ViewBag.Phase = 0;
if (Request.Method == "POST" && Request.Form["Phase"].TryToInt(0) > 0)
{
Phase = (PhaseEnume)Request.Form["Phase"].TryToInt(0);
ViewBag.Phase = Request.Form["Phase"].TryToInt(0);
}
ValueGradeEnume? ValueGrade = null;
ViewBag.ValueGrade = 0;
if (Request.Method == "POST" && Request.Form["ValueGrade"].TryToInt(0) > 0)
{
ValueGrade = (ValueGradeEnume)Request.Form["ValueGrade"].TryToInt(0);
ViewBag.ValueGrade = Request.Form["ValueGrade"].TryToInt(0);
}
CustSource? Source = null;
ViewBag.Source = 0;
if (Request.Method == "POST" && Request.Form["Source"].TryToInt(0) > 0)
{
Source = (CustSource)Request.Form["Source"].TryToInt(0);
ViewBag.Source = Request.Form["Source"].TryToInt(0);
}
bool? IsHeat = null;
ViewBag.IsHeat = false;
if (Request.Method == "POST" && !Request.Form["IsHeat"].TryToString().IsNull())
{
IsHeat = Request.Form["IsHeat"].TryToString() == "on";
ViewBag.IsHeat = IsHeat;
}
DegreeOfHeatEnume? DegreeOfHeat = null;
ViewBag.DegreeOfHeat = 0;
if (Request.Method == "POST" && Request.Form["DegreeOfHeat"].TryToInt(0) > 0)
{
DegreeOfHeat = (DegreeOfHeatEnume)Request.Form["DegreeOfHeat"].TryToInt(0);
ViewBag.DegreeOfHeat = Request.Form["DegreeOfHeat"].TryToInt(0);
}
string Province = null;
ViewBag.Province = string.Empty;
if (Request.Method == "POST" && !Request.Form["Province"].TryToString().IsNull())
{
Province = Request.Form["Province"].TryToString();
ViewBag.Province = Request.Form["Province"].TryToString();
}
string City = null;
ViewBag.City = string.Empty;
if (Request.Method == "POST" && !Request.Form["City"].TryToString().IsNull())
{
City = Request.Form["City"].TryToString();
ViewBag.City= Request.Form["City"].TryToString();
}
DateTime? UpdateTime = null;
bool? timeType = null;
ViewBag.UpdateTime = 0;
if (Request.Method == "POST" && Request.Form["UpdateTime"].TryToInt(0) > 0)
{
ViewBag.UpdateTime = Request.Form["UpdateTime"].TryToInt(0);
switch (Request.Form["UpdateTime"].TryToInt(0))
{
case 1:
UpdateTime = DateTime.Now.AddDays(-7);
break;
case 2:
UpdateTime = DateTime.Now.AddDays(-15);
break;
case 3:
UpdateTime = DateTime.Now.AddDays(-30);
break;
case 4:
UpdateTime = DateTime.Now.AddDays(-60);
break;
case 5:
UpdateTime = DateTime.Now.AddDays(-90);
break;
case 6:
UpdateTime = DateTime.Now.AddDays(-3);
timeType = true;
break;
case 7:
UpdateTime = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day);
timeType = true;
break;
}
}
EnterCustContactsBll ecbll = new EnterCustContactsBll();
List<int> idlist = new List<int>();
string Telephone = string.Empty;
if (Request.Method == "POST" && !Request.Form["Telephone"].TryToString().IsNull())
{
ViewBag.Telephone = Request.Form["Telephone"].TryToString();
Telephone = Request.Form["Telephone"].TryToString();
}
string QQ = string.Empty;
if (Request.Method=="POST" && !Request.Form["QQ"].TryToString().IsNull())
{
ViewBag.QQ = Request.Form["QQ"].TryToString();
QQ = Request.Form["QQ"].TryToString();
}
if (!QQ.IsNull() || !Telephone.IsNull())
{
var eclists = await ecbll.GetListAsync(Telephone, QQ);
if (eclists!=null && eclists.Count>0)
{
var ids = from ec in eclists
select ec.EnterCustID;
idlist.AddRange(ids);
}
}
EnterCustomerBll bll = new EnterCustomerBll();
EnterCustPhaseLogBll eclogbll = new EnterCustPhaseLogBll();
List<EnterCustContacts> eclist = new List<EnterCustContacts>();
List<EnterCustPhaseLog> ecplogList = new List<EnterCustPhaseLog>();
var list = await bll.GetAsync(pageIndex, pageSize, User.ID, EnterName, CustomerType, Relationship, Phase, ValueGrade, Source, IsHeat, DegreeOfHeat, Province, City, UpdateTime, timeType, idlist);
if (list != null && list.Item1!=null)
{
foreach(var info in list.Item1)
{
var elist = await ecbll.GetListAsync(info.ID);
if (elist != null && elist.Count > 0)
eclist.AddRange(elist);
var eclog = await eclogbll.ListAsync(info.ID);
if (eclog != null && eclog.Count > 0)
ecplogList.Add(eclog.FirstOrDefault());
}
}
ViewBag.ecplogList = ecplogList;
ViewBag.eclist = eclist;
ViewBag.count = list.Item2;
ViewBag.pageIndex = pageIndex;
ViewBag.UserID = User.ID;
ViewBag.UserName = User.Name;
ViewBag.root = "enter";
return View(list.Item1);
//return View();
}
public async Task<IActionResult> AllEnterList()
{
DistrictInfoBll dbll = new DistrictInfoBll();
var ProvinceList = await dbll.GetAsync(0);
ViewBag.ProvinceList = ProvinceList;
int pageIndex = 1;
if (Request.Method == "POST")
{
pageIndex = Request.Form["page"].TryToInt(1);
}
int pageSize = 20;
string EnterName = Request.Method == "POST" ? Request.Form["EnterName"].TryToString() : string.Empty;
ViewBag.EnterName = EnterName;
CustomerTypeEnum? CustomerType = null;
ViewBag.CustomerType = 0;
if (Request.Method == "POST" && Request.Form["CustomerType"].TryToInt(0) > 0)
{
CustomerType = (CustomerTypeEnum)Request.Form["CustomerType"].TryToInt(0);
ViewBag.CustomerType = Request.Form["CustomerType"].TryToInt(0);
}
RelationshipEnume? Relationship = null;
ViewBag.Relationship = 0;
if (Request.Method == "POST" && Request.Form["Relationship"].TryToInt(0) > 0)
{
Relationship = (RelationshipEnume)Request.Form["Relationship"].TryToInt(0);
ViewBag.Relationship = Request.Form["Relationship"].TryToInt(0);
}
PhaseEnume? Phase = null;
ViewBag.Phase = 0;
if (Request.Method == "POST" && Request.Form["Phase"].TryToInt(0) > 0)
{
Phase = (PhaseEnume)Request.Form["Phase"].TryToInt(0);
ViewBag.Phase = Request.Form["Phase"].TryToInt(0);
}
ValueGradeEnume? ValueGrade = null;
ViewBag.ValueGrade = 0;
if (Request.Method == "POST" && Request.Form["ValueGrade"].TryToInt(0) > 0)
{
ValueGrade = (ValueGradeEnume)Request.Form["ValueGrade"].TryToInt(0);
ViewBag.ValueGrade = Request.Form["ValueGrade"].TryToInt(0);
}
CustSource? Source = null;
ViewBag.Source = 0;
if (Request.Method == "POST" && Request.Form["Source"].TryToInt(0) > 0)
{
Source = (CustSource)Request.Form["Source"].TryToInt(0);
ViewBag.Source = Request.Form["Source"].TryToInt(0);
}
bool? IsHeat = null;
ViewBag.IsHeat = false;
if (Request.Method == "POST" && !Request.Form["IsHeat"].TryToString().IsNull())
{
IsHeat = Request.Form["IsHeat"].TryToString() == "on";
ViewBag.IsHeat = IsHeat;
}
DegreeOfHeatEnume? DegreeOfHeat = null;
ViewBag.DegreeOfHeat = 0;
if (Request.Method == "POST" && Request.Form["DegreeOfHeat"].TryToInt(0) > 0)
{
DegreeOfHeat = (DegreeOfHeatEnume)Request.Form["DegreeOfHeat"].TryToInt(0);
ViewBag.DegreeOfHeat = Request.Form["DegreeOfHeat"].TryToInt(0);
}
string Province = null;
ViewBag.Province = string.Empty;
if (Request.Method == "POST" && !Request.Form["Province"].TryToString().IsNull())
{
Province = Request.Form["Province"].TryToString();
ViewBag.Province = Request.Form["Province"].TryToString();
}
string City = null;
ViewBag.City = string.Empty;
if (Request.Method == "POST" && !Request.Form["City"].TryToString().IsNull())
{
City = Request.Form["City"].TryToString();
ViewBag.City = Request.Form["City"].TryToString();
}
DateTime? UpdateTime = null;
ViewBag.UpdateTime = 0;
if (Request.Method == "POST" && Request.Form["UpdateTime"].TryToInt(0) > 0)
{
ViewBag.UpdateTime = Request.Form["UpdateTime"].TryToInt(0);
switch (Request.Form["UpdateTime"].TryToInt(0))
{
case 1:
UpdateTime = DateTime.Now.AddDays(-7);
break;
case 2:
UpdateTime = DateTime.Now.AddDays(-15);
break;
case 3:
UpdateTime = DateTime.Now.AddDays(-30);
break;
case 4:
UpdateTime = DateTime.Now.AddDays(-60);
break;
case 5:
UpdateTime = DateTime.Now.AddDays(-90);
break;
}
}
int? userid = null;
if (Request.Method == "POST" && Request.Form["UserID"].TryToInt()>0)
{
userid = Request.Form["UserID"].TryToInt();
}
ViewBag.userid = userid;
EnterCustomerBll bll = new EnterCustomerBll();
var list = await bll.GetAllAsync(pageIndex, pageSize, userid, EnterName, CustomerType, Relationship, Phase, ValueGrade, Source, IsHeat, DegreeOfHeat, Province, City, UpdateTime);
ViewBag.count = list.Item2;
ViewBag.pageIndex = pageIndex;
UserBll userBll = new UserBll();
List<UserInfo> userlist = await userBll.GetListAsync();
EnterCustContactsBll enterCustContactsBll = new EnterCustContactsBll();
List<EnterCustContacts> eclist = new List<EnterCustContacts>();
if (list.Item1!=null)
{
foreach (var enterCustomer in list.Item1)
{
var ecs = await enterCustContactsBll.GetListAsync(enterCustomer.ID);
if (ecs!=null && ecs.Count>0)
{
eclist.AddRange(ecs);
}
}
}
ViewBag.eclist = eclist;
ViewBag.userlist = userlist;
ViewBag.root = "enter";
return View(list.Item1);
}
/// <summary>
/// 查看联系人
/// </summary>
/// <param name="EnterCustID"></param>
/// <returns></returns>
public async Task<IActionResult> EnterCustContactsList(int EnterCustID)
{
EnterCustContactsBll bll = new EnterCustContactsBll();
var list = await bll.GetListAsync(EnterCustID);
return View(list);
}
//[HttpPost]
//public async Task<IActionResult> EnterCustomlist()
//{
// int pageIndex = Request.Form["page"].TryToInt(1);
// int pageSize = 20;
// string EnterName = Request.Form["EnterName"].TryToString();
// CustomerTypeEnum? CustomerType = null;
// if (Request.Form["CustomerType"].TryToInt(0)>0)
// {
// CustomerType = (CustomerTypeEnum)Request.Form["CustomerType"].TryToInt(0);
// }
// RelationshipEnume? Relationship = null;
// if (Request.Form["Relationship"].TryToInt(0) > 0)
// Relationship = (RelationshipEnume)Request.Form["Relationship"].TryToInt(0);
// PhaseEnume? Phase = null;
// if (Request.Form["Phase"].TryToInt(0) > 0)
// Phase = (PhaseEnume)Request.Form["Phase"].TryToInt(0);
// ValueGradeEnume? ValueGrade = null;
// if (Request.Form["ValueGrade"].TryToInt(0) > 0)
// ValueGrade = (ValueGradeEnume)Request.Form["ValueGrade"].TryToInt(0);
// CustSource? Source = null;
// if (Request.Form["Source"].TryToInt(0) > 0)
// Source = (CustSource)Request.Form["Source"].TryToInt(0);
// bool? IsHeat = null;
// if (!Request.Form["IsHeat"].TryToString().IsNull())
// IsHeat = Request.Form["IsHeat"].TryToString()== "on";
// DegreeOfHeatEnume? DegreeOfHeat = null;
// if (Request.Form["DegreeOfHeat"].TryToInt(0) > 0)
// DegreeOfHeat = (DegreeOfHeatEnume)Request.Form["DegreeOfHeat"].TryToInt(0);
// string Province = null;
// if (!Request.Form["Province"].TryToString().IsNull())
// Province = Request.Form["Province"].TryToString();
// string City = null;
// if (!Request.Form["City"].TryToString().IsNull())
// City = Request.Form["City"].TryToString();
// DateTime? UpdateTime = null;
// if (Request.Form["UpdateTime"].TryToInt(0) > 0)
// {
// switch (Request.Form["UpdateTime"].TryToInt(0))
// {
// case 1:
// UpdateTime = DateTime.Now.AddDays(-7);
// break;
// case 2:
// UpdateTime = DateTime.Now.AddDays(-15);
// break;
// case 3:
// UpdateTime = DateTime.Now.AddDays(-30);
// break;
// case 4:
// UpdateTime = DateTime.Now.AddDays(-60);
// break;
// case 5:
// UpdateTime = DateTime.Now.AddDays(-90);
// break;
// }
// }
// EnterCustomerBll bll = new EnterCustomerBll();
// var list =await bll.GetAsync(pageIndex,pageSize,User.ID,EnterName,CustomerType,Relationship,Phase,ValueGrade,Source,IsHeat,DegreeOfHeat,Province,City,UpdateTime);
// ViewBag.count = list.Item2;
// return View(list.Item1);
//}
/// <summary>
/// 添加客户信息
/// </summary>
/// <returns></returns>
public async Task<IActionResult> AddEnterCustom(int id)
{
EnterCustomer enterCustomer = new EnterCustomer();
DistrictInfoBll dbll = new DistrictInfoBll();
if (id>0)
{
EnterCustomerBll bll = new EnterCustomerBll();
enterCustomer =await bll.GetAsync(id);
}
var ProvinceList = await dbll.GetAsync(0);
ViewBag.ProvinceList = ProvinceList;
ViewBag.root = "enter";
return View(enterCustomer);
}
/// <summary>
/// 企业客户详情
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<IActionResult> EnterCustomInfo(int id,int t=0)
{
EnterCustomerBll bll = new EnterCustomerBll();
EnterCustomer enterCustomer = await bll.GetAsync(id);
EnterCustContactsBll enterCustContactsBll = new EnterCustContactsBll();
List<EnterCustContacts> conlist =await enterCustContactsBll.GetListAsync(id);
ViewBag.conlist = conlist;
EnterCustPhaseLogBll logbll = new EnterCustPhaseLogBll();
List<EnterCustPhaseLog> loglist =await logbll.ListAsync(id);
ViewBag.loglist = loglist;
SalesProjectBll projectBll = new SalesProjectBll();
List<SalesProject> projectList =await projectBll.GetListAsync(id);
ViewBag.projectList = projectList;
Dictionary<int, double> recpayDic = new Dictionary<int, double>();
if (projectList != null && projectList.Count > 0)
{
ReceivedPaymentsLogBll rpbll = new ReceivedPaymentsLogBll();
foreach (var info in projectList)
{
var rplog = await rpbll.GetListAsync(info.ID);
if (rplog != null && rplog.Count > 0)
{
var rp = from log in rplog
select log.Amt;
recpayDic[info.ID] = rp.Sum();
}
}
}
ViewBag.recpayDic = recpayDic;
ViewBag.t = t;
return View(enterCustomer);
}
/// <summary>
/// 快速添加企业信息
/// </summary>
/// <returns></returns>
public async Task<IActionResult> AddEnterCustomQuick()
{
DistrictInfoBll dbll = new DistrictInfoBll();
var ProvinceList = await dbll.GetAsync(0);
ViewBag.ProvinceList = ProvinceList;
ViewBag.root = "enter";
return View();
}
/// <summary>
/// 校验企业名称是否已经存在
/// </summary>
/// <param name="id"></param>
/// <param name="EnterName"></param>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> ExistsEnterName(int id,string EnterName)
{
EnterCustomerBll bll = new EnterCustomerBll();
bool flag =await bll.ExistsEnterNameAsync(id,EnterName);
return Json(new { code = 1, result = flag });
}
[HttpPost]
public async Task<IActionResult> SaveEnterCustom()
{
EnterCustomerBll bll = new EnterCustomerBll();
int id = Request.Form["ID"].TryToInt(0);
EnterCustPhaseLogBll logbll = new EnterCustPhaseLogBll();
if (id > 0)
{
var info = await bll.GetAsync(id);
info.Address = Request.Form["Address"].TryToString();
info.City = Request.Form["City"].TryToString();
info.CustAbstract = Request.Form["CustAbstract"].TryToString();
info.CustomerType = (CustomerTypeEnum)Request.Form["CustomerType"].TryToInt(0);
info.DegreeOfHeat = (DegreeOfHeatEnume)Request.Form["DegreeOfHeat"].TryToInt(0);
info.Email = Request.Form["Email"].TryToString();
info.EnterName = Request.Form["EnterName"].TryToString();
info.FaxNumber = Request.Form["FaxNumber"].TryToString();
info.HeatMsg = Request.Form["HeatMsg"].TryToString();
info.HeatTYPE = (HeatTypeEnum)Request.Form["HeatTYPE"].TryToInt(0);
info.InvoiceMsg = Request.Form["InvoiceMsg"].TryToString();
info.IsHeat = Request.Form["IsHeat"].TryToString().Equals("on");
if (info.Phase != (PhaseEnume)Request.Form["Phase"].TryToInt(0))
{
info.Phase = (PhaseEnume)Request.Form["Phase"].TryToInt(0);
//EnterCustPhaseLog enterCustPhaseLog = new EnterCustPhaseLog();
//enterCustPhaseLog.CreateTime = DateTime.Now;
//enterCustPhaseLog.EnterCustomerID = id;
//enterCustPhaseLog.Phase = info.Phase;
//enterCustPhaseLog.UserID = User.ID;
//enterCustPhaseLog.UserName = User.Name;
//enterCustPhaseLog.Rem = "客户信息修改";
//await logbll.AddAsync(enterCustPhaseLog);
}
info.Province = Request.Form["Province"].TryToString();
info.Relationship = (RelationshipEnume)Request.Form["Relationship"].TryToInt(0);
info.Rem = Request.Form["Rem"].TryToString();
info.Source = (CustSource)Request.Form["Source"].TryToInt(0);
info.Telephone = Request.Form["Telephone"].TryToString();
info.UpdateTime = DateTime.Now;
info.ValueGrade = (ValueGradeEnume)Request.Form["ValueGrade"].TryToInt(0);
info.WebSit = Request.Form["WebSit"].TryToString();
info.ZipCode = Request.Form["ZipCode"].TryToString();
info.Landline = Request.Form["Landline"].TryToString();
bool flag = await bll.UpdateEnterCustomerAsync(info);
if (flag)
{
return Json(new { code = 1, msg = "OK",id= info.ID });
}
else
return Json(new { code = 0, msg = "保存失败" });
}
else
{
EnterCustomer info = new EnterCustomer();
info.Address = Request.Form["Address"].TryToString();
info.City = Request.Form["City"].TryToString();
info.CustAbstract = Request.Form["CustAbstract"].TryToString();
info.CustomerType = (CustomerTypeEnum)Request.Form["CustomerType"].TryToInt(0);
info.DegreeOfHeat = (DegreeOfHeatEnume)Request.Form["DegreeOfHeat"].TryToInt(0);
info.Email = Request.Form["Email"].TryToString();
info.EnterName = Request.Form["EnterName"].TryToString();
info.FaxNumber = Request.Form["FaxNumber"].TryToString();
info.HeatMsg = Request.Form["HeatMsg"].TryToString();
info.HeatTYPE = (HeatTypeEnum)Request.Form["HeatTYPE"].TryToInt(0);
info.InvoiceMsg = Request.Form["InvoiceMsg"].TryToString();
info.IsHeat = Request.Form["IsHeat"].TryToString().Equals("on");
info.Phase = (PhaseEnume)Request.Form["Phase"].TryToInt(0);
info.Province = Request.Form["Province"].TryToString();
info.Relationship = (RelationshipEnume)Request.Form["Relationship"].TryToInt(0);
info.Rem = Request.Form["Rem"].TryToString();
info.Source = (CustSource)Request.Form["Source"].TryToInt(0);
info.Telephone = Request.Form["Telephone"].TryToString();
info.UpdateTime = DateTime.Now;
info.ValueGrade = (ValueGradeEnume)Request.Form["ValueGrade"].TryToInt(0);
info.WebSit = Request.Form["WebSit"].TryToString();
info.ZipCode = Request.Form["ZipCode"].TryToString();
info.Landline = Request.Form["Landline"].TryToString();
info.CreateTime = DateTime.Now;
info.CreateUserID = User.ID;
info.State = StateEnum.Invalid;
info.UserID = User.ID;
id = await bll.AddEnterCustomer(info);
if (id>0)
{
//EnterCustPhaseLog enterCustPhaseLog = new EnterCustPhaseLog();
//enterCustPhaseLog.CreateTime = DateTime.Now;
//enterCustPhaseLog.EnterCustomerID = id;
//enterCustPhaseLog.Phase = info.Phase;
//enterCustPhaseLog.UserID = User.ID;
//enterCustPhaseLog.UserName = User.Name;
//enterCustPhaseLog.Rem = "客户信息录入";
//await logbll.AddAsync(enterCustPhaseLog);
return Json(new { code = 1, msg = "OK", id=id });
}
else
return Json(new { code = 0, msg = "保存失败" });
}
}
[HttpPost]
public async Task<IActionResult> SaveEnterAndCust()
{
EnterCustomerBll bll = new EnterCustomerBll();
EnterCustContactsBll enterCustContactsBll = new EnterCustContactsBll();
EnterCustomer info = new EnterCustomer();
info.Address = Request.Form["Address"].TryToString();
info.City = Request.Form["City"].TryToString();
info.CustAbstract = Request.Form["CustAbstract"].TryToString();
info.CustomerType = (CustomerTypeEnum)Request.Form["CustomerType"].TryToInt(0);
info.DegreeOfHeat = (DegreeOfHeatEnume)Request.Form["DegreeOfHeat"].TryToInt(0);
info.Email = Request.Form["Email"].TryToString();
info.EnterName = Request.Form["EnterName"].TryToString();
info.FaxNumber = Request.Form["FaxNumber"].TryToString();
info.HeatMsg = Request.Form["HeatMsg"].TryToString();
info.HeatTYPE = (HeatTypeEnum)Request.Form["HeatTYPE"].TryToInt(0);
info.InvoiceMsg = Request.Form["InvoiceMsg"].TryToString();
info.IsHeat = Request.Form["IsHeat"].TryToString().Equals("on");
info.Phase = (PhaseEnume)Request.Form["Phase"].TryToInt(0);
info.Province = Request.Form["Province"].TryToString();
info.Relationship = (RelationshipEnume)Request.Form["Relationship"].TryToInt(0);
info.Rem = Request.Form["Rem"].TryToString();
info.Source = (CustSource)Request.Form["Source"].TryToInt(0);
//info.Telephone = Request.Form["Telephone"].TryToString();
info.UpdateTime = DateTime.Now;
info.ValueGrade = (ValueGradeEnume)Request.Form["ValueGrade"].TryToInt(0);
info.WebSit = Request.Form["WebSit"].TryToString();
info.ZipCode = Request.Form["ZipCode"].TryToString();
//info.Landline = Request.Form["Landline"].TryToString();
info.CreateTime = DateTime.Now;
info.CreateUserID = User.ID;
info.State = StateEnum.Invalid;
info.UserID = User.ID;
EnterCustContacts enterCustContacts = new EnterCustContacts();
enterCustContacts.Address = Request.Form["Address"].TryToString();
enterCustContacts.Business = Request.Form["Business"].TryToString();
enterCustContacts.Department = Request.Form["Department"].TryToString();
enterCustContacts.Duties = Request.Form["Duties"].TryToString();
enterCustContacts.Email = Request.Form["Email"].TryToString();
enterCustContacts.Name = Request.Form["Name"].TryToString();
enterCustContacts.QQ = Request.Form["QQ"].TryToString();
enterCustContacts.Rem = Request.Form["Rem"].TryToString();
enterCustContacts.Sex = (SexEnum)Request.Form["Sex"].TryToInt();
enterCustContacts.Telephone = Request.Form["Telephone"].TryToString();
enterCustContacts.WeChart = Request.Form["WeChart"].TryToString();
enterCustContacts.Landline = Request.Form["Landline"].TryToString();
int id = await bll.AddEnterCustomer(info);
if (id>0)
{
enterCustContacts.EnterCustID = id;
await enterCustContactsBll.Add(enterCustContacts);
return Json(new { code = 1, msg = "OK",id = id });
}
return Json(new {code =0, msg = "OK"});
}
/// <summary>
/// 删除
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> DelEnter(int id)
{
EnterCustomerBll bll = new EnterCustomerBll();
bool flag = await bll.DelAsync(id);
if (flag)
return Json(new { code = 1, msg = "OK" });
return Json(new { code = 0, msg = "OK" });
}
/// <summary>
/// 回收
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> EnterCallback(int id)
{
EnterCustomerBll bll = new EnterCustomerBll();
var info =await bll.GetAsync(id);
if (info!=null)
{
info.UserID = 0;
bool flag = await bll.UpdateEnterCustomerAsync(info);
if (flag)
return Json(new { code = 1, msg = "OK" });
}
return Json(new { code = 0, msg = "OK" });
}
/// <summary>
/// 根据省份ID获取城市列表
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> GetCityList(int id)
{
DistrictInfoBll dbll = new DistrictInfoBll();
var citylist = await dbll.GetAsync(id);
return Json(new { code = 1, citylist = citylist });
}
public async Task<IActionResult> AddEnterCustContacts(int id,int EnterCustID,int type=0)
{
EnterCustContactsBll bll = new EnterCustContactsBll();
var info = await bll.GetAsync(id);
ViewBag.EnterCustID = EnterCustID;
ViewBag.root = "enter";
ViewBag.type = type;
return View(info);
}
/// <summary>
/// 保存企业联系人
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> SaveEnterCustContacts()
{
EnterCustContactsBll bll = new EnterCustContactsBll();
int ID = Request.Form["ID"].TryToInt();
if (ID > 0)
{
var info = await bll.GetAsync(ID);
if (info != null)
{
info.Address = Request.Form["Address"].TryToString();
info.Business = Request.Form["Business"].TryToString();
info.Department = Request.Form["Department"].TryToString();
info.Duties = Request.Form["Duties"].TryToString();
info.Email = Request.Form["Email"].TryToString();
info.EnterCustID = Request.Form["EnterCustID"].TryToInt();
info.Name = Request.Form["Name"].TryToString();
info.QQ = Request.Form["QQ"].TryToString();
info.Rem = Request.Form["Rem"].TryToString();
info.Sex = (SexEnum)Request.Form["Sex"].TryToInt();
info.Telephone = Request.Form["Telephone"].TryToString();
info.WeChart = Request.Form["WeChart"].TryToString();
info.Landline = Request.Form["Landline"].TryToString();
bool flag = await bll.UpdateAsync(info);
if (flag)
return Json(new { code = 1, msg = "OK" });
}
}
else
{
EnterCustContacts info = new EnterCustContacts();
info.Address = Request.Form["Address"].TryToString();
info.Business = Request.Form["Business"].TryToString();
info.Department = Request.Form["Department"].TryToString();
info.Duties = Request.Form["Duties"].TryToString();
info.Email = Request.Form["Email"].TryToString();
info.EnterCustID = Request.Form["EnterCustID"].TryToInt();
info.Name = Request.Form["Name"].TryToString();
info.QQ = Request.Form["QQ"].TryToString();
info.Rem = Request.Form["Rem"].TryToString();
info.Sex = (SexEnum)Request.Form["Sex"].TryToInt();
info.Telephone = Request.Form["Telephone"].TryToString();
info.WeChart = Request.Form["WeChart"].TryToString();
info.Landline = Request.Form["Landline"].TryToString();
int id = await bll.Add(info);
if (id > 0)
return Json(new { code = 1, msg = "OK" });
}
return Json(new { code = 0, msg = "保存失败" });
}
/// <summary>
/// 公共客户池
/// </summary>
/// <returns></returns>
public async Task<IActionResult> EnterPoolIndex()
{
DistrictInfoBll dbll = new DistrictInfoBll();
var ProvinceList = await dbll.GetAsync(0);
ViewBag.ProvinceList = ProvinceList;
int pageIndex = 1;
int pageSize = 20;
string EnterName = string.Empty;
CustomerTypeEnum? CustomerType = null;
RelationshipEnume? Relationship = null;
PhaseEnume? Phase = null;
ValueGradeEnume? ValueGrade = null;
CustSource? Source = null;
bool? IsHeat = null;
DegreeOfHeatEnume? DegreeOfHeat = null;
DateTime? UpdateTime = null;
string City = null;
string Province = null;
if (Request.Method=="POST")
{
pageIndex = Request.Form["page"].TryToInt(1);
EnterName = Request.Form["EnterName"].TryToString();
if (Request.Form["CustomerType"].TryToInt(0) > 0)
{
CustomerType = (CustomerTypeEnum)Request.Form["CustomerType"].TryToInt(0);
ViewBag.CustomerType = Request.Form["CustomerType"].TryToInt(0);
}
if (Request.Form["Relationship"].TryToInt(0) > 0)
{
Relationship = (RelationshipEnume)Request.Form["Relationship"].TryToInt(0);
ViewBag.Relationship = Request.Form["Relationship"].TryToInt(0);
}
if (Request.Form["Phase"].TryToInt(0) > 0)
{
Phase = (PhaseEnume)Request.Form["Phase"].TryToInt(0);
ViewBag.Phase = Request.Form["Phase"].TryToInt(0);
}
if (Request.Form["ValueGrade"].TryToInt(0) > 0)
{
ValueGrade = (ValueGradeEnume)Request.Form["ValueGrade"].TryToInt(0);
ViewBag.ValueGrade= Request.Form["ValueGrade"].TryToInt(0);
}
if (Request.Form["Source"].TryToInt(0) > 0)
{
Source = (CustSource)Request.Form["Source"].TryToInt(0);
ViewBag.Source= Request.Form["Source"].TryToInt(0);
}
if (!Request.Form["IsHeat"].TryToString().IsNull())
{
IsHeat = Request.Form["IsHeat"].TryToString() == "on";
ViewBag.IsHeat = IsHeat;
}
if (Request.Form["DegreeOfHeat"].TryToInt(0) > 0)
{
DegreeOfHeat = (DegreeOfHeatEnume)Request.Form["DegreeOfHeat"].TryToInt(0);
ViewBag.DegreeOfHeat = Request.Form["DegreeOfHeat"].TryToInt(0); ;
}
if (!Request.Form["Province"].TryToString().IsNull())
{
Province = Request.Form["Province"].TryToString();
ViewBag.Province = Request.Form["Province"].TryToString();
}
if (!Request.Form["City"].TryToString().IsNull())
{
City = Request.Form["City"].TryToString();
ViewBag.City= Request.Form["City"].TryToString();
}
if (Request.Form["UpdateTime"].TryToInt(0) > 0)
{
ViewBag.UpdateTime = Request.Form["UpdateTime"].TryToInt(0);
switch (Request.Form["UpdateTime"].TryToInt(0))
{
case 1:
UpdateTime = DateTime.Now.AddDays(-7);
break;
case 2:
UpdateTime = DateTime.Now.AddDays(-15);
break;
case 3:
UpdateTime = DateTime.Now.AddDays(-30);
break;
case 4:
UpdateTime = DateTime.Now.AddDays(-60);
break;
case 5:
UpdateTime = DateTime.Now.AddDays(-90);
break;
}
}
}
ViewBag.pageIndex = pageIndex;
ViewBag.EnterName = EnterName;
EnterCustomerBll bll = new EnterCustomerBll();
var list = await bll.GetAsync(pageIndex, pageSize, 0, EnterName, CustomerType, Relationship, Phase, ValueGrade, Source, IsHeat, DegreeOfHeat, Province, City, UpdateTime);
ViewBag.count = list.Item2;
ViewBag.root = "enter";
return View(list.Item1);
}
[HttpPost]
public async Task<IActionResult> EnterPoolList()
{
int pageIndex = Request.Form["page"].TryToInt(1);
int pageSize = 20;
string EnterName = Request.Form["EnterName"].TryToString();
CustomerTypeEnum? CustomerType = null;
if (Request.Form["CustomerType"].TryToInt(0) > 0)
{
CustomerType = (CustomerTypeEnum)Request.Form["CustomerType"].TryToInt(0);
}
RelationshipEnume? Relationship = null;
if (Request.Form["Relationship"].TryToInt(0) > 0)
Relationship = (RelationshipEnume)Request.Form["Relationship"].TryToInt(0);
PhaseEnume? Phase = null;
if (Request.Form["Phase"].TryToInt(0) > 0)
Phase = (PhaseEnume)Request.Form["Phase"].TryToInt(0);
ValueGradeEnume? ValueGrade = null;
if (Request.Form["ValueGrade"].TryToInt(0) > 0)
ValueGrade = (ValueGradeEnume)Request.Form["ValueGrade"].TryToInt(0);
CustSource? Source = null;
if (Request.Form["Source"].TryToInt(0) > 0)
Source = (CustSource)Request.Form["Source"].TryToInt(0);
bool? IsHeat = null;
if (!Request.Form["IsHeat"].TryToString().IsNull())
IsHeat = Request.Form["IsHeat"].TryToString() == "on";
DegreeOfHeatEnume? DegreeOfHeat = null;
if (Request.Form["DegreeOfHeat"].TryToInt(0) > 0)
DegreeOfHeat = (DegreeOfHeatEnume)Request.Form["DegreeOfHeat"].TryToInt(0);
string Province = null;
if (!Request.Form["Province"].TryToString().IsNull())
Province = Request.Form["Province"].TryToString();
string City = null;
if (!Request.Form["City"].TryToString().IsNull())
City = Request.Form["City"].TryToString();
DateTime? UpdateTime = null;
if (Request.Form["UpdateTime"].TryToInt(0) > 0)
{
switch (Request.Form["UpdateTime"].TryToInt(0))
{
case 1:
UpdateTime = DateTime.Now.AddDays(-7);
break;
case 2:
UpdateTime = DateTime.Now.AddDays(-15);
break;
case 3:
UpdateTime = DateTime.Now.AddDays(-30);
break;
case 4:
UpdateTime = DateTime.Now.AddDays(-60);
break;
case 5:
UpdateTime = DateTime.Now.AddDays(-90);
break;
}
}
EnterCustomerBll bll = new EnterCustomerBll();
var list = await bll.GetAsync(pageIndex, pageSize, 0, EnterName, CustomerType, Relationship, Phase, ValueGrade, Source, IsHeat, DegreeOfHeat, Province, City, UpdateTime);
ViewBag.count = list.Item2;
return View(list.Item1);
}
/// <summary>
/// 领用
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> UseEnterCust(int id)
{
EnterCustomerBll bll = new EnterCustomerBll();
var info = await bll.GetAsync(id);
if(info != null)
{
info.UserID = User.ID;
info.CreateTime = DateTime.Now;
bool flag =await bll.UpdateEnterCustomerAsync(info);
if (flag)
return Json(new { code = 1, msg = "OK" });
}
return Json(new { code = 0, msg = "OK" });
}
/// <summary>
/// 分配
/// </summary>
/// <param name="userid"></param>
/// <param name="eid"></param>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> DistrutionEc(int userid,int eid)
{
EnterCustomerBll bll = new EnterCustomerBll();
var info = await bll.GetAsync(eid);
if (info!=null)
{
info.UserID = userid;
bool flag = await bll.UpdateEnterCustomerAsync(info);
if (flag)
return Json(new { code = 1, msg = "OK" });
}
return Json(new { code = 0, msg = "OK" });
}
/// <summary>
/// 保存客户阶段日志
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> SaveEnterCustPhaseLog()
{
EnterCustPhaseLogBll bll = new EnterCustPhaseLogBll();
EnterCustPhaseLog log = new EnterCustPhaseLog();
log.CreateTime = DateTime.Now;
log.EnterCustomerID = Request.Form["EnterCustomerID"].TryToInt();
log.Phase = (PhaseEnume)Request.Form["Phase"].TryToInt(0);
log.Rem = Request.Form["Rem"].TryToString();
log.UserID = User.ID;
log.UserName = User.Name;
int id = await bll.AddAsync(log);
if (id>0)
{
EnterCustomerBll ebll = new EnterCustomerBll();
var info = await ebll.GetAsync(log.EnterCustomerID);
if (info!=null)
{
info.Phase = log.Phase;
info.UpdateTime = DateTime.Now;
await ebll.UpdateEnterCustomerAsync(info);
}
return Json(new { code = 1, msg = "OK" });
}
return Json(new { code = 0, msg = "保存失败" });
}
public async Task<IActionResult> EnterCustPhaseLogList(int id)
{
string EnterName = string.Empty;
List<EnterCustPhaseLog> LogList = null;
EnterCustomerBll bll = new EnterCustomerBll();
var info = await bll.GetAsync(id);
if (info != null)
{
EnterName = info.EnterName;
EnterCustPhaseLogBll logbll = new EnterCustPhaseLogBll();
LogList = await logbll.ListAsync(id);
}
ViewBag.EnterName = EnterName;
ViewBag.root = "enter";
return View(LogList);
}
/// <summary>
/// 销售项目首页
/// </summary>
/// <returns></returns>
public async Task<IActionResult> SalesProjectIndex()
{
string Title = string.Empty ;
if (Request.Method=="POST")
{
Title = Request.Form["Title"].TryToString();
}
ViewBag.Title = Title;
ProjectStateEnum? ProjectState = null;
ViewBag.ProjectState = 0;
if (Request.Method=="POST" && Request.Form["ProjectState"].TryToInt(0) > 0)
{
ProjectState = (ProjectStateEnum)Request.Form["ProjectState"].TryToInt();
ViewBag.ProjectState = Request.Form["ProjectState"].TryToInt();
}
ProjectTypeEnum? ProjectType = null;
ViewBag.ProjectType = 0;
if (Request.Method == "POST" && Request.Form["ProjectType"].TryToInt(0) > 0)
{
ProjectType = (ProjectTypeEnum)Request.Form["ProjectType"].TryToInt(0);
ViewBag.ProjectType = Request.Form["ProjectType"].TryToInt(0);
}
DateTime? ProjectStartTime = null;
ViewBag.ProjectStartTime = string.Empty;
if (Request.Method == "POST" && !Request.Form["ProjectStartTime"].TryToString().IsNull())
{
ProjectStartTime = Request.Form["ProjectStartTime"].TryToDateTime();
ViewBag.ProjectStartTime = Request.Form["ProjectStartTime"].TryToString();
}
DateTime? ProjectEndTime = null;
ViewBag.ProjectEndTime = string.Empty;
if (Request.Method == "POST" && !Request.Form["ProjectEndTime"].TryToString().IsNull())
{
ProjectEndTime = Request.Form["ProjectEndTime"].TryToDateTime();
ViewBag.ProjectEndTime = Request.Form["ProjectEndTime"].TryToString();
}
int pageIndex = 1;
if (Request.Method=="POST")
{
pageIndex = Request.Form["page"].TryToInt(1);
}
ViewBag.pageIndex = pageIndex;
int pageSize = 20;
SalesProjectBll bll = new SalesProjectBll();
List<EnterCustomer> enterlist = new List<EnterCustomer>();
var list = await bll.GetTupleAsync(pageIndex, pageSize, User.ID, Title, null, ProjectState, ProjectType, ProjectStartTime, ProjectEndTime);
if (list.Item1!=null)
{
EnterCustomerBll enterCustomerBll = new EnterCustomerBll();
foreach (var info in list.Item1)
{
var enter =await enterCustomerBll.GetAsync(info.EnterCustomerID);
if (enter!=null)
{
enterlist.Add(enter);
}
}
}
Dictionary<int, double> recpayDic = new Dictionary<int, double>();
if (list != null && list.Item1.Count > 0)
{
ReceivedPaymentsLogBll rpbll = new ReceivedPaymentsLogBll();
foreach (var info in list.Item1)
{
var rplog = await rpbll.GetListAsync(info.ID);
if (rplog != null && rplog.Count > 0)
{
var rp = from log in rplog
select log.Amt;
recpayDic[info.ID] = rp.Sum();
}
}
}
ViewBag.recpayDic = recpayDic;
ViewBag.enterlist = enterlist;
ViewBag.Count = list.Item2;
ViewBag.root = "sale";
return View(list.Item1);
}
[HttpPost]
public async Task<IActionResult> SalesProjectList()
{
string Title = Request.Form["Title"].TryToString();
ProjectStateEnum? ProjectState = null;
if (Request.Form["ProjectState"].TryToInt(0)>0)
{
ProjectState = (ProjectStateEnum)Request.Form["ProjectState"].TryToInt();
}
ProjectTypeEnum? ProjectType = null;
if (Request.Form["ProjectType"].TryToInt(0)>0)
{
ProjectType = (ProjectTypeEnum)Request.Form["ProjectType"].TryToInt(0);
}
DateTime? ProjectStartTime = null;
if (!Request.Form["ProjectStartTime"].TryToString().IsNull())
{
ProjectStartTime = Request.Form["ProjectStartTime"].TryToDateTime();
}
DateTime? ProjectEndTime = null;
if (!Request.Form["ProjectEndTime"].TryToString().IsNull())
{
ProjectEndTime = Request.Form["ProjectEndTime"].TryToDateTime();
}
int pageIndex = Request.Form["page"].TryToInt(1);
int pageSize = 20;
SalesProjectBll bll = new SalesProjectBll();
var list = await bll.GetTupleAsync(pageIndex, pageSize, User.ID,Title,null,ProjectState,ProjectType,ProjectStartTime,ProjectEndTime);
ViewBag.Count = list.Item2;
ViewBag.pageIndex = pageIndex;
return View(list.Item1);
}
/// <summary>
/// 添加销售项目
/// </summary>
/// <param name="EnterCustomerID"></param>
/// <returns></returns>
public async Task<IActionResult> AddSalesProject(int EnterCustomerID)
{
UserBll userBll = new UserBll();
var userlist = await userBll.GetListAsync();
ViewBag.userlist = userlist;
ViewBag.EnterCustomerID = EnterCustomerID;
ViewBag.root = "sale";
return View();
}
[HttpPost]
public async Task<IActionResult> SaveSalesProject()
{
SalesProject salesProject = new SalesProject();
salesProject.CreateTime = DateTime.Now;
salesProject.CreateUserID = User.ID;
salesProject.EnterCustomerID = Request.Form["EnterCustomerID"].TryToInt();
salesProject.HeadID = Request.Form["HeadID"].TryToInt();
salesProject.ProjectAbstract = Request.Form["ProjectAbstract"].TryToString();
salesProject.ProjectAmt = Request.Form["ProjectAmt"].TryToDouble();
salesProject.ProjectState = (ProjectStateEnum)Request.Form["ProjectState"].TryToInt(0);
salesProject.ProjectTime = Request.Form["ProjectTime"].TryToDateTime();
salesProject.ProjectType = (ProjectTypeEnum)Request.Form["ProjectType"].TryToInt(0);
salesProject.Title = Request.Form["Title"].TryToString();
salesProject.ReceoverPayTime = Request.Form["ReceoverPayTime"].TryToDateTime();
SalesProjectBll bll = new SalesProjectBll();
int id = await bll.AddAsync(salesProject);
if (id>0)
{
SalesProjectStateLog log = new SalesProjectStateLog();
log.UserName = User.UserName;
log.UserID = User.ID;
log.CreateTime = DateTime.Now;
log.ProjectState = salesProject.ProjectState;
log.Rem = "创建项目";
log.SalesProjectID = id;
SalesProjectStateLogBll salesProjectStateLogBll = new SalesProjectStateLogBll();
await salesProjectStateLogBll.AddAsync(log);
return Json(new { code = 1, msg = "OK" });
}
return Json(new { code = 0, msg = "保存失败" });
}
public IActionResult AddSalesProjectStateLog(int SalesProjectID)
{
ViewBag.SalesProjectID = SalesProjectID;
ViewBag.root = "sale";
return View();
}
[HttpPost]
public async Task<IActionResult> SaveSalesProjectStateLog()
{
SalesProjectStateLog log = new SalesProjectStateLog();
log.CreateTime = DateTime.Now;
log.ProjectState = (ProjectStateEnum)Request.Form["ProjectState"].TryToInt(0);
log.Rem = Request.Form["Rem"].TryToString();
log.SalesProjectID = Request.Form["SalesProjectID"].TryToInt(0);
log.UserID = User.ID;
log.UserName = User.Name;
SalesProjectStateLogBll bll = new SalesProjectStateLogBll();
int id = await bll.AddAsync(log);
if (id>0)
{
SalesProjectBll pbll = new SalesProjectBll();
var project = await pbll.GetAsync(log.SalesProjectID);
if (project!=null && project.ProjectState != log.ProjectState)
{
project.ProjectState = log.ProjectState;
await pbll.UpdateAsync(project);
}
return Json(new { code = 1, msg = "OK" });
}
return Json(new { code = 0, mes = "保存失败" });
}
/// <summary>
/// 销售项目状态变更时间线
/// </summary>
/// <param name="SalesProjectID"></param>
/// <returns></returns>
public async Task<IActionResult> GetSalesProjectStateLog(int SalesProjectID)
{
SalesProjectStateLogBll bll = new SalesProjectStateLogBll();
var list = await bll.GetListAsync(SalesProjectID);
SalesProjectBll pbll = new SalesProjectBll();
var project =await pbll.GetAsync(SalesProjectID);
string Title = string.Empty;
if (project!=null)
{
Title = project.Title;
}
ViewBag.name = Title;
ViewBag.root = "sale";
return View(list);
}
/// <summary>
/// 添加工作计划
/// </summary>
/// <param name="EnterCustID"></param>
/// <returns></returns>
public IActionResult AddWorkPlan(int EnterCustID)
{
ViewBag.EnterCustID = EnterCustID;
return View();
}
[HttpPost]
public async Task<IActionResult> SaveWorkPlan()
{
WorkPlan workPlan = new WorkPlan();
workPlan.CreateTime = DateTime.Now;
workPlan.EnterCustID = Request.Form["EnterCustID"].TryToInt(0);
workPlan.PlanContent = Request.Form["PlanContent"].TryToString();
workPlan.PlanTime = Request.Form["PlanTime"].TryToDateTime();
workPlan.UserID = User.ID;
workPlan.WorkPlanState = WorkPlanStateEnum.NoFinish;
WorkPlanBll bll = new WorkPlanBll();
int id = await bll.AddAsync(workPlan);
if(id>0)
return Json(new { code = 1, msg = "OK" });
return Json(new { code = 0, msg = "保存失败" });
}
/// <summary>
/// 工作计划
/// </summary>
/// <returns></returns>
public async Task<IActionResult> WorkPlanIndex(int pageIndex)
{
int pageSize = 30;
WorkPlanBll bll = new WorkPlanBll();
var list = await bll.TupleAsync(User.ID, pageIndex, pageSize);
ViewBag.count = list.Item2;
List<EnterCustomer> elist = new List<EnterCustomer>();
if (list != null && list.Item1.Count > 0)
{
EnterCustomerBll ebll = new EnterCustomerBll();
foreach (var info in list.Item1)
{
var e = await ebll.GetAsync(info.EnterCustID);
if (e != null)
{
elist.Add(e);
}
}
}
ViewBag.pageIndex = pageIndex;
ViewBag.elist = elist;
return View(list.Item1);
}
[HttpGet]
public async Task<IActionResult> FinishPlan(int id)
{
WorkPlanBll bll = new WorkPlanBll();
var workplan = await bll.GetAsync(id);
workplan.WorkPlanState = WorkPlanStateEnum.Finish;
await bll.UpdateAsync(workplan);
return Json(new { code = 1, msg = "OK" });
}
[HttpGet]
public async Task<IActionResult> DelPlan(int id)
{
WorkPlanBll bll = new WorkPlanBll();
var workplan = await bll.GetAsync(id);
if (workplan!=null)
{
await bll.DelAsync(workplan);
}
return Json(new { code = 1, msg = "OK" });
}
/// <summary>
/// 首页
/// </summary>
/// <returns></returns>
public async Task<IActionResult> ConsoleIndex()
{
EnterCustomerBll customerBll = new EnterCustomerBll();
SalesProjectBll salesProjectBll = new SalesProjectBll();
ViewBag.entercustomTotalToday = null; //今天客户数量
ViewBag.entercustomTotalWeek = null; // 本周客户数量
ViewBag.entercustomTotalMonth = null;// 本月客户数量
List<UserEnterReport> entercustomTotalToday = await customerBll.GetAsync(DateTime.Now.ToString("yyyy-MM-dd").TryToDateTime(), DateTime.Now.AddDays(1).ToString("yyyy-MM-dd").TryToDateTime(),User.ID);
List<UserEnterReport> entercustomTotalWeek = await customerBll.GetAsync(DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek+1).ToString("yyyy-MM-dd").TryToDateTime(), DateTime.Now.AddDays(1).ToString("yyyy-MM-dd").TryToDateTime(), User.ID);
List<UserEnterReport> entercustomTotalMonth = await customerBll.GetAsync(DateTime.Now.AddDays(-DateTime.Now.Day + 1).ToString("yyyy-MM-dd").TryToDateTime(), DateTime.Now.AddDays(1).ToString("yyyy-MM-dd").TryToDateTime(), User.ID);
if (entercustomTotalToday!=null && entercustomTotalToday.Count>0)
{
ViewBag.entercustomTotalToday = entercustomTotalToday.First();
}
if (entercustomTotalWeek!=null && entercustomTotalWeek.Count>0)
{
ViewBag.entercustomTotalWeek = entercustomTotalWeek.First();
}
if (entercustomTotalMonth!=null && entercustomTotalMonth.Count>0)
{
ViewBag.entercustomTotalMonth = entercustomTotalMonth[0];
}
ViewBag.projecttotalToday = 0; //今天成单数量
ViewBag.projecttotalWeek = 0; //本周成单数量
ViewBag.projecttotalMonth = 0; // 本月成单数量
var projectToday = await salesProjectBll.GetAsync(DateTime.Now.ToString("yyyy-MM-dd").TryToDateTime(), DateTime.Now.AddDays(1).ToString("yyyy-MM-dd").TryToDateTime(), User.ID);
if (projectToday!=null && projectToday.Count>0)
{
ViewBag.projecttotalToday = projectToday.First().Total;
}
var projectWeek = await salesProjectBll.GetAsync(DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek + 1).ToString("yyyy-MM-dd").TryToDateTime(), DateTime.Now.AddDays(1).ToString("yyyy-MM-dd").TryToDateTime(), User.ID);
if (projectWeek!=null && projectWeek.Count>0)
{
ViewBag.projecttotalWeek = projectWeek.First().Total;
}
var projectMonth = await salesProjectBll.GetAsync(DateTime.Now.AddDays(-DateTime.Now.Day + 1).ToString("yyyy-MM-dd").TryToDateTime(), DateTime.Now.AddDays(1).ToString("yyyy-MM-dd").TryToDateTime(), User.ID);
if (projectMonth!=null && projectMonth.Count>0)
{
ViewBag.projecttotalMonth = projectMonth.First().Total;
}
ViewBag.telphoneToday = 0;// 今天电话量
ViewBag.telphoneWeek = 0;// 本周电话量
ViewBag.telphoneMonth = 0;// 本月电话量
EnterCustPhaseLogBll phlogbll = new EnterCustPhaseLogBll();
var telphoneToday = await phlogbll.GetAsync(DateTime.Now.ToString("yyyy-MM-dd").TryToDateTime(), DateTime.Now.AddDays(1).ToString("yyyy-MM-dd").TryToDateTime(), User.ID);
if (telphoneToday!=null && telphoneToday.Count>0)
{
ViewBag.telphoneToday = telphoneToday.First().Total;
}
var telphoneWeek = await phlogbll.GetAsync(DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek + 1).ToString("yyyy-MM-dd").TryToDateTime(), DateTime.Now.AddDays(1).ToString("yyyy-MM-dd").TryToDateTime(), User.ID);
if (telphoneWeek!=null && telphoneWeek.Count>0)
{
ViewBag.telphoneWeek = telphoneWeek.First().Total;
}
var telphoneMonth = await phlogbll.GetAsync(DateTime.Now.AddDays(-DateTime.Now.Day + 1).ToString("yyyy-MM-dd").TryToDateTime(), DateTime.Now.AddDays(1).ToString("yyyy-MM-dd").TryToDateTime(), User.ID);
if (telphoneMonth!=null && telphoneMonth.Count>0)
{
ViewBag.telphoneMonth = telphoneMonth.First().Total;
}
ViewBag.ReceoverPay = 0;//本月应收账款
var projectlist =await salesProjectBll.GetListAsync(User.ID, DateTime.Now.AddDays(-DateTime.Now.Day + 1).ToString("yyyy-MM-dd").TryToDateTime(), DateTime.Now.AddDays(1).ToString("yyyy-MM-dd").TryToDateTime());
if (projectlist!=null && projectlist.Count>0)
{
var amtlist = from project in projectlist
select project.ProjectAmt;
if (amtlist!=null)
{
ViewBag.ReceoverPay = amtlist.Sum();
}
}
ViewBag.HReceoverPay = 0;// 本月已收账款
ReceivedPaymentsLogBll receivedPaymentsLogBll = new ReceivedPaymentsLogBll();
var receivedlist = await receivedPaymentsLogBll.GetListAsync(DateTime.Now.AddDays(-DateTime.Now.Day + 1).ToString("yyyy-MM-dd").TryToDateTime(), DateTime.Now.AddDays(1).ToString("yyyy-MM-dd").TryToDateTime(), User.ID);
if (receivedlist!=null)
{
var amtlist = from received in receivedlist
select received.Amt;
if (amtlist!=null)
{
ViewBag.HReceoverPay = amtlist.Sum();
}
}
ViewBag.TargetAmt = User.TargetAmt;
WorkPlanBll planbll = new WorkPlanBll();
List<EnterCustomer> enterlist = new List<EnterCustomer>();
var workplanlist = await planbll.ListAsync(User.ID);
if (workplanlist!=null)
{
foreach (var plan in workplanlist)
{
var enter =await customerBll.GetAsync(plan.EnterCustID);
if (enter != null)
enterlist.Add(enter);
}
}
ViewBag.workplanlist = workplanlist;
ViewBag.enterlist = enterlist;
ViewBag.root = "console";
int userid = User.ID;
if (User.UserName == "admin")
{
userid = 0;
}
DateTime startTime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd").TryToDateTime();
DateTime endTime = DateTime.Now.ToString("yyyy-MM-dd").TryToDateTime();
UserBll userBll = new UserBll();
List<UserInfo> userlist = await userBll.GetListAsync();
// 成单量统计
List<UserEnterReport> entercustomTotal = await salesProjectBll.GetAsync(startTime, endTime, 0);
// 客户量统计
List<UserEnterReport> customerTotal = await customerBll.GetAsync(startTime, endTime, 0);
//电话量统计
List<UserEnterReport> phonetotal = await phlogbll.GetAsync(startTime, endTime, 0);
List<UserReportViewModel> reportlist = new List<UserReportViewModel>();
// 应收账款
var ReceoverPayList = await salesProjectBll.GetListAsync(0, startTime, endTime);
var ReceivedPaymentsLogList = await receivedPaymentsLogBll.GetListAsync(startTime, endTime, 0);
if (userlist != null)
{
foreach (var user in userlist)
{
UserReportViewModel userReportView = new UserReportViewModel();
if (customerTotal != null && customerTotal.Count > 0)
{
var customer = customerTotal.FirstOrDefault(x => x.UserID == user.ID);
if (customer != null)
{
userReportView.CustomorTotal = customer.Total;
}
}
if (entercustomTotal != null && entercustomTotal.Count > 0)
{
var enter = entercustomTotal.FirstOrDefault(x => x.UserID == user.ID);
if (enter != null)
{
userReportView.SalesProjectTotal = enter.Total;
}
}
if (phonetotal != null && phonetotal.Count > 0)
{
var phone = phonetotal.FirstOrDefault(x => x.UserID == user.ID);
if (phone != null)
{
userReportView.PhoneTotal = phone.Total;
}
}
userReportView.UserID = user.ID;
userReportView.UserName = user.Name;
userReportView.TargetAmt = user.TargetAmt;
if (ReceoverPayList != null && ReceoverPayList.Count > 0)
{
var rlist = from rpay in ReceoverPayList
where rpay.HeadID == user.ID
select rpay.ProjectAmt;
if (rlist != null)
userReportView.ReceoverPay = rlist.Sum();
}
if (ReceivedPaymentsLogList != null && ReceivedPaymentsLogList.Count > 0)
{
var rplist = from rplog in ReceivedPaymentsLogList
where rplog.UserID == user.ID
select rplog.Amt;
if (rplist != null)
userReportView.HReceoverPay = rplist.Sum();
}
reportlist.Add(userReportView);
}
}
ViewBag.reportlist = reportlist;
bool isadmin = false;
if (User.UserName == "admin")
isadmin = true;
ViewBag.isadmin = isadmin;
return View();
}
/// <summary>
/// 昨天的客户信息
/// </summary>
/// <param name="userid"></param>
/// <returns></returns>
public async Task<IActionResult> CustomorTotalList(int userid)
{
DateTime startTime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd").TryToDateTime();
DateTime endTime = DateTime.Now.ToString("yyyy-MM-dd").TryToDateTime();
EnterCustomerBll enterCustomerBll = new EnterCustomerBll();
var list = await enterCustomerBll.ListAsync(startTime,endTime, userid);
return View(list);
}
public async Task<IActionResult> CustomorTotalLReport(string startTime, string endTime, int userid)
{
EnterCustomerBll enterCustomerBll = new EnterCustomerBll();
var list = await enterCustomerBll.ListAsync(startTime.TryToDateTime(), endTime.TryToDateTime(), userid);
return View(list);
}
/// <summary>
/// 昨天电话信息
/// </summary>
/// <param name="userid"></param>
/// <returns></returns>
public async Task<IActionResult> PhoneTotalList(int userid)
{
DateTime startTime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd").TryToDateTime();
DateTime endTime = DateTime.Now.ToString("yyyy-MM-dd").TryToDateTime();
EnterCustPhaseLogBll phlogbll = new EnterCustPhaseLogBll();
var list = await phlogbll.ListAsync(startTime,endTime,userid);
List<EnterCustomer> enlist = new List<EnterCustomer>();
if (list!=null)
{
EnterCustomerBll bll = new EnterCustomerBll();
foreach (var log in list)
{
EnterCustomer ec =await bll.GetAsync(log.EnterCustomerID);
if (ec!=null)
{
enlist.Add(ec);
}
}
}
ViewBag.enlist = enlist;
return View(list);
}
public async Task<IActionResult> PhoneTotalReport(int userid,string startTime, string endTime)
{
EnterCustPhaseLogBll phlogbll = new EnterCustPhaseLogBll();
var list = await phlogbll.ListAsync(startTime.TryToDateTime(), endTime.TryToDateTime(), userid);
List<EnterCustomer> enlist = new List<EnterCustomer>();
if (list != null)
{
EnterCustomerBll bll = new EnterCustomerBll();
foreach (var log in list)
{
EnterCustomer ec = await bll.GetAsync(log.EnterCustomerID);
if (ec != null)
{
enlist.Add(ec);
}
}
}
ViewBag.enlist = enlist;
return View(list);
}
/// <summary>
/// 添加回款记录
/// </summary>
/// <param name="SalesProjectID"></param>
/// <returns></returns>
public IActionResult AddReceovedPayLog(int SalesProjectID)
{
ViewBag.SalesProjectID = SalesProjectID;
ViewBag.root = "sale";
return View();
}
[HttpPost]
public async Task<IActionResult> SaveReceovedPayLog()
{
ReceivedPaymentsLog log = new ReceivedPaymentsLog();
log.Amt = Request.Form["Amt"].TryToDouble();
log.CreateTime = DateTime.Now;
log.Rem = Request.Form["Rem"].TryToString();
log.SalesProjectID = Request.Form["SalesProjectID"].TryToInt();
log.UserID = User.ID;
ReceivedPaymentsLogBll bll = new ReceivedPaymentsLogBll();
int id = await bll.AddAsync(log);
SalesProjectBll salesProjectBll = new SalesProjectBll();
if (id > 0)
{
var project = await salesProjectBll.GetAsync(log.SalesProjectID);
project.ReceoverPay = project.ReceoverPay + log.Amt;
await salesProjectBll.UpdateAsync(project);
return Json(new { code = 1, msg = "OK" });
}
return Json(new { code = 0, msg = "保存失败" });
}
/// <summary>
/// 本月应收账款的项目
/// </summary>
/// <returns></returns>
public async Task<IActionResult> ProjectAmtList()
{
SalesProjectBll salesProjectBll = new SalesProjectBll();
List<EnterCustomer> enterlist = new List<EnterCustomer>();
var list = await salesProjectBll.GetListAsync(User.ID, DateTime.Now.AddDays(-DateTime.Now.Day + 1).ToString("yyyy-MM-dd").TryToDateTime(), DateTime.Now.AddDays(1).ToString("yyyy-MM-dd").TryToDateTime());
if (list!=null && list.Count>0)
{
EnterCustomerBll bll = new EnterCustomerBll();
foreach (var project in list)
{
var info =await bll.GetAsync(project.EnterCustomerID);
enterlist.Add(info);
}
}
ViewBag.enterlist = enterlist;
return View(list);
}
/// <summary>
/// 本月已经已收账款明细
/// </summary>
/// <returns></returns>
public async Task<IActionResult> ReceovedPayLogList()
{
ReceivedPaymentsLogBll bll = new ReceivedPaymentsLogBll();
var list =await bll.GetListAsync(DateTime.Now.AddDays(-DateTime.Now.Day + 1).ToString("yyyy-MM-dd").TryToDateTime(), DateTime.Now.AddDays(1).ToString("yyyy-MM-dd").TryToDateTime(), User.ID);
List<SalesProject> projectlist = new List<SalesProject>();
if (list!=null && list.Count>0)
{
SalesProjectBll salesProjectBll = new SalesProjectBll();
foreach (var info in list)
{
SalesProject salesProject =await salesProjectBll.GetAsync(info.SalesProjectID);
if (salesProject!=null)
{
projectlist.Add(salesProject);
}
}
}
ViewBag.projectlist = projectlist;
return View(list);
}
/// <summary>
/// 设置月到账目标金额
/// </summary>
/// <param name="amt"></param>
/// <returns></returns>
public async Task<IActionResult> SetAmtTarget(double amt)
{
User.TargetAmt = amt;
UserBll bll = new UserBll();
await bll.Update(User);
return Json(new { code = 1, msg = "OK" });
}
public async Task<IActionResult> AddEnterCustPhaseLog(int id,int types=0)
{
EnterCustomerBll customerBll = new EnterCustomerBll();
var enter = await customerBll.GetAsync(id);
ViewBag.types = types;
return View(enter);
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace CursoCsharp.Colecoes
{
class IgualdadeEqualseGetHashCode
{
public static void Executar()
{
var p1 = new Produto("Caneta", 1.89);
var p2 = new Produto("Caneta", 1.89);
var p3 = p2;
//comparação por mememorias diferentes
Console.WriteLine("p1 é igual a p2? " + (p1 == p2)); // não sera igual, pq é armazenado em memorias diferentes.
Console.WriteLine("P3 é igual a p2? " + (p3 == p2) + " é igual pq usa a mesma referencia.");
//Continuacao no List
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mojang.Minecraft.Protocol.Providers;
namespace Mojang.Minecraft
{
public class EntityProperty : IPackageField
{
public string Key { get; set; }
public double Value { get; set; }
public Modifier[] Modifiers { get; set; }
void IPackageField.AppendIntoField(FieldMaker fieldMaker)
{
throw new NotImplementedException();
}
void IPackageField.FromField(FieldMatcher fieldMatcher)
{
Key = fieldMatcher.MatchPackageField<PString>();
Value = fieldMatcher.MatchMetaType<double>();
int listLength = fieldMatcher.MatchPackageField<VarInt>();
var modifierList = new List<Modifier>();
for (var i = 0; i < listLength; i++)
{
var currentModifier = new Modifier();
currentModifier.Uuid = fieldMatcher.MatchMetaType<Uuid>();
currentModifier.Amount = fieldMatcher.MatchMetaType<double>();
currentModifier.Operation = fieldMatcher.MatchMetaType<byte>();
modifierList.Add(currentModifier);
}
Modifiers = modifierList.ToArray();
}
}
public struct Modifier
{
public Uuid Uuid;
public double Amount;
public byte Operation;
}
}
|
namespace classicSortingAlgorithms.SortingClasses {
using System.Collections.Generic;
using System.Diagnostics;
class BubbleSorting<T> : Sort<T> {
public override string ClassName { get; set; } = "Bubble";
public override T[] Sorting(T[] array) {
bool isSorted = false;
int lastUnsorted = array.Length - 1;
while (!isSorted) {
isSorted = true;
for (int i = 0; i < lastUnsorted; i++) {
if (Comparer.Compare(array[i], array[i + 1]) == 1) {
Swap(array, i, i + 1);
isSorted = false;
}
}
lastUnsorted--;
}
return array;
}
public BubbleSorting(T[] array, IComparer<T> comparer) : base(array) {
Comparer = comparer;
}
public BubbleSorting(IComparer<T> comparer) : base() {
Comparer = comparer;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MonsterSpawner : MonoBehaviour
{
public GameObject[] Monsters;
private int SelectedMonster;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("SpawnMonster", 5f, 5f);
}
private void SpawnMonster()
{
SelectedMonster = Random.Range(0, 3);
if (SelectedMonster == 3)
{
GameObject.Instantiate(Monsters[Monsters.Length - 1],transform);
}
else
{
GameObject.Instantiate(Monsters[0],transform);
}
}
}
|
using Vlc.DotNet.Core.Interops.Signatures;
namespace Vlc.DotNet.Core.Interops
{
public sealed partial class VlcManager
{
/// <summary>
/// Sets the application name.
/// LibVLC passes this as the user agent string when a protocol requires it.
/// </summary>
/// <param name="name">human-readable application name, e.g. "FooBar player 1.2.3"</param>
/// <param name="http">HTTP User Agent, e.g. "FooBar/1.2.3 Python/2.6.0"</param>
public void SetUserAgent(string name, string http)
{
using (var nameInterop = Utf8InteropStringConverter.ToUtf8StringHandle(name))
using (var httpInterop = Utf8InteropStringConverter.ToUtf8StringHandle(http))
{
myLibraryLoader.GetInteropDelegate<SetUserAgent>().Invoke(this.myVlcInstance, nameInterop, httpInterop);
}
}
}
}
|
using System;
namespace _5_Const
{
static class Math
{
public const double PI = 3.14159;
public const double E = 2.71828;
public static double Square(double x)
{
return x * x;
}
public static double Add(double a, double b)
{
return a + b;
}
}
class Program
{
static void Main(string[] args)
{
// We don't want to have a separate instance for every
// single time we use the Math class, so we make it static.
Console.WriteLine(Math.Square(Math.E));
Console.WriteLine(Math.Add(Math.E, Math.PI));
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
namespace Profiling2.Web.Mvc.Areas.Profiling.Controllers.ViewModels
{
public class AdminSuggestionPersonResponsibilityViewModel
{
[Required(ErrorMessage = "A person is required.")]
[Range(1, int.MaxValue, ErrorMessage = "A valid person is required.")]
public int? PersonId { get; set; }
[Required(ErrorMessage = "An event is required.")]
[Range(1, int.MaxValue, ErrorMessage = "A valid event is required.")]
public int? EventId { get; set; }
public bool IsAccepted { get; set; }
public string SuggestionFeatures { get; set; }
public DateTime DecisionDateTime { get; set; }
public int DecisionAdminUserId { get; set; }
public bool Archive { get; set; }
public string Notes { get; set; }
}
} |
namespace com.Sconit.Service.Impl
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.Services.Transaction;
using com.Sconit.Entity;
using com.Sconit.Entity.ACC;
using com.Sconit.Entity.Exception;
using com.Sconit.Entity.ISS;
using com.Sconit.Entity.SYS;
using com.Sconit.Utility;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.Type;
[Transactional]
public class IssueMgrImpl : BaseMgr, IIssueMgr
{
#region 变量
private static log4net.ILog log = log4net.LogManager.GetLogger("DebugLog");
public IGenericMgr genericMgr { get; set; }
public ISystemMgr systemMgr { get; set; }
public IQueryMgr queryMgr { get; set; }
public INumberControlMgr numberControlMgr { get; set; }
public IIssueLogMgr issueLogMgr { get; set; }
#endregion
#region public methods
[Transaction(TransactionMode.Requires)]
public void DeleteIssueTypeTo(string code)
{
IssueTypeToMaster issueTypeToMaster = genericMgr.FindById<IssueTypeToMaster>(code);
if (issueTypeToMaster != null)
{
string hql = string.Empty;
hql = "delete from IssueTypeToUserDetail where IssueTypeTo = ?";
genericMgr.Update(hql, issueTypeToMaster.Code, NHibernateUtil.String);
hql = "delete from IssueTypeToRoleDetail where IssueTypeTo = ?";
genericMgr.Update(hql, issueTypeToMaster.Code, NHibernateUtil.String);
hql = "delete from IssueTypeToMaster where Code = ?";
genericMgr.Update(hql, issueTypeToMaster.Code, NHibernateUtil.String);
}
else
{
throw new BusinessException(Resources.ISS.IssueMaster.NotFound, code);
}
}
[Transaction(TransactionMode.Unspecified)]
public IList<IssueMaster> GetIssueMasterByIssueAddress(string issueAddress)
{
DetachedCriteria criteria = DetachedCriteria.For(typeof(IssueMaster));
criteria.Add(Expression.Eq("IssueAddress.Id", issueAddress));
return this.queryMgr.FindAll<IssueMaster>(criteria);
}
[Transaction(TransactionMode.Requires)]
public void Create(IssueMaster issue)
{
#region 创建IssueMaster
issue.Status = com.Sconit.CodeMaster.IssueStatus.Create;
issue.Code = numberControlMgr.GetIssueNo(issue);
this.genericMgr.Create(issue);
if (issue.ReleaseIssue)
{
this.Release(issue);
}
#endregion
}
public void Release(string code)
{
IssueMaster issue = this.genericMgr.FindById<IssueMaster>(code);
this.Release(issue);
}
private IssueLevel GetDefaultIssueLevel()
{
IList<IssueLevel> issueLevelList = this.genericMgr.FindAll<IssueLevel>("from IssueLevel where isDefault = true ");
if (issueLevelList != null && issueLevelList.Count > 0)
{
return issueLevelList[0];
}
else
{
return null;
}
}
[Transaction(TransactionMode.Requires)]
public void Start(string id, string finishedUserCode, DateTime? finishedDate, string solution)
{
IssueMaster issue = this.genericMgr.FindById<IssueMaster>(id);
if (issue.Status == com.Sconit.CodeMaster.IssueStatus.Submit)
{
issue.FinishedUserCode = finishedUserCode;
issue.Solution = solution;
if (finishedDate.HasValue)
{
issue.FinishedDate = finishedDate;
}
issue.StartDate = DateTime.Now;
User user = SecurityContextHolder.Get();
issue.StartUser = user.Id;
issue.StartUserName = user.FullName;
issue.Status = com.Sconit.CodeMaster.IssueStatus.InProcess;
this.genericMgr.Update(issue);
//发送给计划完成人
if (!string.IsNullOrWhiteSpace(finishedUserCode))
{
IList<User> userList = this.genericMgr.FindAll<User>("from User where code ='" + finishedUserCode.Trim() + "'");
if (userList != null && userList.Count > 0)
{
}
}
}
else
{
throw new BusinessException(Resources.ISS.IssueMaster.Errors_StatusErrorWhenStart, new string[] { issue.Status.ToString(), issue.Code });
}
}
[Transaction(TransactionMode.Requires)]
public void Release(IssueMaster issue)
{
//try
//{
IssueLevel issueLevel = this.GetDefaultIssueLevel();
if (issueLevel == null)
{
throw new BusinessException(Resources.ISS.IssueMaster.Errors_DefaultLevelNotFound, issue.IssueType.Code);
}
if (issue.Status == com.Sconit.CodeMaster.IssueStatus.Create)
{
User user = SecurityContextHolder.Get();
issue.Status = com.Sconit.CodeMaster.IssueStatus.Submit;
issue.ReleaseDate = DateTime.Now;
issue.ReleaseUser = user.Id;
issue.ReleaseUserName = user.FullName;
this.genericMgr.Update(issue);
#region 创建IssueDetail
#region 用户
string hql = "select ittud from IssueTypeToUserDetail ittud ";
hql += " join ittud.IssueTypeTo ittm ";
hql += " join ittm.IssueLevel il ";
hql += " join ittm.IssueType it ";
hql += " join ittud.User u ";
hql += " where ((ittud.IsEmail = true and u.Email is not null and u.Email != '') ";
hql += " or (ittud.IsSMS = true and u.MobilePhone is not null and u.MobilePhone != '')) ";
hql += " and il.IsActive = true and ittm.IsActive = true ";
hql += " and ittud.IssueTypeTo=ittm.Code and it.Code =? ";
hql += " order by il.Sequence asc ";
IList<IssueTypeToUserDetail> issueTypeToUserDetailList = this.genericMgr.FindAll<IssueTypeToUserDetail>(hql, issue.IssueTypeCode);
IList<IssueDetail> submitSendUser = new List<IssueDetail>();
foreach (IssueTypeToUserDetail issueTypeToUserDetail in issueTypeToUserDetailList)
{
IssueDetail issueDeatail = new IssueDetail();
issueDeatail.User = issueTypeToUserDetail.User;
//issueDeatail.UserName = issueTypeToUserDetail.User.FullName;
issueDeatail.MobilePhone = issueTypeToUserDetail.User.MobilePhone;
issueDeatail.Email = issueTypeToUserDetail.User.Email;
issueDeatail.IsActive = true;
issueDeatail.EmailCount = 0;
issueDeatail.SMSCount = 0;
issueDeatail.EmailStatus = com.Sconit.CodeMaster.SendStatus.NotSend;
issueDeatail.SMSStatus = com.Sconit.CodeMaster.SendStatus.NotSend;
issueDeatail.IssueLevel = issueTypeToUserDetail.IssueTypeTo.IssueLevel.Code;
issueDeatail.IsInProcess = issueTypeToUserDetail.IssueTypeTo.IssueLevel.IsInProcess;
issueDeatail.IsSubmit = issueTypeToUserDetail.IssueTypeTo.IssueLevel.IsSubmit;
issueDeatail.IsDefault = issueTypeToUserDetail.IssueTypeTo.IssueLevel.IsDefault;
issueDeatail.IssueCode = issue.Code;
issueDeatail.IsSMS = issueTypeToUserDetail.IsSMS;
issueDeatail.IsEmail = issueTypeToUserDetail.IsEmail;
issueDeatail.Sequence = issueTypeToUserDetail.IssueTypeTo.IssueLevel.Sequence;
issueDeatail.IssueTypeToUserDetailId = issueTypeToUserDetail.Id;
this.genericMgr.Create(issueDeatail);
if (issueDeatail.IsDefault)
{
submitSendUser.Add(issueDeatail);
}
}
#endregion
#region 角色 暂不支持
#endregion
#endregion
this.SendMailAndSMS(issue, issueLevel, submitSendUser);
}
else
{
throw new BusinessException(Resources.ISS.IssueMaster.Errors_StatusErrorWhenRelease, issue.Code, systemMgr.GetCodeDetailDescription(com.Sconit.CodeMaster.CodeMaster.IssueStatus, ((int)issue.Status).ToString()));
}
//}
//catch (Exception e)
//{
// log.Error(e.Message, e);
//}
}
[Transaction(TransactionMode.Requires)]
private void SendMailAndSMS(IssueMaster issue, IssueLevel level, IList<IssueDetail> issueDetailList)
{
try
{
if (issueDetailList == null || issueDetailList.Count == 0)
{
throw new BusinessException(Resources.ISS.IssueMaster.EmailListIsNull);
}
SendEmail(issue, level.Code, ref issueDetailList);
SendSMS(issue, level.Code, ref issueDetailList);
foreach (IssueDetail issueDetail in issueDetailList)
{
if (issueDetail.SMSStatus != com.Sconit.CodeMaster.SendStatus.Fail)
{
issueDetail.SMSStatus = com.Sconit.CodeMaster.SendStatus.Success;
issueLogMgr.LogInfo(issue.Code, issueDetail, issue.Content);
}
issueDetail.SMSCount = issueDetail.SMSCount + 1;
if (issueDetail.EmailStatus != com.Sconit.CodeMaster.SendStatus.Fail)
{
issueDetail.EmailStatus = com.Sconit.CodeMaster.SendStatus.Success;
issueLogMgr.LogInfo(issue.Code, issueDetail, issue.Content);
}
issueDetail.EmailCount = issueDetail.EmailCount + 1;
this.genericMgr.Update(issueDetail);
}
}
catch (Exception e)
{
issueLogMgr.LogError(issue.Code, e.Message);
}
}
[Transaction(TransactionMode.Requires)]
private string GetMobilePhone(string issueCode, ref IList<IssueDetail> issueDetailList)
{
StringBuilder mobilePhone = new StringBuilder();
try
{
foreach (IssueDetail issueDetail in issueDetailList)
{
User u = issueDetail.User;
if (u != null)
{
if (ControlHelper.IsValidMobilePhone(u.MobilePhone))
{
mobilePhone.Append(u.MobilePhone);
mobilePhone.Append(";");
issueDetail.MobilePhone = u.MobilePhone;
}
else
{
issueDetail.SMSStatus = com.Sconit.CodeMaster.SendStatus.Fail;
issueLogMgr.LogWarn(issueDetail.IssueCode, issueDetail, Resources.ISS.IssueLog.MobilePhoneIsInvalid);
}
}
}
}
catch (Exception e)
{
issueLogMgr.LogWarn(issueCode, e.Message);
}
return mobilePhone.ToString();
}
[Transaction(TransactionMode.Requires)]
private void SendSMS(IssueMaster issue, string level, ref IList<IssueDetail> issueDetailList)
{
string body = GetSMSBody(issue, level);
string toMobilePhone = GetMobilePhone(issue.Code, ref issueDetailList);
if (toMobilePhone != string.Empty && body != string.Empty)
{
//SMSService smsService = new SMSService();
//smsService.AsyncSend(toMobilePhone, body);
//smsMgr.AsyncSend(toMobilePhone, body);
}
else
{
issueLogMgr.LogError(issue.Code, null, "Issue.Code:" + issue.Code + ",toMobilePhone:" + toMobilePhone + ", body:" + body);
throw new BusinessException(Resources.ISS.IssueMaster.ParamsIsNull, new string[] { issue.Code, toMobilePhone, body });
}
}
[Transaction(TransactionMode.Requires)]
private void SendEmail(IssueMaster issue, string level, ref IList<IssueDetail> issueDetailList)
{
try
{
//string userMail = string.Empty;
//if (issue.Email != null && ControlHelper.IsValidEmail(issue.Email))
//{
// if (issue.UserName != null && issue.UserName.Length > 0)
// {
// userMail = issue.UserName + "," + issue.Email;
// }
// else
// {
// userMail = issue.Email;
// }
//}
//else
//{
// userMail = systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.SMTPEmailAddr);
//}
//string toEmail = GetEmail(issue.Code, ref issueDetailList);
//string body = GetEmailBody(issue, level);
//string subject = string.Empty;
//if (issue.Priority == com.Sconit.CodeMaster.IssuePriority.Urgent)
//{
// subject = systemMgr.GetCodeDetailDescription(com.Sconit.CodeMaster.CodeMaster.IssuePriority, ((int)com.Sconit.CodeMaster.IssuePriority.Urgent).ToString()) + " " + issue.IssueSubject;
//}
//else
//{
// subject = issue.IssueSubject;
//}
//MailPriority mailPriority;
//if (issue.Priority == com.Sconit.CodeMaster.IssuePriority.Urgent)
//{
// mailPriority = MailPriority.High;
//}
//else
//{
// mailPriority = MailPriority.Normal;
//}
//#region email发送
//EmailService emailService = new EmailService();
//emailService.AsyncSend(subject, body, toEmail, mailPriority);
////smsMgr.SendEmail(subject, body, toEmail, userMail, mailPriority);
//#endregion
}
catch (Exception e)
{
log.Error(e.Message, e);
}
}
[Transaction(TransactionMode.Requires)]
private string GetEmail(string issueCode, ref IList<IssueDetail> issueDetailList)
{
StringBuilder email = new StringBuilder();
try
{
foreach (IssueDetail issueDetail in issueDetailList)
{
User u = issueDetail.User;
if (u != null)
{
if (ControlHelper.IsValidEmail(u.Email))
{
email.Append(u.Email);
email.Append(";");
issueDetail.Email = u.Email;
}
else
{
issueDetail.EmailStatus = com.Sconit.CodeMaster.SendStatus.Fail;
issueLogMgr.LogWarn(issueDetail.IssueCode, issueDetail, Resources.ISS.IssueLog.EmailAddressIsInvalid);
}
}
}
}
catch (Exception e)
{
issueLogMgr.LogWarn(issueCode, e.Message);
}
return email.ToString();
}
[Transaction(TransactionMode.Unspecified)]
public string GetEmailBody(IssueMaster issue, string level)
{
return this.GetBody(issue, level, true);
}
[Transaction(TransactionMode.Unspecified)]
public string GetSMSBody(IssueMaster issue, string level)
{
return this.GetBody(issue, level, false);
}
[Transaction(TransactionMode.Unspecified)]
public string GetBody(IssueMaster issue, string level, bool isEmail)
{
string separator = string.Empty;
if (isEmail)
{
separator = "<br>";
}
else
{
separator = "\r\n";
}
StringBuilder content = new StringBuilder();
try
{
if (isEmail)
{
content.Append(Resources.ISS.IssueMaster.Code + ": " + issue.Code);
content.Append(separator);
}
content.Append(Resources.ISS.IssueMaster.BackYards + ": " + issue.BackYards);
content.Append(separator);
content.Append(Resources.ISS.IssueMaster.IssueSubject + ": " + issue.IssueSubject);
if (issue.Status == com.Sconit.CodeMaster.IssueStatus.Submit)
{
TimeSpan now = new TimeSpan(DateTime.Now.Ticks);
TimeSpan ReleaseDate = new TimeSpan(issue.ReleaseDate.Value.Ticks);
TimeSpan diff = now.Subtract(ReleaseDate).Duration();
if (diff.Hours > 0)
{
content.Append("(" + Resources.ISS.IssueMaster.ConfirmOvertime + " " + diff.Hours + "小时)");
}
}
else if (issue.Status == com.Sconit.CodeMaster.IssueStatus.InProcess)
{
TimeSpan now = new TimeSpan(DateTime.Now.Ticks);
TimeSpan inprocessDate = new TimeSpan(issue.StartDate.Value.Ticks);
TimeSpan diff = now.Subtract(inprocessDate).Duration();
if (diff.Hours > 0)
{
content.Append("(" + Resources.ISS.IssueMaster.CompleteOvertime + " " + diff.Hours + "小时)");
}
}
if (issue.Priority == com.Sconit.CodeMaster.IssuePriority.Urgent)
{
content.Append("[" + systemMgr.GetCodeDetailDescription(com.Sconit.CodeMaster.CodeMaster.IssuePriority, ((int)com.Sconit.CodeMaster.IssuePriority.Urgent).ToString()) + "]");
}
content.Append(separator);
content.Append(Resources.ISS.IssueMaster.DateTime + ": " + DateTime.Now + separator);
if (isEmail || issue.IssueAddress != null)
{
content.Append(Resources.ISS.IssueMaster.IssueAddress + ": ");
content.Append(issue.IssueAddress != null ? issue.IssueAddress : string.Empty);
content.Append(separator);
}
content.Append(Resources.ISS.IssueMaster.IssueType + ": " + issue.IssueType.Code + separator);
if (issue.IssueNo != null)
{
content.Append(Resources.ISS.IssueMaster.IssueNo + ": " + issue.IssueNo.Code + separator);
}
/*
if (level != null && level.Length > 0)
content.Append("等级: " + codeMasterMgrE.GetCachedCodeMaster(BusinessConstants.CODE_MASTER_ISSUE_TYPE_TO_LEVEL, level).Description + separator);
content.Append("状态: " + codeMasterMgrE.GetCachedCodeMaster(BusinessConstants.CODE_MASTER_ISSUE_STATUS, issue.Status).Description + separator);
*/
if (isEmail)
{
content.Append(separator + separator);
content.Append(issue.Content);
content.Append(separator + separator);
if (issue.UserName != null && issue.UserName.Trim() != string.Empty)
content.Append(issue.UserName + separator);
if (issue.MobilePhone != null && issue.MobilePhone.Trim() != string.Empty && ControlHelper.IsValidMobilePhone(issue.MobilePhone))
content.Append("Tel: " + issue.MobilePhone + separator);
if (issue.Email != null && issue.Email.Trim() != string.Empty && ControlHelper.IsValidEmail(issue.Email))
content.Append("Email: " + issue.Email + separator);
}
else
{
if (issue.Content != null && issue.Content.Trim() != string.Empty)
{
content.Append(issue.Content);
content.Append(separator);
}
if ((issue.UserName != null && issue.UserName.Trim() != string.Empty)
|| (issue.MobilePhone != null && issue.MobilePhone.Trim() != string.Empty && ControlHelper.IsValidMobilePhone(issue.MobilePhone)))
{
content.Append("[");
}
if (issue.UserName != null && issue.UserName.Trim() != string.Empty)
{
content.Append(issue.UserName);
}
if (issue.MobilePhone != null && issue.MobilePhone.Trim() != string.Empty && ControlHelper.IsValidMobilePhone(issue.MobilePhone))
{
content.Append(", " + issue.MobilePhone);
}
if ((issue.UserName != null && issue.UserName.Trim() != string.Empty)
|| (issue.MobilePhone != null && issue.MobilePhone.Trim() != string.Empty && ControlHelper.IsValidMobilePhone(issue.MobilePhone)))
{
content.Append("]");
}
content.Append(separator);
content.Append(Resources.ISS.IssueMaster.Confirmation + " " + issue.Code + "+" + Resources.ISS.IssueMaster.Space + "+Y");
}
}
catch (Exception e)
{
log.Error(e.Message, e);
}
return content.ToString();
}
[Transaction(TransactionMode.RequiresNew)]
public void SendIssue()
{
try
{
//已经发送了,但是超过2小时没有确认的。
//已经确认,超过2小时没有解决的
IList<IssueMaster> issueMasterSendList = this.genericMgr.FindAll<IssueMaster>("select im from IssueMaster im where im.status= " + (int)com.Sconit.CodeMaster.IssueStatus.Submit + " and im.status =" + (int)com.Sconit.CodeMaster.IssueStatus.InProcess);
double completeHours = double.Parse(systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.CompleteIssueWaitingTime));
double inProcessHours = double.Parse(systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.InProcessIssueWaitingTime));
User user = this.systemMgr.GetMonitorUser();
IList<IssueLevel> issueLevelsSubmit = null;
IList<IssueLevel> issueLevelsInprocess = null;
foreach (IssueMaster issue in issueMasterSendList)
{
if (issue.Status == com.Sconit.CodeMaster.IssueStatus.Submit
&& !issue.StartDate.HasValue)
{
issueLevelsSubmit = this.genericMgr.FindAll<IssueLevel>("select il from IssueLevel as il where il.Code in (select distinct det.Level from IssueDetail det where det.Level = il.Code and det.IsSubmit = true)");
if (issueLevelsSubmit != null && issueLevelsSubmit.Count > 0)
{
SendMailAndSMS(issue, inProcessHours, issue.ReleaseDate.Value, issueLevelsSubmit, user);
}
}
else if (issue.Status == com.Sconit.CodeMaster.IssueStatus.InProcess
&& !issue.CompleteDate.HasValue)
{
issueLevelsInprocess = this.genericMgr.FindAll<IssueLevel>("select il from IssueLevel as il where il.Code in (select distinct det.Level from IssueDetail det where det.Level = il.Code and det.IsInProcess = true)");
if (issueLevelsInprocess != null && issueLevelsInprocess.Count > 0)
{
SendMailAndSMS(issue, completeHours, issue.ReleaseDate.Value, issueLevelsInprocess, user);
}
}
}
}
catch (Exception e)
{
log.Error(e.Message, e);
}
}
[Transaction(TransactionMode.Requires)]
private void SendMailAndSMS(IssueMaster issue, double hours, DateTime date, IList<IssueLevel> issueLevels, User user)
{
int count = issueLevels.Count;
foreach (IssueLevel issueLevel in issueLevels)
{
if (date.AddHours(count * hours) < DateTime.Now)
{
//是否发送过
if (!this.IsSended(issue, issueLevel))
{
IList<IssueDetail> issueDetailList = this.genericMgr.FindAll<IssueDetail>("select det from IssueDetail where IssueCode = ? and IssueLevel = ? ", new object[] { issue.Code, issueLevel.Code });
SendMailAndSMS(issue, issueLevel, issueDetailList);
}
break;
}
count--;
}
}
public bool IsSended(IssueMaster issue, IssueLevel issueLevel)
{
string hql = "select count(*) from IssueDetail where IsActive = true and IssueCode =? and Level = ? and (EmailStatus !=0 or SMSStatus !=0 )";
IList<long> count = this.genericMgr.FindAll<long>(hql, new object[] { issue.Code, issueLevel.Code });
if (count != null && count.Count > 0 && count[0] > 0)
{
return true;
}
return false;
}
#region batch
public int BatchClose(string codeStr, bool isAdmin)
{
return Batch("Close", codeStr, isAdmin);
}
public int BatchDelete(string codeStr, bool isAdmin)
{
return Batch("Delete", codeStr, isAdmin);
}
[Transaction(TransactionMode.Requires)]
private int Batch(string action, string codeStr, bool isAdmin)
{
int resultCount = 0;
IList<string> codeList = (codeStr.Split(',')).ToList<string>();
if (codeList != null && codeList.Count > 0)
{
string hql = string.Empty;
object[] para = new object[codeList.Count];
IType[] type = new IType[codeList.Count];
for (int i = 0; i < codeList.Count; i++)
{
if (i == 0)
{
if (action == "Delete")
{
hql += "delete from IssueMaster where Status = " + (int)com.Sconit.CodeMaster.IssueStatus.Create;
}
else if (action == "Close")
{
hql += "update from IssueMaster set Status = " + (int)com.Sconit.CodeMaster.IssueStatus.Close + " where Status = " + (int)com.Sconit.CodeMaster.IssueStatus.Complete;
}
hql += " and Code = ? ";
if (!isAdmin)
{
hql += " and CreateUserId = " + SecurityContextHolder.Get().Id;
}
}
else
{
hql += " or Code = ? ";
}
para[i] = codeList[i];
type[i] = NHibernateUtil.String;
}
if (hql != string.Empty)
{
resultCount = this.genericMgr.Update(hql, para, type);
}
}
return resultCount;
}
#endregion
/*
[Transaction(TransactionMode.Requires)]
public void SendFail(User user)
{
try
{
IList<IssueDetail> issueDetails = this.GetIssueDetail(BusinessConstants.CODE_MASTER_SEND_STATUS_FAIL);
if (issueDetails != null && issueDetails.Count > 0)
{
IList<EntityPreference> entityPreferences = this.entityPreferenceMgrE.GetEntityPreferenceOrderBySeq(new string[] { BusinessConstants.ENTITY_PREFERENCE_CODE_SMTPEMAILHOST, BusinessConstants.ENTITY_PREFERENCE_CODE_SMTPEMAILADDR, BusinessConstants.ENTITY_PREFERENCE_CODE_SMTPEMAILPASSWD });
string SMTPEmailHost = string.Empty;
string SMTPEmailPasswd = string.Empty;
string emailFrom = string.Empty;
foreach (EntityPreference e in entityPreferences)
{
if (e.Id == (int)EntityPreference.CodeEnum.SMTPEmailHost)
{
SMTPEmailHost = e.Value;
}
else if (e.Id == (int)EntityPreference.CodeEnum.SMTPEmailPasswd)
{
SMTPEmailPasswd = e.Value;
}
else if (e.Id == (int)EntityPreference.CodeEnum.SMTPEmailAddr)
{
if (ControlHelper.IsValidEmail(e.Value))
{
emailFrom = e.Value;
}
else
{
IssueLog log = new IssueLog();
log.Content = "Mail地址无效 : " + e.Value;
log.CreateDate = DateTime.Now;
log.Level = IssueLog.LOG_LEVEL_ERROR;
this.genericMgr.Create(log);
throw new BusinessErrorException("Issue.Error.MailIsInvalid", e.Value);
}
}
}
foreach (IssueDetail issueDetail in issueDetails)
{
string toEmail = issueDetail.Email;
IssueMaster issue = issueDetail.Issue;
string userMail = string.Empty;
if (issue.Email != null && ControlHelper.IsValidEmail(issue.Email))
{
if (issue.UserName != null && issue.UserName.Length > 0)
{
userMail = issue.UserName + "," + issue.Email;
}
else
{
userMail = issue.Email;
}
}
else
{
userMail = emailFrom;
}
string subject = string.Empty;
if (issue.Priority == com.Sconit.CodeMaster.IssuePriority.Urgent)
{
subject = codeMasterMgrE.GetCachedCodeMaster(BusinessConstants.CODE_MASTER_ISSUE_PRIORITY, issue.Priority) + " " + issue.IssueSubject;
}
else
{
subject = issue.IssueSubject;
}
MailPriority mailPriority;
if (issue.Priority == com.Sconit.CodeMaster.IssuePriority.Urgent)
{
mailPriority = MailPriority.High;
}
else
{
mailPriority = MailPriority.Normal;
}
string body = this.GetEmailBody(issue, issueDetail.Level);
#region email发送
string sendResult = SMTPHelper.SendSMTPEMail(subject, body, emailFrom, toEmail, SMTPEmailHost, SMTPEmailPasswd, userMail, mailPriority);
if (sendResult != string.Empty)
{
throw new BusinessErrorException(sendResult);
}
#endregion
}
}
else
{
throw new BusinessErrorException("Issue.Error.MailListIsNull");
}
}
catch (Exception e)
{
log.Error(e.Message, e);
}
}
*/
[Transaction(TransactionMode.Unspecified)]
private IList<IssueDetail> GetIssueDetail(string status)
{
try
{
DetachedCriteria criteria = DetachedCriteria.For(typeof(IssueDetail));
criteria.Add(Expression.Eq("EmailStatus", status));
criteria.Add(Expression.Eq("SMSStatus", status));
criteria.AddOrder(Order.Asc("EmailStatus"));
criteria.AddOrder(Order.Asc("SMSStatus"));
IList<IssueDetail> issueDetailList = this.queryMgr.FindAll<IssueDetail>(criteria);
if (issueDetailList.Count > 0)
{
return issueDetailList;
}
}
catch (Exception e)
{
log.Error(e.Message, e);
}
return null;
}
[Transaction(TransactionMode.Unspecified)]
public IList<IssueMaster> GetIssueMaster(string[] status)
{
DetachedCriteria criteria = DetachedCriteria.For(typeof(IssueMaster));
criteria.Add(Expression.In("Status", status));
criteria.AddOrder(Order.Asc("Status"));
IList<IssueMaster> issueList = queryMgr.FindAll<IssueMaster>(criteria);
if (issueList.Count > 0)
{
return issueList;
}
return null;
}
#endregion
}
[Transactional]
public class IssueLogMgrImpl : IIssueLogMgr
{
public IGenericMgr genericMgr { get; set; }
#region IssueLog
public void LogError(string issue, string content)
{
this.Log(issue, null, content, IssueLog.LOG_LEVEL_ERROR);
}
public void LogFatal(string issue, string content)
{
this.Log(issue, null, content, IssueLog.LOG_LEVEL_FATAL);
}
public void LogInfo(string issue, string content)
{
this.Log(issue, null, content, IssueLog.LOG_LEVEL_INFO);
}
public void LogWarn(string issue, string content)
{
this.Log(issue, null, content, IssueLog.LOG_LEVEL_WARN);
}
public void LogDebug(string issue, string content)
{
this.Log(issue, null, content, IssueLog.LOG_LEVEL_DEBUG);
}
public void LogError(string issue, IssueDetail issueDetail, string content)
{
this.Log(issue, issueDetail, content, IssueLog.LOG_LEVEL_ERROR);
}
public void LogFatal(string issue, IssueDetail issueDetail, string content)
{
this.Log(issue, issueDetail, content, IssueLog.LOG_LEVEL_FATAL);
}
public void LogInfo(string issue, IssueDetail issueDetail, string content)
{
this.Log(issue, issueDetail, content, IssueLog.LOG_LEVEL_INFO);
}
public void LogWarn(string issue, IssueDetail issueDetail, string content)
{
this.Log(issue, issueDetail, content, IssueLog.LOG_LEVEL_WARN);
}
public void LogDebug(string issue, IssueDetail issueDetail, string content)
{
this.Log(issue, issueDetail, content, IssueLog.LOG_LEVEL_DEBUG);
}
[Transaction(TransactionMode.Requires)]
private void Log(string issue, IssueDetail issueDetail, string content, string logLevel)
{
IssueLog log = new IssueLog();
log.Level = logLevel;
log.Content = content;
if (!string.IsNullOrWhiteSpace(issue))
{
log.Issue = issue;
}
if (issueDetail != null)
{
log.Email = issueDetail.User.Email;
log.MPhone = issueDetail.User.MobilePhone;
log.IssueDetail = issueDetail.Id;
log.IsSMS = issueDetail.IsSMS;
log.IsEmail = issueDetail.IsEmail;
log.EmailStatus = issueDetail.EmailStatus.ToString();
log.SMSStatus = issueDetail.SMSStatus.ToString();
}
this.genericMgr.Create(log);
}
#endregion
}
[Transactional]
public class IssueUtilMgrImpl : IIssueUtilMgr
{
public IGenericMgr genericMgr { get; set; }
public bool HavePermission(string issueCode, com.Sconit.CodeMaster.IssueStatus status)
{
return HavePermission(issueCode, SecurityContextHolder.Get(), status);
}
[Transaction(TransactionMode.Unspecified)]
public bool HavePermission(string issueCode, User user, com.Sconit.CodeMaster.IssueStatus status)
{
string hql = "select count(*) from IssueDetail where IsActive =true and IssueCode =? and UserId = ? ";
if (status == com.Sconit.CodeMaster.IssueStatus.InProcess)
{
hql += "and IsDefault != true";
}
IList<long> count = this.genericMgr.FindAll<long>(hql, new object[] { issueCode, user.Id });
if (count != null && count.Count > 0 && count[0] > 0)
{
return true;
}
return false;
}
}
} |
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml.Serialization;
using NeuroLinker.Helpers;
using NeuroLinker.Interfaces;
using NeuroLinker.Interfaces.Helpers;
using NeuroLinker.Interfaces.Workers;
using NeuroLinker.Models;
using VaraniumSharp.Attributes;
namespace NeuroLinker.Workers
{
/// <summary>
/// Retrieve a user list from MAL
/// </summary>
[AutomaticContainerRegistration(typeof(IListRetrievalWorker))]
public class ListRetrievalWorker : IListRetrievalWorker
{
#region Constructor
/// <summary>
/// DI Constructor
/// </summary>
/// <param name="pageRetriever">PageRetriever instance</param>
public ListRetrievalWorker(IPageRetriever pageRetriever)
{
_pageRetriever = pageRetriever;
}
#endregion
#region Public Methods
/// <summary>
/// Retrieve a user's MAL list
/// </summary>
/// <param name="username">User's username</param>
/// <returns>Mal list</returns>
public async Task<UserList> RetrieveUserListAsync(string username)
{
var userList = new UserList();
var retrievalWrapper =
await _pageRetriever.RetrieveDocumentAsStringAsync(MalRouteBuilder.UserListUrl(username));
try
{
var xml = XDocument.Parse(retrievalWrapper.RetrievedBody);
var userInfo = xml.Root?.Element("myinfo");
var userAnime = xml.Root?.Elements("anime").ToList();
if (userInfo == null || userAnime.Count == 0)
{
throw new Exception("Failed to retrieve or parse User's My Anime List");
}
var xmlInfoSerializer = new XmlSerializer(typeof(UserListInformation));
var info = (UserListInformation)xmlInfoSerializer.Deserialize(userInfo.CreateReader());
userList.Info = info;
var xmlAnimeSerializer = new XmlSerializer(typeof(UserListAnime));
foreach (var item in userAnime)
{
var anime = (UserListAnime)xmlAnimeSerializer.Deserialize(item.CreateReader());
userList.Anime.Add(anime);
}
}
catch (Exception exception)
{
userList.ErrorOccured = true;
userList.ErrorMessage = exception.Message;
}
return userList;
}
#endregion
#region Variables
private readonly IPageRetriever _pageRetriever;
#endregion
}
} |
using Unity.Jobs;
using UnityEngine;
using UnityEngine.Jobs;
// namespace Lobby.JobSystem
// {
// [ComputeJobOptimization]
// public struct BuldingCrustJob: IJobParallelTransform
// {
// // public float deltaTime;
// public Vector3 position;
// public void Execute(int index, TransformAccess transform)
// {
// Vector3 pos = transform.position;
// pos = position;
// transform.position = pos;
// }
// }
// } |
using System;
using System.Collections.Generic;
namespace Pe.GyM.Security.Account.Model
{
/// <summary>
/// Objecto que representa una vista de módulo
/// </summary>
/// <remarks>
/// Creación: GMD 20150319
/// Modificación:
/// </remarks>
[Serializable]
public class Vista
{
/// <summary>
/// Código de identificación
/// </summary>
public int Codigo { get; set; }
/// <summary>
/// Nombre
/// </summary>
public string Nombre { get; set; }
/// <summary>
/// URL de acceso
/// </summary>
public string URL { get; set; }
/// <summary>
/// Indicado si es vista principal
/// </summary>
public bool EsPrincipal { get; set; }
/// <summary>
/// Lista de controles asignados
/// </summary>
public List<Control> Controles { get; set; }
}
}
|
using CommandLine;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace SagecomRouterAPI
{
public enum Request
{
[RequestDef(@".\Requests\get-devices.json")]
GetDevices,
[RequestDef(@".\Requests\get-hosts.json")]
GetHosts,
[RequestDef(@".\Requests\get-port-mappings.json")]
GetPortMappings,
[RequestDef(@".\Requests\get-device-info.json")]
GetDeviceInfo,
}
class Program
{
public class Options
{
[Option('u', Required = true)]
public string Username { get; set; }
[Option('p', Required = true)]
public string Password { get; set; }
[Option('c', Required = true)]
public string Command { get; set; }
[Option('o', Required = true)]
public string Host { get; set; }
[Option('r', Required = true)]
public Request Request { get; set; }
}
static void Main(string[] args)
{
try
{
Console.WriteLine("Request");
var parser = new Parser(cfg => cfg.CaseInsensitiveEnumValues = true);
var res = parser.ParseArguments<Options>(args).WithParsed(Run).WithNotParsed(ParseError);
//res = res.WithParsedAsync(Run).Result;
//res.WithNotParsed(ParseError);
//res.
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
private static void Run(Options options)
{
Router router = new Router();
try
{
Console.WriteLine("Reques1");
var k = router.HandleRequest(options.Request, options.Username, options.Password, options.Host).Result;
}
catch (Exception e)
{
Console.WriteLine($"Error processing request. Error: {e.Message}");
}
}
private static void ParseError(IEnumerable<Error> errors)
{
Console.WriteLine("Errors:");
foreach (var error in errors)
{
Console.WriteLine(error);
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class HealthManager : AbstractManager {
public float intervalSeconds;
public int percentChance;
public int maxZ;
public float minZ;
protected override IEnumerator ManageSpawn() {
while ( true ) {
int random = Random.Range(0, 100);
if ( random <= percentChance ) {
SpawnGameObject();
}
yield return new WaitForSeconds(intervalSeconds);
}
}
protected override void SpawnGameObject() {
float randomPosition = Random.Range(minZ, maxZ);
CacheManager.SpawnNewGameObject(objects, Vector3.forward * randomPosition + Vector3.up * 0.3f, transform.rotation);
}
protected override void CacheGameObjects() {
CacheManager.CachePrefabs(out objects, maxNumberOfObjects, prefab);
}
}
|
using System;
using System.Xml;
using AIMLbot.AIMLTagHandlers;
using AIMLbot.Utils;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AIMLbot.UnitTest.TagTests
{
[TestClass]
public class LearnTagTests
{
private ChatBot _chatBot;
private SubQuery _query;
private Learn _tagHandler;
[TestInitialize]
public void Setup()
{
_chatBot = new ChatBot();
ChatBot.Graphmaster = new Node();
ChatBot.Size = 0;
_query = new SubQuery();
_query.InputStar.Insert(0, "first star");
_query.InputStar.Insert(0, "second star");
}
[TestMethod]
public void TestWithBadInput()
{
Assert.AreEqual(0, ChatBot.Size);
XmlNode testNode = StaticHelpers.GetNode("<learn>./nonexistent/Salutations.aiml</learn>");
_tagHandler = new Learn(testNode);
Assert.AreEqual("", _tagHandler.ProcessChange());
Assert.AreEqual(0, ChatBot.Size);
}
[TestMethod]
public void TestWithEmptyInput()
{
Assert.AreEqual(0, ChatBot.Size);
XmlNode testNode = StaticHelpers.GetNode("<learn/>");
_tagHandler = new Learn(testNode);
Assert.AreEqual("", _tagHandler.ProcessChange());
Assert.AreEqual(0, ChatBot.Size);
}
[TestMethod]
public void TestWithValidInput()
{
Assert.AreEqual(0, ChatBot.Size);
var path = Environment.CurrentDirectory + @"\AIML\Salutations.aiml";
XmlNode testNode = StaticHelpers.GetNode($"<learn>{path}</learn>");
_tagHandler = new Learn(testNode);
Assert.AreEqual("", _tagHandler.ProcessChange());
Assert.AreEqual(16, ChatBot.Size);
}
}
} |
using Business.Concrete;
using DataAccess.Concrete.EntityFramework;
using DataAccess.Concrete.InMemory;
using Entities.Concrete;
using System;
namespace ConsoleUI
{
class Program
{
static void Main(string[] args)
{
// Product product1 = new Product() { CategoryId = 2, ProductName = "tablo" };
//productManager.Add(product1);
//productManager.Delete(product1);
//Test01();
//Test02();
//AddProduct(product1);
//GetAllTest();
AllCategoryTest();
//ProductDetailsDto();
//ProductManager productManager = new ProductManager(new EfProductDal());
//productManager.Add(new Product { CategoryId = 2, ProductName = "patates", UnitsInStock = 2, UnitPrice = 5 });
//foreach (var p in productManager.GetAll().Data)
//{
// Console.WriteLine(p.ProductName);
//}
}
private static void ProductDetailsDto()
{
ProductManager productManager = new ProductManager(new EfProductDal());
var result = productManager.GetProductDetails();
if (result.Success==true)
{
foreach (var p in result.Data)
{
Console.WriteLine(p.ProductId + " *** " + p.ProductName + " *** " + p.CategoryName);
}
}
else
{
Console.WriteLine(result.Message);
}
}
private static void AllCategoryTest()
{
CategoryManager categoryManager = new CategoryManager(new EfCategoryDal());
var result1 = categoryManager.GetAll();
foreach (var category in result1.Data)
{
Console.WriteLine(category.CategoryName);
}
}
private static void GetAllTest()
{
ProductManager productManager = new ProductManager(new EfProductDal());
foreach (var p in productManager.GetAll().Data)
{
Console.WriteLine(p.ProductId + " " + p.ProductName);
}
}
private static void AddProduct(Product product1)
{
ProductManager productManager = new ProductManager(new EfProductDal());
productManager.Add(product1);
foreach (var product in productManager.GetAll().Data)
{
Console.WriteLine(product.ProductName);
}
}
//private static void Test02()
//{
// ProductManager productManager = new ProductManager(new EfProductDal());
// foreach (var product in productManager.GetById(2))
// {
// Console.WriteLine(product.ProductName);
// }
//}
private static void Test01()
{
ProductManager productManager = new ProductManager(new EfProductDal());
foreach (var product in productManager.GetByUnitPrice(40, 50).Data)
{
Console.WriteLine(product.ProductName);
}
}
}
}
|
using System.Windows.Controls;
namespace Lite
{
/// <summary>
/// The header page
/// </summary>
public partial class LitePrintA4Template1HeaderPageView : UserControl
{
/// <summary>
/// Default constructor
/// </summary>
public LitePrintA4Template1HeaderPageView()
{
InitializeComponent();
}
}
}
|
namespace LogViewer.Model
{
/// <summary>
/// Настройки чтения логов
/// </summary>
public sealed class ReadLogOptions
{
public ReadLogOptions(string logPath, int readAmount)
{
LogPath = logPath;
ReadAmount = readAmount;
}
/// <summary>
/// Путь к файлу с логами
/// </summary>
public string LogPath { get; }
/// <summary>
/// Объём чтения логов из файла
/// </summary>
public int ReadAmount { get; }
}
} |
using System;
using RabbitMQ.Client;
namespace Spring.Messaging.Amqp.Rabbit.Support
{
/// <summary>
/// Date Extension Methods
/// </summary>
internal static class DateExtensions
{
/// <summary>
/// Helper method to convert from DateTime to AmqpTimestamp.
/// </summary>
/// <param name="datetime">
/// The datetime.
/// </param>
/// <returns>
/// The AmqpTimestamp.
/// </returns>
internal static AmqpTimestamp ToAmqpTimestamp(this DateTime datetime)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var unixTime = (datetime.ToUniversalTime() - epoch).TotalSeconds;
var timestamp = new AmqpTimestamp((long)unixTime);
return timestamp;
}
/// <summary>
/// Helper method to convert from AmqpTimestamp.UnixTime to a DateTime (for the local machine).
/// </summary>
/// <param name="timestamp">
/// The timestamp.
/// </param>
/// <returns>
/// The DateTime.
/// </returns>
internal static DateTime ToDateTime(this AmqpTimestamp timestamp)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return epoch.AddSeconds(timestamp.UnixTime).ToLocalTime();
}
internal static long ToMilliseconds(this DateTime datetime)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var unixTime = (datetime.ToUniversalTime() - epoch).TotalMilliseconds;
return (long)unixTime;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AirMouseTab
{
class Obrabotka
{
internal const int BUTTON1_DOWN_MASK = 1;
internal const int BUTTON2_DOWN_MASK = 2;
internal const int BUTTON3_DOWN_MASK = 3;
internal const int MOUSE_BUTTON4 = 4;
internal const int MOUSE_BUTTON5 = 5;
// private byte[] buf;
private int pin;
internal const byte DEFAULT = 0;
internal const byte MOUSE = 1;
internal const byte MMOVE = 2;
internal const byte MWHELL = 4;
internal const byte KEY = 3;
internal const byte KEYCOM = 6;
internal const byte MESSAGE = 10;
internal const byte NONE = 99;
internal const byte CLOSE = 100;
internal const byte ERROR = 101;
float lastx = 0.0f; //остаток от предыдущего движения x
float lasty = 0.0f; //остаток от предыдущего движения y
int otmena = 0;//Число раз неправильно присланных котрольных значений
Robot robot = new Robot();
private float readFloat(byte[] buf, int start)
{
if (BitConverter.IsLittleEndian)
{
Array.Reverse(buf,start,4); // Convert big endian to little endian
}
return BitConverter.ToSingle(buf, start);
}
private int readInt(byte[] buf, int start)
{
return (buf[start] << 24) | (buf[start+1] << 16) | (buf[start+2] << 8) | (buf[start+3]);
// return BitConverter.ToInt32(buf, start);
}
public Obrabotka( int pin)
{
// this.buf = buf;
this.pin = pin;
}
internal byte run(byte[] buf)
{
var tip = buf[0];
var command = buf[1];
var pinCode = readInt(buf, 28);
//Console.WriteLine(">" + tip + " > " + command);
if (pinCode != pin)
{
otmena += 1;
if (otmena > 10)
return ERROR;
else
return NONE;
}
else
otmena = 0;
switch (tip)
{
case MMOVE:
try
{
var x = readFloat(buf, 2);
var y = readFloat(buf, 6);
var velocity = readInt(buf, 10);
//println(s"$x $y $velocity")
Point b = robot.getLocation();
var tekx = b.X + x + lastx;
var teky = b.Y + y + lasty;
int endx = (int)Math.Round(tekx);
int endy = (int)Math.Round(teky);
//lastx=tekx-endx
//lasty=teky-endy
// println("velocity "+velocity)
robot.mouseMove(endx, endy);
// Thread.sleep(10)
}
catch
{
}
break;
case MOUSE:
try
{
byte btn = 0;
switch (command)
{
case 1: btn = BUTTON1_DOWN_MASK; break;
case 2: btn = BUTTON2_DOWN_MASK; break;
case 3: btn = BUTTON3_DOWN_MASK; break;
case 4: btn = MOUSE_BUTTON4; break;
case 5: btn = MOUSE_BUTTON5; break;
}
if (btn > 0)
{
switch (buf[2])
{
case 1:
robot.mousePress(btn);
break;
case 2:
robot.mouseRelease(btn);
break;
}
}
}
catch
{
}
break;
case KEY:
{
int key = 0;
if (',' <= command && command <= ']')
{
key = command;
}
else {
switch (command)
{
case (byte)'a': key = (int)Keys.Alt; break;
case (byte)'c': key = (int)Keys.LControlKey; break;
case (byte)'s': key = (int)Keys.LShiftKey; break;
case (byte)'w': key = (int)Keys.LWin; break;
case (byte)'e': key = (int)Keys.Enter; break;
case (byte)'z': key = readInt(buf, 6); break;
default:
break;
}
}
// Console.Out.WriteLine(">>"+key+" >> "+ buf[2]);
try
{
// Simulate a key press
switch (buf[2])
{
case 0:
robot.keyTap(key);
break;
case 1:
robot.keyPress(key);
break;
case 2:
robot.keyRelease(key);
break;
}
}
catch(Exception e)
{
// Console.Out.WriteLine(e.Message);
}
}
break;
case KEYCOM:
{
int key = readInt(buf, 6);
bool shift = (command & 0x1) > 0;
bool control = (command & 0x2) > 0;
bool alt = (command & 0x4) > 0;
bool win = (command & 0x8) > 0;
if (shift) robot.keyPress((int)Keys.LShiftKey);
if (control) robot.keyPress((int)Keys.LControlKey);
if (alt) robot.keyPress((int)Keys.Alt);
if (win) robot.keyPress((int)Keys.LWin);
robot.keyPress(key);
robot.keyRelease(key);
if (win) robot.keyRelease((int)Keys.LWin);
if (alt) robot.keyRelease((int)Keys.Alt);
if (control) robot.keyRelease((int)Keys.LControlKey);
if (shift) robot.keyRelease((int)Keys.LShiftKey);
break;
}
case MWHELL:
break;
case MESSAGE:
println(command);
break;
default:
break;
}
return tip;
}
private void println(byte command)
{
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TwoState : MonoBehaviour
{
public bool facingLeft;
public Sprite spriteLeft, spriteMiddle, spriteRight;
bool switching;
// Start is called before the first frame update
void Start()
{
GetComponent<SpriteRenderer>().sprite = (facingLeft ? spriteLeft : spriteRight);
}
public void Notify(bool left)
{
if (left == facingLeft) {
switching = true;
GetComponent<SpriteRenderer>().sprite = spriteMiddle;
} else if (switching) {
facingLeft = !facingLeft;
switching = true;
GetComponent<SpriteRenderer>().sprite = (facingLeft ? spriteLeft : spriteRight);
Array.ForEach(FindObjectsOfType<TwoStateBlock>(), o => o.Toggle());
}
}
void OnTriggerExit2D(Collider2D collider)
{
if (collider.gameObject.tag == "Player") {
switching = false;
GetComponent<SpriteRenderer>().sprite = (facingLeft ? spriteLeft : spriteRight);
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Threading;
using System.Xml;
using NLog;
using SimpleJSON;
namespace TwitchIntegrationPlugin
{
public class BeatBot
{
//private const string Beatsaver = "https://beatsaver.com/";
private readonly Config _config;
private readonly Thread _botThread;
private readonly Thread _queueThread;
private bool _retry;
private bool _exit;
private readonly Logger _logger;
//EventWaitHandle _wait = new AutoResetEvent(false);
private string _currUser = "QueueBot";
private bool _isModerator;
private bool _isSubscriber;
private bool _isBroadcaster;
//private bool _isAcceptingRequests; No longer needed due to combination with twitch mode button.
private readonly ArrayList _banList = new ArrayList();
private readonly ArrayList _randomizedList = new ArrayList();
private readonly ArrayList _messageQueue = new ArrayList();
private StreamWriter _writer;
private void CreateConfigDirectory()
{
if (Directory.Exists("Plugins\\Config")) return;
_logger.Debug("Creating Directory 'Plugins\\Config'");
Directory.CreateDirectory("Plugins\\Config");
}
public BeatBot()
{
_logger = LogManager.GetCurrentClassLogger();
CreateConfigDirectory();
LoadQueue();
if (!File.Exists("Plugins\\Config\\song_blacklist.txt"))
{
_logger.Info("Creating Blacklist File");
using (File.Create("Plugins\\Config\\song_blacklist.txt"))
{
_logger.Debug("Created Blacklist File");
}
}
else
{
var file = new StreamReader("Plugins\\Config\\song_blacklist.txt");
string line;
while ((line = file.ReadLine()) != null)
{
_logger.Info(line);
_banList.Add(line);
}
file.Close();
}
_config = ReadCredsFromConfig();
_botThread = new Thread(Initiate);
_queueThread = new Thread(SendMessageQueue); // send messages from queue
}
public void Start()
{
_botThread.Start();
_queueThread.Start();
}
public void Exit()
{
_retry = false;
_exit = true;
_botThread.Abort();
_botThread.Join();
_queueThread.Abort();
_queueThread.Join();
SaveQueue();
}
/**
* load queue from song_queue.txt
*/
private void LoadQueue()
{
// create config directory if not exists
CreateConfigDirectory();
// ignore load if file doesn't exists
if (!File.Exists("Plugins\\Config\\song_queue.txt")) return;
// get json from file
var file = new StreamReader("Plugins\\Config\\song_queue.txt");
var json = "";
string line;
while ((line = file.ReadLine()) != null)
{
json += line;
}
var node = JSON.Parse(json);
for (var i = 0; i < node.Count; i++)
{
var song = node[i];
var qs = new QueuedSong(
song["songName"],
song["name"],
song["authorName"],
song["bpm"],
song["id"],
song["songSubName"],
song["downloadUrl"],
song["requestedBy"],
song["coverUrl"]
);
AddQueueSong(qs, false);
}
file.Close();
}
/**
* save queue to song_queue.txt
*/
private void SaveQueue()
{
// create config directory if not exists
CreateConfigDirectory();
// delete old song_queue.txt
if (File.Exists("Plugins\\Config\\song_queue.txt"))
{
File.Delete("Plugins\\Config\\song_queue.txt");
}
// build json string -> todo json class?
var json = "";
foreach (var song in StaticData.QueueList)
{
if (json.Length > 0)
{
json += ", ";
}
json += song.ToString();
}
// save into file
File.WriteAllText("Plugins\\Config\\song_queue.txt", "[" + json + "]");
}
/**
* check if queue has messages to send to irc server
*/
private void SendMessageQueue()
{
_logger.Debug("starting queue thread ;)");
while (!_exit)
{
// skip while if messageQueue is empty :)
if (_messageQueue.Count == 0) continue;
// send message to irc server and wait 1750ms (because twitch rate limit)
_writer.WriteLine(_messageQueue[0]);
_writer.Flush();
_messageQueue.RemoveAt(0);
Thread.Sleep(1750);
}
}
private void Initiate()
{
_logger.Debug("Twitch bot starting...");
var retryCount = 0;
if (_config == null) return;
do
{
try
{
using (var irc = new TcpClient("irc.chat.twitch.tv", 6667))
using (var stream = irc.GetStream())
using (var reader = new StreamReader(stream))
using (var writer = new StreamWriter(stream))
{
// Set a global Writer
_writer = writer;
// Login Information for the irc client
_logger.Debug("Connection to twitch server established. Beginning Login.");
SendMessage("PASS " + _config.Token);
SendMessage("NICK " + _config.Username);
SendMessage("JOIN #" + _config.Channel);
// Adding Capabilities Requests so that we can parse Viewer information
SendMessage("CAP REQ :twitch.tv/membership twitch.tv/commands twitch.tv/tags");
_logger.Debug("Login complete Beat bot online. -> " + _config.Username);
while (!_exit)
{
string inputLine;
while ((inputLine = reader.ReadLine()) != null || _exit)
{
_logger.Debug(inputLine);
ProcessIrcMessage(inputLine);
if (inputLine == null) continue;
var splitInput = inputLine.Split(' ');
if (splitInput[0] == "PING")
{
SendMessage("PONG " + splitInput[1]);
continue;
}
// ignore server stuff there not privmsg or whisper (remove whisper?)
if (splitInput[2] != "PRIVMSG" && splitInput[2] != "WHISPER") continue;
splitInput = inputLine.Split(':');
OnCommandReceived(splitInput[2], _currUser);
}
}
}
}
catch (Exception e)
{
_logger.Debug("----------");
_logger.Debug(e.ToString());
_logger.Debug("----------");
_retry = ++retryCount <= 20;
if (_exit)
{
_retry = false;
}
else
{
Thread.Sleep(5000);
}
}
} while (_retry);
}
private void OnCommandReceived(string command, string username)
{
var parameters = command.Split();
var commandName = parameters[0].Trim().ToLower();
if (_isModerator || _isBroadcaster)
{
switch (commandName)
{
case "!next":
MoveToNextSongInQueue();
return;
case "!clearall":
RemoveAllSongsFromQueue();
return;
case "!remove":
if (parameters.Length < 2)
{
SendMessage("Missing Song ID!");
return;
}
if (StaticData.QueueList.Count < 1)
{
SendMessage("BeatSaber queue was empty.");
return;
}
var qs = ApiConnection.GetSongFromBeatSaver(false, parameters[1], username);
if (qs == null)
{
SendMessage("Couldn't Parse BeatSaver Data.");
return;
}
for (var i = 0; i < StaticData.QueueList.Count; i++)
{
if (!((QueuedSong) StaticData.QueueList[i]).SongName.Contains(qs.SongName))
continue;
StaticData.QueueList.RemoveAt(i);
SendMessage("Removed \"" + qs.SongName + "\" from the queue");
return;
}
SendMessage("\"" + qs.SongName + "\" is not in the queue");
return;
case "!block":
case "!unblock":
if (parameters.Length < 2)
{
SendMessage("Missing song ID!");
return;
}
BlacklistSong(
ApiConnection.GetSongFromBeatSaver(false, parameters[1], ""),
commandName == "!block"
);
return;
case "!randomize":
var randomizer = new Random();
for (var i = 0; StaticData.QueueList.Count > 0 && i < _config.RandomizeLimit; i++)
{
var randomIndex = randomizer.Next(StaticData.QueueList.Count);
var randomSong = (QueuedSong) StaticData.QueueList[randomIndex];
//System.out.println(" " + randomSong.getFirst());
_randomizedList.Add(randomSong);
StaticData.QueueList.RemoveAt(randomIndex);
}
StaticData.QueueList.Clear();
StaticData.QueueList.AddRange(_randomizedList);
_randomizedList.Clear();
SendMessage(_config.RandomizeLimit + " songs were randomly chosen from queue!");
DisplaySongsInQueue(StaticData.QueueList, false);
return;
case "!songinfo":
if (StaticData.QueueList.Count < 1)
{
SendMessage("No songs in the queue.");
return;
}
SendMessage(
"Song Currently Playing: " +
"[ID: " + ((QueuedSong) StaticData.QueueList[0]).Id + "], " +
"[Song: " + ((QueuedSong) StaticData.QueueList[0]).SongName + "], " +
"[Download: " + ((QueuedSong) StaticData.QueueList[0]).DownloadUrl + "]"
);
return;
//This block is unnessecary now that queue has been moved to rely on twitch button.
/*else if (command.StartsWith("!close"))
{
if (_isAcceptingRequests)
{
_isAcceptingRequests = false;
SendMessage("The queue has been closed!");
}
else
{
SendMessage("The queue was already closed.");
}
}
else if (command.StartsWith("!open"))
{
if (!_isAcceptingRequests)
{
_isAcceptingRequests = true;
SendMessage("The queue has been opened!");
}
else
{
SendMessage("The queue is already open.");
}
}*/
}
}
if (
// mod only and is mod or broadcaster
_config.ModOnly && (_isModerator || _isBroadcaster) ||
// sub only and is mod, broadcaster or sub
_config.SubOnly && (_isModerator || _isBroadcaster || _isSubscriber) ||
// no mod only and no sub only -> everyone can use command
!_config.ModOnly && !_config.SubOnly
)
{
BasicCommands(commandName, parameters, username);
}
}
private void BasicCommands(string commandName, IReadOnlyList<string> parameters, string username)
{
switch (commandName)
{
case "!bsr":
if (parameters.Count < 2)
{
SendMessage("Missing song ID or song name!");
return;
}
try
{
var split = string.Join(" ", parameters.Skip(1));
AddRequestedSongToQueue(!char.IsDigit(split, 0), split, username);
}
catch (Exception e)
{
_logger.Error(e);
}
break;
case "!add":
if (parameters.Count < 2)
{
SendMessage("Missing song ID or song name!");
return;
}
try
{
AddRequestedSongToQueue(false, parameters[1], username);
}
catch (Exception e)
{
_logger.Error(e);
}
break;
case "!queue":
DisplaySongsInQueue(StaticData.QueueList, false);
break;
case "!blist":
DisplaySongsInQueue(_banList, true);
break;
case "!qhelp":
SendMessage("These are the valid commands for the Beat Saber Queue system.");
SendMessage("!add <songId>, !queue, !blist, [Mod only] !next, !clearall, !block <songId>, !unblock <songId>, !open, !close !randomize");
break;
}
}
public void AddRequestedSongToQueue(bool isTextSearch, string queryString, string requestedBy)
{
if (!StaticData.TwitchMode && !_isModerator && !_isBroadcaster)
{
SendMessage("The queue is currently closed.");
return;
}
var qs = ApiConnection.GetSongFromBeatSaver(isTextSearch, queryString, requestedBy);
if (qs == null)
{
SendMessage("Invalid request");
return;
}
var limitReached = false;
var isAlreadyBanned = false;
// Check to see if song is banned.
foreach (string banValue in _banList)
{
if (queryString.Contains("-"))
{
if (banValue.Contains(queryString.Split('-')[0]))
{
isAlreadyBanned = true;
}
}
else if (banValue.Contains(queryString))
{
isAlreadyBanned = true;
}
}
// Check for song against Blacklist, else proceed to get Song information
if (isAlreadyBanned)
{
SendMessage("Song is currently Blacklisted");
return;
}
if (StaticData.QueueList.Count == 0)
{
AddQueueSong(qs, true);
return;
}
var internalCounter = 0;
foreach (QueuedSong q in StaticData.QueueList)
{
if (!q.SongName.Contains(qs.SongName)) continue;
SendMessage("\"" + qs.SongName + "\" already exists in the queue");
return;
}
foreach (QueuedSong q in StaticData.QueueList)
{
if (q.RequestedBy.Equals(requestedBy))
{
internalCounter++;
}
}
// Todo optimize if...
if (!_isBroadcaster && !_isModerator)
{
if (_config.SubLimit == _config.ViewerLimit)
{
limitReached = internalCounter == _config.ViewerLimit;
}
else if (!_isSubscriber && (internalCounter == _config.ViewerLimit))
{
limitReached = true;
}
else if (_isSubscriber && (internalCounter == _config.SubLimit))
{
limitReached = true;
}
}
if (limitReached)
{
SendMessage(requestedBy + ", you've reached the request limit.");
return;
}
AddQueueSong(qs, true);
}
/**
* add a song to the queue
*/
public void AddQueueSong(QueuedSong qs, bool sendMessage)
{
StaticData.QueueList.Add(qs);
if (StaticData.QueueList.Count == 1) StaticData.SongAddedToQueueEvent?.Invoke(qs);
if (sendMessage)
{
SendMessage(qs.RequestedBy + " added \"" + qs.SongName + "\", uploaded by " + qs.AuthName + " to queue!");
}
}
public void MoveToNextSongInQueue()
{
if (StaticData.QueueList.Count < 1)
{
SendMessage("BeatSaber queue is empty.");
return;
}
StaticData.QueueList.RemoveAt(0);
if (StaticData.QueueList.Count == 0)
{
SendMessage("Queue is now empty.");
return;
}
var remSong = ((QueuedSong) StaticData.QueueList[0]).SongName;
SendMessage(
"Removed \"" + remSong + "\" from the queue, next song is \"" +
((QueuedSong) StaticData.QueueList[0]).SongName + "\" requested by " +
((QueuedSong) StaticData.QueueList[0]).RequestedBy
);
}
public void RemoveAllSongsFromQueue()
{
if (StaticData.QueueList.Count == 0)
{
SendMessage("BeatSaber queue was empty");
return;
}
StaticData.QueueList.Clear();
SendMessage("Removed all songs from the BeatSaber queue");
}
public void DisplaySongsInQueue(ArrayList queue, bool isBanlist)
{
var curr = "Current song list: ";
var isEmptyMsg = "No songs in the queue";
if (isBanlist)
{
curr = "Current banned list: ";
isEmptyMsg = "No songs currently banned.";
}
if (queue.Count == 0)
{
SendMessage(isEmptyMsg);
return;
}
for (var i = 0; i < StaticData.QueueList.Count; i++)
{
curr += ((QueuedSong) queue[i]).SongName;
if (i < queue.Count - 1)
{
curr += ", ";
}
}
SendMessage(curr);
}
private void BlacklistSong(QueuedSong song, bool isAdd)
{
if (song.Id == null) return;
if (isAdd && _banList.Contains(song.Id) || !isAdd && !_banList.Contains(song.Id))
{
SendMessage(isAdd ? "Song already on banlist." : "Song is not on banlist.");
return;
}
if (isAdd)
{
_banList.Add(song.Id);
}
else
{
_banList.Remove(song.Id);
}
if (!File.Exists("Plugins\\Config\\song_blacklist.txt")) return;
// add song to blacklist.txt
if (isAdd)
{
// add song id to file
File.AppendAllText("Plugins\\Config\\song_blacklist.txt", song.Id + Environment.NewLine);
// send feedback
SendMessage("Added \"" + song.SongName + "\", uploaded by " + song.AuthName + " to banlist!");
return;
}
// remove song from blacklist.txt (list remaining songs)
var bannedSongs = "";
foreach (string banValue in _banList)
{
bannedSongs += banValue + Environment.NewLine;
}
File.WriteAllText("Plugins\\Config\\song_blacklist.txt", bannedSongs);
// send feedback
SendMessage("Removed \"" + song.SongName + "\", uploaded by " + song.AuthName + " from banlist!");
}
[SuppressMessage("ReSharper", "PossibleNullReferenceException")]
private Config ReadCredsFromConfig()
{
if (!Directory.Exists("Plugins\\Config"))
{
Directory.CreateDirectory("Plugins\\Config");
}
if (!File.Exists("Plugins\\Config\\TwitchIntegration.xml"))
{
using (var writer = XmlWriter.Create("Plugins\\Config\\TwitchIntegration.xml"))
{
writer.WriteStartDocument();
writer.WriteStartElement("Config");
writer.WriteElementString("Username", "Twitch Username");
writer.WriteElementString("Oauth", "Oauth Token");
writer.WriteElementString("Channel", "Channel Name");
writer.WriteElementString("ModeratorOnly", "false");
writer.WriteElementString("SubscriberOnly", "false");
writer.WriteElementString("ViewerRequestLimit", "5");
writer.WriteElementString("SubscriberLimitOverride", "5");
writer.WriteElementString("ContinueQueue", "false");
writer.WriteElementString("Randomize", "false");
writer.WriteElementString("RandomizeLimit", "5");
writer.WriteEndElement();
writer.WriteEndDocument();
}
return null;
}
try
{
var doc = new XmlDocument();
doc.Load("Plugins\\Config\\TwitchIntegration.xml");
var configNode = doc.SelectSingleNode("Config");
var username = configNode.SelectSingleNode("Username").InnerText.ToLower();
var token = configNode.SelectSingleNode("Oauth").InnerText;
var channel = configNode.SelectSingleNode("Channel").InnerText.ToLower();
var modOnly = ConvertToBoolean(configNode.SelectSingleNode("ModeratorOnly").InnerText.ToLower());
var subOnly = ConvertToBoolean(configNode.SelectSingleNode("SubscriberOnly").InnerText.ToLower());
var viewerLimit = ConvertToInteger(configNode.SelectSingleNode("ViewerRequestLimit").InnerText.ToLower());
var subLimit = ConvertToInteger(configNode.SelectSingleNode("SubscriberLimitOverride").InnerText.ToLower());
var continueQueue = ConvertToBoolean(configNode.SelectSingleNode("ContinueQueue").InnerText.ToLower());
var randomize = ConvertToBoolean(configNode.SelectSingleNode("Randomize").InnerText.ToLower());
var randomizeLimit = ConvertToInteger(configNode.SelectSingleNode("RandomizeLimit").InnerText.ToLower());
return new Config(channel, token, username, modOnly, subOnly, viewerLimit, subLimit, continueQueue, randomize, randomizeLimit);
}
catch (Exception e)
{
_logger.Error("Error loading xml file: " + e);
return null;
}
}
private void ProcessIrcMessage(string message)
{
if (!message.Contains("PRIVMSG")) return;
var splitInput = message.Split(';');
_isBroadcaster = splitInput[0].Contains("broadcaster");
_isModerator = splitInput[5].Contains("mod=1");
_isSubscriber = splitInput[7].Contains("subscriber=1");
_currUser = splitInput[2].Split('=')[1];
}
// Wanted defaults set when conversions failed, so I wrapped in a try/catch block and assigned defaults.
private bool ConvertToBoolean(string value)
{
try
{
return Convert.ToBoolean(value);
}
catch (FormatException)
{
_logger.Error("Value should be a Boolean, but doesn't convert. Default of \"False\" being used.");
return false;
}
}
private int ConvertToInteger(string value)
{
try
{
return int.Parse(value);
}
catch (FormatException)
{
_logger.Error("Value should be a Integer, but doesn't convert. Default of \"5\" being used.");
return 5;
}
}
private void SendMessage(string message)
{
// ignore pong, it should be not send with a sleep
// ignore others only on start (faster bot start)
if (message.StartsWith("PASS") || message.StartsWith("NICK") || message.StartsWith("JOIN #") || message.StartsWith("CAP REQ") || message.StartsWith("PONG"))
{
_writer.WriteLine(message);
_writer.Flush();
}
else
{
_messageQueue.Add("PRIVMSG #" + _config.Channel + " :" + message);
}
}
}
} |
using System;
namespace ArkSavegameToolkitNet
{
public interface ISaveState
{
float? GameTime { get; set; }
DateTime SaveTime { get; set; }
string MapName { get; set; }
}
} |
using System;
using Microsoft.AspNetCore.Mvc;
using PP_Optimalization.Service;
namespace PP_Optimalization.Controllers
{
[Route("[controller]")]
public class HomeController : Controller
{
private readonly IMathService _mathService;
public HomeController(IMathService mathService)
{
_mathService = mathService;
}
[HttpGet]
public IActionResult Get()
{
var watch = System.Diagnostics.Stopwatch.StartNew();
var valuesData = new ValuesData
{
A = 10,
B = 10,
C = 10,
D = 10,
E = 10,
X = 10,
Count = 100,
N = 10
};
var data = _mathService.GetExamples(valuesData);
watch.Stop();
data.NetSummaryTime = watch.Elapsed.TotalMilliseconds;
return Ok(data);
}
[HttpPost]
public IActionResult Post([FromBody]ValuesData valuesData)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
var data = _mathService.GetExamples(valuesData);
watch.Stop();
data.NetSummaryTime = watch.Elapsed.TotalMilliseconds;
return Ok(data);
}
}
}
|
namespace BDTest.Example.Context;
public class MyTestContext
{
public MyApiContext ApiContext { get; } = new();
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DuplicateCollect : Collectable
{
private Throw _throw;
public float delay = 0.1f;
public int extraBlocks = 2;
public float deltaAngle = 15f;
private Throw @throw
{
get
{
if (!_throw)
_throw = GetComponentInParent<Throw>();
return _throw;
}
}
public override void Setup()
{
if(!@throw)
return;
@throw.OnThrow.AddListener(OnHit);
}
public void OnDisable()
{
if(!@throw)
return;
@throw.OnThrow.RemoveListener(OnHit);
}
public void OnHit(Manipulable manipulable)
{
if(!manipulable)
return;
Vector2 velocity = manipulable.rigid.velocity;
int totalCount = extraBlocks + 1;
Vector3 size = manipulable.transform.localScale /(float) totalCount;
List<Collider2D> collider2Ds = new List<Collider2D>();
for (int i = 0; i < extraBlocks + 1; i++)
{
int sign = i % 2 == 0 ? -1 : 1;
int step = Mathf.CeilToInt(((float) i) / 2f);
float angle = step * deltaAngle * sign;
GameObject duplicate = Instantiate(manipulable.gameObject, manipulable.transform.position, manipulable.transform.rotation);
//duplicate.transform.localScale = size;
duplicate.GetComponent<Rigidbody2D>().velocity = Quaternion.Euler(0, 0, angle) * velocity;
Collider2D collider2D = duplicate.GetComponent<Collider2D>();
Manipulable manipulableClone = duplicate.GetComponent<Manipulable>();
@throw.SetupManipulable(manipulableClone);
manipulableClone.transform.localScale *= 0.9f;
foreach (var collider in collider2Ds)
{
Physics2D.IgnoreCollision(collider,collider2D);
}
collider2Ds.Add(collider2D);
}
Destroy(manipulable.gameObject);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
namespace IRAP.Global
{
public class MSGHelp
{
private static MSGHelp _instance = null;
public static MSGHelp Instance
{
get
{
if (_instance == null)
_instance = new MSGHelp();
return _instance;
}
}
private MSGHelp() { }
public void ShowErrorMessage(Exception error)
{
int errCode = -1;
string errText = "";
if (error.Data["ErrCode"] != null)
errCode = (int)error.Data["ErrCode"];
if (error.Data["ErrText"] != null)
errText = error.Data["ErrText"].ToString();
else
errText = error.Message;
XtraMessageBox.Show(
string.Format(
errCode == -1 ? "{1}" : "({0}){1}",
errCode,
errText),
"错误信息",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
public void ShowErrorMessage(int errCode, string errText)
{
XtraMessageBox.Show(
string.Format("({0}){1}", errCode, errText),
"错误信息",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
public void ShowErrorMessage(string errText)
{
XtraMessageBox.Show(
errText,
"错误信息",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
public void ShowNormalMessage(string msgText)
{
XtraMessageBox.Show(
msgText,
"提示信息",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using Google.Protobuf;
using Google.Protobuf.Reflection;
using Accounts.Domain.Commands;
using Linedata.Foundation.Domain.Messaging;
using Microsoft.Extensions.Options;
using ProtoBuf;
namespace Accounts.Domain.Commands.Private
{
public class CreateAccount : Command
{
public decimal Amount;
public CreateAccount(decimal amount)
{
Amount = amount;
}
public CreateAccount(CreateAccount cmd)
{
Amount = cmd.Amount;
}
}
}
|
using UnityEngine;
using System.Collections;
public class VoteCheckYesButton : MonoBehaviour {
//投票番号
public int myVote;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnBottonClick() {
GameObject.Find("VoteCheckFrame").GetComponent<VoteCheck>().HideFrame();
GameObject.Find ("ClientController").GetComponent<ClientController> ().myPlayerScript.transform.SendMessage ("SetVote", myVote);
Debug.Log ("Vote : " + myVote);
if (myVote == 1) {
GameObject.Find("BackButton").GetComponent<VoteButton>().AfterVoteSprite();
} else if (myVote == 2) {
GameObject.Find("RightButton").GetComponent<VoteButton>().AfterVoteSprite();
} else if (myVote == 3) {
GameObject.Find("FrontButton").GetComponent<VoteButton>().AfterVoteSprite();
} else if (myVote == 4) {
GameObject.Find("LeftButton").GetComponent<VoteButton>().AfterVoteSprite();
}
}
}
|
using System;
class ModifyABitAtGivenPosition
{
static void Main()
{
Console.WriteLine("Infinite loop. If you want to stop, pres CTRL+C !!!");
while (true)
{
int liNumber, liMask, liBit, liNewBit;
Console.Write("Enter positive integer : ");
liNumber = int.Parse(Console.ReadLine());
Console.Write("Enter a number of bit : ");
liBit = int.Parse(Console.ReadLine());
Console.Write("Enter a new value of a bit : ");
liNewBit = int.Parse(Console.ReadLine());
liMask = 1 << liBit; // Move the 1st bit left by p positions
if (liNewBit == 0)
{
liNumber = liNumber & ~liMask;
}
else
{
liNumber = liNumber | liMask;
}
Console.WriteLine("The new number after change {0}-st bit with {1}, is a {2}", liBit, liNewBit, liNumber);
}
}
} |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using Report_ClassLibrary;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class TransferStockBySKU : System.Web.UI.Page
{
Dictionary<string, bool> UserList = new Dictionary<string, bool>();
List<User> LoginUser = new List<User>();
static List<VanDetails> vanList = new List<VanDetails>();
static Dictionary<string, string> productList = new Dictionary<string, string>();
ReportDocument rdoc = new ReportDocument();
bool validateFilter = false;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["AllCashReportLogin"] != null)
{
UserList = (Dictionary<string, bool>)Session["AllCashReportLogin"];
if (UserList.First().Value.ToString() == "0")
{
Response.Redirect("~/index.aspx");
}
}
if (Session["AllCashReportLogin"] == null)
{
Response.Redirect("~/index.aspx");
}
if (!IsPostBack)
{
Dictionary<string, string> branchList = new Dictionary<string, string>();
InitPage();
}
}
private void InitPage()
{
Dictionary<string, string> branchList = new Dictionary<string, string>();
vanList = new List<VanDetails>();
productList = new Dictionary<string, string>();
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString))
{
cn.Open();
SqlCommand cmd = new SqlCommand("proc_TransferStockDaily_GetBranch", cn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader reader = cmd.ExecuteReader();
branchList.Add("-1", "---All---");
while (reader.Read())
{
branchList.Add(reader["BranchID"].ToString(), reader["BranchName"].ToString());
}
cn.Close();
cn.Open();
cmd = new SqlCommand("proc_TransferStockDaily_BySKU_GetVAN", cn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
reader = cmd.ExecuteReader();
while (reader.Read())
{
VanDetails vd = new VanDetails();
vd.BranchID = reader["BranchID"].ToString();
vd.VAN_ID = reader["VAN_ID"].ToString();
vd.VanCode = reader["VAN_ID"].ToString();
vanList.Add(vd);
}
cn.Close();
cn.Open();
cmd = new SqlCommand("proc_TransferStockDaily_BySKU_GetProduct", cn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
reader = cmd.ExecuteReader();
productList.Add("-1", "---All---");
while (reader.Read())
{
productList.Add(reader["ProductID"].ToString(), reader["ProductID"].ToString() + " - " + reader["ProductName"].ToString());
}
cn.Close();
}
ddlProduct.Items.Clear();
ddlProduct.DataSource = productList;
ddlProduct.DataTextField = "Value";
ddlProduct.DataValueField = "Key";
ddlProduct.DataBind();
ddlBranch.Items.Clear();
ddlBranch.DataSource = branchList;
ddlBranch.DataTextField = "Value";
ddlBranch.DataValueField = "Key";
ddlBranch.DataBind();
string _branchID = branchList.FirstOrDefault().Key;
if (!string.IsNullOrEmpty(_branchID))
{
ddlVan.Items.Clear();
List<VanDetails> _vanList = new List<VanDetails>();
_vanList.Add(new VanDetails { BranchID = "-1", VAN_ID = "-1", VanCode = "---All---" });
_vanList.AddRange(vanList.Where(x => x.BranchID == _branchID).OrderBy(y => y.VAN_ID).ToList());
ddlVan.DataSource = _vanList;
ddlVan.DataTextField = "VanCode";
ddlVan.DataValueField = "VAN_ID";
ddlVan.DataBind();
}
Dictionary<string, string> repportTypeList = new Dictionary<string, string>();
repportTypeList.Add("PAT1", "MonthlyReport");
repportTypeList.Add("PAT2", "YearlyReport");
}
catch (Exception ex)
{
Helper.WriteLog(ex.Message);
throw ex;
}
}
protected void CrystalReportViewer1_Load(object sender, EventArgs e)
{
GenReport();
}
protected void btnReport_Click(object sender, EventArgs e)
{
}
private void GenReport()
{
try
{
if (!string.IsNullOrEmpty(txtDocDate.Text))
{
//DateTime _checkDateF = DateTime.ParseExact(txtDocDate.Text, "dd/MM/yyyy", null); //Convert.ToDateTime(txtStartDate.Text);
//short updateDataFlag = 1;
//if (_checkDateF.ToShortDateString() == DateTime.Now.ToShortDateString())
//{
// DateTime date1 = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 12, 45, 00);
// DateTime date2 = DateTime.Now;
// int value = DateTime.Compare(date1, date2);
// if (value > 0)
// {
// updateDataFlag = 0;
// ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "showStockAlertMsg()", true);
// }
//}
string branch = ddlBranch.SelectedValue.ToString() == "-1" ? "" : ddlBranch.SelectedValue.ToString();
string van = ddlVan.SelectedValue.ToString() == "-1" ? "" : ddlVan.SelectedValue.ToString();
string prdId = ddlProduct.SelectedValue.ToString() == "-1" ? "" : ddlProduct.SelectedValue.ToString();
string docDate = "";
var _docDate = txtDocDate.Text.Split('/').ToList();
docDate = string.Join("/", _docDate[1], _docDate[0], _docDate[2]);
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString))
{
SqlCommand cmd = null;
cn.Open();
cmd = new SqlCommand("proc_TransferStockDaily_BySKU_SubGetData", cn);
cmd.CommandTimeout = 0;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@BranchID", branch));
cmd.Parameters.Add(new SqlParameter("@VAN_ID", van));
cmd.Parameters.Add(new SqlParameter("@DocDate", docDate));
cmd.Parameters.Add(new SqlParameter("@ProductID", prdId));
cmd.ExecuteNonQuery();
cn.Close();
cn.Open();
cmd = new SqlCommand("proc_TransferStockDaily_BySKU_GetData", cn);
cmd.CommandTimeout = 0;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
//cmd.Parameters.Add(new SqlParameter("@BranchID", branch));
//cmd.Parameters.Add(new SqlParameter("@VAN_ID", van));
//cmd.Parameters.Add(new SqlParameter("@DocDate", docDate));
//cmd.Parameters.Add(new SqlParameter("@DocDate", prdId));
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "TransferStockBySKUReport");
DataTable dt = new DataTable();
dt = ds.Tables["TransferStockBySKUReport"];
rdoc.Load(Server.MapPath("TransferStockBySKUReport.rpt"));
rdoc.SetDataSource(dt);
//rdoc.SetParameterValue("@BranchID", branch);
//rdoc.SetParameterValue("@VAN_ID", van);
//rdoc.SetParameterValue("@DocDate", docDate);
CrystalReportViewer1.RefreshReport();
CrystalReportViewer1.ReportSource = rdoc;
CrystalReportViewer1.DataBind();
cn.Close();
}
}
}
catch (Exception ex)
{
Helper.WriteLog(ex.Message);
throw ex;
}
}
protected void ddlBranch_SelectedIndexChanged(object sender, EventArgs e)
{
InitddlBranch();
}
private void InitddlBranch()
{
var _vanList = new List<VanDetails>();
var _salArea = new List<SaleArea>();
if (ddlBranch.SelectedValue != "-1")
{
_vanList.Add(new VanDetails { BranchID = "-1", VAN_ID = "-1", VanCode = "---All---" });
_vanList.AddRange(vanList.Where(x => x.BranchID == ddlBranch.SelectedItem.Value).OrderBy(y => y.VAN_ID).ToList());
}
else
{
_vanList.Add(new VanDetails { BranchID = "-1", VAN_ID = "-1", VanCode = "---All---" });
_vanList.AddRange(vanList.OrderBy(y => y.VAN_ID).ToList());
}
ddlVan.Items.Clear();
ddlVan.DataSource = _vanList;
ddlVan.DataTextField = "VanCode";
ddlVan.DataValueField = "VAN_ID";
ddlVan.DataBind();
}
} |
/*
* Pedometer
* Copyright (c) 2017 Yusuf Olokoba
*/
namespace PedometerU {
using Platforms;
using System;
using System.Linq;
public sealed class Pedometer : IDisposable {
#region --Properties--
/// <summary>
/// How many updates has this pedometer received? Useful for calculating pedometer precision
/// </summary>
public int updateCount { get; private set; }
/// <summary>
/// Pedometer implementation for the current device. Do not use unless you know what you are doing
/// </summary>
public static IPedometer Implementation {
get {
return _Implementation = _Implementation ?? new IPedometer[] {
new PedometerAndroid(),
new PedometeriOS(),
new PedometerGPS() // Always supported, uses GPS (so highly inaccurate)
}.First(impl => impl.IsSupported).Initialize();
}
}
private static IPedometer _Implementation;
#endregion
#region --Op vars--
private int initialSteps; // Some step counters count from device boot, so subtract the initial count we get
private double initialDistance;
private readonly StepCallback callback;
#endregion
#region --Ctor--
/// <summary>
/// Create a new pedometer and start listening for updates
/// </summary>
public Pedometer (StepCallback callback) {
this.callback = callback;
Implementation.OnStep += OnStep;
}
#endregion
#region --Operations--
/// <summary>
/// Stop listening for pedometer updates and dispose the object
/// </summary>
public void Dispose () {
Implementation.OnStep -= OnStep;
}
/// <summary>
/// Release Pedometer and all of its resources
/// </summary>
public static void Release () {
if (_Implementation == null) return;
// Release and dereference
_Implementation.Release();
_Implementation = null;
}
private void OnStep (int steps, double distance) { // DEPLOY // UpdateCount post increment
// Set initials and increment update count
initialSteps = updateCount++ == 0 ? steps : initialSteps;
initialDistance = steps == initialSteps ? distance : initialDistance;
// If this is not the first step, then invoke the callback
if (steps != initialSteps) if (callback != null) callback(steps - initialSteps, distance - initialDistance);
}
#endregion
}
/// <summary>
/// A delegate used to pass pedometer information
/// </summary>
/// <param name="steps">Number of steps taken</param>
/// <param name="distance">Distance walked in meters</param>
public delegate void StepCallback (int steps, double distance);
} |
using System;
using System.Text;
namespace NStandard
{
public static partial class ConvertEx
{
private static class Base58Converter
{
private const string CHARS = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
private static readonly int[] Map =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, -1, -1, -1, -1, -1, -1,
-1, 9, 10, 11, 12, 13, 14, 15, 16, -1, 17, 18, 19, 20, 21, -1,
22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, -1, -1,
-1, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, -1, 44, 45, 46,
47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
};
public static string ToBase58String(byte[] bytes)
{
//Refer: https://github.com/bitcoin/bitcoin/blob/master/src/base58.cpp
// Skip & count leading zeroes.
int zeroCount = 0;
int length = 0;
foreach (var ch in bytes)
{
if (ch == 0) zeroCount++;
else break;
}
// Allocate enough space in big-endian base58 representation.
var size = (bytes.Length - zeroCount) * 138 / 100 + 1; // log(256) / log(58)
var b58 = new byte[size];
// Process the bytes.
foreach (var ch in bytes)
{
int carry = ch;
int len = 0;
// Apply "b58 = b58 * 256 + ch"
for (int i = size - 1; (carry != 0 || len < length) && i >= 0; i--, len++)
{
carry += 256 * b58[i];
b58[i] = (byte)(carry % 58);
carry /= 58;
}
length = len;
}
var sb = new StringBuilder();
sb.Append("1".Repeat(zeroCount));
for (int i = size - length; i < size; i++)
{
// Skip leading zeroes in base58 result.
if (b58[i] == 0) continue;
for (int j = i; j < size; j++)
sb.Append(CHARS[b58[j]]);
break;
}
return sb.ToString();
}
public static byte[] FromBase58String(string str)
{
//Refer: https://github.com/bitcoin/bitcoin/blob/master/src/base58.cpp
str = str.Replace(" ", "");
// Skip and count leading '1's.
int zeroCount = 0;
int length = 0;
foreach (var ch in str)
{
if (ch == '1') zeroCount++;
else break;
}
// Allocate enough space in big-endian base256 representation.
int size = str.Length * 733 / 1000 + 1; // log(58) / log(256), rounded up.
var b256 = new byte[size];
// Process the characters.
foreach (var ch in str)
{
// Decode base58 character
int carry = Map[ch];
if (carry == -1) throw new FormatException("Invalid Base58 character.");
int len = 0;
for (int i = size - 1; (carry != 0 || len < length) && i >= 0; i--, len++)
{
carry += 58 * b256[i];
b256[i] = (byte)(carry % 256);
carry /= 256;
}
length = len;
}
var bytes = new byte[zeroCount + length];
for (int i = size - length, bi = zeroCount; i < size; i++, bi++)
{
bytes[bi] = b256[i];
}
return bytes;
}
}
}
}
|
using System.Web.Mvc;
using Profiling2.Domain.Contracts.Tasks.Sources;
using Profiling2.Domain.Prf;
using Profiling2.Domain.Prf.Sources;
using Profiling2.Web.Mvc.Controllers;
namespace Profiling2.Web.Mvc.Areas.Profiling.Controllers
{
[PermissionAuthorize(AdminPermission.CanViewAndSearchSources)]
public class AdminSourceSearchesController : BaseController
{
protected readonly ISourceTasks sourceTasks;
protected readonly ISourceAttachmentTasks sourceAttachmentTasks;
public AdminSourceSearchesController(ISourceTasks sourceTasks, ISourceAttachmentTasks sourceAttachmentTasks)
{
this.sourceTasks = sourceTasks;
this.sourceAttachmentTasks = sourceAttachmentTasks;
}
public ActionResult Details(int id)
{
AdminSourceSearch model = this.sourceAttachmentTasks.GetAdminSourceSearch(id);
return View(model);
}
}
}
|
using Communicator.Infrastructure.Commands;
using Communicator.Infrastructure.Commands.Users;
using Communicator.Infrastructure.IServices;
using System.Threading.Tasks;
namespace Communicator.Infrastructure.Handlers.Users
{
public class DeleteUserHandler : ICommandHandler<DeleteUser>
{
private readonly IUserService _userService;
public DeleteUserHandler(IUserService service)
{
_userService = service;
}
public async Task Handle(DeleteUser command)
{
await Task.Delay(1);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace APP_Biblioteca
{
public class Libro //Estableciendo valores
{
public Int64 ID { get; set; }
public String Titulo { get; set; }
public String Edicion { get; set; }
public String Idioma { get; set; }
public String Genero { get; set; }
public String ISBN { get; set; }
public String No_Pags { get; set; }
public String Tomo { get; set; }
public String Ubicacion { get; set; }
public String Formato { get; set; }
public String Costo { get; set; }
public bool Estado { get; set; }
public Int32 IDEdit { get; set; }
public Int32 IDAutor { get; set; }
public Int32 IDPais { get; set; }
public Int32 IDMoneda { get; set; }
public Libro() { }
//Constructor
public Libro(Int64 xID, String xTitulo, String xISBN, String xEdicion,
String xGenero, String xIdioma, String xNo_Pags, String xTomo, String xUbicacion,
String xFormato, String xCosto, Int32 xIDEdit, Int32 xIDAutor, Int32 xIDPais, Int32 xIDMoneda)
{
this.ID = xID;
this.Titulo = xTitulo;
this.Edicion = xEdicion;
this.Idioma = xIdioma;
this.Genero = xGenero;
this.ISBN = xISBN;
this.No_Pags = xNo_Pags;
this.Tomo = xTomo;
this.Ubicacion = xUbicacion;
this.Formato = xFormato;
this.Costo = xCosto;
this.Estado = true;
this.IDEdit = xIDEdit;
this.IDAutor = xIDAutor;
this.IDPais = xIDPais;
this.IDMoneda = xIDMoneda;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO.Ports;
using System.IO;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.Management;
using System.Diagnostics;
using Ajustador_Calibrador_ADR3000.Helpers;
namespace Ajustador_Calibrador_ADR3000.Devices
{
/// <summary>
/// Class to communicate with a standard reference meter. It encapsulates the Radian, GFUVE and Zera standards.
/// </summary>
public class StandardMeter : IDisposable
{
private const int GF333B_MEASURES_SIZE = 39;
private const int RMM3006_MEASURES_SIZE = 36;
private const int MAX_RMM3006_TRY = 2; // Max attempts = n + 1 = 3
private const int MAX_GF333B_TRY = 5; // Max attempts = n + 1 = 6
private const int MAX_RD20_TRY = 4; // Max attempts = n + 1 = 3
private const int MAX_PRESCALER_TRY = 4;// Max attempts = n + 1 = 3
//
// Valid values for the measurement mode
//
public const int _4Wa = 0;
public const int _4Wr = 1;
public const int _4Wrc = 2;
public const int _3Wa = 3;
public const int _3Wr = 4;
public const int _3Wrca = 5;
public const int _3Wrcb = 6;
public const int _4Wap = 7;
public const int _4Wr60 = 8;
public const int _3Wap = 9;
public const int _4Q60c = 10;
public const int _3WQ60 = 11;
public const int _3Q60c = 12;
public const int _4Wapg = 13;
public const int _3Wapg = 14;
public const int _4Wrg = 15;
public const int _3Wrg = 16;
public const int U480V = 0;
public const int U240V = 1;
public const int U120V = 2;
public const int U60V = 3;
public const int I200A = 0;
public const int I100A = 1;
public const int I50A = 2;
public const int I20A = 3;
public const int I10A = 4;
public const int I5A = 5;
public const int I2A = 6;
public const int I1A = 7;
public const int I500mA = 8;
public const int I200mA = 9;
public const int I100mA = 10;
public const int I50mA = 11;
public const int I20mA = 12;
public const int I10mA = 13;
public const int I5mA = 14;
public const int LOW_TO_HIGH_THRESHOLD = 16;
//
// Public variables, classes, structures and attributes to be used
//
public enum StandardType
{
/// <summary>
/// GFUVE GF333B standard meter.
/// </summary>
GF333B = 0,
/// <summary>
/// Radian RD20 standard meter.
/// </summary>
RD20 = 1,
/// <summary>
/// Zera RMM3006 standard meter.
/// </summary>
RMM3006 = 2,
GF333BM = 3
};
public enum EnergyType
{
/// <summary>
/// The active energy type.
/// </summary>
ACTIVE = 0,
/// <summary>
/// The reactive energy type.
/// </summary>
REACTIVE = 1
};
public enum RangeType
{
MANUAL,
AUTOMATIC
}
//
// Private variables, classes, structures and attributes to be used
//
private bool disposed;
private readonly SafeHandle handle = new SafeFileHandle(IntPtr.Zero, true);
private SerialPort port, portCounter;
private readonly StandardType standardType;
private byte[] myStdBuffer = new byte[1024];
private string rMM30006_Answer = "";
private string gf333B_Answer = "";
private int mIndex = 0;
public StandardType Standard
{
get
{
return standardType;
}
}
/// <summary>
/// Constructor for the StandardMeter class.
/// </summary>
/// <param name="type">The type of the standard.</param>
public StandardMeter(StandardType type)
{
standardType = type;
}
/// <summary>
/// Verifies wich standard is being used and connects to the correct one.
/// </summary>
public void ConnectToStandard(bool hasPrescaler)
{
switch (standardType)
{
case StandardType.GF333B:
case StandardType.GF333BM:
ConnectToGF333B(hasPrescaler);
break;
case StandardType.RD20:
ConnectToRD20();
break;
case StandardType.RMM3006:
ConnectToRMM3006(hasPrescaler);
break;
default:
break;
}
}
/// <summary>
/// Requests measures from the standard being used by the StandardMeter class.
/// </summary>
/// <returns>A float array containing the measures.</returns>
public float[] GetMeasures()
{
//
// A float array to be returned by the method
//
bool keepTrying;
float[] measures = new float[] { 0.0f };
int i, j, k;
int tryCount = 0;
//
// Checks what type of standard is being used and performs the correct action
//
switch (standardType)
{
case StandardType.GF333B:
case StandardType.GF333BM:
/*Measures:
0 - U1 3 - U12 6 - I1 9 - phi1 12 - phi+ 15 - phiU1U3 18 - phiU1I3 21 - P3 24 - Q2 27 - freq 30 - ES 33 - Ea 36 - N
1 - U2 4 - U23 7 - I2 10 - phi2 13 - phiU1U1 16 - phiU1I1 19 - P1 22 - P+ 25 - Q3 28 - US 31 - Ep 34 - TM 37 - ERROR
2 - U3 5 - U31 8 - I3 11 - phi3 14 - phiU1U2 17 - phiU1I2 20 - P2 23 - Q1 26 - Q+ 29 - IS 32 - Eq 35 - C 38 - Cmeter*/
while (true)
{
try
{
//
// Clears the output buffer, sends a command, reads and clears the input buffer
//
keepTrying = false;
Interlocked.Exchange(ref gf333B_Answer, "");
port.DiscardOutBuffer();
port.Write("$$00000068!!");
uint ticks = GetTickCount();
while (!gf333B_Answer.Contains("!!"))
{
if (GetTickCount() - ticks >= port.ReadTimeout)
{
if (tryCount < MAX_GF333B_TRY)
{
tryCount++;
keepTrying = true;
break;
}
else throw new IOException("Problemas na comunicação com o padrão GF333B");
}
}
if (!keepTrying) break;
}
catch (Exception)
{
if (tryCount < MAX_GF333B_TRY) tryCount++;
else throw new IOException("Problemas na comunicação com o padrão GF333B");
}
}
string answer = gf333B_Answer;
measures = new float[GF333B_MEASURES_SIZE];
//
// First gets the measures values
//
i = 8;
j = 0;
while (j < 28)
{
measures[j++] = ASCIItoFloat(answer.Substring(i, 8));
i += 8;
}
//
// Converts W to kW, var to kvar and VA to kVA
//
for (i = 19; i < 27; i++) measures[i] /= 1000;
//
// Status words for voltage, current and extended
//
i = 29 * 8; // i = 8 + 28 * 8
for (j = 0; j < 3; j++)
{
measures[28 + j] = ASCIItoInteger(answer.Substring(i, 4));
i += 4;
}
//
// Energies in kWh, kvarh and kVA
//
for (j = 0; j < 3; j++)
{
measures[31 + j] = ASCIItoFloat(answer.Substring(i, 8));
i += 8;
}
//
// Energy time in ms
//
measures[34] = ASCIItoInteger(answer.Substring(i, 8));
i += 8;
//
// GF333B-M constant
//
measures[35] = ASCIItoFloat(answer.Substring(i, 8));
i += 8;
//
// Present circle number
//
measures[36] = ASCIItoInteger(answer.Substring(i, 4));
i += 4;
//
// Error
//
measures[37] = ASCIItoFloat(answer.Substring(i, 8));
i += 8;
//
// Meter constant
//
measures[38] = ASCIItoFloat(answer.Substring(i, 8));
break;
case StandardType.RD20:
//
// Instantiates the buffer to be sent to the standard
//
byte[] buffer;
int numOfBytesRead = 0;
int checkSum;
TRY: buffer = new byte[] { 0xA6, 0x0D, 0x00, 0x08, 0x00, 0x24, 0x00, 0x00, 0x00, 0x14, 0xFF, 0xFD, 0x02, 0xEF };
//
// Clears the output buffer, sends a command, reads and clears the input buffer
//
port.DiscardOutBuffer();
port.Write(buffer, 0, buffer.Length);
Thread.Sleep(250);
buffer = new byte[42];
numOfBytesRead = 0;
for (i = 0; i < 42; i++)
{
try
{
numOfBytesRead += port.Read(buffer, i, 1);
}
catch (Exception ex)
{
if (tryCount < MAX_RD20_TRY)
{
tryCount++;
port.DiscardInBuffer();
goto TRY;
}
else throw new IOException(ex.Message + Environment.NewLine + "StandardMeter.GetMeasures().");
}
}
port.DiscardInBuffer();
//
// Verifies the integrity of the answer based on the checksum sent by the RD20
//
checkSum = BitConverter.ToInt32(new byte[] { buffer[numOfBytesRead - 1], buffer[numOfBytesRead - 2], 0, 0 }, 0);
if ((uint)checkSum != CheckSum(buffer, numOfBytesRead - 2))
{
if (tryCount < MAX_RD20_TRY)
{
tryCount++;
port.DiscardInBuffer();
goto TRY;
}
else throw new IOException("Checksum incorreto enviado pelo padrão RD20");
}
//
// Creates a buffer to store only data related to measures, excluding header, footer and checksum
//
byte[] bMeasures = new byte[36], data;
Buffer.BlockCopy(buffer, 4, bMeasures, 0, bMeasures.Length);
//
// Allocates the necessary memory to store the floating point numbers
//
measures = new float[9];
//
// Converts each group of four bytes into one IEEE 754 floating point number
//
k = 0;
for (j = 0; j < bMeasures.Length; j += 4)
{
data = new byte[] { bMeasures[j], bMeasures[j + 1], bMeasures[j + 2], bMeasures[j + 3] };
measures[k++] = bytesTofloat(data);
}
break;
case StandardType.RMM3006:
while (true)
{
try
{
keepTrying = false;
measures = new float[RMM3006_MEASURES_SIZE];
string endChar = "MEACK\r";
Interlocked.Exchange(ref rMM30006_Answer, "");
port.DiscardOutBuffer();
port.Write("ME\r");
uint ticks = GetTickCount();
while (!rMM30006_Answer.Contains(endChar))
{
if (GetTickCount() - ticks >= port.ReadTimeout)
{
if (tryCount < MAX_RMM3006_TRY)
{
tryCount++;
keepTrying = true;
break;
}
else throw new IOException("Problemas na comunicação com o padrão RMM3006");
}
}
if (!keepTrying) break;
}
catch (Exception)
{
if (tryCount < MAX_RMM3006_TRY) tryCount++;
else throw new IOException("Problemas na comunicação com o padrão RMM3006");
}
}
string[] values = rMM30006_Answer.Split('\r');
for (i = 0; i < measures.Length; i++)
{
string[] measure = values[i].Split(';');
measures[i] = float.Parse(measure[1], System.Globalization.NumberStyles.Float);
}
break;
default:
break;
}
return (measures);
}
/// <summary>
/// Get information about the ranges of the standard (voltage and current).
/// </summary>
/// <returns>An int array with the information about the ranges.</returns>
public int[] GetRangeStatus()
{
int[] Ranges = new int[3];
bool keepTrying;
int tryCount = 0;
switch (standardType)
{
case StandardType.RMM3006:
while (true)
{
try
{
keepTrying = false;
string endChar = "STACK\r";
Interlocked.Exchange(ref rMM30006_Answer, "");
port.DiscardOutBuffer();
port.Write("ST\r");
uint ticks = GetTickCount();
while (!rMM30006_Answer.Contains(endChar))
{
if (GetTickCount() - ticks >= port.ReadTimeout)
{
if (tryCount < MAX_RMM3006_TRY)
{
tryCount++;
keepTrying = true;
break;
}
else throw new IOException("Problemas na comunicação com o padrão RMM3006");
}
}
if (!keepTrying) break;
}
catch (Exception)
{
if (tryCount < MAX_RMM3006_TRY) tryCount++;
else throw new IOException("Problemas na comunicação com o padrão RMM3006");
}
}
//
// Treats the standard's answer
//
string[] values = rMM30006_Answer.Split('\r');
string vRng = values[0].Substring(3, 3);
string iRng = values[1].Substring(3, 3);
string mMode = values[2].Substring(2, 5);
switch (vRng)
{
case "240": Ranges[0] = U240V; break;
case "120": Ranges[0] = U120V; break;
case " 60": Ranges[0] = U60V; break;
default: Ranges[0] = U480V; break;
}
switch (iRng)
{
case "100": Ranges[1] = I100A; break;
case " 50": Ranges[1] = I50A; break;
case " 20": Ranges[1] = I20A; break;
case " 10": Ranges[1] = I10A; break;
case " 5": Ranges[1] = I5A; break;
case " 2": Ranges[1] = I2A; break;
case " 1": Ranges[1] = I1A; break;
case "0.5": Ranges[1] = I500mA; break;
case "0.2": Ranges[1] = I200mA; break;
case "0.1": Ranges[1] = I100mA; break;
case "50m": Ranges[1] = I50mA; break;
case "20m": Ranges[1] = I20mA; break;
case "10m": Ranges[1] = I10mA; break;
case " 5m": Ranges[1] = I5mA; break;
default: Ranges[1] = I200A; break;
}
switch (mMode)
{
case " 4Wa": Ranges[2] = _4Wa; break;
case " 4Wr": Ranges[2] = _4Wr; break;
case " 4Wrc": Ranges[2] = _4Wrc; break;
case " 3Wa": Ranges[2] = _3Wa; break;
case " 3Wr": Ranges[2] = _3Wr; break;
case "3Wrca": Ranges[2] = _3Wrca; break;
case "3Wrcb": Ranges[2] = _3Wrcb; break;
case " 4Wap": Ranges[2] = _4Wap; break;
case "4Wr60": Ranges[2] = _4Wr60; break;
case " 3Wap": Ranges[2] = _3Wap; break;
case "4Q60c": Ranges[2] = _4Q60c; break;
case "3WQ60": Ranges[2] = _3WQ60; break;
case "3Q60c": Ranges[2] = _3Q60c; break;
case "4Wapg": Ranges[2] = _4Wapg; break;
case "3Wapg": Ranges[2] = _3Wapg; break;
case " 4Wrg": Ranges[2] = _4Wrg; break;
default: Ranges[2] = _3Wrg; break;
}
break;
default:
break;
}
return Ranges;
}
/// <summary>
/// Gets the best voltage range that suits the standard given a voltage value.
/// </summary>
/// <param name="voltage">A voltage value.</param>
/// <returns>An int array with the range and the constant multiplier.</returns>
public int[] GetBestVoltageRange(float voltage)
{
int UR = U480V;
int vRngMult = 1;
switch (standardType)
{
case StandardType.RMM3006:
if (voltage < 60)
{
UR = U60V;
vRngMult = 8;
}
else if ((voltage >= 60) && (voltage < 120))
{
UR = U120V;
vRngMult = 4;
}
else if ((voltage >= 120) && (voltage < 240))
{
UR = U240V;
vRngMult = 2;
}
else if ((voltage >= 240) && (voltage < 480))
{
UR = U480V;
vRngMult = 1;
}
else
{
throw new ArgumentException("Valor de tensão do ponto inválido.");
}
break;
default:
break;
}
return (new int[] { UR, vRngMult });
}
/// <summary>
/// Gets the best current range that suits the standard given a current value.
/// </summary>
/// <param name="current">A current value.</param>
/// <returns>An int array with the range and the constant multiplier.</returns>
public int[] GetBestCurrentRange(float current)
{
int iRngMult = 1;
int IR = I200A;
switch (standardType)
{
case StandardType.RMM3006:
if ((current >= 0.005f) && (current < 0.010f))
{
IR = I10mA;
iRngMult = 20000;
}
else if ((current >= 0.010f) && (current < 0.020f))
{
IR = I20mA;
iRngMult = 10000;
}
else if ((current >= 0.020f) && (current < 0.050f))
{
IR = I50mA;
iRngMult = 4000;
}
else if ((current >= 0.050f) && (current < 0.100f))
{
IR = I100mA;
iRngMult = 2000;
}
else if ((current >= 0.100f) && (current < 0.200f))
{
IR = I200mA;
iRngMult = 1000;
}
else if ((current >= 0.200f) && (current < 0.500f))
{
IR = I500mA;
iRngMult = 400;
}
else if ((current >= 0.500f) && (current < 1.0f))
{
IR = I1A;
iRngMult = 200;
}
else if ((current >= 1.0f) && (current < 2.0f))
{
IR = I2A;
iRngMult = 100;
}
else if ((current >= 2.0f) && (current < 5.0f))
{
IR = I5A;
iRngMult = 40;
}
else if ((current >= 5.0f) && (current < 10.0f))
{
IR = I10A;
iRngMult = 20;
}
else if ((current >= 10.0f) && (current < 16.0f))
{
IR = I20A;
iRngMult = 10;
}
else if ((current >= 16.0f) && (current < 50.0f))
{
IR = I50A;
iRngMult = 4;
}
else if ((current >= 50.0f) && (current < 100.0f))
{
IR = I100A;
iRngMult = 2;
}
else if ((current >= 100.0f) && (current < 160.0f))
{
IR = I200A;
iRngMult = 1;
}
else
{
throw new ArgumentException("Valor de corrente inválido");
}
break;
default:
break;
}
return (new int[] { IR, iRngMult });
}
/// <summary>
/// Method to configure the voltage range of the standard.
/// </summary>
/// <param name="vRng">An integer representing the range.</param>
/// <returns>true if success, false otherwise.</returns>
public bool SetActualVoltageRange(int vRng)
{
bool keepTrying;
int tryCount = 0;
switch (standardType)
{
case StandardType.RMM3006:
//
// Sends interface connection request to the standard (best of 3)
//
if ((vRng < 0) || (vRng > U60V)) return (false);
while (true)
{
keepTrying = false;
string endChar = "UBACK\r";
Interlocked.Exchange(ref rMM30006_Answer, "");
port.DiscardOutBuffer();
port.Write("UB" + vRng.ToString() + "\r");
uint ticks = GetTickCount();
while (!rMM30006_Answer.Contains(endChar))
{
if (GetTickCount() - ticks >= port.ReadTimeout)
{
if (tryCount < MAX_RMM3006_TRY)
{
tryCount++;
keepTrying = true;
break;
}
else return (false);
}
}
if (!keepTrying) break;
}
break;
default:
break;
}
return (true);
}
/// <summary>
/// Method to configure the current range of the standard.
/// </summary>
/// <param name="iRng">An integer representing the range.</param>
/// <returns>true if success, false otherwise.</returns>
public bool SetActualCurrentRange(int iRng)
{
bool keepTrying;
int tryCount = 0;
switch (standardType)
{
case StandardType.RMM3006:
//
// Sends interface connection request to the standard (best of 3)
//
if ((iRng < 0) || (iRng > I5mA)) return (false);
while (true)
{
keepTrying = false;
string endChar = "IBACK\r";
Interlocked.Exchange(ref rMM30006_Answer, "");
port.DiscardOutBuffer();
port.Write("IB" + iRng.ToString() + "\r");
uint ticks = GetTickCount();
while (!rMM30006_Answer.Contains(endChar))
{
if (GetTickCount() - ticks >= port.ReadTimeout)
{
if (tryCount < MAX_RMM3006_TRY)
{
tryCount++;
keepTrying = true;
break;
}
else return (false);
}
}
if (!keepTrying) break;
}
break;
default:
break;
}
return (true);
}
/// <summary>
/// Requests the interface connection from the standard.
/// </summary>
/// <returns>
/// Returns true if the operation was successful, false otherwise.
/// </returns>
public bool RequestConnection()
{
bool keepTrying;
bool retVal = true;
int tryCount = 0;
switch (standardType)
{
case StandardType.RMM3006:
//
// Sends interface connection request to the standard (best of 3)
//
while (true)
{
keepTrying = false;
string endChar = "RQACK\r";
Interlocked.Exchange(ref rMM30006_Answer, "");
port.DiscardOutBuffer();
port.Write("RQ\r");
uint ticks = GetTickCount();
while (!rMM30006_Answer.Contains(endChar))
{
if (GetTickCount() - ticks >= port.ReadTimeout)
{
if (tryCount < MAX_RMM3006_TRY)
{
tryCount++;
keepTrying = true;
break;
}
else
{
retVal = false;
break;
}
}
}
if (!keepTrying) break;
}
break;
default:
break;
}
return (retVal);
}
public void SetK1K2(bool low_k1, bool high_k2)
{
//
// This method configures the keys for the current path.
// There is one for the high current scale (4 A < I <= 45 A) and
// another for the low current scale (I <= 4 A).
//
int command = 0x11;
long data = 0;
switch (standardType)
{
case StandardType.RMM3006:
if (low_k1) data |= 0x02;
if (high_k2) data |= 0x01;
if (!SendCommandToPrescaller(command, data))
{
throw new IOException("Problemas na comunicação com o prescaller.");
}
break;
default:
break;
}
}
/// <summary>
/// Terminates the interface connection from the standard.
/// </summary>
/// <returns>
/// Returns true if the operation was successful, false otherwise.
/// </returns>
public bool TerminateConnection()
{
bool keepTrying;
bool retVal = true;
int tryCount = 0;
switch (standardType)
{
case StandardType.RMM3006:
//
// Sends interface connection request to the standard (best of 3)
//
while (true)
{
keepTrying = false;
string endChar = "NRACK\r";
Interlocked.Exchange(ref rMM30006_Answer, "");
port.DiscardOutBuffer();
port.Write("NR\r");
uint ticks = GetTickCount();
while (!rMM30006_Answer.Contains(endChar))
{
if (GetTickCount() - ticks >= port.ReadTimeout)
{
if (tryCount < MAX_RMM3006_TRY)
{
tryCount++;
keepTrying = true;
break;
}
else
{
retVal = false;
break;
}
}
}
if (!keepTrying) break;
}
break;
default:
break;
}
return (retVal);
}
/// <summary>
/// Configures the pulse constant in Wh/pulse.
/// </summary>
/// <param name="type">The nature of the energy pulse. Can be active or reactive.</param>
/// <param name="kd">The constant in Wh/pulse.</param>
/// <param name="kh">In the case of the GF333B, it must be passed the kh in pulses/Wh of the current scale</param>
public void SetKd(EnergyType type, float kd, int kh)
{
int numOfBytesRead = 0, i, tryCount = 0;
int command;
long data;
switch (standardType)
{
case StandardType.RMM3006:
command = 0x01;
data = (long)(kd * kh);
if (!SendCommandToPrescaller(command, data)) throw new IOException("Problemas na comunicação com o prescaller.");
break;
case StandardType.GF333B:
case StandardType.GF333BM:
if (type == EnergyType.ACTIVE) command = 0x01;
else command = 0x04;
data = (long)(kd * kh);
if (!SendCommandToPrescaller(command, data)) throw new IOException("Problemas na comunicação com o prescaller.");
break;
case StandardType.RD20:
//
// Creates a buffer to store the bytes related to the TI floating point number
//
byte[] tikd = new byte[4];
//
// Converts the IEEE 754 floating point to 4 bytes representing a TI floating point
//
floatTobytes(kd, tikd);
//
// Creates a buffer to be sent to the RD20 containing the command.
//
byte[] RD20Buffer;
uint cks;
TRY: RD20Buffer = new byte[] { 0xA6, 0x32, 0x00, 0x07, 0x00, (byte)type, 0x00, tikd[0], tikd[1], tikd[2], tikd[3], 0x00, 0x00 };
cks = CheckSum(RD20Buffer, 11);
RD20Buffer[11] = (byte)((cks >> 8) & 0xFF);
RD20Buffer[12] = (byte)(cks & 0xFF);
//
// Clears the output buffer, sends a command, reads and clears the input buffer
//
port.DiscardOutBuffer();
port.Write(RD20Buffer, 0, RD20Buffer.Length);
Thread.Sleep(250);
RD20Buffer = new byte[4];
for (i = 0; i < 4; i++)
{
try
{
numOfBytesRead += port.Read(RD20Buffer, i, 1);
}
catch (Exception ex)
{
if (tryCount < MAX_RD20_TRY)
{
tryCount++;
port.DiscardInBuffer();
goto TRY;
}
else throw new IOException(ex.Message + Environment.NewLine + "StandardMeter.SetKd().");
}
}
port.DiscardInBuffer();
//
// Verifies the integrity of the answer sent by the RD20
//
if (!CheckArrays(RD20Buffer, new byte[] { 0xA3, 0x32, 0x00, 0xD5 }))
{
if (tryCount < MAX_RD20_TRY)
{
tryCount++;
port.DiscardInBuffer();
goto TRY;
}
else throw new IOException("Resposta incorreta enviada pelo padrão RD20.");
}
break;
default:
break;
}
}
public void SetPulseOutputFrequency(ushort scale, ushort currentScales)
{
}
/// <summary>
/// Sets the nature of the energy being represented by the pulse output of the standard.
/// </summary>
/// <param name="type">The type of energy. It can be ACTIVE or REACTIVE.</param>
public void SetPulseEnergyType(EnergyType type)
{
bool keepTrying;
int numOfBytesRead = 0, i, tryCount = 0;
switch (standardType)
{
case StandardType.RMM3006:
//
// Sends interface connection request to the standard (best of 3)
//
while (true)
{
keepTrying = false;
string endChar = "MSACK\r";
Interlocked.Exchange(ref rMM30006_Answer, "");
port.DiscardOutBuffer();
if (type == EnergyType.ACTIVE) port.Write("MS0\r");
else port.Write("MS1\r");
uint ticks = GetTickCount();
while (!rMM30006_Answer.Contains(endChar))
{
if (GetTickCount() - ticks >= port.ReadTimeout)
{
if (tryCount < MAX_RMM3006_TRY)
{
tryCount++;
keepTrying = true;
break;
}
else
{
throw new IOException("Problemas na comunicação com o padrão.");
}
}
}
if (!keepTrying) break;
}
break;
case StandardType.GF333BM:
break;
case StandardType.RD20:
//
// Creates a buffer to be sent to the RD20 containing the command.
//
byte[] answer = new byte[] { 0xAC, 0x1D, 0x00, 0x02, 0x01, 0xCC, 0x01, 0x98 };
byte[] buffer;
TRY: buffer = new byte[] { 0xA6, 0x1D, 0x00, 0x02, 0x02, (byte)type, 0x00, (byte)(0xC7 + type) };
//
// Clears the output buffer, sends a command, reads and clears the input buffer
//
port.DiscardOutBuffer();
port.Write(buffer, 0, buffer.Length);
Thread.Sleep(250);
buffer = new byte[8];
for (i = 0; i < 8; i++)
{
try
{
numOfBytesRead += port.Read(buffer, i, 1);
}
catch (Exception ex)
{
if (tryCount < MAX_RD20_TRY)
{
tryCount++;
port.DiscardInBuffer();
goto TRY;
}
else throw new IOException(ex.Message + Environment.NewLine + "StandardMeter.SetPulseEnergyType().");
}
}
port.DiscardInBuffer();
//
// Verifies the integrity of the answer sent by the RD20
//
if (!CheckArrays(buffer, answer))
{
if (tryCount < MAX_RD20_TRY)
{
tryCount++;
port.DiscardInBuffer();
goto TRY;
}
else throw new IOException("Resposta incorreta enviada pelo padrão RD20.");
}
break;
default:
break;
}
}
public void EnablePulseInputToCalibrateMeter(bool enable)
{
float[] measures;
string cmdChar;
bool keepTrying;
int tryCount = 0;
switch (standardType)
{
case StandardType.GF333B:
case StandardType.GF333BM:
measures = GetMeasures();
ushort US = Convert.ToUInt16(measures[28]);
ushort IS = Convert.ToUInt16(measures[29]);
ushort ES = Convert.ToUInt16(measures[30]);
//
// Enables or disables pulse input
//
if (enable)
{
ES |= 0x0002;
}
else
{
ES &= 0xFFFD;
}
cmdChar = "$$01000E" +
UShortToASCII(US) +
UShortToASCII(IS) +
UShortToASCII(ES) + "00";
string gfCks = GF333BCheckSum(cmdChar);
cmdChar += gfCks + "!!";
while (true)
{
//
// Clears the output buffer, sends a command, reads and clears the input buffer
//
keepTrying = false;
Interlocked.Exchange(ref gf333B_Answer, "");
port.DiscardOutBuffer();
port.Write(cmdChar);
uint ticks = GetTickCount();
while (!gf333B_Answer.Contains("!!"))
{
if (GetTickCount() - ticks >= port.ReadTimeout)
{
if (tryCount < MAX_GF333B_TRY)
{
tryCount++;
keepTrying = true;
break;
}
else throw new IOException("Problemas na comunicação com o padrão GF333B");
}
}
if (!keepTrying) break;
}
break;
default:
break;
}
}
public void ConfigRangeType(RangeType rangeType)
{
bool keepTrying;
string cmdChar;
int tryCount = 0;
switch (standardType)
{
case StandardType.RMM3006:
if (rangeType == RangeType.MANUAL) cmdChar = "AMMMM\r";
else cmdChar = "AMAAA\r";
//
// Sends interface connection request to the standard (best of 3)
//
while (true)
{
keepTrying = false;
string endChar = "AMACK\r";
Interlocked.Exchange(ref rMM30006_Answer, "");
port.DiscardOutBuffer();
port.Write(cmdChar);
uint ticks = GetTickCount();
while (!rMM30006_Answer.Contains(endChar))
{
if (GetTickCount() - ticks >= port.ReadTimeout)
{
if (tryCount < MAX_RMM3006_TRY)
{
tryCount++;
keepTrying = true;
break;
}
else
{
throw new IOException("Problemas na comunicação com o padrão.");
}
}
}
if (!keepTrying) break;
}
break;
default:
break;
}
}
public float ExecuteCalibration(EnergyType energyType, float totalPower,
int duration, float khMeter, float tol, bool considerTolerance)
{
float[] measures;
bool keepTrying, keepTesting;
float error = -1.71714748f;
int tryCount = 0;
int numOfTurns;
string cmdChar, outCondition;
int testTimeout = Convert.ToInt32(3 * 1000 * duration);
uint ticks;
string[] sValues = new string[] { "00", "0.000", "-1.71714748" };
switch (standardType)
{
case StandardType.RMM3006:
outCondition = "0";
tryCount = 0;
numOfTurns = Convert.ToInt32(khMeter * totalPower * duration / 3600);
cmdChar = "EP" + numOfTurns +
";0;" + Convert.ToSingle(khMeter).ToString("0.000000") + "e+003\r";
keepTesting = true;
while (keepTesting)
{
//
// Sends command to the standard (best of 3)
//
while (true)
{
keepTrying = false;
string endChar = "EPACK\r";
Interlocked.Exchange(ref rMM30006_Answer, "");
port.DiscardOutBuffer();
port.Write(cmdChar);
ticks = GetTickCount();
while (!rMM30006_Answer.Contains(endChar))
{
if (GetTickCount() - ticks >= port.ReadTimeout)
{
if (tryCount < MAX_RMM3006_TRY)
{
tryCount++;
keepTrying = true;
break;
}
else
{
throw new IOException("Problemas na comunicação com o padrão. StandardMeter.ExecuteCalibration().");
}
}
}
if (!keepTrying) break;
}
//
// Selects accuracy test
//
cmdChar = "EB0\r";
tryCount = 0;
//
// Sends command start the test (best of 3)
//
while (true)
{
keepTrying = false;
string endChar = "EBACK\r";
Interlocked.Exchange(ref rMM30006_Answer, "");
port.DiscardOutBuffer();
port.Write(cmdChar);
ticks = GetTickCount();
while (!rMM30006_Answer.Contains(endChar))
{
if (GetTickCount() - ticks >= port.ReadTimeout)
{
if (tryCount < MAX_RMM3006_TRY)
{
tryCount++;
keepTrying = true;
break;
}
else
{
throw new IOException("Problemas na comunicação com o padrão. StandardMeter.ExecuteCalibration().");
}
}
}
if (!keepTrying) break;
}
//
// Starts requesting the test status to the standard.
// There is a timeout of 2 x duration of the test.
//
cmdChar = "ES\r";
ticks = GetTickCount();
while (!outCondition.Equals("3") && (GetTickCount() - ticks < testTimeout))
{
while (true)
{
keepTrying = false;
string endChar = "ESACK\r";
Interlocked.Exchange(ref rMM30006_Answer, "");
port.DiscardOutBuffer();
port.Write(cmdChar);
uint mTicks = GetTickCount();
while (!rMM30006_Answer.Contains(endChar))
{
if (GetTickCount() - mTicks >= port.ReadTimeout)
{
if (tryCount < MAX_RMM3006_TRY)
{
tryCount++;
keepTrying = true;
break;
}
else
{
throw new IOException("Problemas na comunicação com o padrão. StandardMeter.ExecuteCalibration().");
}
}
}
if (!keepTrying) break;
}
sValues = rMM30006_Answer.Split('\r');
outCondition = sValues[0].Substring(1, 1);
}
if (GetTickCount() - ticks >= testTimeout)
{
throw new IOException("Problemas na comunicação com o padrão. Timeout. StandardMeter.ExecuteCalibration().");
}
error = Convert.ToSingle(sValues[2]);
if (considerTolerance)
{
if (Math.Abs(error) > tol)
{
if (tryCount < MAX_RMM3006_TRY)
{
tryCount++;
}
else keepTesting = false;
}
else keepTesting = false;
}
else keepTesting = false;
}
break;
case StandardType.GF333B:
case StandardType.GF333BM:
numOfTurns = Convert.ToInt32(khMeter * totalPower * duration / 3600);
int statusWord = 0x08;
if (energyType == EnergyType.REACTIVE) statusWord = 0x09;
keepTesting = true;
while (keepTesting)
{
//
// First parametrizes the test for the GF333B or GF333B-M
//
while (true)
{
keepTrying = false;
cmdChar = "$$020010" +
UShortToASCII(Convert.ToUInt16(numOfTurns & 0xFFFF)) +
FloatToASCII(khMeter * 1000) +
UShortToASCII(Convert.ToUInt16(statusWord & 0xFFFF));
string gfCks = GF333BCheckSum(cmdChar);
cmdChar += gfCks + "!!";
Interlocked.Exchange(ref gf333B_Answer, "");
port.DiscardOutBuffer();
port.Write(cmdChar);
ticks = GetTickCount();
while (!gf333B_Answer.Contains("!!"))
{
if (GetTickCount() - ticks >= port.ReadTimeout)
{
if (tryCount < MAX_GF333B_TRY)
{
tryCount++;
keepTrying = true;
break;
}
else
{
throw new IOException("Problemas na comunicação com o padrão. StandardMeter.ExecuteCalibration().");
}
}
}
if (!keepTrying) break;
}
while (true)
{
keepTrying = false;
measures = GetMeasures();
float presentCircleNumber = measures[36];
ticks = GetTickCount();
while (presentCircleNumber == GetMeasures()[36])
{
if (GetTickCount() - ticks >= (2000 * duration))
{
if (tryCount < MAX_GF333B_TRY)
{
tryCount++;
keepTrying = true;
break;
}
else
{
throw new IOException("Problemas na comunicação com o padrão. StandardMeter.ExecuteCalibration().");
}
}
}
if (keepTrying) continue;
while (presentCircleNumber > GetMeasures()[36])
{
if (GetTickCount() - ticks >= (2000 * duration))
{
if (tryCount < MAX_GF333B_TRY)
{
tryCount++;
keepTrying = true;
break;
}
else
{
throw new IOException("Problemas na comunicação com o padrão. StandardMeter.ExecuteCalibration().");
}
}
}
if (!keepTrying) break;
}
//
// Gets the calibration error
//
error = GetMeasures()[37];
if (considerTolerance)
{
if (Math.Abs(error) > tol)
{
if (tryCount < MAX_GF333B_TRY)
{
tryCount++;
}
else keepTesting = false;
}
else keepTesting = false;
}
else keepTesting = false;
}
break;
case StandardType.RD20:
int numOfPulses = Convert.ToInt32(khMeter * totalPower * duration / 3600);
byte[] tiKd = new byte[4];
byte[] bNumPulses = BitConverter.GetBytes(numOfPulses);
float kdOfAdr = 1.0f / khMeter;
floatTobytes(kdOfAdr, tiKd);
//
// Creates a buffer to be sent to the RD20 containing the command.
//
byte[] buffer, inBuffer;
uint cks;
int i;
int pulsesLeft;
TRY: buffer = new byte[] { 0xA6, 0x39, 0x00, 0x10, (byte)energyType, 0x01,
0x00, 0x00, 0xFF, 0xFF, tiKd[0], tiKd[1], tiKd[2], tiKd[3], 0x03, 0x00,
bNumPulses[1], bNumPulses[0], 0x00, 0x01, 0x00, 0x00 };
cks = CheckSum(buffer, 20);
buffer[20] = (byte)((cks >> 8) & 0xFF);
buffer[21] = (byte)(cks & 0xFF);
pulsesLeft = -1;
//
// Starts the test
//
port.DiscardOutBuffer();
port.Write(buffer, 0, buffer.Length);
Thread.Sleep(250);
//
// Reads ACK from RD-20
//
inBuffer = new byte[4];
for (i = 0; i < 4; i++)
{
try
{
port.Read(inBuffer, i, 1);
}
catch (Exception ex)
{
if (tryCount < MAX_RD20_TRY)
{
tryCount++;
port.DiscardInBuffer();
goto TRY;
}
else throw new IOException(ex.Message + Environment.NewLine + "StandardMeter.ExecuteCalibration().");
}
}
port.DiscardInBuffer();
if ((inBuffer[0] != 0xA6) && (inBuffer[0] != 0xAC) && (inBuffer[0] != 0xA3))
{
if (tryCount < MAX_RD20_TRY)
{
tryCount++;
port.DiscardInBuffer();
goto TRY;
}
else throw new IOException("RD-20 respondeu NAK. StandardMeter.ExecuteCalibration().");
}
buffer[5] &= 0xFE; //asks for status
cks = CheckSum(buffer, 20);
buffer[20] = (byte)((cks >> 8) & 0xFF);
buffer[21] = (byte)(cks & 0xFF);
while (pulsesLeft != 0)
{
port.DiscardOutBuffer();
port.Write(buffer, 0, buffer.Length);
Thread.Sleep(250);
inBuffer = new byte[28];
for (i = 0; i < 28; i++)
{
try
{
port.Read(inBuffer, i, 1);
}
catch (Exception ex)
{
if (tryCount < MAX_RD20_TRY)
{
tryCount++;
port.DiscardInBuffer();
goto TRY;
}
else throw new IOException(ex.Message + Environment.NewLine + "StandardMeter.ExecuteCalibration().");
}
}
port.DiscardInBuffer();
pulsesLeft = BitConverter.ToInt32(new byte[] { inBuffer[21], inBuffer[20], inBuffer[19], inBuffer[18] }, 0);
}
error = bytesTofloat(new byte[] { inBuffer[6], inBuffer[7], inBuffer[8], inBuffer[9] });
if (considerTolerance)
{
if (Math.Abs(error) > tol)
{
if (tryCount < MAX_RD20_TRY)
{
tryCount++;
port.DiscardInBuffer();
goto TRY;
}
}
}
break;
default:
break;
}
return (error);
}
/// <summary>
/// Connects to the GF333B standard and connects to the prescaller needed in conjunction with the GF333B.
/// </summary>
private void ConnectToGF333B(bool hasPrescaler)
{
StreamReader reader = new StreamReader("RS232.txt");
int start, length;
string stdPortName = reader.ReadLine();
string stdBaudRate = reader.ReadLine();
string stdDataSize = reader.ReadLine();
string stdStopBits = reader.ReadLine();
string stdParity = reader.ReadLine();
string stdDtr = reader.ReadLine();
string stdRts = reader.ReadLine();
string prePortName = reader.ReadLine();
string preBaudRate = reader.ReadLine();
string preDataSize = reader.ReadLine();
string preStopBits = reader.ReadLine();
string preParity = reader.ReadLine();
string preDtr = reader.ReadLine();
string preRts = reader.ReadLine();
reader.Close();
start = stdPortName.IndexOf("=") + 1;
length = stdPortName.Length - start;
stdPortName = stdPortName.Substring(start, length);
start = stdBaudRate.IndexOf("=") + 1;
length = stdBaudRate.Length - start;
int _stdBaudRate = Convert.ToInt32(stdBaudRate.Substring(start, length));
start = stdDataSize.IndexOf("=") + 1;
length = stdDataSize.Length - start;
int _stdDataSize = Convert.ToInt32(stdDataSize.Substring(start, length));
start = stdStopBits.IndexOf("=") + 1;
length = stdStopBits.Length - start;
int _stdStopBits = Convert.ToInt32(stdStopBits.Substring(start, length));
start = stdParity.IndexOf("=") + 1;
length = stdParity.Length - start;
int _stdParity = Convert.ToInt32(stdParity.Substring(start, length));
bool _stdDtr = false, _stdRts = false;
start = stdDtr.IndexOf("=") + 1;
length = stdDtr.Length - start;
stdDtr = stdDtr.Substring(start, length);
if (stdDtr.Equals("TRUE")) _stdDtr = true;
start = stdRts.IndexOf("=") + 1;
length = stdRts.Length - start;
stdRts = stdRts.Substring(start, length);
if (stdRts.Equals("TRUE")) _stdRts = true;
start = prePortName.IndexOf("=") + 1;
length = prePortName.Length - start;
prePortName = prePortName.Substring(start, length);
start = preBaudRate.IndexOf("=") + 1;
length = preBaudRate.Length - start;
int _preBaudRate = Convert.ToInt32(preBaudRate.Substring(start, length));
start = preDataSize.IndexOf("=") + 1;
length = preDataSize.Length - start;
int _preDataSize = Convert.ToInt32(preDataSize.Substring(start, length));
start = preStopBits.IndexOf("=") + 1;
length = preStopBits.Length - start;
int _preStopBits = Convert.ToInt32(preStopBits.Substring(start, length));
start = preParity.IndexOf("=") + 1;
length = preParity.Length - start;
int _preParity = Convert.ToInt32(preParity.Substring(start, length));
bool _preDtr = false, _preRts = false;
start = preDtr.IndexOf("=") + 1;
length = preDtr.Length - start;
preDtr = preDtr.Substring(start, length);
if (preDtr.Equals("TRUE")) _preDtr = true;
start = preRts.IndexOf("=") + 1;
length = preRts.Length - start;
preRts = preRts.Substring(start, length);
if (preRts.Equals("TRUE")) _preRts = true;
port = new SerialPort
{
PortName = stdPortName,
BaudRate = _stdBaudRate,
DataBits = _stdDataSize,
StopBits = (StopBits)_stdStopBits,
Parity = (Parity)_stdParity,
DtrEnable = _stdDtr,
RtsEnable = _stdRts,
ReadTimeout = 5000
};
port.Open();
if (port.IsOpen)
{
new SerialPortReader(port, 1024, NewDataReceivedForGF333B, ErrorOnReceiveGF333B);
}
try
{
GetMeasures();
}
catch (Exception)
{
throw new IOException("Falha na comunicação com padrão GF333B");
}
if (hasPrescaler)
{
portCounter = new SerialPort
{
PortName = prePortName,
BaudRate = _preBaudRate,
DataBits = _preDataSize,
StopBits = (StopBits)_preStopBits,
Parity = (Parity)_preParity,
DtrEnable = _preDtr,
RtsEnable = _preRts,
ReadTimeout = 5000
};
portCounter.Open();
if (portCounter.IsOpen)
{
new SerialPortReader(portCounter, myStdBuffer.Length, NewDataReceivedFromPrescaler, ErrorOnReceivePrescaler);
}
try
{
if (!SendCommandToPrescaller(1, 324))
{
throw new IOException("Problemas na comunicação com o prescaler.");
}
}
catch (Exception)
{
throw new IOException("Problemas na comunicação com o prescaler.");
}
}
}
/// <summary>
/// Connects to the Radian RD20 standard.
/// </summary>
private void ConnectToRD20()
{
StreamReader reader = new StreamReader("RS232.txt");
int start, length;
string stdPortName = reader.ReadLine();
string stdBaudRate = reader.ReadLine();
string stdDataSize = reader.ReadLine();
string stdStopBits = reader.ReadLine();
string stdParity = reader.ReadLine();
string stdDtr = reader.ReadLine();
string stdRts = reader.ReadLine();
reader.Close();
start = stdPortName.IndexOf("=") + 1;
length = stdPortName.Length - start;
stdPortName = stdPortName.Substring(start, length);
start = stdBaudRate.IndexOf("=") + 1;
length = stdBaudRate.Length - start;
int _stdBaudRate = Convert.ToInt32(stdBaudRate.Substring(start, length));
start = stdDataSize.IndexOf("=") + 1;
length = stdDataSize.Length - start;
int _stdDataSize = Convert.ToInt32(stdDataSize.Substring(start, length));
start = stdStopBits.IndexOf("=") + 1;
length = stdStopBits.Length - start;
int _stdStopBits = Convert.ToInt32(stdStopBits.Substring(start, length));
start = stdParity.IndexOf("=") + 1;
length = stdParity.Length - start;
int _stdParity = Convert.ToInt32(stdParity.Substring(start, length));
bool _stdDtr = false, _stdRts = false;
start = stdDtr.IndexOf("=") + 1;
length = stdDtr.Length - start;
stdDtr = stdDtr.Substring(start, length);
if (stdDtr.Equals("TRUE")) _stdDtr = true;
start = stdRts.IndexOf("=") + 1;
length = stdRts.Length - start;
stdRts = stdRts.Substring(start, length);
if (stdRts.Equals("TRUE")) _stdRts = true;
port = new SerialPort
{
PortName = stdPortName,
BaudRate = _stdBaudRate,
DataBits = _stdDataSize,
StopBits = (StopBits)_stdStopBits,
Parity = (Parity)_stdParity,
DtrEnable = _stdDtr,
RtsEnable = _stdRts,
ReadTimeout = 5000
};
port.Open();
if (port.IsOpen)
{
try
{
GetMeasures();
}
catch (Exception)
{
throw new IOException("Falha na comunicação com padrão RD-20");
}
}
}
/// <summary>
/// Connects to the Zera RMM3006 standard.
/// </summary>
private void ConnectToRMM3006(bool hasPrescaler)
{
StreamReader reader = new StreamReader("RS232.txt");
int start, length;
string stdPortName = reader.ReadLine();
string stdBaudRate = reader.ReadLine();
string stdDataSize = reader.ReadLine();
string stdStopBits = reader.ReadLine();
string stdParity = reader.ReadLine();
string stdDtr = reader.ReadLine();
string stdRts = reader.ReadLine();
string prePortName = reader.ReadLine();
string preBaudRate = reader.ReadLine();
string preDataSize = reader.ReadLine();
string preStopBits = reader.ReadLine();
string preParity = reader.ReadLine();
string preDtr = reader.ReadLine();
string preRts = reader.ReadLine();
reader.Close();
start = stdPortName.IndexOf("=") + 1;
length = stdPortName.Length - start;
stdPortName = stdPortName.Substring(start, length);
start = stdBaudRate.IndexOf("=") + 1;
length = stdBaudRate.Length - start;
int _stdBaudRate = Convert.ToInt32(stdBaudRate.Substring(start, length));
start = stdDataSize.IndexOf("=") + 1;
length = stdDataSize.Length - start;
int _stdDataSize = Convert.ToInt32(stdDataSize.Substring(start, length));
start = stdStopBits.IndexOf("=") + 1;
length = stdStopBits.Length - start;
int _stdStopBits = Convert.ToInt32(stdStopBits.Substring(start, length));
start = stdParity.IndexOf("=") + 1;
length = stdParity.Length - start;
int _stdParity = Convert.ToInt32(stdParity.Substring(start, length));
bool _stdDtr = false, _stdRts = false;
start = stdDtr.IndexOf("=") + 1;
length = stdDtr.Length - start;
stdDtr = stdDtr.Substring(start, length);
if (stdDtr.Equals("TRUE")) _stdDtr = true;
start = stdRts.IndexOf("=") + 1;
length = stdRts.Length - start;
stdRts = stdRts.Substring(start, length);
if (stdRts.Equals("TRUE")) _stdRts = true;
start = prePortName.IndexOf("=") + 1;
length = prePortName.Length - start;
prePortName = prePortName.Substring(start, length);
start = preBaudRate.IndexOf("=") + 1;
length = preBaudRate.Length - start;
int _preBaudRate = Convert.ToInt32(preBaudRate.Substring(start, length));
start = preDataSize.IndexOf("=") + 1;
length = preDataSize.Length - start;
int _preDataSize = Convert.ToInt32(preDataSize.Substring(start, length));
start = preStopBits.IndexOf("=") + 1;
length = preStopBits.Length - start;
int _preStopBits = Convert.ToInt32(preStopBits.Substring(start, length));
start = preParity.IndexOf("=") + 1;
length = preParity.Length - start;
int _preParity = Convert.ToInt32(preParity.Substring(start, length));
bool _preDtr = false, _preRts = false;
start = preDtr.IndexOf("=") + 1;
length = preDtr.Length - start;
preDtr = preDtr.Substring(start, length);
if (preDtr.Equals("TRUE")) _preDtr = true;
start = preRts.IndexOf("=") + 1;
length = preRts.Length - start;
preRts = preRts.Substring(start, length);
if (preRts.Equals("TRUE")) _preRts = true;
port = new SerialPort
{
PortName = stdPortName,
BaudRate = _stdBaudRate,
DataBits = _stdDataSize,
StopBits = (StopBits)_stdStopBits,
Parity = (Parity)_stdParity,
DtrEnable = _stdDtr,
RtsEnable = _stdRts,
ReadTimeout = 5000
};
port.Open();
if (port.IsOpen)
{
new SerialPortReader(port, 1024, NewDataReceivedForRMM3006, ErrorOnReceiveRMM3006);
}
try
{
GetMeasures();
}
catch (Exception)
{
throw new IOException("Falha na comunicação com padrão GF333B");
}
if (hasPrescaler)
{
portCounter = new SerialPort
{
PortName = prePortName,
BaudRate = _preBaudRate,
DataBits = _preDataSize,
StopBits = (StopBits)_preStopBits,
Parity = (Parity)_preParity,
DtrEnable = _preDtr,
RtsEnable = _preRts,
ReadTimeout = 5000
};
portCounter.Open();
if (portCounter.IsOpen)
{
new SerialPortReader(portCounter, myStdBuffer.Length, NewDataReceivedFromPrescaler, ErrorOnReceivePrescaler);
}
try
{
if (!SendCommandToPrescaller(1, 324))
{
throw new IOException("Problemas na comunicação com o prescaler.");
}
}
catch (Exception)
{
throw new IOException("Problemas na comunicação com o prescaler.");
}
}
}
private void NewDataReceivedForRMM3006(byte[] dataReceived)
{
Interlocked.Exchange(ref rMM30006_Answer,
rMM30006_Answer + Encoding.ASCII.GetString(dataReceived));
}
private void NewDataReceivedForGF333B(byte[] dataReceived)
{
Interlocked.Exchange(ref gf333B_Answer,
gf333B_Answer + Encoding.ASCII.GetString(dataReceived));
if ((gf333B_Answer.Length > 2) && (!gf333B_Answer.Contains("##")))
{
Interlocked.Exchange(ref gf333B_Answer, "");
}
}
private void ErrorOnReceiveRMM3006(Exception ex)
{
}
private void ErrorOnReceiveGF333B(Exception ex)
{
}
private void NewDataReceivedFromPrescaler(byte[] dataReceived)
{
Buffer.BlockCopy(dataReceived, 0, myStdBuffer, mIndex, dataReceived.Length);
Interlocked.Exchange( ref mIndex,
(mIndex + dataReceived.Length) % myStdBuffer.Length );
}
private void ErrorOnReceivePrescaler(Exception ex)
{
}
/// <summary>
/// Sends a command to the prescaller and verifies its answer.
/// </summary>
/// <param name="command">The command code.</param>
/// <param name="data">The data to be sent with the command.</param>
/// <returns>True if the answer is correct, false otherwise.</returns>
private bool SendCommandToPrescaller(int command, long data)
{
bool keepTrying;
//
// Instantiates a buffer to be sent to the prescaller according to its protocol
//
byte[] buffer = new byte[] { 0x09,
(byte)command,
(byte)((data & 0x000000FF00000000) >> 32),
(byte)((data & 0x00000000FF000000) >> 24),
(byte)((data & 0x0000000000FF0000) >> 16),
(byte)((data & 0x000000000000FF00) >> 8),
(byte)( data & 0x00000000000000FF),
0x00,
0x00 };
//
// Calculates the checksum to be sent
//
int checkSum = 0, i;
for (i = 0; i < 7; i++) checkSum += buffer[i];
buffer[7] = (byte)((checkSum >> 8) & 0xFF);
buffer[8] = (byte)(checkSum & 0xFF);
int tryCount = 0;
//
// Clears the outbuffer and attempts to send the buffer
//
int framesize = 9;
while (true)
{
keepTrying = false;
//
// Clears used variables
//
Interlocked.Exchange(ref mIndex, 0);
myStdBuffer = new byte[1024];
portCounter.DiscardOutBuffer();
portCounter.Write(buffer, 0, buffer.Length);
uint ticks = GetTickCount();
while (mIndex < framesize)
{
if (GetTickCount() - ticks >= portCounter.ReadTimeout)
{
if (tryCount < MAX_PRESCALER_TRY)
{
tryCount++;
keepTrying = true;
break;
}
else throw new IOException("Problemas na comunicação com o prescaler");
}
}
if (!keepTrying) break;
}
byte[] inBuffer = new byte[framesize];
Buffer.BlockCopy(myStdBuffer, 0, inBuffer, 0, framesize);
return (CheckArrays(buffer, inBuffer));
}
private int getNPP()
{
byte[] buffer = new byte[] { 0x09, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12 };
portCounter.DiscardOutBuffer();
portCounter.Write(buffer, 0, buffer.Length);
//
// Reads the answer according to the prescaller's protocol and clears the input buffer
//
int i;
for (i = 0; i < 9; i++) portCounter.Read(buffer, i, 1);
portCounter.DiscardInBuffer();
//
// Returns the result of the comparison between the checksums
//
return (BitConverter.ToInt32(new byte[] { buffer[6], buffer[5], buffer[4], buffer[3] }, 0));
}
private int getNPA()
{
byte[] buffer = new byte[] { 0x09, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13 };
portCounter.DiscardOutBuffer();
portCounter.Write(buffer, 0, buffer.Length);
//
// Reads the answer according to the prescaller's protocol and clears the input buffer
//
int i;
for (i = 0; i < 9; i++) portCounter.Read(buffer, i, 1);
portCounter.DiscardInBuffer();
//
// Returns the result of the comparison between the checksums
//
return (BitConverter.ToInt32(new byte[] { buffer[6], buffer[5], buffer[4], buffer[3] }, 0));
}
/// <summary>
/// Converts a hexadecimal array to a floating point number.
/// </summary>
/// <param name="str">The string to be converted.</param>
/// <returns>The floating point number.</returns>
private float ASCIItoFloat(string str)
{
uint num;
byte[] floatVal;
num = uint.Parse(str, System.Globalization.NumberStyles.AllowHexSpecifier);
floatVal = BitConverter.GetBytes(num);
return (BitConverter.ToSingle(floatVal, 0));
}
/// <summary>
/// Converts ASCII hex to an integer.
/// </summary>
/// <param name="str">The hex integer in string format.</param>
/// <returns>The corresponding integer.</returns>
private int ASCIItoInteger(string str)
{
int num;
num = int.Parse(str, System.Globalization.NumberStyles.AllowHexSpecifier);
return num;
}
/// <summary>
/// Converts a floating point to a hexadecimal array, or string.
/// </summary>
/// <param name="value">The floating point number to be converted.</param>
/// <returns>An string representing the float.</returns>
private string FloatToASCII(float value)
{
byte[] buffer;
byte[] aux = new byte[4];
string str;
buffer = BitConverter.GetBytes(value);
aux[0] = buffer[3];
aux[1] = buffer[2];
aux[2] = buffer[1];
aux[3] = buffer[0];
str = BitConverter.ToString(aux).Replace("-", "");
return (str);
}
/// <summary>
/// Converts an unsigned short (16 bit length unsigned integer) to a hexadecimal array, or string.
/// </summary>
/// <param name="value">The integer number to be converted.</param>
/// <returns>An string representing the ushort.</returns>
private string UShortToASCII(ushort value)
{
byte[] buffer = BitConverter.GetBytes(value);
byte[] aux = new byte[2];
aux[0] = buffer[1];
aux[1] = buffer[0];
string str = BitConverter.ToString(aux).Replace("-", "");
return (str);
}
/// <summary>
/// Converts an unsigned int (32 bit length unsigned integer) to a hexadecimal array, or string.
/// </summary>
/// <param name="value">The integer number to be converted.</param>
/// <returns>An string representing the uint.</returns>
private string UIntToASCII(uint value)
{
byte[] buffer = BitConverter.GetBytes(value);
byte[] aux = new byte[4];
aux[0] = buffer[3];
aux[1] = buffer[2];
aux[2] = buffer[1];
aux[3] = buffer[0];
string str = BitConverter.ToString(aux).Replace("-", "");
return (str);
}
/// <summary>
/// Method that returns the system ticks counting.
/// </summary>
/// <returns>
/// An unsigned integer representing the tick
/// counting.
/// </returns>
[DllImport("kernel32.dll")]
static extern uint GetTickCount();
/// <summary>
/// Converts an array of 4 bytes representing a TI float into an actual IEEE 754 floating point number.
/// </summary>
/// <param name="data">The 4 bytes array of the TI float. It must be in Big Endian</param>
/// <returns>A IEEE 754 float</returns>
[DllImport("lib_RD20/RD20COMM.dll", EntryPoint = "DDeviceMemStructsbytesToFloatTMS320@4")]
static extern float bytesTofloat(byte[] data);
/// <summary>
/// Converts an IEEE 754 floating point number into and array of 4 bytes representing a TI float.
/// </summary>
/// <param name="value">A floating point number in the IEEE 754 format.</param>
/// <param name="data">The array to keep the bytes of the TI float.</param>
[DllImport("lib_RD20/RD20COMM.dll", EntryPoint = "DDeviceMemStructsfloatToBytesTMS320@8")]
static extern void floatTobytes(float value, byte[] data);
/// <summary>
/// Calculates the unsigned sum of the bytes of a byte array.
/// </summary>
/// <param name="data">An array of bytes to be summed.</param>
/// <param name="size">The number of bytes to be summed.</param>
/// <returns>The calculated checksum.</returns>
[DllImport("lib_RD20/RD20COMM.dll", EntryPoint = "CalculateChecksum@8")]
static extern uint CheckSum(byte[] data, int size);
/// <summary>
/// Compares two arrays element by element.
/// </summary>
/// <param name="a1">The first array.</param>
/// <param name="a2">The second array.</param>
/// <returns>True if the arrays are identic, false otherwise.</returns>
private bool CheckArrays(Array a1, Array a2)
{
//
// Checks if the arrays are the same reference
//
if (a1 == a2) return (true);
//
// Checks if one of them is a null reference
//
if ((a1 == null) || (a2 == null)) return (false);
//
// Checks if they have the same length
//
if (a1.Length != a2.Length) return (false);
//
// Verifies each element of the arrays and if the arrays are not identical to each other
// returns false
//
int i;
for (i = 0; i < a1.Length; i++)
{
if ((byte)a1.GetValue(i) != (byte)a2.GetValue(i)) return (false);
}
//
// If there is no problem returns true
//
return (true);
}
private string GF333BCheckSum(string str)
{
byte[] buffer = Encoding.ASCII.GetBytes(str);
uint cSum = 0x0;
//calcula checksum
foreach (byte b in buffer) cSum += b;
buffer = BitConverter.GetBytes(cSum);
string ret = BitConverter.ToString(buffer).Replace("-", "");
return (ret.Substring(0, 2));
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
// Free any other managed objects here.
//
try
{
if (handle != null) handle.Dispose();
if (port != null) port.Dispose();
if (portCounter != null) portCounter.Dispose();
}
catch (Exception) { }
}
// Free any unmanaged objects here.
//
disposed = true;
}
/// <summary>
/// Disposes this instace of the StandardMeter class.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
|
#version 430
layout(local_size_x = 8) in;
layout(binding = 0) uniform sampler2D tex_I0;
layout(binding = 1) uniform sampler2D tex_I1;
layout(binding = 0, rg32f) uniform image2D im_UV_x_y;
layout(binding = 1, rg32f) uniform image2D im_S_x_y;
layout(binding = 2, rg32f) uniform image2D im_grad_I0_x_y;
layout(binding = 3, rgba32f) uniform image2D im_prod_I0_xx_yy_xy;
layout(binding = 4, rg32f) uniform image2D im_sum_I0_x_y;
uniform int patch_stride = 4;
uniform int patch_size = 8;
subroutine void launchSubroutine();
subroutine uniform launchSubroutine patchInverseSubroutine;
float computeSSDMeanNorm()
{
float sum_square_diff = 0.0f;
float sum_diff = 0.0f;
// process 16 patches per workgroup, 1 per invocation
int xOffset = int(gl_LocalInvocationID.x) * patch_size / 2;
int yOffset = int(gl_LocalInvocationID.y) * patch_size / 2;
// loops offest by 4 (0-8, 4-12, 8-16, 12-20)
for (int i = xOffset; i < xOffset + patch_size; ++i)
{
for (int j = yOffset; j < yOffset + patch_size; ++j)
{
float diff = y_data[i - xOffset][j - yOffset] - x_data[i][j];
sum_diff += diff;
sum_square_diff += diff * diff;
}
}
return sum_square_diff - sum_diff * sum_diff / float(patch_size * patch_size);
}
float processPatchMeanNorm(inout float dst_dUx, inout float dst_dUy, float x_grad_sum, float y_grad_sum)
{
float n = float(patch_size * patch_size);
float sum_square_diff = 0.0f;
float sum_diff = 0.0f;
float diff;
float sum_I0x_mul = 0.0f;
float sum_I0y_mul = 0.0f;
// here we need to process the gradient full size images
int xOffset = int(gl_LocalInvocationID.x) * patch_size / 2;
int yOffset = int(gl_LocalInvocationID.y) * patch_size / 2;
for (int i = xOffset; i < xOffset + patch_size; ++i)
{
for (int j = yOffset; j < yOffset + patch_size; ++j)
{
diff = y_data[i - xOffset][j - yOffset] - x_data[i][j]; //SWAPED THESE AROUND
sum_diff += diff;
sum_square_diff += diff * diff;
sum_I0x_mul += diff * x_grad_data[i][j];
sum_I0y_mul += diff * y_grad_data[i][j];
}
}
dst_dUx = sum_I0x_mul - sum_diff * x_grad_sum / n;
dst_dUy = sum_I0y_mul - sum_diff * y_grad_sum / n;
return sum_square_diff - sum_diff * sum_diff / n;
}
subroutine(launchSubroutine)
void patchInverseFwd1()
{
ivec2 denseSize = ivec2(imageSize(im_UV_x_y).xy);
ivec2 sparseSize = ivec2(imageSize(im_S_x_y).xy);
int id = int(gl_GlobalInvocationID.y);
int is = id / 8;
if (id >= (denseSize.y)) return;
int i = is * patch_stride;
int j = 0;
int psz = patch_size;
int psz2 = psz / 2;
vec2 prev_flow_UxUy = imageLoad(im_UV_x_y, ivec2(j + psz2, i + psz2)).xy;
imageStore(im_S_x_y, ivec2(0, is), vec4(prev_flow_UxUy, 0, 0));
j += patch_stride;
for (int js = 1; js < sparseSize.x; js++, j += patch_stride)
{
float min_SSD, cur_SSD;
vec2 flow_UxUy = imageLoad(im_UV_x_y, ivec2(j + psz2, i + psz2)).xy;
}
}
subroutine(launchSubroutine)
void patchInverseFwd2()
{
}
subroutine(launchSubroutine)
void patchInverseBwd2()
{
}
subroutine(launchSubroutine)
void patchInverseBwd2()
{
}
void main()
{
patchInverseSubroutine();
} |
using System;
using System.IO.Compression;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Pickers;
using Exercise3.UWP.ViewModels;
using Windows.UI.Xaml.Controls;
using Exercise3.UWP.Utils;
namespace Exercise3.UWP.Views
{
public sealed partial class MainPage : Page, IOnFileDropped
{
public MainViewModel ViewModel { get; } = new MainViewModel();
public MainPage()
{
InitializeComponent();
ViewModel.ViewHandler = this;
}
public async Task<string> OnFileDropped(CompressionMode compressionMode)
{
switch (compressionMode)
{
case CompressionMode.Compress:
await OpenFolderPickerPrompt($"{ViewModel.SourceFile.Name}.zip").ConfigureAwait(false);
break;
case CompressionMode.Decompress:
await OpenFolderPickerPrompt(ViewModel.SourceFile.GetNameWithoutZipExtension()).ConfigureAwait(false);
break;
default:
throw new ArgumentOutOfRangeException(nameof(compressionMode), compressionMode, null);
}
return await ViewModel.StartCompression(compressionMode).ConfigureAwait(false);
}
private async Task OpenFolderPickerPrompt(string fileName)
{
var folderPicker = new FolderPicker();
folderPicker.FileTypeFilter.Add("*");
var folder = await folderPicker.PickSingleFolderAsync();
var file = await folder.CreateFileAsync(fileName,
CreationCollisionOption.ReplaceExisting);
if (file != null)
{
ViewModel.OutputFile = file;
}
}
}
public interface IOnFileDropped
{
Task<string> OnFileDropped(CompressionMode compressionMode);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Atc.Collections;
using Atc.Tests.XUnitTestTypes;
using Xunit;
namespace Atc.Tests.Extensions
{
public class TypeExtensionsTests
{
[Theory]
[InlineData(false, typeof(NumericAlphaComparer))]
[InlineData(true, typeof(EmailAddressAttribute))]
public void HasValidationAttributes(bool expected, Type type)
{
// Act
var actual = type.HasValidationAttributes();
// Assert
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(false, typeof(NumericAlphaComparer))]
[InlineData(true, typeof(Delegate))]
public void IsDelegate(bool expected, Type type)
{
// Act
var actual = type.IsDelegate();
// Assert
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(false, typeof(double))]
[InlineData(true, typeof(double?))]
public void IsNullable(bool expected, Type type)
{
// Act
var actual = type.IsNullable();
// Assert
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(false, typeof(NumericAlphaComparer))]
[InlineData(false, typeof(EmailAddressAttribute))]
[InlineData(true, typeof(DayOfWeek))]
[InlineData(true, typeof(int))]
[InlineData(true, typeof(string))]
public void IsSimple(bool expected, Type type)
{
// Act
var actual = type.IsSimple();
// Assert
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(false, typeof(DataTypeAttribute), typeof(DataTypeAttribute))]
[InlineData(false, typeof(DataTypeAttribute), typeof(EmailAddressAttribute))]
[InlineData(false, typeof(EmailAddressAttribute), typeof(EmailAddressAttribute))]
[InlineData(true, typeof(EmailAddressAttribute), typeof(DataTypeAttribute))]
public void IsInheritedFrom(bool expected, Type type, Type baseType)
{
// Act
var actual = type.IsInheritedFrom(baseType);
// Assert
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(false, typeof(EmailAddressAttribute), typeof(EmailAddressAttribute), typeof(EmailAddressAttribute))]
public void IsInheritedFromGenericWithArgumentType(bool expected, Type type, Type baseType, Type argumentType)
{
// Act
var actual = type.IsInheritedFromGenericWithArgumentType(baseType, argumentType);
// Assert
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(false, typeof(EmailAddressAttribute), typeof(EmailAddressAttribute), typeof(EmailAddressAttribute), false)]
public void IsInheritedFromGenericWithArgumentType_MatchAlsoOnArgumentTypeInterface(bool expected, Type type, Type baseType, Type argumentType, bool matchAlsoOnArgumentTypeInterface)
{
// Act
var actual = type.IsInheritedFromGenericWithArgumentType(baseType, argumentType, matchAlsoOnArgumentTypeInterface);
// Assert
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(false, typeof(EmailAddressAttribute))]
public void GetBaseTypeGenericArgumentType(bool expected, Type type)
{
// Act
var actual = type.GetBaseTypeGenericArgumentType();
// Assert
if (expected)
{
Assert.NotNull(actual);
}
else
{
Assert.Null(actual);
}
}
[Theory]
[InlineData(0, typeof(EmailAddressAttribute))]
public void GetBaseTypeGenericArgumentTypes(int expected, Type type)
{
// Act
var actual = type.GetBaseTypeGenericArgumentTypes();
// Assert
if (expected == 0)
{
Assert.Null(actual);
}
else
{
Assert.NotNull(actual);
Assert.Equal(expected, actual.Length);
}
}
[Theory]
[InlineData(true, typeof(EmailAddressAttribute))]
[InlineData(false, typeof(NumericAlphaComparer))]
public void GetAttribute(bool expected, Type type)
{
// Act
var actual = type.GetAttribute<AttributeUsageAttribute>();
// Assert
if (expected)
{
Assert.NotNull(actual);
}
else
{
Assert.Null(actual);
}
}
[Theory]
[InlineData(true, typeof(EmailAddressAttribute))]
[InlineData(false, typeof(NumericAlphaComparer))]
public void TryGetAttribute(bool expected, Type type)
{
// Act
var actual = type.TryGetAttribute<AttributeUsageAttribute>();
// Assert
if (expected)
{
Assert.NotNull(actual);
}
else
{
Assert.Null(actual);
}
}
[Theory]
[InlineData(1, typeof(EmailAddressAttribute))]
[InlineData(0, typeof(NumericAlphaComparer))]
public void GetAttributes(int expected, Type type)
{
// Act
var actual = type.GetAttributes<AttributeUsageAttribute>();
// Assert
Assert.Equal(expected, actual.Count());
}
[Theory]
[InlineData(1, typeof(EmailAddressAttribute))]
public void GetPublicDeclaredOnlyMethods(int expected, Type type)
{
// Act
var actual = type.GetPublicDeclaredOnlyMethods();
// Assert
Assert.Equal(expected, actual.Length);
}
[Theory]
[InlineData(0, typeof(EmailAddressAttribute))]
public void GetPrivateDeclaredOnlyMethods(int expected, Type type)
{
// Act
var actual = type.GetPrivateDeclaredOnlyMethods();
// Assert
Assert.Equal(expected, actual.Length);
}
[Theory]
[InlineData(false, typeof(EmailAddressAttribute), "IsValid")]
public void GetPrivateDeclaredOnlyMethod(bool expected, Type type, string methodName)
{
// Act
var actual = type.GetPrivateDeclaredOnlyMethod(methodName);
// Assert
if (expected)
{
Assert.NotNull(actual);
}
else
{
Assert.Null(actual);
}
}
[Theory]
[InlineData("ConcurrentHashSet", typeof(ConcurrentHashSet<int>))]
[InlineData("LocalizedDescriptionAttribute", typeof(LocalizedDescriptionAttribute))]
[InlineData("Dictionary", typeof(Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>))]
public void GetNameWithoutGenericType(string expected, Type type)
{
Assert.Equal(expected, type.GetNameWithoutGenericType());
}
[Theory]
[InlineData("ConcurrentHashSet", typeof(ConcurrentHashSet<int>), false)]
[InlineData("LocalizedDescriptionAttribute", typeof(LocalizedDescriptionAttribute), false)]
[InlineData("Dictionary", typeof(Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>), false)]
[InlineData("Atc.Collections.ConcurrentHashSet", typeof(ConcurrentHashSet<int>), true)]
[InlineData("Atc.LocalizedDescriptionAttribute", typeof(LocalizedDescriptionAttribute), true)]
[InlineData("System.Collections.Generic.Dictionary", typeof(Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>), true)]
public void GetNameWithoutGenericType_UseFullName(string expected, Type type, bool useFullName)
{
Assert.Equal(expected, type.GetNameWithoutGenericType(useFullName));
}
[Theory]
[InlineData("typeof(int)", typeof(int))]
[InlineData("typeof(bool)", typeof(bool))]
[InlineData("typeof(LocalizedDescriptionAttribute)", typeof(LocalizedDescriptionAttribute))]
[InlineData("typeof(Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>)", typeof(Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>))]
[InlineData("typeof(List<Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>>)", typeof(List<Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>>))]
public void BeautifyTypeOfName(string expected, Type type)
{
Assert.Equal(expected, type.BeautifyTypeOfName());
}
[Theory]
[InlineData("typeof(int)", typeof(int), false)]
[InlineData("typeof(int)", typeof(int), true)]
[InlineData("typeof(bool)", typeof(bool), false)]
[InlineData("typeof(bool)", typeof(bool), true)]
[InlineData("typeof(LocalizedDescriptionAttribute)", typeof(LocalizedDescriptionAttribute), false)]
[InlineData("typeof(Atc.LocalizedDescriptionAttribute)", typeof(LocalizedDescriptionAttribute), true)]
[InlineData("typeof(Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>)", typeof(Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>), false)]
[InlineData("typeof(System.Collections.Generic.Dictionary<Atc.LocalizedDescriptionAttribute, Atc.LocalizedDescriptionAttribute>)", typeof(Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>), true)]
[InlineData("typeof(List<Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>>)", typeof(List<Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>>), false)]
[InlineData("typeof(System.Collections.Generic.List<System.Collections.Generic.Dictionary<Atc.LocalizedDescriptionAttribute, Atc.LocalizedDescriptionAttribute>>)", typeof(List<Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>>), true)]
public void BeautifyTypeOfName_UseFullName(string expected, Type type, bool useFullName)
{
Assert.Equal(expected, type.BeautifyTypeOfName(useFullName));
}
[Theory]
[InlineData("typeof(int)", typeof(int), false, false)]
[InlineData("typeof(int)", typeof(int), true, false)]
[InlineData("typeof(bool)", typeof(bool), false, false)]
[InlineData("typeof(bool)", typeof(bool), true, false)]
[InlineData("typeof(LocalizedDescriptionAttribute)", typeof(LocalizedDescriptionAttribute), false, false)]
[InlineData("typeof(Atc.LocalizedDescriptionAttribute)", typeof(LocalizedDescriptionAttribute), true, false)]
[InlineData("typeof(Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>)", typeof(Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>), false, false)]
[InlineData("typeof(System.Collections.Generic.Dictionary<Atc.LocalizedDescriptionAttribute, Atc.LocalizedDescriptionAttribute>)", typeof(Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>), true, false)]
[InlineData("typeof(List<Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>>)", typeof(List<Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>>), false, false)]
[InlineData("typeof(System.Collections.Generic.List<System.Collections.Generic.Dictionary<Atc.LocalizedDescriptionAttribute, Atc.LocalizedDescriptionAttribute>>)", typeof(List<Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>>), true, false)]
[InlineData("typeof(int)", typeof(int), false, true)]
[InlineData("typeof(int)", typeof(int), true, true)]
[InlineData("typeof(bool)", typeof(bool), false, true)]
[InlineData("typeof(bool)", typeof(bool), true, true)]
[InlineData("typeof(LocalizedDescriptionAttribute)", typeof(LocalizedDescriptionAttribute), false, true)]
[InlineData("typeof(Atc.LocalizedDescriptionAttribute)", typeof(LocalizedDescriptionAttribute), true, true)]
[InlineData("typeof(Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>)", typeof(Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>), false, true)]
[InlineData("typeof(System.Collections.Generic.Dictionary<Atc.LocalizedDescriptionAttribute, Atc.LocalizedDescriptionAttribute>)", typeof(Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>), true, true)]
[InlineData("typeof(List<Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>>)", typeof(List<Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>>), false, true)]
[InlineData("typeof(System.Collections.Generic.List<System.Collections.Generic.Dictionary<Atc.LocalizedDescriptionAttribute, Atc.LocalizedDescriptionAttribute>>)", typeof(List<Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>>), true, true)]
public void BeautifyTypeOfName_UseFullName_UseHtmlFormat(string expected, Type type, bool useFullName, bool useHtmlFormat)
{
Assert.Equal(expected, type.BeautifyTypeOfName(useFullName, useHtmlFormat));
}
[Theory]
[InlineData("int", typeof(int))]
[InlineData("bool", typeof(bool))]
[InlineData("LocalizedDescriptionAttribute", typeof(LocalizedDescriptionAttribute))]
[InlineData("Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>", typeof(Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>))]
[InlineData("List<Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>>", typeof(List<Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>>))]
public void BeautifyName(string expected, Type type)
{
Assert.Equal(expected, type.BeautifyName());
}
[Theory]
[InlineData("int", typeof(int), false)]
[InlineData("int", typeof(int), true)]
[InlineData("bool", typeof(bool), false)]
[InlineData("bool", typeof(bool), true)]
[InlineData("LocalizedDescriptionAttribute", typeof(LocalizedDescriptionAttribute), false)]
[InlineData("Atc.LocalizedDescriptionAttribute", typeof(LocalizedDescriptionAttribute), true)]
[InlineData("Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>", typeof(Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>), false)]
[InlineData("System.Collections.Generic.Dictionary<Atc.LocalizedDescriptionAttribute, Atc.LocalizedDescriptionAttribute>", typeof(Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>), true)]
[InlineData("List<Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>>", typeof(List<Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>>), false)]
[InlineData("System.Collections.Generic.List<System.Collections.Generic.Dictionary<Atc.LocalizedDescriptionAttribute, Atc.LocalizedDescriptionAttribute>>", typeof(List<Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>>), true)]
public void BeautifyName_UseFullName(string expected, Type type, bool useFullName)
{
Assert.Equal(expected, type.BeautifyName(useFullName));
}
[Theory]
[InlineData("int", typeof(int), false, false)]
[InlineData("int", typeof(int), true, false)]
[InlineData("bool", typeof(bool), false, false)]
[InlineData("bool", typeof(bool), true, false)]
[InlineData("LocalizedDescriptionAttribute", typeof(LocalizedDescriptionAttribute), false, false)]
[InlineData("Atc.LocalizedDescriptionAttribute", typeof(LocalizedDescriptionAttribute), true, false)]
[InlineData("Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>", typeof(Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>), false, false)]
[InlineData("System.Collections.Generic.Dictionary<Atc.LocalizedDescriptionAttribute, Atc.LocalizedDescriptionAttribute>", typeof(Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>), true, false)]
[InlineData("List<Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>>", typeof(List<Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>>), false, false)]
[InlineData("System.Collections.Generic.List<System.Collections.Generic.Dictionary<Atc.LocalizedDescriptionAttribute, Atc.LocalizedDescriptionAttribute>>", typeof(List<Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>>), true, false)]
[InlineData("int", typeof(int), false, true)]
[InlineData("int", typeof(int), true, true)]
[InlineData("bool", typeof(bool), false, true)]
[InlineData("bool", typeof(bool), true, true)]
[InlineData("LocalizedDescriptionAttribute", typeof(LocalizedDescriptionAttribute), false, true)]
[InlineData("Atc.LocalizedDescriptionAttribute", typeof(LocalizedDescriptionAttribute), true, true)]
[InlineData("Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>", typeof(Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>), false, true)]
[InlineData("System.Collections.Generic.Dictionary<Atc.LocalizedDescriptionAttribute, Atc.LocalizedDescriptionAttribute>", typeof(Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>), true, true)]
[InlineData("List<Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>>", typeof(List<Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>>), false, true)]
[InlineData("System.Collections.Generic.List<System.Collections.Generic.Dictionary<Atc.LocalizedDescriptionAttribute, Atc.LocalizedDescriptionAttribute>>", typeof(List<Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>>), true, true)]
public void BeautifyName_UseFullName_UseHtmlFormat(string expected, Type type, bool useFullName, bool useHtmlFormat)
{
Assert.Equal(expected, type.BeautifyName(useFullName, useHtmlFormat));
}
[Theory]
[InlineData("Dictionary<T, LocalizedDescriptionAttribute>", typeof(Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>), false, false, true)]
public void BeautifyName_UseFullName_UseHtmlFormat_UseGenericParameterNamesAsT(string expected, Type type, bool useFullName, bool useHtmlFormat, bool useGenericParameterNamesAsT)
{
Assert.Equal(expected, type.BeautifyName(useFullName, useHtmlFormat, useGenericParameterNamesAsT));
}
[Theory]
[InlineData("T, LocalizedDescriptionAttribute?", typeof(Dictionary<LocalizedDescriptionAttribute, LocalizedDescriptionAttribute>), false, false, true, true)]
public void BeautifyName_UseFullName_UseGenericParameterNamesAsT_UseSuffixQuestionMarkForGeneric(string expected, Type type, bool useFullName, bool useHtmlFormat, bool useGenericParameterNamesAsT, bool useSuffixQuestionMarkForGeneric)
{
Assert.Equal(expected, type.BeautifyName(useFullName, useHtmlFormat, useGenericParameterNamesAsT, useSuffixQuestionMarkForGeneric));
}
[Theory]
[InlineData("object", null)]
[InlineData("object", typeof(object))]
[InlineData("void", typeof(void))]
[InlineData("string", typeof(string))]
[InlineData("bool", typeof(bool))]
[InlineData("int", typeof(int))]
[InlineData("uint", typeof(uint))]
[InlineData("byte", typeof(byte))]
[InlineData("sbyte", typeof(sbyte))]
[InlineData("short", typeof(short))]
[InlineData("ushort", typeof(ushort))]
[InlineData("long", typeof(long))]
[InlineData("ulong", typeof(ulong))]
[InlineData("char", typeof(char))]
[InlineData("float", typeof(float))]
[InlineData("double", typeof(double))]
[InlineData("decimal", typeof(decimal))]
[InlineData("bool?", typeof(bool?))]
[InlineData("int?", typeof(int?))]
[InlineData("uint?", typeof(uint?))]
[InlineData("byte?", typeof(byte?))]
[InlineData("sbyte?", typeof(sbyte?))]
[InlineData("short?", typeof(short?))]
[InlineData("ushort?", typeof(ushort?))]
[InlineData("long?", typeof(long?))]
[InlineData("ulong?", typeof(ulong?))]
[InlineData("char?", typeof(char?))]
[InlineData("float?", typeof(float?))]
[InlineData("double?", typeof(double?))]
[InlineData("decimal?", typeof(decimal?))]
[InlineData("string[]", typeof(string[]))]
[InlineData("bool[]", typeof(bool[]))]
[InlineData("int[]", typeof(int[]))]
[InlineData("uint[]", typeof(uint[]))]
[InlineData("byte[]", typeof(byte[]))]
[InlineData("sbyte[]", typeof(sbyte[]))]
[InlineData("short[]", typeof(short[]))]
[InlineData("ushort[]", typeof(ushort[]))]
[InlineData("long[]", typeof(long[]))]
[InlineData("ulong[]", typeof(ulong[]))]
[InlineData("char[]", typeof(char[]))]
[InlineData("float[]", typeof(float[]))]
[InlineData("double[]", typeof(double[]))]
[InlineData("decimal[]", typeof(decimal[]))]
[InlineData("LocalizedDescriptionAttribute", typeof(LocalizedDescriptionAttribute))]
public void BeautifyTypeName(string expected, Type type)
{
Assert.Equal(expected, type.BeautifyTypeName());
}
[Theory]
[InlineData("int", typeof(int), false)]
[InlineData("int", typeof(int), true)]
[InlineData("bool", typeof(bool), false)]
[InlineData("bool", typeof(bool), true)]
[InlineData("LocalizedDescriptionAttribute", typeof(LocalizedDescriptionAttribute), false)]
[InlineData("Atc.LocalizedDescriptionAttribute", typeof(LocalizedDescriptionAttribute), true)]
public void BeautifyTypeName_UseFullName(string expected, Type type, bool useFullName)
{
Assert.Equal(expected, type.BeautifyTypeName(useFullName));
}
[Fact]
public void TryGetEnumType()
{
// Arrange
var testType = typeof(DayOfWeek);
// Act
var actual = testType.TryGetEnumType(out var actualType);
// Assert
Assert.True(actual);
Assert.Equal(typeof(DayOfWeek), actualType);
}
[Fact]
public void IsSubClassOfRawGeneric()
{
// Arrange
var testType = typeof(TestStringList);
// Act
var actual = typeof(List<>).IsSubClassOfRawGeneric(testType);
// Assert
Assert.True(actual);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FadeOverTime : MonoBehaviour
{
public float fadeTime;
//
/*
NAME: Start
SYNOPSIS:
Start is called before the first frame update
DESCRIPTION:
Start is called before the first frame update
RETURNS:
AUTHOR:
Thomas Furletti
DATE:
07/08/2020
*/
void Start()
{
}
//
/*
NAME: Update
SYNOPSIS:
This update function fades objects on destrucion.
DESCRIPTION:
Used to fade objects out of view when either an enemy or player is destroyed.
RETURNS:
AUTHOR:
Thomas Furletti
DATE:
07/08/2020
*/
void Update()
{
fadeTime -= Time.deltaTime;
if(fadeTime <= 0) {
Destroy(gameObject);
}
}
}
|
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Text;
namespace MergeSort
{
public class FishService
{
public void ConsoleRun()
{
////Array
//var array = string.Empty;
//while (array.ToLower() != "exit")
//{
// Console.WriteLine("Enter an array: ");
// array = Console.ReadLine();
// if (array == "exit")
// break;
// Console.WriteLine("Enter number of times to shift: ");
// var line2 = Console.ReadLine();
// if (line2 == "exit")
// break;
// else
// {
// int[] arr = Array.ConvertAll(array.Split(" "), int.Parse);
// var outputArray = GetNumberOfRemainingFish(arr, Convert.ToInt32(line2));
// string output = outputArray[0].ToString();
// for (int i = 1; i < arr.Length; i++)
// {
// output = output + ", " + outputArray[i].ToString();
// }
// Console.WriteLine($"Output: {output}");
// }
//}
}
public int GetNumberOfRemainingFish(int[] arrSize, int[] arrDirection)
{
var count = arrSize.Length;
var stack = new Stack<int>();
//Loop through arrays looking for B[P] = 1
for (int i = 0; i < arrSize.Length; i++)
{
//Stack B[P] = 1 //continue;
if (arrDirection[i] == 1)
{
stack.Push(i);
continue;
}
while (stack.Count > 0)
{
var downFish = stack.Pop();
if (arrSize[i] < arrSize[downFish])
{
count--;
stack.Push(downFish);
break;
}
else
count--;
}
}
return count;
}
}
[TestFixture]
public class FishServiceTests
{
public FishService service = new FishService();
[Test]
public void FishServiceTest1()
{
var given = new int[] { 4, 3, 2, 1, 5 };
var given2 = new int[] { 0, 1, 0, 0, 0 };
var expected = 2;
Assert.AreEqual(expected, service.GetNumberOfRemainingFish(given, given2));
}
[Test]
public void FishServiceTest2()
{
var given = new int[] { 4, 3, 2, 1, 5 };
var given2 = new int[] { 0, 1, 0, 0, 0 };
var expected = 2;
Assert.AreEqual(expected, service.GetNumberOfRemainingFish(given, given2));
}
[Test]
public void FishServiceTest3()
{
var given = new int[] { 4, 3, 2, 1, 5 };
var given2 = new int[] { 0, 1, 0, 0, 0 };
var expected = 2;
Assert.AreEqual(expected, service.GetNumberOfRemainingFish(given, given2));
}
}
}
|
using ApiSGCOlimpiada.Models;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
namespace ApiSGCOlimpiada.Data.OcupacaoDAO
{
public class OcupacaoDAO : IOcupacaoDAO
{
private readonly string _conn;
public OcupacaoDAO(IConfiguration config)
{
_conn = config.GetConnectionString("conn");
}
MySqlConnection conn;
MySqlDataAdapter adapter;
MySqlCommand cmd;
DataTable dt;
public bool Add(Ocupacao ocupacao)
{
try
{
conn = new MySqlConnection(_conn);
conn.Open();
cmd = new MySqlCommand($"Insert into Ocupacoes values(null, '{ocupacao.Nome}', '{ocupacao.Numero}')", conn);
int rows = cmd.ExecuteNonQuery();
if (rows != -1)
{
return true;
}
return false;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
finally
{
conn.Close();
}
}
public Ocupacao Find(long id)
{
try
{
conn = new MySqlConnection(_conn);
conn.Open();
cmd = new MySqlCommand($"Select * from Ocupacoes where id = {id}", conn);
adapter = new MySqlDataAdapter(cmd);
dt = new DataTable();
adapter.Fill(dt);
Ocupacao ocupacao = null;
foreach (DataRow item in dt.Rows)
{
ocupacao = new Ocupacao();
ocupacao.Id = Convert.ToInt64(item["Id"]);
ocupacao.Nome = item["Nome"].ToString();
ocupacao.Numero = item["Numero"].ToString();
}
return ocupacao;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
finally
{
conn.Close();
}
}
public List<Ocupacao> FindBySearch(string search)
{
List<Ocupacao> ocupacaos = new List<Ocupacao>();
try
{
conn = new MySqlConnection(_conn);
conn.Open();
cmd = new MySqlCommand($"Select * from Ocupacoes where nome LIKE '%{search}%' or numero LIKE '%{search}%'", conn);
adapter = new MySqlDataAdapter(cmd);
dt = new DataTable();
adapter.Fill(dt);
Ocupacao ocupacao = null;
foreach (DataRow item in dt.Rows)
{
ocupacao = new Ocupacao();
ocupacao.Id = Convert.ToInt64(item["Id"]);
ocupacao.Nome = item["Nome"].ToString();
ocupacao.Numero = item["Numero"].ToString();
ocupacaos.Add(ocupacao);
}
return ocupacaos;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
finally
{
conn.Close();
}
}
public IEnumerable<Ocupacao> GetAll()
{
try
{
List<Ocupacao> ocupacaos = new List<Ocupacao>();
conn = new MySqlConnection(_conn);
conn.Open();
cmd = new MySqlCommand($"Select * from Ocupacoes", conn);
adapter = new MySqlDataAdapter(cmd);
dt = new DataTable();
adapter.Fill(dt);
foreach (DataRow item in dt.Rows)
{
Ocupacao ocupacao = new Ocupacao();
ocupacao.Id = Convert.ToInt64(item["Id"]);
ocupacao.Nome = item["Nome"].ToString();
ocupacao.Numero = item["Numero"].ToString();
ocupacaos.Add(ocupacao);
}
return ocupacaos;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
finally
{
conn.Close();
}
}
public bool Remove(long id)
{
try
{
conn = new MySqlConnection(_conn);
conn.Open();
cmd = new MySqlCommand($"Delete from Ocupacoes where id = {id}", conn);
int rows = cmd.ExecuteNonQuery();
if (rows != -1)
{
return true;
}
return false;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
finally
{
conn.Close();
}
}
public bool Update(Ocupacao ocupacao, long id)
{
try
{
conn = new MySqlConnection(_conn);
conn.Open();
cmd = new MySqlCommand($"Update Ocupacoes set Nome = '{ocupacao.Nome}', Numero = '{ocupacao.Numero}' where id = {id}", conn);
int rows = cmd.ExecuteNonQuery();
if (rows != -1)
{
return true;
}
return false;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
finally
{
conn.Close();
}
}
public List<Ocupacao> GetBySolicitacao(long idSolicitacao)
{
try
{
List<Ocupacao> ocupacaos = new List<Ocupacao>();
conn = new MySqlConnection(_conn);
conn.Open();
cmd = new MySqlCommand($"Select o.id, o.nome, o.numero from Ocupacoes as o inner join ocupacoessolicitacaocompras as osc on osc.ocupacoesId = o.id inner join solicitacaoCompras as sc on osc.solicitacaoComprasId = sc.id where sc.id = {idSolicitacao}", conn);
adapter = new MySqlDataAdapter(cmd);
dt = new DataTable();
adapter.Fill(dt);
foreach (DataRow item in dt.Rows)
{
Ocupacao ocupacao = new Ocupacao();
ocupacao.Id = Convert.ToInt64(item["Id"]);
ocupacao.Nome = item["Nome"].ToString();
ocupacao.Numero = item["Numero"].ToString();
ocupacaos.Add(ocupacao);
}
return ocupacaos;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
finally
{
conn.Close();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TravelerZeppelinMVC.Types
{
public class CityInformation
{
public string StartCityPlate { get; set; }
public double DistanceValue { get; set; }
public string CityPlate { get; set; }
public List<string> Plates { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using UnityEngine;
using UnityEngine.UI;
public class PointChecker : MonoBehaviour
{
public static int currentLevel= 0;
public float targetHit = 3;
public float perfectHit = 4;
public float missHit = 2;
public AudioSource yay;
public AudioSource complete;
public AudioSource wrong;
[SerializeField] private Image completeText;
[SerializeField] private Image failureText;
[SerializeField] private Image successText;
// Start is called before the first frame update
void Start()
{
complete = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter(Collider other) //if something enters this trigger
{
if (GameManager.instance.hit >= perfectHit)
{
if(other.CompareTag("Player"))
{
successText.enabled = true;
}
yay.Play();
complete.Play();
currentLevel++;
Invoke("NextLevel", 4f);
}
if (GameManager.instance.hit == targetHit)
{
if (other.CompareTag("Player"))
{
completeText.enabled = true;
}
complete.Play();
currentLevel++;
Invoke("NextLevel", 4f);
}
if(GameManager.instance.hit <= missHit)
{
if (other.CompareTag("Player"))
{
failureText.enabled = true;
}
wrong.Play();
Invoke("Reset", 2f);
}
}
void NextLevel()
{
GameManager.instance.hit = 0;
failureText.enabled = false;
completeText.enabled = false;
successText.enabled = false;
SceneManager.LoadScene(currentLevel);
}
void Reset()
{
SceneManager.LoadScene(currentLevel);
}
}
|
using UnityEngine;
using System.Collections;
using System.IO;
public static class PNGUtility
{
public static Sprite LoadSpriteFromFile(string path, int width, int height)
{
if (System.IO.File.Exists (path))
{
byte[] bytes = File.ReadAllBytes (path);
Texture2D texture = new Texture2D (width, height);
texture.filterMode = FilterMode.Trilinear;
texture.LoadImage (bytes);
Sprite sprite = Sprite.Create (texture, new Rect (0, 0, width, height), new Vector2 (0.5f, 0.0f), 1.0f);
return sprite;
}
else
return null;
}
public static void SaveRenderTextureToFile(string filePath, RenderTexture rt)
{
// get contents of RenderTexture to Texture2D
Texture2D tempTexture = new Texture2D (rt.width, rt.height);
RenderTexture.active = rt;
tempTexture.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
tempTexture.Apply();
// write Texture2D to a file
byte[] bytes;
bytes = tempTexture.EncodeToPNG ();
System.IO.File.WriteAllBytes (filePath, bytes);
RenderTexture.active = null;
}
}
|
namespace Sentry.Internal.ScopeStack;
internal interface IScopeStackContainer
{
KeyValuePair<Scope, ISentryClient>[]? Stack { get; set; }
}
|
using Orleans;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.Host;
using System;
namespace SiloHostTutorial
{
/// <summary>
/// Orleans test silo host
/// </summary>
public class Program
{
static private IClusterClient client;
private static void Main(string[] args)
{
// First, configure and start a local silo
var siloConfig = ClusterConfiguration.LocalhostPrimarySilo();
var silo = new SiloHost("TestSilo", siloConfig);
silo.InitializeOrleansSilo();
silo.StartOrleansSilo();
Console.WriteLine("Silo started.");
// Then configure and connect a client.
var clientConfig = ClientConfiguration.LocalhostSilo();
client = new ClientBuilder().UseConfiguration(clientConfig).Build();
client.Connect().Wait();
Console.WriteLine("Client connected.");
CreateTimer();
Console.WriteLine("\nPress Enter to terminate...");
Console.ReadLine();
// Shut down
client.Close();
silo.ShutdownOrleansSilo();
}
private static void CreateTimer()
{
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += ATimer_Elapsed1; ;
aTimer.Interval = 1000;
aTimer.Enabled = true;
}
private static void ATimer_Elapsed1(object sender, System.Timers.ElapsedEventArgs e)
{
Random rnd = new Random();
var converterGrain = client.GetGrain<ConverterContracts.IConverter>(new Guid());
int value1 = rnd.Next(1000);
int value2 = rnd.Next(1000);
var result1 = converterGrain.ConvertToKm(value1);
var result2 = converterGrain.ConvertToMile(value2);
Console.WriteLine($"Original Value: {value1} Miles Converted Value: {result1.Result} Km");
Console.WriteLine($"Original Value: {value2} Km Converted Value: {result2.Result} Miles");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Euler_Logic.Problems.AdventOfCode.Y2020 {
public class Problem03 : AdventOfCodeBase {
public override string ProblemName => "Advent of Code 2020: 3";
public override string GetAnswer() {
return Answer2().ToString();
}
private ulong Answer1() {
return GetTreeCount(Input(), new Tuple<int, int>(3, 1));
}
private ulong Answer2() {
var map = Input();
ulong total = 1;
total *= GetTreeCount(map, new Tuple<int, int>(1, 1));
total *= GetTreeCount(map, new Tuple<int, int>(3, 1));
total *= GetTreeCount(map, new Tuple<int, int>(5, 1));
total *= GetTreeCount(map, new Tuple<int, int>(7, 1));
total *= GetTreeCount(map, new Tuple<int, int>(1, 2));
return total;
}
private ulong GetTreeCount(List<string> map, Tuple<int, int> slope) {
int x = slope.Item1;
int y = slope.Item2;
int length = map[0].Length;
ulong treeCount = 0;
do {
if (map[y][x] == '#') {
treeCount++;
}
x = (x + slope.Item1) % length;
y += slope.Item2;
} while (y < map.Count);
return treeCount;
}
private List<string> TestInput() {
return new List<string>() {
"..##.......",
"#...#...#..",
".#....#..#.",
"..#.#...#.#",
".#...##..#.",
"..#.##.....",
".#.#.#....#",
".#........#",
"#.##...#...",
"#...##....#",
".#..#...#.#"
};
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class LevelButton : MonoBehaviour
{
public GameObject pauseMenu,settingsMenu,menu;
public Text gameOver, gameOverTxt, scoreTxt;
public void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
Time.timeScale = 1f;
Debug.Log("çalıştı");
}
public void Main()
{
SceneManager.LoadScene("menu");
Time.timeScale = 1f;
PlayerPrefs.SetInt("life", 3);
}
public void Pause()
{
if (menu.activeInHierarchy == false)
{
PlayerPrefs.SetInt("mnu", 1);
pauseMenu.SetActive(true);
Time.timeScale = 0f;
}
}
public void Back()
{
PlayerPrefs.SetInt("menu", 0);
pauseMenu.SetActive(false);
settingsMenu.SetActive(false);
Time.timeScale = 1f;
}
public void Settings()
{
settingsMenu.SetActive(true);
Time.timeScale = 0f;
}
public void changeTr()
{
Text gameOver = gameObject.GetComponent<Text>();
Text gameOverTxt = gameObject.GetComponent<Text>();
Text scoreTxt = gameObject.GetComponent<Text>();
Text scoreTxt2 = gameObject.GetComponent<Text>();
gameOver.text = "oyun bitti";
gameOverTxt.text = "kaldıgın yerden devam etmek icin oyna butonuna bas.";
scoreTxt.text = "skor";
scoreTxt2.text = "skor";
}
}
|
using System;
using System.IO;
using System.Text;
public static class GClass3
{
public static readonly Encoding encoding_0 = Encoding.GetEncoding(28591);
public static long smethod_0(Stream stream_0, Stream stream_1)
{
long long_ = 9223372036854775807L;
try
{
long_ = stream_1.Length;
}
catch
{
}
return GClass3.smethod_1(stream_0, stream_1, long_);
}
public static long smethod_1(Stream stream_0, Stream stream_1, long long_0)
{
byte[] array = new byte[2097152];
long num = 0L;
while (num < long_0)
{
int num2 = stream_1.Read(array, 0, array.Length);
num += (long)num2;
if (num > long_0)
{
num2 -= (int)(num - long_0);
}
if (num2 == 0)
{
break;
}
stream_0.Write(array, 0, num2);
if (num2 < array.Length)
{
break;
}
}
return num;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PowerupScript : MonoBehaviour
{
public SpitterScript.SpitState whichPowerup;
private ParticleSystem _particle;
private bool _canPowerup;
private Rigidbody _rb;
public SpawnPowerup _spawner;
private void Start()
{
_canPowerup = true;
_rb = GetComponent<Rigidbody>();
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
_spawner.Spawning = true;
other.GetComponentInChildren<SpitterScript>().ChangeState(whichPowerup);
Destroy(gameObject);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ComponentFactory.Krypton.Toolkit;
using TY.SPIMS.Controllers;
using System.IO;
using TY.SPIMS.Utilities;
using TY.SPIMS.Controllers.Interfaces;
namespace TY.SPIMS.Client.Inventory
{
public partial class ViewItemForm : ComponentFactory.Krypton.Toolkit.KryptonForm
{
private readonly IAutoPartController autoPartController;
public int AutoPartDetailId { get; set; }
BackgroundWorker pictureWorker = new BackgroundWorker();
public ViewItemForm()
{
this.autoPartController = IOC.Container.GetInstance<AutoPartController>();
InitializeComponent();
pictureWorker.DoWork += new DoWorkEventHandler(pictureWorker_DoWork);
pictureWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(pictureWorker_RunWorkerCompleted);
}
#region Worker
void pictureWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Result != null)
{
ItemPictureBox.ImageLocation = e.Result.ToString();
}
}
void pictureWorker_DoWork(object sender, DoWorkEventArgs e)
{
if (e.Argument != null)
{
string serverIP = TY.SPIMS.Utilities.Helper.GetServerIP();
string serverPath = string.Format(@"\\{0}\{1}\", serverIP, AutoPartController._pictureFolderName);
string picPath = Path.Combine(serverPath, e.Argument.ToString());
if(File.Exists(picPath))
e.Result = picPath;
}
}
#endregion
private void ViewItem_Load(object sender, EventArgs e)
{
LoadItemDetails();
CheckUserAccess();
if (UserInfo.IsVisitor == false)
ItemPictureBox.Visible = false;
}
private void CheckUserAccess()
{
if (UserInfo.IsVisitor)
{
EditButton.Visible = false;
BuyingGroup.Visible = false;
}
}
private void LoadItemDetails()
{
if (AutoPartDetailId != 0)
{
var part = this.autoPartController.FetchAutoPartDetailById(AutoPartDetailId);
if (part != null)
{
AutoPartLabel.Text = part.AutoPart.PartName;
DescriptionLabel.Text = part.Description;
PartNumberLabel.Text = part.PartNumber;
if (part.AutoPartAltPartNumber.Count > 0)
{
StringBuilder s = new StringBuilder();
foreach (var p in part.AutoPartAltPartNumber)
s.AppendFormat("{0}{1}", p.AltPartNumber, Environment.NewLine);
AltPartNumberLabel.Text = s.ToString();
}
else
AltPartNumberLabel.Text = "-";
BrandLabel.Text = part.Brand.BrandName;
MakeLabel.Text = !string.IsNullOrWhiteSpace(part.Make) ?
part.Make : "-";
ModelLabel.Text = !string.IsNullOrWhiteSpace(part.Model) ?
part.Model : "-";
SizeLabel.Text = !string.IsNullOrWhiteSpace(part.Size) ?
part.Size : "-";
SellingPriceLabel.Text = part.SellingPrice1.HasValue ?
part.SellingPrice1.Value.ToString("Php #,##0.00") : "Php 0.00";
SellingPrice2Label.Text = part.SellingPrice2.HasValue ?
part.SellingPrice2.Value.ToString("Php #,##0.00") : "Php 0.00";
BuyingLabel.Text = part.BuyingPrice.HasValue ?
part.BuyingPrice.Value.ToString("Php #,##0.00") : "Php 0.00";
QuantityLabel.Text = string.Format("{0} {1}",
part.Quantity.HasValue ? part.Quantity.Value.ToString() : "0",
part.Unit);
if (!string.IsNullOrWhiteSpace(part.Picture))
{
pictureWorker.RunWorkerAsync(part.Picture);
}
}
}
}
private void EditButton_Click(object sender, EventArgs e)
{
ClientHelper.IsEdit = true;
this.Close();
}
}
} |
using Core;
using ServiceCenter.ViewModel.Repair;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace ServiceCenter.View.Repair
{
public partial class Repair : UserControl
{
public Repair()
{
InitializeComponent();
DatePickerIn.Language = System.Windows.Markup.XmlLanguage.GetLanguage("ru-RU");
DatePickerOut.Language = System.Windows.Markup.XmlLanguage.GetLanguage("ru-RU");
}
private void DataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (this.DataContext != null)
{
var context = this.DataContext as RepairViewModel;
context.OrderDetailCommand.Execute(new object());
}
}
private void btnClear_Click(object sender, System.Windows.RoutedEventArgs e)
{
if (DataContext != null && !string.IsNullOrEmpty(tbSearch.Text))
{
RepairViewModel context = (RepairViewModel)DataContext;
context.CancelSearchCommand.Execute(new object());
}
}
private void tbSearch_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
if (DataContext != null)
{
RepairViewModel context = (RepairViewModel)DataContext;
context.SearchOrderCommand.Execute(new object());
}
}
}
private void MenuItem_Click(object sender, System.Windows.RoutedEventArgs e)
{
if (DataContext != null)
{
RepairViewModel context = (RepairViewModel)DataContext;
context.OrderToWork((e.OriginalSource as MenuItem).Header.ToString());
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using OUTDOOR.src.tools.objects;
namespace OUTDOOR.src.view.options
{
public partial class Inicio_option : UserControl
{
Thread hilo;
public Inicio_option()
{
InitializeComponent();
hilo = new Thread(parpadeo);
hilo.Start();
}
private Jugador _jugador;
public void insertarNombre(Jugador jugador)
{
_jugador = jugador;
this.label2.Text = "Score de " + _jugador.Nombre + " " + _jugador.Apepat + " " + _jugador.Apemat;
}
private void parpadeo()
{
while (true)
{
Thread.Sleep(1000);
par();
}
}
private void par()
{
if (InvokeRequired)
{
del_parpadeo dp = new del_parpadeo(par);
Invoke(dp);
}
else
{
if (label1.Visible)
{
label1.Visible = false;
}
else
{
label1.Visible = true;
}
}
}
private delegate void del_parpadeo();
public int nivel()
{
return int.Parse(comboBox1.SelectedItem.ToString());
}
public void pararHilo()
{
this.hilo.Abort();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace NoteManager.Models
{
public class Notebook
{
public int NotebookId { get; set; }
[Required]
[StringLength(60, MinimumLength = 3)]
public string Name { get; set; }
[Required]
[StringLength(300, MinimumLength = 15)]
public string Description { get; set; }
[Required]
[DataType(DataType.DateTime)]
public DateTime CreatedDateUtc { get; set; }
[StringLength(450)]
public string CreatorId { get; set; }
public ApplicationUser Creator { get; set; }
public ICollection<Note> Notes { get; set; }
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.