text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TRPO_labe_6.Models;
using TRPO_labe_6.Models.FileWorkers;
namespace TRPO_labe_6_console
{
public class ShopsContext
{
private List<Shop> Shops { get; }
public ShopsContext()
{
Shops = GetBoolAnswer("Десериализовать ли магазины из файла? \n1. Да\n2. Нет",
x => x == 1) ? new JsonFileDeserializer<List<Shop>>($"{Directory.GetCurrentDirectory()}//shops.json")
.Read() : new List<Shop>();
StartContext();
}
private void StartContext()
{
while (true)
{
Console.WriteLine("1. Добавить магазин");
Console.WriteLine("2. Сохранить текущее состояние в файле");
Console.WriteLine("3. Контроллер магазина");
Console.WriteLine("Ответ: ");
if (int.TryParse(Console.ReadLine(), out int answer))
{
switch (answer)
{
case 1:
{
var builder = new ShopBuilder();
var shop = builder.Build();
Shops.Add(shop);
break;
}
case 2:
{
var serializer = new JsonFileSerializer<List<Shop>>($"{Directory.GetCurrentDirectory()}//shops.json");
serializer.Rewrite(Shops);
break;
}
case 3:
{
if (Shops.Count == 0)
Console.WriteLine("Магазинов нет!");
else
{
var shop = GetShop();
ShopController(shop);
}
break;
}
}
}
}
}
private void ShopController(Shop shop)
{
Console.WriteLine("1. Добавить продавца");
Console.WriteLine("2. Удалить продавца");
Console.WriteLine("3. Добавить товар");
Console.WriteLine("4. Продать товар");
Console.WriteLine("5. Посчитать общую сумму всех покупок");
int answer = int.Parse(Console.ReadLine());
switch (answer)
{
case 1:
{
var builder = new ShopAssistantBuilder();
var assistant = builder.Build();
shop.Assistants.Add(assistant);
break;
}
case 2:
{
if (shop.Assistants.Count == 0)
{
Console.WriteLine("Работников в этом магазине нет!");
}
else
{
var assist = GetShopAssistant(shop);
shop.Assistants.Remove(assist);
}
break;
}
case 3:
{
var builder = new ProductBuilder();
var product = builder.Build();
shop.AddProduct(product);
break;
}
case 4:
{
var assist = GetShopAssistant(shop);
if (assist == null)
return;
var product = GetProduct(shop);
if (product == null)
return;
shop.SellProduct(assist, product);
break;
}
case 5:
{
Console.WriteLine($"Общая стоимость покупок: {shop.CalculateOverall()}");
break;
}
}
}
private Shop GetShop()
{
Console.WriteLine("Список магазинов: ");
for (int i = 0; i < Shops.Count; i++)
Console.WriteLine($"{i} : {Shops[i]}");
int index = int.Parse(Console.ReadLine() ?? throw new InvalidOperationException());
if (index < 0 || index >= Shops.Count) throw new IndexOutOfRangeException();
return Shops[index];
}
private ShopAssistant GetShopAssistant(Shop shop)
{
if (shop.Assistants.Count == 0)
{
Console.WriteLine("Ассистентов нет!");
return null;
}
Console.WriteLine("Список работников: ");
for (int i = 0; i < shop.Assistants.Count; i++)
Console.WriteLine($"{i} : {shop.Assistants[i]}");
int index = int.Parse(Console.ReadLine() ?? throw new InvalidOperationException());
if (index < 0 || index >= shop.Assistants.Count) throw new IndexOutOfRangeException();
return shop.Assistants[index];
}
private Product GetProduct(Shop shop)
{
if (shop.Products.Count == 0)
{
Console.WriteLine("В магазине нет продуктов!");
return null;
}
Console.WriteLine("Список продуктов: ");
for (int i = 0; i < shop.Products.Count; i++)
Console.WriteLine($"{i} : {shop.Products.ElementAt(i)}");
int index = int.Parse(Console.ReadLine() ?? throw new InvalidOperationException());
if (index < 0 || index >= shop.Products.Count) throw new IndexOutOfRangeException();
return shop.Products.ElementAt(index);
}
private bool GetBoolAnswer(string text, Func<int, bool> func)
{
Console.WriteLine(text);
string answer = Console.ReadLine();
if (int.TryParse(answer, out int answerResult))
{
if (func.Invoke(answerResult))
{
return true;
}
}
return false;
}
private bool GetBoolAnswer(string text, Func<string, bool> func)
{
Console.WriteLine(text);
string answer = Console.ReadLine();
if (func.Invoke(answer))
return true;
return false;
}
}
}
|
namespace com.Sconit.Entity.SI.SD_INV
{
using System;
using System.Collections.Generic;
[Serializable]
public class StockTakeMaster
{
#region O/R Mapping Properties
public String StNo { get; set; }
//全盘,抽盘
public com.Sconit.CodeMaster.StockTakeType StockTakeType { get; set; }
//动态盘点,静态盘点
//public com.Sconit.CodeMaster.StockTakeType StockTakeDsType { get; set; }
public String Location { get; set; }
public com.Sconit.CodeMaster.StockTakeStatus Status { get; set; }
//是否需要扫描条码
public Boolean IsScan { get; set; }
//生效时间,用于调节历史库存
public DateTime EffectiveDate { get; set; }
//取库存比较的时间,以此时间点的库存和盘点结果作比较得出盘点差异
public DateTime StockTakeDate { get; set; }
public String Region { get; set; }
#endregion
#region 辅助字段
public string CurrentBin { get; set; }
public List<StockTakeDetail> StockTakeDetails { get; set; }
#endregion
}
}
|
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Camera))]
public class CameraFollow : MonoBehaviour {
public Transform[] targets;
public bool useDefaultCameraOffset;
public bool useMouseRotation;
public bool useMouseZoom;
public bool updateCameraTargetVerticalOffset;
public float mouseSmoothing = 5f;
public float cameraMinimumZoomDistance = 50f;
public float cameraMaximumZoomDistance = 200f;
public float cameraTargetVerticalOffset = 3f;
private Vector3 offset;
private void Start() {
Application.targetFrameRate = 120;
if ( useDefaultCameraOffset ) {
transform.position = GetTarget() + new Vector3(18, 2.5f, 0);
LookAtSubject();
}
offset = GetTarget() - transform.position;
}
private void Update() {
UpdateCameraZoom();
UpdateCameraPosition();
UpdateCameraRotation();
UpdateCameraOffset();
}
private void UpdateCameraPosition() {
transform.position = GetTarget() - offset;
}
private void UpdateCameraRotation() {
if ( useMouseRotation )
transform.RotateAround(GetTarget(), Vector3.up, Input.GetAxis("Mouse X") * mouseSmoothing);
LookAtSubject();
}
private void UpdateCameraZoom() {
if ( !useMouseZoom )
return;
float scrollWheel = Input.GetAxis("Mouse ScrollWheel");
if ( ZoomIn(scrollWheel) ) {
if ( CanZoomIn() ) {
float cameraZoom = 0.9f;
offset *= cameraZoom;
if ( TooMuchZoom() ) {
cameraZoom = CalculateExcessZoom();
offset *= cameraZoom;
} else if ( updateCameraTargetVerticalOffset ) {
cameraTargetVerticalOffset *= CalculateCameraTargetVerticalOffset(cameraZoom);
}
}
} else if ( ZoomOut(scrollWheel) ) {
if ( CanZoomOut() ) {
float cameraZoom = 1.1f;
offset *= cameraZoom;
if ( TooLittleZoom() ) {
cameraZoom = CalculateMissingZoom();
offset *= cameraZoom;
} else if ( updateCameraTargetVerticalOffset ) {
cameraTargetVerticalOffset *= CalculateCameraTargetVerticalOffset(cameraZoom);
}
}
}
}
private void UpdateCameraOffset() {
offset = GetTarget() - transform.position;
}
private void LookAtSubject() {
transform.LookAt(GetTarget() + Vector3.up * cameraTargetVerticalOffset);
}
private bool ZoomIn(float scrollWheel) {
return scrollWheel > 0f;
}
private bool ZoomOut(float scrollWheel) {
return scrollWheel < 0f;
}
private bool CanZoomIn() {
return offset.sqrMagnitude > cameraMinimumZoomDistance;
}
private bool CanZoomOut() {
return offset.sqrMagnitude < cameraMaximumZoomDistance;
}
private bool TooMuchZoom() {
return !CanZoomIn();
}
private bool TooLittleZoom() {
return !CanZoomOut();
}
private float CalculateCameraTargetVerticalOffset(float cameraZoom) {
return 1 - (1 - cameraZoom) / 2;
}
private float CalculateExcessZoom() {
return (1 - offset.sqrMagnitude / cameraMinimumZoomDistance) / 2 + 1;
}
private float CalculateMissingZoom() {
return (1 - offset.sqrMagnitude / cameraMaximumZoomDistance) / 2 + 1;
}
private Vector3 GetTarget() {
Vector3 target = Vector3.zero;
CheckForNewGame();
for ( int i = 0; i < targets.Length; i++ ) {
target += targets[i].position;
}
target /= targets.Length;
return target;
}
private void CheckForNewGame() {
bool newGame = false;
if(targets[0] == null || targets[1] == null) {
newGame = true;
}
if ( newGame ) {
targets[0] = GameObject.FindGameObjectWithTag("Player").transform;
targets[1] = GameObject.FindGameObjectWithTag("Player2").transform;
}
}
}
|
using System;
using System.Net.Sockets;
using System.Text;
namespace Client
{
class Program
{
private const int port = 8888;
private const string host = "127.0.0.1";
static void Main(string[] args)
{
try
{
TcpClient client = new TcpClient();
client.Connect(host, port);
byte[] buffer = new byte[256];
StringBuilder response = new StringBuilder();
NetworkStream stream = client.GetStream();
do
{
int bytes = stream.Read(buffer, 0, buffer.Length);
response.Append(Encoding.UTF8.GetString(buffer, 0, bytes));
}
while (stream.DataAvailable); // пока данные есть в потоке
Console.WriteLine(response.ToString());
// Закрываем потоки
stream.Close();
client.Close();
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
catch (Exception e)
{
Console.WriteLine("Exception: {0}", e.Message);
}
Console.WriteLine("Запрос завершен...");
Console.Read();
}
}
}
|
using mec.Model.Processes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mec.Database.Repositories
{
public class FlowRepository : BaseRepository
{
public IEnumerable<FlowCard> Gets(FlowParam param)
{
using (var db = new OracleDbContext(this.connectName))
{
var q = from a in db.FlowCards
where a.ORG_CODE == param.OrgCode
select a;
if (string.IsNullOrEmpty(param.WorkNo) == false)
{
q = q.Where(p => p.C_WORK_ORDER == param.WorkNo);
}
if (string.IsNullOrEmpty(param.Status) == false)
{
q = q.Where(p => p.C_STATUS == param.Status);
}
if (string.IsNullOrEmpty(param.QualifiedType) == false)
{
q = q.Where(p => p.C_QUALIFIED_TYPE == param.QualifiedType);
}
if (q.Any())
{
return q.ToList();
}
return null;
}
}
}
}
|
using System.Collections.Generic;
namespace WebStore.Domain
{
public class PageQueryResult<T>
{
public IEnumerable<T> Items { get; init; }
public int TotalCount { get; init; }
//public int Page { get; init; }
//public int TotalPageCount => (int) Math.Ceiling((double) TotalCount / Items.Count());
}
} |
using Cs_Notas.Dominio.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Notas.Dominio.Interfaces.Repositorios
{
public interface IRepositorioBensAtosConjuntos: IRepositorioBase<BensAtosConjuntos>
{
List<BensAtosConjuntos> ObterBensAtoConjuntosPorIdAto(int idAto);
}
}
|
using Plotter.Tweet.Processing;
using System;
using System.Collections.Concurrent;
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 IOTest : Form
{
private ConcurrentQueue<Tweet.Tweet> _incomingQueue;
public IOTest()
{
InitializeComponent();
label3.Text = "";
var syncContext = new WindowsFormsSynchronizationContext();
_incomingQueue = new ConcurrentQueue<Tweet.Tweet>();
QueueProcessor processor = new QueueProcessor(_incomingQueue, new TestDBContext());
processor.TweetReady += (object sender, Tweet.Tweet e) =>
{
syncContext.Post((object userData) =>
{
label3.Text = e.Text;
if (e.Image != null && e.Image.Length > 0)
{
MemoryStream ms = new MemoryStream(e.Image);
ms.Write(e.Image, 0, e.Image.Length);
ms.Position = 0;
pictureBox1.Image = Image.FromStream(ms);
}
else
{
pictureBox1.Image = null;
}
}, null);
};
}
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.Image = null;
label3.Text = "";
_incomingQueue.Enqueue(new Tweet.Tweet()
{
CreatorScreenName = "@test",
Text = textBox1.Text
});
textBox1.Text = "";
}
}
}
|
// <copyright file="DownloadManager.cs" company="Firoozeh Technology LTD">
// Copyright (C) 2019 Firoozeh Technology LTD. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using FiroozehGameService.Builder;
using FiroozehGameService.Core.ApiWebRequest;
using FiroozehGameService.Handlers;
using FiroozehGameService.Models;
using FiroozehGameService.Models.Enums;
using FiroozehGameService.Models.EventArgs;
using FiroozehGameService.Models.Internal;
using FiroozehGameService.Utils;
/**
* @author Alireza Ghodrati
*/
namespace FiroozehGameService.Core
{
/// <summary>
/// Represents Game Service DownloadManager
/// </summary>
internal class DownloadManager
{
internal DownloadManager(GameServiceClientConfiguration config)
{
_configuration = config;
_webClients = new Dictionary<string, WebClient>();
}
internal async Task StartDownload(string tag)
{
try
{
var assetInfo = await ApiRequest.GetAssetInfo(_configuration.ClientId, tag);
await StartDownloadWithInfo(assetInfo);
}
catch (Exception e)
{
DownloadEventHandlers.DownloadError?.Invoke(this, new DownloadErrorArgs
{
Error = e.Message
});
}
}
internal async Task StartDownload(string tag, string path)
{
try
{
var assetInfo = await ApiRequest.GetAssetInfo(_configuration.ClientId, tag);
StartDownloadWithInfo(assetInfo, path);
}
catch (Exception e)
{
DownloadEventHandlers.DownloadError?.Invoke(this, new DownloadErrorArgs
{
Error = e.Message
});
}
}
internal async Task StartDownloadWithInfo(AssetInfo info)
{
try
{
if (_webClients.ContainsKey(info.AssetInfoData.Name))
{
DownloadEventHandlers.DownloadError?.Invoke(this, new DownloadErrorArgs
{
AssetInfo = info,
Error = "Tag \"" + info.AssetInfoData.Name + "\" is Already in Download Queue!"
});
return;
}
var client = new WebClient();
_webClients.Add(info.AssetInfoData.Name, client);
// Set Events
client.DownloadProgressChanged += (s, progress) =>
{
DownloadEventHandlers.DownloadProgress?.Invoke(this, new DownloadProgressArgs
{
FileTag = info.AssetInfoData.Name,
BytesReceived = progress.BytesReceived,
TotalBytesToReceive = progress.TotalBytesToReceive,
ProgressPercentage = progress.ProgressPercentage
});
};
client.DownloadDataCompleted += (sender, args) =>
{
if (args.Cancelled)
{
DownloadEventHandlers.DownloadCancelled?.Invoke(this,
new DownloadCancelledArgs {AssetInfo = info});
return;
}
client.Dispose();
_webClients.Remove(info.AssetInfoData.Name);
DownloadEventHandlers.DownloadCompleted?.Invoke(this, new DownloadCompleteArgs
{
DownloadedAssetAsBytes = args.Result
});
};
await client.DownloadDataTaskAsync(info.AssetInfoData.Link);
}
catch (Exception e)
{
_webClients.Remove(info.AssetInfoData.Name);
DownloadEventHandlers.DownloadError?.Invoke(this, new DownloadErrorArgs
{
AssetInfo = info,
Error = e.Message
});
}
}
internal void StartDownloadWithInfo(AssetInfo info, string path)
{
var completeAddress = path + '/' + info.AssetInfoData.Name;
try
{
if (_webClients.ContainsKey(info.AssetInfoData.Name))
{
DownloadEventHandlers.DownloadError?.Invoke(this, new DownloadErrorArgs
{
AssetInfo = info,
SavePath = completeAddress,
Error = "Tag \"" + info.AssetInfoData.Name + "\" is Already in Download Queue!"
});
return;
}
var client = new WebClient();
_webClients.Add(info.AssetInfoData.Name, client);
// Set Events
client.DownloadProgressChanged += (s, progress) =>
{
DownloadEventHandlers.DownloadProgress?.Invoke(this, new DownloadProgressArgs
{
FileTag = info.AssetInfoData.Name,
BytesReceived = progress.BytesReceived,
TotalBytesToReceive = progress.TotalBytesToReceive,
ProgressPercentage = progress.ProgressPercentage
});
};
client.DownloadFileCompleted += (s, e) =>
{
if (e.Cancelled)
{
RemoveCancelledFile(completeAddress);
DownloadEventHandlers.DownloadCancelled?.Invoke(this,
new DownloadCancelledArgs {AssetInfo = info, SavePath = path});
return;
}
client.Dispose();
_webClients.Remove(info.AssetInfoData.Name);
DownloadEventHandlers.DownloadCompleted?.Invoke(this, new DownloadCompleteArgs
{
DownloadedAssetPath = completeAddress
});
};
client.DownloadFileAsync(new Uri(info.AssetInfoData.Link), completeAddress);
}
catch (Exception e)
{
_webClients.Remove(info.AssetInfoData.Name);
DownloadEventHandlers.DownloadError?.Invoke(this, new DownloadErrorArgs
{
AssetInfo = info,
SavePath = completeAddress,
Error = e.Message
});
}
}
internal void CancelAllDownloads()
{
foreach (var client in _webClients)
{
client.Value?.CancelAsync();
client.Value?.Dispose();
}
_webClients.Clear();
}
internal void CancelDownload(string tag)
{
if (!_webClients.ContainsKey(tag))
throw new GameServiceException("The Tag \"" + tag + "\" is Not Exist In Download Queue!")
.LogException<DownloadManager>(DebugLocation.Internal, "CancelDownload(string)");
_webClients[tag]?.CancelAsync();
_webClients[tag]?.Dispose();
_webClients.Remove(tag);
}
internal void CancelDownload(AssetInfo info)
{
var tag = info.AssetInfoData.Name;
if (!_webClients.ContainsKey(tag))
throw new GameServiceException("The Tag \"" + tag + "\" is Not Exist In Download Queue!")
.LogException<DownloadManager>(DebugLocation.Internal, "CancelDownload(AssetInfo)");
_webClients[tag]?.CancelAsync();
_webClients[tag]?.Dispose();
_webClients.Remove(tag);
}
private static void RemoveCancelledFile(string fullPath)
{
File.Delete(fullPath);
}
#region DownloadRegion
private readonly GameServiceClientConfiguration _configuration;
private readonly Dictionary<string, WebClient> _webClients;
#endregion
}
} |
using DistCWebSite.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Http.WebHost;
using System.Net.Http;
namespace DistCWebSite
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { action = RouteParameter.Optional, id = RouteParameter.Optional }
);
//GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
UserModel user = new UserModel(HttpContext.Current.User.Identity.Name);
HttpContext.Current.User = user;
}
}
}
}
}
|
using MeriMudra.Models;
using MeriMudra.Models.ViewModels;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
namespace MeriMudra.Controllers
{
public class CreditCardController : Controller
{
private MmDbContext db = new MmDbContext();
// GET: CreditCard
public ActionResult Index()
{
return View(db.CreditCards.ToList());
}
public ActionResult CardDetail(int id = 1)
{
var ccViewModel = new CreditCardViewModel(id);
return View(ccViewModel);
}
// Pass CreditCard Application Id
public ActionResult AvilableCreditCardsAsPerApplication()
{
string id = TempData["ApplyId"] == null ? null : Convert.ToString(TempData["ApplyId"]);
var avilableCreditCards = new List<CreditCard> { };
var avilableCardids = new List<int> { };
var avilableCityGroupId = new List<int> { };
if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var userCcApplication = db.UserCCApplyDetail.Find(Convert.ToInt32(id));
if (userCcApplication == null) return HttpNotFound();
var cGrp = (from cg in db.CityGroups select new { cg.GroupId, cg.CityIds }).AsEnumerable().Select(item => new KeyValuePair<int, string>(item.GroupId, item.CityIds)).ToList();
foreach (var item in cGrp)
{
if (item.Value.Split(',').Any(cid => cid.Equals(userCcApplication.CityId.ToString())))
{
avilableCityGroupId.Add(item.Key);
}
}
foreach (var cgId in avilableCityGroupId)
{
var sc = db.CcEligibilityCriterias.ToList();
avilableCardids.AddRange(db.CcEligibilityCriterias.Where(ec => ec.CityGroupId == cgId).Select(ec => ec.CardId).ToList());
var ecs = db.CcEligibilityCriterias.Where(ec => ec.CityGroupId == cgId).ToList();
foreach (var ec in ecs)
{
if (userCcApplication.EmployerType.Value)
{
if (userCcApplication.GrossIncomeOrNetSalary.Value >= ec.MinSalary)
{
userCcApplication.CreditCardId = ec.CardId;
db.SaveChanges(); break;
}
}
else
{
if (userCcApplication.GrossIncomeOrNetSalary.Value >= ec.MinItr)
{
userCcApplication.CreditCardId = ec.CardId;
db.SaveChanges(); break;
}
}
}
}
avilableCardids = avilableCardids.Distinct().ToList();
foreach (var cardId in avilableCardids) avilableCreditCards.Add(db.CreditCards.Find(cardId));
ViewBag.userCcApplication = userCcApplication;
return View(avilableCreditCards);
}
public int InterestedFor(int CcApplicationId, int Cardid)
{
var updateFlag = 0;
var ccApplication = db.UserCCApplyDetail.Find(CcApplicationId);
if (ccApplication != null)
{
ccApplication.CreditCardId = Cardid;
db.Entry(ccApplication).State = System.Data.Entity.EntityState.Modified;
updateFlag = db.SaveChanges();
}
return updateFlag;
}
public ActionResult CreditCard(int id = 0)
{
ViewBag.id = id;
//sendsms.run("9140764725", "run");
var model = new detailsForApplyCard { Banks = db.Banks.ToList(), CreditCards = db.CreditCards.ToList(), Citys = db.Citys.ToList(), Companys = db.Companys.ToList() };
return View(model);
}
[HttpPost]
public int savestep(object convertedJSON, int isfinish = 0)
{
var a = (string[])convertedJSON;
//string []a1 = (string[])convertedJSON;
var userdata = new UserCCApplyDetail();
foreach (var item in a)
{
userdata = JsonConvert.DeserializeObject<UserCCApplyDetail>(item);
}
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MmDbConnectionString"].ConnectionString))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction;
transaction = connection.BeginTransaction("SampleTransaction");
command.Connection = connection;
command.Transaction = transaction;
try
{
if (userdata.CurrentOrPrevLoan == "1")
userdata._CurrentOrPrevLoan = true;
else if (userdata.CurrentOrPrevLoan == "0")
userdata._CurrentOrPrevLoan = false;
command.Parameters.Clear();
command.CommandText = "Insert_UserCCApplyDetail";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@Id", userdata.Id);
command.Parameters.AddWithValue("@CompanyName", userdata.CompanyName);
command.Parameters.AddWithValue("@GrossIncomeOrNetSalary", userdata.GrossIncomeOrNetSalary);
command.Parameters.AddWithValue("@Name", userdata.Name);
command.Parameters.AddWithValue("@DOB", userdata.DOB);
command.Parameters.AddWithValue("@CityId", userdata.CityId);
command.Parameters.AddWithValue("@CityName", !string.IsNullOrEmpty(userdata.CityName) ? userdata.CityName : db.Citys.Find(userdata.CityId).Name);
command.Parameters.AddWithValue("@PinCode", userdata.PinCode);
command.Parameters.AddWithValue("@MobileNumber", userdata.MobileNumber);
command.Parameters.AddWithValue("@OTP", userdata.OTP);
command.Parameters.AddWithValue("@email", userdata.email);
string accountWith = string.Join(",", userdata.AccountWithIdList);
accountWith = accountWith.Length > 4 ? accountWith.Substring(4, accountWith.Length - 4) : "";
string CreditCardWith = string.Join(",", userdata.CreditCardWith);
CreditCardWith = CreditCardWith.Length > 4 ? CreditCardWith.Substring(4, CreditCardWith.Length - 4) : "";
command.Parameters.AddWithValue("@AccountWith", accountWith);
command.Parameters.AddWithValue("@CreditCardWith", CreditCardWith);
command.Parameters.AddWithValue("@CreditCardMaxLimit", userdata.CreditCardMaxLimit);
command.Parameters.AddWithValue("@CurrentOrPrevLoan", userdata._CurrentOrPrevLoan);
command.Parameters.AddWithValue("@EmployerType", userdata.EmployerType);
command.Parameters.AddWithValue("@CreditCardId", userdata.CreditCardId);
command.Parameters.AddWithValue("@PanCard", userdata.PanCard);
if (isfinish == 1)
command.Parameters.AddWithValue("@isUserActive", true);
else
command.Parameters.AddWithValue("@isUserActive", false);
var id = command.ExecuteScalar();
transaction.Commit();
connection.Close();
TempData["ApplyId"] = id;
return Convert.ToInt32(id);
}
catch (Exception ex)
{
transaction.Rollback();
connection.Close();
}
}
System.Threading.Thread.Sleep(1000);
return 0;
// var d= JsonConvert.DeserializeObject<detailsForApplyCard>(convertedJSON);
}
}
} |
using UnityEngine;
using System.Collections;
// This adds a 'follow buffer' in which the player won't be detected if they enter it, but if they move out of
// detection range into this range the enemy will still try to follow them.
public class DetectPlayerWithFollowBuffer : DetectPlayer {
[Tooltip("How far the player can stray outside the detection range and still be followed by this mob")]
public float followBuffer = 2;
private float followRange;
void Awake() {
followRange = detectionRange + followBuffer;
}
protected override void OnDrawGizmos() {
base.OnDrawGizmos();
if (gunObject != null && enabled) {
Gizmos.color = Color.green;
Gizmos.DrawWireSphere(gunObject.transform.position, followRange);
}
}
protected override bool IsPlayerDetectable () {
return PlayerInFollowRange();
}
public bool PlayerInFollowRange() {
float distanceToPlayer = Vector2.Distance(enemyPosition, Player.GetPlayerPosition());
return distanceToPlayer <= followRange;
}
}
|
namespace TagProLeague.Models
{
public class SeriesFormat : Document
{
public int GameCount { get; set; }
}
}
|
using System;
using System.Drawing;
using Console = Colorful.Console;
using PasswordStorage.Formatters;
using EncryptStore.BLL;
namespace PasswordStorage
{
class Program
{
static void Main(string[] args)
{
TextDisplayers displayer = new TextDisplayers();
PasswordEncryptDecrypt accessor = new PasswordEncryptDecrypt();
displayer.printHeader(Color.Green, Color.Yellow);
}
}
}
|
using FluentAssertions.Primitives;
namespace Sentry.Testing;
// Reference: https://fluentassertions.com/extensibility/
// This code ensures that when we compare Envelope objects for equivalency, that we
// ignore the `sent_at` header in the envelope, and the `length` header in each item within the envelope.
// TODO: There's probably a better implementation using FA's "step by step" assertions.
// https://fluentassertions.com/extensibility/#equivalency-assertion-step-by-step
public static class FluentAssertionExtensions
{
public static EnvelopeAssertions Should(this Envelope instance) => new(instance);
public static EnvelopeItemAssertions Should(this EnvelopeItem instance) => new(instance);
}
public class EnvelopeAssertions : ReferenceTypeAssertions<Envelope, EnvelopeAssertions>
{
private const string SentAtKey = "sent_at";
public EnvelopeAssertions(Envelope instance) : base(instance)
{
}
protected override string Identifier => "envelope";
public AndConstraint<EnvelopeAssertions> BeEquivalentTo(Envelope expectation)
{
var subjectHasKey = Subject.Header.ContainsKey(SentAtKey);
var expectationHasKey = expectation.Header.ContainsKey(SentAtKey);
if (subjectHasKey == expectationHasKey)
{
// We can check the header directly
Subject.Header.Should().BeEquivalentTo(expectation.Header);
}
else
{
// Check the header separately so we can exclude sent_at
Subject.Header
.Where(x => x.Key != SentAtKey)
.Should().BeEquivalentTo(expectation.Header);
}
// Check the items individually so we can apply our custom assertion to each item
Subject.Items.Should().HaveSameCount(expectation.Items);
for (int i = 0; i < Subject.Items.Count; i++)
{
Subject.Items[i].Should().BeEquivalentTo(expectation.Items[i]);
}
return new AndConstraint<EnvelopeAssertions>(this);
}
}
public class EnvelopeItemAssertions : ReferenceTypeAssertions<EnvelopeItem, EnvelopeItemAssertions>
{
private const string LengthKey = "length";
public EnvelopeItemAssertions(EnvelopeItem instance) : base(instance)
{
}
protected override string Identifier => "envelope item";
public AndConstraint<EnvelopeItemAssertions> BeEquivalentTo(EnvelopeItem expectation)
{
var subjectHasKey = Subject.Header.ContainsKey(LengthKey);
var expectationHasKey = expectation.Header.ContainsKey(LengthKey);
if (subjectHasKey == expectationHasKey)
{
// We can check the entire object directly
AssertionExtensions.Should(Subject).BeEquivalentTo(expectation);
}
else
{
// Check the header separately so we can exclude length
Subject.Header
.Where(x => x.Key != LengthKey)
.Should().BeEquivalentTo(expectation.Header);
// Check the rest of the item, excluding the header
AssertionExtensions.Should(Subject).BeEquivalentTo(expectation,
o => o.Excluding(item => item.Header));
}
return new AndConstraint<EnvelopeItemAssertions>(this);
}
}
|
using System;
using Windows.Networking;
using System.Diagnostics;
using Windows.Networking.Sockets;
using System.Threading.Tasks;
namespace SlotCar
{
class CommUDP
{
private const uint bufLen = 8192;
private string listingOnPort;
private readonly DatagramSocket socket = null;
public delegate void TrackSpeedUpdate(float speed);
public event TrackSpeedUpdate speedUpdate;
public event TrackSpeedUpdate SpeedUpdate
{
add
{
speedUpdate += value;
}
remove
{
speedUpdate -= value;
}
}
internal CommUDP(string port)
{
listingOnPort = port;
socket = new DatagramSocket();
socket.MessageReceived += Receive;
}
internal async Task StartServer(string ip)
{
await socket.BindEndpointAsync(new HostName(ip), listingOnPort);
}
private void Receive(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
uint length = args.GetDataReader().UnconsumedBufferLength;
string pwm = args.GetDataReader().ReadString(length);
Debug.WriteLine(pwm);
float speed = float.Parse(pwm.Split('"')[3]);
speedUpdate(speed);
}
}
}
|
// This file has been generated by the GUI designer. Do not modify.
namespace Compi_segundo
{
public partial class WidgetBuscarRemplazar
{
private global::Gtk.UIManager UIManager;
private global::Gtk.Action goUpAction;
private global::Gtk.Action goDownAction;
private global::Gtk.Action cancelAction;
private global::Gtk.Action Action;
private global::Gtk.VBox vbox8;
private global::Gtk.HBox hbox15;
private global::Gtk.HBox hbox16;
protected virtual void Build ()
{
global::Stetic.Gui.Initialize (this);
// Widget Compi_segundo.WidgetBuscarRemplazar
Stetic.BinContainer w1 = global::Stetic.BinContainer.Attach (this);
this.UIManager = new global::Gtk.UIManager ();
global::Gtk.ActionGroup w2 = new global::Gtk.ActionGroup ("Default");
this.goUpAction = new global::Gtk.Action ("goUpAction", null, null, "gtk-go-up");
w2.Add (this.goUpAction, null);
this.goDownAction = new global::Gtk.Action ("goDownAction", null, null, "gtk-go-down");
w2.Add (this.goDownAction, null);
this.cancelAction = new global::Gtk.Action ("cancelAction", null, null, "gtk-cancel");
w2.Add (this.cancelAction, null);
this.Action = new global::Gtk.Action ("Action", null, null, null);
w2.Add (this.Action, null);
this.UIManager.InsertActionGroup (w2, 0);
this.Name = "Compi_segundo.WidgetBuscarRemplazar";
// Container child Compi_segundo.WidgetBuscarRemplazar.Gtk.Container+ContainerChild
this.vbox8 = new global::Gtk.VBox ();
this.vbox8.Name = "vbox8";
this.vbox8.Spacing = 6;
// Container child vbox8.Gtk.Box+BoxChild
this.hbox15 = new global::Gtk.HBox ();
this.hbox15.Name = "hbox15";
this.hbox15.Spacing = 6;
// Container child hbox15.Gtk.Box+BoxChild
this.hbox16 = new global::Gtk.HBox ();
this.hbox16.Name = "hbox16";
this.hbox16.Spacing = 6;
this.hbox15.Add (this.hbox16);
global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.hbox15 [this.hbox16]));
w3.Position = 1;
this.vbox8.Add (this.hbox15);
global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.vbox8 [this.hbox15]));
w4.Position = 1;
this.Add (this.vbox8);
if ((this.Child != null)) {
this.Child.ShowAll ();
}
w1.SetUiManager (UIManager);
this.Hide ();
}
}
}
|
using System;
namespace HelloWorld
{
public class DisplayMessage
{
public DisplayMessage()
{}
public string messageText
{ get; set; }
public void DisplayGreeting(string message)
{
if(message != null && message.Length != 0)
{
Console.WriteLine(message);
}
else
{
Console.WriteLine("Please enter a greeting.");
}
}
}
} |
using System;
namespace Lesson.Pocos
{
public class Class1
{
}
}
|
using System;
using System.Collections.Generic;
namespace Collections
{
class Program
{
static void Main(string[] args)
{
// Three Basic Arrays
int[] numArray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
string[] nameArray = { "Tim", "Martin", "Nikki", "Sara" };
bool[] booleanArray = { true, false, true, false, true, false, true, false, true, false };
// List of flavors
List<string> flavors = new List<string>();
flavors.Add("Chocolate");
flavors.Add("Vanilla");
flavors.Add("Mocha");
flavors.Add("Cookies & Cream");
flavors.Add("Strawberry");
for (int idx = 0; idx < flavors.Count; idx++)
{
Console.WriteLine(flavors[idx]);
}
Console.WriteLine(flavors.Count);
Console.WriteLine(flavors[2]);
flavors.RemoveAt(2);
Console.WriteLine(flavors.Count);
// Dictionary
Random rand = new Random();
Dictionary<string, string> favorites = new Dictionary<string, string>();
for (int i = 0; i < nameArray.Length; i++)
{
favorites.Add(nameArray[i], flavors[rand.Next(nameArray.Length)]);
}
foreach (var entry in favorites)
{
Console.WriteLine(entry.Key + " - " + entry.Value);
}
}
}
}
|
namespace WinAppDriver.UI
{
using System;
using WinAppDriver.WinUserWrapper;
internal class WindowFactory : IWindowFactory
{
private IUIAutomation uiAutomation;
private IKeyboard keyboard;
private IWinUserWrap winUserWrap;
public WindowFactory(IUIAutomation uiAutomation, IKeyboard keyboard, IWinUserWrap winUserWrap)
{
this.uiAutomation = uiAutomation;
this.keyboard = keyboard;
this.winUserWrap = winUserWrap;
}
public IWindow GetWindow(IntPtr handle)
{
return new Window(handle, this.uiAutomation, this.keyboard, this.winUserWrap);
}
}
} |
using System;
using SFA.DAS.Authorization.ModelBinding;
namespace SFA.DAS.ProviderCommitments.Web.Models.Cohort;
public class SelectPilotStatusViewModel : IAuthorizationContextModel
{
public Guid CacheKey { get; set; }
public long ProviderId { get; set; }
public ChoosePilotStatusOptions? Selection { get; set; }
public bool IsEdit { get; set; }
} |
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 MultiplechoiseSystem.DTO;
using MultiplechoiseSystem.DAO;
using LiveCharts;
using LiveCharts.Wpf;
namespace MultiplechoiseSystem.FORM
{
public partial class UCCourseDetail : UserControl
{
public EventHandler BtnCloseClick;
public UCCourseDetail()
{
InitializeComponent();
AutoCompleteSearch();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void lb_namecourse_Click(object sender, EventArgs e)
{
}
private void btnClose_Click(object sender, EventArgs e)
{
if (this.BtnCloseClick != null)
{
this.BtnCloseClick(this, e);
}
}
private void AutoCompleteSearch()
{
string query = @"Select courseID from COURSE";
DataTable data = DataProvider.Instance.ExecuteQuery(query);
AutoCompleteStringCollection source = new AutoCompleteStringCollection();
//use LINQ method syntax to pull the Title field from a DT into a string array...
string[] postSource = data
.AsEnumerable()
.Select<System.Data.DataRow, String>(x => x.Field<String>("courseID"))
.ToArray();
source.AddRange(postSource);
txtSearchResult.AutoCompleteCustomSource = source;
txtSearchResult.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txtSearchResult.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
private void pn_result_st_Paint(object sender, PaintEventArgs e)
{
}
private void btnReset_Click(object sender, EventArgs e)
{
txtSearchResult.Clear();
}
private int COUNT_NO =1;
private Panel createFrameResult(SheetDTO sheet)
{
Panel p = new Panel();
p.Size = new Size(1365, 70);
p.BackColor = SystemColors.InactiveCaption;
Label NO = new Label();
Label Fullname = new Label();
Label dateDo = new Label();
Label scoreTest = new Label();
Button detail = new Button();
NO.Text = COUNT_NO.ToString();
NO.Location = new Point(5, 24);
Fullname.Text = sheet.Fullname;
Fullname.AutoSize = false;
Fullname.Location = new Point(58, 24);
Fullname.Size = new Size(390, 30);
Fullname.TextAlign = ContentAlignment.MiddleCenter;
dateDo.Text =sheet.DateTake.ToString("dd/MM/yyyy h:mm tt");
dateDo.Location = new Point(510, 24);
dateDo.AutoSize = false;
dateDo.TextAlign = ContentAlignment.MiddleLeft;
dateDo.Size = new Size(404, 30);
scoreTest.Text = sheet.Marks;
scoreTest.Location = new Point(956, 24);
scoreTest.AutoSize = false;
scoreTest.Size = new Size(121, 30);
scoreTest.TextAlign = ContentAlignment.MiddleCenter;
detail.Text = "Detail";
detail.Location = new Point(1167, 0);
detail.Size = new Size(218, 70);
detail.FlatStyle = FlatStyle.Flat;
detail.FlatAppearance.BorderSize = 0;
detail.BackColor = System.Drawing.SystemColors.ActiveCaption;
detail.Click += Btndetail_Click;
detail.Tag = sheet;
COUNT_NO += 1;
p.Controls.Add(NO);
p.Controls.Add(Fullname);
p.Controls.Add(dateDo);
p.Controls.Add(scoreTest);
p.Controls.Add(detail);
return p;
}
private void Btndetail_Click(object sender, EventArgs e)
{
SheetDTO sheet = (sender as Button).Tag as SheetDTO;
string query = $"select codetest from SHEET_ANSWER where userID='{sheet.userID}' and examID='{sheet.examID}' and courseID='{sheet.courseID}'";
DataTable result = DataProvider.Instance.ExecuteQuery(query);
string codeexam = result.Rows[0]["codeTest"].ToString();
FTest1 f = new FTest1(codeexam, UserDTO.Instance.examSelected.courseID, UserDTO.Instance.examSelected.examID, sheet.userID , true);
f.Show();
}
private void DisplayManagerFunction()
{
if (UserDTO.Instance.UserType.Trim()== UserDTO.Instance.Student)
{
pn_search.Visible = false;
pn_manage.Visible = false;
}
else
{
pn_search.Visible = true;
pn_manage.Visible = true;
}
}
private void Displaylabel()
{
lb_namecourse.Text = UserDTO.Instance.examSelected.examID+" "+ UserDTO.Instance.examSelected.courseName;
lbTimeTest.Text = UserDTO.Instance.examSelected.ExamTime+" minutes";
label3.Text = UserDTO.Instance.examSelected.testDate.ToString();
lbnguoirade.Text = UserDTO.Instance.examSelected.teacherCreate;
}
private void UCCourseDetail_Load(object sender, EventArgs e)
{
DisplayManagerFunction();
Displaylabel();
CheckStatusReview();
}
private void CheckStatusReview()
{
string query = $"select * from SHEET_ANSWER where examID='{UserDTO.Instance.examSelected.examID}' and CourseID='{UserDTO.Instance.examSelected.courseID}' and userID='{UserDTO.Instance.userID}'";
DataTable a=DataProvider.Instance.ExecuteQuery(query);
if (a.Rows.Count == 0 && UserDTO.Instance.UserType == UserDTO.Instance.Student)
btnDo.Visible = true;
else
{
if (UserDTO.Instance.UserType == UserDTO.Instance.Student)
foreach( SheetDTO i in SheetAnswerDAO.Instance.getSheetAnswerByIduser(UserDTO.Instance.examSelected.examID, UserDTO.Instance.examSelected.courseID, UserDTO.Instance.userID))
{
flp_result.Controls.Add(createFrameResult(i));
}
else
{
foreach (SheetDTO i in SheetAnswerDAO.Instance.getAllSheetAnswer(UserDTO.Instance.examSelected.examID, UserDTO.Instance.examSelected.courseID))
{
flp_result.Controls.Add(createFrameResult(i));
}
}
}
}
private void flp_result_Paint(object sender, PaintEventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label6_Click(object sender, EventArgs e)
{
}
private void bnSearch_Click(object sender, EventArgs e)
{
}
private void btnDo_Click(object sender, EventArgs e)
{
Random random = new Random();
try
{
List<TestDTO> lst = TestDAO.Instance.getListTestByExamID_courseID(UserDTO.Instance.examSelected.examID, UserDTO.Instance.examSelected.courseID);
string codeexam = lst[random.Next(0, lst.Count)].code;
FTest1 f = new FTest1(codeexam, UserDTO.Instance.examSelected.courseID, UserDTO.Instance.examSelected.examID, UserDTO.Instance.userID, false);
btnDo.Visible = false;
f.ShowDialog();
CheckStatusReview();
}
catch(Exception a)
{
MessageBox.Show(a.ToString());
}
}
Func<ChartPoint,string> labelPoint= chartpoint => string.Format("{0} ({1:P})", chartpoint.Y , chartpoint.Participation);
private void Analysis()
{
SeriesCollection series = new SeriesCollection();
string query = $"select MARKS, COUNT(*) AS C from sheet_answer where courseID='{UserDTO.Instance.examSelected.courseID}' and examID='{UserDTO.Instance.examSelected.examID}' GROUP BY Marks";
DataTable result = DataProvider.Instance.ExecuteQuery(query);
foreach (DataRow i in result.Rows)
{
series.Add(new PieSeries() {Title=i["Marks"].ToString().Trim(),Values=new ChartValues<int> { (int)i["c"]},DataLabels=true, LabelPoint=labelPoint });
}
pieChart1.Series = series;
}
private void btnAnalysis_Click(object sender, EventArgs e)
{
panel_analys.Visible = true;
Analysis();
chart1.Series.Clear();
chart1.Series.Add("Question");
string query = "procRateCorrectAnswer @examID , @courseID";
DataTable result = DataProvider.Instance.ExecuteQuery(query, new object[] { UserDTO.Instance.examSelected.examID, UserDTO.Instance.examSelected.courseID });
int count = 1;
foreach (DataRow i in result.Rows)
{
double t = double.Parse(i["Rate"].ToString());
t = Math.Floor(t * 100) / 100;
string question = "Q " + count.ToString();
chart1.Series["Question"].Points.AddXY(question ,t);
chart1.Series["Question"].YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
chart1.Series["Question"].IsValueShownAsLabel = true;
flpQuestion.Controls.Add(btnShowQuestion(i["questionID"].ToString().Trim(), "Question " + count.ToString()));
count++;
}
}
private Button btnShowQuestion(string questionID, string questionName)
{
Button button2 = new Button();
button2.BackColor = System.Drawing.Color.SkyBlue;
button2.FlatAppearance.BorderSize = 0;
button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
button2.Location = new System.Drawing.Point(3, 3);
button2.Size = new System.Drawing.Size(186, 39);
button2.TabIndex = 0;
button2.Text = questionName;
button2.Click += button2_Click;
button2.Tag = questionID;
return button2;
}
private void button2_Click(object sender, EventArgs e)
{
string questionID = (sender as Button).Tag as string;
FShowQuestion f = new FShowQuestion(questionID);
f.ShowDialog();
}
private void btnCLoseAnalys_Click(object sender, EventArgs e)
{
panel_analys.Visible = false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using MultiUserBlock.Common.Repository;
using MultiUserBlock.ViewModels;
namespace MultiUserBlock.Web.Controllers
{
public class AdminController : Controller
{
private readonly IUserRepository _userRepository;
public AdminController(IUserRepository UserRepository)
{
_userRepository = UserRepository;
}
[Authorize(Policy = "AdminPolicy")]
public async Task<IActionResult> Index()
{
var result = await _userRepository.GetAll();
result.Insert(0, new UserViewModel()
{
UserId = -1,
ShowName = "Neu...",
Roles = new int[] { -1 }
});
return View(new AdminViewModel()
{
Users = result
});
}
public async Task<AdminViewModel> SaveUser(UserViewModel user)
{
List<UserViewModel> result;
if (!ModelState.IsValid)
{
result = await _userRepository.GetAll();
result.Insert(0, new UserViewModel()
{
UserId = -1,
ShowName = "Neu...",
Roles = new int[] { -1 }
});
return new AdminViewModel()
{
Users = result,
Errors = GetModelStateErrors(ModelState)
};
}
await _userRepository.AddOrUpdate(user);
result = await _userRepository.GetAll();
result.Insert(0, new UserViewModel()
{
UserId = -1,
ShowName = "Neu...",
Roles = new int[] { -1 }
});
return new AdminViewModel()
{
Users = result,
};
}
public async Task<AdminViewModel> DelUser(UserViewModel user)
{
await _userRepository.Remove(user.UserId);
var result = await _userRepository.GetAll();
result.Insert(0, new UserViewModel()
{
UserId = -1,
ShowName = "Neu...",
Roles = new int[] { -1 }
});
return new AdminViewModel()
{
Users = result,
};
}
public IActionResult Error()
{
return View();
}
public List<string> GetModelStateErrors(ModelStateDictionary ModelState)
{
List<string> errorMessages = new List<string>();
var validationErrors = ModelState.Values.Select(x => x.Errors);
validationErrors.ToList().ForEach(ve =>
{
var errorStrings = ve.Select(x => x.ErrorMessage);
errorStrings.ToList().ForEach(em =>
{
errorMessages.Add(em);
});
});
return errorMessages;
}
}
}
//_logger.LogWarning("loulou");
//_logger.LogError("loulou");
//_logger.LogWarning(LoggingEvents.GET_ITEM, "Getting item {ID}", 1); |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MVC4.Sample.Common.Entities;
namespace MVC4.Sample.Common.ViewModels.Knockoutjs
{
public class RecursiveFolderViewModel
{
public List<RecursiveFolder> Folders { get; set; }
public RecursiveFolder Template { get; set; }
}
}
|
/***************************************************************
*
* add by OceanHo 2015/8/28 10:41:44
*
****************************************************************/
using AimaTeam.WebFormLightAPI.httpCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
namespace AimaTeam.WebFormLightAPI.httpUtility
{
/// <summary>
/// 定义一个工具类。包含基础的 HttpRequest辅助方法
/// </summary>
public sealed class RequestUtility
{
/// <summary>
/// 获取请求客户端的唯一标识符
/// </summary>
/// <param name="request">HttpRequest对象</param>
/// <returns></returns>
internal static string GetReqID(HttpRequest request)
{
return MD5Utility.Encrypt(
string.Concat(RequestUtility.GetSchemeHostAndPort(
request), RequestUtility.GetIP(request)), MD5Mode.Default);
}
/// <summary>
/// 获取请求客户端的IP地址(有可能获取到的是代理IP地址)
/// </summary>
/// <param name="request">HttpRequest对象</param>
/// <returns></returns>
internal static string GetIP(HttpRequest request)
{
return request.UserHostAddress;
}
/// <summary>
/// 获取请求客户端的方案名称(http/https)+://+主机名+:+端口+/
/// </summary>
/// <param name="request">HttpRequest对象</param>
/// <returns></returns>
public static string GetSchemeHostAndPort(HttpRequest request)
{
return request.Url.Scheme + "://" + request.Url.Host + ":" + request.Url.Port + "/";
}
}
}
|
/**
Copyright (c) 2020, Institut Curie, Institut Pasteur and CNRS
Thomas BLanc, Mohamed El Beheiry, Jean Baptiste Masson, Bassam Hajj and Clement Caporal
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software
must display the following acknowledgement:
This product includes software developed by the Institut Curie, Insitut Pasteur and CNRS.
4. Neither the name of the Institut Curie, Insitut Pasteur and CNRS nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Animations;
using VR_Interaction.Convex_Hull;
using VRTK;
using Data;
namespace VR_Interaction
{
public class PointSelectorConvexHull : MonoBehaviour
{
public CloudData cloud_data;
public MeshCollider m_collider;
//public ConvexHullCreator creator;
public Dictionary<int, Face> hullFaces;
public List<GameObject> hullPointList;
public List<Vector3> hullPositionList;
public bool parent_activated;
public bool threadON;
private PointSelectorConvexHullThread thread;
public HashSet<int> selectedPoints = new HashSet<int>();
//public Transform target;
public bool selectionNotDone;
// Start is called before the first frame update
void Start()
{
selectionNotDone = true;
parent_activated = false;
threadON = false;
}
private void OnTriggerEnter(Collider cloud_box)
{
if (cloud_box.tag == "PointCloud")
{
/**
if (!parent_activated)
{
GameObject container = new GameObject("container");
container.transform.position = this.transform.position;
container.transform.SetParent(cloud_box.transform,true);
gameObject.AddComponent<VRTK_TransformFollow>();
gameObject.GetComponent<VRTK_TransformFollow>().followsScale = false;
gameObject.GetComponent<VRTK_TransformFollow>().gameObjectToChange = this.gameObject;
gameObject.GetComponent<VRTK_TransformFollow>().gameObjectToFollow = container;
gameObject.GetComponent<VRTK_TransformFollow>().moment = VRTK_TransformFollow.FollowMoment.OnLateUpdate;
}
**/
cloud_data = cloud_box.transform.parent.GetComponentInChildren<CloudData>();
if (selectionNotDone)
{
findPointsInsideHull();
selectionNotDone = false;
}
}
}
/**
private void Update()
{
if (parent_activated)
{
//transform.LookAt(target.position);
Vector3 offsetVector = target.transform.position - this.transform.position ;
transform.rotation = target.rotation;
if ((transform.position - target.position).magnitude > 0.01f)
{
transform.position+=offsetVector;
}
}
}
**/
public void findPointsInsideHull()
{
if (cloud_data == null)
{
return;
}
/**
for (int i = 0; i<hullPositionList.Count;i++)
{
hullPositionList[i] = hullPointList[i].transform.position;
}
**/
Color[] colors = new Color[cloud_data.pointDataTable.Count];
Matrix4x4 local_to_world = cloud_data.transform.localToWorldMatrix;
Matrix4x4 world_to_local = cloud_data.transform.worldToLocalMatrix;
thread = new PointSelectorConvexHullThread();
thread.data = cloud_data;
thread.local_to_world = local_to_world;
thread.world_to_local = world_to_local;
thread.rotation = transform.rotation;
thread.colors = colors;
thread.hullFaces = hullFaces;
thread.hullPointList = hullPointList;
thread.hullPositionList = hullPositionList;
thread.StartThread();
threadON = true;
}
private void Update()
{
if (threadON)
{
if (thread.isRunning == false)
{
threadON = false;
//Mesh newmesh = cloud_data.gameObject.GetComponent<MeshFilter>().mesh;
//newmesh.colors = thread.colors;
selectedPoints = thread.pointSelectionList;
thread.StopThread();
CloudUpdater.instance.UpdatePointSelection();
//CloudSelector.instance.selectedPointList = thread.pointSelectionList;
//CloudSelector.instance.pointSelectionID = cloud_data.globalMetaData.cloud_id;
//cloud_data.gameObject.GetComponent<MeshFilter>().mesh = newmesh;
}
}
}
private void OnEnable()
{
//CloudUpdater.instance.ColorOverride(selectedPoints, false);
}
private void OnDisable()
{
//CloudUpdater.instance.ColorOverride(selectedPoints, true);
}
private void OnDestroy()
{
CloudUpdater.instance.UpdatePointSelection();
}
}
public class PointSelectorConvexHullThread : RunnableThread
{
public CloudData data;
public Dictionary<int, Face> hullFaces;
public List<GameObject> hullPointList;
public List<Vector3> hullPositionList;
public Matrix4x4 local_to_world;
public Matrix4x4 world_to_local;
public Quaternion rotation;
public Color[] colors;
public HashSet<int> pointSelectionList;
protected override void Run()
{
//int _inside = 0;
//int _outside = 0;
pointSelectionList = new HashSet<int>();
foreach (KeyValuePair<int, PointData> item in data.pointDataTable)
{
Vector3 pointWorldPosition = local_to_world.MultiplyPoint3x4(item.Value.normed_position);
bool outside = false;
foreach (KeyValuePair<int, Face> kvp in hullFaces)
{
Vector3 hullLocalPosition = world_to_local.MultiplyPoint3x4(hullPositionList[kvp.Value.Vertex0]);
float dist = Vector3.Dot(kvp.Value.normal, item.Value.normed_position - hullLocalPosition);
//float dist = Vector3.Dot(kvp.Value.normal, pointWorldPosition - (Quaternion.Inverse(rotation) * hullPositionList[kvp.Value.Vertex0] ));
//float dist = Vector3.Dot(kvp.Value.normal, pointWorldPosition - (Quaternion.Inverse(rotation) * hullPositionList[kvp.Value.Vertex0]));
if (dist >= 0f)
{
//Debug.Log(dist);
outside = true;
//colors[item.Key] = item.Value.color;
//_outside++;
break;
}
}
if (!outside)
{
//colors[item.Key] = Color.green;
//item.Value.color = Color.green;
pointSelectionList.Add(item.Key);
//_inside++;
}
}
//Debug.Log(_inside + " points inside");
//Debug.Log(_outside + " points outside");
isRunning = false;
}
}
} |
using MvcProjesi.Attributes;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace MvcProjesi.Data
{
public class Yorum : BaseClass
{
[Column("Yorum_Id")]
public override int Id { get; set; }
[Required(ErrorMessage = "Lütfen yorumun içeriğini giriniz.")]
[StringLength(50, ErrorMessage = "Yorumun içeriği 50 karakterden uzun olamaz.")]
public string Icerik { get; set; }
//[Column("Tarih")]
//public override DateTime OlusturmaTarih { get; set; } = DateTime.Now;
public virtual Makale Makale { get; set; }
public virtual Uye Uye { get; set; }
}
} |
using System;
using System.ComponentModel.DataAnnotations;
using com.Sconit.Entity.ACC;
namespace com.Sconit.Entity.ISS
{
[Serializable]
public partial class IssueDetail : EntityBase, IAuditable
{
#region O/R Mapping Properties
//[Display(Name = "Id", ResourceType = typeof(Resources.ISS.IssueDetail))]
public Int32 Id { get; set; }
[Display(Name = "IssueCode", ResourceType = typeof(Resources.ISS.IssueDetail))]
public string IssueCode { get; set; }
[Display(Name = "Sequence", ResourceType = typeof(Resources.ISS.IssueDetail))]
public Int32 Sequence { get; set; }
[Display(Name = "IssueLevel", ResourceType = typeof(Resources.ISS.IssueDetail))]
public string IssueLevel { get; set; }
[Display(Name = "IsSubmit", ResourceType = typeof(Resources.ISS.IssueDetail))]
public Boolean IsSubmit { get; set; }
[Display(Name = "IsInProcess", ResourceType = typeof(Resources.ISS.IssueDetail))]
public Boolean IsInProcess { get; set; }
[Display(Name = "IsDefault", ResourceType = typeof(Resources.ISS.IssueDetail))]
public Boolean IsDefault { get; set; }
[Display(Name = "IsEmail", ResourceType = typeof(Resources.ISS.IssueDetail))]
public Boolean IsEmail { get; set; }
[Display(Name = "IsSMS", ResourceType = typeof(Resources.ISS.IssueDetail))]
public Boolean IsSMS { get; set; }
[Display(Name = "Priority", ResourceType = typeof(Resources.ISS.IssueDetail))]
public Int16 Priority { get; set; }
//[Display(Name = "User", ResourceType = typeof(Resources.ISS.IssueDetail))]
public User User { get; set; }
[Display(Name = "Email", ResourceType = typeof(Resources.ISS.IssueDetail))]
public string Email { get; set; }
[Display(Name = "EmailStatus", ResourceType = typeof(Resources.ISS.IssueDetail))]
public com.Sconit.CodeMaster.SendStatus EmailStatus { get; set; }
[Display(Name = "EmailCount", ResourceType = typeof(Resources.ISS.IssueDetail))]
public Int32 EmailCount { get; set; }
[Display(Name = "MobilePhone", ResourceType = typeof(Resources.ISS.IssueDetail))]
public string MobilePhone { get; set; }
[Display(Name = "SMSStatus", ResourceType = typeof(Resources.ISS.IssueDetail))]
public com.Sconit.CodeMaster.SendStatus SMSStatus { get; set; }
[Display(Name = "SMSCount", ResourceType = typeof(Resources.ISS.IssueDetail))]
public Int32 SMSCount { get; set; }
[Display(Name = "IsActive", ResourceType = typeof(Resources.ISS.IssueDetail))]
public Boolean IsActive { get; set; }
public Int32 CreateUserId { get; set; }
[Display(Name = "Common_CreateUserName", ResourceType = typeof(Resources.SYS.Global))]
public string CreateUserName { get; set; }
[Display(Name = "Common_CreateDate", ResourceType = typeof(Resources.SYS.Global))]
public DateTime CreateDate { get; set; }
public Int32 LastModifyUserId { get; set; }
[Display(Name = "Common_LastModifyUserName", ResourceType = typeof(Resources.SYS.Global))]
public string LastModifyUserName { get; set; }
[Display(Name = "Common_LastModifyDate", ResourceType = typeof(Resources.SYS.Global))]
public DateTime LastModifyDate { get; set; }
public Int32? IssueTypeToUserDetailId { get; set; }
public Int32? IssueTypeToRoleDetailId { get; set; }
#endregion
public override int GetHashCode()
{
if (Id != 0)
{
return Id.GetHashCode();
}
else
{
return base.GetHashCode();
}
}
public override bool Equals(object obj)
{
IssueDetail another = obj as IssueDetail;
if (another == null)
{
return false;
}
else
{
return (this.Id == another.Id);
}
}
}
}
|
using System;
namespace FizzBuzzTest
{
class Utilities
{
public static int ReadNumericInput()
{
int input;
while (!Int32.TryParse(Console.ReadLine(), out input))
{
Console.WriteLine("Please Enter a valid integer");
}
return input;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Projekt_3_Schichten_Architektur
{
/// <summary>
/// Interaktionslogik für GUI.xaml
/// </summary>
public partial class GUI : Window
{
IFachkonzept IF;
public GUI(IFachkonzept _IF)
{
InitializeComponent();
this.IF = _IF;
this.Show();
FillAuthors();
}
private void lstAuthors_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (lstAuthors.SelectedItem != null)
{
FillBooks(IF.GetBuecher(((Autor)lstAuthors.SelectedItem).Autoren_id));
txtAuthorName.Text = ((Autor)lstAuthors.SelectedItem).Name;
txtAuthorID.Text = ((Autor)lstAuthors.SelectedItem).Autoren_id.ToString();
}
}
private void lstBooks_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (lstBooks.SelectedItem != null)
{
txtBookISBN.Text = ((Buch)lstBooks.SelectedItem).ISBN;
txtBookTitle.Text = ((Buch)lstBooks.SelectedItem).Titel;
}
}
private void btnAllBooks_Click(object sender, RoutedEventArgs e)
{
FillBooks(IF.GetBuecher());
EmptyFields();
}
private void btnAddAuthor_Click(object sender, RoutedEventArgs e)
{
string Name = txtAuthorName.Text;
IF.SpeichereAutor(Name);
FillAuthors();
if (lstAuthors.SelectedItem != null)
{
FillBooks(IF.GetBuecher(int.Parse(lstAuthors.SelectedValue.ToString())));
}
else
{
FillBooks(IF.GetBuecher());
}
EmptyFields();
}
private void btnSaveAuthor_Click(object sender, RoutedEventArgs e)
{
string Name = txtAuthorName.Text;
int ID = int.Parse(txtAuthorID.Text);
IF.AktualisiereAutor(ID, Name);
FillAuthors();
EmptyFields();
}
private void btnDeleteAuthor_Click(object sender, RoutedEventArgs e)
{
if (lstAuthors.SelectedItem != null)
{
int ID = int.Parse(lstAuthors.SelectedValue.ToString());
IF.LoescheAutor(ID);
FillAuthors();
FillBooks(IF.GetBuecher());
}
else
{
MessageBox.Show("Kein Autor ausgewählt.");
}
EmptyFields();
}
private void btnAddBook_Click(object sender, RoutedEventArgs e)
{
if (lstAuthors.SelectedItem != null)
{
int AuthorID = int.Parse(lstAuthors.SelectedValue.ToString());
string ISBN = txtBookISBN.Text;
string Titel = txtBookTitle.Text;
IF.SpeichereBuch(AuthorID, ISBN, Titel);
FillBooks(IF.GetBuecher(int.Parse(lstAuthors.SelectedValue.ToString())));
}
else
{
MessageBox.Show("Kein Autor ausgewählt.");
}
EmptyFields();
}
private void btnSaveBook_Click(object sender, RoutedEventArgs e)
{
string ISBN = ((Buch)lstBooks.SelectedItem).ISBN;
string Titel = txtBookTitle.Text;
IF.AktualisiereBuch(ISBN, Titel);
if (lstAuthors.SelectedItem != null)
{
FillBooks(IF.GetBuecher(int.Parse(lstAuthors.SelectedValue.ToString())));
}
else
{
FillBooks(IF.GetBuecher());
}
EmptyFields();
}
private void btnDeleteBook_Click(object sender, RoutedEventArgs e)
{
if (lstBooks.SelectedItem != null)
{
string ISBN = ((Buch)lstBooks.SelectedItem).ISBN;
IF.LoescheBuch(ISBN);
}
else
{
MessageBox.Show("Kein Buch ausgewählt.");
}
if (lstAuthors.SelectedItem != null)
{
FillBooks(IF.GetBuecher(int.Parse(lstAuthors.SelectedValue.ToString())));
}
else
{
FillBooks(IF.GetBuecher());
}
EmptyFields();
}
private void FillAuthors()
{
List<Autor> Autoren = IF.GetAutoren();
lstAuthors.ItemsSource = Autoren;
lstAuthors.DisplayMemberPath = "Name";
lstAuthors.SelectedValuePath = "Autoren_id";
}
private void FillBooks(List<Buch> Buecher)
{
lstBooks.ItemsSource = Buecher;
lstBooks.DisplayMemberPath = "Titel";
lstBooks.SelectedValuePath = "ISBN";
}
private void EmptyFields()
{
txtAuthorID.Text = "";
txtAuthorName.Text = "";
txtBookISBN.Text = "";
txtBookTitle.Text = "";
lstAuthors.SelectedItem = null;
}
}
}
|
using Client.Bussness;
using Client.Bussness.Biz;
using GalaSoft.MvvmLight.Command;
using MahApps.Metro.Controls.Dialogs;
using Meeting.NewClient.UI;
using System.Windows;
using WPF.NewClientl.UI.Dialogs;
namespace WPF.NewClientl.ViewModel.Dialogs
{
public class MeetingVoteViewModel : BaseGridViewModel<Meeting.Client.VoteInfo>
{
private FrameBussiness frameBussiness = new FrameBussiness();
private string _MeetingTopicTitle = string.Empty;
public string MeetingTopicTitle
{
get { return _MeetingTopicTitle; }
set { Set(ref _MeetingTopicTitle, value); }
}
#region ShowMeetingVoteItemsCommand
private RelayCommand<string> _showMeetingVoteItemsCommand;
public RelayCommand<string> ShowMeetingVoteItemsCommand
{
get
{
if (_showMeetingVoteItemsCommand == null)
_showMeetingVoteItemsCommand = new RelayCommand<string>(voteId =>
{
var voteItemDialog = new MeetingVoteItemDialog() { DataContext = new MeetingVoteItemViewModel(voteId) };
var customDialog = new CustomDialog() { Title = "投票" };
customDialog.Style = (Style)PageMainFrame.parent.Resources.MergedDictionaries[0]["PageCustomDialogStyle"];
customDialog.Content = voteItemDialog;
voteItemDialog.BaseMetroDialog = customDialog;
DialogManager.ShowMetroDialogAsync(PageMainFrame.parent, customDialog);
});
return _showMeetingVoteItemsCommand;
}
}
#endregion
public MeetingVoteViewModel( )
{
MeetingTopicTitle = string.Format("{0}投票", AppClientContext.Context.Meeting.Name);
var sourse = frameBussiness.GetMeetingVoteLists();
int index = 1;
sourse.ForEach(v => {
v.Index ="["+ index.ToString()+"]";
index++;
});
this.InitePage(sourse);
}
}
}
|
using System;
using Autofac;
using Tests.Pages.ActionID;
using Framework.Core.Common;
using NUnit.Framework;
using Tests.Data.Oberon;
using Tests.Pages.Oberon.Contact;
using Tests.Pages.Oberon.Disbursement;
namespace Tests.Projects.Oberon.Disbursements
{
public class DisbursementCreateWithRequiredFields : BaseTest
{
private Driver Driver { get {return Scope.Resolve<Driver>(); }}
private ActionIdLogIn ActionLogIn { get { return Scope.Resolve<ActionIdLogIn>(); } }
/// <summary>
/// Test the creation of a disbursement with all fields
/// </summary>
[Test]
[Category("oberon"), Category("oberon_smoketest"), Category("oberon_disbursements"), Category("oberon_PRODUCTION")]
public void DisbursementCreateWithRequiredFieldsTest()
{
ActionLogIn.LogInTenant();
// Create a contact
var testContact = Scope.Resolve<TestContact>();
var createPage = Scope.Resolve<ContactCreate>();
testContact.Id = createPage.CreateContact(testContact);
// set disbursement
var detailPage = Scope.Resolve<ContactDetail>();
var testDisbursement = new TestDisbursement { Amount = "10" };
testDisbursement.Id = detailPage.AddNewDisbursement(testDisbursement);
// verify contribution amount on detail page
var disburmentDetail = Scope.Resolve<DisbursementDetail>();
//_driver.WaitForElementPresent(disburmentDetail.Amount);
Assert.IsTrue(disburmentDetail.Amount.Text.Contains(testDisbursement.Amount));
}
}
}
|
using Core.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Core.Interfaces
{
public interface IProductRepository
{
//return task of type product
//can await this method because we used async
Task<Product> GetProductByIdAsync(int id);
//product type object is returned
//IReadOnly gives read only access
Task<IReadOnlyList<Product>> GetProductAsync();
Task<IReadOnlyList<ProductBrand>> GetProductBrandsAsync();
Task<IReadOnlyList<ProductType>> GetProductTypesAsync();
}
}
|
using Allyn.Domain.Models.Basic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
namespace Allyn.Infrastructure.EfRepositories.ModelConfigurations
{
internal class UserRoleTypeConfiguration : EntityTypeConfiguration<UserRole>
{
/// <summary>
/// 用于"用户角色"领域概念模型和数据库映射配置.
/// </summary>
internal UserRoleTypeConfiguration() {
ToTable("BUserRole");
HasKey(k => k.Id)
.Property(p => p.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(p => p.UserKey)
.IsRequired();
Property(p => p.RoleKey)
.IsRequired();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Strategy.Calculator;
using Strategy.Cars;
namespace Strategy
{
class Program
{
static void Main(string[] args)
{
CalculeteType operation = CalculeteType.Addition;
CalculatorContext calContext = null;
int number1 = 34;
int number2 = 16;
switch (operation)
{
case CalculeteType.Addition:
calContext = new CalculatorContext(new AdditionCalc());
break;
case CalculeteType.Substraction:
calContext = new CalculatorContext(new SubstractionCalc());
break;
case CalculeteType.Multiplication:
calContext = new CalculatorContext(new MultiplicationCalc());
break;
case CalculeteType.Division:
calContext = new CalculatorContext(new DivisionCalc());
break;
}
Console.WriteLine("Suma liczb: {0}", calContext.Calculate(number1, number2));
CarModel carModel = CarModel.Lamborgini;
CarContext carContext = null;
switch (carModel)
{
case CarModel.Porsche:
carContext = new CarContext(new PorscheCar());
break;
case CarModel.Ferrari:
carContext = new CarContext(new FerrariCar());
break;
case CarModel.Lamborgini:
carContext = new CarContext(new LamborginiCar());
break;
}
carContext.ShowMaxSpeed();
}
}
}
|
/* 作者: 盛世海
* 创建时间: 2012/7/20 17:08:04
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MODEL;
using Newtonsoft.Json;
using System.Web;
namespace MODEL.ViewModel
{
/// <summary>
/// 按钮数据类
/// </summary>
public class MyButton
{
/// <summary>
/// 按钮ID
/// </summary>
public string BtnNo { get; set; }
/// <summary>
/// 按钮功能名称
/// </summary>
public string BtnName { get; set; }
/// <summary>
/// 按钮图标地址
/// </summary>
public string BtnIcon { get; set; }
/// <summary>
/// 点击事件(暂时停用)
/// </summary>
public string BtnClick { get; set; }
/// <summary>
/// 菜单标识
/// </summary>
public string MenuNo { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this, Formatting.Indented,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, });
}
/// <summary>
/// 转化为按钮实体
/// </summary>
/// <param name="menu"></param>
public static MyButton ToEntity(FW_PERMISSION menu)
{
MyButton item = new MyButton();
item.BtnNo = menu.ACTIONNAME;
item.BtnName = menu.NAME;
item.BtnIcon = menu.ICON;
item.BtnClick = menu.SCRIPT;
return item;
}
}
}
|
using BlueSky.Commands;
using BlueSky.Commands.File;
using BlueSky.Commands.Output;
using BlueSky.Services;
using BSky.ConfigService.Services;
using BSky.ConfService.Intf.Interfaces;
using BSky.Controls;
using BSky.Controls.Controls;
using BSky.DynamicClassCreator;
using BSky.Interfaces.Commands;
using BSky.Interfaces.Interfaces;
using BSky.Interfaces.Services;
using BSky.Lifetime;
using BSky.Lifetime.Interfaces;
using BSky.OutputGenerator;
using BSky.Statistics.Common;
using BSky.Statistics.Service.Engine.Interfaces;
using C1.WPF.FlexGrid;
using Microsoft.Win32;
using RDotNet;
using ScintillaNET;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Xml;
namespace BlueSky
{
public enum RCommandType { RCOMMAND, CONDITIONORLOOP, BSKYFORMAT, BSKYLOADREFRESHDATAFRAME, BSKYREMOVEREFRESHDATAFRAME, GRAPHIC, GRAPHICXML, SPLIT, REFRESHGRID, RDOTNET }
/// <summary>
/// Interaction logic for SyntaxEditorWindow.xaml
/// </summary>
public partial class SyntaxEditorWindow : Window
{
IAnalyticsService analytics = LifetimeService.Instance.Container.Resolve<IAnalyticsService>();
IConfigService confService = LifetimeService.Instance.Container.Resolve<IConfigService>();//23nov2012
ILoggerService logService = LifetimeService.Instance.Container.Resolve<ILoggerService>();//13Dec2012
bool AdvancedLogging;
CommandRequest sinkcmd = new CommandRequest();
C1.WPF.FlexGrid.FileFormat fileformat = C1.WPF.FlexGrid.FileFormat.Html;
bool extratags = true; // true means default file type will be .BSO
string fullfilepathname = string.Empty;
Dictionary<string, ImageDimensions> registeredGraphicsList = new Dictionary<string, ImageDimensions>();//28May2015
OutputMenuHandler omh = new OutputMenuHandler();//Output menu
bool SEForceClose = false;//05Feb2013
bool Modified = false; //19Feb2013 to track if any modification has been done after last save
bool bsky_no_row_header; //14Jul2014 for supressing the default rowheaders "1","2","3"
long EMPTYIMAGESIZE = 318;// bytes
int _currentGraphicWidth = 600;//current width of the image
int _currentGraphicHeight = 600;//current height of the image
string doubleClickedFilename;//17May2013
public string DoubleClickedFilename
{
get;
set;
}
BSkyDialogProperties DlgProp; // for storing dialog properties.
FrameworkElement felement;
public FrameworkElement FElement //for some commands it is important to set this property
{
get { return felement; }
set { felement = value; }
}
object menuParameter;
public object MenuParameter
{
get { return menuParameter; }
set { menuParameter = value; }
}
//15Nov2013 for storing all commands those got executed when RUN button was cliced once
SessionOutput sessionlst;
OutputWindow ow;
//07Nov2014 To Get SessionList items count at any point.
public int SesssionListItemCount
{
get { return sessionlst.Count; }
}
#region Scintilla Textbox
private List<string> Keywords1 = null;
private List<string> Keywords2 = null;
private string AutoCompleteKeywords = null;
Scintilla inputTextbox = null;
private void ConfigureScintilla()
{
PrepareKeywords();
ConfigureRScriptSyntaxHighlight();
ConfigureRScriptAutoFolding();
ConifugreRScriptAutoComplete();
inputTextbox.Margins[0].Width = 16;
}
#region Scintilla Configuration Methods
private void PrepareKeywords()
{
Keywords1 = @"commandArgs detach length dev.off stop lm library predict lmer
plot print display anova read.table read.csv complete.cases dim attach as.numeric seq max
min data.frame lines curve as.integer levels nlevels ceiling sqrt ranef order
AIC summary str head png tryCatch par mfrow interaction.plot qqnorm qqline".Split(new char[] { ' ', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries).ToList();
Keywords2 = @"TRUE FALSE if else for while in break continue function".Split(new char[] { ' ', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries).ToList();
List<string> keywords = Keywords1.ToList();
keywords.AddRange(Keywords2);
keywords.Sort();
AutoCompleteKeywords = string.Join(" ", keywords);
}
private void ConfigureRScriptSyntaxHighlight()
{
//StyleCollection
inputTextbox.StyleResetDefault();
inputTextbox.Styles[ScintillaNET.Style.Default].Font = "Consolas";
inputTextbox.Styles[ScintillaNET.Style.Default].Size = 10;
inputTextbox.StyleClearAll();
inputTextbox.Styles[ScintillaNET.Style.R.Default].ForeColor = System.Drawing.Color.Brown;
inputTextbox.Styles[ScintillaNET.Style.R.Comment].ForeColor = System.Drawing.Color.FromArgb(0, 128, 0); // Green
inputTextbox.Styles[ScintillaNET.Style.R.Number].ForeColor = System.Drawing.Color.Olive;
inputTextbox.Styles[ScintillaNET.Style.R.BaseKWord].ForeColor = System.Drawing.Color.Purple;
inputTextbox.Styles[ScintillaNET.Style.R.Identifier].ForeColor = System.Drawing.Color.Black;
inputTextbox.Styles[ScintillaNET.Style.R.String].ForeColor = System.Drawing.Color.FromArgb(163, 21, 21); // Red
inputTextbox.Styles[ScintillaNET.Style.R.KWord].ForeColor = System.Drawing.Color.Blue;
inputTextbox.Styles[ScintillaNET.Style.R.OtherKWord].ForeColor = System.Drawing.Color.Blue;
inputTextbox.Styles[ScintillaNET.Style.R.String2].ForeColor = System.Drawing.Color.OrangeRed;
inputTextbox.Styles[ScintillaNET.Style.R.Operator].ForeColor = System.Drawing.Color.Purple;
inputTextbox.Lexer = Lexer.R;
inputTextbox.SetKeywords(0, string.Join(" ", Keywords1));
inputTextbox.SetKeywords(1, string.Join(" ", Keywords2));
}
private void ConifugreRScriptAutoComplete()
{
inputTextbox.CharAdded += scintilla_CharAdded;
}
private void scintilla_CharAdded(object sender, CharAddedEventArgs e)
{
Scintilla scintilla = inputTextbox;
// Find the word start
var currentPos = scintilla.CurrentPosition;
var wordStartPos = scintilla.WordStartPosition(currentPos, true);
// Display the autocompletion list
var lenEntered = currentPos - wordStartPos;
if (lenEntered > 0)
{
scintilla.AutoCShow(lenEntered, AutoCompleteKeywords);
}
}
private void ConfigureRScriptAutoFolding()
{
Scintilla scintilla = inputTextbox;
//Instruct the lexer to calculate folding
scintilla.SetProperty("fold", "1");
scintilla.SetProperty("fold.compact", "1");
//Configure a margin to display folding symbols
scintilla.Margins[2].Type = MarginType.Symbol;
scintilla.Margins[2].Mask = Marker.MaskFolders;
scintilla.Margins[2].Sensitive = true;
scintilla.Margins[2].Width = 20;
//Set colors for all folding markers
for (int i = 25; i <= 31; i++)
{
scintilla.Markers[i].SetForeColor(System.Drawing.SystemColors.ControlLightLight);
scintilla.Markers[i].SetBackColor(System.Drawing.SystemColors.ControlDark);
}
//Configure folding markers with respective symbols
scintilla.Markers[Marker.Folder].Symbol = MarkerSymbol.BoxPlus;
scintilla.Markers[Marker.FolderOpen].Symbol = MarkerSymbol.BoxMinus;
scintilla.Markers[Marker.FolderEnd].Symbol = MarkerSymbol.BoxPlusConnected;
scintilla.Markers[Marker.FolderMidTail].Symbol = MarkerSymbol.TCorner;
scintilla.Markers[Marker.FolderOpenMid].Symbol = MarkerSymbol.BoxMinusConnected;
scintilla.Markers[Marker.FolderSub].Symbol = MarkerSymbol.VLine;
scintilla.Markers[Marker.FolderTail].Symbol = MarkerSymbol.LCorner;
// Enable automatic folding
scintilla.AutomaticFold = (AutomaticFold.Show | AutomaticFold.Click | AutomaticFold.Change);
}
#endregion
#endregion
public SyntaxEditorWindow()
{
InitializeComponent();
inputTextbox = windowsFormsHost1.Child as Scintilla;
inputTextbox.Text = "";
ConfigureScintilla();
this.MinWidth = 440;// 384;
this.MinHeight = 200;
this.Width = 750;// 976;
this.Height = 550;
this.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
SMenu.Items.Add(omh.OutputMenu);///Add Output menu ///
inputTextbox.Focus();//set focus inside text box.
//opening Graphics device with sytax Editor. //05May2013
OpenGraphicsDevice();
sessionlst = new SessionOutput();
}
//05Feb2013 For controlling forcefull close of Syn Edt.
public bool SynEdtForceClose
{
get { return SEForceClose; }
set { SEForceClose = value; }
}
private void runButton_Click(object sender, RoutedEventArgs e)
{
/////Selected or all commands from textbox////30Apr2013
string commands = inputTextbox.SelectedText;//selected text
if (commands != null && commands.Length > 0)
{
//MessageBox.Show(seltext);
}
else
{
commands = inputTextbox.Text;//All text
//MessageBox.Show(seltext);
}
if (commands.Trim().Length > 0)
{
RunCommands(commands);
DisplayAllSessionOutput();//22Nov2013
}
}
public void RunCommands(string commands, BSkyDialogProperties dlgprop = null, string fname="") //30Apr2013
{
try
{
AdvancedLogging = AdvancedLoggingService.AdvLog;//01May2015
logService.WriteToLogLevel("Adv Log Flag:" + AdvancedLogging.ToString(), LogLevelEnum.Info);
DlgProp = dlgprop;
#region Load registered graphic commands from GraphicCommandList.txt 18Sep2012
// loads each time run is clicked. Performance will be effected.
string grplstfullfilepath = string.Format(@"{0}GraphicCommandList.txt", BSkyAppData.RoamingUserBSkyConfigPath);
//if graphic file does not exist the n create one.
if (!IsValidFullPathFilename(grplstfullfilepath, true))//17Jan2014
{
string text = "plot";
System.IO.File.WriteAllText(@grplstfullfilepath, text);
}
// load default value if no path is set or invalid path is set
if (grplstfullfilepath.Trim().Length == 0 || !IsValidFullPathFilename(grplstfullfilepath, true))
{
MessageBox.Show(this, BSky.GlobalResources.Properties.Resources.sinkregstrdgrphConfigKeyNotFound);
}
else
{
LoadRegisteredGraphicsCommands(@grplstfullfilepath);
}
#endregion
#region Save to Disk
if (saveoutput.IsChecked == true)
{
if (fullpathfilename.Text != null && fullpathfilename.Text.Trim().Length > 0)
{
fullfilepathname = fullpathfilename.Text;///setting filename
bool fileExists = File.Exists(fullfilepathname); fileExists = false;
if (fullfilepathname.Contains('.') && !fileExists)
{
string extension = Path.GetExtension(fullfilepathname).ToLower();
if (extension.Equals(".csv"))
{ fileformat = C1.WPF.FlexGrid.FileFormat.Csv; extratags = false; }
else if (extension.Equals(".html"))
{ fileformat = C1.WPF.FlexGrid.FileFormat.Html; extratags = false; }
else if (extension.Equals(".bsoz"))
{ fileformat = C1.WPF.FlexGrid.FileFormat.Html; extratags = true; }
else
{ fileformat = C1.WPF.FlexGrid.FileFormat.Html; extratags = true; fullfilepathname = fullfilepathname + ".bsoz"; }
}
else
{
MessageBox.Show(this, "Output File Already Exists! Provide different name in Command Editor window.");
return;
}
}
else
{
MessageBox.Show(this, "Please provide new output filename and fileformat by clicking 'Browse' in Command Editor for saving the output.", "Save Output is checked...", MessageBoxButton.OK, MessageBoxImage.Asterisk);
return;
}
}
#endregion
#region Get Active output Window
//////// Active output window ///////
OutputWindowContainer owc = (LifetimeService.Instance.Container.Resolve<IOutputWindowContainer>()) as OutputWindowContainer;
ow = owc.ActiveOutputWindow as OutputWindow; //get currently active window
if (saveoutput.IsChecked == true)
{
ow.ToDiskFile = true;//save lst to disk. Dump
}
#endregion
#region Executing Syntax Editors Commands
///// Now statements from Syntax Editor will be executed ////
CommandOutput lst = new CommandOutput(); ////one analysis////////
lst.IsFromSyntaxEditor = true;
if (saveoutput.IsChecked == true)//10Jan2013
lst.SelectedForDump = true;
////17Nov2017 for opening a flat file that has ; as a field separator. this field separator is not for line termination in R syntax.
commands = commands.Replace("\";\"", "'BSkySemiColon'").Replace("';'", "'BSkySemiColon'");
////03Oct2014 We should remove R comments right here, before proceeding with execution.
string nocommentscommands = RemoveCommentsFromCommands(commands);
ExecuteCommandsAndCreateSinkFile(ow, lst, nocommentscommands, fname);
bool s = true;
if (s) CreateOuput(ow); /// for last remaining few non BSkyFormat commands, if any.
///
#endregion
#region Saving to Disk
//////Dumping results from Syntax Editor ////08Aug2012
if (saveoutput.IsChecked == true)
ow.DumpAllAnalyisOuput(fullfilepathname, fileformat, extratags);
#endregion
}
catch (Exception ex)
{
SendCommandToOutput(BSky.GlobalResources.Properties.Resources.ErrExecutingCommand, BSky.GlobalResources.Properties.Resources.ErrInRCommand);
logService.WriteToLogLevel("Exeception:" + ex.Message, LogLevelEnum.Error);
//15Sep2015 Following may be needed to remove lock from sink file
ResetSink();
CloseSinkFile();
}
finally
{
BSkyMouseBusyHandler.HideMouseBusy(true);// true means forcing mousefree in just one call.
}
}
#region Mouse Busy - Mouse Free
Cursor defaultcursor;
private void ShowMouseBusy_old()
{
defaultcursor = Mouse.OverrideCursor;
Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
}
//Hides Progressbar
private void HideMouseBusy_old()
{
Mouse.OverrideCursor = null;
}
#endregion
//03Oct2014 Removing comments from the selection
private string RemoveCommentsFromCommands(string alltext)
{
StringBuilder final = new StringBuilder();
char[] splitchars = { '\r', '\n', ';' };
string[] lines = alltext.Split(splitchars);
int len = lines.Length;
for (int i = 0; i < len; i++)
{
if (lines[i] != null && lines[i].Length > 0)
final.AppendLine(RemoveComments(lines[i].Trim()));// +"\r\n";
}
return (final.ToString());
}
//Checks if number of different types of brakets have openbracket count == closebracket count.
private bool AreBracketsBalanced(string commands, out string msg)
{
bool balanced = true;
int roundbrackets = 0;
int curlybrackets = 0;
int squarebrackets = 0;
//loop thru char by char to find each type
foreach (char ch in commands)
{
if (ch == '(') roundbrackets++;
else if (ch == ')') roundbrackets--;
else if (ch == '{') curlybrackets++;
else if (ch == '}') curlybrackets--;
else if (ch == '[') squarebrackets++;
else if (ch == ']') squarebrackets--;
}
if (roundbrackets != 0 || curlybrackets != 0 || squarebrackets != 0)
balanced = false;
////Generating error message based on counts
string msg1 = string.Empty, msg2 = string.Empty, msg3 = string.Empty;
if (roundbrackets > 0)
{
msg1 = BSky.GlobalResources.Properties.Resources.missing + " ')'";
}
if (roundbrackets < 0)
{
msg1 = BSky.GlobalResources.Properties.Resources.unexpected + " ')' ";
}
if (curlybrackets > 0)
{
msg2 = BSky.GlobalResources.Properties.Resources.missing + " '}'";
}
if (curlybrackets < 0)
{
msg2 = BSky.GlobalResources.Properties.Resources.unexpected + " '}' ";
}
if (squarebrackets > 0)
{
msg3 = BSky.GlobalResources.Properties.Resources.missing + " ']'";
}
if (squarebrackets < 0)
{
msg3 = BSky.GlobalResources.Properties.Resources.unexpected + " ']' ";
}
msg = msg1 + " " + msg2 + " " + msg3;
return balanced;
}
//22Nov2013 for sending session contents to output window.
public void DisplayAllSessionOutput(string sessionheader = "", OutputWindow selectedOW = null)
{
sessionlst.NameOfSession = sessionheader;
sessionlst.isRSessionOutput = true;
if (sessionlst.Count > 0)//07Nov2014
{
if (selectedOW == null)
{
if (ow != null)
{
ow.AddSynEdtSessionOutput(sessionlst);
}
}
else
{
selectedOW.AddSynEdtSessionOutput(sessionlst);
}
}
//21Nov2013
sessionlst = new SessionOutput();//28Nov2013 for creating new instance and not deleting old one
}
//////////pull all the currently loaded datasets names //////////
private string getActiveDatasetNames()
{
string allDatasetnames = string.Empty;
UIControllerService layoutController = LifetimeService.Instance.Container.Resolve<IUIController>() as UIControllerService;
foreach (TabItem ti in (layoutController.DocGroup.Items))
{
if (allDatasetnames.Trim().Length < 1)
allDatasetnames = "[" + (ti.Tag as DataSource).Name + "] - " + (ti.Tag as DataSource).FileName;
else
allDatasetnames = allDatasetnames + "\n" + "[" + (ti.Tag as DataSource).Name + "] - " + (ti.Tag as DataSource).FileName;
}
return allDatasetnames;
}
/// Delete old existing imagexxx.png files just before launching graphic device (each time) ///06May2013
private void DeleteOldGraphicFiles()
{
string synedtimgname = confService.GetConfigValueForKey("sinkimage");//23nov2012
string tempDir = BSkyAppData.RoamingUserBSkyTempPath;
string synedtimg = Path.Combine(tempDir, synedtimgname);
int percentindex = synedtimg.IndexOf("%");
int dindex = synedtimg.IndexOf("d", percentindex);
string percentstr = synedtimg.Substring(percentindex, (dindex - percentindex + 1));
string tempsynedtimg = Path.GetFileName(synedtimg).Replace(percentstr, "*");
//Delete all image Files in temp Folder ///
foreach (FileInfo fi in new DirectoryInfo(tempDir).GetFiles(tempsynedtimg))
{
DeleteFileIfPossible(@fi.FullName);
}
}
int GraphicDeviceImageCounter = 0;//to keep track of the next image file name.
private void OpenGraphicsDevice(int imagewidth = 0, int imageheight = 0)//05May2013
{
DeleteOldGraphicFiles();//06May2013
CommandRequest grpcmd = new CommandRequest();
string synedtimgname = confService.GetConfigValueForKey("sinkimage");//23nov2012
string synedtimg = Path.Combine(BSkyAppData.RoamingUserBSkyTempPath, synedtimgname);
// load default value if no path is set or invalid path is set
if (synedtimg.Trim().Length == 0 || !IsValidFullPathFilename(synedtimg, false))
{
MessageBox.Show(this, BSky.GlobalResources.Properties.Resources.sinkimageConfigKeyNotFound);
return;
}
//27May2015. if parameters are passed, parameter values will take over ( overrides the values set through 'Options'
if (imageheight > 0 && imagewidth > 0)
{
_currentGraphicWidth = imagewidth;
_currentGraphicHeight = imageheight;
}
else // use dimenstions set in 'Options' config. IF thats absent then use 580 as default.
{
_currentGraphicWidth = 580;
_currentGraphicHeight = 580;//defaults
//get image size from config
string imgwidth = confService.GetConfigValueForKey("imagewidth");//
string imgheight = confService.GetConfigValueForKey("imageheight");//
// load default value if no value is set or invalid value is set
if (imgwidth.Trim().Length != 0)
{
Int32.TryParse(imgwidth, out _currentGraphicWidth);
}
if (imgheight.Trim().Length != 0)
{
Int32.TryParse(imgheight, out _currentGraphicHeight);
}
}
////Actually image height and width should be same(assumed).
grpcmd.CommandSyntax = "png(\"" + synedtimg + "\", width=" + _currentGraphicWidth + ",height=" + _currentGraphicHeight + ")";
analytics.ExecuteR(grpcmd, false, false);
//close graphic device to get the size of empty image.
CloseGraphicsDevice();
// Basically, make sure to find the exact first image name(with full path) that is created when graphic device is opened.
string tempimgname = synedtimg.Replace("%03d", "001");
if (File.Exists(tempimgname))
{
EMPTYIMAGESIZE = new FileInfo(tempimgname).Length;
}
EMPTYIMAGESIZE = EMPTYIMAGESIZE + 10;
//Now finally open graphic device to actually wait for graphic command to execute and capture it.
grpcmd.CommandSyntax = "png(\"" + synedtimg + "\", width=" + _currentGraphicWidth + ",height=" + _currentGraphicHeight + ")";
analytics.ExecuteR(grpcmd, false, false);
GraphicDeviceImageCounter = 0;//09Jun2015
}
//Closes current graphics device
private void CloseGraphicsDevice()
{
CommandRequest grpcmd = new CommandRequest();
grpcmd.CommandSyntax = "if(dev.cur()[[1]] == 2) dev.off()";//09Jun2015 "dev.off()"; // "graphic.off()"; //msg <-
analytics.ExecuteR(grpcmd, false, false);
}
//check file size of PNG file generated by R
private long GetGraphicSize()//05May2013
{
long size = 0;
CommandRequest grpcmd = new CommandRequest();
string synedtimgname = confService.GetConfigValueForKey("sinkimage");//23nov2012
string synedtimg = Path.Combine(BSkyAppData.RoamingUserBSkyTempPath, synedtimgname);
// load default value if no path is set or invalid path is set
if (synedtimg.Trim().Length == 0 || !IsValidFullPathFilename(synedtimg, false))
{
MessageBox.Show(this, BSky.GlobalResources.Properties.Resources.sinkimageConfigKeyNotFound);
return 0;
}
if (File.Exists(synedtimg))
{
size = new FileInfo(synedtimg).Length;
}
return size;
}
//if in config window the image size has been altered,
//we must close graphic device and open it again with new dimentions from config
public void RefreshImgSizeForGraphicDevice()
{
int newwidth = 10;
int newheight = 10;
//get image size from config
string imgwidth = confService.GetConfigValueForKey("imagewidth");//
string imgheight = confService.GetConfigValueForKey("imageheight");//
// load default value if no value is set or invalid value is set
if (imgwidth.Trim().Length != 0)
{
Int32.TryParse(imgwidth, out newwidth);
}
if (imgheight.Trim().Length != 0)
{
Int32.TryParse(imgheight, out newheight);
}
if (_currentGraphicWidth != newwidth || _currentGraphicHeight != newheight) // if config setting modified
{
CloseGraphicsDevice();
OpenGraphicsDevice();
}
}
//18Nov2013 Add BSky OSMT and CrossTab to Session. This output is return back from OutputWindow
public void AddToSession(CommandOutput co)
{
if (co != null && co.Count > 0)
{
sessionlst.Add(co);
co = new CommandOutput();//after adding to session new object is allocated for futher output creation
}
}
private void ExecuteCommandsAndCreateSinkFile(OutputWindow ow, CommandOutput lst, string seltext, string fname)//sending message and output to sink file
{
string objectname;
seltext = seltext.Replace('\n', ';').Replace('\r', ' ').Trim();
seltext = JoinCommaSeparatedStatment(seltext);
string stmt = "";
//////wrap in sink////////
string sinkfilename = confService.GetConfigValueForKey("tempsink");//23nov2012
string sinkfilefullpathname = Path.Combine(BSkyAppData.RoamingUserBSkyTempPath, sinkfilename);
// load default value if no path is set or invalid path is set
if (sinkfilefullpathname.Trim().Length == 0 || !IsValidFullPathFilename(sinkfilefullpathname, false))
{
MessageBox.Show(this, BSky.GlobalResources.Properties.Resources.tempsinkConfigKeyNotFound);
return;
}
OpenSinkFile(@sinkfilefullpathname, "wt");
SetSink();
string stm = string.Empty;
string _command = string.Empty;//05May2013
int bskyfrmtobjcount = 0, next = 0, strt = 0, eol = 0;
bool breakfor = false;
for (int start = 0, end = 0; start < seltext.Length; start = start + end + 1) //28Jan2013 final condition was start < seltext.Length-1
{
objectname = "";
end = seltext.IndexOf(';', start) - start;
if (end < 0) // if ; not found
end = seltext.IndexOf('\n', start) - start;
if (end < 0)// if new line not found
end = seltext.Length - start;
stmt = seltext.Substring(start, end).Replace('\n', ' ').Replace('\r', ' ').Trim();
stmt = HasFilePath(stmt);
if (stmt.Trim().Length < 1 || stmt.Trim().IndexOf('#') == 0)
continue;
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Syntax going to execute : " + stmt, LogLevelEnum.Info);
if (stmt.Trim().IndexOf('#') > 1) //12May2014 if any statment has R comments in the end in same line.
stmt = stmt.Substring(0, stmt.IndexOf("#"));
object o = null;
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Categorizing command before execution.", LogLevelEnum.Info);
_command = ExtractCommandName(stmt);//07sep2012
RCommandType rct = GetRCommandType(_command);
//17Nov2017 Putting back the semicolon in place of BSkySemiColon
stmt = stmt.Replace("'BSkySemiColon'", "';'");
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Syntax command category : " + rct.ToString(), LogLevelEnum.Info);
try
{
switch (rct)
{
case RCommandType.CONDITIONORLOOP: //Block Commands
int end2 = end;
stmt = CurlyBracketParser(seltext, start, ref end);
if (stmt.Equals("ERROR"))
{
breakfor = true;
}
else
{
SendCommandToOutput(stmt, "R-Command");
ExecuteOtherCommand(ow, stmt);
}
//02Dec2014
ResetSink();
CloseSinkFile();
CreateOuput(ow);
OpenSinkFile(@sinkfilefullpathname, "wt");
SetSink();
///02Dec2015 Now add graphic (all of them, from temp location)
CreateAllGraphicOutput(ow);//get all grphics and send to output
break;
case RCommandType.GRAPHIC:
CommandRequest grpcmd = new CommandRequest();
grpcmd.CommandSyntax = "write(\"" + stmt.Replace("<", "<").Replace('"', '\'') + "\",fp)";// http://www.w3schools.com/xml/xml_syntax.asp
o = analytics.ExecuteR(grpcmd, false, false); //for printing command in file
CloseGraphicsDevice();
ResetSink();
CloseSinkFile();
CreateOuput(ow);
OpenSinkFile(@sinkfilefullpathname, "wt");
SetSink();
OpenGraphicsDevice();//05May2013
break;
case RCommandType.GRAPHICXML:
ExecuteXMLTemplateDefinedCommands(stmt);
break;
case RCommandType.BSKYFORMAT:
ResetSink();
CloseSinkFile();
CreateOuput(ow);
SendCommandToOutput(stmt, "BSkyFormat");//26Aug2014 blue colored
ExecuteBSkyFormatCommand(stmt, ref bskyfrmtobjcount, ow);
OpenSinkFile(@sinkfilefullpathname, "wt");
SetSink();
break;
case RCommandType.BSKYLOADREFRESHDATAFRAME:
ResetSink();
CloseSinkFile();
CreateOuput(ow);
SendCommandToOutput(stmt, "Load-Refresh Dataframe");//26Aug2014 blue colored
bool success = ExecuteBSkyLoadRefreshDataframe(stmt, fname);
if (!success)
{
SendErrorToOutput(BSky.GlobalResources.Properties.Resources.ErrCantLodRefDataset, ow); //03Jul2013
SendErrorToOutput(BSky.GlobalResources.Properties.Resources.DFNotExists, ow); //03Jul2013
SendErrorToOutput(BSky.GlobalResources.Properties.Resources.NotDataframe, ow); //03Jul2013
SendErrorToOutput(BSky.GlobalResources.Properties.Resources.ReqRPkgMissing, ow); //03Jul2013
}
OpenSinkFile(@sinkfilefullpathname, "wt");
SetSink();
break;
case RCommandType.BSKYREMOVEREFRESHDATAFRAME:
ResetSink();
CloseSinkFile();
CreateOuput(ow);
ExecuteBSkyRemoveRefreshDataframe(stmt);
OpenSinkFile(@sinkfilefullpathname, "wt");
SetSink();
break;
case RCommandType.SPLIT:
ResetSink();
CloseSinkFile();
CreateOuput(ow);
ExecuteSplit(stmt);
OpenSinkFile(@sinkfilefullpathname, "wt");
SetSink();
break;
case RCommandType.RCOMMAND:
SendCommandToOutput(stmt, "R-Command");
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Categorized. Before execution.", LogLevelEnum.Info);
ExecuteOtherCommand(ow, stmt);
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Categorized. After execution.", LogLevelEnum.Info);
ResetSink();
CloseSinkFile();
CreateOuput(ow);
OpenSinkFile(@sinkfilefullpathname, "wt");
SetSink();
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Categorized. Before getting graphic if any.", LogLevelEnum.Info);
///02Dec2015 Now add graphic (all of them, from temp location)
CreateAllGraphicOutput(ow);//get all grphics and send to output
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Categorized. After getting graphic if any.", LogLevelEnum.Info);
break;
case RCommandType.RDOTNET:
InitializeRDotNet();
RDotNetOpenDataset();
RDotNetExecute(ow);
DisposeRDotNet();
break;
default:
break;
}//switch
}
catch (Exception exc)
{
SendCommandToOutput(exc.Message, "Error:");
logService.WriteToLogLevel("Error executing: " + _command, LogLevelEnum.Error);
logService.WriteToLogLevel(exc.Message, LogLevelEnum.Error);
}
if (breakfor)
break;
}/////for
//////wrap in sink////////
ResetSink();
CloseSinkFile();
}
private bool AreBalanced(string stmt)
{
bool isBalanced = true;
int stmtlen = stmt.Length;
int parencount = 0, curlycount = 0;
for (int i = 0; i < stmtlen; i++)
{
switch (stmt[i])
{
case '(':
parencount++;
break;
case ')':
if (parencount > 0) //this helps to verify if brackets appeared in right order or not eg.. )(
parencount--;
break;
case '{':
curlycount++;
break;
case '}':
if (curlycount > 0) //this helps to verify if brackets appeared in right order or not eg.. }{
curlycount--;
break;
default:
break;
}
}
if (parencount != 0 || curlycount != 0)
return false;
else
return true;
}
private string RemoveSemicolonAfterBrackets(string stmt)
{
StringBuilder resultstr = new StringBuilder();
bool beginwatch = false;
for (int i = 0; i < stmt.Length; i++)
{
if (stmt[i] == '(' || stmt[i] == '{')
{
beginwatch = true;
}
else if (stmt[i] != ' ' && stmt[i] != ';')
{
beginwatch = false;
}
if (beginwatch && stmt[i] == ';')
{
resultstr.Append(' ');
}
else
{
resultstr.Append(stmt[i]);
}
}
return resultstr.ToString();
}
private string RemoveSemicolonBetweenBrackets(String stmt)
{
StringBuilder sb = new StringBuilder();
return sb.ToString();
}
//13Nov2013
private RCommandType GetRCommandType(string _command)
{
RCommandType rct;
if (isConditionalOrLoopingCommand(_command))
rct = RCommandType.CONDITIONORLOOP;
else if (isGraphicCommand(_command))
{
if (isXMLDefined())
{
rct = RCommandType.GRAPHICXML;
}
else
{
rct = RCommandType.RCOMMAND; //
}
}
else if (_command.Contains("BSkyFormat("))
rct = RCommandType.BSKYFORMAT;
else if (_command.Contains("BSkyLoadRefreshDataframe("))
rct = RCommandType.BSKYLOADREFRESHDATAFRAME;
else if (_command.Contains("BSkyRemoveRefreshDataframe("))
rct = RCommandType.BSKYREMOVEREFRESHDATAFRAME;
else if (_command.Contains("BSkySetDataFrameSplit(")) //set or remove split
rct = RCommandType.SPLIT;
else if (_command.Contains("RDotNetTest"))
rct = RCommandType.RDOTNET;
else
rct = RCommandType.RCOMMAND;
return rct;
}
private string HasFilePath(string command)
{
//path string that begins and ends with single or double quote
string pat = @"[""']((\\\\[a-zA-Z0-9-]+\\[a-zA-Z0-9`~!@#$%^&(){}'._-]+([ ]+[a-zA-Z0-9`~!@#$%^&(){}'._-]+)*)|([a-zA-Z]:))(\\[^ \\/:*?""<>|]+([ ]+[^'\\/:*?""<>|]+)*)*\\?[""']";
bool found = false;
string strfound = string.Empty;
string resultstr = command; // if path not found then command should be returned as is
MatchCollection mcol = Regex.Matches(command, pat);
if (mcol.Count > 0)
{
found = true;
strfound = mcol[0].ToString();
string strreplace = strfound.Replace(@"\", @"/");
resultstr = Regex.Replace(command, pat, strreplace);
}
return resultstr;
}
/// Join the statments Ends in comma
private string JoinCommaSeparatedStatment(string comm)//, int start, ref int end)
{
comm = Regex.Replace(comm, @",\s*;", ",");
return comm;
}
////curly block parser////
private string CurlyBracketParser(string comm, int start, ref int end)
{
string str = string.Empty;
int curlyopen = 0, curlyclose = 0;
for (int i = comm.IndexOf('{', start); i < comm.Length; i++)
{
if (comm.ElementAt(i).Equals('{')) curlyopen++;
else if (comm.ElementAt(i).Equals('}')) curlyclose++;
if (curlyopen == curlyclose)
{
end = i + 1 - start;
//if(start < comm.Length)
str = comm.Substring(start, end).Replace("}}", "} }").Replace(";{", "{").Replace("{;", "{").Replace("}", ";} ");
start = i + 1;
break;
}
}
if (curlyopen != curlyclose)
{
//MessageBox.Show("Error in block declaration. Mismatch { or }");
CommandRequest cmdprn = new CommandRequest();
cmdprn.CommandSyntax = "write(\"" + BSky.GlobalResources.Properties.Resources.ErrCurlyMismatch + "\",fp)";
analytics.ExecuteR(cmdprn, false, false); /// for printing command in file
return "ERROR";
}
str = Regex.Replace(str, @";+", ";");//multi semicolon to one ( no space between them)
//str = Regex.Replace(str, @"}\s+;", "} ");//semicolon after close }
str = Regex.Replace(str, @";\s*;", ";");//multi semicolon to one(space between them)
str = Regex.Replace(str, @"}\s*;\s*}", "} }");//semicolon between two closing } }
str = Regex.Replace(str, @"{\s*;", "{ ");//semicolon immediatly after opening {
str = Regex.Replace(str, @";\s*{", "{ ");//semicolon immediatly after opening {
if (str.Contains("else"))
{
str = Regex.Replace(str, @"}\s*;*\s*else", "} else");//semicolon before for is needed. Fix for weird bug.
}
///if .. else if logic ///
if ((str.Trim().StartsWith("if") || str.Trim().StartsWith("else")) && comm.Length > end + 1)
{
string elsestr = string.Empty;
if (start + 1 < comm.Length)
elsestr = comm.Substring(start + 1);
int originalLen = elsestr.Length;
elsestr = Regex.Replace(elsestr, @";*\s*else", " else").Trim();
int newLen = elsestr.Length;
if (elsestr.StartsWith("else"))
{
int end2 = 0;
str = str + CurlyBracketParser(elsestr, 0, ref end2);
end = end + end2 + (originalLen - newLen + 1);
}
}
if (isRoundBracketBlock(str))
{
//search closing round bracket from original string and append to str. Update start
int idxclosinground = comm.IndexOf(")", start);
string closinground = comm.Substring(start, idxclosinground - start + 1).Replace(";", " ").Trim();
if (closinground.Equals(")"))
{
end = idxclosinground + 1;
}
return str + closinground;
}
return str;
}
private bool isRoundBracketBlock(string comm)
{
bool isroundblock = false;
string subs = string.Empty;
int roundbrktidx = comm.IndexOf("(");
int curlybrktidx = comm.IndexOf("{");
if (roundbrktidx > -1 && curlybrktidx > -1 && roundbrktidx < curlybrktidx)
{
subs = comm.Substring(roundbrktidx + 1, curlybrktidx - roundbrktidx - 1);//extract string between ( and {.eg.. local(;{
subs = subs.Replace(";", " ");
if (subs.Trim().Length > 0)//this is true is there was something in between ( and { eg.. if(condi){
{
isroundblock = false;
}
else //there was nothing in between ( and {. eg.. local( {
{
isroundblock = true;
}
}
return isroundblock;
}
////round bracket block parser////
private string RoundBracketParser(string comm, int start, ref int end)
{
string str = string.Empty;
int roundopen = 0, roundclose = 0;
for (int i = comm.IndexOf('(', start); i < comm.Length; i++)
{
if (i < 0)
continue;
if (comm.ElementAt(i).Equals('(')) roundopen++;
else if (comm.ElementAt(i).Equals(')')) roundclose++;
if (roundopen == roundclose)
{
int idx = comm.IndexOf(";", i);
if (idx > i)
{
end = idx - start;
str = comm.Substring(start, end).Replace("))", ") )").Replace(";(", "(").Replace("(;", "(");
}
else
{
end = comm.Length - start;
str = comm.Substring(start, end).Replace("))", ") )").Replace(";(", "(").Replace("(;", "(");
}
break;
}
}
if (roundopen != roundclose)
{
//MessageBox.Show("Error in block declaration. Mismatch { or }");
CommandRequest cmdprn = new CommandRequest();
cmdprn.CommandSyntax = "write(\"" + BSky.GlobalResources.Properties.Resources.ErrParenthesisMismatch + "\",fp)";
analytics.ExecuteR(cmdprn, false, false); /// for printing command in file
return "ERROR";
}
str = str.Replace(";", " ");
str = RemoveComments(str);
return str;
}
private string RemoveComments_others(string str)//14May2014
{
if (str == null || str.Length < 1)
return null;
int len = str.Length;
int sidx = str.IndexOf("#");
int eidx = 0, remvlen = 0;
if (sidx < 0) // if there is no comment
return str;
for (; ; )
{
eidx = str.IndexOf(";", sidx);
remvlen = eidx - sidx;
str = str.Remove(sidx, remvlen);
//len = str.Length;
sidx = str.IndexOf("#");
if (sidx < 0)
break;
}
return str;
}
////03Oct2014 New Remove comments logic
private string RemoveComments(string text)
{
string nocommenttext = string.Empty;
int openbracketcount = 0, singlequote = 0, doublequote = 0;
if (text != null && text.Length > 0 && text.Contains('#'))
{
int idx = 0;
for (idx = 0; idx < text.Length; idx++) // go character by character
{
if (text[idx].Equals('(')) openbracketcount++;
else if (text[idx].Equals(')')) openbracketcount--;
else if (text[idx].Equals('\'')) singlequote++;
else if (text[idx].Equals('"')) doublequote++;
else if (text[idx].Equals('#'))
{
if (openbracketcount == 0 && singlequote % 2 == 0 && doublequote % 2 == 0) // # is outside any quotes or brackets
{
nocommenttext = text.Substring(0, idx);
break;
}
}
}
}
else//that means there is no #-comment in that line.
{
nocommenttext = text;
}
return nocommenttext;
}
//// curly block logics ////NOT in Use
private string BlockCodeParser(string seltext, int start, ref int end)
{
string stmt = string.Empty;
string subs = seltext.Substring(start).Replace("}}", "} }").Replace(";{", "{").Replace("{;", "{");
int blockendindex = 0;
int curlyopen = 0;
int indeOfFirstCloseCurly = subs.IndexOf('}');
for (int st = 0; st < indeOfFirstCloseCurly;)//count opening curly brackets
{
int curindex = subs.IndexOf('{', st);
if (curindex >= 0 && curindex < indeOfFirstCloseCurly)
{ curlyopen++; st = curindex + 1; }
else break;
}
int curlyclose = 0;
for (int st = 0; st < subs.Length - 1;)//count closing curly brackets
{
int curindex = subs.IndexOf('}', st);
if (curindex >= 0)//if found
{ curlyclose++; st = curindex + 1; }
else break;
if (curlyclose == curlyopen)
{
blockendindex = curindex;//length to be extracted
break;
}
}
if (curlyopen != curlyclose)
{
MessageBox.Show(this, BSky.GlobalResources.Properties.Resources.ErrCurlyMismatch);
return "";
}
string tmpstr = subs.Substring(0, blockendindex + 1).Replace('\n', ';').Replace('\r', ' ').Replace(" in ", "$#in#$").Replace(" ", string.Empty).Replace("$#in#$", " in ").Trim();
do
{
stmt = tmpstr.Replace(";;", ";");///.Replace("}", ";};")
} while (stmt.Contains(";;"));
end = blockendindex + 1;
stmt = stmt.Replace("}", ";} ");
return stmt;
}
// reading back sink file and creating & displaying output; for non-BSkyFormat commands
private void CreateOuput(OutputWindow ow)
{
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Started creating output.", LogLevelEnum.Info);
//////////////////// for fetching BSkyFormat object Queue and process each object //////////////////////
int bskyformatobjectindex = 0;
bool bskyQFetched = false;
CommandRequest fetchQ = null;
string sinkfileBSkyFormatMarker = "[1] \"BSkyFormatInternalSyncFileMarker\"";
string sinkfileBSkyGraphicFormatMarker = "[1] \"BSkyGraphicsFormatInternalSyncFileMarker\""; //09Jun2015
bool isBlockCommand = false;
bool isBlockGraphicCommand = false;
bool isBlock = false;
////////////////////////////////////////////////////////////////////////////////////////////////////////
//if (true) return;
CommandOutput lst = new CommandOutput(); ////one analysis////////
CommandOutput grplst = new CommandOutput();//21Nov2013 Separate for Graphic. So Parent node name will be R-Graphic
lst.IsFromSyntaxEditor = true;//lst belongs to Syn Editor
if (saveoutput.IsChecked == true)//10Jan2013
lst.SelectedForDump = true;
XmlDocument xd = null;
//string auparas = "";
StringBuilder sbauparas = new StringBuilder("");
//////////////// Read output ans message from file and create output then display /////
//// read line by line /////
string sinkfilename = confService.GetConfigValueForKey("tempsink");//23nov2012
string sinkfilefullpathname = Path.Combine(BSkyAppData.RoamingUserBSkyTempPath, sinkfilename);
// load default value if no path is set or invalid path is set
if (sinkfilefullpathname.Trim().Length == 0 || !IsValidFullPathFilename(sinkfilefullpathname, true))
{
MessageBox.Show(this, BSky.GlobalResources.Properties.Resources.tempsinkConfigKeyNotFound);
return;
}
try
{
FileStream fs = new FileStream(sinkfilefullpathname, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
System.IO.StreamReader file = new System.IO.StreamReader(fs);//, Encoding.Default);
object linetext = null; string line;
bool insideblock = false;//20May2014
bool readSinkFile = true;
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Started reading sink", LogLevelEnum.Info);
while ((line = file.ReadLine()) != null)//(readSinkFile)
{
{
linetext = line;
}
if (linetext == null || linetext.ToString().Equals("EOF"))
{
break;
}
if (linetext != null && linetext.Equals("NULL") && lastcommandwasgraphic)
{
continue;
}
if (linetext.ToString().Trim().Contains(sinkfileBSkyFormatMarker))
{
isBlockCommand = true;
}
else if (linetext.ToString().Trim().Contains(sinkfileBSkyGraphicFormatMarker))
{
isBlockGraphicCommand = true;
}
else
{
isBlockCommand = false;
}
//////// create XML doc /////////
if (linetext != null)//06May2013 we need formatting so we print blank lines..
{
/////// Trying to extract command from print //////
string commnd = linetext.ToString();
int opncurly = commnd.IndexOf("{");
int closcurly = commnd.IndexOf("}");
int lencommnd = closcurly - opncurly - 1;
if (opncurly != -1 && closcurly != -1)
commnd = commnd.Substring(opncurly + 1, lencommnd);//could be graphic or BSkyFormat in sink file.
if (false)
{
SendToOutput(sbauparas.ToString(), ref lst, ow);//22May2014
sbauparas.Clear();
}
else if (isBlockCommand)//14Jun2014 for Block BSkyFormat.
{
if (sbauparas.Length > 0)
{
createAUPara(sbauparas.ToString(), lst);//Create & Add AUPara to lst
sbauparas.Clear();
}
}
else
{
if (sbauparas.Length < 1)
{
sbauparas.Append(linetext.ToString());//First Line of AUPara. Without \n
if (sbauparas.ToString().Trim().IndexOf("BSkyFormat(") == 0)//21Nov2013
lst.NameOfAnalysis = "BSkyFormat-Command";
}
else
{
sbauparas.Append("\n" + linetext.ToString());//all lines separated by new line
}
}
if (isBlockGraphicCommand)//for block graphics //09Jun2015
{
CloseGraphicsDevice();
insideblock = true;
string synedtimgname = confService.GetConfigValueForKey("sinkimage");//23nov2012
string synedtimg = Path.Combine(BSkyAppData.RoamingUserBSkyTempPath, synedtimgname);
/////03May2013 Create zero padding string //// %03d means 000, %04d means 0000
int percentindex = synedtimg.IndexOf("%");
int dindex = synedtimg.IndexOf("d", percentindex);
string percentstr = synedtimg.Substring(percentindex, (dindex - percentindex + 1));
string numbr = synedtimg.Substring(percentindex + 1, (dindex - percentindex - 1));
int zerocount = Convert.ToInt16(numbr);
string zeropadding = string.Empty;
for (int zeros = 1; zeros <= zerocount; zeros++)
{
zeropadding = zeropadding + "0";
}
{
GraphicDeviceImageCounter++;//imgcount++;
string tempsynedtimg = synedtimg.Replace(percentstr, GraphicDeviceImageCounter.ToString(zeropadding));
// load default value if no path is set or invalid path is set
if (tempsynedtimg.Trim().Length == 0 || !IsValidFullPathFilename(tempsynedtimg, true))
{
isBlockGraphicCommand = false; //09Jun2015 reset, as we dont know what next command is. May or may not be graphic marker
break;
}
string source = @tempsynedtimg;
Image myImage = new Image();
var bitmap = new BitmapImage();
try
{
var stream = File.OpenRead(source);
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = stream;
bitmap.EndInit();
stream.Close();
stream.Dispose();
myImage.Source = bitmap;
bitmap.StreamSource.Close(); //trying to close stream 03Feb2014
if (isBlockGraphicCommand)
createBSkyGraphic(myImage, lst); //20May2014 If graphic is inside block or loop
else
createBSkyGraphic(myImage, grplst); //if graphic is outside block or loop
DeleteFileIfPossible(@tempsynedtimg);
}
catch (Exception ex)
{
logService.WriteToLogLevel("Error reading Image file " + source + "\n" + ex.Message, LogLevelEnum.Error);
MessageBox.Show(this, ex.Message);
}
}
if (GraphicDeviceImageCounter < 1) ////03May2013 if no images were added to output lst. then return.
{
sbauparas.Clear();//resetting
isBlockGraphicCommand = false;
return;
}
sbauparas.Clear();//resetting
isBlockGraphicCommand = false;
}
else if (isBlockCommand)
{
int bskyfrmtobjcount = 0;
if (!bskyQFetched)
{
fetchQ = new CommandRequest();
fetchQ.CommandSyntax = "BSkyQueue = BSkyGetHoldFormatObjList()";
analytics.ExecuteR(fetchQ, false, false);
fetchQ.CommandSyntax = "is.null(BSkyQueue)";
object o = analytics.ExecuteR(fetchQ, true, false);
if (o.ToString().ToLower().Equals("false"))
{
bskyQFetched = true;
}
}
if (bskyQFetched)
{
bskyformatobjectindex++;
commnd = "BSkyFormat(BSkyQueue[[" + bskyformatobjectindex + "]])";
ExecuteSinkBSkyFormatCommand(commnd, ref bskyfrmtobjcount, lst);
lst = new CommandOutput();//"Child already has parent" error, fix
isBlock = true;
}
isBlockCommand = false;//09Jun2015 next command may or may not be BSkyFormat marker.
}
}//if
}//while
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Finished reading sink", LogLevelEnum.Info);
file.Close();
SendToOutput(sbauparas.ToString(), ref lst, ow, isBlock);//send output to window or disk file
SendToOutput(null, ref grplst, ow, isBlock);//21Nov2013. separate node for graphic
if (lst != null && lst.Count > 0 && isBlock) // Exceutes when there is block command
{
sessionlst.Add(lst);//15Nov2013
lst = new CommandOutput();//after adding to session new object is allocated for futher output creation
}
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Finished creating output.", LogLevelEnum.Info);
}
catch (Exception ex)
{
logService.WriteToLogLevel("Error reading sink.", LogLevelEnum.Info);
logService.WriteToLogLevel(ex.Message, LogLevelEnum.Info);
SendToOutput("Error:" + ex.Message, ref lst, ow);
}
}
//This method gets outputs all the graphics.
private void CreateAllGraphicOutput(OutputWindow ow)
{
CommandOutput grplst = new CommandOutput();
long EmptyImgSize = EMPTYIMAGESIZE;
CloseGraphicsDevice();
////// now add image to lst ////
string synedtimgname = confService.GetConfigValueForKey("sinkimage");//23nov2012
string synedtimg = Path.Combine(BSkyAppData.RoamingUserBSkyTempPath, synedtimgname);
int percentindex = synedtimg.IndexOf("%");
int dindex = synedtimg.IndexOf("d", percentindex);
string percentstr = synedtimg.Substring(percentindex, (dindex - percentindex + 1));
string numbr = synedtimg.Substring(percentindex + 1, (dindex - percentindex - 1));
int zerocount = Convert.ToInt16(numbr);
string zeropadding = string.Empty;
for (int zeros = 1; zeros <= zerocount; zeros++)
{
zeropadding = zeropadding + "0";
}
int imgcount = GraphicDeviceImageCounter;//number of images to load in output
for (; ; )
{
imgcount++;
string tempsynedtimg = synedtimg.Replace(percentstr, imgcount.ToString(zeropadding));
// load default value if no path is set or invalid path is set
if (tempsynedtimg.Trim().Length == 0 || !IsValidFullPathFilename(tempsynedtimg, true))
{
break;
}
string source = @tempsynedtimg;
long imgsize = new FileInfo(source).Length;//find size of the imagefile
if (imgsize > EmptyImgSize)//if image is not an empty image
{
Image myImage = new Image();
var bitmap = new BitmapImage();
try
{
var stream = File.Open(source, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = stream;
bitmap.EndInit();
stream.Close();
stream.Dispose();
myImage.Source = bitmap;
bitmap.StreamSource.Close(); //trying to close stream 03Feb2014
createBSkyGraphic(myImage, grplst); //add graphic
DeleteFileIfPossible(@tempsynedtimg);
}
catch (Exception ex)
{
logService.WriteToLogLevel("Error reading Image file " + source + "\n" + ex.Message, LogLevelEnum.Error);
MessageBox.Show(this, ex.Message);
}
}
}
if (imgcount < 1) ////03May2013 if no images were added to output lst. then return.
{
return;
}
SendToOutput(null, ref grplst, ow, false);//send all graphic to output
OpenGraphicsDevice();//in case of errors or no errors, you must open graphic device
}
private void DeleteFileIfPossible(string fulpathfilename)
{
try
{
File.Delete(fulpathfilename);
}
catch (IOException ex)
{
logService.Error("Unable to delete :" + fulpathfilename);
logService.Error("IOException: " + ex.Message);
}
catch (Exception ex1) //Added this on 25Jan2016 for catching other execeptions(those may crash the app)
{
logService.Error("Unable to delete :" + fulpathfilename);
logService.Error("Exception: " + ex1.Message);
}
}
private void SendToOutput(string auparas, ref CommandOutput lst, OutputWindow ow, bool isBlockCommand = false)//, bool last=false)
{
if (auparas != null && auparas.Trim().Length > 0)
{
this.createAUPara(auparas, lst);//Create & Add AUPara to lst and empty dommid
auparas = null;
}
//////// send output to current active window ////////outputopencommand.cs
if (lst != null && lst.Count > 0 && !isBlockCommand) //if non block command, then sent to output
{
sessionlst.Add(lst);//15Nov2013
lst = new CommandOutput();//after adding to session new object is allocated for futher output creation
}
}
private void SetSink() // set desired sink
{
sinkcmd.CommandSyntax = "options('warn'=1)";// trying to flush old errors
analytics.ExecuteR(sinkcmd, false, false);
sinkcmd.CommandSyntax = "sink(fp, append=FALSE, type=c(\"output\"))";// command
analytics.ExecuteR(sinkcmd, false, false);
sinkcmd.CommandSyntax = "sink(fp, append=FALSE, type=c(\"message\"))";// command
analytics.ExecuteR(sinkcmd, false, false);
}
private void ResetSink()
{
sinkcmd.CommandSyntax = "sink(stderr(), type=c(\"message\"))";// command
analytics.ExecuteR(sinkcmd, false, false);
sinkcmd.CommandSyntax = "sink()";//stdout(), type=\"output\")";// command
analytics.ExecuteR(sinkcmd, false, false);
}
private void OpenSinkFile(string fullpathfilename, string mode)
{
string unixstylepath = fullpathfilename.Replace("\\", "/");
sinkcmd.CommandSyntax = "fp<- file(\"" + unixstylepath + "\",encoding = \"UTF-8\", open=\"" + "w+" + "\")";// command. use r+ for read/write
analytics.ExecuteR(sinkcmd, false, false);
}
private void CloseSinkFile()
{
sinkcmd.CommandSyntax = "flush(fp)";// command
analytics.ExecuteR(sinkcmd, false, false);
sinkcmd.CommandSyntax = "close(fp)";// command
analytics.ExecuteR(sinkcmd, false, false);
}
private string findHeaderName(string bskyformatcmd)
{
if (bskyformatcmd.Trim().Contains("data.frame"))
return "data.frame";
else if (bskyformatcmd.Trim().Contains("array"))
return "array";
else if (bskyformatcmd.Trim().Contains("matrix"))
return "matrix";
else
{
return (bskyformatcmd);
}
}
private bool IsAnalyticsCommand(string command)
{
bool bskycomm = false;
return bskycomm;
}
private void ExecuteSplit(string stmt)
{
CommandRequest cmd = new CommandRequest();
CommandExecutionHelper ceh = new CommandExecutionHelper();
UAMenuCommand uamc = new UAMenuCommand();
uamc.bskycommand = stmt;
uamc.commandtype = stmt;
cmd.CommandSyntax = stmt;
ceh.ExecuteSplit(stmt, FElement);
ceh = null;
}
private void ExecuteBSkyCommand(string stmt)
{
CommandRequest cmd = new CommandRequest();
if (IsAnalyticsCommand(stmt))
{
ResetSink();
cmd.CommandSyntax = stmt;// command
object o = analytics.ExecuteR(cmd, false, false);//executing syntax editor commands
SetSink();
}
}
private void ExecuteBSkyFormatCommand(string stmt, ref int bskyfrmtobjcount, OutputWindow ow)
{
KillTempBSkyFormatObj("bskytempvarname");
KillTempBSkyFormatObj("bskyfrmtobj");
string originalCommand = stmt;
CommandOutput lst = new CommandOutput(); ////one analysis////////
lst.IsFromSyntaxEditor = true;//lst belongs to Syn Editor
if (saveoutput.IsChecked == true)//10Jan2013
lst.SelectedForDump = true;
object o;
CommandRequest cmd = new CommandRequest();
cmd.CommandSyntax = originalCommand;
//16Aug2016 Not executing the command but sending it to logs because
analytics.LogCommandNotExecute(cmd);//this command is modified below and then executed after several checks.
string subcomm = string.Empty, varname = string.Empty, BSkyLeftVar = string.Empty, headername = string.Empty;
string firstparam = string.Empty, restparams = string.Empty, leftvarname = string.Empty;//23Sep2014
string userpassedtitle = string.Empty;
//SplitBSkyFormat(stmt, out subcomm, out varname, out BSkyLeftVar);
SplitBSkyFormatParams(stmt, out firstparam, out restparams, out userpassedtitle);//23Spe2014
if (userpassedtitle.Trim().Length > 0)//user passed title has the highest priority
{
headername = userpassedtitle.Trim();
}
{
//23Sep2014 if firstParam is of the type obj<-OSMT(...) OR obj<-obj2
if (firstparam.Contains("<-") || firstparam.Contains("=")) //if it has assignment
{
int idxassign = -1, idxopenbrket = -1;
if (firstparam.Contains("("))// if obj<-OSMT(...)
{
idxopenbrket = firstparam.IndexOf("(");
string firsthalf = firstparam.Substring(0, idxopenbrket);// "obj <- OSMT("
idxassign = firsthalf.IndexOf("<-");
if (idxassign == -1)// '<-' not present(found in half)
idxassign = firsthalf.IndexOf("=");
}
if (idxassign > -1 && idxopenbrket > -1 && idxopenbrket > idxassign)
{
leftvarname = firstparam.Substring(0, idxassign);
headername = leftvarname.Trim();
cmd.CommandSyntax = firstparam;// command: osmt<-one.smt.tt(...)
o = analytics.ExecuteR(cmd, false, false);//executing sub-command; osmt<-one.smt.tt(...)
}
else if (idxopenbrket < 0)//type obj <- obj2
{
idxassign = firstparam.IndexOf("<-");
if (idxassign == -1)// '<-' not present
idxassign = firstparam.IndexOf("=");
if (idxassign > -1)//if assignment is there
{
leftvarname = firstparam.Substring(0, idxassign);
headername = leftvarname.Trim();
cmd.CommandSyntax = firstparam;// command: osmt<-one.smt.tt(...)
o = analytics.ExecuteR(cmd, false, false);//executing sub-command; osmt<-one.smt.tt(...)
}
}
}
/////25Feb2013 for writing errors in OutputWindow////
string sinkfilename = confService.GetConfigValueForKey("tempsink");//23nov2012
string sinkfilefullpathname = Path.Combine(BSkyAppData.RoamingUserBSkyTempPath, sinkfilename);
// load default value if no path is set or invalid path is set
if (sinkfilefullpathname.Trim().Length == 0 || !IsValidFullPathFilename(sinkfilefullpathname, false))
{
MessageBox.Show(this, BSky.GlobalResources.Properties.Resources.tempsinkConfigKeyNotFound);
return; //return type was void before 22May2014
}
OpenSinkFile(@sinkfilefullpathname, "wt"); //06sep2012
SetSink(); //06sep2012
////////////////////////////////////////////////////////////////////////
varname = "bskytempvarname";
KillTempBSkyFormatObj(varname);
//Now run command
firstparam = (leftvarname.Trim().Length > 0 ? leftvarname : firstparam);
cmd.CommandSyntax = varname + " <- " + firstparam;// varname <- obj OR OSMT()
o = analytics.ExecuteR(cmd, false, false);//executing sub-command
////////////////////////////////////////////////////////////////////////
/////25Feb2013 for writing errors in OutputWindow////
ResetSink();
CloseSinkFile();
CreateOuput(ow);
}
//if var does not exist then there could be error in command execution.
cmd.CommandSyntax = "exists('" + varname + "')";
o = analytics.ExecuteR(cmd, true, false);
if (o.ToString().ToLower().Equals("false"))//possibly some error occured
{
string ewmessage = BSky.GlobalResources.Properties.Resources.ObjCantBSkyFormat + " " + firstparam + ", " + BSky.GlobalResources.Properties.Resources.DoesNotExist;
SendErrorToOutput(originalCommand + "\n" + ewmessage, ow); //03Jul2013
return; //return type was void before 22May2014
}
//Check if varname is null
cmd.CommandSyntax = "is.null(" + varname + ")";
o = analytics.ExecuteR(cmd, true, false);
if (o.ToString().ToLower().Equals("true"))//possibly some error occured
{
string ewmessage = BSky.GlobalResources.Properties.Resources.ObjCantBSkyFormat + " " + firstparam + ", " + BSky.GlobalResources.Properties.Resources.isNull;
SendErrorToOutput(originalCommand + "\n" + ewmessage, ow); //03Jul2013
return; //return type was void before 22May2014
}
bsky_no_row_header = false;
cmd.CommandSyntax = "is.null(row.names(" + varname + ")[1])";
o = analytics.ExecuteR(cmd, true, false);
if (o.ToString().ToLower().Equals("false"))//row name at [1] exists
{
cmd.CommandSyntax = "row.names(" + varname + ")[1]";
o = analytics.ExecuteR(cmd, true, false);
if (o.ToString().Trim().ToLower().Equals("bsky_no_row_header"))
{
bsky_no_row_header = true;
}
}
//one mandatory parameter
string mandatoryparamone = ", bSkyFormatAppRequest = TRUE";
if (restparams.Trim().Length > 0 && restparams.Trim().Contains("bSkyFormatAppRequest"))
{
mandatoryparamone = string.Empty;
}
//second mandatory parameter
string mandatoryparamtwo = ", singleTableOutputHeader = '" + headername + "'";
if (restparams.Trim().Length > 0 && restparams.Trim().Contains("singleTableOutputHeader"))
{
mandatoryparamtwo = string.Empty;
}
//create BSkyFormat command for execution and execute
if (restparams.Trim().Length > 0)
stmt = "BSkyFormat(" + varname + mandatoryparamone + mandatoryparamtwo + "," + restparams + ")";
else
stmt = "BSkyFormat(" + varname + mandatoryparamone + mandatoryparamtwo + " )";
stmt = BSkyLeftVar + stmt;
/// BSkyLeftVar <- can be blank if user has no assigned leftvar to BSkyFormat
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Command reconstructed : " + stmt, LogLevelEnum.Info);
string objclass = "", objectname = "";
if (stmt.Contains("BSkyFormat("))// Array, Matrix, Data Frame or BSkyObject(ie..Analytic commands)
{
bskyfrmtobjcount++;
stmt = "bskyfrmtobj <- " + stmt;
objectname = "bskyfrmtobj";
cmd.CommandSyntax = stmt;// command
o = analytics.ExecuteR(cmd, false, false);//executing BSkyFormat
///Check if returned object is null
cmd.CommandSyntax = "is.null(" + objectname + ")";
o = analytics.ExecuteR(cmd, true, false);
if (o.ToString().ToLower().Equals("true"))//possibly some error occured
{
string ewmessage = BSky.GlobalResources.Properties.Resources.ObjCantBSkyFormat2 + "\n " + BSky.GlobalResources.Properties.Resources.BSkyFormatSupportedTypes;
SendErrorToOutput(originalCommand + "\n" + ewmessage, ow); //03Jul2013
return; //return type was void before 22May2014
}
#region Generate UI for data.frame/ matrix / array and analytics commands
if (BSkyLeftVar.Trim().Length < 1) // if left var does not exist then generate UI tables
{
lst.NameOfAnalysis = originalCommand.Contains("BSkyFormat") ? "BSkyFormat-Command" : originalCommand;
//cmd.CommandSyntax = "class(bskyfrmtobj" + bskyfrmtobjcount.ToString() + ")";
cmd.CommandSyntax = "class(bskyfrmtobj)";
objclass = (string)analytics.ExecuteR(cmd, true, false);
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: BSkyFormat object type : " + objclass, LogLevelEnum.Info);
//Following 2 lines commented because we o not want to show "data.frame", "matrix", "array" as headers.
//if (headername.Trim().Length < 1)//13Aug2012
// headername = objclass.ToString();
if (objclass.ToString().ToLower().Equals("data.frame") || objclass.ToString().ToLower().Equals("matrix") || objclass.ToString().ToLower().Equals("array"))
{
//lst.NameOfAnalysis = originalCommand;//for tree Parent node 07Aug2012
if (headername != null && headername.Trim().Length < 1) //06May2014
headername = subcomm;
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: BSkyFormatting DF/Matrix/Arr : " + objclass, LogLevelEnum.Info);
BSkyFormatDFMtxArr(lst, objectname, headername, ow);
}
else if (objclass.ToString().ToLower().Equals("list"))//BSkyObject returns "list"
{
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: BSkyFormatting : " + objclass, LogLevelEnum.Info);
//if (ow != null)//22May2014
SendToOutput("", ref lst, ow);
///tetsing whole else if
objectname = "bskyfrmtobj";// +bskyfrmtobjcount.ToString();
//cmd.CommandSyntax = objectname + "$uasummary[[7]]";//"bsky.histogram(colNameOrIndex=c('age'), dataSetNameOrIndex='Dataset1')";//
cmd.CommandSyntax = "is.null(" + objectname + "$BSkySplit)";//$BSkySplit or $split in return structure
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Executing : " + cmd.CommandSyntax, LogLevelEnum.Info);
bool isNonBSkyList1 = false;
object isNonBSkyList1str = analytics.ExecuteR(cmd, true, false);
if (isNonBSkyList1str != null && isNonBSkyList1str.ToString().ToLower().Equals("true"))
{
isNonBSkyList1 = true;
}
cmd.CommandSyntax = "is.null(" + objectname + "$list2name)";//another type pf BSky list
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Executing : " + cmd.CommandSyntax, LogLevelEnum.Info);
bool isNonBSkyList2 = false;
object isNonBSkyList2str = analytics.ExecuteR(cmd, true, false);
if (isNonBSkyList2str != null && isNonBSkyList2str.ToString().ToLower().Equals("true"))
{
isNonBSkyList2 = true;
}
if (!isNonBSkyList1)
{
//if there was error in execution, say because non scale field has scale variable
// so now if we first check if $executionstatus = -2, we know that some error has occured.
cmd.CommandSyntax = objectname + "$executionstatus";//$BSkySplit or $split in return structure
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Executing : " + cmd.CommandSyntax, LogLevelEnum.Info);
object errstat = analytics.ExecuteR(cmd, true, false);
if (errstat != null && (errstat.ToString().ToLower().Equals("-2") || errstat.ToString().ToLower().Equals("-1")))
{
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Execution Stat : " + errstat, LogLevelEnum.Info);
//if (errstat.ToString().ToLower().Equals("-2"))
// SendErrorToOutput("Critical Error Occurred!", ow);//15Jan2015
if (errstat.ToString().ToLower().Equals("-2"))
SendErrorToOutput(BSky.GlobalResources.Properties.Resources.CriticalError, ow);//15Jan2015
else
SendErrorToOutput(BSky.GlobalResources.Properties.Resources.ErrorOccurred, ow);//03Jul2013
}
cmd.CommandSyntax = objectname + "$nooftables";//$nooftables=0, means no data to display. Not even error warning tables are there.
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Executing : " + cmd.CommandSyntax, LogLevelEnum.Info);
object retval = analytics.ExecuteR(cmd, true, false);
if (retval != null && retval.ToString().ToLower().Equals("0"))
{
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: No of Tables : " + retval, LogLevelEnum.Info);
SendErrorToOutput(BSky.GlobalResources.Properties.Resources.NoTablesReturned, ow);//03Jul2013
}
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Start creating actual UI tables : ", LogLevelEnum.Info);
//finally we can now format the tables of BSkyReturnStruture list
RefreshOutputORDataset(objectname, cmd, originalCommand, ow); //list like one sample etc..
}
else if (!isNonBSkyList2)
{
//if (ow != null)//22May2014
FormatBSkyList2(lst, objectname, headername, ow); //list that contains tables 2nd location onwards
}
}
else // invalid format
{
/// put it in right place
string ewmessage = BSky.GlobalResources.Properties.Resources.CantBSkyFormatErrorMsg;
//if (ow != null)//22May2014
SendErrorToOutput(originalCommand + "\n" + ewmessage, ow);//03Jul2013
}
}/// if leftvar is not assigned generate UI
#endregion
}
return;//22May2014
}
//30Sep2014
// This var must be removed from R memory otherwise when next BSkyFormat fails.
private void KillTempBSkyFormatObj(string varname)
{
object o;
CommandRequest cmd = new CommandRequest();
//Find if bskytempvarname already exists. If it exists then remove from memory
cmd.CommandSyntax = "tiscuni <- exists('" + varname + "')";//removing var so that old obj from last session is not present.
o = analytics.ExecuteR(cmd, true, false);
if (o.ToString().ToLower().Equals("true")) // if found, remove it
{
cmd.CommandSyntax = "rm('" + varname + "')";//removing var so that old obj from last session is not present.
o = analytics.ExecuteR(cmd, false, false);
}
}
private void ExecuteSinkBSkyFormatCommand(string stmt, ref int bskyfrmtobjcount, CommandOutput lst)
{
string originalCommand = stmt;
lst.IsFromSyntaxEditor = true;//lst belongs to Syn Editor
if (saveoutput.IsChecked == true)//10Jan2013
lst.SelectedForDump = true;
object o;
CommandRequest cmd = new CommandRequest();
string subcomm = string.Empty, varname = string.Empty, BSkyLeftVar = string.Empty, headername = string.Empty;
SplitBSkyFormat(stmt, out subcomm, out varname, out BSkyLeftVar);
//string leftvarname = BSkyLeftVar;//UI ll not be generated in LeftVar case so no need for table header either
if (BSkyLeftVar.Trim().Length > 0) // if left var exists
{
BSkyLeftVar = BSkyLeftVar + " <- "; // so that BSkyLeftVar <- BSkyFormat(...) )
}
////now execute subcomm first then pass varname in BSkyFormat(varname)
if (varname.Length > 0)
{
headername = varname.Trim();
cmd.CommandSyntax = subcomm;// command: osmt<-one.smt.tt(...)
if (!varname.Equals(subcomm))
o = analytics.ExecuteR(cmd, false, false);
}
else
{
/////25Feb2013 for writing errors in OutputWindow////
string sinkfilename = confService.GetConfigValueForKey("tempsink");//23nov2012
string sinkfilefullpathname = Path.Combine(BSkyAppData.RoamingUserBSkyTempPath, sinkfilename);
// load default value if no path is set or invalid path is set
if (sinkfilefullpathname.Trim().Length == 0 || !IsValidFullPathFilename(sinkfilefullpathname, false))
{
MessageBox.Show(this, BSky.GlobalResources.Properties.Resources.tempsinkConfigKeyNotFound);
return;
}
////////////////////////////////////////////////////////////////////////
varname = "bskytempvarname";
//Find if bskytempvarname already exists. If it exists then remove from memory
cmd.CommandSyntax = "exists('" + varname + "')";//removing var so that old obj from last session is not present.
o = analytics.ExecuteR(cmd, true, false);
if (o.ToString().ToLower().Equals("true")) // if found, remove it
{
cmd.CommandSyntax = "rm('" + varname + "')";//removing var so that old obj from last session is not present.
o = analytics.ExecuteR(cmd, false, false);
}
//Now run command
cmd.CommandSyntax = varname + " <- " + subcomm;// command: varname <- one.smt.tt(...)
o = analytics.ExecuteR(cmd, false, false);//executing sub-command
////////////////////////////////////////////////////////////////////////
}
//if var does not exist then there could be error in command execution.
cmd.CommandSyntax = "exists('" + varname + "')";
o = analytics.ExecuteR(cmd, true, false);
if (o.ToString().ToLower().Equals("false"))//possibly some error occured
{
string ewmessage = BSky.GlobalResources.Properties.Resources.ObjCantBSkyFormat + " " + varname + ", " + BSky.GlobalResources.Properties.Resources.DoesNotExist;
SendErrorToOutput(originalCommand + "\n" + ewmessage, ow); //03Jul2013
return;
}
if (subcomm.Contains("BSkyQueue"))//BSkyFormat already ran and this Q has the table. We just need to extract the table
{
stmt = subcomm;
}
else //for other cases BSkyForamt( onssm() ) or BSkyFormat(res<-onesm())
{
stmt = "BSkyFormat(" + varname + ", bSkyFormatAppRequest = TRUE)";
stmt = BSkyLeftVar + stmt;// command is BSkyLeftVar <- BSkyFormat(varname)
}
string objclass = "", objectname = "";
if (stmt.Contains("BSkyFormat(") || stmt.Contains("BSkyQueue"))// Array, Matrix, Data Frame or BSkyObject(ie..Analytic commands)
{
bskyfrmtobjcount++;
stmt = "bskyfrmtobj <- " + stmt;
objectname = "bskyfrmtobj";
cmd.CommandSyntax = stmt;// command
o = analytics.ExecuteR(cmd, false, false);//executing syntax editor commands
#region Generate UI for data.frame/ matrix / array and analytics commands
if (BSkyLeftVar.Trim().Length < 1) // if left var does not exist then generate UI tables
{
lst.NameOfAnalysis = originalCommand.Contains("BSkyFormat") ? "BSkyFormat-Command" : originalCommand;
cmd.CommandSyntax = "class(bskyfrmtobj)";
objclass = (string)analytics.ExecuteR(cmd, true, false);
if (objclass.ToString().ToLower().Equals("data.frame") || objclass.ToString().ToLower().Equals("matrix") || objclass.ToString().ToLower().Equals("array"))
{
//lst.NameOfAnalysis = originalCommand;//for tree Parent node 07Aug2012
if (headername != null && headername.Trim().Length < 1) //06May2014
{
headername = subcomm;
}
BSkyFormatDFMtxArr(lst, objectname, headername, null);
}
else if (objclass.ToString().Equals("list"))//BSkyObject returns "list"
{
SendToOutput("", ref lst, ow);
objectname = "bskyfrmtobj";
cmd.CommandSyntax = "is.null(" + objectname + "$BSkySplit)";//$BSkySplit or $split in return structure
bool isNonBSkyList1 = false;
object isNonBSkyList1str = analytics.ExecuteR(cmd, true, false);
if (isNonBSkyList1str != null && isNonBSkyList1str.ToString().ToLower().Equals("true"))
{
isNonBSkyList1 = true;
}
cmd.CommandSyntax = "is.null(" + objectname + "$list2name)";//another type pf BSky list
bool isNonBSkyList2 = false;
object isNonBSkyList2str = analytics.ExecuteR(cmd, true, false);
if (isNonBSkyList2str != null && isNonBSkyList2str.ToString().ToLower().Equals("true"))
{
isNonBSkyList2 = true;
}
/////////////////
if (!isNonBSkyList1)
{
RefreshOutputORDataset(objectname, cmd, originalCommand, ow); //list like one sample etc..
}
else if (!isNonBSkyList2)
{
FormatBSkyList2(lst, objectname, headername, ow); //list that contains tables 2nd location onwards
}
}
else // invalid format
{
/// put it in right place
string ewmessage = BSky.GlobalResources.Properties.Resources.CantBSkyFormatErrorMsg;
SendErrorToOutput(originalCommand + "\n" + ewmessage, ow);//03Jul2013
}
}/// if leftvar is not assigned generate UI
#endregion
}
}
private bool ExecuteBSkyLoadRefreshDataframe(string stmt, string fname)//13Feb2014
{
CommandRequest cmd = new CommandRequest();
int start = stmt.IndexOf('(');
int end = stmt.IndexOf(')');
string parameters = stmt.Substring(start + 1, end - start - 1);
string[] eachparam = parameters.Split(',');
string dataframename = string.Empty;
string boolparam = string.Empty;
if (eachparam.Length == 2)
{
//either of the two is dataframe name
if (eachparam[1].Contains("load.dataframe") || eachparam[1].Contains("TRUE") || eachparam[1].Contains("FALSE"))
{
dataframename = eachparam[0];
boolparam = eachparam[1];
}
else // if bool is passed as first parameter and dataframe name as second param.
{
dataframename = eachparam[1];
boolparam = eachparam[0];
}
}
else if (eachparam.Length == 1)//only one madatory param is passed which is dataframe name
{
dataframename = eachparam[0];
if (dataframename.Trim().Equals("load.dataframe") || dataframename.Trim().Equals("FALSE") || dataframename.Trim().Equals("TRUE"))//Dataframe parameter not passed.
{
dataframename = string.Empty;
}
boolparam = "TRUE";
}
/////get dataframe name
if (dataframename.Contains("="))
{
dataframename = dataframename.Substring(dataframename.IndexOf("=") + 1);
}
dataframename = dataframename.Trim();
//09Jun2015 if dataframename is not passed that means there is no need to load/refresh dataframe
if (dataframename.Length < 1)
{
return true;
}
///get bool parama value
if (boolparam.Contains("="))//dframe="Dataset1"
{
boolparam = boolparam.Substring(boolparam.IndexOf("=") + 1);
}
boolparam = boolparam.Trim();
//27Feb2017 check boolparam's value from R
cmd.CommandSyntax = boolparam;//check if boolparam is TRUE or FALSE
object oloaddf = analytics.ExecuteR(cmd, true, false);
if (oloaddf.ToString().ToLower().Equals("true"))
{
boolparam = "TRUE";
}
else
{
boolparam = "FALSE";
}
if (boolparam.Contains("FALSE"))//do not refresh dataframe
{
return true;
}
cmd.CommandSyntax = "exists('" + dataframename + "')";//check if that dataset exists in memory.
object o1 = analytics.ExecuteR(cmd, true, false);
if (o1.ToString().ToLower().Equals("true")) // if found, check if data.frame type. then load it
{
//27Feb2017 Refresh NULL dataset.
cmd.CommandSyntax = "is.null(" + dataframename + ")";//check if dataframe object is null
object odsnull = analytics.ExecuteR(cmd, true, false);
if (odsnull.ToString().ToLower().Equals("true")) // if data.frame is null
{
cmd.CommandSyntax = "length(which('" + dataframename + "'==uadatasets$name)) > 0";//check if dataframe existed before
object odsidx = analytics.ExecuteR(cmd, true, false);
if (odsidx.ToString().ToLower().Equals("true")) // if data.frame index is found
{
IUIController UIController;
UIController = LifetimeService.Instance.Container.Resolve<IUIController>();
DataSource oldDs = UIController.GetDocumentByName(dataframename);//oldDs help us to get the filename
DataSource ds = new DataSource();
ds.Variables = new List<DataSourceVariable>();
ds.FileName = oldDs.FileName;
ds.Name = dataframename;
ds.SheetName = "";
ds.DecimalCharacter = oldDs.DecimalCharacter;
ds.FieldSeparator = oldDs.FieldSeparator;
ds.HasHeader = oldDs.HasHeader;
ds.IsBasketData = oldDs.IsBasketData;
UIController.RefreshBothGrids(ds);
return false;
}
else
{
SendErrorToOutput(BSky.GlobalResources.Properties.Resources.NotdataframeType, ow);
return false;
}
}
else
{
cmd.CommandSyntax = "is.data.frame(" + dataframename + ")";//check if its 'data.frame' type.
object o2 = analytics.ExecuteR(cmd, true, false);
if (o2.ToString().ToLower().Equals("true")) // if data.frame type
{
FileOpenCommand foc = new FileOpenCommand();
return foc.OpenDataframe(dataframename, fname);
}
else
{
SendErrorToOutput(BSky.GlobalResources.Properties.Resources.NotdataframeType, ow);
return false;
}
}
}
else
{
SendErrorToOutput(BSky.GlobalResources.Properties.Resources.DatasetObjNotExists, ow);
return false;
}
}
private void ExecuteBSkyRemoveRefreshDataframe(string stmt)//20Feb2014
{
int start = stmt.IndexOf('(');
int end = stmt.IndexOf(')');
string dataframename = stmt.Substring(start + 1, end - start - 1);
FileCloseCommand fcc = new FileCloseCommand();
fcc.CloseDatasetFromSyntax(dataframename);
}
private void ExecuteXMLTemplateDefinedCommands(string stmt)//10Jul2014
{
CommandRequest xmlgrpcmd = new CommandRequest();
xmlgrpcmd.CommandSyntax = stmt;
UAMenuCommand uamc = new UAMenuCommand();
uamc.bskycommand = stmt;
uamc.commandtype = stmt;
CommandExecutionHelper auacb = new CommandExecutionHelper();
auacb.MenuParameter = menuParameter;
auacb.RetVal = analytics.Execute(xmlgrpcmd);
auacb.ExecuteXMLDefinedDialog(stmt);
}
//pulled out from ExecuteBSkyFromatCommand() method above. For BskyFormat DataFrame Matrix Array
private void BSkyFormatDFMtxArr(CommandOutput lst, string objectname, string headername, OutputWindow ow)
{
CommandRequest cmddf = new CommandRequest();
int dimrow = 1, dimcol = 1;
bool rowexists = false, colexists = false;
string dataclassname = string.Empty;
//Find class of data passed. data.frame, matrix, or array
cmddf.CommandSyntax = "class(" + objectname + ")"; // Row exists
object retres = analytics.ExecuteR(cmddf, true, false);
if (retres != null)
dataclassname = retres.ToString();
//find if dimension exists
cmddf.CommandSyntax = "!is.na(dim(" + objectname + ")[1])"; // Row exists
retres = analytics.ExecuteR(cmddf, true, false);
if (retres != null && retres.ToString().ToLower().Equals("true"))
rowexists = true;
cmddf.CommandSyntax = "!is.na(dim(" + objectname + ")[2])";// Col exists
retres = analytics.ExecuteR(cmddf, true, false);
if (retres != null && retres.ToString().ToLower().Equals("true"))
colexists = true;
/// Find size of matrix(objectname) & initialize data array ///
if (rowexists)
{
cmddf.CommandSyntax = "dim(" + objectname + ")[1]";
retres = analytics.ExecuteR(cmddf, true, false);
if (retres != null)
dimrow = Int16.Parse(retres.ToString());
}
if (colexists)
{
cmddf.CommandSyntax = "dim(" + objectname + ")[2]";
retres = analytics.ExecuteR(cmddf, true, false);
if (retres != null)
dimcol = Int16.Parse(retres.ToString());
}
string[,] data = new string[dimrow, dimcol];
//// now create FlexGrid and add to lst ///
/////////finding Col headers /////
cmddf.CommandSyntax = "colnames(" + objectname + ")";
object colhdrobj = analytics.ExecuteR(cmddf, true, false);
string[] colheaders;
if (colhdrobj != null && !colhdrobj.ToString().Contains("Error"))
{
if (colhdrobj.GetType().IsArray)
colheaders = (string[])colhdrobj;//{ "Aa", "Bb", "Cc" };//
else
{
colheaders = new string[1];
colheaders[0] = colhdrobj.ToString();
}
}
else
{
colheaders = new string[dimcol];
for (int i = 0; i < dimcol; i++)
colheaders[i] = (i + 1).ToString();
}
/////////finding Row headers /////
string numrowheader = confService.AppSettings.Get("numericrowheaders");
// load default value if no value is set
if (numrowheader.Trim().Length == 0)
numrowheader = confService.DefaultSettings["numericrowheaders"];
bool shownumrowheaders = numrowheader.ToLower().Equals("true") ? true : false; ///
cmddf.CommandSyntax = "rownames(" + objectname + ")";
object rowhdrobj = analytics.ExecuteR(cmddf, true, false);
string[] rowheaders;
if (rowhdrobj != null && !rowhdrobj.ToString().Contains("Error"))
{
if (rowhdrobj.GetType().IsArray)
rowheaders = (string[])rowhdrobj;
else
{
rowheaders = new string[1];
rowheaders[0] = rowhdrobj.ToString();
}
}
else
{
rowheaders = new string[dimrow];
for (int i = 0; i < dimrow; i++)
rowheaders[i] = (i + 1).ToString();
}
bool isnumericrowheaders = true; // assuming that row headers are numeric
short tnum;
for (int i = 0; i < dimrow; i++)
{
if (!Int16.TryParse(rowheaders[i], out tnum))
{
isnumericrowheaders = false; //row headers are non-numeric
break;
}
}
if (isnumericrowheaders && !shownumrowheaders)
{
for (int i = 0; i < dimrow; i++)
rowheaders[i] = "";
}
/// Populating array using data frame data
bool isRowEmpty = true;//for Virtual.
int emptyRowCount = 0;//for Virtual.
List<int> emptyRowIndexes = new List<int>(); //for Virtual.
string cellData = string.Empty;
for (int r = 1; r <= dimrow; r++)
{
isRowEmpty = true;//for Virtual.
for (int c = 1; c <= dimcol; c++)
{
if (dimcol == 1 && !dataclassname.ToLower().Equals("data.frame"))
cmddf.CommandSyntax = "as.character(" + objectname + "[" + r + "])";
else
cmddf.CommandSyntax = "as.character(" + objectname + "[" + r + "," + c + "])";
object v = analytics.ExecuteR(cmddf, true, false);
cellData = (v != null) ? v.ToString().Trim() : "";
data[r - 1, c - 1] = cellData;// v.ToString().Trim();
if (cellData.Length > 0)
isRowEmpty = false;
}
//for Virtual. // counting empty rows for virtual
if (isRowEmpty)
{
emptyRowCount++;
emptyRowIndexes.Add(r - 1);//making it zero based as in above nested 'for'
}
}
// whether you want C1Flexgrid to be generated by using XML DOM or by Virtual class(Dynamic)
bool DOMmethod = false;
if (DOMmethod)
{
//12Aug2014 Old way of creating grid using DOM and then creating and filling grid step by step
XmlDocument xdoc = createFlexGridXmlDoc(colheaders, rowheaders, data);
createFlexGrid(xdoc, lst, headername);// headername = 'varname' else 'leftvarname' else 'objclass'
}
else//virutal list method
{
if (emptyRowCount > 0)
{
int nonemptyrowcount = dimrow - emptyRowCount;
string[,] nonemptyrowsdata = new string[nonemptyrowcount, dimcol];
string[] nonemptyrowheaders = new string[nonemptyrowcount];
for (int rr = 0, rrr = 0; rr < data.GetLength(0); rr++)
{
if (emptyRowIndexes.Contains(rr))//skip empty rows.
continue;
for (int cc = 0; cc < data.GetLength(1); cc++)
{
nonemptyrowsdata[rrr, cc] = data[rr, cc];//only copy non-empty rows
}
nonemptyrowheaders[rrr] = rowheaders[rr];//copying row headers too.
rrr++;
}
//Using Dynamic Class creation and then populating the grid. //12Aug2014
CreateDynamicClassFlexGrid(headername, colheaders, nonemptyrowheaders, nonemptyrowsdata, lst);
}
else
{
//Using Dynamic Class creation and then populating the grid. //12Aug2014
CreateDynamicClassFlexGrid(headername, colheaders, rowheaders, data, lst);
}
}
if (ow != null)//22May2014
SendToOutput("", ref lst, ow);//send dataframe/matrix/array to output window or disk file
}
REngine engine;
private void InitializeRDotNet()
{
REngine.SetEnvironmentVariables();
engine = REngine.GetInstance();
// REngine requires explicit initialization.
// You can set some parameters.
engine.Initialize();
//load BSky and R packages
engine.Evaluate("library(BlueSky)");
engine.Evaluate("library(foreign)");
engine.Evaluate("library(data.table)");
engine.Evaluate("library(RODBC)");
engine.Evaluate("library(car)");
engine.Evaluate("library(aplpack)");
engine.Evaluate("library(mgcv)");
engine.Evaluate("library(rgl)");
engine.Evaluate("library(gmodels)");
}
private void RDotNetOpenDataset()
{
//open dataset
engine.Evaluate("d2 <- BSkyloadDataset('D:/BlueSky/Projects/Xtras_Required/Data_Files/cars.sav', filetype='SPSS', worksheetName=NULL, replace_ds=FALSE, csvHeader=TRUE, datasetName='Dataset1' )");
}
private void DisposeRDotNet()
{
engine.Dispose();
}
private void RDotNetExecute(OutputWindow ow)
{
CommandOutput lst = new CommandOutput();
lst.IsFromSyntaxEditor = true;
engine.Evaluate("BSky_One_Way_Anova = as.data.frame (summary(dd <- aov(mpg ~ year,data=Dataset1))[[1]])");
engine.Evaluate("bskyfrmtobj <- BSkyFormat(BSky_One_Way_Anova)");
CharacterMatrix cmatrix = engine.Evaluate("bskyfrmtobj").AsCharacterMatrix();
string[,] mtx = new string[cmatrix.RowCount, cmatrix.ColumnCount];
for (int r = 0; r < cmatrix.RowCount; r++)
{
for (int c = 0; c < cmatrix.ColumnCount; c++)
{
mtx[r, c] = cmatrix[r, c];
}
}
string objectname = "bskyfrmtobj";
string headername = "This is generated in R.NET";
CommandRequest cmddf = new CommandRequest();
int dimrow = 1, dimcol = 1;
bool rowexists = false, colexists = false;
string dataclassname = string.Empty;
//Find class of data passed. data.frame, matrix, or array
cmddf.CommandSyntax = "class(" + objectname + ")"; // Row exists
object retres = engine.Evaluate(cmddf.CommandSyntax).AsCharacter()[0];
if (retres != null)
dataclassname = retres.ToString();
//find if dimension exists
cmddf.CommandSyntax = "!is.na(dim(" + objectname + ")[1])"; // Row exists
rowexists = engine.Evaluate(cmddf.CommandSyntax).AsLogical()[0];
cmddf.CommandSyntax = "!is.na(dim(" + objectname + ")[2])";// Col exists
colexists = engine.Evaluate(cmddf.CommandSyntax).AsLogical()[0];
/// Find size of matrix(objectname) & initialize data array ///
if (rowexists)
{
cmddf.CommandSyntax = "dim(" + objectname + ")[1]";
retres = engine.Evaluate(cmddf.CommandSyntax).AsInteger()[0];
if (retres != null)
dimrow = Int16.Parse(retres.ToString());
}
if (colexists)
{
cmddf.CommandSyntax = "dim(" + objectname + ")[2]";
retres = engine.Evaluate(cmddf.CommandSyntax).AsInteger()[0];
if (retres != null)
dimcol = Int16.Parse(retres.ToString());
}
string[,] data = new string[dimrow, dimcol];
//// now create FlexGrid and add to lst ///
/////////finding Col headers /////
cmddf.CommandSyntax = "colnames(" + objectname + ")";
CharacterVector colhdrobj = engine.Evaluate(cmddf.CommandSyntax).AsCharacter();
string[] colheaders;
if (colhdrobj != null && !colhdrobj.ToString().Contains("Error"))
{
if (true)//colhdrobj.GetType().IsArray)
{
int siz = colhdrobj.Count();
colheaders = new string[siz];
for (int ri = 0; ri < siz; ri++)
{
colheaders[ri] = colhdrobj[ri];
}
}
else
{
colheaders = new string[1];
colheaders[0] = colhdrobj.ToString();
}
}
else
{
colheaders = new string[dimcol];
for (int i = 0; i < dimcol; i++)
colheaders[i] = (i + 1).ToString();
}
//read configuration and then decide to pull row headers
bool shownumrowheaders = true; ///
cmddf.CommandSyntax = "rownames(" + objectname + ")";
CharacterVector rowhdrobj = engine.Evaluate(cmddf.CommandSyntax).AsCharacter();
string[] rowheaders;
if (rowhdrobj != null && !rowhdrobj.ToString().Contains("Error"))
{
if (true)
{
int siz = rowhdrobj.Count();
rowheaders = new string[siz];
for (int ri = 0; ri < siz; ri++)
{
rowheaders[ri] = rowhdrobj[ri];
}
}
else
{
rowheaders = new string[1];
rowheaders[0] = rowhdrobj.ToString();
}
}
else
{
rowheaders = new string[dimrow];
for (int i = 0; i < dimrow; i++)
rowheaders[i] = (i + 1).ToString();
}
bool isnumericrowheaders = true; // assuming that row headers are numeric
short tnum;
for (int i = 0; i < dimrow; i++)
{
if (!Int16.TryParse(rowheaders[i], out tnum))
{
isnumericrowheaders = false; //row headers are non-numeric
break;
}
}
if (isnumericrowheaders && !shownumrowheaders)
{
for (int i = 0; i < dimrow; i++)
rowheaders[i] = "";
}
/// Populating array using data frame data
bool isRowEmpty = true;//for Virtual.
int emptyRowCount = 0;//for Virtual.
List<int> emptyRowIndexes = new List<int>(); //for Virtual.
string cellData = string.Empty;
for (int r = 1; r <= dimrow; r++)
{
isRowEmpty = true;//for Virtual.
for (int c = 1; c <= dimcol; c++)
{
if (dimcol == 1 && !dataclassname.ToLower().Equals("data.frame"))
cmddf.CommandSyntax = "as.character(" + objectname + "[" + r + "])";
else
cmddf.CommandSyntax = "as.character(" + objectname + "[" + r + "," + c + "])";
object v = engine.Evaluate(cmddf.CommandSyntax).AsCharacter()[0];
cellData = (v != null) ? v.ToString().Trim() : "";
data[r - 1, c - 1] = cellData;
if (cellData.Length > 0)
isRowEmpty = false;
}
//for Virtual. // counting empty rows for virtual
if (isRowEmpty)
{
emptyRowCount++;
emptyRowIndexes.Add(r - 1);//making it zero based as in above nested 'for'
}
}
// whether you want C1Flexgrid to be generated by using XML DOM or by Virtual class(Dynamic)
bool DOMmethod = false;
if (DOMmethod)
{
//12Aug2014 Old way of creating grid using DOM and then creating and filling grid step by step
XmlDocument xdoc = createFlexGridXmlDoc(colheaders, rowheaders, data);
createFlexGrid(xdoc, lst, headername);// headername = 'varname' else 'leftvarname' else 'objclass'
}
else//virutal list method
{
if (emptyRowCount > 0)
{
int nonemptyrowcount = dimrow - emptyRowCount;
string[,] nonemptyrowsdata = new string[nonemptyrowcount, dimcol];
string[] nonemptyrowheaders = new string[nonemptyrowcount];
for (int rr = 0, rrr = 0; rr < data.GetLength(0); rr++)
{
if (emptyRowIndexes.Contains(rr))//skip empty rows.
continue;
for (int cc = 0; cc < data.GetLength(1); cc++)
{
nonemptyrowsdata[rrr, cc] = data[rr, cc];//only copy non-empty rows
}
nonemptyrowheaders[rrr] = rowheaders[rr];//copying row headers too.
rrr++;
}
//Using Dynamic Class creation and then populating the grid. //12Aug2014
CreateDynamicClassFlexGrid(headername, colheaders, nonemptyrowheaders, nonemptyrowsdata, lst);
}
else
{
//Using Dynamic Class creation and then populating the grid. //12Aug2014
CreateDynamicClassFlexGrid(headername, colheaders, rowheaders, data, lst);
}
}
if (ow != null)//22May2014
SendToOutput("", ref lst, ow);//send dataframe/matrix/array to output window or disk file
}
//15Apr2014. List location 1 will have listname and number of tables it caontains. Location 2 onwards are tables. 1 table per location.
private void FormatBSkyList2(CommandOutput lst, string objectname, string headername, OutputWindow ow) // for BSky list2 processing
{
MessageBox.Show(this, "BSkyList2 Processing... close this box");
}
private void SendErrorToOutput(string ewmessage, OutputWindow ow) //03Jul2013 error warning message
{
object o;
CommandRequest cmd = new CommandRequest();
string sinkfilename = confService.GetConfigValueForKey("tempsink");//23nov2012
string sinkfilefullpathname = Path.Combine(BSkyAppData.RoamingUserBSkyTempPath, sinkfilename);
// load default value if no path is set or invalid path is set
if (sinkfilefullpathname.Trim().Length == 0 || !IsValidFullPathFilename(sinkfilefullpathname, false))
{
MessageBox.Show(this, BSky.GlobalResources.Properties.Resources.tempsinkConfigKeyNotFound);
return;
}
OpenSinkFile(@sinkfilefullpathname, "wt"); //06sep2012
SetSink(); //06sep2012
cmd.CommandSyntax = "write(\"" + ewmessage + ".\",fp)";// command
o = analytics.ExecuteR(cmd, false, false);
ResetSink();//06sep2012
CloseSinkFile();//06sep2012
CreateOuput(ow);//06sep2012
}
//18Dec2013 Sending command to output to make them appear different than command-output
private void SendCommandToOutput(string command, string NameOfAnalysis)
{
string rcommcol = confService.GetConfigValueForKey("rcommcol");//23nov2012
byte red = byte.Parse(rcommcol.Substring(3, 2), NumberStyles.HexNumber);
byte green = byte.Parse(rcommcol.Substring(5, 2), NumberStyles.HexNumber);
byte blue = byte.Parse(rcommcol.Substring(7, 2), NumberStyles.HexNumber);
Color c = Color.FromArgb(255, red, green, blue);
CommandOutput lst = new CommandOutput();
lst.NameOfAnalysis = NameOfAnalysis; // left tree Parent
AUParagraph Title = new AUParagraph();
Title.Text = command; //right side contents
Title.FontSize = BSkyStyler.BSkyConstants.TEXT_FONTSIZE;
Title.textcolor = new SolidColorBrush(c);
Title.ControlType = "Command"; // left tree child
lst.Add(Title);
AddToSession(lst);
}
private void SplitBSkyFormat(string command, out string sub, out string varname, out string BSkyLeftVar)
{
/// patterns is like: "BSkyFormat(var.name <- func.name("
string pattern = @"BSkyFormat\(\s*[A-Za-z0-9_\.]+\s*(<-|=)\s*[A-Za-z0-9_\.]+\(";
int firstindex = command.IndexOf('(');
int lastindex = command.LastIndexOf(')');
sub = "";
varname = "";
BSkyLeftVar = "";
if (firstindex == -1 || lastindex == -1)//21May2014 This check is important to stop app crash.
{
return;
}
#region Finding what's passed in 'BSkyFormat(param)' as parameter.
sub = command.Substring(firstindex + 1, lastindex - firstindex - 1);
#endregion
#region Finding Leftvar in Leftvar <- BSkyFormat
///See if BSkyFormat is assigned to any leftvar. eg.. leftvar <- BSkyFormat(....)
int assignmentIndex, BSkyIndex;
BSkyLeftVar = "";
BSkyIndex = command.Trim().IndexOf("BSkyFormat");
assignmentIndex = command.Trim().LastIndexOf("<-", BSkyIndex);
if (assignmentIndex < 0)//arrow is not there
{
assignmentIndex = command.Trim().LastIndexOf("=", BSkyIndex);
}
if (assignmentIndex > 0)
{
///find 'leftvar' name now
BSkyLeftVar = command.Trim().Substring(0, assignmentIndex).Trim();
}
#endregion
#region Finding varname in BSkyFormat(varname <- data.frame(...) )
/// looking for parameter of type df <- data.frame(...)
bool str = Regex.IsMatch(command, pattern);
MatchCollection mc = Regex.Matches(command, pattern);
int asnmntindex = 0;
if (str)
{
asnmntindex = sub.IndexOf("<-");
if (asnmntindex < 0)
{
asnmntindex = sub.IndexOf('=');
}
varname = sub.Substring(0, asnmntindex);
}
else // for BSkyFormat(m) then varname = m
{
pattern = @"\s*\G[A-Za-z0-9_\.]+\s*[^\(\)\:,;=]?";
str = Regex.IsMatch(sub, pattern);
mc = Regex.Matches(sub, pattern);
if (str && mc.Count == 1 && (sub.Trim().Length == mc[0].ToString().Trim().Length))
{
varname = mc[0].ToString();
}
}
#endregion
varname = varname.Trim();//01Jul2013
return;
}
private void SplitBSkyFormatParams(string command, out string first, out string rest, out string usertitle)
{
string firstParam = string.Empty;//for object to be formatted
string restParams = string.Empty;//for remaining params
usertitle = string.Empty; //for title if passed in function call by the user.
//find header/title
int ttlidx = command.IndexOf("singleTableOutputHeader");
int eqlidx = 0;
int commaidx = 0;
int closebracketidx = 0;
int headerstartidx = 0;
int headerendidx = 0;//modify this to right value
if (ttlidx > 0) //if title is provided
{
eqlidx = command.IndexOf("=", ttlidx);
if (eqlidx > ttlidx)
{
headerstartidx = eqlidx + 1;
headerendidx = eqlidx + 1;//modify this to right value
commaidx = command.IndexOf(",", eqlidx);
closebracketidx = command.IndexOf(")", eqlidx);
if (commaidx > eqlidx) //comma is present
{
headerendidx = commaidx - 1;
}
else //comma not present so end marker is closing bracket
{
headerendidx = closebracketidx - 1;
}
}
usertitle = command.Substring(headerstartidx, (headerendidx - headerstartidx) + 1);
}
///Logic Starts
//look for first comma and split the parameters in two
int paramstart = command.IndexOf("BSkyFormat(") + 11;//11 is the length of BSkyFormat(
string allParams = command.Substring(paramstart, command.Length - 12); //ignore last ')'
int indexOfComma = -1;
int brackets = 0;
for (int idx = 0; idx < allParams.Length; idx++)
{
if (allParams.ElementAt(idx) == '(')
brackets++;
else if (allParams.ElementAt(idx) == ')')
brackets--;
else if (brackets == 0 && allParams.ElementAt(idx) == ',')
indexOfComma = idx;
else
continue;
if (brackets == 0 && indexOfComma > 0)
break;
}
///Logic Ends
if (indexOfComma < 0) // comma not found, means no other params are in this func call.
{
first = allParams;
rest = string.Empty;
}
else
{
first = allParams.Substring(0, indexOfComma);
rest = allParams.Substring(indexOfComma + 1);
}
}
private void ExecuteOtherCommand(OutputWindow ow, string stmt)
{
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Before Executing in R.", LogLevelEnum.Info);
#region Check open close brackets before executing
string unbalmsg;
if (!AreBracketsBalanced(stmt, out unbalmsg))//if unbalanced brackets
{
CommandRequest errmsg = new CommandRequest();
string fullmsg = "Error : " + unbalmsg;
errmsg.CommandSyntax = "write(\"" + fullmsg.Replace("<", "<").Replace('"', '\'') + "\",fp)";//
analytics.ExecuteR(errmsg, false, false); //for printing command in file
return;
}
#endregion
///if command is for loading dataset //
if (stmt.Contains("BSkyloadDataset("))
{
int indexofopening = stmt.IndexOf('(');
int indexofclosing = stmt.LastIndexOf(')');//27Apr2016 fixed. there could be more closing parenthesis. we want closing ')' of BSkloadDataset()
string[] parameters = stmt.Substring(indexofopening + 1, indexofclosing - indexofopening - 2).Split(',');
string filename = string.Empty;
foreach (string s in parameters)
{
if (s.Contains('/') || s.Contains('\\'))
filename = s.Replace('\"', ' ').Replace('\'', ' ');
}
if (filename.Contains("="))
{
filename = filename.Substring(filename.IndexOf("=") + 1);
}
FileOpenCommand fo = new FileOpenCommand();
fo.FileOpen(filename.Trim());
return;
}
///02Aug2016 if command is for close dataset //
if (stmt.Contains("BSkycloseDataset("))
{
string enclosedWithin = string.Empty;
if (stmt.Contains("'"))
enclosedWithin = "'";
else
{
if (stmt.Contains('"'))
enclosedWithin = "\"";
}
int indexofopening = stmt.IndexOf(enclosedWithin);
int indexofclosing = stmt.LastIndexOf(enclosedWithin);//27Apr2016 fixed. there could be more closing parenthesis. we want closing ')' of BSkloadDataset()
string datasetname = stmt.Substring(indexofopening + 1, indexofclosing - indexofopening - 1).Trim();
FileCloseCommand fc = new FileCloseCommand();
fc.CloseDatasetFromSyntax(datasetname);
return;
}
//09Aug2016 Adding mouse busy for commands below
BSkyMouseBusyHandler.ShowMouseBusy();
//This code is not supposed to do any sort processing. It just to puts sort images in col headers
if (stmt.Contains("%>% arrange("))
{
//get asc colnames from command
List<string> asccols = null;
//get desc colnames from command
List<string> desccols = null;
GetAscDescCols(stmt, out asccols, out desccols);
CommandExecutionHelper che = new CommandExecutionHelper();
che.SetSortColForSortIcon(asccols, desccols);
}
object o = null;
CommandRequest cmd = new CommandRequest();
if (stmt.Contains("BSkySortDataframe(") ||
stmt.Contains("BSkyComputeExpression(") || stmt.Contains("BSkyRecode("))
{
//RefreshOutputORDataset("", cmd, stmt);//ExecuteSynEdtrNonAnalysis
CommandExecutionHelper auacb = new CommandExecutionHelper();
UAMenuCommand uamc = new UAMenuCommand();
uamc.bskycommand = stmt;
uamc.commandtype = stmt;
auacb.ExeuteSingleCommandWithtoutXML(stmt);//auacb.ExecuteSynEdtrNonAnalysis(uamc);
auacb.Refresh_Statusbar();
//auacb = null;
}
else
{
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Executing in R.", LogLevelEnum.Info);
isVariable(ref stmt);///for checking if its variable then it must be enclosed within print();
//27May2015 check if command is graphic and get its height width and then reopen graphic device with new dimensions
if (lastcommandwasgraphic)//listed graphic
{
if (imgDim != null && imgDim.overrideImgDim)
{
CloseGraphicsDevice();
OpenGraphicsDevice(imgDim.imagewidth, imgDim.imageheight); // get image dimenstion from external source for this particular graphic.
}
}
cmd.CommandSyntax = stmt;// command
o = analytics.ExecuteR(cmd, false, false); //// get Direct Result and write in sink file
CommandRequest cmdprn = new CommandRequest();
if (o != null && o.ToString().Contains("Error"))//for writing some of the errors those are not taken care by sink.
{
cmdprn.CommandSyntax = "write(\"" + o.ToString() + "\",fp)";
o = analytics.ExecuteR(cmdprn, false, false); /// for printing command in file
///if there is error in assignment, like RHS caused error and LHS var is never updated
///Better make LHS var null.
string lhvar = string.Empty; //these statements are commented as we should not set any var to NULL, R doesn't.
GetLeftHandVar(stmt, out lhvar);
if (lhvar != null)
{
cmd.CommandSyntax = lhvar + " <- NULL";// assign null
o = analytics.ExecuteR(cmd, false, false);
}
}
}
BSkyMouseBusyHandler.HideMouseBusy();//This must be executed. Even if something fails above.
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: After Executing in R.", LogLevelEnum.Info);
}
private void GetAscDescCols(string commandstmt, out List<string> asccolnames, out List<string> desccolnames)
{
asccolnames = new List<string>();
desccolnames = new List<string>();
int strtidx = commandstmt.IndexOf("arrange(");
if (strtidx == -1) //arrange not found
{
return;
}
strtidx = strtidx + 8; // 8 = arrange(
int lastidx = commandstmt.LastIndexOf(")");
int len = lastidx - strtidx;
string substr = commandstmt.Substring(strtidx, len);
char[] separator = new char[] { ',' };
string[] allparams = substr.Split(separator); // here allparams are col names some may be enclosed in desc()
//Now separate them in ascending and descending
foreach (string col in allparams)
{
if (col.Contains("desc("))//col sort is a descending type
{
desccolnames.Add(col.Replace("desc(", "").Replace(")", "").Trim());//removing 'desc(' and ')'. Colname is left
}
else //ascending sort on these cols
{
asccolnames.Add(col);
}
}
}
private void GetLeftHandVar(string stmt, out string lhvar)
{
lhvar = null;//null if no left hand var exists in stmt
int eqidx = stmt.IndexOf("=");
int arrowidx = stmt.IndexOf("<-");
int lowestidx = 0;
bool isvarname = true; // assuming lefthand substring is variable.
if (eqidx < 0 && arrowidx < 0)//no "=" and no "<-"
return;
//if one of the index is -1 then better overwrite that with value of the other
if (eqidx == -1) eqidx = arrowidx;
else if (arrowidx == -1) arrowidx = eqidx;
//find the lowest(leftmost) index between = and <-
if (eqidx < arrowidx)
{
lowestidx = eqidx;// index of =
}
else
{
lowestidx = arrowidx;//index of <-
}
string subs = stmt.Substring(0, lowestidx).Trim();
//you can add more invalid chars to following 'if'
if (subs.Contains(" ") || subs.Contains("(") || subs.Contains(")") ||
subs.Contains("{") || subs.Contains("}")
)
{
isvarname = false;
}
if (isvarname)//if subs is variable
{
lhvar = subs;
}
}
///Finding if R command is a method call that can return some results.
private bool IsMethodName(string stmt)//01May2013
{
string pattern = @"\s*[A-Za-z0-9_\.]+\s*\(\s*";// method name patthern, methodName(
bool str = Regex.IsMatch(stmt, pattern);
MatchCollection mc = Regex.Matches(stmt.Trim(), pattern);
foreach (Match m in mc)
{
if (m.Index == 0)
return true;
}
return false;
}
//For Painting Output window for BSKyFormated object.
private void RefreshOutputORDataset(string objectname, CommandRequest cmd, string originalCommand, OutputWindow ow)
{
UAMenuCommand uamc = new UAMenuCommand();
cmd.CommandSyntax = "is.null(" + objectname + "$BSkySplit)";
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Executing : " + cmd.CommandSyntax, LogLevelEnum.Info);
bool isNonBSkyList = false;
object isNonBSkyListstr = analytics.ExecuteR(cmd, true, false);
if (isNonBSkyListstr != null && isNonBSkyListstr.ToString().ToLower().Equals("true"))
{
isNonBSkyList = true;
}
if (isNonBSkyList)
{
string ewmessage = BSky.GlobalResources.Properties.Resources.CantBSkyFormatErrorMsg;
SendErrorToOutput(ewmessage, ow);//03Jul2013
return;
}
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: $BSkySplit Result (false means non-bsky list): " + isNonBSkyList, LogLevelEnum.Info);
cmd.CommandSyntax = objectname + "$uasummary[[7]]";
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Executing : " + cmd.CommandSyntax, LogLevelEnum.Info);
string bskyfunctioncall = (string)analytics.ExecuteR(cmd, true, false);//actual call with values
if (bskyfunctioncall == null)
{
bskyfunctioncall = ""; //24Apr2014 This is when no Dataset is open.
}
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: $uasummary[[7]] Result : " + bskyfunctioncall, LogLevelEnum.Info);
string bskyfunctionname = "";
if (bskyfunctioncall.Length > 0)
{
if (bskyfunctioncall.Contains("("))
bskyfunctionname = bskyfunctioncall.Substring(0, bskyfunctioncall.IndexOf('(')).Trim();
else
bskyfunctionname = bskyfunctioncall;
}
uamc.commandformat = objectname;// object that stores the result of analysis
uamc.bskycommand = bskyfunctioncall.Replace('\"', '\'');// actual BSkyFunction call. " quotes replaced by '
uamc.commandoutputformat = bskyfunctionname.Length > 0 ? string.Format(@"{0}", BSkyAppData.BSkyAppDirConfigPath) + bskyfunctionname + ".xml" : "";//23Apr2015
uamc.commandtemplate = bskyfunctionname.Length > 0 ? string.Format(@"{0}", BSkyAppData.BSkyAppDirConfigPath) + bskyfunctionname + ".xaml" : "";//23Apr2015
uamc.commandtype = originalCommand;
CommandExecutionHelper auacb = new CommandExecutionHelper();
if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: CommandExecutionHelper: ", LogLevelEnum.Info);
auacb.ExecuteSyntaxEditor(uamc, saveoutput.IsChecked == true ? true : false);//10JAn2013 edit
auacb = null;
}
//was private
public void RefreshDatagrids()//16May2013
{
string stmt = "Refresh Grids";
UAMenuCommand uamc = new UAMenuCommand();
uamc.commandformat = stmt;
uamc.bskycommand = stmt;
uamc.commandtype = stmt;
//cmd.CommandSyntax = stmt;
CommandExecutionHelper auacb = new CommandExecutionHelper();
auacb.DatasetRefreshAndPrintTitle("Refresh Data");
//auacb = null;
}
//16Jul2015 refesh both grids when 'refresh' icon is clicked in output window
public void RefreshBothgrids()//16Jul2015
{
BSkyMouseBusyHandler.ShowMouseBusy();// ShowMouseBusy_old();
string stmt = "Refresh Grids";
UAMenuCommand uamc = new UAMenuCommand();
uamc.commandformat = stmt;
uamc.bskycommand = stmt;
uamc.commandtype = stmt;
CommandExecutionHelper auacb = new CommandExecutionHelper();
auacb.BothGridRefreshAndPrintTitle("Refresh Data");
BSkyMouseBusyHandler.HideMouseBusy();// HideMouseBusy_old();
}
private void isVariable(ref string stmt) // checks if user want to print a variable. Or function call results.
{
//// Check if its conditional command. Then dont enclose in print ////
bool iscondiORloop = false;
string _command = ExtractCommandName(stmt);//07sep2012
RCommandType rct = GetRCommandType(_command);
if (rct == RCommandType.CONDITIONORLOOP)
iscondiORloop = true;
////////////////
int frstopenbrkt = -2, secopenbrkt = -2, closingbrkt = -2, arowassignidx = -2, eqassignidx, assignidx = -2;
bool beginswithprint = stmt.StartsWith("print(");
bool beginswithopenparenthesis = stmt.StartsWith("(");
if (beginswithprint || beginswithopenparenthesis)
{
frstopenbrkt = stmt.IndexOf("(");
secopenbrkt = stmt.IndexOf("(", frstopenbrkt + 1);
}
else
{
secopenbrkt = stmt.IndexOf("(");
}
closingbrkt = stmt.IndexOf(")", secopenbrkt + 1);
bool hasassignmentoperator = (stmt.Contains("=") || stmt.Contains("<-"));
if (hasassignmentoperator && secopenbrkt > 0)
{
eqassignidx = stmt.IndexOf("=");
arowassignidx = stmt.IndexOf("<-");
if (eqassignidx > 0 && arowassignidx > 0) // both assignment oprator exists. say: a<-func(q=TRUE)
{
assignidx = eqassignidx < arowassignidx ? eqassignidx : arowassignidx; // whichever has less idx
}
else if (eqassignidx > 0) // only '=' exists
{
assignidx = eqassignidx;
}
else if (arowassignidx > 0)//only "<-" exists
{
assignidx = arowassignidx;
}
if (assignidx > secopenbrkt && closingbrkt > assignidx)//if closing to secopenbrkt closes after assignment'='
hasassignmentoperator = false;
}
bool beginswithcat = stmt.StartsWith("cat(");
if ((beginswithprint || beginswithopenparenthesis) && hasassignmentoperator) // for print(a<-c('msg')
{
int indexofopeningprintparenthesis = stmt.IndexOf('(');// first (
int indexofclosingprintparenthesis = stmt.LastIndexOf(')');// last )
int indexofassignmentopr = stmt.IndexOf("<-") > 0 ? stmt.IndexOf("<-") : stmt.IndexOf('=');
string varname = stmt.Substring(indexofopeningprintparenthesis + 1, (indexofassignmentopr - indexofopeningprintparenthesis - 1));// a
if (beginswithprint)
{
stmt = stmt.Remove(indexofclosingprintparenthesis).Replace("print(", "") + "; print(" + varname + ");";
}
else if (beginswithopenparenthesis)
{
stmt = stmt + "; print(" + varname + ");";// (a<-c('msg');) print(a);
}
}
if (!beginswithprint && !hasassignmentoperator && !beginswithcat && !iscondiORloop)// for a & a+ a+a+a*2 & help(...) & ?...
{
stmt = "print(" + stmt + ")";
}
}
// Check if command is one of : if, for, while, function
private bool isConditionalOrLoopingCommand(string extractedCommand)//07Sep2012
{
bool iscondloop = false;
if (extractedCommand.Equals("function(") || extractedCommand.Equals("for(") ||
extractedCommand.Equals("while(") || extractedCommand.Equals("if(") ||
extractedCommand.Equals("{") ||
extractedCommand.Equals("local("))
{
iscondloop = true;
}
return iscondloop;
}
// Creating global list of graphic command in begining //
private void LoadRegisteredGraphicsCommands(string grpListPath)//07Sep2012
{
registeredGraphicsList.Clear();//clearing just as precaution. Not actually needed
string line;
string[] lineparts;
char[] separators = new char[] { ',' };//{',', ' ', ';'};
string keyGraphicCommand;
int grphwidth = -1, grphheight = -1; // -1 means use defauls from the options setting.
StreamReader f = null;
try
{
f = new StreamReader(grpListPath);
while ((line = f.ReadLine()) != null)
{
grphwidth = -1; grphheight = -1;
if (line.Trim().Length > 0)//do not add blank lines
{
if (line.Trim().StartsWith("#"))//commented line in GraphicCommandList.txt. Only single line comment is supported.
continue;
lineparts = (line.Trim()).Split(separators);
keyGraphicCommand = lineparts[0].Trim();
if (lineparts.Length > 1 && lineparts[1] != null && lineparts[1].Trim().Length > 0)//get width from file(line)
{
Int32.TryParse(lineparts[1], out grphwidth);//try setting width from file.
}
if (lineparts.Length > 2 && lineparts[2] != null && lineparts[2].Trim().Length > 0)//get height from file(line)
{
if (!Int32.TryParse(lineparts[2], out grphheight))//if conversion fails
{
if (grphwidth > 0)
grphheight = grphwidth; // make height same as width, if height is not provided
}
}
//now add three values to dictionary
if (!registeredGraphicsList.ContainsKey(keyGraphicCommand)) // if the key is not already present. Unique keys are entertained.
registeredGraphicsList.Add(keyGraphicCommand, new ImageDimensions() { imagewidth = grphwidth, imageheight = grphheight });
}
}
f.Close();
}
catch (Exception e)
{
MessageBox.Show(this, BSky.GlobalResources.Properties.Resources.ErrOpeningRegGrpLst+"\n" + e.Message);
logService.WriteToLogLevel("Registered Graphics List not found!", LogLevelEnum.Error);
}
}
ImageDimensions imgDim; //store image dimentions of current graphic, from graphiccommand.txt
bool lastcommandwasgraphic = false;
// Check if graphic command belongs to global list of graphic command //
private bool isGraphicCommand(string extractedCommand)//07Sep2012
{
string command = extractedCommand.Replace('(', ' ').Trim(); //remove the open parenthesis from the end.
//// Extracting command from statement /////
//// searching list ////
bool graphic = false;
string tempcomm;
if (registeredGraphicsList.ContainsKey(command))
{
registeredGraphicsList.TryGetValue(command, out imgDim);
graphic = true;
}
lastcommandwasgraphic = graphic;
return graphic;
}
//if command is single command(or may be 2 lines one for BSkyFormat) then find if XML template is defined
private bool isXMLDefined()
{
bool hasXML = false;
if (DlgProp != null)
hasXML = DlgProp.IsXMLDefined;
return hasXML;
}
// Extracts command name in format like :- "any.command("
private string ExtractCommandName(string stmt)
{
string comm = string.Empty;
stmt = RemoveExtraSpacesBeforeOpeningBracket(stmt);
string pattern = @"[A-Za-z0-9_.]+\(";
bool com = Regex.IsMatch(stmt, pattern);
if (com)//remove extra spaces
{
MatchCollection mc = Regex.Matches(stmt, pattern);
foreach (Match m in mc)
{
comm = m.Value;//picking up the very first command only. Which should be one of
break; // if(, for(, while(, function( or plot( etc..
}
}
else//28Aug2014 if no command name was found return the same string that was received as a parameter
{
comm = stmt;
}
return comm.Trim();
}
private string RemoveExtraSpacesBeforeOpeningBracket(string stmt)
{
string spacelessstmt = stmt;
string pattern = @"[A-Za-z0-9_.]+\s+\(";
bool spaces = Regex.IsMatch(stmt, pattern);
if (spaces)//remove extra spaces
{
MatchCollection mc = Regex.Matches(stmt, pattern);
spacelessstmt = Regex.Replace(stmt, @"\s+\(", "(", RegexOptions.None);
}
return spacelessstmt;
}
private void createAUPara(string auparas, CommandOutput lst)
{
string startdatetime = string.Empty;
if (lst.NameOfAnalysis == null || lst.NameOfAnalysis.Trim().Length < 1)
{
lst.NameOfAnalysis = "R-Output";//Parent Node name. 02Aug2012
}
if (auparas == null || auparas.Trim().Length < 1)
return;
string selectnode = "bskyoutput/bskyanalysis/aup";
string AUPara = "<aup>" + auparas.Replace("&", "&").Replace("<", "<").Replace(">", ">") + "</aup>";
XmlDocument xd = null;
///// Creating DOM for generation output ///////
string fulldom = "<bskyoutput> <bskyanalysis>" + AUPara + "</bskyanalysis> </bskyoutput>";
xd = new XmlDocument(); xd.LoadXml(fulldom);
//// for creating AUPara //////////////
BSkyOutputGenerator bsog = new BSkyOutputGenerator();
int noofaup = xd.SelectNodes(selectnode).Count;// should be 3
for (int k = 1; k <= noofaup; k++)
{
if (lst.NameOfAnalysis.Equals("R-Output") || lst.NameOfAnalysis.Contains("Command Editor Execution"))
{
lst.Add(bsog.createAUPara(xd, selectnode + "[" + (1) + "]", ""));
}
else if (lst.NameOfAnalysis.Equals("Datasets"))
{
lst.Add(bsog.createAUPara(xd, selectnode + "[" + (1) + "]", "Open Datasets"));
}
else
{
//for (int k = 1; k <= noofaup; k++)
lst.Add(bsog.createAUPara(xd, selectnode + "[" + k + "]", startdatetime));
}
}
}
private void createBSkyGraphic(Image img, CommandOutput lst)//30Aug2012
{
lst.NameOfAnalysis = "R-Graphics";
BSkyGraphicControl bsgc = new BSkyGraphicControl();
bsgc.BSkyImageSource = img.Source;
bsgc.ControlType = "Graphic";
lst.Add(bsgc);
}
private void createDiskFileFromImageSource(BSkyGraphicControl bsgc)
{
Image myImage = new System.Windows.Controls.Image();
myImage.Source = bsgc.BSkyImageSource;
string grpcntrlimgname = confService.GetConfigValueForKey("bskygrphcntrlimage");//23nov2012
string grpctrlimg = Path.Combine(BSkyAppData.RoamingUserBSkyTempPath, grpcntrlimgname);
// load default value if no path is set or invalid path is set
if (grpctrlimg.Trim().Length == 0 || !IsValidFullPathFilename(grpctrlimg, false))
{
MessageBox.Show(this, BSky.GlobalResources.Properties.Resources.bskygrphctrlimgConfigKeyNotFound);
return;
}
System.Windows.Media.Imaging.BitmapImage bitmapImage = new System.Windows.Media.Imaging.BitmapImage();
bitmapImage = ((System.Windows.Media.Imaging.BitmapImage)myImage.Source);
System.Windows.Media.Imaging.PngBitmapEncoder pngBitmapEncoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
System.IO.FileStream stream = new System.IO.FileStream(@grpctrlimg, FileMode.Create);
pngBitmapEncoder.Interlace = PngInterlaceOption.On;
pngBitmapEncoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bitmapImage));
pngBitmapEncoder.Save(stream);
stream.Flush();
stream.Close();
}
private XmlDocument createFlexGridXmlDoc(string[] colheaders, string[] rowheaders, string[,] data)
{
XmlDocument xd = new XmlDocument();
int rc = rowheaders.Length;
int cc = colheaders.Length;
string colnames = "<table cellpadding=\"5\" cellspacing=\"0\"><thead><tr><th class=\"h\"></th>";
foreach (string s in colheaders)
{
if (s == null || s.Trim().Length < 1)
colnames = colnames + "<th class=\"c\">" + ".-." + "</th>";//".-.'" is spl char sequence that tells that there is no header
else
colnames = colnames + "<th class=\"c\">" + s + "</th>";
}
colnames = colnames + "</tr></thead>";
//// creating row headers with data ie.. one complete row ////
string rowdata = "<tbody>";
for (int r = 0; r < rc; r++)
{
//Putting Row Header in a row. ".-.'" is spl char sequence that tells that there is no header
if (bsky_no_row_header)
{
rowdata = rowdata + "<tr><td class=\"h\">" + ".-." + "</td>";//rowheader in row
}
else
{
rowdata = rowdata + "<tr><td class=\"h\">" + rowheaders[r] + "</td>";//rowheader in row
}
//Putting Data in a row
for (int c = 0; c < cc; c++)/// data in row
{
rowdata = rowdata + "<td class=\"c\">" + data[r, c].Replace("<", "<").Replace(">", ">") + "</td>";
}
rowdata = rowdata + "</tr>";
}
rowdata = rowdata + "</tbody></table>";
string fullxml = colnames + rowdata;
xd.LoadXml(fullxml);
return xd;
}
private void createFlexGrid(XmlDocument xd, CommandOutput lst, string header)
{
AUXGrid xgrid = new AUXGrid();
AUGrid c1FlexGrid1 = xgrid.Grid;// new C1flexgrid.
xgrid.Header.Text = header;//FlexGrid header as well as Tree leaf node text(ControlType)
var gridfilter = new C1FlexGridFilter(xgrid.Grid);
BSkyOutputGenerator bsog = new BSkyOutputGenerator();
bsog.html2flex(xd, c1FlexGrid1);
lst.Add(xgrid);
}
#region Dynamic Class creation and filling C1Flexgrid
private void CreateDynamicClassFlexGrid(string header, string[] colheaders, string[] rowheaders, string[,] data, CommandOutput lst)
{
IList list;
AUXGrid xgrid = new AUXGrid();
AUGrid c1FlexGrid1 = xgrid.Grid;// new C1flexgrid.
xgrid.Header.Text = header;//FlexGrid header as well as Tree leaf node text(ControlType)
///////////// merge and sizing /////
c1FlexGrid1.AllowMerging = AllowMerging.ColumnHeaders | AllowMerging.RowHeaders;
c1FlexGrid1.AllowSorting = true;
c1FlexGrid1.MaxHeight = 800;// NoOfRows* EachRowHeight;
c1FlexGrid1.MaxWidth = 1000;
int nrows = data.GetLength(0);
int ncols = data.GetLength(1);
//// Dynamic class logic
FGDataSource ds = new FGDataSource();
ds.RowCount = nrows;
ds.Data = data;
foreach (string s in colheaders)
{
ds.Variables.Add(s.Trim());
}
list = new DynamicList(ds);
if (list != null)
{
c1FlexGrid1.ItemsSource = list;
}
FillColHeaders(colheaders, c1FlexGrid1);
FillRowHeaders(rowheaders, c1FlexGrid1);
lst.Add(xgrid);
}
private void FillColHeaders(string[] colHeaders, AUGrid c1fgrid)
{
bool iscolheaderchecked = true;// rowheaderscheck.IsChecked == true ? true : false;
//creating row headers
string[,] colheadersdata = new string[1, colHeaders.Length];
////creating data
for (int r = 0; r < colheadersdata.GetLength(0); r++)
{
for (int c = 0; c < colheadersdata.GetLength(1); c++)
{
colheadersdata[r, c] = colHeaders[c];
}
}
//create & fill row headers
bool fillcolheaders = iscolheaderchecked;
if (fillcolheaders)
{
var FGcolheaders = c1fgrid.ColumnHeaders;
FGcolheaders.Rows[0].AllowMerging = true;
FGcolheaders.Rows[0].HorizontalAlignment = HorizontalAlignment.Center;
for (int i = FGcolheaders.Columns.Count; i < colheadersdata.GetLength(1); i++)
{
C1.WPF.FlexGrid.Column col = new C1.WPF.FlexGrid.Column();
col.AllowMerging = true;
col.VerticalAlignment = VerticalAlignment.Top;
FGcolheaders.Columns.Add(col);
}
for (int i = FGcolheaders.Rows.Count; i < colheadersdata.GetLength(0); i++)
{
C1.WPF.FlexGrid.Row row = new C1.WPF.FlexGrid.Row();
FGcolheaders.Rows.Add(row);
row.AllowMerging = true;
}
//fill row headers
for (int i = 0; i < colheadersdata.GetLength(0); i++)
for (int j = 0; j < colheadersdata.GetLength(1); j++)
{
if (colheadersdata[i, j] != null && colheadersdata[i, j].Trim().Equals(".-."))
FGcolheaders[i, j] = "";//14Jul2014 filling empty header
else
FGcolheaders[i, j] = colheadersdata[i, j];
}
}
}
private void FillRowHeaders(string[] rowHeaders, AUGrid c1fgrid)
{
bool isrowheaderchecked = true;// rowheaderscheck.IsChecked == true ? true : false;
//creating row headers
string[,] rowheadersdata = new string[rowHeaders.Length, 1];
////creating data
for (int r = 0; r < rowheadersdata.GetLength(0); r++)
{
for (int c = 0; c < rowheadersdata.GetLength(1); c++)
{
rowheadersdata[r, c] = rowHeaders[r];
}
}
//create & fill row headers
bool fillrowheaders = isrowheaderchecked;
if (fillrowheaders)
{
var FGrowheaders = c1fgrid.RowHeaders;
FGrowheaders.Columns[0].AllowMerging = true;
FGrowheaders.Columns[0].VerticalAlignment = VerticalAlignment.Top;
FGrowheaders.Columns[0].Width = new GridLength(70);
for (int i = FGrowheaders.Columns.Count; i < rowheadersdata.GetLength(1); i++)
{
C1.WPF.FlexGrid.Column col = new C1.WPF.FlexGrid.Column();
col.AllowMerging = true;
col.VerticalAlignment = VerticalAlignment.Top;
col.Width = new GridLength(70);
FGrowheaders.Columns.Add(col);
}
for (int i = FGrowheaders.Rows.Count; i < rowheadersdata.GetLength(0); i++)
{
C1.WPF.FlexGrid.Row row = new C1.WPF.FlexGrid.Row();
row.AllowMerging = true;
FGrowheaders.Rows.Add(row);
}
//fill row headers
for (int i = 0; i < rowheadersdata.GetLength(0); i++)
for (int j = 0; j < rowheadersdata.GetLength(1); j++)
{
if (rowheadersdata[i, j] != null && rowheadersdata[i, j].Trim().Equals(".-."))
FGrowheaders[i, j] = "";//14Jul2014 filling empty header
else
FGrowheaders[i, j] = rowheadersdata[i, j];
}
}
}
#endregion
private void browse_Click(object sender, RoutedEventArgs e)
{
string FileNameFilter = "BlueSky Format, that can be opened in Output Window later (*.bsoz)|*.bsoz|Comma Seperated (*.csv)|*.csv|HTML (*.html)|*.html"; //BSkyOutput
SaveFileDialog saveasFileDialog = new SaveFileDialog();
saveasFileDialog.Filter = FileNameFilter;
bool? output = saveasFileDialog.ShowDialog(Application.Current.MainWindow);
if (output.HasValue && output.Value)
{
try
{
if (File.Exists(saveasFileDialog.FileName))
{
File.Delete(saveasFileDialog.FileName);
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message);
logService.WriteToLogLevel(ex.Message, LogLevelEnum.Error);
return;
}
fullpathfilename.Text = saveasFileDialog.FileName;
}
}
public void PasteSyntax(string command)//29Jan2013
{
string newlines = (inputTextbox.Text != null && inputTextbox.Text.Trim().Length > 0) ? "\n\n" : string.Empty;
if (command != null && command.Length > 0)
inputTextbox.AppendText(newlines + command);
}
//Not in Use
private void save_Click(object sender, RoutedEventArgs e)
{
//////// Active output window ///////
OutputWindowContainer owc = (LifetimeService.Instance.Container.Resolve<IOutputWindowContainer>()) as OutputWindowContainer;
OutputWindow ow = owc.ActiveOutputWindow as OutputWindow; //get currently active window
if (saveoutput.IsChecked == true)
ow.DumpAllAnalyisOuput(fullfilepathname, fileformat, extratags);
}
private bool IsValidFullPathFilename(string path, bool filemustexist)
{
bool validDir, validFile;
string message = string.Empty;
string dir = Path.GetDirectoryName(path);
string filename = Path.GetFileName(path);
///Check filename
if (filemustexist && !File.Exists(path))
{
validFile = false;
message = BSky.GlobalResources.Properties.Resources.invalidFilename+" " + filename;
}
else
validFile = true;
//// Check Directory path
if (Directory.Exists(dir) || dir.Trim().Length == 0)
{
validDir = true;
}
else
{
message = message + " "+BSky.GlobalResources.Properties.Resources.invalidDir+" " + dir;
validDir = false;
}
if (message.Trim().Length > 0)
{
//MessageBox.Show(message);
logService.Warn(message);
}
return (validDir && validFile);
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (this.Visibility == System.Windows.Visibility.Visible)//Do this only if Syn Edtr is visible.
{
this.Activate();
System.Windows.Forms.DialogResult dresult = System.Windows.Forms.DialogResult.OK;
if (Modified)
{
dresult = System.Windows.Forms.MessageBox.Show(
BSky.GlobalResources.Properties.UICtrlResources.REditorCloseSaveScriptPrompt,
BSky.GlobalResources.Properties.Resources.SaveExitCommandEditor,
System.Windows.Forms.MessageBoxButtons.YesNoCancel,
System.Windows.Forms.MessageBoxIcon.Question);
}
if (dresult == System.Windows.Forms.DialogResult.Cancel)//dont close
{
e.Cancel = true; // do not close this window
this.SEForceClose = false;
}
else
{
///before closing save R scripts in Syntax Editor text area..13Feb2013
if (dresult == System.Windows.Forms.DialogResult.Yes)//Save
SyntaxEditorSaveAs();
/// Do hide OR hide & close ///
inputTextbox.Text = string.Empty; //Clean window
this.Visibility = System.Windows.Visibility.Hidden;// hide window. If you close down you can't reopen it again.
if (!this.SEForceClose)
e.Cancel = true;//stop closing
Modified = false;
Title = BSky.GlobalResources.Properties.UICtrlResources.CommandEditorPanelTitle+" Window";
}
}
}
//clears the command area
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
if (Modified)//if any modification done to command scripts after last Save
{ //allow user to save changes before opening another command script
System.Windows.Forms.DialogResult dresult = System.Windows.Forms.MessageBox.Show(
BSky.GlobalResources.Properties.UICtrlResources.REditorCloseSaveScriptPrompt,
BSky.GlobalResources.Properties.UICtrlResources.REditorSavePromptMsgBoxTitle,
System.Windows.Forms.MessageBoxButtons.YesNoCancel,
System.Windows.Forms.MessageBoxIcon.Question);
if (dresult == System.Windows.Forms.DialogResult.Yes)//Yes Save- and Close
{
SyntaxEditorSaveAs();
}
else if (dresult == System.Windows.Forms.DialogResult.No)//No Save- but Close
{
}
else//no Save no Close
{
return;
}
}
inputTextbox.Text = string.Empty;
this.Activate();
}
private void MenuItemOpen_Click(object sender, RoutedEventArgs e)
{
SyntaxEditorOpen();
this.Activate();//19Feb2013
}
private void MenuItemSaveAs_Click(object sender, RoutedEventArgs e)
{
SyntaxEditorSaveAs();
this.Activate();//19Feb2013
}
private void SyntaxEditorOpen()
{
if (Modified)//if any modification done to command scripts after last Save
{ //allow user to save changes before opening another command script
System.Windows.Forms.DialogResult dresult = System.Windows.Forms.MessageBox.Show(
BSky.GlobalResources.Properties.Resources.SaveScriptPromptBeforeOpen,
BSky.GlobalResources.Properties.UICtrlResources.REditorSavePromptMsgBoxTitle,
System.Windows.Forms.MessageBoxButtons.YesNoCancel,
System.Windows.Forms.MessageBoxIcon.Question);
if (dresult == System.Windows.Forms.DialogResult.Yes)//Yes Save- and Close
{
SyntaxEditorSaveAs();
}
else if (dresult == System.Windows.Forms.DialogResult.No)//No Save- but Close
{
}
else//no Save no Close
{
return;
}
}
const string FileNameFilter = "BSky R scripts, (*.bsr)|*.bsr"; //BSkyR
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = FileNameFilter;
bool? output = openFileDialog.ShowDialog(Application.Current.MainWindow);
if (output.HasValue && output.Value)
{
System.IO.StreamReader file = new System.IO.StreamReader(openFileDialog.FileName);
inputTextbox.Text = file.ReadToEnd();
file.Close();
}
Modified = false;//19Feb2013 Newly loaded script can only be modified after loading finishes.
Title = BSky.GlobalResources.Properties.UICtrlResources.CommandEditorPanelTitle + " Window"; //19Feb2013
}
private void SyntaxEditorSaveAs()
{
const string FileNameFilter = "BSky R scripts, (*.bsr)|*.bsr"; //BSkyR
SaveFileDialog saveasFileDialog = new SaveFileDialog();
saveasFileDialog.Filter = FileNameFilter;
bool? output = saveasFileDialog.ShowDialog(Application.Current.MainWindow);
if (output.HasValue && output.Value)
{
System.IO.StreamWriter file = new System.IO.StreamWriter(saveasFileDialog.FileName);
file.WriteLine(inputTextbox.Text);
file.Close();
}
Modified = false;//19Feb2013 currently saving. So immediately after save there are no new changes/modifications.
Title = BSky.GlobalResources.Properties.UICtrlResources.CommandEditorPanelTitle + " Window"; //19Feb2013
}
//19Feb2013 If anybody edits/changes something in text-area
private void inputTextbox_TextChanged(object sender, TextChangedEventArgs e)
{
Modified = true;
Title = BSky.GlobalResources.Properties.UICtrlResources.CommandEditorPanelTitle +" - < unsaved script >";
}
private void Refresh_Click(object sender, RoutedEventArgs e)
{
RefreshDatagrids();
}
//17May2013
public void ShowWindowLoadFile()
{
try
{
System.IO.StreamReader file = new System.IO.StreamReader(DoubleClickedFilename);
inputTextbox.Text = file.ReadToEnd();
file.Close();
Modified = false;
Title = BSky.GlobalResources.Properties.UICtrlResources.CommandEditorPanelTitle + " Window";
this.Show();
}
catch
{
logService.WriteToLogLevel("Error Opening file by double click", LogLevelEnum.Error);
}
}
}
public class ImageDimensions
{
public int imagewidth { get; set; }
public int imageheight { get; set; }
public bool overrideImgDim
{
get
{
if (imagewidth > -1 && imageheight > -1)
{
return true;
}
else
{
return false;
}
}
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AutoFollow : MonoBehaviour
{
[Tooltip("被跟随的物体")]
public GameObject followed;
[Tooltip("间隔距离")]
public float follow_distance;
[Tooltip("距离多远时停止跟随")]
public float stop_distance;
private bool is_following;
// Update is called once per frame
void Update()
{
InputController.GetKey();
if (InputController.mouseDown)
{
is_following = false;
}
Vector3 offset = followed.transform.position - transform.position;
if (Math.Abs(offset.x) > follow_distance)
{
is_following = true;
}
if (Math.Abs(offset.x) <= (stop_distance + 0.1) && is_following)
{
gameObject.GetComponent<DogMoving>().SendMessage("StopMoving");
is_following = false;
}
#region 跟随某物体移动
if (is_following)
{
gameObject.GetComponent<DogMoving>().SendMessage("StartMoving");
Vector3 target;
if (offset.x > 0)
{
target = new Vector3(followed.transform.position.x - stop_distance, followed.transform.position.y, followed.transform.position.z);
}
else
{
target = new Vector3(followed.transform.position.x + stop_distance, followed.transform.position.y, followed.transform.position.z);
}
GetComponent<DogMoving>().SendMessage("MoveTo", target);
}
#endregion
}
}
|
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using RabbitMQ.Client.Framing.Impl;
namespace Rabbit.Receiver
{
class Program
{
// need to know the end point I am subscribing to
private static string exchangeName = "someExchange";
// note that we cannot really assing a queue name in this case as we are doing multiple subscribers (pub / sub)
// if the name of the queue is hard coded the second subscriber will have the same queue (pissibly with different bindings) as compared with the first subscriber)
// therefore we allow the subscirber to set up the queue name that it deems necessarty.
//private static string queueName = "someQueue";
static void Main(string[] args)
{
var factory = new ConnectionFactory() {HostName = "localhost"};
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.ExchangeDeclare(exchangeName, "topic");
Console.WriteLine("Enter queue name (RabbitMQ will create if does not exist)");
var queueName = Console.ReadLine();
bool durable = true;
channel.QueueDeclare(queueName, durable, false, false, null);
// var queueName = channel.QueueDeclare().QueueName;
channel.CreateBasicProperties().SetPersistent(true);
Console.WriteLine("subscribed to queue {0}", queueName);
// check in case the user has forgotten to input the arguments
if (args.Length < 1)
{
Console.WriteLine("need arguments, what do you want to bind this queue to?");
Console.WriteLine("About to exit of here");
Environment.ExitCode = 1;
Console.ReadLine();
return;
}
// this is where the binding happens.
// Binding in thsi context has nothing to do with MS binding. In this case the binding is the connection between the message and the queue that each consumer will get.
foreach (var keys in args)
{
channel.QueueBind(queueName, exchangeName, keys);
Console.WriteLine("{0} now bound to {1}", queueName, keys);
}
var consumer = new QueueingBasicConsumer(channel);
Console.WriteLine("consumer up and running, waiting for messages");
// this is where we state that we will send acknowledgement back, otherwise pull will make the message disappear
bool NoAck = false;
channel.BasicConsume(queueName, NoAck, consumer);
// this is where the messages are retrieved
while (true)
{
var ea = (BasicDeliverEventArgs) consumer.Queue.Dequeue();
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
var routingKey = ea.RoutingKey;
Console.WriteLine("Received message {0} : {1}", message, routingKey);
channel.BasicAck(ea.DeliveryTag, false);
}
}
}
}
private static string GetMessage(string[] args)
{
// the API for the routing keys is to send messages associated with channels.
// e.g. rabbit.sender some.channel.here
// the subscirber can hook to #.here or to some.*.here
// allowing extra flexibility and reduced coupling
// With binding keys we instead need to know exacltly what we are subscribing to.
return ((args.Length > 0) ? string.Join(" ", args) : "This works!!");
}
}
}
|
using System;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using System.Collections.Generic;
namespace BuildingGame
{
class MapObject
{
Map map;
Cell[,] cells;
Sprite sprite;
public MapObject()
{
}
public virtual void PlaceOnMap(Map map, Cell[,] cells)
{
this.map = map;
this.cells = cells;
map.AddObject(this);
}
public virtual void Update(float tick)
{
}
public virtual void Draw(SpriteBatch spriteBatch, Map map)
{
Vector2 origin = cells[0, 0].Position;
if (map.Rotation == 0)
origin = cells[0, 0].Position;
else if (map.Rotation == 1)
origin = cells[cells.GetLength(0) - 1, 0].Position;
else if (map.Rotation == 2)
origin = cells[cells.GetLength(0) - 1, cells.GetLength(1) - 1].Position;
else if (map.Rotation == 3)
origin = cells[0, cells.GetLength(1) - 1].Position;
sprite.Draw(spriteBatch, map.CalcWorldToScreen(origin));
}
public Map Map
{
get
{
return map;
}
set
{
map = value;
}
}
public Cell[,] Cells
{
get
{
return cells;
}
set
{
cells = value;
}
}
public Sprite Sprite
{
get
{
return sprite;
}
set
{
sprite = value;
}
}
}
} |
using System;
using System.Linq;
using System.Windows.Forms;
using TY.SPIMS.Client.Returns;
using TY.SPIMS.Controllers;
using TY.SPIMS.POCOs;
using TY.SPIMS.Utilities;
using TY.SPIMS.Controllers.Interfaces;
namespace TY.SPIMS.Client.Controls
{
public partial class SalesReturnControl : UserControl, IRefreshable
{
private readonly ICustomerController customerController;
private readonly ISalesReturnController salesReturnController;
public SalesReturnControl()
{
this.customerController = IOC.Container.GetInstance<CustomerController>();
this.salesReturnController = IOC.Container.GetInstance<SalesReturnController>();
InitializeComponent();
}
#region Load
private void SalesReturnControl_Load(object sender, EventArgs e)
{
if (!UserInfo.IsAdmin)
DeleteButton.Visible = false;
LoadCustomers();
CustomerDropdown.Focus();
}
private void LoadCustomers()
{
customerDisplayModelBindingSource.DataSource = this.customerController.FetchAllCustomers();
CustomerDropdown.SelectedIndex = -1;
}
private void LoadSalesReturn(SalesReturnFilterModel filter)
{
int records = 0;
long elapsedTime = ClientHelper.PerformFetch(() =>
{
var results = this.salesReturnController.FetchSalesReturnWithSearch(filter);
salesReturnDisplayModelBindingSource.DataSource = results;
if (salesReturnDisplayModelBindingSource.Count == 0)
salesReturnDetailModelBindingSource.DataSource = null;
records = results.Count;
});
((MainForm)this.ParentForm).AttachStatus(records, elapsedTime);
}
private SalesReturnFilterModel ComposeSearch()
{
SalesReturnFilterModel model = new SalesReturnFilterModel();
if (CustomerDropdown.SelectedIndex != -1)
model.CustomerId = (int)CustomerDropdown.SelectedValue;
if (!string.IsNullOrWhiteSpace(MemoTextbox.Text))
model.MemoNumber = MemoTextbox.Text.Trim();
if (!AllDateRB.Checked)
{
if (DateRangeRB.Checked)
{
model.DateType = DateSearchType.DateRange;
model.DateFrom = DateFromPicker.Value;
model.DateTo = DateToPicker.Value;
}
}
else
model.DateType = DateSearchType.All;
if (!AllStatusRB.Checked)
{
if (UsedStatusRB.Checked)
model.Status = ReturnStatusType.Used;
else
model.Status = ReturnStatusType.Unused;
}
else
model.Status = ReturnStatusType.All;
return model;
}
private void SearchButton_Click(object sender, EventArgs e)
{
SalesReturnFilterModel filter = ComposeSearch();
LoadSalesReturn(filter);
}
#endregion
#region Details
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count > 0)
{
DataGridViewRow row = dataGridView1.SelectedRows[0];
int id = (int)row.Cells[SalesReturnIdColumn.Name].Value;
salesReturnDetailModelBindingSource.DataSource = this.salesReturnController.FetchSalesReturnDetails(id);
paymentCreditModelBindingSource.DataSource = this.salesReturnController.FetchPaymentDetails(id);
}
}
#endregion
#region Clear
private void ClearButton_Click(object sender, EventArgs e)
{
ClearSearch();
}
private void ClearSearch()
{
CustomerDropdown.ComboBox.SelectedIndex = -1;
CustomerDropdown.SelectedIndex = -1;
MemoTextbox.Clear();
AllDateRB.Checked = true;
DateToPicker.Value = DateTime.Now;
DateFromPicker.Value = DateTime.Now;
}
#endregion
#region Add/Edit Sales Return
private void AddButton_Click(object sender, EventArgs e)
{
OpenForm(0);
}
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex != -1 && e.ColumnIndex != -1)
{
int id = (int)dataGridView1.Rows[e.RowIndex].Cells[SalesReturnIdColumn.Name].Value;
bool? credited = this.salesReturnController.IsItemCredited(id);
if (credited != null && credited.Value)
{
if(ClientHelper.ShowConfirmMessage("Sales return is already included in a payment. Do you want to continue?") != DialogResult.Yes)
return;
}
OpenForm(id);
}
}
int selectedId = 0;
private void OpenForm(int id)
{
selectedId = id;
Form addForm = this.ParentForm.OwnedForms.FirstOrDefault(a => a.Name == "AddSalesReturnForm");
if (addForm == null)
{
AddSalesReturnForm form = new AddSalesReturnForm();
form.ReturnId = id;
form.Owner = this.ParentForm;
form.SalesReturnUpdated += new SalesReturnUpdatedEventHandler(form_SalesReturnUpdated);
form.Show();
}
else
{
AddSalesReturnForm openedForm = (AddSalesReturnForm)addForm;
openedForm.ReturnId = id;
openedForm.LoadSalesReturnDetails();
openedForm.Focus();
}
}
void form_SalesReturnUpdated(object sender, EventArgs e)
{
SalesReturnFilterModel filter = ComposeSearch();
LoadSalesReturn(filter);
if (selectedId == 0)
salesReturnDisplayModelBindingSource.Position = salesReturnDisplayModelBindingSource.Count - 1;
else
{
SalesReturnDisplayModel item = ((SortableBindingList<SalesReturnDisplayModel>)salesReturnDisplayModelBindingSource.DataSource)
.FirstOrDefault(a => a.Id == selectedId);
int index = salesReturnDisplayModelBindingSource.IndexOf(item);
salesReturnDisplayModelBindingSource.Position = index;
dataGridView1.Rows[index].Selected = true;
}
}
#endregion
#region IRefreshable Members
public void RefreshView()
{
SalesReturnFilterModel filter = ComposeSearch();
LoadSalesReturn(filter);
}
#endregion
private void DeleteButton_Click(object sender, EventArgs e)
{
if (!UserInfo.IsAdmin)
{
ClientHelper.ShowErrorMessage("You are not authorized to delete this record.");
return;
}
if (dataGridView1.SelectedRows.Count > 0)
{
int id = (int)dataGridView1.SelectedRows[0].Cells[SalesReturnIdColumn.Name].Value;
bool? credited = this.salesReturnController.IsItemCredited(id);
if (credited != null && credited.Value)
{
ClientHelper.ShowErrorMessage("Sales return is already included in a payment.");
return;
}
if (ClientHelper.ShowConfirmMessage("Are you sure you want to delete this return?") == DialogResult.Yes)
{
this.salesReturnController.DeleteSalesReturn(id);
ClientHelper.ShowSuccessMessage("Sales return deleted successfully.");
this.RefreshView();
}
}
}
}
}
|
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace VoxelSpace.SceneGraph {
using Graphics;
public abstract class SceneRenderer<T> : IDisposable where T : Scene {
public Camera Camera;
public ShadowMap ShadowMap { get; protected set; }
public void Render(T scene) {
PreRender(scene);
var graphics = G.Graphics;
if (ShadowMap != null) {
graphics.SetRenderTarget(ShadowMap.ShadowTarget);
graphics.Clear(new Color(0x00000000));
Render(scene, RenderPass.Shadow);
}
graphics.SetRenderTarget(null);
graphics.Clear(Color.CornflowerBlue);
Render(scene, RenderPass.Geometry);
}
protected abstract void Render(T scene, RenderPass pass);
public virtual void Dispose() {
ShadowMap?.Dispose();
}
public virtual void OnScreenResize(int width, int height) {}
protected virtual void PreRender(T scene) {}
public void ApplyCamera() {
}
}
} |
using EntityFrameworkCore.BootKit;
using ExpressionEvaluator;
using Newtonsoft.Json.Linq;
using Quickflow.Core;
using Quickflow.Core.Entities;
using Quickflow.Core.Interfacess;
using Quickflow.Core.Utilities;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Text;
using System.Threading.Tasks;
namespace Quickflow.ActivityRepository
{
public class DecisionActivity : EssentialActivity, IWorkflowActivity
{
public async Task Run(Database dc, Workflow wf, ActivityInWorkflow activity, ActivityInWorkflow preActivity)
{
// find a first TURE statement
bool decision = false;
for (int i = 0; i < activity.Options.Count; i++)
{
var option = activity.Options[i];
var cc = new CompiledExpression() { StringToParse = option.Value };
object input = JObject.FromObject(activity.Input.Data).ToObject<ExpandoObject>();
cc.RegisterType("Input", input);
cc.RegisterDefaultTypes();
decision = (bool)cc.Eval();
if (decision)
{
activity.NextActivityId = option.Key;
activity.Output = activity.Input;
break;
}
}
}
}
}
|
using AspNetMvcSample.Core.Data.Repositories;
using AspNetMvcSample.Data.Repositories;
using AspNetMvcSample.References;
using Autofac;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AspNetMvcSample.Capsule.Modules
{
public class RepositoryCapsuleModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterAssemblyTypes(ReferencedAssemblies.Repositories).
Where(_ => _.Name.EndsWith("Repository")).
AsImplementedInterfaces().
InstancePerLifetimeScope();
builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IRepository<>)).InstancePerDependency();
//builder.RegisterGeneric(typeof(ContactRepository)).As(typeof(IContactRepository)).InstancePerDependency();
}
}
} |
using Microsoft.Azure.ServiceBus;
using Microsoft.Extensions.Options;
using System;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace Frank.Scheduler.Api.ServiceBus
{
public class ServiceBusService : IServiceBusService
{
private readonly ServiceBusConfiguration _options;
public ServiceBusService(IOptions<ServiceBusConfiguration> options)
{
_options = options.Value;
}
public async Task<Message> SendMessage<T>(Guid messageId, string messageLabel, T body) =>
await SendMessage(new Message(JsonSerializer.SerializeToUtf8Bytes(body))
{
Label = messageLabel,
ContentType = "application/json",
MessageId = messageId.ToString(),
TimeToLive = TimeSpan.FromHours(1)
});
public async Task<Message> SendMessage(Guid messageId, string messageLabel, string messageBody) =>
await SendMessage(new Message(Encoding.UTF8.GetBytes(messageBody))
{
Label = messageLabel,
ContentType = "application/json",
MessageId = messageId.ToString(),
TimeToLive = TimeSpan.FromHours(1)
});
private async Task<Message> SendMessage(Message message)
{
var topicClient = new TopicClient(_options.Endpoint, _options.TopicName, RetryPolicy.Default);
await topicClient.SendAsync(message);
return message;
}
}
}
|
using Microsoft.EntityFrameworkCore;
using SocialApp.API.Data;
using SocialApp.API.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Threading.Tasks;
namespace SocialApp.API.Authorization
{
public class AuthRepository : IAuthRepository
{
public readonly AppDataContext dataContext;
public AuthRepository(AppDataContext context)
{
dataContext = context;
}
public async Task<User> Login(string username, string password)
{
var user = await dataContext.Users
.Include(c => c.Photos)
.FirstOrDefaultAsync(c => c.Username == username);
if(user == null)
{
return null;
}
if(!VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt))
{
return null;
}
return user;
}
public async Task<User> Register(User user, string password)
{
byte[] passwordHash, passwordSalt;
CreatePasswordHash(password, out passwordHash, out passwordSalt);
user.PasswordHash = passwordHash;
user.PasswordSalt = passwordSalt;
await dataContext.Users.AddAsync(user);
await dataContext.SaveChangesAsync();
return user;
}
public async Task<bool> UserExists(string username)
{
if(await dataContext.Users.AnyAsync(c => c.Username == username))
{
return true;
}
return false;
}
private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
{
using (var hmac = new HMACSHA512(passwordSalt))
{
var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
for (int i = 0; i < computedHash.Length; i++)
{
if(computedHash[i] != passwordHash[i])
{
return false;
}
}
return true;
}
}
private void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
{
using (var hmac = new HMACSHA512())
{
passwordSalt = hmac.Key;
passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
}
}
}
}
|
using Newtonsoft.Json;
namespace SecureNetRestApiSDK.Api.Models
{
public class Schedule
{
#region Properties
[JsonProperty("amount")]
public double Amount { get; set; }
[JsonProperty("installmentDate")]
public string InstallmentDate { get; set; }
[JsonProperty("installmentNum")]
public int InstallmentNum { get; set; }
[JsonProperty("numOfRetries")]
public int NumOfRetries { get; set; }
[JsonProperty("paid")]
public bool Paid { get; set; }
[JsonProperty("paymentdate")]
public object Paymentdate { get; set; }
[JsonProperty("paymentMethodId")]
public string PaymentMethodId { get; set; }
[JsonProperty("processed")]
public bool Processed { get; set; }
[JsonProperty("scheduleId")]
public int ScheduleId { get; set; }
[JsonProperty("transcationId")]
public int TranscationId { get; set; }
#endregion
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using DelftTools.Functions.Generic;
using DelftTools.TestUtils;
using log4net;
using log4net.Config;
using NUnit.Framework;
using Rhino.Mocks.Exceptions;
namespace DelftTools.Functions.Tests
{
[TestFixture]
public class MultiDimensionalArrayViewTest
{
private static readonly ILog log = LogManager.GetLogger(typeof(MultiDimensionalArrayViewTest));
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
LogHelper.ConfigureLogging();
}
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
LogHelper.ResetLogging();
}
[Test]
public void Add()
{
IMultiDimensionalArray<int> array = new MultiDimensionalArray<int>();
IMultiDimensionalArrayView view = new MultiDimensionalArrayView(array, 0, int.MinValue, int.MaxValue);
view.Add(4);
Assert.AreEqual(1, view.Count);
Assert.AreEqual(1, array.Count);
}
[Test]
public void ClearView()
{
IMultiDimensionalArray<int> array = new MultiDimensionalArray<int> { 1, 2, 3, 4, 5 };
IMultiDimensionalArrayView view = new MultiDimensionalArrayView(array, 0, 1, 2);
view.Clear();
Assert.AreEqual(0, view.Count);
Assert.AreEqual(3, array.Count);
Assert.IsTrue(new[] { 1, 4, 5 }.SequenceEqual(array));
}
[Test]
public void ConvertToListUsingCopyConstructor()
{
MultiDimensionalArray array = new MultiDimensionalArray<double>(2);
IMultiDimensionalArray<double> view = new MultiDimensionalArrayView<double>(array);
view[0] = 10;
view[1] = 5;
var arrayList = new ArrayList(view);
Assert.AreEqual(10, arrayList[0]);
Assert.AreEqual(5, arrayList[1]);
}
[Test]
public void ConvertToListUsingCopyConstructorGeneric()
{
IList<int> values = new List<int> { 1, 2, 3, 4 };
MultiDimensionalArray array = new MultiDimensionalArray<int>(values, new[] { 1, 4 });
IMultiDimensionalArray<int> view = new MultiDimensionalArrayView<int>(array);
IList array1D = new List<int>(view);
Assert.AreEqual(4, array1D.Count);
Assert.AreEqual(4, array1D[3]);
Assert.AreEqual(2, array1D[1]);
}
[Test]
public void Count()
{
//array = 1,2,3,4,5
IMultiDimensionalArray<int> array = new MultiDimensionalArray<int> { 1, 2, 3, 4, 5 };
//view = 2,3
IMultiDimensionalArrayView<int> view = new MultiDimensionalArrayView<int>(array, 0, 1, 2);
Assert.AreEqual(2, view.Count);
}
[Test]
public void Create()
{
IMultiDimensionalArray array = new MultiDimensionalArray(new[] { 2, 2 });
array[0, 0] = 1;
array[0, 1] = 2;
array[1, 0] = 3;
array[1, 1] = 4;
IMultiDimensionalArrayView view = new MultiDimensionalArrayView();
view.Parent = array;
//why not same?? If i resize parent i do expect the subarray to be resize as well.
//the values should be the same but not the reference
Assert.AreNotSame(array.Shape, view.Shape);
Assert.IsTrue(view.Shape.SequenceEqual(array.Shape));
Assert.AreEqual(array.Count, view.Count);
Assert.AreEqual(array.Rank, view.Rank);
Assert.AreEqual(array.DefaultValue, view.DefaultValue);
//subArray should have offsetStarts of MinValue and offsetEnds as MaxValue
//so it will resize along with the parent
Assert.IsTrue(view.OffsetStart.SequenceEqual(new[] { int.MinValue, int.MinValue }));
Assert.IsTrue(view.OffsetEnd.SequenceEqual(new[] { int.MaxValue, int.MaxValue }));
//assert values are equal
Assert.AreEqual(array[0, 0], view[0, 0]);
Assert.AreEqual(array[0, 1], view[0, 1]);
Assert.AreEqual(array[1, 0], view[1, 0]);
Assert.AreEqual(array[1, 1], view[1, 1]);
}
[Test]
public void GenericFiltered()
{
IMultiDimensionalArray<double> array = new MultiDimensionalArray<double>(3);
array[0] = 1;
array[1] = 2;
array[2] = 3;
var view = array.Select(0, new[] { 1 });
Assert.AreEqual(2, view[0]);
}
[Test]
public void IndexOf()
{
IMultiDimensionalArray<double> array = new MultiDimensionalArray<double>(3);
array[0] = 1;
array[1] = 2;
array[2] = 3;
var view = array.Select(0, new[] { 1 });
Assert.AreEqual(0, view.IndexOf(2));
}
[Test]
public void Remove()
{
IMultiDimensionalArray<double> array = new MultiDimensionalArray<double>(3);
array[0] = 1;
array[1] = 2;
array[2] = 3;
var view = array.Select(0, new[] { 1 });
view.Remove(2);
Assert.AreEqual(2, array.Count);
Assert.AreEqual(new[] {1.0, 3.0}, array);
}
[Test]
public void InsertAt()
{
IMultiDimensionalArray<double> array = new MultiDimensionalArray<double>(6);
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;
array[5] = 6;
var view = array.Select(0, new[] {0, 2, 4});
view.InsertAt(0, 3); //insert at end
Assert.AreEqual(7, array.Count);
Assert.AreEqual(new[] { 1.0, 2.0, 3.0, 4.0, 5.0, 0.0, 6.0}, array); //Ambiguous!
}
[Test]
[ExpectedException(typeof(IndexOutOfRangeException))]
public void OutOfRangeForChildArray()
{
///create a 2D grid and slice rows and columns
/// 1 2
/// 3 4
IMultiDimensionalArray array = new MultiDimensionalArray(2, 2);
array[0, 0] = 1;
array[0, 1] = 2;
array[1, 0] = 4;
array[1, 1] = 5;
//create a subarray of the top left corner
// 1 |2|
// 4 |5|
//
IMultiDimensionalArray subArray = array.Select(1, 1, 1);
subArray[1, 1] = 5; // <= exception
}
[Test]
public void ReduceArray()
{
// create a 2D grid and slice rows and columns
// 1 2 3
// 4 5 6
// 7 8 9
IMultiDimensionalArray array = new MultiDimensionalArray(3, 3);
array[0, 0] = 1;
array[0, 1] = 2;
array[0, 2] = 3;
array[1, 0] = 4;
array[1, 1] = 5;
array[1, 2] = 6;
array[2, 0] = 7;
array[2, 1] = 8;
array[2, 2] = 9;
//create a reduced array containing the first row
var view = array.Select(0, 0, 0);
view.Reduce[0] = true; //reduce the x dimension
Assert.AreEqual(1, view.Rank);
Assert.AreEqual(new[] { 3 }, view.Shape);
Assert.AreEqual(2, view[1]);
}
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void ReduceOnWrongDimensionThrowsAnException()
{
var array = new MultiDimensionalArray(3, 3);
var subArray = array.Select(0, 0, 1);
subArray.Reduce[0] = true; //try to reduce the first dimension
}
[Test]
public void ReduceWithNonExistentIndex()
{
var array = new MultiDimensionalArray(3, 3);
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
array[i, j] = i*3 + j;
var subArray = new MultiDimensionalArrayView(array);
subArray.SelectedIndexes[0] = new int[] { 3 }; //set non-existent index
subArray.Reduce[0] = true; //try to reduce the first dimension
subArray.Count.Should("Count should be 0").Be.EqualTo(0);
foreach(var value in subArray) //should be empty list
throw new ExpectationViolationException("Shouldn't return any values");
}
[Test]
public void ReduceBeforeAddingValuesAndGetValuesAfterwards()
{
var array = new MultiDimensionalArray(3, 3);
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
array[i, j] = i * 3 + j;
var subArray = new MultiDimensionalArrayView(array);
subArray.SelectedIndexes[0] = new int[] { 3 }; //set non-existent index
subArray.Reduce[0] = true; //try to reduce the first dimension
//we can't get any values
subArray.Count.Should("Count should be 0").Be.EqualTo(0);
foreach(var value in subArray)
throw new ExpectationViolationException("Shouldn't return any values");
//add the index the view is looking for
array.InsertAt(0,3);
array[3, 0] = 9;
array[3, 1] = 10;
array[3, 2] = 11;
//and now we can get values
subArray.Count.Should("Count should be 3").Be.EqualTo(3);
int actualCount = subArray.Cast<object>().Count();
actualCount.Should("Actual count should be 3").Be.EqualTo(3);
}
[Test]
public void ReduceWithEmptyIndex()
{
var array = new MultiDimensionalArray(3,3);
var subArray = new MultiDimensionalArrayView(array);
//set empty index
subArray.SelectedIndexes[0] = new int[]{};
subArray.Reduce[0] = true; //try to reduce the first dimension
subArray.Count.Should("Count should be 0").Be.EqualTo(0);
foreach (var value in subArray) //should be empty list
throw new ExpectationViolationException("Shouldn't return any values");
}
[Test]
public void RemoveAt()
{
//array = 1,2,3,4,5
IMultiDimensionalArray<int> array = new MultiDimensionalArray<int> { 1, 2, 3, 4, 5 };
//view = 2,3
IMultiDimensionalArrayView<int> view = new MultiDimensionalArrayView<int>(array, 0, 1, 2);
Assert.IsTrue(new[] { 2, 3 }.SequenceEqual(view));
view.RemoveAt(0);
//array = 1,3,4,5
//view = 3
Assert.AreEqual(1, view.Count);
Assert.AreEqual(4, array.Count);
Assert.IsTrue(new[] { 3 }.SequenceEqual(view));
Assert.IsTrue(new[] { 1, 3, 4, 5 }.SequenceEqual(array));
view.RemoveAt(0);
Assert.AreEqual(0, view.Count);
Assert.AreEqual(3, array.Count);
Assert.IsTrue(new[] { 1, 4, 5 }.SequenceEqual(array));
}
[Test]
public void ResizeParentAndUpdateShapeOfSubArray()
{
//create a 2D grid of 3x3
IMultiDimensionalArray array = new MultiDimensionalArray(3, 3);
//select rows [1, 2). So skip the first row
IMultiDimensionalArray subArray = array.Select(0, 1, int.MaxValue);
Assert.IsTrue(subArray.Shape.SequenceEqual(new[] { 2, 3 }));
//resize the parent. Add one row and one column. Check the shape of the subArray changes
array.Resize(new[] { 4, 4 });
Assert.IsTrue(subArray.Shape.SequenceEqual(new[] { 3, 4 }));
}
[Test]
public void Select()
{
// create a 2D grid and slice rows and columns
//
// 1 2 3
// 4 5 6
// 7 8 9
//
IMultiDimensionalArray array = new MultiDimensionalArray(3, 3);
array[0, 0] = 1; // row 0
array[0, 1] = 2;
array[0, 2] = 3;
array[1, 0] = 4; // row 1
array[1, 1] = 5;
array[1, 2] = 6;
array[2, 0] = 7; // row 2
array[2, 1] = 8;
array[2, 2] = 9;
Assert.AreEqual(9, array.Count);
Assert.AreEqual(2, array[0, 1]);
IMultiDimensionalArrayView subArray;
// a new array is the middle column of our grid
//
// 1 [2] 3
// 4 [5] 6
// 7 [8] 9
// ^
subArray = array.Select(new[] { int.MinValue, 1 }, new[] { int.MaxValue, 1 });
Assert.AreEqual(3, subArray.Shape[0]);
Assert.AreEqual(1, subArray.Shape[1]);
Assert.AreEqual(int.MinValue, subArray.OffsetStart[0]);
Assert.AreEqual(int.MaxValue, subArray.OffsetEnd[0]);
Assert.AreEqual(1, subArray.OffsetStart[1]);
Assert.AreEqual(1, subArray.OffsetEnd[1]);
// check values
Assert.AreEqual(2, subArray[0, 0]);
Assert.AreEqual(5, subArray[1, 0]);
Assert.AreEqual(8, subArray[2, 0]);
// 1 [2] 3
// 4 [5] 6
// 7 [8] 9
// ^
subArray = array.Select(1, 1, 1); // select 2st column, slicing
Assert.AreEqual(3, subArray.Shape[0]);
Assert.AreEqual(1, subArray.Shape[1]);
Assert.AreEqual(int.MinValue, subArray.OffsetStart[0]);
Assert.AreEqual(int.MaxValue, subArray.OffsetEnd[0]);
Assert.AreEqual(1, subArray.OffsetStart[1]);
Assert.AreEqual(1, subArray.OffsetEnd[1]);
// 1 [2 3)
// 4 [5 6)
// 7 [8 9)
// ^
subArray = array.Select(1, 1, int.MaxValue);
Assert.AreEqual(3, subArray.Shape[0]);
Assert.AreEqual(2, subArray.Shape[1]);
Assert.AreEqual(int.MinValue, subArray.OffsetStart[0]);
Assert.AreEqual(int.MaxValue, subArray.OffsetEnd[0]);
Assert.AreEqual(1, subArray.OffsetStart[1]);
Assert.AreEqual(int.MaxValue, subArray.OffsetEnd[1]);
}
[Test]
public void SelectARow()
{
var array = new MultiDimensionalArray(2, 3);
// 1 2 3 1 2 3
// 4 5 6 ==>
array[0, 0] = 1;
array[0, 1] = 2;
array[0, 2] = 3;
array[1, 0] = 4;
array[1, 1] = 5;
array[1, 2] = 6;
// select the first index of the first dimension (e.g. the row)
var row = array.Select(0, new[] { 0 });
row.Reduce[0] = true;
Assert.AreEqual(new[] { 1, 2, 3 }, row);
}
[Test]
public void SelectOnMultipleIndexes()
{
// more complex example (isn't it another test?)
var array = new MultiDimensionalArray(3, 3);
// 1 9 2 1 2
// 9 9 9 ==>
// 3 9 4 3 4
array[0, 0] = 1;
array[0, 1] = 9;
array[0, 2] = 2;
array[1, 0] = 9;
array[1, 1] = 9;
array[1, 2] = 9;
array[2, 0] = 3;
array[2, 1] = 9;
array[2, 2] = 4;
IMultiDimensionalArrayView view = array.Select(0, new[] { 0, 2 }).Select(1, new[] { 0, 2 });
Assert.IsTrue(new[] { 2, 2 }.SequenceEqual(view.Shape));
Assert.AreEqual(4, view.Count);
Assert.AreEqual(1, view[0, 0]);
Assert.AreEqual(2, view[0, 1]);
Assert.AreEqual(3, view[1, 0]);
Assert.AreEqual(4, view[1, 1]);
}
[Test]
public void SelectUsingIndexes()
{
IMultiDimensionalArray array = new MultiDimensionalArray(3);
array[0] = 1;
array[1] = 2;
array[2] = 3;
IMultiDimensionalArrayView view = array.Select(0, new[] { 0, 2 });
// Select first and last element
Assert.AreEqual(2, view.Count);
Assert.AreEqual(1, view[0]);
Assert.AreEqual(3, view[1]);
Assert.AreEqual(3, view.MaxValue);
Assert.AreEqual(1, view.MinValue);
}
[Test]
public void ShapeCalculationWithStartAndEndOffset()
{
IMultiDimensionalArray array = new MultiDimensionalArray(3, 3);
//skip first element in both dimensions
IMultiDimensionalArrayView subArray = new MultiDimensionalArrayView(array);
subArray.OffsetStart[0] = 1;
subArray.OffsetStart[1] = 1;
Assert.IsTrue(subArray.Shape.SequenceEqual(new int[2] { 2, 2 }));
//skip last element for both dimensions
subArray = new MultiDimensionalArrayView(array);
subArray.OffsetEnd[0] = 1;
subArray.OffsetEnd[1] = 1;
Assert.IsTrue(subArray.Shape.SequenceEqual(new int[2] { 2, 2 }));
//skip last and first element for both dimensions
subArray = new MultiDimensionalArrayView(array);
subArray.OffsetEnd[0] = 1;
subArray.OffsetEnd[1] = 1;
subArray.OffsetStart[0] = 1;
subArray.OffsetStart[1] = 1;
Assert.IsTrue(subArray.Shape.SequenceEqual(new int[2] { 1, 1 }));
//skip first element in both dimensions and resize parent
subArray = new MultiDimensionalArrayView(array);
subArray.OffsetStart[0] = 1;
subArray.OffsetStart[1] = 1;
//resize the parent array
array.Resize(new[] { 4, 4 });
Assert.IsTrue(subArray.Shape.SequenceEqual(new int[2] { 3, 3 }));
}
[Test]
public void StrideCalculation()
{
IMultiDimensionalArray array = new MultiDimensionalArray(new[] { 6, 1 });
IMultiDimensionalArray array2 = new MultiDimensionalArray(new[] { 6, 3 });
//reduce the 2nd dimension to only the 1st element. So it resembles the array
IMultiDimensionalArray view = new MultiDimensionalArrayView(array2, 1, 0, 0);
Assert.AreEqual(array.Stride, view.Stride);
}
[Test]
public void ToString()
{
IMultiDimensionalArray<int> array = new MultiDimensionalArray<int> { 1, 2, 3, 4, 5 };
IMultiDimensionalArrayView view = new MultiDimensionalArrayView(array, 0, 1, 2);
string s = view.ToString();
Assert.IsTrue(s.Contains(2.ToString()));
Assert.IsTrue(s.Contains(3.ToString()));
Assert.IsFalse(s.Contains(1.ToString()));
Assert.IsFalse(s.Contains(4.ToString()));
Assert.IsFalse(s.Contains(5.ToString()));
}
[Test]
public void UseEnumeratorOnMultiDimensionalArrayView()
{
// Setup an array
// 1 2 -
// 3 4 -
// - - -
IMultiDimensionalArray<double> array = new MultiDimensionalArray<double>(3, 3);
array[0, 0] = 1;
array[0, 1] = 2;
array[1, 0] = 3;
array[1, 1] = 4;
// make a selection of the top right corner
IMultiDimensionalArray<double> view = array.Select(0, 0, 1).Select(1, 0, 1);
Assert.IsTrue(new[] { 2, 2 }.SequenceEqual(view.Shape));
// since array supports enumerator - we can enumerate throuth all values as 1D array
Assert.IsTrue(new double[] { 1, 2, 3, 4 }.SequenceEqual(view));
}
[Test]
public void MoveDimensionAtGivenIndexAndLength()
{
var values = new List<int> { 1, 2, 3, 4 };
IMultiDimensionalArray<int> array = new MultiDimensionalArray<int>(values, new[] { 1, 4 });
var view = array.Select(1, 2, 3); // select { 1, 2, [3, 4] }
// move 2nd dimension index
var dimension = 1;
var startIndex = 1;
var length = 2;
var newIndex = 0;
array.Move(dimension, startIndex, length, newIndex); // 1, 2, 3, 4 => 2, 3, 1, 4
// 2, 3, [1, 4]
Assert.IsTrue(view.SequenceEqual(new[] { 1, 4 }));
}
[Test]
public void Clone()
{
IMultiDimensionalArray<double> array = new MultiDimensionalArray<double>(3);
array[0] = 1;
array[1] = 2;
array[2] = 3;
var view = array.Select(0, 1, 1);
var clonedView = (IMultiDimensionalArrayView)view.Clone();
Assert.IsTrue(view.OffsetStart.SequenceEqual(clonedView.OffsetStart));
Assert.IsTrue(view.OffsetEnd.SequenceEqual(clonedView.OffsetEnd));
}
[Test]
public void ReducedIndexing()
{
IMultiDimensionalArray<double> array = new MultiDimensionalArray<double>(1, 3);
array[0, 0] = 1;
array[0, 1] = 2;
array[0, 2] = 3;
var view = array.Select(0, int.MinValue, int.MaxValue);
view.SelectedIndexes[0] = new int[] { 0 };
view.SelectedIndexes[1] = new int[] { 1 };
view.Reduce[0] = true; //reduce the x dimension
//one element
Assert.AreEqual(1, view.Count);
//rank and shape are one
Assert.AreEqual(1, view.Rank);
Assert.AreEqual(new[] { 1 }, view.Shape);
//get the value
Assert.AreEqual(2, view[0]);
}
}
} |
using MetaDslx.Compiler;
using MetaDslx.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MetaDslx.VisualStudio
{
public class MetaModelGenerator : SingleFileGenerator
{
public const string DefaultExtension = ".cs";
private MetaModelCompiler compiler;
public MetaModelGenerator(string inputFilePath, string inputFileContents, string defaultNamespace)
: base(inputFilePath, inputFileContents, defaultNamespace)
{
if (this.InputFileContents != null)
{
compiler = new MetaModelCompiler(this.InputFileContents, this.InputFileName);
compiler.Compile();
}
}
public override string GenerateStringContent()
{
if (compiler == null)
{
return string.Empty;
}
else
{
MetaModelCSharpGenerator generator = new MetaModelCSharpGenerator(compiler.Model.CachedInstances);
return generator.Generate();
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LaserDestroyScript : MonoBehaviour {
public float secToWait;
private int i;
private bool destroy;
public LaserSpawner LS;
// Use this for initialization
void Start () {
destroy = true;
StartCoroutine(timedDestroy());
}
// Update is called once per frame
void Update () {
}
IEnumerator timedDestroy()
{
yield return new WaitForSeconds(secToWait);
if (destroy)
{
/*if(LS != null)
{
LS.endEffects();
}*/
Destroy(this.gameObject);
}
}
public void dontDestroy()
{
destroy = false;
}
}
|
using EntityFrameworkCoreDemo.DbEntities;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EntityFrameworkCoreDemo.Controllers
{
public class SchoolController : Controller
{
private readonly ApplicationDbContext _context;
public SchoolController(ApplicationDbContext context)
{
_context = context;
}
public IActionResult Index()
{
var school = _context.School.FirstOrDefault();
return View(school);
}
}
}
|
using System;
using System.Net.Mail;
using com.Sconit.CodeMaster;
namespace com.Sconit.Entity.MSG
{
[Serializable]
public partial class Email : EntityBase
{
#region O/R Mapping Properties
//[Display(Name = "Id", ResourceType = typeof(Resources.MSG.Email))]
public Int32 Id { get; set; }
//[Display(Name = "Subject", ResourceType = typeof(Resources.MSG.Email))]
public string Subject { get; set; }
//[Display(Name = "Body", ResourceType = typeof(Resources.MSG.Email))]
public string Body { get; set; }
//[Display(Name = "MailTo", ResourceType = typeof(Resources.MSG.Email))]
public string MailTo { get; set; }
//[Display(Name = "ReplayTo", ResourceType = typeof(Resources.MSG.Email))]
public string ReplayTo { get; set; }
//[Display(Name = "Priority", ResourceType = typeof(Resources.MSG.Email))]
public MailPriority Priority { get; set; }
//[Display(Name = "Status", ResourceType = typeof(Resources.MSG.Email))]
public EmailStatus Status { get; set; }
//[Display(Name = "CreateDate", ResourceType = typeof(Resources.MSG.Email))]
public DateTime CreateDate { get; set; }
//[Display(Name = "LastModifyDate", ResourceType = typeof(Resources.MSG.Email))]
public DateTime LastModifyDate { get; set; }
#endregion
public override int GetHashCode()
{
if (Id != 0)
{
return Id.GetHashCode();
}
else
{
return base.GetHashCode();
}
}
public override bool Equals(object obj)
{
Email another = obj as Email;
if (another == null)
{
return false;
}
else
{
return (this.Id == another.Id);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AimaTeam.WebFormLightAPI.Admin
{
using AimaTeam.WebFormLightAPI.httpCore;
using AimaTeam.WebFormLightAPI.httpUtility;
using AimaTeam.WebFormLightAPI.httpEntity;
public partial class Get_ReqCacheItem : System.Web.UI.Page
{
private bool __ = false;
private string cmd = string.Empty;
private string reqId = string.Empty;
protected string reqID = string.Empty;
protected string domain = string.Empty;
protected string ipaddr = string.Empty;
protected ReqCache reqCache = default(ReqCache);
protected void Page_Load(object sender, EventArgs e)
{
this.cmd = Request.Params["cmd"];
this.reqId = Request.Params["reqID"];
this.domain = Request.Form["domain"];
__ = !string.IsNullOrEmpty(this.domain);
this.domain = string.IsNullOrEmpty(this.domain) ? Request.Params["domain"] : this.domain;
this.ipaddr = Request.Form["ipaddr"];
this.ipaddr = string.IsNullOrEmpty(this.ipaddr) ? Request.Params["ipaddr"] : this.ipaddr;
this.ipaddr = string.IsNullOrEmpty(this.ipaddr) ? "::1" : this.ipaddr;
if (!string.IsNullOrEmpty(this.domain) && !string.IsNullOrEmpty(this.ipaddr))
{
reqID = MD5Utility.Encrypt(domain + ipaddr, MD5Mode.Default); // RequestUtility.GetSchemeHostAndPort(Request);
reqCache = ReqCacheDbUtility.GetReqCache(reqID);
}
if (!string.IsNullOrEmpty(cmd) && !__)
{
bool result
= (cmd == "del") ? ReqCacheDbUtility.DeleteReqCache(reqId) // 删除缓存
: (cmd == "set") ? ReqCacheDbUtility.RemoveReqCacheIsBadIP(reqId) // 移除黑名单
: (cmd == "set1") ? ReqCacheDbUtility.AddToIsBadIPForever(reqId) // 永久性黑名单
: (cmd == "set2") ? ReqCacheDbUtility.SetReqCacheIsValidIPForever(reqId) : false; // 永久性非黑名单
}
}
}
} |
using System.CodeDom.Compiler;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[GeneratedCode("wsdl", "2.0.50727.42")]
public delegate void SetExecutionParameters3CompletedEventHandler(object sender, SetExecutionParameters3CompletedEventArgs e);
}
|
using Inventory.Services;
using Windows.ApplicationModel;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
// Документацию по шаблону элемента "Пользовательский элемент управления" см. по адресу https://go.microsoft.com/fwlink/?LinkId=234236
namespace Inventory.Views
{
public sealed partial class PhoneCallConnectOrder : UserControl
{
public PhoneCallViewModel ViewModel { get; set; }
public PhoneCallConnectOrder()
{
if (!DesignMode.DesignModeEnabled)
{
ViewModel = ServiceLocator.Current.GetService<PhoneCallViewModel>();
ViewModel.CoreDispatcher = Dispatcher;
ViewModel.Load();
}
this.InitializeComponent();
}
#region PhoneVisible
public bool PhoneVisible
{
get { return (bool)GetValue(PhoneVisibleProperty); }
set
{
SetValue(PhoneVisibleProperty, value);
ViewModel.PhoneVisible = value;
}
}
public static readonly DependencyProperty PhoneVisibleProperty = DependencyProperty.Register(nameof(PhoneVisible), typeof(bool), typeof(PhoneCallConnectOrder), new PropertyMetadata(null));
#endregion
}
}
|
using FriendStorage.Model;
using Prism.Events;
namespace FriendStorage.UI.Events
{
public class FriendSavedEvent : PubSubEvent<Friend>
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KartObjects;
using KartLib;
namespace KartSystem
{
public class StoresPresenter : BasePresenter
{
IStoresView _storesView;
public StoresPresenter(IStoresView storesView):base()
{
_storesView = storesView;
}
public override void ViewLoad()
{
base.ViewLoad();
if (_storesView != null)
{
KartDataDictionary.sStores = _storesView.Stores = Loader.DbLoad<Store>("")??new List<Store>();
}
}
}
}
|
using Cs_Gerencial.Aplicacao.Interfaces;
using Cs_Gerencial.Dominio.Entities;
using Cs_Gerencial.Dominio.Interfaces.Servicos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Gerencial.Aplicacao.ServicosApp
{
public class AppServicoPlanos: AppServicoBase<Planos>, IAppServicoPlanos
{
private readonly IServicoPlanos _servicoPlanos;
public AppServicoPlanos(IServicoPlanos servicoPlanos)
: base(servicoPlanos)
{
_servicoPlanos = servicoPlanos;
}
public IEnumerable<Planos> ConsultarPlanosPorDescricao(string descricao)
{
return _servicoPlanos.ConsultarPlanosPorDescricao(descricao);
}
}
}
|
using UnityEngine;
using System.Collections;
public class LevelGenerator : MonoBehaviour
{
public GameObject slime;
// Use this for initialization
void Start()
{
slime = GameObject.FindGameObjectWithTag("Finish");
}
// Update is called once per frame
void Update()
{
if (this.transform.position.y > slime.transform.position.y)
{
if (playerController.isGrounded == true)
this.GetComponent<Collider2D>().isTrigger = true;
}
if (slime.transform.position.y - this.transform.position.y > 4)
{
this.transform.position = new Vector3(0, this.transform.position.y + 8, 0);
this.GetComponent<Collider2D>().isTrigger = true;
//this.GetComponentInChildren<MonsterController>().position = 1;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using DChild.Gameplay.Objects;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace DChild.Gameplay
{
public interface IProjectileSpawnHandler
{
Projectile FireAt(Vector2 target);
Projectile FireTowards(Vector2 direction);
}
[System.Serializable]
public struct ProjectileSpawnHandler : IProjectileSpawnHandler
{
[SerializeField]
private GameObject m_projectile;
[SerializeField]
private ProjectileHandler m_handler;
private MonoBehaviour m_owner;
public void SetOwner(MonoBehaviour owner) => m_owner = owner;
public Projectile FireAt(Vector2 target)
{
var projectile = CreateProjectile();
m_handler.FireProjectileAt(projectile, target);
return projectile;
}
public Projectile FireTowards(Vector2 direction)
{
var projectile = CreateProjectile();
m_handler.FireProjectileTowards(projectile, direction);
return projectile;
}
private Projectile CreateProjectile()
{
var instance = m_owner.InstantiateToScene(m_projectile);
return instance.GetComponent<Projectile>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace MyTouristic.Models
{
[DebuggerDisplay("AirlineCode = {AirlineCode}")]
public class Flight
{
public string AirlineCode { get; set; }
public int Number { get; set; }
public DateTime Date { get; set; }
public string Route { get; set; }
private string[] airlineCode = new[] { "UN", "SU", "S7", "AB", "AF" };
private int[] number = new[] { 1235, 5421, 9875 };
public List<Flight> GetRandomFlight(string fromCity, string toCity, DateTime fromDate, DateTime toDate)
{
var random = new Random();
var listFlights = new List<Flight>();
var fl = new Flight();
fl.AirlineCode = airlineCode[random.Next(0, 5)];
fl.Number = Convert.ToInt32(number[random.Next(0, 3)]);
fl.Date = new DateTime(fromDate.Year, fromDate.Month, fromDate.Day, random.Next(0, 24),
random.Next(0, 59), 0);
fl.Route = fromCity + " - " + toCity;
listFlights.Add(fl);
fl = new Flight();
fl.AirlineCode = airlineCode[random.Next(0, 5)];
fl.Number = Convert.ToInt32(number[random.Next(0, 3)]);
fl.Date = new DateTime(toDate.Year, toDate.Month, toDate.Day, random.Next(0, 24), random.Next(0, 59), 0);
fl.Route = toCity + " - " + fromCity;
listFlights.Add(fl);
return listFlights;
}
public List<Flight> GetRandomFlightByShedule(string fromCity, string toCity, DateTime fromDate)
{
var random = new Random();
var listFlights = new List<Flight>();
for (var i = 0; i < 15; i++)
{
var fl = new Flight();
fl.AirlineCode = airlineCode[random.Next(0, 5)];
fl.Number = Convert.ToInt32(number[random.Next(0, 3)]);
fl.Date = new DateTime(fromDate.Year, fromDate.Month, fromDate.Day, random.Next(0, 24),
random.Next(0, 59), 0);
fl.Route = fromCity + " - " + toCity;
listFlights.Add(fl);
}
return listFlights;
}
}
} |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using DelftTools.TestUtils;
using GeoAPI.Geometries;
using GeoAPI.Operations.Buffer;
using GisSharpBlog.NetTopologySuite.Geometries;
using GisSharpBlog.NetTopologySuite.Operation.Buffer;
using NUnit.Framework;
using SharpMap;
using SharpMap.Data.Providers;
using SharpMap.Layers;
using SharpMapTestUtils;
using Point=System.Drawing.Point;
namespace NetTopologySuite.Tests
{
[TestFixture]
public class BufferTest
{
[Test,Category(TestCategory.WindowsForms)]
public void BufferAroundLine()
{
var form = new Form {BackColor = Color.White, Size = new Size(500, 200)};
form.Paint += delegate
{
Graphics g = form.CreateGraphics();
List<ICoordinate> vertices = new List<ICoordinate>();
vertices.Add(new Coordinate(0, 4));
vertices.Add(new Coordinate(40, 15));
vertices.Add(new Coordinate(50, 50));
vertices.Add(new Coordinate(100, 62));
vertices.Add(new Coordinate(240, 45));
vertices.Add(new Coordinate(350, 5));
IGeometry geometry = new LineString(vertices.ToArray());
g.DrawLines(new Pen(Color.Blue, 1), GetPoints(geometry));
BufferOp bufferOp = new BufferOp(geometry);
bufferOp.EndCapStyle = BufferStyle.CapButt;
bufferOp.QuadrantSegments = 0;
IGeometry bufGeo = bufferOp.GetResultGeometry(5);
bufGeo = bufGeo.Union(geometry);
g.FillPolygon(new SolidBrush(Color.Pink), GetPoints(bufGeo));
};
WindowsFormsTestHelper.ShowModal(form);
}
[Test]
[Category(TestCategory.WindowsForms)]
public void IntersectTriangles()
{
ICoordinate[] v1 = new ICoordinate[7];
v1[0] = new Coordinate(0,0);
v1[1] = new Coordinate(5,10);
v1[2] = new Coordinate(10,0);
v1[3] = new Coordinate(8, 0);
v1[4] = new Coordinate(5, 3);
v1[5] = new Coordinate(4, 0);
v1[6] = new Coordinate(0,0);
IGeometry pol1 = new Polygon(new LinearRing(v1));
ICoordinate[] v2 = new ICoordinate[5];
v2[0] = new Coordinate(0, 0);
v2[1] = new Coordinate(10, 0);
v2[2] = new Coordinate(10, 1);
v2[3] = new Coordinate(0, 1);
v2[4] = new Coordinate(0, 0);
IGeometry pol2 = new Polygon(new LinearRing(v2));
/*
IGeometry g = pol1.Difference(pol2);
Assert.AreEqual(6, g.Coordinates.Length);
IGeometry g1 = pol1.Union(pol2);
Assert.AreEqual(7, g1.Coordinates.Length);
*/
Map map = new Map();
IGeometry gIntersection = pol1.Intersection(pol2);
map.Layers.Add(new VectorLayer("g1", new DataTableFeatureProvider(new [] { gIntersection })));
/*
map.Layers.Add(new VectorLayer("g", new DataTableFeatureProvider(new IGeometry[] { pol1 }) ));
map.Layers.Add(new VectorLayer("g1", new DataTableFeatureProvider(new IGeometry[] { pol2 })));
*/
MapTestHelper.Show(map);
}
[Test]
public void IntersectPolygonWithLine()
{
ICoordinate[] coordinates = new ICoordinate[5];
coordinates[0] = new Coordinate(0, 0);
coordinates[1] = new Coordinate(10, 0);
coordinates[2] = new Coordinate(10, 10);
coordinates[3] = new Coordinate(0, 10);
coordinates[4] = new Coordinate(0, 0);
IGeometry pol2 = new Polygon(new LinearRing(coordinates));
var line = new LineString(new[] { new Coordinate(5,5), new Coordinate(6,20),new Coordinate(7,5) });
var result = pol2.Intersection(line);
}
private Point[] GetPoints(IGeometry geometry)
{
List<Point> points = new List<Point>();
foreach (ICoordinate vertex in geometry.Coordinates)
{
points.Add(new Point((int)vertex.X, (int)vertex.Y));
}
return points.ToArray();
}
}
}
|
using Alabo.Cloud.People.Identities.Domain.Entities;
using Alabo.Data.People.Users.ViewModels;
using Alabo.Domains.Entities;
using Alabo.Domains.Services;
using MongoDB.Bson;
namespace Alabo.Cloud.People.Identities.Domain.Services
{
public interface IIdentityService : IService<Identity, ObjectId>
{
/// <summary>
/// Adds the or update.
/// 添加实名认证
/// </summary>
/// <param name="input">The input.</param>
/// <returns>ServiceResult.</returns>
// ServiceResult AddOrUpdate(IdentityView input);
/// <summary>
/// 人脸认证
/// </summary>
/// <param name="view"></param>
/// <returns></returns>
ServiceResult FaceIdentity(Identity view);
/// <summary>
/// 是否实名认证
/// </summary>
/// <param name="userId">用户Id</param>
bool IsIdentity(long userId);
IdentityView GetView(string id);
ServiceResult Identity(Identity view);
}
} |
namespace Uintra.Persistence.Sql
{
public abstract class SqlEntity<TKey>
{
public abstract TKey Id { get; set; }
}
} |
using CyberSoldierServer.Models.BaseModels;
namespace CyberSoldierServer.Models.PlayerModels {
public class SlotDefenceItem {
public int Id { get; set; }
public DungeonSlot Slot { get; set; }
public int SlotId { get; set; }
public DefenceItem DefenceItem { get; set; }
public int DefenceItemId { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace Miniprojet
{
class ManipulationBD
{
public static string StrCon = " Server = localhost; Database = stl; Uid = root; Pwd = ;";
public static MySqlConnection Cnn = new MySqlConnection(StrCon);
public static void ConnectionDataBase()
{
Cnn.Open();
}
public static void DecoonectionDataBase()
{
Cnn.Close();
}
}
}
|
namespace com.Sconit.Web.Controllers.ISS
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using com.Sconit.Utility;
using Telerik.Web.Mvc;
using com.Sconit.Web.Models;
using com.Sconit.Web.Models.SearchModels.ISS;
using com.Sconit.Web.Controllers.ACC;
using com.Sconit.Entity.ISS;
using com.Sconit.Service;
public class IssueAddressController : WebAppBaseController
{
/// <summary>
///
/// </summary>
private static string selectCountStatement = "select count(*) from IssueAddress as ia left join ia.ParentIssueAddress pia ";
/// <summary>
///
/// </summary>
private static string selectStatement = "select ia from IssueAddress as ia left join ia.ParentIssueAddress pia ";
/// <summary>
///
/// </summary>
private static string codeDuiplicateVerifyStatement = @"select count(*) from IssueAddress as ia where ia.Code = ?";
/// <summary>
///
/// </summary>
//public IGenericMgr genericMgr { get; set; }
//
// GET: /IssueAddress/
[SconitAuthorize(Permissions = "Url_IssueAddress_View")]
public ActionResult Index()
{
return View();
}
[GridAction]
[SconitAuthorize(Permissions = "Url_IssueAddress_View")]
public ActionResult List(GridCommand command, IssueAddressSearchModel searchModel)
{
TempData["IssueAddressSearchModel"] = searchModel;
ViewBag.PageSize = base.ProcessPageSize(command.PageSize);
return View();
}
[GridAction(EnableCustomBinding = true)]
[SconitAuthorize(Permissions = "Url_IssueAddress_View")]
public ActionResult _AjaxList(GridCommand command, IssueAddressSearchModel searchModel)
{
SearchStatementModel searchStatementModel = PrepareSearchStatement(command, searchModel);
return PartialView(GetAjaxPageData<IssueAddress>(searchStatementModel, command));
}
[SconitAuthorize(Permissions = "Url_IssueAddress_Edit")]
public ActionResult New()
{
return View();
}
[HttpPost]
[SconitAuthorize(Permissions = "Url_IssueAddress_Edit")]
public ActionResult New(IssueAddress issueAddress)
{
if (!string.IsNullOrWhiteSpace(issueAddress.ParentIssueAddressCode))
{
ViewBag.ParentIssueAddressCode = issueAddress.ParentIssueAddressCode;
IssueAddress parentIssueAddress = new IssueAddress();//this.genericMgr.FindById<IssueType>(issueTypeTo.IssueTypeCode);
parentIssueAddress.Code = issueAddress.ParentIssueAddressCode;
issueAddress.ParentIssueAddress = parentIssueAddress;
ModelState.Remove("ParentIssueAddress");
}
if (ModelState.IsValid)
{
//判断用户名不能重复
if (this.genericMgr.FindAll<long>(codeDuiplicateVerifyStatement, new object[] { issueAddress.Code })[0] > 0)
{
base.SaveErrorMessage(Resources.ISS.IssueAddress.Errors_Existing_IssueAddress, issueAddress.Code);
}
else
{
genericMgr.CreateWithTrim(issueAddress);
SaveSuccessMessage(Resources.ISS.IssueAddress.IssueAddress_Added);
return RedirectToAction("Edit/" + issueAddress.Code);
}
}
return View(issueAddress);
}
[HttpGet]
[SconitAuthorize(Permissions = "Url_IssueAddress_Edit")]
public ActionResult Edit(string id)
{
if (string.IsNullOrWhiteSpace(id))
{
return HttpNotFound();
}
else
{
IssueAddress issueAddress = this.genericMgr.FindById<IssueAddress>(id);
return View(issueAddress);
}
}
/// <summary>
/// Delete action
/// </summary>
/// <param name="id">IssueAddress id for delete</param>
/// <returns>return to List action</returns>
[SconitAuthorize(Permissions = "Url_IssueAddress_Delete")]
public ActionResult Delete(string id)
{
if (string.IsNullOrWhiteSpace(id))
{
return HttpNotFound();
}
else
{
this.genericMgr.DeleteById<IssueAddress>(id);
SaveSuccessMessage(Resources.ISS.IssueAddress.IssueAddress_Deleted);
return RedirectToAction("List");
}
}
[HttpPost]
[SconitAuthorize(Permissions = "Url_IssueAddress_Edit")]
public ActionResult Edit(IssueAddress issueAddress)
{
if (!string.IsNullOrWhiteSpace(issueAddress.ParentIssueAddressCode))
{
ViewBag.ParentIssueAddressId = issueAddress.ParentIssueAddressCode;
IssueAddress parentIssueAddress = new IssueAddress();//this.genericMgr.FindById<IssueType>(issueTypeTo.IssueTypeCode);
parentIssueAddress.Code = issueAddress.ParentIssueAddressCode;
issueAddress.ParentIssueAddress = parentIssueAddress;
ModelState.Remove("ParentIssueAddress");
}
if (ModelState.IsValid)
{
genericMgr.UpdateWithTrim(issueAddress);
SaveSuccessMessage(Resources.ISS.IssueAddress.IssueAddress_Updated);
}
return View(issueAddress);
}
private SearchStatementModel PrepareSearchStatement(GridCommand command, IssueAddressSearchModel searchModel)
{
string whereStatement = string.Empty;
IList<object> param = new List<object>();
if (!string.IsNullOrWhiteSpace(searchModel.ParentIssueAddressCode))
{
HqlStatementHelper.AddEqStatement("Code", searchModel.ParentIssueAddressCode, "pia", ref whereStatement, param);
}
HqlStatementHelper.AddLikeStatement("Description", searchModel.Description, HqlStatementHelper.LikeMatchMode.Start, "ia", ref whereStatement, param);
string sortingStatement = HqlStatementHelper.GetSortingStatement(command.SortDescriptors);
SearchStatementModel searchStatementModel = new SearchStatementModel();
searchStatementModel.SelectCountStatement = selectCountStatement;
searchStatementModel.SelectStatement = selectStatement;
searchStatementModel.WhereStatement = whereStatement;
searchStatementModel.SortingStatement = sortingStatement;
searchStatementModel.Parameters = param.ToArray<object>();
return searchStatementModel;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using OrbisEngine.ItemSystem;
public class ItemUpdateMessage : IMessage
{
public string Message
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
public string UpdateType;
public ItemUpdateMessage(string updateType)
{
UpdateType = updateType;
}
public const string NewComponentAdded = "NEW_COMPONENT";
}
|
using Newtonsoft.Json.Linq;
namespace Entoarox.Framework.Core.Serialization
{
internal class InstanceState
{
/*********
** Accessors
*********/
public string Type;
public JToken Data;
/*********
** Public methods
*********/
public InstanceState() { }
public InstanceState(string type, JToken data)
{
this.Type = type;
this.Data = data;
}
}
}
|
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
namespace TexturePacker.Editor.Animation
{
public static class AnimationGenerator
{
public static AnimationClip GenerateAndSaveAnimation(List<Sprite> sprites, int frameRate, bool isLooping, string path)
{
var animationClip = GenerateAnimation(sprites, frameRate, isLooping, Path.GetFileNameWithoutExtension(path));
if (AssetDatabase.LoadAssetAtPath<AnimationClip>(path) != null) AssetDatabase.DeleteAsset(path);
AssetDatabase.CreateAsset(animationClip, path);
AssetDatabase.SaveAssets();
EditorUtility.SetDirty(animationClip);
return animationClip;
}
public static AnimationClip GenerateAndSaveAnimationToCurrentDirectory(List<Sprite> sprites, int frameRate, bool isLooping, string name)
{
var animationClip = GenerateAnimation(sprites, frameRate, isLooping, name);
ObjectCreatorHelper.CreateAsset(animationClip, string.Format("{0}.anim", name));
return animationClip;
}
private static AnimationClip GenerateAnimation(List<Sprite> sprites, int frameRate, bool isLooping, string name)
{
var animationClip = new AnimationClip()
{
name = name,
frameRate = frameRate
};
if (isLooping)
{
var animationClipSettings = AnimationUtility.GetAnimationClipSettings(animationClip);
animationClipSettings.loopTime = true;
AnimationUtility.SetAnimationClipSettings(animationClip, animationClipSettings);
}
var editorCurveBinding = new EditorCurveBinding()
{
type = typeof(SpriteRenderer),
propertyName = "m_Sprite",
};
var timeStep = 1f / frameRate;
var keyFrames = new ObjectReferenceKeyframe[sprites.Count];
for (var index = 0; index < sprites.Count; index++)
{
keyFrames[index] = new ObjectReferenceKeyframe()
{
time = timeStep * index,
value = sprites[index],
};
}
AnimationUtility.SetObjectReferenceCurve(animationClip, editorCurveBinding, keyFrames);
return animationClip;
}
}
} |
using System.Drawing;
namespace MageTwinstick
{
/// <summary>
/// Superclass for anything that moves, attacks and dies
/// </summary>
abstract class Unit : MovingObject
{
/// <summary>
/// float for the units health
/// </summary>
public float Health { get; set; }
/// <summary>
/// Unit Constructor
/// </summary>
/// <param name="speed">The units movement speed</param>
/// <param name="health">The units starting health</param>
/// <param name="imagePath">Image path for the sprite</param>
/// <param name="startPos">The Units starting position</param>
/// <param name="display">The display rectangle</param>
/// <param name="animationSpeed">The speed of the animation</param>
public Unit(float speed,int health, string imagePath, Vector2D startPos, Rectangle display, float animationSpeed)
: base(speed, imagePath, startPos, display, animationSpeed)
{
Health = health;
}
/// <summary>
/// Abstract function Attack
/// </summary>
public abstract void Attack();
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
namespace Kitap_Takip_Sistemi
{
public partial class AnaSayfa1 : System.Web.UI.Page
{
static SqlConnection baglanti = new SqlConnection("Server=.;Database=Kitap_Takip;Trusted_Connection=True;");
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string KayitEkle(string ad, string soyad, string Adres, string KullaniciAd, string sifre)
{
SqlDataAdapter adapt = new SqlDataAdapter("insert into Uye values(@ad,@soyad,@Adres,@KullaniciAd,@sifre)", baglanti);
adapt.SelectCommand.Parameters.AddWithValue("ad", ad);
adapt.SelectCommand.Parameters.AddWithValue("soyad", soyad);
adapt.SelectCommand.Parameters.AddWithValue("Adres", Adres);
adapt.SelectCommand.Parameters.AddWithValue("KullaniciAd", KullaniciAd);
adapt.SelectCommand.Parameters.AddWithValue("sifre", sifre);
baglanti.Open();
adapt.SelectCommand.ExecuteNonQuery();
baglanti.Close();
SqlDataAdapter adapt2 = new SqlDataAdapter("select * from Uye where KullaniciAd=@KullaniciAd", baglanti);
adapt2.SelectCommand.Parameters.AddWithValue("KullaniciAd", KullaniciAd);
DataTable table = new DataTable();
adapt2.Fill(table);
foreach (DataRow item in table.Rows)
{
HttpContext.Current.Session.Add("Uye_id", item.ItemArray[0].ToString());
return "Profil.aspx";
}
return "Profil.aspx";
}
[WebMethod]
public static string Giris(string ad, string sifre)
{
SqlDataAdapter adapt = new SqlDataAdapter("select * from Uye where KullaniciAd=@kAdi and sifre=@sifre", baglanti);
adapt.SelectCommand.Parameters.AddWithValue("kAdi", ad);
adapt.SelectCommand.Parameters.AddWithValue("sifre", sifre);
DataTable table = new DataTable();
adapt.Fill(table);
foreach (DataRow item in table.Rows)
{
HttpContext.Current.Session.Add("Uye_id", item.ItemArray[0].ToString());
return "Profil.aspx";
}
return "AnaSayfa.aspx";
}
[WebMethod]
public static string KitapGetir()
{
SqlDataAdapter adapt = new SqlDataAdapter("select resim,ad,Tur_Ad from Kitap k join KitapTur t on k.Tur_id=t.Tur_id", baglanti);
DataTable table = new DataTable();
adapt.Fill(table);
string data = JsonConvert.SerializeObject(table, Formatting.Indented);
return data;
}
}
} |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Pacman
{
class StateButton : Button
{
// A button that has multiple states it can be for example: controller, keyboard, mouse button
protected int states, currentState;
protected Rectangle[] stateButtons;
public StateButton(int x, int y, Texture2D sprite, ButtonActions action, int states, int currentState)
: this(x, y, sprite, Alignment.TopLeft, action, states, currentState) { }
public StateButton(int x, int y, Texture2D sprite, Alignment alignment, ButtonActions action, int states, int currentState)
: base(x, y, sprite, alignment, action)
{
this.states = states;
this.currentState = currentState;
Origin = new Vector2(x, y);
stateButtons = new Rectangle[states];
for (int i = 0; i < states; i++)
{
stateButtons[i] = new Rectangle(0, (sprite.Height / states) * i, sprite.Width, sprite.Height / states);
}
}
public override void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(sprite, Position, stateButtons[currentState], Color.White);
}
public override Vector2 SpriteSize
{
get
{
try { return new Vector2(sprite.Width, sprite.Height / states);}
catch
{
// parent constructor, states not yet set
return Vector2.Zero;
}
}
}
/// <summary>The state of a multi-state button.</summary>
public int State
{
get { return currentState; }
set { currentState = (int)MathHelper.Clamp(value, 0, states - 1); }
}
/// <summary>Go to the next state or state 0 if the current state is the last option. Return the new state.</summary>
public int NextState()
{
currentState = (currentState + 1) % states;
return currentState;
}
}
}
|
using System.Web.Mvc;
using Imp.Core.Domain.Users;
namespace Imp.Web.Framework.Controllers
{
public class BaseController : Controller
{
/// <summary>
/// Access denied view
/// </summary>
/// <returns>Access denied view</returns>
protected ActionResult AccessDeniedView()
{
//return new HttpUnauthorizedResult();
return RedirectToAction("AccessDenied", "Security", new { pageUrl = this.Request.RawUrl });
}
}
} |
using System;
namespace HTB.Database.StoredProcs
{
public class spGetInfoForLawyerAkt : Record
{
public DateTime AktDate { get; set; }
public int AktID { get; set; }
public string AktAZ { get; set; }
public DateTime RechnungsDate { get; set; }
public string RechnungsNummer { get; set; }
public string KundenNummer { get; set; }
public double KlientKapital { get; set; }
public double KlientMahnspesen { get; set; }
public double KlientZinsen { get; set; }
public double ECPZinsen { get; set; }
public double ECPKosten { get; set; }
public double Payments { get; set; }
public double Balance { get; set; }
public int GegnerTyp { get; set; }
public string GegnerNachname { get; set; }
public string GegnerVorname { get; set; }
public string GegnerAliasNachname { get; set; }
public string GegnerAliasVorname { get; set; }
public string GegnerStrasse { get; set; }
public string GegnerPLZ { get; set; }
public string GegnerOrt { get; set; }
public string GegnerCountry { get; set; }
public DateTime GegnerGeburtsdatum { get; set; }
public string GegnerEmail { get; set; }
public string GegnerPhoneCountry { get; set; }
public string GegnerPhoneCity { get; set; }
public string GegnerPhone { get; set; }
public string KlientAnrede { get; set; }
public string KlientTitel { get; set; }
public string KlientName1 { get; set; }
public string KlientName2 { get; set; }
public string KlientName3 { get; set; }
public string KlientStrasse { get; set; }
public string KlientPLZ { get; set; }
public string KlientOrt { get; set; }
public string KlientCountry { get; set; }
public string KlientEMail { get; set; }
public string KlientPhoneCountry { get; set; }
public string KlientPhoneCity { get; set; }
public string KlientPhone { get; set; }
public string KlientAnsprechpartner { get; set; }
public string KlientFirmenbuchnummer { get; set; }
public string Auftraggeber { get; set; }
public string AuftraggeberStrasse { get; set; }
public string AuftraggeberPLZ { get; set; }
public string AuftraggeberOrt { get; set; }
public string AuftraggeberCountry { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GodaddyWrapper.Requests
{
public class CertificateSiteSealRetrieve
{
public string theme { get; set; }
public string locale { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using IRAP.Global;
namespace IRAP.Interface.OPC
{
public class TGetDevicesRspBody : TSoftlandBody
{
private List<TGetDevicesRspDetail> details = new List<TGetDevicesRspDetail>();
private string excode;
public string ExCode
{
get { return "GetDevices"; }
set { excode = value; }
}
public string ErrCode { get; set; }
public string ErrText { get; set; }
public TGetDevicesRspBody()
{
}
public static TGetDevicesRspBody LoadFromXMLNode(XmlNode node)
{
TGetDevicesRspBody rlt = new TGetDevicesRspBody();
rlt = IRAPXMLUtils.LoadValueFromXMLNode(GetEX(node), rlt) as TGetDevicesRspBody;
XmlNode paramxml = GetRspBodyNode(node);
if (paramxml != null && paramxml.FirstChild != null && paramxml.FirstChild.Name == "Row")
{
foreach (XmlNode child in paramxml.ChildNodes)
{
rlt.details.Add(TGetDevicesRspDetail.LoadFromXMLNode(child));
}
}
return rlt;
}
public void AddDeviceDetail(TGetDevicesRspDetail item)
{
details.Add(item);
}
public TGetDevicesRspDetail GetDeviceDetail(int index)
{
if (index >= 0 && index < details.Count)
{
return details[index];
}
else
{
return null;
}
}
public int GetDeviceDetailCount()
{
return details.Count;
}
public void RemoveDeviceDetail(TGetDevicesRspDetail item)
{
if (details.IndexOf(item) >= 0)
{
details.Remove(item);
}
}
public void RemoveDeviceDetailAt(int index)
{
if (index >= 0 && index < details.Count)
{
details.RemoveAt(index);
}
}
protected override XmlNode GenerateUserDefineNode()
{
XmlDocument xml = new XmlDocument();
XmlNode result = xml.CreateElement("Result");
XmlNode node = xml.CreateElement("Param");
node = IRAPXMLUtils.GenerateXMLAttribute(node, this);
result.AppendChild(node);
node = xml.CreateElement("ParamXML");
result.AppendChild(node);
for (int i = 0; i < details.Count; i++)
{
details[i].Ordinal = i + 1;
XmlNode row = xml.CreateElement("Row");
row = details[i].GenerateXMLNode(row);
node.AppendChild(row);
}
return result;
}
}
}
|
using System.Web;
using System.Web.Optimization;
namespace ShengUI
{
public class BundleConfig
{
// 有关 Bundling 的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=254725
public static void RegisterBundles(BundleCollection bundles)
{
//bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
// "~/Scripts/jquery-{version}.js"));
//bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
// "~/Scripts/jquery-ui-{version}.js"));
//bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
// "~/Scripts/jquery.unobtrusive*",
// "~/Scripts/jquery.validate*"));
//// 使用 Modernizr 的开发版本进行开发和了解信息。然后,当你做好
//// 生产准备时,请使用 http://modernizr.com 上的生成工具来仅选择所需的测试。
//bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
// "~/Scripts/modernizr-*"));
//bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
bundles.Add(new ScriptBundle("~/validate").Include(
"~/Scripts/jquery-1.7.1.min.js",
"~/Scripts/jquery.unobtrusive-ajax.js",
//<!-- / validate -->
"~/Scripts/Back/plugins/validate/jquery.validate.min.js",
"~/Scripts/jquery.validate.unobtrusive.js"
));
bundles.Add(new StyleBundle("~/Content/Back/base/css").Include(
"~/Content/Back/css/bootstrap/bootstrap.css",
"~/Content/Back/css/bootstrap/bootstrap-responsive.css",
"~/Content/Back/css/jquery_ui/jquery-ui-1.10.0.custom.css",
"~/Content/Back/css/jquery_ui/jquery.ui.1.10.0.ie.css",
// <!-- / switch buttons -->
"~/Content/Back/css/plugins/bootstrap_switch/bootstrap-switch.css",
// <!-- / xeditable -->
"~/Content/Back/css/plugins/xeditable/bootstrap-editable.css",
"~/Content/Back/css/plugins/common/bootstrap-wysihtml5.css",
// <!-- / wysihtml5 (wysywig) -->
"~/Content/Back/css/plugins/common/bootstrap-wysihtml5.css",
// <!-- / jquery file upload -->
"~/Content/Back/css/plugins/jquery_fileupload/jquery.fileupload-ui.css",
// <!-- / full calendar -->
"~/Content/Back/css/plugins/fullcalendar/fullcalendar.css",
//<!-- / select2 -->
"~/Content/Back/css/plugins/select2/select2.css",
//<!-- / mention -->
"~/Content/Back/css/plugins/mention/mention.css",
//<!-- / tabdrop (responsive tabs) -->
"~/Content/Back/css/plugins/tabdrop/tabdrop.css",
// <!-- / jgrowl notifications -->
"~/Content/Back/css/plugins/jgrowl/jquery.jgrowl.css",
//<!-- / datatables -->
"~/Content/Back/css/plugins/datatables/bootstrap-datatable.css",
// <!-- / dynatrees (file trees) -->
"~/Content/Back/css/plugins/dynatree/ui.dynatree.css",
// <!-- / color picker -->
"~/Content/Back/css/plugins/bootstrap_colorpicker/bootstrap-colorpicker.css",
// <!-- / datetime picker -->
"~/Content/Back/css/plugins/bootstrap_datetimepicker/bootstrap-datetimepicker.min.css",
// <!-- / daterange picker) -->
"~/Content/Back/css/plugins/bootstrap_daterangepicker/bootstrap-daterangepicker.css",
// <!-- / flags (country flags) -->
"~/Content/Back/css/plugins/flags/flags.css",
//<!-- / slider nav (address book) -->
"~/Content/Back/css/plugins/slider_nav/slidernav.css",
// <!-- / fuelux (wizard) -->
"~/Content/Back/css/plugins/fuelux/wizard.css",
// <!-- / flatty theme -->
"~/Content/Back/css/light-theme.css",
// <!-- / demo -->
"~/Content/Back/css/demo.css"
));
bundles.Add(new ScriptBundle("~/mvcAjax").Include(
"~/Scripts/jquery-1.7.1.min.js",
"~/Scripts/jquery.unobtrusive-ajax.js",
// "~/Scripts/jquery.validate.js",
"~/Scripts/Back/Common/common.js",
"~/Scripts/Back/Common/LG.js",
//<!-- / jquery mobile events (for touch and slide) -->
"~/Scripts/Back/plugins/mobile_events/jquery.mobile-events.min.js",
//<!-- / jquery migrate (for compatibility with new jquery) -->
"~/Scripts/Back/jquery/jquery-migrate.min.js",
//<!-- / jquery ui -->
"~/Scripts/Back/jquery_ui/jquery-ui.min.js",
//<!-- / bootstrap -->
"~/Scripts/Back/bootstrap/bootstrap.min.js",
"~/Scripts/Back/plugins/flot/excanvas.js",
//<!-- / sparklines -->
"~/Scripts/Back/plugins/sparklines/jquery.sparkline.min.js",
//<!-- / flot charts -->
"~/Scripts/Back/plugins/flot/flot.min.js",
"~/Scripts/Back/plugins/flot/flot.resize.js",
"~/Scripts/Back/plugins/flot/flot.pie.js",
//<!-- / bootstrap switch -->
"~/Scripts/Back/plugins/bootstrap_switch/bootstrapSwitch.min.js",
//<!-- / fullcalendar -->
"~/Scripts/Back/plugins/fullcalendar/fullcalendar.min.js",
//<!-- / datatables -->
// "~/Scripts/Back/plugins/datatables/jquery.dataTables.js",
//"~/Scripts/Back/plugins/datatables/jquery.dataTables.columnFilter.js",
//<!-- / wysihtml5 -->
"~/Scripts/Back/plugins/common/wysihtml5.min.js",
"~/Scripts/Back/plugins/common/bootstrap-wysihtml5.js",
//<!-- / select2 -->
"~/Scripts/Back/plugins/select2/select2.js",
//<!-- / color picker -->
"~/Scripts/Back/plugins/bootstrap_colorpicker/bootstrap-colorpicker.min.js",
//<!-- / mention -->
"~/Scripts/Back/plugins/mention/mention.min.js",
//<!-- / input mask -->
"~/Scripts/Back/plugins/input_mask/bootstrap-inputmask.min.js",
//<!-- / fileinput -->
"~/Scripts/Back/plugins/fileinput/bootstrap-fileinput.js",
//<!-- / modernizr -->
"~/Scripts/Back/plugins/modernizr/modernizr.min.js",
//<!-- / retina -->
"~/Scripts/Back/plugins/retina/retina.js",
//<!-- / fileupload -->
"~/Scripts/Back/plugins/fileupload/tmpl.min.js",
"~/Scripts/Back/plugins/fileupload/load-image.min.js",
"~/Scripts/Back/plugins/fileupload/canvas-to-blob.min.js",
"~/Scripts/Back/plugins/fileupload/jquery.iframe-transport.min.js",
"~/Scripts/Back/plugins/fileupload/jquery.fileupload.min.js",
"~/Scripts/Back/plugins/fileupload/jquery.fileupload-fp.min.js",
"~/Scripts/Back/plugins/fileupload/jquery.fileupload-ui.min.js",
"~/Scripts/Back/plugins/fileupload/jquery.fileupload-init.js",
//<!-- / timeago -->
"~/Scripts/Back/plugins/timeago/jquery.timeago.js",
//<!-- / slimscroll -->
"~/Scripts/Back/plugins/slimscroll/jquery.slimscroll.min.js",
//<!-- / autosize (for textareas) -->
"~/Scripts/Back/plugins/autosize/jquery.autosize-min.js",
//<!-- / charCount -->
"~/Scripts/Back/plugins/charCount/charCount.js",
//<!-- / validate -->
"~/Scripts/Back/plugins/validate/jquery.validate.min.js",
"~/Scripts/jquery.validate.unobtrusive.js",
"~/Scripts/Back/plugins/validate/additional-methods.js",
//<!-- / naked password -->
"~/Scripts/Back/plugins/naked_password/naked_password-0.2.4.min.js",
//<!-- / nestable -->
"~/Scripts/Back/plugins/nestable/jquery.nestable.js",
//<!-- / tabdrop -->
"~/Scripts/Back/plugins/tabdrop/bootstrap-tabdrop.js",
//<!-- / jgrowl -->
"~/Scripts/Back/plugins/jgrowl/jquery.jgrowl.min.js",
//<!-- / bootbox -->
"~/Scripts/Back/plugins/bootbox/bootbox.min.js",
//<!-- / inplace editing -->
"~/Scripts/Back/plugins/xeditable/bootstrap-editable.min.js",
"~/Scripts/Back/plugins/xeditable/wysihtml5.js",
//<!-- / ckeditor -->
"~/Scripts/Back/plugins/ckeditor/ckeditor.js",
//<!-- / filetrees -->
"~/Scripts/Back/plugins/dynatree/jquery.dynatree.min.js",
//<!-- / datetime picker -->
"~/Scripts/Back/plugins/bootstrap_datetimepicker/bootstrap-datetimepicker.js",
//<!-- / daterange picker -->
"~/Scripts/Back/plugins/bootstrap_daterangepicker/moment.min.js",
"~/Scripts/Back/plugins/bootstrap_daterangepicker/bootstrap-daterangepicker.js",
//<!-- / max length -->
"~/Scripts/Back/plugins/bootstrap_maxlength/bootstrap-maxlength.min.js",
//<!-- / dropdown hover -->
"~/Scripts/Back/plugins/bootstrap_hover_dropdown/twitter-bootstrap-hover-dropdown.min.js",
//<!-- / slider nav (address book) -->
"~/Scripts/Back/plugins/slider_nav/slidernav-min.js",
//<!-- / fuelux -->
"~/Scripts/Back/plugins/fuelux/wizard.js",
//<!-- / flatty theme -->
"~/Scripts/Back/nav.js",
// "~/Scripts/Back/table.js",
"~/Scripts/Back/theme.js",
//<!-- / demo -->
"~/Scripts/Back/demo/jquery.mockjax.js",
"~/Scripts/Back/demo/inplace_editing.js",
"~/Scripts/Back/demo/charts.js",
"~/Scripts/Back/demo/demo.js",
"~/Scripts/Back/Common/jquery.loadmask.js"
));
bundles.Add(new ScriptBundle("~/datatables").Include(
"~/Scripts/Back/plugins/datatables/jquery.dataTables.js",
"~/Scripts/Back/plugins/datatables/jquery.dataTables.columnFilter.js",
"~/Scripts/Back/tables.js"
));
BundleTable.EnableOptimizations = true;
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace L2Bot_Dead_Reckoning_Timer
{
public partial class Form1 : Form
{
LoCoMoCo mc;
bool running = false;
Timer tmr = null;
int tmr_state = 0;
public Form1()
{
InitializeComponent();
mc = new LoCoMoCo("COM7");
tmr = new Timer();
tmr.Tick += new EventHandler(tmr_Tick);
tmr.Enabled = false;
}
private void start_stop_btn_Click(object sender, EventArgs e)
{
if (running == false)
{
running = true;
start_stop_btn.Text = "Stop";
tmr_state = 0;
tmr.Interval = 5000;
mc.forward();
tmr.Enabled = true;
tmr.Start();
}
else
{
start_stop_btn.Text = "Start";
running = false;
mc.stop();
tmr.Stop();
tmr.Enabled = false;
}
}
void tmr_Tick(object sender, EventArgs e)
{
tmr.Stop();
switch (tmr_state)
{
// Begin turning
case 0:
mc.turnleft();
tmr.Interval = 3000;
tmr.Start();
tmr_state++;
break;
case 1:
mc.forward();
tmr.Interval = 5000;
tmr.Start();
tmr_state++;
break;
case 2:
mc.stop();
tmr_state = 0;
start_stop_btn.Text = "Start";
running = false;
tmr.Stop();
tmr.Enabled = false;
break;
}
}
protected override void OnClosing(CancelEventArgs e)
{
mc.close();
base.OnClosing(e);
}
}
}
|
using System.Xml.Serialization;
namespace Models.Enemies
{
[XmlType]
public enum EnemyType
{
[XmlEnum] Small,
[XmlEnum] Medium,
[XmlEnum] Large
}
public interface IEnemy
{
EnemyType Type { get; }
int Health { get; }
int Damage { get; }
float Speed { get; }
decimal Price { get; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Classes
{
class ThirdClass
{
private int first;
private int second;
public ThirdClass()
{
first = 1;
second = 2;
Console.WriteLine("1st = {0}\n2nd = {1}",first,second);
}
public ThirdClass(int first)
{
this.first = first;
second = 4;
Console.WriteLine("1st = {0}\n2nd = {1}", first, second);
}
public ThirdClass(int first,int second)
{
this.first = first;
this.second = second;
Console.WriteLine("1st = {0}\n2nd = {1}", first, second);
}
}
}
|
using System;
using Vlc.DotNet.Core.Interops.Signatures;
namespace Vlc.DotNet.Core.Interops
{
public sealed class VlcMediaPlayerInstance : InteropObjectInstance
{
private readonly VlcManager myManager;
internal VlcMediaPlayerInstance(VlcManager manager, IntPtr pointer) : base(pointer)
{
myManager = manager;
}
protected override void Dispose(bool disposing)
{
if (Pointer != IntPtr.Zero)
myManager.ReleaseMediaPlayer(this);
base.Dispose(disposing);
}
public static implicit operator IntPtr(VlcMediaPlayerInstance instance)
{
return instance != null
? instance.Pointer
: IntPtr.Zero;
}
}
} |
using System.Collections.Generic;
using TheMapToScrum.Back.BLL.Interfaces;
using TheMapToScrum.Back.BLL.Mapping;
using TheMapToScrum.Back.DAL.Entities;
using TheMapToScrum.Back.DTO;
using TheMapToScrum.Back.Repositories.Contract;
namespace TheMapToScrum.Back.BLL
{
public class DepartmentLogic : IDepartmentLogic
{
private readonly IDepartmentRepository _repo;
public DepartmentLogic(IDepartmentRepository repo)
{
_repo = repo;
}
public DepartmentDTO Create(DepartmentDTO objet)
{
Department entite = MapDepartment.ToEntity(objet, true);
Department resultat = _repo.Create(entite);
objet = MapDepartmentDTO.ToDto(resultat);
return objet;
}
public DepartmentDTO Update(DepartmentDTO objet)
{
Department entite = MapDepartment.ToEntity(objet, false);
Department resultat = _repo.Update(entite);
DepartmentDTO retour = MapDepartmentDTO.ToDto(resultat);
return retour;
}
public List<DepartmentDTO> List()
{
List<DepartmentDTO> retour = new List<DepartmentDTO>();
List<Department> liste = _repo.GetAll();
retour = MapDepartmentDTO.ToDto(liste);
return retour;
}
public List<DepartmentDTO> ListActive()
{
List<DepartmentDTO> retour = new List<DepartmentDTO>();
List<Department> liste = _repo.GetAllActive();
retour = MapDepartmentDTO.ToDto(liste);
return retour;
}
public DepartmentDTO GetById(int Id)
{
DepartmentDTO retour = new DepartmentDTO();
Department objet = _repo.Get(Id);
retour = MapDepartmentDTO.ToDto(objet);
return retour;
}
public bool Delete(int Id)
{
bool resultat = _repo.Delete(Id);
return resultat;
}
}
}
|
using System.Collections.Generic;
namespace gView.Framework.Data.Filters
{
public interface IRowIDFilter : IQueryFilter
{
List<int> IDs { get; set; }
string RowIDWhereClause { get; }
string IdFieldName { get; }
}
}
|
namespace CSharp
{
using System;
public class CompileErrorException : Exception
{
public CompileErrorException(string message)
: base(message)
{
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Kingdee.CAPP.Common.Logger
{
/// <summary>
/// Not Found Data Xml
/// </summary>
public class DataXmlNotFound: FileNotFoundException
{
public DataXmlNotFound()
: base()
{
/// ToDo
}
public DataXmlNotFound(string message)
: base(message)
{
}
}
}
|
public class Building
{
public TileData[,,] myData;
public Building(int size)
{
myData = new TileData[size, size, size];
}
}
|
// Copyright (C) 2008 Jesse Jones
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using NUnit.Framework;
using MObjc;
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[TestFixture]
public class ExportTests
{
[TestFixtureSetUp]
public void Init()
{
Registrar.CanInit = true;
m_pool = new NSObject(NSObject.AllocAndInitInstance("NSAutoreleasePool"));
}
[TestFixtureTearDown]
public void DeInit()
{
if (m_pool != null)
{
m_pool.release();
m_pool = null;
}
}
[SetUp]
public void Setup()
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
[Test]
public void NewTest()
{
Subclass1 instance = Subclass1.makeDefault();
instance.Call("initValue");
int value = (int) instance.Call("getValue");
Assert.AreEqual(100, value);
}
[Test]
public void StaticNewTest()
{
Class klass = new Class("Subclass1");
Subclass1 instance = klass.Call("makeDefault").To<Subclass1>();
instance.Call("initValue");
int value = (int) instance.Call("getValue");
Assert.AreEqual(100, value);
}
[Test]
public void CreateTest()
{
NSObject instance = (NSObject) new Class("Subclass1").Call("alloc").Call("init");
instance.Call("initValue");
int value = (int) instance.Call("getValue");
Assert.AreEqual(100, value);
}
[Test]
public void ManagedExceptionTest()
{
NSObject instance = new Class("Subclass1").Call("alloc").Call("init").To<NSObject>();
try
{
Managed.LogException = (e) => {};
instance.Call("BadValue");
}
catch (TargetInvocationException ie)
{
ArgumentException ae = (ArgumentException) ie.InnerException;
Assert.AreEqual("alpha", ae.ParamName);
}
finally
{
Managed.LogException = null;
}
}
[Test]
public void OverrideTest()
{
NSObject data = (NSObject) new Class("PrettyData").Call("alloc").Call("init");
int value = (int) data.Call("get33");
Assert.AreEqual(33, value);
NSObject istr = (NSObject) data.Call("description");
string str = Marshal.PtrToStringAuto((IntPtr) istr.Call("UTF8String"));
Assert.AreEqual("pretty: <>", str);
}
[Test]
[ExpectedException(typeof(InvalidCallException))]
public void BadSelector()
{
NSObject data = (NSObject) new Class("PrettyData").Call("alloc").Call("init");
data.Call("initWithUTF8String::", Marshal.StringToHGlobalAuto("hey"));
}
[Test]
public void BaseTest()
{
NSObject str = (NSObject) new Class("MyBase").Call("alloc").Call("init");
// can call NSString methods
sbyte b = (sbyte) str.Call("boolValue");
Assert.AreEqual(0, b);
// can call new MyBase methods
int i = (int) str.Call("get33");
Assert.AreEqual(33, i);
// can call overriden NSString methods
i = (int) str.Call("integerValue");
Assert.AreEqual(43, i);
}
[Test]
public void MyDerived()
{
NSObject str = (NSObject) new Class("MyDerived").Call("alloc").Call("init");
// can call NSString methods
sbyte b = (sbyte) str.Call("boolValue");
Assert.AreEqual(0, b);
// can call MyBase methods
int i = (int) str.Call("get33");
Assert.AreEqual(33, i);
// can call new MyDerived methods
i = (int) str.Call("get63");
Assert.AreEqual(63, i);
// can call overriden NSString methods
i = (int) str.Call("intValue");
Assert.AreEqual(73, i);
// can call overriden MyBase methods
i = (int) str.Call("integerValue");
Assert.AreEqual(74, i);
}
[Test]
public void IVarTest()
{
NSObject instance = (NSObject) new Class("Subclass1").Call("alloc").Call("init");
// ivars start out null
NSObject data = instance["myData"];
Assert.IsTrue(data == null);
// ivars can be set
Class klass = new Class("NSString");
NSObject str = (NSObject) klass.Call("stringWithUTF8String:", Marshal.StringToHGlobalAuto("hello"));
long count = str.retainCount();
instance["myData"] = str;
// the ref count of the value should be incremented when it is
// assigned to an ivar
Assert.AreEqual(count + 1, str.retainCount());
// and we can get the value we set
NSObject result = instance["myData"];
Assert.AreEqual((IntPtr) str, (IntPtr) result);
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void BadIVarGetTest()
{
NSObject instance = (NSObject) new Class("Subclass1").Call("alloc").Call("init");
NSObject data = instance["xxx"];
Assert.IsTrue(data != null);
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void BadIVarSetTest()
{
NSObject instance = (NSObject) new Class("Subclass1").Call("alloc").Call("init");
instance["xxx"] = instance;
}
[Test]
public void UShortArg()
{
NSObject instance = (NSObject) new Class("Subclass1").Call("alloc").Call("init");
ushort n = (ushort) instance.Call("TakeUInt162", (ushort) 12);
Assert.AreEqual(22, n);
}
[Test]
public void StringArg()
{
NSObject instance = (NSObject) new Class("Subclass1").Call("alloc").Call("init");
NSString n = (NSString) instance.Call("TakeString", NSString.Create("hmm"));
Assert.AreEqual("hmmhmm", n.ToString());
}
[Test]
public void ObjectArg1()
{
Subclass1 x = Subclass1.make(13);
Subclass1 y = Subclass1.make(1);
int n = (int) x.Call("TakeBase", y);
Assert.AreEqual(3, n);
}
[Test]
public void ObjectArg2()
{
NSObject x = Subclass1.make(13);
NSObject y = Subclass1.make(1);
int n = (int) x.Call("TakeBase", y);
Assert.AreEqual(3, n);
}
[Test]
public void DerivedArg()
{
Subclass1 x = Subclass1.make(13);
NSString s = NSString.Create("hey");
NSString t = x.Call("concat", s, s).To<NSString>();
Assert.AreEqual("heyhey", t.description());
}
[Test]
public void ObjectResult()
{
NSObject instance = (NSObject) new Class("PrettyData").Call("alloc").Call("init");
string s = (string) instance.description();
Assert.IsTrue(s.StartsWith("pretty: "));
}
[Test]
public void StructTest()
{
NSObject instance = (NSObject) new Class("Subclass1").Call("alloc").Call("init");
NSRange range = new NSRange();
range.location = 5;
range.length = 3;
int result = (int) instance.Call("DiffRange", range);
Assert.AreEqual(result, 2);
}
[Test]
public void NestedStructTest1()
{
NSObject instance = (NSObject) new Class("Subclass1").Call("alloc").Call("init");
NSRect r = (NSRect) instance.Call("GetRect");
Assert.AreEqual(1.0f, r.origin.x);
Assert.AreEqual(2.0f, r.origin.y);
Assert.AreEqual(3.0f, r.size.width);
Assert.AreEqual(4.0f, r.size.height);
}
[Test]
public void NestedStructTest2()
{
NSObject instance = (NSObject) new Class("Subclass1").Call("alloc").Call("init");
NSRect r = new NSRect();
r.origin.x = 1.0f;
r.origin.y = 2.0f;
r.size.width = 3.0f;
r.size.height = 4.0f;
NSObject istr = (NSObject) instance.Call("MungeRect", r);
string str = Marshal.PtrToStringAuto((IntPtr) istr.Call("UTF8String"));
Assert.AreEqual("1234", str);
}
[Test]
public void IVarTest2()
{
Subclass1 instance = Subclass1.makeDefault();
// Can set ivars using IVar.
instance.Data = "hey";
NSString s = (NSString) instance["myData"];
Assert.AreEqual("hey", s.ToString());
// Can get ivars using IVar.
Assert.AreEqual("hey", instance.Data);
}
private NSObject m_pool;
}
|
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using Tamir.SharpSsh;
using Tamir.SharpSsh.jsch;
namespace JDE_Integration_HDL
{
public class SFTPImportExport
{
public string ServerType = string.Empty;
public string ServerIP = string.Empty;
public string UserName = string.Empty;
public string Password = string.Empty;
public string PortNo = string.Empty;
public string RemoteFilePath = string.Empty;
public string DestPath = string.Empty;
public string Name_Con = string.Empty;
public string InputFile = string.Empty;
private StringBuilder sb = new StringBuilder();
public string GettingFilesFromOracleSFTP(string SFTPDetails, string strInputFile)
{
try
{
StreamReader streamReader = new StreamReader((Stream)System.IO.File.OpenRead(SFTPDetails));
string[] strArray = streamReader.ReadLine().Split('|');
InputFile = strInputFile;
while (!streamReader.EndOfStream)
{
string str = streamReader.ReadLine();
if (str.Split('|').Length == strArray.Length)
{
strArray = str.Split('|');
for (int index = 0; index < strArray.Length; ++index)
{
ServerIP = strArray[0].ToString();
ServerType = strArray[1].ToString();
PortNo = strArray[2].ToString();
UserName = strArray[3].ToString();
Password = strArray[4].ToString();
Name_Con = strArray[5].ToString();
RemoteFilePath = strArray[6].ToString();
DestPath = strArray[7].ToString();
}
}
if (ServerType == "SFTP")
GettingFileFrom_SFTP_Server();
else if (ServerType == "FTP")
GettingFileFrom_FTP_Server();
}
}
catch (Exception ex)
{
throw ex;
}
return sb.ToString();
}
private void GettingFileFrom_SFTP_Server()
{
try
{
int num = 0;
string str = string.Empty;
Console.WriteLine("............Downloading Files from SFTP............" + Environment.NewLine + Environment.NewLine);
Console.WriteLine("SFTP Connection initiated successfully." + Environment.NewLine);
this.sb.Append("............Downloading Files from SFTP............" + Environment.NewLine + Environment.NewLine);
this.sb.Append("SFTP Connection initiated successfully." + Environment.NewLine);
Sftp sftp = new Sftp(this.ServerIP, this.UserName, this.Password);
if (this.PortNo != "")
{
sftp.Connect(int.Parse(this.PortNo));
}
else
{
sftp.Connect();
}
Console.WriteLine("SFTP Connection Opened successfully." + Environment.NewLine);
this.sb.Append("SFTP Connection Opened successfully." + Environment.NewLine);
foreach (string str2 in sftp.GetFileList(this.RemoteFilePath))
{
int index = 0;
while (true)
{
char[] separator = new char[] { ',' };
if (index >= this.Name_Con.Split(separator).Length)
{
break;
}
char[] chArray = new char[] { ',' };
if (str2.ToString().StartsWith(this.Name_Con.Split(chArray).GetValue(index).ToString()))
{
sftp.Get(this.RemoteFilePath + "/" + str2, this.DestPath);
Console.WriteLine("The file '" + str2.ToString() + "' has been successfully downloaded in '" + this.DestPath + "'" + Environment.NewLine);
this.sb.Append("The file '" + str2.ToString() + "' has been successfully downloaded in '" + this.DestPath + "'" + Environment.NewLine);
num++;
if (this.DestPath.TrimEnd(new char[] { '\\' }) == this.InputFile.TrimEnd(new char[] { '\\' }))
{
if (str != "")
{
str = str + ",";
}
str = str + this.RemoteFilePath + "/" + str2;
}
}
index++;
}
}
if (str != "")
{
int index = 0;
while (true)
{
char[] separator = new char[] { ',' };
if (index >= str.Split(separator).Length)
{
break;
}
MethodInfo getMethod = sftp.GetType().GetProperty("SftpChannel", BindingFlags.NonPublic | BindingFlags.Instance).GetGetMethod(true);
object obj2 = getMethod.Invoke(sftp, null);
char[] chArray5 = new char[] { ',' };
((ChannelSftp)obj2).rm((String)str.Split(chArray5).GetValue(index).ToString());
index++;
}
}
}
catch (Exception exception1)
{
throw exception1;
}
}
private void GettingFileFrom_FTP_Server()
{
try
{
foreach (string ftpFile in GetFTPFileList())
{
if (ftpFile.ToString().Contains(Name_Con))
FTPFilesDownload(ftpFile);
}
}
catch (Exception ex)
{
throw ex;
}
}
private string[] GetFTPFileList()
{
string[] strArray2;
string str = "";
StringBuilder builder = new StringBuilder();
WebResponse response = null;
StreamReader reader = null;
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + this.ServerIP + str));
request.UseBinary = true;
request.Credentials = new NetworkCredential(this.UserName, this.Password);
request.Method = "NLST";
request.Proxy = null;
request.KeepAlive = false;
request.UsePassive = false;
reader = new StreamReader(request.GetResponse().GetResponseStream());
string str2 = reader.ReadLine();
while (true)
{
if (str2 == null)
{
builder.Remove(builder.ToString().LastIndexOf('\n'), 1);
strArray2 = builder.ToString().Split(new char[] { '\n' });
break;
}
builder.Append(str2);
builder.Append("\n");
str2 = reader.ReadLine();
}
}
catch (Exception)
{
if (reader != null)
{
reader.Close();
}
if (response != null)
{
response.Close();
}
strArray2 = null;
}
return strArray2;
}
private void FTPFilesDownload(string file)
{
string str = "";
try
{
if (new Uri("ftp://" + ServerIP + "/" + file).Scheme != Uri.UriSchemeFtp)
return;
FtpWebRequest ftpWebRequest = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + ServerIP + str + "/" + file));
ftpWebRequest.Credentials = (ICredentials)new NetworkCredential(UserName, Password);
ftpWebRequest.KeepAlive = false;
ftpWebRequest.Method = "RETR";
ftpWebRequest.UseBinary = true;
ftpWebRequest.Proxy = (IWebProxy)null;
ftpWebRequest.UsePassive = false;
FtpWebResponse response = (FtpWebResponse)ftpWebRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
FileStream fileStream = new FileStream(DestPath + file, FileMode.Create);
int count1 = 2048;
byte[] buffer = new byte[count1];
for (int count2 = responseStream.Read(buffer, 0, count1); count2 > 0; count2 = responseStream.Read(buffer, 0, count1))
fileStream.Write(buffer, 0, count2);
Console.WriteLine(file + " has been downloaded from FTP to '" + DestPath + "'" + Environment.NewLine);
sb.Append(file + " has been downloaded from FTP to '" + DestPath + "'" + Environment.NewLine);
fileStream.Close();
response.Close();
}
catch (WebException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Projeto.Domain.Models
{
public class Turma
{
public Guid Id { get; set; }
public string Descricao { get; set; }
public DateTime DataIniciio { get; set; }
public Turma() { }
public Turma(Guid id, string descricao, DateTime dataIniciio)
{
Id = id;
Descricao = descricao;
DataIniciio = dataIniciio;
}
#region Professor
public Guid ProfessorId { get; set; }
public Professor Professor { get; set; }
#endregion
#region Aluno
public List<TurmaAluno> Alunos { get; set; }
#endregion
}
}
|
namespace BudgetApp.Domain.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using BudgetApp.Domain.Concrete;
using BudgetApp.Domain.Entities;
using System.Collections.Generic;
internal sealed class Configuration : DbMigrationsConfiguration<BudgetApp.Domain.DAL.LedgerDBContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(BudgetApp.Domain.DAL.LedgerDBContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
var PaymentPlans = new List<PaymentPlanEntry>
{
//new PaymentPlanEntry { id=4, PaymentDate=DateTime.Parse("2013-03-01"), Card="American Express", PaymentTotal=40.0M },
};
PaymentPlans.ForEach(p => context.PaymentPlanEntries.Add(p));
context.SaveChanges();
}
}
}
|
using gView.Framework.Geometry;
using System;
using System.Collections.Generic;
namespace gView.Framework.Data
{
public class GridIndex<T> where T : class
{
private IEnvelope _bounds;
private int _cellsX, _cellsY;
private double _cX, _cY;
private Dictionary<int, T> _gridCellContainer = new Dictionary<int, T>();
public GridIndex(IEnvelope bounds, int cells)
: this(bounds, cells, cells)
{
}
public GridIndex(IEnvelope bounds, int cellsX, int cellsY)
{
if (bounds == null || cellsX <= 0 || cellsY <= 0)
{
throw new ArgumentException();
}
_bounds = new Envelope(bounds);
((Envelope)_bounds).Raise(120);
_cellsX = cellsX;
_cellsY = cellsY;
_cX = _bounds.Width / cellsX;
_cY = _bounds.Height / cellsY;
}
#region Members
public int XIndex(IPoint p)
{
if (p == null)
{
return -1;
}
int i = (int)Math.Floor((p.X - _bounds.minx) / _cX);
if (i < 0 || i >= _cellsX)
{
return -1;
}
return i;
}
public int YIndex(IPoint p)
{
if (p == null)
{
return -1;
}
int i = (int)Math.Floor((p.Y - _bounds.miny) / _cY);
if (i < 0 || i >= _cellsY)
{
return -1;
}
return i;
}
public int XYIndex(IPoint p)
{
int ix = XIndex(p);
int iy = YIndex(p);
if (ix < 0 || iy < 0)
{
return -1;
}
return iy * _cellsX + ix;
}
public List<int> XYIndices(IEnvelope env)
{
List<int> ret = new List<int>();
int i = XYIndex(new Point(env.minx, env.miny));
ret.Add(i);
i = XYIndex(new Point(env.minx, env.maxy));
if (!ret.Contains(i))
{
ret.Add(i);
}
i = XYIndex(new Point(env.maxx, env.maxy));
if (!ret.Contains(i))
{
ret.Add(i);
}
i = XYIndex(new Point(env.maxx, env.miny));
if (!ret.Contains(i))
{
ret.Add(i);
}
return ret;
}
public T this[int index]
{
get
{
if (_gridCellContainer.ContainsKey(index))
{
return _gridCellContainer[index];
}
return null;
}
set
{
if (_gridCellContainer.ContainsKey(index))
{
_gridCellContainer[index] = value;
}
else
{
_gridCellContainer.Add(index, value);
}
}
}
public T[] AllCells
{
get
{
List<T> ret = new List<T>();
foreach (int key in _gridCellContainer.Keys)
{
T t = _gridCellContainer[key];
if (t == null)
{
continue;
}
ret.Add(t);
}
return ret.ToArray();
}
}
#endregion
}
public class GridArray<T> where T : class
{
private List<GridIndex<T>> _grids = null;
private T _outside;
public GridArray(IEnvelope bounds, int[] cellsX, int[] cellsY)
{
if (cellsX != null && cellsY != null && cellsX.Length == cellsY.Length)
{
_grids = new List<GridIndex<T>>();
for (int i = 0; i < cellsX.Length; i++)
{
_grids.Add(new GridIndex<T>(bounds, cellsX[i], cellsY[i]));
}
_outside = Activator.CreateInstance(typeof(T)) as T;
}
}
#region Members
public T this[IEnvelope env]
{
get
{
foreach (GridIndex<T> grid in _grids)
{
List<int> gridIndices = grid.XYIndices(env);
if (gridIndices.Count == 1)
{
T ret = grid[gridIndices[0]];
if (ret == null)
{
ret = Activator.CreateInstance(typeof(T)) as T;
grid[gridIndices[0]] = ret;
}
return ret;
}
}
return _outside;
}
}
public List<T> Collect(IEnvelope env)
{
List<T> list = new List<T>();
list.Add(_outside);
foreach (GridIndex<T> grid in _grids)
{
foreach (int index in grid.XYIndices(env))
{
T t = grid[index];
if (t != null)
{
list.Add(t);
}
}
}
return list;
}
#endregion
}
}
|
// <copyright file="MyProfileViewModel.cs" company="Caspian Pacific Tech">
// Copyright (c) Caspian Pacific Tech. All rights reserved.
// </copyright>
namespace SmartLibrary.Site.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure;
using SmartLibrary.Infrastructure.DataAnnotations;
using SmartLibrary.Models;
/// <summary>
/// This class is used to Define Model for Table - Customer
/// </summary>
/// <CreatedBy>Bhargav Aboti</CreatedBy>
/// <CreatedDate>20-Sep-2018</CreatedDate>
/// <ModifiedBy></ModifiedBy>
/// <ModifiedDate></ModifiedDate>
/// <ReviewBy></ReviewBy>
/// <ReviewDate></ReviewDate>
public class MyProfileViewModel : BaseModel
{
#region Properties
/// <summary>
/// Gets or sets the Id value.
/// </summary>
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[MappingAttribute(MapName = "Id")]
public int Id { get; set; }
/// <summary>
/// Gets or sets the FirstName value.
/// </summary>
[RestrictSpecialCharacters]
[Required(ErrorMessageResourceType = typeof(Resources.Messages), ErrorMessageResourceName = "RequiredFieldMessage")]
[StringLength(50, ErrorMessageResourceType = typeof(Resources.Messages), ErrorMessageResourceName = "StringLengthMessage")]
[MappingAttribute(MapName = "FirstName")]
public string FirstName { get; set; }
/// <summary>
/// Gets or sets the LastName value.
/// </summary>
[RestrictSpecialCharacters]
[Required(ErrorMessageResourceType = typeof(Resources.Messages), ErrorMessageResourceName = "RequiredFieldMessage")]
[StringLength(50, ErrorMessageResourceType = typeof(Resources.Messages), ErrorMessageResourceName = "StringLengthMessage")]
[MappingAttribute(MapName = "LastName")]
public string LastName { get; set; }
/// <summary>
/// Gets or sets the Email value.
/// </summary>
[Required(ErrorMessageResourceType = typeof(Resources.Messages), ErrorMessageResourceName = "RequiredFieldMessage")]
[Display(Name = "EmailAddress", ResourceType = typeof(Resources.Account))]
[StringLength(75, ErrorMessageResourceType = typeof(Resources.Messages), ErrorMessageResourceName = "StringLengthMessage")]
[RegularExpression(SmartLibrary.Models.RegularExpressions.Email, ErrorMessageResourceType = typeof(Resources.Account), ErrorMessageResourceName = "InvalidEmailAddress")]
[MappingAttribute(MapName = "Email")]
public string Email { get; set; }
/// <summary>
/// Gets or sets the Gender value.
/// </summary>
[MappingAttribute(MapName = "Gender")]
public int? Gender { get; set; }
/// <summary>
/// Gets or sets the Phone value.
/// </summary>
[RegularExpression(@"^(?:\+971|00971|0)(?:2|3|4|6|7|9|50|51|52|55|56)[0-9]{7}$", ErrorMessageResourceType = typeof(Resources.Messages), ErrorMessageResourceName = "InvalidPhoneNumber")]
[MappingAttribute(MapName = "Phone")]
public string Phone { get; set; }
/// <summary>
/// Gets or sets the Password value.
/// </summary>
[StringLength(125, MinimumLength = 6, ErrorMessageResourceType = typeof(Resources.Messages), ErrorMessageResourceName = "PasswordLengthMessageMinMax")]
[DataType(DataType.Password)]
[MappingAttribute(MapName = "Password")]
public string Password { get; set; }
/// <summary>
/// Gets or sets the Active value.
/// </summary>
[MappingAttribute(MapName = "Active")]
public bool? Active { get; set; }
/// <summary>
/// Gets or sets the ProfileImage value.
/// </summary>
[MappingAttribute(MapName = "ProfileImagePath")]
public string ProfileImagePath { get; set; }
/// <summary>
/// Gets or sets the Language value.
/// </summary>
[MappingAttribute(MapName = "Language")]
public short? Language { get; set; }
/// <summary>
/// Gets or sets the CreatedBy value.
/// </summary>
public int? CreatedBy { get; set; }
/// <summary>
/// Gets or sets the CreatedBy Name value.
/// </summary>
[NotMapped]
public string CreatedByName { get; set; }
/// <summary>
/// Gets or sets the CreatedDate value.
/// </summary>
public DateTime? CreatedDate { get; set; }
/// <summary>
/// Gets or sets the ModifiedBy value.
/// </summary>
public int? ModifiedBy { get; set; }
/// <summary>
/// Gets or sets the ModifiedDate value.
/// </summary>
public DateTime? ModifiedDate { get; set; }
/// <summary>
/// Gets or sets the Name value.
/// </summary>
[NotMapped]
public string Name { get; set; }
/// <summary>
/// Gets or sets the Status value.
/// </summary>
[NotMapped]
public string Status { get; set; }
/// <summary>
/// Gets or sets Password
/// </summary>
[NotMapped]
[StringLength(125, MinimumLength = 6, ErrorMessageResourceType = typeof(Resources.Messages), ErrorMessageResourceName = "PasswordLengthMessageMinMax")]
[DataType(DataType.Password)]
[Display(Name = "NewPassword", ResourceType = typeof(Resources.Account))]
[RegularExpression(SmartLibrary.Models.RegularExpressions.HtmlTag, ErrorMessageResourceType = typeof(Resources.Account), ErrorMessageResourceName = "InvalidNewPassword")]
public string NewPassword { get; set; }
/// <summary>
/// Gets or sets Password
/// </summary>
[NotMapped]
[StringLength(125, MinimumLength = 6, ErrorMessageResourceType = typeof(Resources.Messages), ErrorMessageResourceName = "PasswordLengthMessageMinMax")]
[DataType(DataType.Password)]
[Display(Name = "ConfirmPassword", ResourceType = typeof(Resources.Account))]
[Compare(nameof(NewPassword), ErrorMessageResourceType = typeof(Resources.Account), ErrorMessageResourceName = "NewPasswordAndConfirmPasswordNotMatch")]
[RegularExpression(SmartLibrary.Models.RegularExpressions.HtmlTag, ErrorMessageResourceType = typeof(Resources.Account), ErrorMessageResourceName = "InvalidConfirmPassword")]
public string ConfirmPassword { get; set; }
#endregion
}
} |
using System;
namespace Phenix.Test.使用指南._12._6._2._8
{
/// <summary>
/// Serial_AllowIgnoreCheckDirty
/// </summary>
[Serializable]
//* 指定本类允许忽略校验数据库数据在下载到提交期间是否被更改过:AllowIgnoreCheckDirty = true
[Phenix.Core.Mapping.ClassAttribute("PH_SERIAL", FriendlyName = "Serial", AllowIgnoreCheckDirty = true)]
public class Serial_AllowIgnoreCheckDirty : Serial<Serial_AllowIgnoreCheckDirty>
{
}
}
|
using EPiServer.Core;
using EPiServer.DataAbstraction;
namespace PageStructureBuilder
{
public abstract class PageTypeStructureBase<TContainer> :
SingleLevelStructureBase<TContainer>
where TContainer : PageData
{
protected override string GetContainerPageName(
PageData childPage)
{
var pageType = PageType.Load(childPage.PageTypeID);
return pageType.Name;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Json;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Com.Aote.ObjectTools;
namespace s2.Pages
{
public partial class 多次未安检用户排查明细 : UserControl
{
public 多次未安检用户排查明细()
{
InitializeComponent();
}
private void btnSearch_Click(object sender, RoutedEventArgs e)
{
String dt = "1=1";
if (StartDate.Text.Trim().Length != 0)
dt = " DEPARTURE_TIME>='" + StartDate.Text + "'";
String dt2 = "1=1";
if (StartDate.Text.Trim().Length != 0)
dt2 = " DEPARTURE_TIME<='" + EndDate.Text + "'";
checkerList.Path = "sql";
checkerList.Names = "f_userid,f_username,cishu,f_districtname,f_cusDom,f_cusDy,f_cusFloor,f_apartment,f_phone,f_address";
String sql = @"select e.f_userid,f_username,cishu,f_districtname,f_cusDom,f_cusDy,f_cusFloor,f_apartment,f_phone,f_address from t_userfiles u inner join
(select f_userid,COUNT(f_userid) as cishu from T_INSPECTION where " + dt + " and " + dt2 + "and (condition='拒检' or condition='无人') group by f_userid) e on u.f_userid=e.f_userid ";
checkerList.HQL = sql;
checkerList.Load();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace TestHouse.DTOs.DTOs
{
public class TestRunDto
{
/// <summary>
/// Test run id
/// </summary>
public long Id { get; set; }
/// <summary>
/// Test run name
/// </summary>
public string Name { get; set; }
/// <summary>
/// Test run description
/// </summary>
public string Description { get; set; }
/// <summary>
/// List of test cases
/// </summary>
public IEnumerable<TestRunCaseDto> TestCases { get; set; }
/// <summary>
/// Creation date
/// </summary>
public DateTime CreatedAt { get; set; }
}
}
|
using System.Collections.Generic;
namespace CalculatorServices.WebAPI.DTOs
{
public class MultRequest
{
public List<int> Factors { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Reflection.Emit;
using RimWorld;
using Verse;
using UnityEngine;
using Harmony;
namespace DontShaveYourHead
{
[HarmonyPatch(typeof(PawnRenderer), "RenderPawnInternal", new Type[] { typeof(Vector3), typeof(float), typeof(bool), typeof(Rot4), typeof(Rot4), typeof(RotDrawMode), typeof(bool), typeof(bool) })]
public static class Harmony_PawnRenderer
{
private const float DrawOffset = 0.03515625f;
// Reroute of hair DrawMeshNowOrLater call. Replaces normal hair mat with our own
public static void DrawHairReroute(Mesh mesh, Vector3 loc, Quaternion quat, Material mat, bool isPortrait, Pawn pawn, Rot4 facing)
{
// Check if we need to recalculate hair
if (!isPortrait || !Prefs.HatsOnlyOnMap)
{
mat = HairUtility.GetHairMatFor(pawn, facing);
}
GenDraw.DrawMeshNowOrLater(mesh, loc, quat, mat, isPortrait);
}
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
const float hatOffset = 0.03125f;
var writing = false;
foreach (var code in instructions)
{
// Apply draw offset for hat rendering
if (code.opcode == OpCodes.Ldc_R4 && (float)code.operand == hatOffset)
{
yield return new CodeInstruction(OpCodes.Ldc_R4, DrawOffset + hatOffset);
}
// Skip hide hair flag
else if (code.opcode == OpCodes.Ldloc_S && code.operand is LocalBuilder b && b.LocalIndex == 13)
{
var newCode = new CodeInstruction(OpCodes.Ldc_I4_0) { labels = code.labels };
yield return newCode;
}
// Replace hair draw mesh call
else if (code.opcode == OpCodes.Callvirt && code.operand == AccessTools.Method(typeof(PawnGraphicSet), nameof(PawnGraphicSet.HairMatAt)))
{
writing = true;
yield return code;
}
else if (writing && code.opcode == OpCodes.Call && code.operand == AccessTools.Method(typeof(GenDraw), nameof(GenDraw.DrawMeshNowOrLater)))
{
writing = false;
yield return new CodeInstruction(OpCodes.Ldarg_0);
yield return new CodeInstruction(OpCodes.Ldfld, AccessTools.Field(typeof(PawnRenderer), "pawn"));
yield return new CodeInstruction(OpCodes.Ldarg, 5);
yield return new CodeInstruction(OpCodes.Callvirt, AccessTools.Method(typeof(Harmony_PawnRenderer), nameof(DrawHairReroute)));
}
// Default
else
{
yield return code;
}
}
/*
var codes = instructions.ToList();
// look for headGraphic block
var idxHGfx = codes.FirstIndexOf(ci => ci.operand == typeof(PawnGraphicSet).GetField(nameof(PawnGraphicSet.headGraphic)));
if (idxHGfx == -1)
{
Log.Error("Could not find headGraphics block start");
return codes;
}
var postHeadGraphicsLabel = (Label)codes[idxHGfx + 1].operand;
var idxHGfxEnd = codes.FirstIndexOf(ci => ci.labels.Any(l => l == postHeadGraphicsLabel));
if (idxHGfxEnd == -1)
{
Log.Error("Could not find headGraphics block end");
return codes;
}
// head block contents atart at idxHGfx +2 , and at idxHGfxEnd -1
var idxbodyDrawType = -1;
for (var i = idxHGfx + 2; i < idxHGfxEnd - 1; i++)
{
if (codes[i].opcode == OpCodes.Ldarg_S && ((byte)6).Equals(codes[i].operand))
{
idxbodyDrawType = i;
}
}
if (idxbodyDrawType == -1)
{
Log.Error("Could not find bodyDrawType reference");
return codes;
}
codes[idxbodyDrawType - 2].opcode = OpCodes.Ldc_I4_0; // 2nd use of bodyDrawType has <c>flag</c> we want to skip check of
codes[idxbodyDrawType - 2].operand = null;
// Get IL code of hatRenderedFrontOfFace to find hat render block
var hatBlockIndex = codes.FirstIndexOf(c => c.operand == typeof(ApparelProperties).GetField(nameof(ApparelProperties.hatRenderedFrontOfFace)));
// Find next DrawMeshNowOrLaterCall as it is responsible for drawing non-mask hats
for (var i = hatBlockIndex; i < codes.Count; i++)
{
var code = codes[i];
if (code.operand == typeof(GenDraw).GetMethod(nameof(GenDraw.DrawMeshNowOrLater)))
{
code.operand = typeof(Harmony_PawnRenderer).GetMethod(nameof(Harmony_PawnRenderer.DrawHatNowOrLaterShifted)); // Reroute to custom method
break;
}
}
// Find hair DrawMeshNowOrLaterCall to reroute
var foundHairMatAt = false;
var headFacingCode = new CodeInstruction(OpCodes.Nop); // Code that pushes headFacing argument
for (var i = hatBlockIndex; i < codes.Count; i++)
{
// Find hair block
var code = codes[i];
if (code.operand == typeof(PawnGraphicSet).GetMethod(nameof(PawnGraphicSet.HairMatAt)))
{
foundHairMatAt = true;
headFacingCode = codes[i - 1];
}
// Find and replace hair draw call
if (foundHairMatAt
&& code.operand == typeof(GenDraw).GetMethod(nameof(GenDraw.DrawMeshNowOrLater)))
{
// Reroute draw call
code.operand = typeof(Harmony_PawnRenderer).GetMethod(nameof(DrawHairReroute));
// Insert argument calls
var newCodes = new List<CodeInstruction>
{
new CodeInstruction(OpCodes.Ldarg_0),
new CodeInstruction(OpCodes.Ldfld, typeof(PawnRenderer).GetField("pawn", BindingFlags.NonPublic | BindingFlags.Instance)),
new CodeInstruction(headFacingCode.opcode, headFacingCode.operand)
};
codes.InsertRange(i, newCodes);
break;
}
}
if (!foundHairMatAt)
{
Log.Error("DSYH :: Failed to find HairMatAt call");
}
return codes;*/
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.