text stringlengths 13 6.01M |
|---|
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShapeUpp.Domain.Models;
using System;
namespace ShapeUpp.Infrastructure.EntityConfigurations
{
public class ExerciseEntityConfiguration : IEntityTypeConfiguration<Exercise>
{
public void Configure(EntityTypeBuilder<Exercise> builder)
{
builder.ToTable("Exercises");
builder.HasOne(x => x.Category).WithMany(x => x.Exercises).HasForeignKey(x => x.CategoryId);
builder.HasMany(x => x.MuscleGroups).WithMany(x => x.Exercises).UsingEntity(x => x.ToTable("ExerciseMuscles"));
builder.HasMany(x => x.Equipment).WithMany(x => x.Exercises).UsingEntity(x => x.ToTable("ExerciseEquipment"));
builder.Property<DateTimeOffset>("Created").HasDefaultValueSql("GETDATE()");
}
}
}
|
using System;
using System.Runtime.Serialization;
namespace Xero.Api.Core.Model
{
[Serializable]
[DataContract(Namespace = "")]
public sealed class SalesDetails : ItemDetails
{
}
} |
using EnduroCalculator;
using EnduroLibrary;
namespace EnduroCalculator
{
public abstract class TrackCalculator : ITrackCalculator
{
public virtual void Calculate(TrackPoint nextPoint)
{
if (CurrentPoint is null)
{
CurrentPoint = nextPoint;
return;
}
CurrentDirection = DirectionCalculation.CalculateDirectionWithSlope(CurrentPoint, nextPoint, Slope);
}
protected TrackPoint CurrentPoint { get; set; }
public virtual AltitudeDirection CurrentDirection { get; set; }
public virtual double Slope { get; set; }
public virtual double TimeFilter { get; set; }
public abstract void PrintResult();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
namespace XH.APIs.WebAPI.Models.Catalogs
{
[DataContract]
public class UpdateRegionRequest: CreateOrUpdateRegionRequest
{
}
} |
using UnityEngine;
using UnityAtoms.BaseAtoms;
using UnityAtoms.MonoHooks;
namespace UnityAtoms.MonoHooks
{
/// <summary>
/// Variable Instancer of type `ColliderGameObject`. Inherits from `AtomVariableInstancer<ColliderGameObjectVariable, ColliderGameObjectPair, ColliderGameObject, ColliderGameObjectEvent, ColliderGameObjectPairEvent, ColliderGameObjectColliderGameObjectFunction>`.
/// </summary>
[EditorIcon("atom-icon-hotpink")]
[AddComponentMenu("Unity Atoms/Variable Instancers/ColliderGameObject Variable Instancer")]
public class ColliderGameObjectVariableInstancer : AtomVariableInstancer<
ColliderGameObjectVariable,
ColliderGameObjectPair,
ColliderGameObject,
ColliderGameObjectEvent,
ColliderGameObjectPairEvent,
ColliderGameObjectColliderGameObjectFunction>
{ }
}
|
using System.Threading.Tasks;
using AutoMapper;
using DataAccess.Users;
using DB;
using Entities;
using Microsoft.AspNetCore.Identity;
using ViewModel.Users;
namespace DataAccess.DbImplementation.Users
{
public class CreateUserCommand : ICreateUserCommand
{
private readonly UserManager<User> _userManager;
private readonly SignInManager<User> _signInManager;
private readonly IMapper _mapper;
private readonly AppDbContext _context;
public CreateUserCommand(
UserManager<User> userManager,
SignInManager<User> signInManager,
IMapper mapper, AppDbContext context)
{
_userManager = userManager;
_signInManager = signInManager;
_mapper = mapper;
_context = context;
}
public async Task<UserResponse> ExecuteAsync(CreateUserRequest request)
{
User user = new User
{
Email = request.Email,
UserName = request.Email,
};
// добавляем пользователя
var result = await _userManager.CreateAsync(user, request.Password);
// установка куки
if (!result.Succeeded)
throw new CannotCreateUserExeption(result.Errors);
await _signInManager.SignInAsync(user, false);
await _userManager.AddToRoleAsync(user, "user");
return _mapper.Map<User, UserResponse>(user);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
namespace Anywhere2Go.DataAccess.AccountEntity
{
public class eRolePermission
{
public int permissionId { get; set; }
public int roleId { get; set; }
public bool? userView { get; set; }
public bool? userAdd { get; set; }
public bool? userEdit { get; set; }
public bool? userDelete { get; set; }
public bool? blogView { get; set; }
public bool? blogAdd { get; set; }
public bool? blogEdit { get; set; }
public bool? blogDelete { get; set; }
public DateTime? createDate { get; set; }
public DateTime? updateDate { get; set; }
public string createBy { get; set; }
public string updateBy { get; set; }
public virtual ePermission Permission { get; set; }
}
public class RolePermissionConfig : EntityTypeConfiguration<eRolePermission>
{
public RolePermissionConfig()
{
// Table & Column Mappings
ToTable("eRolePermission");
Property(t => t.permissionId).HasColumnName("permission_id");
Property(t => t.roleId).HasColumnName("role_id");
Property(t => t.userView).HasColumnName("user_view");
Property(t => t.userAdd).HasColumnName("user_add");
Property(t => t.userEdit).HasColumnName("user_edit");
Property(t => t.userDelete).HasColumnName("user_delete");
Property(t => t.blogView).HasColumnName("blog_view");
Property(t => t.blogAdd).HasColumnName("blog_add");
Property(t => t.blogEdit).HasColumnName("blog_edit");
Property(t => t.blogDelete).HasColumnName("blog_delete");
Property(t => t.createDate).HasColumnName("create_date");
Property(t => t.updateDate).HasColumnName("update_date");
Property(t => t.createBy).HasColumnName("create_by");
Property(t => t.updateBy).HasColumnName("update_by");
// Primary Key
HasKey(t => new { t.permissionId, t.roleId });
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cards;
namespace Blackjack
{
public class BlackjackHand : Hand
{
#region Properties
public override int Value => ComputeValue();
public int NumAces => cards.Where(c => c.IsAce).Count();
public bool HasAce => NumAces > 0;
public bool IsSoft => HasAce && CheckSoft();
public bool IsPair => (Count == 2) && (this[0].Rank == this[1].Rank);
public bool IsBust => Value > 21;
public bool IsBlackjack => Value == 21;
public bool IsNaturalBlackjack => (Count == 2) && !IsSplit && IsBlackjack;
public bool IsSplit { get; internal set; } = false;
#endregion
public event EventHandler<HoleCardRevealedEventArgs> HoleCardRevealed;
public BlackjackHand() { }
public BlackjackHand(Card first, Card second)
{
Add(first);
Add(second);
}
public void RevealHoleCard()
{
HoleCardRevealed?.Invoke(this, new HoleCardRevealedEventArgs(this[0]));
}
private int ComputeValue()
{
int value = cards.Where(c => !c.IsAce).Select(c => CardValue(c)).Sum();
if (NumAces > 0)
{
value += (NumAces - 1) * 1;
if (value + 11 <= 21)
{
value += 11;
}
else
{
value += 1;
}
}
return value;
}
internal static int CardValue(Card card)
{
if (card.IsAce)
{
return 11;
}
if (card.IsFace)
{
return 10;
}
return 2 + (int)card.Rank;
}
private bool CheckSoft()
{
int value = cards.Where(c => !c.IsAce).Select(c => CardValue(c)).Sum();
if (NumAces > 0)
{
value += (NumAces - 1) * 1;
if (value + 11 <= 21)
{
return true;
}
}
return false;
}
}
public class HoleCardRevealedEventArgs : EventArgs
{
public Card HoleCard { get; }
public HoleCardRevealedEventArgs(Card holeCard)
{
HoleCard = holeCard;
}
}
}
|
using System;
using System.IO;
using ELearning.BAL;
using ELearning.helper;
using ELearning.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
namespace ELearning.Controllers
{
[AppAuthorization("SuperAdmin")]
public class SuperAdminController : Controller
{
CourseBAL bal;
public SuperAdminController(IConfiguration config)
{
bal = new CourseBAL(config);
}
#region Content Management
public IActionResult Index()
{
AdminConfigurationViewModel objModel = bal.AdminConfigurationList();
return View(objModel);
}
public IActionResult Course()
{
return View(bal.GetCourseDetails());
}
[HttpPost]
public IActionResult Course(IFormCollection fc, IFormFile file)
{
if (string.IsNullOrEmpty(fc["cname"]) || string.IsNullOrEmpty(file.FileName))
{
ViewBag.error = "There is an issue saving data";
return View("Index", bal.GetCourseDetails());
}
bool result = bal.SaveCourse(fc["cname"], file.FileName);
if (result)
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "ServerImage", file.FileName);
using (var stream = new FileStream(path, FileMode.Create))
{
file.CopyTo(stream);
}
ViewBag.success = "Successfully Save";
}
else
{
ViewBag.failure = "There is an issue saving data";
}
return View("Course", bal.GetCourseDetails());
}
public IActionResult Module()
{
return View(bal.GetCourseDetails());
}
[HttpPost]
public IActionResult Module(IFormCollection fc, IFormFile file)
{
if (string.IsNullOrEmpty(fc["mname"]) || string.IsNullOrEmpty(fc["courseid"]))
{
ViewBag.error = "There is an issue saving data";
return View("Index", bal.GetCourseDetails());
}
string filename = string.Empty;
if (file != null && file.Length > 0)
{
filename = file.FileName;
}
bool result = bal.SaveModule(fc["mname"], Convert.ToInt32(fc["courseid"]), filename);
if (result)
{
if (file != null && file.Length > 0)
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "Documents", "ModuleFiles", file.FileName);
using (var stream = new FileStream(path, FileMode.Create))
{
file.CopyTo(stream);
}
}
ViewBag.success = "Successfully Save";
}
else
{
ViewBag.faulure = "There is an issue saving data";
}
return View(bal.GetCourseDetails());
}
public IActionResult Lesson()
{
return View(bal.GetCourseDetails());
}
[HttpPost]
public IActionResult Lesson(IFormCollection fc, IFormFile file)
{
if (string.IsNullOrEmpty(fc["lname"]) || string.IsNullOrEmpty(fc["moduleid"])
|| string.IsNullOrEmpty(fc["vname"]) || string.IsNullOrEmpty(fc["vlength"])
|| string.IsNullOrEmpty(file.FileName))
{
ViewBag.error = "There is an issue saving data";
return View("Index", bal.GetCourseDetails());
}
string filename = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
bool result = bal.SaveLesson(fc["lname"], Convert.ToInt32(fc["moduleid"]), filename, fc["vname"], fc["vlength"]);
if (result)
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "Documents", "Videos", filename);
using (var stream = new FileStream(path, FileMode.Create))
{
file.CopyTo(stream);
}
ViewBag.success = "Successfully Save";
}
else
{
ViewBag.faulure = "There is an issue saving data";
}
return View(bal.GetCourseDetails());
}
public IActionResult Test()
{
return View(bal.GetCourseDetails());
}
[HttpPost]
public IActionResult Test(IFormCollection fc, IFormFile file)
{
if (string.IsNullOrEmpty(fc["moduleid"])
|| string.IsNullOrEmpty(fc["answer"]))
{
ViewBag.error = "There is an issue saving data";
return View("Test", bal.GetCourseDetails());
}
TestModel objModel = new TestModel();
objModel.OptionA = Convert.ToString(fc["optiona"]);
objModel.OptionB = Convert.ToString(fc["optionb"]);
objModel.OptionC = Convert.ToString(fc["optionc"]);
objModel.OptionD = Convert.ToString(fc["optiond"]);
objModel.Answer = Convert.ToString(fc["answer"]);
objModel.Module = new ModuleModel { ModuleId = Convert.ToInt32(fc["moduleid"]) };
if (file != null && file.Length > 0)
{
using (MemoryStream ms = new MemoryStream())
{
file.OpenReadStream().CopyTo(ms);
objModel.Image = ms.ToArray();
}
}
objModel.Question = Convert.ToString(fc["question"]);
bool result = bal.SaveTest(objModel);
if (result)
{
ViewBag.success = "Successfully save";
}
else
{
ViewBag.error = "There is an issue saving data";
}
return View("Test", bal.GetCourseDetails());
}
public IActionResult TestList()
{
return View(bal.GetTestList());
}
#endregion
#region Corporate
public IActionResult Institute()
{
return View(bal.GetCourseInstituteDetails());
}
[HttpPost]
public IActionResult Institute(IFormCollection fc)
{
InstituteModel objInsti = new InstituteModel();
Random random = new Random();
var password = random.Next(0, 1000000);
if (!string.IsNullOrEmpty(fc["iname"])) objInsti.Name = fc["iname"];
if (!string.IsNullOrEmpty(fc["year"]) && !string.IsNullOrEmpty(fc["month"]))
objInsti.Subcription = new SubcriptionModel
{
Year = Convert.ToInt16(fc["year"]),
Month = Convert.ToInt16(fc["month"])
};
if (!string.IsNullOrEmpty(fc["nname"])) objInsti.ActivationNumber = fc["nname"];
if (!string.IsNullOrEmpty(fc["uname"]) && !string.IsNullOrEmpty(fc["ename"]))
objInsti.User = new UserModel
{
Name = fc["uname"],
Email = fc["ename"],
Password = password.ToString().EncryptString()
};
bool result = bal.SaveInstitute(objInsti);
if (result)
{
ViewBag.success = "Successfully Saved ";
}
else
{
ViewBag.failure = "Error occured";
}
return View("Institute", bal.GetCourseInstituteDetails());
}
[HttpPost]
public IActionResult MapCourse(IFormCollection fc)
{
bool result = bal.MapCourse(Convert.ToInt32(fc["courseid"]), Convert.ToInt32(fc["instituteid"]));
if (result)
{
ViewBag.success = "Successfully mapped";
}
else
{
ViewBag.failure = "Error occured";
}
return View("Institute", bal.GetCourseDetails());
}
#endregion
public IActionResult AdminUser()
{
return View(bal.GetAdminUser());
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Malchikov6404Server
{
public class ReceivedFile
{
public string FileName { get; set; }
public string FileSize { get; set; }
public byte[] FileContent { get; set; } //раньше был string
}
}
|
// <copyright file="GetLinkTagFixture.cs" company="Morten Larsen">
// Copyright (c) Morten Larsen. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
// </copyright>
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.AspNetCore.Html;
using Moq;
namespace AspNetWebpack.AssetHelpers.Testing
{
/// <summary>
/// Fixture for testing GetLinkTagAsync function in AssetService.
/// </summary>
public class GetLinkTagFixture : AssetServiceBaseFixture
{
/// <summary>
/// Valid bundle name with extension.
/// </summary>
public static readonly string ValidBundleWithExtension = $"{ValidBundleWithoutExtension}.css";
/// <summary>
/// Valid fallback bundle name with extension.
/// </summary>
public static readonly string ValidFallbackBundleWithExtension = $"{ValidFallbackBundleWithoutExtension}.css";
private const string LinkTag = "<link href=\"Bundle.css\" />";
private const string FallbackLinkTag = "<link href=\"FallbackBundle.css\" />";
/// <summary>
/// Initializes a new instance of the <see cref="GetLinkTagFixture"/> class.
/// </summary>
/// <param name="bundle">The bundle name param to be used in GetLinkTagAsync.</param>
/// <param name="fallbackBundle">The fallback bundle name param to be used in GetLinkTagAsync.</param>
public GetLinkTagFixture(string bundle, string? fallbackBundle = null)
: base(ValidBundleWithExtension, ValidFallbackBundleWithExtension)
{
Bundle = bundle;
FallbackBundle = fallbackBundle;
SetupGetFromManifest();
SetupBuildLinkTag(ValidBundleResult, LinkTag);
SetupBuildLinkTag(ValidFallbackBundleResult, FallbackLinkTag);
}
private string Bundle { get; }
private string? FallbackBundle { get; }
/// <summary>
/// Calls GetLinkTagAsync with provided parameters.
/// </summary>
/// <returns>The result of the called function.</returns>
public async Task<HtmlString> GetLinkTagAsync()
{
return await AssetService
.GetLinkTagAsync(Bundle, FallbackBundle)
.ConfigureAwait(false);
}
/// <summary>
/// Verify that GetLinkTagAsync was called with an empty string.
/// </summary>
/// <param name="result">The result to assert.</param>
public void VerifyEmpty(HtmlString result)
{
result.Should().Be(HtmlString.Empty);
VerifyDependencies();
VerifyNoOtherCalls();
}
/// <summary>
/// Verify that GetLinkTagAsync was called with an invalid bundle.
/// </summary>
/// <param name="result">The result to assert.</param>
public void VerifyNonExisting(HtmlString result)
{
result.Should().Be(HtmlString.Empty);
VerifyDependencies();
VerifyGetFromManifest(Bundle, FallbackBundle, ".css");
VerifyNoOtherCalls();
}
/// <summary>
/// Verify that GetLinkTagAsync was called with a valid bundle.
/// </summary>
/// <param name="result">The result to assert.</param>
public void VerifyExisting(HtmlString result)
{
result.Should().BeEquivalentTo(new HtmlString(LinkTag));
VerifyDependencies();
VerifyGetFromManifest(Bundle, FallbackBundle, ".css");
VerifyBuildLinkTag(ValidBundleResult);
VerifyNoOtherCalls();
}
/// <summary>
/// Verify that GetLinkTagAsync was called with an empty string as fallback.
/// </summary>
/// <param name="result">The result to assert.</param>
public void VerifyFallbackEmpty(HtmlString result)
{
result.Should().Be(HtmlString.Empty);
VerifyDependencies();
VerifyGetFromManifest(Bundle, FallbackBundle, ".css");
VerifyNoOtherCalls();
}
/// <summary>
/// Verify that GetLinkTagAsync was called with an invalid bundle and an invalid fallback bundle.
/// </summary>
/// <param name="result">The result to assert.</param>
public void VerifyFallbackNonExisting(HtmlString result)
{
result.Should().Be(HtmlString.Empty);
VerifyDependencies();
VerifyGetFromManifest(Bundle, FallbackBundle, ".css");
VerifyNoOtherCalls();
}
/// <summary>
/// Verify that GetLinkTagAsync was called with an invalid bundle and a valid fallback bundle.
/// </summary>
/// <param name="result">The result to assert.</param>
public void VerifyFallbackExisting(HtmlString result)
{
result.Should().BeEquivalentTo(new HtmlString(FallbackLinkTag));
VerifyDependencies();
VerifyGetFromManifest(Bundle, FallbackBundle, ".css");
VerifyBuildLinkTag(ValidFallbackBundleResult);
VerifyNoOtherCalls();
}
private void SetupBuildLinkTag(string resultBundle, string returnValue)
{
TagBuilderMock
.Setup(x => x.BuildLinkTag(resultBundle))
.Returns(returnValue);
}
private void VerifyBuildLinkTag(string resultBundle)
{
TagBuilderMock.Verify(x => x.BuildLinkTag(resultBundle), Times.Once());
}
}
}
|
using FluentMigrator;
namespace Profiling2.Migrations.Migrations
{
[Migration(201307081542)]
public class AddSortToRoleRank : Migration
{
public override void Down()
{
Delete.Column("RankNameFr").FromTable("PRF_Rank");
Delete.Column("Description").FromTable("PRF_Rank");
Delete.Column("SortOrder").FromTable("PRF_Rank");
Delete.Column("RankNameFr").FromTable("PRF_Rank_AUD");
Delete.Column("Description").FromTable("PRF_Rank_AUD");
Delete.Column("SortOrder").FromTable("PRF_Rank_AUD");
Delete.Column("SortOrder").FromTable("PRF_Role");
Delete.Column("SortOrder").FromTable("PRF_Role_AUD");
}
public override void Up()
{
Alter.Table("PRF_Rank").AddColumn("RankNameFr").AsString().Nullable();
Alter.Table("PRF_Rank").AddColumn("Description").AsString(int.MaxValue).Nullable();
Alter.Table("PRF_Rank").AddColumn("SortOrder").AsInt32().Nullable();
Alter.Table("PRF_Rank_AUD").AddColumn("RankNameFr").AsString().Nullable();
Alter.Table("PRF_Rank_AUD").AddColumn("Description").AsString(int.MaxValue).Nullable();
Alter.Table("PRF_Rank_AUD").AddColumn("SortOrder").AsInt32().Nullable();
Alter.Table("PRF_Role").AddColumn("SortOrder").AsInt32().Nullable();
Alter.Table("PRF_Role_AUD").AddColumn("SortOrder").AsInt32().Nullable();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data;
using System.Collections;
using IRAP.Global;
using IRAPShared;
using IRAPORM;
using IRAP.Entities.SCES;
using IRAP.Entities.MES.Tables;
using IRAP.Entities.MDM.Tables;
using IRAP.Entities.SCES.Tables;
namespace IRAP.BL.SCES
{
public class IRAPSCES : IRAPBLLBase
{
private static string className =
MethodBase.GetCurrentMethod().DeclaringType.FullName;
public IRAPSCES()
{
WriteLog.Instance.WriteLogFileName =
MethodBase.GetCurrentMethod().DeclaringType.Namespace;
}
/// <param name="communityID">社区标识</param>
/// <param name="dstT173LeafID">目标仓储地点叶标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[ProductionWorkOrder]</returns>
public IRAPJsonResult ufn_GetList_ProductionWorkOrdersToDeliverMaterial(
int communityID,
int dstT173LeafID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<ProductionWorkOrder> datas = new List<ProductionWorkOrder>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@DstT173LeafID", DbType.Int32, dstT173LeafID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPSCES..ufn_GetList_ProductionWorkOrdersToDeliverMaterial," +
"参数:CommunityID={0}|DstT173LeafID={1}|SysLogID={2}",
communityID,
dstT173LeafID,
sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL =
"SELECT * " +
"FROM IRAPSCES..ufn_GetList_ProductionWorkOrdersToDeliverMaterial(" +
"@CommunityID, @DstT173LeafID, @SysLogID) " +
"ORDER BY ScheduledStartTime";
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<ProductionWorkOrder> lstDatas =
conn.CallTableFunc<ProductionWorkOrder>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPSCES..ufn_GetList_ProductionWorkOrdersToDeliverMaterial 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <param name="communityID">社区标识</param>
/// <param name="subMaterialCode">子项物料号</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[PWOToDeliverByMaterialCode]</returns>
public IRAPJsonResult ufn_GetList_PWOToDeliverByMaterialCode(
int communityID,
string subMaterialCode,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<PWOToDeliverByMaterialCode> datas =
new List<PWOToDeliverByMaterialCode>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@MaterialCode", DbType.String, subMaterialCode));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPSCES..ufn_GetList_PWOToDeliverByMaterialCode," +
"参数:CommunityID={0}|MaterialCode={1}|SysLogID={2}",
communityID,
subMaterialCode,
sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL =
"SELECT * " +
"FROM IRAPSCES..ufn_GetList_PWOToDeliverByMaterialCode(" +
"@CommunityID, @MaterialCode, @SysLogID) " +
"ORDER BY ScheduledStartTime, FactID";
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<PWOToDeliverByMaterialCode> lstDatas =
conn.CallTableFunc<PWOToDeliverByMaterialCode>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPSCES..ufn_GetList_PWOToDeliverByMaterialCode 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <param name="communityID">社区标识</param>
/// <param name="dstT173LeafID">目标仓储地点叶标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[ProductionWorkOrder]</returns>
public IRAPJsonResult ufn_GetList_ProductionWorkOrdersToDeliverMaterial_N(
int communityID,
int dstT173LeafID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<ProductionWorkOrderEx> datas = new List<ProductionWorkOrderEx>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@DstT173LeafID", DbType.Int32, dstT173LeafID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPSCES..ufn_GetList_ProductionWorkOrdersToDeliverMaterial_N," +
"参数:CommunityID={0}|DstT173LeafID={1}|SysLogID={2}",
communityID,
dstT173LeafID,
sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL =
"SELECT * " +
"FROM IRAPSCES..ufn_GetList_ProductionWorkOrdersToDeliverMaterial_N(" +
"@CommunityID, @DstT173LeafID, @SysLogID) " +
"ORDER BY ScheduledStartTime, FactID";
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<ProductionWorkOrderEx> lstDatas =
conn.CallTableFunc<ProductionWorkOrderEx>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPSCES..ufn_GetList_ProductionWorkOrdersToDeliverMaterial_N 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取工单物料配送指令单
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="pwoIssuingFactID">工单签发事实编号</param>
/// <param name="sysLogID">系统登录标识</param>
public IRAPJsonResult ufn_GetList_MaterialToDeliverForPWO(
int communityID,
long pwoIssuingFactID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<MaterialToDeliver> datas = new List<MaterialToDeliver>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@PWOIssuingFactID", DbType.Int64, pwoIssuingFactID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPSCES..ufn_GetList_MaterialToDeliverForPWO," +
"参数:CommunityID={0}|PWOIssuingFactID={1}|SysLogID={2}",
communityID,
pwoIssuingFactID,
sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL =
"SELECT * " +
"FROM IRAPSCES..ufn_GetList_MaterialToDeliverForPWO(" +
"@CommunityID, @PWOIssuingFactID, @SysLogID)";
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<MaterialToDeliver> lstDatas =
conn.CallTableFunc<MaterialToDeliver>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPSCES..ufn_GetList_MaterialToDeliverForPWO 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 打印生产工单流转卡,并生成工单原辅材料配送临时记录
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="transactNo">申请到的交易号</param>
/// <param name="pwoIssuingFactID">工单签发事实编号</param>
/// <param name="srcT173LeafID">发料库房叶标识</param>
/// <param name="dstT173LeafID">目标超市叶标识</param>
/// <param name="dstT106LeafID_Recv">目标超市收料库位叶标识</param>
/// <param name="dstT1LeafID_Recv">目标超市物料员部门叶标识</param>
/// <param name="pickUpSheetXML">备料清单XML</param>
/// <param name="sysLogID">系统登录标识</param>
public IRAPJsonResult usp_PrintVoucher_PWOMaterialDelivery(
int communityID,
long transactNo,
long pwoIssuingFactID,
int srcT173LeafID,
int dstT173LeafID,
int dstT106LeafID_Recv,
int dstT1LeafID_Recv,
string pickUpSheetXML,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@TransactNo", DbType.Int64, transactNo));
paramList.Add(new IRAPProcParameter("@PWOIssuingFactID", DbType.Int64, pwoIssuingFactID));
paramList.Add(new IRAPProcParameter("@SrcT173LeafID", DbType.Int32, srcT173LeafID));
paramList.Add(new IRAPProcParameter("@DstT173LeafID", DbType.Int32, dstT173LeafID));
paramList.Add(new IRAPProcParameter("@DstT106LeafID_Recv", DbType.Int32, dstT106LeafID_Recv));
paramList.Add(new IRAPProcParameter("@DstT1LeafID_Recv", DbType.Int32, dstT1LeafID_Recv));
paramList.Add(new IRAPProcParameter("@PickUpSheetXML", DbType.String, pickUpSheetXML));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
paramList.Add(
new IRAPProcParameter(
"@ErrCode",
DbType.Int32,
ParameterDirection.Output,
4));
paramList.Add(
new IRAPProcParameter(
"@ErrText",
DbType.String,
ParameterDirection.Output,
400));
WriteLog.Instance.Write(
string.Format("执行存储过程 IRAPSCES..usp_PrintVoucher_PWOMaterialDelivery,参数:" +
"CommunityID={0}|TransactNo={1}|PWOIssuingFactID={2}|SrcT173LeafID={3}|" +
"DstT173LeafID={4}|DstT106LeafID_Recv={5}|DstT1LeafID_Recv={6}|" +
"PickUpSheetXML={7}|SysLogID={8}",
communityID, transactNo, pwoIssuingFactID, srcT173LeafID, dstT173LeafID,
dstT106LeafID_Recv, dstT1LeafID_Recv, pickUpSheetXML, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
IRAPError error =
conn.CallProc(
"IRAPSCES..usp_PrintVoucher_PWOMaterialDelivery",
ref paramList);
errCode = error.ErrCode;
errText = error.ErrText;
WriteLog.Instance.Write(
string.Format(
"({0}){1}",
errCode,
errText),
strProcedureName);
Hashtable rtnParams = new Hashtable();
if (errCode == 0)
{
foreach (IRAPProcParameter param in paramList)
{
if (param.Direction == ParameterDirection.InputOutput ||
param.Direction == ParameterDirection.Output)
{
if (param.DbType == DbType.Int32 && param.Value == DBNull.Value)
rtnParams.Add(param.ParameterName.Replace("@", ""), 0);
else
rtnParams.Add(param.ParameterName.Replace("@", ""), param.Value);
}
}
}
foreach (DictionaryEntry entry in rtnParams)
{
WriteLog.Instance.Write(
string.Format(
"[{0}]=[{1}]",
entry.Key,
entry.Value),
strProcedureName);
}
return Json(rtnParams);
}
#endregion
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("调用 IRAPSCES..usp_PrintVoucher_PWOMaterialDelivery 时发生异常:{0}", error.Message);
return Json(new Hashtable());
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <param name="communityID">社区标识</param>
/// <param name="pwoIssuingFactID">工单签发事实编号</param>
/// <param name="sysLogID">系统登录标识</param>
public IRAPJsonResult ufn_GetList_ProductionFlowCard(
int communityID,
long pwoIssuingFactID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<ProductionFlowCard> datas = new List<ProductionFlowCard>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@PWOIssuingFactID", DbType.Int64, pwoIssuingFactID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPSCES..ufn_GetList_ProductionFlowCard," +
"参数:CommunityID={0}|PWOIssuingFactID={1}|SysLogID={2}",
communityID,
pwoIssuingFactID,
sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL =
"SELECT * " +
"FROM IRAPSCES..ufn_GetList_ProductionFlowCard(" +
"@CommunityID, @PWOIssuingFactID, @SysLogID)";
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<ProductionFlowCard> lstDatas =
conn.CallTableFunc<ProductionFlowCard>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPSCES..ufn_GetList_ProductionFlowCard 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
///
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="materialCode">物料代码</param>
/// <param name="customerCode">物料标签代码</param>
/// <param name="shipToParty">发运地点</param>
/// <param name="qtyInStore">物料计划量</param>
/// <param name="dateCode">物料生产日期</param>
/// <param name="sysLogID">系统登录标识</param>
/// <param name="errCode"></param>
/// <param name="errText"></param>
/// <returns></returns>
public IRAPJsonResult usp_PokaYoke_PallPrint(
int communityID,
string materialCode,
string customerCode,
string shipToParty,
string qtyInStore,
string dateCode,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@MaterialCode", DbType.String, materialCode));
paramList.Add(new IRAPProcParameter("@CustomerCode", DbType.String, customerCode));
paramList.Add(new IRAPProcParameter("@ShipToParty", DbType.String, shipToParty));
paramList.Add(new IRAPProcParameter("@QtyInStore", DbType.String, qtyInStore));
paramList.Add(new IRAPProcParameter("@DateCode", DbType.String, dateCode));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
paramList.Add(
new IRAPProcParameter(
"@ErrCode",
DbType.Int32,
ParameterDirection.Output,
4));
paramList.Add(
new IRAPProcParameter(
"@ErrText",
DbType.String,
ParameterDirection.Output,
400));
WriteLog.Instance.Write(
string.Format("执行存储过程 IRAPSCES..usp_PokaYoke_PallPrint,参数:" +
"CommunityID={0}|MaterialCode={1}|CustomerCode={2}|"+
"ShipToParty={3}|QtyInStore={4}|DateCode={5}|SysLogID={6}",
communityID, materialCode, customerCode, shipToParty,
qtyInStore, dateCode, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
IRAPError error =
conn.CallProc(
"IRAPSCES..usp_PokaYoke_PallPrint",
ref paramList);
errCode = error.ErrCode;
errText = error.ErrText;
WriteLog.Instance.Write(
string.Format(
"({0}){1}",
errCode,
errText),
strProcedureName);
Hashtable rtnParams = new Hashtable();
if (errCode == 0)
{
foreach (IRAPProcParameter param in paramList)
{
if (param.Direction == ParameterDirection.InputOutput ||
param.Direction == ParameterDirection.Output)
{
if (param.DbType == DbType.Int32 && param.Value == DBNull.Value)
rtnParams.Add(param.ParameterName.Replace("@", ""), 0);
else
rtnParams.Add(param.ParameterName.Replace("@", ""), param.Value);
}
}
}
foreach (DictionaryEntry entry in rtnParams)
{
WriteLog.Instance.Write(
string.Format(
"[{0}]=[{1}]",
entry.Key,
entry.Value),
strProcedureName);
}
return Json(rtnParams);
}
#endregion
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("调用 IRAPSCES..usp_PokaYoke_PallPrint 时发生异常:{0}", error.Message);
return Json(new Hashtable());
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取生产工单发料的未结配送指令清单,包括:
/// ⒈ 已排产但尚未配送的
/// ⒉ 已配送但尚未接收的
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="dstT173LeafID">目标仓储地点叶标识</param>
/// <param name="sysLogID">系统登录标识</param>
public IRAPJsonResult ufn_GetList_UnclosedDeliveryOrdersForPWO(
int communityID,
int dstT173LeafID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<UnclosedDeliveryOrdersForPWO> datas =
new List<UnclosedDeliveryOrdersForPWO>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@DstT173LeafID", DbType.Int32, dstT173LeafID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPSCES..ufn_GetList_UnclosedDeliveryOrdersForPWO," +
"参数:CommunityID={0}|DstT173LeafID={1}|SysLogID={2}",
communityID,
dstT173LeafID,
sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL =
"SELECT * " +
"FROM IRAPSCES..ufn_GetList_UnclosedDeliveryOrdersForPWO(" +
"@CommunityID, @DstT173LeafID, @SysLogID)";
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<UnclosedDeliveryOrdersForPWO> lstDatas =
conn.CallTableFunc<UnclosedDeliveryOrdersForPWO>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPSCES..ufn_GetList_UnclosedDeliveryOrdersForPWO 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 生产工单配送流转卡打印后实际配送操作前撤销
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="af482PK">辅助事实分区键</param>
/// <param name="pwoIssuingFactID">工单签发事实编号</param>
/// <param name="sysLogID">系统登录标识</param>
public IRAPJsonResult usp_UndoPrintVoucher_PWOMaterialDelivery(
int communityID,
long af482PK,
long pwoIssuingFactID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@AF482PK", DbType.Int64, af482PK));
paramList.Add(new IRAPProcParameter("@PWOIssuingFactID", DbType.Int64, pwoIssuingFactID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
paramList.Add(
new IRAPProcParameter(
"@ErrCode",
DbType.Int32,
ParameterDirection.Output,
4));
paramList.Add(
new IRAPProcParameter(
"@ErrText",
DbType.String,
ParameterDirection.Output,
400));
WriteLog.Instance.Write(
string.Format("执行存储过程 IRAPSCES..usp_UndoPrintVoucher_PWOMaterialDelivery,参数:" +
"CommunityID={0}|AF482PK={1}|PWOIssuingFactID={2}|" +
"SysLogID={3}",
communityID, af482PK, pwoIssuingFactID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
IRAPError error =
conn.CallProc(
"IRAPSCES..usp_UndoPrintVoucher_PWOMaterialDelivery",
ref paramList);
errCode = error.ErrCode;
errText = error.ErrText;
WriteLog.Instance.Write(
string.Format(
"({0}){1}",
errCode,
errText),
strProcedureName);
Hashtable rtnParams = new Hashtable();
if (errCode == 0)
{
foreach (IRAPProcParameter param in paramList)
{
if (param.Direction == ParameterDirection.InputOutput ||
param.Direction == ParameterDirection.Output)
{
if (param.DbType == DbType.Int32 && param.Value == DBNull.Value)
rtnParams.Add(param.ParameterName.Replace("@", ""), 0);
else
rtnParams.Add(param.ParameterName.Replace("@", ""), param.Value);
}
}
}
foreach (DictionaryEntry entry in rtnParams)
{
WriteLog.Instance.Write(
string.Format(
"[{0}]=[{1}]",
entry.Key,
entry.Value),
strProcedureName);
}
return Json(rtnParams);
}
#endregion
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("调用 IRAPSCES..usp_UndoPrintVoucher_PWOMaterialDelivery 时发生异常:{0}", error.Message);
return Json(new Hashtable());
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 根据制造订单号和制造订单行号,获取工单信息
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="dstT173LeafID">目标仓储地点</param>
/// <param name="moNumber">制造订单号</param>
/// <param name="moLineNo">制造订单行号</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>ReprintPWO</returns>
public IRAPJsonResult mfn_GetInfo_PWOToReprint(
int communityID,
int dstT173LeafID,
string moNumber,
int moLineNo,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
ReprintPWO rlt = new ReprintPWO();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
//paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
//paramList.Add(new IRAPProcParameter("@AF482PK", DbType.Int64, af482PK));
//paramList.Add(new IRAPProcParameter("@PWOIssuingFactID", DbType.Int64, pwoIssuingFactID));
//paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
//paramList.Add(
// new IRAPProcParameter(
// "@ErrCode",
// DbType.Int32,
// ParameterDirection.Output,
// 4));
//paramList.Add(
// new IRAPProcParameter(
// "@ErrText",
// DbType.String,
// ParameterDirection.Output,
// 400));
//WriteLog.Instance.Write(
// string.Format("执行存储过程 IRAPSCES..usp_UndoPrintVoucher_PWOMaterialDelivery,参数:" +
// "CommunityID={0}|AF482PK={1}|PWOIssuingFactID={2}|" +
// "SysLogID={3}",
// communityID, af482PK, pwoIssuingFactID, sysLogID),
// strProcedureName);
#endregion
#region 执行数据库函数或存储过程
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
long partitioningKey = communityID * 1000000000000 + DateTime.Now.Year;
string strSQL =
string.Format(
"SELECT * " +
"FROM IRAPMES..AuxFact_PWOIssuing " +
"WHERE PartitioningKey={0} " +
" AND MONumber='{1}' AND MOLineNo={2}",
partitioningKey,
moNumber,
moLineNo);
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<AuxFact_PWOIssuing> lstOrders =
conn.CallTableFunc<AuxFact_PWOIssuing>(strSQL, paramList);
if (lstOrders.Count == 0)
{
errCode = -1;
errText = string.Format("未找到[{0}]-[{1}]的制造订单", moNumber, moLineNo);
WriteLog.Instance.Write(errText, strProcedureName);
return Json(new ReprintPWO());
}
rlt.PWONo = lstOrders[0].WFInstanceID;
rlt.PlannedStartDate = lstOrders[0].ScheduledStartTime;
rlt.PlannedCloseDate = lstOrders[0].ScheduledCloseTime;
rlt.MONumber = lstOrders[0].MONumber;
rlt.MOLineNo = lstOrders[0].MOLineNo;
rlt.LotNumber = lstOrders[0].LotNumber;
#region 获取制造订单的配料信息
strSQL =
string.Format(
"SELECT * " +
"FROM IRAPSCES..ufn_GetList_MaterialToDeliverForPWO(" +
"{0}, {1}, {2})",
communityID,
lstOrders[0].FactID,
sysLogID);
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<MaterialToDeliver> lstMaterials =
conn.CallTableFunc<MaterialToDeliver>(strSQL, paramList);
if (lstMaterials.Count == 0)
{
errCode = -1;
errText = string.Format("未找到[{0}]-[{1}]制造订单的配料信息", moNumber, moLineNo);
WriteLog.Instance.Write(errText, strProcedureName);
return Json(new ReprintPWO());
}
rlt.T173Code = lstMaterials[0].T173Code;
rlt.T173Name = lstMaterials[0].T173Name;
rlt.AtStoreLocCode = lstMaterials[0].AtStoreLocCode;
rlt.DstWorkShopCode = lstMaterials[0].DstWorkShopCode;
rlt.DstWorkShopDesc = lstMaterials[0].DstWorkShopDesc;
rlt.SuggestedQuantityToPick = lstMaterials[0].SuggestedQuantityToPick.ToString();
rlt.UnitOfMeasure = lstMaterials[0].UnitOfMeasure;
rlt.T131Code = lstMaterials[0].T131Code;
rlt.ActualQtyDecompose = lstMaterials[0].ActualQtyDecompose;
rlt.MaterialCode = lstMaterials[0].MaterialCode;
rlt.MaterialDesc = lstMaterials[0].MaterialDesc;
rlt.ActualQuantityToDeliver = lstMaterials[0].ActualQuantityToDeliver.ToString();
rlt.DstT106Code = lstMaterials[0].DstT106Code;
#endregion
#region 获取制造订单的 T134 父节点信息
strSQL =
string.Format(
"SELECT * " +
"FROM IRAPMDM..stb057 WHERE PartitioningKey={0} " +
"AND NodeID={1}",
communityID * 10000 + 134,
lstOrders[0].T134NodeID);
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<Stb057> lstT134Nodes =
conn.CallTableFunc<Stb057>(strSQL, paramList);
if (lstT134Nodes.Count > 0)
{
rlt.T134Name =
string.Format(
"{0}-[{1}]",
lstT134Nodes[0].NodeName,
lstT134Nodes[0].Code);
}
#endregion
#region 获取工单的计划产量以及产品信息
strSQL =
string.Format(
"SELECT * " +
"FROM IRAPMES..TempFact_OLTP " +
"WHERE PartitioningKey={0} " +
"AND WFInstanceID='{1}' " +
"AND OpID=482 AND OpType=1",
DateTime.Now.Year * 1000000000000 + communityID * 10000 + 482,
rlt.PWONo);
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<FixedFact_MES> lstFixedFacts =
conn.CallTableFunc<FixedFact_MES>(strSQL, paramList);
if (lstFixedFacts.Count != 0)
{
rlt.PlannedQuantity = lstFixedFacts[0].Metric01;
rlt.ProductNo = lstFixedFacts[0].Code01;
int t102LeafID = lstFixedFacts[0].Leaf01;
strSQL =
string.Format(
"SELECT * " +
"FROM IRAPMDM..stb058 " +
"WHERE PartitioningKey={0} " +
"AND LeafID={1}",
communityID * 10000 + 102,
t102LeafID);
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<Stb058> lst058 =
conn.CallTableFunc<Stb058>(strSQL, paramList);
if (lst058.Count > 0)
{
rlt.ProductDesc = lst058[0].NodeName;
}
}
#endregion
#region 如果社区标识是 60030,则需要获取 GateWayWC
if (communityID == 60030)
{
strSQL =
string.Format(
"SELECT * " +
"FROM IRAPSCES..ITEM_INFO " +
"WHERE T102LeafID={0}",
lstMaterials[0].LeafID);
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<ITEM_INFO> lstItems =
conn.CallTableFunc<ITEM_INFO>(strSQL, paramList);
if (lstItems.Count > 0)
{
rlt.GateWayWC = lstItems[0].GATEWAY_WC;
}
}
#endregion
errCode = 0;
errText = "获取成功";
}
#endregion
return Json(rlt);
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("调用 mfn_GetInfo_PWOToReprint 时发生异常:{0}", error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
return Json(new ReprintPWO());
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取指定期间指定库房工单物料配送历史记录
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t173LeafID">仓储地点叶标识</param>
/// <param name="beginDT">开始日期时间</param>
/// <param name="endDT">结束日期时间</param>
public IRAPJsonResult ufn_GetFactList_RMTransferForPWO(
int communityID,
int t173LeafID,
DateTime beginDT,
DateTime endDT,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<RMTransferForPWO> datas = new List<RMTransferForPWO>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T173LeafID", DbType.Int32, t173LeafID));
paramList.Add(new IRAPProcParameter("@BeginDT", DbType.DateTime2, beginDT));
paramList.Add(new IRAPProcParameter("@EndDT", DbType.DateTime2, endDT));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPSCES..ufn_GetFactList_RMTransferForPWO,参数:" +
"CommunityID={0}|T173LeafID={1}|BeginDT={2}|" +
"EndDT={3}|SysLogID={4}",
communityID,
t173LeafID,
beginDT.ToString("yyyy-MM-dd HH:mm:ss.fff"),
endDT.ToString("yyyy-MM-dd HH:mm:ss.fff"),
sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL =
"SELECT * " +
"FROM IRAPSCES..ufn_GetFactList_RMTransferForPWO(" +
"@CommunityID, @T173LeafID, @BeginDT, @EndDT, @SysLogID)";
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<RMTransferForPWO> lstDatas =
conn.CallTableFunc<RMTransferForPWO>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPSCES..ufn_GetFactList_RMTransferForPWO 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 修改生产工单配送数量
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="factID">生产工单事实编号</param>
/// <param name="actualQtyToDeliver">配送数量</param>
/// <param name="subTreeID">子项物料树标识</param>
/// <param name="subLeafID">子项物料叶标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <param name="errCode"></param>
/// <param name="errText"></param>
/// <returns></returns>
public IRAPJsonResult usp_SaveFact_PWODeliveryQty(
int communityID,
long factID,
long actualQtyToDeliver,
int subTreeID,
int subLeafID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@FactID", DbType.Int64, factID));
paramList.Add(new IRAPProcParameter("@ActualQtyToDeliver", DbType.Int64, actualQtyToDeliver));
paramList.Add(new IRAPProcParameter("@SubTreeID", DbType.Int32, subTreeID));
paramList.Add(new IRAPProcParameter("@SubLeafID", DbType.Int32, subLeafID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
paramList.Add(
new IRAPProcParameter(
"@ErrCode",
DbType.Int32,
ParameterDirection.Output,
4));
paramList.Add(
new IRAPProcParameter(
"@ErrText",
DbType.String,
ParameterDirection.Output,
400));
WriteLog.Instance.Write(
string.Format("执行存储过程 IRAPSCES..usp_SaveFact_PWODeliveryQty,参数:" +
"CommunityID={0}|FactID={1}|ActualQtyToDelivery={2}|SubTreeID={3}|"+
"SubLeafID={4}|SysLogID={5}",
communityID, factID, actualQtyToDeliver, subTreeID, subLeafID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
IRAPError error =
conn.CallProc(
"IRAPSCES..usp_SaveFact_PWODeliveryQty",
ref paramList);
errCode = error.ErrCode;
errText = error.ErrText;
WriteLog.Instance.Write(
string.Format(
"({0}){1}",
errCode,
errText),
strProcedureName);
Hashtable rtnParams = new Hashtable();
if (errCode == 0)
{
foreach (IRAPProcParameter param in paramList)
{
if (param.Direction == ParameterDirection.InputOutput ||
param.Direction == ParameterDirection.Output)
{
if (param.DbType == DbType.Int32 && param.Value == DBNull.Value)
rtnParams.Add(param.ParameterName.Replace("@", ""), 0);
else
rtnParams.Add(param.ParameterName.Replace("@", ""), param.Value);
}
}
}
foreach (DictionaryEntry entry in rtnParams)
{
WriteLog.Instance.Write(
string.Format(
"[{0}]=[{1}]",
entry.Key,
entry.Value),
strProcedureName);
}
return Json(rtnParams);
}
#endregion
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("调用 IRAPSCES..usp_SaveFact_PWODeliveryQty 时发生异常:{0}", error.Message);
return Json(new Hashtable());
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
}
}
|
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 PROG1_PROYECTO_FINAL
{
public partial class Prov_Child_AgrProveedor : Form
{
C_Proveedores objeto = new C_Proveedores();
private string idProveedor = null;
public Prov_Child_AgrProveedor()
{
InitializeComponent();
}
private void Prov_Child_AgrProveedor_Load(object sender, EventArgs e)
{
MostrarProvdor();
ComboBoxTipo_Load();
//SETTING DGV
dataGridView1.Columns[3].Width = 200;
dataGridView1.Columns[5].Width = 180;
}
private void ComboBoxTipo_Load()
{
comboBxTipo.Items.Insert(0, "-- Selec. un item --");
comboBxTipo.SelectedIndex = 0;
comboBxTipo.Items.Add("Computadoras");
comboBxTipo.Items.Add("Celulares & Tablets");
comboBxTipo.Items.Add("Accesorios");
}
private void MostrarProvdor()
{
dataGridView1.DataSource = objeto.MostrarProv();
}
private void iconBtnInsert_Click(object sender, EventArgs e)
{
try
{
objeto.InsertarProv(textBoxNombre.Text, textBoxCedula.Text, textBoxTel.Text, textBoxEmail.Text, comboBxTipo.SelectedIndex);
MessageBox.Show("se inserto correctamente");
MostrarProvdor();
CleanForm();
}
catch (Exception ex)
{
MessageBox.Show("no se pudo insertar los datos por: " + ex);
}
}
private void iconBtnEdit_Click(object sender, EventArgs e)
{
try
{
idProveedor = dataGridView1.CurrentRow.Cells[0].Value.ToString();
objeto.EditarProv(int.Parse(idProveedor), textBoxNombre.Text, textBoxCedula.Text, textBoxTel.Text, textBoxEmail.Text, comboBxTipo.SelectedIndex);
MessageBox.Show("Actualizado correctamente");
MostrarProvdor();
CleanForm();
}
catch (Exception ex)
{
MessageBox.Show("no se pudo insertar los datos por: " + ex);
}
}
private void iconBtnDel_Click(object sender, EventArgs e)
{
try
{
idProveedor = dataGridView1.CurrentRow.Cells[0].Value.ToString();
objeto.EliminarProv(idProveedor);
MessageBox.Show("Eliminado correctamente");
MostrarProvdor();
CleanForm();
}
catch (Exception ex)
{
MessageBox.Show("no se pudo insertar los datos por: " + ex);
}
}
private void CleanForm()
{
textBoxNombre.Clear();
textBoxCedula.Clear();
textBoxEmail.Clear();
textBoxTel.Clear();
comboBxTipo.SelectedIndex = 0;
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
try
{
textBoxNombre.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
textBoxCedula.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();
textBoxEmail.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString();
textBoxTel.Text = dataGridView1.CurrentRow.Cells[4].Value.ToString();
comboBxTipo.SelectedItem = dataGridView1.CurrentRow.Cells[5].Value.ToString();
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
private void reporte_Click(object sender, EventArgs e)
{
Reporte_Proveedores reporte_Proveedores = new Reporte_Proveedores();
reporte_Proveedores.ShowDialog();
}
}
}
|
using System;
namespace E3
{
class Program
{
static void Main(string[] args)
{
string nombre;
string posicion;
string pais;
int numeroDeLaFigurita;
int[] count = new int[2];
Console.WriteLine ("Ingrese los datos de la figurita");
Console.WriteLine ("Nombre: ");
nombre = Console.ReadLine();
Console.WriteLine ("Posicion: ");
posicion = Console.ReadLine();
Console.WriteLine ("Pais: ");
pais = Console.ReadLine();
Console.WriteLine ("Numero de la figurita: ");
numeroDeLaFigurita = Int32.Parse(Console.ReadLine());
Album figurita = new Album ();
if (figurita.apareceEnElAlbum(numeroDeLaFigurita)) Console.WriteLine("La figurita esta en el album");
else figurita.ingreso(nombre,posicion,pais,numeroDeLaFigurita);
while (posicion != "Salir"){
Console.WriteLine("Ingrese \"Delantero\" para saber la cantidad de delanteros\n\"Medio Campista\" para saber la cantidad de medio campsitas\nSi desea salir ingrese \"Salir\"");
posicion = Console.ReadLine();
if (posicion != "Salir") Console.WriteLine("La cantidad de "+ posicion + " es: "+ figurita.Contador(posicion));
}
if (figurita.EstaCompleto()) Console.WriteLine("¡¡El album esta completo!!");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace test {
public class LevelBounds:MonoBehaviour {
void OnTriggerEnter2D(Collider2D other) {
if (other.gameObject.GetComponent<PlayerController>()) {
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
}
}
|
namespace Aria.Core.Interfaces
{
public interface IDrawable
{
/// <summary>
/// Call to provide draw code when window renders.
/// </summary>
/// <param name="elapsed"></param>
void Draw(double elapsed);
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
[Serializable]
public class DialogueTree {
public string myName;
public List<Conversation> conversationList;
[NonSerialized]
public Conversation currentConversation;
// Find conversation by name
public Conversation GetConversationByName (string conversationName)
{
foreach (Conversation conversation in conversationList)
{
if (conversation.myName == conversationName)
{
return conversation;
}
}
Debug.LogError ("Can't find conversation");
return null;
}
}
// Conversation - What the conversation is about
[Serializable]
public class Conversation {
public string myName;
public List<DialogueOption> optionList;
}
// Dialogue option
[Serializable]
public class DialogueOption: IConditionable {
public string myTitle;
public List<DialogueSentence> sentenceList;
public List<Condition> conditionList;
public List<Condition> ConditionList
{
get
{
return conditionList;
}
set
{
conditionList = value;
}
}
public void RemoveConditionFromList(Condition condition)
{
if (condition == null)
{
Debug.LogError ("condition is null");
return;
}
if (conditionList.Contains (condition) == false)
{
Debug.LogError ("condition is not in list");
return;
}
conditionList.Remove (condition);
}
}
// Dialogue Sentence
[Serializable]
public class DialogueSentence : ISubinteractable {
public string speakerName;
public string myText;
public bool subinteractImmediately = false;
public List<SubInteraction> mySubIntList;
public List<SubInteraction> SubIntList
{
get
{
return mySubIntList;
}
set
{
mySubIntList = value;
}
}
public DialogueSentence(string speaker, string text, bool subIntIm, List<SubInteraction> subIntList = null)
{
speakerName = speaker;
myText = text;
mySubIntList = subIntList;
subinteractImmediately = subIntIm;
}
} |
//
// © Copyright 2017-2018 HP Development Company, L.P.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Json;
namespace CopyrightHeader
{
public class CopyrightUtil
{
public static IList<string> ReadFile(string fileName)
{
var buffer = new List<string>();
if (File.Exists(fileName))
{
using (var reader = new StreamReader(fileName))
{
var line = "";
while ((line = reader.ReadLine()) != null)
{
buffer.Add(line);
}
}
}
return buffer;
}
public static void WriteFile(string fileName, IEnumerable<string> buffer)
{
var backup = fileName + ".cp.bak";
//Make a backup just in case
if (File.Exists(fileName))
{
if (File.Exists(backup))
{
File.Delete(backup);
}
File.Copy(fileName, backup);
}
try
{
using (var writer = new StreamWriter(fileName))
{
foreach (var line in buffer)
{
writer.WriteLine(line);
}
}
}
catch (Exception)
{
File.Copy(backup, fileName);
}
finally
{
if (File.Exists(backup))
{
File.Delete(backup);
}
}
}
private static void GetCommentInfo(string inputFile, CopyrightTemplate companyTemplate, Action<string> errorAction = null)
{
const string commentSpecFile = "CommentSpecification.json";
try
{
var ext = Path.GetExtension(inputFile);
using (var resource = CopyrightUtil.ResourceStream(commentSpecFile))
{
if (resource != null)
{
var serializer = new DataContractJsonSerializer(typeof(CommentSpec[]));
var commentSpecs = (CommentSpec[])serializer.ReadObject(resource);
var commentSpec = commentSpecs.Find(ext);
if (commentSpec == null)
{
errorAction?.Invoke($"Unsupported file: {inputFile}");
}
Console.WriteLine($"Using {commentSpec?.Name} extension specification");
companyTemplate.CommentSpec = commentSpec;
}
}
}
catch (Exception e)
{
errorAction?.Invoke(e.Message);
}
}
public static CopyrightTemplate ReadTemplate(string inputFile, string templateName, Action<string> errorAction = null)
{
var copyrightTemplate = (CopyrightTemplate) null;
if (!string.IsNullOrWhiteSpace(templateName))
{
var path = "templates." + templateName + ".json";
try
{
using (var resource = ResourceStream(path))
{
if (resource != null)
{
var serializer = new DataContractJsonSerializer(typeof(CopyrightTemplate));
copyrightTemplate = (CopyrightTemplate)serializer.ReadObject(resource);
if (copyrightTemplate == null)
{
errorAction?.Invoke("Invalid template");
}
}
else
{
errorAction?.Invoke($"Bad or missing template: {path}");
}
}
}
catch (Exception e)
{
errorAction?.Invoke(e.Message);
}
}
if (copyrightTemplate != null)
{
GetCommentInfo(inputFile, copyrightTemplate, errorAction);
}
return copyrightTemplate;
}
public static Stream ResourceStream(string name)
{
var assembly = Assembly.GetExecutingAssembly();
var resources = assembly.GetManifestResourceNames();
var resourceName = resources.First(x => x.EndsWith(name));
var stream = assembly.GetManifestResourceStream(resourceName);
return stream;
}
}
}
|
using System;
using System.Web;
using System.Data;
using DrasCommon.Classes;
using DrasCommon.Datalayer;
namespace DrasCommon.Security
{
[Serializable]
public class SessionCache
{
public SessionCache()
{
_appAcronym = HttpContext.Current.Session["AppAcronym"].ToString();
_user = new DRASUser();
}
private DRASUser _user = null;
public DRASUser User
{
get
{
if (_user == null)
{
_appAcronym = HttpContext.Current.Session["AppAcronym"].ToString();
_user = new DRASUser();
}
return _user;
}
set { this._user = value; }
}
private string _dbEnvironment = null;
public string DBEnvironment
{
get { return _dbEnvironment; }
set { this._dbEnvironment = value; }
}
private string _appAcronym = null;
public string AppAcronym
{
get { return _appAcronym; }
set { this._appAcronym = value; }
}
private bool? _isDrasDev = null;
public bool IsDrasDev
{
get
{
if (_isDrasDev == null)
{
_isDrasDev = IsDrasDeveloper();
}
return (bool)_isDrasDev;
}
set { this._isDrasDev = value; }
}
private bool? _appMaintenance = null;
public bool AppMaintenance
{
get
{
return GetAppMaintenance(_appAcronym);
}
set { this._appMaintenance = value; }
}
private bool IsDrasDeveloper()
{
ExecStoredProcedure sp = null;
DataTable dt = new DataTable();
string thisUser = HttpContext.Current.Session["CurrentUserPin"].ToString();
bool ret_val = false;
try
{
sp = new ExecStoredProcedure(SharedConstants.SPGET_DRASDEV);
dt = sp.SPselect();
foreach (DataRow row in dt.Rows)
{
if (thisUser.Equals(row["userPin"].ToString()))
ret_val = true;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
sp.dbConnection.Close();
}
return ret_val;
}
private bool GetAppMaintenance(string appAcronym)
{
ExecStoredProcedure sp = null;
DataTable dt = new DataTable();
bool ret_val = false;
try
{
sp = new ExecStoredProcedure(SharedConstants.SPGET_APPMAINT);
sp.SPAddParm("@appAcronym", SqlDbType.NVarChar, appAcronym, ParameterDirection.Input);
dt = sp.SPselect();
if (dt.Rows[0]["SystemMaintenance"].ToString().Equals("True"))
ret_val = true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
sp.dbConnection.Close();
}
return ret_val;
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Different
{
internal class Exc08
{
public static void MainExc08()
{
ArrayList Lst = new ArrayList();
string text = "This is Awesome!";
string[] word = text.Split(' ');
for(int i = 0; i < word.Length; i++)
{
Lst.Add(word[i]);
}
foreach(string str in Lst)
{
Console.WriteLine(str);
}
}
}
}
|
using System;
namespace TY.SPIMS.POCOs
{
public class PurchaseCounterItemModel
{
public int? PurchaseId { get; set; }
public int? ReturnId { get; set; }
public string InvoiceNumber { get; set; }
public DateTime? Date { get; set; }
public string PONumber { get; set; }
public string MemoNumber { get; set; }
public decimal? Amount { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExamenDALLibrary;
using ExamenUserLibrary;
namespace ExamenBLLibrary
{
public class ExamenBL
{
ExamenDAL dal;
string candidate_Id;
public ExamenBL()
{
dal = new ExamenDAL();
}
public bool InsertIntoCandidates(ExamenStack examen)
{
return dal.InsertCandidate(examen);
}
public List<ExamenStack> GetAllQuestionsandAnswers(string testmodel)
{
return dal.GetAllQuestions(testmodel);
}
public bool UserValidation(string username, string password)
{
return dal.Validation(username, password);
}
public string Payment(string username, string testmodel)
{
string num = "123456789";
int len = num.Length;
string otp = string.Empty;
int otpdigit = 5;
string finaldigit;
int getindex;
for (int i = 0; i < otpdigit; i++)
{
do
{
getindex = new Random().Next(0, len);
finaldigit = num.ToCharArray()[getindex].ToString();
} while (otp.IndexOf(finaldigit)!=-1);
otp += finaldigit;
}
candidate_Id = otp;
string payment = "1";
if(dal.UpdatePayment(username,testmodel,candidate_Id,payment))
{
return candidate_Id;
}
else
{
return candidate_Id = "";
}
}
public bool InsertScores(string CandidateId, string username, string testmodel, int mark)
{
return dal.InsertIntoScores(CandidateId,username,testmodel,mark);
}
public List<ExamenStack> GetScores(string username)
{
return dal.GetScores(username);
}
public List<string> GetAllTestModels()
{
return dal.GetAllTestModels();
}
public bool CheckPayment(string username, string candidate_id)
{
return dal.CheckPayment(username, candidate_id);
}
public bool CheckUserInPayment(string username, string testmodel)
{
return dal.CheckUserInPayment(username, testmodel);
}
public bool InserttoTempScore(int sno, string options)
{
return dal.InserttoTempScore(sno, options);
}
public int GetCount()
{
return dal.GetCount();
}
public bool DeleteTempData()
{
return dal.DeleteTempScores();
}
public bool DeleteUserInPaymentList(string username,string testmodel)
{
return dal.DeleteUserInPaymentList(username,testmodel);
}
public string GetCandId(string username,string testmodel)
{
return dal.GetCandidateId(username,testmodel);
}
public bool UpdateTempScore(string candidate, int mark)
{
return dal.UpdateTempScore(candidate, mark);
}
public int Scores()
{
return dal.Scores();
}
public bool CheckUserInScores(string username)
{
return dal.CheckUserInScore(username);
}
public bool DeleteTemPCalculateScore()
{
return dal.DeleteTemPCalculateScore();
}
}
}
|
namespace ForumSystem.Web.ViewModels.Comments
{
using System;
using System.Linq;
using AutoMapper;
using ForumSystem.Data.Models;
using ForumSystem.Services.Mapping;
using Ganss.XSS;
public class PostCommentViewModel : IMapFrom<Comment>, IHaveCustomMappings
{
public int Id { get; set; }
public string Content { get; set; }
public DateTime CreatedOn { get; set; }
public string UserUserName { get; set; }
public string ImageSrc { get; set; }
public int PostId { get; set; }
public int? ParentId { get; set; }
public int VoteTypeCount { get; set; }
public bool IsSignInUserTheOwnerOfComment { get; set; }
public string VotesCountId => $"votesCount{this.Id}";
public string FormCommentId => $"commentBox{this.Id}";
public string CommentContentSectionId => $"commentContentSection{this.Id}";
public string SanitizeContent => new HtmlSanitizer().Sanitize(this.Content);
public void CreateMappings(IProfileExpression configuration)
{
configuration
.CreateMap<Comment, PostCommentViewModel>()
.ForMember(x => x.VoteTypeCount, opt =>
opt.MapFrom(y => y.CommentVotes.Sum(z => (int)z.Type)));
configuration
.CreateMap<Comment, PostCommentViewModel>()
.ForMember(x => x.ImageSrc, opt =>
opt.MapFrom(y => y.User.HasImage ?
$"/profileImages/{y.User.ProfileImage.Id}{y.User.ProfileImage.Extention}" :
"https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png"));
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KartObjects;
using KartLib;
using AxisEq;
using DevExpress.XtraGrid.Views.Grid;
using AxisPosCore;
using System.IO;
using KartObjects.Entities;
namespace KartSystem
{
public partial class TradeScaleListView : XBaseDictionaryEditor
{
public TradeScaleListView()
{
InitializeComponent();
}
TradeScale _scale;
public TradeScaleListView(TradeScale scale)
{
InitializeComponent();
_scale = scale;
InitView();
EnterValidateForm = false;
}
public BarcodeScannerEO _barcodeScaner;
delegate void SetTextCallback(string value);
void _barcodeScaner_BarcodeReceived(string barcode)
{
if (_barcodeScaner != null && _barcodeScaner.IsOpen)
SetGoodTextSearchText(barcode);
}
private void SetGoodTextSearchText(string text)
{
if (this.gridControl1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetGoodTextSearchText);
this.Invoke(d, new object[] { text });
}
else
{
string weightBarcode = text.Substring(0, 7);
gridView1.FocusedRowHandle = 0;
gridView1.SelectRow(0);
for (int i = 0; i < gridView1.RowCount; i++)
if ((gridView1.GetRow(i) as ScaleGoodDepart).BarCode == weightBarcode)
{
gridView1.ClearSelection();
gridView1.Focus();
gridView1.FocusedRowHandle = i;
gridView1.SelectRow(i);
gridView1.FocusedColumn = gridView1.Columns["BarCode"];
break;
}
}
}
List<ScaleGoodDepart> ScaleGoods;
public override void InitView()
{
base.InitView();
ListToSave = new List<ScaleGoodDepart>();
ScaleGoods = Loader.DbLoad<ScaleGoodDepart>("char_length(barcode)<14 and IdStore=" + _scale.IdStore.Value) ?? new List<ScaleGoodDepart>();
scaleGoodDepartBindingSource.DataSource = ScaleGoods;
if (_barcodeScaner == null)
{
int rate;
if (int.TryParse(Settings.BarcodeScanerBaudRate, out rate))
{
_barcodeScaner = new BarcodeScannerEO(Settings.BarcodeScanerPort, rate);
_barcodeScaner.BarcodeReceived += new DataReceived(_barcodeScaner_BarcodeReceived);
}
}
}
public override void RefreshView()
{
ScaleGoods = Loader.DbLoad<ScaleGoodDepart>("char_length(barcode)<14 and IdStore=" + _scale.IdStore.Value) ?? new List<ScaleGoodDepart>();
scaleGoodDepartBindingSource.DataSource = ScaleGoods;
}
protected override void SaveData()
{
base.SaveData();
for (int i = 0; i < ListToSave.Count; i++)
{
if (!string.IsNullOrEmpty(ListToSave[i].Name))
{
var newGood = Loader.DbLoadSingle<Good>("Id = " + ListToSave[i].Id);
if (newGood != null)
{
newGood.ExpireDate = ListToSave[i].ExpireDate;
newGood.ImplementationPeriod = ListToSave[i].ImplementationPeriod;
newGood.IdUser = KartDataDictionary.User.Id;
Saver.SaveToDb<Good>(newGood);
}
}
}
this.Close();
}
private void simpleButtonCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void gridControl1_EmbeddedNavigator_ButtonClick(object sender, DevExpress.XtraEditors.NavigatorButtonClickEventArgs e)
{
if (e.Button.ButtonType == DevExpress.XtraEditors.NavigatorButtonType.Remove)
{
var deletedGood = scaleGoodDepartBindingSource.Current as ScaleGoodDepart;
if (deletedGood != null)
{
Saver.DeleteFromDb<ScaleGoodDepart>(deletedGood);
// товар из дочерних отделов надо удалять в хранимой процедуре!
}
}
if (e.Button.ButtonType == DevExpress.XtraEditors.NavigatorButtonType.Append)
{
e.Handled = true;
FindGoodForm Form = new FindGoodForm();
Form.checkBox1.Checked = true;
if (Form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (Form.IsGoodFound)
{
Measure _Measure = KartDataDictionary.sMeasures.First(q => q.Id == Form.selectedGood.IdMeasure);
if (!_Measure.IsWeight)
{
MessageBox.Show(this, "Выбран не весовой товар.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
Store _Store = KartDataDictionary.sStores.First(q => q.Id == _scale.IdStore);
PriceListHead h = KartDataDictionary.sPriceListHeads.FirstOrDefault(q => (q.IdStore == _Store.Id) && (q.PriceListType == (int)PriceListType.ScaleLoadList));
if (h == null)
h = KartDataDictionary.sPriceListHeads.FirstOrDefault(q => q.Id == _Store.IdPriceList);
if (h == null)
throw new Exception("Возможно не задан прайс лист для подразделения.");
PriceList PriceListRecord = new PriceList()
{
Id = h.Id,
IdAssortment = (long)Form.selectedGood.Id,
IdGood = Form.selectedGood.Id,
IdStore = _Store.Id,
IsFixed = false,
Price = Form.selectedGood.Price,
PriceListType = PriceListType.ScaleLoadList
};
Saver.SaveToDb<PriceList>(PriceListRecord);
RefreshView();
}
}
if (Form.IsGoodGroupFound)
{
foreach (Good good in Form.selectedGoods)
{
var store = KartDataDictionary.sStores.First(q => q.Id == _scale.IdStore);
var h = KartDataDictionary.sPriceListHeads.FirstOrDefault(q => (q.IdStore == store.Id) && (q.PriceListType == (int)PriceListType.ScaleLoadList)) ??
KartDataDictionary.sPriceListHeads.FirstOrDefault(q => q.Id == store.IdPriceList);
if (h == null)
throw new Exception("Возможно не задан прайс лист для подразделения.");
var priceListRecord = new PriceList()
{
Id = h.Id,
IdAssortment = (long)good.Id,
IdGood = good.Id,
IdStore = store.Id,
IsFixed = false,
Price = good.Price,
PriceListType = PriceListType.ScaleLoadList
};
Saver.SaveToDb(priceListRecord);
}
RefreshView();
}
}
}
}
private decimal GetPrice(long IdPrice, long IdGood)
{
string queryprice = "select p.price from pricelists p where p.id = " + IdPrice + " and p.idgood = " + IdGood;
if (Loader.DataContext.ExecuteScalar(queryprice) != null)
{
decimal price = (decimal)Loader.DataContext.ExecuteScalar(queryprice);
return price;
}
else return 0;
}
List<ScaleGoodDepart> ListToSave;
private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
{
ListToSave.Add(scaleGoodDepartBindingSource.Current as ScaleGoodDepart);
}
private void gridView1_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
{
GridView View = sender as GridView;
if (Convert.ToDouble(View.GetRowCellDisplayText(e.RowHandle, View.Columns["Rest"])) <= 0)
{
e.Appearance.ForeColor = Color.Red;
}
}
public override void SaveSettings()
{
gridView1.SaveLayoutToXml(gvSettingsFileName());
}
public override void LoadSettings()
{
if (File.Exists(gvSettingsFileName()))
gridView1.RestoreLayoutFromXml(gvSettingsFileName());
}
private void TradeScaleListView_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.F12)
{
gridView1.Focus();
gridView1.FocusedColumn = gridView1.Columns["BarCode"];
}
}
}
}
|
using System;
/*
(Count positive and negative numbers and compute the average of numbers) Write
a program that reads an unspecified number of integers, determines how many
positive and negative values have been read, and computes the total and average of
the input values (not counting zeros). Your program ends with the input 0. Display
the average as a floating-point number
*/
namespace PositiveAndNegativeNumbers
{
class Program
{
static void Main(string[] args)
{
int number = 0, timesEntry = 0;
double sum = 0;
int positive = 0, negative = 0;
do
{
Console.WriteLine();
Console.Write("Enter number: ");
number = int.Parse(Console.ReadLine());
if (number != 0 && number > 0) positive++;
else if (number != 0 && number < 0) negative++;
if (number != 0) timesEntry++;
sum += number;
} while (number != 0);
Console.WriteLine("Number of positives = {0} \n Number of negatives = {1}", positive, negative);
Console.WriteLine("Average number is {0} ", sum / timesEntry);
}
}
}
|
using University.Data;
using University.Data.CustomEntities;
using University.Service;
using University.Service.Interface;
using University.UI.Areas.Admin.Models;
using University.UI.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using AutoMapper;
namespace University.UI.Areas.Admin.Controllers
{
public class ProductController : Controller
{
string ProductImagePath = WebConfigurationManager.AppSettings["ProductImagePath"];
private ICategoryMasterService _categoryMasterService;
private ISubCategoryService _subCategoryService;
private IProductService _productService;
//private IProductVideoService _productVideoService;
public ProductController(ICategoryMasterService categoryMasterService, ISubCategoryService subCategoryService, IProductService productService)
{
_categoryMasterService = categoryMasterService;
_subCategoryService = subCategoryService;
_productService = productService;
// _productVideoService = productVideoService;
}
// GET: Admin/Product
public ActionResult Index()
{
//var res = _productService.GetProductList().ToList();
var res= _productService.GetUserVideosList().ToList();
List<ProductViewModel> productViewModel = new List<ProductViewModel>();
foreach (var prod in res)
{
productViewModel.Add(new ProductViewModel
{
Id = prod.Id,
Title = prod.Title,
subcat = prod.subcategoryname,
sumvideorate = prod.VideoRate ?? 0
});
}
// var viewModel = AutoMapper.Mapper.Map<List<ProductEntity>, List<ProductViewModel>>(res);
var viewModel = productViewModel;
return View(viewModel);
}
public ActionResult AddEditProduct(string ProductId)
{
Session["ProductID"] = ProductId;
ProductViewModel viewModel;
if (!string.IsNullOrEmpty(ProductId))
{
var res = _productService.GetProduct(Convert.ToDecimal(ProductId));
viewModel = AutoMapper.Mapper.Map<ProductEntity, ProductViewModel>(res);
if (viewModel.ProductUserGuide == null) { viewModel.ProductUserGuide = new ProductUserGuideViewModel(); }
}
else
{
viewModel = new ProductViewModel();
}
var subcategorys = _subCategoryService.GetSubCategoryList().ToList();
//subcategorys = subcategorys.Where(t => t.AssocitedID == Convert.ToInt32(Session["UserSessionIDs"])).ToList();
ViewBag.SubCategoryList = subcategorys;
return View(viewModel);
}
public ActionResult LoadProductBasicDetails(string ProductId)
{
ProductViewModel viewModel;
if (!string.IsNullOrEmpty(ProductId) && !ProductId.Equals("0"))
{
var res = _productService.GetProduct(Convert.ToDecimal(ProductId));
res.AssocitedCustID = Convert.ToInt32(Session["AdminLoginID"]);
viewModel = AutoMapper.Mapper.Map<ProductEntity, ProductViewModel>(res);
if (viewModel.ProductUserGuide == null) { viewModel.ProductUserGuide = new ProductUserGuideViewModel(); }
}
else
{
viewModel = new ProductViewModel();
}
ViewBag.SubCategoryList = _subCategoryService.GetSubCategoryList();
return View("_AddEditProductBasicDetails", viewModel);
}
//public ActionResult SaveProduct(ProductViewModel model, HttpPostedFileBase file, HttpPostedFileBase Guidefile,HttpPostedFileBase Videofile, HttpPostedFileBase[] FaqVideo)
//{
// var res = AutoMapper.Mapper.Map<ProductViewModel, ProductEntity>(model);
// if (file != null)
// {
// res.ImageURL = UploadFileOnServer(ProductImagePath, file);
// }
// if (Guidefile != null)
// {
// res.ProductUserGuide.ImageURL = UploadFileOnServer(ProductImagePath, Guidefile);
// }
// if (Videofile != null)
// {
// res.ProductVideo.VideoURL = UploadFileOnServer(ProductImagePath, Videofile);
// }
// var isSuccess = _productService.AddOrUpdateProduct(res);
// return Json(isSuccess, JsonRequestBehavior.AllowGet);
//}
public ActionResult SaveProduct(ProductViewModel model, HttpPostedFileBase file)
{
//Session["ProductID"] = model.Id;
if (model.Id == 0)
{
var res = AutoMapper.Mapper.Map<ProductViewModel, ProductEntity>(model);
if (file != null)
{
res.ImageURL = UploadFileOnServer(ProductImagePath, file);
}
res.AssocitedCustID = Convert.ToInt32(Session["AdminLoginID"]);
var productId = _productService.AddUpdateProductBasic(res);
Session["ProductID"] = productId;
return Json(productId, JsonRequestBehavior.AllowGet);
}
else
{
var res = AutoMapper.Mapper.Map<ProductViewModel, ProductEntity>(model);
if (file != null)
{
res.ImageURL = UploadFileOnServer(ProductImagePath, file);
}
res.AssocitedCustID = Convert.ToInt32(Session["AdminLoginID"]);
var productId = _productService.AddUpdateProductBasic(res);
Session["ProductID"] = productId;
//return Json(productId, JsonRequestBehavior.AllowGet);
//return RedirectToAction("LoadProductUserGuide", Session["ProductID"]);
return RedirectToAction("AddEditProduct", "Product", new { ProductId = productId });
// return View("AddEditProduct", productId);
}
}
public ActionResult GetProductFAQ(string ProductId)
{
var product = _productService.GetProduct(Convert.ToDecimal(ProductId));
var viewModel = AutoMapper.Mapper.Map<ProductEntity, ProductViewModel>(product ?? new ProductEntity());
if (viewModel.ProductFAQs.Count == 0) { viewModel.ProductFAQs = new List<ProductFaqViewModel>(); }
return View("_ProductFAQ", viewModel);
}
public ActionResult SaveProductProductFAQ(ProductFaqViewModel model, string FaqId)
{
if (FaqId.ToString() == "0")
{
model.AssocitedCustID = Convert.ToInt32(Session["AdminLoginID"]);
model.Id = Convert.ToDecimal(FaqId);
var res = AutoMapper.Mapper.Map<ProductFaqViewModel, ProductFAQs>(model);
var productFaqId = _productService.SaveProductFAQ(res);
var productFaq = _productService.GetProductFAQ(productFaqId);
var viewModel = AutoMapper.Mapper.Map<ProductFAQs, ProductFaqViewModel>(productFaq);
if (viewModel == null) { viewModel = new ProductFaqViewModel(); }
return View("_ProductFAQForm", viewModel);
}
else
{
model.AssocitedCustID = Convert.ToInt32(Session["AdminLoginID"]);
model.Id = Convert.ToDecimal(FaqId);
var res = AutoMapper.Mapper.Map<ProductFaqViewModel, ProductFAQs>(model);
var productFaqId = _productService.SaveProductFAQ(res);
var productFaq = _productService.GetProductFAQ(productFaqId);
var viewModel = AutoMapper.Mapper.Map<ProductFAQs, ProductFaqViewModel>(productFaq);
if (viewModel == null) { viewModel = new ProductFaqViewModel(); }
return View("_ProductFAQForm", viewModel);
}
}
public ActionResult DeleteProductFAQ(string FaqId)
{
var res = _productService.DeleteProductFAQ(Convert.ToDecimal(FaqId));
return Json(res, JsonRequestBehavior.AllowGet);
}
public ActionResult AddEditFAQVideos(string FaqId)
{
var productFaq = _productService.GetProductFAQ(Convert.ToDecimal(FaqId));
ProductFaqViewModel viewModel = AutoMapper.Mapper.Map<ProductFAQs, ProductFaqViewModel>(productFaq);
if (viewModel != null)
{
var videos = AutoMapper.Mapper.Map<List<ProductFAQVideos>, List<ProductFAQVideoViewModel>>(productFaq.ProductFAQVideos.ToList());
videos.ForEach(x => x.VideoURL = x.VideoURL.Trim());
viewModel.ProductFAQVideoList = videos.Where(y => y.IsDeleted != true).ToList();
}
else
{
viewModel = new ProductFaqViewModel();
}
return View("_FAQVideos", viewModel);
}
private string UploadFileOnServer(string location, HttpPostedFileBase file)
{
string extension = Path.GetFileName(file.FileName);
// string fileId = Guid.NewGuid().ToString().Replace("-", "");
//string filename = fileId + extension;
var path = Path.Combine(Server.MapPath(location), extension);
file.SaveAs(path);
return extension;
}
public ActionResult GetSubCategoryList(string CategoryId)
{
var res = _subCategoryService.GetSubCategoryList(Convert.ToDecimal(CategoryId)).ToList();
var viewModel = AutoMapper.Mapper.Map<List<SubCategoryMaster>, List<DropDownViewModel>>(res);
return Json(viewModel, JsonRequestBehavior.AllowGet);
}
public ActionResult DeleteProduct(string Id)
{
var res = _productService.DeleteProduct(Convert.ToDecimal(Id));
return Json(true, JsonRequestBehavior.AllowGet);
}
public ActionResult SaveProductProductFAQVideo(ProductFAQVideoViewModel model, int FaqVideoId)
{
model.AssocitedCustID = Convert.ToInt32(Session["AdminLoginID"]);
//model.Id = FaqVideoId;
if(FaqVideoId ==0)
{
model.Id = FaqVideoId;
var res = AutoMapper.Mapper.Map<ProductFAQVideoViewModel, ProductFAQVideos>(model);
if (model.FAQVideo != null)
{
res.VideoURL = UploadFileOnServer(ProductImagePath, model.FAQVideo);
}
if (model.FAQVideoImg != null)
{
res.ImageURL = UploadFileOnServer(ProductImagePath, model.FAQVideoImg);
}
var productFaqVideoId = _productService.SaveProductFAQVideo(res);
var productFaqVideo = _productService.GetProductFAQVideo(productFaqVideoId);
var viewModel = AutoMapper.Mapper.Map<ProductFAQVideos, ProductFAQVideoViewModel>(productFaqVideo);
if (viewModel == null) { viewModel = new ProductFAQVideoViewModel(); }
return View("_FAQVideoForm", viewModel);
}
else
{
model.Id = FaqVideoId;
var res = AutoMapper.Mapper.Map<ProductFAQVideoViewModel, ProductFAQVideos>(model);
if (model.FAQVideo != null)
{
res.VideoURL = UploadFileOnServer(ProductImagePath, model.FAQVideo);
}
if (model.FAQVideoImg != null)
{
res.ImageURL = UploadFileOnServer(ProductImagePath, model.FAQVideoImg);
}
var productFaqVideoId = _productService.SaveProductFAQVideo(res);
var productFaqVideo = _productService.GetProductFAQVideo(productFaqVideoId);
var viewModel = AutoMapper.Mapper.Map<ProductFAQVideos, ProductFAQVideoViewModel>(productFaqVideo);
if (viewModel == null) { viewModel = new ProductFAQVideoViewModel(); }
return View("_FAQVideoForm", viewModel);
}
}
public ActionResult DeleteProductFAQVideo(int FaqVideoId)
{
var res = _productService.DeleteProductFAQVideo(FaqVideoId);
return Json(res, JsonRequestBehavior.AllowGet);
}
public ActionResult PlayVideo(string url)
{
return View("_PlayVideo", new VideoViewModel() { Url = url });
}
#region Specification
public ActionResult LoadProductSpecifiction(string ProductId)
{
var res = _productService.GetProductSpecification(Convert.ToDecimal(ProductId));
var viewModel = AutoMapper.Mapper.Map<ProductSpec, ProductSpecViewModel>(res);
if (viewModel == null) { viewModel = new ProductSpecViewModel(); }
return View("_ProductSpec", viewModel);
}
public ActionResult SaveProductSpecifiction(ProductSpecViewModel model, string SpecId)
{
if (SpecId.ToString() == "0")
{
model.AssocitedCustID = Convert.ToInt32(Session["AdminLoginID"]);
model.Id = Convert.ToDecimal(SpecId);
var viewModel = AutoMapper.Mapper.Map<ProductSpecViewModel, ProductSpec>(model);
var res = _productService.SaveProductSpecification(viewModel);
return Json(true, JsonRequestBehavior.AllowGet);
}
else
{
model.AssocitedCustID = Convert.ToInt32(Session["AdminLoginID"]);
model.Id = Convert.ToDecimal(SpecId);
var viewModel = AutoMapper.Mapper.Map<ProductSpecViewModel, ProductSpec>(model);
var res = _productService.SaveProductSpecification(viewModel);
return Json(true, JsonRequestBehavior.AllowGet);
}
}
#endregion Specification
#region User Guide
public ActionResult LoadProductUserGuide(string ProductId)
{
var res = _productService.GetProductUserGuide(Convert.ToDecimal(ProductId));
var viewModel = AutoMapper.Mapper.Map<ProductUserGuide, ProductUserGuideViewModel>(res);
if (viewModel == null)
{
viewModel = new ProductUserGuideViewModel();
}
return View("_ProductUserGuide", viewModel);
}
public JsonResult SaveProductUserGuide(ProductUserGuideViewModel model, string UserGuideId, HttpPostedFileBase file)
{
if (UserGuideId.ToString() == "0")
{
model.AssocitedCustID = Convert.ToInt32(Session["AdminLoginID"]);
model.Id = Convert.ToDecimal(UserGuideId);
if (model.Guidefile != null)
{
model.ImageURL = UploadFileOnServer(ProductImagePath, model.Guidefile);
}
//else if (IsDeletedImg)
//{
// model.ImageURL = "";
//}
var viewModel = AutoMapper.Mapper.Map<ProductUserGuideViewModel, ProductUserGuide>(model);
if (file != null)
{
viewModel.ImageURL = UploadFileOnServer(ProductImagePath, file);
}
var res = _productService.SaveProductUserGuide(viewModel);
return Json(true, JsonRequestBehavior.AllowGet);
}
else
{
model.AssocitedCustID = Convert.ToInt32(Session["AdminLoginID"]);
model.Id = Convert.ToDecimal(UserGuideId);
if (model.Guidefile != null)
{
model.ImageURL = UploadFileOnServer(ProductImagePath, model.Guidefile);
}
//else if (IsDeletedImg)
//{
// model.ImageURL = "";
//}
var viewModel = AutoMapper.Mapper.Map<ProductUserGuideViewModel, ProductUserGuide>(model);
if (file != null)
{
viewModel.ImageURL = UploadFileOnServer(ProductImagePath, file);
}
var res = _productService.SaveProductUserGuide(viewModel);
//return RedirectToAction("LoadProductUserGuide",new { productId = Session["ProductID"] });
return Json(true, JsonRequestBehavior.AllowGet);
//return RedirectToAction("AddEditProduct", res);
// return RedirectToAction("_ProductUserGuide");
//return RedirectToAction("LoadProductUserGuide");
//return View("LoadProductUserGuide", res);
// return RedirectToAction("AddEditProduct", res);
//return RedirectToAction("SaveProductUserGuide", res);
}
}
#endregion Specification
#region Product Video
public ActionResult GetProductVideos(string ProductId)
{
var product = _productService.GetProduct(Convert.ToDecimal(ProductId));
var viewModel = AutoMapper.Mapper.Map<ProductEntity, ProductViewModel>(product ?? new ProductEntity());
if (viewModel.ProductVideos.Count == 0) { viewModel.ProductVideos = new List<ProductVideoViewModel>(); }
return View("_ProductVideos", viewModel);
}
public ActionResult SaveProductVideo(ProductVideoViewModel model, string ProductVideoId)
{
if(ProductVideoId == null)
{
return View();
}
else if (ProductVideoId.ToString() == "0")
{
model.AssocitedCustID = Convert.ToInt32(Session["AdminLoginID"]);
model.Id = Convert.ToDecimal(ProductVideoId);
var res = AutoMapper.Mapper.Map<ProductVideoViewModel, ProductVideos>(model);
if (model.ProductVideo != null)
{
res.VideoURL = UploadFileOnServer(ProductImagePath, model.ProductVideo);
}
if (model.ProductVideoImg != null)
{
res.ThumbnailURL = UploadFileOnServer(ProductImagePath, model.ProductVideoImg);
}
//model.isproductvideofiled = 1;
var productVideoId = _productService.SaveProductVideo(res);
//var productVideoRate = _productService.SaveProductVideoRate(res);
var productVideo = _productService.GetProductVideo(productVideoId);
var viewModel = AutoMapper.Mapper.Map<ProductVideos, ProductVideoViewModel>(productVideo);
if (viewModel == null) { viewModel = new ProductVideoViewModel(); }
return RedirectToAction("_ProductVideoForm", viewModel);
}
else
{
model.AssocitedCustID = Convert.ToInt32(Session["AdminLoginID"]);
model.Id = Convert.ToDecimal(ProductVideoId);
var res = AutoMapper.Mapper.Map<ProductVideoViewModel, ProductVideos>(model);
if (model.ProductVideo != null)
{
res.VideoURL = UploadFileOnServer(ProductImagePath, model.ProductVideo);
}
if (model.ProductVideoImg != null)
{
res.ThumbnailURL = UploadFileOnServer(ProductImagePath, model.ProductVideoImg);
}
var productVideoId = _productService.SaveProductVideo(res);
var productVideo = _productService.GetProductVideo(productVideoId);
var viewModel = AutoMapper.Mapper.Map<ProductVideos, ProductVideoViewModel>(productVideo);
if (viewModel == null) { viewModel = new ProductVideoViewModel(); }
return View("_ProductVideoForm", viewModel);
}
}
public ActionResult DeleteProductVideo(int ProductVideoId)
{
var res = _productService.DeleteProductVideo(Convert.ToDecimal(ProductVideoId));
return Json(res, JsonRequestBehavior.AllowGet);
}
#endregion
#region coursePreview start
public ActionResult LoadCouresPreview(string ProductId)
{
// var courseid = CourseID;
var res = _productService.GetCoursePrviewVideo(Convert.ToDecimal(ProductId));
var viewModel = Mapper.Map<CoursePreviewVideos, CoursePreviewViewModel>(res);
if (viewModel == null)
{
viewModel = new CoursePreviewViewModel();
}
//var viewModel = AutoMapper.Mapper.Map<ProductEntity, ProductViewModel>(product ?? new ProductEntity());
//if (viewModel.CoursePreviewViewModels.Count == 0)
//{
// viewModel.CoursePreviewViewModels = new List<CoursePreviewViewModel>();
//}
return View("_CoursePreviewVideoView", viewModel);
}
public JsonResult SaveoursepreviewVideos(CoursePreviewVideos model, string CourseVideoId)
{
if (CourseVideoId.ToString() == "0")
{
model.AssocitedCustID = Convert.ToInt32(Session["AdminLoginID"]);
model.PreviewID = Convert.ToDecimal(CourseVideoId);
if (model.CoursePreviewVideo != null)
{
model.VideoURL = UploadFileOnServer(ProductImagePath, model.CoursePreviewVideo);
}
//else if (IsDeletedImg)
//{
// model.ImageURL = "";
//}
//var viewModel = Mapper.Map<CoursePreviewViewModel, CoursePreviewVideos>(model);
var res = _productService.SaveCoursePreviewVideo(model);
return Json(res, JsonRequestBehavior.AllowGet);
}
else
{
model.AssocitedCustID = Convert.ToInt32(Session["AdminLoginID"]);
model.PreviewID = Convert.ToDecimal(CourseVideoId);
if (model.CoursePreviewVideo != null)
{
model.VideoURL = UploadFileOnServer(ProductImagePath, model.CoursePreviewVideo);
}
//var viewModel = Mapper.Map<CoursePreviewViewModel, CoursePreviewVideos>(model);
var res = _productService.SaveCoursePreviewVideo(model);
return Json(res, JsonRequestBehavior.AllowGet);
}
}
public ActionResult DeletePreviewVideo(int CourseVideoId)
{
var res = _productService.DeleteProductVideo(Convert.ToDecimal(CourseVideoId));
return Json(res, JsonRequestBehavior.AllowGet);
}
#endregion course preview
#region Product Document
public ActionResult GetProductDocuments(string ProductId)
{
var product = _productService.GetProduct(Convert.ToDecimal(ProductId));
var viewModel = AutoMapper.Mapper.Map<ProductEntity, ProductViewModel>(product ?? new ProductEntity());
if (viewModel.ProductDocuments.Count == 0) { viewModel.ProductDocuments = new List<ProductDocumentViewModel>(); }
return View("_ProductDocument", viewModel);
}
public ActionResult SaveProductDocument(ProductDocumentViewModel model, Decimal ProductDocumentId)
{
if (ProductDocumentId.ToString() == "0")
{
model.AssocitedCustID = Convert.ToInt32(Session["AdminLoginID"]);
model.Id = Convert.ToDecimal(ProductDocumentId);
var res = AutoMapper.Mapper.Map<ProductDocumentViewModel, ProductDocuments>(model);
if (model.ProductDocumentFile != null)
{
res.DocumentURL = UploadFileOnServer(ProductImagePath, model.ProductDocumentFile);
}
var productDoctId = _productService.SaveProductDocument(res);
var productDoc = _productService.GetProductDocument(productDoctId);
var viewModel = AutoMapper.Mapper.Map<ProductDocuments, ProductDocumentViewModel>(productDoc);
if (viewModel == null) { viewModel = new ProductDocumentViewModel(); }
return View("_ProductDocumentForm", viewModel);
}
else
{
model.AssocitedCustID = Convert.ToInt32(Session["AdminLoginID"]);
model.Id = Convert.ToDecimal(ProductDocumentId);
var res = AutoMapper.Mapper.Map<ProductDocumentViewModel, ProductDocuments>(model);
if (model.ProductDocumentFile != null)
{
res.DocumentURL = UploadFileOnServer(ProductImagePath, model.ProductDocumentFile);
}
var productDoctId = _productService.SaveProductDocument(res);
var productDoc = _productService.GetProductDocument(productDoctId);
var viewModel = AutoMapper.Mapper.Map<ProductDocuments, ProductDocumentViewModel>(productDoc);
if (viewModel == null) { viewModel = new ProductDocumentViewModel(); }
return View("_ProductDocumentForm", viewModel);
}
}
public ActionResult DeleteProductDocument(string ProductDocumentId)
{
var res = _productService.DeleteProductDocument(Convert.ToDecimal(ProductDocumentId));
return Json(res, JsonRequestBehavior.AllowGet);
}
#endregion
}
} |
namespace Funding.Data.Models
{
public class Backers
{
public string UserId { get; set; }
public User User { get; set; }
public int ProjectId { get; set; }
public Project Project { get; set; }
}
} |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using PingoSnake.Code.Engine;
using PingoSnake.Code.Entities;
using PingoSnake.Code.GUI;
using PingoSnake.Code.LoadingScreens;
using PingoSnake.Code.SpawnControllers;
using System;
using System.Collections.Generic;
using System.Text;
namespace PingoSnake.Code.Scenes
{
class MainLevel : Scene
{
public override void LoadTextures()
{
base.LoadTextures();
this.AddTexture("ice_background_1", newName: "ice_background");
this.AddTexture("ice_tile_platform_1", newName: "ice_platform");
this.AddTexture("running_penguin_with_duck_1_cropped", newName: "penguin");
this.AddTexture("walrus_1", newName: "walrus");
this.AddTexture("seagule2", newName: "seagull");
this.AddTexture("good_neighbors_32", newName: "spritefont32");
this.AddTexture("good_neighbors_64", newName: "spritefont64");
//this.AddTexture("good_neighbors_128", newName: "spritefont128");
this.AddTexture("snake_v2", newName: "snake");
this.AddTexture("snake_v3", newName: "snake3");
this.AddTexture("snake_v4", newName: "snake4");
this.AddTexture("snake_v5", newName: "snake5");
this.AddTexture("snake_v6", newName: "snake6");
this.AddTexture("snake_v7", newName: "snake7");
this.AddTexture("food20", newName: "food");
//this.AddTexture("dirt_background", newName: "dirt_background");
this.AddTexture("dirt_background1", newName: "dirt_background");
this.AddTexture("divideLine1", newName: "divide_line");
}
public override void LoadSounds()
{
base.LoadSounds();
AddSong("mainTheme", "main_theme");
foreach (KeyValuePair<string, string> soundEffect in Penguin.requestedSoundEffects())
{
AddSoundEffect(soundEffect.Key, soundEffect.Value);
}
AddSoundEffect("eat1", "eat");
AddSoundEffect("dizzy", "dizzy");
}
public override LoadingScreen GetLoadingScreen(Scene scene)
{
return new MainLoadingScreen(scene);
}
/*public override LoadingScreen GetLoadingScreen()
{
return new MainLoadingScreen();
}*/
public override void Initialize()
{
base.Initialize();
int floor_pos_y = this.GetWindowHeight() - 128;
IceBackground background = new IceBackground(new Vector2(0, -800));
this.AddEntity(background);
IcePlatform platform = new IcePlatform(new Vector2(0, floor_pos_y));
this.AddEntity(platform);
Penguin penguin = new Penguin(new Vector2(300, floor_pos_y - 128));
this.AddEntity(penguin);
SnakeBackground snakeBackground = new SnakeBackground(new Vector2(GetWindowWidth() / 2, 0));
AddEntity(snakeBackground);
DivideLine divideLine = new DivideLine(new Vector2(GetWindowWidth() / 2 - 10, 0));
AddEntity(divideLine);
Snake snake = new Snake(new Vector2(400, floor_pos_y - 128), new Vector2(GetWindowWidth()/2 + 10, 0), new Rectangle(0, 0, (GetWindowWidth() / 2)-10, GetWindowHeight()));
AddEntity(snake);
GameGUI gameGUI = new GameGUI();
AddEntity(gameGUI);
Vector2 spawnPoint = new Vector2((int)penguin.GetPosition().X + this.GetWindowWidth(), floor_pos_y - 64);
GameState.Instance.SetVar<int>("floor_pos_y", floor_pos_y);
GameState.Instance.SetVar<Penguin>("penguin", penguin);
GameState.Instance.SetVar<Vector2>("spawn_point", spawnPoint);
GameState.Instance.SetVar<bool>("game_over", false);
GameState.Instance.SetVar<double>("score", 0);
//this.Camera.SetScreenOffset(0.18, 0.83);
this.Camera.SetScreenOffset(0.10, 0.83);
this.Camera.FollowOnlyXAxis();
this.Camera.FollowEntity(penguin);
EnemySpawnController enemySpawnController = new EnemySpawnController();
AddSpawnController(enemySpawnController);
PlaySong("main_theme");
}
public void CheckKeyboard()
{
KeyboardState keyState = Keyboard.GetState();
KeyboardState prevKeyState = GameState.Instance.GetPrevKeyboardState();
if (keyState.IsKeyDown(Keys.P) && !prevKeyState.IsKeyDown(Keys.P))
{
if (!GameState.Instance.GetVar<bool>("game_over"))
TogglePause();
}
if (keyState.IsKeyDown(Keys.Enter) && !prevKeyState.IsKeyDown(Keys.Enter))
{
if (GameState.Instance.GetVar<bool>("game_over"))
GameState.Instance.SetScene(new MainLevel());
}
if (keyState.IsKeyDown(Keys.Escape) && !prevKeyState.IsKeyDown(Keys.Escape))
{
StopSong();
GameState.Instance.SetScene(new MainMenu());
}
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
CheckKeyboard();
}
}
}
|
// //-----------------------------------------------------------------------------
// // <copyright file="FileStrategy.cs" company="DCOM Engineering, LLC">
// // Copyright (c) DCOM Engineering, LLC. All rights reserved.
// // </copyright>
// //-----------------------------------------------------------------------------
namespace NET_GC
{
using System;
using System.IO;
public abstract class FileStrategy : Strategy
{
public string FilePath { get; } = Path.Combine(Environment.CurrentDirectory, @"Sample.tif");
}
} |
using System;
namespace Bus
{
class Program
{
static void Main(string[] args)
{
int initialPassengers = int.Parse(Console.ReadLine());
int numberOfStops = int.Parse(Console.ReadLine());
for (int stopNumber = 1; stopNumber <= numberOfStops; stopNumber++)
{
int goingPassengers = int.Parse(Console.ReadLine());
int comingPassengers = int.Parse(Console.ReadLine());
if (stopNumber % 2 == 0)
{
initialPassengers = initialPassengers - goingPassengers + comingPassengers - 2;
}
else
{
initialPassengers = initialPassengers - goingPassengers + comingPassengers + 2;
}
}
Console.WriteLine($"The final number of passengers is : {initialPassengers}");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Technical.Utilities.Environment;
namespace Manor.ConnectionStrings.DbTypes
{
public class DatabaseModeValidator
{
private readonly ESourceMode _sourceMode = ESourceMode.Undefined;
public ESourceMode SourceMode
{
get { return _sourceMode; }
}
public DatabaseModeValidator()
{
if (MenuServer.SourceModeExists()) _sourceMode = MenuServer.SourceMode();
}
public DatabaseModeValidator(ESourceMode sourceMode)
{
_sourceMode = sourceMode;
}
public List<EDatabaseMode> GetAllowedDatabaseModes()
{
var databaseModes = new List<EDatabaseMode>();
var enumValues = Enum.GetValues(typeof (EDatabaseMode));
foreach (var enumValue in enumValues)
{
var databaseMode = ((EDatabaseMode) enumValue);
var allowedSourceModes = databaseMode.GetAttributesOfType<AllowedSourceModeAttribute>();
databaseModes.AddRange(from allowedSourceMode in allowedSourceModes
where allowedSourceMode.SourceMode == _sourceMode
select databaseMode);
}
return databaseModes;
}
public bool IsAllowed(EDatabaseMode databaseMode)
{
return GetAllowedDatabaseModes().Exists(mode => mode == databaseMode);
}
}
} |
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections.Generic;
using TMPro;
public class LevelSelectManager : MonoBehaviour
{
// instance
public static LevelSelectManager instance;
// UI
[Header("UI")]
public Canvas mainCanvas;
public RectTransform mainCanvasRectTransform;
public RectTransform locationArrowRectTransform;
public Image locationArrowBackImage;
public Image locationArrowFrontImage;
public Image playerHealthImage;
public Text playerHealthText;
public Image coinsCollectedImage;
public TextMeshProUGUI coinsCollectedText;
public Image tearsCollectedImage;
public TextMeshProUGUI tearsCollectedText;
int locationArrowFlickerIndex, locationArrowFlickerRate, locationArrowFlickerCounter;
public Image levelSelectInfoBackImage;
public TextMeshProUGUI levelSelectInfoText;
public Image proceedBackImage;
public TextMeshProUGUI proceedText;
// overlay
[Header("overlay")]
public MeshRenderer overlayMeshRenderer;
public Color overlayColShow, overlayColHide;
Color overlayColCur;
// locations
public List<List<LocationSlot>> locationSlots;
public List<LocationSlot.PositionType> positionTypes;
// state
[HideInInspector] public bool leaving;
public int locationSelectIndex;
[HideInInspector] public int locationCanSwitchDur, locationCanSwitchCounter;
[HideInInspector] public SetupManager.LocationType lastLocationTypeSelected;
void Awake ()
{
instance = this;
}
void Start ()
{
// get data from run
switch (SetupManager.instance.curRunType)
{
case SetupManager.RunType.Normal:
SaveManager.instance.GetLastLevelData(ref SetupManager.instance.curProgressData.normalRunData);
SetupManager.instance.curProgressData.normalRunData.curLevelCoinsCollected = 0;
SetupManager.instance.curProgressData.normalRunData.curLevelTearsCollected = 0;
SetupManager.instance.curProgressData.normalRunData.playerReachedEnd = false;
break;
case SetupManager.RunType.Endless:
SaveManager.instance.GetLastLevelData(ref SetupManager.instance.curProgressData.endlessRunData);
SetupManager.instance.curProgressData.endlessRunData.curLevelCoinsCollected = 0;
SetupManager.instance.curProgressData.endlessRunData.curLevelTearsCollected = 0;
SetupManager.instance.curProgressData.endlessRunData.playerReachedEnd = false;
break;
}
// state
leaving = false;
// overlay
overlayColCur = overlayColHide;
// transition out!
SetupManager.instance.InitStartTransition();
// location arrow flicker behaviour
locationArrowFlickerIndex = 0;
locationArrowFlickerRate = 16;
locationArrowFlickerCounter = 0;
locationSelectIndex = 0;
// create level select objects
CreateLevelSelectObjects();
}
void CreateLevelSelectObjects ()
{
// create objects
locationSlots = new List<List<LocationSlot>>();
positionTypes = new List<LocationSlot.PositionType>();
for (int i = 0; i < SetupManager.instance.runDataRead.curFloorData.locationCount; i++)
{
locationSlots.Add(new List<LocationSlot>());
for (int ii = 0; ii < SetupManager.instance.runDataRead.curFloorData.locationTypes[i].types.Count; ii++)
{
GameObject newLocationSlotO = PrefabManager.instance.SpawnPrefabAsGameObject(PrefabManager.instance.locationSlotPrefab[0], Vector3.zero, Quaternion.identity, 1f);
Transform newLocationSlotTr = newLocationSlotO.transform;
newLocationSlotTr.parent = mainCanvasRectTransform;
BasicFunctions.ResetTransform(newLocationSlotTr);
RectTransform rTr = newLocationSlotO.GetComponent<RectTransform>();
rTr.localScale = Vector3.one;
LocationSlot newLocationSlotScript = newLocationSlotO.GetComponent<LocationSlot>();
newLocationSlotScript.locationIndex = i;
newLocationSlotScript.locationSubIndex = ii;
newLocationSlotScript.myLocationType = (SetupManager.LocationType)(SetupManager.instance.runDataRead.curFloorData.locationTypes[i].types[ii]);
int locationTypeCount = SetupManager.instance.runDataRead.curFloorData.locationTypes[i].types.Count;
if ( locationTypeCount <= 1 )
{
newLocationSlotScript.SetPositionType(LocationSlot.PositionType.Center);
}
else
{
newLocationSlotScript.SetPositionType((ii == 0) ? LocationSlot.PositionType.Top : LocationSlot.PositionType.Bottom);
}
//if ( i == 0 )
//{
// positionTypes.Add(newLocationSlotScript.myPositionType);
//}
locationSlots[i].Add(newLocationSlotScript);
}
}
}
void Update ()
{
// player health text?
bool showPlayerHealth = (!SetupManager.instance.paused && !SetupManager.instance.inFreeze && !SetupManager.instance.inTransition && (SetupManager.instance.runDataRead.curLevelIndex > 0 || SetupManager.instance.runDataRead.curFloorIndex > 1));
if ( playerHealthImage != null && playerHealthText != null )
{
playerHealthImage.enabled = showPlayerHealth;
playerHealthText.enabled = showPlayerHealth;
if (showPlayerHealth)
{
playerHealthText.text = SetupManager.instance.runDataRead.playerHealthCur.ToString();
}
}
// overlay?
if (overlayMeshRenderer != null)
{
Color overlayColTarget = overlayColHide;
float overlayColLerpie = 1.25f;
if (!leaving && !SetupManager.instance.inTransition)
{
overlayColTarget = overlayColShow;
}
else
{
overlayColLerpie = 10f;
}
overlayColCur = Color.Lerp(overlayColCur, overlayColTarget, overlayColLerpie * Time.deltaTime);
overlayMeshRenderer.material.SetColor("_BaseColor", overlayColCur);
}
// handle behaviour for possible options
if (!leaving)
{
int locationCount = SetupManager.instance.runDataRead.curFloorData.locationCount;
//float hOff = 550f;//840f;
//float hAdd = (hOff / (float)(locationCount));
//float hStart = (-(float)(locationCount / 2) * (hOff * 1f));
float hAddSingle = 130f;
float hAddDual = 75f;
float hAddTotal = 0f;// (hAddSingle * 4) + (hAddDual * 4);
for ( int i = 0; i < SetupManager.instance.runDataRead.curFloorData.locationCount; i ++ )
{
if (i < (locationCount - 1))
{
if (SetupManager.instance.runDataRead.curFloorData.locationTypes[i + 1].types.Count > 1 || SetupManager.instance.runDataRead.curFloorData.locationTypes[i].types.Count > 1)
{
hAddTotal += hAddDual;
}
else
{
hAddTotal += hAddSingle;
}
}
}
float hStart = -(hAddTotal / 2); //-420f;
float hAdded = 0f;
for (int i = 0; i < locationCount; i++)
{
bool showLocationSlot = (!SetupManager.instance.paused);
float iFloat = (float)(i);
//bool isSelected = (i == itemBrowseIndex);
//float hAdd = (SetupManager.instance.curProgressData.curFloorData.locationTypes[i].Count > 1 && (i > 0 && SetupManager.instance.curProgressData.curFloorData.locationTypes[i - 1].Count > 1)) ? 20f : 130f;
float hAdd = hAddSingle;//130f;
if ( i < (locationCount - 1) )
{
if ( SetupManager.instance.runDataRead.curFloorData.locationTypes[i + 1].types.Count > 1 || SetupManager.instance.runDataRead.curFloorData.locationTypes[i].types.Count > 1)
{
hAdd = hAddDual;//75f;
}
}
// position
for (int ii = 0; ii < SetupManager.instance.runDataRead.curFloorData.locationTypes[i].types.Count; ii++)
{
Vector3 p = Vector3.zero;
p.x = hStart + hAdded;//(hAdd * iFloat);
p.y = 340f; //0f;
float yOff = 80f;
switch (locationSlots[i][ii].myPositionType)
{
case LocationSlot.PositionType.Top: p.y += yOff; break;
case LocationSlot.PositionType.Center: break;
case LocationSlot.PositionType.Bottom: p.y -= yOff; break;
}
locationSlots[i][ii].myRectTransform.anchoredPosition = p;
locationSlots[i][ii].SetVisible(showLocationSlot);
}
hAdded += hAdd;
}
// location arrow
if ( locationArrowFlickerCounter < locationArrowFlickerRate )
{
locationArrowFlickerCounter++;
}
else
{
locationArrowFlickerCounter = 0;
locationArrowFlickerIndex = (locationArrowFlickerIndex == 0) ? 1 : 0;
}
if (locationArrowRectTransform != null)
{
Vector3 arrowP = locationSlots[0][0].myRectTransform.anchoredPosition;
//Debug.Log("locationSlots: " + locationSlots.Count.ToString() + " || " + "level index: " + SetupManager.instance.runDataRead.curLevelIndex.ToString() + " || " + " locationSlot count: " + locationSlots[0].Count.ToString() + " || " + Time.time.ToString());
LocationSlot curSlot = locationSlots[SetupManager.instance.runDataRead.curLevelIndex][0];
//Debug.Log("curSlot: " + curSlot + " || rectTransform: " + curSlot.myRectTransform + " || " + Time.time.ToString());
arrowP.x = curSlot.myRectTransform.anchoredPosition.x;
arrowP.y -= 140f;
locationArrowRectTransform.anchoredPosition = arrowP;
bool showLocationArrow = (locationArrowFlickerIndex == 1 && !SetupManager.instance.paused && !SetupManager.instance.inTransition);
locationArrowFrontImage.enabled = showLocationArrow;
locationArrowBackImage.enabled = showLocationArrow;
}
// move selection
if (locationCanSwitchCounter < locationCanSwitchDur)
{
locationCanSwitchCounter++;
}
else
{
float selectThreshold = .25f;
float vInput = InputManager.instance.moveDirection.y;
int minIndex = 0;
int maxIndex = (SetupManager.instance.runDataRead.curFloorData.locationTypes[SetupManager.instance.runDataRead.curLevelIndex].types.Count - 1);
if (locationSelectIndex < maxIndex && (vInput < -selectThreshold))
{
locationSelectIndex++;
locationCanSwitchCounter = 0;
// audio
SetupManager.instance.PlayUINavigateSound();
}
if (locationSelectIndex > minIndex && (vInput > selectThreshold))
{
locationSelectIndex--;
locationCanSwitchCounter = 0;
// audio
SetupManager.instance.PlayUINavigateSound();
}
}
}
// level select info
if ( levelSelectInfoBackImage != null )
{
bool showLevelSelectInfo = (!leaving && !SetupManager.instance.paused && !SetupManager.instance.inTransition );
string levelSelectInfoString = "";
if (SetupManager.instance.curRunType == SetupManager.RunType.Endless)
{
levelSelectInfoString += "loop " + SetupManager.instance.runDataRead.curLoopIndex.ToString() + " ";
}
switch (SetupManager.instance.runDataRead.curFloorIndex)
{
case 1: levelSelectInfoString += "sewer"; break;
case 2: levelSelectInfoString += "dungeon"; break;
case 3: levelSelectInfoString += "hell"; break;
}
levelSelectInfoString += " " + (SetupManager.instance.runDataRead.curLevelIndex + 1).ToString();
levelSelectInfoString += "\n";
switch ( (SetupManager.LocationType)(SetupManager.instance.runDataRead.curFloorData.locationTypes[SetupManager.instance.runDataRead.curLevelIndex].types[locationSelectIndex]) )
{
case SetupManager.LocationType.Level: levelSelectInfoString += "encounter"; break;
case SetupManager.LocationType.BossLevel: levelSelectInfoString += "boss"; break;
case SetupManager.LocationType.Shop: levelSelectInfoString += "shop"; break;
case SetupManager.LocationType.Fountain: levelSelectInfoString += "fountain"; break;
case SetupManager.LocationType.Rest: levelSelectInfoString += "rest"; break;
}
levelSelectInfoText.text = levelSelectInfoString;
levelSelectInfoBackImage.enabled = false;
levelSelectInfoText.enabled = showLevelSelectInfo;
}
// coins & tears
if ( coinsCollectedImage != null )
{
bool showCoinsCollected = (!leaving && !SetupManager.instance.paused && !SetupManager.instance.inTransition && (SetupManager.instance.runDataRead.curLevelIndex > 0 || SetupManager.instance.runDataRead.curFloorIndex > 1));
coinsCollectedImage.enabled = showCoinsCollected;
coinsCollectedText.enabled = showCoinsCollected;
coinsCollectedText.text = SetupManager.instance.runDataRead.curRunCoinsCollected.ToString();
}
if (tearsCollectedImage != null)
{
bool showTearsCollected = (!leaving && !SetupManager.instance.paused && !SetupManager.instance.inTransition && (SetupManager.instance.runDataRead.curLevelIndex > 0 || SetupManager.instance.runDataRead.curFloorIndex > 1));
tearsCollectedImage.enabled = showTearsCollected;
tearsCollectedText.enabled = showTearsCollected;
tearsCollectedText.text = SetupManager.instance.runDataRead.curRunTearsCollected.ToString();
}
// proceed
if (proceedBackImage != null)
{
bool showProceed = (!leaving && !SetupManager.instance.paused && !SetupManager.instance.inTransition);
string proceedString = SetupManager.instance.UIInteractionButtonCol + InputManager.instance.interactInputStringUse + SetupManager.instance.UIInteractionBaseCol + " - SELECT";
proceedText.text = proceedString;
proceedBackImage.enabled = showProceed;
proceedText.enabled = showProceed;
// select a level/proceed?
if ( showProceed && !leaving )
{
if (SetupManager.instance.canInteract && InputManager.instance.interactPressed)
{
lastLocationTypeSelected = (SetupManager.LocationType)(SetupManager.instance.runDataRead.curFloorData.locationTypes[SetupManager.instance.runDataRead.curLevelIndex].types[locationSelectIndex]);
switch ( SetupManager.instance.curRunType )
{
case SetupManager.RunType.Normal:
SetupManager.instance.curProgressData.normalRunData.curFloorData.locationVisitedIndex[SetupManager.instance.runDataRead.curLevelIndex] = locationSelectIndex;
break;
case SetupManager.RunType.Endless:
SetupManager.instance.curProgressData.endlessRunData.curFloorData.locationVisitedIndex[SetupManager.instance.runDataRead.curLevelIndex] = locationSelectIndex;
break;
}
locationSelectIndex = 0;
Proceed();
leaving = true;
// audio
SetupManager.instance.PlayUILevelSelectSound();
}
}
}
}
public void Proceed ()
{
SetupManager.instance.SetTransition(SetupManager.TransitionMode.In);
Invoke("LoadNextLevel",SetupManager.instance.sceneLoadWait);
}
void LoadNextLevel ()
{
SetupManager.EncounterType encounterTypeTo = SetupManager.EncounterType.Small;
SetupManager.GameState gameStateSetTo = SetupManager.GameState.Level;
int sceneIndexLoad = 2;
switch (lastLocationTypeSelected)
{
case SetupManager.LocationType.Level:
gameStateSetTo = SetupManager.GameState.Level; sceneIndexLoad = 2;
encounterTypeTo = SetupManager.EncounterType.Small;
break;
case SetupManager.LocationType.BossLevel:
gameStateSetTo = SetupManager.GameState.Level;
sceneIndexLoad = 2;
encounterTypeTo = SetupManager.EncounterType.Boss;
break;
case SetupManager.LocationType.Shop: gameStateSetTo = SetupManager.GameState.Shop; sceneIndexLoad = 5; break;
case SetupManager.LocationType.Fountain: gameStateSetTo = SetupManager.GameState.Fountain; sceneIndexLoad = 4; break;
case SetupManager.LocationType.Rest: gameStateSetTo = SetupManager.GameState.Rest; sceneIndexLoad = 8; break;
}
if ( (SetupManager.instance.runDataRead.curLevelIndex + 1) >= (SetupManager.instance.runDataRead.curFloorData.locationCount) )
{
encounterTypeTo = SetupManager.EncounterType.Boss;
}
else
{
int encountersHadCheck = SetupManager.instance.runDataRead.encountersHad;
if (encountersHadCheck < 2)
{
encounterTypeTo = SetupManager.EncounterType.Small;
}
else if (encountersHadCheck >= 2 && encountersHadCheck < 4)
{
encounterTypeTo = SetupManager.EncounterType.Medium;
}
else if ( encountersHadCheck >= 4)
{
encounterTypeTo = SetupManager.EncounterType.Big;
}
}
SetupManager.instance.SetEncounterType(encounterTypeTo);
SetupManager.instance.SetGameState(gameStateSetTo);
SceneManager.LoadScene(sceneIndexLoad + 1,LoadSceneMode.Single);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace N26.Models
{
public class Currencycode
{
public string currencyCode { get; set; }
}
} |
using gView.Framework.Data.Filters;
using Oracle.ManagedDataAccess.Client;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace gView.Framework.Db
{
public enum DBType { odbc, oledb, sql, oracle, npgsql, unkonwn }
public enum dataType { integer, real, date, text, boolean, currency, unknown }
/// <summary>
/// Zusammenfassung für DBConnection.
/// </summary>
public class CommonDbConnection : ICommonDbConnection
{
protected string _connectionString = "", m_errMsg = "";
protected DBType _dbtype = DBType.oledb;
protected DataTable _schemaTable = null;
protected DbDataAdapter _updateAdapter = null;
protected SqlConnection _sqlConnection = null;
private Exception _lastException = null;
public CommonDbConnection()
{
}
public CommonDbConnection(string conn)
{
_connectionString = conn;
}
public void Dispose()
{
if (_updateAdapter != null)
{
_updateAdapter.Dispose();
_updateAdapter = null;
}
if (_schemaTable != null)
{
_schemaTable.Dispose();
_schemaTable = null;
}
GC.Collect(0);
}
public void CloseConnection()
{
if (_sqlConnection != null)
{
if (_sqlConnection.State != ConnectionState.Closed)
{
_sqlConnection.Close();
}
_sqlConnection.Dispose();
_sqlConnection = null;
}
}
public System.Data.Common.DbConnection OpenConnection()
{
try
{
CloseConnection();
switch (_dbtype)
{
case DBType.sql:
_sqlConnection = new SqlConnection(_connectionString);
_sqlConnection.Open();
return _sqlConnection;
}
return null;
}
catch (Exception ex)
{
try { CloseConnection(); }
catch { }
m_errMsg = ex.Message;
_lastException = ex;
return null;
}
}
public DbConnectionString DbConnectionString
{
set
{
if (value != null)
{
this.ConnectionString2 = value.ConnectionString;
}
}
}
public string ConnectionString2
{
set
{
if (value.ToLower().IndexOf("sql:") == 0 ||
value.ToLower().IndexOf("sqlclient:") == 0)
{
_connectionString = value.Substring(value.IndexOf(":") + 1, value.Length - value.IndexOf(":") - 1);
_dbtype = DBType.sql;
}
else if (value.ToLower().IndexOf("odbc:") == 0)
{
_connectionString = value.Substring(value.IndexOf(":") + 1, value.Length - value.IndexOf(":") - 1);
_dbtype = DBType.odbc;
}
else if (value.ToLower().IndexOf("oracle:") == 0 ||
value.ToLower().IndexOf("oracleclient:") == 0)
{
_connectionString = value.Substring(value.IndexOf(":") + 1, value.Length - value.IndexOf(":") - 1);
_dbtype = DBType.oracle;
}
else if (value.ToLower().IndexOf("npgsql:") == 0)
{
_connectionString = value.Substring(value.IndexOf(":") + 1, value.Length - value.IndexOf(":") - 1);
_dbtype = DBType.npgsql;
}
else
{
if (gView.Framework.system.Wow.Is64BitProcess)
{
_connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;Data Source=" + value;
}
else
{
_connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + value;
}
_dbtype = DBType.oledb;
}
}
}
public string ConnectionString
{
get { return _connectionString; }
set { _connectionString = value; }
}
public DBType dbType
{
get { return _dbtype; }
set { _dbtype = value; }
}
public string dbTypeString
{
get
{
return _dbtype.ToString();
}
set
{
switch (value.ToLower())
{
case "oledb": dbType = DBType.oledb; break;
case "odbc": dbType = DBType.odbc; break;
case "sql":
case "sqlserver": dbType = DBType.sql; break;
case "oracle": dbType = DBType.oracle; break;
}
}
}
public string errorMessage { get { return m_errMsg; } }
public Exception lastException { get { return _lastException; } }
async public Task<bool> SQLQuery(DataSet ds, string sql, string table, bool writeable)
{
if (!writeable)
{
return await SQLQuery(ds, sql, table);
}
if (_updateAdapter != null)
{
_updateAdapter.Dispose();
_updateAdapter = null;
}
try
{
switch (_dbtype)
{
case DBType.sql:
if (_updateAdapter == null)
{
_updateAdapter = new SqlDataAdapter(sql, _connectionString);
SqlCommandBuilder commBuilder3 = new SqlCommandBuilder((SqlDataAdapter)_updateAdapter);
commBuilder3.QuotePrefix = "[";
commBuilder3.QuoteSuffix = "]";
}
break;
case DBType.oracle:
if (_updateAdapter == null)
{
_updateAdapter = new OracleDataAdapter(sql, _connectionString);
OracleCommandBuilder commBuilder4 = new OracleCommandBuilder((OracleDataAdapter)_updateAdapter);
}
break;
case DBType.npgsql:
if (_updateAdapter == null)
{
DbProviderFactory dbfactory = DataProvider.PostgresProvider;
_updateAdapter = dbfactory.CreateDataAdapter();
// Command Builder brauchts auch... ?!
DbCommandBuilder cb = dbfactory.CreateCommandBuilder();
cb.DataAdapter = _updateAdapter;
DbCommand command = dbfactory.CreateCommand();
_updateAdapter.SelectCommand = command;
_updateAdapter.SelectCommand.CommandText = sql;
_updateAdapter.SelectCommand.Connection = dbfactory.CreateConnection();
_updateAdapter.SelectCommand.Connection.ConnectionString = _connectionString;
break;
}
break;
}
_updateAdapter.Fill(ds, table);
}
catch (Exception e)
{
if (_updateAdapter != null)
{
_updateAdapter.Dispose();
_updateAdapter = null;
}
m_errMsg = "QUERY WRITEABLE (" + sql + "): " + e.Message;
_lastException = e;
return false;
}
return true;
}
public bool Update(DataTable table)
{
try
{
_updateAdapter.Update(table);
_updateAdapter.Dispose();
_updateAdapter = null;
}
catch (Exception e)
{
if (_updateAdapter != null)
{
_updateAdapter.Dispose();
_updateAdapter = null;
}
m_errMsg = "UPDATE TABLE " + table + ": " + e.Message;
_lastException = e;
return false;
}
return true;
}
public bool UpdateData(ref DataSet ds, string table)
{
return Update(ds.Tables[table]);
}
public void ReleaseUpdateAdapter()
{
if (_updateAdapter != null)
{
_updateAdapter.Dispose();
_updateAdapter = null;
}
}
public DbDataAdapter UpdateAdapter { get { return _updateAdapter; } }
public Task<DataTable> Select(string fields, string from)
{
return Select(fields, from, "", "", false);
}
public Task<DataTable> Select(string fields, string from, string where)
{
return Select(fields, from, where, "", false);
}
public Task<DataTable> Select(string fields, string from, string where, string orderBy)
{
return Select(fields, from, where, orderBy, false);
}
async public Task<DataTable> Select(string fields, string from, string where, string orderBy, bool writeable)
{
DataSet ds = new DataSet();
string sql = "SELECT " + ((fields == "") ? "*" : fields)
+ " FROM " + from
+ ((where == "") ? "" : " WHERE " + where)
+ ((orderBy == "") ? "" : " ORDER BY " + orderBy);
if (!await SQLQuery(ds, sql, "TAB1", writeable))
{
return null;
}
return ds.Tables[0];
}
public Task<bool> SQLQuery(DataSet ds, string sql, string table)
{
DbDataAdapter adapter = null;
try
{
switch (_dbtype)
{
case DBType.sql:
adapter = new SqlDataAdapter(sql, _connectionString);
break;
case DBType.oracle:
adapter = new OracleDataAdapter(sql, _connectionString);
break;
case DBType.npgsql:
DbProviderFactory dbfactory = DataProvider.PostgresProvider;
adapter = dbfactory.CreateDataAdapter();
adapter.SelectCommand = dbfactory.CreateCommand();
adapter.SelectCommand.CommandText = sql;
adapter.SelectCommand.Connection = dbfactory.CreateConnection();
adapter.SelectCommand.Connection.ConnectionString = _connectionString;
break;
}
adapter.Fill(ds, table);
adapter.Dispose();
adapter = null;
}
catch (Exception e)
{
if (adapter != null)
{
adapter.Dispose();
}
m_errMsg = "QUERY (" + sql + "): " + e.Message;
_lastException = e;
return Task.FromResult(false);
}
return Task.FromResult(true);
}
async public Task<bool> SQLQuery(DataSet ds, string sql, string table, DataRow refRow)
{
string field = getFieldPlacehoder(sql);
while (field != "")
{
if (refRow[field] == null)
{
m_errMsg = "Field " + field + " not found in DataRow !!";
return false;
}
sql = sql.Replace("[" + field + "]", refRow[field].ToString());
field = getFieldPlacehoder(sql);
}
return await SQLQuery(ds, sql, table);
}
async public Task<bool> SQLQuery(string sql, XmlNode feature)
{
return await SQLQuery(sql, feature, true);
}
async public Task<bool> SQLQuery(string sql, XmlNode feature, bool one2n)
{
string field = getFieldPlacehoder(sql);
while (field != "")
{
string val = getFieldValue(feature, field);
if (val == "")
{
return false;
}
sql = sql.Replace("[" + field + "]", val);
field = getFieldPlacehoder(sql);
}
DataSet ds = new DataSet();
if (!await SQLQuery(ds, sql, "JOIN"))
{
return false;
}
if (ds.Tables["JOIN"].Rows.Count == 0)
{
return false;
}
DataRow row = ds.Tables["JOIN"].Rows[0];
XmlNodeList fields = feature.SelectNodes("FIELDS");
if (fields.Count == 0)
{
return false;
}
int rowCount = ds.Tables["JOIN"].Rows.Count;
XmlAttribute attr;
foreach (DataColumn col in ds.Tables["JOIN"].Columns)
{
XmlNode fieldNode = feature.OwnerDocument.CreateNode(XmlNodeType.Element, "FIELD", "");
attr = feature.OwnerDocument.CreateAttribute("name");
attr.Value = col.ColumnName;
fieldNode.Attributes.Append(attr);
attr = feature.OwnerDocument.CreateAttribute("value");
if (!one2n)
{
attr.Value = row[col.ColumnName].ToString();
}
else
{
StringBuilder sb = new StringBuilder();
sb.Append("<table width='100%' cellpadding='0' cellspacing='0' border='0'>");
int count = 1;
foreach (DataRow row2 in ds.Tables["JOIN"].Rows)
{
if (count < rowCount)
{
sb.Append("<tr><td nowrap style='border-bottom: gray 1px solid'>");
}
else
{
sb.Append("<tr><td nowrap>");
}
string val = row2[col.ColumnName].ToString().Trim();
if (val == "")
{
val = " ";
}
sb.Append(val + "</td></tr>");
count++;
}
sb.Append("</table>");
attr.Value = sb.ToString();
}
fieldNode.Attributes.Append(attr);
attr = feature.OwnerDocument.CreateAttribute("type");
attr.Value = "12";
fieldNode.Attributes.Append(attr);
fields[0].AppendChild(fieldNode);
}
return true;
}
async public Task<(DbDataReader reader, DbConnection connection)> DataReaderAsync(string sql)
{
DbDataReader reader = null;
DbConnection connection = null;
try
{
switch (_dbtype)
{
case DBType.sql:
connection = new SqlConnection(_connectionString);
SqlCommand sqlCommand = new SqlCommand(sql, (SqlConnection)connection);
await connection.OpenAsync();
return (await sqlCommand.ExecuteReaderAsync(), connection);
case DBType.oracle:
connection = new OracleConnection(_connectionString);
OracleCommand oracleCommand = new OracleCommand(sql, (OracleConnection)connection);
await connection.OpenAsync();
return (await oracleCommand.ExecuteReaderAsync(), connection);
case DBType.npgsql:
DbProviderFactory dbfactory = DataProvider.PostgresProvider;
connection = dbfactory.CreateConnection();
connection.ConnectionString = _connectionString;
DbCommand dbcommand = dbfactory.CreateCommand();
dbcommand.CommandText = sql;
dbcommand.Connection = connection;
await connection.OpenAsync();
return (await dbcommand.ExecuteReaderAsync(), connection);
}
return (null, null);
}
catch (Exception e)
{
if (connection != null)
{
connection.Dispose();
}
if (reader != null)
{
reader.Dispose();
}
connection = null;
m_errMsg = "QUERY (" + sql + "): " + e.Message;
_lastException = e;
return (null, null);
}
}
async public Task<object> QuerySingleField(string sql, string FieldName)
{
try
{
DataSet ds = new DataSet();
if (await SQLQuery(ds, sql, "FIELD"))
{
if (ds.Tables["FIELD"].Rows.Count > 0)
{
return ds.Tables["FIELD"].Rows[0][FieldName];
}
}
}
catch (Exception ex)
{
m_errMsg = ex.Message;
_lastException = ex;
}
return null;
}
protected string getFieldPlacehoder(string str)
{
int pos = str.IndexOf("[");
if (pos == -1)
{
return "";
}
int pos2 = str.IndexOf("]");
if (pos2 == -1)
{
return "";
}
return str.Substring(pos + 1, pos2 - pos - 1);
}
protected string getFieldValue(XmlNode feature, string name)
{
XmlNodeList fields = feature.SelectNodes("FIELDS/FIELD");
name = name.ToUpper();
foreach (XmlNode field in fields)
{
string fieldname = field.Attributes["name"].Value.ToString().ToUpper();
if (fieldname == name || shortName(fieldname).ToUpper() == name)
{
string val = field.Attributes["value"].Value.ToString();
return val;
}
}
return "";
}
protected string shortName(string name)
{
name.Trim();
int index = name.IndexOf(".");
while (index != -1)
{
name = name.Substring(index + 1, name.Length - index - 1);
index = name.IndexOf(".");
}
return name;
}
public bool createIndex(string name, string table, string field, bool unique)
{
return createIndex(name, table, field, unique, false);
}
public bool createIndex(string name, string table, string field, bool unique, bool grouped)
{
switch (_dbtype)
{
case DBType.sql:
return createIndexSql(name, table, field, unique, grouped);
case DBType.npgsql:
return createIndexNpgsql(name, table, field, unique, grouped);
}
return false;
}
private bool createIndexSql(string name, string table, string field, bool unique, bool grouped)
{
if (_dbtype != DBType.sql)
{
return false;
}
SqlConnection connection = null;
SqlCommand command = null;
try
{
connection = new SqlConnection(_connectionString);
connection.Open();
string sql = "CREATE " + (unique ? "UNIQUE " : "") + (grouped ? "CLUSTERED " : "NONCLUSTERED ") + "INDEX " + name + " ON " + table + " (" + field + ") WITH PAD_INDEX,FILLFACTOR=100;";
command = new SqlCommand(sql, connection);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
connection.Dispose();
}
catch (Exception e)
{
if (command != null)
{
command.Dispose();
}
if (connection != null)
{
connection.Close();
connection.Dispose();
}
m_errMsg = e.Message;
_lastException = e;
return false;
}
return true;
}
private bool createIndexNpgsql(string name, string table, string field, bool unique, bool grouped)
{
// CREATE INDEX fc_waterways_nid ON fc_waterways (fdb_nid);
// CREATE UNIQUE INDEX fc_waterways_id ON fc_waterways (fdb_oid);
// ALTER TABLE fc_waterways CLUSTER ON fc_waterways_id;
if (_dbtype != DBType.npgsql)
{
return false;
}
try
{
DbProviderFactory factory = DataProvider.PostgresProvider;
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = _connectionString;
connection.Open();
string sql1 = "CREATE " + (unique ? "UNIQUE" : "") + " INDEX \"" + name + "\" ON \"" + table + "\" (\"" + field + "\")";
string sql2 = grouped ? "ALTER TABLE \"" + table + "\" CLUSTER ON \"" + name + "\"" : String.Empty;
using (DbCommand command = factory.CreateCommand())
{
command.Connection = connection;
command.CommandText = sql1;
command.ExecuteNonQuery();
}
if (!String.IsNullOrEmpty(sql2))
{
using (DbCommand command = factory.CreateCommand())
{
command.Connection = connection;
command.CommandText = sql2;
command.ExecuteNonQuery();
}
}
}
}
catch (Exception e)
{
m_errMsg = e.Message;
_lastException = e;
return false;
}
return true;
}
public bool createTable(string name, string[] fields, string[] dataTypes)
{
switch (_dbtype)
{
case DBType.sql:
return createTableSql(name, fields, dataTypes);
case DBType.npgsql:
return createTableNpgsql(name, fields, dataTypes);
}
m_errMsg = "Not Implemented...";
return false;
}
public bool ExecuteNoneQuery(string sql)
{
switch (_dbtype)
{
case DBType.sql:
return ExecuteNoneQuerySql(sql);
case DBType.npgsql:
return ExecuteNoneQueryNpqsql(sql);
}
m_errMsg = "Not Implemented...";
return false;
}
private bool ExecuteNoneQuerySql(string sql)
{
if (_dbtype != DBType.sql)
{
return false;
}
SqlConnection connection = null;
SqlCommand command = null;
try
{
if (_sqlConnection == null)
{
connection = new SqlConnection(_connectionString);
connection.Open();
}
else
{
connection = _sqlConnection;
if (connection.State != ConnectionState.Open)
{
connection.Open();
}
}
command = new SqlCommand(sql, connection);
command.ExecuteNonQuery();
command.Dispose();
if (_sqlConnection == null)
{
connection.Close();
connection.Dispose();
}
}
catch (Exception e)
{
if (command != null)
{
command.Dispose();
}
if (connection != null)
{
connection.Close();
connection.Dispose();
}
m_errMsg = e.Message;
_lastException = e;
return false;
}
return true;
}
private bool ExecuteNoneQueryNpqsql(string sql)
{
if (_dbtype != DBType.npgsql)
{
return false;
}
try
{
DbProviderFactory factory = DataProvider.PostgresProvider;
using (DbConnection connection = factory.CreateConnection())
using (DbCommand command = factory.CreateCommand())
{
connection.ConnectionString = _connectionString;
connection.Open();
command.Connection = connection;
command.CommandText = sql;
command.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_errMsg = e.Message;
_lastException = e;
return false;
}
return true;
}
public bool RenameTable(string name, string newName)
{
switch (_dbtype)
{
case DBType.sql:
return ExecuteNoneQuerySql("sp_rename '" + name + "','" + newName + "'");
case DBType.npgsql:
if (!name.Contains("\""))
{
name = "\"" + name + "\"";
}
if (!newName.Contains("\""))
{
newName = "\"" + newName + "\"";
}
return ExecuteNoneQueryNpqsql("ALTER TABLE " + name + " RENAME TO " + newName);
}
m_errMsg = "Not Implemented...";
return false;
}
public bool dropIndex(string name)
{
switch (_dbtype)
{
case DBType.sql:
return dropIndexSql(name);
}
m_errMsg = "Not Implemented...";
return false;
}
private bool dropIndexSql(string name)
{
if (_dbtype != DBType.sql)
{
return false;
}
SqlConnection connection = null;
SqlCommand command = null;
try
{
connection = new SqlConnection(_connectionString);
connection.Open();
string sql = "DROP INDEX " + name + ";";
command = new SqlCommand(sql, connection);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
connection.Dispose();
}
catch (Exception e)
{
if (command != null)
{
command.Dispose();
}
if (connection != null)
{
connection.Close();
connection.Dispose();
}
m_errMsg = e.Message;
_lastException = e;
return false;
}
return true;
}
private bool createTableSql(string name, string[] fields, string[] dataTypes)
{
if (_dbtype != DBType.sql)
{
return false;
}
SqlConnection connection = null;
SqlCommand command = null;
try
{
connection = new SqlConnection(_connectionString);
connection.Open();
string sql = "CREATE TABLE [" + name + "] (";
for (int i = 0; i < fields.Length; i++)
{
string field = fields[i];
if (field == "KEY")
{
field = "KEY_";
}
if (field == "USER")
{
field = "USER_";
}
if (field == "TEXT")
{
field = "TEXT_";
}
sql += "[" + field + "] " + dataTypes[i];
if (i < (fields.Length - 1))
{
sql += ",";
}
}
sql += ") ON [PRIMARY]";
if (sql.IndexOf("[image]") != -1)
{
sql += " TEXTIMAGE_ON [PRIMARY]";
}
sql += ";";
command = new SqlCommand(sql, connection);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
connection.Dispose();
}
catch (Exception e)
{
if (command != null)
{
command.Dispose();
}
if (connection != null)
{
connection.Close();
connection.Dispose();
}
m_errMsg = e.Message;
_lastException = e;
return false;
}
return true;
}
private bool createTableNpgsql(string name, string[] fields, string[] dataTypes)
{
if (_dbtype != DBType.npgsql)
{
return false;
}
try
{
DbProviderFactory factory = DataProvider.PostgresProvider;
using (DbConnection connection = factory.CreateConnection())
using (DbCommand command = factory.CreateCommand())
{
string sql = "create table \"" + name + "\" (";
for (int i = 0; i < fields.Length; i++)
{
string field = fields[i];
sql += "\"" + field + "\" " + dataTypes[i];
if (i < (fields.Length - 1))
{
sql += ",";
}
}
sql += ") WITHOUT OIDS;";
connection.ConnectionString = _connectionString;
command.CommandText = sql;
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_errMsg = e.Message;
_lastException = e;
return false;
}
return true;
}
public bool dropTable(string name)
{
switch (_dbtype)
{
case DBType.sql:
return dropTableSql(name);
case DBType.npgsql:
return dropTableNpgsql(name);
}
m_errMsg = "Not Implemented...";
return false;
}
private bool dropTableSql(string name)
{
SqlConnection connection = null;
SqlCommand command = null;
try
{
connection = new SqlConnection(_connectionString);
connection.Open();
string sql = "DROP TABLE " + name + ";";
command = new SqlCommand(sql, connection);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
connection.Dispose();
}
catch (Exception e)
{
if (command != null)
{
command.Dispose();
}
if (connection != null)
{
connection.Close();
connection.Dispose();
}
m_errMsg = e.Message;
_lastException = e;
return false;
}
return true;
}
private bool dropTableNpgsql(string name)
{
try
{
DbProviderFactory factory = DataProvider.PostgresProvider;
using (DbConnection connection = factory.CreateConnection())
using (DbCommand command = factory.CreateCommand())
{
connection.ConnectionString = _connectionString;
command.CommandText = "drop table " + name;
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_errMsg = e.Message;
_lastException = e;
return false;
}
return true;
}
public bool GetSchema(string name)
{
try
{
switch (_dbtype)
{
case DBType.sql:
SqlConnection sqlconn = null;
SqlCommand sqlcomm = null;
SqlDataReader sqlreader = null;
using (sqlconn = new SqlConnection(_connectionString))
{
sqlconn.Open();
if (sqlconn.State == ConnectionState.Open)
{
sqlcomm = new SqlCommand("SELECT * FROM " + name, sqlconn);
sqlreader = sqlcomm.ExecuteReader(CommandBehavior.SchemaOnly);
_schemaTable = sqlreader.GetSchemaTable();
}
}
break;
case DBType.oracle:
OracleConnection oconn = null;
OracleCommand ocomm = null;
OracleDataReader oreader = null;
using (oconn = new OracleConnection(_connectionString))
{
oconn.Open();
if (oconn.State == ConnectionState.Open)
{
ocomm = new OracleCommand("SELECT * FROM " + name, oconn);
oreader = ocomm.ExecuteReader(CommandBehavior.SchemaOnly);
_schemaTable = oreader.GetSchemaTable();
}
}
break;
case DBType.npgsql:
DbProviderFactory dbfactory = DataProvider.PostgresProvider;
using (DbConnection dbconn = dbfactory.CreateConnection())
{
dbconn.ConnectionString = _connectionString;
dbconn.Open();
if (dbconn.State == ConnectionState.Open)
{
DbCommand dbcomm = dbfactory.CreateCommand();
dbcomm.Connection = dbconn;
if (!name.Contains("\""))
{
name = "\"" + name + "\"";
}
dbcomm.CommandText = "select * from " + name + " limit 0";
DbDataReader dbreader = dbcomm.ExecuteReader(CommandBehavior.SchemaOnly);
_schemaTable = dbreader.GetSchemaTable();
}
}
break;
}
}
catch (Exception e)
{
_schemaTable = null;
m_errMsg = e.Message;
_lastException = e;
return false;
}
return true;
}
public DataTable GetSchema2(string name)
{
DataTable schema = null;
try
{
switch (_dbtype)
{
case DBType.sql:
SqlConnection sqlconn = null;
SqlCommand sqlcomm = null;
SqlDataReader sqlreader = null;
using (sqlconn = new SqlConnection(_connectionString))
{
sqlconn.Open();
if (sqlconn.State == ConnectionState.Open)
{
sqlcomm = new SqlCommand("SELECT * FROM " + name, sqlconn);
sqlreader = sqlcomm.ExecuteReader(CommandBehavior.SchemaOnly);
schema = sqlreader.GetSchemaTable();
}
}
break;
case DBType.oracle:
OracleConnection oconn = null;
OracleCommand ocomm = null;
OracleDataReader oreader = null;
using (oconn = new OracleConnection(_connectionString))
{
oconn.Open();
if (oconn.State == ConnectionState.Open)
{
ocomm = new OracleCommand("SELECT * FROM " + name, oconn);
oreader = ocomm.ExecuteReader(CommandBehavior.SchemaOnly);
schema = oreader.GetSchemaTable();
}
}
break;
case DBType.npgsql:
DbProviderFactory dbfactory = DataProvider.PostgresProvider;
using (DbConnection dbconn = dbfactory.CreateConnection())
{
dbconn.ConnectionString = _connectionString;
dbconn.Open();
if (dbconn.State == ConnectionState.Open)
{
DbCommand dbcomm = dbfactory.CreateCommand();
dbcomm.Connection = dbconn;
if (!name.Contains("\""))
{
name = "\"" + name + "\"";
}
dbcomm.CommandText = "select * from " + name + " limit 0";
DbDataReader dbreader = dbcomm.ExecuteReader(CommandBehavior.SchemaOnly);
schema = dbreader.GetSchemaTable();
}
}
break;
}
}
catch (Exception e)
{
m_errMsg = e.Message;
_lastException = e;
return null;
}
return schema;
}
async public Task<bool> createTable(DataTable tab, bool data)
{
try
{
if (this.GetSchema(tab.TableName))
{
dropTable(tab.TableName);
}
string fields = "", dataTypes = "";
foreach (DataColumn col in tab.Columns)
{
if (fields != "")
{
fields += ";";
dataTypes += ";";
}
fields += col.ColumnName;
if (col.DataType == typeof(int))
{
dataTypes += "INTEGER";
}
else
{
dataTypes += "TEXT(50) WITH COMPRESSION";
}
}
if (createTable(tab.TableName, fields.Split(';'), dataTypes.Split(';')))
{
if (data)
{
DataSet ds = new DataSet();
string[] fields_ = fields.Split(';');
if (await this.SQLQuery(ds, "SELECT * FROM " + tab.TableName, tab.TableName, true))
{
foreach (DataRow row in tab.Rows)
{
DataRow newRow = ds.Tables[0].NewRow();
foreach (string field in fields_)
{
newRow[field] = row[field];
}
ds.Tables[0].Rows.Add(newRow);
}
if (!this.UpdateData(ref ds, tab.TableName))
{
return false;
}
}
else
{
return false;
}
}
return true;
}
else
{
return false;
}
}
catch (Exception e)
{
m_errMsg = e.Message;
_lastException = e;
return false;
}
//return true;
}
public dataType getFieldType(string fieldname)
{
if (_schemaTable == null)
{
return dataType.unknown;
}
DataRow[] row = _schemaTable.Select("ColumnName='" + fieldname + "'");
if (row.Length == 0)
{
return dataType.unknown;
}
if (row[0]["ProviderType"] == null)
{
return dataType.unknown;
}
int type = Convert.ToInt32(row[0]["ProviderType"]);
switch (Convert.ToInt32(row[0]["ProviderType"]))
{
case 3: return dataType.integer;
case 2: return dataType.boolean; // eigentlich Bit (ja/nein) bei SQL-Server
case 202: return dataType.text;
case 5: return dataType.real;
case 4: return dataType.date; // bei SQL-Server ???
case 7: return dataType.date;
case 6: return dataType.currency;
case 11: return dataType.boolean;
}
return dataType.text;
}
public int getFieldSize(string fieldname)
{
if (_schemaTable == null)
{
return 0;
}
DataRow[] row = _schemaTable.Select("ColumnName='" + fieldname + "'");
if (row.Length == 0)
{
return 0;
}
if (row[0]["ColumnSize"] == null)
{
return 0;
}
int len = Convert.ToInt32(row[0]["ColumnSize"]);
return len;
}
// Nur zum Testen...
public string schemaString
{
get
{
if (_schemaTable == null)
{
return "";
}
DataRow[] rows = _schemaTable.Select();
string ret = "";
foreach (DataRow row in rows)
{
ret += row["ColumnName"].ToString() + ": ProviderType=" + row["ProviderType"].ToString() + "\n";
}
return ret;
}
}
public DataTable schemaTable
{
get
{
return _schemaTable;
}
}
static public string providedDBTypes
{
get
{
return "Odbc,OleDb,Sql";
}
}
protected string mdbPath
{
get
{
if (_dbtype != DBType.oledb)
{
return "";
}
int pos1 = _connectionString.IndexOf("Data Source=");
if (pos1 == -1)
{
return "";
}
int pos2 = _connectionString.IndexOf(";", pos1);
if (pos2 == -1)
{
pos2 = _connectionString.Length - 1;
}
return _connectionString.Substring(pos1 + 12, pos2 - pos1 - 11);
}
}
public bool CompactAccessDB()
{
m_errMsg = "Not Implementet";
return false;
//
// gView.DB sollte sich im GAC befinden
// Darum keine Wrapper auf JRO,... einbinden...
//
/*
if(m_dbtype!=DBType.oledb) return false;
string target="C:\\tempdb"+System.Guid.NewGuid().ToString("N")+".mdb";
JRO.JetEngine engine=new JRO.JetEngineClass();
engine.CompactDatabase(m_connStr,"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+target+";Jet OLEDB:Engine Type=5");
System.IO.File.Delete(mdbPath);
System.IO.File.Move(target,mdbPath);
System.Runtime.InteropServices.Marshal.ReleaseComObject(engine);
engine=null;
return true;
* */
}
public string[] TableNames()
{
List<string> tableNames = new List<string>();
try
{
switch (dbType)
{
case DBType.sql:
using (SqlConnection connection = new SqlConnection(this.ConnectionString))
{
connection.Open();
DataTable tables = connection.GetSchema("Tables");
foreach (DataRow row in tables.Rows)
{
string schema = row["TABLE_SCHEMA"].ToString();
string table = string.IsNullOrEmpty(schema) ? row["TABLE_NAME"].ToString() : schema + "." + row["TABLE_NAME"].ToString();
tableNames.Add(table);
}
}
break;
case DBType.npgsql:
DbProviderFactory dbfactory = DataProvider.PostgresProvider;
using (DbConnection dbconnection = dbfactory.CreateConnection())
{
dbconnection.ConnectionString = this.ConnectionString;
DataTable tables3 = dbconnection.GetSchema("Tables");
foreach (DataRow row in tables3.Rows)
{
string schema = row["table_schema"].ToString();
string table = string.IsNullOrEmpty(schema) ? row["table_name"].ToString() : schema + "." + row["table_name"].ToString();
tableNames.Add(table);
}
}
break;
}
}
catch (Exception ex)
{
m_errMsg = ex.Message;
_lastException = ex;
}
return tableNames.ToArray();
}
public (string top, string limit) LimitResults(IQueryFilter filter, Data.IFeatureClass fc)
{
string top = String.Empty, limit = String.Empty;
switch (dbType)
{
case DBType.sql:
if (filter.Limit > 0)
{
if (String.IsNullOrEmpty(fc.IDFieldName) && String.IsNullOrWhiteSpace(filter.OrderBy))
{
top = " top(" + filter.Limit + ") ";
}
else
{
if (String.IsNullOrWhiteSpace(filter.OrderBy))
{
limit += " order by " + filter.fieldPrefix + fc.IDFieldName + filter.fieldPostfix;
}
limit += " offset " + Math.Max(0, filter.BeginRecord - 1) + " rows fetch next " + filter.Limit + " rows only";
}
}
break;
case DBType.npgsql:
if (filter.Limit > 0)
{
if (String.IsNullOrWhiteSpace(filter.OrderBy) && !String.IsNullOrWhiteSpace(fc.IDFieldName))
{
limit += " order by " + filter.fieldPrefix + fc.IDFieldName + filter.fieldPostfix;
}
limit += " limit " + filter.Limit;
if (filter.BeginRecord > 1) // Default in QueryFilter is one!!!
{
limit += " offset " + Math.Max(0, filter.BeginRecord - 1);
}
}
break;
}
return (top: top, limit: limit);
}
}
}
|
using Enviosbase.Data;
using Enviosbase.Model;
using System.Collections.Generic;
namespace Enviosbase.Business
{
public class ResponsableBusiness
{
public ResponsableModel Create(ResponsableModel item)
{
return new ResponsableDataMapper().Create(item);
}
public void Update(ResponsableModel item)
{
ResponsableDataMapper ResponsableDM = new ResponsableDataMapper();
ResponsableDM.Update(item);
}
public List<ResponsableModel> GetAll()
{
return new ResponsableDataMapper().GetAll();
}
public ResponsableModel GetById(int Id)
{
return new ResponsableDataMapper().GetById(Id);
}
public List<ResponsableModel> GetByPais(int IdPais)
{
return new ResponsableDataMapper().GetByPais(IdPais);
}
public List<ResponsableModel> GetByDepartamento(int IdDepto)
{
return new ResponsableDataMapper().GetByDepartamento(IdDepto);
}
public List<ResponsableModel> GetByMunicipio(int IdMunicipio)
{
return new ResponsableDataMapper().GetByMunicipio(IdMunicipio);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EventSound : MonoBehaviour {
public float duration;
AudioSource audioSource;
// Use this for initialization
void Start () {
audioSource = GetComponent<AudioSource>();
audioSource.spatialBlend = 1;
StartEventSound();
}
// Update is called once per frame
void Update () {
}
public void StartEventSound()
{
if (duration == 0)
audioSource.loop = false;
else
{
audioSource.loop = true;
StartCoroutine("StopSoundWithDelay");
}
audioSource.Play();
}
IEnumerator StopSoundWithDelay()
{
yield return new WaitForSeconds(duration);
audioSource.Stop();
}
}
|
using LoowooTech.Stock.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LoowooTech.Stock.Tool
{
public class ValueBaseTool2
{
public string ID { get; set; }
public string TableName { get; set; }
public string RelationName { get; set; }
public List<string> Messages { get; set; } = new List<string>();
public List<VillageMessage> Messages2 { get; set; } = new List<VillageMessage>();
public string Key { get; set; }
}
}
|
using ReactMusicStore.Core.Domain.Entities;
using ReactMusicStore.Services.Interfaces.Common;
namespace ReactMusicStore.Services.Interfaces
{
public interface IGenreAppService : IAppService<Genre>
{
Genre GetWithAlbums(string genreName);
}
}
|
using System.Windows;
namespace EpdSim
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
public App() : base()
{
this.Dispatcher.UnhandledException += OnDispatcherUnhandledException;
}
// unhandled exception handling for wpf applications
void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
string errorMessage = string.Format("An unhandled exception occurred: {0} \n\r\n\r STACKTRACE: {1} \n\r\n\r ERROR STRING: {2}",
e.Exception.Message, e.Exception.StackTrace, e.Exception.ToString());
MessageBox.Show(errorMessage, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
e.Handled = true;
}
}
}
|
//w3resource solution impelmentations of:
//Recursion #14 -- get the reverse of a string using recursion *
//String #2 -- find the length of a string without using library function *
//LINQ #9 -- create a list of numbers and display the numbers greater than 80 as output *
//Also messed around with the .foreach() extension and associated Action<> creation *
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
string input = "";
int length = 0;
List<int> numbers = new List<int> { 10, 23, 42, 17, 39, 100, 75, 84, 66, 175, 31, 200 };
Action<int> action = new Action<int>((n => Console.WriteLine(n * n)));
var over80 = numbers.FindAll(n => n > 80 ? true : false);
numbers.ForEach(action);
foreach(int i in numbers)
{
Console.Write($"{i}, ");
}
foreach(int i in over80)
{
Console.Write($"{i}, ");
}
while (true)
{
Console.Write("\nPlease enter a string: ");
input = Console.ReadLine();
if (input.Length > 0)
break;
else
Console.WriteLine("That is not a valid entry!");
}
input = Reverse(input);
Console.WriteLine($"The reverse of the string that you entered is: {input}");
foreach(char c in input)
{
length++;
}
Console.WriteLine($"The length of the string that you entered is: {length}");
Console.ReadKey();
}
public static string Reverse(string input)
{
if (input.Length > 0)
return input[input.Length - 1] + Reverse(input.Substring(0, input.Length - 1));
else
return input;
}
}
}
/*
//Array #4 -- copy the elements one array into another array *
//String #1 -- input a string and print it *
//String #2 -- find the length of a string without using library function *
//Function #8 -- create a function to display the n number Fibonacci sequence. *
//Recursion #14 -- get the reverse of a string using recursion *
//LINQ #9 -- create a list of numbers and display the numbers greater than 80 as output *
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using System.Threading;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
string input = "";
int fibCount = 0;
int[] fibArray;
int[] fibArray2;
int fibThreshold = 80;
while (input.Length < 1)
{
Console.Write("Please enter a string: ");
input = Console.ReadLine();
}
Console.WriteLine($"The string that you enterd contains - {Count(input)} - characters.");
Console.WriteLine($"\nThe reverse of the string that you entered is: \n\n");
Reverse(input);
while (true)
{
try
{
Console.Write("\n\n\nPlease enter the number of Fibonacci numbers that you would like to see: ");
fibCount = Convert.ToInt32(Console.ReadLine());
break;
}
catch
{
Console.WriteLine("That was not a valid entry!");
}
}
fibArray = new int[fibCount];
Fibonacci(fibCount, ref fibArray);
Console.WriteLine($"The numbers stored in fibArray are: {string.Join(", ", fibArray)}");
fibArray2 = fibArray; //copies number set from fib1 to fib2
Console.WriteLine("FibArray has been copied to fibArray2.");
fibArray = null; //purges fib2 to demonstrate data transfer
Console.WriteLine("FibArray has been purged.");
Console.WriteLine($"The numbers stored in fibArray2 are: {string.Join(", ", fibArray2)}");
try
{
Console.WriteLine($"The numbers stored in fibArray are: {string.Join(", ", fibArray)}");
}
catch
{
Console.WriteLine("fibArray could not be displayed due to null exception.");
}
var fibsOver80 = from fibs in fibArray2 where fibs > fibThreshold select fibs;
Console.WriteLine($"The fibonacci numbers greater than {fibThreshold} are: ");
foreach(var v in fibsOver80)
{
Console.WriteLine(v);
}
Console.ReadKey();
}
public static int Count(string input)
{
int count = 0;
while (input != null && input != input.Substring(0, 1))
{
input = input.Remove(0, 1);
++count;
}
return ++count;
}
public static void Reverse(string input)
{
if (Count(input) > 1)
{
Reverse(input.Remove(0, 1));
Console.Write($"{input.Substring(0, 1)}");
}
else
Console.Write(input);
}
public static void Fibonacci(int count, ref int[] fibArray, int fib1 = 0, int fib2 = 1 )
{
if(count > 0)
{
Console.WriteLine(fib1);
fibArray[fibArray.Length - count] = fib1;
Fibonacci(--count, ref fibArray, fib2, fib1 + fib2 );
}
}
}
}
/*
//File Handling #5 -- create a file with text and read the file
//Function #7 -- create a function to calculate the result of raising an integer number to another
//Struct #8 -- demonstrates struct initialization without using the new operator
//Recursion #13 -- convert a decimal number to binary using recursion
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using System.IO;
using System.Threading;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
Squared number;
int binaryNum = 0;
string fileName = @"test text.txt";
Console.Write("Please enter a number: ");
number.root = Convert.ToInt32(Console.ReadLine());
number.square = Square(number.root);
using (StreamWriter sw = new StreamWriter(File.Open(fileName, FileMode.Append, FileAccess.Write,FileShare.ReadWrite)))
{
sw.WriteLine($"The square of the number {number.root} is: {number.square}");
sw.WriteLine($"The number {number.root} in binary is: {ToBinary(number.root, ref binaryNum)}");
}
Console.WriteLine(Directory.GetCurrentDirectory());
using (StreamReader sr = File.OpenText(fileName))
{
Console.WriteLine(sr.ReadLine());
Console.WriteLine(sr.ReadLine());
}
Console.ReadKey();
}
public struct Squared
{
public int root;
public int square;
public Squared (int num)
{
root = num;
square = Square(num);
}
}
public static int Square (int num)
{
return num * num;
}
public static int ToBinary (int num, ref int bin)
{
if (num > 0)
bin += num % 2 + 10 * ToBinary(num / 2, ref bin);
return bin;
}
}
}
/*
//Function #6 -- create a function to swap the values of two integer numbers
//File Handling #4 -- create a file and add some text
//Struct #7 -- demonstrates struct initialization using both default and parameterized constructors.
//LINQ #8 -- find the string which starts and ends with a specific character
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
List<Word> wordList = new List<Word>();
int wordCount;
wordCount = GetCount();
FillList(wordList, wordCount);
string filePath = @"C:\Users\rloyd\source\repos\w3Resource Exercises\w3Resource Exercises\wordList.txt";
Stream fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
StreamWriter sw = new StreamWriter(fs);
foreach (Word w in wordList)
{
sw.WriteLine(w.ToString());
}
sw.Close();
fs.Close();
char starts = 'a';
char ends = 'e';
var thisWord = from word in wordList where word.startsWith == starts && word.endsWith == ends select word;
foreach(var v in thisWord)
{
Console.WriteLine(v.ToString());
}
Console.Write("Please enter a number: ");
int numInp1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter a number: ");
int numInp2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine($"First num: {numInp1} second num: {numInp2}");
Swap(ref numInp1, ref numInp2);
Console.WriteLine($"First num: {numInp1} second num: {numInp2}");
Console.ReadKey();
}
public struct Word
{
public string theWord;
public char startsWith;
public char endsWith;
public Word(char start = '-', char end = '-')
{
this.startsWith = start;
this.endsWith = end;
this.theWord = "--";
}
public Word (string word)
{
this.startsWith = word[0];
this.endsWith = word[word.Length - 1];
this.theWord = word;
}
public override string ToString()
{
return ($"\"{this.theWord}\" begins with \'{this.startsWith}\' and ends with \'{this.endsWith}\'");
}
}
public static int GetCount()
{
int Count = 0;
while (true)
{
try
{
Console.Write("Please enter the number of words (between 1 and 10) that you would like to log: ");
Count = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("That's not a valid entry!");
}
if (Count < 1 || Count > 10)
Console.WriteLine("The number must be between 1 and 10!");
else
return Count;
}
}
public static void FillList(List<Word> list, int count)
{
for (var i = count; i > 0; i--)
{
try
{
Console.Write($"Please enter word number {i}: ");
list.Add(new Word (Console.ReadLine()));
}
catch
{
Console.WriteLine("That's not a valid entry!");
++i;
}
}
}
public static void Swap(ref int num1, ref int num2)
{
Console.WriteLine($"Before swap the first number is: {num1} and the second number is: {num2}");
num1 = num1 * num2;
num2 = num1 / num2;
num1 = num1 / num2;
Console.WriteLine($"After swap the first number is: {num1} and the second number is: {num2}");
}
}
}
/*
//Function #5 -- calculate the sum of elements in an array
//Recursion #12 -- find the LCM and GCD of two numbers using recursion.
//LINQ #7 -- display numbers, multiplication of number with frequency and frequency of a number of giving array.
using System;
using System.Collections;
using System.Linq;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
int[] nums1;
int[] nums2;
int sum1;
int sum2;
Console.Write("Please enter the number of integers to store in each array: ");
nums1 = new int[Convert.ToInt32(Console.ReadLine())];
nums2 = new int[nums1.Length];
Console.Clear();
GetNums(nums1, "1st");
Console.Clear();
GetNums(nums2, "2nd");
Console.Clear();
sum1 = Sum(nums1, "1st");
sum2 = Sum(nums2, "2nd");
LCM(sum1, sum2, GCD(sum1, sum2));
Frequency(nums1, "1st");
Frequency(nums2, "2nd");
Console.ReadKey();
}
public static void GetNums(int[] nums, string place)
{
for(var i = 0; i < nums.Length; i++)
{
Console.WriteLine($"Okay, let's populate the {place} array!");
try
{
Console.Write($"Please enter the value for element {i} of the array: ");
nums[i] = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("That's not a valid entry!");
i--;
}
}
}
public static int Sum(int[] nums, string place)
{
int sum = 0;
for(var i = 0; i < nums.Length; i++)
{
sum += nums[i];
}
Console.WriteLine($"The sum of the numbers in the {place} array is: {sum}");
return sum;
}
public static int GCD(int num1, int num2, int numGCD = 1, int factor = 1)
{
if (num1 % factor == 0 && num2 % factor == 0)
numGCD = factor;
if (factor < num1 && factor < num2)
return GCD(num1, num2, numGCD, factor + 1);
else
Console.WriteLine($"The GCD of {num1} and {num2} is: {numGCD}");
return numGCD;
}
public static int[] Multiples(int num)
{
ArrayList multiples = new ArrayList();
for(var i = 1; i <= num/2; i++)
{
if (num % i == 0)
multiples.Add(i);
}
multiples.Add(num);
Console.WriteLine($"The multiples of {num} are: " + string.Join(", ", multiples.ToArray()));
return (int[])multiples.ToArray(typeof(int));
}
public static void LCM(int num1, int num2, int GCD)
{
Multiples(num1);
Multiples(num2);
Console.WriteLine($"The LCM of {num1} and {num2} is: {(num1*num2)/GCD}");
}
public static void Frequency(int[] nums, string place)
{
var numSet = from n in nums group n by n into y select y;
Console.WriteLine($"{place} Array:");
Console.WriteLine($"Number\t |\tFrequency\t|\tNumber*Frequency");
foreach(var v in numSet)
{
Console.WriteLine($" {v.Key}\t\t {v.Count()}\t\t\t\t{v.Sum()}");
}
}
}
}
/*
//Function #4 -- create a function to input a string and count number of spaces are in the string
using System;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter a string: ");
string input = Console.ReadLine();
Console.WriteLine($"The string that you entered contains {SpaceCount(input)} spaces.");
Console.ReadKey();
}
public static int SpaceCount(string str)
{
int count = 0;
for(var i = 0; i < str.Length; i++)
{
if (str[i] == ' ')
++count;
}
return count;
}
}
}
/*
//Function #3 -- create a function for the sum of two numbers
using System;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
int num1 = 0, num2 = 0;
num1 = GetNum(num1);
num2 = GetNum(num2);
Console.WriteLine(Add(ref num1, ref num2));
Console.ReadKey();
}
public static int GetNum(int num)
{
while(num == 0)
{
try
{
Console.Write("Please enter a number: ");
num = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("That's not a valid entry!");
}
}
return num;
}
public static T Add<T>(ref T param1, ref T param2)
{
var x = Expression.Parameter(typeof(T), "param1");
var y = Expression.Parameter(typeof(T), "param2");
BinaryExpression expression = Expression.Add(x, y);
Func<T, T, T> add = Expression.Lambda<Func<T, T, T>>(expression, x, y).Compile();
return add(param1, param2);
}
}
}
/*
//Recursion #11 -- generate all possible permutations of an array using recursion.
//LINQ #6 -- display the name of the days of a week.
//Date Time #11 -- add a number of whole and fractional values to a date and time.
//Function #2 -- create a user define function with parameters.
using System;
using System.Collections;
using System.Linq;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
string[] DaysOfWeek = { "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "staurday" };
ArrayList arrayList = new ArrayList();
int[] nums = { 1, 2, 3, 4 };
TimeSpan timeSpan = new TimeSpan(864000000000);
DateTime[] Dates = new DateTime[7];
for(var i = 0; i < Dates.Length; i++)
{
Dates[i] = DateTime.Now + MultiplyTime(i, timeSpan);
}
var weekdays = from days in Dates select days.DayOfWeek;
string[] stringDays = new string[Dates.Length];
int counts = 0;
foreach (var v in weekdays)
{
Console.WriteLine(v);
stringDays[counts] = v.ToString();
++counts;
}
Permute(ref nums, nums.Length-1, 6, 1, arrayList);
Console.WriteLine();
Console.WriteLine(arrayList.ToArray().Count());
var perms = arrayList.ToArray().Distinct(); //checks for unique permutations
int uniques = 0; //unique counter
foreach(var v in perms)
{
Console.WriteLine(v); ;
++uniques;
}
Console.WriteLine(perms.Count()); //result indicates that algorithm does not work for sets larger than 3.
Console.WriteLine($"\nTotal unique permutations: {uniques}");
Console.ReadKey();
}
public static TimeSpan MultiplyTime (int multiplier, TimeSpan timeSpan)
{
long product = 0;
for(var i = 0; i < multiplier; i++)
{
product += Convert.ToInt64(timeSpan.Ticks); //increments timespan by timespan as int64
}
TimeSpan timeSpanProduct = new TimeSpan(product);
return timeSpanProduct;
}
public static void Permute<T>(ref T[] array, int index, int permutations, int count, ArrayList arrayList)
{
T temp = array[index];
if (index + 1 == array.Length) //swaps last with first if swap position is at end of array
{
array[index] = array[0];
array[0] = temp;
}
else //swaps position with next, resulting in moving first backward through array
{
array[index] = array[index + 1];
array[index + 1] = temp;
}
Console.WriteLine();
Console.Write(count + " - ");
foreach (var v in array)
{
Console.Write(v + ", ");
}
arrayList.Add(string.Join(", ",array));
count++; //for confirming the number of permutations
if (index == 0) //resets index to end to continue permutations
{
--permutations;
index = array.Length;
}
if (permutations > 0 && index > -1)
Permute(ref array, index-1, permutations, count, arrayList);
}
}
}
/*
//Function #1 -- create a user define function.
//Structure #6 -- declares a struct with a property, a method, and a private field.
//File Handling #3 -- create a blank file in the disk if the same file already exists
//File Handling #2 -- remove a file from the disk
using System;
using System.IO;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
User[] users = new User[10];
User user = new User();
Console.Write("Please enter your name: ");
user.Name = Console.ReadLine();
user.Hashthis(user.Name);
Greet(user.Name);
user.GetBirthday();
users[user.Hashthis(user.Name)] = user;
string filepath = @"C:\Users\rloyd\source\repos\w3Resource Exercises\w3Resource Exercises\";
try
{
Stream fs = new FileStream(filepath + "userList.txt", FileMode.CreateNew, FileAccess.Write, FileShare.None);
StreamWriter sw = new StreamWriter(fs);
sw.Write(user.ToString());
sw.Close();
fs.Close();
}
catch
{
Stream fs = new FileStream(filepath + "blank.txt", FileMode.Create, FileAccess.Write, FileShare.None);
StreamWriter sw = new StreamWriter(fs);
sw.Write(user.ToString());
sw.Close();
fs.Close();
File.Delete(filepath + "userList.txt");
}
Console.WriteLine(user.ToString());
Console.ReadKey();
}
public struct User
{
public string Name;
public DateTime Birthday;
public int Age;
private int ID;
public int Hashthis(string name)
{
int sum = 0;
foreach (char c in name)
{
sum += Convert.ToInt32(c);
}
ID = (sum) % 9;
return ID;
}
public void GetBirthday()
{
int year;
int month;
int day;
Console.WriteLine($"Okay, {Name}, let's get your birthday in here!");
Console.Write("Please enter the year of your birth ^^: ");
year = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter the month of your birth ^^: ");
month = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter the day of your birth ^^: ");
day = Convert.ToInt32(Console.ReadLine());
this.Birthday = new DateTime(year, month, day);
TimeSpan age = DateTime.Now - Birthday;
Age = Convert.ToInt32((age.TotalDays-age.TotalDays%365)/365);
}
public override string ToString()
{
return ($"Username: {Name} \nBirthday: {Birthday.ToShortDateString()} \nAge: {Age} \nID: {ID}");
}
}
static void Greet(string name)
{
Console.WriteLine($"Hello {name}!");
}
}
}
/*
//Date Time #10 -- determine the day of the week 40 days after the current date.
using System;
namespace cFun
{
class Program
{
static void Main()
{
DateTime today = DateTime.Now;
TimeSpan daysFromToday = new TimeSpan(40, 0, 0, 0);
DateTime later = today.Add(daysFromToday);
Console.WriteLine("Today is: {0:dddd}", today);
Console.WriteLine("40 days from today is: {0:dddd}", later);
Console.ReadKey();
}
}
}
/*
//Date Time #9 -- calculate what day of the week is 40 days from this moment.
using System;
namespace cFun
{
class Program
{
static void Main()
{
int days = 40;
Console.WriteLine($"Today's date is: {DateTime.Now.ToLongDateString()}");
Console.WriteLine($"{days} days from now it will be: {DateTime.Now.AddDays(days).DayOfWeek}");
DateTime now = DateTime.Now;
TimeSpan daysFromNow = new TimeSpan(40, 0, 0, 0);
DateTime then = now.Add(daysFromNow);
Console.WriteLine($"{daysFromNow.Days} days from today it will be: {then.DayOfWeek}");
Console.WriteLine("{0:dd} days from today it will be: {1:dddd}", daysFromNow, then);
Console.ReadKey();
}
}
}
/*
//Date Time #8 -- retrieve the current date.
using System;
namespace cFun
{
class Program
{
static void Main()
{
Console.WriteLine($"General format {DateTime.Now.ToString()}");
Console.WriteLine("Display the date in a variety of formats:");
Console.WriteLine($"\n{DateTime.Now.ToShortDateString()}");
Console.WriteLine($"{DateTime.Now.ToLongDateString()}");
Console.WriteLine($"{DateTime.Now.ToShortDateString()} {DateTime.Now.ToShortTimeString()}");
Console.ReadKey();
}
}
}
/*
//Date Time #7 -- get the time of day from a given array of date time values
using System;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
DateTime[] dateTimes =
{DateTime.Now,
new DateTime(2016, 08, 16, 09, 28, 0),
new DateTime(2011, 05, 28, 10, 35, 0),
new DateTime(1979, 12, 25, 14, 30, 0)
};
foreach(DateTime d in dateTimes)
{
Console.WriteLine($"Day: {d.ToShortDateString()} Time: {d.TimeOfDay}");
Console.WriteLine($"Day: {d.ToShortDateString()} Time: {d.ToShortTimeString()}");
}
Console.ReadKey();
}
}
}
/*
//Date Time #6 -- display the number of ticks that have elapsed since the beginning of the twenty-first century
//and to instantiate a TimeSpan object using the Ticks property.
using System;
using System.Globalization;
namespace cFun
{
class Program
{
static void Main()
{
DateTime now = DateTime.Now;
DateTime then = new DateTime(2001, 01, 01, 00, 00, 00);
TimeSpan timeSpan = new TimeSpan();
timeSpan = now - then;
Console.WriteLine(now.Ticks);
Console.WriteLine(then.Ticks);
Console.WriteLine(timeSpan.Ticks +"\n");
String[] cultures = { "en-JM", "en-NZ", "fr-BE", "de-CH", "nl-NL" };
foreach(string s in cultures)
{
var culture = new CultureInfo(s);
Console.WriteLine($"{culture.EnglishName}");
Console.WriteLine($"Local date and time: {now.ToString(culture)}");
Console.WriteLine($"UTC date and time: {now.ToUniversalTime()}\n");
}
Console.WriteLine(timeSpan.ToString());
Console.WriteLine($"{timeSpan.Days} days {timeSpan.Hours} hours {timeSpan.Minutes} minutes and {timeSpan.Seconds} seconds");
timeSpan -= (now - then);
Console.WriteLine(timeSpan.ToString());
Console.ReadKey();
}
}
}
/*
//Structure #5 -- show what happen when a struct and a class instance is passed to a method.
//Demonstrates that structs are passed as values and changes made to them within a function are made only to
//the values of the instance that were passed to the function, not to the original struct unless the method is
//of the same return type as the struct that was passed into it and then only if the method is assigned to the
//original struct in the program body.
using System;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
RectangleS rectangleS = new RectangleS
{
Length = 10,
Width = 15
};
RectangleC rectangleC = new RectangleC(10, 15);
Resize(rectangleS, 20, 25);
Resize(rectangleC, 20, 25);
Console.WriteLine(rectangleS.ToString());
Console.WriteLine(rectangleC.ToString());
rectangleS = ResizeS(rectangleS, 20, 25);
Console.WriteLine(rectangleS.ToString());
Console.ReadKey();
}
public struct RectangleS
{
public int Length;
public int Width;
public override string ToString()
{
return ($"Struct Rectangle: Length: {Length} Width:{Width}");
}
}
public class RectangleC
{
public int Length;
public int Width;
public RectangleC()
{
this.Length = 1;
this.Width = 1;
}
public RectangleC(int width, int length)
{
this.Length = length;
this.Width = width;
}
public override string ToString()
{
return ($"Class Rectangle: Length:{Length} Width:{Width}");
}
}
public static void Resize(RectangleC rectangle, int length, int width)
{
rectangle.Length = length;
rectangle.Width = width;
}
public static void Resize(RectangleS rectangle, int length, int width)
{
rectangle.Length = length;
rectangle.Width = width;
}
public static RectangleS ResizeS(RectangleS rectangle, int length, int width)
{
rectangle.Length = length;
rectangle.Width = width;
return rectangle;
}
}
}
/*
//Structure #4 -- create a structure and Assign the Value and call it.
//supposed to create a structure and a class, initilize their values, copy them each to new struct and new class
//then change the values of the original and print the values from the copies to witness the differences.
using System;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
NumStruct numStruct = new NumStruct();
numStruct.X = 75;
numStruct.Y = 95;
NumStruct numStruct2 = numStruct;
numStruct.X = 750;
numStruct.Y = 950;
Console.WriteLine($"Assigned in Structure: X:{numStruct2.X} Y:{numStruct2.Y}");
NumClass numClass = new NumClass();
numClass.X = 750;
numClass.Y = 950;
NumClass numClass2 = numClass;
numClass.X = 7500;
numClass.Y = 9500;
Console.WriteLine($"Assigned in Class: X:{numClass2.X} Y:{numClass2.Y}");
Console.ReadKey();
}
public struct NumStruct
{
public int X;
public int Y;
}
public class NumClass
{
public int X;
public int Y;
}
}
}
/*
//Structure #3 -- create a nested struct to store two data for an employee in an array.
using System;
namespace cFun
{
class Program
{
static void Main()
{
Employee[] Employees;
int numberToAdd = 0;
Console.Write($"Hello, how many employees would you like to add? ");
while(numberToAdd == 0)
{
try
{
numberToAdd = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("The number you have entered is invalid. " +
"Please enter the number of employees you would like to add: ");
}
}
Employees = new Employee[numberToAdd];
for (var i = 0; i < Employees.Length; i++)
{
Employees[i] = new Employee();
Console.Write($"Please enter the name of Employee #{i + 1}: ");
Employees[i].Name = Console.ReadLine();
Employees[i].Birthdate = new DoB();
Employees[i].Birthdate.Read(Employees[i].Name, ref Employees[i].Birthdate.year, "year");
Employees[i].Birthdate.Read(Employees[i].Name, ref Employees[i].Birthdate.month, "month");
Employees[i].Birthdate.Read(Employees[i].Name, ref Employees[i].Birthdate.day, "day");
}
foreach(Employee e in Employees)
{
Console.WriteLine(e.ToString());
}
Console.ReadKey();
}
public struct Employee
{
public string Name;
public DoB Birthdate;
public override string ToString()
{
return ($"Employee: {this.Name} " +
$"\nDay of Birth: {this.Birthdate.day} " +
$"\nMonth of Birth: {this.Birthdate.month}" +
$"\nYear of Birth: {this.Birthdate.year}");
}
}
public struct DoB
{
public int day;
public int month;
public int year;
public void Read(string name, ref int param, string unit)
{
while (param == 0)
{
Console.Write($"Please enter the {unit} of birth of {name} as a two digit number: ");
try
{
param = Convert.ToInt32(Console.ReadLine());
if ((unit == "month" && (param > 12 || param < 1)) || (unit == "day" && (param > 31 || param < 1)))
{
param = 0;
Console.WriteLine("Your entry was invalid.");
}
}
catch
{
Console.WriteLine("Your entry was invalid.");
}
}
}
}
}
}
/*
//Structure #2 -- declare a simple structure and use of static fields inside a struct
using System;
using System.Collections.Generic;
namespace cFun
{
class Program
{
static void Main()
{
Console.WriteLine($"The sum of {xAndy.x} and {xAndy.y} is {xAndy.Sum()}.");
Console.ReadKey();
}
public struct xAndy
{
public static int x = 15;
public static int y = 25;
static xAndy() { }
public static int Sum()
{
return x + y;
}
}
}
}
/*
//DateTime #5 -- get a DateTime value that represents the current date and time on the local computer.
//this tutorial actually focuses on Globalization & CultureInfo
//implemented the WriteText function from my earlier IO exercise to dump all the language info to a text file.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
namespace cFun
{
class Program
{
static void Main()
{
DateTime dateLocal = DateTime.Now;
DateTime dateUtc = DateTime.UtcNow;
var cultureList = CultureInfo.GetCultures(CultureTypes.AllCultures);
Stream fs = new FileStream(@"C:\Users\rloyd\source\repos\w3Resource Exercises\culture_list.txt", FileMode.Create, FileAccess.Write, FileShare.None);
StreamWriter sw = new StreamWriter(fs);
foreach(var v in cultureList)
{
Console.WriteLine(v);
var culture = new CultureInfo(v.ToString());
WriteText("", sw);
WriteText($"{culture.NativeName}", sw);
WriteText($"{culture.EnglishName}", sw);
WriteText($"Local date and time: {dateLocal.ToString(culture)}", sw);
WriteText($"UTC date and time: {dateUtc.ToString(culture)}", sw);
}
sw.Close();
fs.Close();
Console.ReadKey();
}
static void WriteText(string input, StreamWriter sw)
{
Console.WriteLine(input);
sw.WriteLine(input);
}
}
}
/*
//DateTime #4 -- display the number of days of the year between two specified years. Second run with additional features.
using System;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
DateTime date1 = new DateTime { };
DateTime date2 = new DateTime { };
date1 = GetYear(date1, "first");
date2 = GetYear(date2, "second");
Console.WriteLine($"There are {CalcDuration(date1, date2)} days between dates within those two years.");
Console.ReadKey();
}
//gets year from user
static DateTime GetYear(DateTime date, string number)
{
while (true)
{
Console.WriteLine($"Please enter the {number} year: ");
try
{
int Year = Convert.ToInt32(Console.ReadLine());
date = new DateTime( Year, 12, 31, 1, 1, 1);
break;
}
catch
{
Console.WriteLine("Invalid entry.");
}
}
return date;
}
//calculates number of days between dates in each year
static int CalcDuration(DateTime date1, DateTime date2)
{
int sum = 0;
for(var i = 0; i <= Math.Abs(date1.Year - date2.Year); i++)
{
DateTime date3 = new DateTime((date1.Year) + i, date1.Month, date1.Day, date1.Hour, date1.Minute, date1.Second);
Console.WriteLine($"{date3} contains {date3.DayOfYear} days");
sum += date3.DayOfYear;
}
return sum;
}
}
}
/*
//DateTime #4 -- display the number of days of the year between two specified years.
using System;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
DateTime date1 = new DateTime(2018, 06, 25, 14, 33, 25);
DateTime date2 = new DateTime(2015, 6, 30, 15, 27, 45);
Console.WriteLine($"{date1} : The year {date1.Year} {(DateTime.IsLeapYear(date1.Year) ? "is" : "is not")} a leap year and contains {(DateTime.IsLeapYear(date1.Year) ? 366 : 365)} days");
Console.ReadKey();
}
}
}
/*
//DateTime #3 -- get the day of the week for a specified date
using System;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
DateTime date = new DateTime(2018, 06, 24, 9, 27, 44);
Console.WriteLine(date.DayOfWeek);
Console.ReadKey();
}
}
}
/*
//DateTime #2 -- display the Day properties (year, month, day, hour, minute, second, millisecond etc.
using System;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
DateTime date = new DateTime(2018, 06, 24, 9, 18, 33);
Console.WriteLine($"\n{date}\n");
Console.WriteLine($"year = {date.Year}");
Console.WriteLine($"month = {date.Month}");
Console.WriteLine($"day = {date.Day}");
Console.WriteLine($"hour = {date.Hour}");
Console.WriteLine($"minute = {date.Minute}");
Console.WriteLine($"second = {date.Second}");
Console.ReadKey();
}
}
}
/*
//DateTime #1 -- extract the Date property and display the DateTime value in the formatted output.
using System;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
DateTime date = new DateTime(2018,12,24,18,30,00);
Console.WriteLine(date.ToUniversalTime());
Console.WriteLine(date.ToLongDateString());
Console.WriteLine(date.ToLongTimeString());
Console.WriteLine(date.ToShortDateString());
Console.WriteLine(date.ToShortTimeString());
Console.WriteLine(date.ToString("MM/dd/yy HH:mm"));
Console.ReadKey();
}
}
}
/*
//File Handling -- Practice with Stream, StreamWriter, DateTime and StreamReader
//to create time-stamped log files and then read them.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
Stream fsw = new FileStream(@"C:\Users\rloyd\source\repos\w3Resource Exercises\textfile.txt", FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
StreamWriter sw = new StreamWriter(fsw);
WriteText("Hello, what is your name?", sw);
string name = ReadText(sw);
WriteText($"Hello, {name}! How are you today?",sw);
ReadText(sw);
WriteText($"Would you like to see a transcript of our conversation so far, {name}?", sw);
while (true)
{
if (ReadText(sw) == "yes")
{
break;
}
else WriteText($"{name}! that's not the answer I am looking for!", sw);
}
sw.Close();
fsw.Close();
Stream fsr = new FileStream(@"C:\Users\rloyd\source\repos\w3Resource Exercises\textfile.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
StreamReader sr = new StreamReader(fsr);
Console.WriteLine(sr.ReadToEnd());
sr.Close();
fsr.Close();
Console.ReadKey();
}
static void WriteText(string text, StreamWriter sw)
{
Console.WriteLine(text);
sw.WriteLine($"[{DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss")}] {text}");
}
static string ReadText(StreamWriter sw)
{
string text = Console.ReadLine();
sw.WriteLine($"[{DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss")}] {text}");
return text;
}
}
}
/*
//File Handling #1 -- create a blank file in the disk newly
using System;
using System.IO;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
//FileInfo filepath = new FileInfo(@"C:\Users\rloyd\source\repos\w3Resource Exercises\file.txt");
//filepath.Create();
Stream fs = new FileStream(@"C:\Users\rloyd\source\repos\w3Resource Exercises\file.txt", FileMode.Open, FileAccess.Write, FileShare.None);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("Text file opened.");
Console.WriteLine("Text file opened.");
sw.WriteLine("Text file ammended.");
Console.WriteLine("Text file ammended.");
sw.WriteLine("Text file closing...");
Console.WriteLine("Text file closing...");
sw.Close();
fs.Close();
Console.ReadKey();
}
}
}
/*
//Array #3 -- find the sum of all elements of the array
using System;
using System.Diagnostics.CodeAnalysis;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
int[] array = new int[CreateArray()];
for (var i = 0; i < array.Length; i++)
{
Console.Write($"Please enter the value for element {i+1}: ");
try
{
array[i] = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("That is not a valid entry.");
i--;
}
}
Console.WriteLine($"The sum of the array values is: {Sum(array)}");
Console.ReadKey();
}
static int CreateArray()
{
int n = 0;
while(n == 0)
{
Console.Write("Please enter the number of elments you would like to store in the array: ");
try
{
n = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("That is not a valid entry.");
}
}
return n;
}
static int Sum(int[] nums)
{
int sum = 0;
for(var i = 0; i < nums.Length; i++)
{
sum += nums[i];
}
return sum;
}
}
}
/*
//Array #2 -- read n number of values in an array and display it in reverse order.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
int[] array = new int[CreateArray()];
for (int i = 0; i < array.Length; i++)
{
try
{
Console.Write($"Please enter element {i+1}: ");
array[i] = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("That is an invalid entry.");
i--;
}
}
Console.WriteLine("\nThank you! Now I will display the contents of this array in reverse order.");
for (int i = array.Length-1; i > -1; i--)
{
Console.WriteLine($"element {i+1} : {array[i]}");
}
Console.ReadKey();
}
static int CreateArray()
{
int n = 0;
while (n == 0)
{
Console.Write("Please enter the number of elements to store in the array: ");
try
{
n = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("That is an invalid entry.");
}
}
return n;
}
}
}
/*
//Array #1 -- store elements in an array and print it.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
int[] input = new int[10];
for (int i = 0; i < input.Length; i++)
{
Console.Write($"enter element {i+1}: ");
input[i] = Convert.ToInt32(Console.ReadLine());
}
for(int i = 0; i < input.Length; i++)
{
Console.WriteLine($"element {i+1} : {input[i]}");
}
Console.ReadKey();
}
}
}
/*
//For Loop #6 -- display the multiplication table of a given integer
using System;
namespace cFun
{
class Program
{
static void Main()
{
Console.Write("Please enter an integer and I will display a multiplication table for it: ");
long input = Convert.ToInt64(Console.ReadLine());
MultTable(input);
Console.ReadKey();
}
static void MultTable(long num)
{
for (int i = 1; i < Math.Sqrt(num); i++)
{
if (num % i == 0)
Console.WriteLine($"{i} x {num / i} = {num}");
}
}
}
}
/*
//Conditionals #6 -- read the value of an integer m and display the value of n is 1
//when m is larger than 0, 0 when m is 0 and -1 when m is less than 0.
using System;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
Console.Write("Please enter an integer: ");
int m = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(evalSign(m));
Console.ReadKey();
}
static int evalSign(int num)
{
if (num > 0)
return 1;
if (num < 0)
return -1;
return 0;
}
}
}
/*
//File Handling #1 -- create a blank file in the disk newly.
using System;
using System.IO;
class Program
{
static void Main()
{
string path = @"C:\Users\rloyd\source\repos\w3Resource Exercises\textfiles";
FileInfo textfile = new FileInfo(path + "\\textfile.txt");
textfile.Directory.Create();
FileStream fs = textfile.Create();
Console.WriteLine($"A new text file as been created at {path}");
fs.Close();
Console.ReadKey();
}
}
/*
//Searching and Sorting #1 -- sort a list of elements using Shell sort.
using System;
class Program
{
static void Main()
{
int[] numarray = new[] { 2, 17, 3, 5, 1, 4, 20, 9, 15, 8, 13, 14, 7, 19, 18, 6 };
ShellSort(numarray, numarray.Length);
foreach (var num in numarray)
{
Console.Write($"{ num}, ");
}
Console.ReadKey();
}
static void ShellSort(int[] nums, int length)
{
int inc = 3;
while(inc > 0)
{
for (int i = 0; i < length; i++)
{
int j = i;
int temp = nums[i];
while ((j >= inc) && (nums[j - inc] > temp))
{
nums[j] = nums[j - inc];
j = j - inc;
}
nums[j] = temp;
}
if (inc / 2 != 0)
inc = inc / 2;
else if (inc == 1)
inc = 0;
else
inc = 1;
}
}
}
/*
//Structure #1 -- declare a simple structure.
using System;
using System.Security.Cryptography.X509Certificates;
class Program
{
static void Main()
{
Console.Write("Please enter a number: ");
int inp1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter a number: ");
int inp2 = Convert.ToInt32(Console.ReadLine());
Simple inpSum = new Simple (inp1, inp2);
Console.WriteLine($"The sum of {inp1} and {inp2} is {inpSum.Sum()}");
Console.ReadKey();
}
struct Simple
{
public int x;
public int y;
public Simple(int inX, int inY)
{
x = inX;
y = inY;
}
public int Sum ()
{
return x + y;
}
}
}
/*
//For Loop #5 -- display the cube of the number upto given an integer.
using System;
class Program
{
static void Main()
{
Console.Write("Please enter the number of cubes you would like: ");
int input = Convert.ToInt32(Console.ReadLine());
for(int i = 1; i < input +1; i++)
{
Console.WriteLine($"Number is: {i} and the cube of {i} is: {cube(i)}");
}
Console.ReadKey();
}
static int cube(int num)
{
return num * num * num;
}
}
/*
//For Loop #4 -- read 10 numbers from keyboard and find their sum and average.
using System;
class Program
{
static void Main()
{
int input = 0;
double avg = 0;
for (int i = 1; i < 11; i++)
{
Console.Write("\nPlease enter a number: ");
input = Convert.ToInt32(Console.ReadLine());
avg = ((avg * (i - 1)) + input) / i;
Console.WriteLine("\nThe sum of the numbers entered is {0} and the average is {1}.", avg*i, avg);
}
Console.ReadKey();
}
}
/*
//For Loop #3 -- display n terms of natural number and their sum.
using System;
class Program
{
static void Main()
{
Console.Write("Please enter the number of numbers you would like to see: ");
int input = Convert.ToInt32(Console.ReadLine());
numSumCount(input);
Console.ReadKey();
}
static void numSumCount(int nums)
{
int sum = 0;
Console.Write("The first {0} natural numbers are: ", nums);
for (int i = 1; i <= nums; i++)
{
Console.Write(i + ", ");
sum += i;
}
Console.WriteLine("\nThe sum of these numbers is: " + sum);
}
}
/*
//For Loop #2 -- find the sum of first 10 natural numbers
using System;
class Program
{
static void Main()
{
sumNums(10);
Console.ReadKey();
}
static void sumNums (int count)
{
int sum = 0;
for(int i = 1; i <= count; i++)
{
sum += i;
}
Console.WriteLine(sum);
}
}
/*
//For Loop #1 -- display the first 10 natural numbers.
using System;
class Program
{
static void Main()
{
writeNums(10);
Console.ReadKey();
}
static void writeNums(int count)
{
for(int i = 0; i < 11; ++i)
{
Console.Write(i + " ");
}
}
}
/*
//Conditionals #5 -- read the age of a candidate and determine whether it is eligible for casting his/her own vote.
using System;
class Program
{
static void Main()
{
Console.Write("Please enter your age: ");
int input = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("{0}", QualifyAge(input));
Console.ReadKey();
}
static string QualifyAge(int age)
{
if (age >= 18)
return "Congratulations! You are eligible to vote!";
return "We are very sorry, but you are not eligible to vote :c";
}
}
/*
//Conditionals #4 -- find whether a given year is a leap year or not
using System;
class Program
{
static void Main()
{
Console.Write("Please enter a year and I will determine whether it is a leap year or not: ");
int input = Convert.ToInt32(Console.ReadLine());
Console.Write("The year {0} {1} a leap year.", input, isLeap(input) == true? "is" : "is not");
Console.ReadKey();
}
static bool isLeap(int year)
{
if (year % 4 == 0)
return true;
return false;
}
}
/*
//Conditionals #3 -- check whether a given number is positive or negative.
using System;
class Program
{
static void Main()
{
Console.Write("Please enter a number and I will tell you whether it is positive or negative: ");
int input = Convert.ToInt32(Console.ReadLine());
isPos(input);
Console.ReadKey();
}
static void isPos (int num)
{
if ( num == 0)
Console.WriteLine($"{0} is neither positive nor negative.");
else if (num > 0)
Console.WriteLine($"The number {num} is positive.");
else if (num < 0)
Console.WriteLine($"The number {num} is negative.");
}
}
/*
//Conditionals #2 -- check whether a given number is even or odd.
using System;
class Program
{
static void Main()
{
Console.Write("Please enter an integer and I will tell you whether it is even or odd: ");
int num = Convert.ToInt32(Console.ReadLine());
if(num % 2 == 0)
Console.WriteLine($"The number {num} is even.");
else Console.WriteLine($"The number {num} is odd.");
Console.ReadKey();
}
}
/*
//Conditionals #1 -- accept two integers and check whether they are equal or not.
using System;
class Program
{
static void Main()
{
Console.WriteLine("Please enter a number: ");
int input = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter another number: ");
int input2 = Convert.ToInt32(Console.ReadLine());
if (input == input2)
Console.WriteLine("These numbers are equal.");
else { Console.WriteLine("These numbers are not equal."); }
Console.ReadKey();
}
}
/*
//LINQ #5 -- display the characters and frequency of character from giving string.
using System;
using System.Linq;
class Program
{
static void Main()
{
Console.WriteLine("Please enter a string:" );
string input = Console.ReadLine();
var letters = from l in input orderby l group l by l into g select g;
foreach(var v in letters)
{
Console.WriteLine($"\"{v.Key}\" occurs {v.Count()} times.");
}
Console.ReadKey();
}
}
/*
//LINQ #4 -- display the number and frequency of number from giving array. Grouping with a query into var allows
// data to be manipulated like a dictionary, or list, or array apparently.
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] nums = new[] { 8, 3, 2, 5, 1, 9, 6, 4, 3, 5, 2, 9, 1, 2, 8 };
var numSets = from n in nums orderby n group n by n into g select g;
foreach (var num in numSets)
{
Console.WriteLine($"{num.Key} appears {num.Count()} times");
}
Console.ReadKey();
}
}
/*
//LINQ #3 -- find the number of an array and the square of each number.
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] nums = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var sqr20plus = from n in nums where n * n > 20 orderby -n select n;
foreach(int i in sqr20plus)
{
Console.WriteLine($"Number = {i}, Square = {i*i}");
}
Console.ReadKey();
}
}
/*
//LINQ #2 -- find the +ve numbers from a list of numbers using two where conditions in LINQ Query.
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] nums = new[] { -5, 1, -3, -2, 3, 9, -8, 10, -14, 6 };
var posNums = from i in nums where i > 0 where i < 12 orderby i select i;
foreach(int i in posNums)
{
Console.Write($"{i} ");
}
Console.ReadKey();
}
}
/*
//LINQ #1 -- shows how the three parts of a query operation execute.
using System;
using System.Linq;
class Program
{
static void Main()
{
//first comes data
int[] nums = new[] {1,2,3,4,5,6,7,8,9, };
//then comes LINQ
var evens = from i in nums where i % 2 == 0 select i;
//then comes output
foreach(int i in evens)
{
Console.Write($"{i} ");
}
Console.ReadKey();
}
}
/*
//Recursion #10 -- find the Fibonacci numbers for a n numbers of series using recursion.
using System;
class Program
{
static void Main()
{
Console.WriteLine("Please enter the number of Fibonacci numbers that you would like to see: ");
int num = Convert.ToInt32(Console.ReadLine());
Fibs(num, 0, 1);
Console.ReadKey();
}
static void Fibs (int count, int fib1, int fib2)
{
if (count < 1)
return;
Console.WriteLine(fib1);
Fibs(--count, fib2, fib1 + fib2);
}
}
/*
//Recursion #9 -- find the factorial of a given number using recursion.
using System;
class Program
{
static void Main()
{
Console.WriteLine(Factorial(5,1));
Console.ReadKey();
}
static int Factorial(int num, int prod)
{
if (num < 1)
return prod;
return num * Factorial(num - 1, prod);
}
}
/*
//Recursion #8 -- Check whether a given String is Palindrome or not using recursion.
using System;
class Program
{
static void Main()
{
Console.WriteLine("Please enter a string and I will tell you if it is a palindrome: ");
string input = Console.ReadLine();
Console.WriteLine(isPal(input, 0));
Console.ReadKey();
}
static bool isPal (string input, int ctr)
{
if (ctr > input.Length - ctr)
return true;
if (input[input.Length - 1 - ctr] != input[0 + ctr])
return false;
return isPal(input, ++ctr);
}
}
/*
//Recursion #7 -- check whether a number is prime or not using recursion.
using System;
class Program
{
static void Main()
{
Console.WriteLine("Enter a number and I will tell you if it is a prime: ");
int input = Convert.ToInt32(Console.ReadLine());
int divisor = Convert.ToInt32(Math.Sqrt(input));
Console.WriteLine(isPrime(input, divisor));
Console.ReadKey();
}
static bool isPrime (int num, int div)
{
if (div < 2)
return true;
if (num % div == 0)
return false;
return isPrime(num, div - 1);
}
}
/*
//Recursion #6 -- print even or odd numbers in a given range using recursion - solution allows for user choice of even or odd
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
class Program
{
static void Main()
{
PrintNums(21, true);
Console.ReadKey();
}
static void PrintNums(int range, bool even)
{
if(range > 0)
{
if (even == true && range % 2 == 0)
{
PrintNums(range - 2, even);
Console.WriteLine(range);
}
if (even == true & range % 2 != 0)
{
PrintNums(range - 1, even);
}
if (even == false && range % 2 != 0)
{
PrintNums(range - 2, even);
Console.WriteLine(range);
}
if (even == false && range % 2 == 0)
{
PrintNums(range - 1, even);
}
}
}
}
/*
//Recursion #5 -- count the number of digits in a number using recursion.
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Diagnostics;
class Program
{
static void Main()
{
Console.WriteLine(Count(12345, 0));
Console.ReadKey();
}
static int Count(int num, int digs)
{
if (num < 1)
return digs;
digs++;
return Count(num / 10, digs);
}
}
/*
//Recursion #4 -- display the individual digits of a given number using recursion
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
class Program
{
static void Main()
{
PrintDigs(12345);
Console.ReadKey();
}
static void PrintDigs (int num)
{
if (num < 10)
{
Console.Write(num);
return;
}
PrintDigs(num / 10);
Console.Write(" {0}", (num % 10));
}
}
/*
//Recursion #3 -- find the sum of first n natural numbers using recursion.
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
class Program
{
static void Main()
{
Console.WriteLine(SumNums(-10));
Console.ReadKey();
}
static int SumNums(int input)
{
if (input > 0)
input += SumNums(input - 1);
return input;
}
}
/*
//Recursion #2 -- print numbers from n to 1 using recursion
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
class Program
{
static void Main()
{
PrintNums(10);
Console.ReadKey();
}
static void PrintNums(int input)
{
if (input > 0)
{
Console.WriteLine(input);
PrintNums(input - 1);
}
}
}
/*
//Recursion #1 -- print the first n natural number using recursion-Revised solution since learning that code
//following the recursive call, will execute back down the stack once the if condition returns false.
//previously I had thought this would be unreachable code. This solution was subsequently shared by someone else.
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
class Program
{
public static void Main()
{
PrintNums(10);
Console.ReadKey();
}
static void PrintNums(int input)
{
if(input > 0)
{
PrintNums(input - 1);
Console.WriteLine(input);
}
}
}
/*
//Recursion #4 sample code from site. Learned from it that code following the recursive method will still
//be executed before the return call is executed because it is all on the stack. In this case, it is
//the n % 10 call. exciting stuff!
using System;
public class RecExercise4
{
static void Main()
{
Console.Write("\n\n Recursion : Display the individual digits of a given number :\n");
Console.Write("------------------------------------------------------------------\n");
Console.Write(" Input any number : ");
int num = Convert.ToInt32(Console.ReadLine());
Console.Write(" The digits in the number {0} are : ", num);
separateDigits(num);
Console.Write("\n\n");
Console.ReadKey();
}
static void separateDigits(int n)
{
if (n < 10)
{
Console.Write("{0} ", n);
return;
}
separateDigits(n / 10);
Console.Write(" {0} ", n % 10);
}
}
/*
//Recursion #4 -- display the individual digits of a given number using recursion
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
Console.WriteLine("Please enter a number:");
int input = Convert.ToInt32(Console.ReadLine());
printDigit(input);
Console.ReadKey();
}
static void printDigit(int num)
{
Console.Write("{0}, ", num.ToString()[0]);
if (num < 10)
return;
string chars = num.ToString().Remove(0, 1);
printDigit(Convert.ToInt32(chars));
}
}
/*
//Recursion #3 -- find the sum of the first n natural numbers using recursion
using System;
class Program
{
static void Main()
{
Console.Write("How many numbers would you like to sum? ");
int input = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The sum of numbers 0 through {0} is: {1}", input, sumNums(input));
Console.ReadKey();
}
static int sumNums(int length)
{
if (length < 1)
return length;
return length + sumNums(length - 1);
}
}
/*
//Recursion #3 -- find the sum of first n natural numbers using recursion
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Xml.Schema;
namespace cFun
{
class Program
{
static void Main()
{
Sum(25);
Console.ReadKey();
}
public static void Sum(int length)
{
Stack<int> numStack = new Stack<int>();
SumNumStack(numStack, length);
}
private static void SumNumStack(Stack<int> stackIn, int length)
{
stackIn.Push(length);
if(length < 1)
{
while(stackIn.Count() > 0)
{
length += stackIn.Pop();
}
Console.WriteLine(length);
return;
}
SumNumStack(stackIn, length - 1);
}
}
}
/*
//Recursion #2 -- print numbers from n to 1 using recursion
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace cFun
{
class Program
{
static void Main()
{
CountDown(20);
Console.ReadKey();
}
public static void CountDown (int length)
{
Console.WriteLine(length);
if (length < 1)
{
return;
}
CountDown(length - 1);
}
}
}
/*
//Recursion #1 -- print the first n natural number using recursion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace cFun
{
class Program
{
public static Stack numStack = new Stack();
static void Main()
{
PrintNums(10);
Console.ReadKey();
}
public static void PrintNums (int length)
{
if (length < 1)
{
while(numStack.Count > 0)
{
Console.WriteLine(numStack.Pop());
}
return;
}
numStack.Push(length);
PrintNums(length - 1);
}
}
}
/*
//Basic Exercise #62 -- reverse the strings contained in each pair of matching parentheses in a given string
//and also remove the parentheses within the given string.
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace cFun
{
class Program
{
static void Main()
{
Console.WriteLine(RemRev("ab(cd(ef)gh)ij"));
Console.ReadKey();
}
public static string RemRev(string str)
{
int lastOp = str.LastIndexOf('(');
if(lastOp == -1)
{
return str;
}
int firstCl = str.IndexOf(')', lastOp);
return RemRev(str.Substring(0, lastOp) + new string(str.Substring(lastOp + 1, firstCl - lastOp-1).Reverse().ToArray()) + str.Substring(firstCl + 1));
}
}
}
/*
//Basic Exercise #61 -- sort the integers in ascending order without moving the number -5.
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Globalization;
using System.Data.SqlTypes;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
int[] nums = new int[] { 3, 1, 8, 2, -5, 4, 9, 7, 6 };
Console.WriteLine(string.Join(",", sort(nums)));
Console.ReadKey();
}
public static int[] sort(int[] num)
{
int[] outs = num.Where(x => x != -5).OrderBy(x => x).ToArray();
int c = 0;
return num.Select(x => x != -5 ? outs[c++] : -5).ToArray();
}
}
}
/*
//Basic Exervise #18 -- check two given integers and return true if one is negative and one is positive.
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace cFun
{
class Program
{
static void Main()
{
Console.WriteLine("Enter an integer: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter a second integer: ");
int num2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(num1 < 0 ^ num2 < 0);
Console.ReadKey();
}
}
}
/*
//Basic Exercise #62 -- reverse the strings contained in each pair of matching parentheses in a given string
//and also remove the parentheses within the given string.
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace cFun
{
class Program
{
static void Main()
{
Console.WriteLine("enter a string: ");
string input = Console.ReadLine();
Console.WriteLine(swap(input));
Console.ReadKey();
}
public static string swap(string phrase)
{
int dex1 = phrase.IndexOf("(");
int dex2 = phrase.IndexOf(")");
string sOut1 = phrase.Substring(dex1, dex2-dex1+1);
phrase = phrase.Remove(dex1, dex2-dex1+1);
Console.WriteLine(phrase);
int dex3 = phrase.IndexOf("(");
int dex4 = phrase.IndexOf(")");
string sOut2 = phrase.Substring(dex3, dex4 - dex3 +1);
phrase = phrase.Insert(dex1, sOut2);
phrase = phrase.Remove(phrase.IndexOf("("), 1);
phrase = phrase.Remove(phrase.IndexOf(")"), 1);
dex3 = phrase.IndexOf("(");
dex4 = phrase.IndexOf(")");
phrase = phrase.Remove(phrase.IndexOf("("), sOut2.Length);
phrase = phrase.Insert(dex3, sOut1);
phrase = phrase.Remove(phrase.IndexOf("("), 1);
phrase = phrase.Remove(phrase.IndexOf(")"), 1);
return phrase;
}
}
}
/*
//Basic Exercise #61 -- sort the integers in ascending order without moving the number -5.
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace cFun
{
class Program
{
static void Main()
{
int[] tests = new int[] { 3, 8, 2, 4, -5, 7, 6, 9, 1 };
Console.WriteLine(string.Join(", ", sort(tests)));
Console.ReadKey();
}
public static int[] sort(int[] ints)
{
int[] outs = ints.Where(v => v != -5).OrderBy(v => v).ToArray();
int c = 0;
return ints.Select(x => x != -5 ? outs[c++] : -5).ToArray();
}
}
}
//Baisc Exerise #61 -- This was my first go before I learned this can be addressed much more elegantly with lambda and LINQ!
/*
namespace cFun
{
class Program
{
static void Main(string[] args)
{
int[] tests = new[] { 3, 8, 2, 4, -5, 7, 6, 9, 1 };
sort(tests);
Console.ReadKey();
}
public static void sort (int[] ints)
{
int[] outs1st = new int[] { };
int[] outs2nd = new int[] { };
List<int> outsAll = new List<int>();
Array.Resize(ref outs1st, Array.IndexOf(ints, -5) + 1);
Array.Copy(ints, outs1st, Array.IndexOf(ints, -5));
Array.Resize(ref outs2nd, ints.Length - Array.IndexOf(ints, -5) - 1);
Array.Copy(ints, Array.IndexOf(ints, -5) + 1, outs2nd, 0, ints.Length - Array.IndexOf(ints, -5)-1);
Array.Sort(outs1st);
Array.Sort(outs2nd);
outsAll.AddRange(outs1st);
outsAll.Add(-5);
outsAll.AddRange(outs2nd);
Console.WriteLine(string.Join(",", outsAll));
}
}
}
/*
//Basic Exercise #60 -- calculate the sum of all the intgers of a rectangular matrix except those integers which are located below an intger of value 0.
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
namespace cFun
{
class Program
{
//Example code from site. The 'for' loop works because it sums vertically and fails to continue on the first
//occurence of a 0 in the column due to the " && my_matrix[j][i] > 0" condition.
public static int sum_matrix_elements(int[][] my_matrix)
{
int x = 0;
for (int i = 0; i < my_matrix[0].Length; i++)
for (int j = 0; j < my_matrix.Length && my_matrix[j][i] > 0; j++)
x += my_matrix[j][i];
return x;
}
public static void Main()
{
Console.WriteLine(sum_matrix_elements(
new int[][] {
new int[]{0, 2, 3, 2},
new int[]{0, 6, 0, 1},
new int[]{4, 0, 3, 0}
}));
Console.WriteLine(sum_matrix_elements(
new int[][] {
new int[]{1, 2, 1, 0 },
new int[]{0, 5, 0, 0},
new int[]{1, 1, 3, 10 }
}));
Console.WriteLine(sum_matrix_elements(
new int[][] {
new int[]{1, 1},
new int[]{2, 2},
new int[]{3, 3},
new int[]{4, 4}
}));
Console.ReadKey();
}
}
}
/*
static void Main()
{
int[,] nums = new[,] { {0, 2, 3, 2 },
{0, 6, 0, 1 },
{4, 0, 3, 0 } };
Console.WriteLine(noZero(nums));
Console.ReadKey();
}
//calculate sum of numbers in a matrix which do not fall beneath a 0.
public static int noZero(int[,] numbers)
{
var sum = 0;
for (var v = 0; v < numbers.GetLength(0); v++)
{
for (var w = 0; w <numbers.GetLength(1); w++)
{
if(v == 0)
{
sum += numbers[v,w];
continue;
}
for (var x = v-1; x >= 0; x--)
{
if (numbers[x,w] == 0)
{
break;
}
sum += numbers[v,w];
}
}
}
return sum;
}
}
}
/*
//Basic Exercise #59 -- check whether it is possible to create a strictly increasing sequence from a given sequence of integers as an array.
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace cFun
{
class Program
{
static void Main()
{
int[] strIn = new[] {1,3,4,5 };
Console.WriteLine(allUnique(new int [] { 1, 3, 4, 5 }));
Console.WriteLine(allUnique(new int[] { 4, 3, 2, 5 }));
Console.ReadKey();
}
//checks if elements of an array may be arranged in a strictly increasing order.
public static bool allUnique (int[] arrIn)
{
Array.Sort(arrIn);
return (arrIn.Last() - arrIn.First() +1 == arrIn.Length);
}
}
}
/*
//Basic Exercise #58 -- Write a C# program which will accept a list of integers and checks how many integers are needed to complete the range
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.ComponentModel;
namespace cFun
{
class Program
{
static void Main()
{
int[] strIn = new[] { 1, 3, 4, 7, 9 };
Console.WriteLine(missInts(strIn));
Console.ReadKey();
}
public static int missInts (int[] ints)
{
int count = 0;
Array.Sort(ints);
for (var v = 0; v < ints.Length-1; v++)
{
count += ints[v + 1] - ints[v] - 1;
}
return count;
}
}
}
/*
//Basic Exercise #57 -- find the pair of adjacent elements that has the highest product of an given array of integers.
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace cFun
{
class Program
{
static void Main()
{
int[] iArr = new[] { 1, 2, 3, 4, 8, 1, 9, 3, 5, 2 };
int prod = 0;
for (var i = 0; i < iArr.Length - 1; i++)
{
prod = Math.Max(iArr[i] * iArr[i + 1], prod);
}
Console.WriteLine(prod);
Console.ReadKey();
}
}
}
/*
//Basic Exercise #56 -- check if a given string is a palindrome or not
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace cFun
{
class Program
{
static void Main()
{
string input;
Console.Write("Please enter a string and I will tell you whether it is a palindrome or not: ");
input = Console.ReadLine();
Console.WriteLine(string.Join("", input.ToCharArray().Reverse()));
Console.WriteLine(input == string.Join("", input.ToCharArray().Reverse()));
Console.WriteLine(isPalindrome(input));
Console.ReadKey();
}
public static bool isPalindrome (string str)
{
for(var i = 0; i <str.Length; i++)
{
if(str[i] != str[str.Length - 1 - i])
{
return false;
}
}
return true;
}
}
}
/*
//Basic Exercise #55 -- find the pair of adjacent elements that has the largest product of an given array.
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.ComponentModel;
namespace cFun
{
class Program
{
static void Main (string[] args)
{
int[] iAr = new[] { 1, 2, 4, 1, 3, 5, 0, 1 };
Console.WriteLine(LP(iAr));
Console.ReadKey();
}
public static int LP (int[] array)
{
int LProd = 0;
for (var i = 0; i < array.Length - 1; i++)
{
LProd = (array[i] * array[i + 1]) > LProd ? array[i] * array[i + 1] : LProd;
}
return LProd;
}
}
}
/*
//Basic Exercise #54 -- get the century from a year
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter a year and I will tell you the century in which it falls: ");
int year = Convert.ToInt32(Console.ReadLine());
int century = year / 100 + (year % 100 == 0? 0:1);
Console.WriteLine(century);
Console.ReadKey();
}
}
}
/*
//Basic Exercise #53 -- check if an array contains an odd number
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Runtime.Remoting.Messaging;
namespace cFun
{
class Program
{
static void Main(string[] args)
{
int[] iAr = new[] { 2, 4, 7, 8, 6 };
for (var i = 0; i < iAr.Length; i++)
{
if (iAr[i] % 2 != 0)
{
Console.WriteLine(iAr.Contains(iAr[i]));
break;
}
}
Console.ReadKey();
}
}
}
/*
//Basic Exercise #52 -- create a new array of length containing the middle elements of three arrays (each length 3) of integers.
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace w3Resource_Exercises
{
class Program
{
static void Main(string[] args)
{
int[] iAr1 = new[] { 1, 2, 5 };
int[] iAr2 = new[] { 0, 3, 8 };
int[] iAr3 = new[] { -1, 0, 2 };
int[] iAr4 = new[] { iAr1[1], iAr2[1], iAr3[1] };
foreach (int i in iAr4) { Console.Write($"{i}, "); }
Console.ReadKey();
}
}
}
/*
//Basic Exerise #51 -- get the larger value between first and last element of an array (length 3) of integers.
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
namespace w3Resource_Exercises
{
class Program
{
static void Main(string[] args)
{
int[] iArr = new[] { 1, 2, 5, 7, 8 };
var high = 0;
for (var i = 0; i < iArr.Length; i++)
{
if (iArr[i] > high) { high = iArr[i]; }
}
Console.WriteLine(high);
if (iArr.First() > iArr.Last())
{
Console.WriteLine(iArr.First());
}
else { Console.WriteLine(iArr.Last()); }
Console.ReadKey();
}
}
}
/*
//Basic Exervise #50 -- Write a C# program to rotate an array (length 3) of integers in left direction
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace w3Resource_Exercises
{
class Program
{
static void Main(string[] args)
{
int[] iArr = new[] { 1, 2, 8 };
iArr[0] += iArr[1]; iArr[1] += iArr[2];
iArr[2] -= (iArr[1] - iArr[0]); iArr[0] -= iArr[2]; iArr[1] -= iArr[0];
Console.WriteLine(string.Join(", ", iArr));
Console.ReadKey();
}
}
}
/*
// Basic Exercise #49 -- Write a C# program to check if the first element or the last element of the two arrays ( length 1 or more) are equal.
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace w3Resource_Exercises
{
class Program
{
static void Main (string[] args)
{
int[] iArr1 = new[] { 1, 2, 2, 3, 3, 4, 5, 6, 5, 7, 7, 7, 8, 8, 1 };
int[] iArr2 = new[] { 1, 2, 2, 3, 3, 4, 5, 6, 5, 7, 7, 7, 8, 8, 5 };
Console.WriteLine((iArr1.First() == iArr2.First()) || (iArr1.Last() == iArr2.Last()));
Console.ReadKey();
}
}
}
/*
///Basic Exercise #48 -- Write a C# program to check if the first element and the last element are equal of an array of integers and the length is 1 or more.
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace w3Resource_Exercises
{
class Program
{
static void Main (string[] args)
{
int[] iArr = new[] { 1, 2, 2, 3, 3, 4, 5, 6, 5, 7, 7, 7, 8, 8, 1 };
Console.WriteLine((iArr.First() == iArr.Last()) && iArr.Length > 1);
Console.ReadKey();
}
}
}
/*
//Basic Exercise #47 -- Write a C# program to compute the sum of all the elements of an array of integers.
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace w3Resource_Exercises
{
class Program
{
static void Main(string[] args)
{
int[] iArr = new[] { 1, 2, 2, 3, 3, 4, 5, 6, 5, 7, 7, 7, 8, 8, 1 };
Console.WriteLine(iArr.Aggregate((a, b) => a +b));
Console.ReadKey();
}
}
}
/*
//Basic Exercise #46 -- Write a C# program to check if a number appears as either the first or last element of an array of integers and the length is 1 or more.
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace w3Resource_Exercise
{
class Program
{
static void Main (string[] args)
{
Console.WriteLine("Enter an integer: ");
int input = Convert.ToInt32(Console.ReadLine());
int[] iArray = new[] { 1, 3, 5, 7, 3, 5, 42, 13, 46, 15 };
Console.WriteLine(lastOrFirst(input, iArray));
Console.WriteLine((iArray.First() == input) || (iArray.Last() == input));
Console.ReadKey();
}
static public bool lastOrFirst(int inp, int[] iArr)
{
if (inp == iArr.First() || inp == iArr.Last())
{
return true;
}
return false;
}
}
}
/*
//Basic Exercise #45
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace w3Resource_Exercises
{
class Program
{
static void Main (string[] args)
{
List<int> intArray = new List<int> ();
Random rnd = new Random();
int input;
//populate list
for (int i = 0; i < 100; i++)
{
intArray.Add(i % 5 + rnd.Next(7));
}
//populate array
Console.Write("Stored array: {0}", string.Join(", ", intArray));
Console.WriteLine();
Console.Write("Please enter a an integer and I will count the number of times it appears in the stored array: ");
input = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The number {0} occurs {1} times in the stored array.", input, intArray.Count(i => i == input));
Console.ReadKey();
}
}
}
/*
//Basic Exercise #44
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Xml;
namespace w3Resource_Exercises
{
class Program
{
static void Main(string [] args)
{
Console.WriteLine("Enter a string and I will make a new one from ever other character:");
string input = Console.ReadLine();
var output = from c in input where input.IndexOf(c) % 2 != 0 select c;
Console.WriteLine(string.Join("", output));
Console.ReadKey();
}
}
}
/*
//Basic Exercise #43
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace w3Resource_Exercises
{
class Program
{
static void Main(string[] args)
{
string input;
Console.WriteLine("please enter a string and I will tell you if it begins with a 'w' and is immediately followed by two sets of 'ww': ");
input = Console.ReadLine();
Console.WriteLine(Checker(input));
Console.ReadKey();
}
public static bool Checker(string inputString)
{
if (inputString.Length > 4 && inputString.StartsWith("w") && inputString.Substring(1,2) == "ww" && inputString.Substring(3,2) == "ww")
{
return true;
}
return false;
}
}
}
/*
//Basic Exercise #42
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Linq;
namespace w3Resource_Exercises
{
class Program
{
static void Main(string[] args)
{
string input;
List<char> output = new List<char>();
Console.WriteLine("Please enter a string: ");
input = Console.ReadLine();
for (int i = 0; i < input.Length; i++)
{
if (i < 4)
{
output.Add(char.ToUpper(input[i]));
}
else { output.Add(input[i]); }
}
foreach(char c in output)
{
Console.Write(c);
}
Console.ReadKey();
}
}
}
/*
//Basic Exerise #41
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
namespace w3Resource_Exercises
{
class Program
{
static void Main (string[] args)
{
string input;
char w = 'w';
Console.WriteLine($"Please enter a string of characters and I will detremine if it contains the character {w} between 1 and 3 times: " );
input = Console.ReadLine();
//if (input.Contains('w'))
//{
// var ws = from c in input where c == w select c;
// Console.WriteLine($"The character '{w}' occurs {ws.Count()} times in the string that you entered.");
//}
//else { Console.WriteLine("The string that you entered does not contain a 'w'"); }
var ws = from c in input where c == w select w;
if (ws.Count() < 4 && ws.Count() > 0)
{
Console.WriteLine("The string that you entered contains a 'w' between 1 and 3 times.");
}
else { Console.WriteLine("The string that you entered does not contain a 'w' between 1 and 3 times."); }
Console.ReadKey();
}
}
}
/*
//Basic Exercise #40
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace w3Resource_Exercises
{
class Program
{
static void Main(string[] args)
{
int cntrl = 20;
int inp1;
int inp2;
Console.WriteLine("Please enter an integer: ");
inp1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter another integer and I will determine which is closer to 20: ");
inp2 = Convert.ToInt32(Console.ReadLine());
if (Math.Abs(cntrl-inp1) > Math.Abs(cntrl - inp2))
{
Console.WriteLine($"{inp2} is closer to {cntrl} than {inp1}.");
}
else { Console.WriteLine($"{inp1} is closer to {cntrl} than {inp2}."); }
Console.ReadKey();
}
}
}
/*
//basic exercise # 39
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Collections;
using System.Runtime.InteropServices.ComTypes;
namespace w3Reasource_Exercises
{
class Program
{
static void Main(string[] args)
{
int[] intArray = new int[3];
Queue intQueye = new Queue();
List<int> intList = new List<int>();
for(int i = 0; i <3; i++)
{
Console.WriteLine("Please enter an integer:");
intList.Add(Convert.ToInt32(Console.ReadLine()));
}
Console.WriteLine("Unsorted intList: {0}", string.Join(", ", intList));
intList.Sort();
Console.WriteLine("Sorted intList: {0}", string.Join(", ", intList));
Console.WriteLine($"Largest number {intList[2]}, Smallest number: {intList[0]}");
Console.ReadKey();
}
}
}
/*
//Basic Exercise # 38
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace w3Resource_Exercises
{
class Program
{
static void Main (string[] args)
{
string input = "PHP";
Console.WriteLine(input);
if (input.StartsWith("PH"))
{
string output = input.Substring(0, 2);
Console.WriteLine(output);
}
Console.ReadKey();
}
}
}
/*
//Basic Exercise # 37
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace w3Resource_Exercises
{
class Program
{
static void Main(string[] args)
{
string aString = "PHP Tutorial";
Console.WriteLine(aString);
//if(Convert.ToString(aString[1]) == "H" && Convert.ToString(aString[2]) == "P")
if(aString.Contains("HP") && aString.IndexOf("HP") == 1)
{
aString = aString.Remove(1, 2);
Console.WriteLine(aString);
Console.ReadKey();
}
}
}
}
*/
|
using JMusic.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JMusic.Services
{
interface ITUserService
{
Task<TUser> CreateAsync(TUser tUser);
TUser GetById(string id);
Task<TUser> GetCurrentAsync();
TUser Update(TUser tUser);
bool Delete(string id);
Task<TToken> AuthenticationAsync(string email, string password);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace MeriMudra.Models.ViewModels
{
[NotMapped]
public class CityGroupViewModel
{
public int GroupId { get; set; }
public string GroupName { get; set; }
public string CityIds { get; set; }
public List<City> IncludedCitys { get; set; }
public CityGroupViewModel(int id)
{
var db = new MmDbContext();
var cg = db.CityGroups.Where(g => g.GroupId == id).FirstOrDefault();
this.GroupId = cg.GroupId;
this.GroupName = cg.GroupName;
this.CityIds = cg.CityIds;
this.IncludedCitys = new List<City>();
this.IncludedCitys = db.Citys.SqlQuery("SELECT Id, City as Name, StateId FROM dbo.CityMaster where id in (" + CityIds + ")").ToList<City>();
IncludedCitys.ForEach(city => { city.State = db.States.Find(city.StateId); });
}
public CityGroupViewModel()
{
}
}
} |
namespace EXON.Data
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using EXON.Model;
public partial class EXONDbContext : DbContext
{
public EXONDbContext()
: base("name=EXONSystem")
{
}
public virtual DbSet<ANSWER> ANSWERS { get; set; }
public virtual DbSet<ANSWERSHEET_DETAIL> ANSWERSHEET_DETAIL { get; set; }
public virtual DbSet<ANSWERSHEET> ANSWERSHEETS { get; set; }
public virtual DbSet<BAGOFTEST> BAGOFTESTS { get; set; }
public virtual DbSet<CONTEST_TYPES> CONTEST_TYPES { get; set; }
public virtual DbSet<CONTESTANT_TYPES> CONTESTANT_TYPES { get; set; }
public virtual DbSet<CONTESTANT> CONTESTANTS { get; set; }
public virtual DbSet<CONTESTANTS_SHIFTS> CONTESTANTS_SHIFTS { get; set; }
public virtual DbSet<CONTESTANTS_SUBJECTS> CONTESTANTS_SUBJECTS { get; set; }
public virtual DbSet<CONTESTANTS_TESTS> CONTESTANTS_TESTS { get; set; }
public virtual DbSet<CONTEST> CONTESTS { get; set; }
public virtual DbSet<DEPARTMENT> DEPARTMENTS { get; set; }
public virtual DbSet<FINGERPRINT> FINGERPRINTS { get; set; }
public virtual DbSet<LOCATION> LOCATIONS { get; set; }
public virtual DbSet<MODULE> MODULES { get; set; }
public virtual DbSet<POSITION> POSITIONS { get; set; }
public virtual DbSet<QUESTION_TYPES> QUESTION_TYPES { get; set; }
public virtual DbSet<QUESTION> QUESTIONS { get; set; }
public virtual DbSet<RECEIPT> RECEIPTS { get; set; }
public virtual DbSet<REGISTER> REGISTERS { get; set; }
public virtual DbSet<REGISTERS_SUBJECTS> REGISTERS_SUBJECTS { get; set; }
public virtual DbSet<ROOMDIAGRAM> ROOMDIAGRAMS { get; set; }
public virtual DbSet<ROOMTEST> ROOMTESTS { get; set; }
public virtual DbSet<SCHEDULE> SCHEDULES { get; set; }
public virtual DbSet<SHIFT> SHIFTS { get; set; }
public virtual DbSet<SHIFTS_STAFFS> SHIFTS_STAFFS { get; set; }
public virtual DbSet<STAFF> STAFFS { get; set; }
public virtual DbSet<STRUCTURE_DETAIL> STRUCTURE_DETAIL { get; set; }
public virtual DbSet<STRUCTURE> STRUCTURES { get; set; }
public virtual DbSet<SUBJECT> SUBJECTS { get; set; }
public virtual DbSet<SUBQUESTION> SUBQUESTIONS { get; set; }
public virtual DbSet<TEST_DETAIL> TEST_DETAIL { get; set; }
public virtual DbSet<TEST> TESTS { get; set; }
public virtual DbSet<TOPIC> TOPICS { get; set; }
public virtual DbSet<TOPICS_STAFFS> TOPICS_STAFFS { get; set; }
public virtual DbSet<VIOLATION_TYPES> VIOLATION_TYPES { get; set; }
public virtual DbSet<VIOLATIONS_CONTESTANTS> VIOLATIONS_CONTESTANTS { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ANSWERSHEET_DETAIL>()
.Property(e => e.AnswerSheetDetailContent)
.IsUnicode(false);
modelBuilder.Entity<ANSWERSHEET>()
.Property(e => e.AnswerContent)
.IsUnicode(false);
modelBuilder.Entity<CONTESTANT>()
.Property(e => e.ContestantCode)
.IsUnicode(false);
modelBuilder.Entity<CONTESTANT>()
.Property(e => e.IdentityCardNumber)
.IsUnicode(false);
modelBuilder.Entity<CONTESTANTS_SHIFTS>()
.Property(e => e.ClientIP)
.IsUnicode(false);
modelBuilder.Entity<CONTESTANTS_SHIFTS>()
.Property(e => e.ContestantPass)
.IsUnicode(false);
modelBuilder.Entity<DEPARTMENT>()
.HasMany(e => e.DEPARTMENTS1)
.WithOptional(e => e.DEPARTMENT1)
.HasForeignKey(e => e.DepartmentIDParent);
modelBuilder.Entity<DEPARTMENT>()
.HasMany(e => e.STAFFS)
.WithRequired(e => e.DEPARTMENT)
.WillCascadeOnDelete(false);
modelBuilder.Entity<DEPARTMENT>()
.HasMany(e => e.SUBJECTS)
.WithRequired(e => e.DEPARTMENT)
.WillCascadeOnDelete(false);
modelBuilder.Entity<POSITION>()
.HasMany(e => e.STAFFS)
.WithRequired(e => e.POSITION)
.WillCascadeOnDelete(false);
modelBuilder.Entity<REGISTER>()
.Property(e => e.IdentityCardNumber)
.IsUnicode(false);
modelBuilder.Entity<ROOMDIAGRAM>()
.Property(e => e.ComputerCode)
.IsUnicode(false);
modelBuilder.Entity<ROOMDIAGRAM>()
.Property(e => e.ComputerName)
.IsUnicode(false);
modelBuilder.Entity<STAFF>()
.Property(e => e.Username)
.IsUnicode(false);
modelBuilder.Entity<STAFF>()
.Property(e => e.Password)
.IsUnicode(false);
modelBuilder.Entity<STAFF>()
.Property(e => e.IdentityCardNumber)
.IsUnicode(false);
modelBuilder.Entity<STAFF>()
.HasMany(e => e.CONTESTS)
.WithOptional(e => e.STAFF)
.HasForeignKey(e => e.StaffID1);
modelBuilder.Entity<STAFF>()
.HasMany(e => e.CONTESTS1)
.WithOptional(e => e.STAFF1)
.HasForeignKey(e => e.StaffID2);
modelBuilder.Entity<STAFF>()
.HasMany(e => e.QUESTIONS)
.WithOptional(e => e.STAFF)
.HasForeignKey(e => e.StaffID1);
modelBuilder.Entity<STAFF>()
.HasMany(e => e.QUESTIONS1)
.WithOptional(e => e.STAFF1)
.HasForeignKey(e => e.StaffID2);
modelBuilder.Entity<STAFF>()
.HasMany(e => e.TOPICS_STAFFS)
.WithOptional(e => e.STAFF)
.HasForeignKey(e => e.StaffID1);
modelBuilder.Entity<STAFF>()
.HasMany(e => e.TOPICS_STAFFS1)
.WithOptional(e => e.STAFF1)
.HasForeignKey(e => e.StaffID2);
modelBuilder.Entity<SUBJECT>()
.HasMany(e => e.MODULES)
.WithRequired(e => e.SUBJECT)
.WillCascadeOnDelete(false);
modelBuilder.Entity<SUBJECT>()
.HasMany(e => e.TOPICS)
.WithRequired(e => e.SUBJECT)
.WillCascadeOnDelete(false);
modelBuilder.Entity<TEST_DETAIL>()
.Property(e => e.RandomAnswer)
.IsUnicode(false);
modelBuilder.Entity<TOPIC>()
.HasMany(e => e.TOPICS_STAFFS)
.WithRequired(e => e.TOPIC)
.WillCascadeOnDelete(false);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
namespace LongigantenAPI.Models
{
[DataContract(Name = "Customer", Namespace = "SchoolProjectAPI")]
public class AddressesDto
{
public int Id { get; set; }
public string ZipCode { get; set; }
public string Address { get; set; }
public string Floor { get; set; }
/*
public AddressesDto(ZipCodeDto zipCode, string address, string floor = "ingen")
{
ZipCode = zipCode;
Address = address;
Floor = floor;
}
public AddressesDto(int id, ZipCodeDto zipCode,string address, string floor = "ingen")
{
Id = id;
ZipCode = zipCode;
Address = address;
Floor = floor;
}
*/
}
}
|
// Bar POS, class Bill
// Versiones:
// V0.01 14-May-2018 Moisés: Basic skeleton
// V0.02 15-May-2018 Moisés: Methods completeds
// V0.03 18-May-2018 Moisés: Method ToString, method ToPrintable
// V0.04 22-May-2018 Moisés: Changes in toPrintable method
using System;
using System.Collections.Generic;
namespace BarPOS
{
[Serializable]
public class Bill
{
private List<BillLine> Lines;
public int LinesCount { get { return Lines.Count; } }
public BillHeader Header { get; set; }
public double SubTotal { get; set; }
public double Total { get; set; }
public bool Found { get; set; }
public double MoneyGiven { get; set; }
public double Change { get; set; }
public Bill()
{
Lines = new List<BillLine>();
}
public void AddLine(BillLine line)
{
Lines.Add(line);
}
public void RemoveLine(int index)
{
Lines.RemoveAt(index - 1);
}
public BillLine GetLine(int index)
{
return Lines[index - 1];
}
public void CalculateTotal()
{
SubTotal = 0;
for (int i = 0; i < Lines.Count; i++)
{
SubTotal += (Lines[i].Amount * Lines[i].LineProduct.Price);
}
}
//Method to make the bill printable, in order to print it
public string[] ToPrintable()
{
List<string> image = new List<string>();
image.Add(Header.CompanyData.Name);
image.Add(Header.CompanyData.Address);
image.Add("Table: " + Header.Table);
image.Add("Date: " + Header.Date);
image.Add("Worker: " + Header.Employee.Name);
image.Add(new string('-', 45));
for (int i = 0; i < Lines.Count; i++)
{
image.Add(Lines[i].LineProduct.Description.Trim() + " " +
Lines[i].Amount + " " + Lines[i].Total);
}
image.Add(new string('-', 45));
image.Add("Total: " + Total);
image.Add("Given: " + MoneyGiven);
image.Add("Change: " + Change);
return image.ToArray();
}
public override string ToString()
{
string bill = "";
bill += Lines[0];
for (int i = 1; i < Lines.Count; i++)
{
bill += "$" + Lines[i].ToString();
}
bill += "|" + Header.ToString();
bill += "|" + Total;
bill += "|" + SubTotal;
bill += "|" + MoneyGiven;
bill += "|" + Change;
return bill;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using StanbicIBTC.BotServices.Models;
namespace StanbicIBTC.BotServices.Context
{
public class BotDBContext : DbContext
{
public DbSet<QuestionsBank> QuestionsBank { get; set; }
}
} |
using System;
using System.Collections.Specialized;
using System.Globalization;
using System.Resources;
using System.Web.Compilation;
namespace Meshop.Framework.Translation
{
class DBResourceProvider: IResourceProvider
{
private string classKey;
private DBResourcesModel m_dalc = new DBResourcesModel();
public DBResourceProvider(string classKey)
{
this.classKey = classKey;
}
public object GetObject(string resourceKey, CultureInfo culture)
{
if (string.IsNullOrEmpty(resourceKey))
{
throw new ArgumentNullException("resourceKey");
}
if (culture == null)
{
culture = CultureInfo.CurrentUICulture;
}
string resourceValue = m_dalc.GetResourceByCultureAndKey(culture, resourceKey);
return resourceValue;
}
public IResourceReader ResourceReader
{
get
{
ListDictionary resourceDictionary = this.m_dalc.GetResourcesByCulture(CultureInfo.InvariantCulture);
return new DBResourceReader(resourceDictionary);
}
}
}
}
|
using Rg.Plugins.Popup.Pages;
using Xamarin.Forms.Xaml;
using XF40Demo.ViewModels;
namespace XF40Demo.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class InSightInfoPopupPage : PopupPage
{
private readonly InSightInfoViewModel vm = new InSightInfoViewModel();
public InSightInfoPopupPage()
{
InitializeComponent();
BindingContext = vm;
}
protected override void OnAppearing()
{
base.OnAppearing();
vm.OnAppearing();
}
protected override void OnDisappearing()
{
base.OnDisappearing();
vm.OnDisappearing();
}
protected override bool OnBackButtonPressed()
{
// Return true if you don't want to close this popup page when a back button is pressed
return base.OnBackButtonPressed();
}
protected override bool OnBackgroundClicked()
{
// Return false if you don't want to close this popup page when a background of the popup page is clicked
// return base.OnBackgroundClicked();
return false;
}
}
} |
using Microsoft.Xna.Framework;
namespace OpenOracle.Old
{
public class ScreenOld
{
public int Height => Tiles?.GetHeight() ?? 0;
public int Width => Tiles?.GetWidth() ?? 0;
public TileOld[,] Tiles { get; private set; }
public void InitializeStaticTiles(int[,,] coordinates)
{
Tiles = new TileOld[coordinates.GetWidth(), coordinates.GetHeight()];
for (var row = 0; row < coordinates.GetHeight(); row++)
{
for (var column = 0; column < coordinates.GetWidth(); column++)
{
int coordinate0 = coordinates[row, column, 0];
int coordinate1 = coordinates[row, column, 1];
Tiles[column, row] = new TileOld(
new Point(coordinate0, coordinate1));
}
}
}
public void PlaceAnimatedTile(int animationIndex, Point coordinates)
{
Tiles[coordinates.X, coordinates.Y] = new TileOld(new Point(0, animationIndex), true);
}
public void PlaceStaticTile(int tileX, int tileY, int textureX, int textureY)
{
Tiles[tileX, tileY] = new TileOld(new Point(textureX, textureY));
}
public void PlaceAnimatedTile(int animationIndex, int[,] coordinates)
{
for (var indexY = 0; indexY < coordinates.GetHeight(); indexY++)
{
PlaceAnimatedTile(animationIndex,
new Point(
coordinates[indexY, 0],
coordinates[indexY, 1]));
}
} //TODO: Remove
}
}
|
using System;
using System.Collections.Generic;
using Bindings;
namespace Server
{
class ServerHandlerNetworkData
{
private delegate void Packet_(int index, byte[] data);
private static Dictionary<int, Packet_> Packets;
public static void InitialiseNetworkPackages()
{
Console.WriteLine("Initialise network packages");
Packets = new Dictionary<int, Packet_>
{
{(int) ClientPackets.CThankyou, HandleThankYou}
};
}
public static void HandleNetworkInformation(int index, byte[] data)
{
int packetnum;
PacketBuffer buffer = new PacketBuffer();
buffer.WriteBytes(data);
packetnum = buffer.ReadInteger();
buffer.Dispose();
if (Packets.TryGetValue(packetnum, out Packet_ Packet))
{
Packet.Invoke(index, data);
}
}
private static void HandleThankYou(int index, byte[] data)
{
PacketBuffer buffer = new PacketBuffer();
buffer.WriteBytes(data);
buffer.ReadInteger();
string msg = buffer.ReadString();
buffer.Dispose();
//CODE HERE
Console.WriteLine(msg);
}
}
}
|
using UnityEngine;
using System.Collections.Generic;
using System.Reflection;
namespace Thesis {
public class BuildingMesh : DrawableObject
{
/*************** FIELDS ***************/
public readonly Building parent;
public List<Face> faces = new List<Face>();
private int _floorCount = 0;
public int floorCount
{
get { return _floorCount; }
set
{
_floorCount = value;
if (_floorHeight > 0f)
height = _floorHeight * _floorCount;
}
}
private float _floorHeight = 0f;
public float floorHeight
{
get { return _floorHeight; }
set
{
_floorHeight = value;
if (_floorCount > 0)
height = _floorHeight * _floorCount;
}
}
public float height = 0f;
/// <summary>
/// Stores the indexes of faces in sorted order.
/// </summary>
public int[] sortedFaces;
private const float _componentWidthMin = 1.1f;
private const float _componentWidthMax = 1.25f;
private const float _componentSpaceMin = 2f;
private const float _componentSpaceMax = 2.25f;
public float windowHeight;
public float doorHeight;
public float balconyHeight;
public float balconyFloorHeight;
public float balconyFloorWidth;
public float balconyFloorDepth;
public Roof roof;
public RoofBase roofBase;
/*************** CONSTRUCTORS ***************/
public BuildingMesh (Building parent, Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4)
{
this.parent = parent;
name = "neo_building_mesh";
var list = MaterialManager.Instance.GetCollection("mat_walls");
material = list[Random.Range(0, list.Count)];
parent.AddCombinable(material.name, this);
if (parent.floorHeight <= 0f)
floorHeight = Random.Range(3.8f, 4f);
else
floorHeight = parent.floorHeight;
if (parent.floorCount <= 0)
floorCount = Util.RollDice(new float[] {0.15f, 0.7f, 0.15f});
else
floorCount = parent.floorCount;
FindMeshOrigin(p1, p3, p2, p4);
boundaries = new Vector3[8];
boundaries[0] = p1 - meshOrigin;
boundaries[1] = p2 - meshOrigin;
boundaries[2] = p3 - meshOrigin;
boundaries[3] = p4 - meshOrigin;
for (int i = 0; i < 4; ++i)
boundaries[i + 4] = boundaries[i] + height * Vector3.up;
ConstructFaces();
ConstructFaceComponents();
ConstructRoof();
}
public BuildingMesh (Building parent, BuildingLot lot)
{
this.parent = parent;
name = "neo_building_mesh";
var list = MaterialManager.Instance.GetCollection("mat_walls");
material = list[Random.Range(0, list.Count)];
parent.AddCombinable(material.name, this);
if (parent.floorHeight <= 0f)
floorHeight = Random.Range(3.8f, 4f);
else
floorHeight = parent.floorHeight;
if (parent.floorCount <= 0)
floorCount = Util.RollDice(new float[] {0.15f, 0.7f, 0.15f});
else
floorCount = parent.floorCount;
FindMeshOrigin(lot.edges[0].start, lot.edges[2].start,
lot.edges[1].start, lot.edges[3].start);
boundaries = new Vector3[8];
boundaries[0] = lot.edges[0].start - meshOrigin;
boundaries[1] = lot.edges[1].start - meshOrigin;
boundaries[2] = lot.edges[2].start - meshOrigin;
boundaries[3] = lot.edges[3].start - meshOrigin;
for (int i = 0; i < 4; ++i)
boundaries[i + 4] = boundaries[i] + height * Vector3.up;
ConstructFaces(lot);
ConstructFaceComponents();
ConstructRoof();
}
/*************** METHODS ***************/
public void ConstructFaces ()
{
faces.Add(new Face(this, boundaries[0], boundaries[1]));
faces.Add(new Face(this, boundaries[1], boundaries[2]));
faces.Add(new Face(this, boundaries[2], boundaries[3]));
faces.Add(new Face(this, boundaries[3], boundaries[0]));
SortFaces();
}
public void ConstructFaces (BuildingLot lot)
{
faces.Add(new Face(this, boundaries[0], boundaries[1],
lot.freeEdges.Contains(0)));
faces.Add(new Face(this, boundaries[1], boundaries[2],
lot.freeEdges.Contains(1)));
faces.Add(new Face(this, boundaries[2], boundaries[3],
lot.freeEdges.Contains(2)));
faces.Add(new Face(this, boundaries[3], boundaries[0],
lot.freeEdges.Contains(3)));
SortFaces();
}
public void ConstructFaceComponents ()
{
if (parent.windowHeight <= 0f)
windowHeight = Random.Range(1.5f, 1.7f);
else
windowHeight = parent.windowHeight;
if (parent.doorHeight <= 0f)
doorHeight = Random.Range(2.8f, 3f);
else
doorHeight = parent.doorHeight;
if (parent.balconyHeight <= 0f)
if (parent.windowHeight <= 0f)
balconyHeight = windowHeight / 2 + floorHeight / 2.25f;
else
balconyHeight = 0.66f * floorHeight;
else
balconyHeight = parent.balconyHeight;
balconyFloorHeight = 0.2f;
balconyFloorDepth = 1f;
balconyFloorWidth = 0.6f;
float component_width = Random.Range(_componentWidthMin, _componentWidthMax);
float inbetween_space = Random.Range(_componentSpaceMin, _componentSpaceMax);
foreach (Face face in faces)
face.ConstructFaceComponents(component_width, inbetween_space);
}
private void ConstructRoof()
{
roofBase = new RoofBase(this);
if (parent.roofBaseMaterial == null)
{
var list = MaterialManager.Instance.GetCollection("mat_roof_base");
roofBase.material = list[Random.Range(0, list.Count - 1)];
}
else
roofBase.material = parent.roofBaseMaterial;
parent.AddCombinable(roofBase.material.name, roofBase);
int maxcpf = Mathf.Max(faces[0].componentsPerFloor, faces[1].componentsPerFloor);
if (parent.roofType == null)
{
int n = Util.RollDice(new float[] { 0.33f, 0.33f, 0.34f });
if (n == 1)
roof = new FlatRoof(this);
else if (n == 2 && maxcpf <= 3)
roof = new SinglePeakRoof(this);
else
roof = new DoublePeakRoof(this);
}
else
{
var ctors = parent.roofType.GetConstructors(BindingFlags.Instance |
BindingFlags.Public);
roof = (Roof) ctors[0].Invoke(new object[] { this });
}
if (parent.roofMaterial == null)
{
var list = MaterialManager.Instance.GetCollection("mat_roof");
if (roof.GetType().Equals(typeof(FlatRoof)))
roof.material = list[Random.Range(0, 2)];
else
roof.material = list[Random.Range(0, list.Count - 1)];
}
else
roof.material = parent.roofMaterial;
parent.AddCombinable(roof.material.name, roof);
}
public override void FindVertices ()
{
int vert_count = 0;
for (int i = 0; i < 4; ++i)
{
faces[i].FindVertices();
vert_count += faces[i].vertices.Length;
}
vertices = new Vector3[vert_count + 4];
// add roof vertices first
for (int i = 0; i < 4; ++i)
vertices[i] = boundaries[i + 4];
// copy the vertices of the faces to this.vertices
// index starts from 4 because of roof vertices
int index = 4;
for (int i = 0; i < 4; ++i)
{
System.Array.Copy(faces[i].vertices, 0, vertices, index, faces[i].vertices.Length);
index += faces[i].vertices.Length;
}
}
public override void FindTriangles ()
{
int tris_count = 0;
for (int i = 0; i < 4; ++i)
if (faces[i].componentsPerFloor == 0)
tris_count += 2;
else
tris_count += floorCount * (6 * faces[i].componentsPerFloor + 2);
triangles = new int[tris_count * 3];
// triangles index
int trin = 0;
int offset = 4;
for (int face = 0; face < 4; ++face)
{
if (faces[face].componentsPerFloor == 0)
{
triangles[trin++] = offset;
triangles[trin++] = offset + 1;
triangles[trin++] = offset + 2;
triangles[trin++] = offset;
triangles[trin++] = offset + 2;
triangles[trin++] = offset + 3;
}
else
{
for (int floor = 0; floor < floorCount; ++floor)
{
int fixedOffset = offset + faces[face].edgeVerticesCount +
8 * faces[face].componentsPerFloor * floor;
int cpfX6 = 6 * faces[face].componentsPerFloor;
int floorX2 = 2 * floor;
triangles[trin++] = offset + floorX2;
triangles[trin++] = fixedOffset;
triangles[trin++] = offset + floorX2 + 2;
triangles[trin++] = fixedOffset;
triangles[trin++] = fixedOffset + cpfX6;
triangles[trin++] = offset + floorX2 + 2;
// wall between each component
int index = fixedOffset + 1;
for (int i = 1; i < faces[face].componentsPerFloor; ++i)
{
triangles[trin++] = index;
triangles[trin++] = index + 1;
triangles[trin++] = index + cpfX6;
triangles[trin++] = index + 1;
triangles[trin++] = index + cpfX6 + 1;
triangles[trin++] = index + cpfX6;
index += 2;
}
triangles[trin++] = index;
triangles[trin++] = offset + floorX2 + 1;
triangles[trin++] = index + cpfX6;
triangles[trin++] = offset + floorX2 + 1;
triangles[trin++] = offset + floorX2 + 3;
triangles[trin++] = index + cpfX6;
// wall over and under each component
for (int i = 0; i < faces[face].componentsPerFloor; ++i)
{
int extOffset = fixedOffset + (i << 1);
// under
triangles[trin++] = extOffset;
triangles[trin++] = extOffset + 1;
triangles[trin++] = extOffset + 2 * faces[face].componentsPerFloor;
triangles[trin++] = extOffset + 1;
triangles[trin++] = extOffset + 2 * faces[face].componentsPerFloor + 1;
triangles[trin++] = extOffset + 2 * faces[face].componentsPerFloor;
// over
triangles[trin++] = extOffset + 4 * faces[face].componentsPerFloor;
triangles[trin++] = extOffset + 4 * faces[face].componentsPerFloor + 1;
triangles[trin++] = extOffset + cpfX6;
triangles[trin++] = extOffset + 4 * faces[face].componentsPerFloor + 1;
triangles[trin++] = extOffset + cpfX6 + 1;
triangles[trin++] = extOffset + cpfX6;
}
}
}
offset += faces[face].vertices.Length;
}
}
public override void Draw ()
{
base.Draw();
foreach (Face face in faces)
foreach (FaceComponent component in face.faceComponents)
component.Draw();
gameObject.transform.position = meshOrigin;
gameObject.transform.parent = parent.gameObject.transform;
roof.FindVertices();
roof.FindTriangles();
roof.Draw();
roofBase.FindVertices();
roofBase.FindTriangles();
roofBase.Draw();
}
/// <summary>
/// Sorts the faces of the building by width.
/// </summary>
public void SortFaces (bool descending = true)
{
List<KeyValuePair<int, float>> lkv = new List<KeyValuePair<int, float>>();
for (int i = 0; i < faces.Count; ++i)
lkv.Add(new KeyValuePair<int, float>(i, faces[i].width));
if (descending)
lkv.Sort(delegate (KeyValuePair<int, float> x, KeyValuePair<int, float> y)
{
return y.Value.CompareTo(x.Value);
});
else
lkv.Sort(delegate (KeyValuePair<int, float> x, KeyValuePair<int, float> y)
{
return x.Value.CompareTo(y.Value);
});
sortedFaces = new int[lkv.Count];
for (int i = 0; i < lkv.Count; ++i)
sortedFaces[i] = lkv[i].Key;
}
public override void Destroy()
{
base.Destroy();
foreach (Face face in faces)
face.Destroy();
roof.Destroy();
roofBase.Destroy();
}
}
} // namespace Thesis |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CSConsoleRL.Game.Managers;
using CSConsoleRL.Components;
using CSConsoleRL.Components.Interfaces;
using CSConsoleRL.Events;
using CSConsoleRL.Entities;
using CSConsoleRL.Enums;
using GameTiles.Tiles;
using CSConsoleRL.Data;
namespace CSConsoleRL.GameSystems
{
public class InventorySystem : GameSystem
{
public InventorySystem(GameSystemManager manager)
{
SystemManager = manager;
_systemEntities = new List<Entity>();
}
public override void InitializeSystem()
{
}
public override void AddEntity(Entity entity)
{
if (entity.Components.ContainsKey(typeof(InventoryComponent)))
{
_systemEntities.Add(entity);
}
}
public override void HandleMessage(IGameEvent gameEvent)
{
switch (gameEvent.EventName)
{
case "RequestActiveItem":
{
var id = (Guid)gameEvent.EventParams[0];
SystemManager.BroadcastEvent(new SendActiveItemEvent(GetActiveItemForEntity(id)));
break;
}
case "ChangeActiveItem":
{
var id = (Guid)gameEvent.EventParams[0];
var ent = _systemEntities.Where(e => e.Id == id).FirstOrDefault();
if (ent != null) ent.GetComponent<InventoryComponent>().IncrementActiveItem();
break;
}
}
}
private Item GetActiveItemForEntity(Guid id)
{
var entity = _systemEntities.Where(ent => ent.Id == id).First();
var inventory = entity.GetComponent<InventoryComponent>();
return inventory.GetActiveItem();
}
}
}
|
using gView.Framework.Geometry;
using gView.GraphicsEngine.Abstraction;
using System;
namespace gView.Framework.Data
{
public interface IRasterPaintContext : IDisposable
{
IBitmap Bitmap { get; }
}
public interface IRasterPointContext2 : IRasterPaintContext
{
IPoint PicPoint1 { get; }
IPoint PicPoint2 { get; }
IPoint PicPoint3 { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Threading;
using IRAP.Global;
using IRAP.Entity.SSO;
using IRAP.WCF.Client.Method;
namespace IRAP.Client.SubSystems
{
public class AvailableWorkUnits
{
private static string className =
MethodBase.GetCurrentMethod().DeclaringType.FullName;
private static AvailableWorkUnits _instance = null;
private int processLeaf = 0;
private List<WorkUnitInfo> _workUnits = new List<WorkUnitInfo>();
private AvailableWorkUnits()
{
}
public static AvailableWorkUnits Instance
{
get
{
if (_instance == null)
_instance = new AvailableWorkUnits();
return _instance;
}
}
public int ProcessLeaf
{
get { return processLeaf; }
}
public List<WorkUnitInfo> WorkUnits
{
get { return _workUnits; }
}
public int GetWorkUnits(int communityID, long sysLogID, int processLeaf)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
int errCode = 0;
string errText = "";
_workUnits.Clear();
IRAPSystemClient.Instance.ufn_GetKanban_WorkUnits(
communityID,
sysLogID,
processLeaf,
ref _workUnits,
out errCode,
out errText);
WriteLog.Instance.Write(
string.Format("({0}){1}", errCode, errText),
strProcedureName);
if (errCode == 0)
return _workUnits.Count;
else
throw new Exception(errText);
}
catch (Exception error)
{
WriteLog.Instance.Write(error.Message, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en")
throw new Exception(
string.Format(
"Unable to obtain stations/functions, reason: {0}",
error.Message));
else
throw new Exception(
string.Format(
"无法获取工位/功能,原因:{0}",
error.Message));
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
public int IndexOf(WorkUnitInfo workUnit)
{
for (int i = 0; i < _workUnits.Count; i++)
{
if (WorkUnits[i].WorkUnitLeaf == workUnit.WorkUnitLeaf)
return i;
}
return -1;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using com.Sconit.Entity.SYS;
using System.ComponentModel.DataAnnotations;
namespace com.Sconit.Entity.CUST
{
public partial class SubPrintOrder
{
[Display(Name = "UserId", ResourceType = typeof(Resources.CUST.SubPrintOrder))]
public string UserCode { get; set; }
[Display(Name = "ExcelTemplate", ResourceType = typeof(Resources.CUST.SubPrintOrder))]
public string ExcelTemplateDescription { get; set; }
}
}
|
namespace ProjetctTiGr13.Domain.FicheComponent
{
public class HealthPointManager
{
public int MaxHp { get; set; }
public int CurrentHp { get; set; }
public int TemporaryHp { get; set; }
public int HpDice { get; set;}
public HealthPointManager()
{
MaxHp = 0;
CurrentHp = 0;
TemporaryHp = 0;
HpDice = 0;
}
}
} |
using OnboardingSIGDB1.Domain.Funcionarios.Validators;
using OnboardingSIGDB1.Domain.Interfaces;
using OnboardingSIGDB1.Domain.Notifications;
using System.Linq;
using System.Threading.Tasks;
namespace OnboardingSIGDB1.Domain.Funcionarios.Services
{
public class VinculadorDeFuncionarioEmpresa
{
private readonly IFuncionarioRepository _funcionarioRepository;
private readonly NotificationContext _notificationContext;
private readonly IValidadorFuncionarioPossuiAlgumaEmpresaVinculada _validadorFuncionarioPossuiAlgumaEmpresaVinculada;
public VinculadorDeFuncionarioEmpresa(IFuncionarioRepository funcionarioRepository,
NotificationContext notificationContext,
IValidadorFuncionarioPossuiAlgumaEmpresaVinculada validadorFuncionarioPossuiAlgumaEmpresaVinculada)
{
_funcionarioRepository = funcionarioRepository;
_notificationContext = notificationContext;
_validadorFuncionarioPossuiAlgumaEmpresaVinculada = validadorFuncionarioPossuiAlgumaEmpresaVinculada;
}
public async Task Vincular(long funcionarioId, long empresaId)
{
var funcionario = (
await _funcionarioRepository
.GetWithIncludes(f => f.Id == funcionarioId)
).FirstOrDefault();
_validadorFuncionarioPossuiAlgumaEmpresaVinculada.Valid(funcionario);
if (_notificationContext.HasNotifications)
{
return;
}
funcionario.AlterarEmpresaId(empresaId);
await _funcionarioRepository.Update(funcionario);
}
}
}
|
using System;
using Microsoft.VisualBasic;
namespace CreatingCustomStrucutres
{
public class CoolList<T>
{
private int capacity;
private T[] data;
public int Count { get; private set; }
public CoolList():
this(4)
{
}
public CoolList(int capacity)
{
this.capacity = capacity;
this.data = new T[capacity];
}
public void Add(T element)
{
if (this.Count == data.Length - 1)
{
Resize();
}
data[this.Count] = element;
this.Count++;
}
public void Swap(int index, int index2)
{
this.ValidateIndex(index);
this.ValidateIndex(index2);
var temp = this.data[index];
this.data[index] = this.data[index2];
this.data[index2] = temp;
}
public T RemoveAt(int index)
{
if (this.Count == this.capacity/2)
{
Shrink();
}
this.ValidateIndex(index);
var removed = this.data[index];
for (int i = index + 1; i < this.Count; i++)
{
this.data[i - 1] = this.data[i];
}
this.Count--;
return removed;
}
public void Clear()
{
this.data = new T[this.capacity];
this.Count = 0;
}
public T this[int index]
{
get
{
this.ValidateIndex(index);
return this.data[index];
}
set
{
this.ValidateIndex(index);
this.data[index] = value;
}
}
private void Shrink()
{
var resizedData = new T[capacity / 2];
this.capacity /= 2;
for (int i = 0; i < resizedData.Length; i++)
{
resizedData[i] = this.data[i];
}
this.data = resizedData;
}
private void Resize()
{
var resizedData = new T[capacity * 2];
this.capacity *= 2;
for (int i = 0; i < this.data.Length; i++)
{
resizedData[i] = this.data[i];
}
this.data = resizedData;
}
private void ValidateIndex(int index)
{
if (index < 0 || index >= this.Count)
{
throw new IndexOutOfRangeException("Index is out of range");
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class CardType : ScriptableObject
{
// would use this class to either init type specific things (text etc)
// or to perform type specific actions
public abstract void OnInitCard();
public abstract string GetTypeString();
public abstract int CardTypeID { get; }
}
|
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 RiveScript;
namespace SentimentAnalysis
{
public partial class frmChat : Form
{
RiveScript.RiveScript bot = new RiveScript.RiveScript();
public frmChat()
{
InitializeComponent();
bot.loadFile(@".\bot.rive");
bot.sortReplies();
}
private void btnSend_Click(object sender, EventArgs e)
{
listMessages.Items.Add("(You) : " + txtMsg.Text);
var reply = bot.reply("local_user", txtMsg.Text);
listMessages.Items.Add("(bot) : " + reply);
}
}
}
|
using Allyn.Domain.Models.Front;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Allyn.Infrastructure.EfRepositories.ModelConfigurations
{
internal class MemberTypeConfiguration : EntityTypeConfiguration<Member>
{
internal MemberTypeConfiguration()
{
ToTable("FMember");
HasKey(k => k.Id)
.Property(p => p.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(p=>p.Name)
.HasColumnType("varchar")
.HasMaxLength(20);
Property(p => p.Avatar)
.HasColumnType("varchar")
.HasMaxLength(200);
Property(p => p.Address)
.HasColumnType("varchar")
.HasMaxLength(200);
Property(p => p.Longitude)
.IsOptional()
.HasPrecision(18, 7);
Property(p => p.Latitude)
.IsOptional()
.HasPrecision(18, 7);
Property(p => p.Description)
.HasColumnType("varchar")
.HasMaxLength(300);
Property(p => p.Modifier)
.IsOptional();
Property(p => p.UpdateDate)
.IsOptional();
Property(p => p.NickName)
.HasColumnType("varchar")
.HasMaxLength(20);
Property(p => p.Phone)
.HasColumnType("varchar")
.HasMaxLength(20);
Property(p => p.Sex)
.HasColumnType("varchar")
.HasMaxLength(5);
Property(p => p.OpenKey)
.IsRequired()
.HasColumnType("varchar")
.HasMaxLength(32);
Property(p => p.GuideKey)
.HasColumnType("varchar")
.HasMaxLength(32);
Property(p => p.Estate)
.HasPrecision(18, 2);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SinusSkateboardsWebApp.Models;
using SinusSkateboardsWebApp.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace SinusSkateboardsWebApp.Controllers
{
public class HomeController : Controller
{
private readonly IProductRepository _productRepository;
private readonly AppDbContext appDbContext;
public HomeController(IProductRepository productRepository, AppDbContext appDbContext)
{
_productRepository = productRepository;
this.appDbContext = appDbContext;
}
public IActionResult Index()
{
var homeViewModel = new HomeViewModel
{
ProductsOfTheWeek = _productRepository.SaleOfTheWeek
};
return View(homeViewModel);
}
public async Task<IActionResult> Search(string searchstring)
{
var products = from p in appDbContext.Product.Include(x => x.ColorCategory).Include(x => x.Category)
select p;
if (!String.IsNullOrEmpty(searchstring))
{
products = products.Where(s => s.Titel.Contains(searchstring) || s.ColorCategory.ColorName.Contains(searchstring) || s.Category.CategoryName.Contains(searchstring));
}
return View(await products.ToListAsync());
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Lighter : Interactable {
public override void Activate()
{
base.Activate();
if (!burning)
{
Burn();
fireScript.canSpread = true;
}
else Deactivate();
}
public override void Deactivate()
{
StopBurning();
}
}
|
using UnityEngine;
namespace UnityAtoms.BaseAtoms
{
/// <summary>
/// Event Reference Listener of type `Vector2Pair`. Inherits from `AtomEventReferenceListener<Vector2Pair, Vector2PairEvent, Vector2PairEventReference, Vector2PairUnityEvent>`.
/// </summary>
[EditorIcon("atom-icon-orange")]
[AddComponentMenu("Unity Atoms/Listeners/Vector2Pair Event Reference Listener")]
public sealed class Vector2PairEventReferenceListener : AtomEventReferenceListener<
Vector2Pair,
Vector2PairEvent,
Vector2PairEventReference,
Vector2PairUnityEvent>
{ }
}
|
namespace NomNom.Domain.Models {
public class Monitor {
public string Destination { get; set; }
public string Name { get; set; }
public string Source { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GoogleCloudSamples.Models
{
/// <summary>
/// An interface for storing teams. Can be implemented by a database,
/// Google Datastore, etc.
/// </summary>
public interface ITeamList
{
/// <summary>
/// Creates a new team. The Id of the team will be filled when the
/// function returns.
/// </summary>
void Create(Team team);
Team Read(long id);
void Update(Team team);
void Delete(long id);
TeamList List(int pageSize, string nextPageToken);
}
/// <summary>
/// Implements ITeamList with a database.
/// </summary>
public class DBTeamList : ITeamList
{
private readonly ApplicationDbContext _dbcontext;
public DBTeamList(ApplicationDbContext dbcontext)
{
_dbcontext = dbcontext;
}
// [START create]
public void Create(Team team)
{
var trackteam = _dbcontext.Teams.Add(team);
_dbcontext.SaveChanges();
team.TeamId = trackteam.TeamId;
}
// [END create]
public void Delete(long id)
{
Team team = _dbcontext.Teams.Single(m => m.TeamId == id);
_dbcontext.Teams.Remove(team);
_dbcontext.SaveChanges();
}
// [START list]
public TeamList List(int pageSize, string nextPageToken)
{
IQueryable<Team> query = _dbcontext.Teams.OrderBy(team => team.TeamId);
var teams = query.ToArray();
return new TeamList()
{
Teams = teams.ToList()
};
}
// [END list]
public Team Read(long id)
{
return _dbcontext.Teams.Single(m => m.TeamId == id);
}
public void Update(Team team)
{
_dbcontext.Entry(team).State = System.Data.Entity.EntityState.Modified;
_dbcontext.SaveChanges();
}
}
} |
namespace HospitalDatabase.Models
{
using System;
public class Comment
{
public int CommentId { get; set; }
public string Text { get; set; }
public int AuthorId { get; set; }
public virtual Visitation Visitation { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.Grid;
using System.Drawing.Imaging;
using System.Runtime.Serialization.Formatters.Binary;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Base;
namespace Utilities
{
public class ClsCommonFn : ClsCommonUiFn
{
enum Mode
{
New = 1,
Edit = 2,
Delete = 3,
View = 4,
Print = 5,
Preview = 6
}
public void ClearFields(Control parent)
{
// Optimised Version - Coder - Mz
//DevExpress.XtraEditors.DateEdit
foreach (Control c in parent.Controls)
{
bool searchParent = true;
if (c.GetType().ToString().Equals("DevExpress.XtraEditors.GridLookUpEdit") ||
c.GetType().ToString().Equals("CustomControlz.XtraEditors.LookUps.ccGridLookUpEdit"))
{
((GridLookUpEdit)c).EditValue = null;
searchParent = false;
}
if (c.GetType().ToString().Equals("DevExpress.XtraEditors.ComboBoxEdit"))
{
((ComboBoxEdit)c).EditValue = null;
searchParent = false;
}
else if (c.GetType().ToString().Equals("DevExpress.XtraEditors.TextEdit")
|| c.GetType().ToString().Equals("pms_Utilities.CustomControls.PMS_TextEditReadOnly"))
{
((TextEdit)c).EditValue = null;
searchParent = false;
}
else if (c.GetType().ToString().Equals("pms_Utilities.CustomControls.PMS_TextEditNumeric"))
{
((TextEdit)c).EditValue = 0;
searchParent = false;
}
else if (c.GetType().ToString().Equals("DevExpress.XtraEditors.DateEdit") || c.GetType().ToString().Equals("pms_Utilities.CustomControls.PMS_DateEdit"))
{
searchParent = false;
}
else if (c.GetType().ToString().Equals("DevExpress.XtraGrid.GridControl"))
{
if (((GridControl)c).Tag == null || ((GridControl)c).Tag == "")
{
((GridControl)c).DataSource = null;
searchParent = false;
}
}
else if (c.GetType().ToString().Equals("DevExpress.XtraTreeList.TreeList"))
{
((DevExpress.XtraTreeList.TreeList)c).DataSource = null;
searchParent = false;
}
else if (c.GetType().ToString().Equals("DevExpress.XtraEditors.ButtonEdit"))
{
((ButtonEdit)c).EditValue = null;
searchParent = false;
}
else if (c.GetType().ToString().Equals("DevExpress.XtraEditors.HyperLinkEdit"))
{
searchParent = false;
}
if (searchParent)
{
if ((c.Controls.Count > 0))
{
ClearFields(c);
}
else
{
if (c.GetType().ToString().Equals("System.Windows.Forms.TextBox"))
{
((TextBox)(c)).Text = "";
}
else if (c.GetType().ToString().Equals("System.Windows.Forms.Label") && ((Label)(c)).Tag == "Y")
{
((Label)(c)).Text = "";
}
else if (c.GetType().ToString().Equals("System.Windows.Forms.ComboBox") && ((System.Windows.Forms.ComboBox)(c)).Tag != "N")
{
((System.Windows.Forms.ComboBox)(c)).SelectedIndex = 0;
}
else if (c.GetType().ToString().Equals("DevExpress.XtraEditors.TextBoxMaskBox"))
{
c.Text = "";
}
else if (c.GetType().ToString().Equals("System.Windows.Forms.NumericTB"))
{
c.Text = "";
}
}
}
}
}
public string SetDate(string strDate)
{
try
{
var cultEnGb = new CultureInfo("en-GB");
var dtGb = Convert.ToDateTime(strDate, cultEnGb.DateTimeFormat);
return dtGb.ToString();
}
catch
{
return string.Format("{0:MM/dd/yyyy}", DateTime.Today);
}
}
public string SetTime(string strTime)
{
try
{
var cultEnGb = new CultureInfo("en-GB");
var dtGb = Convert.ToDateTime(strTime, cultEnGb.DateTimeFormat);
return dtGb.ToString();
}
catch
{
return string.Format("{0:hh:mm:ss}", DateTime.Today);
}
}
public void Find_SysInfo()
{
//BAL.Global_Info.System_Name = Dns.GetHostName();
//var ipEntry = Dns.GetHostEntry(BAL.Global_Info.System_Name);
//var addr = ipEntry.AddressList;
//foreach (var ip in ipEntry.AddressList)
//{
// if (ip.AddressFamily.ToString() == "InterNetwork")
// {
// BAL.Global_Info.System_IP = ip.ToString();
// break;
// }
//}
}
public string FormatDate(string format, DateTime date)
{
return string.Format("{0:" + format + "}", date);
}
public DateTime ConvertDateToMdyFormat(string dt)
{
var convDate = DateTime.Now;
try
{
convDate = DateTime.ParseExact(dt, "MM/dd/yyyy", null);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return convDate;
}
public double ConvertToDbl(string strVal)
{
double outVal;
double.TryParse(strVal.ToString().Trim(), NumberStyles.Float, CultureInfo.CurrentCulture, out outVal);
return outVal;
}
public DateTime ConvertToDate(string strVal)
{
DateTime outVal;
DateTime.TryParse(strVal.ToString().Trim(), out outVal);
return outVal;
}
public decimal ConvertToDecimal(string strVal)
{
decimal outVal;
decimal.TryParse(strVal.ToString().Trim(), NumberStyles.Float, CultureInfo.CurrentCulture, out outVal);
return outVal;
}
public int ConvertToIntVal(string strVal)
{
int outVal;
int.TryParse(strVal.ToString().Trim(), NumberStyles.Any, CultureInfo.CurrentCulture, out outVal);
return outVal;
}
public decimal ConvetDecimalToUpper(decimal value)
{
decimal outValue = 0;
decimal fValue = 0;
try
{
fValue = value - Math.Floor(value);
fValue = 1 - fValue;
if (fValue < 1)
{
outValue = value + fValue;
}
else
{
outValue = value;
}
}
catch
{
}
return outValue;
}
public void DecimalTb(TextEdit tb, KeyPressEventArgs e)
{
try
{
if (tb.Tag == "int")
{
#region int
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
#endregion
}
if (tb.Tag == "decT")
{
#region Decimal 2 Digits
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.'
&& tb.Text.IndexOf('.') > -1)
{
e.Handled = true;
}
if (tb.Text.IndexOf('.') >= 0)
{
var dInd = tb.Text.IndexOf('.');
var kInd = (int)tb.SelectionStart + tb.SelectionLength;
var x = tb.Text.Split('.');
var y = x[0].Length;
var z = x[1].Length;
if (kInd > dInd)
{
if (z >= 2)
{
if (char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
}
}
#endregion
}
if (tb.Tag == "dec3")
{
#region Decimal 3 Digits
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.'
&& tb.Text.IndexOf('.') > -1)
{
e.Handled = true;
}
if (tb.Text.IndexOf('.') >= 0)
{
var dInd = tb.Text.IndexOf('.');
var kInd = (int)tb.SelectionStart + tb.SelectionLength;
var x = tb.Text.Split('.');
var y = x[0].Length;
var z = x[1].Length;
if (kInd > dInd)
{
if (z >= 3)
{
if (char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
}
}
#endregion
}
if (tb.Tag == "decF")
{
#region Decimal Four
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.'
&& tb.Text.IndexOf('.') > -1)
{
e.Handled = true;
}
if (tb.Text.IndexOf('.') > 0)
{
var dInd = tb.Text.IndexOf('.');
var kInd = (int)tb.SelectionStart + tb.SelectionLength;
var x = tb.Text.Split('.');
var y = x[0].Length;
var z = x[1].Length;
if (kInd > dInd)
{
if (z >= 4)
{
if (char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
}
}
#endregion
}
}
catch
{
e.Handled = true;
}
}
public Image ByteToImage(byte[] imgBytes)
{
try
{
// Convert Base64 String to byte[]
//byte[] imgBytes = Convert.FromBase64String(base64String);
var ms = new MemoryStream(imgBytes, 0,
imgBytes.Length);
// Convert byte[] to Image
ms.Write(imgBytes, 0, imgBytes.Length);
var image = Image.FromStream(ms, true);
return image;
}
catch (Exception e)
{
Console.WriteLine(e);
return null;
}
}
public byte[] ImageToByte2(Image img, ImageFormat format)
{
var byteArray = new byte[0];
using (var stream = new MemoryStream())
{
img.Save(stream, format);
stream.Close();
byteArray = stream.ToArray();
}
return byteArray;
}
public void ParseEditValue(GridView gridView, ConvertEditValueEventArgs e)
{
if (Convert.ToDecimal(e.Value) > 0)
{
var noDecPlaces = gridView.GetFocusedRowCellValue("NoDecPlace");
if (noDecPlaces != null) e.Value = Convert.ToDecimal(e.Value).ToString(noDecPlaces.ToString());
e.Handled = true;
}
}
public string GetTag(object noDecPlaces)
{
if (noDecPlaces != null)
{
var x = noDecPlaces.ToString();
if (x.Contains('.'))
{
var len = x.Split('.')[1].Length;
switch (len)
{
case 2:
return "decT";
break;
case 3:
return "dec3";
break;
case 4:
return "decF";
break;
}
}
}
return "int";
}
public string GetRandomAplhaNumericNo(int length)
{
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var random = new Random();
var result = new string(
Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)])
.ToArray());
return result;
}
public void SendMail(string mailId, string subject, string body)
{
var mail = new MailMessage();
var smtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("noreply.pms@gmail.com");
mail.To.Add(mailId);
mail.Subject = subject;
mail.Body = body;
smtpServer.Port = 587;
smtpServer.Credentials = new NetworkCredential("noreply.pms@gmail.com", "referral15");
smtpServer.EnableSsl = true;
smtpServer.Send(mail);
Console.WriteLine("Mail Send");
}
public void SetConnString(ConnectionStringSettings connString)
{
connString.ConnectionString = connString.ConnectionString.Replace(@"data source\W", "data source = ");
}
public string GetMachineKey()
{
string key = "";
var clsReg = new ClsRegistry();
//if (clsReg.ValueCount() == 0)
//{
// clsReg.Write("ServerName", "MzRokz");
// var x = clsReg.Read("ServerName");
//}
foreach (var item in clsReg.MachineKey("Win32_Processor"))
{
foreach (var prop in item.Properties)
{
if (prop.Name == "ProcessorId")
{
key += prop.Value.ToString();
break;
}
}
break;
}
foreach (var item in clsReg.MachineKey("Win32_NetworkAdapter"))
{
foreach (var prop in item.Properties)
{
if (prop.Name == "ProcessorId")
{
key += prop.Value.ToString();
break;
}
}
}
return "";
}
public void DisableControls(Control parent, bool val, ClsGlobalVarz.Mode mode = ClsGlobalVarz.Mode.Open)
{
foreach (Control c in parent.Controls)
{
bool searchParent = true;
if (c.GetType().ToString().Equals("DevExpress.XtraEditors.GridLookUpEdit") ||
c.GetType().ToString().Equals("CustomControlz.XtraEditors.LookUps.ccGridLookUpEdit"))
{
var control = (GridLookUpEdit)c;
var tag = control.Tag;
if (tag != null)
{
if (tag.ToString() == "ne" && val)
control.Properties.ReadOnly = val;
else if (tag.ToString() == "ne" && !val && mode == ClsGlobalVarz.Mode.Add)
control.Properties.ReadOnly = val;
}
else
control.Properties.ReadOnly = val;
//if (tag != null && tag.ToString() == "ne" && val)
// control.Properties.ReadOnly = val;
//else if (tag != null && tag.ToString() != "ne")
// control.Properties.ReadOnly = val;
searchParent = false;
}
if (c.GetType().ToString().Equals("DevExpress.XtraEditors.ComboBoxEdit") ||
c.GetType().ToString().Equals("CustomControlz.XtraEditors.Comboz.ccComboBoxEdit"))
{
((ComboBoxEdit)c).Properties.ReadOnly = val;
searchParent = false;
}
else if (c.GetType().ToString().Equals("DevExpress.XtraEditors.TextEdit")
|| c.GetType().ToString().Equals("CustomControlz.XtraEditors.TextEdits.ccTextEdit"))
{
var control = (TextEdit)c;
var tag = control.Tag;
if (tag != null)
{
if (tag.ToString() == "ne" && val)
control.Properties.ReadOnly = val;
else if (tag.ToString() == "ne" && !val && mode == ClsGlobalVarz.Mode.Add)
control.Properties.ReadOnly = val;
else
return;
}
control.Properties.ReadOnly = val;
//if (tag != null && tag.ToString() == "ne" && val)
// control.Properties.ReadOnly = val;
//else if (tag == null)
// control.Properties.ReadOnly = val;
//else if (tag != null && tag.ToString() != "ne")
// control.Properties.ReadOnly = val;
searchParent = false;
}
else if (c.GetType().ToString().Equals("pms_Utilities.CustomControls.PMS_TextEditNumeric"))
{
((TextEdit)c).EditValue = 0;
searchParent = false;
}
else if (c.GetType().ToString().Equals("DevExpress.XtraEditors.DateEdit") || c.GetType().ToString().Equals("pms_Utilities.CustomControls.PMS_DateEdit"))
{
((DateEdit)c).Properties.ReadOnly = val;
searchParent = false;
}
else if (c.GetType().ToString().Equals("DevExpress.XtraGrid.GridControl"))
{
if (((GridControl)c).Tag == null || ((GridControl)c).Tag == "")
{
((GridView)((GridControl)c).MainView).OptionsBehavior.Editable = !val;
searchParent = false;
}
}
else if (c.GetType().ToString().Equals("DevExpress.XtraTreeList.TreeList"))
{
((DevExpress.XtraTreeList.TreeList)c).Enabled = !val;
searchParent = false;
}
else if (c.GetType().ToString().Equals("DevExpress.XtraEditors.ButtonEdit"))
{
((ButtonEdit)c).Enabled = !val;
searchParent = false;
}
else if (c.GetType().ToString().Equals("DevExpress.XtraEditors.HyperLinkEdit"))
{
((HyperLinkEdit)c).Enabled = !val;
searchParent = false;
}
if (searchParent)
{
if ((c.Controls.Count > 0))
{
DisableControls(c, val, mode);
}
}
}
}
/// <summary>
/// Pass and object to deep clone it without reference.
/// </summary>
/// <param name="obj">The object to clone from.</param>
/// <returns></returns>
public object Clone(object obj)
{
using (MemoryStream buffer = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(buffer, obj);
buffer.Position = 0;
object temp = formatter.Deserialize(buffer);
return temp;
}
}
}
public class ClsCommonUiFn
{
public void GridSetting(GridView gridView1, GridControl gridControl)
{
gridView1.BorderStyle = BorderStyles.Simple;
gridView1.OptionsCustomization.AllowQuickHideColumns = false;
gridView1.OptionsCustomization.AllowFilter = false;
gridView1.OptionsCustomization.AllowSort = false;
gridView1.OptionsMenu.EnableColumnMenu = false;
gridView1.OptionsMenu.EnableFooterMenu = false;
gridView1.OptionsView.ShowDetailButtons = false;
gridView1.OptionsView.ShowGroupPanel = false;
gridView1.OptionsView.ShowIndicator = false;
// Money Twins
gridControl.LookAndFeel.SkinName = "Money Twins";
//GridControl.LookAndFeel.UseDefaultLookAndFeel = true;
gridView1.Appearance.HeaderPanel.Font = new Font("Arial", 8, FontStyle.Bold);
gridView1.Appearance.Row.Font = new Font("Arial", 8);
for (var i = 0; i < gridView1.Columns.Count; i++)
{
var fieldName = gridView1.Columns[i].Caption.ToUpper(CultureInfo.InvariantCulture);
gridView1.Columns[i].Caption = fieldName;
}
gridView1.PostEditor();
}
public void GridSettingReport(GridView gridView1, GridControl gridControl)
{
gridView1.BorderStyle = BorderStyles.Simple;
gridView1.OptionsCustomization.AllowQuickHideColumns = false;
gridView1.OptionsCustomization.AllowSort = true;
gridView1.OptionsCustomization.AllowColumnResizing = true;
gridView1.OptionsCustomization.AllowFilter = true;
gridView1.OptionsNavigation.EnterMoveNextColumn = true;
gridView1.OptionsNavigation.UseTabKey = false;
gridView1.OptionsMenu.EnableColumnMenu = true;
gridView1.OptionsMenu.EnableFooterMenu = false;
gridView1.OptionsBehavior.Editable = false;
gridView1.OptionsView.ShowDetailButtons = false;
gridView1.OptionsView.ShowGroupPanel = false;
gridView1.OptionsView.ShowIndicator = false;
gridControl.LookAndFeel.UseDefaultLookAndFeel = false;
//Office 2007 Silver
gridControl.LookAndFeel.SkinName = "Money Twins";
gridView1.Appearance.HeaderPanel.Font = new Font("Arial", 8, FontStyle.Bold);
gridView1.Appearance.Row.Font = new Font("Arial", 8);
for (var i = 0; i < gridView1.Columns.Count; i++)
{
var fieldName = gridView1.Columns[i].Caption.ToUpper(CultureInfo.InvariantCulture);
gridView1.Columns[i].Caption = fieldName;
}
gridView1.PostEditor();
}
public void GroupControl_Setting(GroupControl grpControl)
{
grpControl.LookAndFeel.SkinName = "DevExpress Style";
grpControl.Text = grpControl.Text.ToUpper();
}
public void GridLookUpSetting(GridLookUpEdit gridLookUp, bool showFilterRow = false)
{
gridLookUp.Properties.View.OptionsCustomization.AllowQuickHideColumns = false;
gridLookUp.Properties.View.OptionsCustomization.AllowSort = false;
gridLookUp.Properties.View.OptionsMenu.EnableFooterMenu = false;
gridLookUp.Properties.View.OptionsMenu.EnableColumnMenu = false;
gridLookUp.Properties.View.OptionsCustomization.AllowSort = false;
gridLookUp.Properties.View.OptionsCustomization.AllowFilter = false;
gridLookUp.Properties.View.OptionsView.ShowIndicator = false;
gridLookUp.Properties.View.OptionsView.ShowViewCaption = false;
//gridLookUp.Properties.View.OptionsView.ShowColumnHeaders = false;
if (showFilterRow)
{
gridLookUp.Properties.View.OptionsView.ShowAutoFilterRow = true;
}
gridLookUp.Properties.ImmediatePopup = true;
gridLookUp.Properties.LookAndFeel.SkinName = "DevExpress Style";
gridLookUp.Properties.View.Appearance.HeaderPanel.Font = new Font("Arial", 8, FontStyle.Bold);
gridLookUp.Properties.View.Appearance.Row.Font = new Font("Arial", 8);
gridLookUp.Properties.PopupFormSize = new Size(gridLookUp.Size.Width, 200);
for (var i = 0; i < gridLookUp.Properties.View.Columns.Count; i++)
{
var fieldName = gridLookUp.Properties.View.Columns[i].Caption.ToUpper(CultureInfo.InvariantCulture);
gridLookUp.Properties.View.Columns[i].Caption = fieldName;
}
gridLookUp.Properties.View.PostEditor();
}
public void RepGridLookUpSetting(RepositoryItemGridLookUpEdit gridLookUp)
{
gridLookUp.View.OptionsCustomization.AllowQuickHideColumns = false;
gridLookUp.View.OptionsCustomization.AllowSort = false;
gridLookUp.View.OptionsMenu.EnableFooterMenu = false;
gridLookUp.View.OptionsMenu.EnableColumnMenu = false;
gridLookUp.View.OptionsView.ShowAutoFilterRow = true;
gridLookUp.ImmediatePopup = true;
gridLookUp.LookAndFeel.SkinName = "DevExpress Style";
gridLookUp.View.Appearance.HeaderPanel.Font = new Font("Arial", 8, FontStyle.Bold);
gridLookUp.View.Appearance.Row.Font = new Font("Arial", 8);
for (var i = 0; i < gridLookUp.View.Columns.Count; i++)
{
var fieldName = gridLookUp.View.Columns[i].Caption.ToUpper(CultureInfo.InvariantCulture);
gridLookUp.View.Columns[i].Caption = fieldName;
}
gridLookUp.View.PostEditor();
}
public void SetGridRowNo(GridView gridView1, string fldName = "")
{
object rowNoValue;
var varFldName = "";
if (fldName != "")
{
varFldName = fldName;
}
else
varFldName = "RowNo";
rowNoValue = gridView1.RowCount;
gridView1.SetFocusedRowCellValue(varFldName, rowNoValue);
for (var i = 0; i <= gridView1.RowCount - 1; i++)
{
rowNoValue = i + 1;
gridView1.SetRowCellValue(i, varFldName, rowNoValue);
}
}
public void SetColumnDecimalPlaces(RepositoryItemTextEdit repTe, GridView gridView, CustomColumnDisplayTextEventArgs e)
{
// Coder - Mz
// Summary: This function is to be called on the GridView's CustomColumnDisplayText Event's handle.
// 1st arg : The repository object associated with the column's ColumnEdit attribute.
// 2nd arg : Name of the repository object passed as string
// 3rd arg : GridView object
// 4th arg : CustomColumnDisplayTextEventArgs object.
try
{
if (e.Column.ColumnEdit == repTe && e.ListSourceRowIndex != GridControl.InvalidRowHandle && e.RowHandle > -1)
{
var noDecPlace = gridView.GetRowCellValue(e.RowHandle, "NoDecPlace").ToString().Trim();
//if (noDecPlace == "")
// noDecPlace = "0.0000";
e.DisplayText = String.Format("{0:" + noDecPlace + "}", e.Value);
//gridView.SetRowCellValue(e.RowHandle, e.Column, Convert.ToDouble(Convert.ToDouble(e.Value).ToString(noDecPlace)));
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
#region For Later use
//repTE.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
//repTE.DisplayFormat.FormatString = NoDecPlace;
//repTE.EditFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
//repTE.EditFormat.FormatString = NoDecPlace;
#endregion
}
public bool ValidateOpenRecord(long transId)
{
if (transId <= 0)
{
MessageBox.Show("Select Record To Edit Or Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
return true;
}
public bool IsValid(string msg)
{
MessageBox.Show(msg, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
public void TryCatchErrorMsg(string msg)
{
MessageBox.Show(msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
public void WarningMsg(string msg)
{
MessageBox.Show(msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
public void InfoMsg(string msg)
{
MessageBox.Show(msg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
public enum EColumnType { Numeric = 0, Date = 1, String = 2 }
public void SetColumnDisplayText(CustomColumnDisplayTextEventArgs e, EColumnType eColumnType)
{
if (eColumnType == EColumnType.Date)
{
if (e.DisplayText == "01/01/1900" || e.DisplayText == "01/01/001" || e.DisplayText == "01/01/0001")
{
e.DisplayText = "";
}
else if (e.DisplayText == "01-01-1900" || e.DisplayText == "01-01-001" || e.DisplayText == "01-01-0001")
{
e.DisplayText = "";
}
}
}
public enum EGridType { Rep = 0, Normal = 1 }
public void ClearColumnFilter(object sender, EGridType eGridType)
{
if (eGridType == EGridType.Rep)
{
var luc = sender as GridLookUpEdit;
if (luc != null) luc.Properties.View.ClearColumnsFilter();
}
else if (eGridType == EGridType.Normal)
{
var luc = sender as GridLookUpEdit;
if (luc != null) luc.Properties.View.ClearColumnsFilter();
}
}
public void MsgBoxCrud(ClsGlobalVarz.Mode mode)
{
if (mode == ClsGlobalVarz.Mode.Add)
MessageBox.Show("Record Saved", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
else if (mode == ClsGlobalVarz.Mode.Edit)
MessageBox.Show("Record Updated", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
else if (mode == ClsGlobalVarz.Mode.Delete)
MessageBox.Show("Record Deleted", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
public bool ValidateCrud(ClsGlobalVarz.Mode mode)
{
var x = false;
if (mode == ClsGlobalVarz.Mode.Add)
x = DialogResult.Yes ==
MessageBox.Show("Do You Want To Save Record ?", "ALERT", MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
else if (mode == ClsGlobalVarz.Mode.Edit)
x = DialogResult.Yes ==
MessageBox.Show("Do You Want To Update Record ?", "ALERT", MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
else if (mode == ClsGlobalVarz.Mode.Delete)
x = DialogResult.Yes ==
MessageBox.Show("Do You Want To Delete Record ?", "ALERT", MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
return x;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using InRule.Repository;
using InRule.Repository.Client;
using InRule.Repository.DecisionTables;
using InRule.Repository.RuleElements;
using InRule.Repository.Service.Data;
using InRule.Runtime;
namespace InRule.RuleApplicationFramework
{
public static class RuleEngineUtil
{
//hack when we lose ability to obtain ruleappdef deep in def model (ie within decision table action defs )
private static RuleApplicationDef _workingRuleAppDef = null;
#region IO related
public static IEnumerable<string> GetRuleApplicationListFromFileSystem(string directoryPath)
{
var ruleApps = new List<string>();
var dirInfo = new DirectoryInfo(directoryPath);
dirInfo.GetFiles("*.ruleapp").ToList().ForEach(r => ruleApps.Add(CaseInsensitiveStringReplace(r.Name, ".ruleapp", "")));
return ruleApps;
}
public static IEnumerable<string> GetRuleApplicationListFromCatalog(RuleExecutionInfo ruleExecutionInfo)
{
var ruleApps = new List<string>();
using (var conn = GetCatalogConnection(ruleExecutionInfo))
{
conn.GetAllRuleApps().ToList().ForEach(r => ruleApps.Add(r.Key.Name));
}
return ruleApps;
}
public static RuleCatalogConnection GetCatalogConnection(RuleExecutionInfo ruleExecutionInfo)
{
return new RuleCatalogConnection(new Uri(ruleExecutionInfo.CatalogUri), new TimeSpan(0, 0, 60), ruleExecutionInfo.Username, ruleExecutionInfo.Password);
}
public static FileSystemRuleApplicationReference GetFileRuleAppReference(RuleExecutionInfo ruleExecutionInfo)
{
return new FileSystemRuleApplicationReference(ruleExecutionInfo.RuleAppFilePath);
}
public static InMemoryRuleApplicationReference GetInMemoryRuleAppReference(RuleApplicationDef ruleApplicationDef)
{
return new InMemoryRuleApplicationReference(ruleApplicationDef);
}
public static CatalogRuleApplicationReference GetCatalogRuleAppReference(RuleExecutionInfo ruleExecutionInfo)
{
var ruleapp = new CatalogRuleApplicationReference(ruleExecutionInfo.CatalogUri, ruleExecutionInfo.RuleAppName, ruleExecutionInfo.Username, ruleExecutionInfo.Password);
ruleapp.SetRefresh(ruleExecutionInfo.CatalogRefreshInterval);
ruleapp.ConnectionTimeout = ruleExecutionInfo.CatalogRuleAppTimeoutInterval;
return ruleapp;
}
public static RuleApplicationDef GetRuleApplicationDefFromFile(RuleExecutionInfo ruleExecutionInfo)
{
return RuleApplicationDef.Load(ruleExecutionInfo.RuleAppFilePath);
}
public static RuleApplicationDef GetRuleApplicationDefFromCatalog(RuleExecutionInfo ruleExecutionInfo)
{
return GetCatalogRuleAppReference(ruleExecutionInfo).GetRuleApplicationDef();
}
public static string CaseInsensitiveStringReplace(string original, string search, string replaceWith)
{
if (original == null)
{
return "";
}
else
{
// building case insensitive replace regex pattern
var s = new StringBuilder();
foreach (var c in search.ToCharArray())
{
s.Append("[");
s.Append(c.ToString().ToUpper());
s.Append(c.ToString().ToLower());
s.Append("]");
}
return Regex.Replace(original, s.ToString(), replaceWith);
}
}
public static void RemoveRuleAppFromCache(string ruleAppName)
{
// NOTE: This does not account for multiple revisions of the same named rule app
foreach (var ruleApplicationReference in RuleSession.RuleApplicationCache.Items)
{
if (ruleApplicationReference.GetRuleApplicationDef().Name == ruleAppName)
{
RuleSession.RuleApplicationCache.Remove(ruleApplicationReference);
break;
}
}
}
#endregion
#region entity related
//public static IEnumerable<string> GetEntityNames(RuleApplicationDef ruleAppDef)
//{
// ruleAppDef.Entities
//}
public static void ActivateRuleSetsByCategory(this RuleSession ruleSession, string categoryName)
{
foreach (var entity in ruleSession.GetEntities())
{
var ruleSets = entity.RuleSets.Where(r => r.Categories.Contains(categoryName)).ToList();
ruleSets.ForEach(r => r.IsActivated = true);
}
}
public static bool IsEntityObjectBound(RuleApplicationDef ruleAppDef, string entityName)
{
// if null, the entity is not object bound
return ruleAppDef.Entities[entityName].BoundEntityTypeInfo != null;
}
#endregion
#region Repository Methods
public static FileInfo[] GetRuleApplicationFileInfos(string directoryPath)
{
DirectoryInfo dirInfo = new DirectoryInfo(directoryPath);
return dirInfo.GetFiles("*.ruleapp");
}
public static RuleApplicationDef GetRuleApplicationDef(string filePath)
{
return RuleApplicationDef.Load(filePath);
}
public static RuleApplicationDef GetRuleApplicationDef(RuleCatalogConnection conn, string ruleAppName)
{
RuleAppRef appRef = conn.GetRuleAppRef(ruleAppName);
return conn.GetSpecificRuleAppRevision(appRef.Guid, appRef.PublicRevision);
}
public static RuleApplicationDef GetRuleApplicationDef(RuleCatalogConnection conn, string ruleAppName, string labelName)
{
RuleAppRef appRef = conn.GetRuleAppRef(ruleAppName, labelName);
return conn.GetSpecificRuleAppRevision(appRef.Guid, appRef.PublicRevision);
}
public static RuleSetDef GetRuleSetDef(string ruleSetName, EntityDef entityDef)
{
//this ensure that rulesets in rule folders are included
return entityDef.GetAllRuleSets().First((r => r.Name == ruleSetName));
}
public static RuleElementDef GetRuleElementDef(string ruleElementName, RuleElementDef parentDef)
{
RuleElementDef ruleDef = null;
if (parentDef is LanguageRuleDef)
{
if (((LanguageRuleDef)parentDef).RuleElement.Name == ruleElementName)
{
ruleDef = ((LanguageRuleDef)parentDef).RuleElement;
}
}
else
{
RuleElementDefCollection ruleDefs = GetRuleElementDefCollection(parentDef);
ruleDef = (RuleElementDef)ruleDefs[ruleElementName];
}
return ruleDef;
}
public static RuleElementDef GetLanguageRuleElementDef(RuleElementDef ruleDef)
{
if (ruleDef is LanguageRuleDef)
{
return ((LanguageRuleDef)ruleDef).RuleElement;
}
return null;
}
public static RuleElementDefCollection GetRuleElementDefCollection(RuleElementDef parentDef)
{
RuleElementDefCollection ruleDefs = null;
if (parentDef is RuleSetDef)
{
ruleDefs = ((RuleSetDef)parentDef).Rules;
}
else if (parentDef is SimpleRuleDef)
{
ruleDefs = ((SimpleRuleDef)parentDef).SubRules;
}
else if (parentDef is ExclusiveRuleDef)
{
ruleDefs = ((ExclusiveRuleDef)parentDef).Conditions;
}
return ruleDefs;
}
public static RuleSetDef GetRuleSetByName(RuleApplicationDef ruleAppDef, string ruleSetName)
{
RuleSetDef ruleSetDef = null;
// first look in Entities for the RuleSet
foreach (EntityDef entityDef in ruleAppDef.Entities)
{
ruleSetDef = GetRuleSetByName(entityDef, ruleSetName);
if (ruleSetDef != null)
{
return ruleSetDef;
}
}
// if we haven't found it, look in the independent rulesets
foreach (RuleSetDef indRuleSetDef in ruleAppDef.GetAllRuleSets())
{
if (indRuleSetDef.Name == ruleSetName)
{
return indRuleSetDef;
}
}
return ruleSetDef;
}
public static RuleSetDef GetRuleSetByName(EntityDef entityDef, string ruleSetName)
{
foreach (RuleSetDef ruleSetDef in entityDef.GetAllRuleSets())
{
if (ruleSetDef.Name == ruleSetName)
{
return ruleSetDef;
}
}
return null;
}
public static string GetMemberRuleSetByName(RuleApplicationDef ruleAppDef, string ruleSetName)
{
var ruleSetDef = GetRuleSetByName(ruleAppDef, ruleSetName);
return GetMemberRuleSetByName(ruleSetDef, ruleSetName);
}
public static string GetMemberRuleSetByName(EntityDef entityDef, string ruleSetName)
{
var ruleSetDef = GetRuleSetByName(entityDef, ruleSetName);
return GetMemberRuleSetByName(ruleSetDef, ruleSetName);
}
public static string GetMemberRuleSetByName(RuleSetDef parentRuleSetDef, string ruleSetName)
{
string memberRuleSetName = string.Empty;
//TODO: this doesn't process each rule, just the last one
foreach (var rule in parentRuleSetDef.Rules)
{
if (rule is ExecuteMemberRuleSetActionDef)
{
// if this is Execute Member action, get the name of the RuleSet so we can find it
memberRuleSetName = ((ExecuteMemberRuleSetActionDef)rule).RuleSet.FormulaText;
}
}
return memberRuleSetName;
}
public static RuleSetDef[] GetExplicitRuleSetDefs(RuleApplicationDef ruleAppDef, string entityName)
{
ArrayList ruleSetDefs = new ArrayList();
EntityDef entityDef = ruleAppDef.Entities[entityName];
if (entityDef != null)
{
foreach (var ruleSetDef in entityDef.GetAllRuleSets())
{
if (ruleSetDef.FireMode == RuleSetFireMode.Explicit && ruleSetDef.IsActive)
ruleSetDefs.Add(ruleSetDef);
}
}
return (RuleSetDef[])ruleSetDefs.ToArray(typeof(RuleSetDef));
}
public static EntityDef GetRootEntityDef(RuleApplicationDef ruleApplicationDef)
{
foreach (EntityDef entityDef in ruleApplicationDef.Entities)
{
if (!entityDef.GetIsReferencedByOtherEntities(false))
{
return entityDef;
}
}
return null;
}
public static string GetRuleExecutionFlowXml(RuleSetDef ruleSetDef)
{
string xml = null;
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
//TODO: this hack is described on the variable definition
_workingRuleAppDef = ruleSetDef.GetRuleApp();
using (xw)
{
xw.WriteStartElement(ruleSetDef.Name);
foreach (RuleRepositoryDefBase def in ruleSetDef.Rules)
{
//xw.WriteRaw("<Collection3>");
AppendToExecutionFlowXml(def as RuleElementDef, xw);
//xw.WriteRaw("</Collection3>");
}
xw.WriteEndElement();
xml = sw.ToString();
}
_workingRuleAppDef = null;
return xml;
}
public static void AppendToExecutionFlowXml(RuleElementDef def, XmlTextWriter xw)
{
if (def != null && def.IsActive)
{
if (def is ExecuteActionDef)
{
AppendExecuteRuleSetTarget(def as ExecuteActionDef, xw);
}
else if (def is ExecuteMemberRuleSetActionDef)
{
AppendExecuteMemberRuleSetTarget(def as ExecuteMemberRuleSetActionDef, xw);
}
else if (def is ExclusiveRuleDef)
{
foreach (SimpleRuleDef simpleRuleDef in ((ExclusiveRuleDef)def).Conditions)
{
//xw.WriteRaw("<Collection4>");
AppendToExecutionFlowXml(simpleRuleDef, xw);
//xw.WriteRaw("</Collection4>");
}
foreach (RuleElementDef ruleDef in ((ExclusiveRuleDef)def).DefaultSubRules)
{
//xw.WriteRaw("<Collection6>");
AppendToExecutionFlowXml(ruleDef, xw);
//xw.WriteRaw("</Collection6>");
}
}
else if (def is DecisionTableDef)
{
DecisionTableDef dtDef = def as DecisionTableDef;
//xw.WriteStartElement(dtDef.Name);
foreach (ActionDimensionDef aDef in dtDef.Actions)
{
//xw.WriteRaw("<" + aDef.DisplayName + ">");
foreach (ActionValueDef actionDef in aDef.ActionValues)
{
//xw.WriteRaw("<Collection>");
AppendToExecutionFlowXml(actionDef.RuleElement as RuleElementDef, xw);
//xw.WriteRaw("</Collection>");
}
//xw.WriteRaw("</" + aDef.DisplayName + ">");
}
//xw.WriteEndElement();
}
else if (def is IContainsRuleElements)
{
foreach (RuleElementDef ruleElementDef in ((IContainsRuleElements)def).RuleElements)
{
//xw.WriteRaw("<Collection2>");
AppendToExecutionFlowXml(ruleElementDef, xw);
//xw.WriteRaw("</Collection2>");
}
}
else if (def is LanguageRuleDef)
{
AppendToExecutionFlowXml(((LanguageRuleDef)def).RuleElement, xw);
}
//else if (def is FireNotificationActionDef)
//{
// if (((FireNotificationActionDef)def).Name.Length > 0)
// {
// xw.WriteStartElement(((FireNotificationActionDef)def).Name);
// xw.WriteEndElement();
// }
// //AppendToExecutionFlowXml(((FireNotificationActionDef)def)., xw);
//}
//else if (def is AddCollectionMemberActionDef)
//{
// if (((AddCollectionMemberActionDef)def).Name.Length > 0)
// {
// xw.WriteStartElement(((AddCollectionMemberActionDef)def).Name);
// xw.WriteEndElement();
// }
// //AppendToExecutionFlowXml(((FireNotificationActionDef)def)., xw);
//}
//else if (def is SetValueActionDef)
//{
// if (((SetValueActionDef)def).Name.Length > 0)
// {
// xw.WriteStartElement(((SetValueActionDef)def).Name);
// xw.WriteEndElement();
// }
// //AppendToExecutionFlowXml(((FireNotificationActionDef)def)., xw);
//}
else
{
//Console.WriteLine(def.ToString());
}
}
}
public static void AppendExecuteRuleSetTarget(ExecuteActionDef def, XmlTextWriter xw)
{
//cant always get the def when deep down, thus the workaround
//var ruleSetDef = GetRuleSetByName(def.GetRuleApp(), def.TargetName);
var ruleSetDef = GetRuleSetByName(_workingRuleAppDef, (def.TargetName.Contains(".")?def.TargetName.Substring(def.TargetName.LastIndexOf(".") + 1):def.TargetName));
var targetName = def.TargetName.Contains(".") ? ruleSetDef.ThisEntity.Name + "." + def.TargetName.Substring(def.TargetName.LastIndexOf(".") + 1) : def.TargetName;
if (ruleSetDef != null && ruleSetDef.IsActive)
{
//xw.WriteStartElement("ExecuteRuleSet");
xw.WriteStartElement(targetName);
//xw.WriteStartElement("_");
foreach (RuleRepositoryDefBase ruleDef in ruleSetDef.Rules)
{
//xw.WriteRaw("<Collection1>");
AppendToExecutionFlowXml(ruleDef as RuleElementDef, xw);
//xw.WriteRaw("</Collection1>");
}
xw.WriteEndElement();
//xw.WriteEndElement();
}
}
public static void AppendExecuteMemberRuleSetTarget(ExecuteMemberRuleSetActionDef def, XmlTextWriter xw)
{
var ruleSetDef = GetRuleSetByName(_workingRuleAppDef, def.RuleSetName);
if (ruleSetDef != null && ruleSetDef.IsActive)
{
//xw.WriteStartElement("Execute_" + def.RuleSetName + "_ForEachMemberIn_" + def.CollectionName);
var collectionEntityMemberName = string.Empty;
if (def.CollectionName.Contains("."))
{
var split = def.CollectionName.Split('.');
var entityName = split[split.Count() - 2];
var collectionFieldName = split[split.Count() - 1];
if (_workingRuleAppDef.Entities[entityName] != null)
collectionEntityMemberName = _workingRuleAppDef.Entities[entityName].Fields[collectionFieldName].DataTypeEntityName;
else
{
if (ruleSetDef.ThisEntity.Fields[collectionFieldName] != null)
collectionEntityMemberName = ruleSetDef.ThisEntity.Fields[collectionFieldName].DataTypeEntityName;
else if (def.ThisRuleSet.Parameters[entityName] != null)
collectionEntityMemberName = _workingRuleAppDef.Entities[def.ThisRuleSet.Parameters[entityName].DataTypeEntityName].Fields[collectionFieldName].DataTypeEntityName;
}
}
else
collectionEntityMemberName = def.Collection.ThisEntity.Fields[def.CollectionName].DataTypeEntityName;
//Console.WriteLine (((InRule.Repository.RuleRepositoryDefBase)(((InRule.Repository.RuleElements.ExecuteMemberRuleSetActionDef)(def)).Collection)).ThisEntity.Name);
//xw.WriteStartElement(def.RuleSetName + "_ForEach_" + def.Collection.ThisEntity.Fields[def.CollectionName].DataTypeEntityName);
xw.WriteStartElement(def.RuleSetName + "_ForEach_" + collectionEntityMemberName);
foreach (RuleRepositoryDefBase ruleDef in ruleSetDef.Rules)
{
//xw.WriteRaw("<Collection>");
AppendToExecutionFlowXml(ruleDef as RuleElementDef, xw);
//xw.WriteRaw("</Collection>");
}
xw.WriteEndElement();
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace lesson5.Services
{
public interface ITimer
{
string GetCurrentDate();
}
}
|
//\===========================================================================================
//\ File: Player.cs
//\ Author: Morgan James
//\ Brief: Contains the player functionality including: controls, audio and animations.
//\===========================================================================================
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
[RequireComponent(typeof(AudioSource))]//Make sure the game object has an audio source also attached.
public class Player : MonoBehaviour
{
[HideInInspector]
public Node m_nCurrentNode;//The node that the player is currently over.
[HideInInspector]
public float m_fTimeRemaining;//How long the player has to complete the maze.
private Text m_tTimerText;//The UI element that displays the timer left.
private Text m_tLootText;//The UI element that displays how many successes the player has had.
private Text m_tDeathsText;//The UI element that displays the amount of deaths the player has endured.
private AudioSource m_AudioSource;//The audio source that the player sounds will play from.
[SerializeField]
private AudioClip m_MoveSound;//The sound the player makes when moving from node to node.
[SerializeField]
private AudioClip m_WinSound;//The sound that plays when the player reaches the end node.
[SerializeField]
private AudioClip m_SplashSound;//The sound the player makes when moving to a node that has not been set.
[SerializeField]
private AudioClip m_DieSound;//The sound the player makes when they ran out of time.
[SerializeField]
private AudioClip m_SpawnSound;//The sound that plays when the player is spawned.
[SerializeField]
private AudioClip m_LowTime;//The sound that plays when the timer gets low.
private bool m_bIsEnding = false;//True when the player has lost to stop the occurrence of repetitive functions.
private bool m_bIsLowTime = false;//True when the time is low to stop the occurrence of repetitive functions.
private Animator m_Animator;//The animator that controls the players animations.
void Start()
{
m_tTimerText = GameObject.Find("Timer").GetComponent<Text>();//Set the timer text by searching for the game objects name.
m_tLootText = GameObject.Find("Loot").GetComponent<Text>();//Set the loot text by searching for the game objects name.
m_tDeathsText = GameObject.Find("Deaths").GetComponent<Text>();//Set the deaths text by searching for the game objects name.
m_tLootText.text = "Loot: " + PlayerPrefs.GetInt("Loot", 0).ToString();//Set the loot displayed to be equal to the saved loot data.
m_tDeathsText.text = "Deaths: " + PlayerPrefs.GetInt("Deaths", 0).ToString();//Set the deaths displayed to be equal to the saved deaths data.
m_Animator = GetComponent<Animator>();//Set the animator.
m_AudioSource = GetComponent<AudioSource>();//Set the audio source.
PlayOneShotSound(m_SpawnSound);//Play the spawn sound(ship wreck).
}
//Move forwards.
private void MoveForwards()
{
//For every node.
for (int x = 0; x < PrimsMazeGenerator.instance.m_iGridSizeX; ++x)
{
for (int y = 0; y < PrimsMazeGenerator.instance.m_iGridSizeY; ++y)
{
//If the node is the current node and the current node isn't the end node.
if (PrimsMazeGenerator.instance.m_nGrid[x, y] == m_nCurrentNode && !m_nCurrentNode.m_bIsEnd)
{
//Make the player face the correct direction.
transform.rotation = Quaternion.Euler(0, 0, 0);
//If there is a Node in front move to it.
if (y + 1 < PrimsMazeGenerator.instance.m_iGridSizeY && PrimsMazeGenerator.instance.m_lSetNodes.Contains(PrimsMazeGenerator.instance.m_nGrid[x, y + 1]))
{
//Move to the node.
transform.position = new Vector3(
PrimsMazeGenerator.instance.m_nGrid[x, y + 1].m_v3WorldPosition.x,
PrimsMazeGenerator.instance.m_nGrid[x, y + 1].m_v3WorldPosition.y + 1,
PrimsMazeGenerator.instance.m_nGrid[x, y + 1].m_v3WorldPosition.z);
//Set the current node to be equal to the node the player moved to.
m_nCurrentNode = PrimsMazeGenerator.instance.m_nGrid[x, y + 1];
//If the player has reached the end.
if (PrimsMazeGenerator.instance.m_nGrid[x, y + 1].m_bIsEnd)
{
StartCoroutine(Win());//Signal that the play has beaten the maze.
}
//If the new node isn't the end.
else
{
PlayOneShotSound(m_MoveSound);//Play a move sound.
}
}
//If there is no node to move to.
else
{
//Move the player.
transform.position = new Vector3(
PrimsMazeGenerator.instance.m_nGrid[x, y].m_v3WorldPosition.x,
PrimsMazeGenerator.instance.m_nGrid[x, y].m_v3WorldPosition.y + 1,
PrimsMazeGenerator.instance.m_nGrid[x, y].m_v3WorldPosition.z + 1);
m_nCurrentNode = null;//Set the current node to be equal to null
}
return;
}
}
}
}
//Move backwards.
private void MoveBackwards()
{
//For every node.
for (int x = 0; x < PrimsMazeGenerator.instance.m_iGridSizeX; ++x)
{
for (int y = 0; y < PrimsMazeGenerator.instance.m_iGridSizeY; ++y)
{
//If the node is the current node and the current node isn't the end node.
if (PrimsMazeGenerator.instance.m_nGrid[x, y] == m_nCurrentNode && !m_nCurrentNode.m_bIsEnd)
{
//Make the player face the correct direction.
transform.rotation = Quaternion.Euler(0, 180, 0);
//If there is a Node behind move to it.
if (y - 1 >= 0 && PrimsMazeGenerator.instance.m_lSetNodes.Contains(PrimsMazeGenerator.instance.m_nGrid[x, y - 1]))
{
//Move to the node.
transform.position = new Vector3(
PrimsMazeGenerator.instance.m_nGrid[x, y - 1].m_v3WorldPosition.x,
PrimsMazeGenerator.instance.m_nGrid[x, y - 1].m_v3WorldPosition.y + 1,
PrimsMazeGenerator.instance.m_nGrid[x, y - 1].m_v3WorldPosition.z);
//Set the current node to be equal to the node the player moved to.
m_nCurrentNode = PrimsMazeGenerator.instance.m_nGrid[x, y - 1];
//If the player has reached the end.
if (PrimsMazeGenerator.instance.m_nGrid[x, y - 1].m_bIsEnd)
{
StartCoroutine(Win());//Signal that the play has beaten the maze.
}
//If the new node isn't the end.
else
{
PlayOneShotSound(m_MoveSound);//Play a move sound.
}
}
else
{
//Move the player.
transform.position = new Vector3(
PrimsMazeGenerator.instance.m_nGrid[x, y].m_v3WorldPosition.x,
PrimsMazeGenerator.instance.m_nGrid[x, y].m_v3WorldPosition.y + 1,
PrimsMazeGenerator.instance.m_nGrid[x, y].m_v3WorldPosition.z - 1);
m_nCurrentNode = null;//Set the current node to be equal to null
}
return;
}
}
}
}
//Move right.
private void MoveRight()
{
//For every node.
for (int x = 0; x < PrimsMazeGenerator.instance.m_iGridSizeX; ++x)
{
for (int y = 0; y < PrimsMazeGenerator.instance.m_iGridSizeY; ++y)
{
//If the node is the current node and the current node isn't the end node.
if (PrimsMazeGenerator.instance.m_nGrid[x, y] == m_nCurrentNode && !m_nCurrentNode.m_bIsEnd)
{
//Make the player face the correct direction.
transform.rotation = Quaternion.Euler(0, 90, 0);
//If there is a Node to the right move to it.
if (x + 1 < PrimsMazeGenerator.instance.m_iGridSizeX && PrimsMazeGenerator.instance.m_lSetNodes.Contains(PrimsMazeGenerator.instance.m_nGrid[x + 1, y]))
{
//Move to the node.
transform.position = new Vector3(
PrimsMazeGenerator.instance.m_nGrid[x + 1, y].m_v3WorldPosition.x,
PrimsMazeGenerator.instance.m_nGrid[x + 1, y].m_v3WorldPosition.y + 1,
PrimsMazeGenerator.instance.m_nGrid[x + 1, y].m_v3WorldPosition.z);
//Set the current node to be equal to the node the player moved to.
m_nCurrentNode = PrimsMazeGenerator.instance.m_nGrid[x + 1, y];
//If the player has reached the end.
if (PrimsMazeGenerator.instance.m_nGrid[x + 1, y].m_bIsEnd)
{
StartCoroutine(Win());//Signal that the play has beaten the maze.
}
//If the new node isn't the end.
else
{
PlayOneShotSound(m_MoveSound);//Play a move sound.
}
}
else
{
//Move the player.
transform.position = new Vector3(
PrimsMazeGenerator.instance.m_nGrid[x, y].m_v3WorldPosition.x + 1,
PrimsMazeGenerator.instance.m_nGrid[x, y].m_v3WorldPosition.y + 1,
PrimsMazeGenerator.instance.m_nGrid[x, y].m_v3WorldPosition.z);
m_nCurrentNode = null;//Set the current node to be equal to null
}
return;
}
}
}
}
//Move left.
private void MoveLeft()
{
//For every node.
for (int x = 0; x < PrimsMazeGenerator.instance.m_iGridSizeX; ++x)
{
for (int y = 0; y < PrimsMazeGenerator.instance.m_iGridSizeY; ++y)
{
//If the node is the current node and the current node isn't the end node.
if (PrimsMazeGenerator.instance.m_nGrid[x, y] == m_nCurrentNode && !m_nCurrentNode.m_bIsEnd)
{
//Make the player face the correct direction.
transform.rotation = Quaternion.Euler(0, 270, 0);
//If there is a Node to the right move to it.
if (x - 1 >= 0 && PrimsMazeGenerator.instance.m_lSetNodes.Contains(PrimsMazeGenerator.instance.m_nGrid[x - 1, y]))
{
//Move to the node.
transform.position = new Vector3(
PrimsMazeGenerator.instance.m_nGrid[x - 1, y].m_v3WorldPosition.x,
PrimsMazeGenerator.instance.m_nGrid[x - 1, y].m_v3WorldPosition.y + 1,
PrimsMazeGenerator.instance.m_nGrid[x - 1, y].m_v3WorldPosition.z);
//Set the current node to be equal to the node the player moved to.
m_nCurrentNode = PrimsMazeGenerator.instance.m_nGrid[x - 1, y];
//If the player has reached the end.
if (PrimsMazeGenerator.instance.m_nGrid[x - 1, y].m_bIsEnd)
{
StartCoroutine(Win());//Signal that the play has beaten the maze.
}
//If the new node isn't the end.
else
{
PlayOneShotSound(m_MoveSound);//Play a move sound.
}
}
else
{
//Move the player.
transform.position = new Vector3(
PrimsMazeGenerator.instance.m_nGrid[x, y].m_v3WorldPosition.x - 1,
PrimsMazeGenerator.instance.m_nGrid[x, y].m_v3WorldPosition.y + 1,
PrimsMazeGenerator.instance.m_nGrid[x, y].m_v3WorldPosition.z);
m_nCurrentNode = null;//Set the current node to be equal to null
}
return;
}
}
}
}
private void Update()
{
//If the game is not paused.
if (Time.timeScale != 0)
{
if (m_bIsEnding == false)//If the game is not ending.
{
m_fTimeRemaining -= Time.deltaTime;//Decrease the time remaining.
m_tTimerText.text = "Time: " + m_fTimeRemaining.ToString("F0");//Set the new time.
//If the player pressed the up arrow/w/swipes up.
if (Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.W) || SwipeManager.instance.IsSwiping(SwipeDirection.Up))
MoveForwards();//Move the player forwards.
//If the player pressed the down arrow/s/swipes down.
if (Input.GetKeyDown(KeyCode.DownArrow) || Input.GetKeyDown(KeyCode.S) || SwipeManager.instance.IsSwiping(SwipeDirection.Down))
MoveBackwards();//Move the player backwards.
//If the player pressed the right arrow/d/swipes right.
if (Input.GetKeyDown(KeyCode.RightArrow) || Input.GetKeyDown(KeyCode.D) || SwipeManager.instance.IsSwiping(SwipeDirection.Right))
MoveRight();//Move the player right.
//If the player pressed the left arrow/a/swipes left.
if (Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.A) || SwipeManager.instance.IsSwiping(SwipeDirection.Left))
MoveLeft();//Move the player left.
}
//If the player is not on a set node and the game is not ending.
if (m_nCurrentNode == null && m_bIsEnding == false)
{
StartCoroutine(LoseWater());//Start ending the game by way of drowning.
m_bIsEnding = true;//Declare that the game is ending.
}
//If the timer runs out and the game is not ending.
if (m_fTimeRemaining <= 0 && m_bIsEnding == false)
{
StartCoroutine(LoseTime());//Start ending the game by way of starvation.
m_bIsEnding = true;//Declare that the game is ending.
}
//If the time remaining is less than or equal to 9 and the low time boolean hasn't been set to true.
if (m_fTimeRemaining <= 9 && m_bIsLowTime == false)
{
m_AudioSource.PlayOneShot(m_LowTime, 1.0F);//Play the low time sound.
m_bIsLowTime = true;//Declare that the time is low.
}
}
}
//Plays the audio clip passed in.
private void PlayOneShotSound(AudioClip a_AudioClip)
{
m_AudioSource.PlayOneShot(a_AudioClip, 1.0F);//Plays the audio clip that was passed in.
}
//The lose state from falling off the crates.
IEnumerator LoseWater()
{
PlayerPrefs.SetInt("Deaths", PlayerPrefs.GetInt("Deaths", 0) + 1);//Increase the amount of deaths.
PlayOneShotSound(m_SplashSound);//Play a splash sound.
transform.position = new Vector3(transform.position.x, transform.position.y - 1, transform.position.z);//Move the player into the water.
m_Animator.SetInteger("State", 1);//Set the animation for the player to be that of drowning.
GetComponentInChildren<ParticleSystem>().Play();//Play the splashing particle effect.
yield return new WaitForSeconds(1);//Wait for a second.
PrimsMazeGenerator.instance.Generate();//Restart the maze.
}
//The lose state for running out of time.
IEnumerator LoseTime()
{
PlayerPrefs.SetInt("Deaths", PlayerPrefs.GetInt("Deaths", 0) + 1);//Increase the amount of deaths.
PlayOneShotSound(m_DieSound);//Play a death sound.
m_Animator.SetInteger("State", 3);//Set the animation for the player to be falling over.
yield return new WaitForSeconds(1);//Wait for a second.
PrimsMazeGenerator.instance.Generate();//Restart the maze.
}
//The win state for reaching the island within the time limit.
IEnumerator Win()
{
PlayerPrefs.SetInt("Loot", PlayerPrefs.GetInt("Loot", 0) + 1);//Increase the loot.
PlayOneShotSound(m_WinSound);//Play the win sound.
m_Animator.SetInteger("State", 2);//Set the animation for the player to be that of cheering.
yield return new WaitForSeconds(1);//Wait for a second.
PrimsMazeGenerator.instance.Generate();//Restart the maze.
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IRAP.Entity.FVS
{
public class AndonEventInfo
{
/// <summary>
/// 事件标识
/// </summary>
public long EventFactID { get; set; }
/// <summary>
/// 事件类型
/// </summary>
public string EventType { get; set; }
/// <summary>
/// 事件描述
/// </summary>
public string EventDescription { get; set; }
/// <summary>
/// 是否已停产
/// </summary>
public bool ProductionDown { get; set; }
/// <summary>
/// 呼叫时间(hh:mm)
/// </summary>
public string CallingTime { get; set; }
/// <summary>
/// 已过时长(分钟)
/// </summary>
public int TimeElapsed { get; set; }
/// <summary>
/// 业务操作标识
/// </summary>
public int OpID { get; set; }
public override string ToString()
{
return string.Format("{0}:{1}", CallingTime, EventDescription);
}
public AndonEventInfo Clone()
{
AndonEventInfo rlt = MemberwiseClone() as AndonEventInfo;
return rlt;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.DataVisualization.Charting;
using System.Web.UI.WebControls;
public partial class AdminGraphs : System.Web.UI.Page
{
WCF.RestfulServiceClient client = new WCF.RestfulServiceClient("BasicHttpBinding_IRestfulService");
int[] dateArray = new int[12];
string[] MonthsArray = new string[12] { "Jan","Feb","Maa","Apr","Mei","Jun","Jul","Aug","Sept","Okt","Nov","Dec"};
public string SelectedYear;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["ADMIN"] == null || Session["USERNAME"] != null)
{
Page.Visible = false;
Response.Redirect("~/Default.aspx");
}
SelectedYear = DropDownList1.SelectedValue;
}
protected void Button1_Click(object sender, EventArgs e)
{
Series seriesChart1 = Chart1.Series["Series1"];
Series seriesChart2 = Chart2.Series["Series1"];
Series seriesChart3 = Chart3.Series["Series1"];
int Amount = client.GetAmountofProducts();
for (int i = 0; i < 12; i++)
{
seriesChart1.Points.AddXY(MonthsArray[i], client.GetUserMonthChartData(i + 1, SelectedYear));
seriesChart2.Points.AddXY(MonthsArray[i], client.GetProductMonthData(i + 1, SelectedYear));
}
for (int i = 0; i < Amount; i++)
{
seriesChart3.Points.AddXY(i + 1, client.GetShoesSold(i + 1, SelectedYear));
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SelectedYear = DropDownList1.SelectedValue;
}
} |
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Project.GameState
{
[Serializable]
public class Player
{
public Inventory inventory;
}
} |
using Senai.AutoPecas.WebApi.Domains;
using Senai.AutoPecas.WebApi.ViewModels;
namespace Senai.AutoPecas.WebApi.Interfaces
{
interface IUsuarioRepository
{
Usuarios BuscarPorEmailESenha(LoginViewModel login);
int Cadastrar(Usuarios usuario);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "Data", menuName = "ScriptableObjects/Ecole", order = 1)]
public class EcoleScriptableObject : ScriptableObject
{
public string Nom;
[TextArea(3,10)]
public string Lieu;
[TextArea(3, 10)]
public string Description;
public string DateJPO;
[TextArea(3, 10)]
public string Modalites;
public string PageInscription;
public int NombreDePresentateurs;
}
|
using System;
using ExplicitInterfaces.Interfaces;
using ExplicitInterfaces.Models;
namespace ExplicitInterfaces
{
public class StartUp
{
public static void Main()
{
var input = Console.ReadLine();
while (input != "End")
{
var line = input.Split();
var name = line[0];
var country = line[1];
var age = int.Parse(line[2]);
Citizen citizen = new Citizen(name, age, country);
IPerson person = citizen;
IResident resident = citizen;
Console.WriteLine(person.GetName());
Console.WriteLine(resident.GetName());
input = Console.ReadLine();
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.SceneManagement;
public class StoryManager : MonoBehaviour {
[SerializeField]
private int levelCompleted = 0;
[HideInInspector]
public static StoryManager instance;
public float RestartDelay = 2f;
private void Awake()
{
if (instance == null)
instance = this;
else
Destroy(gameObject);
DontDestroyOnLoad(gameObject);
}
public int GetIndexOfBattleGround()
{
if (levelCompleted > 7)
{
return 14;
}
else if (levelCompleted > 6)
{
return 3;
}
else if (levelCompleted > 4)
{
return 13;
}
else if (levelCompleted > 3)
{
return 12;
}
else
{
return 3;
}
}
public void CompleteLevel()
{
levelCompleted += 1;
}
public int GetLevel()
{
return levelCompleted;
}
public void SetLevel(int level)
{
levelCompleted = level;
}
public int GetIndexOfTownInStory()
{
if (levelCompleted > 8)
{
return 11;
}
switch (levelCompleted)
{
case 0:
return 2;
case 1:
return 4;
case 2:
return 5;
case 3:
return 6;
case 4:
return 7;
case 5:
return 8;
case 6:
return 9;
case 7:
return 10;
case 8:
return 11;
default:
return 2;
}
}
void OnEnable()
{
SceneManager.sceneLoaded += OnLevelFinishedLoading;
}
void OnLevelFinishedLoading(Scene scene, LoadSceneMode mode)
{
var regex = "Battleground";
var match = Regex.Match(scene.name, regex, RegexOptions.IgnoreCase);
if (match.Success)
{
if (!GameManager.instance.wasGameOver)
StartCoroutine(PlayBgTheme());
Debug.Log("In a battleground : " + scene.name);
ChangeBattleGroundDifficulty();
}
}
private IEnumerator PlayBgTheme()
{
yield return new WaitForSeconds(1f);
if (levelCompleted == 0)
{
FindObjectOfType<AudioManager>().PlayTheme("BgTheme2");
}
else if (levelCompleted > 0 )
{
FindObjectOfType<AudioManager>().PlayTheme("BgTheme1");
}
}
private void ChangeBattleGroundDifficulty()
{
LevelManager levelManager = GameObject.Find("LevelManager").GetComponent<LevelManager>();
if (levelCompleted >= 0 && levelCompleted < 2)
{
levelManager.minWaveSpawnIndex = 1;
levelManager.maxWaveSpawnIndex = 4;
}
else if (levelCompleted >= 2 && levelCompleted < 4)
{
levelManager.minWaveSpawnIndex = 3;
levelManager.maxWaveSpawnIndex = 4;
}
else if (levelCompleted >= 4 && levelCompleted < 6)
{
levelManager.minWaveSpawnIndex = 3;
levelManager.maxWaveSpawnIndex = 6;
}
else if (levelCompleted >= 6 && levelCompleted < 8)
{
levelManager.minWaveSpawnIndex = 5;
levelManager.maxWaveSpawnIndex = 6;
}
else
{
levelManager.minWaveSpawnIndex = 6;
levelManager.maxWaveSpawnIndex = 7;
}
}
// Update is called once per frame
void Update () {
}
}
|
namespace HastaneOtomasyonu
{
public partial class CalisanBaseForm : BaseForm
{
public CalisanBaseForm()
{
InitializeComponent();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static XoloStateMachine;
public abstract class GhostPersonalityInstaller
{
/// <summary>
/// Returns true if anything was modified
/// </summary>
/// <returns></returns>
public abstract bool InstallPersonality(Ghost ghost);
}
|
using SpatialEye.Framework.Client;
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SpatialEye.Framework.Redlining;
using SpatialEye.Framework.Geometry;
using SpatialEye.Framework.Features;
using SpatialEye.Framework.Features.Recipe;
using Lite.Resources.Localization;
using System.Collections.Generic;
namespace Lite
{
public class MapTrailISViewModel :ViewModelBase
{
#region Property Names
/// <summary>
/// Is the submenu of the trail active
/// </summary>
public static string SubMenuIsActivePropertyName = "SubMenuIsActive";
public static string DefaultIsActivePropertyName = "DefaultIsActive";
public const string MarcaActivaPropertyName = "MarcaActiva";
public const string LatitudPropertyName = "Latitud";
public const string LongitudPropertyName = "Longitud";
#endregion
#region Fields
/// <summary>
/// The mapView to use
/// </summary>
private MapViewModel _mapView;
/// <summary>
/// Is the trail submenu active
/// </summary>
private bool _subMenuIsActive;
private bool _defaultIsActive = true;
private bool _marcaActiva;
private bool _settingUpInteractionMode;
private bool _isActive;
private string _latitud = "";
private string _longitud = "";
#endregion
#region Constructor
/// <summary>
/// Constructs the MapTrail ViewModel and attaches it to the specified messenger
/// </summary>
/// <param name="messenger"></param>
public MapTrailISViewModel(Messenger messenger = null)
: base(messenger)
{
// Attach to the messenger; reacting to view model changes
AttachToMessenger();
// Set up the commands to craete/interact with the trail
SetupCommands();
}
#endregion
#region Messenger
/// <summary>
/// Attach to the messenger
/// </summary>
private void AttachToMessenger()
{
// Set up a handler for active mapView changes
RegisterToMessenger();
//this.Messenger.Register<PropertyChangedMessage<LiteMapViewModel>>(this, change => MapView = change.NewValue);
InteractionMode = new MapTrailInteractionModeIS(this) { InterruptMode = MapInteractionMode.InterruptModeType.AllowInterrupt };
}
#endregion
#region Messenger Registration
private void RegisterToMessenger()
{
if (IsInDesignMode)
{
// Skip when in design mode
return;
}
Messenger.Register<PropertyChangedMessage<LiteMapViewModel>>
(this, m =>
{
// In case the active map has changed, pick it up
MapView = m.NewValue;
});
}
#endregion
#region Commands
/// <summary>
/// Set up the commands
/// </summary>
private void SetupCommands()
{
CreateTrailPolygonCommand = new RelayCommand(() => NewTrail(new RedliningPolygon(CoordinateSystem)), CanAddNewElement);
}
/// <summary>
/// Let all commands check their own state
/// </summary>
private void CheckCommands()
{
CreateTrailPolygonCommand.RaiseCanExecuteChanged();
}
/// <summary>
/// Can we add a new element
/// </summary>
private bool CanAddNewElement()
{
return MapView != null && MapView.TrailLayer != null && MapView.CoordinateSystem != null;
}
#endregion
#region Trail Creation Helpers
/// <summary>
/// Create a new element for the Trail Layer
/// </summary>
/// <param name="element">The element to add</param>
///
private void NewTrail(RedliningElement element)
{
// Switch off the submenu
//SubMenuIsActive = false;
//Desactivar, si ya no genera la imagen solo el triangulo rojo
MapView.TrailLayer.NewElement(element);
//MarcaActiva = true;
//Activa el triangulo rojo
//MainPage objMarca = new MainPage();
//objMarca.chkMarca2.IsChecked=true ;
}
#endregion
#region Properties
/// <summary>
/// Internal property to help trail construction be less verbose
/// </summary>
private CoordinateSystem CoordinateSystem
{
get { return MapView != null ? MapView.CoordinateSystem : null; }
}
public RelayCommand CreateTrailPolygonCommand { get; private set; }
/// <summary>
/// The map view we are currently creating trails for
/// </summary>
public MapViewModel MapView
{
get { return _mapView; }
set
{
if (_mapView != null)
{
// Make sure we no longer register to changes of the map and its interaction handler
_mapView.PropertyChanged -= MapViewModel_PropertyChanged;
if (_mapView.InteractionHandler != null)
{
_mapView.InteractionHandler.PropertyChanged -= InteractionHandler_PropertyChanged;
}
}
if (_mapView != value)
{
_mapView = value;
CheckCommands();
}
_mapView = value;
if (_mapView != null)
{
// Register to change notification of the map and its interaction handler
_mapView.PropertyChanged += MapViewModel_PropertyChanged;
if (_mapView.InteractionHandler != null)
{
_mapView.InteractionHandler.PropertyChanged += InteractionHandler_PropertyChanged;
}
}
// Start with the default mode being active
DefaultIsActive = true;
}
}
#endregion
private MapInteractionHandler CurrentInteractionHandler
{
get { return MapView != null ? MapView.InteractionHandler : null; }
}
void MapViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == MapViewModel.EnvelopePropertyName)
{
// The extent of the map has changed; in case this is not in a controlled fashion
// we switch to the default interaction mode. This leafs any measure mode that
// was active
if (!InteractionMode.IsMovingMap && !InteractionMode.IsMouseDown)
{
//DefaultIsActive = true;
}
}
}
void InteractionHandler_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
// In case we are not setting up the map and there is no active mode, switch to the default one
if (!_settingUpInteractionMode && e.PropertyName == MapInteractionHandler.ActiveInteractionModePropertyName)
{
if (this.MapView.InteractionHandler.CurrentDynamicInteractionMode == null)
{
//this.DefaultIsActive = true;
}
}
}
#region Submenu
/// <summary>
/// Gets or sets the value if the trail submenu is active
/// </summary>
public bool SubMenuIsActive
{
get { return _subMenuIsActive; }
set
{
if (value != _subMenuIsActive)
{
_subMenuIsActive = value;
RaisePropertyChanged(SubMenuIsActivePropertyName);
}
}
}
private MapTrailInteractionModeIS InteractionMode { get; set; }
private void SetInteractionMode()
{
if (MapView != null)
{
_settingUpInteractionMode = true;
try
{
// Get the current interaction mode
var currentMode = CurrentInteractionHandler.CurrentDynamicInteractionMode;
CurrentInteractionHandler.CurrentDynamicInteractionMode = null;
var newMode = !DefaultIsActive ? InteractionMode : null;
// Set (or reset) the interaction mode
MapView.InteractionHandler.CurrentDynamicInteractionMode = newMode;
// Indicates whether we are currently active
_isActive = newMode != null;
}
finally
{
_settingUpInteractionMode = false;
}
}
}
/// <summary>
/// Resets the interaction mode, in case we are active.
/// </summary>
private void ResetInteractionMode()
{
if (_isActive)
{
var currentMode = MapView.InteractionHandler.CurrentDynamicInteractionMode;
if (currentMode == InteractionMode)
{
_isActive = false;
// Set (or reset) the interaction mode
MapView.InteractionHandler.CurrentDynamicInteractionMode = null;
}
}
}
#endregion
/// <summary>
#region Interaction State
public bool DefaultIsActive
{
get { return _defaultIsActive; }
set
{
if (_defaultIsActive != value)
{
if (value)
{
// Set active
_defaultIsActive = true;
// Switching off the measure modes
MarcaActiva = false;
//Si desactiva limpiar latitud y longitud
//Comentar por que quita los valores
Latitud = string.Empty;
Longitud = string.Empty;
}
else if (MarcaActiva)
{
// Switch off
_defaultIsActive = false;
}
// Raise the appropriate change
RaisePropertyChanged(DefaultIsActivePropertyName);
if (_defaultIsActive)
{
// Set the interaction mode (if it was turned on)
SetInteractionMode();
}
}
}
}
public bool MarcaActiva
{
get { return _marcaActiva; }
set
{
if (_marcaActiva != value)
{
if (value)
{
// Set active
_marcaActiva = true;
// Switching off others
DefaultIsActive = false;
}
else
{
_marcaActiva = false;
//_latitud = "";
//_longitud = "";
DefaultIsActive = true;
}
// Notify the change
RaisePropertyChanged(MarcaActivaPropertyName);
if (_marcaActiva)
{
CreateTrailPolygonCommand = new RelayCommand(() => NewTrail(new RedliningPolygon(CoordinateSystem)), CanAddNewElement);
CheckCommands();
NewTrail(new RedliningPolygon(CoordinateSystem));
// In case the mode has been switched on, set the new interaction mode
SetInteractionMode();
}
}
}
}
#endregion
#region Properties
/// <summary>
/// Holds the top margin of the map where the measurer should not be active.
/// This allows for extra overlap of the map bar
/// </summary>
public int TopMargin
{
get { return InteractionMode.TopMargin; }
set { InteractionMode.TopMargin = value; }
}
/// <summary>
/// Holds the bottom margin of the map where the measurer should not be active.
/// </summary>
public int BottomMargin
{
get { return InteractionMode.BottomMargin; }
set { InteractionMode.BottomMargin = value; }
}
/// <summary>
/// Holds the left margin of the map where the measurer should not be active.
/// </summary>
public int LeftMargin
{
get { return InteractionMode.LeftMargin; }
set { InteractionMode.LeftMargin = value; }
}
/// <summary>
/// Holds the right margin of the map where the measurer should not be active.
/// </summary>
public int RightMargin
{
get { return InteractionMode.RightMargin; }
set { InteractionMode.RightMargin = value; }
}
public string Latitud
{
get { return _latitud; }
set
{
if (value != _latitud)
{
_latitud = value;
RaisePropertyChanged(LatitudPropertyName);
}
}
}
public string Longitud
{
get { return _longitud; }
set
{
if (value != _longitud)
{
_longitud = value;
RaisePropertyChanged(LongitudPropertyName);
}
}
}
#endregion
}
}
|
using System;
using System.ComponentModel;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Configuration;
namespace ChatProject.Model
{
#region Here goes evil event
public delegate void ReceivedDataEventHandler(object sender, ReceivedDataEventArgs e);
public class ReceivedDataEventArgs : EventArgs
{
public string ReceivedText;
public ReceivedDataEventArgs(string text) { ReceivedText = text; }
}
#endregion Here goes evil event
public class ModelUdp : INotifyPropertyChanged,ControllerToLoad
{
#region Fields
Byte[] sendBytes = new byte[0];
byte[] disconnectingTheReciever = new byte[0];
UdpClient client = new UdpClient();
public UdpClient udpClient;
public IPEndPoint remote;
public IPEndPoint sendTo;
public Thread oThread;
private string connectionText;
public static bool MessageSent = false; //flag to know the message sent status
private string messageEncodedIntoString;
private string messageToSend;
#endregion Fields
#region Events
public AutoResetEvent _ready = new AutoResetEvent(false); //Events to work along with threads
public AutoResetEvent _go = new AutoResetEvent(false);
public event PropertyChangedEventHandler PropertyChanged;
public event ReceivedDataEventHandler DataReceived;
#endregion Events
#region AllMethods
string localIp = ConfigurationManager.AppSettings["IpForUdp"]; //acquiring the ip using app.conf
int sendPort = Convert.ToInt32(ConfigurationManager.AppSettings.Get("sendPort"));
int receivePort = Convert.ToInt32(ConfigurationManager.AppSettings.Get("receivePort"));
public ModelUdp()
{
Initializing(); //Initializes the udpclient
}
public void Initializing()
{
try {
if (udpClient == null)
udpClient = new UdpClient(receivePort); //Must define a port to let the udpclient know at which port to receive
remote = new IPEndPoint(IPAddress.Any, receivePort); //receives data from any host on specified port
if (udpClient != null)
{
connectionText = "Client has started";
}
}
catch(Exception ex) { ex.ToString(); }
}
public void ConnectClientPart()
{
oThread = new Thread(Start); //Udp is started on a different thread
oThread.Start();
oThread.Name = "WorkerThreadUdp";
}
public void Start()
{
sendTo = new IPEndPoint(IPAddress.Parse(localIp), sendPort);
udpClient.Connect(sendTo);
while (true)
{
if (disconnectingTheReciever.Length == 0) //Recieves messages, for that asyncCallback is used
{
udpClient.BeginReceive(new AsyncCallback(CallBackMethod), null); // need changes
}
if (sendBytes.Length > 0) //Sends messages
{
udpClient.Send(sendBytes, sendBytes.Length);
sendBytes = new byte[0];
}
Thread.Sleep(50);
}
}
public void CallBackMethod(IAsyncResult ar)
{
try
{
remote = new IPEndPoint(IPAddress.Any, receivePort); //receives data from any host on specified port
byte[] disconnectingTheReciever = udpClient.EndReceive(ar, ref remote);
if (disconnectingTheReciever.Length > 0)
{
messageEncodedIntoString = Encoding.GetEncoding("Windows-1250").GetString(disconnectingTheReciever); //EncodeIntoString1.GetString(disconnectingTheReciever);
ReceivedDataEventArgs ReceivedDataEvent = new ReceivedDataEventArgs(messageEncodedIntoString);
if (DataReceived != null)
{
DataReceived(this, ReceivedDataEvent); //Everytime a messages arrives this event occurs
}
}
disconnectingTheReciever = new byte[0];
}
catch (Exception e) { e.ToString(); }
}
public void SendMessages(string message) //Preparing the byte to send
{
MessageToSend = message;
try
{
sendBytes = Encoding.ASCII.GetBytes(message);
}
catch (Exception ex)
{
ex.ToString();
}
}
protected void OnPropertyChanged(string name)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(name));
}
public void ClosingThreads() //Each time the radio button changes, this closing happens
{
try {
if (udpClient != null)
{
udpClient.Close();
oThread.Abort();
oThread.Join();
}
}catch(Exception ex) { ex.ToString(); }
}
#endregion AllMethods
#region Properties
public string MessageToSend
{
get { return messageToSend; }
set
{
messageToSend = value; OnPropertyChanged("MessageToSend");
}
}
public string ConnectionText
{
get { return connectionText; }
set { connectionText = value; }
}
#endregion Properties
}
} |
using UnityEngine;
using System;
using System.Collections;
using System.IO;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class AssetBundleLoader : SingletonObject<AssetBundleLoader>
{
void Awake()
{
DontDestroyOnLoad(this);
CreateInstance(this);
}
IEnumerator Start()
{
yield return new WaitForSeconds(2.0f);
yield return StartCoroutine(Initialize());
}
public IEnumerator Initialize()
{
SampleDebuger.Log("bundle dir : " + GetBundleDirName());
var request = AssetBundleManager.Initialize(GetBundleDirName());
UIProgressBar.SetpAssetBundleLoadOperation(request);
if (request != null)
{
SampleDebuger.Log("begin loading manifest");
yield return StartCoroutine(request);
}
yield return new WaitForSeconds(0.5f);
#if UNITY_WEBGL
WWW www = new WWW(Globals.wwwStreamingPath + "/version.txt");
yield return www;
VersionManager.Instance().proCurVersion = www.text.Trim();
LoadLevelAsset(GameConstant.g_szChoseServerScene);
#else
LoadLevelAsset(GameConstant.g_szVersionUpdateScene);
#endif
}
public IEnumerator Reload()
{
var request = AssetBundleManager.ReloadManifest(GetBundleDirName());
if (request != null)
{
SampleDebuger.Log("reloading manifest");
yield return StartCoroutine(request);
}
}
IEnumerator CheckVersion()
{
string path = Globals.wwwPersistenPath + "/version.txt";
WWW www = new WWW(path);
yield return www;
string oldVersionStr = "0.0.0";
if (www.error == null)
{
oldVersionStr = www.text.Trim();
}
Version oldVersion = new Version(oldVersionStr);
www = new WWW(Globals.wwwStreamingPath + "/version.txt");
yield return www;
string curVersionStr = www.text.Trim();
Version curVersion = new Version(curVersionStr);
SampleDebuger.Log("old version : " + oldVersion.proCurVersion + ", cur version : " + curVersion.proCurVersion);
if (oldVersion.IsLower(curVersion))
{
DeleteUpdateBundle();
}
}
public string GetBundleUrl(string fileName)
{
string szUrl = "";
#if UNITY_EDITOR
szUrl = Application.dataPath + "/../AssetBundles/" + SysUtil.GetPlatformName() + "/" + fileName;
//szUrl = m_szAssetUrl + "/AssetBundles/" + SysUtil.GetPlatformName() + "/" + fileName;
//return Application.streamingAssetsPath + "/AssetBundles/" + SysUtil.GetPlatformName() + "/" + fileName;
#elif UNITY_WEBGL
string szPrefix = "";
if (m_szAssetUrl.Length != 0)
{
szPrefix = m_szAssetUrl;
}
else
{
szPrefix = Application.streamingAssetsPath;
}
szUrl = szPrefix + "/AssetBundles/" + SysUtil.GetPlatformName() + "/" + fileName + "?" + VersionManager.Instance().GetVersionUrl();
#else
szUrl = Application.streamingAssetsPath + "/AssetBundles/" + SysUtil.GetPlatformName() + "/" + fileName;
string szUpdatePath = Application.persistentDataPath + "/AssetBundles/" + SysUtil.GetPlatformName() + "/" + fileName;
if (File.Exists(szUpdatePath))
{
szUrl = szUpdatePath;
}
#endif
SampleDebuger.LogGreen("bundle url : " + szUrl);
return szUrl;
}
public void DeleteUpdateBundle()
{
if (Directory.Exists(Application.persistentDataPath + "/AssetBundles"))
{
Directory.Delete(Application.persistentDataPath + "/AssetBundles", true);
}
}
private static string GetBundleDirName()
{
#if UNITY_EDITOR
switch (EditorUserBuildSettings.activeBuildTarget)
{
case BuildTarget.Android:
return "Android";
case BuildTarget.iOS:
return "iOS";
case BuildTarget.StandaloneWindows:
case BuildTarget.StandaloneWindows64:
return "Windows";
case BuildTarget.WebGL:
return "WebGL";
default:
return null;
}
#else
switch (Application.platform)
{
case RuntimePlatform.Android:
return "Android";
case RuntimePlatform.IPhonePlayer:
return "iOS";
case RuntimePlatform.WindowsPlayer:
return "Windows";
case RuntimePlatform.WebGLPlayer:
return "WebGL";
default:
return null;
}
#endif
}
public void LoadAsset(string assetBundleName, string assetName, Action<UnityEngine.Object> fn)
{
StartCoroutine(OnLoadAsset(assetBundleName, assetName, fn));
}
public IEnumerator OnLoadAsset(string assetBundleName, string assetName, Action<UnityEngine.Object> fn)
{
AssetBundleLoadAssetOperation request = AssetBundleManager.LoadAssetAsync(assetBundleName, assetName, typeof(UnityEngine.Object));
if (request == null)
yield break;
yield return StartCoroutine(request);
UnityEngine.Object obj = request.GetAsset<UnityEngine.Object>();
if (fn != null) fn(obj);
}
public void LoadAllAsset(string assetBundleName, string assetName, Action<UnityEngine.Object[]> fn)
{
StartCoroutine(OnLoadAllAsset(assetBundleName, assetName, fn));
}
public IEnumerator OnLoadAllAsset(string assetBundleName, string assetName, Action<UnityEngine.Object[]> fn)
{
AssetBundleLoadAssetOperation request = AssetBundleManager.LoadAssetAsync(assetBundleName, assetName, typeof(UnityEngine.Object), false);
if (request == null)
yield break;
yield return StartCoroutine(request);
UnityEngine.Object[] obj = request.GetAllAsset<UnityEngine.Object>();
//Debug.Log(assetName + (obj == null ? " isn't" : " is") + " loaded successfully at frame " + Time.frameCount);
if (fn != null) fn(obj);
}
public void LoadLevelAsset(string name, Action fn = null)
{
string bundle = GameConstant.g_szSceneBundlePath + name;
StartCoroutine(LoadLevel(bundle.ToLower(), name, fn));
}
protected IEnumerator LoadLevel(string assetBundleName, string levelName, Action fn)
{
// Debug.Log("Start to load scene " + levelName + " at frame " + Time.frameCount);
// Load level from assetBundle.
AssetBundleLoadBaseOperation request = AssetBundleManager.LoadLevelAsync(assetBundleName, levelName, false);
if (request != null)
{
yield return StartCoroutine(request);
}
if (fn != null)
{
fn();
}
}
void OnDestory()
{
}
#if UNITY_WEBGL
[Tooltip("通过这个url重定义streamingAssetsPath 如果不填 代表是使用系统自带的 只在webgl浏览器下起作用 编辑器无效")]
[SerializeField]
string m_szAssetUrl = "";
#endif
} |
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System;
using System.Windows.Forms;
using MagDUR.Classes;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using Syncfusion.Windows.Forms.Tools;
namespace MagDUR
{
public partial class MainForm : RibbonForm
{
// Connect to the local, default instance of SQL Server.
private readonly Server _server =
new Server(
new ServerConnection(new SqlConnection(@"Server=MOBILNY;Database=;User Id=sa;Password=pass;")));
private readonly DataSet ds = new DataSet();
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
if (File.Exists("MyTreeView.xml"))
{
treeView.Nodes.Clear();
var serializer = new TreeViewSerializer();
serializer.DeserializeTreeView(treeView, "MyTreeView.xml");
}
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
var serializer = new TreeViewSerializer();
serializer.SerializeTreeView(treeView, "MyTreeView.xml");
}
private void rbtnExit_Click(object sender, EventArgs e)
{
var serializer = new TreeViewSerializer();
serializer.SerializeTreeView(treeView, "MyTreeView.xml");
Close();
}
private void rbtnOpenDB_Click(object sender, EventArgs e)
{
var openBase = new OpenBase(this);
openBase.Show();
}
private void treeView_BeforeSelect(object sender, TreeViewAdvCancelableSelectionEventArgs args)
{
if (treeView.SelectedNode.Parent != null)
{
ds.Tables.Clear();
if (!_server.Databases.Contains(treeView.SelectedNode.Parent.Text))
{
grid.DataSource = null;
MessageBox.Show(@"Baza o podanej nazwie nie istnieje.");
}
else
{
var connection =
new SqlConnection(
string.Format(@"Server=MOBILNY;Database={0};User Id=sa;Password=pass;",
treeView.SelectedNode.Parent.Text));
var adapter =
new SqlDataAdapter(
"Select id, box, nazwa, nr_ident_dostawca, nr_ident_producent, stan_mag, stan_min, kod, dostawca, sekcja, data from " +
treeView.SelectedNode.Text, connection);
adapter.Fill(ds, treeView.SelectedNode.Text);
grid.DataSource = ds.Tables[0];
}
}
}
private void rbtnCreateDB_Click(object sender, EventArgs e)
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
public class Leaderboard
{
/* public Text textNames, textTimes, textPieces;
*/
List<Player> interm = new List<Player>(), sorted;
string path, jsonString, names, times, pieces;
public void FillInListAndStrings()
{
path = Application.streamingAssetsPath + "/leaderboard.json";
jsonString = File.ReadAllText(path);
Players myList = JsonUtility.FromJson<Players>(jsonString);
foreach (Player player in myList.players)
{
interm.Add(player);
}
sorted = interm.OrderByDescending(player => player.pieces).ThenBy(player => player.time).ToList();
int count = 0;
names += "Name\n";
times += "Time\n";
pieces += "Ship Parts\n";
sorted.ForEach(player => {
if (count <= 4)
{
names += ((count + 1) + " " + player.name + "\n");
times += (player.time + "\n");
pieces += (player.pieces + "\n");
}
count++;
});
}
public string getNames()
{
return (names);
}
public string getTimes()
{
return (times);
}
public string getPieces()
{
return (pieces);
}
/* void Start()
{
}
// Update is called once per frame
void Update()
{
textNames.text = names;
textTimes.text = times;
textPieces.text = pieces;
}*/
}
[System.Serializable]
public class Player
{
public string name;
public string time;
public int pieces;
}
[System.Serializable]
public class Players
{
public Player[] players;
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
using UnityEngine.SceneManagement;
using UnityEditor;
public class ClearState : StageSequenceState
{
const float distanceDelta = 0.04f;
const float angleDelta = 3f;
const float lightSpeed = 0.5f;
const float distanceDiff = 0.005f;
Image nextStageUI;
Image clearUI;
ParticleSystem effect;
Quaternion forwardAngle;
Quaternion backwardAngle;
Light clearLight;
Animator goalDoor;
StageDataBase stageDataBase;
bool hasInput;
public ClearState()
{
nextStageUI = GameObject.Find("NextStageUI").GetComponent<Image>();
clearUI = GameObject.Find("ClearUI").GetComponent<Image>();
effect = GameObject.Find("ClearEffect").GetComponent<ParticleSystem>();
goalDoor = GameObject.Find("goalDoor").GetComponent<Animator>();
clearLight = GameObject.Find("clearLight").GetComponent<Light>();
stageDataBase = AssetDatabase.LoadAssetAtPath<StageDataBase>("Assets/Script/GameState/StageSelect/Stages/StageDataBase.asset");
forwardAngle = Quaternion.Euler(0, 90, 0);
backwardAngle = Quaternion.Euler(0, -90, 0);
hasInput = false;
}
public override void StageEnter()
{
SaveData();
nextStageUI.enabled = true;
clearUI.enabled = true;
effect.Play();
animator.SetBool("Walk", true);
playerStateMachine.enabled = false;
}
public override void StageUpdate()
{
MovePlayerBefore();
RotatePlayerBefore();
HandleInput();
RotatePlayerAfter();
MovePlayerAfter();
ShowLight();
if (hasInput && Mathf.Abs(player.transform.position.z - exitPosition.z) <= distanceDiff)
stateMachine.currentState = StageSequenceMachine.State_StageSequence.ENTER;
}
public override void StageExit()
{
LoadNextScene();
}
//入力前のプレイヤーアニメーション
private void MovePlayerBefore()
{
if (hasInput || Mathf.Abs(player.transform.position.x - goalPosition.x) <= distanceDiff)
return;
player.transform.position = Vector3.MoveTowards(player.transform.position, goalPosition, distanceDelta);
}
private void RotatePlayerBefore()
{
if (hasInput || Mathf.Abs(player.transform.position.x - goalPosition.x) > distanceDiff ||
player.transform.rotation.eulerAngles.y == forwardAngle.y)
return;
player.transform.rotation = Quaternion.RotateTowards(player.transform.rotation, forwardAngle, angleDelta);
if (player.transform.rotation.eulerAngles.y == forwardAngle.eulerAngles.y)
{
animator.SetBool("Walk", false);
animator.SetTrigger("Clear");
}
}
private void HandleInput()
{
if (!hasInput && animator.GetCurrentAnimatorStateInfo(0).fullPathHash != Animator.StringToHash("Base Layer.Clear"))
return;
foreach (KeyCode key in Enum.GetValues(typeof(KeyCode)))
{
if (key == KeyCode.Mouse0 || key == KeyCode.Mouse1 || key == KeyCode.Mouse2 ||
key == KeyCode.Mouse3 || key == KeyCode.Mouse4 || key == KeyCode.Mouse5 || key == KeyCode.Mouse6)
continue;
if (Input.GetKeyDown(key))
{
animator.SetBool("Walk", true);
goalDoor.SetTrigger("OpenDoor");
hasInput = true;
}
}
}
//入力後のプレイヤーアニメーション
private void RotatePlayerAfter()
{
if (!hasInput || player.transform.rotation.eulerAngles.y == backwardAngle.eulerAngles.y)
return;
player.transform.rotation = Quaternion.RotateTowards(player.transform.rotation, backwardAngle, angleDelta);
}
private void MovePlayerAfter()
{
if (!hasInput || player.transform.rotation.eulerAngles.y != backwardAngle.eulerAngles.y)
return;
player.transform.position = Vector3.MoveTowards(player.transform.position, exitPosition, distanceDelta);
}
private void ShowLight()
{
if (!hasInput)
return;
clearLight.range += lightSpeed;
}
private void SaveData()
{
PlayerPrefs.SetInt(SceneManager.GetActiveScene().name, deadTimes);
}
private void LoadNextScene()
{
Pauser.DestoryTarget();
//次のステージ#
int nextStageNum;
int.TryParse(SceneManager.GetActiveScene().name.Remove(0, 5), out nextStageNum);
nextStageNum++;
//クリアしたステージ数
int clearedStageNum = 0;
int stageNumMax = stageDataBase.GetStageList().Count;
for (int i = 1; i <= stageNumMax; i++)
{
if (PlayerPrefs.HasKey("Stage" + i.ToString()))
clearedStageNum++;
}
//次のシーンへ
if (clearedStageNum == stageNumMax)
SceneManager.LoadScene("Ending");
else
{
if(nextStageNum > stageNumMax)
SceneManager.LoadScene("StageSelect");
else
SceneManager.LoadScene("Stage" + nextStageNum.ToString());
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "New GunDefinition", menuName = "Old/New Primary Gun")]
public class PrimaryGunsDefinition : BaseGunDefinition
{
public override void AdsFire(ShootData shootData)
{
shootData.gunScript.Fire();
if (shootData.gunScript.currentShootMode == ShootModes.Burst)
shootData.gunScript.burstCounter++;
shootData.gunScript.fireTimer = 0f;
shootData.gunScript.currentAcc -= shootData.gunScript.currentGun.accuracyDropPerShot;
if(shootData.gunScript.currentAcc <= 0)
shootData.gunScript.currentAcc = 10;
shootData.ShootStuff(shootData.centrePoint);
if(shootData.useRecoil)
AddAdsRecoil(shootData.gunObject);
}
public override void HipFire(ShootData shootData)
{
shootData.gunScript.Fire();
if (shootData.gunScript.currentShootMode == ShootModes.Burst)
shootData.gunScript.burstCounter++;
shootData.gunScript.fireTimer = 0f;
shootData.gunScript.currentAcc -= shootData.gunScript.currentGun.accuracyDropPerShot;
if(shootData.gunScript.currentAcc <= 0)
shootData.gunScript.currentAcc = 10;
if(shootData.useRecoil)
AddHipRecoil(shootData.gunObject);
}
public override void AddAdsRecoil(GameObject gunModel)
{
}
public override void AddHipRecoil(GameObject gunModel)
{
}
}
|
using System;
using System.Collections.Generic;
using Challenge_06_Repository;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Challenge_06_Tests
{
[TestClass]
public class CarTests
{
[TestMethod]
public void AddCarToList()
{
CarRepository carRepository = new CarRepository();
Car carOne = new Car(CarType.Electric, 10, "2017 Chevy", "Bolt EV LT", 16500, 25998m);
Car carTwo = new Car();
carRepository.AddCarToList(carOne);
carRepository.AddCarToList(carTwo);
List<Car> newCarInformation = carRepository.GetListOfCars();
int actual = newCarInformation.Count;
int expected = 2;
Assert.AreEqual(expected, actual);
Assert.IsTrue(newCarInformation.Contains(carTwo));
}
[TestMethod]
public void RemoveClaim()
{
CarRepository carRepo = new CarRepository();
Car car = new Car();
Car carOne = new Car(CarType.Electric, 10, "2017 Chevy", "Bolt EV LT", 16500, 25998m);
carRepo.AddCarToList(car);
carRepo.AddCarToList(carOne);
carRepo.RemoveCar(carOne);
int actual = carRepo.GetListOfCars().Count;
int expected = 1;
Assert.AreEqual(expected, actual);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KartLib.Reports;
using KartObjects;
using FastReport;
using System.IO;
using System.Threading;
using KartLib;
using KartObjects.Entities.Documents;
namespace KartSystem
{
public class InventoryReportViewer : BaseReportViewer
{
public InventoryReportViewer(Form parentForm, string ReportPath)
: base(parentForm, ReportPath)
{
ReportFileName = "CollationSheetReport.frx";
//ReportFileName = "InventoryReport.frx";
}
FormWait frmWait;
/// <summary>
/// Сличительная ведомость
/// </summary>
public void ShowColationSheetReport(Document doc, bool OnlyNullOrZero)
{
using (Report report = new Report())
{
KartDataDictionary.ReportRunningFlag = true;
report.Load(ReportPath + @"\" + ReportFileName);
List<CollationSlipReportRecord> reportRecords = null;
frmWait = new FormWait("Подготовка данных ...");
// Процесс формирования запускаем отдельным потоком
Thread thread = new Thread(new ThreadStart(
delegate
{
reportRecords = Loader.DbLoad<CollationSlipReportRecord>("", 0, doc.Id) ?? new List<CollationSlipReportRecord>();
Thread.Sleep(100);
frmWait.CloseWaitForm();
})) { IsBackground = true };
thread.Start();
frmWait.ShowDialog();
frmWait.Dispose();
frmWait = null;
KartDataDictionary.ReportRunningFlag = false;
if (OnlyNullOrZero) reportRecords = (from a in reportRecords where (a.Quantity == 0) select a).ToList();
//reportRecords.Where(q => (q.Quantity == 0) || (q.Quantity == null));
DataSource.DataSource = reportRecords;
report.RegisterData(DataSource, "CollationSlipReportRecordBindingSource");
report.GetDataSource("CollationSlipReportRecordBindingSource").Enabled = true;
TextObject docDate = (TextObject)report.FindObject("Date");
if (docDate != null)
docDate.Text = doc.DateDoc.ToString("dd.MM.yyyy");
TextObject Number = (TextObject)report.FindObject("Number");
if (Number != null)
Number.Text = doc.Number.ToString();
TextObject Comment = (TextObject)report.FindObject("Comment");
if (Comment != null)
Comment.Text = doc.Comment;
if (report.Prepare())
report.ShowPrepared(true, ParentForm);
}
}
public override void ShowReport(SimpleDbEntity d)
{
using (Report report = new Report())
{
InventoryReport doc = new InventoryReport(d as Document);
if (doc == null) return;
if (!File.Exists(ReportPath + @"\" + ReportFileName))
{
MessageBox.Show("Не найдена форма печати " + ReportFileName + ".", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
report.Load(ReportPath + @"\" + ReportFileName);
if (report == null || doc == null) return;
List<InventoryGoodSpecRecord> docs = Loader.DbLoad<InventoryGoodSpecRecord>("", 0, doc.Id, 1, 0, 1, 0, 0, doc.IdWhSection) ?? new List<InventoryGoodSpecRecord>();
//doc.Records ?? Loader.DbLoad<InventoryGoodSpecRecord>("IdDocument=" + doc.Id) ?? new List<InventoryGoodSpecRecord>();
if (doc == null) return;
DataSource.DataSource = docs;
report.RegisterData(DataSource, "inventoryGoodSpecRecordBindingSource");
report.GetDataSource("inventoryGoodSpecRecordBindingSource").Enabled = true;
TextObject docDate = (TextObject)report.FindObject("Date");
if (docDate != null && doc.DateDoc != null)
docDate.Text = doc.DateDoc.ToString("dd.MM.yyyy");
TextObject Number = (TextObject)report.FindObject("Number");
if (Number != null && doc.Number != null)
Number.Text = doc.Number.ToString();
TextObject docBottomDate = (TextObject)report.FindObject("BottomDate");
if (docBottomDate != null && doc.DateDoc != null)
docBottomDate.Text = doc.DateDoc.ToString("dd.MM.yyyy");
TextObject docBottomPrintDate = (TextObject)report.FindObject("BottomPrintDate");
if (docBottomPrintDate != null && doc.DateDoc != null)
docBottomPrintDate.Text = doc.DateDoc.ToString("dd.MM.yyyy");
TextObject docBottomNumber = (TextObject)report.FindObject("BottomNumber");
if (docBottomNumber != null && doc.Number != null)
docBottomNumber.Text = doc.Number.ToString();
TextObject Warehouse = (TextObject)report.FindObject("Warehouse");
if (Warehouse != null )
Warehouse.Text = (d as Document).NameWh;
TextObject Comment = (TextObject)report.FindObject("Comment");
if (Comment != null && (d as Document).Comment != null)
Comment.Text = (d as Document).Comment.ToString();
if (report.Prepare())
report.ShowPrepared(true, ParentForm);
}
}
}
}
|
using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;
public class bg : MonoBehaviour, IPointerClickHandler {
public GameObject nodes;
// If a player clicks the background ensure any open menus / selection modes are all canceled out
void IPointerClickHandler.OnPointerClick(PointerEventData eventData){
nodes.GetComponent<node_manager> ().AllMenusOff ();
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.IO;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SimplySqlSchema.Attributes;
using SimplySqlSchema.Cache;
using SimplySqlSchema.Delegator;
using SimplySqlSchema.Extractor;
using SimplySqlSchema.Migration;
using SimplySqlSchema.SQLite;
namespace SimplySqlSchema.Tests
{
[TestClass]
public class EndToEndTests
{
protected string SchemaName { get; } = "TestSchema";
protected string TestDbFile { get; } = "QueryTest.db";
protected BackendType Backend { get; set; }
protected IDbConnection Connection { get; set; }
protected ISimplySqlSchema Delegator { get; set; }
[TestInitialize]
public void Setup()
{
this.Backend = BackendType.SQLite;
this.Delegator = new ProviderDelegator(
migrator: new SchemaMigrator(),
managers: new[] { new SQLiteSchemaManager() },
queriers: new[] { new SQLiteQuerier() },
extractor: new DataAnnotationsSchemaExtractor(),
schemaCache: new DictionarySchemaCache(),
connectors: new[] { new SQLiteConnectionFactory() }
);
this.Connection = this.Delegator
.GetConnectionFactory(this.Backend)
.GetConnection($"Data Source={TestDbFile};Version=3;");
}
[TestMethod]
public async Task TestBasicFlow()
{
var schema = this.Delegator.GetExtractor().GetObjectSchema(typeof(TestUser), this.SchemaName);
await this.Delegator.GetMigrator().PlanAndMigrate(
connection: this.Connection,
targetManager: this.Delegator.GetManager(this.Backend),
targetSchema: schema,
options: null
);
var nolan = new TestUser()
{
Name = "Nolan",
Age = 24,
LastUpdated = DateTime.Now,
Address = new TestAddress()
{
ApartmentNumber = 211,
IsApartment = true,
Street = "Not tellin ya"
},
Attributes = new List<TestAttribute>()
{
new TestAttribute()
{
Attribute = "Hair-Colour",
Value = "Blonde"
},
new TestAttribute()
{
Attribute = "Eye-Colour",
Value = "Green"
},
}
};
await this.Delegator.GetQuerier(this.Backend).Insert(
connection: this.Connection,
schema: schema,
obj: nolan
);
var fetchedNolan = await this.Delegator.GetQuerier(this.Backend).Get(
connection: this.Connection,
schema: schema,
keyedObject: new TestUser()
{
Age = nolan.Age,
Name = nolan.Name
}
);
Assert.IsNotNull(fetchedNolan);
Assert.AreEqual(nolan.Name, fetchedNolan.Name);
Assert.AreEqual(nolan.Age, fetchedNolan.Age);
Assert.AreEqual(nolan.LastUpdated, fetchedNolan.LastUpdated);
Assert.AreEqual(nolan.Address.Street, fetchedNolan.Address.Street);
Assert.AreEqual(nolan.Address.IsApartment, fetchedNolan.Address.IsApartment);
Assert.AreEqual(nolan.Address.ApartmentNumber, fetchedNolan.Address.ApartmentNumber);
Assert.AreEqual(nolan.Attributes.Count, fetchedNolan.Attributes.Count);
Assert.AreEqual(nolan.Attributes[0].Attribute, fetchedNolan.Attributes[0].Attribute);
Assert.AreEqual(nolan.Attributes[0].Value, fetchedNolan.Attributes[0].Value);
Assert.AreEqual(nolan.Attributes[1].Attribute, fetchedNolan.Attributes[1].Attribute);
Assert.AreEqual(nolan.Attributes[1].Value, fetchedNolan.Attributes[1].Value);
}
[TestCleanup]
public void Cleanup()
{
this.Delegator.GetManager(this.Backend)
.DeleteObject(this.Connection, this.SchemaName)
.GetAwaiter().GetResult();
this.Connection.Dispose();
if (File.Exists(this.TestDbFile))
{
File.Delete(this.TestDbFile);
}
}
class TestUser
{
[Key]
public int Age { get; set; }
[Key]
public string Name { get; set; }
public DateTime LastUpdated { get; set; }
[JsonNest]
public TestAddress Address { get; set; }
[JsonNest]
public List<TestAttribute> Attributes { get; set; }
}
class TestAddress
{
public string Street { get; set; }
public bool IsApartment { get; set; }
public int? ApartmentNumber { get; set; }
}
class TestAttribute
{
public string Attribute { get; set; }
public string Value { get; set; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Conditions;
using Conditions.Guards;
using Properties.Core.Objects;
namespace Properties.Infrastructure.Data.Extensions
{
public static class PropertyExtensions
{
public static IQueryable<Property> MatchesLandlordReference(this IQueryable<Property> properties, string landlordReference)
{
return properties.Where(p => p.Landlord.LandlordReference == landlordReference);
}
public static IQueryable<Property> MinimumPrice(this IQueryable<Property> properties, decimal price)
{
return properties.Where(p => p.MonthlyPrice >= price);
}
public static IQueryable<Property> MaximumPrice(this IQueryable<Property> properties, decimal price)
{
return properties.Where(p => p.MonthlyPrice <= price);
}
public static IQueryable<Property> MatchesArea(this IQueryable<Property> properties, string area)
{
return properties.Where(p => p.Postcode.ToUpper().StartsWith(area.ToUpper()));
}
public static IQueryable<Property> MatchesAreas(this IQueryable<Property> properties, List<string> areas)
{
return properties.Where(p => areas.Any(x => p.Postcode.ToUpper().StartsWith(x.ToUpper())));
}
public static IEnumerable<Property> FilterByAreas(this IEnumerable<Property> properties, List<string> areas)
{
return properties.Where(p=> areas.Any(a => a.IsOutwardCode()
? string.Equals(p.Postcode.GetOutwardCode(),a, StringComparison.InvariantCultureIgnoreCase)
: string.Equals(p.Postcode.GetPrefix(), a, StringComparison.InvariantCultureIgnoreCase)
));
}
public static IQueryable<Property> MatchesRequirement(this IQueryable<Property> properties,
PropertyDetailType type, string value)
{
return properties.Where(p => p.PropertyDetails.Any(pd => pd.DetailType == type && pd.DetailValue == value));
}
public static IEnumerable<Property> ExceedsBedrooms(this IEnumerable<Property> properties, string value)
{
return
properties.Where(
p =>
p.PropertyDetails.Any(
pd =>
pd.DetailType == PropertyDetailType.NumberOfBedrooms &&
Convert.ToInt32(pd.DetailValue) >= Convert.ToInt32(value)));
}
public static IEnumerable<Property> OrderByTabOrder(this IEnumerable<Property> properties)
{
var eligibleProperties = properties.ToList();
if (eligibleProperties.IsNull() || eligibleProperties.IsEmpty())
return eligibleProperties;
var available = eligibleProperties.Where(p => p.PipelinePosition == PipelinePosition.Available).ToList();
var let = eligibleProperties.Where(p => p.PipelinePosition == PipelinePosition.Let).ToList();
return available.Concat(let).ToList();
}
public static IEnumerable<Property> FilterByArea(this IEnumerable<Property> properties, SearchParameter area)
{
if (area.IsNull())
return properties;
if (area.ParameterValue.IsNullOrEmpty())
return properties;
if (area.ParameterValue.IsOutwardCode())
{
return (from property in properties
let outwardCode = property.Postcode.GetOutwardCode()
where string.Equals(outwardCode, area.ParameterValue, StringComparison.CurrentCultureIgnoreCase)
select property).ToList();
}
return (from property in properties
let postcodePrefix = property.Postcode.GetPrefix()
where string.Equals(postcodePrefix, area.ParameterValue, StringComparison.CurrentCultureIgnoreCase)
select property).ToList();
}
public static IQueryable<Property> OrderProperties(this IQueryable<Property> source, Ordering order)
{
Check.If(source).IsNotNull();
switch (order)
{
case Ordering.Newest:
return source.OrderByDescending(p => p.StartDate);
case Ordering.Oldest:
return source.OrderBy(p => p.StartDate);
case Ordering.LeastExpensive:
return source.OrderBy(p => p.MonthlyPrice);
default:
return source.OrderByDescending(p => p.MonthlyPrice);
}
}
public static IQueryable<Property> Filter(this IQueryable<Property> source, Filtering filter)
{
Check.If(source).IsNotNull();
switch (filter)
{
case Filtering.Available:
return source.Available();
case Filtering.Let:
return source.Let();
default:
return source;
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AttackerSpawner : MonoBehaviour
{
[SerializeField] private GameObject[] attackerPrefab;
// Update is called once per frame
void Update()
{
foreach (GameObject currentAttacker in attackerPrefab)
{
if (isTimeToSpawn(currentAttacker))
{
Spawen(currentAttacker);
}
}
}
private void Spawen(GameObject currentAttacker)
{
GameObject myAttacker = Instantiate(currentAttacker) as GameObject;
myAttacker.transform.parent = transform;
myAttacker.transform.position = transform.position;
}
private bool isTimeToSpawn(GameObject currentAttacker)
{
//currentAttacker.GetComponent<Attacker>().seenEverySeconds Time.timeSinceLevelLoad
Attacker attacker = currentAttacker.GetComponent<Attacker>();
float meanSpawnDelayInSeconds = attacker.seenEverySeconds;
float spawnPerSecond = 1 / meanSpawnDelayInSeconds;
if (Time.deltaTime > meanSpawnDelayInSeconds)
{
Debug.LogWarning("Spawn rate capped by frame rate");
}
float threshold = spawnPerSecond * Time.deltaTime / 5;
//Debug.Log("SpawnPerSecond = " + spawnPerSecond);
//Debug.Log("Time.deltaTime = " + Time.deltaTime);
//Debug.Log("Threshold = " + threshold);
return (UnityEngine.Random.value < threshold);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.EventSystems;
public class MenuSwitcher : MonoBehaviour
{
// public int sceneIndex;
public bool isUsed;
public bool switcher;
public GameObject pauseMenuUi;
bool isOpen;
private AudioSource buttonSource;
private Animator animator;
void Start()
{
buttonSource = gameObject.AddComponent<AudioSource>();
animator = pauseMenuUi.GetComponent<Animator>();
isOpen = animator.GetBool("CreditsStart");
}
public void Switch(int sceneIndex)
{
if (sceneIndex == -1)
{
Application.Quit();
}
SceneManager.LoadScene(sceneBuildIndex: sceneIndex);
}
public void StartCredits()
{
if (!isUsed)
{
Credits();
}
else
{
Resume();
}
}
public void Credits()
{
animator.SetBool("CreditsStart", !isOpen);
isUsed = true;
}
public void Resume()
{
animator.SetBool("CreditsStart", isOpen);
isUsed = false;
}
}
|
using Barker_API.Models;
using Barker_API.Persistence;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Barker_API.Data
{
public class BarkService : IBarkService
{
IBarkRepo repo;
public BarkService()
{
repo = new BarkRepo();
}
public async Task<Bark> CreateBarkAsync(Bark bark)
{
return await repo.CreateBarkAsync(bark);
}
public async Task DeleteBarkAsync(int barkID)
{
await repo.DeleteBarkAsync(barkID);
}
public async Task<Bark> GetBarkAsync(int barkID)
{
return await repo.GetBarkAsync(barkID);
}
public async Task<List<Bark>> GetBarksByUserAsync(int userID)
{
return await repo.GetBarksByUserAsync(userID);
}
public async Task<Bark> UpdateBarkAsync(Bark bark)
{
return await repo.UpdateBarkAsync(bark);
}
}
}
|
using UnityEngine;
using System.Collections;
using Malee.Hive.Core;
public class CharacterAnimation : GameBehaviour {
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Uintra.Core.Activity.Entities;
using Uintra.Core.Member.Abstractions;
using Uintra.Core.Member.Entities;
using Uintra.Core.Member.Services;
using Uintra.Features.Events;
using Uintra.Features.Events.Entities;
using Uintra.Features.Links;
using Uintra.Features.Links.Models;
using Uintra.Features.News;
using Uintra.Features.Notification;
using Uintra.Features.Notification.Entities;
using Uintra.Features.Notification.Entities.Base.Mails;
using Uintra.Features.Notification.Models.NotifierTemplates;
using Uintra.Features.Notification.Services;
using Uintra.Features.Social;
using Uintra.Features.Tagging.UserTags.Services;
using Uintra.Infrastructure.ApplicationSettings;
using Umbraco.Core.Logging;
namespace Uintra.Features.MonthlyMail
{
public class MonthlyEmailService: MonthlyEmailServiceBase
{
private readonly ISocialService<Social.Entities.Social> _bulletinsService;
private readonly IEventsService<Event> _eventsService;
private readonly INewsService<News.Entities.News> _newsService;
private readonly IUserTagRelationService _userTagService;
private readonly IActivityLinkService _activityLinkService;
private readonly INotificationModelMapper<EmailNotifierTemplate, EmailNotificationMessage> _notificationModelMapper;
public MonthlyEmailService(IMailService mailService,
IIntranetMemberService<IntranetMember> intranetMemberService,
ILogger logger,
ISocialService<Social.Entities.Social> bulletinsService,
IEventsService<Event> eventsService,
INewsService<News.Entities.News> newsService,
IUserTagRelationService userTagService,
IActivityLinkService activityLinkService,
INotificationSettingsService notificationSettingsService,
INotificationModelMapper<EmailNotifierTemplate, EmailNotificationMessage> notificationModelMapper,
IApplicationSettings applicationSettings)
: base(mailService, intranetMemberService, logger, notificationSettingsService, applicationSettings)
{
_bulletinsService = bulletinsService;
_eventsService = eventsService;
_newsService = newsService;
_userTagService = userTagService;
_activityLinkService = activityLinkService;
_notificationModelMapper = notificationModelMapper;
}
protected override IEnumerable<(IIntranetActivity activity, UintraLinkModel detailsLink)> GetUserActivitiesFilteredByUserTags(Guid userId)
{
var allActivities = GetAllActivities()
.Select(activity => (activity: activity, activityTagIds: _userTagService.GetForEntity(activity.Id)));
var userTagIds = _userTagService
.GetForEntity(userId)
.ToList();
var result = allActivities
.Where(pair => userTagIds.Intersect(pair.activityTagIds).Any())
.Select(pair => (pair.activity, detailsLink: _activityLinkService.GetLinks(pair.activity.Id).Details));
return result;
}
protected override MailBase GetMonthlyMailModel(IIntranetMember receiver, MonthlyMailDataModel dataModel, EmailNotifierTemplate template) =>
_notificationModelMapper.Map(dataModel, template, receiver);
protected virtual IEnumerable<IIntranetActivity> GetAllActivities()
{
var allBulletins = _bulletinsService.GetAll().Cast<IIntranetActivity>();
var allNews = _newsService.GetAll().Cast<IIntranetActivity>();
var allEvents = _eventsService.GetAll().Cast<IIntranetActivity>();
return allBulletins.Concat(allNews).Concat(allEvents);
}
}
} |
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Runtime.InteropServices;
using UnityEngine.EventSystems;
public static class GameController
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
public static void GameStart()
{
Debug.Log("GameStart!");
Win32Help.SetImeEnable(false);
SceneManager.LoadScene(0);
}
public static void LoadScene(int sceneNumber)
{
SceneManager.LoadScene(sceneNumber);
if (GameObject.Find("EventSystem") != null)
{
GameObject.Find("EventSystem").GetComponent<EventSystem>().enabled = false;
}
InputController.BanButton(false);
InputController.BanMouse(false);
Time.timeScale = 1f;
}
public static int GetCharacterNumber()
{
int characterNumber=0;
switch (SceneManager.GetActiveScene().buildIndex)
{
case 1:
characterNumber = 1;
break;
case 2:
characterNumber = 1;
break;
case 3:
characterNumber = 1;
break;
case 4:
characterNumber = 2;
break;
case 5:
characterNumber = 2;
break;
case 6:
characterNumber = 2;
break;
case 7:
characterNumber = 2;
break;
case 8:
characterNumber = 2;
break;
default:
break;
}
return characterNumber;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DirectXTools
{
/// <summary>
/// Integer based two dimesional size.
/// </summary>
public struct Dim2D
{
public int Width;
public int Height;
public Dim2D(int width, int height)
{
this.Width = width;
this.Height = height;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.