text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Practica01
{
class TV
{
public string color = "", forma = "", tamaño = "";
public double peso = 0.0, costo = 0.0;
public void Prender()
{
Console.WriteLine("estoy prendiendo");
}
public void Trasmitir()
{
Console.WriteLine("estoy trasmitiendo");
}
public void Apagar()
{
Console.WriteLine("me estoy apagando");
}
public void AjustarBrillo()
{
Console.WriteLine("Estoy ajustando el brillo");
}
public void Informar()
{
Console.WriteLine("estoy informando");
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CakeShop.ViewModels
{
public class SplashScreenViewModel:INotifyPropertyChanged
{
public Data.CAKE MainCake { get; set; }
public string MaxTime { get; set; }
private string timeLeft = null;
public string TimeLeft
{
get { return this.timeLeft; }
set
{
if (value != this.timeLeft)
{
this.timeLeft = value;
OnPropertyChanged("TimeLeft");
}
else { return; }
}
}
/// <summary>
/// Hàm cập nhật thay đổi thuộc tính
/// </summary>
/// <param name="name"></param>
private void OnPropertyChanged(string name)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
else { }
}
public SplashScreenViewModel(CakeShop.Data.CAKE cake, string maxtime)
{
MainCake = cake;
MaxTime = maxtime;
TimeLeft = maxtime;
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
namespace StockManager.Models
{
public class FoodModel
{
public int Id { get; set; }
public double Weight { get; set; }
public int Quantity { get; set; }
public string Description { get; set; }
public string Comment { get; set; }
public string Location { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ImageFilter
{
public class ConvolutionalFilters
{
private static int Truncate(int value)
{
if (value > 255)
return 255;
if (value < 0)
return 0;
return value;
}
public static Bitmap ImageWithPadding(Bitmap image, Kernel kernel)
{
Bitmap tmp = new Bitmap(image.Width + kernel.Width - 1, image.Height + kernel.Heigth - 1);
for (int x = 0; x < tmp.Width; x++)
{
for(int y = 0; y < tmp.Height; y++)
{
tmp.SetPixel(x, y, Color.FromArgb(0, 0, 0));
}
}
for (int x = 0; x < image.Width; x++)
{
for(int y = 0; y < image.Height; y++)
{
try
{
tmp.SetPixel(x + kernel.Anchor.X, y + kernel.Anchor.Y, image.GetPixel(x, y));
}
catch
{
MessageBox.Show($"Error occured when creating matrix with padding. Coordinates: x: {x + kernel.Anchor.X} y: {y + kernel.Anchor.Y}");
}
}
}
return tmp;
}
public static Bitmap Filter(Bitmap image, Kernel kernel)
{
Bitmap newImage = new Bitmap(image.Width, image.Height);
Bitmap padded = ImageWithPadding(image, kernel);
for(int x = 0; x < newImage.Width; x++)
{
for(int y = 0; y < newImage.Height; y++)
{
int newR = 0;
int newG = 0;
int newB = 0;
for (int k = 0; k < kernel.Width; k++)
{
for(int l = 0; l < kernel.Heigth; l++)
{
try
{
newR += (kernel.Matrix[k, l] * padded.GetPixel(x + k, y + l).R);
newG += (kernel.Matrix[k, l] * padded.GetPixel(x + k, y + l).G);
newB += (kernel.Matrix[k, l] * padded.GetPixel(x + k, y + l).B);
}
catch
{
MessageBox.Show($"Error occured when applying convolution filter. Coordinates: x:{x + k} y:{y + l}");
}
}
}
newR = (byte)Truncate(kernel.Offset + newR / kernel.Divisor);
newG = (byte)Truncate(kernel.Offset + newG / kernel.Divisor);
newB = (byte)Truncate(kernel.Offset + newB / kernel.Divisor);
try
{
newImage.SetPixel(x, y, Color.FromArgb(newR, newG, newB));
}
catch
{
MessageBox.Show($"Error occured when setting new pixels after filter application. Coordinates: x:{x} y: {y}");
}
}
}
return newImage;
}
public static Kernel FindKernelByName(List <Kernel> kernels, string name)
{
foreach(var kernel in kernels)
{
if (kernel.Name == name)
return kernel;
}
return null;
}
}
}
|
using System;
namespace SFA.DAS.Notifications.Domain.Entities
{
public class Notification
{
public string MessageId { get; set; }
public string SystemId { get; set; }
public DateTime Timestamp { get; set; }
public NotificationFormat Format { get; set; }
public NotificationStatus Status { get; set; }
public string TemplateId { get; set; }
public string Data { get; set; }
}
}
|
namespace HelloWorldBusiness
{
public interface IGreeting
{
string GetGreeting { get; }
}
}
|
using HangoutsDbLibrary.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebAPI.ViewModels;
namespace WebAPI.Mappers
{
public interface IActivityMapper
{
Activity FromActivityViewModelToActivity(ActivityViewModel activityViewModel);
ActivityViewModel FromActivityToActivityViewModel(Activity activity);
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
/// <summary>
/// 戰鬥UI
/// </summary>
public class BattleUI : MonoBehaviour
{
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Zelo.Common.DBUtility;
namespace Zelo.DBService
{
/// <summary>
/// 系统安全服务累
/// </summary>
public class SecurityService
{
private static readonly String USER_PASSWORD_PREFIX = "a49b0cASDFASDFASDF3a279a7e8ASDFASDFSDFA72a49b0cASDFB";
/// <summary>
/// 用户密码加密
/// </summary>
/// <param name="password"></param>
/// <returns></returns>
public static String PasswordEncrypt(String password)
{
return SecurityUtils.AESEncrypt(password,USER_PASSWORD_PREFIX);
}
/// <summary>
/// 用户密码解密
/// </summary>
/// <param name="password"></param>
/// <returns></returns>
public static String PasswordDecrypt(String password)
{
return SecurityUtils.AESDecrypt(password,USER_PASSWORD_PREFIX);
}
/// <summary>
/// 获取GUID
/// </summary>
/// <returns></returns>
public static String RandomGUID()
{
return Guid.NewGuid().ToString();
}
}
}
|
using System;
using System.Collections.Generic;
[Serializable]
public class TodayData
{
public enum CaffeineType
{
Coffee = 1,
Tea = 2,
EnergyDrink = 3,
Other = 4
}
[ReadOnlyField]
public string version = "00.00.00";
public DateTime timestamp = new DateTime();
public List<CaffeineType> caffeineData = new List<CaffeineType>();
[UnityEngine.Range(0, 7)]
public int motivation = 4;
[UnityEngine.Range(0, 7)]
public int happiness = 4;
public string gameOfTheDay = "N/A";
[UnityEngine.TextArea(10, 20)]
public string diary = "";
public TodayData(DateTime dateTime)
{
timestamp = dateTime;
version = TodayManager.Instance.Version;
}
}
|
static public int TitleToNumber(string s) {
int number = 0;
int deliver = 1;
char[] chars = s.ToCharArray();
int length = chars.Length;
for (int i = length - 1; i >= 0; i--) {
number += (chars[i] - 65 + 1) * deliver;
deliver *= 26;
}
return number;
} |
using AutoMapper;
using GeekBurger.Productions.Contracts;
using GeekBurger.Productions.Models;
using GeekBurger.Productions.Repository;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using GeekBurger.Productions.Helper;
using UnprocessableEntityResult = GeekBurger.Productions.Helper.UnprocessableEntityResult;
namespace GeekBurger.Productions.Controllers
{
[ApiController]
[Route("api/production")]
public class ProductionsController : Controller
{
List<Production> Productions;
private IProductionRepository _productionRepository;
private IMapper _mapper;
public ProductionsController(IProductionRepository productionRepository)
{
_productionRepository = productionRepository;
this.Productions = new List<Production>();
this.Productions.Add(new Production() {
ProductionId = new Guid("abcfa5f5-5af2-44c8-87a0-f58f3a3c6a08"),
//Restrictions = new List<string>() { "tomatoes", "potatoes", "onions" },
Restrictions = "tomatoes " + "potatoes " + "onions",
On = true
});
this.Productions.Add(new Production()
{
ProductionId = new Guid("101dd3d3-8e85-4e22-a2c4-735f6b9163ee"),
//Restrictions = new List<string>() { "guten", "milk", "sugar" },
Restrictions = "tomatoes " + "potatoes " + "onions",
On = true
});
this.Productions.Add(new Production()
{
ProductionId = new Guid("832d7db2-d1ca-4b03-85a4-f4d9a7df597e"),
//Restrictions = new List<string>() { "soy", "dairy", "gluten", "peanut" },
Restrictions = "tomatoes " + "potatoes " + "onions",
On = true
});
}
[HttpGet("{guid}")]
public IActionResult GetProductionByProductionin(Guid guid)
{
List<Production> productions = this.Productions.Where(p => p.ProductionId == guid).ToList();
if (productions.Count == 0)
{
return NotFound();
}
return Ok(productions);
}
[HttpGet("")]
public IActionResult GetAllProductions()
{
List<Production> productions = this.Productions.ToList();
if (productions.Count == 0)
{
return NotFound();
}
return Ok(productions);
}
[HttpGet("areas")]
public Production GetAreas()
{
var guid = new Guid("8048e9ec-80fe-4bad-bc2a-e4f4a75c834e");
return new Models.Production
{
ProductionId = guid,
//Restrictions = new List<string>() { "soy", "dairy", "gluten", "peanut" },
Restrictions = "tomatoes " + "potatoes " + "onions",
On = false
};
}
[HttpPost()]
public IActionResult AddProduction([FromBody] Production productionToAdd)
{
if (productionToAdd == null)
return BadRequest();
var production = productionToAdd;//_mapper.Map<Production>(productionToAdd);
if (production.ProductionId == Guid.Empty)
return new UnprocessableEntityResult(ModelState);
_productionRepository.Add(production);
_productionRepository.Save();
var productionToGet = _mapper.Map<Production>(production);
return CreatedAtRoute("GetProduction",
new { id = productionToGet.ProductionId },
productionToGet);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace VSchool.Data.Entities
{
public class Quize : BaseEntity
{
public string Case { get; set; }
public int Type { get; set; }
public ICollection<Question> Questions { get; set; }
}
}
|
namespace CompressionStocking
{
public interface ICompressionMechanism
{
void Compress();
void Decompress();
void Stop();
}
} |
using System.Threading.Tasks;
using APIHealthChecker.Repositories;
using NUnit.Framework;
using Xamarin.UITest;
using System.Linq;
using Xamarin.UITest.Queries;
using APIHealthChecker.Services;
namespace UnitTests
{
[TestFixture(Platform.Android)]
public class Tests
{
IApp app;
Platform platform;
public Tests(Platform platform)
{
this.platform = platform;
}
[SetUp]
public void BeforeEachTest()
{
app = AppInitializer.StartApp(platform);
}
[Test]
public async Task Must_Return_API_EndPoint()
{
var mobApp = await MobAppRepo.GetMobApp("Guess");
Assert.IsNotNull(mobApp);
Assert.IsNotEmpty(mobApp.EndPoints);
}
[Test]
public async Task Must_Successfull_Test_Endpoint()
{
var testResult = await EndPointTestService.TestEndPoint("https://jsonplaceholder.typicode.com/posts", false);
Assert.IsNotNull(testResult);
Assert.IsTrue(testResult.IsWorking);
}
[Test]
public async Task Must_Successfull_Get_AppList()
{
var testResult = await MobAppRepo.GetAllAppNames();
Assert.IsNotNull(testResult);
Assert.IsNotEmpty(testResult);
}
}
}
|
using System;
using System.Linq;
namespace Jamie.Model
{
public enum ListEntryStatus
{ IsOK = 0x1, IsCalculated, IsNotConfirmed }
public class AllDataSets
{
//Variables
private FoodPlanItemSet _FoodPlanItems; //related to Recipes
private IngredientSet _Ingredients; //related to <no other Set>
private RecipeSet _Recipes; // related to Ingredients, Units
private ShoppingListItemSet _ShoppingListItems; //related to Ingredients, Units
private UnitSet _Units; // related to <no other Set>
private UnitTranslationSet _UnitTranslations; //related to Units
//Constructors
public AllDataSets()
{
_Units = new UnitSet();
_UnitTranslations = new UnitTranslationSet(_Units);
_Ingredients = new IngredientSet(_Units);
_Recipes = new RecipeSet(_Units, _Ingredients);
_FoodPlanItems = new FoodPlanItemSet();
_ShoppingListItems = new ShoppingListItemSet();
SetDataReference();
}
public AllDataSets(bool ToBePopulatedWithDefaults)
{
_Units = new UnitSet();
_UnitTranslations = new UnitTranslationSet(_Units);
_Ingredients = new IngredientSet(_Units);
_Recipes = new RecipeSet(_Units, _Ingredients);
_FoodPlanItems = new FoodPlanItemSet();
_ShoppingListItems = new ShoppingListItemSet();
SetDataReference();
if (ToBePopulatedWithDefaults) PopulateSetWithDefaults();
}
//Properties
public FoodPlanItemSet FoodPlanItems
{
get
{
return _FoodPlanItems;
}
set
{
_FoodPlanItems = value;
}
}
public IngredientSet Ingredients
{
get
{
return _Ingredients;
}
set
{
_Ingredients = value;
}
}
public RecipeSet Recipes
{
get { return _Recipes; }
set { _Recipes = value; }
}
public ShoppingListItemSet ShoppingListItems
{
get
{
return _ShoppingListItems;
}
set
{
_ShoppingListItems = value;
}
}
public UnitSet Units
{
get { return _Units; }
set { _Units = value; }
}
public UnitTranslationSet UnitTranslations
{
get { return _UnitTranslations; }
set { _UnitTranslations = value; }
}
//Methods
public void ClearList()
{
FoodPlanItems.Clear();
Ingredients.Clear();
Recipes.Clear();
ShoppingListItems.Clear();
Units.Clear();
UnitTranslations.Clear();
EvaluateMaxIDs();
}
public void EvaluateMaxIDs()
{
Ingredients.EvaluateMaxID();
FoodPlanItems.EvaluateMaxID();
Recipes.EvaluateMaxID();
Units.EvaluateMaxID();
UnitTranslations.EvaluateMaxID();
ShoppingListItems.EvaluateMaxID();
}
public void PopulateSetWithDefaults()
{
Units.PopulateSetWithDefaults();
UnitTranslations.PopulateSetWithDefaults();
Ingredients.PopulateSetWithDefaults();
}
public void SetDataReference()
{
_UnitTranslations.SetDataReference(_Ingredients, _Units);
_Ingredients.SetDataReference(_Units);
_Recipes.SetDataReference(_Ingredients, _Units, _UnitTranslations);
_FoodPlanItems.SetDataReference(_Recipes);
_ShoppingListItems.SetDataReference(_Ingredients, _Units, _UnitTranslations);
Jamie.View.ListHelper.SetDataReference(_Ingredients, _Recipes, _Units);
}
public void SaveSet(string FileName)
{
Units.SaveSet(FileName);
UnitTranslations.SaveSet(FileName);
Ingredients.SaveSet(FileName);
Recipes.SaveSet(FileName);
FoodPlanItems.SaveSet(FileName);
}// --> Data
public void ViewSet()
{
Console.WriteLine();
Console.WriteLine(ToString());
}// --> View
public override string ToString()
{
string ReturnString = "";
ReturnString += FoodPlanItems.ToString();
ReturnString += Ingredients.ToString();
ReturnString += Recipes.ToString();
ReturnString += Units.ToString();
ReturnString += UnitTranslations.ToString();
ReturnString += ShoppingListItems.ToString();
return ReturnString;
}
public void ViewXML()
{
Console.WriteLine();
Console.WriteLine("XML Ausgabe der Listen:");
if (Units.Count == 0) Console.WriteLine("-------> Alle Listen leer <-------");
else
{
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(GetType());
x.Serialize(Console.Out, this);
}
}// --> View
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class ScreenTrigger : Walls
{
public UnityEvent OnTrigger;
public override void OnHit()
{
OnTrigger.Invoke();
}
}
|
using Newtonsoft.Json;
namespace Lykke.Service.SmsSender.Services.SmsSenders.Nexmo
{
public class NexmoResponse
{
[JsonProperty("message-count")]
public int MessagesCount { get; set; }
public NexmoMessage[] Messages { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DisplayScreenInteraction : Interactable
{
public GameObject screen;
public bool hideOnReset = false;
public Checkpoints RelatedCheckpoint;
protected override void OnStart()
{
GameManager.OnReset += Reset;
base.OnStart();
}
void Reset()
{
if (hideOnReset)
{
screen.SetActive(false);
}
if(RelatedCheckpoint == Checkpoints.GunRoomComplete && !GameManager.Instance.CheckpointList[(int)RelatedCheckpoint])
{
screen.SetActive(false);
}
}
protected override void OnInteract(ref InteractionEvent ev)
{
base.OnInteract(ref ev);
screen.SetActive(!screen.activeSelf);
}
}
|
// -----------------------------------------------------------------------
// <copyright file="SharedConfigDictionaryLookup.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root
// for license information.
// </copyright>
// -----------------------------------------------------------------------
using System;
using Mlos.Core;
using Mlos.Core.Collections;
namespace Proxy.Mlos.Core.Internal
{
/// <summary>
/// SharedConfigDictionary lookup implementation based on the given hash table probing policy.
/// </summary>
/// <typeparam name="TProbingPolicy">Probing policy.</typeparam>
internal static class SharedConfigDictionaryLookup<TProbingPolicy>
where TProbingPolicy : IProbingPolicy
{
/// <summary>
/// Internal lookup. TProxy type is deduced by the caller.
/// </summary>
/// <typeparam name="TProxy">Codegen proxy type.</typeparam>
/// <param name="sharedConfigDictionary"></param>
/// <param name="codegenKey"></param>
/// <param name="slotIndex"></param>
/// <returns></returns>
internal static SharedConfig<TProxy> Get<TProxy>(
SharedConfigDictionary sharedConfigDictionary,
ICodegenKey codegenKey,
ref uint slotIndex)
where TProxy : ICodegenProxy, new()
{
TProbingPolicy probingPolicy = default;
uint probingCount = 0;
slotIndex = 0;
UIntArray configsArray = sharedConfigDictionary.ConfigsOffsetArray;
uint elementCount = configsArray.Count;
ProxyArray<uint> sharedConfigsOffsets = configsArray.Elements;
SharedConfig<TProxy> sharedConfig = default;
while (true)
{
slotIndex = probingPolicy.CalculateIndex(codegenKey, ref probingCount, elementCount);
uint offsetToSharedConfig = sharedConfigsOffsets[(int)slotIndex];
if (offsetToSharedConfig == 0)
{
// Slot entry is empty.
//
sharedConfig.Buffer = IntPtr.Zero;
break;
}
// Compare the object keys.
// Create a proxy to the shared config.
//
sharedConfig.Buffer = sharedConfigDictionary.Buffer - sharedConfigDictionary.Allocator.OffsetToAllocator + (int)offsetToSharedConfig;
// Compare key with the proxy.
//
bool foundEntry = codegenKey.CodegenTypeIndex() == sharedConfig.Header.CodegenTypeIndex
&& codegenKey.CompareKey(sharedConfig.Config);
if (foundEntry)
{
break;
}
++probingCount;
}
return sharedConfig;
}
/// <summary>
/// Add a new shared config.
/// </summary>
/// <typeparam name="TType">Codegen config type.</typeparam>
/// <typeparam name="TProxy">Codegen proxy type.</typeparam>
/// <param name="sharedConfigDictionary"></param>
/// <param name="componentConfig"></param>
internal static void Add<TType, TProxy>(
SharedConfigDictionary sharedConfigDictionary,
ComponentConfig<TType, TProxy> componentConfig)
where TType : ICodegenType, new()
where TProxy : ICodegenProxy<TType, TProxy>, new()
{
uint slotIndex = 0;
SharedConfig<TProxy> sharedConfig = Get<TProxy>(sharedConfigDictionary, componentConfig.Config, ref slotIndex);
if (sharedConfig.Buffer != IntPtr.Zero)
{
throw new ArgumentException("Config already present", nameof(componentConfig));
}
TType config = componentConfig.Config;
// Calculate size to allocate.
//
sharedConfig = sharedConfigDictionary.Allocator.Allocate<SharedConfig<TProxy>>();
// Update hash map
//
ProxyArray<uint> sharedConfigOffsets = sharedConfigDictionary.ConfigsOffsetArray.Elements;
// #TODO verify.
sharedConfigOffsets[(int)slotIndex] = (uint)sharedConfig.Buffer.Offset(sharedConfigDictionary.Buffer - sharedConfigDictionary.Allocator.OffsetToAllocator);
// Copy header, copy config.
//
SharedConfigHeader sharedHeader = sharedConfig.Header;
TProxy configProxy = sharedConfig.Config;
// Initialize header.
//
sharedHeader.ConfigId.Store(1);
sharedHeader.CodegenTypeIndex = config.CodegenTypeIndex();
// Copy the config to proxy.
//
CodegenTypeExtensions.Serialize(componentConfig.Config, sharedConfig.Config.Buffer);
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using Fundamentals.Models.Validation;
namespace Fundamentals.DomainModel
{
public class CustomerViewModel
{
[Key]
[Required]
public int Id { get; set; }
[Required]
[StringLength(50)]
public string FirstName { get; set; }
[Required]
[StringLength(50)]
public string LastName { get; set; }
[Required]
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
[CustomerValidation]
public DateTime BirthDate { get; set; }
}
} |
using System;
using System.Linq;
using GlmNet;
using System.Collections.Generic;
using System.Diagnostics;
namespace Tracer
{
class RayTracer
{
public static int ImageWidth = 512;
public static int ImageHeight = 512;
private const float FieldOfView = 60.0f;
private const int MaxDepth = 3;
private List<SceneObject> sceneObjects = new List<SceneObject>();
private Camera camera;
public RayTracer()
{
InitScene();
}
void InitScene()
{
camera = new Camera(new vec3(0.0f, 6.0f, 8.0f), // Where the camera is
new vec3(0.0f, -.8f, -1.0f), // The point it is looking at
FieldOfView, // The field of view of the 'lens'
ImageWidth, ImageHeight); // The size in pixels of the view plane
// Red ball
Material mat = new Material();
mat.albedo = new vec3(.7f, .1f, .1f);
mat.specular = new vec3(.9f, .1f, .1f);
mat.reflectance = 0.5f;
sceneObjects.Add(new Sphere(mat, new vec3(0.0f, 2.0f, 0.0f), 2.0f));
// Red ball
mat.albedo = new vec3(.1f, .7f, .1f);
mat.specular = new vec3(.9f, .1f, .1f);
mat.reflectance = 0.2f;
sceneObjects.Add(new Sphere(mat, new vec3(0.0f, 0.0f, 4.0f), 1.0f));
// Purple ball
mat.albedo = new vec3(0.7f, 0.0f, 0.7f);
mat.specular = new vec3(0.9f, 0.9f, 0.8f);
mat.reflectance = 0.5f;
sceneObjects.Add(new Sphere(mat, new vec3(-2.5f, 1.0f, 2.0f), 1.0f));
// Blue ball
mat.albedo = new vec3(0.0f, 0.3f, 1.0f);
mat.specular = new vec3(0.0f, 0.0f, 1.0f);
mat.reflectance = 0.0f;
mat.emissive = new vec3(0.0f, 0.0f, 0.0f);
sceneObjects.Add(new Sphere(mat, new vec3(-0.0f, 0.5f, 3.0f), 0.5f));
// Green ball
mat.albedo = new vec3(1.0f, 1.0f, 1.0f);
mat.specular = new vec3(0.0f, 0.0f, 0.0f);
mat.reflectance = 0.0f;
mat.emissive = new vec3(2.0f, 2.0f, 2.0f);
sceneObjects.Add(new Sphere(mat, new vec3(2.8f, 0.8f, 2.0f), 0.8f));
// White light
mat.albedo = new vec3(0.0f, 0.8f, 0.0f);
mat.specular = new vec3(0.0f, 0.0f, 0.0f);
mat.reflectance = 0.0f;
mat.emissive = new vec3(1.0f, 1.0f, 1.0f);
sceneObjects.Add(new Sphere(mat, new vec3(-10.8f, 6.4f, 10.0f), 0.4f));
sceneObjects.Add(new TiledPlane(new vec3(0.0f, 0.0f, 0.0f), new vec3(0.0f, 1.0f, 0.0f)));
}
// Trace a ray into the scene, return the accumulated light value
vec3 TraceRay(vec3 rayorig, vec3 raydir, int depth)
{
// Walk the scene objects
//Step 1
//var distance = 0f;
//if (obj.Intersects(rayorig, raydir, out distance))
//{
// var material = obj.GetMaterial(rayorig + (raydir * distance));
// return material.albedo;
//}
foreach (var obj in sceneObjects)
{
var distance = 0f;
if (obj.Intersects(rayorig, raydir, out distance))
{
var intersectionPoint = rayorig + (raydir * distance);
var normal = obj.GetSurfaceNormal(intersectionPoint);
var material = obj.GetMaterial(intersectionPoint);
var lightSource = new vec3(-raydir.x, -raydir.y, -raydir.z);
var lightIntensity = glm.dot(normal, lightSource);
if (lightIntensity < 0) lightIntensity = 0;
var colour = material.emissive;// new vec3(0, 0, 0);// material.albedo * lightIntensity;
foreach (var possibleLight in sceneObjects)
{
var possibleLightMaterial = possibleLight.GetMaterial(rayorig + (raydir * distance));
var emissive = possibleLightMaterial.emissive;
if (emissive.x != 0 || emissive.y != 0 || emissive.z != 0)
{
var fromObjectToLight = possibleLight.GetRayFrom(intersectionPoint);
var inTheWay = false;
float distanceToLight;
possibleLight.Intersects(intersectionPoint, fromObjectToLight, out distanceToLight);
foreach (var occluder in sceneObjects)
{
float distancetooccluder;
if (occluder.Intersects(intersectionPoint, fromObjectToLight, out distancetooccluder))
{
if (distancetooccluder > 0.01f && distancetooccluder < distanceToLight)
inTheWay = true;
}
}
if (!inTheWay)
{
var lightIntensity2 = glm.dot(normal, fromObjectToLight);
if (lightIntensity2 < 0) lightIntensity2 = 0;
var reflectionVector = GeometryMath.reflect(raydir, normal);
var specularIntensity = glm.dot(reflectionVector, fromObjectToLight);
specularIntensity = Math.Max(0, specularIntensity);
var specularIntensityColour = (float)Math.Pow(specularIntensity, 10) * material.specular * possibleLightMaterial.emissive;
colour = colour + (material.albedo * emissive * lightIntensity2) + specularIntensityColour;
}
}
}
if (material.reflectance > 0 && depth < 3)
{
var reflectionVector = GeometryMath.reflect(raydir, normal);
var newColour = TraceRay(intersectionPoint + (reflectionVector * 0.01f), reflectionVector, depth + 1);
colour = colour + (newColour * material.reflectance);
}
colour.x = Math.Max(0, colour.x);
colour.y = Math.Max(0, colour.y);
colour.z = Math.Max(0, colour.z);
colour.x = Math.Min(1, colour.x);
colour.y = Math.Min(1, colour.y);
colour.z = Math.Min(1, colour.z);
return colour;
}
}
// For now, just convert the incoming ray to a 'color' to display it has it changes
return new vec3((raydir * .5f) + new vec3(0.5f, 0.5f, 0.5f));
}
public unsafe void Run(byte* pData, int stride)
{
for (int y = 0; y < ImageHeight; y++)
{
for (int x = 0; x < ImageWidth; x++)
{
vec3 color1 = TraceTheRay(y, x, 0.1f, 0.2f);
vec3 color2 = TraceTheRay(y, x, 0.3f, 0.4f);
vec3 color3 = TraceTheRay(y, x, 0.5f, 0.6f);
vec3 color4 = TraceTheRay(y, x, 0.7f, 0.8f);
var color = new vec3(((color1.x + color2.x + color3.x + color4.x) / 4),
((color1.y + color2.y + color3.y + color4.y) / 4),
((color1.z + color2.z + color3.z + color4.z) / 4));
color *= 255.0f;
// Better way to do this in C# ?
UInt32 outColor = ((UInt32)color.x << 16) | ((UInt32)color.y << 8) | ((UInt32)color.z) | 0xFF000000;
var pPixel = (UInt32*)(pData + (y * stride) + (x * 4));
*pPixel = outColor;
}
}
}
private unsafe vec3 TraceTheRay(int y, int x, float yOffset, float xOffet)
{
vec2 coord = new vec2((float)x + xOffet, (float)y + yOffset);
var ray = camera.GetWorldRay(coord);
// Fire a ray through this pixel, into the world
vec3 color = TraceRay(camera.Position, ray, 0);
return color;
}
}
}
|
using Ambassador.Models.AnnouncementModels.Interfaces;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.ComponentModel.DataAnnotations;
namespace Ambassador.Areas.Admin.Models.AnnouncementViewModels
{
public class AdminAnnouncementCreateViewModel : IAdminCreateAnnouncementModel
{
[Required]
public string Message { get; set; }
public string Url { get; set; }
[Required]
public string ForUserType { get; set; }
public SelectList UserTypesSelectList { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Web;
namespace BPiaoBao.Web.SupplierManager.Controllers.Helpers
{
public class ClientInterpector : IClientMessageInspector
{
public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
{
}
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
{
var tokenHeader = MessageHeader.CreateHeader("Token", "http://tempuri.org/", HttpContext.Current.Request.Cookies["auth"].Values["token"]);
request.Headers.Add(tokenHeader);
return null;
}
}
} |
using System;
using System.Windows.Forms;
using Entity;
using Business;
namespace QuanLyTiemGiatLa.Danhmuc
{
public partial class frmCatDo : Form
{
private Boolean _cothaydoi = false;
private String _khoBefore = String.Empty;
private Int32 _slotBefore = 0;
private Int32 _cotKho = 0;
private Int32 _cotSlot = 0;
private Int32 _cotDaTra = 0;
private Int32 _cotNgayTra = 0;
private Int32 _cotMaVach = 0;
private ListPhieuSlotEntity _lstPhieuSlotBefore = null;
public frmCatDo()
{
InitializeComponent();
this.Load += new EventHandler(frmCatDo_Load);
this.FormClosing += new FormClosingEventHandler(frmCatDo_FormClosing);
dgvDSCatDo.CellBeginEdit += new DataGridViewCellCancelEventHandler(dgvDSCatDo_CellBeginEdit);
dgvDSCatDo.CellEndEdit += new DataGridViewCellEventHandler(dgvDSCatDo_CellEndEdit);
}
private void frmCatDo_Load(object sender, EventArgs e)
{
Xuly.Xuly.ToanManHinh(this);
if (BienChung.isToanManHinh)
dgvDSCatDo.Columns["ghichuDataGridViewTextBoxColumn"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
else
dgvDSCatDo.Columns["ghichuDataGridViewTextBoxColumn"].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
this.TimCotKhoSlot();
}
public void focusMa()
{
if (Xuly.ThaoTacIniCauHinhPhanMem.ReadCatdoFocus() == 0)
txtMaPhieu.Focus();
else
txtMaVach.Focus();
}
private void frmCatDo_FormClosing(object sender, FormClosingEventArgs e)
{
if (_cothaydoi && MessageBox.Show("Bạn chưa lưu, bạn có muốn lưu không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
btnGhi_Click(sender, e);
}
}
private void TimCotKhoSlot()
{
for (int i = 0; i < dgvDSCatDo.ColumnCount; i++)
{
if (dgvDSCatDo.Columns[i].Name == "khoDataGridViewTextBoxColumn")
_cotKho = i;
else if (dgvDSCatDo.Columns[i].Name == "slotDataGridViewTextBoxColumn")
_cotSlot = i;
else if (dgvDSCatDo.Columns[i].Name == "daTraDataGridViewCheckBoxColumn")
_cotDaTra = i;
else if (dgvDSCatDo.Columns[i].Name == "NgayTraDataGridViewTextBoxColumn")
_cotNgayTra = i;
else if (dgvDSCatDo.Columns[i].Name == "maVachDataGridViewTextBoxColumn")
_cotMaVach = i;
}
}
private void dgvDSCatDo_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
try
{
if ((e.ColumnIndex != _cotKho) && (e.ColumnIndex != _cotSlot)) return;
_khoBefore = dgvDSCatDo[_cotKho, e.RowIndex].Value.ToString();
_slotBefore = Convert.ToInt32(dgvDSCatDo[_cotSlot, e.RowIndex].Value);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void RollBack(Int32 rowIndex)
{
dgvDSCatDo[_cotKho, rowIndex].Value = _khoBefore;
dgvDSCatDo[_cotSlot, rowIndex].Value = _slotBefore;
}
private void dgvDSCatDo_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
try
{
if (e.ColumnIndex == _cotDaTra)
{
bool datra = (bool)dgvDSCatDo[_cotDaTra, e.RowIndex].Value;
if (datra)
{
dgvDSCatDo[_cotNgayTra, e.RowIndex].Value = DateTime.Now.ToString("dd/MM/yyyy HH:mm");
}
else
{
dgvDSCatDo[_cotNgayTra, e.RowIndex].Value = "";
}
}
if ((e.ColumnIndex != _cotKho) && (e.ColumnIndex != _cotSlot)) return;
String kho = dgvDSCatDo[_cotKho, e.RowIndex].Value == null ?
String.Empty :
dgvDSCatDo[_cotKho, e.RowIndex].Value.ToString();
Int32 slot = Convert.ToInt32(dgvDSCatDo[_cotSlot, e.RowIndex].Value);
if (slot == 0) return;
Int64 ngoaitrumaphieunay = Convert.ToInt64(dgvDSCatDo[0, e.RowIndex].Value);
String findMaphieuTreoCungMoc = Business.PhieuSlotBO.SelectByKhoSlot(kho, slot, ngoaitrumaphieunay);
if (!String.IsNullOrEmpty(findMaphieuTreoCungMoc))
{
if (MessageBox.Show("Giá này đã được sử dụng bởi phiếu '" + findMaphieuTreoCungMoc + "'"
+ "\nBạn có muốn chèn vào không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
== DialogResult.No)
{
this.RollBack(e.RowIndex);
return;
}
}
_cothaydoi = true;
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void VeDataGrid()
{
System.Drawing.Color colorve;
ListPhieuSlotEntity phieuSlotTrenCSDL = bndsrcDSCatDo.DataSource as ListPhieuSlotEntity;
if (phieuSlotTrenCSDL != null)
{
for (int i = 0; i < phieuSlotTrenCSDL.Count; i++)
{
bool datra = (bool)phieuSlotTrenCSDL[i].DaTra;
if (datra) colorve = BienChung.mautrangthaido.DaTra;
else if (!String.IsNullOrEmpty(phieuSlotTrenCSDL[i].GhiChu))
colorve = BienChung.mautrangthaido.GhiChu;
else if (phieuSlotTrenCSDL[i].Slot != 0)
colorve = BienChung.mautrangthaido.DaGiat;
else colorve = BienChung.mautrangthaido.ChuaGiat;
for (int k = 0; k < dgvDSCatDo.ColumnCount; k++)
dgvDSCatDo.Rows[i].Cells[k].Style.ForeColor = colorve;
dgvDSCatDo.Rows[i].Cells["daTraDataGridViewCheckBoxColumn"].ReadOnly = datra;
dgvDSCatDo.Rows[i].Cells["khoDataGridViewTextBoxColumn"].ReadOnly = datra;
dgvDSCatDo.Rows[i].Cells["slotDataGridViewTextBoxColumn"].ReadOnly = datra;
}
}
}
private void btnSearch_Click(object sender, EventArgs e)
{
try
{
btnSearch.Enabled = false;
this.LoadData();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
btnSearch.Enabled = true;
}
}
private Boolean CheckForm(out Int64 maphieu, out Int64 mavach)
{
maphieu = 0;
mavach = 0;
txtTenDo.Text = txtTenDo.Text.Trim();
//if (String.IsNullOrEmpty(txtMaPhieu.Text) && String.IsNullOrEmpty(txtMaVach.Text) && string.IsNullOrEmpty(txtTenDo.Text))
//{
// MessageBox.Show("Chưa có tiêu chí tìm kiếm!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
// txtMaPhieu.Focus();
// return false;
//}
if (!String.IsNullOrEmpty(txtMaPhieu.Text) && !Int64.TryParse(txtMaPhieu.Text, out maphieu))
{
MessageBox.Show("Mã phiếu phải là số!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
txtMaPhieu.Focus();
txtMaPhieu.SelectAll();
return false;
}
if (!String.IsNullOrEmpty(txtMaVach.Text) && !Int64.TryParse(txtMaVach.Text, out mavach))
{
MessageBox.Show("Mã vạch phải là số!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
txtMaVach.Focus();
txtMaVach.SelectAll();
return false;
}
//if (maphieu > 0 && mavach > 0)
//{
// MessageBox.Show("Bạn chỉ được điền mã phiếu hoặc mã vạch!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
// txtMaPhieu.Focus();
// txtMaPhieu.SelectAll();
// return false;
//}
return true;
}
private void LoadData()
{
try
{
Int64 maphieu, mavach;
if (!this.CheckForm(out maphieu, out mavach)) return;
ListPhieuSlotEntity lstPSTemp = null;
if (maphieu > 0 && mavach == 0)
lstPSTemp = Business.PhieuSlotBO.SelectByMaPhieu_TenDo(maphieu, txtTenDo.Text, chkTimTheoNgay.Checked, dtpTuNgay.Value, dtpDenNgay.Value, chkPhieuChuaTra.Checked);
else if (maphieu == 0 && mavach > 0)
lstPSTemp = Business.PhieuSlotBO.SelectByMaVach_TenDo(mavach, txtTenDo.Text, chkTimTheoNgay.Checked, dtpTuNgay.Value, dtpDenNgay.Value, chkPhieuChuaTra.Checked);
else if (maphieu == 0 && mavach == 0)
lstPSTemp = Business.PhieuSlotBO.SelectByMaPhieu_TenDo(maphieu, txtTenDo.Text, chkTimTheoNgay.Checked, dtpTuNgay.Value, dtpDenNgay.Value, chkPhieuChuaTra.Checked);
else
{ // chả bao h nhảy vào đây
lstPSTemp = null;
MessageBox.Show("Bạn chưa chọn tiêu chí tìm kiếm", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
bndsrcDSCatDo.DataSource = lstPSTemp;
_lstPhieuSlotBefore = Xuly.Xuly.CopyListPhieuSlot(lstPSTemp);
VeDataGrid();
if (dgvDSCatDo.RowCount > 0)
{
int focusrow = 0;
if (mavach > 0 && _cotMaVach > 0)
for (int i = 0; i < dgvDSCatDo.RowCount; i++)
if (dgvDSCatDo[_cotMaVach, i].Value.ToString() == mavach.ToString()) { focusrow = i; break; }
dgvDSCatDo.Focus();
dgvDSCatDo.CurrentCell = dgvDSCatDo[_cotKho, focusrow];
dgvDSCatDo.CurrentCell.Selected = true;
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnCollapse_Click(object sender, EventArgs e)
{
splitContainer1.Panel1Collapsed = !splitContainer1.Panel1Collapsed;
btnCollapse.Text = splitContainer1.Panel1Collapsed ? ">>" : "<<";
}
private void btnGhi_Click(object sender, EventArgs e)
{
dgvDSCatDo.EndEdit();
ListPhieuSlotEntity listPhieuSlot = bndsrcDSCatDo.DataSource as ListPhieuSlotEntity;
if (listPhieuSlot != null)
{
Xuly.Xuly.CapNhatThoiDiemLuu(_lstPhieuSlotBefore, listPhieuSlot);
Business.PhieuSlotBO.Update(listPhieuSlot);
_lstPhieuSlotBefore = Xuly.Xuly.CopyListPhieuSlot(listPhieuSlot);
VeDataGrid();
MessageBox.Show("Cập nhật thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
_cothaydoi = false;
}
private void btnThoat_Click(object sender, EventArgs e)
{
this.Close();
}
private void dgvDSCatDo_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
try
{
if (e.RowIndex < 0) return;
var row = dgvDSCatDo.Rows[e.RowIndex];
var phieuslot = new PhieuSlotEntity()
{
MaPhieu = Convert.ToInt64(row.Cells["maPhieuDataGridViewTextBoxColumn"].Value),
STT = Convert.ToInt32(row.Cells["sTTDataGridViewTextBoxColumn"].Value),
MaVach = Convert.ToInt64(row.Cells["maVachDataGridViewTextBoxColumn"].Value),
TenHang = row.Cells["tenHangDataGridViewTextBoxColumn"].Value.ToString(),
TenKieuGiat = row.Cells["tenKieuGiatDataGridViewTextBoxColumn"].Value.ToString(),
Kho = row.Cells["khoDataGridViewTextBoxColumn"].Value.ToString(),
Slot = Convert.ToInt32(row.Cells["slotDataGridViewTextBoxColumn"].Value),
GhiChu = row.Cells["ghichuDataGridViewTextBoxColumn"].Value.ToString(),
DaTra = (bool)row.Cells[_cotDaTra].Value
};
frmCTCatDo frm = new frmCTCatDo(phieuslot);
frm.onsaved = new OnSaved(this.LoadData);
frm.ShowDialog(this);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ghiToolStripMenuItem_Click(object sender, EventArgs e)
{
if (btnGhi.Enabled) btnGhi_Click(sender, e);
}
private void btnXemPhieu_Click(object sender, EventArgs e)
{
try
{
Int64 maphieu = Convert.ToInt64(dgvDSCatDo.Rows[dgvDSCatDo.SelectedCells[0].RowIndex].Cells["maPhieuDataGridViewTextBoxColumn"].Value);
frmLapPhieu frm = new frmLapPhieu();
frm._phieu = new PhieuEntity() { MaPhieu = maphieu };
frm.onsaved = new OnSaved(this.LoadData);
frm.ShowDialog();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void xemPhieuToolStripMenuItem_Click(object sender, EventArgs e)
{
if (btnXemPhieu.Enabled) btnXemPhieu_Click(sender, e);
}
private void xemKhachHangToolStripMenuItem_Click(object sender, EventArgs e)
{
btnXemKhachHang_Click(null, null);
}
private void btnXemKhachHang_Click(object sender, EventArgs e)
{
try
{
if (dgvDSCatDo.RowCount == 0) return;
var rowIndex = dgvDSCatDo.SelectedCells[0].RowIndex;
Int64 maphieu = Convert.ToInt64(dgvDSCatDo["maPhieuDataGridViewTextBoxColumn", rowIndex].Value);
KhachHangEntity kh = KhachHangBO.SelectByMaPhieu(maphieu);
if (kh != null)
{
txtTenKhachHang.Text = kh.TenKhachHang;
txtSoDienThoai.Text = kh.DienThoai;
}
else
{
txtTenKhachHang.Text = string.Empty;
txtSoDienThoai.Text = string.Empty;
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void chkTimTheoNgay_CheckedChanged(object sender, EventArgs e)
{
lblTuNgay.Visible = chkTimTheoNgay.Checked;
lblDenNgay.Visible = chkTimTheoNgay.Checked;
dtpTuNgay.Visible = chkTimTheoNgay.Checked;
dtpDenNgay.Visible = chkTimTheoNgay.Checked;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using database;
namespace LogOutProCesS
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello Server LogOut check");
while (true)
{
Console.WriteLine("Beginning logout loop");
Console.WriteLine("Updating lastlogin for players.... at " + DateTime.Now);
foreach (Players p in Players.GetAll())
{
if (DateTime.Compare(p.LastLogin.AddMinutes(10), DateTime.Now) < 0 && p.LastLogin != new DateTime())
{
Console.WriteLine("User logedOut: Player " + p.ScreenName + " son last login : " + p.LastLogin);
Players.LogOff(p.Id);
}
}
Console.WriteLine("Deleting anonymous users..");
foreach (Anon anon in Anon.GetAll())
{
if (DateTime.Compare(anon.LastLogin.AddMinutes(10), DateTime.Now) < 0)
{
Console.WriteLine("User logedOut: Anonymous n°" + anon.Id);
Anon.LogOut(anon.Id);
}
}
Console.WriteLine("Waiting for 10 minutes until new loop...");
Thread.Sleep(600000);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TodoBeBlue.Dados.Repositorios;
using TodoBeBlue.Dominio;
namespace TodoBeBlue.Controllers
{
public class TodosController : ApiController
{
public TodoRepositorio todoRepositorio { get; set; }
public TodosController()
{
todoRepositorio = new TodoRepositorio();
}
// GET api/todos
[HttpGet]
public IEnumerable<Todo> Get()
{
var todos = todoRepositorio.GetAll().ToList();
return todos;
}
// GET api/todos/5
public Todo Get(int id)
{
return todoRepositorio.GetById(id);
}
// POST api/todos
public void Post([FromBody]Todo todo)
{
if (todo.CategoriaId == 0 || string.IsNullOrEmpty(todo.Descricao))
return;
todoRepositorio.Add(todo);
todoRepositorio.Commit();
}
// PUT api/todos/5
public void Put([FromBody]Todo todo)
{
todoRepositorio.Edit(todo.TodoId, todo.Feito);
todoRepositorio.Commit();
}
// DELETE api/todos/5
public void Delete(int id)
{
todoRepositorio.Remove(id);
todoRepositorio.Commit();
}
}
}
|
// ----------------------------------------------------------------------------------------------------------------------------------------
// <copyright file="IViewType.cs" company="David Eiwen">
// Copyright © 2016 by David Eiwen
// </copyright>
// <author>David Eiwen</author>
// <summary>
// This file contains the IViewType{T} interface.
// </summary>
// ----------------------------------------------------------------------------------------------------------------------------------------
using System.Collections.Generic;
namespace IndiePortable.Collections
{
/// <summary>
/// Defines a view type for a specified type.
/// </summary>
/// <typeparam name="T">
/// The type of the object that shall be viewed. Must be a class.
/// </typeparam>
public interface IViewType<T>
where T : class
{
/// <summary>
/// Gets the model associated with the view model type.
/// </summary>
/// <value>
/// Contains the model associated with the view model type.
/// </value>
T Model { get; }
}
}
|
using JoggingDating.Models;
using JoggingDating.Services;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Template10.Mvvm;
using Template10.Services.NavigationService;
using Windows.UI.Xaml.Navigation;
using Windows.Web.Http;
namespace JoggingDating.ViewModels
{
public class CourseChoixPageViewModel : ViewModelBase
{
private string _Value;
public string Value { get { return _Value; } set { Set(ref _Value, value); } }
private String _noCourse;
public String NoCourse { get { return _noCourse; } set { Set(ref _noCourse, value); } }
private ObservableCollection<CourseParcours> _list = null;
public ObservableCollection<CourseParcours> List { get { return _list; } set { Set(ref _list, value); } }
public CourseParcours _courseParcours;
ServiceApi serviceApi;
public CourseChoixPageViewModel()
{
serviceApi = new ServiceApi();
}
public CourseParcours SelectedCourse
{
get
{ return _courseParcours = null; }
set
{
Set(ref _courseParcours, value);
GotoViewCourse(_courseParcours.IdCourse);
}
}
public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> suspensionState)
{
Value = (suspensionState.ContainsKey(nameof(Value))) ? suspensionState[nameof(Value)]?.ToString() : parameter?.ToString();
await Task.CompletedTask;
GetCourses();
}
private async void GetCourses()
{
try
{
int level = int.Parse(Value);
List = await serviceApi.GetCourseByLevel(level);
if (List.Count == 0)
{
NoCourse = "There is no courses.";
}
}
catch(Exception ex)
{
var msg = ex.Message;
}
}
public void GotoCreateImportCoursePage() =>
NavigationService.Navigate(typeof(Views.CreateImportCoursePage),Value);
public void GotoViewCourse(int IdCourse)=>
NavigationService.Navigate(typeof(Views.ViewCoursePage), IdCourse);
}
} |
// <copyright file="BooksInMemoryRepository.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace AspNetSandbox.Services
{
using System.Collections.Generic;
using System.Linq;
using AspNetSandbox.Models;
/// <summary>Implement CRUD operations.</summary>
public class BooksInMemoryRepository : IBookRepository
{
private static List<Book> books;
/// <summary>
/// Initializes static members of the <see cref="BooksInMemoryRepository"/> class.
/// Initializes the Bookservice class with 2 Book objects.
/// </summary>
static BooksInMemoryRepository()
{
books = new List<Book>();
books.Add(new Book
{
Id = 1,
Title = "ceva",
Author = "ceva autor",
Language = "ceva limba",
});
books.Add(new Book
{
Id = 2,
Title = "ceva2",
Author = "ceva autor2",
Language = "ceva limba2",
});
}
/// <summary>Gets all books.</summary>
/// <returns>Book list.</returns>
public IEnumerable<Book> GetAllBooks()
{
return books;
}
/// <summary>Gets the book by identifier.</summary>
/// <param name="id">The identifier.</param>
/// <returns>Book object.</returns>
public Book GetBookById(int id)
{
return books.Single(book => book.Id == id);
}
/// <summary>Posts the book.</summary>
/// <param name="value">The value.</param>
public void PostBook(Book value)
{
var sortedBooks = books.OrderBy(book => book.Id).ToList();
value.Id = sortedBooks[sortedBooks.Count - 1].Id + 1;
books.Add(value);
}
/// <summary>Updates or creates a value from book list.</summary>
/// <param name="id">The identifier.</param>
/// <param name="value">The value.</param>
public void PutBook(int id, Book value)
{
var selectedBook = books.Find(book => book.Id == id);
if (books.Exists(book => book.Id == id))
{
selectedBook.Title = value.Title;
selectedBook.Author = value.Author;
selectedBook.Language = value.Language;
}
else
{
value.Id = id;
books.Add(value);
}
}
/// <summary>Deletes the book object with set id.</summary>
/// <param name="id">The identifier.</param>
public void DeleteBook(int id)
{
books.Remove(GetBookById(id));
}
}
} |
using UnityEngine;
[System.Serializable]
public class Sound
{
public string name;
public AudioClip clip;
public enum SoundType { SFX, MUSIC };
public SoundType soundType;
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OnOffHighlight : MonoBehaviour {
private OnOff switchObj;
void Start () {
switchObj = this.transform.parent.gameObject.GetComponent<OnOff> ();
}
protected void OnTriggerStay2D(Collider2D col) {
if (!switchObj.getOnBool ()) {
switchObj.switchVisual.sprite = switchObj.onHighlightSprite;
} else {
switchObj.switchVisual.sprite = switchObj.offHighlightSprite;
}
}
protected void OnTriggerExit2D(Collider2D col) {
if (!switchObj.getOnBool()) {
switchObj.switchVisual.sprite = switchObj.onSprite;
} else {
switchObj.switchVisual.sprite = switchObj.offSprite;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Planning
{
public class KnowledgeState : State
{
public KnowledgeState(Problem p)
: base(p)
{
}
public KnowledgeState(KnowledgeState ksPredecessor)
: base(ksPredecessor)
{
}
public override void GroundAllActions()
{
AvailableActions = Problem.Domain.GroundAllActions(m_lPredicates, true);
HashSet<Predicate> lKnowPredicates = new HashSet<Predicate>();
foreach (CompoundFormula cf in Problem.Hidden)
{
cf.GetAllPredicates(lKnowPredicates);
}
AddKnowledgePredicatesToExistingActions(lKnowPredicates);
AddReasoningActions();
}
private CompoundFormula AddKnowledgePredicatesToFormula(Formula f, HashSet<Predicate> lKnowPredicates)
{
CompoundFormula cf = new CompoundFormula("and");
HashSet<Predicate> lPredicates = new HashSet<Predicate>();
f.GetAllPredicates(lPredicates);
foreach (Predicate p in lPredicates)
{
if (lKnowPredicates.Contains(p))
{
KnowPredicate kp = new KnowPredicate(p);
cf.AddOperand(new PredicateFormula(kp));
}
}
if (f is CompoundFormula && ((CompoundFormula)f).Operator == "and")
{
foreach (Formula fSub in ((CompoundFormula)f).Operands)
cf.AddOperand(fSub);
}
else
cf.AddOperand(f);
return cf;
}
//problem - we have to be over restrictive:
//(xor a b c) + know(a) + know(b) = know(c)
private void AddReasoningActions()
{
foreach (CompoundFormula cf in Problem.Hidden)
{
AvailableActions.AddRange(CreateReasoningActions(cf));
}
}
private Action CreateReasoningAction(Predicate pEffect, HashSet<Predicate> lPredicates)
{
KnowPredicate kpEffect = new KnowPredicate(pEffect);
if (Predicates.Contains(kpEffect))
return null;
Action a = new KnowledgeAction("Reasoning_" + pEffect.ToString());
a.Preconditions = new CompoundFormula("and");
foreach (Predicate pOther in lPredicates)
{
if (pOther != pEffect)
{
KnowPredicate kp = new KnowPredicate(pOther);
if (!Predicates.Contains(kp))
return null;
((CompoundFormula)a.Preconditions).AddOperand(new PredicateFormula(kp));
}
}
CompoundFormula cfEffects = new CompoundFormula("and");
cfEffects.AddOperand(new PredicateFormula(kpEffect));
a.SetEffects(cfEffects);
return a;
}
private List<Action> CreateReasoningActions(CompoundFormula cf)
{
List<Action> lActions = new List<Action>();
Action a = null;
HashSet<Predicate> lPredicates = new HashSet<Predicate>();
cf.GetAllPredicates(lPredicates);
foreach (Predicate p in lPredicates)
{
a = CreateReasoningAction(p, lPredicates);
if (a != null)
lActions.Add(a);
}
return lActions;
}
private void AddKnowledgePredicatesToExistingActions(HashSet<Predicate> lKnowPredicates)
{
List<Action> lActions = AvailableActions;
AvailableActions = new List<Action>();
foreach (Action a in lActions)
{
KnowledgeAction ka = new KnowledgeAction(a);
ka.Preconditions = AddKnowledgePredicatesToFormula(a.Preconditions, lKnowPredicates);
CompoundFormula cfEffects = null;
if (Contains(ka.Preconditions))
{
if (a.Effects != null)
{
cfEffects = AddKnowledgePredicatesToFormula(a.Effects, lKnowPredicates);
}
else
{
cfEffects = new CompoundFormula("and");
}
if (a.Observe != null)
{
HashSet<Predicate> lPredicates = new HashSet<Predicate>();
a.Observe.GetAllPredicates(lPredicates);
foreach (Predicate p in lPredicates)
{
cfEffects.AddOperand(new PredicateFormula(new KnowPredicate(p)));
}
ka.Observe = null;
}
ka.SetEffects(cfEffects);
if (!Contains(ka.Effects))
AvailableActions.Add(ka);
}
}
}
public override State Clone()
{
return new KnowledgeState((KnowledgeState)this);
}
}
}
|
namespace Musher.EchoNest.Models
{
public class Biography
{
public string Text { get; set; }
public string Site { get; set; }
public bool Truncated { get; set; }
}
}
|
using Entities.Concrete;
using System;
using System.Collections.Generic;
using System.Text;
using Core;
namespace DataAccess.Abstract
{
public interface IColorDal : IEntityReposity<Color>
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using SO.Urba.Managers;
namespace SO.Urba.Models.ValueObjects
{
[Table("SurveyAnswer", Schema = "data" )]
[Serializable]
public class SurveyAnswerVo
{
private QuestionTypeManager questionTypeManager = new QuestionTypeManager();
[DisplayName("survey Answer Id")]
[Required]
[Key]
public Guid surveyAnswerId { get; set; }
[DisplayName("referral Id")]
[Required]
public int referralId { get; set; }
[DisplayName("question Id")]
[Required]
public int questionTypeId { get; set; }
[DisplayName("answer")]
public Nullable<int> answer { get; set; }
[DisplayName("created")]
[Required]
public DateTime created { get; set; }
[DisplayName("modified")]
[Required]
public DateTime modified { get; set; }
[DisplayName("created By")]
public Nullable<int> createdBy { get; set; }
[DisplayName("modified By")]
public Nullable<int> modifiedBy { get; set; }
[DisplayName("is Active")]
[Required]
public bool isActive { get; set; }
[ForeignKey("questionTypeId")]
public QuestionTypeVo questionType { get; set; }
[ForeignKey("referralId")]
public ReferralVo referral { get; set; }
public SurveyAnswerVo()
{
this.surveyAnswerId = Guid.NewGuid();
this.isActive = true;
}
public SurveyAnswerVo(int questionId, int? refId = null )
{
this.questionTypeId = questionId;
this.questionType = questionTypeManager.get(questionId);
this.referralId = refId?? 0;
this.surveyAnswerId = Guid.NewGuid();
this.isActive = true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Infestation
{
class AggressionCatalyst : Supplement
{
public AggressionCatalyst()
: base(0, 0, 3)
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class spawner : MonoBehaviour
{
public GameObject coin;
public GameObject badCoin;
public GameObject ballprefab;
public GameObject skillCoin;
// Start is called before the first frame update
void Start()
{
Instantiate(ballprefab,Vector3.zero, Quaternion.identity);
InvokeRepeating("spawnCoin", 2f,5f);
InvokeRepeating("spawnbadCoing", 2f, 5f);
InvokeRepeating("spawnSkillCoin", 2f, 5f);
// old place Instantiate(ballprefab, Vector3.zero, Quaternion.identity);
}
private void spawnCoin()
{
Vector2 spawnpoint = Random.insideUnitCircle * 1.88f;
Instantiate(coin, new Vector3(spawnpoint.x, spawnpoint.y, 0),Quaternion.identity);
}
private void spawnbadCoing()
{
Vector2 spawnpoint = Random.insideUnitCircle * 1.88f;
Instantiate(badCoin, new Vector3(spawnpoint.x, spawnpoint.y, 0), Quaternion.identity);
}
private void spawnSkillCoin()
{
Vector2 spawnpoint = Random.insideUnitCircle * 1.88f;
Instantiate(skillCoin, new Vector3(spawnpoint.x, spawnpoint.y, 0), Quaternion.identity);
}
}
|
using UnityEngine;
using UnityEngine.EventSystems;
public class controleTouch : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
public enum eTouchPlace
{ //direcoes
monster, heroDMG, heroBonus, heroBonus2
}
//ponteiro para as funcoes da mao
public eTouchPlace placeTouch;
public bool turbo;
bool _pressed,_released = false;
//eventos sobrescritos, eles q vao capturar o press e release
public void OnPointerDown(PointerEventData eventData)
{
_pressed = true;
//Debug.Log(eventData.pressPosition) ;
//singletonGP.Instance.touch.makeEffect(eventData.pressPosition);
//singletonGP.Instance.touch.makeEffect(eventData.pressPosition);
}
//eventos sobrescritos, eles q vao capturar o press e release
public void OnPointerUp(PointerEventData eventData)
{
_pressed = false;
_released = true;
}
void Update()
{
if (!_pressed) //agora é soh ver se ta pressionado...
return;
switch (placeTouch) // e chamar a funcao propria.
{
case eTouchPlace.monster:
if (singletonGP.Instance.clickDMG)
if (!turbo){
_pressed=false;
singletonGP.Instance.player.doDMG();
}else {
singletonGP.Instance.player.doDMG();
}
break;
case eTouchPlace.heroDMG:
_pressed=false;
singletonGP.Instance.player.levelPlus();
break;
case eTouchPlace.heroBonus:
_pressed=false;
singletonGP.Instance.player.bonusPlus();
break;
case eTouchPlace.heroBonus2:
_pressed=false;
singletonGP.Instance.player.bonus2Plus();
break;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Park_A_Lot
{
public class Elevator : parkALot
{
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace PhonemesAndStuff
{
public class PhonemeSupporter
{
public int ID { set; get; }
public string Name { set; get; }
public List<int> Allophones { set; get; }
public PhonemeSupporter()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace VocabularyApi.Parsers
{
public class XdXfParser
{
public async Task<Dictionary<string, List<string>>> Parse(Stream stream)
{
var xmlDocument = await XDocument.LoadAsync(stream, LoadOptions.PreserveWhitespace, CancellationToken.None);
var result = new Dictionary<string, List<string>>();
var xdxfDictionary = xmlDocument.Element("xdxf");
if (xdxfDictionary == null)
{
return result;
}
foreach (var word in xdxfDictionary.Elements("ar"))
{
if (word.Nodes().Count() != 2)
{
continue;
}
var englishWord = word.Element("k").Value.ToLower();
var russianWord = word.LastNode.ToString().Trim('\n', '\r', ' ');
var match = Regex.Match(russianWord, "(?<=\")(.*)(?=\")");
russianWord = match.Value.ToLower();
if (!result.ContainsKey(englishWord)) {
result.Add(englishWord, new List<string> { russianWord });
}
else
{
result[englishWord].Add(russianWord);
}
}
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ISKlinike
{
public class KartonDrugeUstanove
{
public int Id { get; set; }
public string NazivUstanove { get; set; }
public DateTime LijecenOd { get; set; }
public DateTime LijecenDo { get; set; }
public string OtpusnaDijagnoza { get; set; }
public string Uputstvo { get; set; }
public virtual Pacijenti Pacijenti { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace VKDesktop.Models.Converters
{
public class OnlineConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
var isOnline = (bool)value;
return (isOnline ? "Онлайн" : "");
// Do the conversion from bool to visibility
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return null;
// Do the conversion from visibility to bool
}
}
}
|
using LuizalabsWishesManager.Domains.Models;
using LuizalabsWishesManager.Domains.Repositories;
namespace LuizalabsWishesManager.Services
{
public class ProductService : ServiceBase<Product>, IProductService
{
private readonly IProductRepository _repository;
public ProductService(IProductRepository repository) : base(repository)
{
_repository = repository;
}
}
}
|
namespace SQLiteUpdate
{
public class UpdateScript
{
public string Identity { get; set; }
public string Script { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Math_Assist
{
public partial class Math_Assist : Form
{
public Math_Assist()
{
InitializeComponent();
}
private void btn_Distance_Click(object sender, EventArgs e)
{
double diff_X = Convert.ToDouble(txtbox_X2.Text) - Convert.ToDouble(txtbox_X1.Text);
double diff_Y = Convert.ToDouble(txtbox_Y2.Text) - Convert.ToDouble(txtbox_Y1.Text);
double distance = Math.Round(Math.Sqrt((diff_X * diff_X) + (diff_Y * diff_Y)), 3);
lbl_Distance.Text = "Distance: " + Convert.ToString(distance);
}
private void btn_Midpoint_Click(object sender, EventArgs e)
{
double X1 = Convert.ToDouble(txtbox_X1.Text);
double Y1 = Convert.ToDouble(txtbox_Y1.Text);
double X2 = Convert.ToDouble(txtbox_X2.Text);
double Y2 = Convert.ToDouble(txtbox_Y2.Text);
double XM = (X1 + X2) / 2;
double YM = (Y1 + Y2) / 2;
lbl_Midpoint.Text = Convert.ToString(Math.Round(XM, 2)) + ", " + Convert.ToString(Math.Round(YM, 2));
}
private void btn_Endpoint_1_Click(object sender, EventArgs e)
{
double X2 = Convert.ToDouble(txtbox_X2.Text);
double Y2 = Convert.ToDouble(txtbox_Y2.Text);
double XM = Convert.ToDouble(txtbox_XM.Text);
double YM = Convert.ToDouble(txtbox_YM.Text);
double X1 = (2 * XM) - X2;
double Y1 = (2 * YM) - Y2;
lbl_Endpoint_1.Text = X1 + ", " + Y1;
}
private void btn_Endpoint_2_Click(object sender, EventArgs e)
{
double X1 = Convert.ToDouble(txtbox_X1.Text);
double Y1 = Convert.ToDouble(txtbox_Y1.Text);
double XM = Convert.ToDouble(txtbox_XM.Text);
double YM = Convert.ToDouble(txtbox_YM.Text);
double X2 = (2 * XM) - X1;
double Y2 = (2 * YM) - Y1;
lbl_Endpoint_2.Text = X2 + ", " + Y2;
}
private void btn_About_Click(object sender, EventArgs e)
{
MessageBox.Show("Math Assist V0.1, Created by Caleb E. Grebill - 2/10/2021");
}
private void btn_Clear_Click(object sender, EventArgs e)
{
lbl_Endpoint_1.Text = "";
lbl_Midpoint.Text = "";
lbl_Endpoint_2.Text = "";
lbl_Distance.Text = "";
txtbox_X1.Text = "";
txtbox_X2.Text = "";
txtbox_XM.Text = "";
txtbox_Y1.Text = "";
txtbox_Y2.Text = "";
txtbox_YM.Text = "";
}
}
}
|
namespace Contoso.Common.Configuration.ExpressionDescriptors
{
public class NotEqualsBinaryOperatorDescriptor : BinaryOperatorDescriptor
{
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Fleck;
using General.Librerias.AccesoDatos;
namespace Demo46
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Iniciando el Servidor Socket");
string ipServidor = "ws://192.168.1.33:9002";
List<IWebSocketConnection> clientes = new List<IWebSocketConnection>();
WebSocketServer servidor = new WebSocketServer(ipServidor);
Console.WriteLine("Servidor Socket iniciado en: {0}", ipServidor);
Console.WriteLine();
servidor.Start(cliente =>
{
cliente.OnOpen = () =>
{
clientes.Add(cliente);
Console.WriteLine("Se abrió la conexión del IP: {0}", cliente.ConnectionInfo.ClientIpAddress);
};
cliente.OnClose = () =>
{
clientes.Remove(cliente);
Console.WriteLine("Se cerró la conexión del IP: {0}", cliente.ConnectionInfo.ClientIpAddress);
};
cliente.OnMessage = (string texto) =>
{
string[] campos = texto.Split('~');
daSQL odaSQL = new daSQL("conNW");
string rpta = "";
if (campos[0] == "Consultar")
{
string nroPag = campos[1];
string nroReg = campos[2];
string data = nroPag + "|" + nroReg;
rpta = odaSQL.ejecutarComando("uspCubso2PaginarCsv", "@data", data);
cliente.Send(rpta);
Console.WriteLine("Recibido: " + texto + " Enviado: " + rpta.Length.ToString());
}
else
{
rpta = odaSQL.ejecutarCopiaMasiva("Articulo", texto, '¬', '|');
cliente.Send("OK");
Console.WriteLine("Recibido: " + texto.Length + " bytes - Enviado: OK");
}
Console.WriteLine("Se envió datos: ", texto);
};
});
Console.WriteLine();
Console.WriteLine("Pulsa Enter para finalizar el Servidor");
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PhoneBook
{
public delegate void InputsForProblem();
class Program
{
static void Main(string[] args)
{
InputsForProblem input = InputsForPhoneBookDiary;
input.Invoke();
}
private static void InputsForPhoneBookDiary()
{
var queries = Convert.ToInt32(Console.ReadLine());
Dictionary<string, string> phoneBook = new Dictionary<string, string>();
for (int i = 0; i < queries; i++)
{
var query = Console.ReadLine().Split(' ');
if (query[0].Equals("add"))
ProcessPhoneBookQuery(query[0], phoneBook, query[1], query[2]);
else
ProcessPhoneBookQuery(query[0], phoneBook, query[1]);
}
}
private static void ProcessPhoneBookQuery(string query, Dictionary<string, string> phoneBook, string key, string value = "")
{
switch(query)
{
case "add":
{
if (phoneBook.ContainsKey(key))
phoneBook[key] = value;
else
phoneBook.Add(key, value);
}
break;
case "del":
{
if (phoneBook.ContainsKey(key))
phoneBook.Remove(key);
}
break;
default:
{
if (phoneBook.ContainsKey(key))
Console.WriteLine(phoneBook[key]);
else
Console.WriteLine("not found");
}
break;
}
}
}
} |
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
#region Usings
using System.ComponentModel.DataAnnotations;
using System.Reflection;
#endregion
namespace DotNetNuke.Web.Validators
{
public class DataAnnotationsObjectValidator : AttributeBasedObjectValidator<ValidationAttribute>
{
protected override ValidationResult ValidateAttribute(object target, PropertyInfo targetProperty, ValidationAttribute attribute)
{
return !attribute.IsValid(targetProperty.GetValue(target, new object[] {})) ? new ValidationResult(new[] {CreateError(targetProperty.Name, attribute)}) : ValidationResult.Successful;
}
protected virtual ValidationError CreateError(string propertyName, ValidationAttribute attribute)
{
return new ValidationError {ErrorMessage = attribute.FormatErrorMessage(propertyName), PropertyName = propertyName, Validator = attribute};
}
}
}
|
/*
* Copyright 2014 Technische Universität Darmstadt
*
* 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 KaVE.Commons.Model.Naming;
using KaVE.Commons.Model.SSTs.Impl;
using KaVE.Commons.Model.SSTs.Impl.Expressions.Simple;
using NUnit.Framework;
namespace KaVE.RS.Commons.Tests_Integration.Analysis.SSTAnalysisTestSuite
{
internal class CastingAndTypeCheckingTest : BaseSSTAnalysisTest
{
[Test, Ignore]
public void TypeOf()
{
CompleteInClass(@"
public void A()
{
var t = typeof(int);
$
}
");
var mA = NewMethodDeclaration(SSTAnalysisFixture.Void, "A");
mA.Body.Add(SSTUtil.Declare("t", Names.Type("System.Type, mscorlib, 4.0.0.0")));
mA.Body.Add(SSTUtil.AssignmentToLocal("t", new ConstantValueExpression()));
AssertAllMethods(mA);
}
[Test, Ignore]
public void CompositionOfTypeOf()
{
CompleteInClass(@"
public void A()
{
var t = typeof(int) == typeof(string);
$
}
");
var mA = NewMethodDeclaration(SSTAnalysisFixture.Void, "A");
mA.Body.Add(SSTUtil.Declare("t", SSTAnalysisFixture.Bool));
mA.Body.Add(SSTUtil.AssignmentToLocal("t", new ConstantValueExpression()));
AssertAllMethods(mA);
}
[Test, Ignore]
public void Is_Reference()
{
CompleteInClass(@"
public void A(object o)
{
var isInstanceOf = o is string;
$
}
");
var mA = NewMethodDeclaration(
SSTAnalysisFixture.Void,
"A",
string.Format("[{0}] o", SSTAnalysisFixture.Object));
mA.Body.Add(SSTUtil.Declare("isInstanceOf", SSTAnalysisFixture.Bool));
mA.Body.Add(SSTUtil.AssignmentToLocal("isInstanceOf", SSTUtil.ComposedExpression("o")));
AssertAllMethods(mA);
}
[Test, Ignore]
public void Is_Const()
{
CompleteInClass(@"
public void A()
{
var isInstanceOf = 1 is double;
$
}
");
var mA = NewMethodDeclaration(SSTAnalysisFixture.Void, "A");
mA.Body.Add(SSTUtil.Declare("isInstanceOf", SSTAnalysisFixture.Bool));
mA.Body.Add(SSTUtil.AssignmentToLocal("isInstanceOf", new ConstantValueExpression()));
AssertAllMethods(mA);
}
[Test, Ignore]
public void As_Reference()
{
CompleteInClass(@"
public void A(object o)
{
var cast = o as string;
$
}
");
var mA = NewMethodDeclaration(
SSTAnalysisFixture.Void,
"A",
string.Format("[{0}] o", SSTAnalysisFixture.Object));
mA.Body.Add(SSTUtil.Declare("cast", SSTAnalysisFixture.String));
mA.Body.Add(SSTUtil.AssignmentToLocal("cast", SSTUtil.ComposedExpression("o")));
AssertAllMethods(mA);
}
[Test, Ignore]
public void As_Const()
{
CompleteInClass(@"
public void A()
{
var cast = 1.0 as object;
$
}
");
var mA = NewMethodDeclaration(SSTAnalysisFixture.Void, "A");
mA.Body.Add(SSTUtil.Declare("cast", SSTAnalysisFixture.Object));
mA.Body.Add(SSTUtil.AssignmentToLocal("cast", new ConstantValueExpression()));
AssertAllMethods(mA);
}
[Test, Ignore]
public void Cast_Const()
{
CompleteInClass(@"
public void A()
{
var i = (int) 1.0;
$
}
");
var mA = NewMethodDeclaration(SSTAnalysisFixture.Void, "A");
mA.Body.Add(SSTUtil.Declare("i", SSTAnalysisFixture.Int));
mA.Body.Add(SSTUtil.AssignmentToLocal("i", new ConstantValueExpression()));
AssertAllMethods(mA);
}
[Test, Ignore]
public void Cast_Reference()
{
CompleteInClass(@"
public void A(object o)
{
var s = (string) o;
$
}
");
var mA = NewMethodDeclaration(
SSTAnalysisFixture.Void,
"A",
string.Format("[{0}] o", SSTAnalysisFixture.Object));
mA.Body.Add(SSTUtil.Declare("s", SSTAnalysisFixture.String));
mA.Body.Add(SSTUtil.AssignmentToLocal("s", SSTUtil.ComposedExpression("o")));
AssertAllMethods(mA);
}
}
} |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CMS.DL
{
public static class DB
{
private static string strConexion = ConfigurationManager.ConnectionStrings["cms"].ToString();
public static SqlConnection Conectar()
{
SqlConnection con = new SqlConnection(strConexion);
con.Open();
return con;
}
public static SqlCommand ArmaCommand(string strSQL, List<SqlParameter> param, SqlConnection con)
{
SqlCommand com = new SqlCommand(strSQL, con);
com.CommandType = CommandType.Text;
foreach (SqlParameter sp in param)
{
com.Parameters.Add(sp);
}
return com;
}
public static SqlDataReader GenerarReader(string strSQL, List<SqlParameter> param, SqlConnection con)
{
SqlCommand com = ArmaCommand(strSQL, param, con);
return com.ExecuteReader();
}
public static DataTable GenerarTable(String strSQL, List<SqlParameter> lista, SqlConnection con)
{
DataTable dt = new DataTable();
dt.Load(GenerarReader(strSQL, lista, con));
return dt;
}
public static int EjecutarCommand(String strSQL, List<SqlParameter> lista,
SqlConnection con)
{
SqlCommand com = ArmaCommand(strSQL, lista, con);
return com.ExecuteNonQuery();
}
public static int EjecutarCommand(String strSQL, List<SqlParameter> lista,
SqlConnection con, SqlTransaction tran)
{
SqlCommand com = ArmaCommand(strSQL, lista, con);
com.Transaction = tran;
return com.ExecuteNonQuery();
}
public static string EjecutarScalar(String strSQL, List<SqlParameter> lista, SqlConnection con, SqlTransaction tran)
{
SqlCommand cmd = ArmaCommand(strSQL, lista, con);
cmd.Transaction = tran;
return cmd.ExecuteScalar().ToString();
}
public static SqlDataReader GenerarReader(string comando, List<SqlParameter> listp, SqlConnection con, SqlTransaction tran)
{
SqlCommand com = ArmaCommand(comando, listp, con);
com.Transaction = tran;
return com.ExecuteReader();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model.DataEntity;
using Model.Helper;
using Model.Locale;
using DataAccessLayer.basis;
using Model.Schema.EIVO;
using Utility;
using System.Linq.Expressions;
using Model.InvoiceManagement.InvoiceProcess;
namespace Model.InvoiceManagement
{
public class B2CInvoiceManager : EIVOEntityManager<InvoiceItem>
{
public B2CInvoiceManager() : base() { }
public B2CInvoiceManager(GenericManager<EIVOEntityDataContext> mgr) : base(mgr) { }
public Dictionary<int, Exception> SaveUploadInvoice(InvoiceRoot item, OrganizationToken owner)
{
Dictionary<int, Exception> result = new Dictionary<int, Exception>();
if (item != null && item.Invoice != null && item.Invoice.Length > 0)
{
for (int idx = 0; idx < item.Invoice.Length; idx++)
{
var invItem = item.Invoice[idx];
try
{
String invNo, trackCode;
if (invItem.InvoiceNumber.Length >= 10)
{
trackCode = invItem.InvoiceNumber.Substring(0, 2);
invNo = invItem.InvoiceNumber.Substring(2);
}
else
{
trackCode = null;
invNo = invItem.InvoiceNumber;
}
if (this.EntityList.Any(i => i.No == invNo && i.TrackCode == trackCode))
{
result.Add(idx, new Exception(String.Format("發票號碼已存在:{0}", invItem.InvoiceNumber)));
continue;
}
var seller = this.GetTable<Organization>().Where(o => o.ReceiptNo == invItem.SellerId).FirstOrDefault();
if (seller == null)
{
result.Add(idx, new Exception(String.Format("賣方為非註冊營業人,統一編號:{0}", invItem.SellerId)));
continue;
}
if (seller.OrganizationStatus.CurrentLevel == (int)Naming.MemberStatusDefinition.Mark_To_Delete)
{
result.Add(idx,new Exception(String.Format("開立人已註記停用,開立人統一編號:{0},TAG:<SellerId />", invItem.SellerId)));
continue;
}
Organization donatory = null;
bool bPrinted = invItem.PrintMark == "Y";
if (invItem.DonateMark == "1")
{
if (bPrinted)
{
result.Add(idx, new Exception(String.Format("發票已列印後不能捐贈,發票號碼:{0}", invItem.InvoiceNumber)));
continue;
}
donatory = this.GetTable<Organization>().Where(o => o.ReceiptNo == invItem.NPOBAN).FirstOrDefault();
if (donatory == null || !this.GetTable<InvoiceWelfareAgency>().Any(w => w.AgencyID == donatory.CompanyID && w.SellerID == seller.CompanyID))
{
result.Add(idx, new Exception(String.Format("發票受捐社福單位不符,統一編號:{0}", invItem.NPOBAN)));
continue;
}
}
InvoiceUserCarrier carrier = null;
if (bPrinted)
{
if (!String.IsNullOrEmpty(invItem.CarrierType) || !String.IsNullOrEmpty(invItem.CarrierId1) || !String.IsNullOrEmpty(invItem.CarrierId2))
{
result.Add(idx, new Exception(String.Format("發票已列印後不能指定歸戶,發票號碼:{0}", invItem.InvoiceNumber)));
continue;
}
}
else
{
carrier = checkInvoiceCarrier(invItem);
if (carrier == null)
{
result.Add(idx, new Exception(String.Format("發票歸戶載具或卡號不符,發票號碼:{0}", invItem.InvoiceNumber)));
continue;
}
}
InvoiceItem newItem = new InvoiceItem
{
CDS_Document = new CDS_Document
{
DocDate = DateTime.Now,
DocType = (int)Naming.DocumentTypeDefinition.E_Invoice,
DocumentOwner = new DocumentOwner
{
OwnerID = seller.CompanyID
},
ProcessType = (int)Naming.InvoiceProcessType.C0401,
},
DonateMark = invItem.DonateMark,
PrintMark = invItem.PrintMark,
InvoiceBuyer = new InvoiceBuyer
{
Name = invItem.BuyerId == "0000000000" ? invItem.BuyerName.CheckB2CMIGName() : invItem.BuyerName,
ReceiptNo = invItem.BuyerId,
BuyerMark = invItem.BuyerMark,
CustomerName = invItem.BuyerName
},
InvoiceDate = DateTime.ParseExact(String.Format("{0} {1}", invItem.InvoiceDate, invItem.InvoiceTime), "yyyy/MM/dd HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture),
InvoiceType = byte.Parse(invItem.InvoiceType),
No = invNo,
TrackCode = trackCode,
SellerID = seller.CompanyID,
InvoiceByHousehold = carrier != null ? new InvoiceByHousehold { InvoiceUserCarrier = carrier } : null,
InvoicePrintAssertion = bPrinted ? new InvoicePrintAssertion { PrintDate = DateTime.Now } : null,
RandomNo = invItem.RandomNumber,
InvoiceAmountType = new InvoiceAmountType
{
DiscountAmount = invItem.DiscountAmount,
SalesAmount = invItem.SalesAmount,
FreeTaxSalesAmount = invItem.FreeTaxSalesAmount,
ZeroTaxSalesAmount = invItem.ZeroTaxSalesAmount,
TaxAmount = invItem.TaxAmount,
TaxRate = invItem.TaxRate,
TaxType = invItem.TaxType,
TotalAmount = invItem.TotalAmount,
TotalAmountInChinese = Utility.ValueValidity.MoneyShow(invItem.TotalAmount),
BondedAreaConfirm = invItem.BondedAreaConfirm,
},
DonationID = donatory != null ? donatory.CompanyID : (int?)null
};
if (seller.OrganizationStatus.EnableTrackCodeInvoiceNoValidation == true)
{
using (TrackNoManager trackMgr = new TrackNoManager(this, seller.CompanyID))
{
if (trackMgr.GetAppliedInterval(newItem.InvoiceDate.Value, newItem.TrackCode, int.Parse(newItem.No)) == null)
{
result.Add(idx, new Exception(String.Format("發票號碼錯誤:{0},TAG:< InvoicNumber />", invItem.InvoiceNumber)));
continue;
}
}
}
var productItems = invItem.InvoiceItem.Select(i => new InvoiceProductItem
{
InvoiceProduct = new InvoiceProduct { Brief = i.Description },
CostAmount = i.Amount,
ItemNo = i.Item,
Piece = i.Quantity,
PieceUnit = i.Unit,
UnitCost = i.UnitPrice,
Remark = i.Remark,
TaxType = i.TaxType
});
newItem.InvoiceDetails.AddRange(productItems.Select(p => new InvoiceDetail
{
InvoiceProduct = p.InvoiceProduct
}));
this.EntityList.InsertOnSubmit(newItem);
C0401Handler.PushStepQueueOnSubmit(this, newItem.CDS_Document, Naming.InvoiceStepDefinition.已開立);
C0401Handler.PushStepQueueOnSubmit(this, newItem.CDS_Document, Naming.InvoiceStepDefinition.已接收資料待通知);
this.SubmitChanges();
}
catch (Exception ex)
{
Logger.Error(ex);
result.Add(idx, ex);
}
}
}
return result;
}
private InvoiceUserCarrier checkInvoiceCarrier(InvoiceRootInvoice invItem)
{
Expression<Func<InvoiceUserCarrier, bool>> expr = null;
if (!String.IsNullOrEmpty(invItem.CarrierId1))
{
expr = c => c.CarrierNo == invItem.CarrierId1;
}
if (!String.IsNullOrEmpty(invItem.CarrierId2))
{
if (expr == null)
{
expr = c => c.CarrierNo2 == invItem.CarrierId2;
}
else
{
expr = expr.And(c => c.CarrierNo2 == invItem.CarrierId2);
}
}
if (expr == null)
return null;
var carrier = this.GetTable<InvoiceUserCarrier>().Where(expr).FirstOrDefault();
if (carrier == null)
{
if (String.IsNullOrEmpty(invItem.CarrierType))
return null;
var carrierType = this.GetTable<InvoiceUserCarrierType>().Where(t => t.CarrierType == invItem.CarrierType).FirstOrDefault();
if (carrierType == null)
{
//carrierType = new InvoiceUserCarrierType
//{
// CarrierType = invItem.CarrierType
//};
return null;
}
carrier = new InvoiceUserCarrier
{
InvoiceUserCarrierType = carrierType,
CarrierNo = invItem.CarrierId1,
CarrierNo2 = invItem.CarrierId2
};
}
return carrier;
}
public Dictionary<int, Exception> SaveUploadInvoiceCancellation(CancelInvoiceRoot item, OrganizationToken owner)
{
Dictionary<int, Exception> result = new Dictionary<int, Exception>();
if (item != null && item.CancelInvoice != null && item.CancelInvoice.Length > 0)
{
for (int idx = 0; idx < item.CancelInvoice.Length; idx++)
{
var invItem = item.CancelInvoice[idx];
try
{
String invNo, trackCode;
if (invItem.CancelInvoiceNumber.Length >= 10)
{
trackCode = invItem.CancelInvoiceNumber.Substring(0, 2);
invNo = invItem.CancelInvoiceNumber.Substring(2);
}
else
{
trackCode = null;
invNo = invItem.CancelInvoiceNumber;
}
invItem.SellerId = invItem.SellerId.GetEfficientString();
var invoice = this.EntityList.Where(i => i.No == invNo && i.TrackCode == trackCode
&& i.Organization.ReceiptNo == invItem.SellerId).FirstOrDefault();
if (invoice == null)
{
result.Add(idx, new Exception(String.Format("發票號碼不存在:{0}", invItem.CancelInvoiceNumber)));
continue;
}
if (invoice.InvoiceCancellation != null)
{
result.Add(idx, new Exception(String.Format("作廢發票已存在,發票號碼:{0}", invItem.CancelInvoiceNumber)));
continue;
}
InvoiceCancellation cancelItem = new InvoiceCancellation
{
InvoiceItem = invoice,
CancellationNo = invItem.CancelInvoiceNumber,
Remark = invItem.Remark,
ReturnTaxDocumentNo = invItem.ReturnTaxDocumentNumber,
CancelDate = DateTime.ParseExact(String.Format("{0} {1}", invItem.CancelDate, invItem.CancelTime), "yyyy/MM/dd HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture)
};
var doc = new DerivedDocument
{
CDS_Document = new CDS_Document
{
DocType = (int)Naming.DocumentTypeDefinition.E_InvoiceCancellation,
DocDate = DateTime.Now,
DocumentOwner = new DocumentOwner
{
OwnerID = owner.CompanyID
}
},
SourceID = invoice.InvoiceID
};
this.GetTable<DerivedDocument>().InsertOnSubmit(doc);
this.SubmitChanges();
}
catch (Exception ex)
{
Logger.Error(ex);
result.Add(idx, ex);
}
}
}
return result;
}
public IEnumerable<WelfareReplication> GetUpdatedWelfareAgenciesForSeller(String receiptNo)
{
return this.GetTable<WelfareReplication>().Where(w => w.InvoiceWelfareAgency.Organization.ReceiptNo == receiptNo);
}
public IEnumerable<InvoiceWelfareAgency> GetWelfareAgenciesForSeller(String receiptNo)
{
return this.GetTable<InvoiceWelfareAgency>().Where(w => w.Organization.ReceiptNo == receiptNo);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OracleClient;
namespace AddressBook
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/*
* DB 불러오는 메소드
*/
public void LoadDB()
{
String sql = "SELECT * FROM ADDRESSBOOK";
DBConnect dbConnect = new DBConnect();
DataTable dt = dbConnect.GetTable(sql);
for (int i = 0; i < dt.Rows.Count; i++ )
{
String[] arr = new string[4];
arr[0] = dt.Rows[i][0].ToString();
arr[1] = dt.Rows[i][1].ToString();
arr[2] = dt.Rows[i][2].ToString();
arr[3] = dt.Rows[i][3].ToString();
ListViewItem lvt = new ListViewItem(arr);
listView1.Items.Add(lvt);
}
}
/*
* Form1을 불렀을때 최초로 실행되는 코드
*/
private void Form1_Load(object sender, EventArgs e)
{
listView1.View = View.Details;
listView1.FullRowSelect = true;
// 컬럼명 "번호", 컬럼크기 100
listView1.Columns.Add("번호", 100);
listView1.Columns.Add("이름", 100);
listView1.Columns.Add("전화번호", 100);
listView1.Columns.Add("주소", 100);
LoadDB();
}
/**
* Form1.cs에서 버튼을 눌렀을 때의 처리
*/
private void btnAppend_Click(object sender, EventArgs e)
{
AppendForm form = new AppendForm();
if(form.ShowDialog() == DialogResult.OK)
{
String sql = "INSERT INTO ADDRESSBOOK(ID, NAME, PHONE, ADDRESS) "
+ " VALUES( (SELECT NVL(MAX(ID), 0)+1 FROM ADDRESSBOOK), ";
sql = sql + " '" + form.name + "' ";
sql = sql + " ,'" + form.phone + "' ";
sql = sql + " ,'" + form.address + "') ";
DBConnect db = new DBConnect();
db.UpdateSql(sql);
listView1.Items.Clear();
LoadDB();
}
else
{
MessageBox.Show("취소");
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if( listView1.SelectedItems.Count > 0 )
{
txtNumber.Text = listView1.SelectedItems[0].SubItems[0].Text;
txtName.Text = listView1.SelectedItems[0].SubItems[1].Text;
txtPhone.Text = listView1.SelectedItems[0].SubItems[2].Text;
txtAddress.Text = listView1.SelectedItems[0].SubItems[3].Text;
}
}
}
}
|
// -----------------------------------------------------------------------
// Copyright (c) David Kean. All rights reserved.
// -----------------------------------------------------------------------
extern alias pcl;
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using pcl::System.Security.Cryptography;
namespace Portable.Security.Cryptography
{
[TestClass]
public class CryptographicExceptionTests
{
[TestMethod]
public void Constructor1_SetsMessagePropertyToDefault()
{
var exception = new CryptographicException();
Assert.IsNotNull(exception.Message);
}
[TestMethod]
public void Constructor1_SetsInnerExceptionPropertyToNull()
{
var exception = new CryptographicException();
Assert.IsNull(exception.InnerException);
}
[TestMethod]
public void Constructor2_NullAsMessage_SetsMessagePropertyToDefault()
{
var exception = new CryptographicException((string)null);
Assert.IsNotNull(exception.Message);
}
[TestMethod]
public void Constructor2_ValueAsMessage_SetsMessageProperty()
{
var exception = new CryptographicException("Message");
Assert.AreEqual("Message", exception.Message);
}
[TestMethod]
public void Constructor2_SetsInnerExceptionToNull()
{
var exception = new CryptographicException((string)null);
Assert.IsNull(exception.InnerException);
}
[TestMethod]
public void Constructor3_NullAsMessage_SetsMessagePropertyToDefault()
{
var exception = new CryptographicException((string)null, (Exception)null);
Assert.IsNotNull(exception.Message);
}
[TestMethod]
public void Constructor3_ValueAsMessage_SetsMessageProperty()
{
var exception = new CryptographicException("Message", (Exception)null);
Assert.AreEqual("Message", exception.Message);
}
[TestMethod]
public void Constructor3_NullAsInner_SetsInnerExceptionToNull()
{
var exception = new CryptographicException((string)null, (Exception)null);
Assert.IsNull(exception.InnerException);
}
[TestMethod]
public void Constructor3_ValueAsInner_SetsInnerExceptionToNull()
{
var inner = new Exception();
var exception = new CryptographicException((string)null, inner);
Assert.AreSame(inner, exception.InnerException);
}
}
}
|
using System;
namespace NetBattle.Field {
public sealed class Health {
public int OverchargeMaximum { get; set; }
public int Maximum { get; set; }
public int Value { get; set; }
public Health(int overchargeMaximum = 100, int maximum = 100, int value = 100) {
if (overchargeMaximum < 1)
throw new ArgumentException($"Overcharge maximum {overchargeMaximum} must be positive");
if (maximum < 1)
throw new ArgumentException($"Maximum {maximum} must be positive");
if (value < 0)
throw new ArgumentException($"Value {value} cannot be negative");
if (maximum > overchargeMaximum)
throw new ArgumentException(
$"Maximum {maximum} cannot be greater than overcharge maximum {overchargeMaximum}");
if (value > maximum)
throw new ArgumentException($"Value {value} cannot be greater than maximum {maximum}");
OverchargeMaximum = overchargeMaximum;
Maximum = maximum;
Value = value;
}
public int Heal(int amount) {
if (amount < 0)
throw new ArgumentException($"Cannot heal negative value {amount}");
Value = Math.Min(Value + amount, OverchargeMaximum);
return Value;
}
public int Decay(int amount) {
if (amount < 0)
throw new ArgumentException($"Cannot decay negative value {amount}");
if (Value < Maximum) return Value;
Value = Math.Max(Value - amount, Maximum);
return Value;
}
public int Damage(int amount) {
if (amount < 0)
throw new ArgumentException($"Cannot decay negative value {amount}");
return Value = Math.Max(Value - amount, 0);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace DataStorage{
public class BDManager
{
private static BDManager dataBase;
private static MySqlCommand comando;
private static MySqlConnection con;
private static string cadena;
private static List<String> parameterNames;
public BDManager()
{
cadena = "server=quilla.lab.inf.pucp.edu.pe;" + "user=inf282g3;" + "database=inf282g3;" + "port=3306;password=H9u1oC;SslMode=none;" + "";
con = new MySqlConnection(cadena);
comando = new MySqlCommand();
comando.Connection = con;
parameterNames = new List<string>();
}
public static BDManager getInstance()
{
if (dataBase == null)
{
dataBase = new BDManager();
}
return dataBase;
}
private void getParameterNames(string procedureName) {
con.Open();
parameterNames.Clear();
comando.CommandText = "getParameterNames";
comando.CommandType = System.Data.CommandType.StoredProcedure;
comando.Parameters.Add("procedureName", MySqlDbType.String).Value = procedureName;
MySqlDataReader reader = comando.ExecuteReader();
while (reader.Read()) {
String s = reader.GetString("PARAMETER_NAME");
parameterNames.Add(s);
}
con.Close();
}
private void setProcedure(string procedureName)
{
Console.WriteLine("Setting procedure " + procedureName + "...");
con.Open();
comando.CommandText = procedureName;
comando.CommandType = System.Data.CommandType.StoredProcedure;
}
private void setParameters(List<Object> parameters)
{
int pos = 0;
foreach (Object parameter in parameters)
{
Console.WriteLine("Setting parameter " + parameter.ToString() + "...");
if (parameter is int) comando.Parameters.Add(parameterNames[pos], MySqlDbType.Int32).Value = Int32.Parse(parameter.ToString());
else if (parameter is double) comando.Parameters.Add(parameterNames[pos], MySqlDbType.Double).Value = Double.Parse(parameter.ToString());
else comando.Parameters.Add(parameterNames[pos], MySqlDbType.String).Value = parameter.ToString();
Console.WriteLine(parameterNames[pos] + parameter.ToString());
pos++;
}
}
private List<Object> executeProcedure()
{
Console.WriteLine("Executing...");
comando.ExecuteNonQuery();
con.Close();
return null;
}
public string passwordVerify(string us)
{
string aux;
con.Open();
comando.CommandText = "SELECT Password FROM User WHERE Dni = " + us;
MySqlDataReader reader = comando.ExecuteReader();
reader.Read();
aux = reader.GetString("Password");
return aux;
}
public void listarClientes()
{
con.Open();
comando.CommandText = "SELECT * FROM Client";
MySqlDataReader reader = comando.ExecuteReader();
while (reader.Read())
{
//Client c = new Client();
string name = reader.GetString("Name");
string surname = reader.GetString("Surname");
string dni = reader.GetString("Dni");
string district = reader.GetString("District");
string phone = reader.GetString("PhoneNumber");
string email = reader.GetString("Email");
}
}
public void AddUpdate(string procedureName, List<Object> parameters) {
getParameterNames(procedureName);
setProcedure(procedureName);
setParameters(parameters);
executeProcedure();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BomTreeView.Database
{
public class SqlDatabaseController
{
private BomDatabaseContext BomDatabaseContext { get; set; }
public SqlDatabaseController()
{
BomDatabaseContext = new BomDatabaseContext();
}
public void WriteBomDbEntryListToBomDatabase(BomDbEntries bomDbEntries)
{
List<BomDbEntry> bomDbEntryList = bomDbEntries.BomDbEntryList;
BomDatabaseContext.BomDbEntrySet.AddRange(bomDbEntryList);
BomDatabaseContext.SaveChanges();
}
public void ClearBomDbEntryTable()
{
List<BomDbEntry> allBomDbEntries = ReadAllBomDbEntriesFromDatabase();
BomDatabaseContext.BomDbEntrySet.RemoveRange(allBomDbEntries);
BomDatabaseContext.SaveChanges();
}
public List<BomDbEntry> ReadAllBomDbEntriesFromDatabase()
{
return BomDatabaseContext.BomDbEntrySet.ToList();
}
public BomDbEntries ReadChildrenFromBomDatabase(BomDisplayEntry selectedBomEntry)
{
String parentName = selectedBomEntry.ComponentName;
List<BomDbEntry> bomDbEntryList = BomDatabaseContext.BomDbEntrySet
.Where(entry=>entry.ParentName == parentName)
.ToList();
return new BomDbEntries(bomDbEntryList);
}
public bool DataExistsInBomTable()
{
List<BomDbEntry> allBomDbEntries = ReadAllBomDbEntriesFromDatabase();
return allBomDbEntries.Count > 0;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DataController : MonoBehaviour {
public static DataController Instance;
public PlayerDataManager PlayerData { get; private set; }
public string ExitDoorName { get; set; }
public Vector3 ExitPosition { get; set; }
/* public string transitionDoor; */
// Use this for initialization
void Awake () {
if (Instance == null) {
DontDestroyOnLoad (gameObject);
Instance = this;
PlayerData = new PlayerDataManager ();
} else if (Instance != this) {
Destroy (gameObject);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HackerrankSolutionConsole
{
class game_of_stones_1 : Challenge
{
public override void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < n; i++)
{
int stones = Convert.ToInt32(Console.ReadLine());
if (stones % 7 >= 2)
Console.WriteLine("First");
else
Console.WriteLine("Second");
}
}
public game_of_stones_1()
{
Name = "Game of Stones";
Path = "game-of-stones-1";
Difficulty = Difficulty.Easy;
Domain = Domain.Algorithms;
Subdomain = Subdomain.GameTheory;
}
}
}
|
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Companies.Models;
namespace Companies.Functions
{
public class GetCompanyById
{
[FunctionName(nameof(GetCompanyById))]
public static IActionResult Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "companies/{id}")] HttpRequest req,
// could I have used a CosmosDBTrigger here with IReadOnlyList<Document> companyToFind as the return type?
[CosmosDB(
databaseName: "CompaniesDB",
collectionName: "Companies",
ConnectionStringSetting = "CosmosDbConnectionString",
Id = "{id}",
PartitionKey = "{id}")] Company companyToFind, ILogger log)
/*
Query alternative:
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
[CosmosDB(
databaseName: "CompaniesDB",
collectionName: "Companies",
ConnectionStringSetting = "CosmosDbConnectionString",
Id = "{Query.id}",
PartitionKey = "{Query.partitionKey}")] Company companyToFind,
*/
{
if (companyToFind == null)
{
log.LogWarning($"No Company with given id found!");
return new NotFoundResult();
}
return new OkObjectResult(companyToFind);
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
namespace DotNetNuke.Entities.Users
{
public interface IFollowerEventHandlers
{
void FollowRequested(object sender, RelationshipEventArgs args);
void UnfollowRequested(object sender, RelationshipEventArgs args);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Odbc;
namespace ADO.Net_DataAdapter
{
class Program
{
static void Main(string[] args)
{
try
{
string connectionString = "DSN=FBMAXX;UID=seniorsoft;PWD=MySenior;Role=ProMaxx";
using (OdbcConnection connection = new OdbcConnection(connectionString))
{
connection.Open();
string sql = "SELECT * FROM UNITNAME;";
using (OdbcCommand cmd = new OdbcCommand(sql, connection))
using (OdbcDataAdapter adapter = new OdbcDataAdapter(cmd))
//The OdbcDataAdapter does not automatically generate the SQL statements required to reconcile changes made to a DataSet associated with the data source.
//However, you can create an OdbcCommandBuilder object that generates SQL statements for single-table updates by setting the SelectCommand property of the OdbcDataAdapter.
//The OdbcCommandBuilder then generates any additional SQL statements that you do not set.
using (OdbcCommandBuilder builder = new OdbcCommandBuilder(adapter))
//When this constructor of OdbcCommandBuilder is invoked, the OdbcCommandBuilder registers itself as a listener for RowUpdating events that are generated by the OdbcDataAdapter specified as an argument of this constructor.
{
DataTable dt = new DataTable();
adapter.Fill(dt);
DataRowCollection dr1 = dt.Rows;
dt.Rows[0][2] = "A";
dt.Rows[1].Delete();
adapter.RowUpdating += OnRowUpdatingListener;
using (OdbcTransaction t = connection.BeginTransaction())
{
cmd.Transaction = t;
try
{
adapter.Update(dt);
}
catch (OdbcException OdbcEx)
{
t.Rollback();
throw OdbcEx;
}
t.Commit();
cmd.Transaction = adapter.DeleteCommand.Transaction = adapter.UpdateCommand.Transaction = adapter.InsertCommand.Transaction = null;
}
}
}
}
catch (Exception e)
{
}
finally
{
}
}
static void OnRowUpdatingListener(object sender, System.Data.Common.RowUpdatingEventArgs e)
{
StatementType statementType = e.StatementType;
UpdateStatus updateStatus = e.Status;
string commandText = e.Command.CommandText;
OdbcParameter[] parameters = new OdbcParameter[e.Command.Parameters.Count]; e.Command.Parameters.CopyTo(parameters, 0);
}
}
}
|
using System;
namespace Paralect.Schematra
{
public class EnumTypeBuilder : EnumType
{
public EnumTypeBuilder(TypeContext typeContext) : base(typeContext)
{
}
public EnumTypeBuilder AddConstant(Int32 index, String name)
{
AddConstantInternal(index, name);
return this;
}
/// <summary>
/// Define name by name and @namespace
/// </summary>
public EnumTypeBuilder SetName(String name, String @namespace)
{
SetNameInternal(name, @namespace);
return this;
}
/// <summary>
/// Define name by full name
/// </summary>
public EnumTypeBuilder SetName(String fullName)
{
SetNameInternal(fullName);
return this;
}
public EnumType Create()
{
return CreateInternal();
}
}
} |
using System;
using System.Collections.Generic;
using Acr.UserDialogs;
using City_Center.Clases;
using City_Center.Helper;
using Xamarin.Forms;
namespace City_Center.Page
{
public partial class DetalleTorneo2 : ContentPage
{
public DetalleTorneo2()
{
InitializeComponent();
NavigationPage.SetTitleIcon(this, "logo@2x.png");
}
async void Chat_click(object sender, System.EventArgs e)
{
bool isLoggedIn = Application.Current.Properties.ContainsKey("IsLoggedIn") ?
(bool)Application.Current.Properties["IsLoggedIn"] : false;
if (isLoggedIn)
{
await ((MasterPage)Application.Current.MainPage).Detail.Navigation.PushAsync(new SeleccionTipoChat());
}
else
{
await Mensajes.Alerta("Es necesario que te registres para completar esta acción");
}
}
async void Fecha_Tapped(object sender, System.EventArgs e)
{
#if __IOS__
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
#endif
var result = await UserDialogs.Instance.DatePromptAsync(new DatePromptConfig
{
IsCancellable = true,
CancelText = "CANCELAR",
Title = "Fecha Nacimiento"
});
if (result.Ok)
{
Fecha.Text = String.Format("{0:dd/MM/yyyy}", result.SelectedDate);
Fecha.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
else
{
Fecha.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
}
async void TipoDocumento_Tapped(object sender, System.EventArgs e)
{
#if __IOS__
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
#endif
var result = await UserDialogs.Instance.ActionSheetAsync("Numero de socio Win", "CANCELAR", null, null, "DNI", "LE", "LC", "CI");
if (result != "CANCELAR")
{
TipoDocumento.Text = result.ToString();
TipoDocumento.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
else
{
TipoDocumento.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
}
//NoDocumento_Tapped
}
}
|
namespace E01_SchoolClasses
{
using System;
using System.Collections.Generic;
public class SchoolClassesMain
{
public static void Main(string[] args)
{
// We are given a school. In the school there are classes of
// students. Each class has a set of teachers. Each teacher
// teaches a set of disciplines. Students have name and
// unique class number. Classes have unique text identifier.
// Teachers have name. Disciplines have name, number of lectures
// and number of exercises. Both teachers and students are people.
// Students, classes, teachers and disciplines could have
// optional comments (free text block).
// Your task is to identify the classes (in terms of OOP) and
// their attributes and operations, encapsulate their fields,
// define the class hierarchy and create a class diagram with Visual Studio.
var gogo = new Student("Gogo", 23);
var vania = new Student("Vania", 24);
var math = new Discipline("Mathematic", 4, 10);
var phys = new Discipline("Physics", 5, 8);
var med = new Discipline("Medicine", 2, 18);
var LDkiro = new List<Discipline>() { math, phys };
var LDpesho = new List<Discipline>() { math, phys, med };
var techerPesho = new Teacher("Pesho", LDpesho);
var techerKiro = new Teacher("Kiro", LDkiro);
techerPesho.Comment = "Imalo edno wreme.";
gogo.Comment = "brrrrr";
Console.WriteLine("Teacher Pesho coment : {0}", techerPesho.Comment);
Console.WriteLine("Student gogo coment : {0}", gogo.Comment);
Console.WriteLine();
Console.WriteLine("Gogo class number : {0}", gogo.ClassNumber);
Console.WriteLine();
Console.WriteLine("Teacher Pesho disciplines:");
foreach (var discipline in techerPesho.DisciplinesList)
{
Console.WriteLine(discipline.Identifier);
}
Console.WriteLine();
var sudentsListA1 = new List<Student>();
sudentsListA1.Add(gogo);
sudentsListA1.Add(vania);
var TeachersListA1 = new List<Teacher>();
TeachersListA1.Add(techerPesho);
var A1 = new SchoolClass("A1", sudentsListA1, TeachersListA1);
var listOfClasses = new List<SchoolClass>();
listOfClasses.Add(A1);
var profIvanov = new School(listOfClasses);
Console.WriteLine("Students of Professor Ivanov:");
foreach (var student in profIvanov.SchoolClassList[0].StudentsList)
{
Console.WriteLine(student.Identifier);
}
Console.WriteLine();
}
}
}
|
using System;
namespace FuzzyLogic.Operations
{
public class Intersection : IBinaryOperation
{
public double Operate(double operand1, double operand2) => Math.Min(operand1, operand2);
}
}
|
using System;
using System.Linq;
using System.Security.Cryptography;
using Microsoft.Extensions.Options;
using trial_api.PasswordHashing;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
namespace trial_api.PasswordHashing
{
public class PasswordHasher// : IPasswordHasher
{
byte[] salt = new byte[128 / 8];
// private const int SaltSize = 16; // 128 bit
public string hashPass(string password)
{
// using (var rng = RandomNumberGenerator.Create())
// {
// rng.GetBytes(salt);
// }
string hashedPassword = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: password,
salt: salt,
prf: KeyDerivationPrf.HMACSHA1,
iterationCount: 1000,
numBytesRequested: 256 / 8
));
return hashedPassword;
}
public bool VerifyPassword(string enteredPassword, string storedHash)
{
// byte[] salt2 = new byte[128 / 8];
// var saltBytes = Convert.FromBase64String(salt2.ToString());
var hashOfEntered = hashPass(enteredPassword);
// var rfc2898DeriveBytes = new Rfc2898DeriveBytes(enteredPassword, saltBytes, 10000);
// return Convert.ToBase64String(rfc2898DeriveBytes.GetBytes(256)) == storedHash;
return hashOfEntered == storedHash;
}
// private const int SaltSize = 16; // 128 bit
// private const int KeySize = 32; // 256 bit
// public (bool Verified, bool NeedsUpgarde) Check(string hash, string password)
// {
// var parts = hash.Split('.',3);
// if(parts.Length != 3){
// throw new FormatException("Unexpected hash format. " +
// "Should be formatted as `{iterations}.{salt}.{hash}`");
// }
// var iterations = Convert.ToInt32(parts[0]);
// var salt = Convert.FromBase64String(parts[1]);
// var key = Convert.FromHexString(parts[2]);
// var needsUpgarde = iterations != Options.Iterations;
// using (var algorithm = new Rfc2898DeriveBytes(
// password,
// salt,
// iterations,
// HashAlgorithmName.SHA256
// ))
// {
// var keyToCheck = algorithm.GetBytes(KeySize);
// var verified = keyToCheck.SequenceEqual(key);
// return (verified, needsUpgarde);
// }
// }
// public string Hash(string pass)
// {
// using (var algorithm = new Rfc2898DeriveBytes(
// pass,
// SaltSize,
// Options.Iterations,
// HashAlgorithmName.SHA256
// ))
// {
// var key = Convert.ToBase64String(algorithm.GetBytes(KeySize));
// var salt = Convert.ToBase64String(algorithm.Salt);
// return $"{Options.Iterations}.{salt}.{key}";
// }
// }
// public PasswordHasher(IOptions<HashOptions> options)
// {
// Options = options.Value;
// }
// private HashOptions Options { get; }
}
} |
using WindowsFormsApplication1;
namespace HouseCostCalculation
{
internal class House
{
public double calculateCost()
{
double cost = 0;
return cost;
}
private Address adress;
private double cost;
public double Cost
{
get
{
return cost;
}
set
{
cost = value;
}
}
public Address Address
{
get
{
return adress;
}
set
{
adress = value;
}
}
public bool saveHouse(mainForm mainForm)
{
{
//string townName = " " + mainForm.Controls["town"].Text + ", ";
//if ((mainForm.Controls["town"].Text == "г. Владикавказ") || (mainForm.Controls["town"].Text == "г.Владикавказ"))
//{
// townName = " ";
//}
//string buildNum = null;
//if (mainForm.Controls["buildingNum"].Text != "")
//{
// buildNum = "корп. " + mainForm.Controls["buildingNum"].Text;
//}
//mainForm.roomsAsString();
//string fullAddress = mainForm.fullAddress();
//string fileName = "отчет номер " + mainForm.Controls["contractNum"].Text + " от " + mainForm.Controls["calculationDate"].Text + " договор от" + mainForm.Controls["contractDate"].Text + " " + fullAddress + " " + mainForm.Controls["ownerSurname"].Text + " " + mainForm.Controls["ownerName"].Text + " для " + mainForm.Controls["customerSurname"].Text + " " + mainForm.Controls["customerName"].Text + " " + mainForm.Controls["bankName"].Text + ".doc";
return true;
// mainForm.saveFileDialog1.FileName = fileName.Replace("\"", " ").ToLower();
// mainForm.saveFileDialog1.FileName = saveFileDialog1.FileName.Replace("/", " ").ToLower();
// mainForm.saveFileDialog1.FileName = saveFileDialog1.FileName.Replace(",", " ").ToLower();
// mainForm.saveFileDialog1.FileName = saveFileDialog1.FileName.Replace("№", " ").ToLower();
// mainForm.saveFileDialog1.FileName = saveFileDialog1.FileName.Replace(".", " ").ToLower();
// saveFileDialog1.FileName = saveFileDialog1.FileName.Replace("-", " ").ToLower();
// saveFileDialog1.FileName = saveFileDialog1.FileName.Replace(" ", " ").ToLower();
// try
// {
// if (DialogResult.OK == saveFileDialog1.ShowDialog())
// {
// wdApp = new Microsoft.Office.Interop.Word.Application();
// Microsoft.Office.Interop.Word.Document wdDoc = new Microsoft.Office.Interop.Word.Document();
// wdDoc = wdApp.Documents.Open(System.Windows.Forms.Application.StartupPath + "\\house.doc", Missing, true);
// object replaceAll = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
// // Gets a NumberFormatInfo associated with the en-US culture.
// NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat;
// nfi.NumberDecimalDigits = 0;
// nfi.NumberGroupSeparator = " ";
// nfi.PositiveSign = "";
// string ownerFullName = ownerSurname.Text + " " + ownerName.Text + " " + ownerInit.Text;
// string customerFullName = customerSurname.Text + " " + customerName.Text + " " + customerInit.Text;
// calculationDate.CustomFormat = "dd MMMM yyyy";
// string calculationDateStr = calculationDate.Text;
// int lenght = calculationDateStr.Length;
// string temp = null;
// string t;
// for (int i = 0; i < lenght; i++)
// {
// if (i == 3)
// {
// t = calculationDateStr[i].ToString().ToUpper();
// temp += t;
// }
// else
// {
// temp += calculationDateStr[i];
// }
// }
// calculationDateStr = temp;
// calculationDate.CustomFormat = "dd/MM/yy";
// int sentencesCount = wdDoc.Sentences.Count;
// string topColontitul = topColontitulCreator();
// wdDoc.Sections[1].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Text = topColontitul;
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@MO@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = MO.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@dirtCost@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dirtCalcGrid.Rows[31].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@dirtCostR@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dirtCalcGrid.Rows[32].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@calculationDateStr@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = calculationDateStr;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@houseType@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = houseType.Text.ToLower();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@roomsT@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = roomsT;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@roomsX@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = roomsX;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@lm2@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = lm2text.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@m2@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = m2text.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@customerNameInits@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = customerFamiliyR + " " + getInits();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@calculationDate@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = calculationDate.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@ownerFullname@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = ownerFullName;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@customerFullname@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = customerFullName;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@rooms1@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// roomsAsString();
// wdApp.Selection.Find.Replacement.Text = rooms1;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@ownerFullnameR@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = ownerFullNameR;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@customerFullnameR@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = customerFullNameR;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@customerFullnameT@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = customerFullNameT;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@ownerFullnameD@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = ownerFullNameD;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@ownerFullnameT@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = ownerFullNameT;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// /*
// /*
// if (newSentence.Contains("@@customerFullnameD@@"))
// {
// newSentence = newSentence.Replace("@@customerFullnameD@@", customerFullNameD);
// changed = true;
// }*/
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@customerFullnameD@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = customerFullNameD;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@rooms@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = roomsAsString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@appartmentNum@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = "№" + appartmentNum.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// /* if (newSentence.Contains("@@town@@"))
// {
// newSentence = newSentence.Replace("@@town@@", town.Text);
// changed = true;
// }*/
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@town@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = town.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// /*if (newSentence.Contains("@@houseNum@@"))
// {
// newSentence = newSentence.Replace("@@houseNum@@", houseNum.Text);
// changed = true;
// }*/
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@houseNum@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = houseNum.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// buildNum = null;
// if (buildingNum.Text != "")
// {
// buildNum = " корп." + buildingNum.Text;
// }
// else
// {
// buildNum = buildingNum.Text;
// }
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@buildingNum@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = buildNum;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// /* if (newSentence.Contains("@@customerAddress@@"))
// {
// newSentence = newSentence.Replace("@@customerAddress@@", customerAddres.Text);
// changed = true;
// }*/
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@customerAddress@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = customerAddres.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// /*if (newSentence.Contains("@@floor@@"))
// {
// newSentence = newSentence.Replace("@@floor@@", floor.Value.ToString());
// changed = true;
// }*/
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@floor@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = floor.Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// /*if (newSentence.Contains("@@floors@@"))
// {
// newSentence = newSentence.Replace("@@floors@@", floors.Text);
// changed = true;
// }*/
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@floors@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = floors.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@town@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = town.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@cost@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = finalCostRounded.ToString("N", nfi);
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// /*if (newSentence.Contains("@@contractNum@@"))
// {
// newSentence = newSentence.Replace("@@contractNum@@", contractNum.Text);
// changed = true;
// }*/
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@contractNum@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = contractNum.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// /*if (newSentence.Contains("@@contractDate@@"))
// {
// newSentence = newSentence.Replace("@@contractDate@@", contractDate.Text);
// changed = true;
// }
// */
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@contractDate@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = contractDate.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// /*if (newSentence.Contains("@@customerName@@"))
// {
// newSentence = newSentence.Replace("@@customerName@@", customerName.Text);
// changed = true;
// }
// */
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@customerName@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = customerName.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// /*if (newSentence.Contains("@@customerInit@@"))
// {
// newSentence = newSentence.Replace("@@customerInit@@", customerInit.Text);
// changed = true;
// }
// */
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@customerInit@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = customerInit.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// /* if (newSentence.Contains("@@likvidCost@@"))
// {
// newSentence = newSentence.Replace("@@likvidCost@@", likvidCost.ToString());
// changed = true;
// }*/
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@likvidCost@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = likvidCost.ToString("N", nfi);
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// /* if (newSentence.Contains("@@stringCost@@"))
// {
// newSentence = newSentence.Replace("@@stringCost@@", costStr);
// changed = true;
// }
// */
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@stringCost@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = costStr.ToLower();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// /*
//if (newSentence.Contains("@@uvaj@@"))
//{
// newSentence = newSentence.Replace("@@uvaj@@", uvaj);
// changed = true;
//}*/
// getUvaj();
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@uvaj@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = uvaj;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// /*if (changed)
// {
// wdDoc.Sentences[i].Text = newSentence;
// }
// */
// /*
// }
// /*int shapesCount = wdDoc.Shapes.Count;
// for (int i = 1; i <= shapesCount; i++)
// {
// //if (wdDoc.Shapes[i].
// if (wdDoc.Shapes[i].TextEffect.Text !=null)
// {
// if (wdDoc.Shapes[i].TextEffect.Text.Contains("@@contractDate@@"))
// {
// wdDoc.Shapes[i].TextEffect.Text.Replace("@@contractDate@@", contractDate.Text);
// }
// }
// }*/
// //Customer Passport
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@customerPassport@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = customerPassport.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@customerPassNum@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = customerPassNum.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@customerPassOVD@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = customerPassOVD.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@customerPassDate@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = customerPassDate.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@customerFullAddress@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = customerAddres.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// //owner Passport
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@passportSerial@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = passportSerial.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@ownerPassNum@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = ownerPassNum.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@ownerPassOVD@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = ownerPassOVD.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@ownerPassDate@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = ownerPassDate.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@ownerFullAddress@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = ownerAddress.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@ownerDoc@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = ownerDocs.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@registrationDoc@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = registrationDoc.Text;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@tehPass@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[41].Cells[1].Value.ToString(); ;
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.1.2@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[2].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.1.3@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[3].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.1.4@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[4].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.1.5@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[5].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.1.6@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[6].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.1.7@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[7].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.1.8@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[8].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.1.9@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[9].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.1.10@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[10].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.1.11@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[11].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.1.12@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[12].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.1.13@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[13].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.1.14@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[14].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.1.15@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[15].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.1@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[17].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.2@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[18].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.3@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[19].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.4@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[20].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.5@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[21].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.6@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[22].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.7@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[23].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.8@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[24].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.9@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[25].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.10@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[26].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.11@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[27].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.12@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[28].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.13@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[29].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.14@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[30].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.15@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[31].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.16@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[32].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.17@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[33].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.18@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[34].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.19@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[35].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.20@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[36].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.21@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[37].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.22@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[38].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.23@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[39].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.24@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[40].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.25@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[41].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.26@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[42].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.27@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[43].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.28@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[44].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.29@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[45].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.30@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[46].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.31@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[47].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.32@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[48].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.33@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[49].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.34@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[50].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.35@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[51].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.36@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[52].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.37@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[53].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.38@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[54].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.39@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[55].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.40@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[56].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "@@2.1.2.41@@";
// wdApp.Selection.Find.Replacement.ClearFormatting();
// wdApp.Selection.Find.Replacement.Text = dataGridView1.Rows[57].Cells[1].Value.ToString();
// wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// wdApp.Selection.Find.ClearFormatting();
// wdApp.Selection.Find.Text = "м2";
// while (wdApp.Selection.Find.Execute(
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// ref Missing, ref Missing, ref Missing, ref Missing, ref Missing))
// {
// wdApp.Selection.Characters[2].Font.Superscript = 1;
// }
// string te = wdApp.Selection.Text;
// //saving
// try
// {
// int x = wdDoc.Shapes.Count;
// x = wdDoc.Shapes.Count;
// for (int k = 1; k < x; k++)
// {
// Microsoft.Office.Interop.Word.Shape shape = wdDoc.Shapes[k];
// //string l = shape.AlternativeText;
// if (shape.AlternativeText.Contains("cont"))
// {
// wdDoc.Shapes[k].TextEffect.Text = "№ " + contractNum.Text + " от " + calculationDate.Text + "г.";
// }
// }
// //for (int k = 1; k < x; k++)
// //{
// // Microsoft.Office.Interop.Word.Shape shape = wdDoc.Shapes[k];
// // if (shape.AlternativeText.Contains("first"))
// // {
// // System.Drawing.Image firstPageImg = System.Drawing.Image.FromFile(imagesGrid.Rows[0].Cells[2].Value.ToString());
// // //Clipboard.SetImage(firstPageImg);
// // shape.Select();
// // wdDoc.Shapes[k].CanvasItems.AddPicture(imagesGrid.Rows[0].Cells[2].Value.ToString());
// // wdDoc.Shapes[k].Apply();
// // // wdApp.Selection.PasteSpecial();
// // // wdApp.ActiveDocument.Shapes.AddPicture(imagesGrid.Rows[0].Cells[2].Value.ToString(), Type.Missing, Type.Missing, Type.Missing, Type.Missing, 500, 370, Type.Missing);
// // //wdApp.Selection.InlineShapes.AddPicture(imagesGrid.Rows[0].Cells[2].Value.ToString(), Type.Missing, Type.Missing, Type.Missing);
// // //wdApp.Selection.InlineShapes
// // //Clipboard.Clear();
// // }
// //}
// }
// catch (Exception exp)
// {
// }
// //foreach (Microsoft.Office.Interop.Word.Table table in wdApp.ActiveDocument.Tables)
// //{
// // try
// // {
// // // if (table.Columns[0].Cells[0].Range.Text.Contains("@@1@@"))
// // //{
// // foreach (Microsoft.Office.Interop.Word.Column col in table.Columns)
// // {
// // foreach (Microsoft.Office.Interop.Word.Cell cell in col.Cells)
// // {
// // int rowCount = imagesGrid.RowCount;
// // string l = cell.Range.Text;
// // if (l.Contains("@@1@@"))
// // {
// // cell.Select();
// // cell.Range.Text = "";
// // wdApp.Selection.InlineShapes.AddPicture(imagesGrid.Rows[1].Cells[2].Value.ToString(), Type.Missing, Type.Missing, Type.Missing);
// // wdApp.Selection.Find.ClearFormatting();
// // wdApp.Selection.Find.Text = "@@1@@";
// // wdApp.Selection.Find.Replacement.ClearFormatting();
// // wdApp.Selection.Find.Replacement.Text = "";
// // wdApp.Selection.Find.Execute(
// // ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// // ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// // ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// // }
// // if (l.Contains("@@2@@"))
// // {
// // cell.Select();
// // //cell.Range.Text = "";
// // wdApp.Selection.InlineShapes.AddPicture(imagesGrid.Rows[2].Cells[2].Value.ToString(), Type.Missing, Type.Missing, Type.Missing);
// // wdApp.Selection.Find.ClearFormatting();
// // wdApp.Selection.Find.Text = "@@2@@";
// // wdApp.Selection.Find.Replacement.ClearFormatting();
// // wdApp.Selection.Find.Replacement.Text = "";
// // wdApp.Selection.Find.Execute(
// // ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// // ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// // ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// // }
// // if (l.Contains("@@3@@"))
// // {
// // cell.Select();
// // //cell.Range.Text = "";
// // wdApp.Selection.InlineShapes.AddPicture(imagesGrid.Rows[3].Cells[2].Value.ToString(), Type.Missing, Type.Missing, Type.Missing);
// // wdApp.Selection.Find.ClearFormatting();
// // wdApp.Selection.Find.Text = "@@3@@";
// // wdApp.Selection.Find.Replacement.ClearFormatting();
// // wdApp.Selection.Find.Replacement.Text = "";
// // wdApp.Selection.Find.Execute(
// // ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// // ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// // ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// // }
// // if (l.Contains("@@4@@"))
// // {
// // cell.Select();
// // //cell.Range.Text = "";
// // wdApp.Selection.InlineShapes.AddPicture(imagesGrid.Rows[4].Cells[2].Value.ToString(), Type.Missing, Type.Missing, Type.Missing);
// // wdApp.Selection.Find.ClearFormatting();
// // wdApp.Selection.Find.Text = "@@4@@";
// // wdApp.Selection.Find.Replacement.ClearFormatting();
// // wdApp.Selection.Find.Replacement.Text = "";
// // wdApp.Selection.Find.Execute(
// // ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// // ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// // ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// // }
// // if (l.Contains("@@5@@"))
// // {
// // cell.Select();
// // //cell.Range.Text = "";
// // wdApp.Selection.InlineShapes.AddPicture(imagesGrid.Rows[5].Cells[2].Value.ToString(), Type.Missing, Type.Missing, Type.Missing);
// // wdApp.Selection.Find.ClearFormatting();
// // wdApp.Selection.Find.Text = "@@5@@";
// // wdApp.Selection.Find.Replacement.ClearFormatting();
// // wdApp.Selection.Find.Replacement.Text = "";
// // wdApp.Selection.Find.Execute(
// // ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// // ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// // ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// // }
// // if (l.Contains("@@6@@"))
// // {
// // cell.Select();
// // //cell.Range.Text = "";
// // wdApp.Selection.InlineShapes.AddPicture(imagesGrid.Rows[6].Cells[2].Value.ToString(), Type.Missing, Type.Missing, Type.Missing);
// // wdApp.Selection.Find.ClearFormatting();
// // wdApp.Selection.Find.Text = "@@6@@";
// // wdApp.Selection.Find.Replacement.ClearFormatting();
// // wdApp.Selection.Find.Replacement.Text = "";
// // wdApp.Selection.Find.Execute(
// // ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// // ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// // ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// // }
// // if (l.Contains("@@7@@"))
// // {
// // cell.Select();
// // //cell.Range.Text = "";
// // wdApp.Selection.InlineShapes.AddPicture(imagesGrid.Rows[7].Cells[2].Value.ToString(), Type.Missing, Type.Missing, Type.Missing);
// // wdApp.Selection.Find.ClearFormatting();
// // wdApp.Selection.Find.Text = "@@7@@";
// // wdApp.Selection.Find.Replacement.ClearFormatting();
// // wdApp.Selection.Find.Replacement.Text = "";
// // wdApp.Selection.Find.Execute(
// // ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// // ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// // ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// // }
// // if (l.Contains("@@8@@"))
// // {
// // cell.Select();
// // //cell.Range.Text = "";
// // wdApp.Selection.InlineShapes.AddPicture(imagesGrid.Rows[8].Cells[2].Value.ToString(), Type.Missing, Type.Missing, Type.Missing);
// // wdApp.Selection.Find.ClearFormatting();
// // wdApp.Selection.Find.Text = "@@8@@";
// // wdApp.Selection.Find.Replacement.ClearFormatting();
// // wdApp.Selection.Find.Replacement.Text = "";
// // wdApp.Selection.Find.Execute(
// // ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// // ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// // ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// // }
// // if (l.Contains("@@9@@"))
// // {
// // cell.Select();
// // //cell.Range.Text = "";
// // wdApp.Selection.InlineShapes.AddPicture(imagesGrid.Rows[9].Cells[2].Value.ToString(), Type.Missing, Type.Missing, Type.Missing);
// // wdApp.Selection.Find.ClearFormatting();
// // wdApp.Selection.Find.Text = "@@9@@";
// // wdApp.Selection.Find.Replacement.ClearFormatting();
// // wdApp.Selection.Find.Replacement.Text = "";
// // wdApp.Selection.Find.Execute(
// // ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// // ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// // ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// // }
// // if (l.Contains("@@10@@"))
// // {
// // cell.Select();
// // //cell.Range.Text = "";
// // wdApp.Selection.InlineShapes.AddPicture(imagesGrid.Rows[10].Cells[2].Value.ToString(), Type.Missing, Type.Missing, Type.Missing);
// // wdApp.Selection.Find.ClearFormatting();
// // wdApp.Selection.Find.Text = "@@10@@";
// // wdApp.Selection.Find.Replacement.ClearFormatting();
// // wdApp.Selection.Find.Replacement.Text = "";
// // wdApp.Selection.Find.Execute(
// // ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// // ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
// // ref replaceAll, ref Missing, ref Missing, ref Missing, ref Missing);
// // }
// // }
// // }
// // }
// // // }
// // catch (Exception except)
// // {
// // }
// //}
// /*for (int k = 1; k < x; k++)
// {
// Microsoft.Office.Interop.Word.Shape shape = wdDoc.Shapes[k];
// float shift = 150;
// string l = shape.AlternativeText;
// if (l == "facade")
// {
// shape.IncrementTop(-shift);
// }
// if (l == "appartmentNum")
// {
// shape.IncrementTop(-shift);
// //shape. = "Оцениваемая квартира №"+appartmentNum.Text;
// }
// if (l == "podezd")
// {
// shape.IncrementTop(-shift);
// }
// if (l == "stairway")
// {
// shape.IncrementTop(-shift);
// }
// }*/
// //
// wdApp.ActiveDocument.SaveAs(saveFileDialog1.FileName);
// wdApp.Quit();
// }
// }
// catch (Exception except)
// {
// wdApp.Quit();
// }
}
}
}
} |
/*
* Copyright (c) 2016 Samsung Electronics Co., Ltd
*
* Licensed under the Flora License, Version 1.1 (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 System;
using Tizen.NUI;
using Tizen.NUI.BaseComponents;
namespace NUI_CustomView
{
public class ContactView : CustomView
{
private string name;
private string resourceDirectory;
//Indexes for registering Visuals in the CustomView
private const int BaseIndex = 10000;
private const int BackgroundVisualIndex = BaseIndex + 1;
private const int LabelVisualIndex = BaseIndex + 2;
private const int ContactBgIconIndex = BaseIndex + 3;
private const int ContactIconIndex = BaseIndex + 4;
private const int ContactEditIndex = BaseIndex + 5;
private const int ContactFavoriteIndex = BaseIndex + 6;
private const int ContactDeleteIndex = BaseIndex + 7;
static ContactView()
{
//Each custom view must have its static constructor to register its type.
CustomViewRegistry.Instance.Register(CreateInstance, typeof(ContactView));
}
static CustomView CreateInstance()
{
//Create and return valid custom view object. In this case ContactView is created.
return new ContactView(null, null);
}
/// <summary>
/// Creates and register background color visual.
/// </summary>
/// <param name="color">RGBA color vector</param>
private void CreateBackground(Vector4 color)
{
PropertyMap map = new PropertyMap();
map.Add(Visual.Property.Type, new PropertyValue((int)Visual.Type.Color))
.Add(ColorVisualProperty.MixColor, new PropertyValue(color));
VisualBase background = VisualFactory.Instance.CreateVisual(map);
RegisterVisual(BackgroundVisualIndex, background);
background.DepthIndex = BackgroundVisualIndex;
}
/// <summary>
/// Creates and register label visual.
/// </summary>
/// <param name="text">String viewed by created label</param>
private void CreateLabel(string text)
{
PropertyMap textVisual = new PropertyMap();
textVisual.Add(Visual.Property.Type, new PropertyValue((int)Visual.Type.Text))
.Add(TextVisualProperty.Text, new PropertyValue(text))
.Add(TextVisualProperty.TextColor, new PropertyValue(Color.Black))
.Add(TextVisualProperty.PointSize, new PropertyValue(12))
.Add(TextVisualProperty.HorizontalAlignment, new PropertyValue("CENTER"))
.Add(TextVisualProperty.VerticalAlignment, new PropertyValue("CENTER"));
VisualBase label = VisualFactory.Instance.CreateVisual(textVisual);
RegisterVisual(LabelVisualIndex, label);
label.DepthIndex = LabelVisualIndex;
PropertyMap imageVisualTransform = new PropertyMap();
imageVisualTransform.Add((int)VisualTransformPropertyType.Offset, new PropertyValue(new Vector2(30, 5)))
.Add((int)VisualTransformPropertyType.OffsetPolicy, new PropertyValue(new Vector2((int)VisualTransformPolicyType.Absolute, (int)VisualTransformPolicyType.Absolute)))
.Add((int)VisualTransformPropertyType.SizePolicy, new PropertyValue(new Vector2((int)VisualTransformPolicyType.Absolute, (int)VisualTransformPolicyType.Absolute)))
.Add((int)VisualTransformPropertyType.Size, new PropertyValue(new Vector2(350, 100)));
label.SetTransformAndSize(imageVisualTransform, new Vector2(this.SizeWidth, this.SizeHeight));
}
/// <summary>
/// Creates and register icon image.
/// </summary>
/// <param name="url">Icon absolute path</param>
/// <param name="x">x icon position</param>
/// <param name="y">y icon position</param>
/// <param name="w">icon width</param>
/// <param name="h">icon height</param>
/// <param name="index">visuals registration index</param>
private void CreateIcon(string url, float x, float y, float w, float h, int index)
{
PropertyMap map = new PropertyMap();
PropertyMap transformMap = new PropertyMap();
map.Add(Visual.Property.Type, new PropertyValue((int)Visual.Type.Image))
.Add(ImageVisualProperty.URL, new PropertyValue(url));
VisualBase icon = VisualFactory.Instance.CreateVisual(map);
PropertyMap imageVisualTransform = new PropertyMap();
imageVisualTransform.Add((int)VisualTransformPropertyType.Offset, new PropertyValue(new Vector2(x, y)))
.Add((int)VisualTransformPropertyType.OffsetPolicy, new PropertyValue(new Vector2((int)VisualTransformPolicyType.Absolute, (int)VisualTransformPolicyType.Absolute)))
.Add((int)VisualTransformPropertyType.SizePolicy, new PropertyValue(new Vector2((int)VisualTransformPolicyType.Absolute, (int)VisualTransformPolicyType.Absolute)))
.Add((int)VisualTransformPropertyType.Size, new PropertyValue(new Vector2(w, h)))
.Add((int)VisualTransformPropertyType.Origin, new PropertyValue((int)Visual.AlignType.CenterBegin))
.Add((int)VisualTransformPropertyType.AnchorPoint, new PropertyValue((int)Visual.AlignType.CenterBegin));
icon.SetTransformAndSize(imageVisualTransform, new Vector2(this.SizeWidth, this.SizeHeight));
RegisterVisual(index, icon);
icon.DepthIndex = index;
}
/// <summary>
/// Contact View constructor
/// </summary>
/// <param name="name">name viewed by CustomView object</param>
/// <param name="resourceDirectory">resource directory path used to create absolute paths to icons</param>
/// <returns></returns>
public ContactView(string name, string resourceDirectory) : base(typeof(ContactView).Name, CustomViewBehaviour.ViewBehaviourDefault)
{
this.name = name;
this.resourceDirectory = resourceDirectory;
//Add background to contact view
CreateBackground(new Vector4(1.0f, 1.0f, 1.0f, 1.0f));
//Append icons using absolute path and icons positions parameters.
CreateIcon(resourceDirectory + "/images/cbg.png", 10.0f, 5.0f, 100.0f, 100.0f, ContactBgIconIndex);
CreateIcon(resourceDirectory + "/images/contact.png", 10.0f, 5.0f, 100.0f, 100.0f, ContactIconIndex);
CreateIcon(resourceDirectory + "/images/edit.png", 130.0f, 40.0f, 50.0f, 50.0f, ContactEditIndex);
CreateIcon(resourceDirectory + "/images/favorite.png", 180.0f, 40.0f, 50.0f, 50.0f, ContactFavoriteIndex);
CreateIcon(resourceDirectory + "/images/delete.png", 640.0f, 40.0f, 50.0f, 50.0f, ContactDeleteIndex);
//Append title
CreateLabel(name);
}
}
}
|
using HealthCareWebsite.Data;
using HealthCareWebsite.Helper;
using HealthCareWebsite.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace HealthCareWebsite.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly DatabaseContext db;
private readonly UserManager<IdentityUser> userManager;
public List<Cart> myCart;
public HomeController(ILogger<HomeController> logger, DatabaseContext _db, UserManager<IdentityUser> userManager)
{
_logger = logger;
db = _db;
this.userManager = userManager;
}
public IActionResult Index()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
public IActionResult MedicineList(string sortField, string currentSortField, string sortDirection)
{
var mlist = (from m in db.Medicines
from c in db.Categories
where m.CategoryId == c.CId
select new MedicinesModel
{
MName = m.MName,
MPrice = m.MPrice,
MImage = m.MImage,
IsAvailable = m.IsAvailable,
CName = c.CName,
MId=m.MId
}
).ToList();
return View(this.SortMeds(mlist, sortField, currentSortField, sortDirection));
}
public List<MedicinesModel> SortMeds(List<MedicinesModel>meds,string sortField,string currentSortField,string sortDirection)
{
if (sortField==null)
{
ViewBag.SortField = "MName";
ViewBag.SortDirection = "Asc";
}
else
{
if (currentSortField == sortField)
ViewBag.SortDirection = sortDirection == "Asc" ? "Des" : "Asc";
else
ViewBag.SortDirection = "Asc";
ViewBag.SortField = sortField;
}
var propertyInfo = typeof(MedicinesModel).GetProperty(ViewBag.SortField);
if (ViewBag.SortDirection == "Asc")
meds = meds.OrderBy(e => propertyInfo.GetValue(e, null)).ToList();
else
meds=meds.OrderByDescending(e=>propertyInfo.GetValue(e, null)).ToList();
return meds;
}
public ActionResult Search()
{
return View();
}
[HttpPost]
public ActionResult Search(String Searching)
{
IEnumerable<MedicinesModel> SearchResult = (from m in db.Medicines
from c in db.Categories
where m.CategoryId==c.CId
where m.MName.Contains(Searching)
|| c.CName.Contains(Searching)
select new MedicinesModel
{
MName = m.MName,
MPrice = m.MPrice,
MImage = m.MImage,
IsAvailable = m.IsAvailable,
CName = c.CName,
MId=m.MId
}
).ToList();
return View("MedicineList", SearchResult);
}
public IActionResult CategoryList()
{
return View(db.Categories.ToList());
}
public IActionResult Category(int id)
{
IEnumerable<MedicinesModel> cs = (from m in db.Medicines
from c in db.Categories
where m.CategoryId == c.CId
where c.CId==id
select new MedicinesModel
{
MName = m.MName,
MPrice = m.MPrice,
MImage = m.MImage,
IsAvailable = m.IsAvailable,
CName = c.CName,
MId = m.MId
}).ToList();
return View("MedicineList",cs);
}
[HttpPost]
public JsonResult AddToCart(int id)
{
var objItem = db.Medicines.Find(id);
var cart = SessionHelper.GetObjectFromJson<List<Cart>>(HttpContext.Session, "cart");
if (cart == null)
{
cart = new List<Cart>
{
new Cart()
{
medicine = objItem,
Quantity = 1
}
};
SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);
}
else
{
var index = Exists(cart, id);
if (index == -1)
{
cart.Add(new Cart()
{
medicine = objItem,
Quantity = 1
});
}
else
{
var newQuantity = cart[index].Quantity + 1;
cart[index].Quantity = newQuantity;
}
SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);
}
return Json(cart);
}
private int Exists(List<Cart> cart, int id)
{
for (int i = 0; i < cart.Count; i++)
{
if (cart[i].medicine.MId.Equals(id))
{
return i;
}
}
return -1;
}
public IActionResult UCart()
{
myCart = SessionHelper.GetObjectFromJson<List<Cart>>(HttpContext.Session, "cart");
return View(myCart);
}
public IActionResult Remove(int id)
{
myCart = SessionHelper.GetObjectFromJson<List<Cart>>(HttpContext.Session, "cart");
var index = Exists(myCart, id);
myCart.RemoveAt(index);
SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", myCart);
return RedirectToAction("UCart");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class Menu : MonoBehaviour
{
public Text text_welcome;
void Start()
{
var auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
if (auth.CurrentUser != null)
text_welcome.text = "BEM VINDO: " + auth.CurrentUser.Email.ToUpper();
else
text_welcome.text = "BEM VINDO: " + "ANONIMO";
}
public void OpenURL(string url)
{
Application.OpenURL(url);
}
public void signOut()
{
var auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
auth.SignOut();
SceneManager.LoadScene("Login");
}
}
|
using System;
using System.IO;
using Appy.Core.Framework;
using Splash.Models;
namespace Splash.Services
{
public class SettingsService : ISettingsService
{
private readonly string SettingsFile;
public SettingsService()
{
var appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
SettingsFile = Dirs.Combine(appDataFolder, "Splash", "Settings.json");
}
public Settings Get()
{
if (File.Exists(SettingsFile))
{
var jsonString = File.ReadAllText(SettingsFile);
return Json.ToObject<Settings>(jsonString);
}
var myDocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
return Settings.Default(defaultDownloadsFolder: Dirs.Combine(myDocs, "Splash"));
}
public Settings Save(Settings settings)
{
settings.LastModified = DateTime.Now;
var jsonString = Json.ToString(settings);
File.WriteAllText(SettingsFile, jsonString);
return settings;
}
}
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfImageDrawApplication1
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//
//this.Dispatcher.Invoke(() => {
var path = System.IO.Path.Combine(System.Environment.CurrentDirectory, @"image.png");
ImageCollection = new ObservableCollection<ImageSourceModel>();
for (int i = 0; i < 5000; i++)
{
// no cache
var image = new BitmapImage();
image.BeginInit();
//image.CacheOption = BitmapCacheOption.OnLoad;
image.CacheOption = BitmapCacheOption.None;
image.CreateOptions = BitmapCreateOptions.DelayCreation;
//image.CreateOptions = BitmapCreateOptions.None;
image.UriSource = new Uri(path, UriKind.Absolute);
image.EndInit();
image.Freeze();
ImageCollection.Add(new ImageSourceModel(image));
//ImageCollection.Add(new ImageSourceModel(new ImageBrush(image)));
}
path = System.IO.Path.Combine(System.Environment.CurrentDirectory, @"image2.png");
var image2 = new BitmapImage();
image2.BeginInit();
image2.CacheOption = BitmapCacheOption.OnLoad;
image2.CreateOptions = BitmapCreateOptions.None;
image2.UriSource = new Uri(path, UriKind.Absolute);
image2.EndInit();
image2.Freeze();
ImageCollection.Add(new ImageSourceModel(image2));
//ImageCollection.Add(new ImageSourceModel(new ImageBrush(image2)));
DataContext = ImageCollection;
/// });
}
public ObservableCollection<ImageSourceModel> ImageCollection
{
set;get;
}
}
public class ImageSourceModel : INotifyPropertyChanged
//public class ImageSourceModel
{
public ImageSourceModel()
{
Bitmap = new BitmapImage();
//Bitmap = new ImageBrush();
}
public ImageSourceModel(BitmapImage path)
//public ImageSourceModel(ImageBrush path)
{
Bitmap = path;
}
private BitmapImage _bitmapImage = new BitmapImage();
public BitmapImage Bitmap
//private ImageBrush _bitmapImage = new ImageBrush();
//public ImageBrush Bitmap
{
get
{
/*
var path = System.IO.Path.Combine(System.Environment.CurrentDirectory, @"image.png");
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.CreateOptions = BitmapCreateOptions.None;
image.UriSource = new Uri(path, UriKind.Absolute);
image.EndInit();
image.Freeze();
_bitmapImage = image;
*/
return _bitmapImage;
}
set
{
_bitmapImage = value;
OnPropertyChanged("Bitmap");
}
}
#region INotifyPropertyChanged メンバ
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string name)
{
if (PropertyChanged == null) return;
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
#endregion
}
}
|
using System;
using IWx_Station;
namespace IWx_Station_Extended
{
// events are declared in the implementing class
public delegate void DelChangedHumidity(Single humidity);
public interface IWxStationExtended : IWxStation
{
// an event is just another way of specifying a method. So spec it in the interface.
event DelChangedHumidity ChangedHumidity;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Clases
{
public class Cartuchera1
{
private List<IAcciones> listaIAcciones;
public bool ProbarElementos()
{
foreach (IAcciones accion in listaIAcciones)
{
float aux = accion.UnidadesDeEscritura;
accion.UnidadesDeEscritura -= 1;
if (accion.UnidadesDeEscritura == aux)
{
return false;
}
if (accion.UnidadesDeEscritura <= 1)
{
accion.Recargar(3);
}
}
return true;
}
public List<IAcciones> ListaAcciones
{
get { return this.listaIAcciones; }
set { this.listaIAcciones = value; }
}
}
}
|
using PDV.DAO.Custom;
using PDV.DAO.DB.Controller;
using PDV.DAO.Entidades.Financeiro;
using PDV.DAO.Enum;
using System.Data;
using System;
namespace PDV.CONTROLER.Funcoes
{
public class FuncoesMovimentoBancario
{
public static bool Salvar(MovimentoBancario Movimento, TipoOperacao Op)
{
using (SQLQuery oSQL = new SQLQuery())
{
switch (Op)
{
case TipoOperacao.INSERT:
oSQL.SQL = @"INSERT INTO MOVIMENTOBANCARIO
(IDMOVIMENTOBANCARIO, IDCONTABANCARIA, IDNATUREZA, DATAMOVIMENTO, VALOR, DOCUMENTO, SEQUENCIA, HISTORICO, TIPO, CONCILIACAO)
VALUES
(@IDMOVIMENTOBANCARIO, @IDCONTABANCARIA, @IDNATUREZA, @DATAMOVIMENTO, @VALOR, @DOCUMENTO, @SEQUENCIA, @HISTORICO, @TIPO, @CONCILIACAO)";
break;
case TipoOperacao.UPDATE:
oSQL.SQL = @"UPDATE MOVIMENTOBANCARIO
SET IDCONTABANCARIA = @IDCONTABANCARIA,
IDNATUREZA = @IDNATUREZA,
DATAMOVIMENTO = @DATAMOVIMENTO,
VALOR = @VALOR,
DOCUMENTO = @DOCUMENTO,
SEQUENCIA = @SEQUENCIA,
HISTORICO = @HISTORICO,
TIPO = @TIPO,
CONCILIACAO = @CONCILIACAO
WHERE IDMOVIMENTOBANCARIO = @IDMOVIMENTOBANCARIO";
break;
}
oSQL.ParamByName["IDMOVIMENTOBANCARIO"] = Movimento.IDMovimentoBancario;
oSQL.ParamByName["IDCONTABANCARIA"] = Movimento.IDContaBancaria;
oSQL.ParamByName["IDNATUREZA"] = Movimento.IDNatureza;
oSQL.ParamByName["DATAMOVIMENTO"] = Movimento.DataMovimento;
oSQL.ParamByName["VALOR"] = Movimento.Valor;
oSQL.ParamByName["DOCUMENTO"] = Movimento.Documento;
oSQL.ParamByName["SEQUENCIA"] = Movimento.Sequencia;
oSQL.ParamByName["HISTORICO"] = Movimento.Historico;
oSQL.ParamByName["TIPO"] = Movimento.Tipo;
oSQL.ParamByName["CONCILIACAO"] = Movimento.Conciliacao;
return oSQL.ExecSQL() == 1;
}
}
public static bool Remover(decimal IDMovimentoBancario)
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = "DELETE FROM MOVIMENTOBANCARIO WHERE IDMOVIMENTOBANCARIO = @IDMOVIMENTOBANCARIO";
oSQL.ParamByName["IDMOVIMENTOBANCARIO"] = IDMovimentoBancario;
return oSQL.ExecSQL() == 1;
}
}
public static MovimentoBancario GetMovimento(decimal IDMovimentoBancario)
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = "SELECT * FROM MOVIMENTOBANCARIO WHERE IDMOVIMENTOBANCARIO = @IDMOVIMENTOBANCARIO";
oSQL.ParamByName["IDMOVIMENTOBANCARIO"] = IDMovimentoBancario;
oSQL.Open();
if (oSQL.IsEmpty)
return null;
return EntityUtil<MovimentoBancario>.ParseDataRow(oSQL.dtDados.Rows[0]);
}
}
public static DataTable GetMovimentos(string Descricao)
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = $@"SELECT MOVIMENTOBANCARIO.IDMOVIMENTOBANCARIO,
MOVIMENTOBANCARIO.DATAMOVIMENTO,
MOVIMENTOBANCARIO.DOCUMENTO,
MOVIMENTOBANCARIO.SEQUENCIA,
CONTABANCARIA.NOME AS CONTABANCARIA,
MOVIMENTOBANCARIO.VALOR,
CASE
WHEN MOVIMENTOBANCARIO.TIPO = 0 THEN 'Débito'
WHEN MOVIMENTOBANCARIO.TIPO = 1 THEN 'Crédito'
END AS TIPO
FROM MOVIMENTOBANCARIO
INNER JOIN CONTABANCARIA ON (MOVIMENTOBANCARIO.IDCONTABANCARIA = CONTABANCARIA.IDCONTABANCARIA)
WHERE (UPPER(MOVIMENTOBANCARIO.DOCUMENTO) LIKE UPPER('%{Descricao}%') OR UPPER(CONTABANCARIA.NOME) LIKE UPPER('%{Descricao}%'))
ORDER BY MOVIMENTOBANCARIO.DATAMOVIMENTO DESC";
oSQL.Open();
return oSQL.dtDados;
}
}
public static bool RemoverPorDocumento(string Documento, decimal Tipo)
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = "DELETE FROM MOVIMENTOBANCARIO WHERE DOCUMENTO = @DOCUMENTO AND TIPO = @TIPO";
oSQL.ParamByName["DOCUMENTO"] = Documento;
oSQL.ParamByName["TIPO"] = Tipo;
return oSQL.ExecSQL() >= 0;
}
}
public static bool Conciliar(decimal IDMovimentoBancario, DateTime? DataConciliacao)
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = "UPDATE MOVIMENTOBANCARIO SET CONCILIACAO = @CONCILIACAO WHERE IDMOVIMENTOBANCARIO = @IDMOVIMENTOBANCARIO";
oSQL.ParamByName["IDMOVIMENTOBANCARIO"] = IDMovimentoBancario;
oSQL.ParamByName["CONCILIACAO"] = DataConciliacao;
return oSQL.ExecSQL() == 1;
}
}
}
} |
namespace Alword.Algoexpert.Tier0
{
public class PalindromeCheckTask
{
public static bool IsPalindrome(string str)
{
for (int i = 0; i < str.Length / 2; i++)
{
if (str[i] != str[str.Length - i - 1])
return false;
}
return true;
}
}
}
|
using System.Windows.Forms;
namespace YongHongSoft.YueChi
{
public partial class FormMain : Form
{
private FormInput input;
private FormOutMap outMap;
public FormMain()
{
InitializeComponent();
}
private void toolStripButtonInput_Click(object sender, System.EventArgs e)
{
if (this.input == null)
{
FormInput input = new FormInput();
this.input = input;
input.TopLevel = false;
input.ShowInTaskbar = false;
input.Parent = this;
input.Show();
if (this.outMap != null)
outMap.Hide();
}
else
{
input.Show();
if(this.outMap!=null)
outMap.Hide();
}
}
private void toolStripButtonOutMap_Click(object sender, System.EventArgs e)
{
if (this.outMap == null)
{
FormOutMap outMap = new FormOutMap();
this.outMap = outMap;
outMap.TopLevel = false;
outMap.ShowInTaskbar = false;
outMap.Parent = this;
outMap.Show();
if (this.input != null)
{
input.Hide();
}
}
else
{
outMap.Show();
if (this.input != null)
{
input.Hide();
}
}
}
private void FormMain_Load(object sender, System.EventArgs e)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Zhouli.DAL.Interface;
using Zhouli.DbEntity.Models;
namespace Zhouli.DAL.Implements
{
public class SysAbRelatedDAL : BaseDAL<SysAbRelated>, ISysAbRelatedDAL
{
public SysAbRelatedDAL(ZhouLiContext db, IDbConnection dbConnection) : base(db, dbConnection)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using API.Dtos;
using API.Models;
using API.Services;
using AutoMapper;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
namespace API.ServicesImpl
{
public class UserService : IUserService
{
private readonly UserManager<AppUser> userManager;
private readonly IMapper mapper;
private readonly RoleManager<AppRole> roleManager;
public UserService(UserManager<AppUser> userManager, RoleManager<AppRole> roleManager, IMapper mapper)
{
this.roleManager = roleManager;
this.mapper = mapper;
this.userManager = userManager;
}
public async Task<IAsyncResult> DeleteAsync(int id)
{
var user = await userManager.FindByIdAsync(id.ToString());
if (user == null) throw new Exception("Not found");
var result = await userManager.DeleteAsync(user);
if (!result.Succeeded) throw new Exception("error deleting an user");
return Task.CompletedTask;
}
public async Task<IEnumerable<UserToReturn>> GetAllAdminsAsync()
{
var users = await userManager.GetUsersInRoleAsync("Admin");
if (users == null) throw new Exception("Not found");
var usersToReturn = mapper.Map<IEnumerable<UserToReturn>>(users);
return usersToReturn;
}
public async Task<IEnumerable<UserToReturn>> GetAllAsync()
{
var users = await userManager.Users.ToListAsync();
if (users == null) throw new Exception("Not found");
var usersToReturn = mapper.Map<IEnumerable<UserToReturn>>(users);
int i = 0;
foreach(var user in usersToReturn)
{
var role = await userManager.GetRolesAsync(users[i]);
user.Role = role[0];
i++;
}
return usersToReturn;
}
public async Task<IEnumerable<UserToReturn>> GetAllUsersAsync()
{
var users = await userManager.GetUsersInRoleAsync("User");
if (users == null) throw new Exception("Not found");
var usersToReturn = mapper.Map<IEnumerable<UserToReturn>>(users);
return usersToReturn;
}
public async Task<UserToReturn> GetAsync(int id)
{
var user = await userManager.FindByIdAsync(id.ToString());
var role = await userManager.GetRolesAsync(user);
if (user == null) throw new Exception("Not found");
var userToReturn = mapper.Map<UserToReturn>(user);
userToReturn.Role = role[0];
return userToReturn;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Infra;
namespace CareerCup150.Chapter4_TreeGraph
{
public class _04_08_SumPath
{
/*
* You are given a binary tree in which each node contains a value. Design an algorithm to print all paths
* which sum up to that value. Note that it can be any path in the tree - it does not have to start at the root.
*/
public List<int> GetAllPath(TreeNode root, int value)
{
List<int> res = new List<int>();
Stack<TreeNode> s = new Stack<TreeNode>();
Stack<TreeNode> r = new Stack<TreeNode>();
s.Push(root);
int sum = 0;
TreeNode tmp = null;
while (s.Count != 0)
{
bool pushed = false;
if (s.Peek().LeftChild != null)
{
s.Push(s.Peek().LeftChild);
pushed = true;
}
else if (s.Peek().RightChild != null)
{
s.Push(s.Peek().RightChild);
pushed = true;
}
else
{
s.Pop();
}
if (pushed)
{
sum = 0;
while (s.Count != 0)
{
tmp = s.Pop();
r.Push(tmp);
sum = tmp.Value++;
if (sum == value)
{
List<int> list = new List<int>();
while (r.Count != 0)
{
tmp = r.Pop();
list.Add(tmp.Value);
s.Push(tmp);
}
}
}
}
}
return res;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace FelixTheCat.BlackHole
{
/// <summary>
/// Generate random objects and lists with random objects
/// </summary>
public static class FiguresGenerator
{
private static readonly List<string[,]> symbols = new List<string[,]>();
private static readonly List<ConsoleColor> colors = new List<ConsoleColor>();
private static readonly int distance = 6;
private static readonly Random randomGenerator = new Random();
/// <summary>
/// All shapes, used for the falling objects
/// </summary>
/// <returns></returns>
public static List<string[,]> GetSymbols()
{
if (symbols.Count > 0)
{
return symbols;
}
string[,] triangle =
{
{" █ "},
{" ███ "},
{" █▓ ██ "},
{" █▓ ██ "},
{"█████████"},
};
symbols.Add(triangle);
string[,] reversedTriangle =
{
{"█████████"},
{" ██ ▓█ "},
{" ██ ▓█ "},
{" ███ "},
{" █ "},
};
symbols.Add(reversedTriangle);
string[,] squareWithDot =
{
{"░███████░"},
{"██ ██"},
{"██ ▒█▒ ██"},
{"██ ██"},
{"░███████░"},
};
symbols.Add(squareWithDot);
string[,] square =
{
{"▒███████▒"},
{"██ ██"},
{"██ ██"},
{"██ ██"},
{"▒███████▒"},
};
symbols.Add(square);
string[,] hexagon =
{
{" █████ "},
{" ██ ▓█ "},
{"██ ▓█"},
{" ██ ▓█ "},
{" █████ "},
};
symbols.Add(hexagon);
string[,] heart =
{
{" ██▓ ██▓ "},
{"██ █▓ █▓"},
{" ██ █▓ "},
{" ██ █▓ "},
{" ██ "},
};
symbols.Add(heart);
string[,] trapezoid =
{
{" ███ "},
{" █▓ ██ "},
{" █▓ ██ "},
{"█▓ ██"},
{"█████████"},
};
symbols.Add(trapezoid);
return symbols;
}
/// <summary>
/// All colors, used for the falling objects
/// </summary>
/// <returns></returns>
public static List<ConsoleColor> GetColors()
{
if (colors.Count > 0)
{
return colors;
}
colors.Add(ConsoleColor.Blue);
colors.Add(ConsoleColor.Cyan);
colors.Add(ConsoleColor.DarkBlue);
colors.Add(ConsoleColor.DarkCyan);
colors.Add(ConsoleColor.DarkGreen);
colors.Add(ConsoleColor.DarkMagenta);
colors.Add(ConsoleColor.DarkYellow);
colors.Add(ConsoleColor.Green);
colors.Add(ConsoleColor.Magenta);
colors.Add(ConsoleColor.Red);
colors.Add(ConsoleColor.Yellow);
return colors;
}
/// <summary>
/// Generate a random list with objects with random shape and color
/// </summary>
/// <param name="number"></param>
/// <param name="windowWidth"></param>
/// <returns></returns>
public static List<Figure> GetRandomList(int number, int windowWidth)
{
GetSymbols();
GetColors();
if (number < 1 || number > symbols.Count)
{
throw new Exception("Number must be between 1 and " + symbols.Count);
}
List<Figure> list = new List<Figure>(number);
symbols.Shuffle();
colors.Shuffle();
for (int i = 0; i < number; i++)
{
list.Add(new Figure(symbols[i], colors[i], 0, 0));
}
CalculateXCoodrinates(ref list, windowWidth);
return list;
}
/// <summary>
/// Remove a random objects from a list
/// </summary>
/// <param name="list"></param>
/// <param name="windowWidth"></param>
/// <returns></returns>
public static Figure RemoveRandomFigureFromList(ref List<Figure> list, int windowWidth)
{
Figure figure = list[randomGenerator.Next(0, list.Count)];
list.Remove(figure);
// recalculate x coordinates
CalculateXCoodrinates(ref list, windowWidth);
return figure;
}
/// <summary>
/// Generate a list, containing the missing objects
/// </summary>
/// <param name="originalList"></param>
/// <param name="missingElement"></param>
/// <param name="windowWidth"></param>
/// <returns></returns>
public static List<Figure> GetResultList(List<Figure> originalList, Figure missingElement, int windowWidth)
{
List<Figure> resultList = originalList.ToList();
resultList.Add(missingElement);
Figure newElement;
do
{
newElement = GetRandomFigure();
} while (resultList.Contains(newElement) == true);
resultList.Add(newElement);
resultList.Shuffle();
CalculateXCoodrinates(ref resultList, windowWidth);
return resultList;
}
/// <summary>
/// Generate an object with random shape and color
/// </summary>
/// <returns></returns>
public static Figure GetRandomFigure()
{
GetSymbols();
GetColors();
return new Figure(symbols[randomGenerator.Next(0, symbols.Count)],
colors[randomGenerator.Next(0, colors.Count)], 0, 0);
}
/// <summary>
/// Calculate the initial column coordinates of the objects
/// </summary>
/// <param name="list"></param>
/// <param name="windowWidth"></param>
private static void CalculateXCoodrinates(ref List<Figure> list, int windowWidth)
{
int figuresWidth = 0;
for (int i = 0; i < list.Count; i++)
{
figuresWidth += list[i].Width;
}
int startX = (windowWidth - (figuresWidth + (distance * (list.Count - 1)))) / 2;
for (int i = 0; i < list.Count; i++)
{
list[i].StartX = startX;
startX += list[i].Width + distance;
}
}
}
}
|
/*
* OpenAPI definition
*
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: v0
*
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Net.Mime;
using LoanStreet.LoanServicing.Client;
using LoanStreet.LoanServicing.Model;
namespace LoanStreet.LoanServicing.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IBorrowingsApiSync : IApiAccessor
{
#region Synchronous Operations
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="LoanStreet.LoanServicing.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="facilityId"></param>
/// <param name="borrowingId"></param>
/// <returns>Borrowing</returns>
Borrowing GetBorrowing (string facilityId, string borrowingId);
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="LoanStreet.LoanServicing.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="facilityId"></param>
/// <param name="borrowingId"></param>
/// <returns>ApiResponse of Borrowing</returns>
ApiResponse<Borrowing> GetBorrowingWithHttpInfo (string facilityId, string borrowingId);
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="LoanStreet.LoanServicing.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="facilityId"></param>
/// <returns>List<Borrowing></returns>
List<Borrowing> ListBorrowings (string facilityId);
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="LoanStreet.LoanServicing.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="facilityId"></param>
/// <returns>ApiResponse of List<Borrowing></returns>
ApiResponse<List<Borrowing>> ListBorrowingsWithHttpInfo (string facilityId);
#endregion Synchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IBorrowingsApiAsync : IApiAccessor
{
#region Asynchronous Operations
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="LoanStreet.LoanServicing.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="facilityId"></param>
/// <param name="borrowingId"></param>
/// <returns>Task of Borrowing</returns>
System.Threading.Tasks.Task<Borrowing> GetBorrowingAsync (string facilityId, string borrowingId);
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="LoanStreet.LoanServicing.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="facilityId"></param>
/// <param name="borrowingId"></param>
/// <returns>Task of ApiResponse (Borrowing)</returns>
System.Threading.Tasks.Task<ApiResponse<Borrowing>> GetBorrowingAsyncWithHttpInfo (string facilityId, string borrowingId);
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="LoanStreet.LoanServicing.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="facilityId"></param>
/// <returns>Task of List<Borrowing></returns>
System.Threading.Tasks.Task<List<Borrowing>> ListBorrowingsAsync (string facilityId);
/// <summary>
///
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="LoanStreet.LoanServicing.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="facilityId"></param>
/// <returns>Task of ApiResponse (List<Borrowing>)</returns>
System.Threading.Tasks.Task<ApiResponse<List<Borrowing>>> ListBorrowingsAsyncWithHttpInfo (string facilityId);
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IBorrowingsApi : IBorrowingsApiSync, IBorrowingsApiAsync
{
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class BorrowingsApi : IBorrowingsApi
{
private LoanStreet.LoanServicing.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="BorrowingsApi"/> class.
/// </summary>
/// <returns></returns>
public BorrowingsApi() : this((string) null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BorrowingsApi"/> class.
/// </summary>
/// <returns></returns>
public BorrowingsApi(String basePath)
{
this.Configuration = LoanStreet.LoanServicing.Client.Configuration.MergeConfigurations(
LoanStreet.LoanServicing.Client.GlobalConfiguration.Instance,
new LoanStreet.LoanServicing.Client.Configuration { BasePath = basePath }
);
this.Client = new LoanStreet.LoanServicing.Client.ApiClient(this.Configuration.BasePath);
this.AsynchronousClient = new LoanStreet.LoanServicing.Client.ApiClient(this.Configuration.BasePath);
this.ExceptionFactory = LoanStreet.LoanServicing.Client.Configuration.DefaultExceptionFactory;
}
/// <summary>
/// Initializes a new instance of the <see cref="BorrowingsApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public BorrowingsApi(LoanStreet.LoanServicing.Client.Configuration configuration)
{
if (configuration == null) throw new ArgumentNullException("configuration");
this.Configuration = LoanStreet.LoanServicing.Client.Configuration.MergeConfigurations(
LoanStreet.LoanServicing.Client.GlobalConfiguration.Instance,
configuration
);
this.Client = new LoanStreet.LoanServicing.Client.ApiClient(this.Configuration.BasePath);
this.AsynchronousClient = new LoanStreet.LoanServicing.Client.ApiClient(this.Configuration.BasePath);
ExceptionFactory = LoanStreet.LoanServicing.Client.Configuration.DefaultExceptionFactory;
}
/// <summary>
/// Initializes a new instance of the <see cref="BorrowingsApi"/> class
/// using a Configuration object and client instance.
/// </summary>
/// <param name="client">The client interface for synchronous API access.</param>
/// <param name="asyncClient">The client interface for asynchronous API access.</param>
/// <param name="configuration">The configuration object.</param>
public BorrowingsApi(LoanStreet.LoanServicing.Client.ISynchronousClient client,LoanStreet.LoanServicing.Client.IAsynchronousClient asyncClient, LoanStreet.LoanServicing.Client.IReadableConfiguration configuration)
{
if(client == null) throw new ArgumentNullException("client");
if(asyncClient == null) throw new ArgumentNullException("asyncClient");
if(configuration == null) throw new ArgumentNullException("configuration");
this.Client = client;
this.AsynchronousClient = asyncClient;
this.Configuration = configuration;
this.ExceptionFactory = LoanStreet.LoanServicing.Client.Configuration.DefaultExceptionFactory;
}
/// <summary>
/// The client for accessing this underlying API asynchronously.
/// </summary>
public LoanStreet.LoanServicing.Client.IAsynchronousClient AsynchronousClient { get; set; }
/// <summary>
/// The client for accessing this underlying API synchronously.
/// </summary>
public LoanStreet.LoanServicing.Client.ISynchronousClient Client { get; set; }
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.BasePath;
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public LoanStreet.LoanServicing.Client.IReadableConfiguration Configuration {get; set;}
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public LoanStreet.LoanServicing.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary>
///
/// </summary>
/// <exception cref="LoanStreet.LoanServicing.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="facilityId"></param>
/// <param name="borrowingId"></param>
/// <returns>Borrowing</returns>
public Borrowing GetBorrowing (string facilityId, string borrowingId)
{
LoanStreet.LoanServicing.Client.ApiResponse<Borrowing> localVarResponse = GetBorrowingWithHttpInfo(facilityId, borrowingId);
return localVarResponse.Data;
}
/// <summary>
///
/// </summary>
/// <exception cref="LoanStreet.LoanServicing.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="facilityId"></param>
/// <param name="borrowingId"></param>
/// <returns>ApiResponse of Borrowing</returns>
public LoanStreet.LoanServicing.Client.ApiResponse< Borrowing > GetBorrowingWithHttpInfo (string facilityId, string borrowingId)
{
// verify the required parameter 'facilityId' is set
if (facilityId == null)
throw new LoanStreet.LoanServicing.Client.ApiException(400, "Missing required parameter 'facilityId' when calling BorrowingsApi->GetBorrowing");
// verify the required parameter 'borrowingId' is set
if (borrowingId == null)
throw new LoanStreet.LoanServicing.Client.ApiException(400, "Missing required parameter 'borrowingId' when calling BorrowingsApi->GetBorrowing");
LoanStreet.LoanServicing.Client.RequestOptions localVarRequestOptions = new LoanStreet.LoanServicing.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = LoanStreet.LoanServicing.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = LoanStreet.LoanServicing.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
if (facilityId != null)
localVarRequestOptions.PathParameters.Add("facilityId", LoanStreet.LoanServicing.Client.ClientUtils.ParameterToString(facilityId)); // path parameter
if (borrowingId != null)
localVarRequestOptions.PathParameters.Add("borrowingId", LoanStreet.LoanServicing.Client.ClientUtils.ParameterToString(borrowingId)); // path parameter
// authentication (bearer-token) required
// http basic authentication required
if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + LoanStreet.LoanServicing.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password));
}
// make the HTTP request
var localVarResponse = this.Client.Get< Borrowing >("/v1/private/facilities/{facilityId}/borrowings/{borrowingId}", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("GetBorrowing", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
///
/// </summary>
/// <exception cref="LoanStreet.LoanServicing.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="facilityId"></param>
/// <param name="borrowingId"></param>
/// <returns>Task of Borrowing</returns>
public async System.Threading.Tasks.Task<Borrowing> GetBorrowingAsync (string facilityId, string borrowingId)
{
LoanStreet.LoanServicing.Client.ApiResponse<Borrowing> localVarResponse = await GetBorrowingAsyncWithHttpInfo(facilityId, borrowingId);
return localVarResponse.Data;
}
/// <summary>
///
/// </summary>
/// <exception cref="LoanStreet.LoanServicing.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="facilityId"></param>
/// <param name="borrowingId"></param>
/// <returns>Task of ApiResponse (Borrowing)</returns>
public async System.Threading.Tasks.Task<LoanStreet.LoanServicing.Client.ApiResponse<Borrowing>> GetBorrowingAsyncWithHttpInfo (string facilityId, string borrowingId)
{
// verify the required parameter 'facilityId' is set
if (facilityId == null)
throw new LoanStreet.LoanServicing.Client.ApiException(400, "Missing required parameter 'facilityId' when calling BorrowingsApi->GetBorrowing");
// verify the required parameter 'borrowingId' is set
if (borrowingId == null)
throw new LoanStreet.LoanServicing.Client.ApiException(400, "Missing required parameter 'borrowingId' when calling BorrowingsApi->GetBorrowing");
LoanStreet.LoanServicing.Client.RequestOptions localVarRequestOptions = new LoanStreet.LoanServicing.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
foreach (var _contentType in _contentTypes)
localVarRequestOptions.HeaderParameters.Add("Content-Type", _contentType);
foreach (var _accept in _accepts)
localVarRequestOptions.HeaderParameters.Add("Accept", _accept);
if (facilityId != null)
localVarRequestOptions.PathParameters.Add("facilityId", LoanStreet.LoanServicing.Client.ClientUtils.ParameterToString(facilityId)); // path parameter
if (borrowingId != null)
localVarRequestOptions.PathParameters.Add("borrowingId", LoanStreet.LoanServicing.Client.ClientUtils.ParameterToString(borrowingId)); // path parameter
// authentication (bearer-token) required
// http basic authentication required
if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + LoanStreet.LoanServicing.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password));
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.GetAsync<Borrowing>("/v1/private/facilities/{facilityId}/borrowings/{borrowingId}", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("GetBorrowing", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
///
/// </summary>
/// <exception cref="LoanStreet.LoanServicing.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="facilityId"></param>
/// <returns>List<Borrowing></returns>
public List<Borrowing> ListBorrowings (string facilityId)
{
LoanStreet.LoanServicing.Client.ApiResponse<List<Borrowing>> localVarResponse = ListBorrowingsWithHttpInfo(facilityId);
return localVarResponse.Data;
}
/// <summary>
///
/// </summary>
/// <exception cref="LoanStreet.LoanServicing.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="facilityId"></param>
/// <returns>ApiResponse of List<Borrowing></returns>
public LoanStreet.LoanServicing.Client.ApiResponse< List<Borrowing> > ListBorrowingsWithHttpInfo (string facilityId)
{
// verify the required parameter 'facilityId' is set
if (facilityId == null)
throw new LoanStreet.LoanServicing.Client.ApiException(400, "Missing required parameter 'facilityId' when calling BorrowingsApi->ListBorrowings");
LoanStreet.LoanServicing.Client.RequestOptions localVarRequestOptions = new LoanStreet.LoanServicing.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = LoanStreet.LoanServicing.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = LoanStreet.LoanServicing.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
if (facilityId != null)
localVarRequestOptions.PathParameters.Add("facilityId", LoanStreet.LoanServicing.Client.ClientUtils.ParameterToString(facilityId)); // path parameter
// authentication (bearer-token) required
// http basic authentication required
if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + LoanStreet.LoanServicing.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password));
}
// make the HTTP request
var localVarResponse = this.Client.Get< List<Borrowing> >("/v1/private/facilities/{facilityId}/borrowings", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("ListBorrowings", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
///
/// </summary>
/// <exception cref="LoanStreet.LoanServicing.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="facilityId"></param>
/// <returns>Task of List<Borrowing></returns>
public async System.Threading.Tasks.Task<List<Borrowing>> ListBorrowingsAsync (string facilityId)
{
LoanStreet.LoanServicing.Client.ApiResponse<List<Borrowing>> localVarResponse = await ListBorrowingsAsyncWithHttpInfo(facilityId);
return localVarResponse.Data;
}
/// <summary>
///
/// </summary>
/// <exception cref="LoanStreet.LoanServicing.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="facilityId"></param>
/// <returns>Task of ApiResponse (List<Borrowing>)</returns>
public async System.Threading.Tasks.Task<LoanStreet.LoanServicing.Client.ApiResponse<List<Borrowing>>> ListBorrowingsAsyncWithHttpInfo (string facilityId)
{
// verify the required parameter 'facilityId' is set
if (facilityId == null)
throw new LoanStreet.LoanServicing.Client.ApiException(400, "Missing required parameter 'facilityId' when calling BorrowingsApi->ListBorrowings");
LoanStreet.LoanServicing.Client.RequestOptions localVarRequestOptions = new LoanStreet.LoanServicing.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
foreach (var _contentType in _contentTypes)
localVarRequestOptions.HeaderParameters.Add("Content-Type", _contentType);
foreach (var _accept in _accepts)
localVarRequestOptions.HeaderParameters.Add("Accept", _accept);
if (facilityId != null)
localVarRequestOptions.PathParameters.Add("facilityId", LoanStreet.LoanServicing.Client.ClientUtils.ParameterToString(facilityId)); // path parameter
// authentication (bearer-token) required
// http basic authentication required
if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + LoanStreet.LoanServicing.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password));
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.GetAsync<List<Borrowing>>("/v1/private/facilities/{facilityId}/borrowings", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("ListBorrowings", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
}
}
|
/*
------Usage Example -----------------------------------------------------------------
private unsafe void Decode(string url)
{
AVHWDeviceType devType = AVHWDeviceType.AV_HWDEVICE_TYPE_QSV;
Console.WriteLine("Decode start");
using (var decoder = new VideoStreamDecoder(url, devType))
{
var sourceSize = decoder.FrameSize;
var outSize = new Size((int)(decoder.FrameSize.Width*0.5F), (int)(decoder.FrameSize.Height*0.5F));
var sourcePxF = GetHWPixelFormat(devType); //AVPixelFormat.AV_PIX_FMT_NV12 for QSV
var outPxF = AVPixelFormat.AV_PIX_FMT_BGR24;
Console.WriteLine("Selected sourcePxF = " + sourcePxF);
using (VideoFrameConverter frameConverter = new VideoFrameConverter(
sourceSize, sourcePxF,
outSize, outPxF))
{
long frameNum = 0;
while (decoder.TryDecodeNextFrame(out var rawFrame) && started)
{
var frame = frameConverter.Convert(rawFrame);
Bitmap bitmap = (Bitmap)new Bitmap(frame.width, frame.height, frame.linesize[0],
System.Drawing.Imaging.PixelFormat.Format24bppRgb, (IntPtr)frame.data[0]);
//Send to subscriber
if (OnFilterResultEvent != null && started)
OnFilterResultEvent(
new MoveDetectionArgs() { OutputFrame = bitmap, IsSuccess = true },
this);
frameNum += 1;
}
Console.WriteLine("Decode END " + frameNum);
}
}
}
private static AVPixelFormat GetHWPixelFormat(AVHWDeviceType hWDevice)
{
switch (hWDevice)
{
case AVHWDeviceType.AV_HWDEVICE_TYPE_NONE:
return AVPixelFormat.AV_PIX_FMT_NONE;
case AVHWDeviceType.AV_HWDEVICE_TYPE_VDPAU:
return AVPixelFormat.AV_PIX_FMT_VDPAU;
case AVHWDeviceType.AV_HWDEVICE_TYPE_CUDA:
return AVPixelFormat.AV_PIX_FMT_CUDA;
case AVHWDeviceType.AV_HWDEVICE_TYPE_VAAPI:
return AVPixelFormat.AV_PIX_FMT_YUV420P;
case AVHWDeviceType.AV_HWDEVICE_TYPE_DXVA2:
return AVPixelFormat.AV_PIX_FMT_NV12;
case AVHWDeviceType.AV_HWDEVICE_TYPE_QSV:
return AVPixelFormat.AV_PIX_FMT_NV12;
case AVHWDeviceType.AV_HWDEVICE_TYPE_VIDEOTOOLBOX:
return AVPixelFormat.AV_PIX_FMT_VIDEOTOOLBOX;
case AVHWDeviceType.AV_HWDEVICE_TYPE_D3D11VA:
return AVPixelFormat.AV_PIX_FMT_NV12;
case AVHWDeviceType.AV_HWDEVICE_TYPE_DRM:
return AVPixelFormat.AV_PIX_FMT_DRM_PRIME;
case AVHWDeviceType.AV_HWDEVICE_TYPE_OPENCL:
return AVPixelFormat.AV_PIX_FMT_OPENCL;
case AVHWDeviceType.AV_HWDEVICE_TYPE_MEDIACODEC:
return AVPixelFormat.AV_PIX_FMT_MEDIACODEC;
default:
return AVPixelFormat.AV_PIX_FMT_NONE;
}
}
------Usage Example Ends -----------------------------------------------------------------
*/
public sealed unsafe class VideoStreamDecoder : IDisposable
{
private readonly AVCodecContext* _pCodecContext;
private readonly AVFormatContext* _pFormatContext;
private readonly AVStream* _videoStream;
private readonly int _streamIndex;
private readonly AVFrame* _pFrame;
private readonly AVFrame* _receivedFrame;
private readonly AVPacket* _pPacket;
public string CodecName { get; }
public Size FrameSize { get; }
public AVPixelFormat PixelFormat { get; private set; }
private bool isHwAccelerate = false;
public AVPixelFormat HWDevicePixelFormat { get; private set; }
private AVCodecContext_get_format get_fmt = (x, t) =>
{
return GetFormat(x, t);
};
public VideoStreamDecoder(string url, AVHWDeviceType HWDeviceType = AVHWDeviceType.AV_HWDEVICE_TYPE_NONE)
{
_pFormatContext = ffmpeg.avformat_alloc_context();
_receivedFrame = ffmpeg.av_frame_alloc();
var pFormatContext = _pFormatContext;
ffmpeg.avformat_open_input(&pFormatContext, url, null, null).ThrowExceptionIfError();
AVCodec* codec = null;
AVBufferRef *codecBuff = null;
if (HWDeviceType is AVHWDeviceType.AV_HWDEVICE_TYPE_QSV)
{
codec = ffmpeg.avcodec_find_decoder_by_name("h264_qsv");
codec->id = AVCodecID.AV_CODEC_ID_H264;
for (int i = 0; i < _pFormatContext->nb_streams; i++)
{
AVStream* st = _pFormatContext->streams[i];
if (st->codecpar->codec_id == AVCodecID.AV_CODEC_ID_H264 && _videoStream == null)
{
_videoStream = st;
Console.WriteLine("Stream founded!");
}
else
{
st->discard = AVDiscard.AVDISCARD_ALL;
}
}
_streamIndex = _videoStream->index;
}
else
{
_streamIndex = ffmpeg.av_find_best_stream(_pFormatContext, AVMediaType.AVMEDIA_TYPE_VIDEO, -1, -1, &codec, 0);
}
_pCodecContext = ffmpeg.avcodec_alloc_context3(codec);
if (HWDeviceType != AVHWDeviceType.AV_HWDEVICE_TYPE_NONE)
{
if (ffmpeg.av_hwdevice_ctx_create(&_pCodecContext->hw_device_ctx,
HWDeviceType, "auto", null, 0) < 0)
{
throw new Exception("HW device init ERROR!");
}
else
{
Console.WriteLine("Device " + HWDeviceType + " init OK");
isHwAccelerate = true;
}
}
if (_pCodecContext == null)
throw new Exception("Codec init error");
ffmpeg.avformat_find_stream_info(_pFormatContext, null); //This is necessary to determine the parameters of online broadcasting
if (_videoStream->codecpar->extradata != null)
{
int size = (int)(_videoStream->codecpar->extradata_size);
_pCodecContext->extradata = (byte*)ffmpeg.av_mallocz((ulong)size +
ffmpeg.AV_INPUT_BUFFER_PADDING_SIZE);
_pCodecContext->extradata_size = (int)size +
ffmpeg.AV_INPUT_BUFFER_PADDING_SIZE;
FFmpegHelper.memcpy((IntPtr)_pCodecContext->extradata,
(IntPtr)_videoStream->codecpar->extradata,
size);
//Or just
/*for (int i = 0; i < size; i++)
_pCodecContext->extradata[i] = _videoStream->codecpar->extradata[i];*/
}
if (HWDeviceType == AVHWDeviceType.AV_HWDEVICE_TYPE_QSV)
{
_pCodecContext->get_format = get_fmt;
}
ffmpeg.avcodec_parameters_to_context(_pCodecContext, _videoStream->codecpar);
ffmpeg.avcodec_open2(_pCodecContext, codec, null);
CodecName = ffmpeg.avcodec_get_name(codec->id);
FrameSize = new Size(_videoStream->codecpar->width,_videoStream->codecpar->height);
PixelFormat = _pCodecContext->sw_pix_fmt; //It doesn't work (== AV_HWDEVICE_TYPE_NONE before the first frame)
Console.WriteLine("Codec: " + CodecName.ToString());
Console.WriteLine("Size: " + FrameSize.ToString());
Console.WriteLine("PixelFormat: " + PixelFormat.ToString());
_pPacket = ffmpeg.av_packet_alloc();
_pFrame = ffmpeg.av_frame_alloc();
}
public void Dispose()
{
var pFrame = _pFrame;
ffmpeg.av_frame_free(&pFrame);
var pPacket = _pPacket;
ffmpeg.av_packet_free(&pPacket);
ffmpeg.avcodec_close(_pCodecContext);
var pFormatContext = _pFormatContext;
ffmpeg.avformat_close_input(&pFormatContext);
}
public static AVPixelFormat GetFormat(AVCodecContext* context, AVPixelFormat *px_fmts)
{
while (*px_fmts != AVPixelFormat.AV_PIX_FMT_NONE)
{
if(*px_fmts == AVPixelFormat.AV_PIX_FMT_QSV)
{
AVHWFramesContext* fr_ctx;
AVQSVFramesContext* qsv_fr_ctx;
context->hw_frames_ctx = ffmpeg.av_hwframe_ctx_alloc(context->hw_device_ctx);
fr_ctx = (AVHWFramesContext*) context->hw_frames_ctx->data;
qsv_fr_ctx = (AVQSVFramesContext*)fr_ctx->hwctx;
int initialPoolSize = 32;
fr_ctx->format = AVPixelFormat.AV_PIX_FMT_QSV;
fr_ctx->sw_format = context->sw_pix_fmt;
fr_ctx->width = context->coded_width.FFALIGN(initialPoolSize);
fr_ctx->height = context->coded_height.FFALIGN(initialPoolSize);
fr_ctx->initial_pool_size = initialPoolSize;
qsv_fr_ctx->frame_type = (int)MFX_MEMTYPE.MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET;
ffmpeg.av_hwframe_ctx_init(context->hw_frames_ctx).ThrowExceptionIfError();
return AVPixelFormat.AV_PIX_FMT_QSV;
}
px_fmts++;
}
return AVPixelFormat.AV_PIX_FMT_NONE;
}
public bool TryDecodeNextFrame(out AVFrame frame)
{
//Обнуление фреймов
ffmpeg.av_frame_unref(_pFrame);
ffmpeg.av_frame_unref(_receivedFrame);
int error;
do
{
try
{
do
{
ffmpeg.av_packet_unref(_pPacket);
error = ffmpeg.av_read_frame(_pFormatContext, _pPacket);
if (error == ffmpeg.AVERROR_EOF)
{
frame = *_pFrame;
return false;
}
} while (_pPacket->stream_index != _streamIndex);
ffmpeg.avcodec_send_packet(_pCodecContext, _pPacket);
}
finally
{
ffmpeg.av_packet_unref(_pPacket);
}
error = ffmpeg.avcodec_receive_frame(_pCodecContext, _pFrame);
}
while (error == ffmpeg.AVERROR(ffmpeg.EAGAIN));
if (error == ffmpeg.AVERROR(ffmpeg.EAGAIN))
{
Console.WriteLine("error == ffmpeg.AVERROR(ffmpeg.EAGAIN)");
}
if (isHwAccelerate)
{
ffmpeg.av_hwframe_transfer_data(_receivedFrame, _pFrame, 0).ThrowExceptionIfError();
frame = *_receivedFrame;
//Console.WriteLine("Transfer OK");
}
else
{
//Console.WriteLine("PIX is not HW");
frame = *_pFrame;
}
return true;
}
public struct AVQSVFramesContext
{
public IntPtr *surfaces;
public int nb_surfaces;
public int frame_type;
}
public IReadOnlyDictionary<string, string> GetContextInfo()
{
AVDictionaryEntry* tag = null;
var result = new Dictionary<string, string>();
while ((tag = ffmpeg.av_dict_get(_pFormatContext->metadata, "", tag, ffmpeg.AV_DICT_IGNORE_SUFFIX)) != null)
{
var key = Marshal.PtrToStringAnsi((IntPtr)tag->key);
var value = Marshal.PtrToStringAnsi((IntPtr)tag->value);
Console.WriteLine("ContextInfo key: " + key+ "val: " + value);
result.Add(key, value);
}
return result;
}
}
public sealed unsafe class VideoFrameConverter : IDisposable
{
private readonly IntPtr _convertedFrameBufferPtr;
private readonly Size _destinationSize;
private readonly byte_ptrArray4 _dstData;
private readonly int_array4 _dstLinesize;
private readonly SwsContext* _pConvertContext;
public VideoFrameConverter(Size sourceSize, AVPixelFormat sourcePixelFormat,
Size destinationSize, AVPixelFormat destinationPixelFormat)
{
_destinationSize = destinationSize;
_pConvertContext = ffmpeg.sws_getContext(sourceSize.Width, sourceSize.Height, sourcePixelFormat,
destinationSize.Width,
destinationSize.Height, destinationPixelFormat,
ffmpeg.SWS_FAST_BILINEAR, null, null, null);
if (_pConvertContext == null) throw new ApplicationException("Could not initialize the conversion context.");
var convertedFrameBufferSize = ffmpeg.av_image_get_buffer_size(destinationPixelFormat,
destinationSize.Width, destinationSize.Height, 1);
_convertedFrameBufferPtr = Marshal.AllocHGlobal(convertedFrameBufferSize);
_dstData = new byte_ptrArray4();
_dstLinesize = new int_array4();
ffmpeg.av_image_fill_arrays(ref _dstData, ref _dstLinesize, (byte*)_convertedFrameBufferPtr,
destinationPixelFormat, destinationSize.Width, destinationSize.Height, 1);
}
public void Dispose()
{
Marshal.FreeHGlobal(_convertedFrameBufferPtr);
ffmpeg.sws_freeContext(_pConvertContext);
}
public AVFrame Convert(AVFrame sourceFrame)
{
ffmpeg.sws_scale(_pConvertContext, sourceFrame.data, sourceFrame.linesize, 0,
sourceFrame.height, _dstData, _dstLinesize);
var data = new byte_ptrArray8();
data.UpdateFrom(_dstData);
var linesize = new int_array8();
linesize.UpdateFrom(_dstLinesize);
return new AVFrame
{
data = data,
linesize = linesize,
width = _destinationSize.Width,
height = _destinationSize.Height
};
}
}
public enum AVPixDescFlag
{
///
// Pixel format is big-endian.
///
AV_PIX_FMT_FLAG_BE = 1 << 0,
///
// Pixel format has a palette in data[1], values are indexes in this palette.
///
AV_PIX_FMT_FLAG_PAL = 1 << 1,
/**
* All values of a component are bit-wise packed end to end.
*/
AV_PIX_FMT_FLAG_BITSTREAM= 1 << 2,
///
// Pixel format is an HW accelerated format.
///
AV_PIX_FMT_FLAG_HWACCEL = 1 << 3,
///
// At least one pixel component is not in the first data plane.
///
AV_PIX_FMT_FLAG_PLANAR = 1 << 4,
///
// The pixel format contains RGB-like data (as opposed to YUV/grayscale).
///
AV_PIX_FMT_FLAG_RGB = 1 << 5,
///
// The pixel format has an alpha channel. This is set on all formats that
// support alpha in some way, including AV_PIX_FMT_PAL8. The alpha is always
// straight, never pre-multiplied.
//
// If a codec or a filter does not support alpha, it should set all alpha to
// opaque, or use the equivalent pixel formats without alpha component, e.g.
// AV_PIX_FMT_RGB0 (or AV_PIX_FMT_RGB24 etc.) instead of AV_PIX_FMT_RGBA.
///
AV_PIX_FMT_FLAG_ALPHA = 1 << 7,
///
// The pixel format is following a Bayer pattern
///
AV_PIX_FMT_FLAG_BAYER = 1 << 8,
///
// The pixel format contains IEEE-754 floating point values. Precision (double,
// single, or half) should be determined by the pixel size (64, 32, or 16 bits).
///
AV_PIX_FMT_FLAG_FLOAT = 1 << 9
}
/// <summary>
/// Type of memory for QSV Decoder
/// From Intel Media SDK
/// </summary>
public enum MFX_MEMTYPE
{
MFX_MEMTYPE_DXVA2_DECODER_TARGET = 0x0010,
MFX_MEMTYPE_DXVA2_PROCESSOR_TARGET = 0x0020,
MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET = MFX_MEMTYPE_DXVA2_DECODER_TARGET,
MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET = MFX_MEMTYPE_DXVA2_PROCESSOR_TARGET,
MFX_MEMTYPE_SYSTEM_MEMORY = 0x0040,
MFX_MEMTYPE_RESERVED1 = 0x0080,
MFX_MEMTYPE_FROM_ENCODE = 0x0100,
MFX_MEMTYPE_FROM_DECODE = 0x0200,
MFX_MEMTYPE_FROM_VPPIN = 0x0400,
MFX_MEMTYPE_FROM_VPPOUT = 0x0800,
MFX_MEMTYPE_FROM_ENC = 0x2000,
MFX_MEMTYPE_FROM_PAK = 0x4000, //reserved
MFX_MEMTYPE_INTERNAL_FRAME = 0x0001,
MFX_MEMTYPE_EXTERNAL_FRAME = 0x0002,
MFX_MEMTYPE_OPAQUE_FRAME = 0x0004,
MFX_MEMTYPE_EXPORT_FRAME = 0x0008,
MFX_MEMTYPE_SHARED_RESOURCE = MFX_MEMTYPE_EXPORT_FRAME,
MFX_MEMTYPE_VIDEO_MEMORY_ENCODER_TARGET = 0x1000,
MFX_MEMTYPE_RESERVED2 = 0x1000
}
/// <summary>
/// Расширяющие методы необходимые для работы библиотек
/// </summary>
internal static class FFmpegHelper
{
public static int FFALIGN(this int x, int a)
{
return (((x) + (a) - 1) & ~((a) - 1));
}
/// <summary>
/// Copy bytes
/// </summary>
/// <param name="dest">From</param>
/// <param name="src">To</param>
/// <param name="count">Size</param>
[DllImport("msvcrt.dll", SetLastError = false)]
public static extern IntPtr memcpy(IntPtr dest, IntPtr src, int count);
public static unsafe string av_strerror(int error)
{
var bufferSize = 1024;
var buffer = stackalloc byte[bufferSize];
ffmpeg.av_strerror(error, buffer, (ulong)bufferSize);
var message = Marshal.PtrToStringAnsi((IntPtr)buffer);
return message;
}
public static int ThrowExceptionIfError(this int error)
{
if (error < 0) throw new ApplicationException(av_strerror(error));
return error;
}
}
|
using System;
namespace Nmli.Acml
{
class Lapack : ILapack
{
#region Double
public int potrf(UpLo uplo, int n, double[] a, int lda)
{
int info = 0;
byte b = Utilities.EnumAsAscii(uplo);
Externs.DPOTRF(ref b, ref n, a, ref lda, ref info);
return info;
}
public int potri(UpLo uplo, int n, double[] a, int lda)
{
int info = 0;
byte b = Utilities.EnumAsAscii(uplo);
Externs.DPOTRI(ref b, ref n, a, ref lda, ref info);
return info;
}
public int posv(UpLo uplo, int n, int nrhs, double[] a, int lda, double[] b, int ldb)
{
int info = 0;
byte u = Utilities.EnumAsAscii(uplo);
Externs.DPOSV(ref u, ref n, ref nrhs, a, ref lda, b, ref ldb, ref info);
return info;
}
public int getrf(int m, int n, double[] a, int lda, ref int[] ipiv)
{
int info = 0;
Externs.DGETRF(ref m, ref n, a, ref lda, ipiv, ref info);
return info;
}
public int getri(int n, double[] a, int lda, int[] ipiv, ref double[] work, int lwork)
{
int info = 0;
Externs.DGETRI(ref n, a, ref lda, ipiv, work, ref lwork, ref info);
return info;
}
public int gels(Transpose trans, int m, int n, int nrhs, double[] a, int lda, double[] b, int ldb, double[] work, int lwork)
{
int info = 0;
byte t = Utilities.EnumAsAscii(trans);
Externs.DGELS(ref t, ref m, ref n, ref nrhs, a, ref lda, b, ref ldb, work, ref lwork, ref info);
return info;
}
#endregion
#region Single
public int posv(UpLo uplo, int n, int nrhs, float[] a, int lda, float[] b, int ldb)
{
int info = 0;
byte u = Utilities.EnumAsAscii(uplo);
Externs.SPOSV(ref u, ref n, ref nrhs, a, ref lda, b, ref ldb, ref info);
return info;
}
public int potrf(UpLo uplo, int n, float[] a, int lda)
{
int info = 0;
byte b = Utilities.EnumAsAscii(uplo);
Externs.SPOTRF(ref b, ref n, a, ref lda, ref info);
return info;
}
public int potri(UpLo uplo, int n, float[] a, int lda)
{
int info = 0;
byte b = Utilities.EnumAsAscii(uplo);
Externs.SPOTRI(ref b, ref n, a, ref lda, ref info);
return info;
}
public int getrf(int m, int n, float[] a, int lda, ref int[] ipiv)
{
int info = 0;
Externs.SGETRF(ref m, ref n, a, ref lda, ipiv, ref info);
return info;
}
public int getri(int n, float[] a, int lda, int[] ipiv, ref float[] work, int lwork)
{
int info = 0;
Externs.SGETRI(ref n, a, ref lda, ipiv, work, ref lwork, ref info);
return info;
}
public int gels(Transpose trans, int m, int n, int nrhs, float[] a, int lda, float[] b, int ldb, float[] work, int lwork)
{
int info = 0;
byte t = Utilities.EnumAsAscii(trans);
Externs.SGELS(ref t, ref m, ref n, ref nrhs, a, ref lda, b, ref ldb, work, ref lwork, ref info);
return info;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace HoraireBeta
{
public class Ressource
{
protected String nom;
protected int id;
public Ressource()
{
}
public Ressource(int id)
{
setId(id);
}
public void setId(int id)
{
this.id = id;
}
public int getId()
{
return id;
}
public List<Poste> getPoste()
{
return (new List<Poste>());
}
public string getNom()
{
return nom;
}
public List<Bloc> getPref()
{
return (new List<Bloc>());
}
public List<Bloc> getDispo()
{
return (new List<Bloc>());
}
public void draw(Bloc bloc, int i, Graphics gfx)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DesignPatterns
{
/*
* Separate the construction of a complex object from its representation so that the
* same construction process (Director) can create different representations (Builders).
*
*
*/
/// <summary>
/// Same construction process
/// </summary>
public class CommandDirector
{
public void Construct(IBuilder b)
{
b.SetId();
}
}
public interface IBuilder
{
void SetId();
Command GetCommand();
}
/// <summary>
/// Representation 1 of the same product
/// </summary>
public class LoadIntegrationCommandBuilder : IBuilder
{
Command p = new Command();
public void SetId()
{
p.SetId(CommandId.LoadIntegration);
}
public Command GetCommand()
{
return p;
}
}
/// <summary>
/// Representation 2 of the same product
/// </summary>
public class ManualIntegrationCommandBuilder : IBuilder
{
Command p = new Command();
public void SetId()
{
p.SetId(CommandId.ManualIntegration);
}
public Command GetCommand()
{
return p;
}
}
public class Command
{
public CommandId Id;
public void SetId(CommandId id)
{
Id = id;
}
public void Display()
{
Console.WriteLine("\nFeature list ...");
Console.WriteLine($"Command id: {Id}");
Console.WriteLine();
}
}
public class Client
{
public static void Main()
{
// Create one director means same construction process
CommandDirector director = new CommandDirector();
//Create builders means same product but different representations
IBuilder b1 = new LoadIntegrationCommandBuilder();
IBuilder b2 = new ManualIntegrationCommandBuilder();
// Construct two products
director.Construct(b1);
//representation 1
Command p1 = b1.GetCommand();
p1.Display();
director.Construct(b2);
//representation 2
Command p2 = b2.GetCommand();
p2.Display();
Console.Read();
}
}
public enum CommandId { LoadIntegration, ManualIntegration }
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace AntColony
{
public class AntHarvesting : AntState
{
// Targeted food node
private Food foodSource;
// Food portion that is being carried
private Food carried;
public AntHarvesting(Ant ant, Food foodSource)
: base(ant)
{
this.foodSource = foodSource;
carried = null;
}
public override void Initialize()
{
base.Initialize();
// Assume already at food
carried = foodSource.Split(ant.Capacity);
ant.Carry(carried.gameObject);
// Produce pheromone trail so that other ants can find food
ant.ProducePheromones();
// Return to colony with captured food
SetDestination(colony.transform.position);
}
public override void DestinationReached()
{
base.DestinationReached();
// Deposit food at colony
colony.Add(carried);
// Stop producing pheromones
ant.StopProducingPheromones();
// Switch to following state
ant.SetState(new AntFollowing(ant));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace HTTP_FINAL_PROJECT
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PLANETSDB db = new PLANETSDB();
ShowPlanetInfo(db);
}
}
// THIS IS THE FUNCTION TO UPDATE THE PLANET WITH THEIR DETAILS
protected void Update_Planet(object sender, EventArgs e)
{
PLANETSDB db = new PLANETSDB();
bool valid = true;
string planetid = Request.QueryString["planets_id"];
if (String.IsNullOrEmpty(planetid)) valid = false;
if (valid)
{
planet new_planet = new planet();
new_planet.SetPtitle(planets_title.Text);
new_planet.SetPbody(planets_body.Text);
try
{
db.Updateplanet(Int32.Parse(planetid), new_planet);
Response.Redirect("planetpages.aspx?planetid=" + planetid);
}
catch
{
valid = false;
}
}
if (!valid)
{
planet.InnerHtml = "There was an error updating that planet.";
}
}
// THIS IS TO SHOW THE DETAILS IN THE TEXTBOXES
protected void ShowPlanetInfo(PLANETSDB db)
{
bool valid = true;
string planet_id = Request.QueryString["planets_id"];
if (String.IsNullOrEmpty(planet_id)) valid = false;
if (valid)
{
planet planet_record = db.Findplanet(Int32.Parse(planet_id));
planets_title.Text = planet_record.GetPtitle();
planets_body.Text = planet_record.GetPbody();
}
if (!valid)
{
planet.InnerHtml = "There was an error finding that planet.";
}
}
}
} |
namespace SRDebugger.Profiler
{
using System.Diagnostics;
using Services;
using SRF;
using SRF.Service;
using UnityEngine;
[Service(typeof (IProfilerService))]
public class ProfilerServiceImpl : SRServiceBase<IProfilerService>, IProfilerService
{
private const int FrameBufferSize = 400;
private readonly SRList<ProfilerCameraListener> _cameraListeners = new SRList<ProfilerCameraListener>();
private readonly CircularBuffer<ProfilerFrame> _frameBuffer = new CircularBuffer<ProfilerFrame>(FrameBufferSize);
private Camera[] _cameraCache = new Camera[6];
//private double _lateUpdateDuration;
private ProfilerLateUpdateListener _lateUpdateListener;
private double _renderDuration;
private int _reportedCameras;
private Stopwatch _stopwatch = new Stopwatch();
private double _updateDuration;
private double _updateToRenderDuration;
public float AverageFrameTime { get; private set; }
public float LastFrameTime { get; private set; }
public CircularBuffer<ProfilerFrame> FrameBuffer
{
get { return _frameBuffer; }
}
protected void PushFrame(double totalTime, double updateTime, double renderTime)
{
//UnityEngine.Debug.Log("Frame: u: {0} r: {1}".Fmt(updateTime, renderTime));
_frameBuffer.PushBack(new ProfilerFrame
{
OtherTime = totalTime - updateTime - renderTime,
UpdateTime = updateTime,
RenderTime = renderTime
});
}
protected override void Awake()
{
base.Awake();
_lateUpdateListener = gameObject.AddComponent<ProfilerLateUpdateListener>();
_lateUpdateListener.OnLateUpdate = OnLateUpdate;
CachedGameObject.hideFlags = HideFlags.NotEditable;
CachedTransform.SetParent(Hierarchy.Get("SRDebugger"), true);
//StartCoroutine(EndFrameCoroutine());
}
protected override void Update()
{
base.Update();
// Set the frame time for the last frame
if (FrameBuffer.Count > 0)
{
var frame = FrameBuffer.Back();
frame.FrameTime = Time.deltaTime;
FrameBuffer[FrameBuffer.Count - 1] = frame;
}
LastFrameTime = Time.deltaTime;
var frameCount = Mathf.Min(20, FrameBuffer.Count);
var f = 0d;
for (var i = 0; i < frameCount; i++)
{
f += FrameBuffer[i].FrameTime;
}
AverageFrameTime = (float) f/frameCount;
// Detect frame skip
if (_reportedCameras != _cameraListeners.Count)
{
//Debug.LogWarning("[SRDebugger] Some cameras didn't report render time last frame");
}
if (_stopwatch.IsRunning)
{
//PushFrame(_stopwatch.Elapsed.TotalSeconds, _updateDuration, _renderDuration);
_stopwatch.Stop();
_stopwatch.Reset();
}
_updateDuration = _renderDuration = _updateToRenderDuration = 0;
_reportedCameras = 0;
CameraCheck();
_stopwatch.Start();
}
private void OnLateUpdate()
{
_updateDuration = _stopwatch.Elapsed.TotalSeconds;
}
/*private IEnumerator EndFrameCoroutine()
{
var endFrame = new WaitForEndOfFrame();
while (true) {
yield return endFrame;
EndFrame();
}
}*/
private void EndFrame()
{
if (_stopwatch.IsRunning)
{
PushFrame(_stopwatch.Elapsed.TotalSeconds, _updateDuration, _renderDuration);
_stopwatch.Reset();
_stopwatch.Start();
}
}
private void CameraDurationCallback(ProfilerCameraListener listener, double duration)
{
/*// Time to first camera
if (_reportedCameras == 0) {
_updateToRenderDuration = _stopwatch.Elapsed.TotalSeconds - duration - _updateDuration;
}*/
//_renderDuration += duration;
_reportedCameras++;
_renderDuration = _stopwatch.Elapsed.TotalSeconds - _updateDuration - _updateToRenderDuration;
if (_reportedCameras >= GetExpectedCameraCount())
{
EndFrame();
}
}
private int GetExpectedCameraCount()
{
var expectedCameraCount
= 0;
for (var i = 0; i < _cameraListeners.Count; i++)
{
if (!_cameraListeners[i].isActiveAndEnabled || !_cameraListeners[i].Camera.isActiveAndEnabled)
{
continue;
}
expectedCameraCount++;
}
return expectedCameraCount;
}
private void CameraCheck()
{
// Check for cameras which have been destroyed
for (var i = _cameraListeners.Count - 1; i >= 0; i--)
{
if (_cameraListeners[i] == null)
{
_cameraListeners.RemoveAt(i);
}
}
// If camera count has not changed, return
if (Camera.allCamerasCount == _cameraListeners.Count)
{
return;
}
// If cache is not large enough to contain current camera count, resize
if (Camera.allCamerasCount > _cameraCache.Length)
{
_cameraCache = new Camera[Camera.allCamerasCount];
}
var cameraCount = Camera.GetAllCameras(_cameraCache);
// Iterate all camera objects and create camera listener for those without
for (var i = 0; i < cameraCount; i++)
{
var c = _cameraCache[i];
var found = false;
for (var j = 0; j < _cameraListeners.Count; j++)
{
if (_cameraListeners[j].Camera == c)
{
found = true;
break;
}
}
if (found)
{
continue;
}
//Debug.Log("[SRDebugger] Found New Camera: {0}".Fmt(c.name));
var listener = c.gameObject.AddComponent<ProfilerCameraListener>();
listener.hideFlags = HideFlags.NotEditable | HideFlags.DontSave;
listener.RenderDurationCallback = CameraDurationCallback;
_cameraListeners.Add(listener);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DriveMgr.IDAL
{
public interface IGoodsDAL
{
/// <summary>
/// 是否存在该记录
/// </summary>
bool IsExistGoods(string categoryName);
/// <summary>
/// 增加一条数据
/// </summary>
bool AddGoods(Model.GoodsModel model);
/// <summary>
/// 更新一条数据
/// </summary>
bool UpdateGoods(Model.GoodsModel model);
/// <summary>
/// 删除一条数据
/// </summary>
bool DeleteGoods(int id);
/// <summary>
/// 批量删除数据
/// </summary>
bool DeleteGoodsList(string idlist);
/// <summary>
/// 得到一个对象实体
/// </summary>
Model.GoodsModel GetGoodsModel(int id);
/// <summary>
/// 获取分页数据
/// </summary>
/// <param name="tableName">表名</param>
/// <param name="columns">要取的列名(逗号分开)</param>
/// <param name="order">排序</param>
/// <param name="pageSize">每页大小</param>
/// <param name="pageIndex">当前页</param>
/// <param name="where">查询条件</param>
/// <param name="totalCount">总记录数</param>
string GetPagerData(string tableName, string columns, string order, int pageSize, int pageIndex, string where, out int totalCount);
/// <summary>
/// 获取物资类别集合
/// </summary>
/// <returns></returns>
string GetGoodsDT();
}
}
|
/*
* Bungie.Net API
*
* These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality.
*
* OpenAPI spec version: 2.1.1
* Contact: support@bungie.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = BungieNetPlatform.Client.SwaggerDateConverter;
namespace BungieNetPlatform.Model
{
/// <summary>
/// The results of a search for Destiny content. This will be improved on over time, I've been doing some experimenting to see what might be useful.
/// </summary>
[DataContract]
public partial class DestinyDefinitionsDestinyEntitySearchResult : IEquatable<DestinyDefinitionsDestinyEntitySearchResult>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="DestinyDefinitionsDestinyEntitySearchResult" /> class.
/// </summary>
/// <param name="SuggestedWords">A list of suggested words that might make for better search results, based on the text searched for..</param>
/// <param name="Results">The items found that are matches/near matches for the searched-for term, sorted by something vaguely resembling \"relevance\". Hopefully this will get better in the future..</param>
public DestinyDefinitionsDestinyEntitySearchResult(List<string> SuggestedWords = default(List<string>), SearchResultOfDestinyEntitySearchResultItem Results = default(SearchResultOfDestinyEntitySearchResultItem))
{
this.SuggestedWords = SuggestedWords;
this.Results = Results;
}
/// <summary>
/// A list of suggested words that might make for better search results, based on the text searched for.
/// </summary>
/// <value>A list of suggested words that might make for better search results, based on the text searched for.</value>
[DataMember(Name="suggestedWords", EmitDefaultValue=false)]
public List<string> SuggestedWords { get; set; }
/// <summary>
/// The items found that are matches/near matches for the searched-for term, sorted by something vaguely resembling \"relevance\". Hopefully this will get better in the future.
/// </summary>
/// <value>The items found that are matches/near matches for the searched-for term, sorted by something vaguely resembling \"relevance\". Hopefully this will get better in the future.</value>
[DataMember(Name="results", EmitDefaultValue=false)]
public SearchResultOfDestinyEntitySearchResultItem Results { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class DestinyDefinitionsDestinyEntitySearchResult {\n");
sb.Append(" SuggestedWords: ").Append(SuggestedWords).Append("\n");
sb.Append(" Results: ").Append(Results).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as DestinyDefinitionsDestinyEntitySearchResult);
}
/// <summary>
/// Returns true if DestinyDefinitionsDestinyEntitySearchResult instances are equal
/// </summary>
/// <param name="input">Instance of DestinyDefinitionsDestinyEntitySearchResult to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(DestinyDefinitionsDestinyEntitySearchResult input)
{
if (input == null)
return false;
return
(
this.SuggestedWords == input.SuggestedWords ||
this.SuggestedWords != null &&
this.SuggestedWords.SequenceEqual(input.SuggestedWords)
) &&
(
this.Results == input.Results ||
(this.Results != null &&
this.Results.Equals(input.Results))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.SuggestedWords != null)
hashCode = hashCode * 59 + this.SuggestedWords.GetHashCode();
if (this.Results != null)
hashCode = hashCode * 59 + this.Results.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
|
using Application.Command;
using Application.Commands;
using Application.DTO;
using Application.Exceptions;
using Domain;
using EFCommands;
using EFDataAccess;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EfCommands
{
public class EfAddRoleCommand : EfBaseCommand, IAddRoleCommand
{
public EfAddRoleCommand(BlogContext context) : base(context)
{
}
public void Execute(AddRoleDto request)
{
if (Context.Roles.Any(r => r.Name == request.Name))
throw new EntityAllreadyExits("Vec postoji, begaj");
Context.Roles.Add(new Role
{
Name = request.Name
});
Context.SaveChanges();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovingPlatform : MonoBehaviour
{
[SerializeField] private Transform _targetA, _targetB;
[SerializeField] private float _speed = 2.0f;
// create a var to tell switch from tarA to tarB
[SerializeField] private bool _isSwitch;
void FixedUpdate()
{
/**
* curr tform val; transform.position = Vector3.Movetowards(curr pos, target, max dist delta aka speed)
* go to point b
* if at point b
* go to point a
* if at point a
* go to point b
* */
if (_isSwitch == false)
{
// move to tarB
transform.position = Vector3.MoveTowards(transform.position, _targetB.position, _speed * Time.deltaTime);
}
else if (_isSwitch == true)
{
transform.position = Vector3.MoveTowards(transform.position, _targetA.position, _speed * Time.deltaTime);
}
// when turn _isSwitch from true to false
if (transform.position == _targetB.position)
{
_isSwitch = true;
}
else if (transform.position == _targetA.position)
{
_isSwitch = false;
}
}
/**
* create collision detection
* if we collide with player
* tk player parent and assign it to this GO
*
* exit collision
* chk if player exited
* tk player parent = null and assign to null so it's free to move off platform
**/
/// <summary>
/// OnTriggerEnter is called when the Collider other enters the trigger.
/// </summary>
/// <param name="other">The other Collider involved in this collision.</param>
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
// tell player has new tform and it's this obj
// assign the parent to the tform this script attached to aka moving platform
other.transform.parent = this.transform;
}
}
/// <summary>
/// OnTriggerExit is called when the Collider other has stopped touching the trigger.
/// </summary>
/// <param name="other">The other Collider involved in this collision.</param>
void OnTriggerExit(Collider other)
{
if (other.tag == "Player")
{
other.transform.parent = null;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PauseScript : MonoBehaviour
{
bool isPaused = false;
public GameObject menuPause;
public Text objectifs;
public static int amisRestants = 3;
public GameObject miniMap;
public void SetObjectifText()
{
objectifs.text = "Il reste " + amisRestants + " amis à libérer...";
}
void Update()
{
if(Input.GetKeyDown(KeyCode.Escape))
{
// TODO: Ajouter un son de pause
if(isPaused)
{
isPaused = false;
menuPause.SetActive(isPaused);
Time.timeScale = 1f;
}
else
{
SetObjectifText();
isPaused = true;
menuPause.SetActive(isPaused);
Time.timeScale = 0f;
}
}
if(Input.GetKeyUp(KeyCode.M))
{
miniMap.active = !miniMap.active;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Riverside.Cms.Services.Reviews.Domain
{
public interface IReviewRepository
{
Task UpdateReviews(long tenantId, IEnumerable<Review> reviews);
Task<IEnumerable<TenantPlace>> ListTenantPlaces();
}
}
|
using System;
using System.Collections.Generic;
namespace Algorithms
{
//check if a expressison is well formed
//IE //[(ABC {DEF}[XYZ (LMN)] is false
public class WellFormedExpression
{
Dictionary<string,string> openingBrackets = new Dictionary<string,string>
{
{
"(",
")"
},
{
"[",
"]"
},
{
"{",
"}"
},
};
Dictionary<string,string> closingBrackets = new Dictionary<string,string>
{
{
")",
"("
},
{
"]",
"["
},
{
"}",
"{"
},
};
public bool isWellFormedExpression(string expr)
{
Stack<string> stack = new Stack<string>();
foreach (var item in expr)
{
if (openingBrackets.ContainsKey(item.ToString()))
stack.Push(item.ToString());
else if (closingBrackets.ContainsKey(item.ToString()))
{
string prevBracket = stack.Pop();
if (closingBrackets [item.ToString()] == prevBracket)
continue;
else
return false;
}
}
return stack.Count == 0;
}
}
}
|
using System;
namespace Repository
{
public class Transaction
{
public DateTimeOffset Date { get; set; }
public string MerchantName { get; set; }
public decimal Amount { get; set; }
public decimal TransactionPercentageFeeAmount { get; set; }
public decimal InvoiceFixedFeeAmount { get; set; }
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.