text stringlengths 13 6.01M |
|---|
namespace YouScan.Sale
{
public class DiscountSettings
{
public double MinAmount { get; set; }
public double? MaxAmount { get; set; }
public double Percentage { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using ORM.ResourceParameters;
using ORM.Models;
namespace ORM.Services
{
public interface IORM
{
List<Exception> ExceptionLogging { get; set; }
Task<Customer> Authenticate(string email, string password);
void OpenConn();
Task CloseConn();
//-----------------------------------------Adresse_Type-----------------------------------------//
//Get requests
Task<List<Address_Type>> GetAllAdresseTypes();
Task<Address_Type> GetAdresseTypeById(int id);
//Delete requests
Task<int> DeleteAdresseType(int id);
//Create requests
Task<Address_Type> CreateAdresseType(Address_Type adresse_Type);
//Update requests
Task<int> UpdateAdresseType(Address_Type adresse_Type);
//-----------------------------------------Adresse-----------------------------------------//
Task<List<Addresses>> GetAllAdresses();
Task<Addresses> GetAddressById(int id);
Task<int> DeleteAddress(int id);
Task<Addresses> CreateAddress(Addresses address);
Task<int> UpdateAddress(Addresses address);
//-----------------------------------------Department-----------------------------------------//
//Get requests
Task<List<Department>> GetAllDepartments();
Task<Department> GetDepartmentById(int id);
//Delete requests
Task<int> DeleteDepartment(int id);
//Create requests
Task<Department> CreateDepartment(Department department);
//Update requests
Task<int> UpdateDepartment(Department department);
//-----------------------------------------Shop-----------------------------------------//
//Get requests
Task<List<Shop>> GetAllShops();
Task<Shop> GetShopById(int id);
//Delete requests
Task<int> DeleteShop(int id);
//Create requests
Task<Shop> CreateShop(Shop shop);
//Update requests
Task<int> UpdateShop(Shop shop);
//-----------------------------------------ShopWarehouse-----------------------------------------//
//Get requests
Task<List<Shop_Item>> GetAllShopWarehouses();
Task<List<Shop_Item>> GetShopWarehouseByShopID(int id);
//Delete requests
Task<int> DeleteShopWarehouse(Shop_Item shopWarehouse);
//Create requests
Task CreateShopWarehouse(Shop_Item shopWarehouse);
//Update requests
Task<int> UpdateShopWarehouse(Shop_Item shopWarehouse);
//-----------------------------------------Category-----------------------------------------//
//Get requests
Task<List<Category>> GetAllCategories();
Task<Category> GetCategoryById(int id);
//Delete requests
Task<int> DeleteCategory(int id);
//Create requests
Task<Category> CreateCategory(Category category);
//Update requests
Task<int> UpdateCategory(Category category);
//-----------------------------------------Customer-----------------------------------------//
//Get requests
Task<bool> CustomerExist(int id);
Task<List<Customer>> GetAllCustomers();
Task<List<Customer>> GetAllCustomers(CustomerParameters customParameters);
Task<Customer> GetCustomerById(int id);
//Delete requests
Task<int> DeleteCustomer(int id);
Task<int> DeleteCustomerData(int id);
//Create requests
Task<Customer> CreateCustomer(Customer customer);
//Update requests
Task<int> UpdateCustomer(Customer customer);
//-----------------------------------------Customer_Addresses-----------------------------------------//
//Get requests
Task<List<Customer_Addresses>> GetAllCustomerAddresses();
Task<List<Customer_Addresses>> GetCustomerAddressesByCustomerID(int id);
//Delete requests
Task<int> DeleteCustomerAddresses(Customer_Addresses customer_Addresses);
//Create requests
Task CreateCustomerAddresses(Customer_Addresses customer_Addresses);
//Update requests
Task<int> UpdateCustomerAddresses(Customer_Addresses customer_Addresses);
//-----------------------------------------Lager_Status-----------------------------------------//
//Get requests
Task<List<Warehouse_Status>> GetAllWarehouseStatus();
Task<Warehouse_Status> GetWarehouseStatusById(int id);
//Delete requests
Task<int> DeleteWarehouseStatus(int id);
//Create requests
Task<Warehouse_Status> CreateWarehouseStatus(Warehouse_Status warehouse_Status);
//Update requests
Task<int> UpdateWarehouseStatus(Warehouse_Status warehouse_Status);
//-----------------------------------------Supplier-----------------------------------------//
//Get requests
Task<List<Supplier>> GetAllSuppliers();
Task<Supplier> GetSupplierById(int id);
//Delete requests
Task<int> DeleteSupplier(int id);
//Create requests
Task<Supplier> CreateSupplier(Supplier supplier);
//Update requests
Task<int> UpdateSupplier(Supplier supplier);
//-----------------------------------------Employee-----------------------------------------//
//Get requests
Task<List<Employee>> GetAllEmployees();
Task<Employee> GetEmployeeById(int id);
//Delete requests
Task<int> DeleteEmployee(int id);
//Create requests
Task<Employee> CreateEmployee(Employee employee);
//Update requests
Task<int> UpdateEmployee(Employee employee);
//-----------------------------------------Order-----------------------------------------//
//Get requests
Task<List<Order>> GetAllOrders();
Task<Order> GetOrderById(int id);
Task<List<Order>> GetOrdersByCustomerId(int customerID);
Task<Order> CreateOrderAndOrderLines(Order order);
//Delete requests
Task<int> DeleteOrder(int id);
//Create requests
Task<Order> CreateOrder(Order order);
//Update requests
Task<int> UpdateOrder(Order order);
//-----------------------------------------Order_Leverings_Metode-----------------------------------------//
//Get requests
Task<List<Order_Delivery_Method>> GetAllOrderDeliveryMethod();
Task<Order_Delivery_Method> GetOrderDeliveryMethodById(int id);
//Delete requests
Task<int> DeleteOrderDeliveryMethod(int id);
//Create requests
Task<Order_Delivery_Method> CreateOrderDeliveryMethod(Order_Delivery_Method order_Delivery_Method);
//Update requests
Task<int> UpdateOrderDeliveryMethod(Order_Delivery_Method order_Delivery_Method);
//-----------------------------------------Order_Status-----------------------------------------//
//Get requests
Task<List<Order_Status>> GetAllOrder_Status();
Task<Order_Status> GetOrder_StatusById(int id);
//Delete requests
Task<int> DeleteOrder_Status(int id);
//Create requests
Task<Order_Status> CreateOrder_Status(Order_Status Order_Status);
//Update requests
Task<int> UpdateOrder_Status(Order_Status Order_Status);
//-----------------------------------------OrderLines-----------------------------------------//
//Get requests
Task<List<OrderLine>> GetAllOrderLines();
Task<List<OrderLine>> GetOrderLinesByOrderID(int id);
//Delete requests
Task<int> DeleteOrderLines(OrderLine orderLines);
//Create requests
//Task CreateOrderLines(OrderLine orderLines);
Task<List<OrderLine>> CreateOrderLines(List<OrderLine> orderLines, int orderID);
//Update requests
Task<int> UpdateOrderLines(OrderLine orderLines);
//-----------------------------------------ZipCode-----------------------------------------//
//Get requests
Task<List<ZipCode>> GetAllZipCode();
Task<ZipCode> GetZipCodeById(int id);
//Delete requests
Task<int> DeleteZipCode(int id);
//Create requests
Task<ZipCode> CreateZipCode(ZipCode zipCode);
//Update requests
Task<int> UpdateZipCode(ZipCode zipCode);
//-----------------------------------------Producent-----------------------------------------//
//Get requests
Task<List<Producent>> GetAllProducent();
Task<Producent> GetProducentById(int id);
//Delete requests
Task<int> DeleteProducent(int id);
//Create requests
Task<Producent> CreateProducent(Producent producent);
//Update requests
Task<int> UpdateProducent(Producent producent);
//-----------------------------------------Product-----------------------------------------//
//Get requests
Task<List<Product>> GetAllProducts();
Task<List<Product>> GetAllProducts(ProductsParameter productsParameter);
Task<Product> GetProductById(int id);
Task<List<Product>> GetProductsByProducentId(int id);
//Delete requests
Task<int> DeleteProduct(int id);
//Create requests
Task<Product> CreateProduct(Product product);
//Update requests
Task<int> UpdateProduct(Product product);
}
}
|
using System;
namespace Bridge
{
class Program
{
static void Main(string[] args)
{
var iPhoneFramework = new XamarinButtonControl(new IphoneKit());
iPhoneFramework.AddButton();
var androidFramework = new XamarinButtonControl(new AndroidKit());
androidFramework.AddButton();
}
}
}
|
using System;
namespace HelloWorld
{
class MainClass
{
public static void Main(string[] args)
{
if (254 < 255)
{ //this is going to print "Hello World!"
//I also added an if statement and a couple of extra lines
// of text just for fun and practice.
Console.WriteLine("Hello World!");
Console.WriteLine("My name is Parker Hague.");
Console.WriteLine("Nice to meet you!");
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace AlmenaraGames.Demo
{
public class SurfaceSound : MonoBehaviour
{
private void Update()
{
//Plays the Audio Object assigned to the Runtime Identifier "surfaceSound"
if (Input.GetKeyDown(KeyCode.Space))
{
MultiAudioManager.PlayAudioObjectByIdentifier("[rt]surfaceSound",transform.position);
}
}
// UI Code - IGNORE
public void OnGUI()
{
int xpos = 40;
int ypos = 20;
GUI.Label(new Rect(xpos, ypos + 64, 200, 40), "Press Spacebar to Play Surface Sound");
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ToggledObjects : MonoBehaviour
{
public List<GameObject> activate;
public List<GameObject> deactivate;
public void Toggle()
{
}
}
|
using System;
using System.Collections.Generic;
using DataAccess;
using DataAccess.Repositories;
using log4net;
using Nest;
namespace FirstMvcApp.Elastic
{
public class ElasticProvider
{
private const string c_indexName = "products";
private readonly ElasticClient m_client;
private readonly IProductRepository m_iProductRepository;
private readonly ILog m_logger;
public ElasticProvider()
{
var settings = new ConnectionSettings(new Uri("http://localhost:9200"), c_indexName);
m_client = new ElasticClient(settings);
m_iProductRepository = new ProductRepository();
m_logger = LogManager.GetLogger(typeof(ElasticProvider));
}
public void RebuildIndex()
{
m_client.DeleteIndex(c_indexName);
var myCustomAnalyzer = new CustomAnalyzer
{
CharFilter = new List<string> {"html_strip"},
Filter = new List<string> {"standard", "lowercase"},
Tokenizer = "standard"
};
var myAutocompleteAnalyzer = new CustomAnalyzer
{
CharFilter = new List<string> {"html_strip"},
Filter = new List<string>
{
"lowercase",
"my_edgengram",
"standard"
},
Tokenizer = "standard"
};
//client.CreateIndex(indexName, ci => ci.NumberOfReplicas(1)
// .NumberOfShards(5)
// //.Settings(s => s
// // .Add("analysis.char_filter.my_html_replacefilter.type","pattern_replace")
// // .Add("analysis.char_filter.my_html_replacefilter.pattern", @"([<>])")
// // .Add("analysis.char_filter.my_html_replacefilter.replacement", " "))
// .Analysis(d => d
// .Analyzers(an => an
// .Add("my_html_analyzer", myCustomAnalyzer)))
// .AddMapping<Product>(m => m
// //.CharFilters(cf => cf.Add("my_html_replacefilter", myFilter)))
// //.Tokenizers(t => t.Add("whitespace", new StandardTokenizer())))
// //.CharFilters(chf=>chf.Add("html_strip",new HtmlStripCharFilter())))
// //.TokenFilters(tf => tf.Add("my_filter", new LowercaseTokenFilter())))
// .AllField(s=>s
// .Analyzer("my_html_analyzer"))));
m_client.CreateIndex(c_indexName, ci => ci
.NumberOfReplicas(0)
.NumberOfShards(1)
.Analysis(d => d
.TokenFilters(tf => tf.Add("my_edgengram", new EdgeNGramTokenFilter
{
MaxGram = 20,
MinGram = 1,
Side = "front"
}))
.Analyzers(an => an
.Add("my_html_analyzer", myCustomAnalyzer)
.Add("my_autocomplete_analyzer", myAutocompleteAnalyzer)))
.AddMapping<Product>(m => m
.MapFromAttributes()
.Properties(p => p
.MultiField(mf => mf
.Name(pmf => pmf.Description)
.Fields(f => f
.String(fs => fs
.Name(pr => pr.Description).Index(FieldIndexOption.Analyzed)
.Analyzer("my_html_analyzer"))))
.MultiField(mf => mf
.Name(pmf => pmf.Name)
.Fields(f => f
.String(fs => fs
.Name(pr => pr.Name.Suffix("autocomplete")).Analyzer("my_autocomplete_analyzer"))
.String(fs => fs
.Name(pr => pr.Name.Suffix("nohtml")).Analyzer("my_html_analyzer"))
.String(fs => fs
.Name(pr => pr.Name.Suffix("exact")).Index(FieldIndexOption.NotAnalyzed))
.String(fs => fs
.Name(pr => pr.Name).Index(FieldIndexOption.Analyzed))))
.MultiField(mf => mf
.Name(pmf => pmf.Category)
.Fields(f => f
.String(fs => fs.Name(pr => pr.Category).Index(FieldIndexOption.Analyzed)
.Analyzer("my_html_analyzer"))))
.MultiField(mf => mf
.Name(pmf => pmf.Price)
.Fields(f => f
.String(fs => fs.Name(pr => pr.Price).Index(FieldIndexOption.Analyzed))))
.MultiField(mf => mf
.Name(pmf => pmf.ProductId)
.Fields(f => f
.String(fs => fs.Name(pr => pr.ProductId).Index(FieldIndexOption.NotAnalyzed)))))));
var iProducts = m_iProductRepository.GetEntities;
foreach (var iProduct in iProducts)
{
var product = new Product
{
ProductId = iProduct.ProductId,
Category = iProduct.Category,
Description = iProduct.Description,
Name = iProduct.Name,
Price = iProduct.Price
};
m_client.Index(product);
}
}
public SearchDescriptor<Product> GetAutocompleteDescriptor(string q)
{
var searchDescriptor = new SearchDescriptor<Product>()
.Filter(f => f
.Bool(fb => fb.Must(sb => sb
.Term(pr => pr.Name.Suffix("autocomplete"), q.ToLower()))));
return searchDescriptor;
}
public SearchDescriptor<Product> GetSearchDescriptor(string q, int page = 0, int pageSize = 0, bool exact = false)
{
var searchDescriptor = new SearchDescriptor<Product>();
if (exact)
{
searchDescriptor = searchDescriptor
.Query(qry => qry.Filtered(fq => fq
.Filter(ft => ft
.Term(fd => fd.Name.Suffix("exact"), q))));
}
else
{
searchDescriptor = searchDescriptor
.Query(qry => qry.Bool(qb => qb.Should(mm => mm
.MultiMatch(mmq => mmq.Query(q)
.OnFields(pr => pr.Price, pr => pr.Description, pr => pr.Category,
pr => pr.Name.Suffix("nohtml"))))));
}
if (pageSize == 0 || page == 0)
{
searchDescriptor = searchDescriptor.Size(6);
}
else
{
searchDescriptor = searchDescriptor
.Skip((page - 1)*pageSize)
.Take(pageSize);
}
return searchDescriptor;
}
public ISearchResponse<Product> GetSearchResults(SearchDescriptor<Product> searchDescriptor)
{
ISearchResponse<Product> response = new SearchResponse<Product>();
try
{
response = m_client.Search<Product>(searchDescriptor);
}
catch (Exception ex)
{
m_logger.Error("Error executing search request. GetSearchResults func.", ex);
}
return response;
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Mercadinho.Model;
using MySql.Data.MySqlClient;
namespace Mercadinho.View
{
public partial class ListarProdutos : Form
{
private Model.Produto produto;
private Conexao.Conexao conexao;
private Carrinho_Produtos carrinhoprodutos;
public ListarProdutos(Carrinho_Produtos carrinhoprodutos)
{
InitializeComponent();
carregarDados();
this.carrinhoprodutos = carrinhoprodutos;
}
private void carregarDados()
{
conexao = new Conexao.Conexao();
dataGridView1.DataSource = null;
dataGridView1.Rows.Clear();
dataGridView1.Refresh();
string connectionString = conexao.getConnectionString();
string query = "SELECT * FROM produto";
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
using (MySqlDataAdapter adapter = new MySqlDataAdapter(query, conn))
{
try
{
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
for (int i = 0; i < dataTable.Rows.Count; i++)
{
dataGridView1.Rows.Add(dataTable.Rows[i][3], dataTable.Rows[i][0], dataTable.Rows[i][1], dataTable.Rows[i][4], dataTable.Rows[i][5], dataTable.Rows[i][6], dataTable.Rows[i][2]);
}
}
catch (Exception ex)
{
MessageBox.Show("Erro: " + ex);
}
}
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
Produto prod = new Produto();
prod.Codigobarras = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[4].Value);
prod.Nome = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
prod.Precovenda = Convert.ToDecimal(dataGridView1.Rows[e.RowIndex].Cells[2].Value);
prod.Datavencimento = Convert.ToDateTime(dataGridView1.Rows[e.RowIndex].Cells[6].Value);
carrinhoprodutos.Listaprodutos.Add(prod);
carrinhoprodutos.carregardados();
carrinhoprodutos.SomarCarrinho();
}
private void btnVoltarRC_Click(object sender, EventArgs e)
{
Close();
}
private void label1_Click(object sender, EventArgs e)
{
}
}
}
|
using UnityEngine;
using UnityEngine.Serialization;
using System.Collections.Generic;
using Fungus;
// TODO(elliot): jump to different target blocks depending on question result
// TODO(elliot): output quest results into variables
[CommandInfo("Narrative",
"Objective",
"Starts an objective")]
[AddComponentMenu("")]
public class StartObjective : Command //, ILocalizable
{
// [Tooltip("Text to display on the menu button")]
// [SerializeField] protected string text = "";
// [Tooltip("Notes about the option text for other authors, localization, etc.")]
// [SerializeField] protected string description = "";
// [Tooltip("NOT IMPLEMENTED YET! Block to execute when this option is selected")]
// [SerializeField] protected Block targetBlockSuccess;
// [Tooltip("Hide this option if the target block has been executed previously")]
// [SerializeField] protected bool skipIfVisited;
// [Tooltip("If false, the menu option will be displayed but will not be selectable")]
// [SerializeField] protected BooleanData interactable = new BooleanData(true);
// [Tooltip("A custom Menu Dialog to use to display this menu. All subsequent Menu commands will use this dialog.")]
// [SerializeField] protected MenuDialog setMenuDialog;
[Tooltip("The NPC who will own the objective.")]
[SerializeField] protected NPC npc;
[Tooltip("The objective to start.")]
[SerializeField] protected DepositObjective objective;
[Tooltip("How many?")]
[SerializeField] protected IntegerData requiredAmount = new IntegerData(1);
[Tooltip("What?")]
[SerializeField] protected Holdable.ItemType requiredType;
#region Public members
//public MenuDialog SetMenuDialog { get { return setMenuDialog; } set { setMenuDialog = value; } }
public override void OnEnter()
{
// if (setMenuDialog != null)
// {
// // Override the active menu dialog
// MenuDialog.ActiveMenuDialog = setMenuDialog;
// }
//bool hideOption = (skipIfVisited && targetBlockSuccess != null && targetBlockSuccess.GetExecutionCount() > 0);
// if (!hideOption)
// {
// var menuDialog = MenuDialog.GetMenuDialog();
// if (menuDialog != null)
// {
// menuDialog.SetActive(true);
// var flowchart = GetFlowchart();
// string displayText = flowchart.SubstituteVariables(text);
// menuDialog.AddOption(displayText, interactable, targetBlockSuccess);
// }
// }
objective.requiredAmount = requiredAmount;
objective.requiredType = requiredType;
objective.complete.AddListener(HandleComplete);
npc.StartObjective(objective);
}
public override void OnExit()
{
objective.complete.RemoveListener(HandleComplete);
}
private void HandleComplete()
{
Continue();
}
// public override void GetConnectedBlocks(ref List<Block> connectedBlocks)
// {
// if (targetBlockSuccess != null)
// {
// connectedBlocks.Add(targetBlockSuccess);
// }
// }
public override string GetSummary()
{
// if (targetBlockSuccess == null)
// {
// return "Error: No target block selected";
// }
// if (text == "")
// {
// return "Error: No button text selected";
// }
if (objective == null)
{
return "Error: no objective set";
}
if (npc == null)
{
return "Error: no NPC set";
}
return "Start " + objective.name + " with " + npc.name;
}
public override Color GetButtonColor()
{
return new Color32(235, 210, 184, 255);
}
#endregion
#region ILocalizable implementation
// public virtual string GetStandardText()
// {
// return text;
// }
// public virtual void SetStandardText(string standardText)
// {
// text = standardText;
// }
// public virtual string GetDescription()
// {
// return description;
// }
// public virtual string GetStringId()
// {
// return "QUEST." + GetFlowchartLocalizationId() + "." + itemId;
// }
#endregion
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using UnityEngine.SceneManagement;
public class GiftPanel : MonoBehaviour
{
public Text ancientText;
public Text gemsText;
public Text coinsText;
public TextMeshProUGUI Massage;
public GameObject MassagePanel;
public GameObject GameOverPanel;
private int[] countGods = new int[3];
public static int GodsMassage;
public int gems;
public int coins;
public int ancients;
private int score_need;
private GameMaster gm;
void Start()
{
GameOverPanel.SetActive(false);
countGods[0] = 0;
countGods[1] = 0;
countGods[2] = 0;
score_need = 0;
gm = GameObject.FindGameObjectWithTag("GameMaster").GetComponent<GameMaster>();
}
void Update()
{
gemsText.text = ("X " + gems);
coinsText.text = ("X " + coins);
ancientText.text = ("X " + ancients);
}
public void Next(){
if (GameMaster.humans>0)
{
SceneManager.LoadScene(3);
PlayerController.gameOver = false;
PlayerController.gameFinish = false;
SpawnRooms.stopSpawnRoom = false;
PauseMenu.paused = false;
PauseMenu.restartTrigger = true;
}else{
GameOverPanel.SetActive(true);
}
}
public void Submit()
{
gm.coins -= coins;
gm.gems -= gems;
gm.ancients -= ancients;
PlayerController.nextCoin -=coins;
PlayerController.nextGem -= gems;
PlayerController.nextAncient -= ancients;
countGods[DialogManager.GodName]++;
score_need += coins*20;
score_need += gems*100;
score_need += ancients*500;
if (score_need >= (300*Mathf.Pow(1.05f, (GameMaster.day-2)) - 0.07*(300*Mathf.Pow(1.05f, (GameMaster.day-2) ))) && score_need <= (300*Mathf.Pow(1.05f, (GameMaster.day-2)) + 0.07*(300*Mathf.Pow(1.05f, (GameMaster.day-2)))))
{
// Debug.Log("Gods satisfied ");
PlayerController.nextScore += countGods[DialogManager.GodName] * 1000;
GodsMassage = 1;
} else if (score_need < (300*Mathf.Pow(1.05f, (GameMaster.day-2)) - 0.07*(300*Mathf.Pow(1.05f, (GameMaster.day-2)))))
{
// Debug.Log("Gods sad ");
GameMaster.humans -- ;
GodsMassage = 2;
} else
{
// Debug.Log("Gods happy");
GodsMassage = 3;
PlayerController.nextScore += countGods[DialogManager.GodName] * 1200;
}
MassagePanel.SetActive(true);
gm.SavePlayer();
if (GodsMassage == 1)
{
Massage.text = "GODS SATISFIED!";
}
else if (GodsMassage == 2)
{
Massage.text = "GODS SAD!";
}
else
{
Massage.text = "GODS HAPPY!";
}
}
public void Quit()
{
Application.Quit();
}
public void MainMenu()
{
SceneManager.LoadScene(0);
PauseMenu.restartTrigger = true;
}
public void PlusCoinButton()
{
if(gm.coins >= coins+2)
coins +=2;
}
public void MinusCoinButton()
{
if(coins>= 2)
coins -=2;
}
public void PlusGemButton()
{
if(gm.gems >= gems+1)
gems ++;
}
public void MinusGemButton()
{
if(gems>= 1)
gems --;
}
public void PlusAncientsButton()
{
if(gm.ancients >= ancients+1)
ancients ++;
}
public void MinusAncientsButton()
{
if(ancients>=1)
ancients --;
}
}
|
/******************************************************************************\
* Copyright (C) 2012-2016 Leap Motion, Inc. All rights reserved. *
* Leap Motion proprietary and confidential. Not for distribution. *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
\******************************************************************************/
namespace LeapInternal
{
using System;
using System.Runtime.InteropServices;
public enum eLeapConnectionStatus : uint
{
eLeapConnectionStatus_NotConnected = 0, //!< // A connection has been established
eLeapConnectionStatus_Connected, //!< The connection has not been completed. Call OpenConnection.
eLeapConnectionStatus_HandshakeIncomplete, //!< The connection handshake has not completed
eLeapConnectionStatus_NotRunning = 0xE7030004 //!< A connection could not be established because the server does not appear to be running
};
public enum eLeapDeviceCaps : uint
{
eLeapDeviceCaps_Color = 0x00000001, //!< The device can send color images
};
public enum eLeapDeviceType : uint
{
eLeapDeviceType_Peripheral = 0x0003, //!< The Leap Motion consumer peripheral
eLeapDeviceType_Dragonfly = 0x1102, //!< Internal research product codename "Dragonfly"
eLeapDeviceType_Nightcrawler = 0x1201 //!< Internal research product codename "Nightcrawler"
};
public enum eDistortionMatrixType
{
eDistortionMatrixType_64x64 //!< A 64x64 matrix of pairs of points.
};
public enum eLeapPolicyFlag : uint
{
eLeapPolicyFlag_BackgroundFrames = 0x00000001, //!< Allows frame receipt even when this application is not the foreground application
eLeapPolicyFlag_OptimizeHMD = 0x00000004, //!< Optimize HMD Policy Flag
eLeapPolicyFlag_AllowPauseResume = 0x00000008, //!< Modifies the security token to allow calls to LeapPauseDevice to succeed
eLeapPolicyFlag_IncludeAllFrames = 0x00008000, //!< Include native-app frames when receiving background frames.
eLeapPolicyFlag_NonExclusive = 0x00800000 //!< Allow background apps to also receive frames.
};
public enum eLeapDeviceStatus : uint
{
eLeapDeviceStatus_Streaming = 0x00000001, //!< Presently sending frames to all clients that have requested them
eLeapDeviceStatus_Paused = 0x00000002, //!< Device streaming has been paused
eLeapDeviceStatus_UnknownFailure = 0xE8010000, //!< The device has failed, but the failure reason is not known
eLeapDeviceStatus_BadCalibration = 0xE8010001, //!< Bad calibration, cannot send frames
eLeapDeviceStatus_BadFirmware = 0xE8010002, //!< Corrupt firmware and/or cannot receive a required firmware update
eLeapDeviceStatus_BadTransport = 0xE8010003, //!< Exhibiting USB communications issues
eLeapDeviceStatus_BadControl = 0xE8010004, //!< Missing critical control interfaces needed for communication
};
public enum eLeapImageType
{
eLeapImageType_Unknown = 0,
eLeapImageType_Default, //!< Default processed IR image
eLeapImageType_Raw //!< Image from raw sensor values
};
public enum eLeapImageFormat : uint
{
eLeapImageFormat_UNKNOWN = 0, //!< Unknown format (shouldn't happen)
eLeapImageType_IR = 0x317249, //!< An infrared image
eLeapImageType_RGBIr_Bayer = 0x49425247, //!< A Bayer RGBIr image with uncorrected RGB channels
};
public enum eLeapPerspectiveType
{
eLeapPerspectiveType_invalid = 0, //!< Reserved, invalid
eLeapPerspectiveType_stereo_left = 1, //!< A canonically left image
eLeapPerspectiveType_stereo_right = 2, //!< A canonically right image
eLeapPerspectiveType_mono = 3, //!< Reserved for future use
};
public enum eLeapImageRequestError
{
eLeapImageRequestError_Unknown, //!< The reason for the failure is unknown
eLeapImageRequestError_ImagesDisabled, //!< Images are turned off in the user's configuration
eLeapImageRequestError_Unavailable, //!< The requested images are not available
eLeapImageRequestError_InsufficientBuffer, //!< The provided buffer is not large enough for the requested images
}
public enum eLeapHandType
{
eLeapHandType_Left, //!< Left hand
eLeapHandType_Right //!< Right hand
};
public enum eLeapLogSeverity
{
eLeapLogSeverity_Unknown = 0,
eLeapLogSeverity_Critical,
eLeapLogSeverity_Warning,
eLeapLogSeverity_Information
};
public enum eLeapValueType : int
{
eLeapValueType_Unknown,
eLeapValueType_Boolean,
eLeapValueType_Int32,
eLeapValueType_Float,
eLeapValueType_String
};
public enum eLeapRS : uint
{
eLeapRS_Success = 0x00000000, //!< The operation completed successfully
eLeapRS_UnknownError = 0xE2010000, //!< An unknown error has occurred
eLeapRS_InvalidArgument = 0xE2010001, //!< An invalid argument was specified
eLeapRS_InsufficientResources = 0xE2010002, //!< Insufficient resources existed to complete the request
eLeapRS_InsufficientBuffer = 0xE2010003, //!< The specified buffer was not large enough to complete the request
eLeapRS_Timeout = 0xE2010004, //!< The requested operation has timed out
eLeapRS_NotConnected = 0xE2010005, //!< The connection is not open
eLeapRS_HandshakeIncomplete = 0xE2010006, //!< The request did not succeed because the client has not finished connecting to the server
eLeapRS_BufferSizeOverflow = 0xE2010007, //!< The specified buffer size is too large
eLeapRS_ProtocolError = 0xE2010008, //!< A communications protocol error has occurred
eLeapRS_InvalidClientID = 0xE2010009, //!< The server incorrectly specified zero as a client ID
eLeapRS_UnexpectedClosed = 0xE201000A, //!< The connection to the service was unexpectedly closed while reading a message
eLeapRS_CannotCancelImageFrameRequest = 0xE201000B, //!< An attempt to cancel an image request failed (either too late, or the image token was invalid)
eLeapRS_NotAvailable = 0xE7010002, //!< A connection could not be established to the Leap Motion service
eLeapRS_NotStreaming = 0xE7010004, //!< The requested operation can only be performed while the device is streaming
/**
* It is possible that the device identifier
* is invalid, or that the device has been disconnected since being enumerated.
*/
eLeapRS_CannotOpenDevice = 0xE7010005, //!< The specified device could not be opened. Invalid device identifier or the device has been disconnected since being enumerated.
};
public enum eLeapEventType
{
eLeapEventType_None = 0, //!< No event occurred in the specified timeout period
eLeapEventType_Connection, //!< A connection event has occurred
eLeapEventType_ConnectionLost, //!< The connection with the service has been lost
eLeapEventType_Device, //!< A device event has occurred
eLeapEventType_DeviceFailure, //!< A device failure event has occurred
eLeapEventType_PolicyChange, //!< A change in policy occurred
eLeapEventType_Tracking = 0x100, //!< A tracking frame has been received
/**
* The user must invoke LeapReceiveImage(evt->Image, ...) if image data is desired. If this call
* is not made, the image will be discarded from the stream.
*
* Depending on the image types the user has requested, this event may be asserted more than once
* per frame.
*/
eLeapEventType_ImageRequestError, //!< A requested image could not be acquired
eLeapEventType_ImageComplete, //!< An image transfer is complete
eLeapEventType_LogEvent, //!< A diagnostic event has occured
/**
* The eLeapEventType_DeviceLost event type will always be asserted regardless of the user flags assignment.
* Users are required to correctly handle this event when it is received.
*
* This event is generally asserted when the device has been detached from the system, when the
* connection to the service has been lost, or if the device is closed while streaming. Generally,
* any event where the system can conclude no further frames will be received will cause this
* method to be invoked.
*/
eLeapEventType_DeviceLost, //!< Event asserted when the underlying device object has been lost
eLeapEventType_ConfigResponse, //!< Response to a Config value request
eLeapEventType_ConfigChange, //!< Success response to a Config value change
eLeapEventType_DeviceStatusChange,
eLeapEventType_DroppedFrame,
};
public enum eLeapDeviceFlag : uint
{
/**
* This flag is updated when the user pauses or resumes tracking on the device from the Leap control
* panel. Modification of this flag will fail if the AllowPauseResume policy is not set on this device
* object.
*/
eLeapDeviceFlag_Stream = 0x00000001 //!< Flag set if the device is presently streaming frames
};
public enum eLeapConnectionFlags : uint
{
eLeapConnectionFlags_Default = 0x00000000, //!< Currently there is only a default state flag.
};
public enum eLeapDroppedFrameType
{
eLeapDroppedFrameType_PreprocessingQueue,
eLeapDroppedFrameType_TrackingQueue,
eLeapDroppedFrameType_Other
};
//Note the following LeapC structs are just IntPtrs in C#:
// LEAP_CONNECTION is an IntPtr
// LEAP_DEVICE is an IntPtr
// LEAP_CLOCK_REBASER is an IntPtr
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
public struct LEAP_CONNECTION_CONFIG
{
public UInt32 size;
public UInt32 flags;
public string server_namespace;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_CONNECTION_INFO
{
public UInt32 size;
public eLeapConnectionStatus status;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_CONNECTION_EVENT
{
public UInt32 flags;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_DEVICE_REF
{
public IntPtr handle; //void *
public UInt32 id;
public LEAP_DEVICE_REF(IntPtr handle, UInt32 id)
{
this.handle = handle;
this.id = id;
}
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_CONNECTION_LOST_EVENT
{
public UInt32 flags;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_DEVICE_EVENT
{
public UInt32 flags;
public LEAP_DEVICE_REF device;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_DEVICE_FAILURE_EVENT
{
public eLeapDeviceStatus status;
public IntPtr hDevice;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_TRACKING_EVENT
{
public LEAP_FRAME_HEADER info;
public Int64 tracking_id;
public LEAP_VECTOR interaction_box_size;
public LEAP_VECTOR interaction_box_center;
public UInt32 nHands;
public IntPtr pHands; //LEAP_HAND*
public float framerate;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_DROPPED_FRAME_EVENT
{
public Int64 frame_id;
public eLeapDroppedFrameType reason;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_CONNECTION_MESSAGE
{
public UInt32 size;
public eLeapEventType type;
public IntPtr eventStructPtr;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_DISCONNECTION_EVENT
{
public UInt32 reserved;
}
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
public struct LEAP_DEVICE_INFO
{
public UInt32 size;
public UInt32 status;
public UInt32 caps;
public eLeapDeviceType type;
public UInt32 baseline;
public UInt32 serial_length;
public IntPtr serial; //char*
public float h_fov;
public float v_fov;
public UInt32 range;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_DISTORTION_MATRIX
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2 * 64 * 64 * 2)]//2floats * 64 width * 64 height * 2 matrices
public float[] matrix_data;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_FRAME_HEADER
{
public IntPtr reserved;
public Int64 frame_id;
public Int64 timestamp;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_IMAGE_FRAME_REQUEST_TOKEN
{
public UInt32 requestID;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_IMAGE_COMPLETE_EVENT
{
public LEAP_IMAGE_FRAME_REQUEST_TOKEN token;
public LEAP_FRAME_HEADER info;
public IntPtr properties; //LEAP_IMAGE_PROPERTIES*
public UInt64 matrix_version;
public IntPtr calib; //LEAP_CALIBRATION
public IntPtr distortionMatrix; //LEAP_DISTORTION_MATRIX* distortion_matrix[2]
public IntPtr pfnData; // void* the user-supplied buffer
public UInt64 data_written; //The amount of data written to the buffer
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_IMAGE_FRAME_DESCRIPTION
{
public Int64 frame_id;
public eLeapImageType type;
public UInt64 buffer_len;
public IntPtr pBuffer;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_IMAGE_FRAME_REQUEST_ERROR_EVENT
{
public LEAP_IMAGE_FRAME_REQUEST_TOKEN token;
public eLeapImageRequestError error;
public UInt64 required_buffer_len; //The required buffer size, for insufficient buffer errors
public LEAP_IMAGE_FRAME_DESCRIPTION description;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_IMAGE_PROPERTIES
{
public eLeapImageType type;
public eLeapImageFormat format;
public UInt32 bpp;
public UInt32 width;
public UInt32 height;
public float x_scale;
public float y_scale;
public float x_offset;
public float y_offset;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_VECTOR
{
public float x;
public float y;
public float z;
public Leap.Vector ToLeapVector()
{
return new Leap.Vector(x, y, z);
}
public LEAP_VECTOR(Leap.Vector leap)
{
x = leap.x;
y = leap.y;
z = leap.z;
}
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_QUATERNION
{
public float x;
public float y;
public float z;
public float w;
public Leap.LeapQuaternion ToLeapQuaternion()
{
return new Leap.LeapQuaternion(x, y, z, w);
}
public LEAP_QUATERNION(Leap.LeapQuaternion q)
{
x = q.x;
y = q.y;
z = q.z;
w = q.w;
}
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_BONE
{
public LEAP_VECTOR prev_joint;
public LEAP_VECTOR next_joint;
public float width;
public LEAP_QUATERNION rotation;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_DIGIT
{
public Int32 finger_id;
public LEAP_BONE metacarpal;
public LEAP_BONE proximal;
public LEAP_BONE intermediate;
public LEAP_BONE distal;
public LEAP_VECTOR tip_velocity;
public LEAP_VECTOR stabilized_tip_position;
public Int32 is_extended;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_PALM
{
public LEAP_VECTOR position;
public LEAP_VECTOR stabilized_position;
public LEAP_VECTOR velocity;
public LEAP_VECTOR normal;
public float width;
public LEAP_VECTOR direction;
public LEAP_QUATERNION orientation;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_HAND
{
public UInt32 id;
public UInt32 flags;
public eLeapHandType type;
public float confidence;
public UInt64 visible_time;
public float pinch_distance;
public float grab_angle;
public float pinch_strength;
public float grab_strength;
public LEAP_PALM palm;
public LEAP_DIGIT thumb;
public LEAP_DIGIT index;
public LEAP_DIGIT middle;
public LEAP_DIGIT ring;
public LEAP_DIGIT pinky;
public LEAP_BONE arm;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_TIP
{
public LEAP_VECTOR position;
public float radius;
}
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
public struct LEAP_LOG_EVENT
{
public eLeapLogSeverity severity;
public Int64 timestamp;
public string message;
}
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
public struct LEAP_POLICY_EVENT
{
public UInt32 reserved;
public UInt32 current_policy;
}
[StructLayout(LayoutKind.Explicit, Pack = 1)]
public struct LEAP_VARIANT_VALUE_TYPE
{
[FieldOffset(0)]
public eLeapValueType type;
[FieldOffset(4)]
public Int32 boolValue;
[FieldOffset(4)]
public Int32 intValue;
[FieldOffset(4)]
public float floatValue;
}
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
public struct LEAP_VARIANT_REF_TYPE
{
public eLeapValueType type;
public string stringValue;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_CONFIG_RESPONSE_EVENT
{
public UInt32 requestId;
public LEAP_VARIANT_VALUE_TYPE value;
}
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
public struct LEAP_CONFIG_RESPONSE_EVENT_WITH_REF_TYPE
{
public UInt32 requestId;
public LEAP_VARIANT_REF_TYPE value;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LEAP_CONFIG_CHANGE_EVENT
{
public UInt32 requestId;
public Int32 status;
}
public class LeapC
{
private LeapC() { }
public static int DistortionSize = 64;
[DllImport("LeapC", EntryPoint = "LeapGetNow")]
public static extern long GetNow();
[DllImport("LeapC", EntryPoint = "LeapCreateClockRebaser")]
public static extern eLeapRS CreateClockRebaser(out IntPtr phClockRebaser);
[DllImport("LeapC", EntryPoint = "LeapDestroyClockRebaser")]
public static extern eLeapRS DestroyClockRebaser(IntPtr hClockRebaser);
[DllImport("LeapC", EntryPoint = "LeapUpdateRebase")]
public static extern eLeapRS UpdateRebase(IntPtr hClockRebaser, Int64 userClock, Int64 leapClock);
[DllImport("LeapC", EntryPoint = "LeapRebaseClock")]
public static extern eLeapRS RebaseClock(IntPtr hClockRebaser, Int64 userClock, out Int64 leapClock);
[DllImport("LeapC", EntryPoint = "LeapCreateConnection")]
public static extern eLeapRS CreateConnection(ref LEAP_CONNECTION_CONFIG pConfig, out IntPtr pConnection);
//Overrides to allow config to be set to null to use default config
[DllImport("LeapC", EntryPoint = "LeapCreateConnection")]
private static extern eLeapRS CreateConnection(IntPtr nulled, out IntPtr pConnection);
public static eLeapRS CreateConnection(out IntPtr pConnection)
{
return CreateConnection(IntPtr.Zero, out pConnection);
}
[DllImport("LeapC", EntryPoint = "LeapGetConnectionInfo")]
public static extern eLeapRS GetConnectionInfo(IntPtr hConnection, out LEAP_CONNECTION_INFO pInfo);
[DllImport("LeapC", EntryPoint = "LeapOpenConnection")]
public static extern eLeapRS OpenConnection(IntPtr hConnection);
[DllImport("LeapC", EntryPoint = "LeapGetDeviceList")]
public static extern eLeapRS GetDeviceList(IntPtr hConnection, [In, Out] LEAP_DEVICE_REF[] pArray, out UInt32 pnArray);
[DllImport("LeapC", EntryPoint = "LeapGetDeviceList")]
private static extern eLeapRS GetDeviceList(IntPtr hConnection, [In, Out] IntPtr pArray, out UInt32 pnArray);
//Override to allow pArray argument to be set to null (IntPtr.Zero) in order to get the device count
public static eLeapRS GetDeviceCount(IntPtr hConnection, out UInt32 deviceCount)
{
return GetDeviceList(hConnection, IntPtr.Zero, out deviceCount);
}
[DllImport("LeapC", EntryPoint = "LeapOpenDevice")]
public static extern eLeapRS OpenDevice(LEAP_DEVICE_REF rDevice, out IntPtr pDevice);
[DllImport("LeapC", EntryPoint = "LeapGetDeviceInfo", CharSet = CharSet.Ansi)]
public static extern eLeapRS GetDeviceInfo(IntPtr hDevice, out LEAP_DEVICE_INFO info);
[DllImport("LeapC", EntryPoint = "LeapSetPolicyFlags")]
public static extern eLeapRS SetPolicyFlags(IntPtr hConnection, UInt64 set, UInt64 clear);
[DllImport("LeapC", EntryPoint = "LeapSetDeviceFlags")]
public static extern eLeapRS SetDeviceFlags(IntPtr hDevice, UInt64 set, UInt64 clear, out UInt64 prior);
[DllImport("LeapC", EntryPoint = "LeapPollConnection")]
public static extern eLeapRS PollConnection(IntPtr hConnection, UInt32 timeout, ref LEAP_CONNECTION_MESSAGE msg);
[DllImport("LeapC", EntryPoint = "LeapGetFrameSize")]
public static extern eLeapRS GetFrameSize(IntPtr hConnection, Int64 timestamp, out UInt64 pncbEvent);
[DllImport("LeapC", EntryPoint = "LeapInterpolateFrame")]
public static extern eLeapRS InterpolateFrame(IntPtr hConnection, Int64 timestamp, IntPtr pEvent, UInt64 ncbEvent);
[DllImport("LeapC", EntryPoint = "LeapRequestImages")]
public static extern eLeapRS RequestImages(IntPtr hConnection, ref LEAP_IMAGE_FRAME_DESCRIPTION description, out LEAP_IMAGE_FRAME_REQUEST_TOKEN pToken);
[DllImport("LeapC", EntryPoint = "LeapCancelImageFrameRequest")]
public static extern eLeapRS CancelImageFrameRequest(IntPtr hConnection, LEAP_IMAGE_FRAME_REQUEST_TOKEN token);
[DllImport("LeapC", EntryPoint = "LeapPixelToRectilinear")]
public static extern LEAP_VECTOR LeapPixelToRectilinear(IntPtr hConnection, eLeapPerspectiveType camera, LEAP_VECTOR pixel);
[DllImport("LeapC", EntryPoint = "LeapRectilinearToPixel")]
public static extern LEAP_VECTOR LeapRectilinearToPixel(IntPtr hConnection, eLeapPerspectiveType camera, LEAP_VECTOR rectilinear);
[DllImport("LeapC", EntryPoint = "LeapCloseDevice")]
public static extern void CloseDevice(IntPtr pDevice);
[DllImport("LeapC", EntryPoint = "LeapDestroyConnection")]
public static extern void DestroyConnection(IntPtr connection);
[DllImport("LeapC", EntryPoint = "LeapSaveConfigValue")]
private static extern eLeapRS SaveConfigValue(IntPtr hConnection, string key, IntPtr value, out UInt32 requestId);
[DllImport("LeapC", EntryPoint = "LeapRequestConfigValue")]
public static extern eLeapRS RequestConfigValue(IntPtr hConnection, string name, out UInt32 request_id);
public static eLeapRS SaveConfigValue(IntPtr hConnection, string key, bool value, out UInt32 requestId)
{
LEAP_VARIANT_VALUE_TYPE valueStruct = new LEAP_VARIANT_VALUE_TYPE(); //This is a C# approximation of a C union
valueStruct.type = eLeapValueType.eLeapValueType_Boolean;
valueStruct.boolValue = value ? 1 : 0;
return LeapC.SaveConfigWithValueType(hConnection, key, valueStruct, out requestId);
}
public static eLeapRS SaveConfigValue(IntPtr hConnection, string key, Int32 value, out UInt32 requestId)
{
LEAP_VARIANT_VALUE_TYPE valueStruct = new LEAP_VARIANT_VALUE_TYPE();
valueStruct.type = eLeapValueType.eLeapValueType_Int32;
valueStruct.intValue = value;
return LeapC.SaveConfigWithValueType(hConnection, key, valueStruct, out requestId);
}
public static eLeapRS SaveConfigValue(IntPtr hConnection, string key, float value, out UInt32 requestId)
{
LEAP_VARIANT_VALUE_TYPE valueStruct = new LEAP_VARIANT_VALUE_TYPE();
valueStruct.type = eLeapValueType.eLeapValueType_Float;
valueStruct.floatValue = value;
return LeapC.SaveConfigWithValueType(hConnection, key, valueStruct, out requestId);
}
public static eLeapRS SaveConfigValue(IntPtr hConnection, string key, string value, out UInt32 requestId)
{
LEAP_VARIANT_REF_TYPE valueStruct;
valueStruct.type = eLeapValueType.eLeapValueType_String;
valueStruct.stringValue = value;
return LeapC.SaveConfigWithRefType(hConnection, key, valueStruct, out requestId);
}
private static eLeapRS SaveConfigWithValueType(IntPtr hConnection, string key, LEAP_VARIANT_VALUE_TYPE valueStruct, out UInt32 requestId)
{
IntPtr configValue = Marshal.AllocHGlobal(Marshal.SizeOf(valueStruct));
eLeapRS callResult = eLeapRS.eLeapRS_UnknownError;
try
{
Marshal.StructureToPtr(valueStruct, configValue, false);
callResult = SaveConfigValue(hConnection, key, configValue, out requestId);
}
finally
{
Marshal.FreeHGlobal(configValue);
}
return callResult;
}
private static eLeapRS SaveConfigWithRefType(IntPtr hConnection, string key, LEAP_VARIANT_REF_TYPE valueStruct, out UInt32 requestId)
{
IntPtr configValue = Marshal.AllocHGlobal(Marshal.SizeOf(valueStruct));
eLeapRS callResult = eLeapRS.eLeapRS_UnknownError;
try
{
Marshal.StructureToPtr(valueStruct, configValue, false);
callResult = SaveConfigValue(hConnection, key, configValue, out requestId);
}
finally
{
Marshal.FreeHGlobal(configValue);
}
return callResult;
}
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
public struct LEAP_RECORDING_PARAMETERS {
public UInt32 mode;
}
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
public struct LEAP_RECORDING_STATUS {
public UInt32 mode;
}
[DllImport("LeapC", EntryPoint = "LeapRecordingOpen")]
public static extern eLeapRS RecordingOpen(ref IntPtr ppRecording, string userPath, LEAP_RECORDING_PARAMETERS parameters);
[DllImport("LeapC", EntryPoint = "LeapRecordingClose")]
public static extern eLeapRS RecordingClose(ref IntPtr ppRecording);
[DllImport("LeapC", EntryPoint = "LeapRecordingGetStatus")]
public static extern eLeapRS LeapRecordingGetStatus(IntPtr pRecording, ref LEAP_RECORDING_STATUS status);
[DllImport("LeapC", EntryPoint = "LeapRecordingReadSize")]
public static extern eLeapRS RecordingReadSize(IntPtr pRecording, ref UInt64 pncbEvent);
[DllImport("LeapC", EntryPoint = "LeapRecordingRead")]
public static extern eLeapRS RecordingRead(IntPtr pRecording, ref LEAP_TRACKING_EVENT pEvent, UInt64 ncbEvent);
[DllImport("LeapC", EntryPoint = "LeapRecordingWrite")]
public static extern eLeapRS RecordingWrite(IntPtr pRecording, ref LEAP_TRACKING_EVENT pEvent, ref UInt64 pnBytesWritten);
}//end LeapC
} //end LeapInternal namespace
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace StudyManagement.Admin
{
public partial class AddCourse : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnCourseAdd_Click(object sender, EventArgs e)
{
string conString = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;
SqlConnection connection = new SqlConnection(conString);
CoursePhoto.SaveAs(Server.MapPath("../images/courses/") + Path.GetFileName(CoursePhoto.FileName));
String photolink = "../images/courses/" + Path.GetFileName(CoursePhoto.FileName);
SqlCommand command = new SqlCommand("insert into STUDYCOURSEINFO1(COURSENAME,COURSEDURATION,COURSEQUALIFICATION,COURSEFEE,COURSEFEEMETHOD,CoursePhoto,CourseDescription)values('" + exampleInputCourse.Text + "','" + exampleInputDuration.Text + "','" + exampleInputQualification.Text + "', " + exampleInputFee.Text + ",'" + exampleInputMethod.Text + "','"+ photolink + "','" + CourseDescription.Text+"')", connection);
connection.Open();
int result = command.ExecuteNonQuery();
if (result > 0)
{
Response.Write("<script LANGUAGE='JavaScript' >alert('Request Submitted Successfully!');window.location='AddCourse.aspx';</script>");
GetClear();
}
else
{
Response.Write("<script LANGUAGE='JavaScript' >alert('There is some error. Please enter again');window.location='AddCourse.aspx';</script>");
}
command.Dispose();
connection.Close();
}
public void GetClear()
{
exampleInputCourse.Text = "";
exampleInputDuration.Text = null;
exampleInputQualification.Text = null;
exampleInputFee.Text = "";
exampleInputMethod.Text = "";
CourseDescription.Text = "";
}
}
} |
/*****************************************************
* 作者:Allyn
* 创建日期:2015年2月6日, PM 11:20:04
* 描述:仓储上下文接口
* ***************************************************/
using Allyn.Domain.Models;
using Allyn.Domain.Models.Basic;
using Allyn.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Allyn.Domain.Repositories
{
/// <summary>
/// 表示仓储上下文类型
/// </summary>
public interface IRepositoryContext : IUnitOfWork, IDisposable
{
/// <summary>
/// 获取仓储上下文的唯一标识.
/// </summary>
Guid Key { get; }
/// <summary>
/// 将指定的聚合根标注为“新建”状态.
/// </summary>
/// <typeparam name="TAggregateRoot">聚合根类型.</typeparam>
/// <param name="obj">需要标注状态的聚合根</param>
void RegisterNew<TAggregateRoot>(TAggregateRoot obj) where TAggregateRoot : class,IAggregateRoot;
/// <summary>
/// 将指定的聚合根标注为“更改”状态.
/// </summary>
/// <typeparam name="TAggregateRoot">聚合根类型.</typeparam>
/// <param name="obj">需要标注状态的聚合根.</param>
void RegisterModified<TAggregateRoot>(TAggregateRoot obj) where TAggregateRoot : class,IAggregateRoot;
/// <summary>
/// 将指定的聚合根标注为“删除”状态.
/// </summary>
/// <typeparam name="TAggregateRoot">聚合根类型.</typeparam>
/// <param name="obj">需要标注状态的聚合根。</param>
void RegisterDeleted<TAggregateRoot>(TAggregateRoot obj) where TAggregateRoot : class,IAggregateRoot;
// <summary>
/// 将给定指定的聚合根附加到集的基础上下文中.也就是说,将实体以"未更改"的状态放置到上下文中,就好像从数据库读取了该实体一样.
/// </summary>
/// <typeparam name="TAggregateRoot">聚合根类型.</typeparam>
/// <param name="obj">需要标注状态的聚合根。</param>
void RegisterAttach<TAggregateRoot>(TAggregateRoot obj) where TAggregateRoot : class,IAggregateRoot;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Livet;
namespace MIV.Models
{
public interface INode
{
// 本(=本棚)、ページのインターフェイス
string Name { get; set; }
INode Parent { get; set; }
ObservableSynchronizedCollection<INode> Children { get; set; }
void Remove(INode node);
void Add(INode node, bool isDir);
string Path { get; set; }
INode Next { get; }
INode Prev { get; }
INode FindRoot();
bool IsDir { get; set; }
}
public abstract class AbstractNode : NotificationObject, INode
{
string name;
public String Name
{
get { return this.name; }
set
{
if (this.name == value) return;
this.name = value;
RaisePropertyChanged("Name");
}
}
INode parent;
public INode Parent
{
get { return this.parent; }
set
{
if (this.parent == value) return;
parent = value;
RaisePropertyChanged("Parent");
}
}
public virtual ObservableSynchronizedCollection<INode> Children
{
get { return null; }
set { throw new InvalidOperationException(); }
}
public virtual void Remove(INode node)
{
throw new InvalidOperationException();
}
public virtual void Add(INode node, bool isDir)
{
throw new InvalidOperationException();
}
string path;
public String Path
{
get { return this.path; }
set
{
if (this.path == value) return;
this.path = value;
RaisePropertyChanged("Path");
}
}
INode next;
public INode Next
{
get
{
var idx = this.parent.Children.IndexOf(this);
if (idx == this.parent.Children.Count - 1) return this;
return this.parent.Children[idx + 1 ];
}
}
INode prev;
public INode Prev
{
get
{
var idx = this.parent.Children.IndexOf(this);
if (idx == 0) return this;
return this.parent.Children[idx - 1];
}
}
public virtual INode FindRoot()
{
if (this.parent == null) return this;
return this.parent.FindRoot();
}
public bool IsDir { get; set; }
}
public class Page : AbstractNode
{
public Page(INode node)
{
this.Parent = node; // 自身を格納するBook
this.IsDir = false;
}
}
public class Book : AbstractNode
{
public string FolderPath { get; set; }
public Book(string path="")
{
this.Name = "root";
this.IsDir = true;
this.FolderPath = path;
}
ObservableSynchronizedCollection<INode> children;
public override ObservableSynchronizedCollection<INode> Children
{
get { return this.children; }
set { this.children = value; }
}
public override void Remove(INode node)
{
this.children.Remove(node);
RaisePropertyChanged("Children");
}
public override void Add(INode node, bool isDir)
{
if (this.children == null)
{
this.children = new ObservableSynchronizedCollection<INode> { };
}
node.Parent = this;
this.children.Add(node);
if (isDir)
{
this.AddPages((Book)node);
node.Path = System.Environment.CurrentDirectory + @"\media\folder.jpg";
}
RaisePropertyChanged("Children");
RaisePropertyChanged("Path");
}
private void AddPages(Book parent)
{
var files = System.IO.Directory.GetFiles(parent.FolderPath, "*.jpg", System.IO.SearchOption.TopDirectoryOnly);
var pages = new List<INode> { };
foreach (var file in files)
{
INode child = new Page(parent);
child.Path = file;
parent.Add(child, false);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebTest
{
public partial class ExportAndImport : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string file = Server.MapPath("/data.xml");
Code.ProductDataManage.Instance.ExportToFile(file, b => b.Id > 0);//导出到文件
Response.Write("成功导出到文件:" + file);
var xml = Code.ProductDataManage.Instance.ExportToXml(b => b.Id > 0);//导出为字符串
}
protected void Button2_Click(object sender, EventArgs e)
{
string file = Server.MapPath("/data.xml");
Code.ProductDataManage.Instance.ImportFromFile(file, b => b.Id > 0);//从文件中导入
Response.Write("成功从文件导入:" + file);
//Code.ProductDataManage.Instance.ImportFromXml("", b => b.Id > 0);//从XML序列化字符串导入
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ZC_IT_TimeTracking.Models
{
public class Utilities
{
public static int RecordPerPage = 5;
public static int GetQuarter()
{
DateTime date = DateTime.Now;
if (date.Month >= 1 && date.Month <= 3)
return 1;
else if (date.Month >= 4 && date.Month <= 7)
return 2;
else if (date.Month >= 8 && date.Month <= 10)
return 3;
else
return 4;
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using X1PL_Backend;
namespace X1PL_Console_UI
{
public class StringArray
{
public string[] Connections { get; set; }
}
class Program
{
static void Main(string[] args)
{
new X1PL_Easy(args[0]);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Windows;
using CODE.Framework.Core.Utilities;
namespace CODE.Framework.Wpf.TestBench
{
/// <summary>
/// Interaction logic for ObjectHelper.xaml
/// </summary>
public partial class ObjectHelperTest : Window
{
public ObjectHelperTest()
{
InitializeComponent();
}
private void GetSimpleValue(object sender, RoutedEventArgs e)
{
var invoice = new Invoice();
var firstName = invoice.GetPropertyValue<string>("FirstName");
Console.WriteLine(firstName);
var addressLine1 = invoice.GetPropertyValue<string>("Address.Line1");
Console.WriteLine(addressLine1);
var description2 = invoice.GetPropertyValue<string>("LineItems[1].Description");
Console.WriteLine(description2);
invoice.SetPropertyValue("FirstName", "John");
invoice.SetPropertyValue("Address.Line1", "Cypresswood Dr.");
invoice.SetPropertyValue("LineItems[1].Description", "Test description");
firstName = invoice.GetPropertyValue<string>("FirstName");
Console.WriteLine(firstName);
addressLine1 = invoice.GetPropertyValue<string>("Address.Line1");
Console.WriteLine(addressLine1);
description2 = invoice.GetPropertyValue<string>("LineItems[1].Description");
Console.WriteLine(description2);
}
private void GetJson(object sender, RoutedEventArgs e)
{
var invoice = new Invoice();
invoice.FirstName = "©®™";
var json = JsonHelper.SerializeToRestJson(invoice, true);
MessageBox.Show(json);
var invoice2 = JsonHelper.DeserializeFromRestJson<Invoice>(json);
}
private void GetDateJson(object sender, RoutedEventArgs e)
{
var json = JsonHelper.SerializeToRestJson(DateTimeOffset.Now);
MessageBox.Show(json);
}
}
public class Invoice
{
public Invoice()
{
FirstName = "Markus";
Address = new Address();
LineItems = new List<LineItem>
{
new LineItem {Description = "Item #1"},
new LineItem {Description = "Item #2"},
new LineItem {Description = "Item #3"}
};
}
public string FirstName { get; set; }
public Address Address { get; set; }
public List<LineItem> LineItems { get; set; }
}
public class Address
{
public Address()
{
Line1 = "Address Line 1";
}
public string Line1 { get; set; }
}
public class LineItem
{
public string Description { get; set; }
}
} |
using AutoFixture;
using Moq;
using NUnit.Framework;
using SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Requests.Cohorts;
using SFA.DAS.ProviderCommitments.Infrastructure.OuterApi;
using SFA.DAS.ProviderCommitments.Web.Models;
using System.Threading.Tasks;
using System.Linq;
using SFA.DAS.ProviderCommitments.Web.Mappers.Cohort;
using SFA.DAS.ProviderCommitments.Interfaces;
using SFA.DAS.ProviderCommitments.Web.Services.Cache;
using System;
using SFA.DAS.ProviderCommitments.Web.Models.Cohort;
namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Mappers.Cohort
{
[TestFixture]
public class SelectCourseViewModelMapperTests
{
private SelectCourseViewModelMapper _mapper;
private Mock<IOuterApiClient> _apiClient;
private SelectCourseRequest _request;
private GetAddDraftApprenticeshipCourseResponse _apiResponse;
private Mock<ICacheStorageService> _cacheService;
private CreateCohortCacheItem _cacheItem;
private readonly Fixture _fixture = new Fixture();
[SetUp]
public void Setup()
{
_request = _fixture.Create<SelectCourseRequest>();
_apiResponse = _fixture.Create<GetAddDraftApprenticeshipCourseResponse>();
_apiClient = new Mock<IOuterApiClient>();
_apiClient.Setup(x => x.Get<GetAddDraftApprenticeshipCourseResponse>(It.Is<GetAddDraftApprenticeshipCourseRequest>(r =>
r.ProviderId == _request.ProviderId)))
.ReturnsAsync(_apiResponse);
_cacheItem = _fixture.Create<CreateCohortCacheItem>();
_cacheService = new Mock<ICacheStorageService>();
_cacheService.Setup(x => x.RetrieveFromCache<CreateCohortCacheItem>(It.IsAny<Guid>()))
.ReturnsAsync(_cacheItem);
_mapper = new SelectCourseViewModelMapper(_apiClient.Object, _cacheService.Object);
}
[Test]
public async Task EmployerName_Is_Mapped_Correctly()
{
var result = await _mapper.Map(_request);
Assert.AreEqual(_apiResponse.EmployerName, result.EmployerName);
}
[Test]
public async Task ProviderId_Is_Mapped_Correctly()
{
var result = await _mapper.Map(_request);
Assert.AreEqual(_request.ProviderId, result.ProviderId);
}
[Test]
public async Task ShowManagingStandardsContent_Is_Mapped_Correctly()
{
var result = await _mapper.Map(_request);
Assert.AreEqual(_apiResponse.IsMainProvider, result.ShowManagingStandardsContent);
}
[Test]
public async Task Standards_Is_Mapped_Correctly()
{
var result = await _mapper.Map(_request);
Assert.IsTrue(TestHelper.EnumerablesAreEqual(_apiResponse.Standards.ToList(), result.Standards.ToList()));
}
[Test]
public async Task CourseCode_Is_Mapped_Correctly()
{
var result = await _mapper.Map(_request);
Assert.AreEqual(_cacheItem.CourseCode, result.CourseCode);
}
}
}
|
using UnityEngine;
public class AimFollow : MonoBehaviour
{
public Texture2D cursorTexture;
public CursorMode cursorMode = CursorMode.Auto;
public Vector2 hotSpot = Vector2.zero;
private void Start()
{
// hotSpot = new Vector2(cursorTexture.width / 2f, cursorTexture.height / 2f);
// Cursor.SetCursor(cursorTexture, hotSpot, cursorMode);
}
private void OnDestroy()
{
Cursor.SetCursor(null, Vector2.zero, cursorMode);
}
} |
namespace PizzaBox.Domain
{
public class Crust : PizzaComponent
{
public Crust(string _name, decimal _cost) : base (_name, _cost) {}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Focuswin.SP.Base.Utility;
using Microsoft.SharePoint;
using YFVIC.DMS.Model.Models.Settings;
using YFVIC.DMS.Model.Models.WorkFlow;
using YFVIC.DMS.Model.Models.Common;
using YFVIC.DMS.Model.Models.HR;
using YFVIC.DMS.Model.Models.DataDictionary;
using YFVIC.DMS.Model.Models.Permission;
using YFVIC.DMS.Model.Models.Project;
using YFVIC.DMS.Model.Models.Distribute;
using YFVIC.DMS.Model.Models.MailManagement;
using YFVIC.DMS.Model.Models.FileCode;
namespace YFVIC.DMS.Model.Models.FileInfo
{
public class FileActiveMgr
{
Logger log = Logger.GetLogger(typeof(FileInfoMgr));
SPUser user = SPContext.Current.Web.CurrentUser;
SysCompanyMgr companymgr = new SysCompanyMgr();
SysOrgMgr orgmgr = new SysOrgMgr();
SysUserMgr usermgr = new SysUserMgr();
DataDicMgr datadicmgr = new DataDicMgr();
PermissionMgr permissionmgr = new PermissionMgr();
ProjectUserMgr projectusermgr = new ProjectUserMgr();
CodeMgr codemgr = new CodeMgr();
#region 文件操作相关
/// <summary>
/// 创建文件
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public string CreateFile(FileInfoEntity file)
{
string id;
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
SettingsEntity Email = mgr.GetSystemSetting(SPContext.Current.Site.Url, "EmailTemp");
SettingsEntity syspre = mgr.GetSystemSetting(SPContext.Current.Site.Url, "SYSPrefix");
SettingsEntity tcpre = mgr.GetSystemSetting(SPContext.Current.Site.Url, "TCPrefix");
using (FileInfoDataDataContext db = new FileInfoDataDataContext(setting.DefaultValue))
{
FileInfoActive fileinfo = new FileInfoActive();
fileinfo.FileName = file.FileName;
fileinfo.FilePath = file.FilePath;
fileinfo.FileDesc = file.FileDesc;
fileinfo.Creater = DMSComm.resolveLogon(user.LoginName);
fileinfo.CreateTime = DateTime.Now.ToString();
fileinfo.Reference = file.References;
fileinfo.FileType = file.FileType;
fileinfo.VersionNum = file.VersionNum;
fileinfo.AssTag = file.AssTag;
fileinfo.IsDelete = "false";
fileinfo.Path = file.Path;
fileinfo.IsDraft = file.IsDraft;
fileinfo.FileLevel = file.FileLevel;
fileinfo.CreateType = file.CreateType;
fileinfo.FileArea = file.FileArea;
if (file.AssTag == "运作体系文件")
{
fileinfo.AreaCompany = file.AreaCompany;
fileinfo.HasForm = file.HasForm;
fileinfo.FormId = file.FormId;
fileinfo.IsRelation = file.IsRelation;
fileinfo.RelationType = file.RelationType;
fileinfo.RelationName = file.RelationName;
fileinfo.RelationId = file.RelationId;
fileinfo.FileHierarchy = file.FileHierarchy;
fileinfo.Area = file.Area;
fileinfo.AreaType = file.AreaType;
fileinfo.CompanyCode = file.CompanyCode;
fileinfo.IsFileNum = file.IsFileNum;
fileinfo.Process = file.Process;
fileinfo.ProcessId = file.ProcessId;
fileinfo.FileNum = file.FileNum;
fileinfo.ReFunction = file.ReFunction;
SysOrgEntity org = orgmgr.GetOrgByUser(fileinfo.Creater);
fileinfo.Depart = org.Area + " " + orgmgr.GetOrgBysid(fileinfo.Creater);
fileinfo.ReceiveDate = DateTime.Now.ToString();
fileinfo.ExpiryDate = file.ExpiryDate;
fileinfo.Deviation = file.Deviation;
fileinfo.DirectDepartment = file.DirectDepartment;
fileinfo.DirectPeople = file.DirectPeople;
}
else if (file.AssTag == "技术文件")
{
fileinfo.ProjectNum = file.ProjectNum;
fileinfo.ProjectLine = file.ProjectLine;
fileinfo.ProjectName = file.ProjectName;
fileinfo.Customer = file.Customer;
}
else if (file.AssTag == "CTC流程文件")
{
fileinfo.ProcessType = file.ProcessType;
fileinfo.AbolishId = file.AbolishId;
fileinfo.L1 = file.L1;
fileinfo.L2 = file.L2;
fileinfo.L3 = file.L3;
fileinfo.AreaCompany = file.AreaCompany;
fileinfo.FileNum = GetFileCode(file);
string codeprdf = GetCodeNP(file);
codemgr.DelRecCode(fileinfo.FileNum.Replace(tcpre.DefaultValue + "-", ""), codeprdf);
}
else if (file.AssTag == "标准文件")
{
fileinfo.ProcessType = file.ProcessType;
fileinfo.BigClass = file.BigClass;
fileinfo.SmallClass = file.SmallClass;
fileinfo.OEM = file.OEM;
fileinfo.ProjectUsed = file.ProjectUserd;
fileinfo.KeyWord = file.KeyWord;
fileinfo.FileNum = GetFileCode(file);
string codeprdf = GetCodeNP(file);
codemgr.DelRecCode(fileinfo.FileNum.Replace(tcpre.DefaultValue + "-", ""), codeprdf);
fileinfo.OEMKey = file.OEMKey;
}
db.FileInfoActives.InsertOnSubmit(fileinfo);
db.SubmitChanges();
id = fileinfo.Id.ToString();
DMSComm.SetFileName(file.FilePath, file.FileName,file.FileArea);
//判断是否草稿
if (file.IsDraft == "false")
{
WFCommEntity item = new WFCommEntity();
item.ApplicantAD = DMSComm.resolveLogon(user.LoginName);
item.Area = file.Area;
item.AreaType = file.AreaType;
item.FileHierarchy = file.FileHierarchy;
item.FileId = id;
item.WFType = ((int)DMSEnum.WFType.Insert).ToString();
item.AssTag = file.AssTag;
WFCommMgr commgr = new WFCommMgr();
if (file.AssTag == "运作体系文件")
{
commgr.StartWorkFlow(item);
}
else if (file.AssTag == "标准文件" || file.AssTag == "CTC流程文件" || file.AssTag == "技术文件")
{
if (file.AssTag != "技术文件")
{
string codeprdf = GetCodeNP(file);
codemgr.UpdataCode(codeprdf, fileinfo.FileNum.Replace(tcpre.DefaultValue + "-", ""));
}
item.BigClass = file.BigClass;
item.SmallClass = file.SmallClass;
item.OEM = file.OEM;
item.EPNum = file.ProjectNum;
commgr.StartTCWorkFlow(item);
if (!string.IsNullOrEmpty(file.AbolishId))
{
string[] ids = file.AbolishId.Split(',');
foreach (string ablishfile in ids)
{
FileInfo fitem = db.FileInfos.Where(p => p.Id == int.Parse(ablishfile)).FirstOrDefault();
fitem.IsChange = "true";
db.SubmitChanges();
}
}
}
}
}
PermissionEntity pitem = new PermissionEntity();
pitem.ItemId = id;
pitem.Account = DMSComm.resolveLogon(user.LoginName);
pitem.IsGroup = "N";
pitem.GroupType = "个人";
pitem.Permission = ((int)DMSEnum.Permission.All).ToString();
pitem.CreateTime = DateTime.Now.ToString();
pitem.Type = ((int)DMSEnum.PermissionType.FileActive).ToString();
permissionmgr.InsertPermission(pitem);
return id;
}
/// <summary>
/// 创建无流程活动文件
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public string InsertActiveFile(FileInfoEntity file)
{
string id;
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (FileInfoDataDataContext db = new FileInfoDataDataContext(setting.DefaultValue))
{
FileInfoActive fileinfo = new FileInfoActive();
fileinfo.FileName = file.FileName;
fileinfo.FilePath = file.FilePath;
fileinfo.FileDesc = file.FileDesc;
fileinfo.Creater = DMSComm.resolveLogon(user.LoginName);
fileinfo.CreateTime = DateTime.Now.ToString();
fileinfo.CreateType = file.CreateType;
fileinfo.Reference = file.References;
fileinfo.FileType = file.FileType;
fileinfo.VersionNum = file.VersionNum;
fileinfo.AssTag = file.AssTag;
fileinfo.IsDelete = "false";
fileinfo.Path = file.Path;
fileinfo.IsDraft = file.IsDraft;
fileinfo.FileLevel = file.FileLevel;
fileinfo.FileArea = file.FileArea;
if (file.AssTag == "运作体系文件")
{
fileinfo.AreaCompany = file.AreaCompany;
fileinfo.HasForm = file.HasForm;
fileinfo.FormId = file.FormId;
fileinfo.FileNum = file.FileNum;
fileinfo.IsFileNum = file.IsFileNum;
fileinfo.IsRelation = file.IsRelation;
fileinfo.RelationType = file.RelationType;
fileinfo.RelationName = file.RelationName;
fileinfo.RelationId = file.RelationId;
fileinfo.FileHierarchy = file.FileHierarchy;
fileinfo.Area = file.Area;
fileinfo.AreaType = file.AreaType;
fileinfo.CompanyCode = file.CompanyCode;
fileinfo.Process = file.Process;
fileinfo.ProcessId = file.ProcessId;
fileinfo.ReFunction = file.ReFunction;
fileinfo.Depart = file.Depart;
fileinfo.ReceiveDate = file.ReceiveDate;
fileinfo.ExpiryDate = file.ExpiryDate;
fileinfo.Deviation = file.Deviation;
fileinfo.DirectDepartment = file.DirectDepartment;
fileinfo.DirectPeople = file.DirectPeople;
}
else if (file.AssTag == "技术文件")
{
fileinfo.ProjectNum = file.ProjectNum;
fileinfo.ProjectLine = file.ProjectLine;
fileinfo.ProjectName = file.ProjectName;
fileinfo.Customer = file.Customer;
}
else if (file.AssTag == "CTC流程文件")
{
fileinfo.ProcessType = file.ProcessType;
fileinfo.AbolishId = file.AbolishId;
fileinfo.L1 = file.L1;
fileinfo.L2 = file.L2;
fileinfo.L3 = file.L3;
fileinfo.AreaCompany = file.AreaCompany;
fileinfo.FileNum = GetFileCode(file);
}
else if (file.AssTag == "标准文件")
{
fileinfo.ProcessType = file.ProcessType;
fileinfo.BigClass = file.BigClass;
fileinfo.SmallClass = file.SmallClass;
fileinfo.OEM = file.OEM;
fileinfo.ProjectUsed = file.ProjectUserd;
fileinfo.KeyWord = file.KeyWord;
fileinfo.OEMKey = file.OEMKey;
fileinfo.FileNum = GetFileCode(file);
}
db.FileInfoActives.InsertOnSubmit(fileinfo);
db.SubmitChanges();
id = fileinfo.Id.ToString();
}
if (!string.IsNullOrEmpty(file.FilePath))
{ DMSComm.SetFileName(file.FilePath, file.FileName,file.FileArea); }
PermissionEntity pitem = new PermissionEntity();
pitem.ItemId = id;
pitem.Account = DMSComm.resolveLogon(user.LoginName);
pitem.IsGroup = "N";
pitem.Permission = ((int)DMSEnum.Permission.All).ToString();
pitem.CreateTime = DateTime.Now.ToString();
pitem.Type = ((int)DMSEnum.PermissionType.FileActive).ToString();
permissionmgr.InsertPermission(pitem);
return id;
}
/// <summary>
/// 更新活动文件
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public bool UpdataActiveFile(FileInfoEntity file)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
SettingsEntity syspre = mgr.GetSystemSetting(SPContext.Current.Site.Url, "SYSPrefix");
SettingsEntity tcpre = mgr.GetSystemSetting(SPContext.Current.Site.Url, "TCPrefix");
using (FileInfoDataDataContext db = new FileInfoDataDataContext(setting.DefaultValue))
{
FileInfoActive fileinfo = db.FileInfoActives.Where(p => p.Id == Convert.ToInt32(file.Id)).FirstOrDefault();
string filenum = fileinfo.FileNum;
string isdraft = fileinfo.IsDraft;
if (file.IsRelation == "是")
{
if (file.RelationType != "无")
{
FileInfo item = db.FileInfos.Where(p => p.Id == int.Parse(file.RelationId)).FirstOrDefault();
if (file.RelationType == "二级")
{
file.Process = item.Process;
}
else if (file.RelationType == "三级")
{
file.Process = item.Process;
file.FileType = item.FileType;
}
}
}
if (file.IsFileNum == "是")
{
if (file.FileHierarchy == "二级")
{
if (file.FileNum.Contains("PP"))
{
file.Process = "PP";
}
else if (file.FileNum.Contains("LP"))
{
file.Process = "LP";
}
else if (file.FileNum.Contains("SP"))
{
file.Process = "SP";
}
}
}
fileinfo.FileName = file.FileName;
fileinfo.FilePath = file.FilePath;
fileinfo.FileDesc = file.FileDesc;
fileinfo.CreateTime = DateTime.Now.ToString();
fileinfo.Reference = file.References;
fileinfo.FileType = file.FileType;
fileinfo.VersionNum = file.VersionNum;
fileinfo.AssTag = file.AssTag;
fileinfo.IsDelete = "false";
fileinfo.Path = file.Path;
fileinfo.FileLevel = file.FileLevel;
fileinfo.IsDraft = file.IsDraft;
fileinfo.EffectiveDate = file.EffectiveDate;
fileinfo.SPVersion = file.SPVersion;
fileinfo.DisId = file.DisId;
fileinfo.BorrowId = file.BorrowId;
fileinfo.FileArea = file.FileArea;
if (file.AssTag == "运作体系文件")
{
fileinfo.AreaCompany = file.AreaCompany;
fileinfo.HasForm = file.HasForm;
fileinfo.FormId = file.FormId;
fileinfo.FileNum = file.FileNum;
fileinfo.IsFileNum = file.IsFileNum;
fileinfo.IsRelation = file.IsRelation;
fileinfo.RelationType = file.RelationType;
fileinfo.RelationName = file.RelationName;
fileinfo.RelationId = file.RelationId;
fileinfo.FileHierarchy = file.FileHierarchy;
fileinfo.Area = file.Area;
fileinfo.AreaType = file.AreaType;
fileinfo.CompanyCode = file.CompanyCode;
fileinfo.Process = file.Process;
fileinfo.ProcessId = file.ProcessId;
fileinfo.ReceiveDate = file.ReceiveDate;
fileinfo.ExpiryDate = file.ExpiryDate;
fileinfo.Deviation = file.Deviation;
fileinfo.ReFunction = file.ReFunction;
fileinfo.DirectDepartment = file.DirectDepartment;
fileinfo.DirectPeople = file.DirectPeople;
}
else if (file.AssTag == "技术文件")
{
fileinfo.ProjectNum = file.ProjectNum;
fileinfo.ProjectLine = file.ProjectLine;
fileinfo.ProjectName = file.ProjectName;
fileinfo.Customer = file.Customer;
fileinfo.AreaCompany = file.AreaCompany;
}
else if (file.AssTag == "CTC流程文件")
{
fileinfo.ProcessType = file.ProcessType;
fileinfo.AbolishId = file.AbolishId;
fileinfo.L1 = file.L1;
fileinfo.L2 = file.L2;
fileinfo.L3 = file.L3;
fileinfo.AreaCompany = file.AreaCompany;
if (string.IsNullOrEmpty(file.FileNum))
{
if (string.IsNullOrEmpty(filenum))
{
fileinfo.FileNum = GetFileCode(file);
string codeprdf = GetCodeNP(file);
codemgr.UpdataCode(codeprdf, fileinfo.FileNum.Replace(tcpre.DefaultValue + "-", ""));
}
}
else
{
string codeprdf = GetCodeNP(file);
fileinfo.FileNum = file.FileNum;
codemgr.DelRecCode(file.FileNum.Replace(tcpre.DefaultValue + "-", ""), codeprdf);
}
}
else if (file.AssTag == "标准文件")
{
fileinfo.ProcessType = file.ProcessType;
fileinfo.BigClass = file.BigClass;
fileinfo.SmallClass = file.SmallClass;
fileinfo.OEM = file.OEM;
fileinfo.ProjectUsed = file.ProjectUserd;
fileinfo.KeyWord = file.KeyWord;
fileinfo.OEMKey = file.OEMKey;
if (string.IsNullOrEmpty(file.FileNum))
{
if (string.IsNullOrEmpty(filenum))
{
fileinfo.FileNum = GetFileCode(file);
string codeprdf = GetCodeNP(file);
codemgr.UpdataCode(codeprdf, fileinfo.FileNum.Replace(tcpre.DefaultValue + "-", ""));
}
}
else
{
fileinfo.FileNum = file.FileNum;
}
}
if (!string.IsNullOrEmpty(file.Abolish))
{
fileinfo.Abolish = file.Abolish;
}
db.SubmitChanges();
if (string.IsNullOrEmpty(filenum))
{
string codeprdf = "";
if (file.AssTag == "运作体系文件") {
codeprdf = GetCodeNP(file);
}
if (!string.IsNullOrEmpty(file.FileNum))
{
if (file.IsFileNum != "是")
{
codemgr.UpdataCode(codeprdf, file.FileNum.Replace(syspre.DefaultValue, ""));
if (file.FileHierarchy == "三级")
{
if (file.RelationType == "无")
{
string[] filenums = file.FileNum.Replace("-" + file.FileType, ",").Split(',');
if (!IsExcelFile(filenums[0].ToString()))
{
codemgr.InsertNUCode(filenums[0].Replace(syspre.DefaultValue, "").ToString());
}
string[] codes = file.FileNum.Split('-');
codemgr.UpdataCode(file.Process, codes[0].Replace(syspre.DefaultValue, "").ToString());
codemgr.DelRecCode(codes[0].Replace(syspre.DefaultValue, ""), file.Process);
}
}
codemgr.DelRecCode(file.FileNum.Replace(syspre.DefaultValue, ""), codeprdf);
}
else
{
codemgr.DelNUCode(file.FileNum.Replace(syspre.DefaultValue, ""));
}
if (file.HasForm == "true")
{
if(!string.IsNullOrEmpty(file.FormId))
{
string[] forms = file.FormId.Split(',');
foreach (string id in forms)
{
FileFormMgr formmgr=new FileFormMgr();
FileFormEntity fileform=formmgr.GetActiveFileFormById(new PagingEntity{Id=id});
if(fileform.Type=="有格式"&&string.IsNullOrEmpty(fileform.FileNum))
{
string formpref=file.FileNum.Replace(syspre.DefaultValue, "")+"-";
fileform.FileNum = syspre.DefaultValue+codemgr.GetCode(formpref);
fileform.FileId = file.Id;
formmgr.UpdataActiveFileForm(fileform);
codemgr.UpdataCode(formpref, fileform.FileNum.Replace(syspre.DefaultValue, "").ToString());
codemgr.DelRecCode(fileform.FileNum.Replace(syspre.DefaultValue, "").ToString(), formpref);
}
}
}
}
}
}
if (!string.IsNullOrEmpty(file.FilePath))
{ DMSComm.SetFileName(file.FilePath, file.FileName,file.FileArea); }
//判断是否草稿
if (file.IsDraft == "false"&&isdraft=="true")
{
WFCommEntity item = new WFCommEntity();
item.ApplicantAD = DMSComm.resolveLogon(user.LoginName);
item.Area = file.Area;
item.AreaType = file.AreaType;
item.FileHierarchy = file.FileHierarchy;
item.FileId = file.Id;
item.WFType = ((int)DMSEnum.WFType.Insert).ToString();
item.AssTag = file.AssTag;
WFCommMgr commgr = new WFCommMgr();
if (file.AssTag == "运作体系文件")
{
commgr.StartWorkFlow(item);
}
else if (file.AssTag == "标准文件" || file.AssTag == "CTC流程文件" || file.AssTag == "技术文件")
{
item.BigClass = file.BigClass;
item.SmallClass = file.SmallClass;
item.OEM = file.OEM;
item.EPNum = file.ProjectNum;
commgr.StartTCWorkFlow(item);
if (!string.IsNullOrEmpty(file.AbolishId))
{
string[] ids = file.AbolishId.Split(',');
foreach (string ablishfile in ids)
{
FileInfo fitem = db.FileInfos.Where(p => p.Id == int.Parse(ablishfile)).FirstOrDefault();
fitem.IsChange = "true";
db.SubmitChanges();
}
}
}
}
}
return true;
}
/// <summary>
/// 更新文件并发起流程
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public bool UpdataFileWF(FileInfoEntity file)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (FileInfoDataDataContext db = new FileInfoDataDataContext(setting.DefaultValue))
{
FileInfoActive fileinfo = db.FileInfoActives.Where(p => p.Id == int.Parse(file.Id)).FirstOrDefault();
fileinfo.FileName = file.FileName;
fileinfo.FilePath = file.FilePath;
fileinfo.FileDesc = file.FileDesc;
fileinfo.UpDateTime= DateTime.Now.ToString();
fileinfo.Reference = file.References;
fileinfo.VersionNum = file.VersionNum;
fileinfo.Path = file.Path;
fileinfo.IsDraft = file.IsDraft;
fileinfo.FileLevel = file.FileLevel;
fileinfo.FileArea = file.FileArea;
if (file.AssTag == "运作体系文件")
{
fileinfo.AreaCompany = file.AreaCompany;
fileinfo.HasForm = file.HasForm;
fileinfo.FormId = file.FormId;
fileinfo.FileNum = file.FileNum;
fileinfo.IsFileNum = file.IsFileNum;
fileinfo.IsRelation = file.IsRelation;
fileinfo.RelationType = file.RelationType;
fileinfo.RelationName = file.RelationName;
fileinfo.RelationId = file.RelationId;
fileinfo.FileHierarchy = file.FileHierarchy;
fileinfo.Area = file.Area;
fileinfo.AreaType = file.AreaType;
fileinfo.CompanyCode = file.CompanyCode;
fileinfo.Process = file.Process;
fileinfo.ReFunction = file.ReFunction;
fileinfo.DirectDepartment = file.DirectDepartment;
fileinfo.DirectPeople = file.DirectPeople;
fileinfo.UpdateType = file.UpdateType;
}
else if (file.AssTag == "技术文件")
{
fileinfo.ProjectNum = file.ProjectNum;
fileinfo.ProjectLine = file.ProjectLine;
fileinfo.ProjectName = file.ProjectName;
fileinfo.Customer = file.Customer;
}
else if (file.AssTag == "CTC流程文件")
{
fileinfo.ProcessType = file.ProcessType;
fileinfo.AreaCompany = file.AreaCompany;
}
else if (file.AssTag == "标准文件")
{
fileinfo.ProcessType = file.ProcessType;
fileinfo.BigClass = file.BigClass;
fileinfo.SmallClass = file.SmallClass;
fileinfo.OEM = file.OEM;
fileinfo.ProjectUsed = file.ProjectUserd;
fileinfo.KeyWord = file.KeyWord;
fileinfo.OEMKey = file.OEMKey;
}
db.SubmitChanges();
FileInfo fitem = db.FileInfos.Where(p => p.Id == int.Parse(file.Id)).FirstOrDefault();
fitem.IsChange = "true";
db.SubmitChanges();
WFCommEntity item = new WFCommEntity();
item.ApplicantAD = DMSComm.resolveLogon(user.LoginName);
item.Area = fileinfo.Area;
item.AreaType = fileinfo.AreaType;
item.FileHierarchy = fileinfo.FileHierarchy;
item.FileId = file.Id;
item.WFType = ((int)DMSEnum.WFType.Update).ToString();
item.AssTag = fileinfo.AssTag;
WFCommMgr commgr = new WFCommMgr();
if (fileinfo.AssTag == "运作体系文件")
{
commgr.StartWorkFlow(item);
}
else if (fileinfo.AssTag == "标准文件" || fileinfo.AssTag == "CTC流程文件" || fileinfo.AssTag == "技术文件")
{
item.BigClass = file.BigClass;
item.SmallClass = file.SmallClass;
item.OEM = file.OEM;
item.EPNum = file.ProjectNum;
commgr.StartTCWorkFlow(item);
}
}
return true;
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public bool DelFileWF(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (FileInfoDataDataContext db = new FileInfoDataDataContext(setting.DefaultValue))
{
FileInfoActive file = db.FileInfoActives.Where(p => p.Id == Convert.ToInt32(obj.Id)).FirstOrDefault();
file.Abolish = obj.Abolish;
file.IsDelete = "true";
db.SubmitChanges();
FileInfo fitem = db.FileInfos.Where(p => p.Id == Convert.ToInt32(obj.Id)).FirstOrDefault();
fitem.IsChange = "true";
db.SubmitChanges();
WFCommEntity item = new WFCommEntity();
item.ApplicantAD = DMSComm.resolveLogon(user.LoginName);
item.Area = file.Area;
item.AreaType = file.AreaType;
item.FileHierarchy = file.FileHierarchy;
item.FileId = obj.Id;
item.WFType = ((int)DMSEnum.WFType.Delete).ToString();
item.AssTag = file.AssTag;
WFCommMgr commgr = new WFCommMgr();
if (file.AssTag == "运作体系文件")
{
commgr.StartWorkFlow(item);
}
else if (file.AssTag == "标准文件" || file.AssTag == "CTC流程文件")
{
item.BigClass = file.BigClass;
item.SmallClass = file.SmallClass;
item.OEM = file.OEM;
commgr.StartTCWorkFlow(item);
}
}
return true;
}
/// <summary>
/// 删除活动文件信息
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public bool DelActiveFile(string id)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (FileInfoDataDataContext db = new FileInfoDataDataContext(setting.DefaultValue))
{
FileInfoActive file = db.FileInfoActives.Where(p => p.Id == Convert.ToInt32(id)).FirstOrDefault();
FileInfoEntity fileinfo = GetActiveFileinfoByid(id);
if (!string.IsNullOrEmpty(fileinfo.FormId))
{
string[] formids = fileinfo.FormId.Split(',');
foreach (string formid in formids)
{
FileFormMgr formmgr = new FileFormMgr();
formmgr.DelActiveFileForm(new PagingEntity { Id=formid});
FileFormEntity form = formmgr.GetFileFormById(new PagingEntity { Id = formid });
formmgr.DelFileForm(new PagingEntity { Id = formid });
}
}
if (!string.IsNullOrEmpty(file.FileNum)&&file.AssTag=="运作体系文件")
{
codemgr.InsertRecCode(GetCodePref(fileinfo), file.FileNum, file.AssTag);
}
try
{
DelFile(SPContext.Current.Site.Url, file.FilePath, file.FileArea);
}
catch
{
}
db.FileInfoActives.DeleteOnSubmit(file);
db.SubmitChanges();
return true;
}
}
/// <summary>
/// 删除网站文件
/// </summary>
/// <param name="weburl"></param>
/// <param name="fileid"></param>
/// <returns></returns>
public bool DelFile(string weburl, string fileid, string filearea)
{
if (filearea == "Sharepoint")
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(weburl))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPFile file = web.GetFile(new Guid(fileid));
if (file != null)
{ file.Delete(); }
web.AllowUnsafeUpdates = false;
}
}
});
}
return true;
}
#region 查阅人相关
/// <summary>
/// 添加查阅人
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public bool AddRefer(FileInfoEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (FileInfoDataDataContext db = new FileInfoDataDataContext(setting.DefaultValue))
{
string drafttype = "";
if (obj.DraftType == "文件")
{ drafttype = ((int)DMSEnum.PermissionType.FileActive).ToString(); }
else if (obj.DraftType == "分发")
{ drafttype = ((int)DMSEnum.PermissionType.Share).ToString(); }
else if (obj.DraftType == "借阅")
{ drafttype = ((int)DMSEnum.PermissionType.Borrow).ToString(); }
PermissionEntity pitem = new PermissionEntity();
pitem.ItemId = obj.Id;
pitem.Account = obj.Refer;
pitem.IsGroup = "N";
pitem.Permission = ((int)DMSEnum.Permission.Download).ToString();
pitem.CreateTime = DateTime.Now.ToString();
pitem.Type = drafttype;
string id= permissionmgr.InsertPermission(pitem);
FileRefer item = new FileRefer();
item.ItemId = obj.Id;
item.Type = drafttype;
item.Refer = obj.Refer;
item.PermissionId = id;
db.FileRefers.InsertOnSubmit(item);
db.SubmitChanges();
}
return true;
}
/// <summary>
/// 发邮件
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public bool SendEmail(PagingEntity obj)
{
MailMgr mailmgr = new MailMgr();
SysUserMgr usermgr = new SysUserMgr();
FileActiveMgr fileacmgr = new FileActiveMgr();
FileInfoEntity file = fileacmgr.GetActiveFileinfoByid(obj.Id);
SysUserEntity creater = usermgr.GetSysUserBySid(file.Creater);
string[] accept = obj.Approver.Split(',');
foreach (string item in accept)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(obj.Weburl))
{
using (SPWeb web = site.OpenWeb())
{
site.AllowUnsafeUpdates = true;
web.AllowUnsafeUpdates = true;
string language = web.Language.ToString();
SPFile fileinfo = web.GetFile(new Guid(file.FilePath));
SPListItem myItem = fileinfo.Item;
if (!myItem.HasUniqueRoleAssignments)
{
myItem.BreakRoleInheritance(true);
}
SPRoleAssignment assignment1 = new SPRoleAssignment(web.EnsureUser(item));
//创建一个权限级别
SPRoleDefinition definition1 = site.RootWeb.RoleDefinitions.GetByType(SPRoleType.Reader);
//给角色绑定一个权限
assignment1.RoleDefinitionBindings.Add(definition1);
//将该角色添加到web的角色集合中
myItem.RoleAssignments.Add(assignment1);
myItem.Update();
web.AllowUnsafeUpdates = false;
site.AllowUnsafeUpdates = false ;
}
}
});
SysUserEntity approver = usermgr.GetSysUserBySid(item);
MailEntity template = mailmgr.GetEmailTemplate(SPContext.Current.Site.Url, "Draft");
string replacedSubjectStr = mailmgr.ReplaceTCMailTemplate(template.Subject, creater.ChineseName, file.FileName, "", "", file.FileName, "", approver.ChineseName, file.CreateTime, file.FileUrl);
string replacedBodyStr = mailmgr.ReplaceTCMailTemplate(template.Body, creater.ChineseName, file.FileName, "", "", file.FileName, "", approver.ChineseName, file.CreateTime, file.FileUrl);
mailmgr.SendEmail(approver.Email, replacedSubjectStr, replacedBodyStr, SPContext.Current.Site.Url, null);
}
return true;
}
/// <summary>
/// 删除查阅人
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public bool RemoveRefer(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (FileInfoDataDataContext db = new FileInfoDataDataContext(setting.DefaultValue))
{
FileRefer item = db.FileRefers.Where(p => p.Id == Convert.ToInt32(obj.Id)).FirstOrDefault();
bool istrue = permissionmgr.DelPermission(new PagingEntity { Id = item.PermissionId });
if (istrue)
{
db.FileRefers.DeleteOnSubmit(item);
db.SubmitChanges();
}
}
return true;
}
/// <summary>
/// 获取查阅人
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public List<FileReferEntity> GetRefers(PagingEntity obj)
{
List<FileReferEntity> listitems = new List<FileReferEntity>();
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (FileInfoDataDataContext db = new FileInfoDataDataContext(setting.DefaultValue))
{
string drafttype="";
if (obj.DraftType == "文件")
{ drafttype = ((int)DMSEnum.PermissionType.FileActive).ToString(); }
else if (obj.DraftType == "分发")
{ drafttype = ((int)DMSEnum.PermissionType.Share).ToString(); }
else if (obj.DraftType == "借阅")
{ drafttype = ((int)DMSEnum.PermissionType.Borrow).ToString(); }
List<FileRefer> items = db.FileRefers.Where(p => p.ItemId == obj.Id && p.Type == drafttype).ToList();
foreach(FileRefer item in items)
{
FileReferEntity refer = new FileReferEntity();
refer.Id = item.Id;
refer.ItemId = item.ItemId;
refer.PermissionId = item.PermissionId;
refer.CDSID = item.Refer;
SysUserEntity user = usermgr.GetSysUserBySid(item.Refer);
refer.UserName = user.ChineseName;
listitems.Add(refer);
}
return listitems;
}
}
/// <summary>
/// 文件签出
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public bool CheckeOutFile(PagingEntity obj)
{
bool flag = false;
using (SPSite site = new SPSite(obj.Weburl))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPFile file = web.GetFile(new Guid(obj.FileId));
if (file.CheckOutStatus == SPFile.SPCheckOutStatus.ShortTerm)
{
file.ReleaseLock(file.LockId);
}
file.CheckOut();
web.AllowUnsafeUpdates = false;
flag = true;
return flag;
}
}
}
/// <summary>
/// 放弃签出
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public bool UndoCheckOutFile(PagingEntity obj)
{
bool flag = false;
using (SPSite site = new SPSite(obj.Weburl))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPFile file = web.GetFile(new Guid(obj.FileId));
file.UndoCheckOut();
web.AllowUnsafeUpdates = false;
flag = true;
return flag;
}
}
}
/// <summary>
/// 文件签入
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public bool CheckInFile(PagingEntity obj)
{
bool flag = false;
using (SPSite site = new SPSite(obj.Weburl))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPFile file = web.GetFile(new Guid(obj.FileId));
if (file.CheckOutStatus == SPFile.SPCheckOutStatus.ShortTerm)
{
file.ReleaseLock(file.LockId);
//file.CheckIn("更新文件并覆盖当前版本", SPCheckinType.OverwriteCheckIn);
}
else
{
file.CheckIn("更新文件并覆盖当前版本", SPCheckinType.OverwriteCheckIn);
}
web.AllowUnsafeUpdates = false;
flag = true;
return flag;
}
}
}
#endregion
#endregion
#region 文件搜索相关
/// <summary>
/// 获取活动的文件
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public FileInfoEntity GetFileActiveById(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
ProjectMgr projectmgr = new ProjectMgr();
using (FileInfoDataDataContext db = new FileInfoDataDataContext(setting.DefaultValue))
{
ProjectEntity proitem = new ProjectEntity();
FileInfoActive file = db.FileInfoActives.Where(p => p.Id == Convert.ToInt32(obj.Id)).FirstOrDefault();
if (!string.IsNullOrEmpty(file.ProjectNum))
{
proitem = projectmgr.GetProjectByEPNum(new PagingEntity { EPNum = file.ProjectNum });
}
FileInfoEntity fileinfo = new FileInfoEntity();
fileinfo.Id = file.Id.ToString();
fileinfo.FileName = file.FileName;
fileinfo.FilePath = file.FilePath;
fileinfo.FileDesc = file.FileDesc;
fileinfo.CompanyCode = file.CompanyCode;
fileinfo.Creater = file.Creater;
fileinfo.CreateTime = file.CreateTime;
fileinfo.HasForm = file.HasForm;
fileinfo.FormId = file.FormId;
fileinfo.References = file.Reference;
fileinfo.FileNum = file.FileNum;
fileinfo.IsFileNum = file.IsFileNum;
fileinfo.IsRelation = file.IsRelation;
fileinfo.RelationType = file.RelationType;
fileinfo.RelationName = file.RelationName;
fileinfo.RelationId = file.RelationId;
fileinfo.VersionNum = file.VersionNum;
fileinfo.FileHierarchy = file.FileHierarchy;
fileinfo.FileType = file.FileType;
fileinfo.FileDesc = file.FileDesc;
fileinfo.Area = file.Area;
fileinfo.AreaType = file.AreaType;
fileinfo.AssTag = file.AssTag;
fileinfo.EffectiveDate = file.EffectiveDate;
fileinfo.AreaCompany = "";
fileinfo.AreaCompanyCode = file.AreaCompany;
fileinfo.KeyWord = file.KeyWord;
fileinfo.ReFunction = file.ReFunction;
fileinfo.Depart = file.Depart;
fileinfo.ReceiveDate = file.ReceiveDate;
fileinfo.ExpiryDate = file.ExpiryDate;
fileinfo.Deviation = file.Deviation;
fileinfo.Process = file.Process;
fileinfo.ProcessId = file.ProcessId;
fileinfo.IsDelete = file.IsDelete;
fileinfo.DirectDepartment = file.DirectDepartment;
fileinfo.DirectPeople = file.DirectPeople;
fileinfo.DisId = file.DisId;
fileinfo.BorrowId = file.BorrowId;
fileinfo.FileArea = file.FileArea;
if (!string.IsNullOrEmpty(file.FilePath))
{
if (file.FileArea == "Sharepoint")
{ fileinfo.FileUrl = DMSComm.GetFilePath(file.FilePath); }
else
{
fileinfo.FileUrl = DMSComm.GetLocalPath(file.FilePath);
}
}
fileinfo.SPVersion = file.SPVersion;
fileinfo.UpdateType = file.UpdateType;
if (!string.IsNullOrEmpty(file.AreaCompany))
{
string[] companys = file.AreaCompany.Split(',');
if (companys.Count() > 0)
{
foreach (string company in companys)
{
DataDicEntity sysitem = datadicmgr.GetDataValueByHidden(company, "Company", SPContext.Current.Site.Url);
if (string.IsNullOrEmpty(fileinfo.AreaCompany))
{
fileinfo.AreaCompany = sysitem.DisplayValue;
}
else
{
fileinfo.AreaCompany = fileinfo.AreaCompany + "," + sysitem.DisplayValue;
}
}
}
else
{
fileinfo.AreaCompany = "";
}
}
fileinfo.IsDraft = file.IsDraft;
fileinfo.Path = file.Path;
fileinfo.PathName = DMSComm.GetFolderPath(file.Path);
fileinfo.FileLevel = file.FileLevel;
fileinfo.ProjectNum = file.ProjectNum;
fileinfo.ProjectLine = proitem.ProjectLine;
fileinfo.ProjectName = proitem.Name;
fileinfo.ProjectUserd = file.ProjectUsed;
fileinfo.Customer = proitem.Customer;
fileinfo.ProcessType = file.ProcessType;
fileinfo.BigClass = file.BigClass;
fileinfo.SmallClass = file.SmallClass;
fileinfo.OEM = file.OEM;
fileinfo.ProjectUserd = file.ProjectUsed;
fileinfo.L1 = file.L1;
fileinfo.L2 = file.L2;
fileinfo.L3 = file.L3;
fileinfo.AbolishId = file.AbolishId;
fileinfo.KeyWord = file.KeyWord;
fileinfo.Abolish = file.Abolish;
fileinfo.OEMKey = file.OEMKey;
return fileinfo;
}
}
/// <summary>
/// 获取文件信息
/// </summary>
/// <param name="obj">页面参数</param>
/// <returns></returns>
public FileInfoEntity GetActiveFileinfoByid(string id)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (FileInfoDataDataContext db = new FileInfoDataDataContext(setting.DefaultValue))
{
FileInfoActive file = db.FileInfoActives.Where(p => p.Id == Convert.ToInt32(id)).FirstOrDefault();
FileInfoEntity fileinfo = new FileInfoEntity();
if (file != null)
{
fileinfo.Id = file.Id.ToString();
fileinfo.Process = file.Process;
fileinfo.FileName = file.FileName;
fileinfo.FilePath = file.FilePath;
fileinfo.FileDesc = file.FileDesc;
fileinfo.AreaCompany = file.AreaCompany;
fileinfo.Creater = file.Creater;
fileinfo.CreateTime = file.CreateTime;
fileinfo.HasForm = file.HasForm;
fileinfo.FormId = file.FormId;
fileinfo.References = file.Reference;
fileinfo.FileNum = file.FileNum;
fileinfo.IsFileNum = file.IsFileNum;
fileinfo.IsRelation = file.IsRelation;
fileinfo.RelationType = file.RelationType;
fileinfo.RelationName = file.RelationName;
fileinfo.RelationId = file.RelationId;
fileinfo.VersionNum = file.VersionNum;
fileinfo.FileHierarchy = file.FileHierarchy;
fileinfo.FileType = file.FileType;
fileinfo.FileDesc = file.FileDesc;
fileinfo.Area = file.Area;
fileinfo.AreaType = file.AreaType;
fileinfo.AssTag = file.AssTag;
fileinfo.CompanyCode = file.CompanyCode;
fileinfo.IsDraft = file.IsDraft;
fileinfo.AreaCompany = file.AreaCompany;
fileinfo.UpdateType = file.UpdateType;
fileinfo.Path = file.Path;
if (!string.IsNullOrEmpty(file.Path))
{ fileinfo.PathName = DMSComm.GetFolderPath(file.Path); }
if (!string.IsNullOrEmpty(file.FilePath))
{
if (file.FileArea == "Sharepoint")
{ fileinfo.FileUrl = DMSComm.GetFilePath(file.FilePath); }
else
{
fileinfo.FileUrl = DMSComm.GetLocalPath(file.FilePath);
}
}
fileinfo.EffectiveDate = file.EffectiveDate;
fileinfo.ProjectNum = file.ProjectNum;
fileinfo.ProjectLine = file.ProjectLine;
fileinfo.ProjectName = file.ProjectName;
fileinfo.Customer = file.Customer;
fileinfo.ProcessType = file.ProcessType;
fileinfo.BigClass = file.BigClass;
fileinfo.SmallClass = file.SmallClass;
fileinfo.OEM = file.OEM;
fileinfo.ProjectUserd = file.ProjectUsed;
fileinfo.ReFunction = file.ReFunction;
fileinfo.Depart = file.Depart;
fileinfo.ReceiveDate = file.ReceiveDate;
fileinfo.ExpiryDate = file.ExpiryDate;
fileinfo.Deviation = file.Deviation;
fileinfo.IsDelete = file.IsDelete;
fileinfo.ProcessId = file.ProcessId;
fileinfo.FileLevel = file.FileLevel;
fileinfo.DirectDepartment = file.DirectDepartment;
fileinfo.DirectPeople = file.DirectPeople;
fileinfo.SPVersion = file.SPVersion;
fileinfo.CreateType = file.CreateType;
fileinfo.DisId = file.DisId;
fileinfo.BorrowId = file.BorrowId;
fileinfo.FileArea = file.FileArea;
}
return fileinfo;
}
}
/// <summary>
/// 检查名称是否存在
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public bool CheckName(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (FileInfoDataDataContext db = new FileInfoDataDataContext(setting.DefaultValue))
{
//List<FileInfoActive> items = db.FileInfoActives.Where(p => p.FileName == obj.Name&&p.Path==obj.Path).ToList();
List<FileInfoActive> items = db.FileInfoActives.Where(p => p.FileName == obj.Name&&p.IsDelete=="false"&&p.AssTag==obj.AssTag).ToList();
if (items.Count == 0)
{
return true;
}
else
{
return false;
}
}
}
/// <summary>
/// 判断编码是否存在关联文件
/// </summary>
/// <param name="filenum"></param>
/// <returns></returns>
public bool IsExcelFile(string filenum)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (FileInfoDataDataContext db = new FileInfoDataDataContext(setting.DefaultValue))
{
List<FileInfoActive> listitem = db.FileInfoActives.Where(p => p.FileNum == filenum).ToList();
if (listitem.Count() > 0)
{
return true;
}
else
{
return false;
}
}
}
/// <summary>
/// 获取文件编号
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public string GetFileIdByName(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (FileInfoDataDataContext db = new FileInfoDataDataContext(setting.DefaultValue))
{
FileInfoActive file = db.FileInfoActives.Where(p => p.FileName == obj.Name && p.AssTag == obj.AssTag && p.IsDelete == "false").FirstOrDefault();
if (file!=null)
{
return file.Id.ToString();
}
else
{
return null;
}
}
}
#endregion
#region 文件编码相关
/// <summary>
/// 获取页面属性自动生成文件代码
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public string GetFileCode(FileInfoEntity obj)
{
string code = "";
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
SettingsEntity syspre = mgr.GetSystemSetting(SPContext.Current.Site.Url, "SYSPrefix");
SettingsEntity tcpre = mgr.GetSystemSetting(SPContext.Current.Site.Url, "TCPrefix");
string weburl = SPContext.Current.Site.Url;
using (FileInfoDataDataContext db = new FileInfoDataDataContext(setting.DefaultValue))
{
if (obj.AssTag == "运作体系文件")
{
if (obj.FileHierarchy == "一级")
{
if (!string.IsNullOrEmpty(obj.Process))
{
CodeEntity filecode = codemgr.GetCodeinfo(obj.Process);
List<FileInfoActive> files = db.FileInfoActives.Where(p => p.FileNum == syspre.DefaultValue + "M01").ToList();
if (files.Count > 0)
{
code = "M01-";
}
else
{
code = "M";
}
code = syspre.DefaultValue + codemgr.GetCode(code);
}
}
else if (obj.FileHierarchy == "二级")
{
if (obj.IsFileNum == "是")
{
code = obj.FileNum;
}
else
{
if (!string.IsNullOrEmpty(obj.Process))
{
code = syspre.DefaultValue + codemgr.GetCode(obj.Process);
}
}
}
else if (obj.FileHierarchy == "三级")
{
if (obj.RelationType == "无")
{
if (!string.IsNullOrEmpty(obj.Process))
{
code = codemgr.GetCode(obj.Process);
if (!string.IsNullOrEmpty(obj.FileType))
{
code = code + "-" + datadicmgr.GetDataValue(obj.FileType, "文件类型", weburl).DisplayValue;
}
code = syspre.DefaultValue + codemgr.GetCode(code);
}
}
else if (obj.RelationType == "二级" )
{
FileInfo fileinfo = db.FileInfos.Where(p => p.Id == int.Parse(obj.RelationId)).FirstOrDefault();
code = fileinfo.FileNum.Replace(syspre.DefaultValue, "").Trim();
if (!string.IsNullOrEmpty(obj.FileType))
{
code = code + "-" + datadicmgr.GetDataValue(obj.FileType, "文件类型", weburl).DisplayValue;
}
if (!string.IsNullOrEmpty(obj.CompanyCode))
{
code = code + "-" + datadicmgr.GetDataValue(obj.CompanyCode, "公司代码", weburl).DisplayValue;
}
code = syspre.DefaultValue + codemgr.GetCode(code);
}
else if (obj.RelationType == "三级")
{
FileInfo fileinfo = db.FileInfos.Where(p => p.Id == int.Parse(obj.RelationId)).FirstOrDefault();
code = fileinfo.FileNum.Replace(syspre.DefaultValue, "").Trim();
if (!string.IsNullOrEmpty(obj.FileType))
{
code = code + "-" + datadicmgr.GetDataValue(obj.FileType, "文件类型", weburl).DisplayValue;
}
if (!string.IsNullOrEmpty(obj.CompanyCode))
{
code = code + "-" + datadicmgr.GetDataValue(obj.CompanyCode, "公司代码", weburl).DisplayValue;
}
code = syspre.DefaultValue + codemgr.GetCode(code);
}
}
}
else if (obj.AssTag == "CTC流程文件")
{
code = obj.ProcessType + "-" + obj.FileType;
code = tcpre.DefaultValue + "-" + codemgr.GetCode(code);
}
else if (obj.AssTag == "标准文件")
{
code = obj.BigClass + "-" + obj.SmallClass;
code = tcpre.DefaultValue + "-" + codemgr.GetCode(code);
}
}
return code;
}
/// <summary>
/// 获取编码前缀
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public string GetCodePref(FileInfoEntity obj)
{
string code = "";
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
SettingsEntity syspre = mgr.GetSystemSetting(SPContext.Current.Site.Url, "SYSPrefix");
SettingsEntity tcpre = mgr.GetSystemSetting(SPContext.Current.Site.Url, "TCPrefix");
string weburl = SPContext.Current.Site.Url;
using (FileInfoDataDataContext db = new FileInfoDataDataContext(setting.DefaultValue))
{
if (obj.AssTag == "运作体系文件")
{
if (obj.FileHierarchy == "一级")
{
string[] codes = obj.FileNum.Split('-');
if (codes.Count() > 1)
{
code = codes[0]+"-";
}
else
{
code = syspre.DefaultValue + obj.Process;
}
}
else if (obj.FileHierarchy == "二级")
{
code = syspre.DefaultValue + obj.Process;
}
else if (obj.FileHierarchy == "三级")
{
if (obj.RelationType == "无")
{
string[] codes = obj.FileNum.Replace(obj.FileType, ",").Split(',');
code = codes[0]+obj.FileType;
}
else if (obj.RelationType == "二级")
{
if (!string.IsNullOrEmpty(obj.CompanyCode))
{
string[] codes = obj.FileNum.Replace(obj.CompanyCode, ",").Split(',');
code = codes[0] + obj.CompanyCode;
}
else
{
string[] codes = obj.FileNum.Replace(obj.FileType, ",").Split(',');
code = codes[0] + obj.FileType;
}
}
else if (obj.RelationType == "三级")
{
string[] codes = obj.FileNum.Replace(obj.CompanyCode, ",").Split(',');
code = codes[0] + obj.CompanyCode;
}
}
}
else if (obj.AssTag == "CTC流程文件")
{
code = tcpre.DefaultValue + "-" + obj.ProcessType + "-" + obj.FileType;
}
else if (obj.AssTag == "标准文件")
{
code = tcpre.DefaultValue + "-" + obj.BigClass + "-" + obj.SmallClass;
}
}
return code;
}
/// <summary>
/// 获取编码前缀
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public string GetCodeNP(FileInfoEntity obj)
{
string code = "";
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
string weburl = SPContext.Current.Site.Url;
SettingsEntity syspre = mgr.GetSystemSetting(SPContext.Current.Site.Url, "SYSPrefix");
using (FileInfoDataDataContext db = new FileInfoDataDataContext(setting.DefaultValue))
{
if (obj.AssTag == "运作体系文件")
{
if (obj.FileHierarchy == "一级")
{
string[] codes = obj.FileNum.Split('-');
if (codes.Count() > 1)
{
code = codes[0]+"-";
}
else
{
code = syspre.DefaultValue + obj.Process;
}
}
else if (obj.FileHierarchy == "二级")
{
code = syspre.DefaultValue + obj.Process;
}
else if (obj.FileHierarchy == "三级")
{
if (obj.RelationType == "无")
{
string[] codes = obj.FileNum.Replace(obj.FileType, ",").Split(',');
code = codes[0] + obj.FileType;
}
else if (obj.RelationType == "二级")
{
if (!string.IsNullOrEmpty(obj.CompanyCode))
{
string[] codes = obj.FileNum.Replace(obj.CompanyCode, ",").Split(',');
code = codes[0] + obj.CompanyCode;
}
else
{
string[] codes = obj.FileNum.Replace(obj.FileType, ",").Split(',');
code = codes[0] + obj.FileType;
}
}
else if (obj.RelationType == "三级")
{
string[] codes = obj.FileNum.Replace(obj.CompanyCode, ",").Split(',');
code = codes[0] + obj.CompanyCode;
}
}
code = code.Replace(syspre.DefaultValue, "");
}
else if (obj.AssTag == "CTC流程文件")
{
code = obj.ProcessType + "-" + obj.FileType;
}
else if (obj.AssTag == "标准文件")
{
code = obj.BigClass + "-" + obj.SmallClass;
}
}
return code;
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.VFX;
public class BoidsVFXTestScript : MonoBehaviour {
public VisualEffect BoidsVFX;
private Vector3 oldPos;
void Start() {
if(!BoidsVFX){
enabled = false;
Debug.LogWarning("no vfx assigned!");
return;
}
oldPos = transform.position;
UpdateVFX();
}
void Update() {
if (oldPos != transform.position) {
oldPos = transform.position;
UpdateVFX();
}
}
void UpdateVFX() {
BoidsVFX.SetVector3("target", oldPos);
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ReactMusicStore.Core.Data.Context.Utilities.Hooks;
using ReactMusicStore.Core.Domain.Entities.Foundation;
using ReactMusicStore.Core.Utilities.Common;
namespace ReactMusicStore.Core.Data.Context.Config
{
public abstract partial class BaseDbContext
{
private SaveChangesOperation _currentSaveOperation;
enum SaveStage
{
PreSave,
PostSave
}
private IEnumerable<DbEntityEntry> GetChangedEntries()
{
return ChangeTracker.Entries().Where(x => x.State > System.Data.Entity.EntityState.Unchanged);
}
//private IHookHandler GetHookHandler()
//{
// return HostingEnvironment.IsHosted
// ? EngineContext.Current.Resolve<IHookHandler>()
// : NullHookHandler.Instance; // never trigger hooks during tooling or tests
//}
public override int SaveChanges()
{
var op = _currentSaveOperation;
if (op != null)
{
if (op.Stage == SaveStage.PreSave)
{
// // This was called from within a PRE action hook. We must get out:...
// // 1.) to prevent cyclic calls
// // 2.) we want new entities in the state tracker (added by pre hooks) to be committed atomically in the core SaveChanges() call later on.
return 0;
}
else if (op.Stage == SaveStage.PostSave)
{
// // This was called from within a POST action hook. Core SaveChanges() has already been called,
// // but new entities could have been added to the state tracker by hooks.
// // Therefore we need to commit them and get outta here, otherwise: cyclic nightmare!
return SaveChangesCore();
}
}
_currentSaveOperation = new SaveChangesOperation(this);
using (new ActionDisposable(() => _currentSaveOperation = null))
{
return _currentSaveOperation.Execute();
}
}
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken)
{
var op = _currentSaveOperation;
if (op != null)
{
if (op.Stage == SaveStage.PreSave)
{
// // This was called from within a PRE action hook. We must get out:...
// // 1.) to prevent cyclic calls
// // 2.) we want new entities in the state tracker (added by pre hooks) to be committed atomically in the core SaveChanges() call later on.
return Task.FromResult(0);
}
else if (op.Stage == SaveStage.PostSave)
{
// // This was called from within a POST action hook. Core SaveChanges() has already been called,
// // but new entities could have been added to the state tracker by hooks.
// // Therefore we need to commit them and get outta here, otherwise: cyclic nightmare!
return SaveChangesCoreAsync(cancellationToken);
}
}
_currentSaveOperation = new SaveChangesOperation(this);
using (new ActionDisposable(() => _currentSaveOperation = null))
{
return _currentSaveOperation.ExecuteAsync(cancellationToken);
}
}
/// <summary>
/// Just calls <c>DbContext.SaveChanges()</c> without any sugar
/// </summary>
/// <returns>The number of affected records</returns>
protected internal int SaveChangesCore(bool? validate = null)
{
var changedEntries = _currentSaveOperation?.ChangedEntries ?? GetChangedEntries();
var validationEnabled = this.Configuration.ValidateOnSaveEnabled;
if (validate != null)
{
Configuration.ValidateOnSaveEnabled = validate.Value;
}
var onDispose = new Action(() =>
{
if (validate != null)
{
Configuration.ValidateOnSaveEnabled = validationEnabled;
}
IgnoreMergedData(changedEntries, false);
});
using (new ActionDisposable(onDispose))
{
IgnoreMergedData(changedEntries, true);
return base.SaveChanges();
}
}
/// <summary>
/// Just calls <c>DbContext.SaveChangesAsync()</c> without any sugar
/// </summary>
/// <returns>The number of affected records</returns>
protected internal Task<int> SaveChangesCoreAsync(CancellationToken cancellationToken, bool? validate = null)
{
var changedEntries = _currentSaveOperation?.ChangedEntries ?? GetChangedEntries();
var validationEnabled = this.Configuration.ValidateOnSaveEnabled;
if (validate != null)
{
Configuration.ValidateOnSaveEnabled = validate.Value;
}
var onDispose = new Action(() =>
{
if (validate != null)
{
Configuration.ValidateOnSaveEnabled = validationEnabled;
}
IgnoreMergedData(changedEntries, false);
});
using (new ActionDisposable(onDispose))
{
IgnoreMergedData(changedEntries, true);
return base.SaveChangesAsync(cancellationToken);
}
}
private void IgnoreMergedData(IEnumerable<DbEntityEntry> entries, bool ignore)
{
//foreach (var entry in entries.OfType<IMergedData>())
//{
// entry.MergedDataIgnore = ignore;
//}
}
class SaveChangesOperation : IDisposable
{
private SaveStage _stage;
private IList<DbEntityEntry> _changedEntries;
private BaseDbContext _ctx;
//private IHookHandler _hookHandler;
public SaveChangesOperation(BaseDbContext ctx)
{
_ctx = ctx;
// _hookHandler = hookHandler;
_changedEntries = ctx.GetChangedEntries().ToList();
}
public IEnumerable<DbEntityEntry> ChangedEntries
{
get { return _changedEntries; }
}
public SaveStage Stage
{
get { return _stage; }
}
public int Execute()
{
// pre
HookedEntityEntry[] changedHookEntries;
PreExecute(out changedHookEntries);
// save
var result = _ctx.SaveChangesCore(false);
// post
PostExecute(changedHookEntries);
return result;
}
public Task<int> ExecuteAsync(CancellationToken cancellationToken)
{
// pre
HookedEntityEntry[] changedHookEntries;
PreExecute(out changedHookEntries);
// save
var result = _ctx.SaveChangesCoreAsync(cancellationToken, false);
// post
result.ContinueWith((t) =>
{
if (!t.IsFaulted)
{
PostExecute(changedHookEntries);
}
});
return result;
}
private void PreExecute(out HookedEntityEntry[] changedHookEntries)
{
bool enableHooks = false;
bool importantHooksOnly = false;
bool anyStateChanged = false;
changedHookEntries = null;
enableHooks = _changedEntries.Any(); // hooking is meaningless without hookable entries
if (enableHooks)
{
// despite the fact that hooking can be disabled, we MUST determine if any "important" pre hook exists.
// If yes, but hooking is disabled, we'll trigger only the important ones.
importantHooksOnly = !_ctx.HooksEnabled;
// we'll enable hooking for this unit of work only when it's generally enabled,
// OR we have "important" hooks in the pipeline.
enableHooks = importantHooksOnly || _ctx.HooksEnabled;
}
//if (enableHooks)
//{
// changedHookEntries = _changedEntries
// .Select(x => new HookedEntityEntry { Entry = x, PreSaveState = (SmartStore.Core.Data.EntityState)((int)x.State) })
// .ToArray();
// // Regardless of validation (possible fixing validation errors too)
// anyStateChanged = _hookHandler.TriggerPreActionHooks(changedHookEntries, false, importantHooksOnly);
//}
if (_ctx.Configuration.ValidateOnSaveEnabled)
{
var results = from entry in _ctx.ChangeTracker.Entries()
where _ctx.ShouldValidateEntity(entry)
let validationResult = entry.GetValidationResult()
where !validationResult.IsValid
select validationResult;
if (results.Any())
{
var ex = new DbEntityValidationException(FormatValidationExceptionMessage(results), results);
//Debug.WriteLine(ex.Message, ex);
throw ex;
}
}
//if (enableHooks)
//{
// anyStateChanged = _hookHandler.TriggerPreActionHooks(changedHookEntries, true, importantHooksOnly);
//}
//if (anyStateChanged)
//{
// // because the state of at least one entity has been changed during pre hooking
// // we have to further reduce the set of hookable entities (for the POST hooks)
// changedHookEntries = changedHookEntries
// .Where(x => x.PreSaveState > SmartStore.Core.Data.EntityState.Unchanged)
// .ToArray();
//}
}
private void PostExecute(HookedEntityEntry[] changedHookEntries)
{
if (changedHookEntries == null || changedHookEntries.Length == 0)
return;
// the existence of hook entries actually implies that hooking is enabled.
_stage = SaveStage.PostSave;
//var importantHooksOnly = !_ctx.HooksEnabled && _hookHandler.HasImportantPostHooks();
//_hookHandler.TriggerPostActionHooks(changedHookEntries, importantHooksOnly);
}
private string FormatValidationExceptionMessage(IEnumerable<DbEntityValidationResult> results)
{
var sb = new StringBuilder();
sb.Append("Entity validation failed" + Environment.NewLine);
foreach (var res in results)
{
var baseEntity = res.Entry.Entity as BaseEntity;
sb.AppendFormat("Entity Name: {0} - Id: {0} - State: {1}",
res.Entry.Entity.GetType().Name,
baseEntity != null ? baseEntity.Id.ToString() : "N/A",
res.Entry.State.ToString());
sb.AppendLine();
foreach (var validationError in res.ValidationErrors)
{
sb.AppendFormat("\tProperty: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
sb.AppendLine();
}
}
return sb.ToString();
}
public void Dispose()
{
_ctx = null;
//_hookHandler = null;
_changedEntries = null;
}
}
}
}
|
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using CC.Utilities.Services;
namespace CC.Mobile.Services
{
public interface ISyncEnabledRepositoryService<T>:IRepositoryService<T>
{
Task<List<T>> GetDirty();
Task SetPristine (List<T> items);
Task Sync(List<T> items);
}
}
|
using System.Collections.Generic;
using L._52ABP.Application.Dtos;
using DgKMS.Cube.CubeCore.Dtos;
namespace DgKMS.Cube.CubeCore.Exporting
{
public interface IEvernoteTagListExcelExporter
{
/// <summary>
/// 导出为Excel文件
/// </summary>
/// <param name="evernoteTagListDtos">传入的数据集合</param>
/// <returns></returns>
FileDto ExportToExcelFile(List<EvernoteTagListDto> evernoteTagListDtos);
//// custom codes
//// custom codes end
}
} |
namespace PizzaBox.Domain.Library
{
public class Addressing
{
public int Id { get; set; }
public string City { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Street { get; set; }
public string PhoneNumber { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MemberRegistrationMicroservice.Business.Abstract;
using MemberRegistrationMicroservice.Business.ServiceAdapters;
using MemberRegistrationMicroservice.Business.ValidationRules.FluentValidation;
using MemberRegistrationMicroservice.DataAccess.Abstract;
using MemberRegistrationMicroservice.Entities.Concrete;
using OK.Core.Aspects.Postsharp;
using OK.Core.Aspects.PostSharp;
namespace MemberRegistrationMicroservice.Business.Concrete
{
public class MemberManager : IMemberService
{
private IMemberDal _memberDal;
private IKpsService _kpsService;
public MemberManager(IMemberDal memberDal, IKpsService kpsService)
{
_memberDal = memberDal;
_kpsService = kpsService;
}
[FluentValidationAspect(typeof(MemberValidator))]
public void Add(Member member)
{
CheckMemberExists(member);
CheckIfIdValidFromKps(member);
_memberDal.Add(member);
}
private void CheckIfIdValidFromKps(Member member)
{
if (_kpsService.ValidateUser(member) == false)
{
throw new Exception("Kullanıcı doğrulanamadı");
}
}
private void CheckMemberExists(Member member)
{
if (_memberDal.Get(x => x.TCKimlikNo == member.TCKimlikNo) != null)
{
throw new Exception("Kayıtlı Tc Kimlik Numarası");
}
}
}
}
|
using System;
using System.Linq;
using System.Text;
namespace Book_Worm
{
class Program
{
static void Main(string[] args)
{
var initString = new StringBuilder(Console.ReadLine());
var size = int.Parse(Console.ReadLine());
var matrix = new char[size,size];
var playerRow = -1;
var playerCol = - 1;
//ReadMatrix
for (int i = 0; i < size; i++)
{
var row = Console.ReadLine();
for (int j = 0; j < size; j++)
{
if (row[j] == 'P')
{
playerRow = i;
playerCol = j;
}
matrix[i, j] = row[j];
}
}
var command = Console.ReadLine();
while (command != "end")
{
if (command == "up")
{
matrix[playerRow, playerCol] = '-';
playerRow--;
if (!CheckForPunishment(matrix,playerRow,playerCol,initString))
{
CheckForLetter(matrix,playerRow,playerCol,initString);
matrix[playerRow, playerCol] = 'P';
}
else
{
matrix[playerRow + 1, playerCol] = 'P';
playerRow++;
}
}
else if (command == "down")
{
matrix[playerRow, playerCol] = '-';
playerRow++;
if (!CheckForPunishment(matrix, playerRow, playerCol, initString))
{
CheckForLetter(matrix, playerRow, playerCol, initString);
matrix[playerRow, playerCol] = 'P';
}
else
{
matrix[playerRow - 1, playerCol] = 'P';
playerRow--;
}
}
else if (command == "left")
{
matrix[playerRow, playerCol] = '-';
playerCol--;
if (!CheckForPunishment(matrix, playerRow, playerCol, initString))
{
CheckForLetter(matrix, playerRow, playerCol, initString);
matrix[playerRow, playerCol] = 'P';
}
else
{
matrix[playerRow, playerCol + 1] = 'P';
playerCol++;
}
}
else if (command == "right")
{
matrix[playerRow, playerCol] = '-';
playerCol++;
if (!CheckForPunishment(matrix, playerRow, playerCol, initString))
{
CheckForLetter(matrix, playerRow, playerCol, initString);
matrix[playerRow, playerCol] = 'P';
}
else
{
matrix[playerRow, playerCol - 1] = 'P';
playerCol--;
}
}
command = Console.ReadLine();
}
Console.WriteLine(initString);
PrintMatrix(matrix);
}
private static void CheckForLetter(char[,] matrix, in int playerRow, in int playerCol, StringBuilder initString)
{
if (Char.IsLetter(matrix[playerRow,playerCol]))
{
initString.Append(matrix[playerRow, playerCol]);
}
}
private static bool CheckForPunishment(char[,] matrix, int playerRow, int playerCol, StringBuilder initString)
{
try
{
var checkValue = matrix[playerRow, playerCol];
return false;
}
catch (Exception e)
{
initString.Remove(initString.Length - 1, 1);
return true;
}
}
private static void PrintMatrix(char[,] matrix)
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i, j]);
}
Console.WriteLine();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace electrika
{
public partial class Pannes : Form
{
private DataTable pannesData;
public Pannes()
{
InitializeComponent();
}
public void SqliteConnection()
{
//initialise the database
SQLiteConnection connection = new SQLiteConnection("Data Source=../../../res/database/laverie.db");
connection.Open();
Console.WriteLine(connection.State.ToString());
//
string sqlQuery = "SELECT e.designation , p.date , p.en_panne FROM " +
"equipement e , panne p WHERE e.id = p.equipement_id ORDER BY p.date DESC";
// Command
SQLiteCommand command = new SQLiteCommand(sqlQuery, connection);
SQLiteDataReader reader = null;
try
{
reader = command.ExecuteReader();
while (reader.Read())
{
string operation;
if (reader.GetString(2).Equals("oui"))
{
operation = "Signalé une panne";
}
else {
operation = "Reparation";
}
string[] oneRow = { reader.GetString(0), reader.GetString(1) , operation};
pannesData.Rows.Add(oneRow);
//pannes_grid.Rows.Add(oneRow);
};
}
catch (Exception error)
{
Console.WriteLine(error.ToString());
}
finally
{
if (reader != null) reader.Close();
connection.Close();
pannesGrid.DataSource = pannesData;
}
}
private void Pannes_Load(object sender, EventArgs e)
{
pannesData = new DataTable();
pannesData.Columns.Add("Equipement", typeof(string));
pannesData.Columns.Add("Date", typeof(string));
pannesData.Columns.Add("Operation", typeof(string));
SqliteConnection();
}
}
}
|
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using ReactMusicStore.Core.Utilities.Extensions;
namespace ReactMusicStore.Core.Utilities.ComponentModel.TypeConversion
{
[SuppressMessage("ReSharper", "CanBeReplacedWithTryCastAndCheckForNull")]
public class TimeSpanConverter : TypeConverterBase
{
public TimeSpanConverter()
: base(typeof(TimeSpan))
{
}
public override bool CanConvertFrom(Type type)
{
return type == typeof(string)
|| type == typeof(DateTime)
|| base.CanConvertFrom(type);
}
public override object ConvertFrom(CultureInfo culture, object value)
{
if (value is DateTime)
{
var time = (DateTime)value;
return new TimeSpan(time.Ticks);
}
if (value is string)
{
var str = (string)value;
TimeSpan span;
if (TimeSpan.TryParse(str, culture, out span))
{
return span;
}
long lng;
if (long.TryParse(str, NumberStyles.None, culture, out lng))
{
return new TimeSpan(lng.FromUnixTime().Ticks);
}
double dbl;
if (double.TryParse(str, NumberStyles.None, culture, out dbl))
{
return new TimeSpan(DateTime.FromOADate(dbl).Ticks);
}
}
try
{
return (TimeSpan)System.Convert.ChangeType(value, typeof(TimeSpan), culture);
}
catch { }
return base.ConvertFrom(culture, value);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CipherSuiteTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
label1.Text = Environment.OSVersion.ToString() + " | " + (Environment.Is64BitOperatingSystem ? "64-bit" : "32-Bit");
}
private void button1_Click(object sender, EventArgs e)
{
UpdateListBox();
var c1 = listBox1.Items.Contains("TLS_RSA_WITH_RC4_128_SHA");
var c2 = listBox1.Items.Contains("TLS_RSA_WITH_RC4_128_MD5");
MessageBox.Show("TLS_RSA_WITH_RC4_128_SHA " + (c1 ? "is present": "is missing") + "\n" + "TLS_RSA_WITH_RC4_128_MD5 " + (c2 ? "is present" : "is missing"));
}
private void UpdateListBox()
{
var cipherList = CipherSuiteControl.GetCipherSuiteList();
listBox1.Items.Clear();
foreach (var ciphersuite in cipherList)
listBox1.Items.Add(ciphersuite);
}
private void button2_Click(object sender, EventArgs e)
{
int v1 = CipherSuiteControl.AddCipherSuite("TLS_RSA_WITH_RC4_128_SHA");
int v2 = CipherSuiteControl.AddCipherSuite("TLS_RSA_WITH_RC4_128_MD5");
MessageBox.Show(String.Format("Add TLS_RSA_WITH_RC4_128_SHA = {0:X8}\nAdd TLS_RSA_WITH_RC4_128_MD5 = {1:X8}", v1, v2));
UpdateListBox();
}
private void button3_Click(object sender, EventArgs e)
{
int v1 = CipherSuiteControl.RemoveCipherSuite("TLS_RSA_WITH_RC4_128_SHA");
int v2 = CipherSuiteControl.RemoveCipherSuite("TLS_RSA_WITH_RC4_128_MD5");
MessageBox.Show(String.Format("Remove TLS_RSA_WITH_RC4_128_SHA = {0:X8}\nRemove TLS_RSA_WITH_RC4_128_MD5 = {1:X8}", v1, v2));
UpdateListBox();
}
}
}
|
using System.Collections.Generic;
using DataAccess.Model;
namespace DataAccess.Repository
{
public interface IShowtimeRepository
{
List<Showtime> Showtimes { get; }
void Refresh();
}
} |
using gView.Framework.Data;
using gView.Framework.Geometry;
using System.Collections;
using System.Collections.Generic;
namespace gView.Framework.Network.Build
{
public class NetworkEdge
{
private int _id;
private IPath _path;
private double _length = 0.0, _geoLength = 0.0;
private bool _oneway = false;
private int _fcId = -1;
private int _featureId = -1;
private int _fromNodeIndex = -1, _toNodeIndex = -1;
private bool _isComplex = false;
private bool _useWithComplexEdges = false;
private IEnvelope _bounds = null;
private Hashtable _weights = null;
#region Properties
public int Id
{
get { return _id; }
set { _id = value; }
}
public IPath Path
{
get { return _path; }
set { _path = value; }
}
public IPoint FromPoint
{
get
{
if (_path == null)
{
return null;
}
return _path[0];
}
}
public IPoint ToPoint
{
get
{
if (_path == null)
{
return null;
}
return _path[_path.PointCount - 1];
}
}
public double Length
{
get
{
return _length;
}
set
{
_length = value;
}
}
public double GeoLength
{
get
{
return _geoLength;
}
set
{
_geoLength = value;
}
}
public bool OneWay
{
get { return _oneway; }
set { _oneway = value; }
}
public int FeatureclassId
{
get { return _fcId; }
set { _fcId = value; }
}
public int FeatureId
{
get { return _featureId; }
set { _featureId = value; }
}
public int FromNodeIndex
{
get { return _fromNodeIndex; }
set { _fromNodeIndex = value; }
}
public int ToNodeIndex
{
get { return _toNodeIndex; }
set { _toNodeIndex = value; }
}
public bool IsComplex
{
get { return _isComplex; }
set { _isComplex = value; }
}
public bool UseWithComplexEdges
{
get { return _useWithComplexEdges; }
set
{
_useWithComplexEdges = value;
if (value == true && _path != null)
{
_bounds = _path.Envelope;
}
}
}
public Hashtable Weights
{
get { return _weights; }
set { _weights = value; }
}
public IEnvelope Bounds
{
get { return _bounds; }
}
#endregion
}
public class NetworkEdges : List<NetworkEdge>
{
private GridArray<List<NetworkEdge>> _gridArray = null;
private int _edgeIdSequence = 0;
public NetworkEdges()
{
}
public NetworkEdges(IEnvelope bounds)
{
if (bounds != null)
{
_gridArray = new GridArray<List<NetworkEdge>>(bounds,
new int[] { 200, 180, 160, 130, 100, 70, 50, 25, 18, 10, 5, 2 },
new int[] { 200, 180, 160, 130, 100, 70, 50, 25, 18, 10, 5, 2 });
}
}
public NetworkEdges(IPolyline polyline)
{
if (polyline == null || polyline.PathCount == 0)
{
return;
}
bool isComplex = polyline.PathCount > 1;
for (int i = 0; i < polyline.PathCount; i++)
{
IPath path = polyline[i];
if (path == null || path.PointCount < 2)
{
continue;
}
double geolength = path.Length;
if (geolength == 0.0)
{
continue;
}
NetworkEdge edge = new NetworkEdge();
edge.Path = path;
edge.Length = edge.GeoLength = geolength;
edge.IsComplex = isComplex;
if (edge.FromPoint == null || edge.ToPoint == null)
{
continue;
}
this.Add(edge);
}
}
new public void Add(NetworkEdge edge)
{
edge.Id = ++_edgeIdSequence;
base.Add(edge);
if (edge.UseWithComplexEdges && _gridArray != null)
{
List<NetworkEdge> indexedEdges = _gridArray[edge.Bounds];
indexedEdges.Add(edge);
}
}
public NetworkEdges SelectFrom(int fromNodeIndex)
{
NetworkEdges edges = new NetworkEdges();
foreach (NetworkEdge edge in this)
{
if (edge.FromNodeIndex == fromNodeIndex)
{
edges.Add(edge);
}
}
edges.Sort(new SortToNodeIndex());
return edges;
}
public NetworkEdges SelectTo(int toNodeIndex)
{
NetworkEdges edges = new NetworkEdges();
foreach (NetworkEdge edge in this)
{
if (edge.ToNodeIndex == toNodeIndex)
{
edges.Add(edge);
}
}
edges.Sort(new SortFromNodeIndex());
return edges;
}
public NetworkEdges Collect(IEnvelope env)
{
NetworkEdges edges = new NetworkEdges();
if (_gridArray != null)
{
foreach (List<NetworkEdge> e in _gridArray.Collect(env))
{
edges.AddRange(e);
}
}
return edges;
}
#region Comparer
private class SortToNodeIndex : IComparer<NetworkEdge>
{
#region IComparer<NetworkEdge> Member
public int Compare(NetworkEdge x, NetworkEdge y)
{
if (x.ToNodeIndex < y.ToNodeIndex)
{
return -1;
}
else if (x.ToNodeIndex > y.ToNodeIndex)
{
return 1;
}
return 0;
}
#endregion
}
private class SortFromNodeIndex : IComparer<NetworkEdge>
{
#region IComparer<NetworkEdge> Member
public int Compare(NetworkEdge x, NetworkEdge y)
{
if (x.FromNodeIndex < y.FromNodeIndex)
{
return -1;
}
else if (x.FromNodeIndex > y.FromNodeIndex)
{
return 1;
}
return 0;
}
#endregion
}
#endregion
}
}
|
namespace Ejercicio
{
public class Abuelos : Adultos
{
public override int seAsusta(Niño niño){
AdultosComunes adultoComun = new AdultosComunes();
return adultoComun.seAsusta(niño) / 2;
}
}
} |
using BulkBook.DataAccess.Data;
using BulkBook.DataAccess.Repository;
using BulkBook.DataAccess.Repository.IRepository;
using BulkyBook.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BulkBook.DataAccess
{
public class CoverTypeRepository: Repository<CoverType>,ICoverTypeRepository
{
private readonly ApplicationDbContext _db;
public CoverTypeRepository(ApplicationDbContext db):base(db)
{
_db = db;
}
public void Update(CoverType coverType)
{
var objFromDb = _db.CoverTypes.FirstOrDefault(s=>s.Id == coverType.Id);
if(objFromDb != null)
{
objFromDb.Name = coverType.Name;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
namespace Курсач.Models
{
public class Order
{
public int OrderID { get; set; }
//Водитель, обслуживающий заказ
public Driver Driver { get; set; }
public int? DriverID { get; set; }
//Дата и время поступления заказа
public DateTime SystemStartTime { get; set; }
//Дата и время прибытия таксиста
public DateTime StartTime { get; set; }
//Время окончания окончания заказа
public DateTime SystemEndTime { get; set; }
//Услуга "Детское кресло"
public bool IsChild { get; set; }
// Услуга "Оптимизировать"
public bool IsOptimised { get; set; }
// Услуга "Грузоперевозки"
public bool IsShipment { get; set; }
//Клиент
public string ApplicationUserID { get; set; }
public ApplicationUser ApplicationUser { get; set; }
//Стартовая позиция клиента
public string StartGPS { get; set; }
//Промежуточные точки
public string IntermediateGPS1 { get; set; }
public string IntermediateGPS2 { get; set; }
public string IntermediateGPS3{ get; set; }
//Пункт назначения
public string EndGPS { get; set; }
//Расстояние (для водителей)
public double Distance { get; set; }
//Стоимость заказа
public double Cost { get; set; }
//Состояние заказа
public virtual ICollection<OrderState> States { get; set; }
}
} |
// Copyright 2011-2013 Anodyne.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
using Kostassoid.Anodyne.Common.Reflection;
namespace Kostassoid.Anodyne.Wiring.Subscription
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Common.CodeContracts;
using Internal;
using Common.Extentions;
internal static class SubscriptionPerformer
{
public static Action Perform<TEvent>(SubscriptionSpecification<TEvent> specification) where TEvent : class, IEvent
{
Requires.NotNull(specification, "specification");
Requires.True(specification.IsValid, "specification", "Invalid specification");
Action unsubscribeAction = () => { };
foreach (var source in ResolveSourceTypes(specification))
{
if (specification.TargetDiscoveryFunction == null)
{
unsubscribeAction += Subscribe(source, specification.HandlerAction, specification);
}
else
{
unsubscribeAction = ResolveHandlers(source, specification)
.Aggregate(unsubscribeAction, (current, target) => current + Subscribe(source, target, specification));
}
}
return unsubscribeAction;
}
private static Action Subscribe<TEvent>(Type source, Action<TEvent> target, SubscriptionSpecification<TEvent> specification) where TEvent : class, IEvent
{
return specification
.EventAggregator
.Subscribe(
new InternalEventHandler<TEvent>(source, target, specification.EventPredicate, specification.Priority, specification.Async));
}
private static IEnumerable<Type> ResolveSourceTypes<TEvent>(SubscriptionSpecification<TEvent> specification) where TEvent : class, IEvent
{
return specification.IsPolymorphic
? FindTypes(specification.BaseEventType, specification.SourceAssemblies, specification.TypePredicate)
: specification.BaseEventType.AsEnumerable();
}
private static IEnumerable<Action<TEvent>> ResolveHandlers<TEvent>(Type eventType, SubscriptionSpecification<TEvent> specification) where TEvent : class, IEvent
{
var methods = specification.TargetType
.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(mi => IsTargetCompatibleWithSource(mi, eventType, specification.EventMatching))
.ToList();
if (methods.Count == 0) yield break;
foreach (var method in methods)
{
var handlerDelegate = CreateHandlerDelegate(method, eventType);
Action<TEvent> handler = ev =>
{
var targetObject = specification.TargetDiscoveryFunction(ev);
if (targetObject.IsNone) return;
handlerDelegate(targetObject.Value, ev);
};
yield return handler;
}
}
delegate void HandlerMethodDelegate(object instance, IEvent @event);
private static HandlerMethodDelegate CreateHandlerDelegate(MethodInfo methodInfo, Type eventType)
{
var instance = Expression.Parameter(typeof(object), "instance");
var ev = Expression.Parameter(typeof(IEvent), "event");
var lambda = Expression.Lambda<HandlerMethodDelegate>(
Expression.Call(
Expression.Convert(instance, methodInfo.DeclaringType),
methodInfo,
Expression.Convert(ev, eventType)
),
instance,
ev
);
return lambda.Compile();
}
private static bool IsTargetCompatibleWithSource(MethodInfo methodInfo, Type eventType, EventMatching eventMatching)
{
if (methodInfo.ReturnType != typeof(void)) return false;
var parameters = methodInfo.GetParameters();
if (parameters.Length != 1) return false;
switch (eventMatching)
{
case EventMatching.Strict:
return parameters[0].ParameterType == eventType;
case EventMatching.All:
return parameters[0].ParameterType.IsAssignableFrom(eventType);
default:
throw new NotSupportedException(string.Format("EventMatching.{0} is not supported", eventMatching));
}
}
private static IEnumerable<Type> FindTypes(Type baseEventType, IEnumerable<Assembly> assemblies, Predicate<Type> typePredicate)
{
return AllTypes.BasedOn(baseEventType, assemblies).Where(t => typePredicate(t));
}
}
} |
using Repo;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Web;
using System.Web.Mvc;
namespace Fina
{
public class DataCache
{
private static ObjectCache cache = MemoryCache.Default;
static IRepository repo = new Repository();
public static IEnumerable<SelectListItem> Employies
{
get
{
var data = cache.GetCacheItem("emploies") as IEnumerable<SelectListItem>;
if (data != null)
return data;
else
data = repo.GetEmployies().Select(a => new SelectListItem()
{
Text = a.Name,
Value = a.Name
});
return data;
}
set
{
var data = cache.GetCacheItem("emploies") as IEnumerable<SelectListItem>;
if (data != null)
cache.Set(repo.GetEmployies().Select(a => new SelectListItem()
{
Text = a.Name,
Value = a.Name
}) as CacheItem, new CacheItemPolicy());
value = cache as IEnumerable<SelectListItem>;
}
}
public static IEnumerable<SelectListItem> Stores
{
get
{
var data = cache.GetCacheItem("stores") as IEnumerable<SelectListItem>;
if (data != null)
return data;
else
data = repo.GetStores().Select(a => new SelectListItem()
{
Text = a.StoreName,
Value = a.StoreName
});
return data;
}
set
{
var data = cache.GetCacheItem("stores") as IEnumerable<SelectListItem>;
if (data != null)
cache.Set(repo.GetStores().Select(a => new SelectListItem()
{
Text = a.StoreName,
Value = a.StoreName
}) as CacheItem, new CacheItemPolicy());
value = cache as IEnumerable<SelectListItem>;
}
}
public static IEnumerable<SelectListItem> Salaries
{
get
{
var data = cache.GetCacheItem("salaries") as IEnumerable<SelectListItem>;
if (data != null)
return data;
else
data = repo.GetSalaries().Select(a => new SelectListItem()
{
Text = a.SalaryName,
Value = a.SalaryName
});
return data;
}
set
{
var data = cache.GetCacheItem("salaries") as IEnumerable<SelectListItem>;
if (data != null)
cache.Set(repo.GetSalaries().Select(a => new SelectListItem()
{
Text = a.SalaryName,
Value = a.SalaryName
}) as CacheItem, new CacheItemPolicy());
value = cache as IEnumerable<SelectListItem>;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace VéloMax.bdd
{
public class Programme
{
/* Attributs */
public readonly int numProg;
public string nomProg
{
get => ControlleurRequetes.ObtenirChampString("Programme", "numProg", numProg, "nomProg");
set { ControlleurRequetes.ModifierChamp("Programme", "numProg", numProg, "nomProg", value); }
}
public int cout
{
get => ControlleurRequetes.ObtenirChampInt("Programme", "numProg", numProg, "cout");
set { ControlleurRequetes.ModifierChamp("Programme", "numProg", numProg, "cout", value); }
}
public int rabais
{
get => ControlleurRequetes.ObtenirChampInt("Programme", "numProg", numProg, "rabais");
set { ControlleurRequetes.ModifierChamp("Programme", "numProg", numProg, "rabais", value); }
}
public int duree
{
get => ControlleurRequetes.ObtenirChampInt("Programme", "numProg", numProg, "duree");
set { ControlleurRequetes.ModifierChamp("Programme", "numProg", numProg, "duree", value); }
}
/* Instantiation */
public Programme(int numProg)
{
this.numProg = numProg;
}
public Programme(string nom, int cout, int rabais, int duree)
{
ControlleurRequetes.Inserer($"INSERT INTO Programme (nomProg, cout, rabais, duree) VALUES ('{nom.Replace("'", "''")}', {cout}, {rabais}, {duree})");
this.numProg = ControlleurRequetes.DernierIDUtilise();
}
/* Suppression */
public void Supprimer()
{
ControlleurRequetes.SupprimerElement("Programme", "numProg", numProg);
}
/* Liste */
public static ReadOnlyCollection<Programme> Lister()
{
List<Programme> list = new List<Programme>();
ControlleurRequetes.SelectionnePlusieurs($"SELECT numProg FROM Programme", (MySqlDataReader reader) => { list.Add(new Programme(reader.GetInt32("numProg"))); });
return new ReadOnlyCollection<Programme>(list);
}
public static ReadOnlyCollection<string> ListerString()
{
List<string> list = new List<string>();
foreach (Programme p in Lister())
{
list.Add($"{p.nomProg} ({p.rabais}%)");
}
return new ReadOnlyCollection<string>(list);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace FIVIL.Litentity
{
class SessionBase
{
internal SessionBase(LitentityUsers user)
{
User = user;
LastSeen = DateTime.Now;
Sessions = new Dictionary<string, object>();
}
internal readonly LitentityUsers User;
public string UserName => User.UserName;
public string Email => User.EmailAddress;
public string PhoneNumber => User.PhoneNumber;
public bool EmailConfirmed => User.EmailConfirmed;
public bool PhoneConfirmed => User.PhoneConfirmed;
public Dictionary<string, object> Sessions;
internal DateTime LastSeen;
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ApplicationRepository;
using System.Collections.Generic;
namespace Application.Tests
{
[TestClass]
public class ProductsBusinessLayerTests
{
[TestMethod]
public void CanGetAllProducts()
{
var mockRepository = new Moq.Mock<IProductRepository>();
mockRepository.Setup(x => x.GetAllProducts()).Returns(new List<Product>()
{
new Product() { Id = 1, Name = "Product1", Category = "Category1", StockCount = 3, Price = 1 }});
var BALProducts = new ApplicationBAL.ProductService(mockRepository.Object);
Assert.AreEqual(BALProducts.GetAllProducts().Count, 1);
}
}
}
|
using Engine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
namespace Mario__.Modules
{
class Menu : Drawable
{
static SpriteFont font;
public Menu (AssetManager manager)
{
this.manager = manager;
}
public override void destroy()
{
}
public override void draw(SpriteBatch spriteBatch)
{
}
public override void load()
{
}
public static void loadContent (ContentManager Content)
{
font = Content.Load<SpriteFont>("Font");
}
public override void update(GameTime gameTime, InputListener input)
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace MVC
{
public class PlayerController
{
private PlayerView _view;
private PlayerModel _model;
public Transform heal;
public Transform dmg;
public PlayerController(PlayerView view)
{
_view = view;
_view.OnPositionChanged = PositionChanged;
_model = new PlayerModel();
_model.OnDead = Dead;
heal = GameObject.FindObjectOfType<Heal>().transform;
dmg = GameObject.FindObjectOfType<Dmg>().transform;
}
private void PositionChanged(Vector3 pos)
{
if (Vector3.Distance(pos, heal.position) < 5)
{
_model.Health += 5;
}
else if (Vector3.Distance(pos, dmg.position) < 5)
{
_model.Health -= 5;
}
Debug.Log(_model.Health);
_model.Position = pos;
}
private void Dead()
{
Debug.Log("Öldün");
}
}
} |
using Microsoft.Xna.Framework;
using StardewValley;
using System;
using System.Collections.Generic;
using static LivelyPets.ModUtil;
namespace LivelyPets
{
class ModUtil
{
//
// ====== RNG =====
//
public static int PickRandom(int[] options)
{
Random r = new Random();
int rand = r.Next(0, options.Length - 1);
return options[rand];
}
public static bool DoRandom(double probability) {
Random r = new Random();
double rand = r.NextDouble();
return rand <= probability;
}
//
// ===== Path Finding =====
//
public static List<int> GetPath(GameLocation location, Vector2 from, Vector2 to, Character pet)
{
var padding = 1;
var gridPos = new Vector2(MathHelper.Min(from.X, to.X) - padding, MathHelper.Min(from.Y, to.Y) - padding);
var width = (int)Math.Abs(to.X - from.X)+1 + padding;
var height = (int)Math.Abs(to.Y - from.Y)+1 + padding;
bool[,] tileGrid = new bool[width, height];
for (int x = 0; x < width; x++)
for (int y = 0; y < height; y++)
tileGrid[x, y] = !pet.currentLocation.isCollidingPosition(new Rectangle((int)(gridPos.X + x)*Game1.tileSize, (int)(gridPos.Y + y)*Game1.tileSize, pet.GetBoundingBox().Width, pet.GetBoundingBox().Height), Game1.viewport, false, 0, false, pet) || (gridPos.X + x == to.X && gridPos.Y + y == to.Y);
Grid grid = new Grid(width, height, tileGrid);
Point _from = new Point((int)(from.X - gridPos.X), (int)(from.Y - gridPos.Y));
Point _to = new Point((int)(to.X - gridPos.X), (int)(to.Y - gridPos.Y));
var path = PathFinder.FindPath(grid, _from, _to);
var pathDirections = new List<int>();
// Translate the path in grid to list of directions to move through path
for (int i = 0; i < path.Count - 1; i++)
{
// Left
if (path[i + 1].X - path[i].X < 0)
pathDirections.Add(3);
// Right
else if (path[i + 1].X - path[i].X > 0)
pathDirections.Add(1);
// Up
if (path[i + 1].Y - path[i].Y < 0)
pathDirections.Add(0);
// Down
else if (path[i + 1].Y - path[i].Y > 0)
pathDirections.Add(2);
}
return pathDirections;
}
private void IsTileObstructed(GameLocation location, Vector2 tile)
{
var obj = location.getObjectAtTile((int)tile.X, (int)tile.Y);
var isObjectPassable = obj == null ? true : obj.isPassable();
}
private static bool[,] GenerateGrid(Vector2 gridPos, int width, int height, Func<Vector2, bool> f)
{
bool[,] grid = new bool[width, height];
for (int x = 0; x < width; x++)
for (int y = 0; y < height; y++)
{
grid[x, y] = f(new Vector2((gridPos.X + x), (gridPos.Y + y)));
}
return grid;
}
// Modified implementation of 2D A* PathFinding Algorithm from https://github.com/RonenNess/Unity-2d-pathfinding
/**
* Provide simple path-finding algorithm with support in penalties.
* Heavily based on code from this tutorial: https://www.youtube.com/watch?v=mZfyt03LDH4
* This is just a Unity port of the code from the tutorial + option to set penalty + nicer API.
*
* Original Code author: Sebastian Lague.
* Modifications & API by: Ronen Ness.
* Since: 2016.
*/
internal class PathFinder
{
public static List<Point> FindPath(Grid grid, Point startPos, Point targetPos)
{
// find path
List<Node> nodes_path = _ImpFindPath(grid, startPos, targetPos);
// convert to a list of points and return
List<Point> ret = new List<Point>();
if (nodes_path != null)
{
foreach (Node node in nodes_path)
{
ret.Add(new Point(node.gridX, node.gridY));
}
}
return ret;
}
// internal function to find path, don't use this one from outside
private static List<Node> _ImpFindPath(Grid grid, Point startPos, Point targetPos)
{
Node startNode = grid.nodes[startPos.X, startPos.Y];
Node targetNode = grid.nodes[targetPos.X, targetPos.Y];
List<Node> openSet = new List<Node>();
HashSet<Node> closedSet = new HashSet<Node>();
openSet.Add(startNode);
while (openSet.Count > 0)
{
Node currentNode = openSet[0];
for (int i = 1; i < openSet.Count; i++)
{
if (openSet[i].fCost < currentNode.fCost || openSet[i].fCost == currentNode.fCost && openSet[i].hCost < currentNode.hCost)
{
currentNode = openSet[i];
}
}
openSet.Remove(currentNode);
closedSet.Add(currentNode);
if (currentNode == targetNode)
{
return RetracePath(grid, startNode, targetNode);
}
foreach (Node neighbour in grid.GetNeighbours(currentNode))
{
if (!neighbour.walkable || closedSet.Contains(neighbour))
{
continue;
}
int newMovementCostToNeighbour = currentNode.gCost + GetDistance(currentNode, neighbour) * (int)(10.0f * neighbour.penalty);
if (newMovementCostToNeighbour < neighbour.gCost || !openSet.Contains(neighbour))
{
neighbour.gCost = newMovementCostToNeighbour;
neighbour.hCost = GetDistance(neighbour, targetNode);
neighbour.parent = currentNode;
if (!openSet.Contains(neighbour))
openSet.Add(neighbour);
}
}
}
return null;
}
private static List<Node> RetracePath(Grid grid, Node startNode, Node endNode)
{
List<Node> path = new List<Node>();
Node currentNode = endNode;
while (currentNode != startNode)
{
path.Add(currentNode);
currentNode = currentNode.parent;
}
path.Reverse();
return path;
}
private static int GetDistance(Node nodeA, Node nodeB)
{
int dstX = Math.Abs(nodeA.gridX - nodeB.gridX);
int dstY = Math.Abs(nodeA.gridY - nodeB.gridY);
if (dstX > dstY)
return 14 * dstY + 10 * (dstX - dstY);
return 14 * dstX + 10 * (dstY - dstX);
}
}
internal class Grid
{
public Node[,] nodes;
int gridSizeX, gridSizeY;
public Grid(int width, int height, float[,] tiles_costs)
{
gridSizeX = width;
gridSizeY = height;
nodes = new Node[width, height];
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
nodes[x, y] = new Node(tiles_costs[x, y], x, y);
}
}
}
public Grid(int width, int height, bool[,] walkable_tiles)
{
gridSizeX = width;
gridSizeY = height;
nodes = new Node[width, height];
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
nodes[x, y] = new Node(walkable_tiles[x, y] ? 1.0f : 0.0f, x, y);
}
}
}
public List<Node> GetNeighbours(Node node)
{
List<Node> neighbours = new List<Node>();
for (int x = -1; x <= 1; x++)
{
for (int y = -1; y <= 1; y++)
{
if (x == 0 && y == 0)
continue;
int checkX = node.gridX + x;
int checkY = node.gridY + y;
if (checkX >= 0 && checkX < gridSizeX && checkY >= 0 && checkY < gridSizeY)
{
neighbours.Add(nodes[checkX, checkY]);
}
}
}
return neighbours;
}
}
}
internal class Node
{
public bool walkable;
public int gridX;
public int gridY;
public float penalty;
// calculated values while finding path
public int gCost;
public int hCost;
public Node parent;
// create the node
// _price - how much does it cost to pass this tile. less is better, but 0.0f is for non-walkable.
// _gridX, _gridY - tile location in grid.
public Node(float _price, int _gridX, int _gridY)
{
walkable = _price != 0.0f;
penalty = _price;
gridX = _gridX;
gridY = _gridY;
}
public int fCost
{
get
{
return gCost + hCost;
}
}
}
}
|
using DevsoftSDK.Extensions;
using log4net;
using SAPbouiCOM.Framework;
using System;
namespace Devsoft.AddonBase
{
class Program
{
static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
log.Debug("Iniciando el AddOn");
try
{
Application oApp = null;
if (args.Length < 1) { oApp = new Application(); }
else { oApp = new Application(args[0]); }
Core.SetCompany((SAPbobsCOM.Company)Application.SBO_Application.Company.GetDICompany()); //Obtener la compañia conectada
Application.SBO_Application.StatusBar.SetText("Iniciando creación de Menus, tablas y campos de usuario", SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Warning);
Config.Core.Install(); //Creación de Menu, Tablas y Campos de Usuario
Application.SBO_Application.StatusBar.SetText("Registrando eventos", SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Warning);
RegistrarEventos(); //Registro de Eventos
//Config.Forms.RegistrarFiltros(); //Filtro de Eventos
Application.SBO_Application.StatusBar.SetText("AddOn iniciado correctamente", SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Success);
log.Debug(String.Format("Se inicio Correctamente en la compañia [{0} - {1}]", Core.GetCompany().CompanyDB, Core.GetCompany().CompanyName));
oApp.Run();
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
log.Error(ex.Message, ex);
}
}
private static void RegistrarEventos()
{
Application.SBO_Application.AppEvent += new SAPbouiCOM._IApplicationEvents_AppEventEventHandler(ApplicationEvents.AppEvent.SBO_Application_AppEvent);
//Application.SBO_Application.FormDataEvent += new SAPbouiCOM._IApplicationEvents_FormDataEventEventHandler(ApplicationEvents.FormDataEvent.SBO_Application_FormDataEvent);
//Application.SBO_Application.ItemEvent += new SAPbouiCOM._IApplicationEvents_ItemEventEventHandler(ApplicationEvents.ItemEvent.SBO_Application_ItemEvent);
//Application.SBO_Application.LayoutKeyEvent += new SAPbouiCOM._IApplicationEvents_LayoutKeyEventEventHandler(ApplicationEvents.LayoutKeyEvent.SBO_Application_LayoutKeyEvent);
Application.SBO_Application.MenuEvent += new SAPbouiCOM._IApplicationEvents_MenuEventEventHandler(ApplicationEvents.MenuEvent.SBO_Application_MenuEvent);
//Application.SBO_Application.PrintEvent += new SAPbouiCOM._IApplicationEvents_PrintEventEventHandler(ApplicationEvents.PrintEvent.SBO_Application_PrintEvent);
//Application.SBO_Application.ProgressBarEvent += new SAPbouiCOM._IApplicationEvents_ProgressBarEventEventHandler(ApplicationEvents.ProgressBarEvent.SBO_Application_ProgressBarEvent);
//Application.SBO_Application.ReportDataEvent += new SAPbouiCOM._IApplicationEvents_ReportDataEventEventHandler(ApplicationEvents.ReportDataEvent.SBO_Application_ReportDataEvent);
//Application.SBO_Application.RightClickEvent += new SAPbouiCOM._IApplicationEvents_RightClickEventEventHandler(ApplicationEvents.RightClickEvent.SBO_Application_RightClickEvent);
//Application.SBO_Application.ServerInvokeCompletedEvent += new SAPbouiCOM._IApplicationEvents_ServerInvokeCompletedEventEventHandler(ApplicationEvents.ServerInvokeCompletedEvent.SBO_Application_ServerInvokeCompletedEvent);
//Application.SBO_Application.StatusBarEvent += new SAPbouiCOM._IApplicationEvents_StatusBarEventEventHandler(ApplicationEvents.StatusBarEvent.SBO_Application_StatusBarEvent);
//Application.SBO_Application.UDOEvent += new SAPbouiCOM._IApplicationEvents_UDOEventEventHandler(ApplicationEvents.UDOEvent.SBO_Application_UDOEvent);
//Application.SBO_Application.WidgetEvent += new SAPbouiCOM._IApplicationEvents_WidgetEventEventHandler(ApplicationEvents.WidgetEvent.SBO_Application_WidgetEvent);
}
}
}
|
namespace Batcher.Tests.TestsData
{
using System.Collections;
using System.Collections.Generic;
internal class CheckAndFillBatchIndexTestData : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
yield return new object[]
{
2,
0,
new List<int> { 1, 2, 3, 4, 5 },
new List<int> { 1, 2, 3 },
5,
new IEnumerable<int>[]
{
new List<int> { 1, 2, 3 },
new List<int> { 4, 5, 6, 7 }
},
0
};
yield return new object[]
{
0,
0,
new List<int> { 1, 2, 3 },
new List<int> { 1, 2, 3 },
5,
new IEnumerable<int>[]
{
new List<int> { 1, 2, 3 }
},
0
};
yield return new object[]
{
0,
0,
new List<int> { 1, 2, 3 },
new List<int> { 1, 2, 3 },
5,
new IEnumerable<int>[]
{
new List<int> { 1, 2, 3 }
},
0
};
}
IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();
}
} |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
namespace Crystal.Plot2D.DataSources
{
/// <summary>
/// Empty data source - for testing purposes, represents data source with 0 points inside.
/// </summary>
public class EmptyDataSource : IPointDataSource
{
#region IPointDataSource Members
public IPointEnumerator GetEnumerator(DependencyObject context) => new EmptyPointEnumerator();
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
private void RaiseDataChanged() => DataChanged?.Invoke(this, EventArgs.Empty);
public event EventHandler DataChanged;
#endregion
private sealed class EmptyPointEnumerator : IPointEnumerator
{
public bool MoveNext() => false;
public void GetCurrent(ref Point p)
{
// nothing to do
}
public void ApplyMappings(DependencyObject target)
{
// nothing to do
}
public void Dispose() { }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace MoneyExchangerApp.Domain.Models
{
public class CurrencyRate
{
public string Base { get; set; }
public DateTime Date { get; set; }
public Dictionary<string, double> Rates { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_IssPrefeitura.Dominio.Entities
{
public class Configuracoes
{
public int ConfiguracoesId { get; set; }
public string Titular { get; set; }
public string Substituto { get; set; }
public string RazaoSocial { get; set; }
public string Cnpj { get; set; }
public int ProximoLivro { get; set; }
public int ProximaFolha { get; set; }
public string TipoCalculoIss { get; set; }
public float Valorliquota { get; set; }
public int TotalFolhasPorLivro { get; set; }
}
}
|
namespace Inventory.Models.Enums
{
public enum DishUnitEnum
{
/// <summary>
/// Грамм
/// </summary>
Gram = 1,
/// <summary>
/// Штука
/// </summary>
Piece = 2,
/// <summary>
/// Миллилитры
/// </summary>
Milliliters = 3
}
}
|
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;
using System.Windows.Data;
using TraceWizard.Entities;
namespace TraceWizard.TwApp {
public partial class TimeFramePanel : UserControl {
public Events Events;
public TimeFramePanel() {
InitializeComponent();
}
public void Initialize() {
SetSettingTopAlignment();
SetSettingShowView();
SetSettingShowTrace();
SetBindings();
Properties.Settings.Default.PropertyChanged += new PropertyChangedEventHandler(Default_PropertyChanged);
}
public void ClearBindings() {
BindingOperations.ClearBinding(textTraceStartTime, TextBlock.TextProperty);
BindingOperations.ClearBinding(textTraceStartDate, TextBlock.TextProperty);
BindingOperations.ClearBinding(textTraceDuration, TextBlock.TextProperty);
BindingOperations.ClearBinding(textTraceDuration, TextBlock.ToolTipProperty);
BindingOperations.ClearBinding(textTraceEndTime, TextBlock.TextProperty);
BindingOperations.ClearBinding(textTraceEndDate, TextBlock.TextProperty);
BindingOperations.ClearBinding(textViewStartTime, TextBlock.TextProperty);
BindingOperations.ClearBinding(textViewStartDate, TextBlock.TextProperty);
BindingOperations.ClearBinding(textViewDuration, TextBlock.TextProperty);
BindingOperations.ClearBinding(textViewEndTime, TextBlock.TextProperty);
BindingOperations.ClearBinding(textViewEndDate, TextBlock.TextProperty);
}
public void SetBindings() {
Binding binding = new Binding("StartTime");
binding.Source = Events;
binding.Converter = new TwHelper.LongTimeConverter();
BindingOperations.SetBinding(textTraceStartTime, TextBlock.TextProperty, binding);
binding = new Binding("StartTime");
binding.Source = Events;
binding.Converter = new TwHelper.ShortDateConverter();
BindingOperations.SetBinding(textTraceStartDate, TextBlock.TextProperty, binding);
binding = new Binding("Duration");
binding.Source = Events;
binding.Converter = new TwHelper.DurationConverter();
BindingOperations.SetBinding(textTraceDuration, TextBlock.TextProperty, binding);
binding = new Binding("Duration");
binding.Source = Events;
binding.Converter = new TwHelper.FriendlierDurationConverter();
BindingOperations.SetBinding(textTraceDuration, TextBlock.ToolTipProperty, binding);
binding = new Binding("EndTime");
binding.Source = Events;
binding.Converter = new TwHelper.LongTimeConverter();
BindingOperations.SetBinding(textTraceEndTime, TextBlock.TextProperty, binding);
binding = new Binding("EndTime");
binding.Source = Events;
binding.Converter = new TwHelper.ShortDateConverter();
BindingOperations.SetBinding(textTraceEndDate, TextBlock.TextProperty, binding);
}
public void Default_PropertyChanged(object sender, PropertyChangedEventArgs e) {
switch (e.PropertyName) {
case "ShowTimeFrameAboveGraph":
SetTopAlignment();
SetSettingTopAlignment();
break;
case "ShowViewTimeFrame":
//SetShowView();
//SetSettingShowView();
break;
case "ShowTraceTimeFrame":
//SetShowTrace();
//SetSettingShowTrace();
break;
}
}
public static readonly DependencyProperty TopAlignmentProperty =
DependencyProperty.Register("TopAlignment", typeof(bool),
typeof(TimeFramePanel), new UIPropertyMetadata(true));
public bool TopAlignment {
get { return (bool)GetValue(TopAlignmentProperty); }
set {
SetValue(TopAlignmentProperty, value);
SetTopAlignment();
}
}
void SetTopAlignment() {
DockPanel.SetDock((DockPanel)this.Parent, TopAlignment ? Dock.Top : Dock.Bottom);
foreach(FrameworkElement item in Grid.Children) {
if (item.Name.ToLower().Contains("view"))
Grid.SetRow(item, TopAlignment ? 1 : 0);
else if (item.Name.ToLower().Contains("trace"))
Grid.SetRow(item, TopAlignment ? 0 : 1);
}
}
void SetSettingTopAlignment() {
TopAlignment = Properties.Settings.Default.ShowTimeFrameAboveGraph;
}
public static readonly DependencyProperty ShowViewProperty =
DependencyProperty.Register("ShowView", typeof(bool),
typeof(TimeFramePanel), new UIPropertyMetadata(true));
public bool ShowView {
get { return (bool)GetValue(ShowViewProperty); }
set {
SetValue(ShowViewProperty, value);
SetShowView();
}
}
void SetShowView() {
foreach(FrameworkElement item in Grid.Children) {
if (item.Name.ToLower().Contains("view"))
item.Visibility = ShowView ? Visibility.Visible : Visibility.Collapsed;
}
}
void SetSettingShowView() {
ShowView = Properties.Settings.Default.ShowViewTimeFrame;
}
public static readonly DependencyProperty ShowTraceProperty =
DependencyProperty.Register("ShowTrace", typeof(bool),
typeof(TimeFramePanel), new UIPropertyMetadata(true));
public bool ShowTrace {
get { return (bool)GetValue(ShowTraceProperty); }
set {
SetValue(ShowTraceProperty, value);
SetShowTrace();
}
}
void SetShowTrace() {
foreach (FrameworkElement item in Grid.Children) {
if (item.Name.ToLower().Contains("trace"))
item.Visibility = ShowTrace ? Visibility.Visible : Visibility.Collapsed;
}
}
void SetSettingShowTrace() {
ShowTrace = Properties.Settings.Default.ShowTraceTimeFrame;
}
}
}
|
using System;
using Microsoft.Xna.Framework;
namespace VoxelSpace {
// returns orientations consistent with CubicGravityField
public class CubicVoxelOrientationField : IVoxelOrientationField {
public Orientation GetVoxelOrientation(Coords c) {
// we have to base things off the center of the voxel
// this calculation doesnt care about the actual positions, just their relation to the origin
// so scaling doesnt change the result. by doubling and adding one, we avoid floating point operations
// which are costly at scale. also its clever and i like being clever
c = (c * 2) + Coords.ONE;
var o = Orientation.Zero;
var ac = c.Abs();
var max = ac.Max();
if (max == ac.X) o |= (c.X >= 0 ? Orientation.Xp : Orientation.Xn);
if (max == ac.Y) o |= (c.Y >= 0 ? Orientation.Yp : Orientation.Yn);
if (max == ac.Z) o |= (c.Z >= 0 ? Orientation.Zp : Orientation.Zn);
return o;
}
}
} |
using DIPS.Samsnakk.Server.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DIPS.Samsnakk.Server.Interfaces
{
public interface IUsers
{
public void AddUser(User user);
public List<User> GetUsers();
public User GetCurrentUser(string id);
public User GetUserByUsername(string username);
}
}
|
using System.Collections;
using UnityEngine;
public class EnemyShootingController : MonoBehaviour
{
#region Variables
#region Components
private Animator m_animator;
private EnemyMovement m_movement;
#endregion
#region Public Variables
#endregion
#region Private Variables
#region Serializable Variables
[SerializeField] private uint m_damage;
[SerializeField] private float m_projectileSpeed;
[SerializeField] private float m_projectileAddSpeedOverTime;
[SerializeField] private LayerMask m_cantSeeBehind;
[SerializeField] private float m_attackSpeed;
[SerializeField] private GameObject m_projectilePrefab;
#endregion
#region Non-Serializable Variables
private float m_shootTime = 0;
private Transform m_playerTransform;
#endregion
#endregion
#endregion
#region BuiltIn Methods
void Start()
{
m_movement = GetComponent<EnemyMovement>();
m_animator = GetComponent<Animator>();
m_shootTime = Random.Range(0, m_attackSpeed*3);
m_playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
}
void FixedUpdate()
{
if (m_shootTime > 0)
{
m_shootTime -= Time.deltaTime;
}
if (m_movement.m_isMoving)
{
if (m_playerTransform)
{
if (CheckForPlayerVisibility() && m_shootTime <= 0)
{
StartAttackAnimation();
}
}
}
}
#endregion
#region Custom Methods
private bool CheckForPlayerVisibility()
{
return !(Physics2D.Linecast(transform.position, m_playerTransform.position, m_cantSeeBehind));
}
private void StartAttackAnimation()
{
m_animator.SetTrigger("Shoot");
m_movement.m_isMoving = false;
StartCoroutine(ResetMovement(m_animator.GetCurrentAnimatorClipInfo(0)[0].clip.length));
}
public void ShootProjectile()
{
if (m_playerTransform)
{
Vector3 dir = (m_playerTransform.position - transform.position).normalized;
GameObject projectile = Instantiate(m_projectilePrefab, transform.position + dir * 0.2f, Quaternion.identity);
projectile.GetComponent<EnemyProjectileController>().Init(m_damage, dir, m_projectileSpeed, m_projectileAddSpeedOverTime);
}
}
private IEnumerator ResetMovement(float time)
{
yield return new WaitForSeconds(time);
m_shootTime = m_attackSpeed;
m_movement.m_isMoving = true;
}
#endregion
}
|
using System;
using System.Linq;
using System.Text;
namespace PangyaFileCore
{
public enum PriceTypeEnum
{
Pang = 0x22,
Pang_Purchase_Only_WithIcon = 0x60,
Cookie = 0x21,
}
public class Part : PangyaFile<Part>
{
public bool Enabled { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public int Price { get; set; }
public int PriceType { get; set; }
public int Power { get; set; }
public int Control { get; set; }
public int Accuracy { get; set; }
public int Spin { get; set; }
public int Curve { get; set; }
public int PowerSlot { get; set; }
public int ControlSlot { get; set; }
public int AccuracySlot { get; set; }
public int SpinSlot { get; set; }
public int CurveSlot { get; set; }
protected override int ItemHeaderLength
{
get
{
return 544;
}
}
protected override Part Get(byte[] data)
{
return new Part()
{
Enabled = Convert.ToBoolean(data[0]), //Posição 0
Id = data.ToIntenger(startIndex: 4, count: 4), //Posição 4
Name = Encoding.ASCII.GetString(data.Skip(8).TakeWhile(x => x != 0x00).ToArray()),
Price = data.ToIntenger(startIndex: 92, count: 2), //Posição 92
PriceType = Convert.ToInt32(data[104]), //Posição 104
//Attributes
Power = Convert.ToInt32(data[460]), //Posição 460
Control = Convert.ToInt32(data[462]),
Accuracy = Convert.ToInt32(data[464]),
Spin = Convert.ToInt32(data[466]),
Curve = Convert.ToInt32(data[468]),
//Slots
PowerSlot = Convert.ToInt32(data[470]),
ControlSlot = Convert.ToInt32(data[472]),
AccuracySlot = Convert.ToInt32(data[474]),
SpinSlot = Convert.ToInt32(data[476]),
CurveSlot = Convert.ToInt32(data[478])
};
}
}
}
|
using FtpProxy.Core.Commands;
using FtpProxy.Entity;
namespace FtpProxy.Core.Factory
{
public interface IRemoteCommandFactory : ICommandFactory
{
}
} |
using ApiSGCOlimpiada.Models;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
namespace ApiSGCOlimpiada.Data.ResponsavelDAO
{
public class ResponsavelDAO : IResponsavelDAO
{
private readonly string _conn;
public ResponsavelDAO(IConfiguration config)
{
_conn = config.GetConnectionString("conn");
}
MySqlConnection conn;
MySqlDataAdapter adapter;
MySqlCommand cmd;
DataTable dt;
public bool Add(Responsavel responsavel)
{
try
{
conn = new MySqlConnection(_conn);
conn.Open();
cmd = new MySqlCommand($"Insert into Responsaveis values(null, '{responsavel.Nome}', '{responsavel.Email}', '{responsavel.Cargo}', {responsavel.EscolaId})", conn);
int rows = cmd.ExecuteNonQuery();
if (rows != -1)
{
return true;
}
return false;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
finally
{
conn.Close();
}
}
public Responsavel Find(long id)
{
try
{
conn = new MySqlConnection(_conn);
conn.Open();
cmd = new MySqlCommand($"select e.*, r.Id as ResponsavelId, r.Nome as responsavelNome, r.email ,r.Cargo, r.EscolasId From Escolas e Inner join Responsaveis r on r.EscolasId = e.id where r.Id = {id}", conn);
adapter = new MySqlDataAdapter(cmd);
dt = new DataTable();
adapter.Fill(dt);
Responsavel responsavel = null;
foreach (DataRow item in dt.Rows)
{
responsavel = new Responsavel();
responsavel.Id = Convert.ToInt64(item["ResponsavelId"]);
responsavel.Nome = item["responsavelNome"].ToString();
responsavel.Email = item["email"].ToString();
responsavel.Cargo = item["Cargo"].ToString();
responsavel.Escola = new Escola();
responsavel.EscolaId = Convert.ToInt64(item["EscolasId"]);
responsavel.Escola.Id = Convert.ToInt64(item["Id"]);
responsavel.Escola.Nome = item["Nome"].ToString();
responsavel.Escola.Cep = item["Cep"].ToString();
responsavel.Escola.Logradouro = item["Logradouro"].ToString();
responsavel.Escola.Bairro = item["Bairro"].ToString();
responsavel.Escola.Numero = item["Numero"].ToString();
responsavel.Escola.Cidade = item["Cidade"].ToString();
responsavel.Escola.Estado = item["Estado"].ToString();
}
return responsavel;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
finally
{
conn.Close();
}
}
public List<Responsavel> FindBySearch(string search)
{
try
{
List<Responsavel> responsaveis = new List<Responsavel>();
conn = new MySqlConnection(_conn);
conn.Open();
cmd = new MySqlCommand($"select e.*, r.Id as ResponsavelId, r.Nome as responsavelNome, r.email ,r.Cargo, r.EscolasId From Escolas e Inner join Responsaveis r on r.EscolasId = e.id where r.Nome LIKE '%{search}%' or e.Nome LIKE '%{search}%'", conn);
adapter = new MySqlDataAdapter(cmd);
dt = new DataTable();
adapter.Fill(dt);
Responsavel responsavel = null;
foreach (DataRow item in dt.Rows)
{
responsavel = new Responsavel();
responsavel.Id = Convert.ToInt64(item["ResponsavelId"]);
responsavel.Nome = item["responsavelNome"].ToString();
responsavel.Cargo = item["Cargo"].ToString();
responsavel.Email = item["email"].ToString();
responsavel.Escola = new Escola();
responsavel.EscolaId = Convert.ToInt64(item["EscolasId"]);
responsavel.Escola.Id = Convert.ToInt64(item["Id"]);
responsavel.Escola.Nome = item["Nome"].ToString();
responsavel.Escola.Cep = item["Cep"].ToString();
responsavel.Escola.Logradouro = item["Logradouro"].ToString();
responsavel.Escola.Bairro = item["Bairro"].ToString();
responsavel.Escola.Numero = item["Numero"].ToString();
responsavel.Escola.Cidade = item["Cidade"].ToString();
responsavel.Escola.Estado = item["Estado"].ToString();
responsaveis.Add(responsavel);
}
return responsaveis;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
finally
{
conn.Close();
}
}
public IEnumerable<Responsavel> GetAll()
{
try
{
List<Responsavel> responsaveis = new List<Responsavel>();
conn = new MySqlConnection(_conn);
conn.Open();
cmd = new MySqlCommand($"select e.*, r.Id as ResponsavelId, r.Nome as responsavelNome, r.email , r.Cargo, r.EscolasId From Escolas e Inner join Responsaveis r on r.EscolasId = e.id", conn);
adapter = new MySqlDataAdapter(cmd);
dt = new DataTable();
adapter.Fill(dt);
foreach (DataRow item in dt.Rows)
{
Responsavel responsavel = new Responsavel();
responsavel.Id = Convert.ToInt64(item["ResponsavelId"]);
responsavel.Nome = item["responsavelNome"].ToString();
responsavel.Email = item["Email"].ToString();
responsavel.Cargo = item["Cargo"].ToString();
responsavel.Escola = new Escola();
responsavel.EscolaId = Convert.ToInt64(item["EscolasId"]);
responsavel.Escola.Id = Convert.ToInt64(item["Id"]);
responsavel.Escola.Nome = item["Nome"].ToString();
responsavel.Escola.Cep = item["Cep"].ToString();
responsavel.Escola.Logradouro = item["Logradouro"].ToString();
responsavel.Escola.Bairro = item["Bairro"].ToString();
responsavel.Escola.Numero = item["Numero"].ToString();
responsavel.Escola.Cidade = item["Cidade"].ToString();
responsavel.Escola.Estado = item["Estado"].ToString();
responsaveis.Add(responsavel);
}
return responsaveis;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
finally
{
conn.Close();
}
}
public IEnumerable<Responsavel> GetBySolicitacao(long idSoliciatacao)
{
try
{
List<Responsavel> responsaveis = new List<Responsavel>();
conn = new MySqlConnection(_conn);
conn.Open();
cmd = new MySqlCommand($"select r.Id, r.nome, r.email, r.cargo, r.escolasId from responsaveis as r inner join escolas as e on r.EscolasId = e.id inner join solicitacaoCompras as sc on sc.escolasid = e.id where sc.id = {idSoliciatacao}; ", conn);
adapter = new MySqlDataAdapter(cmd);
dt = new DataTable();
adapter.Fill(dt);
foreach (DataRow item in dt.Rows)
{
Responsavel responsavel = new Responsavel();
responsavel.Id = Convert.ToInt64(item["id"]);
responsavel.Nome = item["nome"].ToString();
responsavel.Email = item["Email"].ToString();
responsavel.Cargo = item["Cargo"].ToString();
responsavel.EscolaId = Convert.ToInt64(item["escolasId"]);
responsaveis.Add(responsavel);
}
return responsaveis;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
finally
{
conn.Close();
}
}
public bool Remove(long id)
{
try
{
conn = new MySqlConnection(_conn);
conn.Open();
cmd = new MySqlCommand($"Delete from Responsaveis where id = {id}", conn);
int rows = cmd.ExecuteNonQuery();
if (rows != -1)
{
return true;
}
return false;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
finally
{
conn.Close();
}
}
public bool Update(Responsavel responsavel, long id)
{
try
{
conn = new MySqlConnection(_conn);
conn.Open();
cmd = new MySqlCommand($"Update Responsaveis set Nome = '{responsavel.Nome}', Email = '{responsavel.Email}', Cargo = '{responsavel.Cargo}', " +
$"EscolasId = {responsavel.EscolaId} where id = {id}", conn);
int rows = cmd.ExecuteNonQuery();
if (rows != -1)
{
return true;
}
return false;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
finally
{
conn.Close();
}
}
}
}
|
using CoreTest1.Data;
using CoreTest1.Models;
using CoreTest1.Models.MyViewModel;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CoreTest1.Controllers
{
public class StocksController : Controller
{
private readonly RocketContext _context;
public StocksController(RocketContext context)
{
_context = context;
}
// GET: Stocks
public async Task<IActionResult> Index()
{
return View(await _context.Stocks.ToListAsync());
}
// GET: Stocks/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var stock = await _context.Stocks
.Include(s => s.Positions)
.ThenInclude(position => position.Employee)
.AsNoTracking()
.FirstOrDefaultAsync(m => m.ID == id);
if (stock == null)
{
return NotFound();
}
return View(stock);
}
// GET: Stocks/Create
public IActionResult Create()
{
return View();
}
// POST: Stocks/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,Address")] Stock stock)
{
if (ModelState.IsValid)
{
_context.Add(stock);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
PopulatePositionsData(stock);
return View(stock);
}
// GET: Stocks/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var stock = await _context.Stocks
.Include(s=>s.Positions)
.ThenInclude(p => p.Employee)
.AsNoTracking()
.FirstOrDefaultAsync( s => s.ID == id);
if (stock == null)
{
return NotFound();
}
PopulatePositionsData(stock);
return View(stock);
}
// POST: Stocks/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int? id, string[] selectedEmployees)
{
if (id == null)
{
return NotFound();
}
var stockToUpdate = await _context.Stocks
.Include(i => i.Positions)
.ThenInclude(i => i.Employee)
.FirstOrDefaultAsync(m => m.ID == id);
if (await TryUpdateModelAsync<Stock>(
stockToUpdate,
"",
i => i.Address))
{
UpdateStockEmployees(selectedEmployees, stockToUpdate);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException /* ex */)
{
//Log the error (uncomment ex variable name and write a log.)
ModelState.AddModelError("", "Unable to save changes. " +
"Try again, and if the problem persists, " +
"see your system administrator.");
}
return RedirectToAction(nameof(Index));
}
UpdateStockEmployees(selectedEmployees, stockToUpdate);
PopulatePositionsData(stockToUpdate);
return View(stockToUpdate);
}
private void UpdateStockEmployees(string[] selectedEmployees, Stock stockToUpdate)
{
if (selectedEmployees == null)
{
stockToUpdate.Positions = new List<Position>();
return;
}
var selectedEmployeesHS = new HashSet<string>(selectedEmployees);
var StockEmployees = new HashSet<int>
(stockToUpdate.Positions.Select(c => c.Employee.ID));
foreach (var Employee in _context.Employees)
{
if (selectedEmployeesHS.Contains(Employee.ID.ToString()))
{
if (!StockEmployees.Contains(Employee.ID))
{
stockToUpdate.Positions.Add(new Position { StockID = stockToUpdate.ID, EmployeeID = Employee.ID });
}
}
else
{
if (StockEmployees.Contains(Employee.ID))
{
Position EmployeesToRemove = stockToUpdate.Positions.FirstOrDefault(i => i.EmployeeID == Employee.ID);
_context.Remove(EmployeesToRemove);
}
}
}
}
private void PopulatePositionsData(Stock Stock)
{
var allEmployees = _context.Employees;
var StockEmployees = new HashSet<int>(Stock.Positions.Select(c => c.EmployeeID));
var viewModel = new List<PositionData>();
foreach (var Employee in allEmployees)
{
viewModel.Add(new PositionData
{
EmployeeID = Employee.ID,
Name = Employee.FirstName + " " + Employee.Surname,
Assigned = StockEmployees.Contains(Employee.ID)
});
}
ViewData["Employees"] = viewModel;
}
// GET: Stocks/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var stock = await _context.Stocks
.Include(s => s.Positions)
.ThenInclude(p => p.Employee)
.FirstOrDefaultAsync(m => m.ID == id);
if (stock == null)
{
return NotFound();
}
return View(stock);
}
// POST: Stocks/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var stock = await _context.Stocks.FindAsync(id);
if(stock.Positions != null && stock.Positions.Any())
{
foreach(var a in stock.Positions)
{
_context.Positions.Remove(a);
}
}
_context.Stocks.Remove(stock);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool StockExists(int id)
{
return _context.Stocks.Any(e => e.ID == id);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using DatabaseHelper;
using System.Data;
namespace BusinessObjects
{
public class PostList : Event
{
#region Private Members
private BindingList<Post> _List;
private String _path = String.Empty;
#endregion
#region Public Properties
public BindingList<Post> List
{
get { return _List; }
}
public String Path
{
get { return _path; }
set { _path = value; }
}
#endregion
#region Private Methods
#endregion
#region Public Methods
public PostList GetByUserId(Guid userId)
{
Database database = new Database("LooksGoodDatabase");
DataTable dt = new DataTable();
database.Command.CommandType = CommandType.StoredProcedure;
database.Command.CommandText = "tblPostGetByUserId";
database.Command.Parameters.Add("@UserId", SqlDbType.UniqueIdentifier).Value = userId;
dt = database.ExecuteQuery();
foreach (DataRow dr in dt.Rows)
{
Post post = new Post();
post.Initialize(dr);
post.InitializeBusinessData(dr);
_List.Add(post);
}
return this;
}
public PostList GetVotesByPostId(Guid id)
{
Database database = new Database("LooksGoodDatabase");
DataTable dt = new DataTable();
database.Command.CommandType = CommandType.StoredProcedure;
database.Command.CommandText = "tblPostGetVotesByPostId";
database.Command.Parameters.Add("@Id", SqlDbType.UniqueIdentifier).Value = id;
dt = database.ExecuteQuery();
foreach (DataRow dr in dt.Rows)
{
Post post = new Post();
post.Initialize(dr);
post.InitializeBusinessData(dr);
_List.Add(post);
}
return this;
}
public PostList GetMostRecent()
{
Database database = new Database("LooksGoodDatabase");
database.Command.Parameters.Clear();
database.Command.CommandType = CommandType.StoredProcedure;
database.Command.CommandText = "tblPostGetMostRecent";
DataTable dt = database.ExecuteQuery();
foreach (DataRow dr in dt.Rows)
{
Post post = new Post();
post.FilePath = _path;
post.Initialize(dr);
post.InitializeBusinessData(dr);
post.IsNew = false;
post.IsDirty = false;
post.Savable += Post_Savable;
_List.Add(post);
}
return this;
}
public PostList Save()
{
foreach (Post post in _List)
{
if (post.IsSavable() == true)
{
post.Save();
}
}
return this;
}
public Boolean IsSavable()
{
Boolean result = false;
foreach (Post post in _List)
{
if (post.IsSavable() == true)
{
result = true;
break;
}
}
return result;
}
public PostList GetAll()
{
Database database = new Database("LooksGoodDatabase");
database.Command.Parameters.Clear();
database.Command.CommandType = CommandType.StoredProcedure;
database.Command.CommandText = "tblPostGetAll";
DataTable dt = database.ExecuteQuery();
foreach (DataRow dr in dt.Rows)
{
Post post = new Post();
post.Initialize(dr);
post.InitializeBusinessData(dr);
post.IsNew = false;
post.IsDirty = false;
post.Savable += Post_Savable;
_List.Add(post);
}
return this;
}
public PostList GetById(Guid id)
{
Database database = new Database("LooksGoodDatabase");
DataTable dt = new DataTable();
database.Command.CommandType = System.Data.CommandType.StoredProcedure;
database.Command.CommandText = "tblPostGetById";
database.Command.Parameters.Add("@Id", SqlDbType.UniqueIdentifier).Value = id;
dt = database.ExecuteQuery();
if (dt != null && dt.Rows.Count == 1)
{
DataRow dr = dt.Rows[0];
}
return this;
}
#endregion
#region Public Events
private void Post_Savable(SavableEventArgs e)
{
RaiseEvent(e);
}
#endregion
#region Public Event Handlers
private void _List_AddingNew(object sender, AddingNewEventArgs e)
{
e.NewObject = new Post();
Post post = (Post)e.NewObject;
post.Savable += Post_Savable;
}
#endregion
#region Construction
public PostList()
{
_List = new BindingList<Post>();
_List.AddingNew += _List_AddingNew;
}
#endregion
}
} |
namespace Nca.Valdr.Tests
{
using Console;
using NUnit.Framework;
using System.IO;
[TestFixture]
public class CliRunnerTests
{
[Test]
public void CliRunnerBuildJavaScriptTest()
{
// Arrange
var runner = new CliRunner(new CliOptions(new[] { "-i:x", "-o:y" }));
// Act
var result = runner.BuildJavaScript("app", string.Empty);
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result, Is.Not.Empty);
}
[Test]
public void CliRunnerBuildCompleteJavaScriptTest()
{
// Arrange
var parser = new AssemblyParser("Nca.Valdr.Tests.dll", "Nca.Valdr.Tests.DTOs", "en");
var metadata = parser.Parse();
var runner = new CliRunner(new CliOptions(new[] { "-i:x", "-o:y" }));
// Act
var result = runner.BuildJavaScript("app", metadata.ToString());
// Assert
var appValdrJsFile = File.OpenText("../../app/app.valdr.js");
var fileContent = appValdrJsFile.ReadToEnd();
Assert.That(result.Replace("\r", string.Empty), Is.EqualTo(fileContent.Replace("\r", string.Empty)));
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PadBehaviour : MonoBehaviour
{
#region Variables
[Header("Movement Limit")]
[SerializeField] private float minX;
[SerializeField] private float maxX;
private Transform ballTransform;
#endregion
#region Unity lifecycle
private void Start()
{
ballTransform = FindObjectOfType<BallBehaviour>().transform;
}
private void Update()
{
Vector3 padPosition = Vector3.zero;
Vector3 positionInPixels = Input.mousePosition;
Vector3 positionInWorld = Camera.main.ScreenToWorldPoint(positionInPixels);
padPosition = positionInWorld;
padPosition.y = transform.position.y;
padPosition.z = transform.position.z;
padPosition.x = Mathf.Clamp(padPosition.x, minX, maxX);
transform.position = padPosition;
}
#endregion
}
|
namespace Sentry.Tests.Extensibility;
public class DisabledHubTests
{
[Fact]
public void IsEnabled_False() => Assert.False(DisabledHub.Instance.IsEnabled);
[Fact]
public void LastEventId_EmptyGuid() => Assert.Equal(default, DisabledHub.Instance.LastEventId);
[Fact]
public void ConfigureScopeAsync_ReturnsCompletedTask()
=> Assert.Equal(Task.CompletedTask, DisabledHub.Instance.ConfigureScopeAsync(null!));
[Fact]
public void PushScope_ReturnsSelf()
=> Assert.Same(DisabledHub.Instance, DisabledHub.Instance.PushScope());
[Fact]
public void PushScope_WithState_ReturnsSelf()
=> Assert.Same(DisabledHub.Instance, DisabledHub.Instance.PushScope(null as object));
[Fact]
public void CaptureEvent_EmptyGuid()
=> Assert.Equal(Guid.Empty, (Guid)DisabledHub.Instance.CaptureEvent(null!));
[Fact]
public void ConfigureScope_NoOp() => DisabledHub.Instance.ConfigureScope(null!);
[Fact]
public void WithScope_NoOp() => DisabledHub.Instance.WithScope(null!);
[Fact]
public void WithScopeT_NoOp() => DisabledHub.Instance.WithScope<bool>(null!);
[Fact]
public Task WithScopeAsync_NoOp() => DisabledHub.Instance.WithScopeAsync(null!);
[Fact]
public Task WithScopeAsyncT_NoOp() => DisabledHub.Instance.WithScopeAsync<bool>(null!);
[Fact]
public void BindClient_NoOp() => DisabledHub.Instance.BindClient(null!);
[Fact]
public void Dispose_NoOp() => DisabledHub.Instance.Dispose();
[Fact]
public async Task FlushAsync_NoOp() => await DisabledHub.Instance.FlushAsync();
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace ContestsPortal.Domain.Models
{
public partial class UserProfile: IDisposable
{
public void Dispose()
{
}
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<UserProfile, int> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// only 5 default claims are stored.
return userIdentity;
}
}
}
|
using UnityEngine;
using System.Collections;
public class PlatformOperator : MonoBehaviour
{
[Header("Main Properties")]
public GameObject mainCamera;
private Camera mainCamera_cam;
private Collider2D _collider2D;
private bool Launch;
[Header("Ball Properties")]
public float ballForce;
public GameObject ballPrefab;
public GameObject newBall;
//Position and Lerp properties
[Header("Movement Properties")]
public float speed;
private Vector2 rays;
private float time;
void Awake()
{
if (mainCamera == null)
{
Debug.LogError("A camera needs to be assaigned in the inspector of 'PlatformOperator.cs'.");
}
_collider2D = GetComponent<Collider2D>();
mainCamera_cam = mainCamera.GetComponent<Camera>();
SpawnBall();
}
void Update()
{
#if UNITY_EDITOR
EditorUpdate();
#elif UNITY_ANDROID
AndroidUpdate();
#endif
}
void EditorUpdate()
{
if (Input.GetMouseButton(0))
rays = mainCamera_cam.ScreenToWorldPoint(Input.mousePosition);
if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))
{
rays = new Vector2(0, 0);
rays += (Vector2)transform.position + new Vector2(-5, 0);
}
if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D))
{
rays = new Vector2(0, 0);
rays += (Vector2)transform.position + new Vector2(5, 0);
}
if (newBall)
{
Rigidbody2D ballBody = newBall.GetComponent<Rigidbody2D>();
ballBody.position = transform.position + new Vector3(0, 3.5f);
if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow))
{
ballBody.AddForce(new Vector2(0, ballForce));
ballBody.GetComponent<BallOperator>().launched = true;
newBall = null;
}
}
float time = (speed/2) * Time.deltaTime;
float newX = Mathf.Lerp(transform.position.x, rays.x, time);
newX = Mathf.Clamp(newX, -20, 20);
transform.position = new Vector2(newX, transform.position.y);
}
void AndroidUpdate()
{
if (Input.touchCount > 0)
{
foreach (Touch touch in Input.touches)
{
rays = mainCamera_cam.ScreenToWorldPoint(touch.position);
if (touch.phase == TouchPhase.Moved)
{
if (newBall)
{
Rigidbody2D ballBody = newBall.GetComponent<Rigidbody2D>();
ballBody.position = transform.position + new Vector3(0, 3);
}
}
if (touch.phase == TouchPhase.Ended && touch.phase != TouchPhase.Canceled)
if (newBall)
{
Rigidbody2D ballBody = newBall.GetComponent<Rigidbody2D>();
ballBody.position = transform.position + new Vector3(0, 3);
if (Launch)
{
ballBody.AddForce(new Vector2(0, ballForce));
ballBody.GetComponent<BallOperator>().launched = true;
newBall = null;
Launch = false;
}
}
}
}
float time = speed * Time.deltaTime;
float newX = Mathf.Lerp(transform.position.x, rays.x, time);
newX = Mathf.Clamp(newX, -20, 20);
transform.position = new Vector2(newX, transform.position.y);
}
public void SpawnBall()
{
if (ballPrefab == null)
{
Debug.LogError("A ball prefab needs to be assaigned in the inspector of 'PlatformOperator.cs'.");
return;
}
Launch = true;
Vector3 ballPos = transform.position + new Vector3(0, 3);
newBall = (GameObject)Instantiate(ballPrefab, ballPos, Quaternion.identity);
}
void OnCollisionEnter2D(Collision2D col)
{
foreach (ContactPoint2D contact in col.contacts)
{
if (contact.collider != _collider2D)
{
float calc = contact.point.x - transform.position.x;
contact.collider.GetComponent<Rigidbody2D>().AddForce(new Vector3(100f * calc, 0, 0));
}
}
}
}
|
using System.Threading;
using System.Threading.Tasks;
using AutoFixture;
using Moq;
using NUnit.Framework;
using SFA.DAS.CommitmentsV2.Api.Client;
using SFA.DAS.CommitmentsV2.Api.Types.Responses;
using SFA.DAS.ProviderCommitments.Web.Mappers;
using SFA.DAS.ProviderCommitments.Web.Mappers.Apprentice;
using SFA.DAS.ProviderCommitments.Web.Models;
using SFA.DAS.ProviderCommitments.Web.Models.Apprentice.Edit;
namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Mappers.Apprentice
{
[TestFixture]
public class WhenIMapSelectCourseViewModelFromEditApprenticeshipRequestViewModel
{
private SelectCourseViewModelFromEditApprenticeshipRequestViewModelMapper _mapper;
private Mock<ISelectCourseViewModelMapperHelper> _helper;
private Mock<ICommitmentsApiClient> _client;
private SelectCourseViewModel _model;
private GetApprenticeshipResponse _apprenticeshipResponse;
private GetCohortResponse _cohortResponse;
private EditApprenticeshipRequestViewModel _request;
[SetUp]
public void Arrange()
{
var fixture = new Fixture();
_request = fixture.Build<EditApprenticeshipRequestViewModel>().Without(x=>x.BirthDay).Without(x => x.BirthMonth).Without(x => x.BirthYear)
.Without(x => x.StartDate).Without(x => x.StartMonth).Without(x => x.StartYear)
.Without(x => x.EndDate).Without(x => x.EndMonth).Without(x => x.EndYear).Create();
_model = fixture.Create<SelectCourseViewModel>();
_apprenticeshipResponse = fixture.Create<GetApprenticeshipResponse>();
_cohortResponse = fixture.Create<GetCohortResponse>();
_helper = new Mock<ISelectCourseViewModelMapperHelper>();
_helper.Setup(x => x.Map(It.IsAny<string>(), It.IsAny<long>(), It.IsAny<bool?>())).ReturnsAsync(_model);
_client = new Mock<ICommitmentsApiClient>();
_client.Setup(x => x.GetApprenticeship(It.IsAny<long>(), It.IsAny<CancellationToken>())).ReturnsAsync(_apprenticeshipResponse);
_client.Setup(x => x.GetCohort(It.IsAny<long>(), It.IsAny<CancellationToken>())).ReturnsAsync(_cohortResponse);
_mapper = new SelectCourseViewModelFromEditApprenticeshipRequestViewModelMapper(_helper.Object, _client.Object);
}
[Test]
public async Task TheParamsArePassedInCorrectly()
{
var result = await _mapper.Map(_request);
_client.Verify(x => x.GetApprenticeship(_request.ApprenticeshipId, CancellationToken.None));
_client.Verify(x => x.GetCohort(_apprenticeshipResponse.CohortId, CancellationToken.None));
_helper.Verify(x=>x.Map(_request.CourseCode, _cohortResponse.AccountLegalEntityId, null));
}
[Test]
public async Task ThenModelIsReturned()
{
var result = await _mapper.Map(_request);
Assert.AreEqual(_model, result);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "ListObject", menuName = "TransferData/ListObject")]
public class ListObject : ScriptableObject {
public List<GameObject> monsters;
public List<GameObject> tower;
public List<GameObject> crystals;
public City fightCity;
public int star;
}
|
namespace PatientsRegistry.Search
{
public sealed class ContactDto
{
public string Type { get; set; }
public string Kind { get; set; }
public string Value { get; set; }
}
}
|
using System;
using TY.SPIMS.Utilities;
using TY.SPIMS.Entities;
using System.Collections.Generic;
using TY.SPIMS.POCOs;
using System.Linq;
namespace TY.SPIMS.Controllers.Interfaces
{
public interface ISaleController
{
bool CheckIfInvoiceHasDuplicate(string codeToCheck, int id);
void DeleteSale(int id);
string[] FetchAllInvoiceNumbersByCustomer(int customerId);
SortableBindingList<SalesView> FetchAllSales();
SortableBindingList<SaleDisplayModel> FetchARWithSearch(SaleFilterModel filter);
Sale FetchSaleById(int id);
SortableBindingList<SalesView> FetchSaleByIds(List<int> ids);
Sale FetchSaleByInvoiceNumber(string invoiceNumber);
SortableBindingList<SalesDetailViewModel> FetchSaleDetails(int id);
List<SalesDetailViewModel> FetchSaleDetailsPerInvoice(string invoiceNumber);
List<SalesDetailViewModel> FetchSalesPerItemPerCustomer(int autoPartDetailId, int customerId = 0);
SortableBindingList<SalesView> FetchSaleWithSearch(SaleFilterModel filter);
string GetPONumber(int saleId);
void InsertSale(SaleColumnModel model);
bool ItemHasPaymentOrReturn(int id);
void UpdateSale(SaleColumnModel model);
IQueryable<SalesView> FetchSalesWithSearchGeneric(SaleFilterModel filter);
}
}
|
namespace Jedi_Code_X
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
public class Startup
{
public static void Main(string[] args)
{
Execute();
}
private static void Execute()
{
var n = int.Parse(Console.ReadLine());
var builder = new StringBuilder();
for (int i = 0; i < n; i++)
{
builder.Append(Console.ReadLine());
}
var first = Console.ReadLine();
var second = Console.ReadLine();
var regex = new Regex($"{first}([a-zA-Z0-9]" + "{" + $"{first.Length}" + "})");
var firstPatternMatches = regex.Matches(builder.ToString());
var firstPatternStr = new List<string>();
regex = new Regex($"{second}([a-zA-Z0-9]" + "{" + $"{second.Length}" + "})");
var secondPatternMatches = regex.Matches(builder.ToString());
var secondPatternStr = new List<string>();
foreach (Match m in firstPatternMatches)
{
firstPatternStr.Add(m.Groups[1].Value);
}
foreach (Match m in secondPatternMatches)
{
secondPatternStr.Add(m.Groups[1].Value);
}
var indices = Console.ReadLine()
.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
for (int i = 0, j = 0; i < firstPatternStr.Count && j < indices.Length; i++)
{
for (var k = j; k < indices.Length; k++, j++)
{
if (indices[k] - 1 >= 0 && indices[k] - 1 < secondPatternStr.Count)
{
j++;
Console.WriteLine($"{firstPatternStr[i]} - {secondPatternStr[indices[k] - 1]}");
break;
}
}
}
}
}
}
|
using UmbracoIdentity.Models;
namespace Uintra.Models.UmbracoIdentity
{
public class UmbracoApplicationRole : UmbracoIdentityRole
{
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;
namespace ProgramCCS
{
public partial class Inventory_control : Form
{
public SqlConnection con = Connection.con;//Получить строку соединения из класса модели
public Inventory_control()
{
InitializeComponent();
comboBox1.KeyDown += (s, e) => { if (e.KeyCode == Keys.Enter) button1_Click(new object(), new EventArgs()); };//Нажатие кнопки "Добавить" с клавиатуры
textBox4.KeyDown += (s, e) => { if (e.KeyCode == Keys.Enter) button1_Click(new object(), new EventArgs()); };//Нажатие кнопки "Добавить" с клавиатуры
}
private void Sklad_Load(object sender, EventArgs e)//Загрузка формы
{
//-----------------Окраска Гридов-------------------//
DataGridViewRow row1 = this.dataGridView1.RowTemplate;
row1.DefaultCellStyle.BackColor = Color.AliceBlue;//цвет строк
row1.Height = 5;
row1.MinimumHeight = 17;
dataGridView1.EnableHeadersVisualStyles = false;
dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.SteelBlue;//цвет заголовка
DataGridViewRow row2 = this.dataGridView2.RowTemplate;
row2.DefaultCellStyle.BackColor = Color.AliceBlue;//цвет строк
row2.Height = 5;
row2.MinimumHeight = 17;
dataGridView2.EnableHeadersVisualStyles = false;
dataGridView2.ColumnHeadersDefaultCellStyle.BackColor = Color.LightSlateGray;//цвет заголовка
dateTimePicker1.Value = DateTime.Today.AddMonths(-1);
dateTimePicker2.Value = DateTime.Today.AddDays(0);
//итоги
disp_data();
disp_data2();
pereschet();
ITOGI();//Итоги
disp_data();
disp_data2();
}
private void Sklad_FormClosed(object sender, FormClosedEventArgs e)//Закрытие формы
{
if (MessageBox.Show("Вы действительно хотите выйти?!", "Внимание!", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
{
Application.Exit();
}
}
public void disp_data()//Table_Hoz_Osnovnye
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [Table_Hoz_Osnovnye] ORDER BY date";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
public void disp_data2()//Table_Hoz_MBP
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [Table_Hoz_MBP] ORDER BY date";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView2.DataSource = dt;
con.Close();
}
public void pereschet()//Пересчет
{
if (tabControl1.SelectedTab == tabPage1)//Если основные
{
//Через месяц (приход обнуляется, стоимость получает значение цены)
con.Open();//открыть соединение
for (int i = 0; i < dataGridView1.Rows.Count; i++)//Цикл (основные средства)
{ //Действие №1 (-------)
DateTime X = Convert.ToDateTime(dataGridView1.Rows[i].Cells[10].Value);//Переменная столбца даты
DateTime Y = DateTime.Today.AddMonths(-1);//Переменная текущей даты минус 1 месяц
if (X <= Y)// если дата меньше текущей на 1 месяц (основные средства)
{
SqlCommand cmd = new SqlCommand("UPDATE [Table_Hoz_Osnovnye] SET stoimost = @stoimost, prihod = @prihod WHERE id = @id", con);
cmd.Parameters.AddWithValue("@stoimost", Convert.ToInt32(dataGridView1.Rows[i].Cells[4].Value));
cmd.Parameters.AddWithValue("@prihod", 0);
cmd.Parameters.AddWithValue("@id", Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value));
cmd.ExecuteNonQuery();
//dataGridView1.Rows[i].Cells[6].Value = dataGridView1.Rows[i].Cells[4].Value;//стоимость получает значение цены);
//dataGridView1.Rows[i].Cells[7].Value = 0;//приход обнуляется
}
}
con.Close();//закрыть соединение
//основные обнуляются те что в расходе
con.Open();//открыть соединение
for (int i = 0; i < dataGridView1.Rows.Count; i++)//Цикл
{
//Действие №2 (удаление) основные средства
DateTime X = Convert.ToDateTime(dataGridView1.Rows[i].Cells[10].Value);//Переменная столбца даты
DateTime Y = DateTime.Today.AddMonths(-1);//Переменная текущей даты минус 1 месяц
int S = Convert.ToInt32(dataGridView1.Rows[i].Cells[8].Value);//Расход
if (X <= Y && S > 0)// Если дата меньше текущей на 1 месяц и Если расход больше 0
{
SqlCommand cmd = new SqlCommand("UPDATE [Table_Hoz_Osnovnye] SET cena=@cena, stoimost=@stoimost, kol_vo=@kol_vo, prihod=@prihod, rashod=@rashod, itog=@itog WHERE id = @id", con);
cmd.Parameters.AddWithValue("@cena", 0);
cmd.Parameters.AddWithValue("@kol_vo", 0);
cmd.Parameters.AddWithValue("@stoimost", 0);
cmd.Parameters.AddWithValue("@prihod", 0);
cmd.Parameters.AddWithValue("@rashod", 0);
cmd.Parameters.AddWithValue("@itog", 0);
cmd.Parameters.AddWithValue("@id", Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value));
cmd.ExecuteNonQuery();
//dataGridView1.Rows[i].Cells[4].Value = 0;
//dataGridView1.Rows[i].Cells[5].Value = 0;
//dataGridView1.Rows[i].Cells[6].Value = 0;
//dataGridView1.Rows[i].Cells[7].Value = 0;
//dataGridView1.Rows[i].Cells[8].Value = 0;
//dataGridView1.Rows[i].Cells[9].Value = 0;
}
}
con.Close();//закрыть соединение
//Сальдо на конец основные средства
double saldo_konec = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
double incom;
double.TryParse((row.Cells[9].Value ?? "0").ToString().Replace(".", ","), out incom);//Итог
saldo_konec += incom;
}
textBox6.Visible = true;
textBox6.Text = saldo_konec.ToString() + " сом";
//Сальдо на начало основные средства
double saldo_nachalo = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
double incom;
double.TryParse((row.Cells[6].Value ?? "0").ToString().Replace(".", ","), out incom);//Стоимость
saldo_nachalo += incom;
}
textBox7.Visible = true;
textBox7.Text = saldo_nachalo.ToString() + " сом";
}
else if (tabControl1.SelectedTab == tabPage2)//Если МБП
{
//Через месяц (приход обнуляется, стоимость получает значение цены)
con.Open();//открыть соединение
for (int i = 0; i < dataGridView2.Rows.Count; i++)//Цикл (МБП)
{
DateTime W = Convert.ToDateTime(dataGridView2.Rows[i].Cells[12].Value);//Переменная столбца даты
DateTime Z = DateTime.Today.AddMonths(-1);//Переменная текущей даты минус 1 месяц
if (W <= Z)// если дата меньше текущей на 1 месяц (МБП)
{
SqlCommand cmd = new SqlCommand("UPDATE [Table_Hoz_MBP] SET stoimost = @stoimost, prihod = @prihod, kol_vo=@kol_vo, kol_vo_p=@kol_vo_p WHERE id = @id", con);
cmd.Parameters.AddWithValue("@stoimost", Convert.ToInt32(dataGridView1.Rows[i].Cells[7].Value));
cmd.Parameters.AddWithValue("@kol_vo", Convert.ToInt32(dataGridView1.Rows[i].Cells[6].Value));
cmd.Parameters.AddWithValue("@kol_vo_p", 0);
cmd.Parameters.AddWithValue("@prihod", 0);
cmd.Parameters.AddWithValue("@id", Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value));
cmd.ExecuteNonQuery();
//dataGridView2.Rows[i].Cells[5].Value = dataGridView2.Rows[i].Cells[7].Value;//стоимость получает значение цены
//dataGridView2.Rows[i].Cells[4].Value = dataGridView2.Rows[i].Cells[6].Value;//Кол-во получает у кол-во прихода
//dataGridView2.Rows[i].Cells[7].Value = 0;//приход обнуляется
//dataGridView2.Rows[i].Cells[6].Value = 0;//кол-во приход обнуляется
}
}
con.Close();//закрыть соединение
// МБП обнуляются те что в расходе
con.Open();//открыть соединение
for (int i = 0; i < dataGridView2.Rows.Count; i++)//Цикл
{
//Действие №2 (удаление) МБП
DateTime W = Convert.ToDateTime(dataGridView2.Rows[i].Cells[12].Value);//Переменная столбца даты
DateTime Z = DateTime.Today.AddMonths(-1);//Переменная текущей даты минус 1 месяц
int S = Convert.ToInt32(dataGridView2.Rows[i].Cells[9].Value);//Расход
int K = Convert.ToInt32(dataGridView2.Rows[i].Cells[8].Value);//Кол-во расход
int L = Convert.ToInt32(dataGridView2.Rows[i].Cells[4].Value);//Кол-во
if (W <= Z & S > 0 & K == L)// Если дата меньше текущей на 1 месяц и Если расход больше 0 и кол-во расхода равно кол-во
{
SqlCommand cmd = new SqlCommand("UPDATE [Table_Hoz_MBP] SET cena=@cena, stoimost=@stoimost, kol_vo=@kol_vo, kol_vo_p=@kol_vo_p, kol_vo_r=@kol_vo_r, kol_vo_i=@kol_vo_i, prihod=@prihod, rashod=@rashod, itog=@itog WHERE id = @id", con);
cmd.Parameters.AddWithValue("@cena", 0);
cmd.Parameters.AddWithValue("@kol_vo", 0);
cmd.Parameters.AddWithValue("@stoimost", 0);
cmd.Parameters.AddWithValue("@kol_vo_p", 0);
cmd.Parameters.AddWithValue("@kol_vo_r", 0);
cmd.Parameters.AddWithValue("@kol_vo_i", 0);
cmd.Parameters.AddWithValue("@prihod", 0);
cmd.Parameters.AddWithValue("@rashod", 0);
cmd.Parameters.AddWithValue("@itog", 0);
cmd.Parameters.AddWithValue("@id", Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value));
cmd.ExecuteNonQuery();
//dataGridView2.Rows[i].Cells[3].Value = 0;
//dataGridView2.Rows[i].Cells[4].Value = 0;
//dataGridView2.Rows[i].Cells[5].Value = 0;
//dataGridView2.Rows[i].Cells[6].Value = 0;
//dataGridView2.Rows[i].Cells[7].Value = 0;
//dataGridView2.Rows[i].Cells[8].Value = 0;
//dataGridView2.Rows[i].Cells[9].Value = 0;
//dataGridView2.Rows[i].Cells[10].Value = 0;
//dataGridView2.Rows[i].Cells[11].Value = 0;
}
}
con.Close();//закрыть соединение
//Сальдо на конец МБП
double saldo_konec_MBP = 0;
foreach (DataGridViewRow row in dataGridView2.Rows)
{
double incom;
double.TryParse((row.Cells[11].Value ?? "0").ToString().Replace(".", ","), out incom);//Итог МБП
saldo_konec_MBP += incom;
}
textBox9.Visible = true;
textBox9.Text = saldo_konec_MBP.ToString() + " сом";
//Сальдо на начало МБП
double saldo_nachalo_MBP = 0;
foreach (DataGridViewRow row in dataGridView2.Rows)
{
double incom;
double.TryParse((row.Cells[5].Value ?? "0").ToString().Replace(".", ","), out incom);//Стоимость МБП
saldo_nachalo_MBP += incom;
}
textBox8.Visible = true;
textBox8.Text = saldo_nachalo_MBP.ToString() + " сом";
}
}
public void ITOGI()//Итоги
{
if (tabControl1.SelectedTab == tabPage1)//Если основные
{
con.Open();//открыть соединение
for (int i = 0; i < dataGridView1.Rows.Count; i++)//Цикл (основные средства)
{
SqlCommand cmd = new SqlCommand("UPDATE [Table_Hoz_Osnovnye] SET itog = (stoimost + prihod - rashod)" +
"UPDATE [Table_Hoz_MBP] SET itog = (stoimost + prihod - rashod), kol_vo_i = (kol_vo + kol_vo_p - kol_vo_r), prihod = (kol_vo_p * cena)", con);
cmd.ExecuteNonQuery();
}
con.Close();//закрыть соединение
}
else if (tabControl1.SelectedTab == tabPage2)//Если МБП
{
con.Open();//открыть соединение
for (int i = 0; i < dataGridView2.Rows.Count; i++)//Цикл (МБП)
{
SqlCommand cmd = new SqlCommand("UPDATE [Table_Hoz_Osnovnye] SET itog = (stoimost + prihod - rashod)" +
"UPDATE [Table_Hoz_MBP] SET itog = (stoimost + prihod - rashod), kol_vo_i = (kol_vo + kol_vo_p - kol_vo_r), prihod = (kol_vo_p * cena)", con);
cmd.ExecuteNonQuery();
}
con.Close();//закрыть соединение
}
}
private void textBox10_TextChanged(object sender, EventArgs e)//Поиск
{
if (tabControl1.SelectedTab == tabPage1)//Если основные
{
con.Open();//открыть соединение
SqlCommand cmd = new SqlCommand("SELECT * FROM [Table_Hoz_Osnovnye] WHERE name LIKE '%" + Convert.ToString(textBox10.Text) + "%'", con);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();//создаем экземпляр класса DataTable
SqlDataAdapter da = new SqlDataAdapter(cmd);//создаем экземпляр класса SqlDataAdapter
dt.Clear();//чистим DataTable, если он был не пуст
da.Fill(dt);//заполняем данными созданный DataTable
dataGridView1.DataSource = dt;//в качестве источника данных у dataGridView используем DataTable заполненный данными
con.Close();//закрыть соединение
pereschet();
}
else if (tabControl1.SelectedTab == tabPage2)//Если МБП
{
con.Open();//открыть соединение
SqlCommand cmd = new SqlCommand("SELECT * FROM [Table_Hoz_MBP] WHERE name LIKE '%" + Convert.ToString(textBox10.Text) + "%'", con);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();//создаем экземпляр класса DataTable
SqlDataAdapter da = new SqlDataAdapter(cmd);//создаем экземпляр класса SqlDataAdapter
dt.Clear();//чистим DataTable, если он был не пуст
da.Fill(dt);//заполняем данными созданный DataTable
dataGridView2.DataSource = dt;//в качестве источника данных у dataGridView используем DataTable заполненный данными
con.Close();//закрыть соединение
pereschet();
}
}
private void button1_Click(object sender, EventArgs e)//Добавить
{
if (tabControl1.SelectedTab == tabPage1)//Если основные
{
if (textBox1.Text != "" & textBox2.Text != "" & textBox4.Text != "")
{
con.Open();//открыть соединение
SqlCommand cmd = new SqlCommand("INSERT INTO [Table_Hoz_Osnovnye] (inv, name, ed, cena, prihod, rashod, date, kol_vo, stoimost) VALUES (@inv, @name, @ed, @cena, @prihod, @rashod, @date, @kol_vo, @stoimost)", con);
cmd.Parameters.AddWithValue("@inv", textBox1.Text);
cmd.Parameters.AddWithValue("@name", textBox2.Text);
cmd.Parameters.AddWithValue("@date", DateTime.Today);
cmd.Parameters.AddWithValue("@ed", "шт");
cmd.Parameters.AddWithValue("@cena", textBox4.Text);
cmd.Parameters.AddWithValue("@prihod", textBox4.Text);
cmd.Parameters.AddWithValue("@rashod", 0);
cmd.Parameters.AddWithValue("@kol_vo", 1);
cmd.Parameters.AddWithValue("@stoimost", 0);
cmd.ExecuteNonQuery();
con.Close();//закрыть соединение
MessageBox.Show("Запись в Основные успешно добавлена", "Внимание!");
textBox1.Select();//установить курсор
}
else if (textBox1.Text == "" & textBox2.Text == "" & textBox4.Text == "")
{
label6.Visible = true;
label6.Text = "Заполните все поля";
}
else MessageBox.Show("Ошибка, Перейдите на вкладку МБП!", "Внимание!");
}
else if (tabControl1.SelectedTab == tabPage2)//Если МБП
{
if (textBox2.Text != "" && textBox3.Text != "" && textBox4.Text != "" && comboBox1.Text != "")
{
con.Open();//открыть соединение
SqlCommand cmd = new SqlCommand("INSERT INTO [Table_Hoz_MBP] (name, ed, cena, kol_vo, stoimost, kol_vo_p, kol_vo_r, rashod) VALUES (@name, @ed, @cena, @kol_vo, @stoimost, @kol_vo_p, @kol_vo_r, @rashod)", con);
cmd.Parameters.AddWithValue("@name", textBox2.Text);
cmd.Parameters.AddWithValue("@date", DateTime.Today);
cmd.Parameters.AddWithValue("@ed", comboBox1.Text);
cmd.Parameters.AddWithValue("@cena", textBox4.Text);
cmd.Parameters.AddWithValue("@kol_vo", 0);
cmd.Parameters.AddWithValue("@stoimost", 0);
cmd.Parameters.AddWithValue("@kol_vo_p", textBox3.Text);
cmd.Parameters.AddWithValue("@kol_vo_r", 0);
cmd.Parameters.AddWithValue("@rashod", 0);
cmd.ExecuteNonQuery();
con.Close();//закрыть соединение
MessageBox.Show("Запись МБП успешно добавлена", "Внимание!");
textBox2.Select();//установить курсор
}
else if (textBox2.Text == "" && textBox3.Text == "" && textBox4.Text == "" && comboBox1.Text == "")
{
label6.Visible = true;
label6.Text = "Заполните все поля";
}
else MessageBox.Show("Ошибка, Перейдите на вкладку Основные средства!", "Внимание!");
}
disp_data();
disp_data2();
pereschet();
ITOGI();//Итоги
disp_data();
disp_data2();
textBox1.Text = "";//очистка текстовых полей
textBox2.Text = "";//
textBox3.Text = "";//
textBox4.Text = "";//
comboBox1.Text = "";
}
private void button2_Click(object sender, EventArgs e)//Расход
{
if (tabControl1.SelectedTab == tabPage1)//Если основные
{
if (dataGridView1.Rows.Count == 1)
{
con.Open();//открыть соединение
SqlCommand cmd = new SqlCommand("UPDATE [Table_Hoz_Osnovnye] SET rashod = (cena) WHERE id = @id", con);//получаем значение из столбца cena в столбец rashod
cmd.Parameters.AddWithValue("@id", Convert.ToInt32(dataGridView1.Rows[0].Cells[0].Value));//первая строка в гриде
cmd.ExecuteNonQuery();
con.Close();//закрыть соединение
}
else if (dataGridView1.Rows.Count != 1)
{
label6.Visible = true;
label6.Text = "Произведите поиск";
MessageBox.Show("Произведите поиск!", "Внимание!");
}
else if (dataGridView1.Rows.Count <= 0)
{
label6.Text = "В базе не найдено!";
MessageBox.Show("В базе не найдено!", "Внимание!");
}
}
else if (tabControl1.SelectedTab == tabPage2)//Если МБП
{
if (dataGridView2.Rows.Count == 1 & textBox3.Text != "")
{
con.Open();//открыть соединение
SqlCommand cmd = new SqlCommand("UPDATE [Table_Hoz_MBP] SET kol_vo_r = (kol_vo_p - " + textBox3.Text + "), rashod = (cena * kol_vo_r) WHERE id = @id", con);//получаем значение из столбца cena в столбец rashod
cmd.Parameters.AddWithValue("@id", Convert.ToInt32(dataGridView2.Rows[0].Cells[0].Value));//первая строка в гриде
cmd.ExecuteNonQuery();
con.Close();//закрыть соединение
}
else if (textBox3.Text == "")
{
label6.Visible = true;
label6.Text = "Установите кол-во";
MessageBox.Show("Установите кол-во!", "Внимание!");
textBox3.Select();//установить курсор
}
else if (dataGridView2.Rows.Count != 1)
{
label6.Visible = true;
label6.Text = "Произведите поиск";
MessageBox.Show("Произведите поиск!", "Внимание!");
}
else if (dataGridView2.Rows.Count <= 0)
{
label6.Text = "В базе не найдено!";
MessageBox.Show("В базе не найдено!", "Внимание!");
}
}
disp_data();
disp_data2();
pereschet();
ITOGI();//Итоги
disp_data();
disp_data2();
textBox1.Text = "";//очистка текстовых полей
textBox2.Text = "";//
textBox3.Text = "";//
textBox4.Text = "";//
comboBox1.Text = "";
}
private void button6_Click(object sender, EventArgs e)//Удалить записи расхода
{
if (tabControl1.SelectedTab == tabPage1)//Если основные
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)//Цикл
{
//Действие №2 (удаление) основные средства
DateTime X = Convert.ToDateTime(dataGridView1.Rows[i].Cells[10].Value);//Переменная столбца даты
DateTime Y = DateTime.Today.AddMonths(-1);//Переменная текущей даты минус 1 месяц
int S = Convert.ToInt32(dataGridView1.Rows[i].Cells[8].Value);//Расход
if (X <= Y && S > 0 && (MessageBox.Show("Вы действительно хотите удалить записи расхода основных средств?", "Внимание! Рекомендую сохранить отчет", MessageBoxButtons.YesNo) == DialogResult.Yes))// Если дата меньше текущей на 1 месяц и Если расход больше 0
{
con.Open();//открыть соединение
SqlCommand cmd = new SqlCommand("DELETE FROM [Table_Hoz_Osnovnye] WHERE rashod = @rashod", con);//расход удаляется
cmd.Parameters.AddWithValue("@rashod", Convert.ToInt32(dataGridView1.Rows[i].Cells[8].Value));
cmd.ExecuteNonQuery();
con.Close();//закрыть соединение
}
}
}
else if (tabControl1.SelectedTab == tabPage2)//Если МБП
{
for (int i = 0; i < dataGridView2.Rows.Count; i++)//Цикл
{
//Действие №2 (удаление) МБП
DateTime W = Convert.ToDateTime(dataGridView2.Rows[i].Cells[12].Value);//Переменная столбца даты
DateTime Z = DateTime.Today.AddMonths(-1);//Переменная текущей даты минус 1 месяц
int S = Convert.ToInt32(dataGridView2.Rows[i].Cells[9].Value);//Расход
int K = Convert.ToInt32(dataGridView2.Rows[i].Cells[8].Value);//Кол-во расход
int L = Convert.ToInt32(dataGridView2.Rows[i].Cells[4].Value);//Кол-во
if (W <= Z && S > 0 && K == L && (MessageBox.Show("Вы действительно хотите удалить записи расхода МБП?", "Внимание! Рекомендую сохранить отчет", MessageBoxButtons.YesNo) == DialogResult.Yes))// Если дата меньше текущей на 1 месяц и Если расход больше 0 и кол-во расхода равно кол-во
{
con.Open();//открыть соединение
SqlCommand cmd = new SqlCommand("DELETE FROM [Table_2] WHERE rashod = @rashod", con);//расход удаляется
cmd.Parameters.AddWithValue("@rashod", Convert.ToInt32(dataGridView2.Rows[i].Cells[9].Value));
cmd.ExecuteNonQuery();
con.Close();//закрыть соединение
}
}
}
disp_data();
disp_data2();
pereschet();
ITOGI();//Итоги
disp_data();
disp_data2();
textBox1.Text = "";//очистка текстовых полей
textBox2.Text = "";//
textBox3.Text = "";//
textBox4.Text = "";//
comboBox1.Text = "";
}
private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)//Обработчик окраски строк в таблице
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)//Цикл
{
int S = Convert.ToInt32(dataGridView1.Rows[i].Cells[8].Value);//расход
int C = Convert.ToInt32(dataGridView1.Rows[i].Cells[7].Value);//приход
if (S > 0)// Eсли расход больше 0
{
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.LightSalmon;//окраска строк в красный цвет
}
else if (C > 0 & S <= 0)// Если приход больше 0 и расход равен 0
{
dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.LightGreen;//окраска строк в зеленый цвет
}
}
}
private void dataGridView2_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)//Обработчик окраски строк в таблице МБП
{
for (int i = 0; i < dataGridView2.Rows.Count; i++)//Цикл
{
int S = Convert.ToInt32(dataGridView2.Rows[i].Cells[9].Value);//Расход
int C = Convert.ToInt32(dataGridView2.Rows[i].Cells[7].Value);//Приход
if (S > 0)// Eсли расход больше 0
{
dataGridView2.Rows[i].DefaultCellStyle.BackColor = Color.LightSalmon;//окраска строк в красный цвет
}
else if (C > 0 & S <= 0)// Если приход больше 0 и расход равен 0
{
dataGridView2.Rows[i].DefaultCellStyle.BackColor = Color.LightGreen;//окраска строк в зеленый цвет
}
}
}
private void button3_Click(object sender, EventArgs e)//Выборка
{
if (tabControl1.SelectedTab == tabPage1)//Если основные
{
DateTime date = new DateTime();
date = dateTimePicker1.Value;
DateTime date2 = dateTimePicker2.Value;
con.Open();//открыть соединение
SqlCommand cmd = new SqlCommand("SELECT * FROM [Table_Hoz_Osnovnye] WHERE (date BETWEEN @StartDate AND @EndDate)", con);//Выборка по датам
cmd.Parameters.AddWithValue("StartDate", date);
cmd.Parameters.AddWithValue("EndDate", date2);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();//закрыть соединение
pereschet();
}
else if (tabControl1.SelectedTab == tabPage2)//Если МБП
{
DateTime date = new DateTime();
date = dateTimePicker1.Value;
DateTime date2 = dateTimePicker2.Value;
con.Open();//открыть соединение
SqlCommand cmd = new SqlCommand("SELECT * FROM [Table_Hoz_MBP] WHERE (date BETWEEN @StartDate AND @EndDate)", con);//Выборка по датам
cmd.Parameters.AddWithValue("StartDate", date);
cmd.Parameters.AddWithValue("EndDate", date2);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView2.DataSource = dt;
con.Close();//закрыть соединение
pereschet();
}
}
private void button4_Click(object sender, EventArgs e)//Отчеты
{
if (tabControl1.SelectedTab == tabPage1)//Если основные
{
pereschet();
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Word Documents (*.docx)|*.docx";
sfd.FileName = "Отчет основных средств №.docx";
if (sfd.ShowDialog() == DialogResult.OK)
{
Export_Data_To_Word(dataGridView1, sfd.FileName);
}
}
else if (tabControl1.SelectedTab == tabPage2)//Если МБП
{
pereschet();
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Word Documents (*.docx)|*.docx";
sfd.FileName = "Отчет МБП №.docx";
if (sfd.ShowDialog() == DialogResult.OK)
{
Export_Data_To_Word2(dataGridView2, sfd.FileName);
}
}
}
public void Export_Data_To_Word(DataGridView dataGridView1, string filename)//Обработчик Word
{
Word.Document oDoc = new Word.Document();
oDoc.Application.Visible = true;
//ориентация страницы
oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;
// Стиль текста.
object start = 0, end = 0;
Word.Range rng = oDoc.Range(ref start, ref end);
rng.InsertBefore("Заголовок");//Заголовок
rng.Font.Name = "Times New Roman";
rng.Font.Size = 9;
rng.InsertParagraphAfter();
rng.InsertParagraphAfter();
rng.SetRange(rng.End, rng.End);
oDoc.Content.ParagraphFormat.LeftIndent = oDoc.Content.Application.CentimetersToPoints(0); // отступ слева
if (dataGridView1.Rows.Count != 0)
{
int RowCount = dataGridView1.Rows.Count;
int ColumnCount = dataGridView1.Columns.Count;
Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1];
// добавить строки
int r = 0;
for (int c = 0; c <= ColumnCount - 1; c++)
{
for (r = 0; r <= RowCount - 1; r++)
{
DataArray[r, c] = dataGridView1.Rows[r].Cells[c].Value;
} //Конец цикла строки
} //конец петли колонки
//Добавление текста в документ
string saldo_nachalo = Convert.ToString(textBox7.Text);//Сальдо начало
string saldo_konec = Convert.ToString(textBox6.Text);//Сальдо конец
oDoc.Content.SetRange(0, 0);
oDoc.Content.Text = "Сальдо на начало: " + saldo_nachalo + " Сальдо на конец: " + saldo_konec + Environment.NewLine +
Environment.NewLine + "Выполнил__________________" + " " + "Принял_____________________" + Environment.NewLine;
dynamic oRange = oDoc.Content.Application.Selection.Range;
string oTemp = "";
for (r = 0; r <= RowCount - 1; r++)
{
for (int c = 0; c <= ColumnCount - 1; c++)
{
oTemp = oTemp + DataArray[r, c] + "\t";
}
}
//формат таблицы
oRange.Text = oTemp;
object Separator = Word.WdTableFieldSeparator.wdSeparateByTabs;
object ApplyBorders = true;
object AutoFit = true;
object AutoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitContent;
oRange.ConvertToTable(ref Separator, ref RowCount, ref ColumnCount,
Type.Missing, Type.Missing, ref ApplyBorders,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, ref AutoFit, ref AutoFitBehavior, Type.Missing);
oRange.Select();
oDoc.Application.Selection.Tables[1].Select();
oDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0;
oDoc.Application.Selection.Tables[1].Rows.Alignment = 0;
oDoc.Application.Selection.Tables[1].Rows[1].Select();
oDoc.Application.Selection.InsertRowsAbove(1);
oDoc.Application.Selection.Tables[1].Rows[1].Select();
//заголовка стиль строки
oDoc.Application.Selection.Tables[1].Rows[1].Range.Bold = 1;
oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name = "Times New Roman";
oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 9;
//добавить строку заголовка вручную
for (int c = 0; c <= ColumnCount - 1; c++)
{
oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = dataGridView1.Columns[c].HeaderText;
}
//стиль таблицы
oDoc.Application.Selection.Tables[1].Rows.Borders.Enable = 1;//borders
oDoc.Application.Selection.Tables[1].Rows[1].Select();
oDoc.Application.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
//текст заголовка
foreach (Word.Section section in oDoc.Application.ActiveDocument.Sections)
{//Верхний колонтитул
DateTime Now = DateTime.Now;
Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage].Range;
headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage);
section.PageSetup.DifferentFirstPageHeaderFooter = -1;//Включить особый колонтитул
headerRange.Text = "Отчет №_";
headerRange.Font.Size = 12;
headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
//Нижний колонтитул
Word.Range footerRange = section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage].Range;
footerRange.Fields.Add(footerRange, Word.WdFieldType.wdFieldPage);
footerRange.Text = "ГП Служба специальной связи " + Convert.ToString(Now.ToString("dd:MM:yyyy"));
footerRange.Font.Size = 9;
footerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
}
//сохранить файл
oDoc.SaveAs(filename);
}
}
public void Export_Data_To_Word2(DataGridView dataGridView2, string filename)//Обработчик Word МБП
{
Word.Document oDoc = new Word.Document();
oDoc.Application.Visible = true;
//ориентация страницы
oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;
// Стиль текста.
object start = 0, end = 0;
Word.Range rng = oDoc.Range(ref start, ref end);
rng.InsertBefore("Заголовок");//Заголовок
rng.Font.Name = "Times New Roman";
rng.Font.Size = 9;
rng.InsertParagraphAfter();
rng.InsertParagraphAfter();
rng.SetRange(rng.End, rng.End);
oDoc.Content.ParagraphFormat.LeftIndent = oDoc.Content.Application.CentimetersToPoints(0); // отступ слева
if (dataGridView2.Rows.Count != 0)
{
int RowCount = dataGridView2.Rows.Count;
int ColumnCount = dataGridView2.Columns.Count;
Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1];
// добавить строки
int r = 0;
for (int c = 0; c <= ColumnCount - 1; c++)
{
for (r = 0; r <= RowCount - 1; r++)
{
DataArray[r, c] = dataGridView2.Rows[r].Cells[c].Value;
} //Конец цикла строки
} //конец петли колонки
//Добавление текста в документ
string saldo_nachalo = Convert.ToString(textBox8.Text);//Сальдо начало
string saldo_konec = Convert.ToString(textBox9.Text);//Сальдо конец
oDoc.Content.SetRange(0, 0);
oDoc.Content.Text = "Сальдо на начало: " + saldo_nachalo + " Сальдо на конец: " + saldo_konec + Environment.NewLine +
Environment.NewLine + "Выполнил__________________" + " " + "Принял_____________________" + Environment.NewLine;
dynamic oRange = oDoc.Content.Application.Selection.Range;
string oTemp = "";
for (r = 0; r <= RowCount - 1; r++)
{
for (int c = 0; c <= ColumnCount - 1; c++)
{
oTemp = oTemp + DataArray[r, c] + "\t";
}
}
//формат таблицы
oRange.Text = oTemp;
object Separator = Word.WdTableFieldSeparator.wdSeparateByTabs;
object ApplyBorders = true;
object AutoFit = true;
object AutoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitContent;
oRange.ConvertToTable(ref Separator, ref RowCount, ref ColumnCount,
Type.Missing, Type.Missing, ref ApplyBorders,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Type.Missing, ref AutoFit, ref AutoFitBehavior, Type.Missing);
oRange.Select();
oDoc.Application.Selection.Tables[1].Select();
oDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0;
oDoc.Application.Selection.Tables[1].Rows.Alignment = 0;
oDoc.Application.Selection.Tables[1].Rows[1].Select();
oDoc.Application.Selection.InsertRowsAbove(1);
oDoc.Application.Selection.Tables[1].Rows[1].Select();
//заголовка стиль строки
oDoc.Application.Selection.Tables[1].Rows[1].Range.Bold = 1;
oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name = "Times New Roman";
oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 9;
//добавить строку заголовка вручную
for (int c = 0; c <= ColumnCount - 1; c++)
{
oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = dataGridView2.Columns[c].HeaderText;
}
//стиль таблицы
oDoc.Application.Selection.Tables[1].Rows.Borders.Enable = 1;//borders
oDoc.Application.Selection.Tables[1].Rows[1].Select();
oDoc.Application.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
//текст заголовка
foreach (Word.Section section in oDoc.Application.ActiveDocument.Sections)
{//Верхний колонтитул
DateTime Now = DateTime.Now;
Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage].Range;
headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage);
section.PageSetup.DifferentFirstPageHeaderFooter = -1;//Включить особый колонтитул
headerRange.Text = "Отчет №_";
headerRange.Font.Size = 12;
headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
//Нижний колонтитул
Word.Range footerRange = section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage].Range;
footerRange.Fields.Add(footerRange, Word.WdFieldType.wdFieldPage);
footerRange.Text = "ГП Служба специальной связи " + Convert.ToString(Now.ToString("dd:MM:yyyy"));
footerRange.Font.Size = 9;
footerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
}
//сохранить файл
oDoc.SaveAs(filename);
}
}
//private void button9_Click(object sender, EventArgs e)//Печать МБП
//{
// if (MessageBox.Show("Вы выполнили процедуры?", "Внимание! Перед тем как отправить на печать выполните процедуры", MessageBoxButtons.YesNo) == DialogResult.Yes)
// {
// PrintDocument Document = new PrintDocument();
// Document.DefaultPageSettings.Landscape = true;//Альбомная ориентация
// Document.PrintPage += new PrintPageEventHandler(printDocument2_PrintPage);
// PrintPreviewDialog dlg = new PrintPreviewDialog();
// dlg.Document = Document;
// dlg.ShowDialog();
// }
//}
private void printDocument2_PrintPage(object sender, PrintPageEventArgs e)
{
Bitmap bmp2 = new Bitmap(dataGridView2.Size.Width + 10, dataGridView2.Size.Height + 10);
dataGridView2.DrawToBitmap(bmp2, dataGridView2.Bounds);
e.Graphics.DrawImage(bmp2, 0, 0);
}
//private void button4_Click(object sender, EventArgs e)//Печать основных средств
//{
// if (MessageBox.Show("Вы выполнили процедуры?", "Внимание! Перед тем как отправить на печать выполните процедуры", MessageBoxButtons.YesNo) == DialogResult.Yes)
// {
// PrintDocument Document = new PrintDocument();
// Document.DefaultPageSettings.Landscape = true;//Альбомная ориентация
// Document.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
// PrintPreviewDialog dlg = new PrintPreviewDialog();
// dlg.Document = Document;
// dlg.ShowDialog();
// }
//}
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)//Обработчик печати
{
Bitmap bmp = new Bitmap(dataGridView1.Size.Width + 10, dataGridView1.Size.Height + 10);
dataGridView1.DrawToBitmap(bmp, dataGridView1.Bounds);
e.Graphics.DrawImage(bmp, 0, 0);
}
}
}
|
namespace Sentry.Tests;
[UsesVerify]
public class EventProcessorTests
{
private readonly TestOutputDiagnosticLogger _logger;
public EventProcessorTests(ITestOutputHelper output)
{
_logger = new TestOutputDiagnosticLogger(output);
}
[Fact]
public async Task Simple()
{
var transport = new RecordingTransport();
var options = Options(transport);
options.AddEventProcessor(new TheEventProcessor());
var hub = SentrySdk.InitHub(options);
using (SentrySdk.UseHub(hub))
{
hub.CaptureMessage("TheMessage");
await hub.FlushAsync();
}
await Verify(transport.Envelopes)
.IgnoreStandardSentryMembers();
}
[Fact]
public async Task WithTransaction()
{
var transport = new RecordingTransport();
var options = Options(transport);
options.AddEventProcessor(new TheEventProcessor());
var hub = SentrySdk.InitHub(options);
using (SentrySdk.UseHub(hub))
{
var transaction = hub.StartTransaction("my transaction", "my operation");
hub.ConfigureScope(scope => scope.Transaction = transaction);
hub.CaptureMessage("TheMessage");
await hub.FlushAsync();
}
await Verify(transport.Envelopes)
.IgnoreStandardSentryMembers();
}
public class TheEventProcessor : ISentryEventProcessor
{
public SentryEvent Process(SentryEvent @event)
{
@event.Contexts["key"] = "value";
return @event;
}
}
[Fact]
public async Task Discard()
{
var transport = new RecordingTransport();
var options = Options(transport);
options.AddEventProcessor(new DiscardEventProcessor());
var hub = SentrySdk.InitHub(options);
using (SentrySdk.UseHub(hub))
{
hub.CaptureMessage("TheMessage");
await hub.FlushAsync();
}
await Verify(transport.Envelopes)
.IgnoreStandardSentryMembers();
}
public class DiscardEventProcessor : ISentryEventProcessor
{
public SentryEvent Process(SentryEvent @event) => null;
}
private SentryOptions Options(ITransport transport) =>
new()
{
TracesSampleRate = 1,
Debug = true,
Transport = transport,
Dsn = ValidDsn,
DiagnosticLogger = _logger,
AttachStacktrace = false,
Release = "release",
InitNativeSdks = false
};
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebAppMedOffices.Models;
namespace WebAppMedOffices.Controllers
{
public class TurnosController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: Turnos
public async Task<ActionResult> Index()
{
var turnos = db.Turnos.Include(t => t.Especialidad).Include(t => t.Medico).Include(t => t.ObraSocial);
return View(await turnos.ToListAsync());
}
// GET: Turnos/Details/5
public async Task<ActionResult> Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Turno turno = await db.Turnos.FindAsync(id);
if (turno == null)
{
return HttpNotFound();
}
return View(turno);
}
// GET: Turnos/Create
public ActionResult Create()
{
ViewBag.EspecialidadId = new SelectList(db.Especialidades, "Id", "Nombre");
ViewBag.MedicoId = new SelectList(db.Medicos, "Id", "Nombre");
ViewBag.ObraSocialId = new SelectList(db.ObrasSociales, "Id", "Nombre");
return View();
}
// POST: Turnos/Create
// Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que quiere enlazarse. Para obtener
// más detalles, vea https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Id,MedicoId,EspecialidadId,ObraSocialId,Estado,FechaHora,Costo,Sobreturno,TieneObraSocial")] Turno turno)
{
if (ModelState.IsValid)
{
db.Turnos.Add(turno);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.EspecialidadId = new SelectList(db.Especialidades, "Id", "Nombre", turno.EspecialidadId);
ViewBag.MedicoId = new SelectList(db.Medicos, "Id", "Nombre", turno.MedicoId);
ViewBag.ObraSocialId = new SelectList(db.ObrasSociales, "Id", "Nombre", turno.ObraSocialId);
return View(turno);
}
// GET: Turnos/Edit/5
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Turno turno = await db.Turnos.FindAsync(id);
if (turno == null)
{
return HttpNotFound();
}
ViewBag.EspecialidadId = new SelectList(db.Especialidades, "Id", "Nombre", turno.EspecialidadId);
ViewBag.MedicoId = new SelectList(db.Medicos, "Id", "Nombre", turno.MedicoId);
ViewBag.ObraSocialId = new SelectList(db.ObrasSociales, "Id", "Nombre", turno.ObraSocialId);
return View(turno);
}
// POST: Turnos/Edit/5
// Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que quiere enlazarse. Para obtener
// más detalles, vea https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "Id,MedicoId,EspecialidadId,ObraSocialId,Estado,FechaHora,Costo,Sobreturno,TieneObraSocial")] Turno turno)
{
if (ModelState.IsValid)
{
db.Entry(turno).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.EspecialidadId = new SelectList(db.Especialidades, "Id", "Nombre", turno.EspecialidadId);
ViewBag.MedicoId = new SelectList(db.Medicos, "Id", "Nombre", turno.MedicoId);
ViewBag.ObraSocialId = new SelectList(db.ObrasSociales, "Id", "Nombre", turno.ObraSocialId);
return View(turno);
}
// GET: Turnos/Delete/5
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Turno turno = await db.Turnos.FindAsync(id);
if (turno == null)
{
return HttpNotFound();
}
return View(turno);
}
// POST: Turnos/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
Turno turno = await db.Turnos.FindAsync(id);
db.Turnos.Remove(turno);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
using Microsoft.master2.model;
using Microsoft.master2.rules;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TinyMessenger;
namespace Microsoft.master2.messagebus
{
class MethodMessage : ITinyMessage
{
private CSharpMethod cSharpMethod;
public CSharpMethod CSharpMethod
{
get { return cSharpMethod; }
set { cSharpMethod = value; }
}
public object Sender { get; private set; }
}
}
|
using System;
using System.Threading;
using System.Threading.Tasks;
using M220N.Models.Responses;
using M220N.Repositories;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
namespace M220N.Controllers
{
public class MovieController : Controller
{
private readonly MoviesRepository _movieRepository;
public MovieController(MoviesRepository movieRepository)
{
_movieRepository = movieRepository;
}
/// <summary>
/// Returns the Movie with matching ID
/// </summary>
/// <param name="movieId">A string of the _id value of a movie</param>
/// <param name="cancellationToken">Allows the UI to cancel an asynchronous request. Optional.</param>
/// <returns></returns>
[HttpGet("api/v1/movies/getmovie/")]
[HttpGet("api/v1/movies/id/{movieId}")]
public async Task<ActionResult> GetMovieAsync(string movieId, CancellationToken cancellationToken = default)
{
var matchedMovie = await _movieRepository.GetMovieAsync(movieId, cancellationToken);
if (matchedMovie == null) return BadRequest(new ErrorResponse("Not found"));
return Ok(new MovieResponse(matchedMovie));
}
/// <summary>
/// Finds a specified number of movies documents in a given sort order.
/// </summary>
/// <param name="limit">The maximum number of documents to be returned. Defaults to 10.</param>
/// <param name="page">The page number to retrieve. Defaults to 0.</param>
/// <param name="sort">The sorting criteria. Defaults to "title".</param>
/// <param name="sortDirection">The direction of the sort. Defaults to 1 (ascending).</param>
/// <param name="cancellationToken">Allows the UI to cancel an asynchronous request. Optional.</param>
/// <returns></returns>
[HttpGet("api/v1/movies/")]
[HttpGet("api/v1/movies/search")]
[HttpGet("api/v1/movies/getmovies")]
public async Task<ActionResult> GetMoviesAsync(int limit = 20, [FromQuery(Name = "page")] int page = 0,
string sort = "tomatoes.viewers.numReviews", int sortDirection = -1,
CancellationToken cancellationToken = default)
{
var movies = await _movieRepository.GetMoviesAsync(limit, page, sort, sortDirection, cancellationToken);
var movieCount = page == 0 ? await _movieRepository.GetMoviesCountAsync() : -1;
return Ok(new MovieResponse(movies, movieCount, page, null));
}
/// <summary>
/// Return all movies that match one or more countries specified
/// </summary>
/// <param name="cancellationToken">Allows the UI to cancel an asynchronous request. Optional.</param>
/// <param name="countries">a comma-delimited list of country names</param>
/// <returns>A BsonDocument that contains a list of matching movies</returns>
[HttpGet("api/v1/movies/countries")]
public async Task<ActionResult> GetMoviesByCountryAsync(
CancellationToken cancellationToken = default,
params string[] countries)
{
var movies = await _movieRepository.GetMoviesByCountryAsync(cancellationToken, countries);
return Ok(new MovieResponse(movies, -1L, 0, null));
}
/// <summary>
/// Finds movies based on the provided search string
/// </summary>
/// <param name="cancellationToken">Allows the UI to cancel an asynchronous request. Optional.</param>
/// <param name="page">The page to return.</param>
/// <param name="text">The text by which to search movies</param>
/// <returns></returns>
[HttpGet("api/v1/movies/search")]
public async Task<ActionResult> GetMoviesByTextAsync(CancellationToken cancellationToken = default,
int page = 0, [RequiredFromQuery] params string[] text)
{
var movies =
await _movieRepository.GetMoviesByTextAsync(page: page, keywords: text,
cancellationToken: cancellationToken);
return Ok(new MovieResponse(movies, await _movieRepository.GetMoviesCountAsync(), 0, null));
}
/// <summary>
/// Returns all movies that contain one or more of the specified cast members
/// </summary>
/// <param name="cancellationToken">Allows the UI to cancel an asynchronous request. Optional.</param>
/// <param name="page">The page to return</param>
/// <param name="cast">The cast member(s) to search for</param>
/// <returns></returns>
[HttpGet("api/v1/movies/search")]
public async Task<ActionResult> GetMoviesByCastAsync(CancellationToken cancellationToken = default,
int page = 0, [RequiredFromQuery] params string[] cast)
{
//TODO Ticket: Subfield Text Search - implement the expected cast
// filter and sort
var movies =
await _movieRepository.GetMoviesByCastAsync(page: page, cast: cast,
cancellationToken: cancellationToken);
return Ok(new MovieResponse(movies, await _movieRepository.GetMoviesCountAsync(), 0, null));
}
/// <summary>
/// Finds movies by their genre
/// </summary>
/// <param name="cancellationToken">Allows the UI to cancel an asynchronous request. Optional.</param>
/// <param name="page">The page to return</param>
/// <param name="genre">The genre(s) to filter by</param>
/// <returns></returns>
[HttpGet("api/v1/movies/search")]
public async Task<ActionResult> GetMoviesByGenreAsync(CancellationToken cancellationToken = default,
int page = 0, [RequiredFromQuery] params string[] genre)
{
var movies =
await _movieRepository.GetMoviesByGenreAsync(page: page, genres: genre,
cancellationToken: cancellationToken);
return Ok(new MovieResponse(movies, await _movieRepository.GetMoviesCountAsync(), 0, null));
}
/// <summary>
/// Finds movies by cast members.
/// </summary>
/// <param name="cast">The cast members to search for</param>
/// <param name="page">The page to return</param>
/// <param name="cancellationToken">Allows the UI to cancel an asynchronous request. Optional.</param>
/// <returns></returns>
[HttpGet("api/v1/movies/facet-search")]
public async Task<ActionResult> GetMoviesCastFacetedAsync(string cast, int page,
CancellationToken cancellationToken = default)
{
var moviesInfo = await _movieRepository.GetMoviesCastFacetedAsync(cast, page, cancellationToken);
return Ok(new MovieResponse(moviesInfo, page, null));
}
[HttpGet("api/v1/movies/config-options")]
public ActionResult GetConfigOptions()
{
return Ok(new ConfigResponse(_movieRepository.GetConfig()));
}
}
}
|
using UnityEngine;
/// <summary>
/// A GUI toggle button for controlling whether or not a field player
/// is controlled by human user input or computer AI.
/// </summary>
public class PlayerControlToggleButton : MonoBehaviour
{
#region Public Fields
/// <summary>
/// Whether or not the toggle button is right-aligned on the screen.
/// If not, the button will be left-aligned.
/// </summary>
public bool RightAligned = false;
/// <summary>
/// The style of the toggle button GUI.
/// </summary>
public GUIStyle ToggleButtonStyle;
/// <summary>
/// The field player controlled by this button.
/// </summary>
public FieldTeam Team;
#endregion
#region Private Fields
/// <summary>
/// Whether or not the attached player should be controlled by computer AI.
/// </summary>
private bool m_useComputerAi = false;
#endregion
#region GUI Methods
/// <summary>
/// Displays the toggle GUI button and allows users to alter
/// its state to switch the attached player from being controlled
/// by human user input or computer AI.
/// </summary>
private void OnGUI()
{
// CALCULATE THE BOUNDING RECTANGLE POSITION OF THE TOGGLE BUTTON.
const float TOGGLE_BUTTON_TOP_Y_POSITION = 0.0f;
const float TOGGLE_BUTTON_WIDTH = 128.0f;
const float TOGGLE_BUTTON_HEIGHT = 64.0f;
Rect toggleButtonBoundingRectangle;
if (RightAligned)
{
// ALIGN THE TOGGLE BUTTON AT THE RIGHT OF THE SCREEN.
float toggleButtonLeftXPosition = Screen.width - TOGGLE_BUTTON_WIDTH;
toggleButtonBoundingRectangle = new Rect(
toggleButtonLeftXPosition,
TOGGLE_BUTTON_TOP_Y_POSITION,
TOGGLE_BUTTON_WIDTH,
TOGGLE_BUTTON_HEIGHT);
}
else
{
// ALIGN THE TOGGLE BUTTON AT THE LEFT OF THE SCREEN.
float toggleButtonLeftXPosition = 0.0f;
toggleButtonBoundingRectangle = new Rect(
toggleButtonLeftXPosition,
TOGGLE_BUTTON_TOP_Y_POSITION,
TOGGLE_BUTTON_WIDTH,
TOGGLE_BUTTON_HEIGHT);
}
// DRAW THE TOGGLE BUTTON BASED ON THE ATTACHED PLAYER'S CURRENT MOVEMENT SETTING.
m_useComputerAi = GUI.Toggle(toggleButtonBoundingRectangle, m_useComputerAi, "CPU AI");
// UPDATE THE ATTACHED PLAYER'S MOVEMENT SETTING.
if (m_useComputerAi)
{
Team.UseComputerControl();
}
else
{
Team.UseHumanControl();
}
}
#endregion
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WeSplit
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Trip.Children.Clear();
Trip.Children.Add(new Home());
}
private void ButtonOpenMenu_Click(object sender, RoutedEventArgs e)
{
if (Menu.Width.ToString().Equals("60"))
{
Menu.Width = 240;
}
else
{
Menu.Width = 60;
}
}
private void MoveCursorMenu(int index)
{
TrainsitionigContentSlide.OnApplyTemplate();
GridCursor.Margin = new Thickness(0, (0 + (60 * index)), 0, 0);
}
private void itemMenu_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
int index = itemMenu.SelectedIndex;
if (index != 0)
{
MoveCursorMenu(index);
}
switch (index)
{
case 1:
NewTrips t = new NewTrips();
t.Show();
this.Close();
break;
case 2:
Trip.Children.Clear();
Trip.Children.Add(new Home());
break;
case 3:
Trip.Children.Clear();
Trip.Children.Add(new Finish());
break;
case 4:
Trip.Children.Clear();
Trip.Children.Add(new Notebook());
break;
case 5:
Trip.Children.Clear();
Trip.Children.Add(new About());
break;
case 6:
Trip.Children.Clear();
Trip.Children.Add(new Help());
break;
case 7:
Trip.Children.Clear();
Trip.Children.Add(new Setting());
break;
default:
break;
}
}
private void ButtonNew_Click(object sender, RoutedEventArgs e)
{
NewTrips t = new NewTrips();
t.Show();
this.Close();
}
}
} |
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class camera_control : MonoBehaviour {
public GameObject ship;
public byte rotation_speed=70;
public byte zoom_speed=50;
public bool special=false;
public Transform satellite;
public GameObject cam;
// Use this for initialization
void Awake () {
if (!satellite) satellite=transform.GetChild(0);
if (!cam) {cam=satellite.transform.GetChild(0).gameObject;}
Global.cam=cam;
GameObject env_cam=GameObject.Find("menu").GetComponent<SceneResLoader>().environmental_camera;
if (env_cam) {env_cam.GetComponent<env_camera>().c_satellite=satellite;}
}
// Update is called once per frame
void LateUpdate () {
if (ship!=null) transform.position=ship.transform.position;
if (!special) {rotation_speed=Global.cam_rot_speed;zoom_speed=Global.cam_zoom_speed;}
if (Input.GetMouseButton(2)) {
satellite.RotateAround(transform.position,transform.TransformDirection(Vector3.up),rotation_speed*Input.GetAxis("Mouse X"));
satellite.RotateAround(transform.position,satellite.transform.TransformDirection(Vector3.left),rotation_speed*Input.GetAxis("Mouse Y"));
}
if (Input.GetKey(KeyCode.KeypadDivide)) { satellite.RotateAround(transform.position,transform.TransformDirection(Vector3.up),rotation_speed/30);}
if (Input.GetKey(KeyCode.KeypadMultiply)) { satellite.RotateAround(transform.position,transform.TransformDirection(Vector3.up),-rotation_speed/30);}
if (Input.GetKey(KeyCode.KeypadPlus)) { cam.transform.Translate(0,0,zoom_speed/30,cam.transform);}
if (Input.GetKey(KeyCode.KeypadMinus)) { cam.transform.Translate(0,0,-zoom_speed/30,cam.transform);}
if (Input.GetKey(KeyCode.Insert)) { satellite.RotateAround(transform.position,satellite.transform.TransformDirection(Vector3.left),-rotation_speed/30);}
if (Input.GetKey(KeyCode.Delete)) { satellite.RotateAround(transform.position,satellite.transform.TransformDirection(Vector3.left),rotation_speed/30);}
float sw=Input.GetAxis("Mouse ScrollWheel");
if (sw!=0) {cam.transform.Translate(0,0,sw*zoom_speed,cam.transform);}
}
public void SetShip (GameObject a) {
ship=a;transform.position=ship.transform.position;
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Автошкола
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
FormsNames[0] = "Setting";
FormsNames[1] = "GroupsForm";
FormsNames[2] = "AuditoriumsForm";
FormsNames[3] = "WorkersForm";
FormsNames[4] = "TheoryTeachersForm";
FormsNames[5] = "ServiceMastersForm";
FormsNames[6] = "CarriersForm";
FormsNames[7] = "CategoriesForm";
FormsNames[8] = "TransmissionsForm";
FormsNames[9] = "CarriersStatusesForm";
FormsNames[10] = "CarriersRepairsForm";
FormsNames[11] = "JournalUsesForm";
FormsNames[12] = "CurrentStatusesForm";
FormsNames[13] = "StudentsScheduleForm";
FormsNames[14] = "GroupsScheduleForm";
FormsNames[15] = "InstructorsScheduleForm";
FormsNames[16] = "TheoryTeachersScheduleForm";
FormsNames[17] = "InstructorsCategoriesForm";
FormsNames[18] = "CarriersUsesForm";
FormsNames[19] = "ReplacementCarriers";
FormsNames[20] = "AboutProgramForm";
FormsNames[21] = "InstructorsForm";
}
public BusinessLogic BusinessLogic = new BusinessLogic();
AutoschoolDataSet dataSet;
string GroupName = "";
string LastSearchingText = "";
int LastFoundRow = -1;
int LastSelectionIndex;
GroupsForm GroupsForm;
static bool GroupsFormOpened = false;
AuditoriumsForm AuditoriumsForm;
static bool AuditoriumsFormOpened = false;
WorkersForm WorkersForm;
static bool WorkersFormOpened = false;
CarriersForm CarriersForm;
static bool CarriersFormOpened = false;
CategoriesForm CategoriesForm;
static bool CategoriesFormOpened = false;
TransmissionsForm TransmissionsForm;
static bool TransmissionsFormOpened = false;
CarriersStatusesForm CarriersStatusesForm;
static bool CarriersStatusesFormOpened = false;
InstructorsCategoriesForm InstructorsCategoriesForm;
static bool InstructorsCategoriesFormOpened = false;
CarriersUsesForm CarriersUsesForm;
static bool CarriersUsesFormOpened = false;
StudentsScheduleForm StudentsScheduleForm;
static bool StudentsScheduleFormOpened = false;
InstructorsScheduleForm InstructorsScheduleForm;
static bool InstructorsScheduleFormOpened = false;
GroupsScheduleForm GroupsScheduleForm;
static bool GroupsScheduleFormOpened = false;
TheoryTeachersScheduleForm TheoryTeachersScheduleForm;
static bool TheoryTeachersScheduleFormOpened = false;
ReplacementsCarriersForm ReplacementsCarriersForm;
static bool ReplacementsCarriersFormOpened = false;
CarriersRepairsForm CarriersRepairsForm;
static bool CarriersRepairsFormOpened = false;
TheoryTeachersForm TheoryTeachersForm;
static bool TheoryTeachersFormOpened = false;
ServiceMastersForm ServiceMastersForm;
static bool ServiceMastersFormOpened = false;
JournalUsesForm JournalUsesForm;
static bool JournalUsesFormOpened = false;
AboutProgramForm AboutProgramForm;
static bool AboutProgramFormOpened = false;
CurrentStatusesForm CurrentStatusesForm;
static bool CurrentStatusesFormOpened = false;
InstructorsForm InstructorsForm;
static bool InstructorsFormOpened = false;
// здесь храним названия всех форм, открывающихся с главного окна
static public string[] FormsNames = new string[22];
public static void Perem(string s, bool b)
{
switch (s)
{
/*case "Setting":
GroupsFormOpened = b;
break;*/
case "GroupsForm":
GroupsFormOpened = b;
break;
case "AuditoriumsForm":
AuditoriumsFormOpened = b;
break;
case "WorkersForm":
WorkersFormOpened = b;
break;
case "TheoryTeachersForm":
TheoryTeachersFormOpened = b;
break;
case "ServiceMastersForm":
ServiceMastersFormOpened = b;
break;
case "CarriersForm":
CarriersFormOpened = b;
break;
case "CategoriesForm":
CategoriesFormOpened = b;
break;
case "TransmissionsForm":
TransmissionsFormOpened = b;
break;
case "CarriersStatusesForm":
CarriersStatusesFormOpened = b;
break;
case "CarriersRepairsForm":
CarriersRepairsFormOpened = b;
break;
case "JournalUsesForm":
JournalUsesFormOpened = b;
break;
case "CurrentStatusesForm":
CurrentStatusesFormOpened = b;
break;
case "StudentsScheduleForm":
StudentsScheduleFormOpened = b;
break;
case "GroupsScheduleForm":
GroupsScheduleFormOpened = b;
break;
case "InstructorsScheduleForm":
InstructorsScheduleFormOpened = b;
break;
case "TheoryTeachersScheduleForm":
TheoryTeachersScheduleFormOpened = b;
break;
case "InstructorsCategoriesForm":
InstructorsCategoriesFormOpened = b;
break;
case "CarriersUsesForm":
CarriersUsesFormOpened = b;
break;
case "ReplacementCarriers":
ReplacementsCarriersFormOpened = b;
break;
case "AboutProgramForm":
AboutProgramFormOpened = b;
break;
case "InstructorsForm":
InstructorsFormOpened = b;
break;
}
}
void ReloadStudents(string NameOfGroup)
{
dataSet = BusinessLogic.ReadStudentsOfGroup(NameOfGroup);
Students_dGV.DataSource = dataSet;
Students_dGV.DataMember = "Students";
Students_dGV.Columns["ID"].Visible = false;
Students_dGV.Columns["Surname"].Visible = false;
Students_dGV.Columns["FirstName"].Visible = false;
Students_dGV.Columns["PatronymicName"].Visible = false;
Students_dGV.Columns["PhoneNumber"].Visible = false;
Students_dGV.Columns["Retraining"].Visible = false;
Students_dGV.Columns["Group"].Visible = false;
Students_dGV.Columns["CarrierUse"].Visible = false;
Students_dGV.Columns["Photo"].Visible = false;
Students_dGV.Columns["FIO"].Visible = false;
Students_dGV.Columns["InstructorName"].Visible = false;
Students_dGV.Columns["CarrierName"].Visible = false;
IDColumn.DataPropertyName = "ID";
FIOColumn.DataPropertyName = "FIO";
PhoneNumberColumn.DataPropertyName = "PhoneNumber";
RetrainingColumn.DataPropertyName = "Retraining";
GroupColumn.DataSource = dataSet.Groups;
GroupColumn.DisplayMember = "Name";
GroupColumn.ValueMember = "ID";
GroupColumn.DataPropertyName = "Group";
CarrierUseColumn.DataPropertyName = "CarrierUse";
InstructorColumn.DataPropertyName = "InstructorName";
CarrierColumn.DataPropertyName = "CarrierName";
}
void ReloadGroups()
{
string temp = "";
string tempParent = "";
// забираем год и название той группы, которая выделена на текущий момент
if (Groups_treeView.SelectedNode != null && Groups_treeView.SelectedNode.Level == 1)
{
temp = Groups_treeView.SelectedNode.Text;
tempParent = Groups_treeView.SelectedNode.Parent.Text;
}
else
{
temp = "";
tempParent = "";
}
// очищаем дерево
Groups_treeView.Nodes.Clear();
// читаем все группы
dataSet = BusinessLogic.ReadGroups();
// перебираем все группы
for (int i = 0; i < dataSet.Groups.Rows.Count; i++)
{
// берем год группы из даты начала обучения
int year = Convert.ToDateTime(dataSet.Groups.Rows[i][2].ToString()).Year;
bool Find = false;
for (int j = 0; j < Groups_treeView.Nodes.Count; j++)
{
// если такой год уже есть в дереве
if (Convert.ToInt32(Groups_treeView.Nodes[j].Text) == year)
{
Find = true;
// добавляем в уже существующую ветку
Groups_treeView.Nodes[j].Nodes.Add(dataSet.Groups.Rows[i][1].ToString(), dataSet.Groups.Rows[i][1].ToString());
break;
}
}
// если такой год не был найден в дереве
if (!Find)
{
// создаем новую ветку, и добавляем в нее
TreeNode TempNode = Groups_treeView.Nodes.Add(year.ToString(), year.ToString());
TempNode.Nodes.Add(dataSet.Groups.Rows[i][1].ToString(), dataSet.Groups.Rows[i][1].ToString());
}
}
// если до обновления в дереве что-то было выбрано, то возвращаем это выбор
if (temp != "")
{
try
{
Groups_treeView.SelectedNode = Groups_treeView.Nodes[tempParent].Nodes[temp];
Groups_treeView.Focus();
}
catch
{
}
}
}
private void MainForm_Load(object sender, EventArgs e)
{
LastSelectionIndex = -1;
ReloadGroups();
редактироватьЗаписьОКурсантеToolStripMenuItem.Enabled = false;
удалитьКурсантаToolStripMenuItem.Enabled = false;
Students_dGV_SelectionChanged(sender, e);
}
private void Groups_treeView_AfterSelect(object sender, TreeViewEventArgs e)
{
// если была выбрана группа
if (Groups_treeView.SelectedNode.Level == 1)
{
// загружаем студентов этой группы
GroupName = Groups_treeView.SelectedNode.Text;
ReloadStudents(GroupName);
}
else
{
GroupName = "";
}
}
private void UpdateGroups_Button_Click(object sender, EventArgs e)
{
LastSelectionIndex = -1;
ReloadGroups();
}
private void добавитьНовогоКурсантаToolStripMenuItem_Click(object sender, EventArgs e)
{
AutoschoolDataSet dataSetForAllStudent;
dataSetForAllStudent = BusinessLogic.ReadStudents();
AddEditStudentForm AddStudent;
if (GroupName != "")
AddStudent = new AddEditStudentForm(GroupName, dataSetForAllStudent.Students, dataSetForAllStudent.Groups,
dataSetForAllStudent.Instructors, null);
else
AddStudent = new AddEditStudentForm(null, dataSetForAllStudent.Students, dataSetForAllStudent.Groups,
dataSetForAllStudent.Instructors, null);
AddStudent.Text = "Добавление курсанта";
редактироватьЗаписьОКурсантеToolStripMenuItem.Enabled = false;
удалитьКурсантаToolStripMenuItem.Enabled = false;
добавитьНовогоКурсантаToolStripMenuItem.Enabled = false;
AddStudent.ShowDialog();
if (AddStudent.DialogResult == DialogResult.OK)
{
dataSetForAllStudent = BusinessLogic.WriteStudents(dataSetForAllStudent);
if (GroupName != "")
ReloadStudents(GroupName);
}
добавитьНовогоКурсантаToolStripMenuItem.Enabled = true;
Students_dGV_SelectionChanged(sender, e);
}
private void редактироватьЗаписьОКурсантеToolStripMenuItem_Click(object sender, EventArgs e)
{
if (Students_dGV.SelectedRows.Count <= 0)
{
MessageBox.Show("Не выбрана строка для редактирования", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
AutoschoolDataSet dataSetForAllStudent;
dataSetForAllStudent = BusinessLogic.ReadStudents();
AddEditStudentForm EditStudent;
if (GroupName != "")
EditStudent = new AddEditStudentForm(GroupName, dataSetForAllStudent.Students, dataSetForAllStudent.Groups,
dataSetForAllStudent.Instructors, dataSetForAllStudent.Students.Rows.Find(Students_dGV.SelectedRows[0].Cells["ID"].Value));
else
EditStudent = new AddEditStudentForm(null, dataSetForAllStudent.Students, dataSetForAllStudent.Groups,
dataSetForAllStudent.Instructors, dataSetForAllStudent.Students.Rows.Find(Students_dGV.SelectedRows[0].Cells["ID"].Value));
EditStudent.Text = "Редактирование курсанта";
EditStudent.ShowDialog();
if (EditStudent.DialogResult == DialogResult.OK)
{
dataSetForAllStudent = BusinessLogic.WriteStudents(dataSetForAllStudent);
if (GroupName != "")
ReloadStudents(GroupName);
}
}
private void удалитьКурсантаToolStripMenuItem_Click(object sender, EventArgs e)
{
if (Students_dGV.SelectedRows.Count != 1)
{
MessageBox.Show("Не выбрана строка для удаления", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
DialogResult result = MessageBox.Show("Вы действительно хотите удалить выбранную запись?", "Подтверждение удаления", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.Yes)
{
try
{
AutoschoolDataSet dataSetForAllStudent;
dataSetForAllStudent = BusinessLogic.ReadStudents();
dataSetForAllStudent.Students.Rows.Find(Students_dGV.SelectedRows[0].Cells["ID"].Value).Delete();
dataSetForAllStudent = BusinessLogic.WriteStudents(dataSetForAllStudent);
if (GroupName != "")
ReloadStudents(GroupName);
}
catch
{
MessageBox.Show("Не удалось удалить выбранную строку.\nСкорее всего, на данную строку имеются ссылки из других таблиц", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
if (GroupName != "")
ReloadStudents(GroupName);
}
}
}
private void Students_dGV_SelectionChanged(object sender, EventArgs e)
{
if (Students_dGV.SelectedRows.Count == 1)
{
редактироватьЗаписьОКурсантеToolStripMenuItem.Enabled = true;
удалитьКурсантаToolStripMenuItem.Enabled = true;
}
else
{
редактироватьЗаписьОКурсантеToolStripMenuItem.Enabled = false;
удалитьКурсантаToolStripMenuItem.Enabled = false;
}
}
private void Search_button_Click(object sender, EventArgs e)
{
SearchingInDataGridViewClass.Search(SearchStudent_textBox, ref Students_dGV, Direction_checkBox,
ref LastSearchingText, ref LastFoundRow, "FIOColumn");
}
private void SearchStudent_textBox_KeyPress(object sender, KeyPressEventArgs e)
{
if ((char)e.KeyChar == (Char)Keys.Enter)
{
Search_button_Click(sender, e);
}
if ((char)e.KeyChar == (Char)Keys.Back)
{
LastSearchingText = "";
}
}
private void учебныеГруппыToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!GroupsFormOpened)
{
GroupsForm = new GroupsForm();
GroupsForm.Show();
GroupsFormOpened = true;
}
else
{
GroupsForm.Activate();
}
}
private void учебныеАудиторииToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!AuditoriumsFormOpened)
{
AuditoriumsForm = new AuditoriumsForm();
AuditoriumsForm.Show();
AuditoriumsFormOpened = true;
}
else
{
AuditoriumsForm.Activate();
}
}
private void работаССотрудникамиToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!WorkersFormOpened)
{
WorkersForm = new WorkersForm();
WorkersForm.Show();
WorkersFormOpened = true;
}
else
{
WorkersForm.Activate();
}
}
private void учебныеТСToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!CarriersFormOpened)
{
CarriersForm = new CarriersForm();
CarriersForm.Show();
CarriersFormOpened = true;
}
else
{
CarriersForm.Activate();
}
}
private void категорииТСToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!CategoriesFormOpened)
{
CategoriesForm = new CategoriesForm();
CategoriesForm.Show();
CategoriesFormOpened = true;
}
else
{
CategoriesForm.Activate();
}
}
private void трансмиссииToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!TransmissionsFormOpened)
{
TransmissionsForm = new TransmissionsForm();
TransmissionsForm.Show();
TransmissionsFormOpened = true;
}
else
{
TransmissionsForm.Activate();
}
}
private void статусыТСToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!CarriersStatusesFormOpened)
{
CarriersStatusesForm = new CarriersStatusesForm();
CarriersStatusesForm.Show();
CarriersStatusesFormOpened = true;
}
else
{
CarriersStatusesForm.Activate();
}
}
private void категорииИнструкторовToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!InstructorsCategoriesFormOpened)
{
InstructorsCategoriesForm = new InstructorsCategoriesForm();
InstructorsCategoriesForm.Show();
InstructorsCategoriesFormOpened = true;
}
else
{
InstructorsCategoriesForm.Activate();
}
}
private void тСИнструкторовToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!CarriersUsesFormOpened)
{
CarriersUsesForm = new CarriersUsesForm();
CarriersUsesForm.Show();
CarriersUsesFormOpened = true;
}
else
{
CarriersUsesForm.Activate();
}
}
private void расписаниеКурсантаToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!StudentsScheduleFormOpened)
{
StudentsScheduleForm = new StudentsScheduleForm();
StudentsScheduleForm.Show();
StudentsScheduleFormOpened = true;
}
else
{
StudentsScheduleForm.Activate();
}
}
private void расписаниеИнструктораToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!InstructorsScheduleFormOpened)
{
InstructorsScheduleForm = new InstructorsScheduleForm();
InstructorsScheduleForm.Show();
InstructorsScheduleFormOpened = true;
}
else
{
InstructorsScheduleForm.Activate();
}
}
private void расписаниеГруппыToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!GroupsScheduleFormOpened)
{
GroupsScheduleForm = new GroupsScheduleForm();
GroupsScheduleForm.Show();
GroupsScheduleFormOpened = true;
}
else
{
GroupsScheduleForm.Activate();
}
}
private void расписаниеПреподавателяToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!TheoryTeachersScheduleFormOpened)
{
TheoryTeachersScheduleForm = new TheoryTeachersScheduleForm();
TheoryTeachersScheduleForm.Show();
TheoryTeachersScheduleFormOpened = true;
}
else
{
TheoryTeachersScheduleForm.Activate();
}
}
private void заменаТСУИнструктораToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!ReplacementsCarriersFormOpened)
{
ReplacementsCarriersForm = new ReplacementsCarriersForm();
ReplacementsCarriersForm.Show();
ReplacementsCarriersFormOpened = true;
}
else
{
ReplacementsCarriersForm.Activate();
}
}
private void выходToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private void ремонтыТСToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!CarriersRepairsFormOpened)
{
CarriersRepairsForm = new CarriersRepairsForm();
CarriersRepairsForm.Show();
CarriersRepairsFormOpened = true;
}
else
{
CarriersRepairsForm.Activate();
}
}
private void преподавателиТеорииToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!TheoryTeachersFormOpened)
{
TheoryTeachersForm = new TheoryTeachersForm();
TheoryTeachersForm.Show();
TheoryTeachersFormOpened = true;
}
else
{
TheoryTeachersForm.Activate();
}
}
private void мастераСервисаToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!ServiceMastersFormOpened)
{
ServiceMastersForm = new ServiceMastersForm();
ServiceMastersForm.Show();
ServiceMastersFormOpened = true;
}
else
{
ServiceMastersForm.Activate();
}
}
private void журналИспользованияТСToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!JournalUsesFormOpened)
{
JournalUsesForm = new JournalUsesForm();
JournalUsesForm.Show();
JournalUsesFormOpened = true;
}
else
{
JournalUsesForm.Activate();
}
}
private void оПрограммеToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!AboutProgramFormOpened)
{
AboutProgramForm = new AboutProgramForm();
AboutProgramForm.Show();
AboutProgramFormOpened = true;
}
else
AboutProgramForm.Activate();
}
private void текущиеСостоянияТСToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!CurrentStatusesFormOpened)
{
CurrentStatusesForm = new CurrentStatusesForm();
CurrentStatusesForm.Show();
CurrentStatusesFormOpened = true;
}
else
CurrentStatusesForm.Activate();
}
private void инструктораToolStripMenuItem1_Click(object sender, EventArgs e)
{
if (!InstructorsFormOpened)
{
InstructorsForm = new InstructorsForm();
InstructorsForm.Show();
InstructorsFormOpened = true;
}
else
InstructorsForm.Activate();
}
private void путьКБДToolStripMenuItem_Click(object sender, EventArgs e)
{
PathToBDForm PathToBDForm = new PathToBDForm();
PathToBDForm.ShowDialog();
}
}
}
|
using KeepTeamAutotests.Pages;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KeepTeamAutotests.Menues
{
public class SettingMenu : BaseMenu
{
[FindsBy(How = How.XPath, Using = "//ul[@class = 'b-sidebar-menu-list b-sidebar-menu-list--first'] ")]
private IWebElement Menu;
public SettingMenu(PageManager pageManager)
: base(pageManager)
{
}
public void ClickByText(String text)
{
Menu.FindElement(By.LinkText(text)).Click();
}
public void ClickByIndex(int index)
{
Menu.FindElements(By.ClassName("b-sidebar-menu-list-item"))[index].Click();
}
public void ensurePageLoaded()
{
var wait = new WebDriverWait(pageManager.driver, TimeSpan.FromSeconds(PageManager.WAITTIMEFORFINDELEMENT));
wait.Until(d => d.FindElement(By.XPath("//*[contains(@class,'b-employees-personal-header')]")));
}
}
}
|
namespace ClounceMathExamples.Helper {
using System.IO;
using System.Collections.Generic;
sealed class SampleDataLoader {
private static string path = "../../sample_data";
public static IEnumerable<IEnumerable<dynamic>> GetSamplesFromFile() {
string line;
using (StreamReader sampleData = new StreamReader(path)) {
while ((line = sampleData.ReadLine()) != null) {
if (string.IsNullOrWhiteSpace(line)) {
continue;
}
IList<dynamic> sample = new List<dynamic>();
foreach (string data in line.Split(',')) {
double.TryParse(data, out double point);
sample.Add(point);
}
yield return sample;
}
}
}
}
} |
using System;
using System.Data;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using Docller.Core.Common;
using Docller.Core.Common.DataStructures;
using Docller.Core.Models;
using Docller.Core.Repository;
using Docller.Core.Services;
using Docller.Core.Storage;
using Docller.Serialization;
using Docller.Tests;
using Docller.Tests.Mocks;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using StructureMap;
using File = Docller.Core.Models.File;
namespace Docller.UnitTests
{
[TestClass]
public class StorageServiceFixture : FixtureBase
{
/// <summary>
/// Inits the specified context.
/// </summary>
/// <param name="context">The context.</param>
[ClassInitialize]
public static void Init(TestContext context)
{
FixtureBase.RegisterMappings();
}
/// <summary>
/// Cleans up.
/// </summary>
/// <remarks></remarks>
///
[ClassCleanup]
public static void CleanUp()
{
ObjectFactory.EjectAllInstancesOf<Database>();
}
#region FileUpload Unit Test
[TestMethod]
public void Verify_GetFilesWithAttachments()
{
//Get the test filenames
List<string> fileNames = new List<string>();
using(StreamReader reader = new StreamReader(@"..\..\..\Docller.UnitTests\FileList.txt"))
{
while(!reader.EndOfStream)
{
fileNames.Add(reader.ReadLine());
}
}
IStorageService storageService = new MockStorageService(ObjectFactory.GetInstance<IStorageRepository>(), ObjectFactory.GetInstance < IBlobStorageProvider>());
IEnumerable<Core.Models.File> fileResults = storageService.GetPreUploadInfo(0,0,fileNames.ToArray(), false, false);
Assert.IsTrue(fileResults.Count() == 32, "Getting Files without attachments failed");
fileResults = storageService.GetPreUploadInfo(0, 0, fileNames.ToArray(), true, false);
Assert.IsTrue(fileResults.Count() == 20, "20 Files where expected");
var filesWithAttachments = from f in fileResults
where f.Attachments != null
select f;
Assert.IsTrue(filesWithAttachments.Count() == 12, "Exactly 12 files with attachment were expected");
foreach (var file in filesWithAttachments)
{
FileInfo fileInfo = new FileInfo(file.FileName);
FileInfo attachmentInfo = new FileInfo(file.Attachments[0].FileName);
Assert.IsTrue(
fileInfo.Name.Replace(fileInfo.Extension, string.Empty).Equals(
attachmentInfo.Name.Replace(attachmentInfo.Extension, string.Empty),
StringComparison.InvariantCultureIgnoreCase),"File names did not match");
}
}
[TestMethod]
public void Verify_GetPreUploadInfo()
{
long customerId = this.AddCustomer();
SetDocllerContext(customerId, AdminUserName);
int projectId = this.AddProject(customerId);
int folderId = this.AddFolder(customerId, projectId, 0, "Test");
IStorageService storageService = new StorageService(ObjectFactory.GetInstance<IStorageRepository>(), ObjectFactory.GetInstance<IBlobStorageProvider>());
//Get the test filenames
List<string> fileNames = new List<string>();
using (StreamReader reader = new StreamReader(@"..\..\..\Docller.UnitTests\FileList.txt"))
{
while (!reader.EndOfStream)
{
fileNames.Add(reader.ReadLine());
}
}
IEnumerable<Core.Models.File> files = storageService.GetPreUploadInfo(projectId, folderId, fileNames.ToArray(), false, false);
Assert.IsTrue(files.Count() == 32, "Getting Files without attachments failed");
//make sure we don't get anyy attachments
var noAttachments = from f in files
where f.Attachments == null || f.Attachments.Count == 0
select f;
Assert.IsTrue(noAttachments.Count() == 32, "No Attachment was expcted");
files = storageService.GetPreUploadInfo(projectId, folderId, fileNames.ToArray(), true, false);
Assert.IsTrue(files.Count() == 20, "20 Files where expected");
var filesWithAttachments = from f in files
where f.Attachments != null && f.Attachments.Count > 0
select f;
Assert.IsTrue(filesWithAttachments.Count() == 12, "Exactly 12 files with attachment were expected");
foreach (var filesWithAttachment in filesWithAttachments)
{
Core.Models.File attachment = filesWithAttachment;
var attachmednts = from fa in filesWithAttachment.Attachments
where fa.ParentFile != attachment.FileInternalName
select fa;
Assert.IsTrue(attachmednts.Count() == 0,"Found an attachment whose ParentFile is not same as FileInternalName");
}
}
[TestMethod]
public void Verify_AddingFilesAndAttachments_With_No_Revision_Extraction()
{
long customerId = this.AddCustomer();
SetDocllerContext(customerId, AdminUserName);
int projectId = this.AddProject(customerId);
int folderId = this.AddFolder(customerId, projectId, 0, "Test");
int companyId = Convert.ToInt32(this.GetValue("Companies", "CompanyId"));
Database db = GetDb();
db.ExecuteNonQuery(CommandType.Text,
string.Format(
@"UPDATE Companies SET RevisionRegEx='\s*-\s*REV\s*-\s*(?<revision>[a-zA-Z0-9]*)$' WHERE CompanyId={0}",
companyId));
IStorageService storageService = new StorageService(ObjectFactory.GetInstance<IStorageRepository>(), ObjectFactory.GetInstance<IBlobStorageProvider>());
string[] fileNames = { "63-WHR-001-03-REV-A.pdf", "63-WHR-001-03-REV-A.dwg" };
IEnumerable<Core.Models.File> files = storageService.GetPreUploadInfo(projectId, folderId, fileNames, true, false);
foreach (Core.Models.File file in files)
{
file.Project.ProjectId = projectId;
file.Folder.FolderId = folderId;
file.CustomerId = customerId;
file.ContentType = "";
storageService.AddFile(file, true, null);
//Mae sure base file name is same as filename
string baseFileName = this.GetValue("Files", "BaseFileName").ToString();
Assert.IsTrue(baseFileName.Equals(file.FileName,StringComparison.InvariantCultureIgnoreCase), "Base Filename was expected to be same as filename");
if (file.Attachments != null)
{
foreach (FileAttachment attachment in file.Attachments)
{
attachment.Project.ProjectId = projectId;
attachment.Folder.FolderId = folderId;
attachment.ParentFile = file.FileInternalName;
storageService.AddAttachment(attachment, true, null);
baseFileName = this.GetValue("FileAttachments", "BaseFileName").ToString();
Assert.IsTrue(baseFileName.Equals(attachment.FileName, StringComparison.InvariantCultureIgnoreCase), "Base Filename was expected to be same as filename");
}
}
}
}
[TestMethod]
public void Verify_AddingFilesAndAttachments_With_Revision_In_FileName()
{
long customerId = this.AddCustomer();
SetDocllerContext(customerId, AdminUserName);
int projectId = this.AddProject(customerId);
int folderId = this.AddFolder(customerId, projectId, 0, "Test");
int companyId = Convert.ToInt32(this.GetValue("Companies", "CompanyId"));
Database db = GetDb();
db.ExecuteNonQuery(CommandType.Text,
string.Format(
@"UPDATE Companies SET RevisionRegEx='\s*-\s*REV\s*-\s*(?<revision>[a-zA-Z0-9]*)$' WHERE CompanyId={0}",
companyId));
IStorageService storageService = new StorageService(ObjectFactory.GetInstance<IStorageRepository>(), ObjectFactory.GetInstance<IBlobStorageProvider>());
string[] fileNames = { "63-WHR-001-03-REV-A.pdf", "63-WHR-001-03-REV-A.dwg" };
IEnumerable<Core.Models.File> files = storageService.GetPreUploadInfo(projectId, folderId, fileNames, true, true);
foreach (Core.Models.File file in files)
{
file.Project.ProjectId = projectId;
file.Folder.FolderId = folderId;
file.CustomerId = customerId;
storageService.AddFile(file, true, null);
if(file.Attachments != null)
{
foreach (FileAttachment attachment in file.Attachments)
{
attachment.Project.ProjectId = projectId;
attachment.Folder.FolderId = folderId;
attachment.ParentFile = file.FileInternalName;
storageService.AddAttachment(attachment, true, null);
}
}
}
int count = this.GetCount("Files");
Assert.IsTrue(count == 1, "Only one file was expected");
string[] versions = {"B", "C", "D", "E", "F", "G"};
for(int index = 0; index < versions.Length; index++)
{
string version = versions[index];
string[] newVersionfileName = { "63-WHR-001-03-REV- A.pdf".Replace("A", version), "63-WHR-001-03-REV- A.dwg".Replace("A", version) };
files = storageService.GetPreUploadInfo(projectId, folderId, newVersionfileName, true, true );
foreach (Core.Models.File file in files)
{
file.Project.ProjectId = projectId;
file.Folder.FolderId = folderId;
file.CustomerId = customerId;
storageService.AddFile(file, true, "fubar");
int rev = Convert.ToInt32(this.GetValue("Files", "CurrentRevision",
string.Format("WHERE FileInternalName = '{0}'", file.FileInternalName)));
Assert.IsTrue(rev == index + 2, "Revision for FileName" + file.FileName + " did not have currect revision number");
if (file.Attachments != null)
{
foreach (FileAttachment attachment in file.Attachments)
{
attachment.Project.ProjectId = projectId;
attachment.Folder.FolderId = folderId;
attachment.ParentFile = file.FileInternalName;
StorageServiceStatus status = storageService.AddAttachment(attachment, true, null);
Assert.IsTrue(status == StorageServiceStatus.VersionPathNull, "VersionPathNull was expected");
storageService.AddAttachment(attachment, true, "fubar");
rev = Convert.ToInt32(this.GetValue("FileAttachments", "RevisionNumber",
string.Format("WHERE FileId = {0} ORDER BY CreatedDate DESC", file.FileId)));
Assert.IsTrue(rev == index + 2, "Revision for FileName" + file.FileName + " did not have currect revision number");
}
}
}
}
}
[TestMethod]
public void Verify_AddingFiles_With_NoAttachments_And_SameNames()
{
long customerId = this.AddCustomer();
SetDocllerContext(customerId, AdminUserName);
int projectId = this.AddProject(customerId);
int folderId = this.AddFolder(customerId, projectId, 0, "Test");
IStorageService storageService = new StorageService(ObjectFactory.GetInstance<IStorageRepository>(), ObjectFactory.GetInstance<IBlobStorageProvider>());
//Get the test filenames
List<string> fileNames = new List<string>();
using (StreamReader reader = new StreamReader(@"..\..\..\Docller.UnitTests\FileList.txt"))
{
while (!reader.EndOfStream)
{
fileNames.Add(reader.ReadLine());
}
}
IEnumerable<Core.Models.File> files = storageService.GetPreUploadInfo(projectId, folderId, fileNames.ToArray(), false, true);
foreach (Core.Models.File file in files)
{
file.Project.ProjectId = projectId;
file.Folder.FolderId = folderId;
file.CustomerId = customerId;
file.ContentType = "fubar";
storageService.AddFile(file, true, null);
}
int count = this.GetCount("Files");
Assert.IsTrue(count == 32, "Exactly 32 files were expected to be added to the DB");
files = storageService.GetPreUploadInfo(projectId, folderId, fileNames.ToArray(), false, true);
foreach (Core.Models.File file in files)
{
file.Project.ProjectId = projectId;
file.Folder.FolderId = folderId;
file.CustomerId = customerId;
//Try adding the file with the same name but version as false
file.ContentType = "fubar";
StorageServiceStatus status = storageService.AddFile(file, false, null);
Assert.IsTrue(status==StorageServiceStatus.ExistingFile,"Status was expected to be Exisiting file");
storageService.AddFile(file, true, "fubar");
}
Assert.IsTrue(count == 32, "Exactly 32 files were expected to be added to the DB");
foreach (Core.Models.File file in files)
{
int rev =
Convert.ToInt32(this.GetValue("Files", "CurrentRevision",
string.Format("WHERE FileInternalName = '{0}'", file.FileInternalName)));
Assert.IsTrue(rev == 2, string.Format("CurrentRevision for {0} is not 2",file.FileName));
}
}
[TestMethod]
public void Verify_AddingFiles_And_Attachments()
{
long customerId = this.AddCustomer();
SetDocllerContext(customerId, AdminUserName);
int projectId = this.AddProject(customerId);
int folderId = this.AddFolder(customerId, projectId, 0, "Test");
IStorageService storageService = new StorageService(ObjectFactory.GetInstance<IStorageRepository>(), ObjectFactory.GetInstance<IBlobStorageProvider>());
//Get the test filenames
List<string> fileNames = new List<string>();
using (StreamReader reader = new StreamReader(@"..\..\..\Docller.UnitTests\FileList.txt"))
{
while (!reader.EndOfStream)
{
fileNames.Add(reader.ReadLine());
}
}
IEnumerable<Core.Models.File> files = storageService.GetPreUploadInfo(projectId, folderId, fileNames.ToArray(), true, false);
foreach (Core.Models.File file in files)
{
file.Project.ProjectId = projectId;
file.Folder.FolderId = folderId;
file.CustomerId = customerId;
file.ContentType = "fubar";
storageService.AddFile(file, true, null);
if(file.Attachments != null)
{
foreach (FileAttachment attachment in file.Attachments)
{
Assert.IsFalse(attachment.ParentFile.Equals(Guid.Empty), "ParentFile is null in " + attachment.FileName);
attachment.Project.ProjectId = projectId;
attachment.Folder.FolderId = folderId;
attachment.ParentFile = file.FileInternalName;
attachment.ContentType = "fubar";
storageService.AddAttachment(attachment,true,null);
int revision =
Convert.ToInt32(this.GetValue("FileAttachments", "RevisionNumber",
string.Format("WHERE FileId={0} ORDER BY CreatedDate DESC", file.FileId)));
Assert.IsTrue(revision == 1, "Number for Attachments were expected to be 1");
//Add a Version of the Same File
storageService.AddFile(file, true, "fubar");
//Add another version of the attachment
StorageServiceStatus storageServiceStatus = storageService.AddAttachment(attachment, false, null);
Assert.IsTrue(storageServiceStatus == StorageServiceStatus.ExistingFile,"Status was expected to be existing file");
storageService.AddAttachment(attachment, true, "Fubar");
int count = this.GetCount("FileAttachments",
string.Format("WHERE FileId={0}", file.FileId));
Assert.IsTrue(count == 2, "Two attachments were expected");
revision =
Convert.ToInt32(this.GetValue("FileAttachments", "RevisionNumber",
string.Format("WHERE FileId={0} ORDER BY CreatedDate DESC", file.FileId)));
Assert.IsTrue(revision == 2, "Number for Attachments were expected to be 2 for " + attachment.FileName);
}
}
}
}
[TestMethod]
public void Verify_Add_File_DocNumber()
{
long customerId = this.AddCustomer();
SetDocllerContext(customerId, AdminUserName);
int projectId = this.AddProject(customerId);
int folderId = this.AddFolder(customerId, projectId, 0, "Test");
IStorageService storageService = new StorageService(ObjectFactory.GetInstance<IStorageRepository>(), ObjectFactory.GetInstance<IBlobStorageProvider>());
//Get the test filenames
List<string> fileNames = new List<string>();
using (StreamReader reader = new StreamReader(@"..\..\..\Docller.UnitTests\FileList.txt"))
{
while (!reader.EndOfStream)
{
fileNames.Add(reader.ReadLine());
break;
}
}
Core.Models.File fileToAdd = storageService.GetPreUploadInfo(projectId, folderId, fileNames.ToArray(), true, false).First();
fileToAdd.Project.ProjectId = projectId;
fileToAdd.Folder.FolderId = folderId;
fileToAdd.CustomerId = customerId;
fileToAdd.ContentType = "fubar";
storageService.AddFile(fileToAdd, true, null);
string documber = this.GetValue("Files", "DocNumber").ToString();
FileInfo fileInfo = new FileInfo(fileToAdd.FileName);
string expectedDocNum = fileToAdd.BaseFileName.Replace(fileInfo.Extension, string.Empty);
Assert.IsTrue(documber.Equals(expectedDocNum, StringComparison.InvariantCultureIgnoreCase), "DocNUmber is not what was expected");
}
#endregion
#region Folders Unit Test
[TestMethod]
public void Verify_TreeStructure()
{
Tree<Folder> tree = new Tree<Folder>(new Folder() { FolderInternalName = "Root" });
tree.AddChild(new Folder() { FolderInternalName = "Architecture" });
tree.AddChild(new Folder() { FolderInternalName = "Services" });
tree.AddChild(new Folder() { FolderInternalName = "Submittals" });
Tree<Folder> architecture = tree.GetChild(1);
architecture.AddChild(new Folder() { FolderInternalName = "HV" });
architecture.AddChild(new Folder() { FolderInternalName = "Saousorus" });
// Tree<Folder>.Traverse(tree, new Action<Folder>(OnAction));
}
[TestMethod]
public void Verify_AddingFolder()
{
long customerId = this.AddCustomer();
SetDocllerContext(customerId, AdminUserName);
int projectId = this.AddProject(customerId);
IStorageService storageService = ServiceFactory.GetStorageService(customerId);
List<Folder> folders = new List<Folder>();
for (int i = 0; i < 10; i++)
{
folders.Add(new Folder() { FolderName = "Folder" + i });
}
FolderCreationStatus creationStatus = storageService.CreateFolders(AdminUserName, projectId, folders);
Assert.IsTrue(creationStatus.Status == StorageServiceStatus.Success, "Should have been success");
Assert.IsTrue(creationStatus.DuplicateFolders == null || creationStatus.DuplicateFolders.Count() == 0, "Should not have duplicate folders");
int folderCount = this.GetCount("Folders");
Assert.IsTrue(folderCount == 10, "10 Folders were expected");
int permissionsCount = this.GetCount("CompanyFolderPermissions");
Assert.IsTrue(permissionsCount == 10, "10 Folder Permissions were expected");
//Get Id for a folder
int parentFolderId = Convert.ToInt32(this.GetValue("Folders", "FolderId", "WHERE FolderName = 'Folder0'"));
//Check the full path
string fullPath =
this.GetValue("Folders", "FullPath",
string.Format("Where FolderId = {0}", parentFolderId)).ToString();
Assert.IsTrue(fullPath.Equals("f-" + parentFolderId, StringComparison.CurrentCultureIgnoreCase),
"Folder Full path should be same as Folder internal name");
List<Folder> childFolders = new List<Folder>() { new Folder() { FolderName = "ChildFolder", FullPath = "FullPath" } };
storageService.CreateFolders(AdminUserName, projectId, parentFolderId, childFolders);
int childFolderCount = this.GetCount("Folders", "WHERE ParentFolderId = " + parentFolderId);
Assert.IsTrue(childFolderCount == 1);
permissionsCount = this.GetCount("CompanyFolderPermissions");
Assert.IsTrue(permissionsCount == 11, "11 Folder Permissions were expected");
//check the full path of the child folder
int childFolderId = Convert.ToInt32(this.GetValue("Folders", "FolderId", "WHERE FolderName='ChildFolder'"));
string expectedFullPath = string.Format("{0}{1}f-{2}", fullPath,
Config.GetValue<string>(ConfigKeys.AzureFolderPathSeperator),
childFolderId);
fullPath =
this.GetValue("Folders", "FullPath",
string.Format("Where FolderId = {0}", childFolderId)).ToString();
Assert.IsTrue(expectedFullPath.Equals(fullPath, StringComparison.CurrentCultureIgnoreCase),
"Folder Full path is not what was expected");
//Try adding all of them as duplicate at root level
foreach (Folder folder in folders)
{
folder.FolderId = 0;
}
creationStatus = storageService.CreateFolders(AdminUserName, projectId, folders);
Assert.IsTrue(creationStatus.Status == StorageServiceStatus.ExistingFolder, "Should have been Duplicate folders");
Assert.IsTrue(creationStatus.DuplicateFolders != null && creationStatus.DuplicateFolders.Count() == 10);
//Just ensure we still only have 10 top level folders!
folderCount = this.GetCount("Folders", "WHERE ParentFolderId IS NULL");
Assert.IsTrue(folderCount == 10, "10 Folders were expected");
//Now try and insert the same child folder into the same parent
foreach (Folder childFolder in childFolders)
{
childFolder.FolderId = 0;
}
creationStatus = storageService.CreateFolders(AdminUserName, projectId, parentFolderId, childFolders);
Assert.IsTrue(creationStatus.Status == StorageServiceStatus.ExistingFolder);
Assert.IsTrue(creationStatus.DuplicateFolders.Count == 1);
//Now try and insert the same child folder into some other parent
parentFolderId = Convert.ToInt32(this.GetValue("Folders", "FolderId", "WHERE FolderName = 'Folder1'"));
foreach (Folder childFolder in childFolders)
{
childFolder.FolderId = 0;
}
creationStatus = storageService.CreateFolders(AdminUserName, projectId, parentFolderId, childFolders);
Assert.IsTrue(creationStatus.Status == StorageServiceStatus.Success);
Assert.IsTrue(creationStatus.DuplicateFolders.Count == 0);
folderCount = this.GetCount("Folders", "WHERE ParentFolderId = " + parentFolderId);
Assert.IsTrue(folderCount == 1, "1 Folder was expected");
}
[TestMethod]
public void Verify_RenameFolder()
{
long customerId = this.AddCustomer();
SetDocllerContext(customerId, AdminUserName);
int testProjectId = this.AddProject(customerId);
IStorageService storageService = ServiceFactory.GetStorageService(customerId);
// Test For Success
int testfolderId = this.AddFolder(customerId, testProjectId, 0, "TestFolder");
StorageServiceStatus serviceStatus = storageService.RenameFolder(new Folder { ProjectId = testProjectId, ParentFolderId = 0, FolderId = testfolderId, FolderName = "RenameTest" });
Assert.IsTrue(serviceStatus == StorageServiceStatus.Success, "Status should have been success");
// Test for Parent Folder
int testChildFolderId = this.AddFolder(customerId, testProjectId, testfolderId, "ParentTestFolder");
serviceStatus = storageService.RenameFolder(new Folder { ProjectId = testProjectId, ParentFolderId = testfolderId, FolderId = testChildFolderId, FolderName = "RenameChildFolderTest" });
Assert.IsTrue(serviceStatus == StorageServiceStatus.Success, "Status should have been success");
// Rename Folder Test For Existing Folder
int folderId1 = this.AddFolder(customerId, testProjectId, 0, "Folder1");
this.AddFolder(customerId, testProjectId, 0, "Folder2");
serviceStatus = storageService.RenameFolder(new Folder { ProjectId = testProjectId, ParentFolderId = 0, FolderId = folderId1, FolderName = "Folder2" });
Assert.IsTrue(serviceStatus == StorageServiceStatus.ExistingFolder, "Status should have been ExistingFolder");
// Rename Folder Test of Existing Folder For Parent Folder
int childfolderId1 = this.AddFolder(customerId, testProjectId, testfolderId, "ChildFolder1");
this.AddFolder(customerId, testProjectId, testfolderId, "ChildFolder2");
serviceStatus = storageService.RenameFolder(new Folder { ProjectId = testProjectId, ParentFolderId = testfolderId, FolderId = childfolderId1, FolderName = "ChildFolder2" });
Assert.IsTrue(serviceStatus == StorageServiceStatus.ExistingFolder, "Status should have been ExistingFolder");
}
[TestMethod]
public void Verify_GetDefaultFolders()
{
long customerId = this.AddCustomer();
SetDocllerContext(customerId, AdminUserName);
long testProjectId = this.AddProjectViaService(customerId);
IStorageService storageService = ServiceFactory.GetStorageService(customerId);
Folders folders = storageService.GetFolders(AdminUserName, testProjectId);
Assert.IsTrue(folders.Count == 11, "11 Folders were expected");
}
[TestMethod]
public void Verify_FolderStructureAncestor()
{
long customerId = this.AddCustomer();
SetDocllerContext(customerId, AdminUserName);
long testProjectId = this.AddProjectViaService(customerId);
long folderId = Convert.ToInt64(this.GetValue("Folders", "FolderId", "WHERE FolderName='Structural'"));
int childfolderId = this.AddFolder(customerId, (int)testProjectId, (int)folderId, "ChildFolder");
int grandChild = this.AddFolder(customerId, (int)testProjectId, childfolderId,"GrandChildFolder");
int greatGrandChild = AddFolder(customerId, (int)testProjectId, grandChild,"GreatGrandChildFolder");
IStorageService storageService = ServiceFactory.GetStorageService(customerId);
Folders folders = storageService.GetFolders(AdminUserName, testProjectId);
Assert.IsTrue(folders.IsAncestor(greatGrandChild, grandChild), "GrandChildFolder was expected to be a an ancestor");
Assert.IsTrue(folders.IsAncestor(greatGrandChild, childfolderId), "ChildFolder was expected to be a an ancestor");
Assert.IsTrue(folders.IsAncestor(greatGrandChild, folderId), "Structural Folder was expected to be a an ancestor");
long anotherFolderId = Convert.ToInt64(this.GetValue("Folders", "FolderId", "WHERE FolderName='MEP'"));
Assert.IsFalse(folders.IsAncestor(greatGrandChild, anotherFolderId), "MEPS Folder was not expected to be a an ancestor");
}
[TestMethod]
public void Verify_GetDefaulFoldersWithChildren()
{
long customerId = this.AddCustomer();
SetDocllerContext(customerId, AdminUserName);
long testProjectId = this.AddProjectViaService(customerId);
IStorageService storageService = ServiceFactory.GetStorageService(customerId);
Folders folders = storageService.GetFolders(AdminUserName, testProjectId);
foreach (Folder folder in folders)
{
for(int i =0;i<10;i++)
{
int childfolderId = this.AddFolder(customerId, (int) testProjectId, (int) folder.FolderId,
string.Format("ChildFolder_{0}", i));
for(int j=0;j<5;j++)
{
int grandChild = this.AddFolder(customerId, (int)testProjectId, childfolderId,
string.Format("GrandChildFolder_{0}", j));
for(int k=0;k<2;k++)
{
AddFolder(customerId, (int)testProjectId, grandChild,
string.Format("GreatGrandChildFolder_{0}", k));
}
}
}
}
folders = storageService.GetFolders(AdminUserName, testProjectId);
Assert.IsTrue(folders.Count() == 11);
foreach (Folder folder in folders)
{
Assert.IsTrue(folder.AllParents.Count == 0, "No parent folders were expected");
Assert.IsTrue(folder.SubFolders.Count == 10, "Exactly 10 child folders were expected");
IEnumerable<Folder> childFolders = folder.SubFolders;
foreach (Folder childFolder in childFolders)
{
Assert.IsTrue(childFolder.SubFolders.Count() == 5, "Exactly 5 Grand child were expected");
Assert.IsTrue(childFolder.AllParents.Count == 1, "One parent folders were expected");
IEnumerable<Folder> grandKids = childFolder.SubFolders;
foreach (Folder grandKid in grandKids)
{
Assert.IsTrue(grandKid.SubFolders.Count() == 2, "Exactly 2 Great Grand child were expected");
Assert.IsTrue(grandKid.AllParents.Count == 2, "two parent folders were expected");
IEnumerable<Folder> greatGrandKids = grandKid.SubFolders;
foreach (Folder greatGrandKid in greatGrandKids)
{
Assert.IsTrue(greatGrandKid.AllParents.Count == 3, "3 parent folders were expected");
}
}
}
}
}
#endregion
#region File Edit Test
[TestMethod]
public void Verify_Get_FilesToEditUpload()
{
long customerId = this.AddCustomer();
SetDocllerContext(customerId, AdminUserName);
int projectId = this.AddProject(customerId);
int folderId = this.AddFolder(customerId, projectId, 0, "Test");
IStorageService storageService = new StorageService(ObjectFactory.GetInstance<IStorageRepository>(), ObjectFactory.GetInstance<IBlobStorageProvider>());
//Get the test filenames
List<string> fileNames = new List<string>();
using (StreamReader reader = new StreamReader(@"..\..\..\Docller.UnitTests\FileList.txt"))
{
while (!reader.EndOfStream)
{
fileNames.Add(reader.ReadLine());
}
}
IEnumerable<Core.Models.File> files = storageService.GetPreUploadInfo(projectId, folderId, fileNames.ToArray(), true, false);
int attachmentCounts=0;
foreach (File file in files)
{
file.Project.ProjectId = projectId;
file.Folder.FolderId = folderId;
file.CustomerId = customerId;
file.ContentType = "fubar";
storageService.AddFile(file, true, null);
if (file.Attachments != null && file.Attachments.Count == 1)
{
storageService.AddAttachment(file.Attachments[0], false, null);
attachmentCounts++;
}
}
List<File> filesToSend =
files.Select(file => new File() {FileInternalName = file.FileInternalName}).ToList();
IEnumerable<File> filesToEdit = storageService.GetFilesForEdit(new List<File>(filesToSend));
Assert.IsTrue(filesToEdit.Count() == 20, "20 Files were expected");
var attacmnents = from a in filesToEdit
where a.Attachments != null && a.Attachments.Count() > 0
select a;
Assert.IsTrue(attacmnents.Count() == attachmentCounts, "Attachment counts result is unexpected");
}
[TestMethod]
public void Verify_Update_Files()
{
long customerId = this.AddCustomer();
SetDocllerContext(customerId, AdminUserName);
int projectId = this.AddProject(customerId);
int folderId = this.AddFolder(customerId, projectId, 0, "Test");
IStorageService storageService = new StorageService(ObjectFactory.GetInstance<IStorageRepository>(), ObjectFactory.GetInstance<IBlobStorageProvider>());
//Get the test filenames
List<string> fileNames = new List<string>();
using (StreamReader reader = new StreamReader(@"..\..\..\Docller.UnitTests\FileList.txt"))
{
while (!reader.EndOfStream)
{
fileNames.Add(reader.ReadLine());
}
}
IEnumerable<Core.Models.File> files = storageService.GetPreUploadInfo(projectId, folderId, fileNames.ToArray(), false, false);
foreach (File file in files)
{
file.Project.ProjectId = projectId;
file.Folder.FolderId = folderId;
file.CustomerId = customerId;
file.ContentType = "fubar";
storageService.AddFile(file, true, null);
}
List<File> filesToSend =
files.Select(file => new File() { FileInternalName = file.FileInternalName }).ToList();
IEnumerable<File> filesToEdit = storageService.GetFilesForEdit(new List<File>(filesToSend));
IProjectService projectService = ServiceFactory.GetProjectService(customerId);
Status[] allStatus = projectService.GetProjectStatuses(projectId).ToArray();
Random random = new Random();
filesToEdit.First().FileName = "New FileName 123";
foreach (File file in filesToEdit)
{
file.StatusId = allStatus[random.Next(0, 7)].StatusId;
}
IEnumerable<File> dupFiles;
StorageServiceStatus status = storageService.TryUpdateFiles(filesToEdit.ToList(), out dupFiles);
Assert.IsTrue(status == StorageServiceStatus.Success, "Update status of success was expected");
Assert.IsTrue(dupFiles == null || dupFiles.Count() == 0, "No duplicate files were expected");
File firstFile = filesToEdit.First();
object fileName = this.GetValue("Files", "FileName", string.Format("WHERE FileId={0}", firstFile.FileId));
Assert.IsTrue(fileName.ToString().Equals(string.Concat("New FileName 123", firstFile.FileExtension)), "FileName of New FileName 123 was expected");
object baseFileName = this.GetValue("Files", "BaseFileName", string.Format("WHERE FileId={0}", firstFile.FileId));
Assert.IsTrue(baseFileName.ToString().Equals(string.Concat("New FileName 123", firstFile.FileExtension)), "Basefile of New FileName 123 was expected");
//Check with duplicate files names
File dupFile = filesToEdit.ToList()[1];
dupFile.FileName = "New FileName 123.dwg";
status = storageService.TryUpdateFiles(filesToEdit.ToList(), out dupFiles);
Assert.IsTrue(status == StorageServiceStatus.ExistingFile, "Update status of exisiting file was expected");
Assert.IsTrue(dupFiles == null || dupFiles.Count() == 1, "No duplicate files were expected");
Assert.IsTrue(dupFiles.First().FileInternalName == dupFile.FileInternalName, "Duplicate FileId was not correct");
}
#endregion
#region GetFiles
[TestMethod]
public void Verify_GetFiles()
{
long customerId = this.AddCustomer();
SetDocllerContext(customerId, AdminUserName);
int projectId = AddProject(customerId);
int folderId = AddFolder(customerId, projectId, 0, "Test");
AddFiles(customerId,projectId,folderId, null);
AddFiles(customerId, projectId, folderId, 1);
IStorageService storageService = ServiceFactory.GetStorageService(customerId);
Files files = storageService.GetFiles(projectId, folderId, AdminUserName, FileSortBy.Date, SortDirection.Descending, 1, 10);
Assert.IsTrue(files.Count == 10, "10 files were expected");
Assert.IsTrue(files.TotalCount == 20, "Total 20 files were expected");
files = storageService.GetFiles(projectId, folderId, AdminUserName, FileSortBy.Date, SortDirection.Descending, 1, files.TotalCount);
Assert.IsTrue(files.Count == 20, "Total 20 files were expected");
var withVersion = from v in files
where v.HasVersions
select v;
Assert.IsTrue(withVersion.Count() == 1, "Only one file with version was expected");
//check for attachments
var withAttachments = from a in files
where a.Attachments.Count == 1
select a;
Assert.IsTrue(withAttachments.Count() == 12, "12 Files with Attachments were expected");
}
[TestMethod]
public void Verify_GetFiles_Sorting()
{
long customerId = this.AddCustomer();
SetDocllerContext(customerId, AdminUserName);
int projectId = AddProject(customerId);
int folderId = AddFolder(customerId, projectId, 0, "Test");
AddFiles(customerId, projectId, folderId, null);
IStorageService storageService = ServiceFactory.GetStorageService(customerId);
Files files = storageService.GetFiles(projectId, folderId, AdminUserName, FileSortBy.Date, SortDirection.Ascending, 1, 10);
//test out sorting by date desc
long fileId = long.Parse(this.GetValue("Files", "FileId", "ORDER BY CreatedDate ASC").ToString());
Assert.IsTrue(files.FirstOrDefault().FileId == fileId, "Sort By Date ASC, does not seem to be right");
files = storageService.GetFiles(projectId, folderId, AdminUserName, FileSortBy.FileName, SortDirection.Descending, 1, 10);
fileId = long.Parse(this.GetValue("Files", "FileId", "ORDER BY FileName DESC").ToString());
Assert.IsTrue(files.FirstOrDefault().FileId == fileId, "Sort By FileName DESC does not seem to be right");
files = storageService.GetFiles(projectId, folderId, AdminUserName, FileSortBy.FileName, SortDirection.Ascending, 1, 10);
fileId = long.Parse(this.GetValue("Files", "FileId", "ORDER BY FileName ASC").ToString());
Assert.IsTrue(files.FirstOrDefault().FileId == fileId, "Sort By FileName ASC does not seem to be right");
}
#endregion
#region Misc
[TestMethod]
public void Verify_CompanyPref()
{
long customerId = this.AddCustomer();
SetDocllerContext(customerId,AdminUserName);
int companyId = Convert.ToInt32(this.GetValue("Companies", "CompanyId"));
Database db = GetDb();
db.ExecuteNonQuery(CommandType.Text,
string.Format(
@"UPDATE Companies SET RevisionRegEx='RegEx', AttributeMappingsXml='TestXml' WHERE CompanyId={0}",
companyId));
IStorageRepository repository = ObjectFactory.GetInstance<IStorageRepository>();
Company company = repository.GetFilePreferences(AdminUserName);
Assert.IsNotNull(company,"Company name cannot be null");
Assert.IsTrue(!string.IsNullOrEmpty(company.AttributeMappingsXml) || !string.IsNullOrEmpty(company.RevisionRegEx), "Either Attribute Mappings or RegEx is null");
}
[TestMethod]
public void Verify_JSONTree()
{
SetDocllerContext(122, "pateketu@gmail.com");
IStorageService storageService = ServiceFactory.GetStorageService(122);
Folders folders = storageService.GetFolders("pateketu@gmail.com", 1);
string jscon = JsonConvert.SerializeObject(folders, Formatting.Indented,
new JsonSerializerSettings()
{
ContractResolver = new TreeContractResolver(),
NullValueHandling = NullValueHandling.Ignore
});
}
#endregion
#region version history
//TODO Needs unit testing
[TestMethod]
public void Verify_GetFileHistroy()
{
//IStorageService storageService = ServiceFactory.GetStorageService();
//IEnumerable<BlobBase> history = storageService.GetFileHistory(1801);
}
#endregion
#region attachment
//TODO
[TestMethod]
public void Verify_GetFileAttachments()
{
//IStorageService storageService = ServiceFactory.GetStorageService(1);
//IEnumerable<BlobBase> history = storageService.GetFileHistory(1801);
}
//TODO
[TestMethod]
public void Verify_DeleteAttachment()
{
//IStorageService storageService = ServiceFactory.GetStorageService(1);
//IEnumerable<BlobBase> history = storageService.GetFileHistory(1801);
}
#endregion
private void AddFiles(long customerId, int projectId, int folderId, int? number)
{
IStorageService storageService = new StorageService(ObjectFactory.GetInstance<IStorageRepository>(), ObjectFactory.GetInstance<IBlobStorageProvider>());
//Get the test filenames
List<string> fileNames = new List<string>();
int i = 0;
using (StreamReader reader = new StreamReader(@"..\..\..\Docller.UnitTests\FileList.txt"))
{
while (!reader.EndOfStream)
{
fileNames.Add(reader.ReadLine());
i++;
if (number != null)
{
if (i == number.Value)
{
break;
}
}
}
}
IEnumerable<Core.Models.File> files = storageService.GetPreUploadInfo(projectId, folderId, fileNames.ToArray(), true, false);
int attachmentCounts = 0;
foreach (File file in files)
{
file.Project.ProjectId = projectId;
file.Folder.FolderId = folderId;
file.CustomerId = customerId;
file.ContentType = "fubar";
file.Title = file.FileName[0].ToString();
storageService.AddFile(file, true, "fubar");
if (file.Attachments != null && file.Attachments.Count == 1)
{
storageService.AddAttachment(file.Attachments[0], false, null);
attachmentCounts++;
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace MoneyWeb.Models
{
public class CarteiraModel
{
public int IdCarteira { get; set; }
public int IdConta { get; set; }
public string NomeCarteira {get;set; }
public decimal RentabilidadeDesejada { get; set; }
public virtual ContaModel Conta { get; set; }
}
}
|
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SFA.DAS.ProviderCommitments.Configuration;
using StackExchange.Redis;
namespace SFA.DAS.ProviderCommitments.Web.Extensions
{
public static class DataProtectionStartupExtensions
{
public static IServiceCollection AddDataProtection(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment environment)
{
if (!environment.IsDevelopment())
{
var config = configuration.GetSection(ProviderCommitmentsConfigurationKeys.DataProtectionConnectionStrings).Get<DataProtectionConnectionStrings>();
if (config != null)
{
var redisConnectionString = config.RedisConnectionString;
var dataProtectionKeysDatabase = config.DataProtectionKeysDatabase;
var redis = ConnectionMultiplexer
.Connect($"{redisConnectionString},{dataProtectionKeysDatabase}");
services.AddDataProtection()
.SetApplicationName("das-providercommitments-web")
.PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys");
}
}
return services;
}
}
}
|
using System;
namespace PasswordValidator
{
class Program
{
static void Main(string[] args)
{
string password = Console.ReadLine();
bool IsBetween6and10symbols = CheckLengthOfPassword(password);
if(IsBetween6and10symbols==false)
{
Console.WriteLine("Password must be between 6 and 10 characters");
}
bool ConsistOnlyOfLettersAndDigits = CheckContainsOnlyDigitsAndLetters(password);
if(ConsistOnlyOfLettersAndDigits==false)
{
Console.WriteLine("Password must consist only of letters and digits");
}
bool ContainAtLeast2Digits = CheckContainAtLeast2Digits(password);
if(ContainAtLeast2Digits==false)
{
Console.WriteLine("Password must have at least 2 digits");
}
if(IsBetween6and10symbols && ConsistOnlyOfLettersAndDigits && ContainAtLeast2Digits == true)
{
Console.WriteLine("Password is valid");
}
}
private static bool CheckContainAtLeast2Digits(string password)
{
int count = 0;
for(int i=0;i<password.Length;i++)
{
char symbol = password[i];
if(char.IsDigit(symbol))
{
count++;
}
}
// return count>=2 ? true : false;
if (count >= 2)
{
return true;
}
else
{
return false;
}
}
private static bool CheckContainsOnlyDigitsAndLetters(string password)
{
for (int i = 0; i < password.Length; i++)
{
char symbol = password[i];
if(!char.IsLetterOrDigit(symbol))
{
return false;
}
}
return true;
}
private static bool CheckLengthOfPassword(string password)
{
return password.Length >= 6 && password.Length <= 10 ? true : false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _20200621_계산기_만들어보기
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("========================");
Console.WriteLine("=====계산기프로그램=====");
Console.WriteLine("=========1.덧셈=========");
Console.WriteLine("=========2.뺄셈=========");
Console.WriteLine("=========3.곱셈=========");
Console.WriteLine("=========4.나눗셈=======");
Console.WriteLine("=========5.종료=========");
Console.WriteLine("========================");
Console.WriteLine("메뉴를 입력하세요 : ");
int iNUM = int.Parse(Console.ReadLine());
Console.WriteLine("정수를 입력하세요 : ");
int iNUM1 = int.Parse(Console.ReadLine());
Console.WriteLine("두번째 정수를 입력하세요 : ");
int iNUM2 = int.Parse(Console.ReadLine());
if (iNUM == 1)
{
ADD(iNUM1, iNUM2);
Console.WriteLine("정답은: " + ADD(iNUM1, iNUM2));
}
if (iNUM == 2)
{
SUB(iNUM1, iNUM2);
Console.WriteLine("정답은: " + SUB(iNUM1, iNUM2));
}
if (iNUM == 3)
{
MUL(iNUM1, iNUM2);
Console.WriteLine("정답은: " + MUL(iNUM1, iNUM2));
}
if (iNUM == 4)
{
DIV(iNUM1, iNUM2);
Console.WriteLine("정답은: " + DIV(iNUM1, iNUM2));
}
}
static int ADD(int add, int add1)
{
return add + add1;
}
static int SUB(int add, int add1)
{
return add - add1;
}
static int MUL(int add, int add1)
{
return add * add1;
}
static int DIV(int add, int add1)
{
return add / add1;
}
}
}
|
using CyberSoldierServer.Models.BaseModels;
namespace CyberSoldierServer.Dtos.EjectDtos {
public class SlotDefenceItemDto {
public int Id { get; set; }
public int BaseDefenceItemId { get; set; }
public int PrefabId { get; set; }
public int Level { get; set; }
public DefenceType DefenceType { get; set; }
}
}
|
using System;
using Utilities;
namespace EddiDataDefinitions
{
public class Statistics
{
public BankAccountStats bankaccount { get; set; } = new BankAccountStats();
public CombatStats combat { get; set; } = new CombatStats();
public CrimeStats crime { get; set; } = new CrimeStats();
public SmugglingStats smuggling { get; set; } = new SmugglingStats();
public TradingStats trading { get; set; } = new TradingStats();
public MiningStats mining { get; set; } = new MiningStats();
public ExplorationStats exploration { get; set; } = new ExplorationStats();
public PassengerStats passengers { get; set; } = new PassengerStats();
public SearchAndRescueStats searchandrescue { get; set; } = new SearchAndRescueStats();
public CraftingStats crafting { get; set; } = new CraftingStats();
public NpcCrewStats npccrew { get; set; } = new NpcCrewStats();
public MulticrewStats multicrew { get; set; } = new MulticrewStats();
public ThargoidEncounterStats thargoidencounters { get; set; } = new ThargoidEncounterStats();
public MaterialTraderStats materialtrader { get; set; } = new MaterialTraderStats();
public CQCstats cqc { get; set; } = new CQCstats();
}
public class BankAccountStats
{
[PublicAPI("The commander's current total wealth in credits (including all assets)")]
public long? wealth { get; set; }
[PublicAPI("The credits spent on ships")]
public long? spentonships { get; set; }
[PublicAPI("The credits spent on outfitting")]
public long? spentonoutfitting { get; set; }
[PublicAPI("The credits spent on repairs")]
public long? spentonrepairs { get; set; }
[PublicAPI("The credits spent on fuel")]
public long? spentonfuel { get; set; }
[PublicAPI("The credits spent on ammo and consumables")]
public long? spentonammoconsumables { get; set; }
[PublicAPI("The credits spent on insurance")]
public long? insuranceclaims { get; set; }
[PublicAPI("The number of insurance claims filed")]
public long? spentoninsurance { get; set; }
[PublicAPI("The number of ships owned")]
public long? ownedshipcount { get; set; }
}
public class CombatStats
{
[PublicAPI("The number of bounties claimed")]
public long? bountiesclaimed { get; set; }
[PublicAPI("The total credits earned from bounty claims")]
public decimal? bountyhuntingprofit { get; set; }
[PublicAPI("The number of combat bonds claimed")]
public long? combatbonds { get; set; }
[PublicAPI("The total credits earned from combat bond claims")]
public long? combatbondprofits { get; set; }
[PublicAPI("The number of assassinations performed")]
public long? assassinations { get; set; }
[PublicAPI("The total credits earned from assassinations")]
public long? assassinationprofits { get; set; }
[PublicAPI("The largest credit reward collected from combat")]
public long? highestsinglereward { get; set; }
[PublicAPI("The number of skimmers destroyed")]
public long? skimmerskilled { get; set; }
}
public class CrimeStats
{
[PublicAPI("The current criminal notoriety")]
public int? notoriety { get; set; }
[PublicAPI("The number of fines received")]
public long? fines { get; set; }
[PublicAPI("The total credits accumulated in fines")]
public long? totalfines { get; set; }
[PublicAPI("The number of bounties received")]
public long? bountiesreceived { get; set; }
[PublicAPI("The total credits accumulated in bounties")]
public long? totalbounties { get; set; }
[PublicAPI("The largest credit bounty received")]
public long? highestbounty { get; set; }
}
public class SmugglingStats
{
[PublicAPI("The number of black markets traded with")]
public long? blackmarketstradedwith { get; set; }
[PublicAPI("The total credits earned from trading with black markets")]
public long? blackmarketprofits { get; set; }
[PublicAPI("The number of resources smuggled")]
public long? resourcessmuggled { get; set; }
[PublicAPI("The average credits earned from black market transactions")]
public decimal? averageprofit { get; set; }
[PublicAPI("The largest credit reward from smuggling")]
public long? highestsingletransaction { get; set; }
}
public class ThargoidEncounterStats
{
[PublicAPI("The number of Thargoid wakes scanned")]
public long? wakesscanned { get; set; }
[PublicAPI("The number of Thargoid imprints achieved")]
public long? imprints { get; set; }
[PublicAPI("The total number of Thargoid enounters")]
public long? totalencounters { get; set; }
[PublicAPI("The last system where a Thargoid was enountered")]
public string lastsystem { get; set; }
public DateTime? lasttimestamp { get; set; }
[PublicAPI("The last ship piloted during a Thargoid enounter")]
public string lastshipmodel { get; set; }
[PublicAPI("The total number of Thargoid scouts destroyed")]
public long? scoutsdestroyed { get; set; }
}
public class TradingStats
{
[PublicAPI("The number of legal markets traded with")]
public long? marketstradedwith { get; set; }
[PublicAPI("The total credits earned from trading with legal markets")]
public long? marketprofits { get; set; }
[PublicAPI("The number of resources traded")]
public long? resourcestraded { get; set; }
[PublicAPI("The average credits earned from legal market transactions")]
public decimal? averageprofit { get; set; }
[PublicAPI("The largest credit reward from trading")]
public long? highestsingletransaction { get; set; }
}
public class MiningStats
{
[PublicAPI("The total number of credits earned from mining")]
public long? profits { get; set; }
[PublicAPI("The number of commodities refined from mining")]
public long? quantitymined { get; set; }
[PublicAPI("The number of materials collected while mining")]
public long? materialscollected { get; set; }
}
public class ExplorationStats
{
[PublicAPI("The number of systems visited")]
public long? systemsvisited { get; set; }
[PublicAPI("The total number of credits earned from exploration")]
public long? profits { get; set; }
[PublicAPI("The number of planets and moons scanned to level 2")]
public long? planetsscannedlevel2 { get; set; }
[PublicAPI("The number of planets and moons scanned to level 3")]
public long? planetsscannedlevel3 { get; set; }
[PublicAPI("The largest credit reward from exploration")]
public long? highestpayout { get; set; }
[PublicAPI("The total distance traveled in light years")]
public decimal? totalhyperspacedistance { get; set; }
[PublicAPI("The total number of hyperspace jumps performed")]
public long? totalhyperspacejumps { get; set; }
[PublicAPI("The largest distance traveled in light years from starting")]
public decimal? greatestdistancefromstart { get; set; }
[PublicAPI("The total time played, in seconds")]
public long? timeplayedseconds { get; set; }
}
public class PassengerStats
{
[PublicAPI("The total number of passengers accepted for transport")]
public long? accepted { get; set; }
[PublicAPI("The total number of disgruntled passengers")]
public long? disgruntled { get; set; }
[PublicAPI("The total number of bulk passengers transported")]
public long? bulk { get; set; }
[PublicAPI("The total number of VIP passengers transported")]
public long? vip { get; set; }
[PublicAPI("The total number of passengers delivered")]
public long? delivered { get; set; }
[PublicAPI("The total number of passengers ejected")]
public long? ejected { get; set; }
}
public class SearchAndRescueStats
{
[PublicAPI("The total number of search and rescue items traded")]
public long? traded { get; set; }
[PublicAPI("The total number of credits earned from search and rescue")]
public long? profit { get; set; }
[PublicAPI("The number of search and rescue transactions")]
public long? count { get; set; }
}
public class CraftingStats
{
[PublicAPI("The total number of engineers used")]
public long? countofusedengineers { get; set; }
[PublicAPI("The total number of recipes generated")]
public long? recipesgenerated { get; set; }
[PublicAPI("The total number of grade 1 recipes generated")]
public long? recipesgeneratedrank1 { get; set; }
[PublicAPI("The total number of grade 2 recipes generated")]
public long? recipesgeneratedrank2 { get; set; }
[PublicAPI("The total number of grade 3 recipes generated")]
public long? recipesgeneratedrank3 { get; set; }
[PublicAPI("The total number of grade 4 recipes generated")]
public long? recipesgeneratedrank4 { get; set; }
[PublicAPI("The total number of grade 5 recipes generated")]
public long? recipesgeneratedrank5 { get; set; }
}
public class NpcCrewStats
{
[PublicAPI("The total credits paid to npc crew")]
public long? totalwages { get; set; }
[PublicAPI("The number of npc crew hired")]
public long? hired { get; set; }
[PublicAPI("The number of npc crew fired")]
public long? fired { get; set; }
[PublicAPI("The number of npc crew which have died")]
public long? died { get; set; }
}
public class MulticrewStats
{
[PublicAPI("The total time spent in multicrew, in seconds")]
public long? timetotalseconds { get; set; }
[PublicAPI("The total time spent in multicrew in a gunner role, in seconds")]
public long? gunnertimetotalseconds { get; set; }
[PublicAPI("The total time spent in multicrew in a fighter role, in seconds")]
public long? fightertimetotalseconds { get; set; }
[PublicAPI("The total credits rewarded in multicrew")]
public long? multicrewcreditstotal { get; set; }
[PublicAPI("The total credits accumulated in fines received in multicrew")]
public long? multicrewfinestotal { get; set; }
}
public class MaterialTraderStats
{
[PublicAPI("The number of trades performed at a material trader")]
public long? tradescompleted { get; set; }
[PublicAPI("The number of materials traded at a material trader")]
public long? materialstraded { get; set; }
[PublicAPI("The number of encoded materials traded at a material trader")]
public long? encodedmaterialstraded { get; set; }
[PublicAPI("The number of raw materials traded at a material trader")]
public long? rawmaterialstraded { get; set; }
[PublicAPI("The number of grade 1 materials traded at a material trader")]
public long? grade1materialstraded { get; set; }
[PublicAPI("The number of grade 2 materials traded at a material trader")]
public long? grade2materialstraded { get; set; }
[PublicAPI("The number of grade 3 materials traded at a material trader")]
public long? grade3materialstraded { get; set; }
[PublicAPI("The number of grade 4 materials traded at a material trader")]
public long? grade4materialstraded { get; set; }
[PublicAPI("The number of grade 5 materials traded at a material trader")]
public long? grade5materialstraded { get; set; }
}
public class CQCstats
{
[PublicAPI("The total credits earned from CQC combat")]
public long? creditsearned { get; set; }
[PublicAPI("The total time spent in CQC combat, in seconds")]
public long? timeplayedseconds { get; set; }
[PublicAPI("The total number of kills earned in CQC combat")]
public long? kills { get; set; }
[PublicAPI("The ratio of kills to deaths in CQC combat")]
public decimal? killdeathratio { get; set; }
[PublicAPI("The ratio of wins to losses in CQC combat")]
public decimal? winlossratio { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Routing;
using System.Web.UI.WebControls;
using BusinessLogic;
using DataAccess;
namespace FirstWebStore.Pages
{
public partial class OrderPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var userId = (Guid)Session["UserId"];
if (userId != Guid.Empty)
{
return;
}
var thisUrl = HttpUtility.UrlEncode(Request.RawUrl);
var virtualPathData = RouteTable.Routes.GetVirtualPath(null, "login", null);
if (virtualPathData == null)
{
return;
}
var loginUrl = virtualPathData.VirtualPath;
Response.Redirect(loginUrl + "?returnurl=" + thisUrl);
}
protected void PlaceOrderBtn_OnCommand(object sender, CommandEventArgs e)
{
if (e.CommandName != "PlaceOrder")
{
return;
}
var userId = (Guid)Session["UserId"];
var newOrder = new OrderFactory().Create(new Order());
newOrder.FirstName = FirstName.Text;
newOrder.LastName = LastName.Text;
newOrder.City = City.Text;
newOrder.Address = Address.Text;
newOrder.UserId = userId;
newOrder.OrderDateTime = DateTime.Now;
newOrder.OrderItems = new List<OrderItem>();
var businessLogicOrder = StrMapContainer.GetInstance.GetContainer
.GetInstance<BusinessLogicOrder>();
businessLogicOrder.PlaceOrder(userId, newOrder);
shippingForm.Visible = false;
HyperLink2.Visible = false;
doneMessage.Visible = true;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Kitchen : Room
{
KitchenTileset tileSet;
int pantryBreadth;
int pantryLength;
IntRange pantryBreadthRange = new IntRange(3, 4);
IntRange pantryLengthRange = new IntRange(5, 8);
Direction pantryDirection;
private Vector2Int kitchenDoorPosition;
private Vector2Int kitchenPantryMedium;
private Vector2Int pantryDoorPosition;
int pantryWall = 1;
int kX, kY, kWidth, kHeight;
int pX, pY, pWidth, pHeight;
List<Furniture> pantryOptions;
List<float> pantryChances;
List<Furniture> pantryCornerOptions;
List<float> pantryCornerChances;
int counterMargin = 3;
int counterMinBreadth = 2;
public Kitchen() : base()
{
roomCode = RoomCode.Kitchen;
widthRange = new IntRange(12, 20);
heightRange = new IntRange(12, 20);
tileSet = (KitchenTileset)TileSet;
pantryOptions = new List<Furniture>()
{
tileSet.crate,
tileSet.potatoSack,
tileSet.flourSack,
null
};
pantryChances = new List<float>()
{
.6f,
.1f,
.1f,
.2f
};
pantryCornerOptions = new List<Furniture>()
{
tileSet.potatoSack,
tileSet.flourSack,
null
};
pantryCornerChances = new List<float>()
{
.3f,
.3f,
.4f
};
}
public override void SetupRoom(Doorway doorway, int story)
{
base.SetupRoom(doorway, story);
SetKitchenPantryDimensions();
}
public override void PostValiditySetup()
{
SetKitchenPantryDimensions();
}
public override void GenerateFurniture()
{
GenerateLightSwitch();
GeneratePantryFurniture();
GenerateKitchenFurniture();
}
private void SetKitchenPantryDimensions()
{
pantryBreadth = pantryBreadthRange.Random;
pantryLength = pantryLengthRange.Random;
//Need to finish this
Orientation orientation;
if (width > height)
orientation = Orientation.Horizontal;
else
orientation = Orientation.Vertical;
if (DirectionUtil.Orientation(doorways[0].roomOutDirection) == orientation)
{
pantryDirection = DirectionUtil.Reverse(doorways[0].roomOutDirection);
}
else
{
if (DirectionUtil.Orientation(doorways[0].roomOutDirection) == Orientation.Vertical)
{
if (pX + pantryBreadth + pantryWall >= doorways[0].x)
pantryDirection = Direction.East;
else if (x + width - pantryBreadth - pantryWall < doorways[0].x)
pantryDirection = Direction.West;
else
pantryDirection = Random.value > .5f ? Direction.East : Direction.West;
}
else
{
if (pY + pantryBreadth + pantryWall >= doorways[0].y)
pantryDirection = Direction.North;
else if (y + height - pantryBreadth - pantryWall < doorways[0].y)
pantryDirection = Direction.South;
else
pantryDirection = Random.value > .5f ? Direction.North : Direction.South;
}
}
if (pantryDirection == Direction.North)
{
kX = x; kY = y; kWidth = width; kHeight = height - pantryBreadth - pantryWall;
pX = x; pY = y + height - pantryBreadth; pWidth = width; pHeight = pantryBreadth;
pantryDoorPosition = new Vector2Int(Random.Range(pX + 1, pX + pWidth - 2), pY);
kitchenPantryMedium = new Vector2Int(pantryDoorPosition.x, pantryDoorPosition.y - 1);
kitchenDoorPosition = new Vector2Int(pantryDoorPosition.x, pantryDoorPosition.y - 2);
}
else if (pantryDirection == Direction.South)
{
kX = x; kY = y + pantryBreadth + pantryWall; kWidth = width; kHeight = height - pantryBreadth - pantryWall;
pX = x; pY = y; pWidth = width; pHeight = pantryBreadth;
pantryDoorPosition = new Vector2Int(Random.Range(pX + 1, pX + pWidth - 2), pY + pHeight - 1);
kitchenPantryMedium = new Vector2Int(pantryDoorPosition.x, pantryDoorPosition.y + 1);
kitchenDoorPosition = new Vector2Int(pantryDoorPosition.x, pantryDoorPosition.y + 2);
}
else if (pantryDirection == Direction.East)
{
kX = x; kY = y; kWidth = width - pantryBreadth - pantryWall; kHeight = height;
pX = x + width - pantryBreadth; pY = y; pWidth = pantryBreadth; pHeight = height;
pantryDoorPosition = new Vector2Int(pX, Random.Range(pY + 1, pY + pHeight - 2));
kitchenPantryMedium = new Vector2Int(pantryDoorPosition.x - 1, pantryDoorPosition.y);
kitchenDoorPosition = new Vector2Int(pantryDoorPosition.x - 2, pantryDoorPosition.y);
}
else
{
kX = x + pantryBreadth + pantryWall; kY = y; kWidth = width - pantryBreadth - pantryWall; kHeight = height;
pX = x; pY = y; pWidth = pantryBreadth; pHeight = height;
pantryDoorPosition = new Vector2Int(pX + pWidth - 1, Random.Range(pY + 1, pY + pHeight - 2));
kitchenPantryMedium = new Vector2Int(pantryDoorPosition.x + 1, pantryDoorPosition.y);
kitchenDoorPosition = new Vector2Int(pantryDoorPosition.x + 2, pantryDoorPosition.y);
}
}
public void GeneratePantryFurniture()
{
//Corners
float precompTotal = WeightedChoice.PrecompTotal(pantryCornerChances);
Furniture prefab = RandomPantryItem(precompTotal);
if (prefab != null)
{
InstantiateFurniture(prefab, new Vector2(pX, pY));
}
prefab = RandomPantryItem(precompTotal);
if (prefab != null)
{
InstantiateFurniture(prefab, new Vector2(pX + pWidth - 1, pY));
}
prefab = RandomPantryItem(precompTotal);
if (prefab != null)
{
InstantiateFurniture(prefab, new Vector2(pX, pY + pHeight - 1));
}
prefab = RandomPantryItem(precompTotal);
if (prefab != null)
{
InstantiateFurniture(prefab, new Vector2(pX + pWidth - 1, pY + pHeight - 1));
}
//Sides
precompTotal = WeightedChoice.PrecompTotal(pantryChances);
//Horizontal sides
for (int xPos = pX + 1; xPos < pX + pWidth - 1; xPos++)
{
prefab = RandomPantryItem(precompTotal);
Vector2 position = new Vector3(xPos, pY);
if (prefab != null && position != pantryDoorPosition)
{
InstantiateFurniture(prefab, position);
}
prefab = RandomPantryItem(precompTotal);
position = new Vector3(xPos, pY + pHeight - 1);
if (prefab != null && position != pantryDoorPosition)
{
InstantiateFurniture(prefab, position);
}
}
//Vertical sides
for (int yPos = pY + 1; yPos < pY + pHeight - 1; yPos++)
{
prefab = RandomPantryItem(precompTotal);
Vector2 position = new Vector3(pX, yPos);
if (prefab != null && position != pantryDoorPosition)
{
InstantiateFurniture(prefab, position);
}
prefab = RandomPantryItem(precompTotal);
position = new Vector3(pX + pWidth - 1, yPos);
if (prefab != null && position != pantryDoorPosition)
{
InstantiateFurniture(prefab, position);
}
}
}
public void GenerateKitchenFurniture()
{
GenerateCenterCounter();
//Generate the corners
float rng = Random.value;
Furniture firstSpawn = rng > .5f ? tileSet.fridge : tileSet.oven;
Furniture secondSpawn = rng > .5f ? tileSet.oven : tileSet.fridge;
Rect firstSpawnRect;
Rect secondSpawnRect;
Rect firstCornerFiller;
Rect secondCornerFiller;
if (doorways[0].roomOutDirection == Direction.North)
{
firstSpawnRect = new Rect(kX, kY, 2, 2);
secondSpawnRect = new Rect(kX + kWidth - 2, kY, 2, 2);
firstCornerFiller = new Rect(kX, kY + kHeight - 1, 1, 1);
secondCornerFiller = new Rect(kX + kWidth - 1, kY + kHeight - 1, 1, 1);
}
else if (doorways[0].roomOutDirection == Direction.South)
{
firstSpawnRect = new Rect(kX, kY + kHeight - 2, 2, 2);
secondSpawnRect = new Rect(kX + kWidth - 2, kY + kHeight - 2, 2, 2);
firstCornerFiller = new Rect(kX, kY, 1, 1);
secondCornerFiller = new Rect(kX + kWidth - 1, kY, 1, 1);
}
else if (doorways[0].roomOutDirection == Direction.East)
{
firstSpawnRect = new Rect(kX, kY, 2, 2);
secondSpawnRect = new Rect(kX, kY + kHeight - 2, 2, 2);
firstCornerFiller = new Rect(kX + kWidth - 1, kY, 1, 1);
secondCornerFiller = new Rect(kX + kWidth - 1, kY + kHeight - 1, 1, 1);
}
else //(doorways[0].roomOutDirection == Direction.West)
{
firstSpawnRect = new Rect(kX + kWidth - 2, kY + kHeight - 2, 2, 2);
secondSpawnRect = new Rect(kX + kWidth - 2, kY, 2, 2);
firstCornerFiller = new Rect(kX, kY, 1, 1);
secondCornerFiller = new Rect(kX, kY + kHeight - 1, 1, 1);
}
AttemptFurnitureInstantiation(firstSpawn, firstSpawnRect);
AttemptFurnitureInstantiation(secondSpawn, secondSpawnRect);
AttemptFurnitureInstantiation(tileSet.plainCounter, firstCornerFiller);
AttemptFurnitureInstantiation(tileSet.plainCounter, secondCornerFiller);
List<Vector2> availableSpots = new List<Vector2>();
for (int xPos = kX + 1; xPos < kX + kWidth - 1; xPos++)
{
Rect rect = new Rect(xPos, kY, 1, 1);
if (!ObstructsDoorway(rect) && !firstSpawnRect.Overlaps(rect) && !secondSpawnRect.Overlaps(rect) && rect.position != kitchenDoorPosition)
availableSpots.Add(new Vector2(rect.x, rect.y));
rect.y = kY + kHeight - 1;
if (!ObstructsDoorway(rect) && !firstSpawnRect.Overlaps(rect) && !secondSpawnRect.Overlaps(rect) && rect.position != kitchenDoorPosition)
availableSpots.Add(new Vector2(rect.x, rect.y));
}
for (int yPos = kY + 1; yPos < kY + kHeight - 1; yPos++)
{
Rect rect = new Rect(kX, yPos, 1, 1);
if (!ObstructsDoorway(rect) && !firstSpawnRect.Overlaps(rect) && !secondSpawnRect.Overlaps(rect) && rect.position != kitchenDoorPosition)
availableSpots.Add(new Vector2(rect.x, rect.y));
rect.x = kX + kWidth - 1;
if (!ObstructsDoorway(rect) && !firstSpawnRect.Overlaps(rect) && !secondSpawnRect.Overlaps(rect) && rect.position != kitchenDoorPosition)
availableSpots.Add(new Vector2(rect.x, rect.y));
}
foreach(Vector2 spot in availableSpots)
{
InstantiateFurniture(tileSet.cabinetCounter, spot);
}
}
public void GenerateCenterCounter()
{
//Find the dimensions
int cX = Random.Range(kX + counterMargin, kX + kWidth - counterMinBreadth - counterMargin);
int cY = Random.Range(kY + counterMargin, kY + kHeight - counterMinBreadth - counterMargin);
int cWidth = Random.Range(counterMinBreadth, kX + kWidth - counterMargin - cX);
int cHeight = Random.Range(counterMinBreadth, kY + kHeight - counterMargin - cY);
//Corners
TileSetRegistry.I.floorTilemaps[story].SetTile(new Vector3Int(cX, cY, 0), tileSet.counterBottomLeft);
TileSetRegistry.I.floorTilemaps[story].SetTile(new Vector3Int(cX + cWidth - 1, cY, 0), tileSet.counterBottomRight);
TileSetRegistry.I.floorTilemaps[story].SetTile(new Vector3Int(cX, cY + cHeight - 1, 0), tileSet.counterTopLeft);
TileSetRegistry.I.floorTilemaps[story].SetTile(new Vector3Int(cX + cWidth - 1, cY + cHeight - 1, 0), tileSet.counterTopRight);
for (int xPos = cX + 1; xPos < cX + cWidth - 1; xPos++)
{
TileSetRegistry.I.floorTilemaps[story].SetTile(new Vector3Int(xPos, cY, 0), tileSet.counterBottomCenter);
TileSetRegistry.I.floorTilemaps[story].SetTile(new Vector3Int(xPos, cY + cHeight - 1, 0), tileSet.counterTopCenter);
}
for (int yPos = cY + 1; yPos < cY + cHeight - 1; yPos++)
{
TileSetRegistry.I.floorTilemaps[story].SetTile(new Vector3Int(cX, yPos, 0), tileSet.counterMidLeft);
TileSetRegistry.I.floorTilemaps[story].SetTile(new Vector3Int(cX + cWidth - 1, yPos, 0), tileSet.counterMidRight);
}
for (int xPos = cX + 1; xPos < cX + cWidth - 1; xPos++)
{
for (int yPos = cY + 1; yPos < cY + cHeight - 1; yPos++)
{
TileSetRegistry.I.floorTilemaps[story].SetTile(new Vector3Int(xPos, yPos, 0), tileSet.counterMidCenter);
}
}
Vector2 position = new Vector2(cX + cWidth / 2f - .5f, cY + cHeight / 2f - .5f);
Furniture counterCollider = InstantiateFurniture(PrefabRegistry.I.boxOverlay.GetComponent<Furniture>(), position);
counterCollider.transform.localScale = new Vector2(cWidth, cHeight);
}
public Furniture RandomPantryCornerItem(float precompTotal)
{
return WeightedChoice.Choose(pantryCornerOptions, pantryCornerChances, precompTotal);
}
public Furniture RandomPantryItem(float precompTotal)
{
return WeightedChoice.Choose(pantryOptions, pantryChances, precompTotal);
}
public override Doorway PossibleDoorway()
{
Direction desiredDirection = FindDesiredDoorDirection(new List<Direction>() { pantryDirection });
int northFridgeDiscount = doorways[0].roomOutDirection == Direction.North ? 0 : 2;
int southFridgeDiscount = doorways[0].roomOutDirection == Direction.South ? 0 : 2;
int eastFridgeDiscount = doorways[0].roomOutDirection == Direction.East ? 0 : 2;
int westFridgeDiscount = doorways[0].roomOutDirection == Direction.West ? 0 : 2;
switch (desiredDirection)
{
case Direction.North:
return new Doorway(Random.Range(kX + westFridgeDiscount, kX + kWidth - generatedDoorwayBreadth - eastFridgeDiscount), kY + kHeight - 1, Direction.North);
case Direction.South:
return new Doorway(Random.Range(kX + westFridgeDiscount, kX + kWidth - generatedDoorwayBreadth - eastFridgeDiscount), kY, Direction.South);
case Direction.East:
return new Doorway(kX + kWidth - 1, Random.Range(kY + southFridgeDiscount, kY + kHeight - generatedDoorwayBreadth - northFridgeDiscount), Direction.East);
default:
return new Doorway(kX, Random.Range(kY + southFridgeDiscount, kY + kHeight - generatedDoorwayBreadth - northFridgeDiscount), Direction.West);
}
}
public override void PrintToTilesArray(sbyte[][][] tiles)
{
for (int yPos = kY; yPos < kY + kHeight; yPos++)
{
for (int xPos = kX; xPos < kX + kWidth; xPos++)
{
tiles[story][yPos][xPos] = (sbyte)roomCode;
}
}
for (int yPos = pY; yPos < pY + pHeight; yPos++)
{
for (int xPos = pX; xPos < pX + pWidth; xPos++)
{
tiles[story][yPos][xPos] = (sbyte)roomCode;
}
}
tiles[story][kitchenPantryMedium.y][kitchenPantryMedium.x] = (sbyte)roomCode;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class DragOut : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
Vector3 origin;
RectTransform inventoryPanel;
public List<RectTransform> instantiatedPanels = new List<RectTransform>();
public List<RectTransform> instantiatedItemPanels = new List<RectTransform>();
public void OnDrag(PointerEventData eventData) {
transform.position = eventData.position;
}
//required for OnDrag() to work
public void OnBeginDrag(PointerEventData eventData) {
Debug.Log("dragging");
origin = transform.position;
}
//required for OnDrag() to work
public void OnEndDrag(PointerEventData eventData)
{
if(!RectTransformUtility.RectangleContainsScreenPoint(transform.parent.GetComponent<RectTransform>(), Input.mousePosition))
{
transform.position = eventData.position;
} else // dropped within the items panel
{
//transform.position = origin;
// check if the item is dropped on a grid with an item already there
// need access to array of items
for (int i = 0; i < instantiatedPanels.Count; i++)
{
if(RectTransformUtility.RectangleContainsScreenPoint(instantiatedPanels[i].GetComponent<RectTransform>(), Input.mousePosition)) // check if there the drag ended on a panel square
{
for (int j = 0; j < instantiatedItemPanels.Count; j++)
{
if(RectTransformUtility.RectangleContainsScreenPoint(instantiatedItemPanels[j].GetComponent<RectTransform>(), Input.mousePosition))
{
transform.position = origin;
Debug.Log("item there");
break;
} else
{
transform.position = instantiatedPanels[i].position;
Debug.Log("no item there");
Debug.Log(transform.position);
Debug.Log(instantiatedPanels[i].position);
break;
}
}
} else
{
//transform.position = origin;
}
}
}
}
}
|
using System.Diagnostics.CodeAnalysis;
using Atc.Resources;
// ReSharper disable once CheckNamespace
namespace Atc
{
/// <summary>
/// Enumeration: DateTimeDiffCompareType.
/// </summary>
public enum DateTimeDiffCompareType
{
/// <summary>
/// Ticks.
/// </summary>
[LocalizedDescription("DateTimeDiffCompareTypeTicks", typeof(EnumResources))]
Ticks,
/// <summary>
/// Milliseconds.
/// </summary>
[LocalizedDescription("DateTimeDiffCompareTypeMilliseconds", typeof(EnumResources))]
Milliseconds,
/// <summary>
/// Seconds.
/// </summary>
[LocalizedDescription("DateTimeDiffCompareTypeSeconds", typeof(EnumResources))]
Seconds,
/// <summary>
/// Minutes.
/// </summary>
[LocalizedDescription("DateTimeDiffCompareTypeMinutes", typeof(EnumResources))]
Minutes,
/// <summary>
/// Hours.
/// </summary>
[LocalizedDescription("DateTimeDiffCompareTypeHours", typeof(EnumResources))]
Hours,
/// <summary>
/// Days.
/// </summary>
[LocalizedDescription("DateTimeDiffCompareTypeDays", typeof(EnumResources))]
Days,
/// <summary>
/// Year.
/// </summary>
[LocalizedDescription("DateTimeDiffCompareTypeYear", typeof(EnumResources))]
Year,
/// <summary>
/// Quartal.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Quartal", Justification = "OK.")]
[LocalizedDescription("DateTimeDiffCompareTypeQuartal", typeof(EnumResources))]
Quartal,
}
} |
using System;
using System.Runtime.InteropServices;
namespace NetVlc
{
public class Media : IDisposable
{
#region DLL Calls
[DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr libvlc_media_new(IntPtr p_instance,
[MarshalAs(UnmanagedType.LPStr)] string psz_mrl, ref libvlc_exception_t ex);
[DllImport("libvlc")]
static extern void libvlc_media_release(IntPtr p_meta_desc);
#endregion
private IntPtr mediaHandler;
public IntPtr Handler
{
get { return this.mediaHandler; }
}
public Media(Core core, string path)
{
libvlc_exception_t ex = new libvlc_exception_t();
this.mediaHandler = libvlc_media_new(core.Handler, path, ref ex);
if (this.mediaHandler == IntPtr.Zero) throw new VlcException();
}
public void Dispose()
{
libvlc_media_release(this.mediaHandler);
}
}
}
|
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace WebPrueba.Models
{
public class PersonContext : DbContext
{
public PersonContext(DbContextOptions<PersonContext> options)
: base(options)
{}
public DbSet<Person> Persons { get; set; }
}
public class Person
{
public int PersonId { get; set; }
[Required(ErrorMessage = "Campo Requerido")]
public string Nombres { get; set; }
[Required(ErrorMessage = "Campo Requerido")]
public string Apellidos { get; set; }
[Required(ErrorMessage = "Campo Requerido")]
public string Telefono { get; set; }
[Required(ErrorMessage = "Campo Requerido")]
[RegularExpression(@"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", ErrorMessage = "Ingrese un correo valido")]
public string Email { get; set; }
[Required(ErrorMessage = "Campo Requerido")]
public string Cedula { get; set; }
[Required(ErrorMessage = "Campo Requerido")]
public string Direccion { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class PlayerController03 : MonoBehaviour
{
public float Speed;
public Text scoreText;
public Text timeText;
//public Text winText;
public Text uIText;
private Rigidbody rb;
private int score;
void Start()
{
rb = GetComponent<Rigidbody>();
score = 0;
//winText.text = "";
//uIText.text = "";
SetScoreText();
uIText.text = "Level 3";
uIText.enabled = true;
StartCoroutine(Test());
uIText.enabled = false;
//StartCoroutine(ShowMessage("Level 3", 5 / 2));
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(movement * Speed);
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Pick Up"))
{
other.gameObject.SetActive(false);
score++;
SetScoreText();
}
if (other.gameObject.CompareTag("Bonus"))
{
other.gameObject.SetActive(false);
score += 2;
SetScoreText();
}
if(other.gameObject.CompareTag("Trigger"))
{
SceneManager.LoadScene("Level03");
}
}
void SetScoreText()
{
scoreText.text = "Score: " + score.ToString();
if (score >= 60)
//if (score >= 60 && score < 100)
{
uIText.text = "You Win!";
uIText.enabled = true;
StartCoroutine(Test());
uIText.enabled = false;
uIText.text = "Congratulations! You Completed The Game";
uIText.enabled = true;
StartCoroutine(Test());
uIText.enabled = false;
uIText.text = "Loading Level 1";
uIText.enabled = true;
StartCoroutine(Test());
uIText.enabled = false;
//winText.text = "You Win!";
/*StartCoroutine(ShowMessage("You Win!", 5 / 2));
StartCoroutine(ShowMessage("Congratulations! You Completed The Game", 5 / 2));
StartCoroutine(ShowMessage("Loading Level 1", 5 / 2));*/
SceneManager.LoadScene("Level01");
}
if (score == 100)
{
//StartCoroutine(ShowMessage("Bonus Level Unlocked!", 5));
uIText.text = "Bonus Level Unlocked";
uIText.enabled = true;
StartCoroutine(Test());
uIText.enabled = false;
SceneManager.LoadScene("Bonus Level");
}
}
public IEnumerator Test()
{
yield return new WaitForSecondsRealtime(5/2);
//SceneManager.LoadScene("Level01");
}
/*public IEnumerator ShowMessage(string message, float delay)
{
uIText.text = message;
uIText.enabled = true;
yield return new WaitForSeconds(delay);
uIText.enabled = false;
}*/
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Net.Http.Headers;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private async void button1_Click(object sender, EventArgs e)
{
using (HttpClient client = new HttpClient())
{
var data = "{ {'CompetitionId': '9A5370D3-B9C1-42AA-B699-2FE831B56992'}, {'CompetitorId': '9A5370D3-B9C1-42AA-B699-2FE831B56992'}}";
ResultModel mod = new ResultModel()
{
CompetitorId = Guid.NewGuid(),
CompetitionId = Guid.NewGuid()
};
var json = JsonConvert.SerializeObject(mod);
client.BaseAddress = new Uri("http://localhost:64721");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsync("/api/results", new StringContent(json, Encoding.UTF8, "application/json"));
//string content = await response.Content.ReadAsStringAsync();
//return await Task.Run(() => Newtonsoft.Json.JsonConvert. JsonObject.Parse(content));
}
}
}
public class ResultModel
{
public Guid CompetitionId { get; set; }
public Guid CompetitorId { get; set; }
}
public class FieldShootingResult : ResultModel
{
public int Station { get; set; }
public int Hits { get; set; }
public int Targets { get; set; }
}
}
|
using System;
namespace Decorator
{
class Program
{
static void Main(string[] args)
{
var messenger1 = new MessengerService(new MsmqMessage());
messenger1.SendMessage("Hello MSMQ");
var messenger2 = new MessengerService(new RabbitmqMessage());
messenger2.SendMessage("Hello RabbitMQ");
var messenger3 = new MessengerService(new EncryptedMessage(new MsmqMessage()));
messenger3.SendMessage("Hello encrypted message");
var messenger4 = new MessengerService(new SerializeMessage(new RabbitmqMessage()));
messenger4.SendMessage("Hello serialized message");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity;
using Unity.Interception.ContainerIntegration;
using Unity.Interception.InterceptionBehaviors;
using Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception;
using Unity.Interception.PolicyInjection.Pipeline;
namespace _20.UnityInterception
{
class Program
{
static void Main(string[] args)
{
IUnityContainer container = new UnityContainer();
var fooInterception = new Interception();
container.AddExtension(fooInterception);
container.RegisterType<IMessage, ConsoleMessage>(
new Interceptor<InterfaceInterceptor>(),
new InterceptionBehavior<AppLog>(),
new InterceptionBehavior<VirtualLog>());
IMessage message = container.Resolve<IMessage>();
Console.WriteLine($"{Environment.NewLine} Call IMessage.Write");
message.Write("Hi Vulcan");
Console.WriteLine($"{Environment.NewLine} Call IMessage.Empty");
message.Empty();
Console.WriteLine("Press any key for continuing...");
Console.ReadKey();
}
}
public interface IMessage
{
void Write(string message);
void Empty();
}
public class ConsoleMessage : IMessage
{
public void Write(string message)
{
Console.WriteLine($"Message: {message} ");
}
public void Empty()
{
Console.WriteLine($"this is a Empty Function");
}
}
public class AppLog : IInterceptionBehavior
{
public bool WillExecute => true;
public IEnumerable<Type> GetRequiredInterfaces()
{
return Type.EmptyTypes;
}
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
IMethodReturn result = null;
if (input.MethodBase.Name == "Write")
{
Console.WriteLine($"(AppLog) Before:{input.MethodBase.DeclaringType.Name}.{input.MethodBase.Name}");
result = getNext()(input, getNext);
Console.WriteLine($"(AppLog) After:{input.MethodBase.DeclaringType.Name}{input.MethodBase.Name}");
return result;
}
return getNext()(input, getNext);
}
}
public class VirtualLog : IInterceptionBehavior
{
public bool WillExecute => true;
public IEnumerable<Type> GetRequiredInterfaces()
{
return Type.EmptyTypes;
}
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
IMethodReturn result = null;
if (input.MethodBase.Name == "Empty")
{
Console.WriteLine($"(VirtualLog) Before:{input.MethodBase.DeclaringType.Name}.{input.MethodBase.Name}");
result = getNext()(input, getNext);
Console.WriteLine($"(VirtualLog) After:{input.MethodBase.DeclaringType.Name}{input.MethodBase.Name}");
return result;
}
return getNext()(input, getNext);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercicio18
{
class LeituraMatriz3D
{
static void Main(string[] args)
{
{
Console.Write("Tamanho 1. dimensão ");
int T = Convert.ToInt16(Console.ReadLine());
Console.Write("Tamanho 2. dimensão ");
int N = Convert.ToInt16(Console.ReadLine());
Console.Write("Tamanho 3. dimensão ");
int M = Convert.ToInt16(Console.ReadLine());
string[,,] A = new string[T, N, M];
for (int P = 0; P <= T - 1; P++)
for (int I = 0; I <= N - 1; I++)
for (int J = 0; J <= M - 1; J++)
{
Console.Write("a[{0},{1},{2}]=", P, I, J);
A[P, I, J] = Console.ReadLine();
}
for (int P = 0; P <= T - 1; P++)
{
Console.WriteLine("Escola {0}", P);
for (int I = 0; I <= N - 1; I++)
{
for (int J = 0; J <= M - 1; J++)
Console.Write(A[P, I, J].PadRight(12));
Console.WriteLine();
}
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.