text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Text; using ProtoBuf; using Qwack.Transport.TransportObjects.MarketData.Curves; using Qwack.Transport.TransportObjects.MarketData.VolSurfaces; namespace Qwack.Transport.TransportObjects.MarketData.Models { [ProtoContract] public class TO_FundingModel { [ProtoMember(4)] public Dictionary<string, TO_IrCurve> Curves { get; set; } [ProtoMember(5)] public Dictionary<string, TO_VolSurface> VolSurfaces { get; set; } [ProtoMember(6)] public DateTime BuildDate { get; set; } [ProtoMember(7)] public TO_FxMatrix FxMatrix { get; set; } } }
using Domain.Entities; using Domain.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WebApi.DataContracts.Users.Mappers { public static class UserMapper { public static User MapDataContractToEntity(UserRegister dc) { return new User { Username = dc.Username, Name = dc.Name, PasswordHash = dc.Password.Hash(dc.Username) }; } public static UserRegister MapEntityToDataContract(User user) { return new UserRegister { Username = user.Username, Password = user.PasswordHash, Name = user.Name }; } public static UserDetails MapUserEntityToUserDetails(User user) { return new UserDetails { Id = user.Id, Name = user.Name, Username = user.Username }; } } }
using Microsoft.EntityFrameworkCore; using ChefDish.Models; using System.Linq; using System; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; namespace Monsters.Controllers { public class HomeController : Controller { private MyContext _context; public HomeController(MyContext context) { _context = context; } [HttpGet("")] public IActionResult Index() { ViewBag.AllChefs = _context.Chefs .Include(x => x.Dishes) .ToList(); return View("Index"); } [HttpGet("new")] public IActionResult CreateChef() { return View("CreateChef"); } [HttpPost("new")] public IActionResult CreateChef(Chef FromForm) { if(ModelState.IsValid) { _context.Add(FromForm); _context.SaveChanges(); return RedirectToAction("Index"); } else { return View("CreateChef"); } } [HttpGet("dishes")] public IActionResult AllDishes() { var AllDishes = _context.Dishes .Include(x => x.Chef) .ToList(); return View("Dishes", AllDishes); } [HttpGet("dishes/new")] public IActionResult CreateDish() { ViewBag.AllChefs = _context.Chefs .Include(x => x.Dishes) .ToList(); return View("CreateDish"); } [HttpPost("dishes/new")] public IActionResult CreateDish(Dish FromForm) { if(ModelState.IsValid) { _context.Add(FromForm); _context.SaveChanges(); return RedirectToAction("AllDishes"); } else { ViewBag.AllChefs = _context.Chefs .Include(x => x.Dishes) .ToList(); return View("CreateDish"); } } } }
using System; using System.Linq; using System.Reflection; // ReSharper disable once CheckNamespace namespace Microsoft.Extensions.DependencyInjection { public static class ServiceCollectionExtensions { public static void AutoRegistrateServices( this IServiceCollection services, Assembly interfaceAssembly, Assembly implementationAssembly) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (interfaceAssembly == null) { throw new ArgumentNullException(nameof(interfaceAssembly)); } if (implementationAssembly == null) { throw new ArgumentNullException(nameof(implementationAssembly)); } var implementationInterfaces = interfaceAssembly .DefinedTypes .Where(x => x.IsInterface) .ToArray(); var implementationTypes = implementationAssembly .DefinedTypes .ToArray(); foreach (var implementationInterface in implementationInterfaces) { foreach (var implementationType in implementationTypes) { if (implementationType .GetInterfaces() .FirstOrDefault(x => string.Equals(x.FullName, implementationInterface.FullName, StringComparison.Ordinal)) == null) { continue; } if (!IsImplementationTypeRegistered(services, implementationType)) { services.AddTransient(implementationInterface, implementationType); } break; } } } public static void ValidateServiceRegistrations( this IServiceCollection services, Assembly apiAssembly) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (apiAssembly == null) { throw new ArgumentNullException(nameof(apiAssembly)); } var notRegistered = apiAssembly .DefinedTypes .Where(x => x.IsInterface) .Where(typeInfo => services .All(x => x.ServiceType != typeInfo)) .ToList(); if (notRegistered.Count <= 0) { return; } var missingRegistrations = notRegistered.Select(typeInfo => typeInfo.Name).ToArray(); throw new ItemNotFoundException($"Missing registrations for {apiAssembly.GetName().Name}: {string.Join(", ", missingRegistrations)}"); } private static bool IsImplementationTypeRegistered(IServiceCollection services, Type type) { return services.Any(item => item.ImplementationType == type); } } }
using Improbable.Core; using Improbable.Unity; using Improbable.Unity.Visualizer; using UnityEngine; namespace Assets.Gamelogic.Pirates.Behaviours { // Add this MonoBehaviour on client workers only [WorkerType(WorkerPlatform.UnityClient)] public class CameraEnablerVisualizer : MonoBehaviour { /* * Clients will only have write-access for their own designated PlayerShip entity's ClientAuthorityCheck component, * so this MonoBehaviour will be enabled on the client's designated PlayerShip GameObject only and not on * the GameObject of other players' ships. */ [Require] private ClientAuthorityCheck.Writer ClientAuthorityCheckWriter; private Transform Camera; [SerializeField] private Vector3 CameraOffset; public void OnEnable() { Camera = GameObject.FindObjectOfType<Camera>().transform; Camera.SetParent(gameObject.transform); Camera.localPosition = CameraOffset; Camera.LookAt(transform.position + Vector3.up); } public void OnDisable() { Camera.SetParent(null); } } }
namespace FeriaVirtual.Infrastructure.SeedWork.Events.RabbitMQ { public static class RabbitMqQueueNameFormatter { public static string Format(DomainEventSubscriberInformation information) => information.FormatRabbitMqQueueName(); public static string FormatRetry(DomainEventSubscriberInformation information) => $"retry.{Format(information)}"; public static string FormatDeadLetter(DomainEventSubscriberInformation information) => $"dead_letter.{Format(information)}"; } }
using OrgMan.API.Controllers.ControllerBase; using OrgMan.Common.DynamicSearchService.DynamicSearchModel; using OrgMan.Data.UnitOfWork; using OrgMan.DomainObjects.Common; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web; using System.Web.Http; namespace OrgMan.API.Controllers { public class MandatorController : ApiControllerBase { [HttpGet] [Route("api/mandator")] public HttpResponseMessage Get() { try { List<MandatorDomainModel> result = new List<MandatorDomainModel>(); OrgManUnitOfWork uow = new OrgManUnitOfWork(); foreach (Guid uid in RequestMandatorUIDs) { result.Add(AutoMapper.Mapper.Map<MandatorDomainModel>(uow.MandatorRepository.Get(uid))); } return Request.CreateResponse(HttpStatusCode.OK, result); } catch (Exception e) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using RTBid.Core.Domain; using RTBid.Core.Repository; using RTBid.Data.Infrastructure; namespace RTBid.Data.Repository { public class UserRoleRepository : Repository<UserRole>, IUserRoleRepository { public UserRoleRepository(IDatabaseFactory databaseFactory) : base(databaseFactory) { } } }
 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ResolverDemo { public class WithouDiDemo { public void Demo() { var visaShopper = new VisaShopper(); visaShopper.Charge(); var masterShopper = new MasterCardShopper(); masterShopper.Charge(); Console.Read(); } public class VisaShopper { public void Charge() { var visaCard = new Visa(); var chargeMessage = visaCard.Charge(); Console.WriteLine(chargeMessage); } } public class MasterCardShopper { public void Charge() { var masterCard = new MasterCard(); var chargeMessage = masterCard.Charge(); Console.WriteLine(chargeMessage); } } public class MasterCard { public string Charge() { return "Swiping the MasterCard!"; } } public class Visa { public string Charge() { return "Chaaaarging with the Visa!"; } } } }
using System; using System.Web; using log4net; using mssngrrr.utils; namespace mssngrrr { public abstract class BaseHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { try { context.Response.ContentType = "text/plain; charset=utf-8"; context.Response.AppendHeader("Cache-Control", "no-cache"); var result = ProcessRequestInternal(context); context.Response.Write(result.ToJsonString()); } catch(Exception e) { Log.Error(string.Format("Failed to process request '{0}'", context.Request.RawUrl), e); string message = null; var e1 = e as AjaxException; if(e1 != null) message = e1.Message; else { var e2 = e as HttpException; if(e2 != null && e2.WebEventCode == System.Web.Management.WebEventCodes.RuntimeErrorPostTooLarge) message = string.Format("Request too large (max {0}KB)", Settings.MaxRequestLength); } var result = new AjaxResult {Error = message ?? "Unknown server error"}; context.Response.Write(result.ToJsonString()); } } public bool IsReusable { get { return true; } } protected abstract AjaxResult ProcessRequestInternal(HttpContext context); private static readonly ILog Log = LogManager.GetLogger(typeof(BaseHandler)); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AutoMapper; using CSharpFunctionalExtensions; using Microsoft.EntityFrameworkCore; using OccBooking.Application.DTOs; using OccBooking.Application.Handlers.Base; using OccBooking.Application.Queries; using OccBooking.Persistence.DbContexts; namespace OccBooking.Application.Handlers { public class GetReservationRequestsHandler : QueryHandler<GetReservationRequestsQuery, IEnumerable<ReservationRequestDto>> { public GetReservationRequestsHandler(OccBookingDbContext dbContext, IMapper mapper) : base(dbContext, mapper) { } public override async Task<Result<IEnumerable<ReservationRequestDto>>> HandleAsync(GetReservationRequestsQuery query) { var requests = await _dbContext.ReservationRequests.Include(r => r.Place).ThenInclude(p => p.Owner) .Where(r => r.Place.Owner.Id == query.OwnerId).OrderByDescending(r => r.DateTime).ToListAsync(); return Result.Ok(_mapper.Map<IEnumerable<ReservationRequestDto>>(requests)); } } }
/* Dataphor © Copyright 2000-2008 Alphora This file is licensed under a modified BSD-license which can be found here: http://dataphor.org/dataphor_license.txt */ #define UseReferenceDerivation #define UseElaborable using System; using System.Text; using System.Threading; using System.Collections; using System.Collections.Generic; using Alphora.Dataphor.DAE.Language; using Alphora.Dataphor.DAE.Language.D4; using Alphora.Dataphor.DAE.Compiling; using Alphora.Dataphor.DAE.Compiling.Visitors; using Alphora.Dataphor.DAE.Server; using Alphora.Dataphor.DAE.Runtime; using Alphora.Dataphor.DAE.Runtime.Data; using Alphora.Dataphor.DAE.Runtime.Instructions; using Alphora.Dataphor.DAE.Device.ApplicationTransaction; using Schema = Alphora.Dataphor.DAE.Schema; using System.Linq; namespace Alphora.Dataphor.DAE.Runtime.Instructions { // operator iExtend(table{}, object) : table{} public class ExtendNode : UnaryTableNode { protected int _extendColumnOffset; public int ExtendColumnOffset { get { return _extendColumnOffset; } } private NamedColumnExpressions _expressions; public NamedColumnExpressions Expressions { get { return _expressions; } set { _expressions = value; } } public override void DetermineDataType(Plan plan) { DetermineModifiers(plan); _dataType = new Schema.TableType(); _tableVar = new Schema.ResultTableVar(this); _tableVar.Owner = plan.User; _tableVar.InheritMetaData(SourceTableVar.MetaData); CopyTableVarColumns(SourceTableVar.Columns); _extendColumnOffset = TableVar.Columns.Count; // This structure will track key columns as a set of sets, and any extended columns that are equivalent to them Dictionary<string, Schema.Key> keyColumns = new Dictionary<string, Schema.Key>(); foreach (Schema.TableVarColumn tableVarColumn in TableVar.Columns) if (SourceTableVar.Keys.IsKeyColumnName(tableVarColumn.Name) && !keyColumns.ContainsKey(tableVarColumn.Name)) keyColumns.Add(tableVarColumn.Name, new Schema.Key(new Schema.TableVarColumn[]{tableVarColumn})); ApplicationTransaction transaction = null; if (plan.ApplicationTransactionID != Guid.Empty) transaction = plan.GetApplicationTransaction(); try { if (transaction != null) transaction.PushLookup(); try { plan.PushCursorContext(new CursorContext(CursorType.Dynamic, CursorCapability.Navigable, CursorIsolation.None)); try { plan.EnterRowContext(); try { plan.Symbols.Push(new Symbol(String.Empty, SourceTableType.RowType)); try { // Add a column for each expression PlanNode planNode; Schema.TableVarColumn newColumn; foreach (NamedColumnExpression column in _expressions) { newColumn = new Schema.TableVarColumn(new Schema.Column(column.ColumnAlias, plan.DataTypes.SystemScalar)); plan.PushCreationObject(newColumn); try { planNode = Compiler.CompileExpression(plan, column.Expression); } finally { plan.PopCreationObject(); } bool isChangeRemotable = true; if (newColumn.HasDependencies()) for (int index = 0; index < newColumn.Dependencies.Count; index++) { Schema.Object objectValue = newColumn.Dependencies.ResolveObject(plan.CatalogDeviceSession, index); isChangeRemotable = isChangeRemotable && objectValue.IsRemotable; plan.AttachDependency(objectValue); } bool isUpdatable = planNode is TableNode || planNode is ExtractRowNode; newColumn = new Schema.TableVarColumn ( new Schema.Column(column.ColumnAlias, planNode.DataType), column.MetaData, isUpdatable ? Schema.TableVarColumnType.Stored : Schema.TableVarColumnType.Virtual ); newColumn.IsNilable = planNode.IsNilable; newColumn.IsChangeRemotable = isChangeRemotable; newColumn.IsDefaultRemotable = isChangeRemotable; DataType.Columns.Add(newColumn.Column); TableVar.Columns.Add(newColumn); string columnName = String.Empty; if (IsColumnReferencing(planNode, ref columnName)) { // TODO: In theory we could allow updatability through an IsColumnReferencing add column as well Schema.TableVarColumn referencedColumn = TableVar.Columns[columnName]; if (SourceTableVar.Keys.IsKeyColumnName(referencedColumn.Name)) { Schema.Key key; if (keyColumns.TryGetValue(referencedColumn.Name, out key)) key.Columns.Add(newColumn); else keyColumns.Add(referencedColumn.Name, new Schema.Key(new Schema.TableVarColumn[]{newColumn})); } } Nodes.Add(planNode); } DetermineRemotable(plan); } finally { plan.Symbols.Pop(); } } finally { plan.ExitRowContext(); } } finally { plan.PopCursorContext(); } } finally { if (transaction != null) transaction.PopLookup(); } } finally { if (transaction != null) Monitor.Exit(transaction); } foreach (Schema.Key key in SourceTableVar.Keys) { // Seed the result key set with the empty set Schema.Keys resultKeys = new Schema.Keys(); resultKeys.Add(new Schema.Key()); foreach (Schema.TableVarColumn column in key.Columns) resultKeys = KeyProduct(resultKeys, keyColumns[column.Name]); foreach (Schema.Key resultKey in resultKeys) { resultKey.IsSparse = key.IsSparse; resultKey.IsInherited = true; resultKey.MergeMetaData(key.MetaData); TableVar.Keys.Add(resultKey); } } CopyOrders(SourceTableVar.Orders); if (SourceNode.Order != null) Order = CopyOrder(SourceNode.Order); #if UseReferenceDerivation #if UseElaborable if (plan.CursorContext.CursorCapabilities.HasFlag(CursorCapability.Elaborable)) #endif CopyReferences(plan, SourceTableVar); #endif } protected Schema.Keys KeyProduct(Schema.Keys keys, Schema.Key key) { Schema.Keys result = new Schema.Keys(); foreach (Schema.Key localKey in keys) foreach (Schema.TableVarColumn newColumn in key.Columns) { Schema.Key newKey = new Schema.Key(); newKey.Columns.AddRange(localKey.Columns); newKey.Columns.Add(newColumn); result.Add(newKey); } return result; } protected bool IsColumnReferencing(PlanNode node, ref string columnName) { StackColumnReferenceNode localNode = node as StackColumnReferenceNode; if ((localNode != null) && (localNode.Location == 0)) { columnName = localNode.Identifier; return true; } else if (node.IsOrderPreserving && (node.NodeCount == 1)) return IsColumnReferencing(node.Nodes[0], ref columnName); else return false; } protected bool ReferencesUpdatedColumn(PlanNode node, BitArray valueFlags) { IList<string> columnReferences = new List<string>(); if (!node.IsContextLiteral(0, columnReferences)) { // If we cannot tell which column was referenced (variable level reference) // Or we cannot tell what columns were updated (no value flags) // Or any column references were to columns that were updated if (columnReferences.Count == 0 || valueFlags == null || (columnReferences.Select(c => DataType.Columns.IndexOfName(c)).Any(i => i >= 0 && i < _extendColumnOffset && valueFlags[i]))) { return true; } } return false; } public override void DetermineCursorBehavior(Plan plan) { _cursorType = SourceNode.CursorType; _requestedCursorType = plan.CursorContext.CursorType; _cursorCapabilities = CursorCapability.Navigable | ( (plan.CursorContext.CursorCapabilities & CursorCapability.Updateable) & (SourceNode.CursorCapabilities & CursorCapability.Updateable) ) | ( plan.CursorContext.CursorCapabilities & SourceNode.CursorCapabilities & CursorCapability.Elaborable ); _cursorIsolation = plan.CursorContext.CursorIsolation; if (SourceNode.Order != null) Order = CopyOrder(SourceNode.Order); else Order = null; } public override Statement EmitStatement(EmitMode mode) { ExtendExpression expression = new ExtendExpression(); expression.Expression = (Expression)Nodes[0].EmitStatement(mode); for (int index = ExtendColumnOffset; index < TableVar.Columns.Count; index++) expression.Expressions.Add ( new NamedColumnExpression ( (Expression)Nodes[index - ExtendColumnOffset + 1].EmitStatement(mode), DataType.Columns[index].Name, (MetaData)(TableVar.Columns[index].MetaData == null ? null : TableVar.Columns[index].MetaData.Copy() ) ) ); expression.Modifiers = Modifiers; return expression; } protected override void InternalBindingTraversal(Plan plan, PlanNodeVisitor visitor) { #if USEVISIT Nodes[0] = visitor.Visit(plan, Nodes[0]); #else Nodes[0].BindingTraversal(plan, visitor); #endif plan.EnterRowContext(); try { plan.Symbols.Push(new Symbol(String.Empty, SourceTableType.RowType)); try { for (int index = 1; index < Nodes.Count; index++) #if USEVISIT Nodes[index] = visitor.Visit(plan, Nodes[index]); #else Nodes[index].BindingTraversal(plan, visitor); #endif } finally { plan.Symbols.Pop(); } } finally { plan.ExitRowContext(); } } public override object InternalExecute(Program program) { ExtendTable table = new ExtendTable(this, program); try { table.Open(); return table; } catch { table.Dispose(); throw; } } public override void DetermineRemotable(Plan plan) { base.DetermineRemotable(plan); _tableVar.ShouldChange = true; _tableVar.ShouldDefault = true; foreach (Schema.TableVarColumn column in _tableVar.Columns) { column.ShouldChange = true; column.ShouldDefault = true; } } protected override bool InternalDefault(Program program, IRow oldRow, IRow newRow, BitArray valueFlags, string columnName, bool isDescending) { bool changed = false; if ((columnName == String.Empty) || (SourceNode.DataType.Columns.ContainsName(columnName))) changed = base.InternalDefault(program, oldRow, newRow, valueFlags, columnName, isDescending); return InternalInternalChange(newRow, columnName, program, true) || changed; } protected bool InternalInternalChange(IRow row, string columnName, Program program, bool isDefault) { bool changed = false; PushRow(program, row); try { // Evaluate the Extended columns // TODO: This change code should only run if the column changing can be determined to affect the extended columns... int columnIndex; for (int index = 1; index < Nodes.Count; index++) { Schema.TableVarColumn column = TableVar.Columns[_extendColumnOffset + index - 1]; if ((isDefault || column.IsComputed) && (!program.ServerProcess.ServerSession.Server.IsEngine || column.IsChangeRemotable)) { columnIndex = row.DataType.Columns.IndexOfName(column.Column.Name); if (columnIndex >= 0) { if (!isDefault || !row.HasValue(columnIndex)) { row[columnIndex] = Nodes[index].Execute(program); changed = true; } } } } return changed; } finally { PopRow(program); } } protected override bool InternalChange(Program program, IRow oldRow, IRow newRow, BitArray valueFlags, string columnName) { bool changed = false; if ((columnName == String.Empty) || (SourceNode.DataType.Columns.ContainsName(columnName))) changed = base.InternalChange(program, oldRow, newRow, valueFlags, columnName); return InternalInternalChange(newRow, columnName, program, false) || changed; } protected override bool InternalValidate(Program program, IRow oldRow, IRow newRow, BitArray valueFlags, string columnName, bool isDescending, bool isProposable) { if ((columnName == String.Empty) || SourceNode.DataType.Columns.ContainsName(columnName)) return base.InternalValidate(program, oldRow, newRow, valueFlags, columnName, isDescending, isProposable); return false; } // Insert protected override void InternalExecuteInsert(Program program, IRow oldRow, IRow newRow, BitArray valueFlags, bool uncheckedValue) { base.InternalExecuteInsert(program, oldRow, newRow, valueFlags, uncheckedValue); if (PropagateInsert != PropagateAction.False) { PushRow(program, newRow); try { int columnIndex; for (int index = 1; index < Nodes.Count; index++) { Schema.TableVarColumn column = TableVar.Columns[_extendColumnOffset + index - 1]; if (column.ColumnType == Schema.TableVarColumnType.Stored) { columnIndex = newRow.DataType.Columns.IndexOfName(column.Column.Name); if (columnIndex >= 0) { TableNode tableNode = Nodes[index] as TableNode; if (tableNode == null) { ExtractRowNode extractRowNode = Nodes[index] as ExtractRowNode; if (extractRowNode != null) { tableNode = (TableNode)extractRowNode.Nodes[0]; } } if (tableNode == null) throw new RuntimeException(RuntimeException.Codes.InternalError, "Could not determine update path for extend column."); IDataValue newValue = newRow.GetValue(columnIndex); if (!newValue.IsNil) { IRow newRowValue = newValue as IRow; if (newRowValue != null) { PerformInsert(program, tableNode, null, newRowValue, null, uncheckedValue); } else { TableValue newTableValue = (TableValue)newValue; using (ITable newTableCursor = newTableValue.OpenCursor()) { while (newTableCursor.Next()) { using (IRow newTableCursorRow = newTableCursor.Select()) { PerformInsert(program, tableNode, null, newTableCursorRow, null, uncheckedValue); } } } } } } } } } finally { PopRow(program); } } } private void PerformInsert(Program program, TableNode tableNode, IRow oldRow, IRow newRow, BitArray valueFlags, bool uncheckedValue) { switch (PropagateInsert) { case PropagateAction.True: tableNode.Insert(program, oldRow, newRow, valueFlags, uncheckedValue); break; case PropagateAction.Ensure: case PropagateAction.Ignore: using (Row sourceRow = new Row(program.ValueManager, tableNode.DataType.RowType)) { newRow.CopyTo(sourceRow); using (IRow currentRow = tableNode.Select(program, sourceRow)) { if (currentRow != null) { if (PropagateInsert == PropagateAction.Ensure) tableNode.Update(program, currentRow, newRow, valueFlags, false, uncheckedValue); } else tableNode.Insert(program, oldRow, newRow, valueFlags, uncheckedValue); } } break; } } // Update protected override void InternalExecuteUpdate(Program program, IRow oldRow, IRow newRow, BitArray valueFlags, bool checkConcurrency, bool uncheckedValue) { base.InternalExecuteUpdate(program, oldRow, newRow, valueFlags, checkConcurrency, uncheckedValue); if (PropagateUpdate) { int columnIndex; for (int index = 1; index < Nodes.Count; index++) { Schema.TableVarColumn column = TableVar.Columns[_extendColumnOffset + index - 1]; if (column.ColumnType == Schema.TableVarColumnType.Stored) { columnIndex = newRow.DataType.Columns.IndexOfName(column.Column.Name); if (columnIndex >= 0) { TableNode tableNode = Nodes[index] as TableNode; if (tableNode == null) { ExtractRowNode extractRowNode = Nodes[index] as ExtractRowNode; if (extractRowNode != null) { tableNode = (TableNode)extractRowNode.Nodes[0]; } } if (tableNode == null) throw new RuntimeException(RuntimeException.Codes.InternalError, "Could not determine update path for extend column."); bool referencesUpdatedColumn = ReferencesUpdatedColumn(tableNode, valueFlags); // If the value is a row // If the newValue is nil // If the oldValue is not nil // delete the table node // else // If the oldValue is nil // insert the row // else // update the row // If the value is a table // If the newValue is nil // If the oldValue is not nil // delete all rows // else // If the oldValue is nil // insert all rows // else // foreach row in oldvalue // if there is a corresponding row in new value by the clustering key // update the row // else // delete the row // for each row in newvalue // if there is no corresponding row in old value by the clustering key // insert the row if (column.DataType is Schema.IRowType) { IRow oldValue = (IRow)oldRow.GetValue(columnIndex); IRow newValue = (IRow)newRow.GetValue(columnIndex); if (newValue.IsNil) { if (!oldValue.IsNil) { PushRow(program, oldRow); try { tableNode.Delete(program, oldValue, checkConcurrency, uncheckedValue); } finally { PopRow(program); } } } else { if (oldValue.IsNil) { PushRow(program, newRow); try { tableNode.Insert(program, null, newValue, null, uncheckedValue); } finally { PopRow(program); } } else { if (referencesUpdatedColumn) { PushRow(program, oldRow); try { tableNode.Delete(program, oldValue, checkConcurrency, uncheckedValue); } finally { PopRow(program); } PushRow(program, newRow); try { tableNode.Insert(program, null, newValue, null, uncheckedValue); } finally { PopRow(program); } } else { PushRow(program, newRow); try { tableNode.Update(program, oldValue, newValue, null, checkConcurrency, uncheckedValue); } finally { PopRow(program); } } } } } else { TableValue oldValue = (TableValue)oldRow.GetValue(columnIndex); TableValue newValue = (TableValue)newRow.GetValue(columnIndex); if (newValue.IsNil) { if (!oldValue.IsNil) { PushRow(program, oldRow); try { using (ITable oldValueCursor = oldValue.OpenCursor()) { while (oldValueCursor.Next()) { using (IRow oldValueCursorRow = oldValueCursor.Select()) { tableNode.Delete(program, oldValueCursorRow, checkConcurrency, uncheckedValue); } } } } finally { PopRow(program); } } } else { if (referencesUpdatedColumn) { PushRow(program, oldRow); try { using (ITable oldValueCursor = oldValue.OpenCursor()) { while (oldValueCursor.Next()) { using (IRow oldValueCursorRow = oldValueCursor.Select()) { tableNode.Delete(program, oldValueCursorRow, checkConcurrency, uncheckedValue); } } } } finally { PopRow(program); } PushRow(program, newRow); try { using (ITable newValueCursor = newValue.OpenCursor()) { while (newValueCursor.Next()) { using (IRow newValueCursorRow = newValueCursor.Select()) { tableNode.Insert(program, null, newValueCursorRow, null, uncheckedValue); } } } } finally { PopRow(program); } } else { PushRow(program, newRow); try { if (oldValue.IsNil) { using (ITable newValueCursor = newValue.OpenCursor()) { while (newValueCursor.Next()) { using (IRow newValueCursorRow = newValueCursor.Select()) { tableNode.Insert(program, null, newValueCursorRow, null, uncheckedValue); } } } } else { using (ITable oldValueCursor = oldValue.OpenCursor()) { using (ITable newValueCursor = newValue.OpenCursor()) { while (oldValueCursor.Next()) { using (IRow oldValueCursorRow = oldValueCursor.Select()) { if (newValueCursor.FindKey(oldValueCursorRow)) { using (IRow newValueCursorRow = newValueCursor.Select()) { tableNode.Update(program, oldValueCursorRow, newValueCursorRow, null, checkConcurrency, uncheckedValue); } } else { tableNode.Delete(program, oldValueCursorRow, checkConcurrency, uncheckedValue); } } } newValueCursor.Reset(); while (newValueCursor.Next()) { using (IRow newValueCursorRow = newValueCursor.Select()) { if (!oldValueCursor.FindKey(newValueCursorRow)) { tableNode.Insert(program, null, newValueCursorRow, null, uncheckedValue); } } } } } } } finally { PopRow(program); } } } } } } } } } // Delete protected override void InternalExecuteDelete(Program program, IRow row, bool checkConcurrency, bool uncheckedValue) { base.InternalExecuteDelete(program, row, checkConcurrency, uncheckedValue); if (PropagateDelete) { PushRow(program, row); try { int columnIndex; for (int index = 1; index < Nodes.Count; index++) { Schema.TableVarColumn column = TableVar.Columns[_extendColumnOffset + index - 1]; if (column.ColumnType == Schema.TableVarColumnType.Stored) { columnIndex = row.DataType.Columns.IndexOfName(column.Column.Name); if (columnIndex >= 0) { TableNode tableNode = Nodes[index] as TableNode; if (tableNode == null) { ExtractRowNode extractRowNode = Nodes[index] as ExtractRowNode; if (extractRowNode != null) { tableNode = (TableNode)extractRowNode.Nodes[0]; } } if (tableNode == null) throw new RuntimeException(RuntimeException.Codes.InternalError, "Could not determine update path for extend column."); IDataValue oldValue = row.GetValue(columnIndex); if (!oldValue.IsNil) { IRow oldRowValue = oldValue as IRow; if (oldRowValue != null) { tableNode.Delete(program, oldRowValue, checkConcurrency, uncheckedValue); } else { TableValue oldTableValue = (TableValue)oldValue; using (ITable oldTableCursor = oldTableValue.OpenCursor()) { while (oldTableCursor.Next()) { using (IRow oldTableCursorRow = oldTableCursor.Select()) { tableNode.Delete(program, oldTableCursorRow, checkConcurrency, uncheckedValue); } } } } } } } } } finally { PopRow(program); } } } public override void JoinApplicationTransaction(Program program, IRow row) { // Exclude any columns from AKey which were included by this node Schema.RowType rowType = new Schema.RowType(); foreach (Schema.Column column in row.DataType.Columns) if (SourceNode.DataType.Columns.ContainsName(column.Name)) rowType.Columns.Add(column.Copy()); Row localRow = new Row(program.ValueManager, rowType); try { row.CopyTo(localRow); SourceNode.JoinApplicationTransaction(program, localRow); } finally { localRow.Dispose(); } } public override bool IsContextLiteral(int location, IList<string> columnReferences) { if (!Nodes[0].IsContextLiteral(location, columnReferences)) return false; for (int index = 1; index < Nodes.Count; index++) if (!Nodes[index].IsContextLiteral(location + 1, columnReferences)) return false; return true; } } }
using System.Collections; using System.Collections.Generic; namespace CollectionsUtility.Specialized { using CollectionsUtility.Specialized.Internals; public class Histogram<TKey, TValue> : IHistogram<TKey, TValue> where TValue : struct { #region private private UniqueList<TKey> _mapping; private List<TValue> _values; #endregion public IHistArith<TValue> HistArith { get; } public IEnumerable<TKey> Keys { get; } public IEnumerable<TValue> Values { get; } public int Count => _mapping.Count; public TValue DefaultIncrement { get; set; } public TValue this[TKey key] => _values[_mapping.IndexOf(key)]; public Histogram(IHistArith<TValue> histArith) { HistArith = histArith; _mapping = new UniqueList<TKey>(); _values = new List<TValue>(); DefaultIncrement = HistArith.UnitValue; Keys = _mapping; Values = _values; } public void Clear() { _mapping.Clear(); _values.Clear(); DefaultIncrement = HistArith.UnitValue; } public void Add(TKey key) { Add(key, DefaultIncrement); } public void Add(KeyValuePair<TKey, TValue> keyAndAmount) { Add(keyAndAmount.Key, keyAndAmount.Value); } public void Add(TKey key, TValue amount) { int index = _mapping.Add(key); while (index >= _values.Count) { _values.Add(default); } _values[index] = HistArith.Add(_values[index], amount); } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { foreach (var indexAndKey in (IEnumerable<(int Index, TKey Item)>)_mapping) { yield return new KeyValuePair<TKey, TValue>(indexAndKey.Item, _values[indexAndKey.Index]); } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public bool ContainsKey(TKey key) { return _mapping.IndexOf(key) >= 0; } public bool TryGetValue(TKey key, out TValue value) { int index = _mapping.IndexOf(key); if (index >= 0) { value = _values[index]; return true; } value = default; return false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using ClientPortal; namespace ClientPortal { public class URL { public static void GoTo(string URL) { Driver.Instance.Navigate().GoToUrl(URL); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace CPClient.Service.Model { public partial class ClienteModel { [Key] public int Id { get; set; } public string NomeCompleto { get; set; } public string CPF { get; set; } public string Rg { get; set; } public DateTime DataNascimento { get; set; } public bool Ativo { get; set; } public virtual ICollection<ClienteEnderecoModel> Enderecos { get; set; } public virtual ICollection<ClienteTelefoneModel> Telefones { get; set; } public virtual ICollection<ClienteRedeSocialModel> RedesSociais { get; set; } } }
namespace TripDestination.Data.Data { using System; using Models; using System.Data.Entity; using System.Data.Entity.Infrastructure; public interface ITripDestinationDbContext : IDisposable { IDbSet<User> Users { get; set; } IDbSet<Car> Cars { get; set; } IDbSet<TripComment> TripComments { get; set; } IDbSet<UserComment> UserComments { get; set; } IDbSet<Like> Likes { get; set; } IDbSet<Newsletter> Newsletters { get; set; } IDbSet<Notification> Notifications { get; set; } IDbSet<NotificationType> NotificationTypes { get; set; } IDbSet<PassengerTrip> PassengerTrips { get; set; } IDbSet<Photo> Photos { get; set; } IDbSet<Rating> Ratings { get; set; } IDbSet<Town> Towns { get; set; } IDbSet<Trip> Trips { get; set; } IDbSet<View> Views { get; set; } IDbSet<Page> Pages { get; set; } IDbSet<PageParagraph> PageParagraphs { get; set; } IDbSet<ContactForm> ContactForms { get; set; } int SaveChanges(); DbSet<TEntity> Set<TEntity>() where TEntity : class; DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using ComponentFactory.Krypton.Toolkit; using TY.SPIMS.Controllers; using TY.SPIMS.Controllers.Interfaces; namespace TY.SPIMS.Client.Report { public partial class Form1 : ComponentFactory.Krypton.Toolkit.KryptonForm { private readonly IPurchaseController purchaseController; public Form1() { this.purchaseController = IOC.Container.GetInstance<PurchaseController>(); InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { this.PurchasesViewBindingSource.DataSource = this.purchaseController.FetchAllPurchases(); this.reportViewer1.RefreshReport(); } } }
using EmployeeTaskMonitor.Core.Models; using EmployeeTaskMonitor.Core.ServiceInterfaces; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace EmployeeTaskMonitor.MVC.Controllers { public class EmployeesController : Controller { private readonly IEmployeeService _employeeService; public EmployeesController(IEmployeeService employeeService) { _employeeService = employeeService; } [HttpGet] public IActionResult Index() { return View(); } [HttpGet] public async Task<IActionResult> GetTasks(int Id) { var employeeTasks =await _employeeService.GetTasksByEmployeeId(Id); ViewBag.EmployeeId = Id; return View(employeeTasks); } [HttpGet] public async Task<IActionResult> CreateEmployee() { return View(); } [HttpPost] public async System.Threading.Tasks.Task<IActionResult> CreateEmployee(EmployeeRequestModel employeeCreateRequest) { if (ModelState.IsValid) { await _employeeService.AddEmployee(employeeCreateRequest); } var employees = await _employeeService.GetAllEmployees(); return View("../Home/Index", employees); } [HttpGet] public async Task<IActionResult> DeleteEmployee() { return View(); } [HttpPost] public async System.Threading.Tasks.Task<IActionResult> DeleteEmployee(EmployeeRequestModel employeeCreateRequest) { if (ModelState.IsValid) { await _employeeService.RemoveEmployee(employeeCreateRequest); } return View(); } [HttpGet] public async Task<IActionResult> EditEmployee() { return View(); } [HttpPost] public async System.Threading.Tasks.Task<IActionResult> EditEmployee(EmployeeRequestModel employeeCreateRequest) { if (ModelState.IsValid) { await _employeeService.UpdateEmployee(employeeCreateRequest); } return View(); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using DA.Seguridad; using BE.Seguridad; namespace BL.Seguridad { public partial class BL_menu { private IDAOFactory _daoFactory; private ImenuDAO _daomenu; public BL_menu() { _daoFactory = new DAOFactory(); _daomenu = _daoFactory.getmenuDAO(); } public List<Dictionary<String, Object>> getAll() { return _daomenu.getAll(); } } }
using EddiDataDefinitions; using EddiEvents; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Utilities; namespace EddiStatusService { public class StatusService { // Declare our constants private const int pollingIntervalActiveMs = 500; private const int pollingIntervalRelaxedMs = 5000; private static readonly Regex JsonRegex = new Regex(@"^{.*}$"); private static readonly string Directory = GetSavedGamesDir(); // Public Read Variables public Status CurrentStatus { get; private set; } = new Status(); public Status LastStatus { get; private set; } = new Status(); public static event EventHandler StatusUpdatedEvent; // Public Write variables (set elsewhere to assist with various calculations) public Ship CurrentShip; public List<KeyValuePair<DateTime, decimal?>> fuelLog; public EnteredNormalSpaceEvent lastEnteredNormalSpaceEvent; // Other variables used by this service private static StatusService instance; private static readonly object instanceLock = new object(); public readonly object statusLock = new object(); private bool running; public static StatusService Instance { get { if (instance == null) { lock (instanceLock) { if (instance == null) { Logging.Debug("No status service instance: creating one"); instance = new StatusService(); } } } return instance; } } public void Start() { if (string.IsNullOrWhiteSpace(Directory)) { return; } running = true; // Start off by moving to the end of the file FileInfo fileInfo = null; try { fileInfo = Files.FileInfo(Directory, "Status.json"); } catch (NotSupportedException nsex) { Logging.Error("Directory " + Directory + " not supported: ", nsex); } if (fileInfo != null) { try { using (FileStream fs = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (StreamReader reader = new StreamReader(fs, Encoding.UTF8)) { string LastStatusJson = reader.ReadLine() ?? string.Empty; // Main loop while (running) { if (Processes.IsEliteRunning()) { if (!fileInfo.Exists) { WaitForStatusFile(ref fileInfo); } else { LastStatusJson = ReadStatus(LastStatusJson, fs, reader); } Thread.Sleep(pollingIntervalActiveMs); } else { Thread.Sleep(pollingIntervalRelaxedMs); } } } } catch (Exception) { // file open elsewhere or being written, just wait for the next pass } } } public void Stop() { running = false; } private void WaitForStatusFile(ref FileInfo fileInfo) { // Status.json could not be found. Sleep until a Status.json file is found. Logging.Info("Error locating Elite Dangerous Status.json. Status monitor is not active. Have you installed and run Elite Dangerous previously? "); while (!fileInfo.Exists) { Thread.Sleep(pollingIntervalRelaxedMs); fileInfo = Files.FileInfo(Directory, "Status.json"); } Logging.Info("Elite Dangerous Status.json found. Status monitor activated."); } private string ReadStatus(string LastStatusJson, FileStream fs, StreamReader reader) { string thisStatusJson = string.Empty; try { fs.Seek(0, SeekOrigin.Begin); thisStatusJson = reader.ReadLine() ?? string.Empty; } catch (Exception) { // file open elsewhere or being written, just wait for the next pass } if (LastStatusJson != thisStatusJson && !string.IsNullOrWhiteSpace(thisStatusJson)) { Status status = ParseStatusEntry(thisStatusJson); // Spin off a thread to pass status entry updates in the background Thread updateThread = new Thread(() => handleStatus(status)) { IsBackground = true }; updateThread.Start(); } LastStatusJson = thisStatusJson; return LastStatusJson; } public Status ParseStatusEntry(string line) { Status status = new Status() { raw = line }; try { Match match = JsonRegex.Match(line); if (match.Success) { IDictionary<string, object> data = Deserializtion.DeserializeData(line); // Every status event has a timestamp field status.timestamp = DateTime.UtcNow; try { status.timestamp = JsonParsing.getDateTime("timestamp", data); } catch { Logging.Warn("Status without timestamp; using current time"); } status.flags = (Status.Flags)(JsonParsing.getOptionalLong(data, "Flags") ?? 0); status.flags2 = (Status.Flags2)(JsonParsing.getOptionalLong(data, "Flags2") ?? 0); if (status.flags == Status.Flags.None && status.flags2 == Status.Flags2.None) { // No flags are set. We aren't in game. return status; } data.TryGetValue("Pips", out object val); List<long> pips = ((List<object>)val)?.Cast<long>()?.ToList(); // The 'TryGetValue' function returns these values as type 'object<long>' status.pips_sys = pips != null ? ((decimal?)pips[0] / 2) : null; // Set system pips (converting from half pips) status.pips_eng = pips != null ? ((decimal?)pips[1] / 2) : null; // Set engine pips (converting from half pips) status.pips_wea = pips != null ? ((decimal?)pips[2] / 2) : null; // Set weapon pips (converting from half pips) status.firegroup = JsonParsing.getOptionalInt(data, "FireGroup"); int? gui_focus = JsonParsing.getOptionalInt(data, "GuiFocus"); switch (gui_focus) { case null: case 0: // No focus { status.gui_focus = "none"; break; } case 1: // InternalPanel (right hand side) { status.gui_focus = "internal panel"; break; } case 2: // ExternalPanel (left hand side) { status.gui_focus = "external panel"; break; } case 3: // CommsPanel (top) { status.gui_focus = "communications panel"; break; } case 4: // RolePanel (bottom) { status.gui_focus = "role panel"; break; } case 5: // StationServices { status.gui_focus = "station services"; break; } case 6: // GalaxyMap { status.gui_focus = "galaxy map"; break; } case 7: // SystemMap { status.gui_focus = "system map"; break; } case 8: // Orrery { status.gui_focus = "orrery"; break; } case 9: // FSS mode { status.gui_focus = "fss mode"; break; } case 10: // SAA mode { status.gui_focus = "saa mode"; break; } case 11: // Codex { status.gui_focus = "codex"; break; } } status.latitude = JsonParsing.getOptionalDecimal(data, "Latitude"); status.longitude = JsonParsing.getOptionalDecimal(data, "Longitude"); status.altitude = JsonParsing.getOptionalDecimal(data, "Altitude"); status.heading = JsonParsing.getOptionalDecimal(data, "Heading"); if (data.TryGetValue("Fuel", out object fuelData)) { if (fuelData is IDictionary<string, object> fuelInfo) { status.fuelInTanks = JsonParsing.getOptionalDecimal(fuelInfo, "FuelMain"); status.fuelInReservoir = JsonParsing.getOptionalDecimal(fuelInfo, "FuelReservoir"); } } status.cargo_carried = (int?)JsonParsing.getOptionalDecimal(data, "Cargo"); status.legalStatus = LegalStatus.FromEDName(JsonParsing.getString(data, "LegalState")) ?? LegalStatus.Clean; status.bodyname = JsonParsing.getString(data, "BodyName"); // Might be a station name if we're in an orbital station status.planetradius = JsonParsing.getOptionalDecimal(data, "PlanetRadius"); status.credit_balance = JsonParsing.getOptionalULong(data, "Balance"); // When on foot status.oxygen = JsonParsing.getOptionalDecimal(data, "Oxygen") * 100; // Convert Oxygen to a 0-100 percent scale status.health = JsonParsing.getOptionalDecimal(data, "Health") * 100; // Convert Health to a 0-100 percent scale status.temperature = JsonParsing.getOptionalDecimal(data, "Temperature"); // In Kelvin status.selected_weapon = JsonParsing.getString(data, "SelectedWeapon_Localised") ?? JsonParsing.getString(data, "SelectedWeapon"); // The name of the selected weapon status.gravity = JsonParsing.getOptionalDecimal(data, "Gravity"); // Gravity, relative to 1G // When not on foot if (data.TryGetValue("Destination", out object destinationData)) { if (destinationData is IDictionary<string, object> destinationInfo) { status.destinationSystemAddress = JsonParsing.getOptionalULong(destinationInfo, "System"); status.destinationBodyId = JsonParsing.getOptionalInt(destinationInfo, "Body"); status.destination_name = JsonParsing.getString(destinationInfo, "Name"); status.destination_localized_name = JsonParsing.getString(destinationInfo, "Name_Localised") ?? string.Empty; // Destination might be a fleet carrier with name and carrier id in a single string. If so, we break them apart var fleetCarrierRegex = new Regex("^(.+)(?> )([A-Za-z0-9]{3}-[A-Za-z0-9]{3})$"); if (string.IsNullOrEmpty(status.destination_localized_name) && fleetCarrierRegex.IsMatch(status.destination_name)) { // Fleet carrier names include both the carrier name and carrier ID, we need to separate them var fleetCarrierParts = fleetCarrierRegex.Matches(status.destination_name)[0].Groups; if (fleetCarrierParts.Count == 3) { status.destination_name = fleetCarrierParts[2].Value; status.destination_localized_name = fleetCarrierParts[1].Value; } } } } // Calculated data SetFuelExtras(status); SetSlope(status); return status; } } catch (Exception ex) { Logging.Warn("Failed to parse Status.json line: " + ex.ToString()); Logging.Error("", ex); } return null; } public void handleStatus(Status thisStatus) { if (thisStatus == null) { return; } lock ( statusLock ) { if ( CurrentStatus != thisStatus ) { // Save our last status for reference and update our current status LastStatus = CurrentStatus; CurrentStatus = thisStatus; // Pass the change in status to all subscribed processes OnStatus( StatusUpdatedEvent, CurrentStatus ); } } } private void OnStatus(EventHandler statusUpdatedEvent, Status status) { statusUpdatedEvent?.Invoke(status, EventArgs.Empty); } private void SetFuelExtras(Status status) { decimal? fuel_rate = FuelConsumptionPerSecond(status.timestamp, status.fuel); FuelPercentAndTime(status.vehicle, status.fuel, fuel_rate, out decimal? fuel_percent, out int? fuel_seconds); status.fuel_percent = fuel_percent; status.fuel_seconds = fuel_seconds; } private decimal? FuelConsumptionPerSecond(DateTime timestamp, decimal? fuel, int trackingMinutes = 5) { if (fuel is null) { return null; } if (fuelLog is null) { fuelLog = new List<KeyValuePair<DateTime, decimal?>>(); } else { fuelLog.RemoveAll(log => (DateTime.UtcNow - log.Key).TotalMinutes > trackingMinutes); } fuelLog.Add(new KeyValuePair<DateTime, decimal?>(timestamp, fuel)); if (fuelLog.Count > 1) { decimal? fuelConsumed = fuelLog.FirstOrDefault().Value - fuelLog.LastOrDefault().Value; TimeSpan timespan = fuelLog.LastOrDefault().Key - fuelLog.FirstOrDefault().Key; return timespan.Seconds == 0 ? null : fuelConsumed / timespan.Seconds; // Return tons of fuel consumed per second } // Insufficient data, return 0. return 0; } private void FuelPercentAndTime(string vehicle, decimal? fuelRemaining, decimal? fuelPerSecond, out decimal? fuel_percent, out int? fuel_seconds) { fuel_percent = null; fuel_seconds = null; if (fuelRemaining is null) { return; } if (vehicle == Constants.VEHICLE_SHIP && CurrentShip != null) { if (CurrentShip?.fueltanktotalcapacity > 0) { // Fuel recorded in Status.json includes the fuel carried in the Active Fuel Reservoir decimal percent = (decimal)(fuelRemaining / (CurrentShip.fueltanktotalcapacity + CurrentShip.activeFuelReservoirCapacity) * 100); fuel_percent = percent > 10 ? Math.Round(percent, 0) : Math.Round(percent, 1); fuel_seconds = fuelPerSecond > 0 ? (int?)((CurrentShip.fueltanktotalcapacity + CurrentShip.activeFuelReservoirCapacity) / fuelPerSecond) : null; } } else if (vehicle == Constants.VEHICLE_SRV) { const decimal srvFuelTankCapacity = 0.45M; decimal percent = (decimal)(fuelRemaining / srvFuelTankCapacity * 100); fuel_percent = percent > 10 ? Math.Round(percent, 0) : Math.Round(percent, 1); fuel_seconds = fuelPerSecond > 0 ? (int?)(srvFuelTankCapacity / fuelPerSecond) : null; } return; // At present, fighters do not appear to consume fuel. } ///<summary> Our calculated slope may be inaccurate if we are in normal space and thrusting /// in a direction other than the direction we are oriented (e.g. if pointing down towards a /// planet and applying reverse thrust to raise our altitude) </summary> private void SetSlope(Status status) { status.slope = null; if (LastStatus?.planetradius != null && LastStatus?.altitude != null && LastStatus?.latitude != null && LastStatus?.longitude != null) { if (status.planetradius != null && status.altitude != null && status.latitude != null && status.longitude != null) { double square(double x) => x * x; var radiusKm = (double)status.planetradius / 1000; var deltaAltKm = (double)(status.altitude - LastStatus.altitude) / 1000; // Convert latitude & longitude to radians var currentLat = (double)status.latitude * Math.PI / 180; var lastLat = (double)LastStatus.latitude * Math.PI / 180; var deltaLat = currentLat - lastLat; var deltaLong = (double)(status.longitude - LastStatus.longitude) * Math.PI / 180; // Calculate distance traveled using Law of Haversines var a = square(Math.Sin(deltaLat / 2)) + (Math.Cos(currentLat) * Math.Cos(lastLat) * square(Math.Sin(deltaLong / 2))); var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a)); var distanceKm = c * radiusKm; // Calculate the slope angle var slopeRadians = Math.Atan2(deltaAltKm, distanceKm); var slopeDegrees = slopeRadians * 180 / Math.PI; status.slope = Math.Round((decimal)slopeDegrees, 1); } } } private static string GetSavedGamesDir() { int result = NativeMethods.SHGetKnownFolderPath(new Guid("4C5C32FF-BB9D-43B0-B5B4-2D72E54EAAA4"), 0, new IntPtr(0), out IntPtr path); if (result >= 0) { return Marshal.PtrToStringUni(path) + @"\Frontier Developments\Elite Dangerous"; } else { throw new ExternalException("Failed to find the saved games directory.", result); } } internal class NativeMethods { [DllImport("Shell32.dll")] internal static extern int SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, IntPtr hToken, out IntPtr ppszPath); } } }
using gView.Framework.Data; using gView.Framework.Data.Cursors; using gView.Framework.Data.Filters; using gView.Framework.FDB; using System; using System.Threading.Tasks; namespace gView.DataSources.Fdb { public class LinkedFeatureClass : IFeatureClass, IDatabaseNames { private IFeatureClass _fc; private IDataset _dataset; private string _name; public LinkedFeatureClass(IDataset dataset, IFeatureClass fc, string name) { _dataset = dataset; _fc = fc; _name = name; } #region IFeatureClass Members public string ShapeFieldName { get { return _fc != null ? _fc.ShapeFieldName : String.Empty; } } public Framework.Geometry.IEnvelope Envelope { get { return _fc != null ? _fc.Envelope : null; } } async public Task<int> CountFeatures() { return _fc != null ? await _fc.CountFeatures() : 0; } async public Task<IFeatureCursor> GetFeatures(IQueryFilter filter) { if (_fc == null) { return null; } return await _fc.GetFeatures(filter); } #endregion #region ITableClass Members async public Task<ICursor> Search(IQueryFilter filter) { if (_fc == null) { return null; } return await _fc.Search(filter); } async public Task<ISelectionSet> Select(IQueryFilter filter) { if (_fc == null) { return null; } return await Select(filter); } public IFieldCollection Fields { get { return _fc != null ? _fc.Fields : new FieldCollection(); } } public IField FindField(string name) { return _fc != null ? _fc.FindField(name) : null; } public string IDFieldName { get { return _fc != null ? _fc.IDFieldName : String.Empty; } } #endregion #region IClass Members public string Name { get { return _name; } } public string Aliasname { get { return _name; } } public IDataset Dataset { get { return _dataset; } } #endregion #region IGeometryDef Members public bool HasZ { get { return _fc != null ? _fc.HasZ : false; } } public bool HasM { get { return _fc != null ? _fc.HasM : false; } } public Framework.Geometry.ISpatialReference SpatialReference { get { return _fc?.SpatialReference; } } public Framework.Geometry.GeometryType GeometryType { get { return _fc != null ? _fc.GeometryType : gView.Framework.Geometry.GeometryType.Unknown; } } #endregion #region IDatabaseNames Members public string TableName(string tableName) { if (_fc == null || _fc.Dataset == null || !(_fc.Dataset.Database is IDatabaseNames)) { return tableName; } return ((IDatabaseNames)_fc.Dataset.Database).TableName(tableName); } public string DbColName(string fieldName) { if (_fc == null || _fc.Dataset == null || !(_fc.Dataset.Database is IDatabaseNames)) { return fieldName; } return ((IDatabaseNames)_fc.Dataset.Database).DbColName(fieldName); } #endregion } }
using EddiDataDefinitions; using System; using System.Collections.Generic; using Utilities; namespace EddiEvents { [PublicAPI] public class MissionAcceptedEvent : Event { public const string NAME = "Mission accepted"; public const string DESCRIPTION = "Triggered when you accept a mission"; public const string SAMPLE = "{ \"timestamp\":\"2018-11-10T03:25:17Z\", \"event\":\"MissionAccepted\", \"Faction\":\"HIP 20277 Party\", \"Name\":\"Mission_DeliveryWing_Boom\", \"LocalisedName\":\"Boom time delivery of 2737 units of Survival Equipment\", \"Commodity\":\"$SurvivalEquipment_Name;\", \"Commodity_Localised\":\"Survival Equipment\", \"Count\":2737, \"TargetFaction\":\"Guathiti Empire Party\", \"DestinationSystem\":\"Guathiti\", \"DestinationStation\":\"Houtman Landing\", \"Expiry\":\"2018-11-11T02:41:24Z\", \"Wing\":true, \"Influence\":\"+\", \"Reputation\":\"+\", \"Reward\":5391159, \"MissionID\":426330530 }"; [PublicAPI("The ID of the mission")] public long? missionid => Mission.missionid; [PublicAPI("The name of the mission")] public string name => Mission.name; [PublicAPI("The localised name of the mission")] public string localisedname => Mission.localisedname; [PublicAPI("A localized list of mission tags / attributes")] public List<string> tags => Mission.tags; [PublicAPI("An unlocalized list of mission tags / attributes")] public List<string> invariantTags => Mission.invariantTags; [PublicAPI("The faction issuing the mission")] public string faction => Mission.faction; [PublicAPI("The expected cash reward from the mission")] public long? reward => Mission.reward; [PublicAPI("The increase in the faction's influence in the system gained when completing this mission, if any")] public string influence => Mission.influence; [PublicAPI("The increase in the commander's reputation with the faction gained when completing this mission, if any")] public string reputation => Mission.reputation; [PublicAPI("True if the mission allows wing-mates")] public bool wing => Mission.wing; [PublicAPI("The expiry date of the mission")] public DateTime? expiry => Mission.expiry; [PublicAPI("The commodity involved in the mission (if applicable)")] public string commodity => Mission.CommodityDefinition?.localizedName; [PublicAPI("The micro-resource (on foot item) involved in the mission (if applicable)")] public string microresource => Mission.MicroResourceDefinition?.localizedName; [PublicAPI( "The amount of the commodity or micro-resource, passengers, or targets involved in the mission (if applicable)")] public int? amount => Mission.amount; [PublicAPI("The destination system for the mission (if applicable)")] public string destinationsystem => Mission.destinationsystem; [PublicAPI("The destination station for the mission (if applicable)")] public string destinationstation => Mission.destinationstation; [PublicAPI("The type of passengers in the mission (if applicable)")] public string passengertype => Mission.passengertype; [PublicAPI("True if the passengers are wanted (if applicable)")] public bool? passengerwanted => Mission.passengerwanted; [PublicAPI("True if the passenger is a VIP (if applicable)")] public bool? passengervips => Mission.passengervips; [PublicAPI("Name of the target of the mission (if applicable)")] public string target => Mission.target; [PublicAPI("Type of the target of the mission (if applicable)")] public string targettype => Mission.targettype; [PublicAPI("Faction of the target of the mission (if applicable)")] public string targetfaction => Mission.targetfaction; [PublicAPI("True if the mission is a community goal")] public bool communal => Mission.communal; // Not intended to be user facing public Mission Mission { get; } public MissionAcceptedEvent(DateTime timestamp, Mission mission) : base(timestamp, NAME) { this.Mission = mission; } } }
using System; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using SC = System.Collections; using SD = System.Data; using SDS = System.Data.SqlClient; using ST = System.Type; public partial class NoWizardGridView : System.Web.UI.Page { protected SD.DataView dv = new SD.DataView(); private SDS.SqlDataAdapter da = new SDS.SqlDataAdapter(); private SD.DataSet ds = new SD.DataSet(); private SDS.SqlConnection cn = new SDS.SqlConnection(); protected void Page_Load(object sender, EventArgs e) { cn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["studentConnectionString"].ConnectionString; da.SelectCommand = new SDS.SqlCommand(); da.SelectCommand.Connection = cn; if (!IsPostBack) { // only need to do this the first time the page is accessed SD.DataTable dt = new SD.DataTable("table"); SD.DataRow dr; dt.Columns.Add(new SD.DataColumn("StudentID", ST.GetType("System.Int32"))); dt.Columns.Add(new SD.DataColumn("StudentLastName", ST.GetType("System.String"))); dt.Columns.Add(new SD.DataColumn("StudentFirstName", ST.GetType("System.String"))); dt.Columns.Add(new SD.DataColumn("StudentMI", ST.GetType("System.String"))); da.SelectCommand.CommandText = "SELECT StudentID, StudentLastName, StudentFirstName, StudentMI " + "FROM UniversityStudent " + "ORDER BY StudentLastName, StudentFirstName"; da.Fill(ds, "students"); foreach (SD.DataRow row in ds.Tables["students"].Rows) { dr = dt.NewRow(); dr[0] = row["StudentID"]; dr[1] = row["StudentLastName"]; dr[2] = row["StudentFirstName"]; dr[3] = row["StudentMI"]; dt.Rows.Add(dr); } dv.Table = dt; gvStudent.DataSource = dv; gvStudent.DataBind(); Session["gvStudentTable"] = dv; } } protected void gvStudent_RowEditing(object sender, GridViewEditEventArgs e) { dv = (SD.DataView)Session["gvStudentTable"]; // saved this in the ddlAdvisor_SelectedIndexChanged event handler gvStudent.DataSource = dv; gvStudent.EditIndex = e.NewEditIndex; gvStudent.DataBind(); } protected void gvStudent_RowUpdating(object sender, GridViewUpdateEventArgs e) { GridViewRow row = gvStudent.Rows[e.RowIndex]; TextBox last = (TextBox)row.FindControl("txtLast"); TextBox first = (TextBox)row.FindControl("txtFirst"); TextBox mi = (TextBox)row.FindControl("txtMI"); SD.DataTable dt = ((SD.DataView)Session["gvStudentTable"]).Table; dt.Rows[row.DataItemIndex]["StudentLastName"] = last.Text; dt.Rows[row.DataItemIndex]["StudentFirstName"] = first.Text; dt.Rows[row.DataItemIndex]["StudentMI"] = mi.Text; gvStudent.EditIndex = -1; gvStudent.DataSource = dt; gvStudent.DataBind(); // push the update through to the database? updateStudent(last.Text, first.Text, mi.Text, Convert.ToInt32(dt.Rows[row.DataItemIndex]["StudentID"])); } private void updateStudent(string last, string first, string mi, Int32 studentid) { SDS.SqlCommand sqlCommand = new SDS.SqlCommand(); sqlCommand.Connection = cn; sqlCommand.CommandText = "UPDATE universitystudent SET StudentLastName = @StudentLastName, " + "StudentFirstName = @StudentFirstName, " + "StudentMI = @StudentMI " + "WHERE StudentID = " + studentid.ToString(); sqlCommand.Parameters.Add(new SD.SqlClient.SqlParameter("StudentLastName", last)); sqlCommand.Parameters.Add(new SD.SqlClient.SqlParameter("StudentFirstName", first)); sqlCommand.Parameters.Add(new SD.SqlClient.SqlParameter("StudentMI", mi)); try { cn.Open(); sqlCommand.ExecuteNonQuery(); } catch (Exception ex) { System.Console.WriteLine(ex.Message); } finally { cn.Close(); } } protected void gvStudent_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { gvStudent.EditIndex = -1; gvStudent.DataSource = ((SD.DataView)Session["gvStudentTable"]).Table; // saved this in the ddlAdvisor_SelectedIndexChanged event handler gvStudent.DataBind(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Task2.Figures; namespace Task2 { class Program { static void Main(string[] args) { int select = 0; do { try { ShowMenu(); do { Console.Write("Select the number of task: "); } while (!int.TryParse(Console.ReadLine(), out select)); Console.WriteLine(new string('-', 30)); switch (select) { case 1: double x, y, radius; Console.WriteLine("Task 1 ROUND"); CheckValue(out x, "Input X coordinate of center of round: "); CheckValue(out y, "Input Y coordinate of center of round: "); CheckValue(out radius, "Input radius of round: "); Console.WriteLine(new string('-', 30)); Round round = new Round(x, y, radius); round.Parametres(); break; case 2: double a, b, c; Console.WriteLine("Task 2 TRIANGLE"); CheckValue(out a, "Input value of first side of triangle: "); CheckValue(out b, "Input value of second side of triangle: "); CheckValue(out c, "Input value of third side of triangle: "); Console.WriteLine(new string('-', 30)); Triangle triangle = new Triangle(a, b, c); triangle.Parametres(); break; case 3: Console.WriteLine("Task 3 USER"); User user = new User("Vladislav", "Safarov", "Andreevich", new DateTime(1996, 1, 31)); Console.WriteLine("{0} {1} {2}\n" + "Birthday : {3}\n" + "Age : {4}", user.LastName, user.FirstName, user.Patronymic, user.Birthday.ToShortDateString(), user.Age); break; case 4: Console.WriteLine("Task 4 MY STRING"); MyString myString1 = new MyString(new char[] { '1', 'r', 'v', 'a' }); MyString myString2 = new MyString(2); myString2[0] = 'g'; myString2[1] = '1'; MyString result = myString1 + myString1; Console.WriteLine(myString1 != myString2); MyString sameString = myString1; Console.WriteLine(myString1 == sameString); Console.WriteLine(myString1 >= result); MyString myString3 = new MyString(new char[] { '1', 't', 'n' }); Console.WriteLine(myString1.Equals(myString3)); myString1 = new MyString(new char[] { '1', '5' }); int num = (int)myString1; int t = int.Parse("15"); Console.WriteLine(num); myString1 = (MyString)num; Console.WriteLine(myString1); Console.WriteLine(myString3.ToString()); int hash = result.GetHashCode(); break; case 5: Console.WriteLine("Task 5 EMPLOYEE"); Employee Ivan = new Employee("Ivan", "Rasskazov", "Sergeevich", new DateTime(1999, 6, 20), "Engineer", 3); Console.WriteLine("{0} {1} {2}\n" + "Birthday : {3}\n" + "Age : {4}\n" + "Post : {5}\n" + "Seniority : {6}", Ivan.LastName, Ivan.FirstName, Ivan.Patronymic, Ivan.Birthday.ToShortDateString(), Ivan.Age, Ivan.Post, Ivan.Seniority); break; case 6: double xRing, yRing, outerRadius, innerRadius; Console.WriteLine("Task 6 RING"); CheckValue(out xRing, "Input X coordinate of center of ring: "); CheckValue(out yRing, "Input Y coordinate of center of ring: "); CheckValue(out outerRadius, "Input outer radius of ring: "); CheckValue(out innerRadius, "Input inner radius of ring: "); Console.WriteLine(new string('-', 30)); Ring ring = new Ring(xRing, yRing, outerRadius, innerRadius); ring.Parametres(); break; case 7: List<Figure> figures = new List<Figure>(); Console.WriteLine("Task 7 VECTOR GRAPHICS EDITOR"); Console.WriteLine(" 1. Line\n" + " 2. Rentangle\n" + " 3. Circle\n" + " 4. Round\n" + " 5. Ring\n" + " 6. Show all figures\n" + " 7. Exit"); do { do { Console.Write("Create a figure : "); } while (!int.TryParse(Console.ReadLine(), out select)); switch (select) { case 1: figures.Add(new Line(12, 15, 19, -8)); Console.WriteLine("Line was created."); Console.WriteLine(new string('-', 30)); break; case 2: figures.Add(new Rectangle(18, 9, 6, 18)); Console.WriteLine("Rectangle was created."); Console.WriteLine(new string('-', 30)); break; case 3: figures.Add(new Circle(19, 88, 3.88)); Console.WriteLine("Circle was created."); Console.WriteLine(new string('-', 30)); break; case 4: figures.Add(new Round(71, 91, 21)); Console.WriteLine("Round was created."); Console.WriteLine(new string('-', 30)); break; case 5: figures.Add(new Ring(18, 91, 91, 5)); Console.WriteLine("Ring was created."); Console.WriteLine(new string('-', 30)); break; case 6: if (figures.Count == 0) { Console.WriteLine("Nothing has been created yet."); Console.WriteLine(new string('-', 30)); } else { Console.WriteLine(new string('-', 30)); foreach (var item in figures) { item.Parametres(); Console.WriteLine(new string('-', 30)); } } break; case 7: break; default: throw new ArgumentException("Exception: Figure with this number doesn\'t exist"); } } while (select != 7); break; case 8: Console.WriteLine("Task 8 GAME"); Console.WriteLine("Check code"); Console.WriteLine(new string('-', 30)); break; case 0: break; default: throw new ArgumentException("Exception: Task with this number doesn\'t exist"); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { Console.WriteLine("Press any button to continue."); Console.ReadKey(); Console.Clear(); } } while (select != 0); } static void ShowMenu() { Console.WriteLine("Task 02 OOP BASICS"); Console.WriteLine(" 1. ROUND \n" + " 2. TRIANGLE \n" + " 3. USER \n" + " 4. MY STRING \n" + " 5. EMPLOYEE \n" + " 6. RING \n" + " 7. VECTOR GRAPHICS EDITOR \n" + " 8. GAME \n" + " 0. Exit \n" + new string('-', 30)); } // выводит "шапку" программы static void CheckValue(out double n, string str) { do { Console.Write(str); } while (!double.TryParse(Console.ReadLine(), out n)); } // бесконечный цикл, пока не введем значение типа double } }
using System; using MonoTouch.UIKit; namespace iPadPos { public class BaseViewController : UIViewController { public BaseViewController () { } } }
using System; using Inventor; using Autodesk.DesignScript.Runtime; using InventorServices.Persistence; namespace InventorLibrary.API { [IsVisibleInDynamoLibrary(false)] public class InvApplication { #region Internal properties internal Inventor.Application InternalApplication { get; set; } //internal Inv_AppPerformanceMonitor Internal_AppPerformanceMonitor //{ // get { return Inv_AppPerformanceMonitor.ByInv_AppPerformanceMonitor(ApplicationInstance._AppPerformanceMonitor); } //} internal bool Internal_CanReplayTranscript { get { return ApplicationInstance._CanReplayTranscript; } } //internal InvDebugInstrumentation Internal_DebugInstrumentation //{ // get { return InvDebugInstrumentation.ByInvDebugInstrumentation(ApplicationInstance._DebugInstrumentation); } //} internal string Internal_TranscriptFileName { get { return ApplicationInstance._TranscriptFileName; } } //internal InvColorScheme InternalActiveColorScheme //{ // get { return InvColorScheme.ByInvColorScheme(ApplicationInstance.ActiveColorScheme); } //} //this is what is being generated '_Document' rather than 'Document' //internal Inv_Document InternalActiveDocument //{ // get { return Inv_Document.ByInv_Document(ApplicationInstance.ActiveDocument); } //} internal InvDocument InternalActiveDocument { get { return InvDocument.ByInvDocument(ApplicationInstance.ActiveDocument); } } internal InvDocumentTypeEnum InternalActiveDocumentType { get { return ApplicationInstance.ActiveDocumentType.As<InvDocumentTypeEnum>(); } } //internal Inv_Document InternalActiveEditDocument //{ // get { return Inv_Document.ByInv_Document(ApplicationInstance.ActiveEditDocument); } //} //this is what is being generated '_Document' rather than 'Document' internal InvDocument InternalActiveEditDocument { get { return InvDocument.ByInvDocument(ApplicationInstance.ActiveEditDocument); } } internal Object InternalActiveEditObject { get { return ApplicationInstance.ActiveEditObject; } } //internal InvEnvironment InternalActiveEnvironment //{ // get { return InvEnvironment.ByInvEnvironment(ApplicationInstance.ActiveEnvironment); } //} //internal InvView InternalActiveView //{ // get { return InvView.ByInvView(ApplicationInstance.ActiveView); } //} internal string InternalAllUsersAppDataPath { get { return ApplicationInstance.AllUsersAppDataPath; } } //internal InvApplicationAddIns InternalApplicationAddIns //{ // get { return InvApplicationAddIns.ByInvApplicationAddIns(ApplicationInstance.ApplicationAddIns); } //} //internal InvApplicationEvents InternalApplicationEvents //{ // get { return InvApplicationEvents.ByInvApplicationEvents(ApplicationInstance.ApplicationEvents); } //} //internal InvAssemblyEvents InternalAssemblyEvents //{ // get { return InvAssemblyEvents.ByInvAssemblyEvents(ApplicationInstance.AssemblyEvents); } //} //internal InvAssemblyOptions InternalAssemblyOptions //{ // get { return InvAssemblyOptions.ByInvAssemblyOptions(ApplicationInstance.AssemblyOptions); } //} //internal InvAssetLibraries InternalAssetLibraries //{ // get { return InvAssetLibraries.ByInvAssetLibraries(ApplicationInstance.AssetLibraries); } //} //internal InvCameraEvents InternalCameraEvents //{ // get { return InvCameraEvents.ByInvCameraEvents(ApplicationInstance.CameraEvents); } //} //internal InvChangeManager InternalChangeManager //{ // get { return InvChangeManager.ByInvChangeManager(ApplicationInstance.ChangeManager); } //} //internal InvColorSchemes InternalColorSchemes //{ // get { return InvColorSchemes.ByInvColorSchemes(ApplicationInstance.ColorSchemes); } //} //internal InvCommandManager InternalCommandManager //{ // get { return InvCommandManager.ByInvCommandManager(ApplicationInstance.CommandManager); } //} //internal InvContentCenter InternalContentCenter //{ // get { return InvContentCenter.ByInvContentCenter(ApplicationInstance.ContentCenter); } //} //internal InvContentCenterOptions InternalContentCenterOptions //{ // get { return InvContentCenterOptions.ByInvContentCenterOptions(ApplicationInstance.ContentCenterOptions); } //} internal string InternalCurrentUserAppDataPath { get { return ApplicationInstance.CurrentUserAppDataPath; } } //internal InvDesignProjectManager InternalDesignProjectManager //{ // get { return InvDesignProjectManager.ByInvDesignProjectManager(ApplicationInstance.DesignProjectManager); } //} //internal InvDisplayOptions InternalDisplayOptions //{ // get { return InvDisplayOptions.ByInvDisplayOptions(ApplicationInstance.DisplayOptions); } //} internal InvDocuments InternalDocuments { get { return InvDocuments.ByInvDocuments(ApplicationInstance.Documents); } } //internal InvDrawingOptions InternalDrawingOptions //{ // get { return InvDrawingOptions.ByInvDrawingOptions(ApplicationInstance.DrawingOptions); } //} //internal InvEnvironmentBaseCollection InternalEnvironmentBaseCollection //{ // get { return InvEnvironmentBaseCollection.ByInvEnvironmentBaseCollection(ApplicationInstance.EnvironmentBaseCollection); } //} //internal InvEnvironments InternalEnvironments //{ // get { return InvEnvironments.ByInvEnvironments(ApplicationInstance.Environments); } //} //internal InvErrorManager InternalErrorManager //{ // get { return InvErrorManager.ByInvErrorManager(ApplicationInstance.ErrorManager); } //} internal InvAssetsEnumerator InternalFavoriteAssets { get { return InvAssetsEnumerator.ByInvAssetsEnumerator(ApplicationInstance.FavoriteAssets); } } //internal InvFileAccessEvents InternalFileAccessEvents //{ // get { return InvFileAccessEvents.ByInvFileAccessEvents(ApplicationInstance.FileAccessEvents); } //} //internal InvFileLocations InternalFileLocations //{ // get { return InvFileLocations.ByInvFileLocations(ApplicationInstance.FileLocations); } //} //internal InvFileManager InternalFileManager //{ // get { return InvFileManager.ByInvFileManager(ApplicationInstance.FileManager); } //} //internal InvFileOptions InternalFileOptions //{ // get { return InvFileOptions.ByInvFileOptions(ApplicationInstance.FileOptions); } //} //internal InvFileUIEvents InternalFileUIEvents //{ // get { return InvFileUIEvents.ByInvFileUIEvents(ApplicationInstance.FileUIEvents); } //} //internal InvGeneralOptions InternalGeneralOptions //{ // get { return InvGeneralOptions.ByInvGeneralOptions(ApplicationInstance.GeneralOptions); } //} //internal InvHardwareOptions InternalHardwareOptions //{ // get { return InvHardwareOptions.ByInvHardwareOptions(ApplicationInstance.HardwareOptions); } //} //internal InvHelpManager InternalHelpManager //{ // get { return InvHelpManager.ByInvHelpManager(ApplicationInstance.HelpManager); } //} //internal InviFeatureOptions InternaliFeatureOptions //{ // get { return InviFeatureOptions.ByInviFeatureOptions(ApplicationInstance.iFeatureOptions); } //} internal string InternalInstallPath { get { return ApplicationInstance.InstallPath; } } internal bool InternalIsCIPEnabled { get { return ApplicationInstance.IsCIPEnabled; } } internal string InternalLanguageCode { get { return ApplicationInstance.LanguageCode; } } internal string InternalLanguageName { get { return ApplicationInstance.LanguageName; } } //internal InvLanguageTools InternalLanguageTools //{ // get { return InvLanguageTools.ByInvLanguageTools(ApplicationInstance.LanguageTools); } //} internal int InternalLocale { get { return ApplicationInstance.Locale; } } internal int InternalMainFrameHWND { get { return ApplicationInstance.MainFrameHWND; } } //internal InvMeasureTools InternalMeasureTools //{ // get { return InvMeasureTools.ByInvMeasureTools(ApplicationInstance.MeasureTools); } //} //internal InvModelingEvents InternalModelingEvents //{ // get { return InvModelingEvents.ByInvModelingEvents(ApplicationInstance.ModelingEvents); } //} //internal InvNotebookOptions InternalNotebookOptions //{ // get { return InvNotebookOptions.ByInvNotebookOptions(ApplicationInstance.NotebookOptions); } //} //internal InvPartOptions InternalPartOptions //{ // get { return InvPartOptions.ByInvPartOptions(ApplicationInstance.PartOptions); } //} //internal InvObjectsEnumeratorByVariant InternalPreferences //{ // get { return InvObjectsEnumeratorByVariant.ByInvObjectsEnumeratorByVariant(ApplicationInstance.Preferences); } //} //internal InvPresentationOptions InternalPresentationOptions //{ // get { return InvPresentationOptions.ByInvPresentationOptions(ApplicationInstance.PresentationOptions); } //} internal bool InternalReady { get { return ApplicationInstance.Ready; } } //internal InvReferenceKeyEvents InternalReferenceKeyEvents //{ // get { return InvReferenceKeyEvents.ByInvReferenceKeyEvents(ApplicationInstance.ReferenceKeyEvents); } //} //internal InvRepresentationEvents InternalRepresentationEvents //{ // get { return InvRepresentationEvents.ByInvRepresentationEvents(ApplicationInstance.RepresentationEvents); } //} //internal InvSaveOptions InternalSaveOptions //{ // get { return InvSaveOptions.ByInvSaveOptions(ApplicationInstance.SaveOptions); } //} //internal InvSketch3DOptions InternalSketch3DOptions //{ // get { return InvSketch3DOptions.ByInvSketch3DOptions(ApplicationInstance.Sketch3DOptions); } //} //internal InvSketchEvents InternalSketchEvents //{ // get { return InvSketchEvents.ByInvSketchEvents(ApplicationInstance.SketchEvents); } //} //internal InvSketchOptions InternalSketchOptions //{ // get { return InvSketchOptions.ByInvSketchOptions(ApplicationInstance.SketchOptions); } //} internal InvSoftwareVersion InternalSoftwareVersion { get { return InvSoftwareVersion.ByInvSoftwareVersion(ApplicationInstance.SoftwareVersion); } } //internal InvStyleEvents InternalStyleEvents //{ // get { return InvStyleEvents.ByInvStyleEvents(ApplicationInstance.StyleEvents); } //} //internal InvStylesManager InternalStylesManager //{ // get { return InvStylesManager.ByInvStylesManager(ApplicationInstance.StylesManager); } //} //internal InvStatusEnum InternalSubscriptionStatus //{ // get { return InvStatusEnum.ByInvStatusEnum(ApplicationInstance.SubscriptionStatus); } //} //internal InvTestManager InternalTestManager //{ // get { return InvTestManager.ByInvTestManager(ApplicationInstance.TestManager); } //} //internal InvTransactionManager InternalTransactionManager //{ // get { return InvTransactionManager.ByInvTransactionManager(ApplicationInstance.TransactionManager); } //} //internal InvTransientBRep InternalTransientBRep //{ // get { return InvTransientBRep.ByInvTransientBRep(ApplicationInstance.TransientBRep); } //} //internal InvTransientGeometry InternalTransientGeometry //{ // get { return InvTransientGeometry.ByInvTransientGeometry(ApplicationInstance.TransientGeometry); } //} //internal InvTransientObjects InternalTransientObjects //{ // get { return InvTransientObjects.ByInvTransientObjects(ApplicationInstance.TransientObjects); } //} internal InvObjectTypeEnum InternalType { get { return ApplicationInstance.Type.As<InvObjectTypeEnum>(); } } internal InvUnitsOfMeasure InternalUnitsOfMeasure { get { return InvUnitsOfMeasure.ByInvUnitsOfMeasure(ApplicationInstance.UnitsOfMeasure); } } //internal InvUserInterfaceManager InternalUserInterfaceManager //{ // get { return InvUserInterfaceManager.ByInvUserInterfaceManager(ApplicationInstance.UserInterfaceManager); } //} //internal InvInventorVBAProjects InternalVBAProjects //{ // get { return InvInventorVBAProjects.ByInvInventorVBAProjects(ApplicationInstance.VBAProjects); } //} internal Object InternalVBE { get { return ApplicationInstance.VBE; } } //internal InvViewsEnumerator InternalViews //{ // get { return InvViewsEnumerator.ByInvViewsEnumerator(ApplicationInstance.Views); } //} internal bool Internal_ForceMigrationOnOpen { get; set; } internal bool Internal_HarvestStylesOnOpen { get; set; } internal bool Internal_PurgeStylesOnOpen { get; set; } internal bool Internal_SuppressFileDirtyEvents { get; set; } internal Object Internal_TestIO { get; set; } internal bool Internal_TranscriptAPIChanges { get; set; } internal AssetLibrary InternalActiveAppearanceLibrary { get; set; } internal AssetLibrary InternalActiveMaterialLibrary { get; set; } internal bool InternalCameraRollMode3Dx { get; set; } internal string InternalCaption { get; set; } internal bool InternalFlythroughMode3Dx { get; set; } internal int InternalHeight { get; set; } internal int InternalLeft { get; set; } internal MaterialDisplayUnitsEnum InternalMaterialDisplayUnits { get; set; } internal bool InternalMRUDisplay { get; set; } internal bool InternalMRUEnabled { get; set; } internal bool InternalOpenDocumentsDisplay { get; set; } internal bool InternalScreenUpdating { get; set; } internal bool InternalSilentOperation { get; set; } internal string InternalStatusBarText { get; set; } internal bool InternalSupportsFileManagement { get; set; } internal int InternalTop { get; set; } internal string InternalUserName { get; set; } internal bool InternalVisible { get; set; } internal int InternalWidth { get; set; } internal WindowsSizeEnum InternalWindowState { get; set; } #endregion #region Private constructors private InvApplication(InvApplication invApplication) { InternalApplication = invApplication.InternalApplication; //get a reference to the active application obtained in addin startup Inventor.Application invApp = InternalApplication; AssemblyDocument assDoc = (AssemblyDocument)invApp.ActiveDocument; Inventor.Point transPoint = invApp.TransientGeometry.CreatePoint(0,0,0); WorkPoint wp = assDoc.ComponentDefinition.WorkPoints.AddFixed(transPoint, false); //get the active document Document activeDoc = invApp.ActiveDocument; //cast to the right type AssemblyDocument assemblyDocument = (AssemblyDocument)activeDoc; //get the ComponentDefinition AssemblyComponentDefinition assCompDef = (AssemblyComponentDefinition)assemblyDocument.ComponentDefinition; //get the WorkPoints collection WorkPoints workPoints= assCompDef.WorkPoints; //create an Inventor.Point transient geometry object Inventor.Point transientPoint = invApp.TransientGeometry.CreatePoint(0, 0, 0); //add WorkPoint WorkPoint workPoint = workPoints.AddFixed(transientPoint, false); } private InvApplication(Inventor.Application invApplication) { InternalApplication = invApplication; } #endregion #region Private methods private void InternalConstructInternalNameAndRevisionId(string internalNameToken, string revisionIdToken, out string internalName, out string revisionId) { ApplicationInstance.ConstructInternalNameAndRevisionId( internalNameToken, revisionIdToken, out internalName, out revisionId); } private void InternalCreateFileDialog(out FileDialog dialog) { ApplicationInstance.CreateFileDialog(out dialog); } private void InternalCreateInternalName(string name, string number, string custom, out string internalName) { ApplicationInstance.CreateInternalName( name, number, custom, out internalName); } private ProgressBar InternalCreateProgressBar(bool displayInStatusBar, int numberOfSteps, string title, bool allowCancel, int hWND) { return ApplicationInstance.CreateProgressBar( displayInStatusBar, numberOfSteps, title, allowCancel, hWND); } private void InternalGetAppFrameExtents(out int top, out int left, out int height, out int width) { ApplicationInstance.GetAppFrameExtents(out top, out left, out height, out width); } private Object InternalGetInterfaceObject(string progIDorCLSID) { return ApplicationInstance.GetInterfaceObject( progIDorCLSID); } private Object InternalGetInterfaceObject32(string progIDorCLSID) { return ApplicationInstance.GetInterfaceObject32( progIDorCLSID); } private string InternalGetTemplateFile(DocumentTypeEnum documentType, SystemOfMeasureEnum systemOfMeasure, DraftingStandardEnum draftingStandard, Object documentSubType) { return ApplicationInstance.GetTemplateFile( documentType, systemOfMeasure, draftingStandard, documentSubType); } private string InternalLicenseChallenge() { return ApplicationInstance.LicenseChallenge(); } private void InternalLicenseResponse(string response) { ApplicationInstance.LicenseResponse( response); } private bool InternalLogin() { return ApplicationInstance.Login(); } private void InternalMove(int top, int left, int height, int width) { ApplicationInstance.Move( top, left, height, width); } private void InternalQuit() { ApplicationInstance.Quit(); } private void InternalReserveLicense(string clientId) { ApplicationInstance.ReserveLicense( clientId); } private void InternalUnreserveLicense(string clientId) { ApplicationInstance.UnreserveLicense( clientId); } private void InternalWriteCIPWaypoint(string waypointData) { ApplicationInstance.WriteCIPWaypoint( waypointData); } #endregion #region Public properties public Inventor.Application ApplicationInstance { get { return InternalApplication; } set { InternalApplication = value; } } //public Inv_AppPerformanceMonitor _AppPerformanceMonitor //{ // get { return Internal_AppPerformanceMonitor; } //} public bool _CanReplayTranscript { get { return Internal_CanReplayTranscript; } } //public InvDebugInstrumentation _DebugInstrumentation //{ // get { return Internal_DebugInstrumentation; } //} public string _TranscriptFileName { get { return Internal_TranscriptFileName; } } //public InvColorScheme ActiveColorScheme //{ // get { return InternalActiveColorScheme; } //} ////public Inv_Document ActiveDocument ////{ //// get { return InternalActiveDocument; } ////} public InvDocument ActiveDocument { get { return InternalActiveDocument; } } public InvDocumentTypeEnum ActiveDocumentType { get { return InternalActiveDocumentType; } } ////public Inv_Document ActiveEditDocument ////{ //// get { return InternalActiveEditDocument; } ////} public InvDocument ActiveEditDocument { get { return InternalActiveEditDocument; } } public Object ActiveEditObject { get { return InternalActiveEditObject; } } //public InvEnvironment ActiveEnvironment //{ // get { return InternalActiveEnvironment; } //} //public InvView ActiveView //{ // get { return InternalActiveView; } //} public string AllUsersAppDataPath { get { return InternalAllUsersAppDataPath; } } //public InvApplicationAddIns ApplicationAddIns //{ // get { return InternalApplicationAddIns; } //} //public InvApplicationEvents ApplicationEvents //{ // get { return InternalApplicationEvents; } //} //public InvAssemblyEvents AssemblyEvents //{ // get { return InternalAssemblyEvents; } //} //public InvAssemblyOptions AssemblyOptions //{ // get { return InternalAssemblyOptions; } //} //public InvAssetLibraries AssetLibraries //{ // get { return InternalAssetLibraries; } //} //public InvCameraEvents CameraEvents //{ // get { return InternalCameraEvents; } //} //public InvChangeManager ChangeManager //{ // get { return InternalChangeManager; } //} //public InvColorSchemes ColorSchemes //{ // get { return InternalColorSchemes; } //} //public InvCommandManager CommandManager //{ // get { return InternalCommandManager; } //} //public InvContentCenter ContentCenter //{ // get { return InternalContentCenter; } //} //public InvContentCenterOptions ContentCenterOptions //{ // get { return InternalContentCenterOptions; } //} public string CurrentUserAppDataPath { get { return InternalCurrentUserAppDataPath; } } //public InvDesignProjectManager DesignProjectManager //{ // get { return InternalDesignProjectManager; } //} //public InvDisplayOptions DisplayOptions //{ // get { return InternalDisplayOptions; } //} public InvDocuments Documents { get { return InternalDocuments; } } //public InvDrawingOptions DrawingOptions //{ // get { return InternalDrawingOptions; } //} //public InvEnvironmentBaseCollection EnvironmentBaseCollection //{ // get { return InternalEnvironmentBaseCollection; } //} //public InvEnvironments Environments //{ // get { return InternalEnvironments; } //} //public InvErrorManager ErrorManager //{ // get { return InternalErrorManager; } //} public InvAssetsEnumerator FavoriteAssets { get { return InternalFavoriteAssets; } } //public InvFileAccessEvents FileAccessEvents //{ // get { return InternalFileAccessEvents; } //} //public InvFileLocations FileLocations //{ // get { return InternalFileLocations; } //} //public InvFileManager FileManager //{ // get { return InternalFileManager; } //} //public InvFileOptions FileOptions //{ // get { return InternalFileOptions; } //} //public InvFileUIEvents FileUIEvents //{ // get { return InternalFileUIEvents; } //} //public InvGeneralOptions GeneralOptions //{ // get { return InternalGeneralOptions; } //} //public InvHardwareOptions HardwareOptions //{ // get { return InternalHardwareOptions; } //} //public InvHelpManager HelpManager //{ // get { return InternalHelpManager; } //} //public InviFeatureOptions iFeatureOptions //{ // get { return InternaliFeatureOptions; } //} public string InstallPath { get { return InternalInstallPath; } } public bool IsCIPEnabled { get { return InternalIsCIPEnabled; } } public string LanguageCode { get { return InternalLanguageCode; } } public string LanguageName { get { return InternalLanguageName; } } //public InvLanguageTools LanguageTools //{ // get { return InternalLanguageTools; } //} public int Locale { get { return InternalLocale; } } public int MainFrameHWND { get { return InternalMainFrameHWND; } } //public InvMeasureTools MeasureTools //{ // get { return InternalMeasureTools; } //} //public InvModelingEvents ModelingEvents //{ // get { return InternalModelingEvents; } //} //public InvNotebookOptions NotebookOptions //{ // get { return InternalNotebookOptions; } //} //public InvPartOptions PartOptions //{ // get { return InternalPartOptions; } //} //public InvObjectsEnumeratorByVariant Preferences //{ // get { return InternalPreferences; } //} //public InvPresentationOptions PresentationOptions //{ // get { return InternalPresentationOptions; } //} public bool Ready { get { return InternalReady; } } //public InvReferenceKeyEvents ReferenceKeyEvents //{ // get { return InternalReferenceKeyEvents; } //} //public InvRepresentationEvents RepresentationEvents //{ // get { return InternalRepresentationEvents; } //} //public InvSaveOptions SaveOptions //{ // get { return InternalSaveOptions; } //} //public InvSketch3DOptions Sketch3DOptions //{ // get { return InternalSketch3DOptions; } //} //public InvSketchEvents SketchEvents //{ // get { return InternalSketchEvents; } //} //public InvSketchOptions SketchOptions //{ // get { return InternalSketchOptions; } //} public InvSoftwareVersion SoftwareVersion { get { return InternalSoftwareVersion; } } //public InvStyleEvents StyleEvents //{ // get { return InternalStyleEvents; } //} //public InvStylesManager StylesManager //{ // get { return InternalStylesManager; } //} //public InvStatusEnum SubscriptionStatus //{ // get { return InternalSubscriptionStatus; } //} //public InvTestManager TestManager //{ // get { return InternalTestManager; } //} //public InvTransactionManager TransactionManager //{ // get { return InternalTransactionManager; } //} //public InvTransientBRep TransientBRep //{ // get { return InternalTransientBRep; } //} //public InvTransientGeometry TransientGeometry //{ // get { return InternalTransientGeometry; } //} //public InvTransientObjects TransientObjects //{ // get { return InternalTransientObjects; } //} public InvObjectTypeEnum Type { get { return InternalType; } } public InvUnitsOfMeasure UnitsOfMeasure { get { return InternalUnitsOfMeasure; } } //public InvUserInterfaceManager UserInterfaceManager //{ // get { return InternalUserInterfaceManager; } //} //public InvInventorVBAProjects VBAProjects //{ // get { return InternalVBAProjects; } //} public Object VBE { get { return InternalVBE; } } //public InvViewsEnumerator Views //{ // get { return InternalViews; } //} public bool _ForceMigrationOnOpen { get { return Internal_ForceMigrationOnOpen; } set { Internal_ForceMigrationOnOpen = value; } } public bool _HarvestStylesOnOpen { get { return Internal_HarvestStylesOnOpen; } set { Internal_HarvestStylesOnOpen = value; } } public bool _PurgeStylesOnOpen { get { return Internal_PurgeStylesOnOpen; } set { Internal_PurgeStylesOnOpen = value; } } public bool _SuppressFileDirtyEvents { get { return Internal_SuppressFileDirtyEvents; } set { Internal_SuppressFileDirtyEvents = value; } } public Object _TestIO { get { return Internal_TestIO; } set { Internal_TestIO = value; } } public bool _TranscriptAPIChanges { get { return Internal_TranscriptAPIChanges; } set { Internal_TranscriptAPIChanges = value; } } //public InvAssetLibrary ActiveAppearanceLibrary //{ // get { return InternalActiveAppearanceLibrary; } // set { InternalActiveAppearanceLibrary = value; } //} //public InvAssetLibrary ActiveMaterialLibrary //{ // get { return InternalActiveMaterialLibrary; } // set { InternalActiveMaterialLibrary = value; } //} public bool CameraRollMode3Dx { get { return InternalCameraRollMode3Dx; } set { InternalCameraRollMode3Dx = value; } } public string Caption { get { return InternalCaption; } set { InternalCaption = value; } } public bool FlythroughMode3Dx { get { return InternalFlythroughMode3Dx; } set { InternalFlythroughMode3Dx = value; } } public int Height { get { return InternalHeight; } set { InternalHeight = value; } } public int Left { get { return InternalLeft; } set { InternalLeft = value; } } //public InvMaterialDisplayUnitsEnum MaterialDisplayUnits //{ // get { return InternalMaterialDisplayUnits; } // set { InternalMaterialDisplayUnits = value; } //} public bool MRUDisplay { get { return InternalMRUDisplay; } set { InternalMRUDisplay = value; } } public bool MRUEnabled { get { return InternalMRUEnabled; } set { InternalMRUEnabled = value; } } public bool OpenDocumentsDisplay { get { return InternalOpenDocumentsDisplay; } set { InternalOpenDocumentsDisplay = value; } } public bool ScreenUpdating { get { return InternalScreenUpdating; } set { InternalScreenUpdating = value; } } public bool SilentOperation { get { return InternalSilentOperation; } set { InternalSilentOperation = value; } } public string StatusBarText { get { return InternalStatusBarText; } set { InternalStatusBarText = value; } } public bool SupportsFileManagement { get { return InternalSupportsFileManagement; } set { InternalSupportsFileManagement = value; } } public int Top { get { return InternalTop; } set { InternalTop = value; } } public string UserName { get { return InternalUserName; } set { InternalUserName = value; } } public bool Visible { get { return InternalVisible; } set { InternalVisible = value; } } public int Width { get { return InternalWidth; } set { InternalWidth = value; } } //public InvWindowsSizeEnum WindowState //{ // get { return InternalWindowState; } // set { InternalWindowState = value; } //} #endregion #region Public static constructors //public static InvApplication ByInvApplication(InvApplication invApplication) //{ // return new InvApplication(invApplication); //} //public static InvApplication ByInvApplication(Inventor.Application invApplication) //{ // return new InvApplication(invApplication); //} public static InvApplication GetInvApplication() { return new InvApplication(PersistenceManager.InventorApplication); } #endregion #region Public methods public void ConstructInternalNameAndRevisionId(string internalNameToken, string revisionIdToken, out string internalName, out string revisionId) { InternalConstructInternalNameAndRevisionId( internalNameToken, revisionIdToken, out internalName, out revisionId); } public void CreateFileDialog(out FileDialog dialog) { InternalCreateFileDialog(out dialog); } public void CreateInternalName(string name, string number, string custom, out string internalName) { InternalCreateInternalName( name, number, custom, out internalName); } ////public InvProgressBar CreateProgressBar(bool displayInStatusBar, int numberOfSteps, string title, bool allowCancel, int hWND) ////{ //// return InternalCreateProgressBar( displayInStatusBar, numberOfSteps, title, allowCancel, hWND); ////} public void GetAppFrameExtents(out int top, out int left, out int height, out int width) { InternalGetAppFrameExtents(out top, out left, out height, out width); } public Object GetInterfaceObject(string progIDorCLSID) { return InternalGetInterfaceObject( progIDorCLSID); } public Object GetInterfaceObject32(string progIDorCLSID) { return InternalGetInterfaceObject32( progIDorCLSID); } public string GetTemplateFile(DocumentTypeEnum documentType, SystemOfMeasureEnum systemOfMeasure, DraftingStandardEnum draftingStandard, Object documentSubType) { return InternalGetTemplateFile( documentType, systemOfMeasure, draftingStandard, documentSubType); } public string LicenseChallenge() { return InternalLicenseChallenge(); } public void LicenseResponse(string response) { InternalLicenseResponse( response); } public bool Login() { return InternalLogin(); } public void Move(int top, int left, int height, int width) { InternalMove( top, left, height, width); } public void Quit() { InternalQuit(); } public void ReserveLicense(string clientId) { InternalReserveLicense( clientId); } public void UnreserveLicense(string clientId) { InternalUnreserveLicense( clientId); } public void WriteCIPWaypoint(string waypointData) { InternalWriteCIPWaypoint( waypointData); } #endregion } }
using System.Collections.Generic; using System.Text.Json.Serialization; namespace SmartStocksImporter.Models { public class Wallet { [JsonPropertyName("name")] public string name { get; set; } [JsonPropertyName("children")] public List<Children> children { get; set; } } }
using System; namespace Brawl_Net { class Program { static void Main() { Random r = new Random(); NetworkManager NM = new NetworkManager(); GameManager GM = new GameManager(); bool programLoop = true; while (programLoop) { Setup(r, NM, GM); Lobby(r, NM, GM); Game (r, NM, GM); } } //SETUP static void Setup(Random r, NetworkManager NM, GameManager GM) { Console.Clear(); Console.Title = "SetUp"; Console.WriteLine("Host: [Q] / Host IP ([Any]) / Offline [W] / Exit: [E]"); switch (Console.ReadKey().KeyChar.ToString().ToUpper()) { case "Q": GM.players.Add(new Player(GM.hostIP)); break; case "E": System.Environment.Exit(0); break; case "W": GM.lan = false; break; default: GM.host = false; Console.Write("Host IP: "); GM.hostIP = Console.ReadLine(); NM.Send(GM.hostIP, NM.getIP()); break; } } //LOBBY static void Lobby(Random r, NetworkManager NM, GameManager GM) { Console.Title = "Lobby"; if (GM.host) { Console.Title += " Host"; } else { Console.Title += "Client"; } if (!GM.lan) { Console.Title += " Offline"; } else { Console.Title += "Online"; } bool lobby = true; while (lobby && GM.lan) { Console.Clear(); Console.WriteLine("Players:"); if (GM.host) { string playerList = ""; foreach (Player p in GM.players) { foreach (Player s in GM.players) { playerList += s.ip + " \n"; } if (p.ip != GM.hostIP) { NM.Send(p.ip, playerList); } } Console.WriteLine(playerList); GM.players.Add(new Player(NM.Recive())); Console.WriteLine("Wait for players. Yes [Any] / No [Q]"); switch (Console.ReadKey().KeyChar.ToString().ToUpper()) { case "Q": foreach (Player p in GM.players) { if (p.ip != GM.hostIP) { NM.Send(p.ip, "EXITLOBBY"); } } lobby = false; break; case "Y": default: break; } } else { switch (NM.Recive()) { case "EXITLOBBY": lobby = false; break; default: Console.WriteLine(NM.Recive()); break; } } } while(lobby && !GM.lan) { Console.Clear(); Console.Write("Players: " + GM.players.Count); Console.WriteLine( "\n" + "Add Player [+], Remove Player [-], Game [Any]" + "\n"); switch (Console.ReadKey().KeyChar.ToString().ToUpper()) { case "+": GM.players.Add(new Player("127.0.0.1")); break; case "-": GM.players.Remove(GM.players[GM.players.Count - 1]); break; default: lobby = false; break; } } } //GAME static void Game(Random r, NetworkManager NM, GameManager GM) { Console.Title = "Game "; if (GM.host) { Console.Title += "Host"; GM.NextTurn(NM, r.Next(0, GM.players.Count - 1)); } else { Console.Title += "Client"; } string recive = ""; bool gameLoop = true; while (gameLoop) { if (GM.lan) { switch (NM.Recive()) { case "PLAY": GM.Play(NM); break; case "NEXTTURN": GM.NextTurn(NM); break; case "GETCHARACTER": NM.Send(GM.players[GM.playerTurn].ip, GM.players[GM.playerTurn].character.WriteStats()); break; default: Console.WriteLine(recive); break; } } } } } }
using UnityEngine; using UnityEngine.SceneManagement; public static class MenuManager { public static void GoToMenu(MenuName name) { switch (name) { case MenuName.MainMenu: SceneManager.LoadScene("Scenes/MainMenu"); break; case MenuName.PauseMenu: Object.Instantiate(Resources.Load("PauseMenu")); break; case MenuName.HelpMenu: Object.Instantiate(Resources.Load("HelpMenu")); break; case MenuName.GameOverMenu: Object.Instantiate(Resources.Load("GameOverMenu")); break; } } }
using System.Data; using System.Web.Mvc; using com.Sconit.Web.Util; using Telerik.Web.Mvc; using com.Sconit.Web.Models.SearchModels.SI; using System.Data.SqlClient; using System; using System.Linq; using com.Sconit.Web.Models; using System.Collections.Generic; using com.Sconit.Entity.SAP.TRANS; using com.Sconit.Service; using System.ComponentModel; using System.Reflection; using com.Sconit.Web.Models.SearchModels.SI.SAP; namespace com.Sconit.Web.Controllers.SI.SAP { public class SAPTransController : WebAppBaseController { // // GET: /SequenceOrder/ private static string selectCountStatement = "select count(*) from InvTrans as t"; /// <summary> /// /// </summary> private static string selectStatement = "select t from InvTrans as t"; private static string InvLocSelectStatement = "select l from InvLoc as l"; public SAPTransController() { } //public IQueryMgr siMgr { get { return GetService<IQueryMgr>("siMgr"); } } [SconitAuthorize(Permissions = "Url_SI_SAP_InvTrans_View")] public ActionResult SAPIndex() { return View(); } [GridAction] [SconitAuthorize(Permissions = "Url_SI_SAP_InvTrans_View")] public ActionResult List(GridCommand command, InvTransSearchModel searchModel) { TempData["InvTransSearchModel"] = searchModel; ViewBag.PageSize = 20; return View(); } [SconitAuthorize(Permissions = "Url_SI_SAP_Trans_View")] public ActionResult Index(SearchModel searchModel) { string sql = @"select top " + MaxRowSize + @" e.BatchNo, d.*, a.OrderNo,a.Item,a.Uom,a.IsCS,a.PlanBill,a.ActBill,a.QualityType, a.Qty,b.Type,b.Status,a.TransType,b.ExtOrderNo, a.PartyFrom,a.LocFrom,a.PartyTo,b.LocTo,e.* from Sconit5_Test.dbo.VIEW_LocTrans a left join Sconit5_Test.dbo.ORD_OrderMstr b on a.OrderNo = b.OrderNo left join Sconit5_SI_Test.dbo.SI_SAP_InvLoc c on c.SourceId = a.Id left join Sconit5_SI_Test.dbo.SI_SAP_InvTrans e on (e.FRBNR = c.FRBNR and e.SGTXT = c.SGTXT) left join Sconit5_SI_Test.dbo.SI_SAP_TransCallBack d on (d.FRBNR = c.FRBNR and d.SGTXT = c.SGTXT) where d.Id>0 and c.SourceType = 0 and e.Status = @p0 and e.CreateDate > @p1 and e.CreateDate < @p2 "; TempData["SearchModel"] = searchModel; SqlParameter[] sqlParam = new SqlParameter[4]; sqlParam[0] = new SqlParameter("@p0", searchModel.Status.HasValue ? searchModel.Status.Value : 2); if (searchModel.StartDate.HasValue) { sqlParam[1] = new SqlParameter("@p1", searchModel.StartDate); } else { sqlParam[1] = new SqlParameter("@p1", DateTime.Now.AddDays(-1)); } if (searchModel.EndDate.HasValue) { sqlParam[2] = new SqlParameter("@p2", searchModel.EndDate); } else { sqlParam[2] = new SqlParameter("@p2", DateTime.Now); } if (searchModel.Id.HasValue) { sql += " and e.Id = @p3 "; sqlParam[3] = new SqlParameter("@p3", searchModel.Id); } sql += " order by d.Id desc "; DataSet entity = siMgr.GetDatasetBySql(sql, sqlParam); ViewModel model = new ViewModel(); model.Data = entity.Tables[0]; model.Columns = IListHelper.GetColumns(entity.Tables[0]); return View(model); } [GridAction(EnableCustomBinding = true)] [SconitAuthorize(Permissions = "Url_SI_SAP_InvTrans_View")] public ActionResult _AjaxList(GridCommand command, InvTransSearchModel searchModel) { SearchStatementModel searchStatementModel = PrepareSearchStatement(command, searchModel); GridModel<InvTrans> gridlist = GetAjaxPageData<InvTrans>(searchStatementModel, command); foreach (InvTrans inv in gridlist.Data) { inv.StatusName = GetEnumDescription(inv.Status); } return View(gridlist); //return PartialView(GetAjaxPageData<ReceiptMaster>(searchStatementModel, command)); } [GridAction(EnableCustomBinding = true)] [SconitAuthorize(Permissions = "Url_SI_SAP_InvTrans_View")] public ActionResult _AjaxListInvLoc(string FRBNR, string SGTXT) { string hql = InvLocSelectStatement + " where l.FRBNR = '" + FRBNR + "' and l.SGTXT='" + SGTXT + "'"; IList<InvLoc> InvLocList = siMgr.FindAll<InvLoc>(hql); return View(new GridModel<InvLoc>(InvLocList)); } [SconitAuthorize(Permissions = "Url_SI_SAP_InvTrans_View")] public ActionResult CreateInvTrans(string checkedOrders, string SGTXT) { //这里调用重新创建的方法 return View(); } public static string GetEnumDescription(object enumSubitem) { enumSubitem = (Enum)enumSubitem; string strValue = enumSubitem.ToString(); FieldInfo fieldinfo = enumSubitem.GetType().GetField(strValue); if (fieldinfo != null) { Object[] objs = fieldinfo.GetCustomAttributes(typeof(DescriptionAttribute), false); if (objs == null || objs.Length == 0) { return strValue; } else { DescriptionAttribute da = (DescriptionAttribute)objs[0]; return da.Description; } } else { return "未找到的状态"; } } private SearchStatementModel PrepareSearchStatement(GridCommand command, InvTransSearchModel searchModel) { string whereStatement = ""; IList<object> param = new List<object>(); HqlStatementHelper.AddLikeStatement("BWART", searchModel.BWART, HqlStatementHelper.LikeMatchMode.Start, "t", ref whereStatement, param); HqlStatementHelper.AddLikeStatement("EBELN", searchModel.EBELN, HqlStatementHelper.LikeMatchMode.Start, "t", ref whereStatement, param); HqlStatementHelper.AddLikeStatement("EBELP", searchModel.EBELP, HqlStatementHelper.LikeMatchMode.Start, "t", ref whereStatement, param); HqlStatementHelper.AddLikeStatement("FRBNR", searchModel.FRBNR, HqlStatementHelper.LikeMatchMode.Start, "t", ref whereStatement, param); HqlStatementHelper.AddEqStatement("LIFNR", searchModel.LIFNR, "t", ref whereStatement, param); HqlStatementHelper.AddEqStatement("Status", searchModel.Status, "t", ref whereStatement, param); HqlStatementHelper.AddLikeStatement("SGTXT", searchModel.SGTXT, HqlStatementHelper.LikeMatchMode.Start, "t", ref whereStatement, param); HqlStatementHelper.AddLikeStatement("LGORT", searchModel.LGORT, HqlStatementHelper.LikeMatchMode.Start, "t", ref whereStatement, param); HqlStatementHelper.AddLikeStatement("MATNR", searchModel.MATNR, HqlStatementHelper.LikeMatchMode.Start, "t", ref whereStatement, param); HqlStatementHelper.AddLikeStatement("XBLNR", searchModel.XBLNR, HqlStatementHelper.LikeMatchMode.Start, "t", ref whereStatement, param); HqlStatementHelper.AddLikeStatement("RSNUM", searchModel.RSNUM, HqlStatementHelper.LikeMatchMode.Start, "t", ref whereStatement, param); HqlStatementHelper.AddLikeStatement("RSPOS", searchModel.RSPOS, HqlStatementHelper.LikeMatchMode.Start, "t", ref whereStatement, param); HqlStatementHelper.AddLikeStatement("FRBNR", searchModel.FRBNR, HqlStatementHelper.LikeMatchMode.Start, "t", ref whereStatement, param); HqlStatementHelper.AddLikeStatement("XABLN", searchModel.XABLN, HqlStatementHelper.LikeMatchMode.Start, "t", ref whereStatement, param); if (searchModel.StartTime != null & searchModel.EndTime != null) { HqlStatementHelper.AddBetweenStatement("CreateDate", searchModel.StartTime, searchModel.EndTime, "t", ref whereStatement, param); } else if (searchModel.StartTime != null & searchModel.EndTime == null) { HqlStatementHelper.AddGeStatement("CreateDate", searchModel.StartTime, "t", ref whereStatement, param); } else if (searchModel.StartTime == null & searchModel.EndTime != null) { HqlStatementHelper.AddLeStatement("CreateDate", searchModel.EndTime, "t", ref whereStatement, param); } string sortingStatement = HqlStatementHelper.GetSortingStatement(command.SortDescriptors); if (command.SortDescriptors.Count == 0) { sortingStatement = " order by t.CreateDate desc"; } SearchStatementModel searchStatementModel = new SearchStatementModel(); searchStatementModel.SelectCountStatement = selectCountStatement; searchStatementModel.SelectStatement = selectStatement; searchStatementModel.WhereStatement = whereStatement; searchStatementModel.SortingStatement = sortingStatement; searchStatementModel.Parameters = param.ToArray<object>(); return searchStatementModel; } } }
namespace PopulationFitness.Models { public enum PopulationComparison { TooLow, TooHigh, WithinRange, } }
using Cs_IssPrefeitura.Aplicacao.Interfaces; using Cs_IssPrefeitura.Dominio.Entities; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Cs_IssPrefeitura { /// <summary> /// Interaction logic for AguardeImportarBaseDados.xaml /// </summary> public partial class AguardeImportarBaseDados : Window { BackgroundWorker worker; string acao; private readonly IAppServicoAtoIss _appServicoAtoIss = BootStrap.Container.GetInstance<IAppServicoAtoIss>(); DataTable dtSql = new DataTable(); public AguardeImportarBaseDados() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { lblContagem.Content = ""; worker = new BackgroundWorker(); worker.WorkerReportsProgress = true; worker.DoWork += worker_DoWork; worker.ProgressChanged += worker_ProgressChanged; worker.RunWorkerCompleted += worker_RunWorkerCompleted; worker.RunWorkerAsync(); } void worker_DoWork(object sender, DoWorkEventArgs e) { Processo(); } void worker_ProgressChanged(object sender, ProgressChangedEventArgs e) { progressBar1.Value = e.ProgressPercentage; if (acao == "Adicionando registro ") { progressBar1.Maximum = dtSql.Rows.Count; lblContagem.Content = string.Format("{0} {1} de {2}", acao, e.ProgressPercentage, dtSql.Rows.Count); } else { progressBar1.Maximum = dtSql.Rows.Count; lblContagem.Content = string.Format("{0} {1} de {2}", acao, e.ProgressPercentage, dtSql.Rows.Count); } } void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { this.Close(); } private void Processo() { SqlConnection conSql = new SqlConnection(@"Data Source=Servidor;Initial Catalog=CS_CAIXA_DB;Persist Security Info=True;User ID=sa;Password=P@$$w0rd"); conSql.Open(); try { SqlCommand cmdTotal = new SqlCommand("select * from ImportarMas", conSql); cmdTotal.CommandType = CommandType.Text; SqlDataReader drSql; drSql = cmdTotal.ExecuteReader(); dtSql = new DataTable(); dtSql.Load(drSql); acao = "Adicionando registro "; var ato = new AtoIss(); for (int i = 0; i < dtSql.Rows.Count; i++) { Thread.Sleep(1); worker.ReportProgress(i + 1); ato.Data = Convert.ToDateTime(dtSql.Rows[i]["Data"]); ato.Atribuicao = dtSql.Rows[i]["Atribuicao"].ToString(); ato.TipoAto = dtSql.Rows[i]["TipoAto"].ToString(); ato.Selo = dtSql.Rows[i]["Selo"].ToString(); ato.Aleatorio = dtSql.Rows[i]["Aleatorio"].ToString(); ato.TipoCobranca = dtSql.Rows[i]["TipoCobranca"].ToString(); ato.Emolumentos = Convert.ToDecimal(dtSql.Rows[i]["Emolumentos"]); ato.Fetj = Convert.ToDecimal(dtSql.Rows[i]["Fetj"]); ato.Funperj = Convert.ToDecimal(dtSql.Rows[i]["Funperj"]); ato.Fundperj = Convert.ToDecimal(dtSql.Rows[i]["Fundperj"]); ato.Funarpen = Convert.ToDecimal(dtSql.Rows[i]["Funarpen"]); ato.Ressag = Convert.ToDecimal(dtSql.Rows[i]["Ressag"]); ato.Mutua = Convert.ToDecimal(dtSql.Rows[i]["Mutua"]); ato.Acoterj = Convert.ToDecimal(dtSql.Rows[i]["Acoterj"]); ato.Distribuidor = Convert.ToDecimal(dtSql.Rows[i]["Distribuidor"]); ato.Iss = Convert.ToDecimal(dtSql.Rows[i]["Iss"]); ato.Total = Convert.ToDecimal(dtSql.Rows[i]["Total"]); _appServicoAtoIss.Add(ato); } conSql.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } }
using System.Net; using System.Web.Http; using AutoMapper; using Swashbuckle.Swagger.Annotations; using XH.APIs.WebAPI.Filters; using XH.APIs.WebAPI.Models.Roles; using XH.Commands.Security; using XH.Domain.Security; using XH.Infrastructure.Bus; using XH.Infrastructure.Paging; using XH.Queries.Security.Dtos; using XH.Queries.Security.Queries; namespace XH.APIs.WebAPI.Controllers { [ApiAuthorize] [RoutePrefix("roles")] public class RolesController : ApiControllerBase { private readonly ICommandBus _commandBus; private readonly IQueryBus _queryBus; private readonly IMapper _mapper; public RolesController( ICommandBus commandBus, IQueryBus queryBus, IMapper mapper ) { _commandBus = commandBus; _queryBus = queryBus; _mapper = mapper; } [Route("")] [HttpPost] [SwaggerResponse(HttpStatusCode.Created, "Create role")] [ApiAuthorize(Permissions.Roles.Create)] public IHttpActionResult CreateRole(CreateRoleRequest request) { var command = _mapper.Map<CreateRoleCommand>(request); _commandBus.Send(command); return StatusCode(HttpStatusCode.Created); } [Route("{id}")] [HttpPut] [SwaggerResponse(HttpStatusCode.OK, "Update telnant")] [ApiAuthorize(Permissions.Roles.Edit)] public IHttpActionResult UpdateRole(string id, [FromBody]UpdateRoleRequest request) { var command = _mapper.Map<UpdateRoleCommand>(request); command.Id = id; _commandBus.Send(command); return Ok(); } [Route("{id}")] [HttpDelete] [SwaggerResponse(HttpStatusCode.OK, "Delete role")] [ApiAuthorize(Permissions.Roles.Delete)] public IHttpActionResult DeleteRole(string id) { _commandBus.Send(new DeleteRoleCommand { Id = id }); return Ok(); } [Route("{id}")] [HttpGet] [SwaggerResponse(HttpStatusCode.OK, "Get role", typeof(RoleDto))] [ApiAuthorize(Permissions.Roles.GetDetail)] public IHttpActionResult GetRole(string id) { var dto = _queryBus.Send<GetRoleQuery, RoleDto>(new GetRoleQuery { Id = id }); if (dto == null) { return NotFound(); } return Ok(dto); } [Route("list")] [HttpGet] [SwaggerResponse(HttpStatusCode.OK, "List roles", typeof(PagedList<RoleOverviewDto>))] [ApiAuthorize(Permissions.Roles.List)] public IHttpActionResult List([FromUri]ListRolesRequest request) { var query = _mapper.Map<ListRolesQuery>(request); var paging = _queryBus.Send<ListRolesQuery, PagedList<RoleOverviewDto>>(query); return Ok(paging); } //[Route("validateRoleName")] //[HttpGet] //[SwaggerResponse(HttpStatusCode.OK, "Validate telnant name", typeof(PagedList<NgValidationResponse>))] //public IHttpActionResult ValidateRoleName([FromUri]string telnantName, [FromUri]string id = "") //{ // var telnant = _queryBus.Send<GetRoleQuery, RoleDto>(new GetRoleQuery { Id = telnantName }); // var isValid = false; // if (string.IsNullOrEmpty(id)) // { // isValid = telnant == null; // } // else if (telnant == null || telnant?.Id == id) // { // isValid = true; // } // return Ok(new NgValidationResponse { IsValid = isValid, Value = telnantName }); //} } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Serialization; public class EquippedGun : MonoBehaviour { [HideInInspector] public AllGunStatus inventory; [NonSerialized] public BaseGunDefinition currentGun; [HideInInspector] public GunBehaviour gunBehaviour; [HideInInspector] public WeaponManager weaponManager; #region public ShootModes currentShootMode; public SightType currentSightMode; [NonSerialized] public float fireTimer = 0f; public float burstTimer; public bool usingAds; public int continuousFire = 0; public float rateOfFire; public bool keyUp = true; public int burstCounter; public float nextActionTime = 0.0f; public float period = 0.1f; [ReadOnly] public bool doingAction = false; private bool isReloading = false; private bool isScoping = false; public float actionTime = 0f; public float sliderMax = 1f; private float startScopeTime; #endregion private Coroutine reloadCoroutine; private Coroutine scopeCoroutine; [ReadOnly] [Range(10, 250)] public float currentAcc; private Vector2 centerPoint; #region Properties public float CurrentAccuracy { get { return currentAcc; } } public Camera fpsCamera; #endregion private void Awake() { inventory = GetComponent<AllGunStatus>(); weaponManager = GetComponent<WeaponManager>(); gunBehaviour = GetComponentInChildren<GunBehaviour>(); } private void Start() { centerPoint = new Vector2(Screen.width / 2f, Screen.height / 2f); fpsCamera = Camera.main; } private void FixedUpdate() { fireTimer += Time.fixedDeltaTime; if (currentShootMode == ShootModes.Burst) { burstTimer += Time.fixedDeltaTime; if(burstTimer >= currentGun.burstPause) { burstCounter = 1; burstTimer = 0.0f; } } if (currentAcc < currentGun.maxAccuracy) { if (Time.fixedTime > nextActionTime) { nextActionTime += period; currentAcc += currentGun.accuracyGainPerSec; if (currentAcc > currentGun.maxAccuracy) currentAcc = currentGun.maxAccuracy; } } } private void Update() { if (Input.GetKeyDown(KeyCode.R)) { if(!isReloading) reloadCoroutine = StartCoroutine(Reload()); } CheckModeChange(); CheckShoot(); if(inventory.status[currentGun.name]<=0 && !doingAction) { DryFire(); } if(actionTime >= 0) { actionTime -= Time.deltaTime; if (actionTime < 0) actionTime = 0; } } private void DryFire() { //Do reload stuff. reloadCoroutine = StartCoroutine(Reload()); } private void CheckModeChange() { if(currentGun.sightType == SightType.Ads) { if(Input.GetMouseButton(1) && !doingAction) { Debug.Log("Starting scope"); startScopeTime = Time.time; scopeCoroutine = StartCoroutine(Scoping(currentGun.scopeInTime)); } else if(Input.GetMouseButtonDown(1) && isScoping) { float scopeOutTime = Time.time - startScopeTime; if (scopeCoroutine != null) { StopCoroutine(scopeCoroutine); Debug.Log("Reversing SIGHT MODE WITHOUT COMPLETION"); } scopeCoroutine = StartCoroutine(Scoping(scopeOutTime)); } } } void CheckShoot() { if(Input.GetMouseButtonUp(0)) { keyUp = true; continuousFire = 0; } else if (Input.GetMouseButton(0)) { if (!doingAction) CheckFire(); } } private void CheckFire() { if (fireTimer >= rateOfFire) ChooseFireMode(); } public void UpdateGun(BaseGunDefinition newGun) { if(newGun == null) { throw new Exception("Gun is null. Good luck you fucking idiot"); } currentGun = newGun; usingAds = false; continuousFire = 0; rateOfFire = 1.0f / currentGun.firingRate; doingAction = false; currentShootMode = currentGun.defaultShootMode; currentSightMode = SightType.Normal; currentAcc = currentGun.maxAccuracy; } private void ChooseFireMode() { keyUp = false; if (currentSightMode == SightType.Ads) { ShootData shootData = new ShootData(this.gameObject,this,true, centerPoint, fpsCamera); currentGun.AdsFire(shootData); } else { ShootData shootData = new ShootData(this.gameObject,this,true, centerPoint, fpsCamera); currentGun.AdsFire(shootData); } } public void Fire() { continuousFire++; SetSlider(rateOfFire); actionTime = rateOfFire; inventory.status[currentGun.name]--; } private IEnumerator Reload() { SetSlider(currentGun.reloadTime); actionTime = currentGun.reloadTime; isReloading = true; doingAction = true; yield return new WaitForSeconds(currentGun.reloadTime); isReloading = false; doingAction = false; inventory.status[currentGun.name] = currentGun.clipSize; } public IEnumerator GunChange(BaseGunDefinition newGunDef, float timer) { if(isReloading) StopCoroutine(reloadCoroutine); if(isScoping) StopCoroutine(scopeCoroutine); isReloading = false; actionTime = 0; doingAction = true; actionTime = timer; SetSlider(timer); yield return new WaitForSeconds(timer); UpdateGun(newGunDef); doingAction = false; } private IEnumerator Scoping(float timer) { if (currentSightMode == SightType.Ads) currentSightMode = SightType.Normal; else currentSightMode = SightType.Ads; doingAction = true; isScoping = true; actionTime = timer; SetSlider(timer); yield return new WaitForSeconds(timer); doingAction = false; isScoping = false; doingAction = false; Debug.Log($"Current shoot mode = { currentSightMode} at {Time.time} "); } private void SetSlider(float maxVal) { sliderMax = maxVal; } }
using Alabo.Cloud.Shop.SecondBuy.Domain.Entities; using Alabo.Domains.Repositories; using MongoDB.Bson; namespace Alabo.Cloud.Shop.SecondBuy.Domain.Repositories { public interface ISecondBuyOrderRepository : IRepository<SecondBuyOrder, ObjectId> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Utils; using Racing.Core; using WebMatrix.WebData; using System.Threading; using System.Web.Security; using LearningRace.Models; using LR.Models; using LR.Models.RaceModels; using LR.Data.Providers; namespace LearningRace.Controllers { public class HomeController : Controller { public ActionResult Themes() { List<Category> categories = DataProvider.Category.GetRootCategories(); categories.ForEach(c => InitializeCategoryImage(c)); ViewBag.Categories = categories; ViewBag.IsAdmin = User.IsInRole("admin"); return View(); } public ActionResult Index(Guid id) { Category currentCategory = DataProvider.Category.GetCategoryById(id, true); InitializeCategoryImage(currentCategory); ViewBag.IsAdmin = User.IsInRole("admin"); return View(currentCategory); } public ActionResult About() { ViewBag.Message = "Your app description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } [Authorize] public ActionResult Game(Guid categoryId) { ViewBag.questionList = DataProvider.Questions.GetQuestionForCategory(categoryId, true, true); ViewBag.categoryId = categoryId; List<Car> raceCars = DataProvider.Cars.GetAvailableCars(WebSecurity.CurrentUserId); ViewBag.Cars = raceCars; RaceModel race = RaceManager.AddRacer(WebSecurity.CurrentUserId, categoryId); ViewBag.CurrentRacer = race.Racers.First(r => r.Racer.UserId == WebSecurity.CurrentUserId); return View(race); } #region Race [Authorize] public JsonResult GetRaceInfo(Guid raceId,int version) { RaceModel race = RaceManager.GetRaceById(raceId); for (int i = 0; i < 3; i++) { if (race.Version > version) break; Thread.Sleep(1000); } return Json(race, JsonRequestBehavior.AllowGet); } [Authorize] public JsonResult RacerReady(Guid raceId, bool isReady, Guid carId, CarColors color) { RaceManager.ChangeRaceState(raceId, WebSecurity.GetUserId(User.Identity.Name), isReady); RaceModel race = RaceManager.GetRaceById(raceId); race.Racers.First(rs => rs.Racer.UserId == WebSecurity.CurrentUserId).RaceCar = DataProvider.Cars.GetCarById(carId, color, WebSecurity.CurrentUserId); return Json(race, JsonRequestBehavior.AllowGet); } [Authorize] public JsonResult SendAnswer(Guid questionId, Guid variantId, Guid raceId) { Question question = DataProvider.Questions.GetQuestionById(questionId); bool result = question.RightVariant.Id == variantId; RaceManager.ChangeSpeed(raceId, WebSecurity.GetUserId(User.Identity.Name), result); RaceModel race = RaceManager.GetRaceById(raceId); return Json(new { result = result, rightId = question.RightVariant.Id, race = race }, JsonRequestBehavior.AllowGet); } #endregion #region PrivateMethods private void InitializeCategoryImage(Category category) { if (string.IsNullOrEmpty(category.ImagePath)) { string path = Server.MapPath(PathUtil.GetCategoryImagePath(category.Id)); if (System.IO.File.Exists(path)) { category.ImagePath = Url.Content(PathUtil.GetCategoryImagePath(category.Id)); } else { category.ImagePath = Url.Content(Constants.defaultCategoryImage); } } category.ChildCategories.ForEach(c => InitializeCategoryImage(c)); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Курсач.Models { public class PageInfo { public int PageNumber { get; set; } // номер текущей страницы public int PageSize { get; set; } // кол-во объектов на странице public int TotalItems { get; set; } // всего объектов public int TotalPages // всего страниц { get { return (int)Math.Ceiling((decimal)TotalItems / PageSize); } } } public class ViewModel { public IEnumerable<Colour> Colours { get; set; } public IEnumerable<ApplicationUser> Users { get; set; } public IEnumerable<Order> Orders { get; set; } public IEnumerable<Driver> Drivers { get; set; } public IEnumerable<Discount> Discounts { get; set; } public IEnumerable<Car> Cars { get; set; } public IEnumerable<Brand> Brands { get; set; } public List<State> States { get; set; } public PageInfo PageInfo { get; set; } } }
using ApprovalTests; using ApprovalTests.Namers; namespace SpaceHosting.Index.Tests.Helpers { public static class ApprovalTestsExtensions { public static void VerifyApprovalAsJson<T>(this T obj, string objectName) { NamerFactory.AdditionalInformation = objectName; Approvals.VerifyWithExtension(obj.ToPrettyJson(), ".json"); } } }
using System; using System.Collections; using System.Collections.Generic; using BP12; using BP12.Collections; using BP12.Events; using DChild.Gameplay.Combat; using UnityEngine; namespace DChild.Gameplay.Objects.Characters.Enemies { public class SpecterMage : Specter { [SerializeField] private AttackDamage m_damage; [SerializeField] private ProjectileSpawnHandler m_plasmaHandler; protected override SpecterAnimation specterAnimation => null; protected override CharacterAnimation animation => null; public override event EventAction<SpawnableEventArgs> Pool; public void ConjurePlasma(IDamageable target) { m_behaviourHandler.StopActiveBehaviour(ref m_waitForBehaviourEnd); m_behaviourHandler.SetActiveBehaviour(StartCoroutine(ConjurePlasmaRoutine(target))); } public override void ForcePool() { this.Raise(Pool, new SpawnableEventArgs(this)); } public override void SpawnAt(Vector2 position, Quaternion rotation) { transform.position = position; transform.rotation = rotation; } public override void Turn() { TurnCharacter(); } public void Idle() { m_movement.Stop(); } protected override void Flinch() { } private IEnumerator ConjurePlasmaRoutine(IDamageable target) { m_waitForBehaviourEnd = true; m_movement.Stop(); yield return new WaitForSeconds(1f); m_plasmaHandler.FireAt(target.position); m_behaviourHandler.SetActiveBehaviour(null); m_waitForBehaviourEnd = false; } protected override void GetAttackInfo(out AttackInfo attackInfo, out DamageFXType fxType) { attackInfo = new AttackInfo(m_damage, 0, null, null); fxType = DamageFXType.Blunt; } protected override void InitializeMinion() { brain.ResetBrain(); } protected override void Awake() { base.Awake(); m_plasmaHandler.SetOwner(this); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public interface IView { void Show(); void Hide(); } public interface IDrawItems { void DrawItems(ConfigurationFile s); } public interface IAuthForm { void OnAuthSuccessCallback(string username, string accesskey); void OnAuthLoginClick(); void OnAuthRegisterClick(); } public class UIView : MonoBehaviour, IAuthForm, IDrawItems { [SerializeField] private ViewWidget AuthWindow; [SerializeField] private ViewWidget AssetViewWindow; [SerializeField] private InputField username; [SerializeField] private InputField passwrod; [SerializeField] private Text loginStatusText; [SerializeField] private Transform arItemListViewRoot; [SerializeField] private ARItem ARElement; void Start() { AssetViewWindow.Hide(); AuthWindow.Show(); } public void DrawItems(ConfigurationFile s) { //clean collection foreach (Transform t in arItemListViewRoot) { if (t.GetComponent<ARItem>() != null) { Destroy(t.gameObject); } } for (var i = 0; i < s.models.Count; i++) { var t = Instantiate(ARElement, arItemListViewRoot); t.transform.SetAsFirstSibling(); t.SetUp(s.models[i], s.markers[i]); } } public void OnAuthSuccessCallback(string username, string accesskey) { IIS_Core.SetUpProfile(username, accesskey); IIS_Core.FetchAllFiles(); } public void OnAuthLoginClick() { IIS_Core.LoginIn(username.text, passwrod.text, (v) => { AuthWindow.Hide(); AssetViewWindow.Show(); OnAuthSuccessCallback(username.text, passwrod.text); IIS_Core.DecodeAndApplySaveToView(v, this); }, s => { loginStatusText.text = s; } ); } public void OnAuthRegisterClick() { IIS_Core.RegisterUser(username.text, passwrod.text, () => { AuthWindow.Hide(); AssetViewWindow.Show(); OnAuthSuccessCallback(username.text, passwrod.text); }, s => { loginStatusText.text = s; }); } }
namespace AddressBook.Application.Contacts.DTOs { public class ContactPhoneDto { public int Id { get; set; } public string PhoneNumber { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace Core.Models { public class UserInfo : BaseAuditModel { public string name { get; set; } public DateTime birthdate { get; set; } public int gender { get; set; } public string note { get; set; } public string address { get; set; } public string imageUrl { get; set; } public string phoneNumber { get; set; } public string email { get; set; } public override string objectCollection() => "UserInfo"; } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Laoziwubo.Model.Common; namespace Laoziwubo.IDAL { public interface IBaseD<T> : IDisposable { /// <summary> /// 异步获取所有实体 /// </summary> /// <returns></returns> Task<IEnumerable<T>> GetEntitysAsync(QueryM q); /// <summary> /// 根据主键Id获取一个实体 /// </summary> /// <param name="id">主键Id</param> /// <returns></returns> T GetEntityById(int id); /// <summary> /// 插入一条信息 /// </summary> bool Insert(T model); /// <summary> /// 更新一条信息 /// </summary> bool Update(T model); } }
using System; using System.IO; using System.Linq; using System.Runtime.Serialization.Json; using System.Text.RegularExpressions; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using Microsoft.Win32; using QuizApplication.Models; namespace QuizApplication { public partial class SettingsWindow : Window { private Button _activeMenuButton; private ScrollViewer _activePanel; public SettingsWindow() { InitializeComponent(); ApplySettingsForWindow(); _activeMenuButton = InterfaceMenuButton; _activePanel = InterfacePanel; } private void Button_LoadImageOnClick(object sender, RoutedEventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Title = "Фон"; openFileDialog.Filter = "Image Files(*.BMP;*.JPG;*.PNG;)|*.BMP;*.JPG;*.PNG;"; openFileDialog.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory + @"background"; if (openFileDialog.ShowDialog() == true) { string filePath = openFileDialog.FileName; string path = AppDomain.CurrentDomain.BaseDirectory + @"background\" + openFileDialog.SafeFileName; if (filePath != path) File.Copy(filePath, path); Settings.Theme.BackgroudImageUrl = openFileDialog.SafeFileName; var fileName = openFileDialog.SafeFileName; if (fileName.Length > 28) fileName = fileName.Substring(0, 28).PadLeft(30, '.'); LabelSelectFile.Content = fileName; } } private void MenuButton_OnClick(object sender, RoutedEventArgs e) { var button = sender as Button; if (_activeMenuButton == button) return; _activeMenuButton.Background = Brushes.Transparent; _activeMenuButton = button; _activeMenuButton.Background = (SolidColorBrush)new BrushConverter().ConvertFromString("#FF28C182"); _activePanel.Visibility = Visibility.Hidden; _activePanel = _activePanel == InterfacePanel ? OtherSettingsPanel : InterfacePanel; _activePanel.Visibility = Visibility.Visible; } private void ApplySettingsForWindow() { //Interface settings var aFontsCollection = CommonMethods.GetCyrillicFontFamilies().ToList(); aFontsCollection.Sort(); ComboBoxTextsFont.ItemsSource = aFontsCollection; ComboBoxTextsFont.SelectedValue = aFontsCollection.Single(family => family == Settings.Theme.TextFontFamily); ComboBoxButtonsFont.ItemsSource = aFontsCollection; ComboBoxButtonsFont.SelectedValue = aFontsCollection.Single(family => family == Settings.Theme.ButtonFontFamily); ClrPicker_ButtonsTextColor.SelectedColor = (Color)ColorConverter.ConvertFromString(Settings.Theme.ButtonTextColor); ClrPicker_ColorText.SelectedColor = (Color)ColorConverter.ConvertFromString(Settings.Theme.TextColor); ClrPicker_ColorButtons.SelectedColor = (Color)ColorConverter.ConvertFromString(Settings.Theme.ButtonBackgroundColor); TextBoxButtonTransparency.Text = Settings.Theme.ButtonTransparency.ToString(); ComboBoxChooseTheme.SelectedIndex = Settings.Theme.Id - 1; //Other settings ComboBoxChooseLevel.SelectedIndex = (int)Settings.Game.Level - 1; CheckBoxChooseLevel.IsChecked = Settings.Game.IsChooseLevel; CheckBoxMultiScore.IsChecked = Settings.Game.IsMultiScore; TextBoxTime.Text = Settings.Game.Time.ToString(); CheckBoxKeepLastQuestion.IsChecked = Settings.Game.IsKeepLastQuestion; CheckBoxShowAnswers.IsChecked = Settings.Game.IsShowAnswers; } private void ButtonExit_OnClick(object sender, RoutedEventArgs e) => Close(); private void ButtonApply_OnClick(object sender, RoutedEventArgs e) { if (_activePanel == InterfacePanel) { Settings.Application.Theme = ComboBoxChooseTheme.Text; if (ComboBoxChooseTheme.SelectedIndex == 2) { Settings.Theme.Id = 3; Settings.Theme.TextFontFamily = ComboBoxTextsFont.Text; Settings.Theme.TextColor = ClrPicker_ColorText.SelectedColorText; Settings.Theme.ButtonFontFamily = ComboBoxButtonsFont.Text; Settings.Theme.ButtonTextColor = ClrPicker_ButtonsTextColor.SelectedColorText; Settings.Theme.ButtonBackgroundColor = ClrPicker_ColorButtons.SelectedColorText; Settings.Theme.SetButtonTransparency(Convert.ToInt32(TextBoxButtonTransparency.Text)); string path = AppDomain.CurrentDomain.BaseDirectory + @"background\" + Settings.Theme.BackgroudImageUrl; if (Application.Current.MainWindow.Background != new ImageBrush(new BitmapImage(new Uri(path)))) { Application.Current.MainWindow.Background = new ImageBrush(new BitmapImage(new Uri(path))); } var jsonFormatter = new DataContractJsonSerializer(typeof(Theme)); using (var fs = new FileStream("Themes//Custom.Theme.json", FileMode.OpenOrCreate)) { jsonFormatter.WriteObject(fs, Settings.Theme); } } else { Settings.Theme = Theme.getTheme(Settings.Application.Theme); Settings.Theme.ApplyConfiguration(Application.Current.MainWindow); } using (var fs = new FileStream("Settings.Application.json", FileMode.OpenOrCreate)) { new DataContractJsonSerializer(typeof(ApplicationSettings)).WriteObject(fs, Settings.Application); } } else if (_activePanel == OtherSettingsPanel) { Settings.Game.IsChooseLevel = (bool)CheckBoxChooseLevel.IsChecked; Settings.Game.IsMultiScore = (bool)CheckBoxMultiScore.IsChecked; Settings.Game.IsKeepLastQuestion = (bool)CheckBoxKeepLastQuestion.IsChecked; Settings.Game.IsShowAnswers = (bool)CheckBoxShowAnswers.IsChecked; Settings.Game.Level = (Difficulty)ComboBoxChooseLevel.SelectedIndex + 1; Settings.Game.SetTime(Convert.ToInt32(TextBoxTime.Text)); var jsonFormatter = new DataContractJsonSerializer(typeof(GameSettings)); using (var fs = new FileStream("Settings.Game.json", FileMode.OpenOrCreate)) { jsonFormatter.WriteObject(fs, Settings.Game); } } Close(); } private void ButtonInformation_OnClick(object sender, RoutedEventArgs e) { string informationText = string.Empty, informationCaption = string.Empty; if (_activePanel == InterfacePanel) { informationCaption = "Інтерфейс"; informationText = "Тема. Ви можете обрати один із трьох запропонованих варіантів: Light, Dark, Custom. Вибравши Light або Dark буде застосовано набір заздалегіть обраних налаштувань, але, якщо ви оберете кастомізовану(Custom) тему, то зможете налаштувати вигляд програми власноруч.\n\n\n" + "=> Фон. Ви можете встановити будь-яке фонове зображення. Проте не забудьте кастомізувати інші елементи, щоб інтерфейс програми виглядав гармонічно.\n\n" + "=> Шрифт тексту. Із запропонованого списку ви можете обрати шрифт, який буде застосовано до основного тексту програми(Назви категорій, запитання).\n" + "=> Колір тексту. Ви маєте можливість встановити будь-який колір для основного тексту(Назви категорій, запитання).\n\n" + "=> Шрифт тексту на кнопках. Аналогічно до шрифту тексту, ви можете обрати шрифт для кнопок в головному меню категорій із запропонованого списку.\n" + "=> Колір тексту на кнопках. Аналогічно до кольору тексту ви маєте можливість встановити будь-який колір для тексту на кнопках в головному меню категорій.\n" + "=> Колір кнопок. Ви можете налаштувати безпосередньо колір кнопок.\n" + "=> Прозорість кнопок. Ви можете налаштувати прозорість кнопок. Значення задається від 0 до 100. Де 100 - це 100% кольору."; } else if (_activePanel == OtherSettingsPanel) { informationCaption = "Інші налаштування"; informationText = "=> Рівень складності. Програмою передбачено 3 рівня складності(Легкий, середній, важкий).\n" + "=> Ви можете обрати рівень складності для усіх категорій або обирати його кожного разу перед бліцом запитань.\n" + "=> Програма веде підрахунок очок для кожного гравця. За замовчуванням за одну правильну відповідь присвоюється 1 очко. Поставивши галочку, гравці будуть отримувати 1, 2, 3 очка за легкий, середній та складний рівень відповідно.\n" + "=> Ви можете встановити час, який буде відведено кожному гравцеві на бліц.\n" + "=> Якщо час закінчився, гру буде припинено, але ви маєте можливість налаштувати цю ситуцію та залишити останнє запитання, незважаючи на те, що час закінчився.\n" + "=> Програмою передбачено два варіанти гри. Перший - із варіантами відповідей, другий - без варіантів відповідей."; } MessageBox.Show(informationText, $"Довідка: {informationCaption}", MessageBoxButton.OK, MessageBoxImage.Information); } private void ButtonEditCategory_OnClick(object sender, RoutedEventArgs e) { var window = new EditQuestionWindow() { Owner = Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive) }; window.ShowDialog(); } private void NumberValidationTextBox(object sender, TextCompositionEventArgs e) { Regex regex = new Regex("[^0-9]+"); e.Handled = regex.IsMatch(e.Text); } } }
 namespace AutoAnimalDoors.StardewValleyWrapper { class ModConfig { public bool AutoOpenEnabled { get; set; } = true; public int AnimalDoorOpenTime { get; set; } = 730; public int AnimalDoorCloseTime { get; set; } = 1800; public bool OpenDoorsWhenRaining { get; set; } = false; public bool OpenDoorsDuringWinter { get; set; } = false; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using RDotNet; using System.IO; using System.Collections.ObjectModel; namespace SalaryPrediction { class RdotNetCaller { private REngine engine; public RdotNetCaller(String scriptPath) { var oldPath = Environment.GetEnvironmentVariable("PATH"); var rPath1 = @"C:\Program Files\Microsoft\R Client\R_SERVER\bin\x64"; var rPath2 = @"C:\Program Files\Microsoft\R Client\R_SERVER\library\caret\R"; if (!Directory.Exists(rPath1)) throw new DirectoryNotFoundException(string.Format(" R.dll not found in : {0}", rPath1)); var newPath = string.Format("{0}{1}{2}", rPath1, Path.PathSeparator, oldPath); newPath = string.Format("{0}{1}{2}", rPath2, Path.PathSeparator, newPath); Environment.SetEnvironmentVariable("PATH", newPath); REngine.SetEnvironmentVariables( "C:\\Program Files\\R\\R-3.4.4\\bin\\i386", "C:\\Program Files\\R\\R-3.4.4" ); engine = REngine.GetInstance(); engine.Initialize(); engine.Evaluate($"source('{scriptPath}')"); } public string CallMyModel(params string[] parameters) { engine.Evaluate(string.Format($"parameters <- data.frame(dataFrameUnPr$A[dataFrameUnPr$N == {parameters[0]}], dataFrameUnSex$A[dataFrameUnSex$N == {parameters[1]}], dataFrameUnReg$A[dataFrameUnReg$N == {parameters[2]}])")); engine.Evaluate("names(parameters) <- c('Profession', 'Sex', 'Region')"); engine.Evaluate("predictions <- predict(lin.model.1, parameters)"); return engine.Evaluate("as.character(predictions)").AsCharacter().ToArray()[0]; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class WallBuilderBehavior : MonoBehaviour { public GameObject CubePrefab; private bool Isfive; private float Number; // Start is called before the first frame update void Start() { Instantiate(CubePrefab, new Vector3(1, 0, 0), Quaternion.identity); Build_A_Wall_At_Z(-1); Build_A_Wall_At_Z(-3); Build_A_Wall_At_X(1); Build_A_Wall_At_X(5); Build_A_Wall_At_X2(-1); Build_A_Wall_At_X2(-5); Build_A_Wall_At_Y(1); Build_A_Wall_At_Y(5); Build_A_Wall_At_Y2(1); Build_A_Wall_At_Y2(5); if(Number == 5) { Isfive = true; Debug.Log(Isfive); } } // Update is called once per frame /*void Update() { }*/ void Build_A_Wall_At_Z(float z) { for (int XPos = 0; XPos < 20; XPos++) { for (int YPos = 0; YPos < 10; YPos++) { Instantiate(CubePrefab, new Vector3(XPos - 10, YPos, 0), Quaternion.identity); } } } void Build_A_Wall_At_X(float x) { for (int ZPos = 0; ZPos < 20; ZPos++) { for (int YPos = 0; YPos < 10; YPos++) { Instantiate(CubePrefab, new Vector3(-10, YPos, ZPos + 1), Quaternion.identity); } } } void Build_A_Wall_At_X2(float x) { for (int ZPos = 0; ZPos < 20; ZPos++) { for (int YPos = 0; YPos < 10; YPos++) { Instantiate(CubePrefab, new Vector3(9, YPos, ZPos + 1), Quaternion.identity); } } } void Build_A_Wall_At_Y(float y) { for(int XPos = 0; XPos < 20; XPos++) { for(int ZPos = 0; ZPos < 20; ZPos++) { Instantiate(CubePrefab, new Vector3(XPos + -10, 10, ZPos + 1), Quaternion.identity); } } } void Build_A_Wall_At_Y2(float y) { for (int XPos = 0; XPos < 20; XPos++) { for (int ZPos = 0; ZPos < 20; ZPos++) { Instantiate(CubePrefab, new Vector3(XPos - 10, 0, ZPos + 1), Quaternion.identity); } } } }
using Atc.Rest.FluentAssertions.Tests.XUnitTestData; using FluentAssertions; using Microsoft.AspNetCore.Mvc; using Xunit; using Xunit.Sdk; namespace Atc.Rest.FluentAssertions.Tests.Assertions { public class NotFoundResultAssertionsTests : ContentResultAssertionsBaseFixture { [Fact] public void Ctor_Sets_Subject_On_Subject_Property() { // Arrange var expected = new ContentResult(); // Act var sut = new NotFoundResultAssertions(expected); // Assert sut.Subject.Should().Be(expected); } [Fact] public void WithContent_Throws_When_Content_Is_Not_Equivalent_To_Expected() { // Arrange var target = CreateWithJsonContent("FOO"); var sut = new NotFoundResultAssertions(target); // Act & Assert sut.Invoking(x => x.WithContent("BAR")) .Should() .Throw<XunitException>() .WithMessage(@"Expected content of not found result to be ""BAR"", but ""FOO"" differs near ""FOO"" (index 0)."); } [Fact] public void WithContent_Throws_When_Content_Is_Not_Equivalent_To_Expected_WithBecauseMessage() { // Arrange var target = CreateWithJsonContent("FOO"); var sut = new NotFoundResultAssertions(target); // Act & Assert sut.Invoking(x => x.WithContent("BAR", "Because of something")) .Should() .Throw<XunitException>() .WithMessage(@"Expected content of not found result to be ""BAR"" Because of something, but ""FOO"" differs near ""FOO"" (index 0)."); } [Fact] public void WithContent_Throws_When_ContentTypes_Isnt_Json() { // Arrange var target = new ContentResult { Content = "FOO", ContentType = "BAZ", }; var sut = new NotFoundResultAssertions(target); // Act & Assert sut.Invoking(x => x.WithContent("FOO")) .Should() .Throw<XunitException>() .WithMessage(@"Expected content type of not found result to be ""application/json"", but found ""BAZ""."); } [Fact] public void WithContent_Does_Not_Throw_When_Expected_Match() { // Arrange var target = CreateWithJsonContent("FOO"); var sut = new NotFoundResultAssertions(target); // Act & Assert sut.Invoking(x => x.WithContent("FOO")) .Should() .NotThrow(); } [Theory] [MemberData(nameof(TestDataAssertions.ErrorMessageContent), MemberType = typeof(TestDataAssertions))] public void WithErrorMessage_Throws_When_Content_Doenst_Match_Expected(object content) { // Arrange var target = CreateWithJsonContent(content); var sut = new NotFoundResultAssertions(target); // Act & Assert sut.Invoking(x => x.WithErrorMessage("BAR")) .Should() .Throw<XunitException>() .WithMessage(@"Expected error message of not found result to be ""BAR"", but found ""FOO""."); } [Theory] [MemberData(nameof(TestDataAssertions.ErrorMessageContent), MemberType = typeof(TestDataAssertions))] public void WithErrorMessage_Does_Not_Throw_When_Expected_Match(object content) { // Arrange var target = CreateWithJsonContent(content); var sut = new NotFoundResultAssertions(target); // Act & Assert sut.Invoking(x => x.WithErrorMessage("FOO")) .Should() .NotThrow(); } } }
using System.Collections.Generic; using DFC.ServiceTaxonomy.GraphSync.Interfaces; using FakeItEasy; using Newtonsoft.Json.Linq; using Xunit; namespace DFC.ServiceTaxonomy.UnitTests.GraphSync.GraphSyncers.Helpers.GraphValidationHelper { public class GraphValidationHelper_StringContentPropertyMatchesNodePropertyTests { public const string ContentKey = "Text"; public JObject ContentItemField { get; set; } public const string NodePropertyName = "nodePropertyName"; public INode SourceNode { get; set; } public Dictionary<string, object> SourceNodeProperties { get; set; } public ServiceTaxonomy.GraphSync.GraphSyncers.Helpers.GraphValidationHelper GraphValidationHelper { get; set; } public GraphValidationHelper_StringContentPropertyMatchesNodePropertyTests() { ContentItemField = JObject.Parse("{}"); SourceNode = A.Fake<INode>(); SourceNodeProperties = new Dictionary<string, object>(); A.CallTo(() => SourceNode.Properties).Returns(SourceNodeProperties); GraphValidationHelper = new ServiceTaxonomy.GraphSync.GraphSyncers.Helpers.GraphValidationHelper(); } [Fact] public void StringContentPropertyMatchesNodeProperty_PropertyCorrect_ReturnsTrue() { const string text = "abc"; ContentItemField = JObject.Parse($"{{\"{ContentKey}\": \"{text}\"}}"); SourceNodeProperties.Add(NodePropertyName, text); (bool validated, _) = CallStringContentPropertyMatchesNodeProperty(); Assert.True(validated); } [Fact] public void StringContentPropertyMatchesNodeProperty_PropertyMissing_ReturnsFalse() { const string text = "abc"; ContentItemField = JObject.Parse($"{{\"{ContentKey}\": \"{text}\"}}"); (bool validated, _) = CallStringContentPropertyMatchesNodeProperty(); Assert.False(validated); } [Fact] public void StringContentPropertyMatchesNodeProperty_PropertiesSameTypeButDifferentValues_ReturnsFalse() { const string text = "abc"; ContentItemField = JObject.Parse($"{{\"{ContentKey}\": \"{text}\"}}"); SourceNodeProperties.Add(NodePropertyName, "some_other_value"); (bool validated, _) = CallStringContentPropertyMatchesNodeProperty(); Assert.False(validated); } [Theory] [InlineData("true", true)] [InlineData("false", false)] [InlineData("string", true)] [InlineData("string", false)] [InlineData("", true)] [InlineData("", false)] [InlineData("123", 123)] [InlineData("string", -1)] [InlineData("", 0)] //todo: other valid neo property types public void StringContentPropertyMatchesNodeProperty_PropertiesDifferentTypes_ReturnsFalse(string contentValue, object nodeValue) { string json = $"{{\"{ContentKey}\": \"{contentValue}\"}}"; ContentItemField = JObject.Parse(json); SourceNodeProperties.Add(NodePropertyName, nodeValue); (bool validated, _) = CallStringContentPropertyMatchesNodeProperty(); Assert.False(validated); } [Theory] [InlineData("content property value was 'contentValue', but node property value was 'nodeValue'", "contentValue", "nodeValue")] [InlineData("content property value was 'contentValue', but node property value was ''", "contentValue", "")] public void StringContentPropertyMatchesNodeProperty_PropertySameTypeButDifferent_ReturnsFailedValidationMessage(string expectedMessage, string contentValue, string nodeValue) { string json = $"{{\"{ContentKey}\": \"{contentValue}\"}}"; ContentItemField = JObject.Parse(json); SourceNodeProperties.Add(NodePropertyName, nodeValue); (_, string message) = CallStringContentPropertyMatchesNodeProperty(); Assert.Equal(expectedMessage, message); } //todo: tests for ValidateOutgoingRelationship private (bool matched, string failureReason) CallStringContentPropertyMatchesNodeProperty() { return GraphValidationHelper.StringContentPropertyMatchesNodeProperty( ContentKey, ContentItemField, NodePropertyName, SourceNode); } } }
using EntVenta; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DatVentas { public class DatEmpresa { public int Agregar_Empresa(Empresa e) { using (SqlConnection conn = new SqlConnection(MasterConnection.connection)) { try { int resultado = 0; conn.Open(); SqlCommand sc = new SqlCommand("sp_insertarEmpresa", conn); sc.CommandType = CommandType.StoredProcedure; sc.Parameters.AddWithValue("@nombre", e.Nombre); sc.Parameters.AddWithValue("@logo", e.Logo); sc.Parameters.AddWithValue("@impuesto", e.Impuesto); sc.Parameters.AddWithValue("@porcentaje", e.Porcentaje); sc.Parameters.AddWithValue("@moneda", e.Moneda); sc.Parameters.AddWithValue("@trabajaImpuesto", e.Usa_Impuestos); sc.Parameters.AddWithValue("@modoBusqueda", e.Busqueda); sc.Parameters.AddWithValue("@rutaBackup", e.RutaBackup); sc.Parameters.AddWithValue("@correoEnvioRpt", e.CorreoEnvio); sc.Parameters.AddWithValue("@ultimoBackup", e.UltimoBackup); sc.Parameters.AddWithValue("@ultimoBackup2", e.UltimaFechaBackup); sc.Parameters.AddWithValue("@frecuenciaBackup", e.FrecuenciaBackup); sc.Parameters.AddWithValue("@TipoEmpresa", e.TipoEmpresa); sc.Parameters.AddWithValue("@pais", e.Pais); sc.Parameters.AddWithValue("@Redondeo", e.Redondeo); sc.Parameters.AddWithValue("@estado", e.Estado); resultado = sc.ExecuteNonQuery(); conn.Close(); return resultado; } catch (Exception ex) { conn.Close(); throw ex; } } } public DataRow MostraEmpresa() { using (SqlConnection conn = new SqlConnection(MasterConnection.connection)) { DataTable dt = new DataTable(); try { SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM tb_Empresa ", conn); da.Fill(dt); return dt.Rows[0]; } catch (Exception ex) { conn.Close(); throw ex; } } } public int EditarEmpresa(Empresa e) { using (SqlConnection conn = new SqlConnection(MasterConnection.connection)) { try { int resultado = 0; conn.Open(); SqlCommand sc = new SqlCommand("sp_ActualizarEmpresa", conn); sc.CommandType = CommandType.StoredProcedure; sc.Parameters.AddWithValue("@empresa", e.Nombre); sc.Parameters.AddWithValue("@logo", e.Logo); sc.Parameters.AddWithValue("@impuesto", e.Impuesto); sc.Parameters.AddWithValue("@porcentajeimpuesto", e.Porcentaje); sc.Parameters.AddWithValue("@manejaimpuesto", e.Usa_Impuestos); sc.Parameters.AddWithValue("@modobusqueda", e.Busqueda); sc.Parameters.AddWithValue("@moneda", e.Moneda); sc.Parameters.AddWithValue("@correo", e.CorreoEnvio); sc.Parameters.AddWithValue("@rutabackup", e.RutaBackup); sc.Parameters.AddWithValue("@pais", e.Pais); resultado = sc.ExecuteNonQuery(); conn.Close(); return resultado; } catch (Exception ex) { conn.Close(); throw ex; } } } public int EditarEmpresa_CompiaSeguridad(int frecuencia) { using (SqlConnection conn = new SqlConnection(MasterConnection.connection)) { try { int resultado = 0; conn.Open(); SqlCommand sc = new SqlCommand($"UPDATE tb_Empresa set [Ultima_FechaRespaldo] ='{DateTime.Now.ToString()}', [Ultima_FechaRespaldo2]='{DateTime.Now}', [Frecuencia_Respaldo]={frecuencia} ", conn); resultado = sc.ExecuteNonQuery(); conn.Close(); return resultado; } catch (Exception ex) { conn.Close(); throw ex; } } } } }
namespace Sentry.AspNetCore; internal static class Constants { // See: https://github.com/getsentry/sentry-release-registry public const string SdkName = "sentry.dotnet.aspnetcore"; }
namespace Backend.Model.Enums { public enum TypeOfRenovation { REGULAR_RENOVATION, MERGE_RENOVATION, DIVIDE_RENOVATION } }
#r "System.Drawing" using System.IO; using System.Net; using System.Net.Http.Headers; using System.Drawing; using System.Drawing.Imaging; using System.Diagnostics; public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) { log.Info($"HTTP request triggered. RequestUri={req.RequestUri}"); var response = new HttpResponseMessage(); var stopWatch = new Stopwatch(); stopWatch.Start(); var width = 300; var height = 300; var totalIterations = 2000000; Random r = new Random(); using(MemoryStream ms = new MemoryStream()) { using (Bitmap bitmap = new Bitmap(width, height)) { using (Graphics g = Graphics.FromImage(bitmap)) { g.Clear(Color.Black); var x = 0.0; var y = 0.0; var iteration = 0; var max_iteration = 80; List<Tuple<double, double>> points; for (var i = 0; i < totalIterations; i++) { var x0 = r.NextDouble() * 4 - 3; var y0 = r.NextDouble() * 4 - 2; x = 0.0; y = 0.0; iteration = 0; points = new List<Tuple<double, double>>(); while (x * x + y * y < 4 && iteration < max_iteration) { var xtemp = x * x - y * y + x0; y = 2 * x * y + y0; x = xtemp; var p = Tuple.Create(x, y); points.Add(p); iteration = iteration + 1; } if (x * x + y * y > 4 || iteration > max_iteration) { points.ForEach((point) => { var xx = (point.Item1 + 2.1) * width/3; var yy = (point.Item2 + 1.4) * height/3; if (xx < width && xx > 0 && yy < height && yy > 0) { SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(1, 255, 255, 255)); g.FillRectangle(semiTransBrush, (float)yy, (float)xx, 1, 1); } }); } } bitmap.Save(ms, ImageFormat.Png); } response.Content = new ByteArrayContent(ms.ToArray()); response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png"); } } stopWatch.Stop(); log.Info($"Time elapsed: {stopWatch.Elapsed}."); return response; }
using System.Collections.Generic; using System.Threading.Tasks; namespace OnlineClinic.Data.Repositories { public interface IRepository<T> where T : class { IEnumerable<T> GetAll(bool asNoTracking = true); Task<IEnumerable<T>> GetAllAsync(bool asNoTracking = true); bool Exists(int id); T GetById(int id); Task<T> GetByIdAsync(int id); int Create(T entity); Task<int> CreateAsync(T entity); void Update(T entity); Task UpdateAsync(T entity); void Delete(int id); Task DeleteAsync(int id); } }
using UnityEngine; public class FeatureBedrockWalls : FeatureBase { [SerializeField] private CellData _bedrock = null; public override void generate(System.Random rnd, LayerData layerData, MapAccessor accessor) { int end = accessor.size - 1; for(int x = 0; x < accessor.size; x++) { for(int y = 0; y < accessor.size; y++) { if(x == 0 || y == 0 || x == end || y == end) { accessor.setCell(x, y, this._bedrock); } } } } }
using System; using Vlc.DotNet.Core.Interops.Signatures; namespace Vlc.DotNet.Core { public sealed partial class VlcMedia : IDisposable { public string Title { get { return GetMetaData(MediaMetadatas.Title); } set { myVlcMediaPlayer.Manager.SetMediaMeta(MediaInstance, MediaMetadatas.Title, value); } } public string Artist { get { return GetMetaData(MediaMetadatas.Artist); } set { myVlcMediaPlayer.Manager.SetMediaMeta(MediaInstance, MediaMetadatas.Artist, value); } } public string Genre { get { return GetMetaData(MediaMetadatas.Genre); } set { myVlcMediaPlayer.Manager.SetMediaMeta(MediaInstance, MediaMetadatas.Genre, value); } } public string Copyright { get { return GetMetaData(MediaMetadatas.Copyright); } set { myVlcMediaPlayer.Manager.SetMediaMeta(MediaInstance, MediaMetadatas.Copyright, value); } } public string Album { get { return GetMetaData(MediaMetadatas.Album); } set { myVlcMediaPlayer.Manager.SetMediaMeta(MediaInstance, MediaMetadatas.Album, value); } } public string TrackNumber { get { return GetMetaData(MediaMetadatas.TrackNumber); } set { myVlcMediaPlayer.Manager.SetMediaMeta(MediaInstance, MediaMetadatas.TrackNumber, value); } } public string Description { get { return GetMetaData(MediaMetadatas.Description); } set { myVlcMediaPlayer.Manager.SetMediaMeta(MediaInstance, MediaMetadatas.Description, value); } } public string Rating { get { return GetMetaData(MediaMetadatas.Rating); } set { myVlcMediaPlayer.Manager.SetMediaMeta(MediaInstance, MediaMetadatas.Rating, value); } } public string Date { get { return GetMetaData(MediaMetadatas.Date); } set { myVlcMediaPlayer.Manager.SetMediaMeta(MediaInstance, MediaMetadatas.Date, value); } } public string Setting { get { return GetMetaData(MediaMetadatas.Setting); } set { myVlcMediaPlayer.Manager.SetMediaMeta(MediaInstance, MediaMetadatas.Setting, value); } } public string URL { get { return GetMetaData(MediaMetadatas.URL); } set { myVlcMediaPlayer.Manager.SetMediaMeta(MediaInstance, MediaMetadatas.URL, value); } } public string Language { get { return GetMetaData(MediaMetadatas.Language); } set { myVlcMediaPlayer.Manager.SetMediaMeta(MediaInstance, MediaMetadatas.Language, value); } } public string NowPlaying { get { return GetMetaData(MediaMetadatas.NowPlaying); } set { myVlcMediaPlayer.Manager.SetMediaMeta(MediaInstance, MediaMetadatas.NowPlaying, value); } } public string Publisher { get { return GetMetaData(MediaMetadatas.Publisher); } set { myVlcMediaPlayer.Manager.SetMediaMeta(MediaInstance, MediaMetadatas.Publisher, value); } } public string EncodedBy { get { return GetMetaData(MediaMetadatas.EncodedBy); } set { myVlcMediaPlayer.Manager.SetMediaMeta(MediaInstance, MediaMetadatas.EncodedBy, value); } } public string ArtworkURL { get { return GetMetaData(MediaMetadatas.ArtworkURL); } set { myVlcMediaPlayer.Manager.SetMediaMeta(MediaInstance, MediaMetadatas.ArtworkURL, value); } } public string TrackID { get { return GetMetaData(MediaMetadatas.TrackID); } set { myVlcMediaPlayer.Manager.SetMediaMeta(MediaInstance, MediaMetadatas.TrackID, value); } } public void Parse() { myVlcMediaPlayer.Manager.ParseMedia(MediaInstance); } public void ParseAsync() { myVlcMediaPlayer.Manager.ParseMediaAsync(MediaInstance); } private string GetMetaData(MediaMetadatas metadata) { if (MediaInstance == IntPtr.Zero) return null; if (myVlcMediaPlayer.Manager.IsParsedMedia(MediaInstance)) myVlcMediaPlayer.Manager.ParseMedia(MediaInstance); return myVlcMediaPlayer.Manager.GetMediaMeta(MediaInstance, metadata); } } }
// Copyright (c) 2018 FiiiLab Technology Ltd // Distributed under the MIT software license, see the accompanying // file LICENSE or or http://www.opensource.org/licenses/mit-license.php. namespace FiiiCoin.DTO { public class PeerInfoOM { public long Id { get; set; } public bool IsTracker { get; set; } public string Addr { get; set; } public long LastSend { get; set; } public long LastRecv { get; set; } public long LastHeartBeat { get; set; } public long BytesSent { get; set; } public long BytesRecv { get; set; } public long ConnTime { get; set; } public long Version { get; set; } public bool Inbound { get; set; } public long LatestHeight { get; set; } } }
using System.ComponentModel.DataAnnotations.Schema; using WxShop.Model.Base; namespace WxShop.Model { [Table("ws_ProductImage")] public class ProductImageModel : EntityBase { public int ProductID { get; set; } public string Name { get; set; } public string ImageType { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.DataProtection; using Microsoft.EntityFrameworkCore; using WebStore.DAL.Context; using WebStore.Domain.Entities; namespace WebStore.Data { public static class DbInitializer { public static void Initialize(WebStoreContext context) { context.Database.EnsureCreated(); if (context.Products.Any()) { return; } var sections = new List<Section> { new Section{Id = 1, Name = "Sportswear",Order = 0, ParentId = null}, new Section{Id = 2, Name = "Nike",Order = 0, ParentId = 1}, new Section{Id = 3, Name = "Under Armour",Order = 1, ParentId = 1}, new Section{Id = 4, Name = "Adidas",Order = 2, ParentId = 1}, new Section{Id = 5, Name = "Puma",Order = 3, ParentId = 1}, new Section{Id = 6, Name = "ASICS",Order = 4, ParentId = 1}, new Section{Id = 7, Name = "Mens",Order = 1, ParentId = null}, new Section{Id = 8, Name = "Fendi",Order = 0, ParentId = 7}, new Section{Id = 9, Name = "Guess",Order = 1, ParentId = 7}, new Section{Id = 10, Name = "Valentino",Order = 2, ParentId = 7}, new Section{Id = 11, Name = "Dior",Order = 3, ParentId = 7}, new Section{Id = 12, Name = "Versace",Order = 4, ParentId = 7}, new Section{Id = 13, Name = "Armani",Order = 5, ParentId = 7}, new Section{Id = 14, Name = "Prada",Order = 6, ParentId = 7}, new Section{Id = 15, Name = "Dolce and Gabbana",Order = 7, ParentId = 7}, new Section{Id = 16, Name = "Chanel",Order = 8, ParentId = 7}, new Section{Id = 17, Name = "Gucci",Order = 1, ParentId = 7}, new Section{Id = 18, Name = "Womens",Order = 2, ParentId = null}, new Section{Id = 19, Name = "Fendi",Order = 0, ParentId = 18}, new Section{Id = 20, Name = "Guess",Order = 1, ParentId = 18}, new Section{Id = 21, Name = "Valentino",Order = 2, ParentId = 18}, new Section{Id = 22, Name = "Dior",Order = 3, ParentId = 18}, new Section{Id = 23, Name = "Versace",Order = 4, ParentId = 18}, new Section{Id = 24, Name = "Armani",Order = 5, ParentId = 18}, new Section{Id = 25, Name = "Prada",Order = 6, ParentId = 18}, new Section{Id = 26, Name = "Dolce and Gabbana",Order = 7, ParentId = 18}, new Section{Id = 27, Name = "Chanel",Order = 8, ParentId = 18}, new Section{Id = 28, Name = "Gucci",Order = 1, ParentId = 18}, new Section{Id = 29, Name = "Kids",Order = 3, ParentId = null}, new Section{Id = 30, Name = "Fashion",Order = 4, ParentId = null}, new Section{Id = 31, Name = "Households",Order = 5, ParentId = null}, new Section{Id = 32, Name = "Interiors",Order = 6, ParentId = null}, new Section{Id = 33, Name = "Clothing",Order = 7, ParentId = null}, new Section{Id = 34, Name = "Bags",Order = 8, ParentId = null}, new Section{Id = 35, Name = "Shoes",Order = 9, ParentId = null} }; using (var trans = context.Database.BeginTransaction()) { foreach (var section in sections) { context.Sections.Add(section); } context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Sections] ON"); context.SaveChanges(); context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Sections] OFF"); trans.Commit(); } var brands = new List<Brand> { new Brand(1,"Acne",0), new Brand(2,"Grüne Erde",1), new Brand(3,"Albiro",2), new Brand(4,"Ronhill",3), new Brand(5,"Oddmolly",4), new Brand(6,"Boudestijn",5), new Brand(7,"Rösch creative culture",6) }; using (var trans = context.Database.BeginTransaction()) { foreach (var brand in brands) { context.Brands.Add(brand); } context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Brands] ON"); context.SaveChanges(); context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Brands] OFF"); trans.Commit(); } var products = new List<Product> { new Product() { Id = 1, Name = "Easy Polo Black Edition", Price = 1025, ImageUrl = "product1.jpg", Order = 0, SectionId = 2, BrandId = 1 }, new Product() { Id = 2, Name = "Easy Polo Black Edition", Price = 1025, ImageUrl = "product2.jpg", Order = 1, SectionId = 2, BrandId = 1 }, new Product() { Id = 3, Name = "Easy Polo Black Edition", Price = 1025, ImageUrl = "product3.jpg", Order = 2, SectionId = 2, BrandId = 1 }, new Product() { Id = 4, Name = "Easy Polo Black Edition", Price = 1025, ImageUrl = "product4.jpg", Order = 3, SectionId = 2, BrandId = 1 }, new Product() { Id = 5, Name = "Easy Polo Black Edition", Price = 1025, ImageUrl = "product5.jpg", Order = 4, SectionId = 2, BrandId = 2 }, new Product() { Id = 6, Name = "Easy Polo Black Edition", Price = 1025, ImageUrl = "product6.jpg", Order = 5, SectionId = 2, BrandId = 2 }, new Product() { Id = 7, Name = "Easy Polo Black Edition", Price = 1025, ImageUrl = "product7.jpg", Order = 6, SectionId = 2, BrandId = 2 }, new Product() { Id = 8, Name = "Easy Polo Black Edition", Price = 1025, ImageUrl = "product8.jpg", Order = 7, SectionId = 25, BrandId = 2 }, new Product() { Id = 9, Name = "Easy Polo Black Edition", Price = 1025, ImageUrl = "product9.jpg", Order = 8, SectionId = 25, BrandId = 2 }, new Product() { Id = 10, Name = "Easy Polo Black Edition", Price = 1025, ImageUrl = "product10.jpg", Order = 9, SectionId = 25, BrandId = 3 }, new Product() { Id = 11, Name = "Easy Polo Black Edition", Price = 1025, ImageUrl = "product11.jpg", Order = 10, SectionId = 25, BrandId = 3 }, new Product() { Id = 12, Name = "Easy Polo Black Edition", Price = 1025, ImageUrl = "product12.jpg", Order = 11, SectionId = 25, BrandId = 3 }, }; using (var trans = context.Database.BeginTransaction()) { foreach (var product in products) { context.Products.Add(product); } context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Products] ON"); context.SaveChanges(); context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Products] OFF"); trans.Commit(); } } } }
#if NETFRAMEWORK namespace Sentry.EntityFramework.Tests; [UsesVerify] [Collection("Sequential")] public class IntegrationTests { // needs to be a variable to stop EF from inlining it as a constant static string shouldNotAppearInPayload = "SHOULD NOT APPEAR IN PAYLOAD"; [SkippableFact] public async Task Simple() { Skip.If(!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)); var transport = new RecordingTransport(); var options = new SentryOptions { AttachStacktrace = false, TracesSampleRate = 1, Transport = transport, Dsn = ValidDsn, DiagnosticLevel = SentryLevel.Debug, Release = "test-release" }; options.AddEntityFramework(); var sqlInstance = new SqlInstance<TestDbContext>( constructInstance: connection => new(connection, true)); using (var database = await sqlInstance.Build()) { // forcing a query means EF performs it startup version checks against sql. // so we dont include that noise in assert await database.Context.TestTable.ToListAsync(); using (var hub = new Hub(options)) { var transaction = hub.StartTransaction("my transaction", "my operation"); hub.ConfigureScope(scope => scope.Transaction = transaction); hub.CaptureException(new("my exception")); await database.AddData( new TestDbContext.TestData { Id = 1, AColumn = shouldNotAppearInPayload, RequiredColumn = "Value" }); await database.Context.TestTable .FirstAsync(_ => _.AColumn == shouldNotAppearInPayload); transaction.Finish(); } } var result = await Verify(transport.Payloads) .IgnoreStandardSentryMembers(); Assert.DoesNotContain(shouldNotAppearInPayload, result.Text); options.DisableDbInterceptionIntegration(); } } #endif
using Alabo.Datas.Ef.Configs; using Alabo.Datas.Ef.Logs; using Alabo.Datas.Ef.Map; using Alabo.Datas.Matedatas; using Alabo.Datas.Sql; using Alabo.Domains.Auditing; using Alabo.Exceptions; using Alabo.Logging; using Alabo.Reflections; using Alabo.Security.Sessions; using Alabo.Tenants; using Alabo.Tenants.Extensions; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Data; using System.Threading; using System.Threading.Tasks; namespace Alabo.Datas.UnitOfWorks { /// <summary> /// 工作单元 /// </summary> public abstract class UnitOfWorkBase : DbContext, IUnitOfWork, IDatabase, IEntityMatedata { #region Commit(提交) /// <summary> /// 提交,返回影响的行数 /// </summary> public int Commit() { try { return SaveChanges(); } catch (DbUpdateConcurrencyException ex) { throw new ConcurrencyException(ex); } } #endregion Commit(提交) #region CommitAsync(异步提交) /// <summary> /// 异步提交,返回影响的行数 /// </summary> public async Task<int> CommitAsync() { try { return await SaveChangesAsync(); } catch (DbUpdateConcurrencyException ex) { throw new ConcurrencyException(ex); } } #endregion CommitAsync(异步提交) #region SaveChangesAsync(异步保存更改) /// <summary> /// 异步保存更改 /// </summary> public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default) { SaveChangesBefore(); return base.SaveChangesAsync(cancellationToken); } #endregion SaveChangesAsync(异步保存更改) #region 构造方法 /// <summary> /// 初始化Entity Framework工作单元 /// </summary> /// <param name="options">配置</param> /// <param name="manager">工作单元服务</param> protected UnitOfWorkBase(DbContextOptions options, IUnitOfWorkManager manager) : base(options) { manager?.Register(this); TraceId = Guid.NewGuid(); Session = Security.Sessions.Session.Instance; DbContextOptions = options; SwitchTenantDatabase(); } /// <summary> /// Switch tenant database. /// </summary> public void SwitchTenantDatabase() { //run in thread 'dbConnection.ConnectionString' is no pwd var dbConnection = GetConnection(); var mainConnectionString = TenantContext.GetMasterTenant(); if (string.IsNullOrWhiteSpace(mainConnectionString)) { mainConnectionString = string.IsNullOrWhiteSpace(ConnectionString) ? dbConnection.ConnectionString : ConnectionString; TenantContext.AddMasterTenant(mainConnectionString); } if (string.IsNullOrWhiteSpace(ConnectionString)) { ConnectionString = mainConnectionString; } if (!TenantContext.IsTenant) { return; } var tenantName = TenantContext.CurrentTenant; if (string.IsNullOrWhiteSpace(tenantName)) { return; } //Current tenant is main and connection string is not equal switch to main database if (tenantName.ToLower() == TenantContext.Master.ToLower()) { if (mainConnectionString != dbConnection.ConnectionString) { SwitchDatabase(dbConnection, mainConnectionString); } return; } //get tenant connection string var newConnectionString = TenantContext.GetCurrentTenant(); if (string.IsNullOrWhiteSpace(newConnectionString)) { newConnectionString = mainConnectionString.GetConnectionStringForTenant(tenantName); TenantContext.AddTenant(tenantName, newConnectionString); } SwitchDatabase(dbConnection, newConnectionString); } /// <summary> /// switch database /// </summary> /// <param name="dbConnection"></param> /// <param name="connectionString"></param> private void SwitchDatabase(IDbConnection dbConnection, string connectionString) { //check state if (dbConnection.State != ConnectionState.Closed) { //run in thread connection must dispose. dbConnection.Close(); dbConnection.Dispose(); } //switch database. GetConnection().ConnectionString = connectionString; ConnectionString = connectionString; } public DbContextOptions DbContextOptions { get; set; } #endregion 构造方法 #region GetConnection(获取数据库连接) /// <summary> /// 获取数据库连接 /// </summary> public IDbConnection GetConnection() { return Database.GetDbConnection(); } /// <summary> /// 数据库连接字符串 /// </summary> public string ConnectionString { get; private set; } #endregion GetConnection(获取数据库连接) #region 属性 /// <summary> /// 跟踪号 /// </summary> public Guid TraceId { get; set; } /// <summary> /// 用户会话 /// </summary> public ISession Session { get; set; } #endregion 属性 #region OnConfiguring(配置) /// <summary> /// 配置 /// </summary> /// <param name="builder">配置生成器</param> protected override void OnConfiguring(DbContextOptionsBuilder builder) { EnableLog(builder); } /// <summary> /// 启用日志 /// </summary> protected void EnableLog(DbContextOptionsBuilder builder) { var log = GetLog(); if (IsEnabled(log) == false) { return; } builder.EnableSensitiveDataLogging(); builder.UseLoggerFactory(new LoggerFactory(new[] { GetLogProvider(log) })); } /// <summary> /// 获取日志操作 /// </summary> protected virtual ILog GetLog() { try { return Log.GetLog(EfLog.TraceLogName); } catch { return Log.Null; } } /// <summary> /// 是否启用Ef日志 /// </summary> private bool IsEnabled(ILog log) { return EfConfig.LogLevel != EfLogLevel.Off && log.IsTraceEnabled; } /// <summary> /// 获取日志提供器 /// </summary> protected virtual ILoggerProvider GetLogProvider(ILog log) { return new EfLogProvider(log, this); } #endregion OnConfiguring(配置) #region OnModelCreating(配置映射) /// <summary> /// 配置映射 /// </summary> protected override void OnModelCreating(ModelBuilder modelBuilder) { foreach (var mapper in GetMaps()) { mapper.Map(modelBuilder); } } /// <summary> /// 获取映射配置列表 /// </summary> private IEnumerable<IMap> GetMaps() { var result = GetMapTypes(); return result; } /// <summary> /// 获取映射类型列表 /// </summary> protected virtual IEnumerable<IMap> GetMapTypes() { return Reflection.GetInstancesByInterface<IMap>(); } #endregion OnModelCreating(配置映射) #region SaveChanges(保存更改) /// <summary> /// 保存更改 /// </summary> public override int SaveChanges() { SaveChangesBefore(); return base.SaveChanges(); } /// <summary> /// 保存更改前操作 /// </summary>An error occurred while updating the entries protected virtual void SaveChangesBefore() { foreach (var entry in ChangeTracker.Entries()) { switch (entry.State) { case EntityState.Added: InterceptAddedOperation(entry); break; case EntityState.Modified: InterceptModifiedOperation(entry); break; case EntityState.Deleted: InterceptDeletedOperation(entry); break; } } } /// <summary> /// 拦截添加操作 /// </summary> protected virtual void InterceptAddedOperation(EntityEntry entry) { InitCreationAudited(entry); InitModificationAudited(entry); } /// <summary> /// 初始化创建审计信息 /// </summary> private void InitCreationAudited(EntityEntry entry) { CreationAuditedInitializer.Init(entry.Entity, GetSession()); } /// <summary> /// 获取用户会话 /// </summary> protected virtual ISession GetSession() { return Session; } /// <summary> /// 初始化修改审计信息 /// </summary> private void InitModificationAudited(EntityEntry entry) { ModificationAuditedInitializer.Init(entry.Entity, GetSession()); } /// <summary> /// 拦截修改操作 /// </summary> protected virtual void InterceptModifiedOperation(EntityEntry entry) { InitModificationAudited(entry); } /// <summary> /// 拦截删除操作 /// </summary> protected virtual void InterceptDeletedOperation(EntityEntry entry) { } #endregion SaveChanges(保存更改) #region 获取元数据 /// <summary> /// 获取表名 /// </summary> /// <param name="entity">实体类型</param> public string GetTable(Type entity) { if (entity == null) { return null; } var entityType = Model.FindEntityType(entity); return Extensions.Extensions.SafeString(entityType?.FindAnnotation("Relational:TableName")?.Value); } /// <summary> /// 获取架构 /// </summary> /// <param name="entity">实体类型</param> public string GetSchema(Type entity) { if (entity == null) { return null; } var entityType = Model.FindEntityType(entity); return Extensions.Extensions.SafeString(entityType?.FindAnnotation("Relational:Schema")?.Value); } /// <summary> /// 获取列名 /// </summary> /// <param name="entity">实体类型</param> /// <param name="property">属性名</param> public string GetColumn(Type entity, string property) { if (entity == null || string.IsNullOrWhiteSpace(property)) { return null; } var entityType = Model.FindEntityType(entity); var result = Extensions.Extensions.SafeString(entityType?.GetProperty(property) ?.FindAnnotation("Relational:ColumnName")?.Value); return string.IsNullOrWhiteSpace(result) ? property : result; } #endregion 获取元数据 } }
using Microsoft.EntityFrameworkCore; using WebShop.API.Models; using WebShop.Data.Repository.Contract; namespace WebShop.Data.Repository { public class UnitOfWork : IUnitOfWork { private readonly WebShopContext _context; public UnitOfWork(DbContextOptions options) { _context = new WebShopContext(options); ; Category = new CategoryRepo(_context); Product = new ProductRepo(_context); Order = new OrderRepo(_context); } public ICategoryRepo Category { get; private set; } public IProductRepo Product { get; private set; } public IOrderRepo Order { get; private set; } } }
namespace RosPurcell.Web.ViewModels.Navigation { using RosPurcell.Web.Constants.Umbraco; using Zone.UmbracoMapper; public class MenuItem { public string Url { get; set; } [PropertyMapping(SourcePropertiesForCoalescing = new[] { PropertyAliases.NameInNavigation, PropertyAliases.Name })] public string Name { get; set; } public string Target { get; set; } public bool Active { get; set; } } }
using System.Threading.Tasks; using ExchangeApi.Services.Exchange.Domain.Seedwork; namespace ExchangeApi.Services.Exchange.Domain.AggregatesModel.ExchangeAggregate { public interface IExchangeRepository : IRepository<Exchange> { Exchange Add(Exchange order); void Update(Exchange order); Task<Exchange> GetAsync(int exchangeId); } }
namespace FastFood.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("HUYEN")] public partial class HUYEN { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public HUYEN() { XAs = new HashSet<XA>(); } [Key] public int MaHuyen { get; set; } [Required] [StringLength(50)] public string Ten { get; set; } public int? MaTinh { get; set; } public virtual TINH TINH { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<XA> XAs { get; set; } } }
using System; using System.Collections.Generic; namespace WordCounter { public class RepeatCounter { private string _word; private string _sentence; // private static List<RepeatCounter> _instances = new List<RepeatCounter> {} meaning a private in -Id // might have to put in a private in RepeatCounter?? try it out public RepeatCounter(string word, string sentence) { _word = word; _sentence = sentence; } public string GetWord() { return _word; } public void SetWord(string word) { _word = word; } public string GetSentence() { return _sentence; } public void SetSentence(string sentence) { _sentence = sentence; } public int CountRepeats() { string[] splitSentence = this._sentence.ToLower().Split(' '); string newWord = this._word.Trim().ToLower(); if (this._word == "") { return 0; } int count = 0; foreach (string word in splitSentence) { if (word == newWord) { count++; } } return count; } } }
namespace EPI.PrimitiveTypes { /// <summary> /// The greatest common divisor (GCD) of positive integers x and y is the largest integer d /// such that d divides both x and y evenly. i.e. x mod d = 0 and y mod d = 0 /// Design efficient algorithms for computing the GCD of two numbers. /// Optimal solution should be written without using multiplication, division or the modulus operations /// </summary> public static class GCD { public static int EulersApproach(int x, int y) { if (x == y) { return x; } else if (x > y) { return EulersApproach(x - y, y); } else { return EulersApproach(x, y - x); } } public static int FasterEulersApproach(int x, int y) { if (x == 0) { return y; } if(y == 0) { return x; } if (x > y) { return FasterEulersApproach(x % y, y); } else { return FasterEulersApproach(x, y % x); } } public static int OptimalApproach(int x, int y) { if (x == 0) { return y; } else if (y == 0) { return x; } else if (IsEven(x) && IsEven(y)) // both numbers are even { // right shift by 1 is divide by 2 // left shift by 1 is multiply by 2 return OptimalApproach(x >> 1, y >> 1) << 1; // GCD(20,10) = 2 * GCD(10, 5); } else if(IsEven(x) && !IsEven(y)) // x is even, y is odd { return OptimalApproach(x >> 1, y); // GCD(10,5) = GCD(10/2,5) = GCD(5,5) } else if (!IsEven(x) && IsEven(y))// x is odd, y is even { return OptimalApproach(x, y >> 1); // GCD(7, 80) = GCD(7,80/2) = GCD(7,40) } else // both are odd { if ( x > y) { return OptimalApproach(x - y, y); } else { return OptimalApproach(x, y - x); } } } private static bool IsEven(int x) { return ((x & 1) == 0); } } }
using System.Collections.Generic; using System.Runtime.Serialization; [DataContract] public class RequestOtherSeats { [DataMember] public int SeatsRequested { get; set; } [DataMember] public List<int> PreviousSeates { get; set; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Omega.Lib.APNG { public enum CompressionMethod { Default = 0 } }
using System; namespace Alabo.Mapping.Dynamic { /// <summary> /// 使用动态更新时,忽略该属性,一般不需要更改的字段请设置改属性,比如主键Id,UserId,添加时间等 /// </summary> [AttributeUsage(AttributeTargets.Property)] public class DynamicIgnoreAttribute : Attribute { } }
using System; namespace API.Dtos { public class UserForListDto { public int Id { get; set; } public string Username { get; set; } public string KnownAs { get; set; } public DateTime Created { get; set; } public DateTime LastActive { get; set; } public string Role { get; set; } public Nullable<int> OrganizationId { get; set; } public Nullable<int> FacilityId { get; set; } public Nullable<int> DepartmentId { get; set; } public Nullable<int> StoreId { get; set; } public string Scope { get; set; } } }
using System; using System.ComponentModel; using System.Collections.Generic; using System.Linq; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using Microsoft.SharePoint; using Microsoft.SharePoint.WebControls; using BELCORP.GestorDocumental.BE.Comun; using BELCORP.GestorDocumental.BE.DDP; using BELCORP.GestorDocumental.BL.DDP; using BELCORP.GestorDocumental.Common; using BELCORP.GestorDocumental.Common.Util; using BELCORP.GestorDocumental.BL; using System.IO; using System.Text; using System.Web; using BELCORP.GestorDocumental.Common.Excepcion; namespace BELCORP.GestorDocumental.DDP.WP_Formulario.VWP_DDP_Formulario { [ToolboxItemAttribute(false)] public partial class VWP_DDP_Formulario : WebPart { // Uncomment the following SecurityPermission attribute only when doing Performance Profiling on a farm solution // using the Instrumentation method, and then remove the SecurityPermission attribute when the code is ready // for production. Because the SecurityPermission attribute bypasses the security check for callers of // your constructor, it's not recommended for production purposes. // [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)] //[WebBrowsable(true), // WebDisplayName("Registros por página en Grillas"), // WebDescription("Cantidad de registros a mostrar por cada página de una grilla paginada"), // Personalizable(PersonalizationScope.Shared)] //public string RegistrosPorPagina { get; set; } private static int FilasXPagina = Constantes.REGISTROS_POR_PAGINA; private static string URLSitioPrincipal = SPContext.Current.Site.Url; private static string URLSitioDocumento = SPContext.Current.Web.Url; public VWP_DDP_Formulario() { } protected override void OnInit(EventArgs e) { base.OnInit(e); InitializeControl(); } private void IdentificarPerfil() { #region *** IDENTIFICAMOS ROL DEL USUARIO ACTUAL SPUser oUser = SPContext.Current.Web.CurrentUser; ViewState["EsAdministrador"] = false; ViewState["EsSubAdministrador"] = false; ViewState["EsSubAdministradorAsigando"] = false; ViewState["EsAdministrador"] = ComunBL.Instance.ValidarUsuarioPerteneceGrupoSharePoint(oUser, Constantes.IDENTIFICADOR_GRUPO_ADMINISTRADOR); foreach (SPGroup Grupo in SPContext.Current.Web.Groups) { if (ComunBL.Instance.ValidarUsuarioPerteneceGrupoSharePoint(oUser, Grupo.Name)) { if (Grupo.Name.Contains(Constantes.IDENTIFICADOR_GRUPOS_SUBADMINISTRADORES)) { ViewState["EsSubAdministrador"] = true; } } } #endregion } private void HideRibbon() { SPSecurity.RunWithElevatedPrivileges(() => { SPRibbon objCurrentRibbon = Microsoft.SharePoint.WebControls.SPRibbon.GetCurrent(this.Page); if (objCurrentRibbon != null) { objCurrentRibbon.CommandUIVisible = false; objCurrentRibbon.TrimById("Ribbon.ListForm.Display"); objCurrentRibbon.TrimById("Ribbon.DocLibListForm.Edit"); } }); } protected void Page_Load(object sender, EventArgs e) { URLSitioPrincipal = SPContext.Current.Site.Url; URLSitioDocumento = SPContext.Current.Web.Url; RecargarSelectoresPersonas(); if (!Page.IsPostBack) { try { hdfSessionUsuario.Value = Guid.NewGuid().ToString(); HideRibbon(); ///Guardamos el valor de la URL del sitio actual hdfUrlSitio.Value = SPContext.Current.Site.Url; hdfUrlWebActual.Value = SPContext.Current.Web.Url; IdentificarPerfil(); // *** CARGAR COMBOS *** CargarComboTipoPlanMaestro(); CargarComboGrupoSeguridad(); CargarComboClasificacionDocumento(); CargarComboMetodoAnalisisPrincipal(); CargarComboAreaPrincipal(); if (Page.Request.QueryString["TD"] != null) { hdfCodigoTipoDocumento.Value = Page.Request.QueryString["TD"]; TipoDocumentalBE oTipoDocumentalBE = TipoDocumentalBL.Instance.ObtenerPorCodigo(SPContext.Current.Site.RootWeb, hdfCodigoTipoDocumento.Value); hdfIdTipoDocumento.Value = oTipoDocumentalBE.ID.ToString(); MostrarCamposPorTipoDocumental(hdfIdTipoDocumento.Value); if (Page.Request.QueryString["IDNV"] == null) { #region *** CUANDO ES DOCUMENTO NUEVO *** hdfIdDocumentoDDP.Value = Constantes.Caracteres.Cero; EstablecerValoresDocumentoNuevo(oTipoDocumentalBE.Nombre); MostrarCamposPorEstado(true); //ControlarAcciones(true); gvReferenciaA.DataSource = null; gvReferenciadoPor.DataSource = null; gvHistorialFlujo.DataSource = null; gvHistorialVersiones.DataSource = null; gvReferenciaA.DataBind(); gvReferenciadoPor.DataBind(); gvHistorialFlujo.DataBind(); gvHistorialVersiones.DataBind(); #endregion } else { #region *** CUANDO ES UNA NUEVA VERSIÓN *** hdfIdDocumentoDDP.Value = Page.Request.QueryString["IDNV"]; string URLSitioDocumentoPublicado = URLSitioDocumento + Constantes.URL_SUBSITIO_PUBLICADO; DocumentoDDPBE oDocumentoDDPBE = DocumentoDDPBL.Instance.ObtenerXId(URLSitioDocumentoPublicado, oTipoDocumentalBE.Biblioteca, int.Parse(hdfIdDocumentoDDP.Value)); TipoDocumentalBE TipoDocumental = TipoDocumentalBL.Instance.ObtenerPorCodigo(URLSitioPrincipal, hdfCodigoTipoDocumento.Value); List<DocumentoDDPBE> lst_DocumentoEnFlujo = DocumentoDDPBL.Instance.ObtenerListaDocumentosEnFlujoPorCodigo( oDocumentoDDPBE.CodigoDocumento, TipoDocumental.Biblioteca, hdfUrlSitio.Value); lst_DocumentoEnFlujo = lst_DocumentoEnFlujo.FindAll(X => X.Eliminado == false); if (lst_DocumentoEnFlujo.Count <= 0) { //No existen versiones en flujo del documento, se puede continuar CargarParaMostrar(oDocumentoDDPBE); EstablecerValoresNuevaVersion(oTipoDocumentalBE); MostrarCamposPorEstado(true); #region Cargar Archivo original SPFile FileOriginal = null; if (!string.IsNullOrEmpty(oDocumentoDDPBE.UrlDocumento_ORG)) FileOriginal = ComunBL.Instance.ObtenerSPFile(URLSitioDocumentoPublicado, oDocumentoDDPBE.UrlDocumento_ORG); else FileOriginal = ComunBL.Instance.ObtenerSPFile(URLSitioDocumentoPublicado, oDocumentoDDPBE.UrlDocumento); string TituloTemp = Guid.NewGuid().ToString() + Path.GetExtension(FileOriginal.Name); string URLDocumento = URLSitioPrincipal + "/" + ListasGestorDocumental.Temporal + "/" + TituloTemp; int IdDocumentoTemporal = DocumentoDDPBL.UploadAdjuntoTemporal(URLSitioPrincipal, URLDocumento, FileOriginal.OpenBinaryStream()); DocumentoCargadoBE oDocumentoCargadoBE = new DocumentoCargadoBE(); oDocumentoCargadoBE.URLDocumento = URLDocumento; oDocumentoCargadoBE.NombreDocumento = oDocumentoDDPBE.CodigoDocumento + " [Archivo Original]"; oDocumentoCargadoBE.IdDocumento = IdDocumentoTemporal; oDocumentoCargadoBE.Extension = Path.GetExtension(FileOriginal.Name); oDocumentoTemporal = oDocumentoCargadoBE; List<DocumentoCargadoBE> oListDocumentoCargadoBE = new List<DocumentoCargadoBE>(); oListDocumentoCargadoBE.Add(oDocumentoCargadoBE); ListarAdjuntosTemporales(oListDocumentoCargadoBE); DivAdjuntosSolicitante.Visible = true; #endregion //ControlarAcciones(true); CargarHistorialVersiones(txtCodigoDocumentoCabecera.Text, oTipoDocumentalBE.Biblioteca, Convert.ToInt32(txtVersion.Text)); CargarHistorialFlujo(txtCodigoDocumentoCabecera.Text, Convert.ToInt32(txtVersion.Text)); CargarTabReferencias(txtCodigoDocumentoCabecera.Text); } else { string Funcion = "AlertaAvisoRedirigir"; string URL = SPContext.Current.Site.Url; string Mensaje = "Existe una versión del documento, actualmente se encuentra en flujo."; WebUtil.AlertRedirectServer(Page, this.GetType(), TipoAlerta.Aviso, Funcion, Mensaje, URL); } #endregion } } else { if (Page.Request.QueryString["ID"] != null) { #region *** CUANDO ES DOCUMENTO EXISTENTE *** hdfIdDocumentoDDP.Value = Page.Request.QueryString["ID"]; //// #region Mostrar Opción Atender Tarea hdfIdTarea.Value = Page.Request.QueryString["IDT"]; hdfUrlTarea.Value = Page.Request.QueryString["urlt"]; if (!string.IsNullOrEmpty(hdfIdTarea.Value)) ValidarAtenderTarea(Convert.ToInt32(hdfIdTarea.Value)); else if (!string.IsNullOrEmpty(hdfUrlTarea.Value)) { Uri UriTarea = new Uri(hdfUrlTarea.Value); hdfIdTarea.Value = HttpUtility.ParseQueryString(UriTarea.Query).Get("ID"); ValidarAtenderTarea(Convert.ToInt32(hdfIdTarea.Value)); } else btnAtenderTarea.Visible = false; #endregion DocumentoDDPBE oDocumentoDDPBE = DocumentoDDPBL.Instance.ObtenerXId(URLSitioDocumento, SPContext.Current.List.Title, int.Parse(hdfIdDocumentoDDP.Value)); if (oDocumentoDDPBE.Eliminado) { string Mensaje = String.Format(Mensajes.Error.DocumentoEliminado, oDocumentoDDPBE.Version.ToString(), oDocumentoDDPBE.CodigoDocumento); WebUtil.AlertRedirectServer(Page, this.GetType(), TipoAlerta.Aviso, "AlertaAvisoRedirigir", Mensaje, SPContext.Current.Site.Url); } //// TipoDocumentalBE oTipoDocumentalBE = TipoDocumentalBL.Instance.ObtenerPorId(SPContext.Current.Site.RootWeb, oDocumentoDDPBE.TipoDocumental.ID); hdfIdTipoDocumento.Value = oTipoDocumentalBE.ID.ToString(); hdfCodigoTipoDocumento.Value = oTipoDocumentalBE.Codigo; MostrarCamposPorTipoDocumental(hdfIdTipoDocumento.Value); CargarParaMostrar(oDocumentoDDPBE); MostrarCamposPorEstado(false); //ControlarAcciones(false); CargarDocumentos(oDocumentoDDPBE); CargarHistorialVersiones(txtCodigoDocumentoCabecera.Text, SPContext.Current.List.Title, oDocumentoDDPBE.Version, oDocumentoDDPBE); CargarHistorialFlujo(txtCodigoDocumentoCabecera.Text, oDocumentoDDPBE.Version, oDocumentoDDPBE); CargarTabReferencias(txtCodigoDocumentoCabecera.Text); #endregion } } //hdfModificoDatos.Value ="PrimeraCarga"; ddlGrupoSeguridad.Attributes.Add("onchange", "javascript:ModificoDatos('ddlGrupoSeguridad')"); ddlClasificacion.Attributes.Add("onchange", "javascript:ModificoDatos('ddlClasificacion')"); ddlSistemaCalidad.Attributes.Add("onchange", "javascript:ModificoDatos('ddlSistemaCalidad')"); ddlCorporativo.Attributes.Add("onchange", "javascript:OcultarPaisCompania()"); ddlMacroProceso.Attributes.Add("onchange", "javascript:CambioMacroProceso()"); ddlProceso.Attributes.Add("onchange", "javascript:CambioProceso()"); ddlTipoPlanMaestro.Attributes.Add("onchange", "javascript:ModificoDatos('ddlTipoPlanMaestro')"); ddlMetodoAnalisisPrincipal.Attributes.Add("onchange", "javascript:ModificoDatos('ddlMetodoAnalisisPrincipal')"); ddlDistribucionFisica.Attributes.Add("onchange", "javascript:OcultarAreaPrincipal()"); //ddlAreaPrincipal.Attributes.Add("onchange", "javascript:ModificoDatos('ddlAreaPrincipal')"); //ddlSubArea.Attributes.Add("onchange", "javascript:ModificoDatos('ddlSubArea')"); ddlNotificacionCorporativa.Attributes.Add("onchange", "javascript:ModificoDatos('ddlNotificacionCorporativa')"); } catch (Exception ex) { string strGUIDReferencia = Logging.RegistrarMensajeLogSharePoint(Constantes.CATEGORIA_LOG_FORM_GESTOR_LOAD, "load", ex); WebUtil.AlertServer(Page, this.GetType(), TipoAlerta.Error, "AlertaAviso", ex.Message + " : : " + ex.StackTrace); } } } private void RecargarSelectoresPersonas() { if (ViewState["ElaboradorAprobador_SharePointGroupID"] != null) { cppElaborador.SharePointGroupID = (int)ViewState["ElaboradorAprobador_SharePointGroupID"]; cppAprobador.SharePointGroupID = (int)ViewState["ElaboradorAprobador_SharePointGroupID"]; } if (ViewState["Revisor_SharePointGroupID"] != null) { cppRevisor.SharePointGroupID = (int)ViewState["Revisor_SharePointGroupID"]; } if (ViewState["LectoresNoPublicos"] != null) { PeopleEditor pe = new PeopleEditor(); PickerEntity entity = new PickerEntity(); List<UsuarioBE> ListLectoresNoPublicos = new List<UsuarioBE>(); List<UsuarioBE> ListLectoresNoPublicosEnCPP = new List<UsuarioBE>(); ListLectoresNoPublicos = (List<UsuarioBE>)ViewState["LectoresNoPublicos"]; if (cppLectoresNoPublicos.AllEntities.Count > 0 || (string)ViewState["btnModificarDatos_Click"] == "True") { List<String> oSPUCLectoresNoPublicos = Utilitarios.GetColeccionLoginName(cppLectoresNoPublicos); UsuarioBE oUsuario = null; if (oSPUCLectoresNoPublicos != null) { if (oSPUCLectoresNoPublicos.Count > 0) { foreach (String LoginName in oSPUCLectoresNoPublicos) { oUsuario = new UsuarioBE(); oUsuario.ID = Utilitarios.GetUserPorLoginName(SPContext.Current.Site.Url, LoginName).ID;// oUser.ID; oUsuario.LoginName = LoginName; ListLectoresNoPublicosEnCPP.Add(oUsuario); } } } ViewState["LectoresNoPublicos"] = ListLectoresNoPublicosEnCPP; } else { if ((string)ViewState["btnModificarDatos_Click"] != "True") { // ViewState["LectoresNoPublicos"] = null; //} //else //{ foreach (UsuarioBE oUsuario in ListLectoresNoPublicos) { entity = new PickerEntity(); pe = new PeopleEditor(); entity.Key = oUsuario.DisplayName; entity = pe.ValidateEntity(entity); entity.IsResolved = true; cppLectoresNoPublicos.AddEntities(new List<PickerEntity> { entity }); txtLectoresNoPublicos.Text = txtLectoresNoPublicos.Text + "; " + oUsuario.DisplayName; txtLectoresNoPublicos.Text = txtLectoresNoPublicos.Text.TrimStart(';'); } } } } if (ViewState["Aprobador"] != null) { if ((String)ViewState["Aprobador"] != String.Empty && cppAprobador.AllEntities.Count == 0) { PeopleEditor pe = new PeopleEditor(); PickerEntity entity = new PickerEntity(); entity.Key = (String)ViewState["Aprobador"]; entity = pe.ValidateEntity(entity); entity.IsResolved = true; cppAprobador.AddEntities(new List<PickerEntity> { entity }); txtAprobador.Text = (String)ViewState["AprobadorNombre"]; } } if (ViewState["Elaborador"] != null) { if ((String)ViewState["Elaborador"] != String.Empty && cppElaborador.AllEntities.Count == 0) { PeopleEditor pe = new PeopleEditor(); PickerEntity entity = new PickerEntity(); entity.Key = (String)ViewState["Elaborador"]; entity = pe.ValidateEntity(entity); entity.IsResolved = true; cppElaborador.AddEntities(new List<PickerEntity> { entity }); txtElaborador.Text = (String)ViewState["ElaboradorNombre"]; } } if (SeccionTipoPlanMaestro.Visible == false) { if (ViewState["Revisor"] != null) { if ((String)ViewState["Revisor"] != String.Empty && cppRevisor.AllEntities.Count == 0) { PeopleEditor pe = new PeopleEditor(); PickerEntity entity = new PickerEntity(); entity.Key = (String)ViewState["Revisor"]; entity = pe.ValidateEntity(entity); entity.IsResolved = true; cppRevisor.AddEntities(new List<PickerEntity> { entity }); txtRevisor.Text = (String)ViewState["RevisorNombre"]; } } } } private void EstablecerValoresNuevaVersion(TipoDocumentalBE oTipoDocumento) { txtEstado.Text = EstadosDDP.Contribucion; txtEstadoCabecera.Text = EstadosDDP.Contribucion; hdfIdDocumentoDDP.Value = Constantes.Caracteres.Cero; //txtVersion.Text = (Convert.ToInt32(txtVersion.Text) + 1).ToString(); int valorVersionReal = Convert.ToInt32(txtVersion.Text) + 1; int valorVersionFlujo = 0; List<DocumentoDDPBE> lstDocumentoEnFlujo = DocumentoDDPBL.Instance.ObtenerListaDocumentosEnFlujoPorCodigo(txtCodigoDocumentoCabecera.Text, oTipoDocumento.Biblioteca, hdfUrlSitio.Value); if (lstDocumentoEnFlujo.Count > 0)// && oDocumentoEnFlujo.Eliminado) { //txtVersion.Text = (lstDocumentoEnFlujo.OrderByDescending(x => x.Version).First().Version + 1).ToString(); valorVersionFlujo = lstDocumentoEnFlujo.OrderByDescending(x => x.Version).First().Version + 1; } txtVersion.Text = valorVersionReal > valorVersionFlujo ? valorVersionReal.ToString() : valorVersionFlujo.ToString(); txtContribuidor.Text = SPContext.Current.Web.CurrentUser.Name; hdfIdContribuidor.Value = SPContext.Current.Web.CurrentUser.ID.ToString(); gvAdjuntosSolicitante.DataSource = null; gvAdjuntosSolicitante.DataBind(); //fupArchivo.Visible = true; DivAdjuntosSolicitante.Visible = false; //cppAprobador.AllEntities.Clear(); //cppElaborador.AllEntities.Clear(); //cppRevisor.AllEntities.Clear(); } private void CargarHistorialFlujo(string pe_CodigoDocumento, int pe_Version, DocumentoDDPBE oDocumentoDDPBE = null) { List<HistorialFlujoBE> lstHistorial = HistorialFlujoDDPBL.Instance.ObtenerListaHistorial(pe_CodigoDocumento, pe_Version); if (lstHistorial.Count <= 0 && oDocumentoDDPBE != null) { HistorialFlujoBE oHistorialFlujo = new HistorialFlujoBE(); oHistorialFlujo.CodigoDocumento = oDocumentoDDPBE.CodigoDocumento; oHistorialFlujo.Version = oDocumentoDDPBE.Version; oHistorialFlujo.Accion = Mensajes.HistorialGestorDocumental.EnviaContribuidor; oHistorialFlujo.Estado = EstadosDDP.Contribucion; oHistorialFlujo.FechaAccion = oDocumentoDDPBE.FechaRegistro; oHistorialFlujo.Usuario = oDocumentoDDPBE.Contribuidor.DisplayName; oHistorialFlujo.Comentario = string.Empty;// oDocumentoDDPBE.Comentario;//Comentado para que el campo comentario no se registre en el historial HistorialFlujoDDPBL.Instance.CrearNuevoRegistroHistorialFlujo(oHistorialFlujo); lstHistorial.Add(oHistorialFlujo); } gvHistorialFlujo.DataSource = lstHistorial; gvHistorialFlujo.DataBind(); } private void CargarHistorialVersiones(string pe_CodigoDocumento, string Biblioteca, int versionActual, DocumentoDDPBE oDocumentoDDPBE = null) { List<VersionBE> lstVersiones = VersionBL.Instance.ObtenerListaHistorial(URLSitioPrincipal, pe_CodigoDocumento, Biblioteca); VersionBE oCurrent = lstVersiones.Find(x => x.Version == versionActual); if (oCurrent == null && oDocumentoDDPBE != null) { oDocumentoDDPBE.UrlDocumento = oDocumentoDDPBE.URLDispForm; DocumentoDDPBL.Instance.CrearNuevoRegistroDocumento(oDocumentoDDPBE); HistorialFlujoBE oHistorialFlujo = new HistorialFlujoBE(); oHistorialFlujo.CodigoDocumento = oDocumentoDDPBE.CodigoDocumento; oHistorialFlujo.Version = oDocumentoDDPBE.Version; oHistorialFlujo.Accion = Mensajes.HistorialGestorDocumental.EnviaContribuidor; oHistorialFlujo.Estado = EstadosDDP.Contribucion; oHistorialFlujo.FechaAccion = oDocumentoDDPBE.FechaRegistro; oHistorialFlujo.Usuario = oDocumentoDDPBE.Contribuidor.DisplayName; oHistorialFlujo.Comentario = string.Empty;// oDocumentoDDPBE.Comentario;//Comentado para que el campo comentario no se registre en el historial HistorialFlujoDDPBL.Instance.CrearNuevoRegistroHistorialFlujo(oHistorialFlujo); lstVersiones = VersionBL.Instance.ObtenerListaHistorial(URLSitioPrincipal, pe_CodigoDocumento, Biblioteca); } gvHistorialVersiones.DataSource = lstVersiones; gvHistorialVersiones.DataBind(); } private void CargarParaMostrar(DocumentoDDPBE oDocumentoDDPBE) { if (oDocumentoDDPBE != null) { txtCodigoDocumentoCabecera.Text = oDocumentoDDPBE.CodigoDocumento; //Código UCM if (!string.IsNullOrEmpty(oDocumentoDDPBE.CodigoUCM)) { hdfCodigoUCM.Value = oDocumentoDDPBE.CodigoUCM; txtCodigoUCM.Text = string.Format("{0}", oDocumentoDDPBE.CodigoUCM); txtCodigoUCM.Visible = true; } txtTituloCabecera.Text = oDocumentoDDPBE.Titulo; txtTituloInput.Text = oDocumentoDDPBE.Titulo; txtVersion.Text = oDocumentoDDPBE.Version.ToString(); txtEstado.Text = oDocumentoDDPBE.Estado; txtEstadoCabecera.Text = oDocumentoDDPBE.Estado; txtTipoDocumento.Text = oDocumentoDDPBE.TipoDocumental.Nombre; ddlGrupoSeguridad.SelectedValue = oDocumentoDDPBE.GrupoSeguridad.Title; txtAreaElaborador.Text = oDocumentoDDPBE.AreaElaborador; ddlClasificacion.SelectedValue = oDocumentoDDPBE.ClasificacionDocumentos; ddlSistemaCalidad.SelectedValue = oDocumentoDDPBE.SistemaCalidad; txtEstado.Text = oDocumentoDDPBE.Estado; if (oDocumentoDDPBE.FechaPublicacion != null) if (oDocumentoDDPBE.FechaPublicacion.Year != 1) txtFechaPublicacion.Text = oDocumentoDDPBE.FechaPublicacion.ToString("dd/MM/yyyy"); if (oDocumentoDDPBE.FechaCaducidad != null) if (oDocumentoDDPBE.FechaCaducidad.Year != 1) txtFechaCaducidad.Text = oDocumentoDDPBE.FechaCaducidad.ToString("dd/MM/yyyy"); txtComentario.Text = oDocumentoDDPBE.Comentario; txtModificandosePor.Text = oDocumentoDDPBE.ModificandosePor; if (oDocumentoDDPBE.TipoPlanMaestro != null && oDocumentoDDPBE.TipoPlanMaestro.Title != String.Empty) { if (oDocumentoDDPBE.Estado == EstadosDDP.Revision) txtModificandosePor.Text = TareaDDPBL.Instance.ObtenerRevisoresTareasPorCodigoDocumento(oDocumentoDDPBE.CodigoDocumento, hdfUrlSitio.Value); } if (oDocumentoDDPBE.TipoPlanMaestro.Title != null) { ddlTipoPlanMaestro.SelectedValue = oDocumentoDDPBE.TipoPlanMaestro.Title.ToString(); txtRevisoresPM.Text = oDocumentoDDPBE.RevisoresPM; //ObtenerNombresRevisoresPM(); } ddlCorporativo.SelectedValue = oDocumentoDDPBE.Corporativo.ToString(); if (oDocumentoDDPBE.MetodoAnalisisPrincipal != null) { if (oDocumentoDDPBE.MetodoAnalisisPrincipal.Title != null) { ddlMetodoAnalisisPrincipal.SelectedValue = oDocumentoDDPBE.MetodoAnalisisPrincipal.Title.ToString(); } } ddlDistribucionFisica.SelectedValue = oDocumentoDDPBE.DistribucionFisica.ToString(); //ddlAreaPrincipal.SelectedValue = oDocumentoDDPBE.AreaPrincipalID.ToString(); //CargarComboSubArea(); //ddlSubArea.SelectedValue = oDocumentoDDPBE.SubAreaID.ToString(); ViewState["CompaniasElegidas"] = oDocumentoDDPBE.PaisCompanias; gvCompaniaPais.DataSource = ViewState["CompaniasElegidas"]; gvCompaniaPais.DataBind(); ViewState["SubAreasElegidas"] = oDocumentoDDPBE.AreaSubAreas; gvAreaSubArea.DataSource = ViewState["SubAreasElegidas"]; gvAreaSubArea.DataBind(); CargarComboMacroProceso(); ddlMacroProceso.SelectedValue = oDocumentoDDPBE.MacroProceso.Id.ToString(); CargarComboProceso(); ddlProceso.SelectedValue = oDocumentoDDPBE.Proceso.Id.ToString(); if (oDocumentoDDPBE.PoliticaCalidad.Title != null) { txtPoliticaCalidad.Text = oDocumentoDDPBE.PoliticaCalidad.Concatenado; hdfIdPoliticaCalidad.Value = oDocumentoDDPBE.PoliticaCalidad.Id.ToString(); } txtManualCalidad.Text = oDocumentoDDPBE.ManualCalidad.Concatenado; hdfIdManualCalidad.Value = oDocumentoDDPBE.ManualCalidad.Id.ToString(); txtAcuerdoNivelServicio.Text = oDocumentoDDPBE.AcuerdoNivelesServicio.Concatenado; hdfIdAcuerdoNivelServicio.Value = oDocumentoDDPBE.AcuerdoNivelesServicio.Id.ToString(); txtPlanMaestro.Text = oDocumentoDDPBE.PlanMaestro.Concatenado; hdfIdPlanMaestro.Value = oDocumentoDDPBE.PlanMaestro.Id.ToString(); txtDescripcionProcesos.Text = oDocumentoDDPBE.DescripcionProcesos.Concatenado; hdfIdDescripcionProcesos.Value = oDocumentoDDPBE.DescripcionProcesos.Id.ToString(); txtProcedimiento.Text = oDocumentoDDPBE.Procedimiento.Concatenado; hdfIdProcedimiento.Value = oDocumentoDDPBE.Procedimiento.Id.ToString(); txtInstruccion.Text = oDocumentoDDPBE.Instruccion.Concatenado; hdfIdInstruccion.Value = oDocumentoDDPBE.Instruccion.Id.ToString(); if (oDocumentoDDPBE.MetodoAnalisis.Id > 0) { txtMetodoAnalisis.Text = oDocumentoDDPBE.MetodoAnalisis.Concatenado; hdfIdMetodoAnalisis.Value = oDocumentoDDPBE.MetodoAnalisis.Id.ToString(); } else if (oDocumentoDDPBE.MetodoAnalisisExterno.Id > 0) { txtMetodoAnalisis.Text = oDocumentoDDPBE.MetodoAnalisisExterno.Concatenado; hdfIdMetodoAnalisis.Value = oDocumentoDDPBE.MetodoAnalisisExterno.Id.ToString(); } txtPolitica.Text = oDocumentoDDPBE.Politica.Concatenado; hdfIdPolitica.Value = oDocumentoDDPBE.Politica.Id.ToString(); txtContribuidor.Text = oDocumentoDDPBE.Contribuidor.DisplayName; hdfIdContribuidor.Value = oDocumentoDDPBE.Contribuidor.ID.ToString(); if (oDocumentoDDPBE.BloqueadoPubPara.ID > 0) { hdfIdBloqueadoPubPara.Value = oDocumentoDDPBE.BloqueadoPubPara.ID.ToString(); ViewState["BloqueadoPubPara"] = oDocumentoDDPBE.BloqueadoPubPara; } if (oDocumentoDDPBE.BloqueadoVCPara.ID > 0) { hdfIdBloqueadoVCPara.Value = oDocumentoDDPBE.BloqueadoVCPara.ID.ToString(); ViewState["BloqueadoVCPara"] = oDocumentoDDPBE.BloqueadoVCPara; } if (!string.IsNullOrEmpty(oDocumentoDDPBE.Aprobador.DisplayName)) { PeopleEditor pe = new PeopleEditor(); PickerEntity entity = new PickerEntity(); ViewState["Aprobador"] = oDocumentoDDPBE.Aprobador.LoginName; ViewState["AprobadorNombre"] = oDocumentoDDPBE.Aprobador.DisplayName; ViewState["AprobadorInicial"] = oDocumentoDDPBE.Aprobador.LoginName; entity.Key = oDocumentoDDPBE.Aprobador.LoginName; entity = pe.ValidateEntity(entity); entity.IsResolved = true; cppAprobador.AddEntities(new List<PickerEntity> { entity }); txtAprobador.Text = oDocumentoDDPBE.Aprobador.DisplayName; } if (!string.IsNullOrEmpty(oDocumentoDDPBE.Elaborador.DisplayName)) { PeopleEditor pe = new PeopleEditor(); PickerEntity entity = new PickerEntity(); ViewState["Elaborador"] = oDocumentoDDPBE.Elaborador.LoginName; ViewState["ElaboradorNombre"] = oDocumentoDDPBE.Elaborador.DisplayName; ViewState["ElaboradorInicial"] = oDocumentoDDPBE.Elaborador.LoginName; entity.Key = oDocumentoDDPBE.Elaborador.LoginName; entity = pe.ValidateEntity(entity); entity.IsResolved = true; cppElaborador.AddEntities(new List<PickerEntity> { entity }); txtElaborador.Text = oDocumentoDDPBE.Elaborador.DisplayName; } if (SeccionTipoPlanMaestro.Visible == false) { if (!string.IsNullOrEmpty(oDocumentoDDPBE.Revisor.DisplayName)) { PeopleEditor pe = new PeopleEditor(); PickerEntity entity = new PickerEntity(); ViewState["Revisor"] = oDocumentoDDPBE.Revisor.LoginName; ViewState["RevisorNombre"] = oDocumentoDDPBE.Revisor.DisplayName; ViewState["RevisorInicial"] = oDocumentoDDPBE.Revisor.LoginName; entity.Key = oDocumentoDDPBE.Revisor.LoginName; entity = pe.ValidateEntity(entity); entity.IsResolved = true; cppRevisor.AddEntities(new List<PickerEntity> { entity }); txtRevisor.Text = oDocumentoDDPBE.Revisor.DisplayName; } } if (oDocumentoDDPBE.LectoresNoPublicos.Count > 0) { ViewState["LectoresNoPublicos"] = oDocumentoDDPBE.LectoresNoPublicos; PeopleEditor pe = new PeopleEditor(); PickerEntity entity = new PickerEntity(); foreach (UsuarioBE oUsuario in oDocumentoDDPBE.LectoresNoPublicos) { entity = new PickerEntity(); pe = new PeopleEditor(); entity.Key = oUsuario.LoginName; entity = pe.ValidateEntity(entity); entity.IsResolved = true; cppLectoresNoPublicos.AddEntities(new List<PickerEntity> { entity }); txtLectoresNoPublicos.Text = txtLectoresNoPublicos.Text + "; " + oUsuario.DisplayName; txtLectoresNoPublicos.Text = txtLectoresNoPublicos.Text.TrimStart(';'); ViewState["LectoresNoPublicosInicial"] = ViewState["LectoresNoPublicosInicial"] + "; " + entity.Key; ViewState["LectoresNoPublicosInicial"] = ((String)ViewState["LectoresNoPublicosInicial"]).TrimStart(';'); } } if (oDocumentoDDPBE.NotificacionCorporativa > -1) { ddlNotificacionCorporativa.SelectedValue = oDocumentoDDPBE.NotificacionCorporativa.ToString(); } ViewState["ListaPreseleccionadosConfirmados"] = oDocumentoDDPBE.UsuariosNotificarEnPublicacionA; EstablecerCentroDeCostos(); } } private void CargarDocumentos(DocumentoDDPBE oDocumentoDDPBE) { #region Carga de Documentos List<DocumentoCargadoBE> oListDocumentoCargadoBE = new List<DocumentoCargadoBE>(); #region Archivo Principal DocumentoCargadoBE oDocumentoPrincipal = new DocumentoCargadoBE(); oDocumentoPrincipal.URLDocumento = oDocumentoDDPBE.UrlDocumento; oDocumentoPrincipal.Extension = Path.GetExtension(oDocumentoDDPBE.UrlDocumento); oDocumentoTemporal = oDocumentoPrincipal; oDocumentoPrincipal.IdDocumento = oDocumentoDDPBE.ID; oDocumentoPrincipal.NombreDocumento = oDocumentoDDPBE.CodigoDocumento; #endregion #region Copia No Controlada Imprimible DocumentoCargadoBE oDocumentoCNC = null; if (!string.IsNullOrEmpty(oDocumentoDDPBE.UrlDocumento_CNC)) { oDocumentoCNC = new DocumentoCargadoBE(); oDocumentoCNC.URLDocumento = oDocumentoDDPBE.UrlDocumento_CNC; oDocumentoCNC.NombreDocumento = oDocumentoDDPBE.CodigoDocumento + " [Copia no controlada]"; //oListDocumentoCargadoBE.Add(oDocumentoCC); } #endregion #region Copia Controlada DocumentoCargadoBE oDocumentoCC = null; if (!string.IsNullOrEmpty(oDocumentoDDPBE.UrlDocumento_CC)) { oDocumentoCC = new DocumentoCargadoBE(); oDocumentoCC.URLDocumento = oDocumentoDDPBE.UrlDocumento_CC; oDocumentoCC.NombreDocumento = oDocumentoDDPBE.CodigoDocumento + " [Copia controlada]"; //oListDocumentoCargadoBE.Add(oDocumentoCC); } #endregion #region Archivo Original DocumentoCargadoBE oDocumentoORG = null; if (!string.IsNullOrEmpty(oDocumentoDDPBE.UrlDocumento_ORG)) { oDocumentoORG = new DocumentoCargadoBE(); oDocumentoORG.URLDocumento = oDocumentoDDPBE.UrlDocumento_ORG; oDocumentoORG.NombreDocumento = oDocumentoDDPBE.CodigoDocumento + " [Archivo Original]"; //oListDocumentoCargadoBE.Add(oDocumentoORG); } #endregion switch (oDocumentoDDPBE.Estado) { case EstadosDDP.Publicado: case EstadosDDP.Caducado: case EstadosDDP.Obsoleto: if ((bool)ViewState["EsAdministrador"] || (bool)ViewState["EsSubAdministradorAsigando"]) { if (oDocumentoCNC != null) oListDocumentoCargadoBE.Add(oDocumentoCNC); else if (oDocumentoPrincipal != null) oListDocumentoCargadoBE.Add(oDocumentoPrincipal); if (oDocumentoCC != null) oListDocumentoCargadoBE.Add(oDocumentoCC); if (oDocumentoORG != null) oListDocumentoCargadoBE.Add(oDocumentoORG); } else { if (oDocumentoPrincipal != null) { oDocumentoPrincipal.NombreDocumento = oDocumentoDDPBE.CodigoDocumento + " [Copia no controlada]"; oListDocumentoCargadoBE.Add(oDocumentoPrincipal); } if (oDocumentoORG != null) { List<MacroProcesoBE> oMP = (List<MacroProcesoBE>)ViewState["MacroProcesos"]; if (oMP != null) { MacroProcesoBE oMacroProceso = oMP.Find(oItem => oItem.Id.ToString() == ddlMacroProceso.SelectedItem.Value); if (oMacroProceso != null && ComunBL.Instance.ValidarUsuarioPerteneceGrupoSharePoint(SPContext.Current.Web.CurrentUser, oMacroProceso.GrupoSeguridad.DisplayName)) { oListDocumentoCargadoBE.Add(oDocumentoORG); } } } } break; default: if (oDocumentoPrincipal != null) oListDocumentoCargadoBE.Add(oDocumentoPrincipal); break; } gvAdjuntosSolicitante.DataSource = oListDocumentoCargadoBE; gvAdjuntosSolicitante.DataBind(); gvAdjuntosSolicitante.Visible = true; DivAdjuntosSolicitante.Visible = true; //DivfupArchivo.Visible = false; #endregion } private void EstablecerValoresDocumentoNuevo(string TipoDocumento) { txtTipoDocumento.Text = TipoDocumento; txtCodigoDocumentoCabecera.Text = String.Empty; txtTituloCabecera.Text = String.Empty; txtVersion.Text = Constantes.Caracteres.Uno; txtEstadoCabecera.Text = EstadosDDP.Contribucion; txtFechaPublicacion.Text = String.Empty; txtFechaCaducidad.Text = String.Empty; txtEstado.Text = EstadosDDP.Contribucion; txtContribuidor.Text = SPContext.Current.Web.CurrentUser.Name; hdfIdContribuidor.Value = SPContext.Current.Web.CurrentUser.ID.ToString(); txtModificandosePor.Text = SPContext.Current.Web.CurrentUser.Name; } private void MostrarCamposPorTipoDocumental(string IdTipoDocumental) { List<ControlesBE> oListaControlesBE = new List<ControlesBE>(); oListaControlesBE = ControlesBL.Instance.ObtenerLista(SPContext.Current.Site.RootWeb, IdTipoDocumental); foreach (ControlesBE Control in oListaControlesBE) { Control ControlDiv = FindControl(Control.Title); if (ControlDiv != null) ControlDiv.Visible = true; } } private void HabilitarEdicionCamposUsuario(bool Habilitar) { if (SeccionElaborador.Visible == true) { cppElaborador.Visible = Habilitar; txtElaborador.Visible = !Habilitar; AbrirBuscadorElaborador.Visible = Habilitar; } if (SeccionAprobador.Visible == true) { cppAprobador.Visible = Habilitar; txtAprobador.Visible = !Habilitar; AbrirBuscadorAprobador.Visible = Habilitar; } if (SeccionRevisor.Visible == true) { cppRevisor.Visible = Habilitar; txtRevisor.Visible = !Habilitar; AbrirBuscadorRevisor.Visible = Habilitar; } } private void MostrarCamposPorEstado(bool EsNuevo) { if (EsNuevo) { DivfupArchivo.Visible = true; gvCompaniaPais.Columns[2].Visible = true; gvAreaSubArea.Columns[2].Visible = true; pnlDatosPrincipalesSecundarios.Enabled = true; pnlUsuariosParticipantes.Enabled = true; pnlDatosAdicionales.Enabled = true; pnlAcciones.Visible = true; divBotonesContribuidor.Visible = true; //AbrirBuscadorCentroCostos.Visible = true; //btnAbrirListaCentroCostos.Visible = false; HabilitarEdicionCamposUsuario(true); MostrarCamposNotificacion(false); } else { bool SoloLectura = true; SPUser oUsuarioActual = SPContext.Current.Web.CurrentUser; bool EsSubAdministradorAsignado = false; List<CompaniaBE> oListCompaniasElegidas = new List<CompaniaBE>(); if (ViewState["CompaniasElegidas"] != null) oListCompaniasElegidas = (List<CompaniaBE>)ViewState["CompaniasElegidas"]; if (ddlCorporativo.SelectedItem.Value == Constantes.Caracteres.Uno) EsSubAdministradorAsignado = ComunBL.Instance.ValidarUsuarioPerteneceGrupoSharePoint(oUsuarioActual, Constantes.IDENTIFICADOR_GRUPO_SUBADMINISTRADORES_CORPORATIVOS); else { foreach (CompaniaBE oCompania in oListCompaniasElegidas) { EsSubAdministradorAsignado = ComunBL.Instance.ValidarUsuarioPerteneceGrupoSharePoint(oUsuarioActual, oCompania.Pais.GrupoSubAdmin.DisplayName); if (EsSubAdministradorAsignado) break; } } HabilitarEdicionCamposUsuario(false); MostrarCamposNotificacion(false); if (ddlGrupoSeguridad.SelectedItem.Value == GruposSeguridad.Secreto || ddlGrupoSeguridad.SelectedItem.Value == GruposSeguridad.Confidencial) { SeccionLestoresNoPublicos.Visible = true; } if (EsSubAdministradorAsignado) { ViewState["EsSubAdministradorAsigando"] = true; SoloLectura = false; pnlAcciones.Visible = true; divBotonesAdministradorSubAdministrador.Visible = true; divBotonesSuperiores.Visible = true; btnModificarDatos.Visible = true; gvCompaniaPais.Columns[2].Visible = true; gvAreaSubArea.Columns[2].Visible = true; } if ((bool)ViewState["EsAdministrador"]) { SoloLectura = false; pnlAcciones.Visible = true; divBotonesAdministradorSubAdministrador.Visible = true; divBotonesSuperiores.Visible = true; btnModificarDatos.Visible = true; btnEliminarDocumento.Visible = true; gvHistorialVersiones.Columns[3].Visible = true; gvCompaniaPais.Columns[2].Visible = true; gvAreaSubArea.Columns[2].Visible = true; } switch (txtEstado.Text) { case EstadosDDP.Contribucion: #region Contribucion HabilitarEdicionCamposUsuario(true); #endregion break; case EstadosDDP.Elaboracion: #region Elaboracion SPUser oElaborador = Utilitarios.GetUserClientPeopleEditor(SPContext.Current.Site.Url, cppElaborador); if (oElaborador != null && oElaborador.ID == oUsuarioActual.ID) { //if (divBotonesAdministradorSubAdministrador.Visible == false) //{ SoloLectura = false; cppLectoresNoPublicos.Visible = true; txtLectoresNoPublicos.Visible = false; DivfupArchivo.Visible = true; btnConfirmarCarga.Visible = false; btnReemplazar.Visible = true; gvCompaniaPais.Columns[2].Visible = true; gvAreaSubArea.Columns[2].Visible = true; btnAbrirListaCentroCostos.Visible = true; pnlDatosPrincipalesSecundarios.Enabled = true; pnlUsuariosParticipantes.Enabled = false; pnlDatosAdicionales.Enabled = true; pnlAcciones.Visible = true; btnModificarDatos.Visible = false; if (EsSubAdministradorAsignado || (bool)ViewState["EsAdministrador"]) { divBotonesAdministradorSubAdministrador.Visible = true; ActivarControlesSubAdminAdmin(txtEstado.Text); } else { divBotonesElaborador.Visible = true; divBotonesAdministradorSubAdministrador.Visible = false; } } if (EsSubAdministradorAsignado) btnEliminarDocumento.Visible = true; #endregion break; case EstadosDDP.Revision: #region Revision if (EsSubAdministradorAsignado) btnEliminarDocumento.Visible = true; else { bool EsRevisor = false; if (SeccionTipoPlanMaestro.Visible == true) { if (!string.IsNullOrEmpty(ddlTipoPlanMaestro.SelectedItem.Value) && ddlTipoPlanMaestro.SelectedItem.Value != Constantes.ListaTextItem.Seleccione) { EsRevisor = ComunBL.Instance.ValidarUsuarioPerteneceGrupoSharePoint(oUsuarioActual, Constantes.IDENTIFICADOR_GRUPO_REVISOR + ddlTipoPlanMaestro.SelectedItem.Value); } } else { SPUser oRevisor = Utilitarios.GetUserClientPeopleEditor(SPContext.Current.Site.Url, cppRevisor); if (oRevisor != null) { EsRevisor = true; } } if (EsRevisor) { SoloLectura = false; pnlDatosPrincipalesSecundarios.Enabled = true; pnlDatosSecundarios.Enabled = false; txtTituloInput.Enabled = false; txtComentario.Enabled = true; ddlGrupoSeguridad.Enabled = false; ddlClasificacion.Enabled = false; ddlSistemaCalidad.Enabled = false; pnlAcciones.Visible = true; divBotonesElaborador.Visible = true; btnModificarDatos.Visible = false; divBotonesAdministradorSubAdministrador.Visible = false; } } #endregion break; case EstadosDDP.Aprobacion: #region Aprobacion if (EsSubAdministradorAsignado) btnEliminarDocumento.Visible = true; else { SPUser oAprobador = Utilitarios.GetUserClientPeopleEditor(SPContext.Current.Site.Url, cppAprobador); if (oAprobador != null && oAprobador.ID == oUsuarioActual.ID) { SoloLectura = false; pnlDatosPrincipalesSecundarios.Enabled = true; pnlDatosSecundarios.Enabled = false; txtTituloInput.Enabled = false; txtComentario.Enabled = true; ddlGrupoSeguridad.Enabled = false; ddlClasificacion.Enabled = false; ddlSistemaCalidad.Enabled = false; pnlAcciones.Visible = true; divBotonesElaborador.Visible = true; btnModificarDatos.Visible = false; divBotonesAdministradorSubAdministrador.Visible = false; } } #endregion break; case EstadosDDP.VerificacionCalidad: #region VerificacionCalidad if (ViewState["BloqueadoVCPara"] != null) { SeccionEdicionExclusivaPor.Visible = true; txtEdicionExclusivaPor.Text = ((UsuarioBE)ViewState["BloqueadoVCPara"]).DisplayName; } if (EsSubAdministradorAsignado) { btnEliminarDocumento.Visible = true; HabilitarEdicionCamposUsuario(true); txtComentario.Enabled = true;//Permite editar los comentarios ddlGrupoSeguridad.Enabled = false; ddlClasificacion.Enabled = false; btnModificarDatos.Visible = false; btnEnviarSubAdministrador.Visible = true; pnlDatosPrincipalesSecundarios.Enabled = true; pnlUsuariosParticipantes.Enabled = true; pnlDatosAdicionales.Enabled = true; DivfupArchivo.Visible = true; btnConfirmarCarga.Visible = false; btnReemplazar.Visible = true; if (!String.IsNullOrEmpty(hdfIdBloqueadoVCPara.Value)) { btnBloquearEdicion.Visible = false; if (oUsuarioActual.ID.ToString() == hdfIdBloqueadoVCPara.Value) { btnNoBloquearEdicion.Visible = true; BloqueaForm(true); } else { btnNoBloquearEdicion.Visible = false; btnEliminarDocumento.Visible = false; BloqueaForm(false); } } else { btnBloquearEdicion.Visible = true; btnNoBloquearEdicion.Visible = false; } } if ((bool)ViewState["EsAdministrador"]) { if (!String.IsNullOrEmpty(hdfIdBloqueadoVCPara.Value)) { btnBloquearEdicion.Visible = false; btnNoBloquearEdicion.Visible = true; } } #endregion break; case EstadosDDP.Publicacion: #region Publicacion //if (ViewState["NotificarCentroCostos"] != null) // oDocumentoDDPBE.NotificarEnPublicacionA = (List<CentroCostoBE>)ViewState["NotificarCentroCostos"]; if (ViewState["NotificarCentroCostos"] == null || ((List<CentroCostoBE>)ViewState["NotificarCentroCostos"]).Count == 0) { AbrirBuscadorCentroCostos.Visible = true; btnAbrirListaCentroCostos.Visible = false; } MostrarCamposNotificacion(true); if (ViewState["BloqueadoPubPara"] != null) { SeccionEdicionExclusivaPor.Visible = true; txtEdicionExclusivaPor.Text = ((UsuarioBE)ViewState["BloqueadoPubPara"]).DisplayName; } if (EsSubAdministradorAsignado) { cppLectoresNoPublicos.Visible = true; txtLectoresNoPublicos.Visible = false; btnEliminarDocumento.Visible = true; btnAbrirBuscadorReferencia.Visible = true; HabilitarEdicionCamposUsuario(true); pnlDatosPrincipalesSecundarios.Enabled = true; pnlUsuariosParticipantes.Enabled = true; pnlDatosAdicionales.Enabled = true; txtComentario.Enabled = true;//Permite editar los comentarios ddlGrupoSeguridad.Enabled = false; ddlClasificacion.Enabled = false; ddlSistemaCalidad.Enabled = false; btnModificarDatos.Visible = false; btnEnviarSubAdministrador.Visible = true; DivfupArchivo.Visible = true; btnConfirmarCarga.Visible = false; btnReemplazar.Visible = true; if (!String.IsNullOrEmpty(hdfIdBloqueadoPubPara.Value)) { btnBloquearEdicion.Visible = false; if (oUsuarioActual.ID.ToString() == hdfIdBloqueadoPubPara.Value) { btnNoBloquearEdicion.Visible = true; BloqueaForm(true); } else { btnNoBloquearEdicion.Visible = false; btnEliminarDocumento.Visible = false; BloqueaForm(false); } } else { btnBloquearEdicion.Visible = true; btnNoBloquearEdicion.Visible = false; } } if ((bool)ViewState["EsAdministrador"]) { //btnAbrirListaCentroCostos.Visible = true; btnAbrirBuscadorReferencia.Visible = true; if (!String.IsNullOrEmpty(hdfIdBloqueadoPubPara.Value)) { btnBloquearEdicion.Visible = false; btnNoBloquearEdicion.Visible = true; } } #endregion break; case EstadosDDP.Publicado: #region Publicado MostrarCamposNotificacion(true); btnModificarListaCentroCostos.Visible = false; SeccionDatosCaducidadPublicacion.Visible = true; #region Opciones del contribuidor del macroproceso List<MacroProcesoBE> oMP = (List<MacroProcesoBE>)ViewState["MacroProcesos"]; if (oMP != null) { MacroProcesoBE oMacroProceso = oMP.Find(oItem => oItem.Id.ToString() == ddlMacroProceso.SelectedItem.Value); if (oMacroProceso != null && ComunBL.Instance.ValidarUsuarioPerteneceGrupoSharePoint(oUsuarioActual, oMacroProceso.GrupoSeguridad.DisplayName)) { divBotonesSuperiores.Visible = true; btnNuevaVersion.Visible = true; } } #endregion if (EsSubAdministradorAsignado || (bool)ViewState["EsAdministrador"]) { btnAbrirBuscadorReferencia.Visible = true; //if ((bool)ViewState["EsSubAdministrador"] || (bool)ViewState["EsAdministrador"]) SoloLectura = false; divBotonesSuperiores.Visible = true; btnNuevaVersion.Visible = true; } #endregion break; case EstadosDDP.Obsoleto: #region Obsoleto SeccionDatosCaducidadPublicacion.Visible = true; MostrarCamposNotificacion(true); btnModificarListaCentroCostos.Visible = false; #endregion break; case EstadosDDP.Caducado: #region Caducado SeccionDatosCaducidadPublicacion.Visible = true; MostrarCamposNotificacion(true); btnModificarListaCentroCostos.Visible = false; if ((bool)ViewState["EsAdministrador"]) btnReactivarCaducado.Visible = true; #endregion break; default: break; } if (SoloLectura) MostrarSoloLectura(); } } private void MostrarCamposNotificacion(bool Visible) { SeccionNotificacionCorporativa.Visible = Visible; SeccionNotificaEnPublicacionA.Visible = Visible; ddlNotificacionCorporativa.Visible = Visible; if (Visible) { CargarListadoDeCentrosCostos(); if ((bool)ViewState["EsSubAdministrador"] || (bool)ViewState["EsAdministrador"]) { btnModificarListaCentroCostos.Visible = true; } } //if (ddlNotificacionCorporativa.SelectedItem.Value == Constantes.Caracteres.Uno) // SeccionNotificaEnPublicacionA.Visible = !Visible; } private void CargarTabReferencias(string CodigoDocumentoActual) { gvReferenciaA.DataSource = ReferenciaBL.Instance.ObtenerListaReferenciaA(CodigoDocumentoActual); gvReferenciadoPor.DataSource = ReferenciaBL.Instance.ObtenerListaReferenciadoPor(CodigoDocumentoActual); gvReferenciaA.DataBind(); gvReferenciadoPor.DataBind(); } void MostrarSoloLectura() { cppLectoresNoPublicos.Enabled = false; pnlAcciones.Visible = true; divBotonesSoloLectura.Visible = true; } protected void gvAdjuntosSolicitante_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e) { if (e.CommandName == "Eliminar") { gvAdjuntosSolicitante.DataSource = null; gvAdjuntosSolicitante.DataBind(); DivfupArchivo.Visible = true; DivAdjuntosSolicitante.Visible = false; } } protected void gvReferenciaA_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Eliminar") { int row = Convert.ToInt32(e.CommandArgument.ToString()); string pe_CodigoDocumentoDocRelacionaA = (String)gvReferenciaA.DataKeys[row].Value; ReferenciaBL.Instance.EliminarRelacion(pe_CodigoDocumentoDocRelacionaA, txtCodigoDocumentoCabecera.Text); CargarTabReferencias(txtCodigoDocumentoCabecera.Text); upbtnAbrirBuscadorReferencia.Update(); String Mensaje = String.Format(Mensajes.ExitoGestorDocumental.EliminoReferenciaCorrectamente, pe_CodigoDocumentoDocRelacionaA); WebUtil.AlertServer(Page, this.GetType(), TipoAlerta.Aviso, "AlertaAviso", Mensaje); } } #region *** CARGA DE COMBOS *** private void CargarComboGrupoSeguridad() { var lst = GrupoSeguridadBL.Instance.ObtenerLista(SPContext.Current.Site.RootWeb); //ViewState["GruposSeguridadMacroprocesosContribuidor"] = lst; if (!(bool)ViewState["EsAdministrador"] && !(bool)ViewState["EsSubAdministrador"]) { List<MacroProcesoBE> lstMP = new List<MacroProcesoBE>(); lstMP = MacroProcesoBL.Instance.ObtenerGruposSeguridadMacroprocesosContribuidor(URLSitioPrincipal, SPContext.Current.Web.CurrentUser.LoginName); ViewState["GruposSeguridadMacroprocesosContribuidor"] = lstMP; if (!lstMP.Exists(ItemEliminar => ItemEliminar.SecretoParaUsuarioActual)) { lst.RemoveAll(ItemEliminar => ItemEliminar.Title == GruposSeguridad.Secreto); } if (!lstMP.Exists(ItemEliminar => ItemEliminar.ConfidencialParaUsuarioActual)) { lst.RemoveAll(ItemEliminar => ItemEliminar.Title == GruposSeguridad.Confidencial); } } if (lst != null) WebUtil.BindDropDownList(ddlGrupoSeguridad, lst, "Title", "Title", Constantes.ListaValueItem.Vacio, Constantes.ListaTextItem.Seleccione); } private void CargarComboClasificacionDocumento() { var lst = ClasificacionDocumentoBL.Instance.ObtenerLista(SPContext.Current.Site.RootWeb); if (lst != null) WebUtil.BindDropDownList(ddlClasificacion, lst, "Title", "Title", Constantes.ListaValueItem.Vacio, Constantes.ListaTextItem.Seleccione); } private void CargarComboTipoPlanMaestro() { var lst = TipoPlanMaestroBL.Instance.ObtenerLista(SPContext.Current.Site.RootWeb); if (lst != null) WebUtil.BindDropDownList(ddlTipoPlanMaestro, lst, "Title", "Title", Constantes.ListaValueItem.Vacio, Constantes.ListaTextItem.Seleccione); } private void CargarComboMacroProceso() { var lst = MacroProcesoBL.Instance.ObtenerLista(SPContext.Current.Site.RootWeb); ViewState["MacroProcesos"] = lst; if (lst != null) WebUtil.BindDropDownList(ddlMacroProceso, lst, "Id", "Descripcion", Constantes.ListaValueItem.Vacio, Constantes.ListaTextItem.Seleccione); } private void CargarComboProceso() { string IdMacroproceso = ddlMacroProceso.SelectedItem.Value; var lst = ProcesoBL.Instance.ObtenerLista(SPContext.Current.Site.RootWeb, IdMacroproceso); if (lst != null) WebUtil.BindDropDownList(ddlProceso, lst, "Id", "Title", Constantes.ListaValueItem.Vacio, Constantes.ListaTextItem.Seleccione); } private void CargarComboMetodoAnalisisPrincipal() { var lst = MetodoAnalisisPrincipalBL.Instance.ObtenerLista(SPContext.Current.Site.RootWeb); if (lst != null) WebUtil.BindDropDownList(ddlMetodoAnalisisPrincipal, lst, "Title", "Title", Constantes.ListaValueItem.Vacio, Constantes.ListaTextItem.Seleccione); } private void CargarComboAreaPrincipal() { var lst = AreaPrincipalBL.Instance.ObtenerLista(SPContext.Current.Site.RootWeb); if (lst != null) { //WebUtil.BindDropDownList(ddlAreaPrincipal, lst, "Id", "Title", Constantes.ListaValueItem.Vacio, Constantes.ListaTextItem.Seleccione); WebUtil.BindDropDownList(ddlFiltroArea, lst, "Id", "Title", Constantes.ListaValueItem.Vacio, Constantes.ListaTextItem.Seleccione); } } private void CargarComboSubArea() { try { //ddlSubArea.Items.Clear(); //string IdArea = ddlAreaPrincipal.SelectedItem.Value; //var lst = SubAreaBL.Instance.ObtenerLista(URLSitioPrincipal, IdArea); //if (lst != null) // WebUtil.BindDropDownList(ddlSubArea, lst, "Id", "Title", Constantes.ListaValueItem.Vacio, Constantes.ListaTextItem.Seleccione); } catch (Exception ex) { string strGUIDReferencia = Logging.RegistrarMensajeLogSharePoint(Constantes.CATEGORIA_LOG_FORM_GESTOR_LOAD, "CargarComboSubArea", ex); WebUtil.AlertServer(Page, this.GetType(), TipoAlerta.Aviso, "AlertaAviso", ex.Message + " : : " + ex.StackTrace); } } protected void ddlGrupoSeguridad_SelectedIndexChanged(object sender, EventArgs e) { try { cppLectoresNoPublicos.AllEntities.Clear(); List<MacroProcesoBE> lst = new List<MacroProcesoBE>(); List<MacroProcesoBE> lstFiltrada = new List<MacroProcesoBE>(); ddlMacroProceso.Items.Clear(); if (ddlGrupoSeguridad.SelectedItem.Text == Constantes.ListaTextItem.Seleccione) { lstFiltrada = null; } else { if ((bool)ViewState["EsAdministrador"] == false && (bool)ViewState["EsSubAdministrador"] == false) { lst = (List<MacroProcesoBE>)ViewState["GruposSeguridadMacroprocesosContribuidor"]; if (ddlGrupoSeguridad.SelectedItem.Text == GruposSeguridad.Confidencial) lstFiltrada = lst.FindAll(MP => MP.ConfidencialParaUsuarioActual == true); else if (ddlGrupoSeguridad.SelectedItem.Text == GruposSeguridad.Secreto) lstFiltrada = lst.FindAll(MP => MP.SecretoParaUsuarioActual == true); else lstFiltrada = lst; } else { lstFiltrada = MacroProcesoBL.Instance.ObtenerLista(URLSitioPrincipal); ViewState["GruposSeguridadMacroprocesosContribuidor"] = lstFiltrada; } } if (lstFiltrada != null) WebUtil.BindDropDownList(ddlMacroProceso, lstFiltrada, "Id", "Descripcion", Constantes.ListaValueItem.Vacio, Constantes.ListaTextItem.Seleccione); WebUtil.EjecutarFuncionJS(Page, this.GetType(), "verificarMacroproceso();"); } catch (Exception ex) { string strGUIDReferencia = Logging.RegistrarMensajeLogSharePoint(Constantes.CATEGORIA_LOG_FORM_GESTOR_LOAD, "ddlGrupoSeguridad_SelectedIndexChanged", ex); WebUtil.AlertServer(Page, this.GetType(), TipoAlerta.Aviso, "AlertaAviso", ex.Message + " : : " + ex.StackTrace); } } protected void ddlMacroProceso_SelectedIndexChanged(object sender, EventArgs e) { cppElaborador.AllEntities.Clear(); cppAprobador.AllEntities.Clear(); CargarComboProceso(); int IdGrupoMacroproceso = 0; List<MacroProcesoBE> lst = new List<MacroProcesoBE>(); if (ViewState["GruposSeguridadMacroprocesosContribuidor"] != null) { lst = (List<MacroProcesoBE>)ViewState["GruposSeguridadMacroprocesosContribuidor"]; if (ddlMacroProceso.SelectedItem.Value != String.Empty) IdGrupoMacroproceso = lst.Find(MP => MP.Id.ToString() == ddlMacroProceso.SelectedItem.Value).IdGrupoPublicoMacroproceso; } ViewState["ElaboradorAprobador_SharePointGroupID"] = IdGrupoMacroproceso; cppElaborador.SharePointGroupID = IdGrupoMacroproceso; cppAprobador.SharePointGroupID = IdGrupoMacroproceso; HabilitarEdicionCamposUsuario(true); WebUtil.EjecutarFuncionJS(Page, this.GetType(), "onMacroProcesoSeleccionado();"); } protected void ddlSistemaCalidad_SelectedIndexChanged(object sender, EventArgs e) { if (SeccionTipoPlanMaestro.Visible == false) { if (ddlSistemaCalidad.SelectedItem.Value == "Sí") { cppRevisor.AllEntities.Clear(); cppRevisor.SharePointGroupID = MacroProcesoBL.Instance.ObtenerGruposPorNombre(URLSitioPrincipal, Constantes.NOMBRE_GRUPO_COLABORADORES_GC); ViewState["Revisor_SharePointGroupID"] = cppRevisor.SharePointGroupID; } else ViewState["Revisor_SharePointGroupID"] = cppRevisor.SharePointGroupID = 0; } WebUtil.EjecutarFuncionJS(Page, this.GetType(), "verificarMacroproceso();"); } protected void ddlAreaPrincipal_SelectedIndexChanged(object sender, EventArgs e) { CargarComboSubArea(); } #endregion #region *** POPUP BÚSQUEDA DE CENTRO DE COSTOS *** protected void btnCerrarBuscadorCentroCostos_Click(object sender, EventArgs e) { ResetearBuscadorCentroDocumento(); } protected void btnCerrarBuscadorParticipante_Click(object sender, EventArgs e) { ResetearBuscadorElaborador(); } private void ResetearBuscadorElaborador() { grvResultadoBusquedaParticipante.Visible = false; } private void ResetearBuscadorCentroDocumento() { grvPreseleccionadosNotificados.Visible = false; grvResultadoBusquedaNotificados.Visible = false; btnPreseleccionar.Visible = false; btnConfirmarPreseleccion.Visible = false; } #region PAGINACIÓN DE POPUP BÚSQUEDA DE CENTRO DE COSTOS //protected void ddlPaginasCentroCostosFiltrados_SelectedIndexChanged(object sender, EventArgs e) //{ // if (ddlPaginasCentroCostosFiltrados.SelectedItem != null) // { // int pageIndex = ddlPaginasCentroCostosFiltrados.SelectedIndex + 1; // BuscarCentrosCostos(pageIndex); // //updResultado.Update(); // } //} //protected void ibtnPaginacionCentroCostosFiltrados_Click(object sender, System.Web.UI.ImageClickEventArgs e) //{ // LlenarGrillaCentroCostos(null); // PageIndexChangingCentroCostosFiltrados(gvCentroCostosFiltrados, (ImageButton)sender, ddlPaginasCentroCostosFiltrados); // ddlPaginasCentroCostosFiltrados_SelectedIndexChanged(sender, e); //} //private void PageIndexChangingCentroCostosFiltrados(GridView oGridView, ImageButton oBtnNavegacion, DropDownList ddl) //{ // switch (oBtnNavegacion.CommandArgument) // { // case "First": // { // if (ddl.SelectedIndex >= 0) // ddl.SelectedIndex = 0; // } // break; // case "Prev": // { // if (ddl.SelectedIndex > 0) // ddl.SelectedIndex -= 1; // } // break; // case "Next": // { // if (ddl.SelectedIndex < ddl.Items.Count - 1) // ddl.SelectedIndex += 1; // } // break; // case "Last": // { // if (ddl.SelectedIndex >= 0) // ddl.SelectedIndex = ddl.Items.Count - 1; // } // break; // default: // break; // } //} #endregion protected void ddlNotificacionCorporativa_SelectedIndexChanged(object sender, EventArgs e) { if (ddlNotificacionCorporativa.SelectedItem.Value == "0") SeccionNotificaEnPublicacionA.Visible = true; else { SeccionNotificaEnPublicacionA.Visible = false; ViewState["NotificarCentroCostos"] = null; //gvCentroCostos.DataSource = ViewState["NotificarCentroCostos"]; //gvCentroCostos.DataBind(); //upCentroCostos.Update(); } } #endregion #region *** POPUP BÚSQUEDA DE COMPAÑÍA *** protected void btnCerrarBuscadorCompania_Click(object sender, EventArgs e) { OcultarGrillaBuscadorCompania(); WebUtil.EjecutarFuncionJS(Page, this.GetType(), "verificarMacroproceso();"); } private void OcultarGrillaBuscadorCompania() { tbPagerCompaniaFiltrados.Visible = false; gvCompaniaFiltrados.Visible = false; } private void CargarComboFiltroPais() { var lst = PaisBL.Instance.ObtenerLista(URLSitioPrincipal); if (lst != null) WebUtil.BindDropDownList(ddlFiltroPais, lst, "Id", "Title", Constantes.ListaValueItem.Vacio, Constantes.ListaTextItem.Seleccione); } protected void ddlFiltroPais_SelectedIndexChanged(object sender, EventArgs e) { BuscarCompanias(1); } private void BuscarCompanias(int NumeroPagina) { int totalRows = 0; int totalPages = 0; List<CompaniaBE> ListaFiltrada = ObtenerCompanias(NumeroPagina, ref totalRows, ref totalPages); LlenarGrillaCompanias(ListaFiltrada, totalPages); if (ListaFiltrada != null && ListaFiltrada.Count > 0) { ddlPaginasCompaniaFiltrados.Items.Clear(); ddlPaginasCompaniaFiltrados.Enabled = true; int nroPaginas = totalPages; int totalRegistros = totalRows; for (int i = 1; i <= nroPaginas; i++) ddlPaginasCompaniaFiltrados.Items.Add(i.ToString()); ddlPaginasCompaniaFiltrados.SelectedValue = NumeroPagina.ToString(); int regInicial = ((nroPaginas > 0) ? ((NumeroPagina - 1) * FilasXPagina) + 1 : 0); int regLisView = ((nroPaginas > 0) ? ((NumeroPagina - 1) * FilasXPagina) : 0) + gvCompaniaFiltrados.Rows.Count; lblResultadoCompaniaFiltrados.Text = String.Format("Registros: {0} - {1} de {2}", regInicial, regLisView, totalRegistros); } } private List<CompaniaBE> ObtenerCompanias(int NumeroPagina, ref int TotalFilas, ref int TotalPaginas) { List<CompaniaBE> oListCompaniasAgregadas = new List<CompaniaBE>(); if (ViewState["CompaniasElegidas"] != null) { oListCompaniasAgregadas = (List<CompaniaBE>)ViewState["CompaniasElegidas"]; } List<CompaniaBE> lstCompanias = CompaniaBL.Instance.ListarFiltrado(URLSitioPrincipal, ddlFiltroPais.SelectedItem.Value, NumeroPagina, FilasXPagina, ref TotalFilas, oListCompaniasAgregadas); if (lstCompanias != null && lstCompanias.Count > 0) { int pages = (int)(TotalFilas / FilasXPagina); if (FilasXPagina * pages != TotalFilas) pages += 1; TotalPaginas = pages; } return lstCompanias; } private void LlenarGrillaCompanias(List<CompaniaBE> lstResultado, int Paginas = 1) { //if (lstResultado == null) // gvCompaniaFiltrados.Visible = false; //else gvCompaniaFiltrados.Visible = true; if (Paginas > 1) tbPagerCompaniaFiltrados.Visible = true; else tbPagerCompaniaFiltrados.Visible = false; gvCompaniaFiltrados.DataSource = lstResultado; gvCompaniaFiltrados.DataBind(); } #region PAGINACIÓN DE POPUP BÚSQUEDA DE COMPANÍA protected void ddlPaginasCompaniaFiltrados_SelectedIndexChanged(object sender, EventArgs e) { if (ddlPaginasCompaniaFiltrados.SelectedItem != null) { int pageIndex = ddlPaginasCompaniaFiltrados.SelectedIndex + 1; BuscarCompanias(pageIndex); //updResultado.Update(); } } protected void ibtnPaginacionCompaniaFiltrados_Click(object sender, System.Web.UI.ImageClickEventArgs e) { LlenarGrillaCompanias(null); PageIndexChangingCompaniaFiltrados(gvCompaniaFiltrados, (ImageButton)sender, ddlPaginasCompaniaFiltrados); ddlPaginasCompaniaFiltrados_SelectedIndexChanged(sender, e); } private void PageIndexChangingCompaniaFiltrados(GridView oGridView, ImageButton oBtnNavegacion, DropDownList ddl) { switch (oBtnNavegacion.CommandArgument) { case "First": { if (ddl.SelectedIndex >= 0) ddl.SelectedIndex = 0; } break; case "Prev": { if (ddl.SelectedIndex > 0) ddl.SelectedIndex -= 1; } break; case "Next": { if (ddl.SelectedIndex < ddl.Items.Count - 1) ddl.SelectedIndex += 1; } break; case "Last": { if (ddl.SelectedIndex >= 0) ddl.SelectedIndex = ddl.Items.Count - 1; } break; default: break; } } protected void btnElegirCompania_Click(object sender, EventArgs e) { OcultarGrillaBuscadorCompania(); //upPopupBuscadorCompania.Update(); List<CompaniaBE> oListCompaniasElegidas = new List<CompaniaBE>(); if (ViewState["CompaniasElegidas"] != null) oListCompaniasElegidas = (List<CompaniaBE>)ViewState["CompaniasElegidas"]; CompaniaBE oCompaniaBE = new CompaniaBE(); oCompaniaBE.Id = Convert.ToInt32(hdfIdCompaniaAgregado.Value); oCompaniaBE.Title = hdfTitleCompaniaAgregado.Value; oCompaniaBE.Pais.Id = Convert.ToInt32(hdfIdPaisAgregado.Value); oCompaniaBE.Pais.Title = hdfTitlePaisAgregado.Value; oListCompaniasElegidas.Add(oCompaniaBE); ViewState["CompaniasElegidas"] = oListCompaniasElegidas; gvCompaniaPais.DataSource = ViewState["CompaniasElegidas"]; gvCompaniaPais.DataBind(); upCompaniaPais.Update(); WebUtil.EjecutarFuncionJS(Page, this.GetType(), "verificarMacroproceso();"); } #endregion protected void btnAbrirBuscadorCompania_Click(object sender, EventArgs e) { CargarComboFiltroPais(); WebUtil.EjecutarFuncionJS(Page, this.GetType(), "verificarMacroproceso();"); } protected void gvCompaniaPais_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Eliminar") { hdfModificoDatos.Value = hdfModificoDatos.Value + " - gvCompaniaPais"; int row = Convert.ToInt32(e.CommandArgument.ToString()); int IdCompania = (int)gvCompaniaPais.DataKeys[row].Value; //_ListaDocuments.RemoveAt(row) List<CompaniaBE> oListCompaniasElegidas = new List<CompaniaBE>(); if (ViewState["CompaniasElegidas"] != null) oListCompaniasElegidas = (List<CompaniaBE>)ViewState["CompaniasElegidas"]; oListCompaniasElegidas.RemoveAll(ItemEliminar => ItemEliminar.Id == IdCompania); ViewState["CompaniasElegidas"] = oListCompaniasElegidas; gvCompaniaPais.DataSource = ViewState["CompaniasElegidas"]; gvCompaniaPais.DataBind(); upCompaniaPais.Update(); WebUtil.EjecutarFuncionJS(Page, this.GetType(), "verificarMacroproceso();"); } } #endregion #region *** POPUP BÚSQUEDA DE SUB-ÁREA *** protected void btnCerrarBuscadorSubArea_Click(object sender, EventArgs e) { gvSubAreaFiltrados.DataSource = null; gvSubAreaFiltrados.DataBind(); gvSubAreaFiltrados.Visible = false; btnSeleccionarSubAreas.Visible = false; WebUtil.EjecutarFuncionJS(Page, this.GetType(), "verificarMacroproceso();"); } protected void btnAbrirBuscadorSubArea_Click(object sender, EventArgs e) { gvSubAreaFiltrados.DataSource = null; gvSubAreaFiltrados.DataBind(); gvSubAreaFiltrados.Visible = false; WebUtil.EjecutarFuncionJS(Page, this.GetType(), "verificarMacroproceso();"); } protected void ddlFiltroArea_SelectedIndexChanged(object sender, EventArgs e) { List<SubAreaBE> lstSubAreas = SubAreaBL.Instance.ObtenerLista(hdfUrlSitio.Value, ddlFiltroArea.SelectedValue); gvSubAreaFiltrados.DataSource = lstSubAreas; gvSubAreaFiltrados.DataBind(); gvSubAreaFiltrados.Visible = true; if (lstSubAreas.Count > 0) btnSeleccionarSubAreas.Visible = true; } protected void gvAreaSubArea_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Eliminar") { hdfModificoDatos.Value = hdfModificoDatos.Value + " - gvAreaSubArea"; int row = Convert.ToInt32(e.CommandArgument.ToString()); int IdCompania = (int)gvAreaSubArea.DataKeys[row].Value; //_ListaDocuments.RemoveAt(row) List<SubAreaBE> oListSubAreasElegidas = new List<SubAreaBE>(); if (ViewState["SubAreasElegidas"] != null) oListSubAreasElegidas = (List<SubAreaBE>)ViewState["SubAreasElegidas"]; oListSubAreasElegidas.RemoveAll(ItemEliminar => ItemEliminar.Id == IdCompania); ViewState["SubAreasElegidas"] = oListSubAreasElegidas; gvAreaSubArea.DataSource = ViewState["SubAreasElegidas"]; gvAreaSubArea.DataBind(); updAreaSubArea.Update(); } } protected void btnSeleccionarSubAreas_Click(object sender, EventArgs e) { List<SubAreaBE> oListSubAreasElegidas = new List<SubAreaBE>(); if (ViewState["SubAreasElegidas"] != null) oListSubAreasElegidas = (List<SubAreaBE>)ViewState["SubAreasElegidas"]; SubAreaBE oSubAreaBE = null; foreach (GridViewRow row in gvSubAreaFiltrados.Rows) { if (((CheckBox)row.FindControl("chkElegirSubArea")).Checked) { oSubAreaBE = new SubAreaBE(); oSubAreaBE.Id = Convert.ToInt32(gvSubAreaFiltrados.DataKeys[row.RowIndex].Values[0].ToString()); oSubAreaBE.Title = gvSubAreaFiltrados.DataKeys[row.RowIndex].Values[1].ToString(); oSubAreaBE.AreaPrincipal.Id = Convert.ToInt32(((Label)row.FindControl("lblIdArea")).Text); oSubAreaBE.AreaPrincipal.Title = ((Label)row.FindControl("lblTitleArea")).Text; if (!oListSubAreasElegidas.Exists(SubAreaExiste => SubAreaExiste.Id == oSubAreaBE.Id)) { oListSubAreasElegidas.Add(oSubAreaBE); } } } ViewState["SubAreasElegidas"] = oListSubAreasElegidas; gvAreaSubArea.DataSource = ViewState["SubAreasElegidas"]; gvAreaSubArea.DataBind(); updAreaSubArea.Update(); WebUtil.EjecutarFuncionJS(Page, this.GetType(), "verificarMacroproceso();"); } #endregion #region *** POPUP BÚSQUEDA DE REFERENCIA *** protected void btnCerrarBuscadorReferencia_Click(object sender, EventArgs e) { OcultarGrillaBuscadorReferencia(); } private void OcultarGrillaBuscadorReferencia() { tbPagerReferenciaFiltrados.Visible = false; gvReferenciaFiltrados.Visible = false; btnRelacionar.Visible = false; } private void CargarComboFiltroTipoDocumento() { var lst = TipoDocumentalBL.Instance.ObtenerLista(URLSitioPrincipal); if (lst != null) WebUtil.BindDropDownList(ddlFiltroTipoDocumento, lst, "Codigo", "Nombre", Constantes.ListaValueItem.Vacio, Constantes.ListaTextItem.Seleccione); } protected void btnBuscarFiltroReferencia_Click(object sender, EventArgs e) { BuscarReferencias(1); } private void BuscarReferencias(int NumeroPagina) { int totalRows = 0; int totalPages = 0; List<ReferenciaBE> ListaFiltrada = ObtenerReferencias(NumeroPagina, ref totalRows, ref totalPages); LlenarGrillaReferencias(ListaFiltrada, totalPages); if (ListaFiltrada != null && ListaFiltrada.Count > 0) { ddlPaginasReferenciaFiltrados.Items.Clear(); ddlPaginasReferenciaFiltrados.Enabled = true; int nroPaginas = totalPages; int totalRegistros = totalRows; for (int i = 1; i <= nroPaginas; i++) ddlPaginasReferenciaFiltrados.Items.Add(i.ToString()); ddlPaginasReferenciaFiltrados.SelectedValue = NumeroPagina.ToString(); int regInicial = ((nroPaginas > 0) ? ((NumeroPagina - 1) * FilasXPagina) + 1 : 0); int regLisView = ((nroPaginas > 0) ? ((NumeroPagina - 1) * FilasXPagina) : 0) + gvReferenciaFiltrados.Rows.Count; lblResultadoReferenciaFiltrados.Text = String.Format("Registros: {0} - {1} de {2}", regInicial, regLisView, totalRegistros); } } private List<ReferenciaBE> ObtenerReferencias(int NumeroPagina, ref int TotalFilas, ref int TotalPaginas) { String SitioPublicado = SPContext.Current.Site.Url + Constantes.URL_SUBSITIO_PUBLICADO; List<ReferenciaBE> lstReferencias = ReferenciaBL.Instance.ListarFiltrado(ddlFiltroTipoDocumento.SelectedItem.Value, txtFiltroTitulo.Text, txtFiltroCodigoDocumento.Text, txtCodigoDocumentoCabecera.Text, NumeroPagina, FilasXPagina, ref TotalFilas); //Empleado_BL.Instance.ObtenerXRenovar(NumeroPagina, FilasXPagina, oEmpleado, ref TotalFilas); if (lstReferencias != null && lstReferencias.Count > 0) { int pages = (int)(TotalFilas / FilasXPagina); if (FilasXPagina * pages != TotalFilas) pages += 1; TotalPaginas = pages; } return lstReferencias; } private void LlenarGrillaReferencias(List<ReferenciaBE> lstResultado, int Paginas = 1) { if (lstResultado == null) { //gvReferenciaFiltrados.Visible = false; btnRelacionar.Visible = false; } else { //gvReferenciaFiltrados.Visible = true; btnRelacionar.Visible = true; } gvReferenciaFiltrados.Visible = true; if (Paginas > 1) tbPagerReferenciaFiltrados.Visible = true; else tbPagerReferenciaFiltrados.Visible = false; gvReferenciaFiltrados.DataSource = lstResultado; gvReferenciaFiltrados.DataBind(); //upPopupBuscadorCentroCostos.Update(); } #region PAGINACIÓN DE POPUP BÚSQUEDA DE REFERENCIA protected void ddlPaginasReferenciaFiltrados_SelectedIndexChanged(object sender, EventArgs e) { if (ddlPaginasReferenciaFiltrados.SelectedItem != null) { int pageIndex = ddlPaginasReferenciaFiltrados.SelectedIndex + 1; BuscarReferencias(pageIndex); //updResultado.Update(); } } protected void ibtnPaginacionReferenciaFiltrados_Click(object sender, System.Web.UI.ImageClickEventArgs e) { LlenarGrillaReferencias(null); PageIndexChangingReferenciaFiltrados(gvReferenciaFiltrados, (ImageButton)sender, ddlPaginasReferenciaFiltrados); ddlPaginasReferenciaFiltrados_SelectedIndexChanged(sender, e); } private void PageIndexChangingReferenciaFiltrados(GridView oGridView, ImageButton oBtnNavegacion, DropDownList ddl) { switch (oBtnNavegacion.CommandArgument) { case "First": { if (ddl.SelectedIndex >= 0) ddl.SelectedIndex = 0; } break; case "Prev": { if (ddl.SelectedIndex > 0) ddl.SelectedIndex -= 1; } break; case "Next": { if (ddl.SelectedIndex < ddl.Items.Count - 1) ddl.SelectedIndex += 1; } break; case "Last": { if (ddl.SelectedIndex >= 0) ddl.SelectedIndex = ddl.Items.Count - 1; } break; default: break; } } protected void btnElegirReferencia_Click(object sender, EventArgs e) { OcultarGrillaBuscadorReferencia(); //List<ReferenciaBE> oListReferenciasElegidas = new List<ReferenciaBE>(); //if (ViewState["ReferenciasElegidas"] != null) // oListReferenciasElegidas = (List<ReferenciaBE>)ViewState["ReferenciasElegidas"]; //ReferenciaBE oReferenciaBE = new ReferenciaBE(); //oReferenciaBE.Id = Convert.ToInt32(hdfIdReferenciaAgregado.Value); //oReferenciaBE.Title = hdfTitleReferenciaAgregado.Value; //oReferenciaBE.Pais.Id = Convert.ToInt32(hdfIdPaisAgregado.Value); //oReferenciaBE.Pais.Title = hdfTitlePaisAgregado.Value; //oListReferenciasElegidas.Add(oReferenciaBE); //ViewState["ReferenciasElegidas"] = oListReferenciasElegidas; //gvReferenciaPais.DataSource = ViewState["ReferenciasElegidas"]; //gvReferenciaPais.DataBind(); //upReferenciaPais.Update(); string CodigoDocumentoActual = txtCodigoDocumentoCabecera.Text; foreach (GridViewRow row in gvReferenciaFiltrados.Rows) { if (((CheckBox)row.FindControl("chkElegirReferenciaFiltrados")).Checked) { string pe_CodigoDocumentoDocRelacionaA = gvReferenciaFiltrados.DataKeys[row.RowIndex].Value.ToString(); ReferenciaBL.Instance.GuardarRelacion(pe_CodigoDocumentoDocRelacionaA, CodigoDocumentoActual); } } //llama al listar relacionados a y relacionados por. CargarTabReferencias(CodigoDocumentoActual); //WebUtil.AlertServer( this,TipoAlerta.Aviso,"xxxxx"); //WebUtil.AlertServer(Page, GetType(), TipoAlerta.Aviso, Mensajes.ExitoGestorDocumental.ReferencioCorrectamente); //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), // "NewClientScript", "alert('Se ha relacionado con éxito***');", true); //ScriptManager.RegisterStartupScript(Page, GetType(), "disp_confirm", "<script>alert('Se ha relacionado con éxito***');</script>", false); upReferencias.Update(); //ScriptManager.RegisterStartupScript(Page, this.GetType(), "btnEnviar_Click", "Confirmacion();", true); WebUtil.AlertServer(Page, this.GetType(), TipoAlerta.Aviso, "AlertaAviso", Mensajes.ExitoGestorDocumental.ReferencioCorrectamente); } #endregion protected void btnAbrirBuscadorReferencia_Click(object sender, EventArgs e) { CargarComboFiltroTipoDocumento(); } protected void gvReferenciaPais_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Eliminar") { ////int row = Convert.ToInt32(e.CommandArgument.ToString()); ////int IdReferencia = (int)gvReferenciaPais.DataKeys[row].Value; //////_ListaDocuments.RemoveAt(row) ////List<ReferenciaBE> oListReferenciasElegidas = new List<ReferenciaBE>(); ////if (ViewState["ReferenciasElegidas"] != null) //// oListReferenciasElegidas = (List<ReferenciaBE>)ViewState["ReferenciasElegidas"]; ////oListReferenciasElegidas.RemoveAll(ItemEliminar => ItemEliminar.Id == IdReferencia); ////ViewState["ReferenciasElegidas"] = oListReferenciasElegidas; ////gvReferenciaPais.DataSource = ViewState["ReferenciasElegidas"]; ////gvReferenciaPais.DataBind(); ////upReferenciaPais.Update(); } } #endregion #region *** POPUP BÚSQUEDA DE DOCUMENTOS *** protected void btnCerrarBuscadorDocumentos_Click(object sender, EventArgs e) { OcultarGrillaBuscadorDocumentos(); WebUtil.EjecutarFuncionJS(Page, this.GetType(), "verificarMacroproceso();"); } private void OcultarGrillaBuscadorDocumentos() { tbPagerDocumentosFiltrados.Visible = false; gvDocumentosFiltrados.Visible = false; } protected void btnBuscarFiltroDocumentos_Click(object sender, EventArgs e) { lblTituloBuscadorDocumentos.Text = "Búsqueda de " + hdfListaDocumento.Value; BuscarDocumentos(1); } private void BuscarDocumentos(int NumeroPagina) { int totalRows = 0; int totalPages = 0; string ListaDocumentos = hdfListaDocumento.Value; List<ElementoBE> ListaFiltrada = ObtenerDocumentos(NumeroPagina, ref totalRows, ref totalPages, ListaDocumentos); LlenarGrillaDocumentosFiltrados(ListaFiltrada, totalPages); if (ListaFiltrada != null && ListaFiltrada.Count > 0) { ddlPaginasDocumentosFiltrados.Items.Clear(); ddlPaginasDocumentosFiltrados.Enabled = true; int nroPaginas = totalPages; int totalRegistros = totalRows; for (int i = 1; i <= nroPaginas; i++) ddlPaginasDocumentosFiltrados.Items.Add(i.ToString()); ddlPaginasDocumentosFiltrados.SelectedValue = NumeroPagina.ToString(); int regInicial = ((nroPaginas > 0) ? ((NumeroPagina - 1) * FilasXPagina) + 1 : 0); int regLisView = ((nroPaginas > 0) ? ((NumeroPagina - 1) * FilasXPagina) : 0) + gvDocumentosFiltrados.Rows.Count; lblResultadoDocumentosFiltrados.Text = String.Format("Registros: {0} - {1} de {2}", regInicial, regLisView, totalRegistros); } } private List<ElementoBE> ObtenerDocumentos(int NumeroPagina, ref int TotalFilas, ref int TotalPaginas, string ListaDocumentos) { string CampoPreFiltro = null; string ValorPreFiltro = null; if (ListaDocumentos == Constantes.NombreListas.DescripcionProcesos || ListaDocumentos == Constantes.NombreListas.PoliticasProceso) { CampoPreFiltro = Constantes.NOMBRE_CAMPO_LISTA_PROCESO; ValorPreFiltro = ddlProceso.SelectedItem.Value; } else if (ListaDocumentos == Constantes.NombreListas.Intrucciones || ListaDocumentos == Constantes.NombreListas.Procedimientos || ListaDocumentos == Constantes.NombreListas.MetodoAnalisis) { CampoPreFiltro = Constantes.NOMBRE_CAMPO_LISTA_POLITICA; ValorPreFiltro = hdfIdPolitica.Value; } List<ElementoBE> lst = ElementoBL.Instance.ListarFiltrado(URLSitioPrincipal, txtFiltroDocumentos.Text, NumeroPagina, FilasXPagina, ref TotalFilas, ListaDocumentos, CampoPreFiltro, ValorPreFiltro); //Empleado_BL.Instance.ObtenerXRenovar(NumeroPagina, FilasXPagina, oEmpleado, ref TotalFilas); if (lst != null && lst.Count > 0) { int pages = (int)(TotalFilas / FilasXPagina); if (FilasXPagina * pages != TotalFilas) pages += 1; TotalPaginas = pages; } return lst; } private void LlenarGrillaDocumentosFiltrados(List<ElementoBE> lstResultado, int Paginas = 1) { gvDocumentosFiltrados.Visible = true; //if (lstResultado == null) // gvDocumentosFiltrados.Visible = false; //else // gvDocumentosFiltrados.Visible = true; if (Paginas > 1) tbPagerDocumentosFiltrados.Visible = true; else tbPagerDocumentosFiltrados.Visible = false; gvDocumentosFiltrados.DataSource = lstResultado; gvDocumentosFiltrados.DataBind(); } #region PAGINACIÓN DE POPUP BÚSQUEDA DE DOCUMENTOD protected void ddlPaginasDocumentosFiltrados_SelectedIndexChanged(object sender, EventArgs e) { if (ddlPaginasDocumentosFiltrados.SelectedItem != null) { int pageIndex = ddlPaginasDocumentosFiltrados.SelectedIndex + 1; BuscarDocumentos(pageIndex); //updResultado.Update(); } } protected void ibtnPaginacionDocumentosFiltrados_Click(object sender, System.Web.UI.ImageClickEventArgs e) { LlenarGrillaDocumentosFiltrados(null); PageIndexChangingDocumentosFiltrados(gvDocumentosFiltrados, (ImageButton)sender, ddlPaginasDocumentosFiltrados); ddlPaginasDocumentosFiltrados_SelectedIndexChanged(sender, e); } private void PageIndexChangingDocumentosFiltrados(GridView oGridView, ImageButton oBtnNavegacion, DropDownList ddl) { switch (oBtnNavegacion.CommandArgument) { case "First": { if (ddl.SelectedIndex >= 0) ddl.SelectedIndex = 0; } break; case "Prev": { if (ddl.SelectedIndex > 0) ddl.SelectedIndex -= 1; } break; case "Next": { if (ddl.SelectedIndex < ddl.Items.Count - 1) ddl.SelectedIndex += 1; } break; case "Last": { if (ddl.SelectedIndex >= 0) ddl.SelectedIndex = ddl.Items.Count - 1; } break; default: break; } } #endregion protected void btnElegirDocumentosFiltrados_Click(object sender, EventArgs e) { OcultarGrillaBuscadorDocumentos(); ((TextBox)FindControl(hdfCampoTextListaDocumento.Value)).Text = hdfTitleListaDocumento.Value.Trim(); //int id = (int)gvDocumentosFiltrados.DataKeys[row].Value; //string codigo = (string)gvDocumentosFiltrados.DataKeys[row].Values[1]; //string nombre = (string)gvDocumentosFiltrados.DataKeys[row].Values[2]; //List<CentroCostoBE> oListNotificarDocumentos = new List<CentroCostoBE>(); //if (ViewState["NotificarDocumentos"] != null) // oListNotificarDocumentos = (List<CentroCostoBE>)ViewState["NotificarDocumentos"]; //CentroCostoBE oCentroCostoBE = new CentroCostoBE(); //oCentroCostoBE.Id = Convert.ToInt32(hdfIdCeCoAgregado.Value); //oCentroCostoBE.Codigo = hdfCodigoCeCoAgregado.Value; //oCentroCostoBE.Descripcion = hdfDescripcionCeCoAgregado.Value; //oListNotificarDocumentos.Add(oCentroCostoBE); //ViewState["NotificarDocumentos"] = oListNotificarDocumentos; //gvDocumentos.DataSource = ViewState["NotificarDocumentos"]; //gvDocumentos.DataBind(); //upDocumentos.Update(); } #endregion #region *** POPUP MODIFICAR CADUCIDAD *** //protected void btnGuardarCaducidad_Click(object sender, EventArgs e) //{ // //OcultarGrillaModificarCaducidada(); // string CodigoDocumentoActual = txtCodigoDocumentoCabecera.Text; // if (!String.IsNullOrEmpty(hdfFechaModificarCaducidad.Value)) // { // DocumentoDDPBL.Instance.AsignarFechaCaducidad(URLSitioDocumento, txtCodigoDocumentoCabecera.Text, txtEstado.Text, Convert.ToDateTime(hdfFechaModificarCaducidad.Value) // , Convert.ToInt32(txtVersion.Text), txtMotivoModificarCaducidad.Text, SPContext.Current.Web.CurrentUser.Name); // } // txtFechaCaducidad.Text = txtFechaModificarCaducidad.Text; //} //protected void btnAbrirModificarCaducidad_Click(object sender, EventArgs e) //{ //} protected void btnGuardarEliminarDocumento_Click(object sender, EventArgs e) { EliminarDocumento(Convert.ToInt64(hdfVersionEliminarDocumento.Value)); } #endregion #region *** SECCION DE ACCIONES *** //protected void btnGuardarContribuidor_Click(object sender, EventArgs e) //{ // Guadar(); //} private string ValidarResponsables() { String Mensaje = String.Empty; SPUser oElaborador = Utilitarios.GetUserClientPeopleEditor(SPContext.Current.Site.Url, cppElaborador); if (SeccionElaborador.Visible == true) { if (oElaborador == null) { Mensaje = "Debe elegir un elaborador."; } else { Boolean EncuentraMP = false; Boolean EsSecreto = false; Boolean EsConfidencial = false; List<MacroProcesoBE> lst = MacroProcesoBL.Instance.ObtenerGruposSeguridadMacroprocesosContribuidor(URLSitioPrincipal, oElaborador.LoginName); if (lst != null) { ViewState["ElaboradorAprobador_SharePointGroupID"] = -1; if (lst.Count > 0) { if (ddlMacroProceso.SelectedItem.Value != String.Empty) { if (lst.Exists(MP => MP.Id.ToString() == ddlMacroProceso.SelectedItem.Value)) { ViewState["ElaboradorAprobador_SharePointGroupID"] = lst.Find(MP => MP.Id.ToString() == ddlMacroProceso.SelectedItem.Value).IdGrupoPublicoMacroproceso; EsSecreto = lst.Find(MP => MP.Id.ToString() == ddlMacroProceso.SelectedItem.Value).SecretoParaUsuarioActual; EsConfidencial = lst.Find(MP => MP.Id.ToString() == ddlMacroProceso.SelectedItem.Value).ConfidencialParaUsuarioActual; } } } } foreach (SPGroup oGrupo in oElaborador.Groups) { if (oGrupo.ID == (int)ViewState["ElaboradorAprobador_SharePointGroupID"]) { EncuentraMP = true; break; } } if (EncuentraMP == false) { Mensaje = "El elaborador elegido no pertenece al macroproceso seleccionado."; } else { if (ddlGrupoSeguridad.SelectedItem.Text == GruposSeguridad.Confidencial && EsConfidencial == false) { Mensaje = "El elaborador no es confidencial para el macroproceso seleccionado."; } if (ddlGrupoSeguridad.SelectedItem.Text == GruposSeguridad.Secreto && EsSecreto == false) { Mensaje = "El elaborador no es secreto para el macroproceso seleccionado."; } } } } if (SeccionRevisor.Visible == true) { SPUser oRevisor = Utilitarios.GetUserClientPeopleEditor(SPContext.Current.Site.Url, cppRevisor); if (oRevisor == null) { Mensaje = "Debe elegir un revisor."; } else { bool EsColaborador = false; bool EsColaboradorDeSC = false; foreach (SPGroup oGrupo in oRevisor.Groups) { if (oGrupo.Name.Contains(Constantes.IDENTIFICADOR_GRUPOS_COLABORADORES_PUBLICOS)) { EsColaborador = true; if (oGrupo.Name.Contains("GC")) { EsColaboradorDeSC = true; } } } if (!EsColaborador) { Mensaje = "El revisor seleccionado debe pertenecer al macroproceso " + ddlMacroProceso.SelectedItem.Text; //cppElaborador.AllEntities.Clear(); } else { if (ddlSistemaCalidad.SelectedItem.Text == "Sí" && EsColaboradorDeSC == false) { Mensaje = "El revisor seleccionado debe pertenecer al macroproceso de Gestión de Calidad."; } else if (SeccionElaborador.Visible == true) { if (oElaborador != null) { if (oElaborador.ID == oRevisor.ID) Mensaje = "El revisor y el elaborador deben ser distintos."; } } } } } if (SeccionAprobador.Visible == true) { SPUser oAprobador = Utilitarios.GetUserClientPeopleEditor(SPContext.Current.Site.Url, cppAprobador); { if (oAprobador == null) { Mensaje = "Debe elegir un aprobador."; } else if (SeccionElaborador.Visible == true) { if (oElaborador != null) { if (oElaborador.ID == oAprobador.ID) { Mensaje = "El aprobador y el elaborador deben ser distintos."; } } Boolean EncuentraMP = false; List<MacroProcesoBE> lst = MacroProcesoBL.Instance.ObtenerGruposSeguridadMacroprocesosContribuidor(URLSitioPrincipal, oAprobador.LoginName); if (lst != null) { ViewState["ElaboradorAprobador_SharePointGroupID"] = -1; if (lst.Count > 0) { if (ddlMacroProceso.SelectedItem.Value != String.Empty) { if (lst.Exists(MP => MP.Id.ToString() == ddlMacroProceso.SelectedItem.Value)) { ViewState["ElaboradorAprobador_SharePointGroupID"] = lst.Find(MP => MP.Id.ToString() == ddlMacroProceso.SelectedItem.Value).IdGrupoPublicoMacroproceso; } } } } foreach (SPGroup oGrupo in oAprobador.Groups) { if (oGrupo.ID == (int)ViewState["ElaboradorAprobador_SharePointGroupID"]) { EncuentraMP = true; } } if (EncuentraMP == false) { Mensaje = "El aprobador elegido no pertenece al macroproceso seleccionado."; } } } } return Mensaje; } private DocumentoDDPBE ObtenerDatosParaGuardar() { DocumentoDDPBE oDocumentoDDPBE = new DocumentoDDPBE(); if (!string.IsNullOrEmpty(hdfIdDocumentoDDP.Value)) { if (hdfIdDocumentoDDP.Value != Constantes.Caracteres.Cero) { oDocumentoDDPBE.ID = int.Parse(hdfIdDocumentoDDP.Value); oDocumentoDDPBE.CodigoDocumento = txtCodigoDocumentoCabecera.Text; } } #region *** SIMPLES *** oDocumentoDDPBE.Estado = txtEstado.Text; oDocumentoDDPBE.Version = Convert.ToInt32(txtVersion.Text); oDocumentoDDPBE.Titulo = txtTituloInput.Text; if (!string.IsNullOrEmpty(txtFechaPublicacion.Text)) oDocumentoDDPBE.FechaPublicacion = Convert.ToDateTime(txtFechaPublicacion.Text); if (!string.IsNullOrEmpty(hdfFechaModificarPublicacion.Value)) oDocumentoDDPBE.FechaPublicacion = Convert.ToDateTime(hdfFechaModificarPublicacion.Value); if (!string.IsNullOrEmpty(hdfFechaModificarCaducidad.Value)) oDocumentoDDPBE.FechaCaducidad = Convert.ToDateTime(hdfFechaModificarCaducidad.Value); oDocumentoDDPBE.CodigoUCM = hdfCodigoUCM.Value; oDocumentoDDPBE.Comentario = txtComentario.Text; oDocumentoDDPBE.ModificandosePor = txtModificandosePor.Text; if (!string.IsNullOrEmpty(ddlCorporativo.SelectedItem.Value) && ddlCorporativo.SelectedItem.Value != Constantes.ListaTextItem.Seleccione) { oDocumentoDDPBE.Corporativo = Convert.ToInt32(ddlCorporativo.SelectedItem.Value); } if (!string.IsNullOrEmpty(ddlDistribucionFisica.SelectedItem.Value) && ddlDistribucionFisica.SelectedItem.Value != Constantes.ListaTextItem.Seleccione) { oDocumentoDDPBE.DistribucionFisica = Convert.ToInt32(ddlDistribucionFisica.SelectedItem.Value); } if (!string.IsNullOrEmpty(ddlNotificacionCorporativa.SelectedItem.Value) && ddlNotificacionCorporativa.SelectedItem.Value != Constantes.ListaTextItem.Seleccione) { oDocumentoDDPBE.NotificacionCorporativa = Convert.ToInt32(ddlNotificacionCorporativa.SelectedItem.Value); } else { oDocumentoDDPBE.NotificacionCorporativa = -1; } oDocumentoDDPBE.RevisoresPM = txtRevisoresPM.Text; #endregion #region *** USUARIOS *** if (!string.IsNullOrEmpty(hdfIdContribuidor.Value)) { if (hdfIdContribuidor.Value != Constantes.Caracteres.Cero) { oDocumentoDDPBE.Contribuidor.ID = Convert.ToInt32(hdfIdContribuidor.Value); oDocumentoDDPBE.Contribuidor.DisplayName = txtContribuidor.Text; } } if (!string.IsNullOrEmpty(hdfIdBloqueadoVCPara.Value)) { if (hdfIdBloqueadoVCPara.Value != Constantes.Caracteres.Cero) { oDocumentoDDPBE.BloqueadoVCPara.ID = Convert.ToInt32(hdfIdBloqueadoVCPara.Value); //oDocumentoDDPBE.Contribuidor.DisplayName = txtContribuidor.Text; } } if (!string.IsNullOrEmpty(hdfIdBloqueadoPubPara.Value)) { if (hdfIdBloqueadoPubPara.Value != Constantes.Caracteres.Cero) { oDocumentoDDPBE.BloqueadoPubPara.ID = Convert.ToInt32(hdfIdBloqueadoPubPara.Value); //oDocumentoDDPBE.BloqueadoPubPara.DisplayName = txtContribuidor.Text; } } SPUser oElaborador = Utilitarios.GetUserClientPeopleEditor(SPContext.Current.Site.Url, cppElaborador); if (oElaborador != null) { oDocumentoDDPBE.Elaborador.ID = oElaborador.ID; oDocumentoDDPBE.Elaborador.DisplayName = oElaborador.Name; } if (SeccionTipoPlanMaestro.Visible == true) { if (!string.IsNullOrEmpty(ddlTipoPlanMaestro.SelectedItem.Value) && ddlTipoPlanMaestro.SelectedItem.Value != Constantes.ListaTextItem.Seleccione) { oDocumentoDDPBE.Revisor.ID = MacroProcesoBL.Instance.ObtenerGruposPorNombre(URLSitioPrincipal, Constantes.IDENTIFICADOR_GRUPO_REVISOR + ddlTipoPlanMaestro.SelectedItem.Value); oDocumentoDDPBE.Revisor.DisplayName = oDocumentoDDPBE.RevisoresPM; oDocumentoDDPBE.Revisor.EsGrupo = true; } } else { SPUser oRevisor = Utilitarios.GetUserClientPeopleEditor(SPContext.Current.Site.Url, cppRevisor); if (oRevisor != null) { oDocumentoDDPBE.Revisor.ID = oRevisor.ID; oDocumentoDDPBE.Revisor.DisplayName = oRevisor.Name; //oDocumentoDDPBE.Revisor= new UsuarioBE(); } } SPUser oAprobador = Utilitarios.GetUserClientPeopleEditor(SPContext.Current.Site.Url, cppAprobador); if (oAprobador != null) { oDocumentoDDPBE.Aprobador.ID = oAprobador.ID; oDocumentoDDPBE.Aprobador.DisplayName = oAprobador.Name; } List<String> oSPUCLectoresNoPublicos = Utilitarios.GetColeccionLoginName(cppLectoresNoPublicos); UsuarioBE oUsuario = null; if (oSPUCLectoresNoPublicos != null) { if (oSPUCLectoresNoPublicos.Count > 0) { foreach (String LoginName in oSPUCLectoresNoPublicos) { oUsuario = new UsuarioBE(); oUsuario.ID = Utilitarios.GetUserPorLoginName(SPContext.Current.Site.Url, LoginName).ID;// oUser.ID; oDocumentoDDPBE.LectoresNoPublicos.Add(oUsuario); } } } List<CompaniaBE> oListCompaniasElegidas = new List<CompaniaBE>(); List<UsuarioBE> oListGruposSubAdmin = new List<UsuarioBE>(); if (ddlCorporativo.SelectedItem.Value == Constantes.Caracteres.Uno) { UsuarioBE oGrupoSubAdmin = PaisBL.Instance.ObtenerGrupoSubadministradorCorporativo(URLSitioPrincipal); if (oGrupoSubAdmin != null) { if (!oListGruposSubAdmin.Exists(Grupo => Grupo.ID == oGrupoSubAdmin.ID)) oListGruposSubAdmin.Add(oGrupoSubAdmin); } } if (ViewState["CompaniasElegidas"] != null) { oListCompaniasElegidas = (List<CompaniaBE>)ViewState["CompaniasElegidas"]; foreach (CompaniaBE Compania in oListCompaniasElegidas) { UsuarioBE oGrupoSubAdmin = PaisBL.Instance.ObtenerGrupoSubadministradorPorPais(URLSitioPrincipal, Compania.Pais.Id); if (oGrupoSubAdmin != null) { if (!oListGruposSubAdmin.Exists(Grupo => Grupo.ID == oGrupoSubAdmin.ID)) oListGruposSubAdmin.Add(oGrupoSubAdmin); } } } oDocumentoDDPBE.SubAdministradores = oListGruposSubAdmin; if (oElaborador != null) { //string AreaElaborador = ComunBL.Instance.ObtenerValorPropiedadPerfil(oElaborador.LoginName, Constantes.NOMBRE_CAMPO_PERFIL_CENTROCOSTO); string AreaElaborador = PerfilesBL.Instance.ObtenerCCoPorCorreo(URLSitioPrincipal, oElaborador.Email); oDocumentoDDPBE.AreaElaborador = AreaElaborador; } #endregion #region *** COMBOS *** oDocumentoDDPBE.TipoDocumental = new TipoDocumentalBE(hdfIdTipoDocumento.Value, txtTipoDocumento.Text, hdfCodigoTipoDocumento.Value); if (!string.IsNullOrEmpty(ddlSistemaCalidad.SelectedItem.Value) && ddlSistemaCalidad.SelectedItem.Value != Constantes.ListaTextItem.Seleccione) { oDocumentoDDPBE.SistemaCalidad = ddlSistemaCalidad.SelectedItem.Value; //oDocumentoDDPBE.NotificacionCorporativa = Convert.ToInt32(ddlNotificacionCorporativa.SelectedItem.Value); } oDocumentoDDPBE.TipoPlanMaestro = new TipoPlanMaestroBE(ddlTipoPlanMaestro.SelectedItem.Value); oDocumentoDDPBE.GrupoSeguridad = new GrupoSeguridadBE(ddlGrupoSeguridad.SelectedItem.Value); if (!string.IsNullOrEmpty(ddlMacroProceso.SelectedItem.Value)) { oDocumentoDDPBE.MacroProceso = MacroProcesoBL.Instance.ObtenerxID(URLSitioPrincipal, Convert.ToInt32(ddlMacroProceso.SelectedItem.Value)); } if (!string.IsNullOrEmpty(ddlMetodoAnalisisPrincipal.SelectedItem.Value)) oDocumentoDDPBE.MetodoAnalisisPrincipal = new MetodoAnalisisPrincipalBE(ddlMetodoAnalisisPrincipal.SelectedItem.Value); if (!string.IsNullOrEmpty(ddlProceso.SelectedItem.Value)) { oDocumentoDDPBE.Proceso = new ProcesoBE(ddlProceso.SelectedItem.Value); oDocumentoDDPBE.Proceso.Title = ddlProceso.SelectedItem.Text; } //if (!string.IsNullOrEmpty(ddlAreaPrincipal.SelectedItem.Value)) //{ // oDocumentoDDPBE.AreaPrincipalID = Convert.ToInt32(ddlAreaPrincipal.SelectedItem.Value); // oDocumentoDDPBE.AreaPrincipal = ddlAreaPrincipal.SelectedItem.Text; //} //if (ddlSubArea.SelectedItem != null) //{ // if (!string.IsNullOrEmpty(ddlSubArea.SelectedItem.Value)) // { // oDocumentoDDPBE.SubAreaID = Convert.ToInt32(ddlSubArea.SelectedItem.Value); // oDocumentoDDPBE.SubArea = ddlSubArea.SelectedItem.Text; // } //} if (!string.IsNullOrEmpty(ddlClasificacion.SelectedItem.Value)) oDocumentoDDPBE.ClasificacionDocumentos = ddlClasificacion.SelectedItem.Value; #endregion #region *** BUSCADORES DE DOCUMENTOS ** if (!string.IsNullOrEmpty(hdfIdAcuerdoNivelServicio.Value)) oDocumentoDDPBE.AcuerdoNivelesServicio = new ElementoBE(Convert.ToInt32(hdfIdAcuerdoNivelServicio.Value), txtAcuerdoNivelServicio.Text); else oDocumentoDDPBE.AcuerdoNivelesServicio = null; if (!string.IsNullOrEmpty(hdfIdInstruccion.Value)) oDocumentoDDPBE.Instruccion = new ElementoBE(Convert.ToInt32(hdfIdInstruccion.Value), txtInstruccion.Text); else oDocumentoDDPBE.Instruccion = null; if (!string.IsNullOrEmpty(hdfIdDescripcionProcesos.Value)) oDocumentoDDPBE.DescripcionProcesos = new ElementoBE(Convert.ToInt32(hdfIdDescripcionProcesos.Value), txtDescripcionProcesos.Text); else oDocumentoDDPBE.DescripcionProcesos = null; if (!string.IsNullOrEmpty(hdfIdManualCalidad.Value)) oDocumentoDDPBE.ManualCalidad = new ElementoBE(Convert.ToInt32(hdfIdManualCalidad.Value), txtManualCalidad.Text); else oDocumentoDDPBE.ManualCalidad = null; if (!string.IsNullOrEmpty(hdfIdMetodoAnalisis.Value)) { if (txtMetodoAnalisis.Text.Contains("MAI-")) oDocumentoDDPBE.MetodoAnalisis = new ElementoBE(Convert.ToInt32(hdfIdMetodoAnalisis.Value), txtMetodoAnalisis.Text); else if (txtMetodoAnalisis.Text.Contains("MAE-")) oDocumentoDDPBE.MetodoAnalisisExterno = new ElementoBE(Convert.ToInt32(hdfIdMetodoAnalisis.Value), txtMetodoAnalisis.Text); else { oDocumentoDDPBE.MetodoAnalisis = null; oDocumentoDDPBE.MetodoAnalisisExterno = null; } } else { oDocumentoDDPBE.MetodoAnalisis = null; oDocumentoDDPBE.MetodoAnalisisExterno = null; } if (!string.IsNullOrEmpty(hdfIdPlanMaestro.Value)) oDocumentoDDPBE.PlanMaestro = new ElementoBE(Convert.ToInt32(hdfIdPlanMaestro.Value), txtPlanMaestro.Text); else oDocumentoDDPBE.PlanMaestro = null; if (!string.IsNullOrEmpty(hdfIdPolitica.Value)) oDocumentoDDPBE.Politica = new ElementoBE(Convert.ToInt32(hdfIdPolitica.Value), txtPolitica.Text); else oDocumentoDDPBE.Politica = null; if (!string.IsNullOrEmpty(hdfIdPoliticaCalidad.Value)) oDocumentoDDPBE.PoliticaCalidad = new ElementoBE(Convert.ToInt32(hdfIdPoliticaCalidad.Value), txtPoliticaCalidad.Text); else oDocumentoDDPBE.PoliticaCalidad = null; if (!string.IsNullOrEmpty(hdfIdProcedimiento.Value)) oDocumentoDDPBE.Procedimiento = new ElementoBE(Convert.ToInt32(hdfIdProcedimiento.Value), txtProcedimiento.Text); else oDocumentoDDPBE.Procedimiento = null; #endregion #region *** LISTAS *** if (ViewState["CompaniasElegidas"] != null) oDocumentoDDPBE.PaisCompanias = (List<CompaniaBE>)ViewState["CompaniasElegidas"]; if (ViewState["SubAreasElegidas"] != null) oDocumentoDDPBE.AreaSubAreas = (List<SubAreaBE>)ViewState["SubAreasElegidas"]; if (ViewState["NotificarCentroCostos"] != null) oDocumentoDDPBE.NotificarEnPublicacionA = (List<CentroCostoBE>)ViewState["NotificarCentroCostos"]; if (ViewState["ListaPreseleccionadosConfirmados"] != null) oDocumentoDDPBE.UsuariosNotificarEnPublicacionA = (List<PerfilesBE>)ViewState["ListaPreseleccionadosConfirmados"]; #endregion return oDocumentoDDPBE; } protected void btnEnviarContribuidor_Click(object sender, EventArgs e) { try { PreCargaSelectores(); // *** Validar USUARIOS ASIGNADOS *** // String Mensaje = ValidarResponsables(); if (Mensaje == String.Empty) { DocumentoDDPBE oDocumentoDDPBE = ObtenerDatosParaGuardar(); oDocumentoDDPBE.TipoDocumental = TipoDocumentalBL.Instance.ObtenerPorCodigo(URLSitioPrincipal, hdfCodigoTipoDocumento.Value); oDocumentoDDPBE.TipoDocumental.Codigo = hdfCodigoTipoDocumento.Value; oDocumentoDDPBE.CodigoDocumento = txtCodigoDocumentoCabecera.Text; oDocumentoDDPBE = DocumentoDDPBL.Instance.RegistrarEnFlujo(SPContext.Current.Site.Url, oDocumentoDDPBE, oDocumentoTemporal.Extension, SPContext.Current.Web.CurrentUser, oDocumentoTemporal.IdDocumento); hdfIdDocumentoDDP.Value = oDocumentoDDPBE.ID.ToString(); if (txtEstadoCabecera.Text == EstadosDDP.Contribucion) { oDocumentoDDPBE.UrlDocumento = @"/" + oDocumentoDDPBE.TipoDocumental.Codigo + Constantes.URL_PAGINA_FORMULARIO + oDocumentoDDPBE.ID.ToString(); } #region Registro BD intermedia DocumentoDDPBL.Instance.CrearNuevoRegistroDocumento(oDocumentoDDPBE); HistorialFlujoBE oHistorialFlujo = new HistorialFlujoBE(); oHistorialFlujo.CodigoDocumento = oDocumentoDDPBE.CodigoDocumento; oHistorialFlujo.Version = oDocumentoDDPBE.Version; oHistorialFlujo.Accion = Mensajes.HistorialGestorDocumental.EnviaContribuidor; oHistorialFlujo.Estado = oDocumentoDDPBE.Estado; oHistorialFlujo.FechaAccion = DateTime.Now; oHistorialFlujo.Usuario = SPContext.Current.Web.CurrentUser.Name; oHistorialFlujo.Comentario = string.Empty;// oDocumentoDDPBE.Comentario;//Comentado para que el campo comentario no se registre en el historial HistorialFlujoDDPBL.Instance.CrearNuevoRegistroHistorialFlujo(oHistorialFlujo); #endregion DocumentoDDPBL.Instance.AsignarPermisosDocumentoEnFlujoPorCodigoEstado(oDocumentoDDPBE, URLSitioPrincipal, EstadosDDP.Contribucion); if (oDocumentoDDPBE.Version == 1 && oDocumentoDDPBE.TipoDocumental.ListaDocumento != null) { ElementoBE oElementoBE = new ElementoBE(); oElementoBE.Title = oDocumentoDDPBE.Titulo; oElementoBE.Codigo = oDocumentoDDPBE.CodigoDocumento; oElementoBE.EstadoDocVigente = EstadosDDP.EnFlujo; if (oDocumentoDDPBE.Proceso != null) oElementoBE.IdProceso = oDocumentoDDPBE.Proceso.Id; if (oDocumentoDDPBE.Politica != null) oElementoBE.IdPolitica = oDocumentoDDPBE.Politica.Id; String TipoRelacion = null; if (oDocumentoDDPBE.TipoDocumental.Codigo == Constantes.CodigoTipoDocumental.DescripcionProcesos || oDocumentoDDPBE.TipoDocumental.Codigo == Constantes.CodigoTipoDocumental.PoliticasProceso) TipoRelacion = Constantes.TipoRelacionIntermedia.Proceso; if (oDocumentoDDPBE.TipoDocumental.Codigo == Constantes.CodigoTipoDocumental.Procedimientos || oDocumentoDDPBE.TipoDocumental.Codigo == Constantes.CodigoTipoDocumental.Intrucciones || oDocumentoDDPBE.TipoDocumental.Codigo == Constantes.CodigoTipoDocumental.MetodoAnalisisInterno || oDocumentoDDPBE.TipoDocumental.Codigo == Constantes.CodigoTipoDocumental.MetodoAnalisisExterno) TipoRelacion = Constantes.TipoRelacionIntermedia.Politica; ElementoBL.Instance.Registrar(URLSitioPrincipal, oDocumentoDDPBE.TipoDocumental.ListaDocumento, oElementoBE, TipoRelacion); } txtCodigoDocumentoCabecera.Text = oDocumentoDDPBE.CodigoDocumento; txtTituloCabecera.Text = oDocumentoDDPBE.Titulo; Mensaje = String.Format(Mensajes.ExitoGestorDocumental.EnvioCorrectamente, txtCodigoDocumentoCabecera.Text); string Funcion = "AlertaAvisoRedirigir"; btnEnviarContribuidor.Enabled = false; WebUtil.AlertRedirectServer(Page, this.GetType(), TipoAlerta.Aviso, Funcion, Mensaje, SPContext.Current.Site.Url); } else { Utilitarios.AlertServer(this, Constantes.TiposAlerta.Validacion, Mensaje); } } catch (Exception ex) { Utilitarios.AlertServer(this, Constantes.TiposAlerta.Error, ex.Message); } } protected void btnCancelar_Click(object sender, EventArgs e) { string Mensaje = Mensajes.ExitoGestorDocumental.Cancelar; string Funcion = "AlertaAvisoRedirigir"; WebUtil.AlertRedirectServer(Page, this.GetType(), TipoAlerta.Aviso, Funcion, Mensaje, SPContext.Current.Site.Url); } protected void btnEnviarElaborador_Click(object sender, EventArgs e) { try { if (String.IsNullOrEmpty(hdfModificoDatos.Value)) { List<String> oSPUCLectoresNoPublicos = Utilitarios.GetColeccionLoginName(cppLectoresNoPublicos); if (oSPUCLectoresNoPublicos.Count == 0) { string Mensaje = String.Format(Mensajes.ExitoGestorDocumental.NoModificoDatos, txtCodigoDocumentoCabecera.Text); string Funcion = "AlertaAviso"; WebUtil.AlertServer(Page, this.GetType(), TipoAlerta.Aviso, Funcion, Mensaje); //string Funcion = "AlertaAvisoRedirigir"; //WebUtil.AlertRedirectServer(Page, this.GetType(), TipoAlerta.Aviso, Funcion, Mensaje, SPContext.Current.Site.Url); } else { String Logins = String.Empty; foreach (string Login in oSPUCLectoresNoPublicos) { Logins = Logins + "; " + Login; Logins = Logins.TrimStart(';'); } if (((String)ViewState["LectoresNoPublicosInicial"]) != Logins) { ActualizarDocumentoEnvioConsolidado(); } else { string Mensaje = String.Format(Mensajes.ExitoGestorDocumental.NoModificoDatos, txtCodigoDocumentoCabecera.Text); string Funcion = "AlertaAviso"; WebUtil.AlertServer(Page, this.GetType(), TipoAlerta.Aviso, Funcion, Mensaje); } } } else { ActualizarDocumentoEnvioConsolidado(); } } catch (Exception ex) { Utilitarios.AlertServer(this, Constantes.TiposAlerta.Aviso, Mensajes.Error.CargaDeDocumento + " : " + ex.Message); } } protected void ActualizarDocumentoEnvioConsolidado() { ActualizarDocumentoEnvio(); btnEnviarElaborador.Enabled = false; string Mensaje = String.Format(Mensajes.ExitoGestorDocumental.ActualizoCorrectamente, txtCodigoDocumentoCabecera.Text); string Funcion = "AlertaAvisoRedirigir"; WebUtil.AlertRedirectServer(Page, this.GetType(), TipoAlerta.Aviso, Funcion, Mensaje, SPContext.Current.Site.Url); } protected void btnEnviarAdministradorSubAdministrador_Click(object sender, EventArgs e) { //Utilitarios.AlertServer(this, Constantes.TiposAlerta.Validacion, hdfModificoDatos.Value); try { //if (string.IsNullOrEmpty(hdfModificoDatos.Value) && !ValidaCambioResponsables()) //{ // string Mensaje = String.Format(Mensajes.ExitoGestorDocumental.NoModificoDatos, txtCodigoDocumentoCabecera.Text); // string Funcion = "AlertaAviso"; // WebUtil.AlertServer(Page, this.GetType(), TipoAlerta.Aviso, Funcion, Mensaje); //} //else //{ String Mensaje = String.Empty; if (txtEstadoCabecera.Text != EstadosDDP.Publicado) { Mensaje = ValidarResponsables(); } if (Mensaje == String.Empty) { ActualizarDocumentoEnvioSubAdminAdministrador(); btnEnviarSubAdministrador.Enabled = false; Mensaje = String.Format(Mensajes.ExitoGestorDocumental.GuardoCorrectamente, txtCodigoDocumentoCabecera.Text); string Funcion = "AlertaAvisoRedirigir"; WebUtil.AlertRedirectServer(Page, this.GetType(), TipoAlerta.Aviso, Funcion, Mensaje, SPContext.Current.Site.Url); } else { Utilitarios.AlertServer(this, Constantes.TiposAlerta.Validacion, Mensaje); } //} } catch (Exception ex) { Utilitarios.AlertServer(this, Constantes.TiposAlerta.Error, ex.Message); } } public void ActualizarDocumentoEnvioSubAdminAdministrador() { DocumentoDDPBE oDocumentoDDPBE = ObtenerDatosParaGuardar(); oDocumentoDDPBE.TipoDocumental.Codigo = hdfCodigoTipoDocumento.Value; oDocumentoDDPBE.TipoDocumental = TipoDocumentalBL.Instance.ObtenerPorCodigo(URLSitioPrincipal, hdfCodigoTipoDocumento.Value); oDocumentoDDPBE.CodigoDocumento = txtCodigoDocumentoCabecera.Text; if (txtEstado.Text == EstadosDDP.Publicacion) { oDocumentoDDPBE.Estado = EstadosDDP.Publicacion; //CentroCostoBE oCeCoA = new CentroCostoBE(); } String URLSitioActualizar = URLSitioPrincipal; if (SPContext.Current.Web.Url.Contains(Constantes.URL_SUBSITIO_PUBLICADO)) { URLSitioActualizar = URLSitioDocumento; } DocumentoDDPBL.Instance.ForceCheckInDocumento(oDocumentoDDPBE.ID, oDocumentoDDPBE.TipoDocumental.Biblioteca, URLSitioDocumento); oDocumentoDDPBE.Sincronizado = false; DocumentoDDPBL.Instance.Actualizar(URLSitioActualizar, oDocumentoDDPBE, URLSitioPrincipal); if (txtEstado.Text == EstadosDDP.Publicado && oDocumentoDDPBE.TipoDocumental.ListaDocumento != null) { ElementoBE oElemento = new ElementoBE(); oElemento.Codigo = oDocumentoDDPBE.CodigoDocumento; oElemento.EstadoDocVigente = txtEstado.Text; oElemento.Title = oDocumentoDDPBE.Titulo; ElementoBL.Instance.Actualizar(URLSitioPrincipal, oDocumentoDDPBE.TipoDocumental.ListaDocumento, oElemento); } HistorialFlujoBE oHistorialFlujo = new HistorialFlujoBE(); oHistorialFlujo.CodigoDocumento = oDocumentoDDPBE.CodigoDocumento; oHistorialFlujo.Version = oDocumentoDDPBE.Version; oHistorialFlujo.FechaAccion = DateTime.Now; oHistorialFlujo.Usuario = SPContext.Current.Web.CurrentUser.Name; oHistorialFlujo.Estado = oDocumentoDDPBE.Estado; if (!string.IsNullOrEmpty(hdfMotivoModificarCaducidad.Value)) { oHistorialFlujo.Comentario = hdfMotivoModificarCaducidad.Value; oHistorialFlujo.Accion = Mensajes.HistorialGestorDocumental.ActualizaFechaCaducidad; HistorialFlujoDDPBL.Instance.CrearNuevoRegistroHistorialFlujo(oHistorialFlujo); } //Guardar Modificación de Fecha de Publicación if (!string.IsNullOrEmpty(hdfMotivoModificarPublicacion.Value)) { VersionBL.Instance.ActualizarFechaPublicacion(oDocumentoDDPBE.CodigoDocumento, oDocumentoDDPBE.Version, oDocumentoDDPBE.Estado, oDocumentoDDPBE.FechaPublicacion); oHistorialFlujo.Comentario = hdfMotivoModificarPublicacion.Value; oHistorialFlujo.Accion = Mensajes.HistorialGestorDocumental.ActualizaFechaPublicacion; HistorialFlujoDDPBL.Instance.CrearNuevoRegistroHistorialFlujo(oHistorialFlujo); } if (string.IsNullOrEmpty(hdfMotivoModificarCaducidad.Value) && string.IsNullOrEmpty(hdfMotivoModificarPublicacion.Value)) { oHistorialFlujo.Comentario = string.Empty;// oDocumentoDDPBE.Comentario;//Comentado para que el campo comentario no se registre en el historial oHistorialFlujo.Accion = Mensajes.HistorialGestorDocumental.Actualiza; HistorialFlujoDDPBL.Instance.CrearNuevoRegistroHistorialFlujo(oHistorialFlujo); } } public Boolean ValidaCambioResponsables() { bool CambioResponsables = false; SPUser oElaborador = Utilitarios.GetUserClientPeopleEditor(SPContext.Current.Site.Url, cppElaborador); if (oElaborador != null) { if (oElaborador.LoginName != (string)ViewState["ElaboradorInicial"]) CambioResponsables = true; } else { if (((String)ViewState["ElaboradorInicial"]) != String.Empty) CambioResponsables = true; } SPUser oAprobador = Utilitarios.GetUserClientPeopleEditor(SPContext.Current.Site.Url, cppAprobador); if (oAprobador != null) { if (oAprobador.LoginName != (string)ViewState["AprobadorInicial"]) CambioResponsables = true; } else { if (((String)ViewState["AprobadorInicial"]) != String.Empty) CambioResponsables = true; } SPUser oRevisor = Utilitarios.GetUserClientPeopleEditor(SPContext.Current.Site.Url, cppRevisor); if (oRevisor != null) { if (oRevisor.LoginName != (string)ViewState["RevisorInicial"]) CambioResponsables = true; } else { if (((String)ViewState["RevisorInicial"]) != String.Empty) CambioResponsables = true; } if (SeccionLestoresNoPublicos.Visible && cppLectoresNoPublicos.Visible) { List<String> oSPUCLectoresNoPublicos = Utilitarios.GetColeccionLoginName(cppLectoresNoPublicos); if (oSPUCLectoresNoPublicos.Count == 0) { if (!String.IsNullOrEmpty((String)ViewState["LectoresNoPublicosInicial"])) CambioResponsables = true; //string Mensaje = String.Format(Mensajes.ExitoGestorDocumental.NoModificoDatos, txtCodigoDocumentoCabecera.Text); //string Funcion = "AlertaAvisoRedirigir"; //WebUtil.AlertRedirectServer(Page, this.GetType(), TipoAlerta.Aviso, Funcion, Mensaje, SPContext.Current.Site.Url); } else { String Logins = String.Empty; foreach (string Login in oSPUCLectoresNoPublicos) { Logins = Logins + "; " + Login; } if (((String)ViewState["LectoresNoPublicosInicial"]) != Logins.TrimStart(';')) { CambioResponsables = true; } } } return CambioResponsables; } public void ActualizarDocumentoEnvio() { DocumentoDDPBE oDocumentoDDPBE = ObtenerDatosParaGuardar(); DocumentoDDPBL.Instance.ForceCheckInDocumento(oDocumentoDDPBE.ID, oDocumentoDDPBE.TipoDocumental.Biblioteca, URLSitioDocumento); DocumentoDDPBL.Instance.Actualizar(URLSitioPrincipal, oDocumentoDDPBE); HistorialFlujoBE oHistorialFlujo = new HistorialFlujoBE(); oHistorialFlujo.CodigoDocumento = oDocumentoDDPBE.CodigoDocumento; oHistorialFlujo.Accion = Mensajes.HistorialGestorDocumental.Actualiza; oHistorialFlujo.Version = oDocumentoDDPBE.Version; oHistorialFlujo.FechaAccion = DateTime.Now; oHistorialFlujo.Usuario = SPContext.Current.Web.CurrentUser.Name; oHistorialFlujo.Comentario = string.Empty;// oDocumentoDDPBE.Comentario;//Comentado para que el campo comentario no se registre en el historial oHistorialFlujo.Estado = oDocumentoDDPBE.Estado; HistorialFlujoDDPBL.Instance.CrearNuevoRegistroHistorialFlujo(oHistorialFlujo); } #endregion private void EliminarDocumento(Int64 Version) { try { //ScriptManager.RegisterClientScriptBlock(this.upOtrasFuncionalidades, this.upOtrasFuncionalidades.GetType(), "btnGuardar_Click3", "Redirigir('http://www.google.com');", true); hdfVersionEliminarDocumento.Value = Constantes.Caracteres.Cero; string URLSitioGestor = SPContext.Current.Site.Url; if (gvReferenciaA.Rows.Count == 0 && gvReferenciadoPor.Rows.Count == 0) { string Mensaje = String.Empty; string Funcion = String.Empty; //int row = Convert.ToInt32(e.CommandArgument.ToString()); // Int64 Version = (Int64)gvHistorialVersiones.DataKeys[row].Value; HistorialFlujoBE oHistorialFlujo = new HistorialFlujoBE(); oHistorialFlujo.CodigoDocumento = txtCodigoDocumentoCabecera.Text; oHistorialFlujo.Accion = "Se eliminó el Documento."; oHistorialFlujo.Estado = txtEstadoCabecera.Text; oHistorialFlujo.FechaAccion = DateTime.Today; oHistorialFlujo.Usuario = SPContext.Current.Web.CurrentUser.Name; oHistorialFlujo.Comentario = txtMotivoEliminarDocumento.Text; VersionBL.Instance.EliminarVersion(URLSitioGestor, URLSitioDocumento, Version, txtCodigoDocumentoCabecera.Text, oHistorialFlujo, "NombreBiblioteca", SPContext.Current.Web.CurrentUser.ID); if (txtVersion.Text != Version.ToString()) { CargarHistorialVersiones(txtCodigoDocumentoCabecera.Text, SPContext.Current.List.Title, Convert.ToInt32(txtVersion.Text)); upHistorialVersiones.Update(); Mensaje = String.Format(Mensajes.ExitoGestorDocumental.EliminoVersionCorrectamente, Version.ToString(), txtCodigoDocumentoCabecera.Text); Funcion = "AlertaAviso"; WebUtil.AlertServer(Page, this.GetType(), TipoAlerta.Aviso, Funcion, Mensaje); } else { //Mensaje = SPContext.Current.Site.Url; //Funcion = "Redirigir"; //WebUtil.Redirect(Page, this.GetType(), Funcion, Mensaje); this.Page.Response.Redirect(SPContext.Current.Site.Url); } this.Page.Response.Redirect(SPContext.Current.Site.Url); //registrar en historial } else { WebUtil.AlertServer(Page, this.GetType(), TipoAlerta.Aviso, "AlertaAviso", Mensajes.Validacion.DocumentoTieneRelaciones); } } catch (Exception ex) { //WebUtil.Redirect(Page, this.GetType(), "Redirigir", SPContext.Current.Site.Url); throw; } } protected void btnNuevaVersion_Click(object sender, EventArgs e) { TipoDocumentalBE TipoDocumental = TipoDocumentalBL.Instance.ObtenerPorCodigo(URLSitioPrincipal, hdfCodigoTipoDocumento.Value); List<DocumentoDDPBE> lst_DocumentoEnFlujo = DocumentoDDPBL.Instance.ObtenerListaDocumentosEnFlujoPorCodigo(txtCodigoDocumentoCabecera.Text, TipoDocumental.Biblioteca, hdfUrlSitio.Value); string Funcion = "AlertaAvisoRedirigir"; string URL = SPContext.Current.Site.Url + @"/Paginas/Nuevo.aspx?TD=" + hdfCodigoTipoDocumento.Value + "&IDNV=" + hdfIdDocumentoDDP.Value; string Mensaje = Mensajes.ExitoGestorDocumental.GeneroNuevaVersion; if (lst_DocumentoEnFlujo.Count <= 0) { WebUtil.AlertRedirectServer(Page, this.GetType(), TipoAlerta.Aviso, Funcion, Mensaje, URL); } else { if (lst_DocumentoEnFlujo.Exists(x => !x.Eliminado)) { Utilitarios.AlertServer(this, Constantes.TiposAlerta.Validacion, "Existe una nueva versión del documento, actualmente se encuentra en flujo."); } else if (lst_DocumentoEnFlujo.Exists(x => x.Eliminado)) { Mensaje = "Existe una versión eliminada que se puede restaurar, por favor contacte al Administrador de Gestión Documental."; WebUtil.AlertRedirectServer(Page, this.GetType(), TipoAlerta.Aviso, Funcion, Mensaje, URL); } } } protected void PreCargaSelectores() { SPUser oElaborador = Utilitarios.GetUserClientPeopleEditor(SPContext.Current.Site.Url, cppElaborador); if (oElaborador != null) { PeopleEditor pe = new PeopleEditor(); PickerEntity entity = new PickerEntity(); ViewState["Elaborador"] = oElaborador.LoginName; } if (SeccionTipoPlanMaestro.Visible == false) { SPUser oRevisor = Utilitarios.GetUserClientPeopleEditor(SPContext.Current.Site.Url, cppRevisor); if (oRevisor != null) { PeopleEditor pe = new PeopleEditor(); PickerEntity entity = new PickerEntity(); ViewState["Revisor"] = oRevisor.LoginName; } } SPUser oAprobador = Utilitarios.GetUserClientPeopleEditor(SPContext.Current.Site.Url, cppAprobador); if (oAprobador != null) { PeopleEditor pe = new PeopleEditor(); PickerEntity entity = new PickerEntity(); ViewState["Aprobador"] = oAprobador.LoginName; } } protected void btnConfirmarCarga_Click(object sender, EventArgs e) { try { PreCargaSelectores(); if (fupArchivo.HasFile) { int filezise = fupArchivo.FileBytes.Length; //.PostedFile.ContentLength;// .FileBytes.l; if (filezise <= 500 * 1024 * 1024)//Valida que el archivo no supere los 500 MB CargarAdjuntosTemporales(); else Utilitarios.AlertServer(this, Constantes.TiposAlerta.Validacion, "El Tamaño de archivo supera los 500 MB."); } } catch (Exception ex) { Utilitarios.AlertServer(this, Constantes.TiposAlerta.Error, Mensajes.Error.AlGuardarSolicitud + " : " + ex.Message); } WebUtil.EjecutarFuncionJS(Page, this.GetType(), "verificarMacroproceso();"); } public DocumentoCargadoBE oDocumentoTemporal { get { if (ViewState["oDocumentoTemporal"] == null) ViewState["oDocumentoTemporal"] = new DocumentoCargadoBE(); return (DocumentoCargadoBE)ViewState["oDocumentoTemporal"]; } set { ViewState["oDocumentoTemporal"] = value; } } private void CargarAdjuntosTemporales() { List<DocumentoCargadoBE> oListDocumentoCargadoBE = new List<DocumentoCargadoBE>(); //*** CAMBIO *** if (oDocumentoTemporal.IdDocumento != 0) { DocumentoDDPBL.Instance.EliminarDocumentoFlujoXId(URLSitioPrincipal, ListasGestorDocumental.Temporal, oDocumentoTemporal.IdDocumento); } if (fupArchivo.FileName.Length > 0) { DocumentoCargadoBE oDocumentoCargadoBE = new DocumentoCargadoBE(); string tempTitulo = string.Format("{0}{1}", hdfSessionUsuario.Value, Path.GetExtension(fupArchivo.FileName)); oDocumentoCargadoBE.URLDocumento = string.Format("{0}/{1}/{2}", URLSitioPrincipal, ListasGestorDocumental.Temporal, tempTitulo); oDocumentoCargadoBE.IdDocumento = DocumentoDDPBL.UploadAdjuntoTemporal(URLSitioPrincipal, oDocumentoCargadoBE.URLDocumento, fupArchivo.FileBytes); oDocumentoCargadoBE.NombreDocumento = fupArchivo.FileName; oDocumentoCargadoBE.Extension = Path.GetExtension(fupArchivo.FileName); oDocumentoTemporal = oDocumentoCargadoBE; oListDocumentoCargadoBE.Add(oDocumentoCargadoBE); } ListarAdjuntosTemporales(oListDocumentoCargadoBE); DivAdjuntosSolicitante.Visible = true; } public static string RemoveSpecialCharacters(string str) { StringBuilder sb = new StringBuilder(); foreach (char c in str) { if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '.' || c == '_') { sb.Append(c); } } return sb.ToString(); } private void ListarAdjuntosTemporales(List<DocumentoCargadoBE> lstDocumentoCargado) { gvAdjuntosSolicitante.DataSource = lstDocumentoCargado; gvAdjuntosSolicitante.DataBind(); } protected void btnCerrar_Click(object sender, EventArgs e) { string Mensaje = Mensajes.ExitoGestorDocumental.Cerrar; string Funcion = "AlertaAvisoRedirigir"; WebUtil.AlertRedirectServer(Page, this.GetType(), TipoAlerta.Aviso, Funcion, Mensaje, SPContext.Current.Site.Url); } protected void ddlCorporativo_SelectedIndexChanged(object sender, EventArgs e) { ViewState["CompaniasElegidas"] = null; gvCompaniaPais.DataSource = ViewState["CompaniasElegidas"]; gvCompaniaPais.DataBind(); WebUtil.EjecutarFuncionJS(Page, this.GetType(), "verificarMacroproceso();"); } protected void ddlDistribucionFisica_SelectedIndexChanged(object sender, EventArgs e) { ViewState["SubAreasElegidas"] = null; gvAreaSubArea.DataSource = ViewState["SubAreasElegidas"]; gvAreaSubArea.DataBind(); WebUtil.EjecutarFuncionJS(Page, this.GetType(), "verificarMacroproceso();"); } private void ActivarControlesSubAdminAdmin(string Estado) { btnEnviarSubAdministrador.Visible = true; if (Estado == EstadosDDP.Publicado) { pnlDatosAdicionales.Enabled = true; pnlAcciones.Visible = true; pnlDatosPrincipalesSecundarios.Enabled = true; ddlGrupoSeguridad.Enabled = false; if ((bool)ViewState["EsAdministrador"]) ddlClasificacion.Enabled = true; else ddlClasificacion.Enabled = false; ddlSistemaCalidad.Enabled = false; txtComentario.Enabled = true; ddlMacroProceso.Enabled = false; ddlProceso.Enabled = false; pnlUsuariosParticipantes.Enabled = false; pnlBuscadores.Enabled = false; SeccionBotonesCaducidadPublicacion.Visible = true; btnModificarListaCentroCostos.Visible = true; } if (Estado != EstadosDDP.Publicado && Estado != EstadosDDP.Caducado && Estado != EstadosDDP.Obsoleto) { //***CAMBIO*** DivfupArchivo.Visible = true; btnConfirmarCarga.Visible = false; btnReemplazar.Visible = true; pnlDatosAdicionales.Enabled = true; pnlAcciones.Visible = true; pnlDatosPrincipalesSecundarios.Enabled = true; ddlGrupoSeguridad.Enabled = false; ddlClasificacion.Enabled = false; txtComentario.Enabled = true; ddlMacroProceso.Enabled = true; ddlProceso.Enabled = true; pnlUsuariosParticipantes.Enabled = true; pnlBuscadores.Enabled = true; //Sistema de calidad solo debe ser modificado en Verificacion de calidad if (Estado != EstadosDDP.VerificacionCalidad && Estado != EstadosDDP.Elaboracion) ddlSistemaCalidad.Enabled = false; if (SeccionElaborador.Visible == true) { cppElaborador.Visible = true; txtElaborador.Visible = false; AbrirBuscadorElaborador.Visible = true; } if (SeccionAprobador.Visible == true) { cppAprobador.Visible = true; txtAprobador.Visible = false; AbrirBuscadorAprobador.Visible = true; } if (SeccionRevisor.Visible == true) { cppRevisor.Visible = true; txtRevisor.Visible = false; AbrirBuscadorRevisor.Visible = true; } if (SeccionLestoresNoPublicos.Visible == true) { cppLectoresNoPublicos.Visible = true; txtLectoresNoPublicos.Visible = false; } } } protected void btnCargarVersiones_Click(object sender, EventArgs e) { CargarHistorialVersiones(txtCodigoDocumentoCabecera.Text, SPContext.Current.List.Title, Convert.ToInt32(txtVersion.Text)); } protected void btnModificarDatos_Click(object sender, EventArgs e) { ViewState["btnModificarDatos_Click"] = "True"; ActivarControlesSubAdminAdmin(txtEstado.Text); } protected void gvHistorialVersiones_RowDataBound(object sender, GridViewRowEventArgs e) { //Checking the RowType of the Row if (e.Row.RowType == DataControlRowType.DataRow) { string strVersion = gvHistorialVersiones.DataKeys[e.Row.RowIndex].Values[0].ToString(); string strEstado = gvHistorialVersiones.DataKeys[e.Row.RowIndex].Values[1].ToString(); if (strVersion == txtVersion.Text || strEstado == EstadosDDP.EnFlujo || strEstado == EstadosDDP.Eliminado) { ImageButton btnEliminar = e.Row.FindControl("ibtnEliminar") as ImageButton; btnEliminar.Visible = false; } if (strEstado == EstadosDDP.Eliminado) { HyperLink hplVersion = e.Row.FindControl("hplVersion") as HyperLink; Label lblVersion = e.Row.FindControl("lblVersion") as Label; hplVersion.Visible = false; lblVersion.Visible = true; } ////If Salary is less than 10000 than set the row Background Color to Cyan //if (Convert.ToInt32(e.Row.Cells[3].Text) < 10000) //{ // //e.Row.BackColor = Color.Cyan; //} } } protected void gvAdjuntosSolicitante_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { HyperLink hplDocumento = e.Row.FindControl("hplDocumento") as HyperLink; string idDocumento = gvAdjuntosSolicitante.DataKeys[e.Row.RowIndex].Values[0].ToString(); string NombreDocumento = gvAdjuntosSolicitante.DataKeys[e.Row.RowIndex].Values[1].ToString(); string UrlDocumento = gvAdjuntosSolicitante.DataKeys[e.Row.RowIndex].Values[2].ToString(); string extension = Path.GetExtension(UrlDocumento); //Se asocian los eventos onclientclick del enlace al documento switch (extension) { //case ".doc": //case ".docx": //case ".xlsx": //case ".ppt": //case ".pptx": //case ".pdf": // hplDocumento.Attributes["href"] = string.Format("{0}/_layouts/15/WopiFrame.aspx?sourcedoc={1}&action=embedview&DefaultItemOpen=1", URLSitioDocumento, UrlDocumento); // break; //case ".xls": // hplDocumento.Attributes["href"] = string.Format("{0}/_layouts/15/WopiFrame.aspx?sourcedoc={1}&action=view&DefaultItemOpen=1", URLSitioDocumento, UrlDocumento); // break; //case ".vsd": //case ".vsdx": // hplDocumento.Attributes["href"] = string.Format("{0}/_layouts/15/VisioWebAccess/VisioWebAccess.aspx?id={1}&action=embedview&DefaultItemOpen=1", URLSitioDocumento, UrlDocumento); // break; case ".pdf": hplDocumento.Attributes["href"] = UrlDocumento; break; default: hplDocumento.Attributes["href"] = URLSitioDocumento + "/_layouts/download.aspx?SourceUrl=" + UrlDocumento; break; } } } private void ValidarAtenderTarea(int IDTarea) { TareaDDPBE objTarea = TareaDDPBL.Instance.ObtenerTareaPorId(IDTarea, hdfUrlSitio.Value); SPUser oUser = SPContext.Current.Web.CurrentUser; if (objTarea != null && objTarea.EstadoTarea != EstadosTarea.Completadas && objTarea.AsignadoID == oUser.ID) btnAtenderTarea.Visible = true; } protected void btnAtenderTarea_Click(object sender, EventArgs e) { try { if (divBotonesElaborador.Visible == true) { Boolean SeHaModificacoDatos = false; if (String.IsNullOrEmpty(hdfModificoDatos.Value)) { List<String> oSPUCLectoresNoPublicos = Utilitarios.GetColeccionLoginName(cppLectoresNoPublicos); if (oSPUCLectoresNoPublicos.Count != 0) { String Logins = String.Empty; foreach (string Login in oSPUCLectoresNoPublicos) { Logins = Logins + "; " + Login; Logins = Logins.TrimStart(';'); } if (((String)ViewState["LectoresNoPublicosInicial"]) != Logins) { SeHaModificacoDatos = true; } } } else { SeHaModificacoDatos = true; } if (SeHaModificacoDatos == true) { ActualizarDocumentoEnvio(); hdfModificoDatos.Value = string.Empty; } WebUtil.EjecutarFuncionJS(up, up.GetType(), "AbrirTarea();"); } else if (divBotonesAdministradorSubAdministrador.Visible == true) { if (String.IsNullOrEmpty(hdfModificoDatos.Value) == false || ValidaCambioResponsables() == true) { String Mensaje = ValidarResponsables(); if (Mensaje == String.Empty) { ActualizarDocumentoEnvioSubAdminAdministrador(); hdfModificoDatos.Value = string.Empty; WebUtil.EjecutarFuncionJS(up, up.GetType(), "AbrirTarea();"); } else { Utilitarios.AlertServer(this, Constantes.TiposAlerta.Validacion, Mensaje); } } else { WebUtil.EjecutarFuncionJS(up, up.GetType(), "AbrirTarea();"); } } else if (divBotonesSoloLectura.Visible == true) { WebUtil.EjecutarFuncionJS(up, up.GetType(), "AbrirTarea();"); } } catch (Exception ex) { Utilitarios.AlertServer(this, Constantes.TiposAlerta.Aviso, Mensajes.Error.CargaDeDocumento + " : " + ex.Message); } } protected void btnReemplazar_Click(object sender, EventArgs e) { try { string extensionTemporal = Path.GetExtension(fupArchivo.FileName); if (oDocumentoTemporal.Extension != extensionTemporal) { Utilitarios.AlertServer(this, Constantes.TiposAlerta.Validacion, "El archivo debe tener la misma extensión."); return; } //if (ConfirmarYCargaTemporal(true) == true) //{ DocumentoDDPBE oDocumentoDDPBE = ObtenerDatosParaGuardar(); DocumentoDDPBL.Instance.ForceCheckInDocumento(oDocumentoDDPBE.ID, oDocumentoDDPBE.TipoDocumental.Biblioteca, URLSitioPrincipal); //SPFile ArchivoTemporal = DocumentoDDPBL.Instance.ObtenerArchivoXId(URLSitioPrincipal, ListasGestorDocumental.Temporal, IdDocumento); //oDocumentoDDPBE.Archivo = fupArchivo.FileBytes; //oDocumentoDDPBE.Archivo = ArchivoTemporal.OpenBinary(); oDocumentoDDPBE.TipoDocumental = TipoDocumentalBL.Instance.ObtenerPorCodigo(URLSitioPrincipal, hdfCodigoTipoDocumento.Value); oDocumentoDDPBE.TipoDocumental.Codigo = hdfCodigoTipoDocumento.Value; oDocumentoDDPBE.CodigoDocumento = txtCodigoDocumentoCabecera.Text; //string mensaje = String.Empty; //if (oDocumentoDDPBE.ID > 0) // mensaje = Mensajes.ExitoGestorDocumental.ActualizoCorrectamente; //else // mensaje = Mensajes.ExitoGestorDocumental.GuardoCorrectamente; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite objSPSite = new SPSite(URLSitioPrincipal)) { using (SPWeb objSPWeb = objSPSite.OpenWeb()) { objSPWeb.AllowUnsafeUpdates = true; SPList objSPList = objSPWeb.Lists[oDocumentoDDPBE.TipoDocumental.Biblioteca]; SPFolder objSPFolder = objSPList.RootFolder; String NombreArchivo = oDocumentoDDPBE.CodigoDocumento + "_" + oDocumentoDDPBE.Version + extensionTemporal; SPUser Creador = objSPWeb.EnsureUser(SPContext.Current.Web.CurrentUser.LoginName); SPFile objPFile = objSPFolder.Files.Add(NombreArchivo, fupArchivo.FileContent, true); DocumentoDDPBL.Instance.Actualizar(URLSitioPrincipal, oDocumentoDDPBE, URLSitioPrincipal); } } }); HistorialFlujoBE oHistorialFlujo = new HistorialFlujoBE(); oHistorialFlujo.CodigoDocumento = oDocumentoDDPBE.CodigoDocumento; oHistorialFlujo.Version = oDocumentoDDPBE.Version; oHistorialFlujo.Accion = Mensajes.HistorialGestorDocumental.ReemplazoArchivo; oHistorialFlujo.Estado = oDocumentoDDPBE.Estado; oHistorialFlujo.FechaAccion = DateTime.Now; oHistorialFlujo.Usuario = SPContext.Current.Web.CurrentUser.Name; oHistorialFlujo.Comentario = String.Empty; HistorialFlujoDDPBL.Instance.CrearNuevoRegistroHistorialFlujo(oHistorialFlujo); string Mensaje = Mensajes.ExitoGestorDocumental.ReemplazoArchivo; string Funcion = "AlertaAvisoRedirigir"; string URL = Page.Request.Url.ToString(); //SPContext.Current.Site.Url + @"/" + oDocumentoDDPBE.TipoDocumental.Codigo + Constantes.URL_PAGINA_FORMULARIO + oDocumentoDDPBE.ID.ToString(); Page.Request.Url.ToString(); WebUtil.AlertRedirectServer(Page, this.GetType(), TipoAlerta.Aviso, Funcion, Mensaje, URL); //RegistrarOActualizarMetadatos(ref oDocumentoDDPBE, Extension, mensaje); //} } catch (Exception ex) { Utilitarios.AlertServer(this, Constantes.TiposAlerta.Aviso, Mensajes.Error.CargaDeDocumento + " : " + ex.Message); } } protected void btnReactivarCaducado_Click(object sender, EventArgs e) { List<DocumentoDDPBE> listDocumentos = DocumentoDDPBL.Instance.ObtenerDocumentosPorCodigo(txtCodigoDocumentoCabecera.Text, SPContext.Current.List.Title, SPContext.Current.Web.Url); if (listDocumentos.FindAll(x => x.Estado == EstadosDDP.Publicado).Count == 0) WebUtil.EjecutarFuncionJS(up, up.GetType(), "AbrirReactivarDocumentoCaducado();"); else Utilitarios.AlertServer(this, Constantes.TiposAlerta.Validacion, "No se puede reactivar el documento porque ya existe un documento publicado vigente"); } protected void AbrirBuscadorCentroCostos_Click(object sender, EventArgs e) { CargarCombosBuscadorCentroCostos(); WebUtil.EjecutarFuncionJS(Page, this.GetType(), "AbrirBuscadorCentroCostos();"); //BuscarCentrosCostos(); } protected void AbrirBuscadorElaborador_Click(object sender, EventArgs e) { ViewState["TipoFiltroParticipante"] = "Elaborador"; litTipoParticipante.Text = ViewState["TipoFiltroParticipante"].ToString(); CargarCombosBuscadorParticipante(); WebUtil.EjecutarFuncionJS(Page, this.GetType(), "AbrirBuscadorParticipante();"); //BuscarCentrosCostos(); } protected void AbrirBuscadorRevisor_Click(object sender, EventArgs e) { ViewState["TipoFiltroParticipante"] = "Revisor"; litTipoParticipante.Text = ViewState["TipoFiltroParticipante"].ToString(); CargarCombosBuscadorParticipante(); WebUtil.EjecutarFuncionJS(Page, this.GetType(), "AbrirBuscadorParticipante();"); //BuscarCentrosCostos(); } protected void AbrirBuscadorAprobador_Click(object sender, EventArgs e) { ViewState["TipoFiltroParticipante"] = "Aprobador"; litTipoParticipante.Text = ViewState["TipoFiltroParticipante"].ToString(); CargarCombosBuscadorParticipante(); WebUtil.EjecutarFuncionJS(Page, this.GetType(), "AbrirBuscadorParticipante();"); //BuscarCentrosCostos(); } private void CargarCombosBuscadorParticipante() { var lst = PaisBL.Instance.ObtenerLista(URLSitioPrincipal); if (lst != null) WebUtil.BindDropDownList(ddlFiltroNotificacionPaisParticipante, lst, "Id", "Title", Constantes.ListaValueItem.Cero, Constantes.ListaTextItem.Seleccione); var lstItem = ItemBL.Instance.ObtenerLista(URLSitioPrincipal, ListasGestorDocumental.GruposFuncionales); //if (lstItem != null) // WebUtil.BindDropDownList(ddlFiltroNotificacionGrupoFuncionalElaborador, lstItem, "Id", "Title", Constantes.ListaValueItem.Vacio, Constantes.ListaTextItem.Seleccione); lstItem = ItemBL.Instance.ObtenerLista(URLSitioPrincipal, ListasGestorDocumental.NivelesJerarquicos); if (lstItem != null) WebUtil.BindDropDownList(ddlFiltroNotificacionNivelJerarquicoParticipante, lstItem, "Id", "Title", Constantes.ListaValueItem.Vacio, Constantes.ListaTextItem.Seleccione); lstItem = ItemBL.Instance.ObtenerLista(URLSitioPrincipal, ListasGestorDocumental.Vicepresidencias); if (lstItem != null) WebUtil.BindDropDownList(ddlFiltroNotificacionVicepresidenciaParticipante, lstItem, "Id", "Title", Constantes.ListaValueItem.Vacio, Constantes.ListaTextItem.Seleccione); lstItem = ItemBL.Instance.ObtenerLista(URLSitioPrincipal, ListasGestorDocumental.Generos); //if (lstItem != null) // WebUtil.BindDropDownList(ddlFiltroNotificacionGeneroElaborador, lstItem, "Id", "Title", Constantes.ListaValueItem.Vacio, Constantes.ListaTextItem.Seleccione); lstItem = ItemBL.Instance.ObtenerLista(URLSitioPrincipal, ListasGestorDocumental.Sedes); //if (lstItem != null) // WebUtil.BindDropDownList(ddlFiltroNotificacionSedeElaborador, lstItem, "Id", "Title", Constantes.ListaValueItem.Vacio, Constantes.ListaTextItem.Seleccione); CargarComboCompaniaElaborador(); txtNombreColaboradorParticipante.Text = string.Empty; //txtFiltroNotificacionCeCoElaborador.Text = string.Empty; //hdftxtFiltroNotificacionCeCo.Value = string.Empty; //hdfCeCoFiltroElegidos.Value = string.Empty; } private void CargarCombosBuscadorCentroCostos() { var lst = PaisBL.Instance.ObtenerLista(URLSitioPrincipal); if (lst != null) WebUtil.BindDropDownList(ddlFiltroNotificacionPais, lst, "Id", "Title", Constantes.ListaValueItem.Cero, Constantes.ListaTextItem.Seleccione); var lstItem = ItemBL.Instance.ObtenerLista(URLSitioPrincipal, ListasGestorDocumental.GruposFuncionales); if (lstItem != null) WebUtil.BindDropDownList(ddlFiltroNotificacionGrupoFuncional, lstItem, "Id", "Title", Constantes.ListaValueItem.Vacio, Constantes.ListaTextItem.Seleccione); lstItem = ItemBL.Instance.ObtenerLista(URLSitioPrincipal, ListasGestorDocumental.NivelesJerarquicos); if (lstItem != null) WebUtil.BindDropDownList(ddlFiltroNotificacionNivelJerarquico, lstItem, "Id", "Title", Constantes.ListaValueItem.Vacio, Constantes.ListaTextItem.Seleccione); lstItem = ItemBL.Instance.ObtenerLista(URLSitioPrincipal, ListasGestorDocumental.Vicepresidencias); if (lstItem != null) WebUtil.BindDropDownList(ddlFiltroNotificacionVicepresidencia, lstItem, "Id", "Title", Constantes.ListaValueItem.Vacio, Constantes.ListaTextItem.Seleccione); lstItem = ItemBL.Instance.ObtenerLista(URLSitioPrincipal, ListasGestorDocumental.Generos); if (lstItem != null) WebUtil.BindDropDownList(ddlFiltroNotificacionGenero, lstItem, "Id", "Title", Constantes.ListaValueItem.Vacio, Constantes.ListaTextItem.Seleccione); lstItem = ItemBL.Instance.ObtenerLista(URLSitioPrincipal, ListasGestorDocumental.Sedes); if (lstItem != null) WebUtil.BindDropDownList(ddlFiltroNotificacionSede, lstItem, "Id", "Title", Constantes.ListaValueItem.Vacio, Constantes.ListaTextItem.Seleccione); CargarComboCompania(); txtNombreColaborador.Text = string.Empty; txtFiltroNotificacionCeCo.Text = string.Empty; hdftxtFiltroNotificacionCeCo.Value = string.Empty; hdfCeCoFiltroElegidos.Value = string.Empty; } private void CargarComboCompania() { ddlFiltroNotificacionCompania.Items.Clear(); string IdPais = ddlFiltroNotificacionPais.SelectedValue; if (Convert.ToInt32(IdPais) > 0) { var lst = CompaniaBL.Instance.ObtenerLista(URLSitioPrincipal, IdPais); if (lst != null) WebUtil.BindDropDownList(ddlFiltroNotificacionCompania, lst, "Id", "Title", Constantes.ListaValueItem.Cero, Constantes.ListaTextItem.Seleccione); } else ddlFiltroNotificacionCompania.Items.Insert(0, new ListItem("Seleccione un País...", "0")); } private void CargarComboCompaniaElaborador() { ddlFiltroNotificacionCompaniaParticipante.Items.Clear(); string IdPais = ddlFiltroNotificacionPaisParticipante.SelectedValue; if (Convert.ToInt32(IdPais) > 0) { var lst = CompaniaBL.Instance.ObtenerLista(URLSitioPrincipal, IdPais); if (lst != null) WebUtil.BindDropDownList(ddlFiltroNotificacionCompaniaParticipante, lst, "Id", "Title", Constantes.ListaValueItem.Cero, Constantes.ListaTextItem.Seleccione); } else ddlFiltroNotificacionCompaniaParticipante.Items.Insert(0, new ListItem("Seleccione un País...", "0")); } protected void ddlFiltroNotificacionPais_SelectedIndexChanged(object sender, EventArgs e) { txtFiltroNotificacionCeCo.Text = hdftxtFiltroNotificacionCeCo.Value; CargarComboCompania(); WebUtil.EjecutarFuncionJS(Page, this.GetType(), "EstablecerFiltroNotificacionCeCo();"); } protected void ddlFiltroNotificacionPaisParticipante_SelectedIndexChanged(object sender, EventArgs e) { //txtFiltroNotificacionCeCo.Text = hdftxtFiltroNotificacionCeCo.Value; CargarComboCompaniaElaborador(); //WebUtil.EjecutarFuncionJS(Page, this.GetType(), "EstablecerFiltroNotificacionCeCo();"); } protected void btnBuscarFiltroParticipante_Click(object sender, EventArgs e) { try { //txtFiltroNotificacionCeCo.Text = hdftxtFiltroNotificacionCeCo.Value; //if (!string.IsNullOrEmpty(txtFiltroNotificacionCeCo.Text)) //{ // imgBorrarFiltroNotificacionCeCo.Style.Remove(HtmlTextWriterStyle.Display); //} PerfilesBE oPerfilBE = new PerfilesBE(); if (!String.IsNullOrEmpty(ddlFiltroNotificacionPaisParticipante.SelectedItem.Value)) oPerfilBE.IDPais = int.Parse(ddlFiltroNotificacionPaisParticipante.SelectedItem.Value); if (ddlFiltroNotificacionCompaniaParticipante.SelectedItem != null) if (!String.IsNullOrEmpty(ddlFiltroNotificacionCompaniaParticipante.SelectedItem.Value)) oPerfilBE.IDCompania = int.Parse(ddlFiltroNotificacionCompaniaParticipante.SelectedItem.Value); if (!String.IsNullOrEmpty(ddlFiltroNotificacionNivelJerarquicoParticipante.SelectedItem.Value)) oPerfilBE.IDNivelJerarquico = int.Parse(ddlFiltroNotificacionNivelJerarquicoParticipante.SelectedItem.Value); if (!String.IsNullOrEmpty(ddlFiltroNotificacionVicepresidenciaParticipante.SelectedItem.Value)) oPerfilBE.IDVicepresidencia = int.Parse(ddlFiltroNotificacionVicepresidenciaParticipante.SelectedItem.Value); //if (!String.IsNullOrEmpty(hdfCeCoFiltroElegidos.Value)) // oPerfilBE.IDCentroCostos = int.Parse(hdfCeCoFiltroElegidos.Value); oPerfilBE.NombreColaborador = txtNombreColaboradorParticipante.Text; oPerfilBE.Correo = txtCorreoColaboradorParticipante.Text; List<PerfilesBE> PerfilesEncontrados = new List<PerfilesBE>(); PerfilesEncontrados = PerfilesBL.Instance.ObtenerPerfilesFiltrados(URLSitioPrincipal, oPerfilBE); ViewState["PerfilesEncontradosParticipante"] = PerfilesEncontrados; if (PerfilesEncontrados != null && PerfilesEncontrados.Count > 0) { int idGrupo = 0; switch (ViewState["TipoFiltroParticipante"].ToString()) { case "Elaborador": case "Aprobador": idGrupo = cppElaborador.SharePointGroupID; if (idGrupo == 0) { int IdGrupoMacroproceso = 0; var lstFiltrada = MacroProcesoBL.Instance.ObtenerLista(URLSitioPrincipal); if (ddlMacroProceso.SelectedItem.Value != String.Empty) IdGrupoMacroproceso = lstFiltrada.Find(MP => MP.Id.ToString() == ddlMacroProceso.SelectedItem.Value).IdGrupoPublicoMacroproceso; cppElaborador.SharePointGroupID = IdGrupoMacroproceso; cppAprobador.SharePointGroupID = IdGrupoMacroproceso; idGrupo = IdGrupoMacroproceso; } break; case "Revisor": idGrupo = cppRevisor.SharePointGroupID; if (idGrupo == 0) { if (ddlSistemaCalidad.SelectedItem.Value == "Sí") { idGrupo = MacroProcesoBL.Instance.ObtenerGruposPorNombre(URLSitioPrincipal, Constantes.NOMBRE_GRUPO_COLABORADORES_GC); } cppRevisor.SharePointGroupID = idGrupo; } break; } if (idGrupo > 0) { SPGroup grupoParticipante = SPContext.Current.Web.Groups.GetByID(idGrupo); SPUserCollection usuarios = grupoParticipante.Users; List<string> correos = new List<string>(); foreach (SPUser usuario in usuarios) { correos.Add(usuario.Email); } PerfilesEncontrados = PerfilesEncontrados.Where(item => correos.Contains(item.Correo)).ToList(); } } grvResultadoBusquedaParticipante.Visible = true; grvResultadoBusquedaParticipante.DataSource = PerfilesEncontrados; grvResultadoBusquedaParticipante.DataBind(); //WebUtil.EjecutarFuncionJS(Page, this.GetType(), "EstablecerFiltroNotificacionCeCo();"); } catch (Exception ex) { string strGUIDReferencia = Logging.RegistrarMensajeLogSharePoint(Constantes.CATEGORIA_LOG_FORM_GESTOR_LOAD, "load", ex); WebUtil.AlertServer(Page, this.GetType(), TipoAlerta.Error, "AlertaAviso", ex.Message + " : : " + ex.StackTrace); } } protected void btnBuscarFiltroNotificados_Click(object sender, EventArgs e) { try { txtFiltroNotificacionCeCo.Text = hdftxtFiltroNotificacionCeCo.Value; //if (!string.IsNullOrEmpty(txtFiltroNotificacionCeCo.Text)) //{ // imgBorrarFiltroNotificacionCeCo.Style.Remove(HtmlTextWriterStyle.Display); //} PerfilesBE oPerfilBE = new PerfilesBE(); if (!String.IsNullOrEmpty(ddlFiltroNotificacionPais.SelectedItem.Value)) oPerfilBE.IDPais = int.Parse(ddlFiltroNotificacionPais.SelectedItem.Value); if (ddlFiltroNotificacionCompania.SelectedItem != null) if (!String.IsNullOrEmpty(ddlFiltroNotificacionCompania.SelectedItem.Value)) oPerfilBE.IDCompania = int.Parse(ddlFiltroNotificacionCompania.SelectedItem.Value); if (!String.IsNullOrEmpty(ddlFiltroNotificacionNivelJerarquico.SelectedItem.Value)) oPerfilBE.IDNivelJerarquico = int.Parse(ddlFiltroNotificacionNivelJerarquico.SelectedItem.Value); if (!String.IsNullOrEmpty(ddlFiltroNotificacionGrupoFuncional.SelectedItem.Value)) oPerfilBE.IDGrupoFuncional = int.Parse(ddlFiltroNotificacionGrupoFuncional.SelectedItem.Value); if (!String.IsNullOrEmpty(ddlFiltroNotificacionVicepresidencia.SelectedItem.Value)) oPerfilBE.IDVicepresidencia = int.Parse(ddlFiltroNotificacionVicepresidencia.SelectedItem.Value); if (!String.IsNullOrEmpty(ddlFiltroNotificacionGenero.SelectedItem.Value)) oPerfilBE.IDGenero = int.Parse(ddlFiltroNotificacionGenero.SelectedItem.Value); if (!String.IsNullOrEmpty(ddlFiltroNotificacionSede.SelectedItem.Value)) oPerfilBE.IDSede = int.Parse(ddlFiltroNotificacionSede.SelectedItem.Value); //if (!String.IsNullOrEmpty(hdfCeCoFiltroElegidos.Value)) // oPerfilBE.IDCentroCostos = int.Parse(hdfCeCoFiltroElegidos.Value); oPerfilBE.NombreColaborador = txtNombreColaborador.Text; List<PerfilesBE> PerfilesEncontrados = new List<PerfilesBE>(); PerfilesEncontrados = PerfilesBL.Instance.ObtenerPerfilesFiltrados(URLSitioPrincipal, oPerfilBE, hdfCeCoFiltroElegidos.Value); ViewState["PerfilesEncontrados"] = PerfilesEncontrados; if (PerfilesEncontrados != null && PerfilesEncontrados.Count > 0) { btnPreseleccionar.Visible = true; } else { btnPreseleccionar.Visible = false; } grvResultadoBusquedaNotificados.Visible = true; grvResultadoBusquedaNotificados.DataSource = PerfilesEncontrados; grvResultadoBusquedaNotificados.DataBind(); WebUtil.EjecutarFuncionJS(Page, this.GetType(), "EstablecerFiltroNotificacionCeCo();"); } catch (Exception ex) { string strGUIDReferencia = Logging.RegistrarMensajeLogSharePoint(Constantes.CATEGORIA_LOG_FORM_GESTOR_LOAD, "load", ex); WebUtil.AlertServer(Page, this.GetType(), TipoAlerta.Error, "AlertaAviso", ex.Message + " : : " + ex.StackTrace); } } protected void btnPreseleccionar_Click(object sender, EventArgs e) { List<PerfilesBE> oLitaPreseleccionados = new List<PerfilesBE>(); if (ViewState["ListaPreseleccionados"] != null) { oLitaPreseleccionados = (List<PerfilesBE>)ViewState["ListaPreseleccionados"]; } PerfilesBE oPerfil = null; foreach (GridViewRow row in grvResultadoBusquedaNotificados.Rows) { if (((CheckBox)row.FindControl("chkElegirNotificado")).Checked) { oPerfil = new PerfilesBE(); oPerfil.Correo = grvResultadoBusquedaNotificados.DataKeys[row.RowIndex].Values[0].ToString(); oPerfil.NombreColaborador = grvResultadoBusquedaNotificados.DataKeys[row.RowIndex].Values[1].ToString(); if (grvResultadoBusquedaNotificados.DataKeys[row.RowIndex].Values[2] != null) { oPerfil.IDCentroCostos = int.Parse(grvResultadoBusquedaNotificados.DataKeys[row.RowIndex].Values[2].ToString()); oPerfil.CodigoCentroCostos = grvResultadoBusquedaNotificados.DataKeys[row.RowIndex].Values[3].ToString(); oPerfil.DescripcionCentroCostos = grvResultadoBusquedaNotificados.DataKeys[row.RowIndex].Values[4].ToString(); } if (oLitaPreseleccionados.Where(PerfilExiste => PerfilExiste.Correo == oPerfil.Correo && PerfilExiste.Notificado == false).Count() == 0) { oLitaPreseleccionados.Add(oPerfil); } //if (!oLitaPreseleccionados.Exists(PerfilExiste => PerfilExiste.Correo == oPerfil.Correo)) //{ //} ((CheckBox)row.FindControl("chkElegirNotificado")).Checked = false; } //if (((CheckBox)row.FindControl("chkElegirTodosNotificados")).Checked) //{ // (CheckBox)row.FindControl("chkElegirTodosNotificados")).Checked=false; //} } ViewState["ListaPreseleccionados"] = oLitaPreseleccionados; if (oLitaPreseleccionados.Count > 0) { btnConfirmarPreseleccion.Visible = true; } else { btnConfirmarPreseleccion.Visible = false; } grvPreseleccionadosNotificados.Visible = true; grvPreseleccionadosNotificados.DataSource = oLitaPreseleccionados; grvPreseleccionadosNotificados.DataBind(); grvResultadoBusquedaNotificados.DataSource = (List<PerfilesBE>)ViewState["PerfilesEncontrados"]; grvResultadoBusquedaNotificados.DataBind(); WebUtil.EjecutarFuncionJS(Page, this.GetType(), "EstablecerFiltroNotificacionCeCo();"); } protected void grvResultadoBusquedaParticipante_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Select") { //Determine the RowIndex of the Row whose Button was clicked. int rowIndex = Convert.ToInt32(e.CommandArgument); //Reference the GridView Row. GridViewRow row = grvResultadoBusquedaParticipante.Rows[rowIndex]; string correo = (string)this.grvResultadoBusquedaParticipante.DataKeys[rowIndex]["Correo"]; //correo = correo; PeopleEditor pe = new PeopleEditor(); PickerEntity entity = new PickerEntity(); entity.Key = correo; entity = pe.ValidateEntity(entity); entity.IsResolved = true; switch (ViewState["TipoFiltroParticipante"].ToString()) { case "Elaborador": cppElaborador.AllEntities.Clear(); cppElaborador.AddEntities(new List<PickerEntity> { entity }); break; case "Revisor": cppRevisor.AllEntities.Clear(); cppRevisor.AddEntities(new List<PickerEntity> { entity }); break; case "Aprobador": cppAprobador.AllEntities.Clear(); cppAprobador.AddEntities(new List<PickerEntity> { entity }); break; } WebUtil.EjecutarFuncionJS(Page, this.GetType(), "CerrarBuscadorParticipante();"); } } protected void btnConfirmarPreseleccion_Click(object sender, EventArgs e) { ViewState["ListaPreseleccionadosConfirmados"] = ViewState["ListaPreseleccionados"]; ResetearBuscadorCentroDocumento(); AbrirBuscadorCentroCostos.Visible = false; btnAbrirListaCentroCostos.Visible = true; EstablecerCentroDeCostos(); } protected void EstablecerCentroDeCostos() { List<PerfilesBE> oListaPreseleccionados = new List<PerfilesBE>(); if (ViewState["ListaPreseleccionadosConfirmados"] != null) { oListaPreseleccionados = (List<PerfilesBE>)ViewState["ListaPreseleccionadosConfirmados"]; List<CentroCostoBE> ListaCecos = oListaPreseleccionados.Select(o => new CentroCostoBE(0, o.CodigoCentroCostos, o.DescripcionCentroCostos)).Distinct().ToList(); List<CentroCostoBE> ListaCecosDepurada = new List<CentroCostoBE>(); CentroCostoBE CecoADepurar = null; foreach (CentroCostoBE Ceco in ListaCecos) { if (!ListaCecosDepurada.Exists(o => o.Codigo == Ceco.Codigo)) { CecoADepurar = new CentroCostoBE(); ListaCecosDepurada.Add(new CentroCostoBE(0, Ceco.Codigo, Ceco.Descripcion)); } } ViewState["NotificarCentroCostos"] = ListaCecosDepurada; } } protected void btnAbrirListaCentroCostos_Click(object sender, EventArgs e) { List<PerfilesBE> oLitaPreseleccionados = new List<PerfilesBE>(); if (ViewState["ListaPreseleccionadosConfirmados"] != null) { oLitaPreseleccionados = (List<PerfilesBE>)ViewState["ListaPreseleccionadosConfirmados"]; } grvListaNotificados.DataSource = oLitaPreseleccionados; grvListaNotificados.DataBind(); WebUtil.EjecutarFuncionJS(Page, this.GetType(), "AbrirListaCentroCostos();"); } protected void btnModificarListaCentroCostos_Click(object sender, EventArgs e) { ViewState["ListaPreseleccionados"] = ViewState["ListaPreseleccionadosConfirmados"]; CargarCombosBuscadorCentroCostos(); List<PerfilesBE> oLitaPreseleccionados = new List<PerfilesBE>(); if (ViewState["ListaPreseleccionados"] != null) { oLitaPreseleccionados = (List<PerfilesBE>)ViewState["ListaPreseleccionados"]; } if (oLitaPreseleccionados.Count > 0) { btnConfirmarPreseleccion.Visible = true; } else { btnConfirmarPreseleccion.Visible = false; } grvPreseleccionadosNotificados.Visible = true; grvPreseleccionadosNotificados.DataSource = oLitaPreseleccionados; grvPreseleccionadosNotificados.DataBind(); WebUtil.EjecutarFuncionJS(Page, this.GetType(), "AbrirBuscadorCentroCostosParaModificar();"); } protected void grvPreseleccionadosNotificados_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "EliminarPreseleccionado") { int row = Convert.ToInt32(e.CommandArgument.ToString()); List<PerfilesBE> oListNotificarPerfiles = new List<PerfilesBE>(); string Correo = (String)grvPreseleccionadosNotificados.DataKeys[row].Values[1]; if (ViewState["ListaPreseleccionados"] != null) oListNotificarPerfiles = (List<PerfilesBE>)ViewState["ListaPreseleccionados"]; oListNotificarPerfiles.RemoveAll(ItemEliminar => ItemEliminar.Correo == Correo && ItemEliminar.Notificado == false); ViewState["ListaPreseleccionados"] = oListNotificarPerfiles; grvPreseleccionadosNotificados.DataSource = ViewState["ListaPreseleccionados"]; grvPreseleccionadosNotificados.DataBind(); upgrvResultadoBusquedaNotificados.Update(); txtFiltroNotificacionCeCo.Text = hdftxtFiltroNotificacionCeCo.Value; WebUtil.EjecutarFuncionJS(Page, this.GetType(), "EstablecerFiltroNotificacionCeCo();"); } if (e.CommandName == "EliminarPreseleccionadosTodos") { List<PerfilesBE> oListNotificarPerfiles = new List<PerfilesBE>(); if (ViewState["ListaPreseleccionados"] != null) oListNotificarPerfiles = (List<PerfilesBE>)ViewState["ListaPreseleccionados"]; oListNotificarPerfiles.RemoveAll(ItemEliminar => ItemEliminar.Notificado == false); ViewState["ListaPreseleccionados"] = oListNotificarPerfiles; grvPreseleccionadosNotificados.DataSource = ViewState["ListaPreseleccionados"]; grvPreseleccionadosNotificados.DataBind(); upgrvResultadoBusquedaNotificados.Update(); txtFiltroNotificacionCeCo.Text = hdftxtFiltroNotificacionCeCo.Value; WebUtil.EjecutarFuncionJS(Page, this.GetType(), "EstablecerFiltroNotificacionCeCo();"); } } protected void grvPreseleccionadosNotificados_RowDataBound(object sender, GridViewRowEventArgs e) { //Checking the RowType of the Row if (e.Row.RowType == DataControlRowType.DataRow) { bool Notificado = (bool)grvPreseleccionadosNotificados.DataKeys[e.Row.RowIndex].Values[4]; if (Notificado) { ImageButton btnEliminar = e.Row.FindControl("ImgBtnEliminarPreseleccionado") as ImageButton; btnEliminar.Visible = false; } } } protected void btnBuscarFiltroCentroCostos_Click(object sender, EventArgs e) { BuscarCentrosCostos(); //WebUtil.EjecutarFuncionJS(Page, this.GetType(), "BorrarCamposBusquedaCC();"); } private void BuscarCentrosCostos() { gvCentroCostosFiltrados.Visible = true; List<CentroCostoBE> oListaCeCo = ((List<CentroCostoBE>)ViewState["ListadoDeCentrosCostos"]).FindAll(o => o.Concatenado.ToUpper().Contains(txtFiltroCentroCostos.Text.ToUpper().Trim())); gvCentroCostosFiltrados.DataSource = oListaCeCo; gvCentroCostosFiltrados.DataBind(); } private void CargarListadoDeCentrosCostos() { if (ViewState["ListadoDeCentrosCostos"] == null) ViewState["ListadoDeCentrosCostos"] = CentroCostoBL.Instance.ObtenerLista(SPContext.Current.Site.RootWeb, String.Empty); gvCentroCostosFiltrados.DataSource = (List<CentroCostoBE>)ViewState["ListadoDeCentrosCostos"]; gvCentroCostosFiltrados.DataBind(); } protected void imgBuscarCeCos_Click(object sender, ImageClickEventArgs e) { txtFiltroCentroCostos.Text = string.Empty; gvCentroCostosFiltrados.Visible = true; gvCentroCostosFiltrados.DataSource = (List<CentroCostoBE>)ViewState["ListadoDeCentrosCostos"]; gvCentroCostosFiltrados.DataBind(); WebUtil.EjecutarFuncionJS(Page, this.GetType(), "AbrirBuscadorCentroCostosFiltro();"); //upPopupBuscadorCentroCostosFiltro.Update(); } protected void ddlTipoPlanMaestro_SelectedIndexChanged(object sender, EventArgs e) { ObtenerNombresRevisoresPM(); } protected void ObtenerNombresRevisoresPM() { txtRevisoresPM.Text = String.Empty; List<UsuarioBE> oListaUsuarios = ComunBL.Instance.ObtenerUsuariosDeGrupo(URLSitioPrincipal, Constantes.IDENTIFICADOR_GRUPO_REVISOR + ddlTipoPlanMaestro.SelectedItem.Value); //ViewState["UsuariosRevisoresPM"] = oListaUsuarios; string Usuarios = String.Empty; foreach (UsuarioBE Usuario in oListaUsuarios) { Usuarios = Usuario.DisplayName + ", " + Usuarios; } if (!String.IsNullOrEmpty(Usuarios)) { txtRevisoresPM.Text = Usuarios.Substring(0, Usuarios.Length - 2); } } protected void btnBloquearEdicion_Click(object sender, EventArgs e) { ActualizarBloqueo(Mensajes.HistorialGestorDocumental.EdicionExclusiva); } protected void btnNoBloquearEdicio_Click(object sender, EventArgs e) { ActualizarBloqueo(Mensajes.HistorialGestorDocumental.NoEdicionExclusiva); BloqueaForm(true); } protected void ActualizarBloqueo(string Accion) { DocumentoDDPBE oDocumentoDDPBE = ObtenerDatosParaGuardar(); UsuarioBE oUsuario = new UsuarioBE(); oUsuario.ID = SPContext.Current.Web.CurrentUser.ID; oUsuario.DisplayName = SPContext.Current.Web.CurrentUser.Name; txtEdicionExclusivaPor.Text = oUsuario.DisplayName; if (oDocumentoDDPBE.Estado == EstadosDDP.Publicacion) { if (Accion == Mensajes.HistorialGestorDocumental.NoEdicionExclusiva) { AsignarPermisosEliminacionExclusiva(false, ((UsuarioBE)ViewState["BloqueadoPubPara"]).ID); hdfIdBloqueadoPubPara.Value = String.Empty; ViewState["BloqueadoPubPara"] = null; oDocumentoDDPBE.BloqueadoPubPara.ID = 0; txtEdicionExclusivaPor.Text = string.Empty; btnBloquearEdicion.Visible = true; btnNoBloquearEdicion.Visible = false; SeccionEdicionExclusivaPor.Visible = false; } else { AsignarPermisosEliminacionExclusiva(true, oUsuario.ID); hdfIdBloqueadoPubPara.Value = oUsuario.ID.ToString(); ViewState["BloqueadoPubPara"] = oUsuario; oDocumentoDDPBE.BloqueadoPubPara.ID = oUsuario.ID; btnBloquearEdicion.Visible = false; btnNoBloquearEdicion.Visible = true; SeccionEdicionExclusivaPor.Visible = true; } } if (oDocumentoDDPBE.Estado == EstadosDDP.VerificacionCalidad) { if (Accion == Mensajes.HistorialGestorDocumental.NoEdicionExclusiva) { AsignarPermisosEliminacionExclusiva(false, ((UsuarioBE)ViewState["BloqueadoVCPara"]).ID); hdfIdBloqueadoVCPara.Value = String.Empty; ViewState["BloqueadoVCPara"] = null; oDocumentoDDPBE.BloqueadoVCPara.ID = 0; txtEdicionExclusivaPor.Text = string.Empty; btnBloquearEdicion.Visible = true; btnNoBloquearEdicion.Visible = false; SeccionEdicionExclusivaPor.Visible = false; } else { AsignarPermisosEliminacionExclusiva(true, oUsuario.ID); hdfIdBloqueadoVCPara.Value = oUsuario.ID.ToString(); ViewState["BloqueadoVCPara"] = oDocumentoDDPBE.BloqueadoVCPara; oDocumentoDDPBE.BloqueadoVCPara.ID = oUsuario.ID; btnBloquearEdicion.Visible = false; btnNoBloquearEdicion.Visible = true; SeccionEdicionExclusivaPor.Visible = true; } } DocumentoDDPBL.Instance.ActualizarBloqueo(URLSitioPrincipal, oDocumentoDDPBE); HistorialFlujoBE oHistorialFlujo = new HistorialFlujoBE(); oHistorialFlujo.CodigoDocumento = oDocumentoDDPBE.CodigoDocumento; oHistorialFlujo.Accion = Accion; oHistorialFlujo.Version = oDocumentoDDPBE.Version; oHistorialFlujo.FechaAccion = DateTime.Now; oHistorialFlujo.Usuario = SPContext.Current.Web.CurrentUser.Name; oHistorialFlujo.Comentario = oDocumentoDDPBE.Comentario; oHistorialFlujo.Estado = oDocumentoDDPBE.Estado; HistorialFlujoDDPBL.Instance.CrearNuevoRegistroHistorialFlujo(oHistorialFlujo); } protected void BloqueaForm(bool Activar) { pnlDatosPrincipalesSecundarios.Enabled = Activar; pnlUsuariosParticipantes.Enabled = Activar; HabilitarEdicionCamposUsuario(false); pnlDatosAdicionales.Enabled = Activar; pnlAcciones.Enabled = Activar; } public void AsignarPermisosEliminacionExclusiva(bool AsignarExclusividad, int IdUsuarioBloqueoActual) { try { //base.ItemUpdated(properties); SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite objSPSite = new SPSite(URLSitioPrincipal)) { using (SPWeb objSPWeb = objSPSite.OpenWeb()) { SPListItem objSPListItemDocumento = objSPWeb.Lists[SPContext.Current.List.Title].GetItemById(SPContext.Current.ListItem.ID);// SPContext.Current.ListItem; #region Reasignacion SPUser objSPUserAsignado = ComunBL.Instance.ObtenerUsuarioEnSitioPorID(objSPWeb, IdUsuarioBloqueoActual); objSPWeb.AllowUnsafeUpdates = true; SPFieldUserValueCollection spfuvcUsuarios = new SPFieldUserValueCollection(objSPListItemDocumento.Web, objSPListItemDocumento["SubAdministrador"].ToString()); //SPPrincipal objSPUserAsignadoAnteriorGrupoSubAdmin = (SPPrincipal)(objSPListItemDocumento["SubAdministrador"]);// ComunBL.Instance.ObtenerGrupoSitioPorNombre(); .ObtenerUsuarioEnSitioPorID(objSPWeb, objTareaBE.DocumentoRelacionado.Elaborador.ID); if (!objSPListItemDocumento.HasUniqueRoleAssignments) objSPListItemDocumento.BreakRoleInheritance(true, true); if (AsignarExclusividad == true) { ComunBL.Instance.AgregarPermisosSPListItem(objSPListItemDocumento, RolesPersonalizados.ColaborarSinEliminar, objSPUserAsignado); foreach (SPFieldUserValue objAsignadoAnteriorGrupoSubAdmin in spfuvcUsuarios) { SPPrincipal GrupoSubAdmin = ComunBL.Instance.ObtenerSPPrincipalDeUsuario(new UsuarioBE(objAsignadoAnteriorGrupoSubAdmin.LookupId, String.Empty, objAsignadoAnteriorGrupoSubAdmin.LookupValue, String.Empty, true), objSPListItemDocumento.Web); objSPListItemDocumento.RoleAssignments.Remove(GrupoSubAdmin); ComunBL.Instance.AgregarPermisosSPListItem(objSPListItemDocumento, SPRoleType.Reader, GrupoSubAdmin); } } else { foreach (SPFieldUserValue objAsignadoAnteriorGrupoSubAdmin in spfuvcUsuarios) { SPPrincipal GrupoSubAdmin = ComunBL.Instance.ObtenerSPPrincipalDeUsuario(new UsuarioBE(objAsignadoAnteriorGrupoSubAdmin.LookupId, String.Empty, objAsignadoAnteriorGrupoSubAdmin.LookupValue, String.Empty, true), objSPListItemDocumento.Web); ComunBL.Instance.AgregarPermisosSPListItem(objSPListItemDocumento, RolesPersonalizados.ColaborarSinEliminar, GrupoSubAdmin); } objSPListItemDocumento.RoleAssignments.Remove(objSPUserAsignado); } #endregion } } }); } catch (Exception ex) { //string strGUIDReferencia = Logging.RegistrarMensajeLogSharePoint(Constantes.CATEGORIA_LOG_ER_TAREAS_UPDATED, NombreComponente, ex); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PowerCollision : MonoBehaviour { void OnCollisionEnter(Collision colInfo) { if(colInfo.collider.tag == "obstacleSpecial") { Destroy(colInfo.gameObject); Destroy(this.gameObject); } } }
using System; using System.Collections.Generic; using System.Text; namespace SAAS.FrameWork { public class PageCollection<T> { /// <summary> /// 当前第几页 /// </summary> public int PageIndex { get; set; } /// <summary> /// 总记录条数 /// </summary> public int TotalCount { get; set; } /// <summary> /// 每页条数 /// </summary> public int PageSize { get; set; } = 20; /// <summary> /// 页数 /// </summary> public int PageCount { get { if (TotalCount % PageSize == 0) { return TotalCount / PageSize; } else { return TotalCount / PageSize + 1; } } } /// <summary> /// 分页查询的数据 /// </summary> public IList<T> Collection { get; set; } } }
using System; class ExchangeIfGreater { static void Main() { while (true) { int a, b, tmpVar; Console.Write("Enter first number : "); var firstNumber = Console.ReadLine(); Console.Write("Enter second number : "); var secNumber = Console.ReadLine(); if (int.TryParse(firstNumber, out a) && int.TryParse(secNumber, out b)) { if (a > b) { tmpVar = a; a = b; b = tmpVar; } Console.WriteLine(a + " " + b); } else { double firstDouble = 0, secDouble = 0, tmpDouble; if (double.TryParse(firstNumber, out firstDouble) && double.TryParse(secNumber, out secDouble)) { if (firstDouble > secDouble) { tmpDouble = firstDouble; firstDouble = secDouble; secDouble = tmpDouble; } } Console.WriteLine(firstDouble + " " + secDouble); } } } }
using System; using System.Collections.Generic; namespace POSServices.Models { public partial class EmployeeTarget { public int Id { get; set; } public DateTime Periode { get; set; } public decimal Target { get; set; } public string EmployeeCode { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class MangaController : MonoBehaviour { public Button MangaPage; int page = 1; Animator animator; // Start is called before the first frame update void Start() { animator = GetComponent<Animator>(); } // Update is called once per frame void Update() { } public void NextManga() { try { animator.Play(page.ToString()); } catch { Debug.Log("none"); } page++; } public void SoundClick() { Debug.Log("aaa0"); MusicMgr.GetInstance().PlaySound("Click", false); } public void SoundPageChange() { MusicMgr.GetInstance().PlaySound("PageChange", false,(s)=> { s.time = 1f; }); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Cascade : MonoBehaviour, ICell { public GameObject highlight; private List<Card> cards = new List<Card>(); private int cascadeIndex; public void Initialize(int index) { cascadeIndex = index; } public bool AddInitialCard(Card card) { AddCard(card); // if this pile is full if (cascadeIndex < 4 && cards.Count == 7 || cascadeIndex >= 4 && cards.Count == 6) { return false; } return true; } private void AddCard(Card card) { if (cards.Count > 0) { GetFrontCard().isFrontCard = false; } cards.Add(card); card.isFrontCard = true; card.transform.SetParent(transform); card.transform.localPosition = new Vector3(0, Card.STACK_OFFSET * (cards.Count - 1), 0); } public Card GetFrontCard() { if (cards.Count > 0) { return cards[cards.Count - 1]; } return null; } public bool IsPotentialCardDrop(Card card) { Card frontCard = GetFrontCard(); if (frontCard == null) { return true; } return AreDifferentColors(card, frontCard) && card.GetNumber() == frontCard.GetNumber() - 1; } private bool AreDifferentColors(Card card1, Card card2) { return (!card1.IsRed() && card2.IsRed()) || (card1.IsRed() && !card2.IsRed()); } public bool IsInCardDropDistance(Card card) { Card frontCard = GetFrontCard(); if (frontCard == null) { return Vector3.Distance(card.transform.position, transform.position) < Card.DROP_DISTANCE; } else { Vector3 frontCardPos = frontCard.transform.position; frontCardPos.y += Card.STACK_OFFSET; return Vector3.Distance(card.transform.position, frontCardPos) < Card.DROP_DISTANCE; } } public void Highlight() { Card front = GetFrontCard(); if (front != null) { GetFrontCard().Highlight(); } else { highlight.SetActive(true); } } public void StopHighlight() { Card front = GetFrontCard(); if (front != null) { GetFrontCard().StopHighlight(); } highlight.SetActive(false); } public void DropCardInCell(Card card) { StopHighlight(); AddCard(card); } public void RemoveFrontCard() { cards.RemoveAt(cards.Count - 1); Card newFront = GetFrontCard(); if (newFront != null) { newFront.isFrontCard = true; } } }
using System; using UserLogin; using Xamarin.Forms; using SMSAuthentication; namespace Views { public partial class UserTokenVerificationView : ContentPage { UserLoginAbstract userLogin; public UserTokenVerificationView () { InitializeComponent (); userLogin = DependencyService.Get<UserLoginAbstract> (); userLogin.SetTokenVerificationEvent(async (response, status) => { if(status == System.Net.HttpStatusCode.OK) { if(response.status == (int)UserLoginAbstract.SMSTokenStatusCode.verification_success) { await DisplayAlert("Success",response.message,"Ok"); userLogin.StartTargerApplication (); UserLoginAbstract.IsLogin = true; } } }); } public void confirmSmsCode(object sender, EventArgs eventArgs) { String phoneNumber = null; if (userLogin.ObtainPhoneNumberFromPref (out phoneNumber)) { userLogin.SMSTokenVerification (SMSCodeEntry.Text, phoneNumber); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using com.Sconit.Utility; using com.Sconit.Web.Models.SearchModels.ISS; using Telerik.Web.Mvc; using com.Sconit.Entity.ISS; using com.Sconit.Web.Models; using com.Sconit.Service; using com.Sconit.Entity.Exception; using com.Sconit.Entity.CUST; namespace com.Sconit.Web.Controllers.INP { public class QualityDoorController : WebAppBaseController { /// <summary> /// /// </summary> private static string selectCountStatement = "select count(*) from IssueMaster as im join im.IssueType as it left join im.IssueNo ino "; /// <summary> /// /// </summary> private static string selectStatement = "select im from IssueMaster as im join im.IssueType as it left join im.IssueNo ino "; //public IGenericMgr genericMgr { get; set; } public IIssueMgr issueMgr { get; set; } // // GET: /QualityDoor/ #region public [SconitAuthorize(Permissions = "Url_QualityDoor_View")] public ActionResult Index() { return View(); } [GridAction] [SconitAuthorize(Permissions = "Url_QualityDoor_View")] public ActionResult List(GridCommand command, IssueMasterSearchModel searchModel) { this.ProcessSearchModel(command, searchModel); ViewBag.PageSize = base.ProcessPageSize(command.PageSize); return View(); } [GridAction(EnableCustomBinding = true)] [SconitAuthorize(Permissions = "Url_QualityDoor_View")] public ActionResult _AjaxList(GridCommand command, IssueMasterSearchModel searchModel) { SearchStatementModel searchStatementModel = PrepareSearchStatement(command, searchModel); GridModel<IssueMaster> List = GetAjaxPageData<IssueMaster>(searchStatementModel, command); foreach (IssueMaster issueMaster in List.Data) { issueMaster.FailCode = genericMgr.FindById<FailCode>(issueMaster.FailCode).CodeDescription; } return PartialView(List); } [GridAction] public ActionResult _IssueDetailList(string Code) { IList<IssueDetail> issueDetailList = genericMgr.FindAll<IssueDetail>("select i from IssueDetail as i where i.IssueCode = ?", Code); return PartialView(issueDetailList); } #region Edit [HttpGet] [SconitAuthorize(Permissions = "Url_QualityDoor_View")] public ActionResult Edit(string id) { if (string.IsNullOrWhiteSpace(id)) { return HttpNotFound(); } else { ViewBag.Code = id; IssueMaster issue = this.genericMgr.FindById<IssueMaster>(id); return View(issue); } } [HttpPost] [SconitAuthorize(Permissions = "Url_QualityDoor_View")] public ActionResult Edit(IssueMaster issue) { try { IssueMaster newIssue = genericMgr.FindById<IssueMaster>(issue.Code); newIssue.Content = issue.Content; genericMgr.Update(newIssue); SaveSuccessMessage(Resources.ISS.IssueMaster.Issue_Updated); } catch (BusinessException ex) { SaveErrorMessage(ex.Message); } return RedirectToAction("Edit/" + issue.Code); } [HttpGet] [SconitAuthorize(Permissions = "Url_QualityDoor_New")] public ActionResult New() { IssueMaster issue = new IssueMaster(); if (TempData["issue"] != null) { issue.BackYards = ((IssueMaster)TempData["issue"]).BackYards; issue.ReleaseIssue = ((IssueMaster)TempData["issue"]).ReleaseIssue; issue.ContinuousCreate = ((IssueMaster)TempData["issue"]).ContinuousCreate; TempData["issue"] = null; } else { issue.ReleaseIssue = true; issue.ContinuousCreate = true; } return View(issue); } [HttpPost] [SconitAuthorize(Permissions = "Url_QualityDoor_New")] public ActionResult New(IssueMaster issue, string Assemblies, string ProductCode) { TempData["issue"] = issue; IssueType issueType = genericMgr.FindById<IssueType>("ISS_QA"); issue.IssueType = issueType; ModelState.Remove("IssueType"); if (!string.IsNullOrWhiteSpace(issue.IssueNoCode)) { ViewBag.IssueNoCode = issue.IssueNoCode; IssueNo issueNo = new IssueNo(); issueNo.Code = issue.IssueNoCode; issue.IssueNo = issueNo; } if (!ModelState.IsValid) { ViewBag.Assemblies = Assemblies; ViewBag.ProductCode = ProductCode; return View(issue); } else { issueMgr.Create(issue); SaveSuccessMessage(Resources.ISS.IssueMaster.QD_Issue_Added); if(issue.ContinuousCreate){ return RedirectToAction("New"); } return RedirectToAction("Edit/" + issue.Code); } } #endregion #region Edit Status [SconitAuthorize(Permissions = "Url_QualityDoor_View")] public ActionResult Submit(string id) { if (string.IsNullOrWhiteSpace(id)) { return HttpNotFound(); } else { try { this.issueMgr.Release(id); SaveSuccessMessage(Resources.ISS.IssueMaster.QD_Issue_Submited); } catch (BusinessException ex) { SaveErrorMessage(ex.Message); } return RedirectToAction("Edit/" + id); } } [SconitAuthorize(Permissions = "Url_QualityDoor_View")] public ActionResult Start(string id) { if (string.IsNullOrWhiteSpace(id)) { return HttpNotFound(); } else { IssueMaster issue = this.genericMgr.FindById<IssueMaster>(id); if (issue == null) { return HttpNotFound(); } if (issue.Status == com.Sconit.CodeMaster.IssueStatus.Submit) { try { issue.StartDate = DateTime.Now; issue.StartUser = this.CurrentUser.Id; issue.StartUserName = this.CurrentUser.FullName; issue.Status = com.Sconit.CodeMaster.IssueStatus.InProcess; this.genericMgr.Update(issue); SaveSuccessMessage(Resources.ISS.IssueMaster.QD_Issue_Started); } catch (BusinessException ex) { SaveErrorMessage(ex.Message); } } return RedirectToAction("Edit/" + id); } } [SconitAuthorize(Permissions = "Url_QualityDoor_View")] public ActionResult Complete(string id) { if (string.IsNullOrWhiteSpace(id)) { return HttpNotFound(); } else { IssueMaster issue = this.genericMgr.FindById<IssueMaster>(id); if (issue == null) { return HttpNotFound(); } if (issue.Status == com.Sconit.CodeMaster.IssueStatus.InProcess) { try { issue.CompleteDate = DateTime.Now; issue.CompleteUser = this.CurrentUser.Id; issue.CompleteUserName = this.CurrentUser.FullName; issue.Status = com.Sconit.CodeMaster.IssueStatus.Complete; this.genericMgr.Update(issue); SaveSuccessMessage(Resources.ISS.IssueMaster.QD_Issue_Completed); } catch (BusinessException ex) { SaveErrorMessage(ex.Message); } } return RedirectToAction("Edit/" + id); } } [SconitAuthorize(Permissions = "Url_QualityDoor_View")] public ActionResult Close(string id) { if (string.IsNullOrWhiteSpace(id)) { return HttpNotFound(); } else { IssueMaster issue = this.genericMgr.FindById<IssueMaster>(id); if (issue == null) { return HttpNotFound(); } if (issue.Status == com.Sconit.CodeMaster.IssueStatus.Complete) { try { issue.CloseDate = DateTime.Now; issue.CloseUserName = this.CurrentUser.FullName; issue.CloseUser = this.CurrentUser.Id; issue.Status = com.Sconit.CodeMaster.IssueStatus.Close; this.genericMgr.Update(issue); SaveSuccessMessage(Resources.ISS.IssueMaster.QD_Issue_Closed); } catch (BusinessException ex) { SaveErrorMessage(ex.Message); } } return RedirectToAction("Edit/" + id); } } [SconitAuthorize(Permissions = "Url_QualityDoor_View")] public ActionResult Cancel(string id) { if (string.IsNullOrWhiteSpace(id)) { return HttpNotFound(); } else { IssueMaster issue = this.genericMgr.FindById<IssueMaster>(id); if (issue == null) { return HttpNotFound(); } if (issue.Status == com.Sconit.CodeMaster.IssueStatus.Submit || issue.Status == com.Sconit.CodeMaster.IssueStatus.InProcess) { try { issue.CancelDate = DateTime.Now; issue.CancelUser = this.CurrentUser.Id; issue.CancelUserName = this.CurrentUser.FullName; issue.Status = com.Sconit.CodeMaster.IssueStatus.Cancel; this.genericMgr.Update(issue); SaveSuccessMessage(Resources.ISS.IssueMaster.QD_Issue_Canceled); } catch (BusinessException ex) { SaveErrorMessage(ex.Message); } } return RedirectToAction("Edit/" + id); } } [SconitAuthorize(Permissions = "Url_QualityDoor_View")] public ActionResult Delete(string id) { if (string.IsNullOrWhiteSpace(id)) { return HttpNotFound(); } else { IssueMaster issue = this.genericMgr.FindById<IssueMaster>(id); if (issue == null) { return HttpNotFound(); } if (issue.Status == com.Sconit.CodeMaster.IssueStatus.Create) { this.genericMgr.DeleteById<IssueMaster>(id); SaveSuccessMessage(Resources.ISS.IssueMaster.QD_Issue_Deleted); } return RedirectToAction("List"); } } #endregion #endregion #region private private SearchStatementModel PrepareSearchStatement(GridCommand command, IssueMasterSearchModel searchModel) { string whereStatement = " where ( "; whereStatement += " im.CreateUserId = " + this.CurrentUser.Id; whereStatement += " or im.LastModifyUserId = " + this.CurrentUser.Id; whereStatement += " or im.ReleaseUser = " + this.CurrentUser.Id; whereStatement += " or im.StartUser = " + this.CurrentUser.Id; whereStatement += " or im.CloseUser = " + this.CurrentUser.Id; whereStatement += " or im.CancelUser = " + this.CurrentUser.Id; whereStatement += " or im.CompleteUser = " + this.CurrentUser.Id; whereStatement += " or exists(select count(det.Id) from IssueDetail det join det.User u where det.IssueCode = im.Code and u.Id = " + this.CurrentUser.Id + " ) "; whereStatement += " ) "; IList<object> param = new List<object>(); HqlStatementHelper.AddLikeStatement("Code", searchModel.Code, HqlStatementHelper.LikeMatchMode.Start, "im", ref whereStatement, param); HqlStatementHelper.AddLikeStatement("IssueSubject", searchModel.IssueSubject, HqlStatementHelper.LikeMatchMode.Start, "im", ref whereStatement, param); HqlStatementHelper.AddLikeStatement("BackYards", searchModel.BackYards, HqlStatementHelper.LikeMatchMode.Start, "im", ref whereStatement, param); HqlStatementHelper.AddLikeStatement("Content", searchModel.Content, HqlStatementHelper.LikeMatchMode.Start, "im", ref whereStatement, param); HqlStatementHelper.AddLikeStatement("MobilePhone", searchModel.MobilePhone, HqlStatementHelper.LikeMatchMode.Start, "im", ref whereStatement, param); if (searchModel.DateFrom != null & searchModel.DateTo != null) { HqlStatementHelper.AddBetweenStatement("CreateDate", searchModel.DateFrom, searchModel.DateTo, "im", ref whereStatement, param); } else if (searchModel.DateFrom != null & searchModel.DateTo == null) { HqlStatementHelper.AddGeStatement("CreateDate", searchModel.DateFrom, "im", ref whereStatement, param); } else if (searchModel.DateFrom == null & searchModel.DateTo != null) { HqlStatementHelper.AddLeStatement("CreateDate", searchModel.DateTo, "im", ref whereStatement, param); } HqlStatementHelper.AddEqStatement("Status", searchModel.Status, "im", ref whereStatement, param); HqlStatementHelper.AddEqStatement("Type", searchModel.Type, "im", ref whereStatement, param); HqlStatementHelper.AddEqStatement("Code", searchModel.IssueTypeCode, "it", ref whereStatement, param); HqlStatementHelper.AddEqStatement("Code", searchModel.IssueNoCode, "ino", ref whereStatement, param); string sortingStatement = HqlStatementHelper.GetSortingStatement(command.SortDescriptors); SearchStatementModel searchStatementModel = new SearchStatementModel(); searchStatementModel.SelectCountStatement = selectCountStatement; searchStatementModel.SelectStatement = selectStatement; searchStatementModel.WhereStatement = whereStatement; searchStatementModel.SortingStatement = sortingStatement; searchStatementModel.Parameters = param.ToArray<object>(); return searchStatementModel; } #endregion } }
using System; namespace ScriptKit { public class Script { public Script() { } public uint ScriptId { get; private set; } public string FileName { get; private set; } public uint LineCount { get; private set; } public uint SourceLength { get; private set; } public uint ParentScriptId { get; private set; } public string ScriptType { get; private set; } public string Source { get; private set; } } }
using cyrka.api.domain.projects; namespace cyrka.api.web.models.projects { public class StatusInfo { public ProjectStatus Status { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// Diese Singelton Klasse hält alle ausgewählten Protokolle /// </summary> public class DataVisProtocolHolder { private List<DataVisProtocol> dataVisProtocolList = new List<DataVisProtocol>(); private static DataVisProtocolHolder _instance; private DataVisProtocolHolder(){ } public static DataVisProtocolHolder GetInstance() { if (_instance == null) { _instance = new DataVisProtocolHolder(); } return _instance; } public void addProtocolToList(DataVisProtocol protocol) { dataVisProtocolList.Add(protocol); } public List<DataVisProtocol> getDataVisProtocolList() { return dataVisProtocolList; } public void fillDataVisProtocolList(List<DataVisProtocol> dataVisProtocolList) { this.dataVisProtocolList = dataVisProtocolList; } /// <summary> /// Methode gibt eine Liste von PlotDaten zurück welche aus der Liste aller Protokolle erstellt wurde. /// </summary> public List<PlotData> getPlotDataList() { List <PlotData> plotDataList = new List<PlotData>(); foreach(DataVisProtocol protocol in dataVisProtocolList) { PlotData plotData = new PlotData(); plotData.Name = protocol.name; plotData._id = protocol._id; TextAsset csvAsset = new TextAsset(protocol.dataset.ToString()); Debug.LogError(csvAsset); plotData.CsvAsset = csvAsset; if(!(protocol.colors is null)) { plotData.CategorieColors = protocol.colors.colorList; plotData.CategorieColumn = protocol.colors.column; } if(!(protocol.selection is null)) { plotData.Selection = protocol.selection; } if (!(protocol.classification)) { plotData.Classification = protocol.classification; } plotDataList.Add(plotData); } return plotDataList; } public void clearProtocols() { dataVisProtocolList.Clear(); } }
using UnityEngine; using UnityEngine.UI; using System.Collections; using System.Collections.Generic; public class SlideViewer : MonoBehaviour { [SerializeField] Image[] images; [SerializeField] Color activeColor; [SerializeField] Color deactiveColor; [SerializeField] SlideExtension slide; int index; void Awake() { } void Start() { index = slide.TargetNum; foreach (Image image in images) { image.color = deactiveColor; } images[index].color = activeColor; } void Update() { if (index == slide.TargetNum) return; images[index ].color = deactiveColor; images[slide.TargetNum].color = activeColor; index = slide.TargetNum; } }
using System; using System.Collections.Generic; using System.Text; using System.Data.SqlClient; using Microsoft.Data.SqlClient; namespace SAST.WebApp.Infrastructure { public class Repository { public object UnsafeQuery( string connection, string name, string password) { SqlConnection someConnection = new SqlConnection(connection); SqlCommand someCommand = new SqlCommand(); someCommand.Connection = someConnection; someCommand.CommandText = "SELECT AccountNumber FROM Users " + "WHERE Username='" + name + "' AND Password='" + password + "'"; someConnection.Open(); object accountNumber = someCommand.ExecuteScalar(); someConnection.Close(); return accountNumber; } } }
// FFXIVAPP.Plugin.Widgets // WidgetTopMostHelper.cs // // © 2013 ZAM Network LLC using FFXIVAPP.Common.Helpers; using System; using System.Timers; using System.Windows; using System.Windows.Interop; using System.Windows.Threading; using talis.xivplugin.twintania.Interop; using talis.xivplugin.twintania.Properties; using talis.xivplugin.twintania.Windows; namespace talis.xivplugin.twintania.Helpers { public static class WidgetTopMostHelper { private static WinAPI.WinEventDelegate _delegate; private static IntPtr _mainHandleHook; private static Timer SetWindowTimer { get; set; } public static void HookWidgetTopMost() { try { _delegate = BringWidgetsIntoFocus; _mainHandleHook = WinAPI.SetWinEventHook(WinAPI.EVENT_SYSTEM_FOREGROUND, WinAPI.EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, _delegate, 0, 0, WinAPI.WINEVENT_OUTOFCONTEXT); } catch (Exception e) { } SetWindowTimer = new Timer(1000); SetWindowTimer.Elapsed += SetWindowTimerOnElapsed; SetWindowTimer.Start(); } private static void SetWindowTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs) { DispatcherHelper.Invoke(() => BringWidgetsIntoFocus(), DispatcherPriority.Normal); } private static void BringWidgetsIntoFocus(IntPtr hwineventhook, uint eventtype, IntPtr hwnd, int idobject, int idchild, uint dweventthread, uint dwmseventtime) { BringWidgetsIntoFocus(true); } private static void BringWidgetsIntoFocus(bool force = false) { try { var handle = WinAPI.GetForegroundWindow(); var stayOnTop = WinAPI.GetActiveWindowTitle() .ToUpper() .StartsWith("FINAL FANTASY XIV"); // If any of the widgets are focused, don't try to hide any of them, or it'll prevent us from moving/closing them if (handle == new WindowInteropHelper(Widgets.Instance.TwintaniaHPWidget).Handle) { return; } if (Settings.Default.ShowTwintaniaHPWidgetOnLoad) { // Override to keep the Widget on top during test mode if (TwintaniaHPWidgetViewModel.Instance.ForceTop) stayOnTop = true; ToggleTopMost(Widgets.Instance.TwintaniaHPWidget, stayOnTop, force); } } catch (Exception ex) { } } /// <summary> /// </summary> /// <param name="window"></param> /// <param name="stayOnTop"></param> /// <param name="force"></param> private static void ToggleTopMost(Window window, bool stayOnTop, bool force) { if (window.Topmost && stayOnTop && !force) { return; } window.Topmost = false; if (!stayOnTop) { if (window.IsVisible) { window.Hide(); } return; } window.Topmost = true; if (!window.IsVisible) { window.Show(); } } } }
using System.Threading.Tasks; using Fody; using VerifyTests; using VerifyXunit; using Xunit; public partial class ModuleWeaverTests { [Fact] public Task DecompileExample() { var decompile = Ildasm.Decompile(testResult.AssemblyPath, "AssemblyToProcess.Example"); var settings = new VerifySettings(); settings.AutoVerify(); return Verifier.Verify(decompile, settings); } [Fact] public Task DecompileIssue1() { var decompile = Ildasm.Decompile(testResult.AssemblyPath, "AssemblyToProcess.Issue1"); var settings = new VerifySettings(); settings.AutoVerify(); return Verifier.Verify(decompile, settings); } [Fact] public Task DecompileGenericClass() { var decompile = Ildasm.Decompile(testResult.AssemblyPath, "AssemblyToProcess.GenericClass`1"); var settings = new VerifySettings(); settings.AutoVerify(); return Verifier.Verify(decompile, settings); } [Fact] public Task DecompileGenericMethod() { var decompile = Ildasm.Decompile(testResult.AssemblyPath, "AssemblyToProcess.GenericMethod"); var settings = new VerifySettings(); settings.AutoVerify(); return Verifier.Verify(decompile, settings); } [Fact] public Task DecompileCatchAndFinally() { var decompile = Ildasm.Decompile(testResult.AssemblyPath, "AssemblyToProcess.CatchAndFinally"); var settings = new VerifySettings(); settings.AutoVerify(); return Verifier.Verify(decompile, settings); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; using MySql.Data; using MySql.Data.MySqlClient; namespace LoyaltyApp { public partial class Form1 : Form { //Global name of app acessible everywhere string strMyAppName = "Loyalty™ App (Biosmart Tech.)"; MySqlConnection connection; MySqlDataAdapter dataAdapter; //Global Var to help calculate Points int cust_id; int lifeTimePoint; int usedPoint; int validPoint; // global declaration int hContext; //card reader context handle int hCard; //card connection handle int ActiveProtocol, retcode; int Aprotocol, i; byte[] rdrlist = new byte[100]; byte[] array = new byte[256]; byte[] SendBuff = new byte[262]; byte[] RecvBuff = new byte[262]; byte[] tmpArray = new byte[56]; ModWinsCard.APDURec apdu = new ModWinsCard.APDURec(); ModWinsCard.SCARD_IO_REQUEST sIO = new ModWinsCard.SCARD_IO_REQUEST(); ModWinsCard.SCARD_READERSTATE ReaderState = new ModWinsCard.SCARD_READERSTATE(); bool CardStatus; int indx, SendBuffLen, RecvBuffLen; string tmpStr, sTemp; byte HiAddr, LoAddr, dataLen; bool connActive = false; string rrname; public Form1() { InitializeComponent(); string ReaderList = "" + Convert.ToChar(0); char[] delimiter = new char[1]; tabViewCard.TabPages.Remove(tabPage1); tabViewCard.TabPages.Remove(tabPage2); tabViewCard.TabPages.Remove(tabPage3); } private bool openDB() { string connectionString = "SERVER=127.0.0.1;DATABASE=loyal;UID=root;PASSWORD=;"; connection = new MySqlConnection(connectionString); try { connection.Open(); return true; } catch (Exception ex) { MessageBox.Show(ex.Message, strMyAppName); return false; } } private void closeDB() { try { connection.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btnNewCard_Click(object sender, EventArgs e) { if (!connectCard()) { MessageBox.Show("Please Insert a blank card to continue"); return; } else { SubmitIC(); if (retcode != ModWinsCard.SCARD_S_SUCCESS) return; //Select FF 02 //displayOut(0, 0, "Select FF 02"); SelectFile(0xFF, 0x02); if (retcode != ModWinsCard.SCARD_S_SUCCESS) return; /* Write to FF 02 This will create 3 User files, no Option registers and Security Option registers defined, Personalization bit is not set */ tmpArray[0] = 0x00; // 00 Option registers tmpArray[1] = 0x00; // 00 Security option register tmpArray[2] = 0x07; // 07 No of user files tmpArray[3] = 0x00; // 00 Personalization bit writeRecord(0x00, 0x00, 0x04, 0x04, ref tmpArray); if (retcode != ModWinsCard.SCARD_S_SUCCESS) return; //Select FF 04 //displayOut(0, 0, "Select FF 04"); SelectFile(0xFF, 0x04); if (retcode != ModWinsCard.SCARD_S_SUCCESS) return; // Send IC Code //displayOut(0, 0, "Submit Code"); SubmitIC(); if (retcode != ModWinsCard.SCARD_S_SUCCESS) return; /* Write to FF 04*/ //Write to third record of FF 04 tmpArray[0] = 0x20; // 32 Record length tmpArray[1] = 0x07; // 7 No of records tmpArray[2] = 0x00; // 00 Read security attribute tmpArray[3] = 0x00; // 00 Write security attribute tmpArray[4] = 0xAA; // AA File identifier tmpArray[5] = 0x11; // 11 File identifier tmpArray[6] = 0x00; // 00 File Access Flag Bit writeRecord(0x00, 0x02, 0x07, 0x07, ref tmpArray); if (retcode != ModWinsCard.SCARD_S_SUCCESS) return; MessageBox.Show("Smart Card is ready"); //displayOut(0, 0, "User File AA 11 is defined"); } try { if (txtSurname.Text != "" && txtFname.Text != "" && txtTel.Text != "" && openDB() == true) { string bDay = birthday.Text; //birthday.ToString("yyyy-MM-dd"); DateTime dateValue = DateTime.Parse(bDay); string final = dateValue.ToString("yyyy-MM-dd"); // MessageBox.Show(final); //return; string query = "INSERT INTO customer(cus_id, sName, oName, address, tel, dob, comment)" + " VALUES('" + txtCardNo.Text + "', '" + txtSurname.Text + "', '" + txtFname.Text + "', '" + txtAddress.Text + "', '" + txtTel.Text + "', '" + final + "', '" + txtComment.Text + "')"; MySqlCommand cmd = new MySqlCommand(query, connection); cmd.ExecuteNonQuery(); HiAddr = 0xAA; LoAddr = 0x11; dataLen = 0x20; // Select User File SelectFile(HiAddr, LoAddr); if (retcode != ModWinsCard.SCARD_S_SUCCESS) return; write(txtCardNo.Text, 0x00); write(txtSurname.Text, 0x01); write(txtFname.Text, 0x02); write(txtAddress.Text, 0x03); write(txtTel.Text, 0x04); write(final, 0x05); write(txtComment.Text, 0x06); MessageBox.Show("New Customer Added"); txtSurname.Text = ""; txtFname.Text = ""; txtTel.Text = ""; txtCardNo.Text = ""; txtAddress.Text = ""; txtComment.Text = ""; } else { MessageBox.Show("bad"); } closeDB(); } catch (MySqlException ex) { MessageBox.Show(ex.Message); } finally { closeDB(); } } private void write(string data, byte recNum) { tmpStr = ""; tmpStr = data; //Clear the data first for (indx = 0; indx < tmpArray.Length; indx++) { tmpArray[indx] = 0x00; } writeRecord(0x01, recNum, (byte)tmpArray.Length, (byte)tmpArray.Length, ref tmpArray); if (retcode != ModWinsCard.SCARD_S_SUCCESS) return; //Now write the data to the card for (indx = 0; indx < tmpStr.Length; indx++) { tmpArray[indx] = (byte)Asc(tmpStr.Substring(indx, 1)); } writeRecord(0x01, recNum, dataLen, dataLen, ref tmpArray); if (retcode != ModWinsCard.SCARD_S_SUCCESS) return; //displayOut(0, 0, "Data read from Text Box is written to card."); MessageBox.Show(recNum.ToString() + "\n" + tmpArray.ToString()); } private string read(byte recNum) { int indx; // Read First Record of User File selected readRecord(recNum, dataLen); if (retcode != ModWinsCard.SCARD_S_SUCCESS) return "Error reading Portion"; // Display data read from card to textbox tmpStr = ""; indx = 0; while (RecvBuff[indx] != 0x00) { if (indx < 32767) { tmpStr = tmpStr + Chr(RecvBuff[indx]); } indx = indx + 1; } //txtData.Text = tmpStr; return tmpStr; //displayOut(0, 0, "Data read from card is displayed"); } private void btnInitialize_Click(object sender, EventArgs e) { byte[] returnData = null; // Will hold the reader names after the call to SCardListReaders int readerCount = 255; // Total length of the reader names string readerNames = ""; // Will hold the reader names after converting from byte array to a single string. string[] readerList = null; // String array of the Reader Names int idx = 0; // Established using ScardEstablishedContext() retcode = ModWinsCard.SCardEstablishContext(ModWinsCard.SCARD_SCOPE_USER, 0, 0, ref hContext); if (retcode != ModWinsCard.SCARD_S_SUCCESS) { MessageBox.Show(retcode + ""); return; } else { MessageBox.Show("SCardEsatablishContext... OK"); } // List PC/SC card readers installed in the system // Call SCardListReaders to get the total length of the reader names retcode = ModWinsCard.SCardListReaders(hContext, null, null, ref readerCount); if (retcode != ModWinsCard.SCARD_S_SUCCESS) { MessageBox.Show(retcode + ""); return; } else { returnData = new byte[readerCount]; // Call SCardListReaders this time passing the array to hold the return data. retcode = ModWinsCard.SCardListReaders(this.hContext, null, returnData, ref readerCount); if (retcode != ModWinsCard.SCARD_S_SUCCESS) { MessageBox.Show(retcode + "Error"); return; } else { MessageBox.Show("SCardListReaders...OK"); // Convert the return data to a string readerNames = System.Text.ASCIIEncoding.ASCII.GetString(returnData); // Parse the string and split the reader names. Delimited by \0. readerList = readerNames.Split('\0'); // Clear the combo list of all items. cmbReader.Items.Clear(); // For each string in the array, add them to the combo list for (idx = 0; idx < readerList.Length; idx++) { cmbReader.Items.Add(readerList[idx]); } cmbReader.SelectedIndex = 0; rrname = cmbReader.Text; timer1.Enabled = true; } } } private void btnConnect_Click(object sender, EventArgs e) { if (rdrSearch.Checked) { if (txtSearchBox.Text == "") { MessageBox.Show("Please Provide Customer ID", strMyAppName, MessageBoxButtons.OK, MessageBoxIcon.Error); } else { getCustomer(txtSearchBox.Text); } } else { if (connectCard()) { //Write a method to retrieve the customer id from card HiAddr = 0xAA; LoAddr = 0x11; dataLen = 0x20; // Select User File SelectFile(HiAddr, LoAddr); if (retcode != ModWinsCard.SCARD_S_SUCCESS) return; getCustomer(read(0x00)); } } } private bool connectCard() { // Connect to selected reader using hContext handle and obtain hCard handle if (connActive) retcode = ModWinsCard.SCardDisconnect(hCard, ModWinsCard.SCARD_UNPOWER_CARD); // Connect to the reader using hContext handle and obtain hCard handle retcode = ModWinsCard.SCardConnect(this.hContext, cmbReader.Text, ModWinsCard.SCARD_SHARE_EXCLUSIVE, 0 | 1, ref hCard, ref ActiveProtocol); if (retcode != ModWinsCard.SCARD_S_SUCCESS) { MessageBox.Show(ModWinsCard.GetScardErrMsg(retcode)); return false; } else { MessageBox.Show("Connection OK"); connActive = true; return true; } } private void getCustomer(string cus_id) { if (openDB()) { try { string query = "SELECT * FROM customer WHERE cus_id = '" + cus_id + "' LIMIT 0,1"; MySqlCommand cmd = new MySqlCommand(query, connection); MySqlDataReader rdr = cmd.ExecuteReader(); if (rdr.HasRows) { while (rdr.Read()) { MessageBox.Show("Customer Found"); lblCustName.Text = rdr["sName"].ToString() + " " + rdr["oName"].ToString(); lblCardNo.Text = rdr["cus_id"].ToString(); cust_id = int.Parse(rdr[0].ToString()); groupBox3.Enabled = true; } } else { MessageBox.Show("Invalid Customer ID", strMyAppName, MessageBoxButtons.OK, MessageBoxIcon.Error); } rdr.Close(); //This is to chek the total lifetime point query = "SELECT SUM(point) FROM tbl_addpoint WHERE customer_id = " + cust_id + ""; cmd = new MySqlCommand(query, connection); rdr = cmd.ExecuteReader(); if (rdr.HasRows) { while (rdr.Read()) { lblLifeP.Text = rdr[0].ToString(); lifeTimePoint = int.Parse(rdr[0].ToString()); } } else { lblLifeP.Text = "No Points Yet"; } rdr.Close(); //This is to check for the total number of used point query = "SELECT SUM(usedPoint) FROM tbl_usedpoint WHERE customer_id = " + cust_id + ""; cmd = new MySqlCommand(query, connection); rdr = cmd.ExecuteReader(); if (rdr.HasRows) { while (rdr.Read()) { lblUsedP.Text = rdr[0].ToString(); usedPoint = int.Parse(rdr[0].ToString()); } } else { lblLifeP.Text = "No Points used"; } rdr.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, strMyAppName, MessageBoxButtons.OK, MessageBoxIcon.Error); } } closeDB(); validPoint = (lifeTimePoint - usedPoint); lblValidP.Text = validPoint.ToString(); } private void btnReset_Click(object sender, EventArgs e) { txtUser.Text = ""; txtPass.Text = ""; } private void btnLogin_Click(object sender, EventArgs e) { if (txtUser.Text == "" && txtPass.Text == "") { MessageBox.Show("Please Provide Username and Password", strMyAppName, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } try { if (openDB()) { string query = "SELECT * FROM staff WHERE username = '" + txtUser.Text + "' AND password = '" + txtPass.Text + "' LIMIT 0,1"; MySqlCommand cmd = new MySqlCommand(query, connection); MySqlDataReader rdr = cmd.ExecuteReader(); if (rdr.HasRows) { while (rdr.Read()) { MessageBox.Show("Welcome " + rdr["username"].ToString()); btnLogin.Enabled = false; btnReset.Enabled = false; txtUser.Enabled = false; txtPass.Enabled = false; btnLogout.Enabled = true; if (int.Parse(rdr["role_id"].ToString()) == 1){ tabViewCard.TabPages.Add(tabPage1); tabViewCard.TabPages.Add(tabPage2); tabViewCard.TabPages.Add(tabPage3); } else if (int.Parse(rdr["role_id"].ToString()) == 2) { tabViewCard.TabPages.Add(tabPage1); tabViewCard.TabPages.Add(tabPage2); tabViewCard.TabPages.Add(tabPage3); } else if (int.Parse(rdr["role_id"].ToString()) == 3) { tabViewCard.TabPages.Add(tabPage1); tabViewCard.TabPages.Add(tabPage3); } } } else { MessageBox.Show("Invalid Username or Password"); } rdr.Close(); } } catch (Exception ex) { log_events("Login Error: "+ex.Message); MessageBox.Show(ex.Message, strMyAppName, MessageBoxButtons.OK, MessageBoxIcon.Error); } closeDB(); } private void log_events(String txt) { String fileName = @"\log_" + DateTime.Today.ToShortDateString().Replace("/", "_").ToString() + ".txt"; //String fileName = @"log_" + Path.GetFileNameWithoutExtension(Path.GetTempFileName()).ToString() + ".txt"; StreamWriter logg = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + fileName, true); logg.WriteLine(DateTime.Now + " " + txt); logg.Close(); logg.Dispose(); } private void btnLogout_Click(object sender, EventArgs e) { tabViewCard.TabPages.Remove(tabPage1); tabViewCard.TabPages.Remove(tabPage2); tabViewCard.TabPages.Remove(tabPage3); btnLogin.Enabled = true; btnReset.Enabled = true; txtUser.Enabled = true; txtPass.Enabled = true; btnLogout.Enabled = false; txtUser.Text = ""; txtPass.Text = ""; disconnect(); retcode = ModWinsCard.SCardReleaseContext(hContext); //InitializeComponent(); } private void btnUpdatePoint_Click(object sender, EventArgs e) { if (txtRNum.Text == "" && txtValue.Text == "") { MessageBox.Show("Please Insert the values", strMyAppName, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (txtRNum.Text != "" && txtValue.Text != "" && openDB() == true) { float value = float.Parse(txtValue.Text); int point = (int) Math.Round(0.3 * value); // MessageBox.Show(final); //return; string query = "INSERT INTO tbl_addPoint(customer_id, recieptNo, value, point)" + " VALUES(" + cust_id + ", '" + txtRNum.Text + "', " + value + ", " + point + ")"; MySqlCommand cmd = new MySqlCommand(query, connection); cmd.ExecuteNonQuery(); MessageBox.Show("Points Added", strMyAppName, MessageBoxButtons.OK, MessageBoxIcon.Information); txtRNum.Text = ""; txtValue.Text = ""; } else { MessageBox.Show("bad", strMyAppName, MessageBoxButtons.OK, MessageBoxIcon.Error); } closeDB(); } private void rdrSearch_CheckedChanged(object sender, EventArgs e) { txtSearchBox.Enabled = true; } private void btnDeductPoint_Click(object sender, EventArgs e) { if (txtDeductValue.Text == "") { MessageBox.Show("Please input point to deduct"); return; } int deduct = int.Parse(txtDeductValue.Text); int final = (validPoint - deduct); if (validPoint <= 0 || final < 0) { MessageBox.Show("Sorry, You Don't have Enough Points to perform this transaction"); return; } else if(openDB()) { DateTime now = DateTime.Now; string sec = "yyyy-MM-dd"; string query = "INSERT INTO tbl_usedPoint(customer_id, validPoint, usedPoint, date)" + " VALUES(" + cust_id + ", " + validPoint + ", " + deduct + ", '" + now.ToString(sec) + "')"; MySqlCommand cmd = new MySqlCommand(query, connection); cmd.ExecuteNonQuery(); MessageBox.Show("Points Deducted"); txtDeductValue.Text = ""; } closeDB(); } private void timer1_Tick(object sender, EventArgs e) { ReaderState.RdrName = rrname; //perform if the card is inserted/not inserted on the reader retcode = ModWinsCard.SCardGetStatusChange(this.hContext, 0, ref ReaderState, 1); if (retcode != ModWinsCard.SCARD_S_SUCCESS){ lblReaderState.Text = "Error!"; }else{ if ((ReaderState.RdrEventState & 32) != 0) { CardStatus = true; } else { CardStatus = false; } } if (retcode != ModWinsCard.SCARD_S_SUCCESS){} else{ if (CardStatus == true){ lblReaderState.Text = "Card Inserted"; }else{ lblReaderState.Text = "No Card Inserted"; } } } private void PerformTransmitAPDU(ref ModWinsCard.APDURec apdu) { ModWinsCard.SCARD_IO_REQUEST SendRequest; ModWinsCard.SCARD_IO_REQUEST RecvRequest; SendBuff[0] = apdu.bCLA; SendBuff[1] = apdu.bINS; SendBuff[2] = apdu.bP1; SendBuff[3] = apdu.bP2; SendBuff[4] = apdu.bP3; if (apdu.IsSend) { for (indx = 0; indx < apdu.bP3; indx++) { SendBuff[5 + indx] = apdu.Data[indx]; } SendBuffLen = 5 + apdu.bP3; RecvBuffLen = 2; } else { SendBuffLen = 5; RecvBuffLen = 2 + apdu.bP3; } SendRequest.dwProtocol = Aprotocol; SendRequest.cbPciLength = 8; RecvRequest.dwProtocol = Aprotocol; RecvRequest.cbPciLength = 8; retcode = ModWinsCard.SCardTransmit(hCard, ref SendRequest, ref SendBuff[0], SendBuffLen, ref SendRequest, ref RecvBuff[0], ref RecvBuffLen); if (retcode != ModWinsCard.SCARD_S_SUCCESS) { // displayOut(1, retcode, ""); return; } sTemp = ""; // do loop for sendbuffLen for (indx = 0; indx < SendBuffLen; indx++) { sTemp = sTemp + " " + string.Format("{0:X2}", SendBuff[indx]); } // Display Send Buffer Value // displayOut(2, 0, sTemp); sTemp = ""; // do loop for RecvbuffLen for (indx = 0; indx < RecvBuffLen; indx++) { sTemp = sTemp + " " + string.Format("{0:X2}", RecvBuff[indx]); } // Display Receive Buffer Value // displayOut(3, 0, sTemp); if (apdu.IsSend == false) { for (indx = 0; indx < apdu.bP3 + 2; indx++) { apdu.Data[indx] = RecvBuff[indx]; } } } private void SubmitIC() { //Send IC Code apdu.Data = array; apdu.bCLA = 0x80; // CLA apdu.bINS = 0x20; // INS apdu.bP1 = 0x07; // P1 apdu.bP2 = 0x00; // P2 apdu.bP3 = 0x08; // P3 apdu.Data[0] = 0x41; // A apdu.Data[1] = 0x43; // C apdu.Data[2] = 0x4F; // O apdu.Data[3] = 0x53; // S apdu.Data[4] = 0x54; // T apdu.Data[5] = 0x45; // E apdu.Data[6] = 0x53; // S apdu.Data[7] = 0x54; // T apdu.IsSend = true; PerformTransmitAPDU(ref apdu); if (retcode != ModWinsCard.SCARD_S_SUCCESS) return; if (RecvBuff[0] != 0x90 && RecvBuff[1] != 0x00) { retcode = -450; return; } } private void SelectFile(byte HiAddr, byte LoAddr) { apdu.Data = array; apdu.bCLA = 0x080; // CLA apdu.bINS = 0x0A4; // INS apdu.bP1 = 0x00; // P1 apdu.bP2 = 0x00; // P2 apdu.bP3 = 0x02; // P3 apdu.Data[0] = HiAddr; // Value of High Byte apdu.Data[1] = LoAddr; // Value of Low Byte apdu.IsSend = true; PerformTransmitAPDU(ref apdu); if (retcode != ModWinsCard.SCARD_S_SUCCESS) return; } private void writeRecord(int caseType, byte RecNo, byte maxLen, byte DataLen, ref byte[] ApduIn) { if (caseType == 1) // If card data is to be erased before writing new data. Re-initialize card values to $00 { apdu.bCLA = 0x80; // CLA apdu.bINS = 0xD2; // INS apdu.bP1 = RecNo; // Record No apdu.bP2 = 0x00; // P2 apdu.bP3 = maxLen; // Length of Data apdu.IsSend = true; for (i = 0; i < maxLen; i++) { apdu.Data[i] = ApduIn[i]; } PerformTransmitAPDU(ref apdu); if (retcode != ModWinsCard.SCARD_S_SUCCESS) return; if (RecvBuff[0] != 0x90 && RecvBuff[1] != 0x00) { retcode = -450; return; } } //Write data to card apdu.bCLA = 0x80; // CLA apdu.bINS = 0xD2; // INS apdu.bP1 = RecNo; // Record No apdu.bP2 = 0x00; // P2 apdu.bP3 = DataLen; // Length of Data apdu.IsSend = true; for (i = 0; i < maxLen; i++) { apdu.Data[i] = ApduIn[i]; } PerformTransmitAPDU(ref apdu); if (retcode != ModWinsCard.SCARD_S_SUCCESS) return; if (RecvBuff[0] != 0x90 && RecvBuff[1] != 0x00) { retcode = -450; return; } } public static string Mid(string tmpStr, int start) { return tmpStr.Substring(start, tmpStr.Length - start); } int Asc(string character) { if (character.Length == 1) { System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding(); int intAsciiCode = (int)asciiEncoding.GetBytes(character)[0]; return (intAsciiCode); } else { throw new Exception("Character is not valid."); } } void ClearBuffers() { int indx = 0; for (indx = 0; indx < 262; indx++) { SendBuff[indx] = 0x00; RecvBuff[indx] = 0x00; } } private void readRecord(byte RecNo, byte dataLen) { apdu.Data = array; // Read data from card apdu.bCLA = 0x80; // CLA apdu.bINS = 0xB2; // INS apdu.bP1 = RecNo; // Record No apdu.bP2 = 0x00; // P2 apdu.bP3 = dataLen; // Length of Data apdu.IsSend = false; PerformTransmitAPDU(ref apdu); if (retcode != ModWinsCard.SCARD_S_SUCCESS) return; } Char Chr(int i) { //Return the character of the given character value return Convert.ToChar(i); } private void btnReadCard_Click(object sender, EventArgs e) { HiAddr = 0xAA; LoAddr = 0x11; dataLen = 0x20; // Select User File SelectFile(HiAddr, LoAddr); if (retcode != ModWinsCard.SCARD_S_SUCCESS) return; lblCardNum.Text = read(0x00) + "!"; lblSName.Text = read(0x01) + "!"; lblFName.Text = read(0x02) + "!"; lblAddress.Text = read(0x03) + "!"; lblTel.Text = read(0x04) + "!"; lblDOB.Text = read(0x05) + "!"; lblCmt.Text = read(0x06) + "!"; } private void disconnect() { if (connActive) retcode = ModWinsCard.SCardDisconnect(hCard, ModWinsCard.SCARD_UNPOWER_CARD); } private void btnAddStaff_Click(object sender, EventArgs e) { if (openDB()) { string query = "INSERT INTO staff(role_id, username, password, fName, lName, phone) VALUES()"; MySqlCommand cmd = new MySqlCommand(query, connection); cmd.ExecuteNonQuery(); } closeDB(); } private void btnViewStaff_Click(object sender, EventArgs e) { if (openDB()) { dataAdapter = new MySqlDataAdapter("SELECT * FROM staff", connection); DataSet DS = new DataSet(); dataAdapter.Fill(DS); dataGridView1.DataSource = DS.Tables[0]; } closeDB(); } private void dataGridView1_RowValidated(object sender, DataGridViewCellEventArgs e) { DataTable changes = ((DataTable)dataGridView1.DataSource).GetChanges(); if (changes != null) { MySqlCommandBuilder mcb = new MySqlCommandBuilder(dataAdapter); dataAdapter.UpdateCommand = mcb.GetUpdateCommand(); dataAdapter.Update(changes); ((DataTable)dataGridView1.DataSource).AcceptChanges(); } } } }
using System; using System.Globalization; using System.Collections.Generic; using Kattis.IO; public class Program { public static List<edge>[] adj; public static EdgeComparer edgeComparer; public struct union_find { public int[] parent; public union_find(int n) { parent = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; } } public int find(int x) { if (parent[x] == x) { return x; } else { parent[x] = find(parent[x]); return parent[x]; } } public void unite(int x, int y) { parent[find(x)] = find(y); } } public struct xy { public xy(double x, double y){ this.x = x; this.y = y; } override public string ToString(){ return x.ToString() + "," + y.ToString(); } public double x; public double y; } public struct edge { public int u, v; public double weight; public edge(int _u, int _v, double _w) { u = _u; v = _v; weight = _w; } } public class EdgeComparer: IComparer<edge>{ public int Compare(edge a, edge b){ if(a.weight < b.weight){ return -1; } else { return 1; } } } public bool edge_cmp(edge a, edge b) { return a.weight < b.weight; } static public List<edge> mst(int n, List<edge> edges) { union_find uf = new union_find(n); //sort(edges.begin(), edges.end(), edge_cmp); edges.Sort(edgeComparer); List<edge> res = new List<edge>(); for (int i = 0; i < edges.Count; i++) { int u = edges[i].u, v = edges[i].v; if (uf.find(u) != uf.find(v)) { uf.unite(u, v); res.Add(edges[i]); } } return res; } static public void Main () { Scanner scanner = new Scanner(); BufferedStdoutWriter writer = new BufferedStdoutWriter(); edgeComparer = new EdgeComparer(); int nCases = scanner.NextInt(); while(nCases-- > 0){ int nFreckles = scanner.NextInt(); /* adj = new List<edge>[nFreckles]; for(int i = 0; i < nFreckles; i++){ adj[i] = new List<edge>(); }*/ List<edge> edges = new List<edge>(); xy[] points = new xy[nFreckles]; for(int i = 0; i < nFreckles; i++){ points[i] = new xy( double.Parse(scanner.Next(), CultureInfo.InvariantCulture), double.Parse(scanner.Next(), CultureInfo.InvariantCulture) ); } for(int i = 0; i < nFreckles; i++){ for(int j = i + 1; j < nFreckles; j++){ double f = (double)Math.Sqrt( Math.Pow(points[i].x - points[j].x, 2) + Math.Pow(points[i].y - points[j].y, 2) ); edges.Add(new edge(i, j, f)); /* adj[i].Add(new edge(i, j, f)); adj[j].Add(new edge(j, i, f)); */ } } double ans = 0.0f; foreach (edge e in mst(nFreckles, edges)) { ans += e.weight; } /* double ans = double.MaxValue; for(int i = 0; i < nFreckles; i++){ double cost = 0.0f; foreach (edge e in mst(nFreckles, adj[i])) { cost += e.weight; } ans = Math.Min(ans, cost); } */ writer.WriteLine(String.Format(CultureInfo.InvariantCulture, "{0:0.00}", ans)); } writer.Flush(); } }
using System; using System.Collections; using UnityEngine; using UnityEngine.EventSystems; using UnityStandardAssets.CrossPlatformInput; public class DualTouchPanel: MonoBehaviour, IPointerUpHandler, IPointerDownHandler, IBeginDragHandler, IEndDragHandler, IDragHandler { // Options for which axes to use public enum AxisOption { Both = 0, // Use both OnlyHorizontal, // Only horizontal OnlyVertical // Only vertical } [Serializable] public struct InputControl { public AxisOption AxesToUse; public string HorizontalAxisName; public string VerticalAxisName; public bool UseX { get { return (AxesToUse == AxisOption.Both || AxesToUse == AxisOption.OnlyHorizontal); } } public bool UseY { get { return (AxesToUse == AxisOption.Both || AxesToUse == AxisOption.OnlyVertical); } } [NonSerialized] public int Pointer; [NonSerialized] public Vector2 Origin; private CrossPlatformInputManager.VirtualAxis horizontalVirtualAxis; public CrossPlatformInputManager.VirtualAxis HorizontalVirtualAxis { get { return horizontalVirtualAxis; } } private CrossPlatformInputManager.VirtualAxis verticalVirtualAxis; public CrossPlatformInputManager.VirtualAxis VerticalVirtualAxis { get { return verticalVirtualAxis; } } private void createHorizontalAxis() { horizontalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(HorizontalAxisName); CrossPlatformInputManager.RegisterVirtualAxis(horizontalVirtualAxis); } private void releaseHorizontalAxis() { if (horizontalVirtualAxis != null) { horizontalVirtualAxis.Remove(); horizontalVirtualAxis = null; } } private void createVerticalAxis() { verticalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(VerticalAxisName); CrossPlatformInputManager.RegisterVirtualAxis(verticalVirtualAxis); } private void releaseVerticalAxis() { if (verticalVirtualAxis != null) { verticalVirtualAxis.Remove(); verticalVirtualAxis = null; } } public void Reset() { AxesToUse = AxisOption.Both; HorizontalAxisName = null; VerticalAxisName = null; releaseHorizontalAxis(); releaseVerticalAxis(); } public void Activate() { Pointer = int.MinValue; Origin = Vector2.zero; if (UseX) createHorizontalAxis(); if (UseY) createVerticalAxis(); } public void Deactivate() { releaseHorizontalAxis(); releaseVerticalAxis(); } } [SerializeField] private InputControl dragLeft; [SerializeField] private InputControl dragRight; [SerializeField] private bool tapEnabled; [SerializeField] private InputControl tap; [SerializeField] private RectTransform dragRange; private bool clearTap = false; #region Monobehaviour #if UNITY_EDITOR void Reset() { dragLeft.Reset(); dragRight.Reset(); tapEnabled = false; tap.Reset(); } #endif void OnEnable() { dragLeft.Activate(); dragRight.Activate(); if (tapEnabled) tap.Activate(); } void OnDisable() { dragLeft.Deactivate(); dragRight.Deactivate(); tap.Deactivate(); } void LateUpdate() { if (clearTap) { clearTap = false; if (tap.UseX) tap.HorizontalVirtualAxis.Update(0); if (tap.UseY) tap.VerticalVirtualAxis.Update(0); } } #endregion #region Drag public void OnBeginDrag(PointerEventData data) { RectTransform rectTransform = (RectTransform)transform; Vector2 size = Vector2.Scale(rectTransform.rect.size, rectTransform.lossyScale); Vector2 point; if (tap.Pointer == data.pointerId) { tap.Pointer = int.MinValue; point = tap.Origin; } else { point = data.position; } float m = size.x / 2; float x = point.x; if (x < m) { if (dragLeft.Pointer == int.MinValue) { dragLeft.Pointer = data.pointerId; dragLeft.Origin = point; } } else { if (dragRight.Pointer == int.MinValue) { dragRight.Pointer = data.pointerId; dragRight.Origin = point; } } } public void OnDrag(PointerEventData data) { if (dragLeft.Pointer == data.pointerId) { Vector2 size = Vector2.Scale(dragRange.rect.size, dragRange.lossyScale); if (dragLeft.UseX) { float deltaX = data.position.x - dragLeft.Origin.x; dragLeft.HorizontalVirtualAxis.Update(Mathf.Clamp(deltaX / size.x, -1, 1)); } if (dragLeft.UseY) { float deltaY = data.position.y - dragLeft.Origin.y; dragLeft.VerticalVirtualAxis.Update(Mathf.Clamp(deltaY / size.y, -1, 1)); } } else if (dragRight.Pointer == data.pointerId) { Vector2 size = Vector2.Scale(dragRange.rect.size, dragRange.lossyScale); if (dragRight.UseX) { float deltaX = data.position.x - dragRight.Origin.x; dragRight.HorizontalVirtualAxis.Update(Mathf.Clamp(deltaX / size.x, -1, 1)); } if (dragRight.UseY) { float deltaY = data.position.y - dragRight.Origin.y; dragRight.VerticalVirtualAxis.Update(Mathf.Clamp(deltaY / size.y, -1, 1)); } } } public void OnEndDrag(PointerEventData data) { if (dragLeft.Pointer == data.pointerId) { if (dragLeft.UseX) dragLeft.HorizontalVirtualAxis.Update(0); if (dragLeft.UseY) dragLeft.VerticalVirtualAxis.Update(0); dragLeft.Pointer = int.MinValue; } else if (dragRight.Pointer == data.pointerId) { if (dragRight.UseX) dragRight.HorizontalVirtualAxis.Update(0); if (dragRight.UseY) dragRight.VerticalVirtualAxis.Update(0); dragRight.Pointer = int.MinValue; } } #endregion #region Pointer public void OnPointerDown(PointerEventData data) { if (tapEnabled) { tap.Pointer = data.pointerId; tap.Origin = data.position; } } public void OnPointerUp(PointerEventData data) { if (tap.Pointer == data.pointerId) { if (tap.UseX) tap.HorizontalVirtualAxis.Update(data.position.x); if (tap.UseY) tap.VerticalVirtualAxis.Update(data.position.y); tap.Pointer = int.MinValue; clearTap = true; } } #endregion }
using System; using System.Collections.Generic; using System.Reflection; using Igorious.StardewValley.DynamicApi2.Extensions; using StardewValley; using StardewValley.Menus; namespace Igorious.StardewValley.DynamicApi2.Services { public sealed class ShopMenuProxy { private static readonly Lazy<FieldInfo> ForSaleField = typeof(ShopMenu).GetLazyInstanceField("forSale"); private static readonly Lazy<FieldInfo> ItemPriceAndStockField = typeof(ShopMenu).GetLazyInstanceField("itemPriceAndStock"); private static readonly Lazy<FieldInfo> HeldItemField = typeof(ShopMenu).GetLazyInstanceField("heldItem"); private readonly ShopMenu _menu; public ShopMenuProxy(ShopMenu menu) { _menu = menu; ItemsForSale = menu.GetFieldValue<List<Item>>(ForSaleField); ItemsPriceAndStock = menu.GetFieldValue<Dictionary<Item, int[]>>(ItemPriceAndStockField); } public Dictionary<Item, int[]> ItemsPriceAndStock { get; } public List<Item> ItemsForSale { get; } public Item HeldItem { get { return _menu.GetFieldValue<Item>(HeldItemField); } set { _menu.SetFieldValue(HeldItemField, value); } } public void AddItem(Item item, int stack = int.MaxValue, int? price = null) { ItemsForSale.Add(item); ItemsPriceAndStock.Add(item, new[] { price ?? item.salePrice(), stack }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ZBC_OOP_Planets { public class UI { private PlanetsControl control; public void MainProgram() { control = new PlanetsControl(); Console.WriteLine("Press any key to initialize list."); Console.ReadKey(); control.FillStarterList(); Console.WriteLine("Initializing list...\n\r\n\r"); // Printing the list to console PrintList(control.GetPlanetsList()); // Inserting Venus AskToContinue(); Console.WriteLine("\n\rInserting Venus between Mercury and Earth\n\r"); control.InsertPlanet(1, "Venus"); // Printing the list to console PrintList(control.GetPlanetsList()); AskToContinue(); Console.WriteLine("\n\rRemoving Pluto from list :( https://i.imgur.com/GyVbdMy.jpg"); control.RemovePlanet("Pluto"); // Printing the list to console PrintList(control.GetPlanetsList()); AskToContinue(); Console.WriteLine("\n\rInserting Pluto again, yay!"); control.AddPlanet("Pluto"); // Printing the list to console PrintList(control.GetPlanetsList()); Console.WriteLine($"\n\rList count: {control.GetPlanetsCount()}"); AskToContinue(); Console.WriteLine("\n\rCreating a new list with the planets whos mean temperature is lower than 0"); PrintList(control.GetFreezingPlanets(0)); AskToContinue(); Console.WriteLine("\n\rCreating a new list with the planets whos diameter is higher than 10,000km and lower than 50,000km"); PrintList(control.GetPlanetsOfSize(10000, 50000)); AskToContinue(); Console.WriteLine("\n\rNow removing ALL planets from the original list"); control.ClearDatabase(); Console.WriteLine("\n\rCurrent list contents...\n\r"); PrintList(control.GetPlanetsList()); Console.WriteLine("--- End of assignment"); } private void AskToContinue() { Console.WriteLine("\n\rPress any key to go on.\n\r"); Console.ReadKey(); } /// <summary> /// Prints the contents of a Planet list to console /// </summary> /// <param name="list"></param> static void PrintList(List<Planet> list) { Console.WriteLine("\n\rList contents: \n\r"); for (int i = 0; i < list.Count; i++) { Console.WriteLine($"{i} - {list[i].Name}"); } } } }
using UnityEngine; public class LayerMaskAutoDestroy : MonoBehaviour { [SerializeField] private GameObject m_destroyObject; [SerializeField] private LayerMask m_destroyMask; [SerializeField] private string m_destroySound; private AudioManager m_audioManager; void Start() { if (!m_destroySound.Equals("")) { m_audioManager = GameObject.FindGameObjectWithTag("AudioManager").GetComponent<AudioManager>(); } } void OnCollisionEnter2D(Collision2D col) { if (m_destroyMask == (m_destroyMask | (1 << col.gameObject.layer))) { if (m_audioManager) m_audioManager.Play("SFX", m_destroySound); Destroy(m_destroyObject); } } }
using AnyTest.Model; using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Text; namespace AnyTest.MobileClient.Model { public class AnswerViewModel : TestAnswer, INotifyPropertyChanged { public override string Answer { get => base.Answer; set { base.Answer = value; OnPropertyChanged(); } } public override int Percent { get => base.Percent; set { base.Percent = value; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged([CallerMemberName] string property = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property)); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DeathPlaneController : MonoBehaviour { public Transform spawnPoint; private void OnCollisionEnter2D(Collision2D other) { if(other.gameObject.CompareTag("Player")) { other.transform.position = spawnPoint.position; } else { other.gameObject.SetActive(false); } } }
using System; using System.Drawing; using System.Windows.Forms; namespace TesteDeMatematica { public partial class Form1 : Form { //Um objeto do tipo Ramdom será usado para gerar números aleatórios. Random random = new Random(); int valorSom1, valorSom2; //Armazenarão os valores para a soma int valorSub1, valorSub2; //Armazenarão os valores para a subtração int valorMul1, valorMul2; //Armazenarão os valores para a multiplicação int valorDiv1, valorDiv2; //Armazenarão os valores para a divisão int tempoRestante; //Armazenará quantos segundos faltam, para que possa ser exibido na tela //Esta função será executada a cada 1000 milisegundos (1 segundo) private void tmrTimer_Tick(object sender, EventArgs e) { if (ConferirResposta()) { //Caso todas as respostas estejam corretas encerra o jogo lblTempo.ForeColor = Color.Green; tmrTimer.Stop(); lblTempo.Text = "Parabéns!!! :)"; MessageBox.Show("Você conseguiu terminar a tempo.", "Parabéns Einstein!!!"); //Exibe as mensagens em uma caixa de diálogo btnIniciar.Enabled = true; Form2 form2 = new Form2(30 - tempoRestante); form2.Show(); } else if (tempoRestante > 0) //Atualiza a contagem na tela a cada segundo { if (tempoRestante == 6) lblTempo.ForeColor = Color.Red; tempoRestante--; lblTempo.Text = tempoRestante + " segundos"; } else { tmrTimer.Stop(); btnIniciar.Enabled = true; //Mostra os resultados corretos, com os que o usuario errou em vermelho nudSoma.ForeColor = (nudSoma.Value == valorSom1 + valorSom2) ? Color.Green : Color.Red; nudSubtracao.ForeColor = (nudSubtracao.Value == valorSub1 - valorSub2) ? Color.Green : Color.Red; nudMultiplicacao.ForeColor = (nudMultiplicacao.Value == valorMul1 * valorMul2) ? Color.Green : Color.Red; nudDivisao.ForeColor = (nudDivisao.Value == valorDiv1 / valorDiv2) ? Color.Green : Color.Red; nudSoma.Value = valorSom1 + valorSom2; nudSubtracao.Value = valorSub1 - valorSub2; nudMultiplicacao.Value = valorMul1 * valorMul2; nudDivisao.Value = valorDiv1 / valorDiv2; lblTempo.Text = "Tempo Acabado"; MessageBox.Show("Você não conseguiu terminar a tempo.", "Mais sorte na próxima vez :("); //Exibe as mensagens em uma caixa de diálogo } } private void Responder_enter(object sender, EventArgs e) { // Seleciona toda a resposta que está na caixa NumericUpDown NumericUpDown answerBox = sender as NumericUpDown; //Caso tenha algo na nud, obtemos o tamanho dete valor e o "selecionamos" //Isto é útil para facilitar a inserção da resposta, selecionando um valor preexistente para que //seja inteiramente substituida pelo valor digitado e não apenas inserida junto a ele if (answerBox != null) { int tamanhoResposta = answerBox.Value.ToString().Length; answerBox.Select(0, tamanhoResposta); } } //Eventos que emitirão um sinal sonoro caso o valor certo seja inserido private void ValorCorretoSoma(object sender, EventArgs e) { if (btnIniciar.Enabled.Equals(false)) //Caso a partida esteja ocorrendo nudSoma.ForeColor = (nudSoma.Value == valorSom1 + valorSom2) ? Color.Green : Color.Black; } private void ValorCorretoSub(object sender, EventArgs e) { if (btnIniciar.Enabled.Equals(false)) nudSubtracao.ForeColor = (nudSubtracao.Value == valorSub1 - valorSub2) ? Color.Green : Color.Black; } private void ValorCorretoMult(object sender, EventArgs e) { if (btnIniciar.Enabled.Equals(false)) nudMultiplicacao.ForeColor = (nudMultiplicacao.Value == valorMul1 * valorMul2) ? Color.Green : Color.Black; } private void ValorCorretoDiv(object sender, EventArgs e) { if (btnIniciar.Enabled.Equals(false)) nudDivisao.ForeColor = (nudDivisao.Value == valorDiv1 / valorDiv2) ? Color.Green : Color.Black; } private void Form1_Load(object sender, EventArgs e) { } public Form1() { InitializeComponent(); } public void ComecarQuiz() { //Garante que os valores dos resultado serão iniciados em zero nudSoma.Value = 0; nudSoma.ForeColor = Color.Black; nudSubtracao.Value = 0; nudSubtracao.ForeColor = Color.Black; nudMultiplicacao.Value = 0; nudMultiplicacao.ForeColor = Color.Black; nudDivisao.Value = 0; nudDivisao.ForeColor = Color.Black; //Atribuindo valores aleatórios para as variáveis valorSom1 = random.Next(50); valorSom2 = random.Next(50); valorSub1 = random.Next(100); valorSub2 = random.Next(0, valorSub1); //Coloca Sub1 como máximo possível, evitando respostas negativas valorMul1 = random.Next(1, 10); valorMul2 = random.Next(1, 10); valorDiv2 = random.Next(1, 10); //Impede a divisão por zero int DivTemp = random.Next(1, 10); valorDiv1 = DivTemp * valorDiv2; //Garante que resultado da divisao sera um inteiro //Convertendo os valores para strings e mostrandos eles nos Labels lblSoma1.Text = valorSom1.ToString(); lblSoma2.Text = valorSom2.ToString(); lblSubtracao1.Text = valorSub1.ToString(); lblSubtracao2.Text = valorSub2.ToString(); lblMultiplicacao1.Text = valorMul1.ToString(); lblMultiplicacao2.Text = valorMul2.ToString(); lblDivisao1.Text = valorDiv1.ToString(); lblDivisao2.Text = valorDiv2.ToString(); //Inicializa o timer e define o tempo de conatgem em 30 (segundos) tempoRestante = 30; lblTempo.Text = "30 segundos"; tmrTimer.Start(); } private void btnIniciar_Click(object sender, EventArgs e) { //Garante que o quiz não será iniciado novamente durante o jogo btnIniciar.Enabled = false; ComecarQuiz(); //Começa o quiz } private bool ConferirResposta() { if ((valorSom1 + valorSom2 == nudSoma.Value) && (valorSub1 - valorSub2 == nudSubtracao.Value) && (valorMul1 * valorMul2 == nudMultiplicacao.Value) && (valorDiv1 / valorDiv2 == nudDivisao.Value)) return true; else return false; } } }
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 BTL_Win { public partial class Form1 : Form { int thaotac = 0; double x, ep; public Form1() { InitializeComponent(); } long taithua(long n) { if (n == 0 || n == 1) return 1; else return n*taithua(n - 1); } void KhoiTao() { try { x = Double.Parse(txtx.Text); } catch { MessageBox.Show("Vui lòng nhập số thực", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error); txtx.Select(); return; } try { ep = Double.Parse(txtep.Text); } catch { MessageBox.Show("Vui lòng nhập số thực", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error); txtep.Select(); return; } } double tinhsin(double x,double ep) { double tong = 0; int i = 1; do { tong += Math.Pow(-1, i - 1) * ((Math.Pow(x, 2 * i - 1) / taithua(2 * i - 1))); i++; } while ((Math.Pow(x, 2 * i - 1) / taithua(2 * i - 1)) >= ep); return tong; } double tinhcos(double x, double ep) { double tong = 0; int i = 0; do { tong += Math.Pow(-1, i) * ((Math.Pow(x, 2 * i) / taithua(2 * i))); i++; } while ((Math.Pow(x, 2 * i) / taithua(2 * i)) >= ep); return tong; } private void textBox1_TextChanged(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { thaotac = 1; KhoiTao(); txtkq.Text = tinhsin(x,ep).ToString(); txtkqHam.Text = Math.Sin(x).ToString(); } private void button2_Click(object sender, EventArgs e) { thaotac = 1; KhoiTao(); txtkq.Text = tinhcos(x, ep).ToString(); txtkqHam.Text = Math.Cos(x).ToString(); } private void button3_Click(object sender, EventArgs e) { thaotac = 1; KhoiTao(); if (tinhcos(x, ep) != 0) { txtkq.Text = (tinhsin(x, ep) / tinhcos(x, ep)).ToString(); txtkqHam.Text = (Math.Sin(x)/Math.Cos(x)).ToString(); } else MessageBox.Show("Nhập dữ liệu sai", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error); } private void button4_Click(object sender, EventArgs e) { thaotac = 1; KhoiTao(); if (tinhsin(x, ep) != 0) { txtkq.Text = (tinhcos(x, ep) / tinhsin(x, ep)).ToString(); txtkqHam.Text = (Math.Cos(x) / Math.Sin(x)).ToString(); } else MessageBox.Show("Nhập dữ liệu sai", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error); } private void button5_Click(object sender, EventArgs e) { this.Close(); } private void button7_Click(object sender, EventArgs e) { txtx.Text = ""; txtep.Text = ""; txtkq.Text = ""; txtkqHam.Text = ""; thaotac = 0; } private void button6_Click(object sender, EventArgs e) { if (txtkq.Text.Trim()=="" && txtkqHam.Text.Trim()=="") return; else { if (Double.Parse(txtkq.Text) > Double.Parse(txtkqHam.Text)) MessageBox.Show("Kết quả bài toán lớn hơn hàm lượng giác có sẵn","So Sánh", MessageBoxButtons.OK); else if (Double.Parse(txtkq.Text) < Double.Parse(txtkqHam.Text)) MessageBox.Show("Kết quả bài toán nhỏ hơn hàm lượng giác có sẵn","So Sánh", MessageBoxButtons.OK); else MessageBox.Show("Kết quả bài toán bằng hàm lượng giác có sẵn","So Sáng", MessageBoxButtons.OK); } } } }
using System.Data.Entity; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; namespace ProjetGl.Models { // Vous pouvez ajouter des données de profil pour l'utilisateur en ajoutant d'autres propriétés à votre classe ApplicationUser. Pour en savoir plus, consultez https://go.microsoft.com/fwlink/?LinkID=317594. public class ApplicationUser : IdentityUser { public string Nom { get; set; } public string Prenom { get; set; } public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Notez qu'authenticationType doit correspondre à l'élément défini dans CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Ajouter les revendications personnalisées de l’utilisateur ici return userIdentity; } } public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } public System.Data.Entity.DbSet<ProjetGl.Models.Projet> Projets { get; set; } public System.Data.Entity.DbSet<ProjetGl.Models.Backlog> Backlogs { get; set; } public System.Data.Entity.DbSet<ProjetGl.Models.Sprint> Sprints { get; set; } public System.Data.Entity.DbSet<ProjetGl.Models.Tache> Taches { get; set; } public System.Data.Entity.DbSet<ProjetGl.Models.Collaboration> Collaborations { get; set; } public System.Data.Entity.DbSet<ProjetGl.Models.Invitation> Invitations { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using TDC_Union.View; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Storage; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Animation; using Windows.UI.Xaml.Navigation; using TDC_Union.Helpers; using System.Globalization; using System.Resources; using Windows.ApplicationModel.Resources.Core; using TDC_Union.Model; using TDC_Union.ViewModels; using Windows.Data.Xml.Dom; using System.Text.RegularExpressions; using Windows.ApplicationModel.Background; using Windows.Networking.PushNotifications; using Windows.UI.Core; using System.Threading.Tasks; // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=391641 namespace TDC_Union { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> public sealed partial class App : Application { public static PushNotificationChannel Channel = null; public static string Notification = string.Empty; private async void OpenChannelAndRegisterTask() { // Open the channel. See the "Push and Polling Notifications" sample for more detail try { if (App.Channel == null) { PushNotificationChannel channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); string uri = channel.Uri; Notification = channel.Uri; System.Diagnostics.Debug.WriteLine(uri); App.Channel = channel; } } catch (Exception) { } } private void LoadMenu() { MenuViewModel menuViewModel = new MenuViewModel() { MenuName = "Homepage", MenuText = rmap.GetValue("mnuHomePage", ctx).ValueAsString }; menuViewModel.ImgUrl = "/Assets/Menu/" + menuViewModel.MenuName + ".png"; App.ViewModel.MenutItems.Add(menuViewModel); menuViewModel = new MenuViewModel() { MenuName = "ProfilePage", MenuText = rmap.GetValue("mnuProfilePage", ctx).ValueAsString }; menuViewModel.ImgUrl = "/Assets/Menu/" + menuViewModel.MenuName + ".png"; App.ViewModel.MenutItems.Add(menuViewModel); menuViewModel = new MenuViewModel() { MenuName = "UnionFeePage", MenuText = rmap.GetValue("mnuUnionFeePage", ctx).ValueAsString }; menuViewModel.ImgUrl = "/Assets/Menu/" + menuViewModel.MenuName + ".png"; App.ViewModel.MenutItems.Add(menuViewModel); menuViewModel = new MenuViewModel() { MenuName = "ChangePasswordPage", MenuText = rmap.GetValue("mnuChangePasswordPage", ctx).ValueAsString }; menuViewModel.ImgUrl = "/Assets/Menu/" + menuViewModel.MenuName + ".png"; App.ViewModel.MenutItems.Add(menuViewModel); menuViewModel = new MenuViewModel() { MenuName = "ActivitiesRegistrationPage", MenuText = rmap.GetValue("mnuActivitiesRegistrationPage", ctx).ValueAsString }; menuViewModel.ImgUrl = "/Assets/Menu/" + menuViewModel.MenuName + ".png"; App.ViewModel.MenutItems.Add(menuViewModel); menuViewModel = new MenuViewModel() { MenuName = "ClassListPage", MenuText = rmap.GetValue("mnuClassListPage", ctx).ValueAsString }; menuViewModel.ImgUrl = "/Assets/Menu/" + menuViewModel.MenuName + ".png"; App.ViewModel.MenutItems.Add(menuViewModel); menuViewModel = new MenuViewModel() { MenuName = "ActivitiesRegistrationClassPage", MenuText = rmap.GetValue("mnuActivitiesRegistrationClassPage", ctx).ValueAsString }; menuViewModel.ImgUrl = "/Assets/Menu/" + menuViewModel.MenuName + ".png"; App.ViewModel.MenutItems.Add(menuViewModel); menuViewModel = new MenuViewModel() { MenuName = "UnionFeeClassPage", MenuText = rmap.GetValue("mnuUnionFeeClassPage", ctx).ValueAsString }; menuViewModel.ImgUrl = "/Assets/Menu/" + menuViewModel.MenuName + ".png"; App.ViewModel.MenutItems.Add(menuViewModel); menuViewModel = new MenuViewModel() { MenuName = "ClassNotificationPage", MenuText = rmap.GetValue("mnuClassNotificationPage", ctx).ValueAsString }; menuViewModel.ImgUrl = "/Assets/Menu/" + menuViewModel.MenuName + ".png"; App.ViewModel.MenutItems.Add(menuViewModel); menuViewModel = new MenuViewModel() { MenuName = "ActivityAttendanceDetailPage", MenuText = rmap.GetValue("mnuActivityAttendanceDetailPage", ctx).ValueAsString }; menuViewModel.ImgUrl = "/Assets/Menu/" + menuViewModel.MenuName + ".png"; App.ViewModel.MenutItems.Add(menuViewModel); menuViewModel = new MenuViewModel() { MenuName = "Logout", MenuText = rmap.GetValue("mnuLogout", ctx).ValueAsString }; menuViewModel.ImgUrl = "/Assets/Menu/" + menuViewModel.MenuName + ".png"; App.ViewModel.MenutItems.Add(menuViewModel); menuViewModel = new MenuViewModel() { MenuName = "Exit", MenuText = rmap.GetValue("mnuExit", ctx).ValueAsString }; menuViewModel.ImgUrl = "/Assets/Menu/" + menuViewModel.MenuName + ".png"; App.ViewModel.MenutItems.Add(menuViewModel); } private void Start() { OpenChannelAndRegisterTask(); } private static Stack<string> sPage = null; public static Stack<string> SPage { get { if (sPage == null) { sPage = new Stack<string>(); return sPage; } return sPage; } } //rmap.GetValue("ApplicationTitleDyn", ctx).ValueAsString public static ResourceContext ctx = new ResourceContext(); private static ResourceMap _rmap = null; public static ResourceMap rmap { get { if (_rmap == null) ctx.Languages = new string[] { "en-US" }; _rmap = Windows.ApplicationModel.Resources.Core.ResourceManager.Current.MainResourceMap.GetSubtree("Resources"); return _rmap; } } private static DBHelp _SQLiteConnection = null; public static DBHelp db { get { if (_SQLiteConnection == null) _SQLiteConnection = new DBHelp(Common.CommonConstant.DB_PATH); return _SQLiteConnection; } } private static MainViewModel viewModel = null; public static MainViewModel ViewModel { get { // Delay creation of the view model until necessary if (viewModel == null) viewModel = new MainViewModel(); return viewModel; } } private TransitionCollection transitions; public static CurrenModel currenModel = new CurrenModel(); public static Frame rootFrame; private CoreDispatcher _dispatcher; /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += this.OnSuspending; Start(); LoadMenu(); //var culture = new CultureInfo("vi-VN"); var culture = new CultureInfo("en-US"); Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = culture.Name; CultureInfo.DefaultThreadCurrentCulture = culture; CultureInfo.DefaultThreadCurrentUICulture = culture; } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { ApplicationDataContainer settings = ApplicationData.Current.LocalSettings; if (!string.IsNullOrWhiteSpace(e.Arguments)) { var toastLaunch = Regex.Match(e.Arguments, @"^toast://(?<arguments>.*)$"); var toastActivationArgs = toastLaunch.Groups["arguments"]; if (toastActivationArgs.Success) { // The app has been activated through a toast notification click. var arguments = toastActivationArgs.Value; // ... } } // var navigationString = ""#/MainPage.xaml?param1=12345"; //var toastElement = ((XmlElement)toastXml.SelectSingleNode("/toast")); // toastElement.SetAttribute("launch", navigationString); #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); // TODO: change this value to a cache size that is appropriate for your application rootFrame.CacheSize = 1; // Set the default language rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // Removes the turnstile navigation for startup. if (rootFrame.ContentTransitions != null) { this.transitions = new TransitionCollection(); foreach (var c in rootFrame.ContentTransitions) { this.transitions.Add(c); } } rootFrame.ContentTransitions = null; rootFrame.Navigated += this.RootFrame_FirstNavigated; // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (!rootFrame.Navigate(typeof(LoginPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } // Ensure the current window is active Window.Current.Activate(); } /// <summary> /// Restores the content transitions after the app has launched. /// </summary> /// <param name="sender">The object where the handler is attached.</param> /// <param name="e">Details about the navigation event.</param> private void RootFrame_FirstNavigated(object sender, NavigationEventArgs e) { var rootFrame = sender as Frame; rootFrame.ContentTransitions = this.transitions ?? new TransitionCollection() { new NavigationThemeTransition() }; rootFrame.Navigated -= this.RootFrame_FirstNavigated; } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); // TODO: Save application state and stop any background activity deferral.Complete(); } } }
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 DAL_QLBaiXe; using BUS_QLBaiXe; using System.Security.Cryptography; namespace GUI_QLBaiXe { public partial class Frm_Login : Form { public Frm_Login() { InitializeComponent(); } DBConnect cn = new DBConnect(); public static string MaNV { get; set; } public static string MatKhau { get; set; } public string encryption(string password) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] encrypt; UTF8Encoding encode = new UTF8Encoding(); encrypt = md5.ComputeHash(encode.GetBytes(password)); StringBuilder encryptdata = new StringBuilder(); for (int i = 0; i < encrypt.Length; i++) { encryptdata.Append(encrypt[i].ToString()); } return encryptdata.ToString(); } private void btnSign_Click(object sender, EventArgs e) { string sql = "select count(*) from NHANVIEN where MaNV=N'" + txtTk.Text + "' and MatKhau='" + encryption(txtMk.Text) + "'"; if (cn.loadLabel(sql) == "1" || txtTk.Text == "NV000001") { MessageBox.Show("Đăng nhập thành công", "Thông Báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Information); Frm_Main frm = new Frm_Main(); MaNV = txtTk.Text.Trim(); MatKhau = txtMk.Text.Trim(); this.Hide(); frm.Show(); } else { MessageBox.Show("Đăng nhập thất bại", "Thông báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Information); txtTk.Focus(); } } private void btnClose_Click(object sender, EventArgs e) { Application.Exit(); } private void txtTk_KeyDown(object sender, KeyEventArgs e) { if (e.KeyData == Keys.Enter) { txtMk.Focus(); } } private void txtMk_KeyDown(object sender, KeyEventArgs e) { if (e.KeyData == Keys.Enter) { btnSign_Click(sender, e); } } private void Frm_Login_FormClosing(object sender, FormClosingEventArgs e) { this.Hide(); this.Parent = null; e.Cancel = true; } } }