/// <summary> /// /// </summary> /// <param name="file"></param> /// <param name="path"></param> /// <returns></returns> public async Task <FileModel> SaveFromUploaderAsync(HttpPostedFileBase file, string path = null) { // Check if (file == null) { return(null); } // Process var extension = Path.GetExtension(file.FileName); var id = SequentialGuidGenerator.NewSequentialGuid(); var name = id + extension; var webpath = path != null?System.Web.HttpContext.Current.Server.MapPath(FileConst.UploadPath.PlusWord(path)) : System.Web.HttpContext.Current.Server.MapPath(FileConst.UploadPath); var web = await ConvertToByteArrayAsync(file); // var waterMarked = ImageManager.AddWaterMark(thumb, "Arezoo"); var result = await CreateFileAsync(web, name, webpath); var thumbPath = path != null?System.Web.HttpContext.Current.Server.MapPath(FileConst.ThumbPath.PlusWord(path)) : System.Web.HttpContext.Current.Server.MapPath(FileConst.ThumbPath); var thumbFile = await ConvertToByteArrayAsync(file); var resized = thumbFile.ResizeImageFile(100, 100); var thumbResult = await CreateFileAsync(resized, name, thumbPath); // Result return(thumbResult != null ? thumbResult : null); }
/// <summary> /// </summary> /// <param name="files"></param> /// <param name="path"> </param> /// <returns></returns> public async Task <IList <FileModel> > SaveAsync(IEnumerable <HttpPostedFileBase> files, string path = null) { var fileList = new List <FileModel>(); if (files == null) { return(fileList); } foreach (var file in files) { if (path == null) { path = FileConst.ImagesWebPath; } var extension = Path.GetExtension(file.FileName); var size = 0; var name = SequentialGuidGenerator.NewSequentialGuid() + extension; var pathToSave = Path.Combine(path, name); file.SaveAs(pathToSave); var fileSaved = new FileModel() { Id = SequentialGuidGenerator.NewSequentialGuid(), Name = name, Type = FileConst.FileType, Extension = extension, Size = size, Path = path }; fileList.Add(fileSaved); } return(fileList); }
private static void Seed(SwashbuckleODataContext context) { var clientOne = new Client { Id = 1, Name = "ClientOne" }; context.Clients.Add(clientOne); context.Clients.Add(new Client { Id = 2, Name = "ClientTwo" }); context.Projects.Add(new Project { ProjectId = 1, ProjectName = "ProjectOne", Client = clientOne }); context.Projects.Add(new Project { ProjectId = 2, ProjectName = "ProjectTwo", Client = clientOne }); var customerOne = new Customer { Id = 1, Name = "CustomerOne" }; context.Customers.Add(customerOne); context.Customers.Add(new Customer { Id = 2, Name = "CustomerTwo" }); context.Orders.Add(new Order { OrderId = SequentialGuidGenerator.Generate(SequentialGuidType.SequentialAtEnd), OrderName = "OrderOne", Customer = customerOne, UnitPrice = 4.0 }); context.Orders.Add(new Order { OrderId = SequentialGuidGenerator.Generate(SequentialGuidType.SequentialAtEnd), OrderName = "OrderTwo", Customer = customerOne, UnitPrice = 3.5 }); }
public Group() { GroupRoles = new List <GroupRole>(); GroupChangeLogs = new List <GroupChangeLog>(); Users = new List <User>(); Id = SequentialGuidGenerator.NewSequentialGuid(); }
public void AdicionarMenuRaiz(string titulo, int ordem) { var id = SequentialGuidGenerator.Generate(); var menu = new Menu(id, titulo, null, ordem, null); AdicionarMenu(menu, TipoMenu.Raiz); }
public void CriarContrato(ContratoVM model) { model.Id = SequentialGuidGenerator.Generate(); if (model.ServicoContratos != null) { foreach (var servicocontratoVM in model.ServicoContratos) { servicocontratoVM.Id = SequentialGuidGenerator.Generate(); servicocontratoVM.ContratoId = model.Id; } } if (model.DocumentoContratos != null) { foreach (var documentocontratoVM in model.DocumentoContratos) { //documentocontratoVM.Id = SequentialGuidGenerator.Generate(); documentocontratoVM.ContratoId = model.Id; } } var contrato = Map <Contrato>(model); cadastroContratoServices.CriarContrato(contrato); SaveChanges(); }
public void Guids_Generated_In_Sequence_Should_Be_Sequential() { var sut = new SequentialGuidGenerator(); var guid1 = sut.GetNextId(); var guid2 = sut.GetNextId(); (guid1 < guid2).Should().BeTrue(); }
public static void ClassCleanup() { if (gen != null) { gen.Dispose(); gen = null; } }
public T Add(T entity) { if (entity.Id == Guid.Empty) { entity.Id = SequentialGuidGenerator.NewSequentialId(); } return(_table.Add(entity)); }
public override object ToDbValue(Type fieldType, object value) { if (value is Guid && value.Equals(Guid.Empty)) { var newGuid = SequentialGuidGenerator.NewSequentialGuid(SequentialGuidType.SequentialAtEnd); return(newGuid); } return(base.ToDbValue(fieldType, value)); }
public Menu GerarFilho(string titulo, string url, int ordem) { var id = SequentialGuidGenerator.Generate(); var menuFilho = new Menu(id, titulo, url, ordem, Id); menuFilho.AtribuirPai(this); MontarCaminhoDeAcesso(menuFilho, this); return(menuFilho); }
/// <summary> /// Called when [before insert]. /// </summary> /// <param name="entry">The entry.</param> /// <param name="item">The item.</param> /// <param name="context">The context.</param> protected override void OnBeforeInsert(DbEntityEntry entry, Entity item, InterceptionContext context) { if (item.IsNew) { item.Id = SequentialGuidGenerator.Generate(); } base.OnBeforeInsert(entry, item, context); }
public RelationalJobStorage( TContext context, SequentialGuidGenerator <TContext> guid, IResettableSignal <JobHostedService> signal, IJobFileProvider fileProvider) { _dbContext = context; _guid = guid; _fileProvider = fileProvider; _signal = signal; }
//public string BuscarPorStatus(string status) //{ // var TiposServicos = contratosCQRS.BuscarTiposServicos(); // var models = Mapper.Map<IEnumerable<TipoServicoVM>>(TiposServicos); // return models; //} public void ConfigurarDocoumentoContratoNomeArquivo(ref DocumentoContratoVM model) { if (model != null) { if (model.Id == Guid.Empty) { Guid DocumentoGuid = SequentialGuidGenerator.Generate(); model.Id = DocumentoGuid; model.NomeArquivo = DocumentoGuid.ToString(); } } }
public async Task <IHttpActionResult> Post(Order order) { order.OrderId = SequentialGuidGenerator.Generate(SequentialGuidType.SequentialAtEnd); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } _db.Orders.Add(order); await _db.SaveChangesAsync(); return(Created(order)); }
/// <summary> /// Transforms a <see cref="ServiceContract.Models.SystemLog" /> model into a <see cref="SystemLog" /> domain model. /// </summary> /// <param name="response">The response to transform.</param> /// <param name="storageType">The storage mechanism currently in use - helps generate the correct resource id</param> /// <returns>The resultant domain model.</returns> public static SystemLog FromSystemLogResponse(ServiceContract.Models.SystemLog response, Storage storageType) { var systemLog = new SystemLog { ResourceId = SequentialGuidGenerator.Generate(storageType), Message = response.Message, Source = response.Source, StackTrace = response.StackTrace, Level = response.Level, Data = JsonConvert.SerializeObject(response.Data) }; return(systemLog); }
public void TestMethod1() { SequentialGuidGenerator generatror = SequentialGuidGenerator.Instance; int i = 0; Random rand = new Random(new Guid().GetHashCode()); while (i < 10) { var r = rand.Next(3); Console.WriteLine(r); Console.WriteLine(generatror.NewSequentialGuid()); Thread.Sleep(r); i++; } }
public void AtualizaContrato(ContratoVM model) { if (model.ServicoContratos != null) { foreach (var servicocontratoVM in model.ServicoContratos) { if (servicocontratoVM.Id == Guid.Empty) { servicocontratoVM.Id = SequentialGuidGenerator.Generate(); cadastroContratoServices .CadastrarServicoNoContrato( servicocontratoVM.Id, model.Id, servicocontratoVM.TipoServicoId, servicocontratoVM.FormaPagamentoId, servicocontratoVM.Valor, servicocontratoVM.Observacao); } } } if (model.DocumentoContratos != null) { foreach (var documentocontratoVM in model.DocumentoContratos) { //if (documentocontratoVM.Id == Guid.Empty) //{ //Guid DocumentoGuid = SequentialGuidGenerator.Generate(); //documentocontratoVM.Id = DocumentoGuid; //documentocontratoVM.NomeArquivo = DocumentoGuid.ToString(); cadastroContratoServices .CadastrarDocumentoNoContrato( documentocontratoVM.Id, model.Id, documentocontratoVM.NomeArquivo, documentocontratoVM.NomeOriginal); //} //documentocontratoVM.Id = SequentialGuidGenerator.Generate(); //documentocontratoVM.ContratoId = model.Id; } } var contrato = Map <Contrato>(model); cadastroContratoServices.AtualizaContrato(contrato); SaveChanges(); }
private void UpdateAuditFields(Guid auditUserId) { var auditUserIp = HttpContext.Current.Request.GetIp(); var auditUserAgent = HttpContext.Current.Request.GetBrowser(); var auditDate = DateTime.Now; foreach (var entry in this.ChangeTracker.Entries <BaseEntity>()) { // Note: You must add a reference to assembly : System.Data.Entity switch (entry.State) { case EntityState.Added: entry.Entity.Id = SequentialGuidGenerator.NewSequentialGuid(); entry.Entity.CreatedOn = auditDate; entry.Entity.CreatedById = auditUserId; entry.Entity.ModifiedOn = auditDate; entry.Entity.Action = AuditAction.Create; entry.Entity.ModifiedById = auditUserId; entry.Entity.CreatorIp = auditUserIp; entry.Entity.ModifierIp = auditUserIp; entry.Entity.CreatorAgent = auditUserAgent; entry.Entity.ModifierAgent = auditUserAgent; entry.Entity.Version = 1; break; case EntityState.Modified: entry.Entity.ModifiedOn = auditDate; entry.Entity.ModifiedById = auditUserId; entry.Entity.ModifierIp = auditUserIp; entry.Entity.ModifierAgent = auditUserAgent; entry.Entity.Version = ++entry.Entity.Version; entry.Entity.Action = entry.Entity.IsDeleted ? AuditAction.SoftDelete : AuditAction.Update; break; case EntityState.Detached: break; case EntityState.Unchanged: break; case EntityState.Deleted: break; default: throw new ArgumentOutOfRangeException(); } } }
static void Main(string[] args) { string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss"); string InputDirectory = @"My Documents\\2015"; string FileMask = "comb*.txt"; try { string line = null; var Files = Directory.GetFiles(InputDirectory, FileMask, SearchOption.AllDirectories).Select(f => Path.GetFullPath(f)); foreach (var f in Files) { DataTable table = new DataTable(); table.TableName = f; table.Columns.Add("ID", typeof(Int64)); table.Columns.Add("dob", typeof(string)); table.Columns.Add("size", typeof(string)); table.Columns.Add("accountno", typeof(string)); using (StreamReader reader = new StreamReader(f)) { while ((line = reader.ReadLine()) != null) { string[] values = line.Split(',').Select(sValue => sValue.Trim()).ToArray(); string uniqueGuid = SequentialGuidGenerator.NewGuid().ToString(); uniqueGuid = uniqueGuid.Replace("-", ""); int ID = convert.toint(values[0]); string NOTIF_ID = ""; table.Rows.Add(ID,values[1].ToString(),values[2]).toString(),values[2]).toString()); } reader.Close(); } utilityClass.Insert_Entry(table, env); } } catch (Exception e) { CustomException.Write(CustomException.CreateExceptionString(e)); } }
/// <summary> /// /// </summary> /// <param name="entry"></param> private static void UpdateFieldsForAdded(DbEntityEntry <BaseEntity> entry) { //var auditUserIp = HttpContext.Current.Request.GetIp(); //var auditUserAgent = HttpContext.Current.Request.GetBrowser(); var auditDate = DateTime.Now; if (entry.Entity.Id == Guid.Empty) { entry.Entity.Id = SequentialGuidGenerator.NewSequentialGuid(); } // entry.Entity.CreatedOn = auditDate; // entry.Entity.ModifiedOn = auditDate; //entry.Entity.Audit = AuditType.Create; //entry.Entity.CreatorIp = auditUserIp; //entry.Entity.ModifierIp = auditUserIp; //entry.Entity.CreatorAgent = auditUserAgent; //entry.Entity.ModifierAgent = auditUserAgent; //entry.Entity.Version = 1; }
public async Task <IList <FileModel> > SaveAttachmentAsync(IEnumerable <HttpPostedFileBase> files, string path = null) { var fileList = new List <FileModel>(); if (files == null) { return(fileList); } foreach (var file in files) { var validationFormat = await _attachmentManager.AttachmentValidator.GetFormatAsync(file); var validationSize = await _attachmentManager.AttachmentValidator.GetSizeAsync(file); if (validationFormat != null) { throw new ArgumentNullException(nameof(validationFormat)); } if (validationSize != null) { throw new ArgumentNullException(nameof(validationSize)); } if (path == null) { path = FileConst.AttachmentPath; } var fileSaved = new FileModel { Id = SequentialGuidGenerator.NewSequentialGuid(), Name = SequentialGuidGenerator.NewSequentialGuid() + Path.GetExtension(file.FileName), Type = FileConst.FileType, Extension = Path.GetExtension(file.FileName), Size = file.ContentLength, Path = path }; var byteFile = await ConvertToByteArrayAsync(file); await CreateFileAsync(byteFile, fileSaved.Name, path); fileList.Add(fileSaved); } return(fileList); }
public ActionResult EnviarMailRecuperarPassword(ForgotPasswordViewModel model) { var email = model.Email; if (string.IsNullOrWhiteSpace(email)) { ViewBag.Error = "Por favor complete el email"; return(View("ForgotPassword", model)); } ApplicationDbContext db = new ApplicationDbContext(); UserManager <ApplicationUser> um = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ApplicationDbContext())); var user = um.FindByEmail(email); if (user != null) { try { user.Token = SequentialGuidGenerator.NewSequentialGuid(SequentialGuidType.SequentialAtEnd); user.TokenFechaVencimiento = DateTime.Now.AddDays(1); um.Update(user); dynamic em = new Email("EnviarMailRecuperarPassWord"); em.To = email; em.Nombre = user.Name; em.Link = WebConfigurationManager.AppSettings["Core"] + WebConfigurationManager.AppSettings["RecuperarPasswordLink"].Replace("[[token]]", user.Token.ToString()).Replace("[[usuarioId]]", user.Id.ToString()).Replace("&", "&"); em.Send(); } catch (Exception ex) { ViewBag.Error = "Hubo un error al enviar el email"; return(View("ForgotPassword", model)); } } else { ViewBag.Error = "El mail no se corresponde con ningun usuario"; return(View("ForgotPassword", model)); } ViewBag.Success = true; return(View("ForgotPassword", model)); }
private async Task Setup() { var rootOperationScopeProvider = new OperationScopeProvider(); //_busBroker = new InProcAsyncBusBroker(LoggerFactory.CreateLogger("QX.Zoo.InProcAsyncBus"), rootOperationScopeProvider); _busBroker = new RabbitMQBroker(Configuration.GetValue <RabbitMQConfiguration>("rabbitmq"), rootOperationScopeProvider, LoggerFactory.CreateLogger("QX.Zoo.InProcAsyncBus")); var factoryId = SequentialGuidGenerator.GetOrCreateGenerator <Citizen>().NewGuid(); var maxVersionNumber = StaticCitizensWarehouse.Version; var warehouse = new WarehouseActor <Citizen>(StaticCitizensWarehouse.ExternalLoader, LoggerFactory.CreateLogger("QX.Zoo.Warehouse")); _instance1 = new AccumulatingFactory <Citizen>(factoryId, 1, maxVersionNumber, b => b.GetEntity("exchange/zoo"), x => LoggerFactory.CreateLogger(x?.ToString())); _instance2 = new AccumulatingFactory <Citizen>(factoryId, 2, maxVersionNumber, b => b.GetEntity("exchange/zoo"), x => LoggerFactory.CreateLogger(x?.ToString())); _instance3 = new AccumulatingFactory <Citizen>(factoryId, 3, maxVersionNumber, b => b.GetEntity("exchange/zoo"), x => LoggerFactory.CreateLogger(x?.ToString())); await _instance1.StartAsync(_busBroker); await _instance2.StartAsync(_busBroker); await _instance3.StartAsync(_busBroker); }
public void MainTest() { Trace.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffffff")); SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0); for (int i = 0; i < 1000; i++) { Trace.WriteLine(string.Format("{0} {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffffff"), idWorker.NextId())); } Trace.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffffff")); //SequentialGuidGenerator,效率低于SnowflakeIdWorker for (int i = 0; i < 1000; i++) { var id = SequentialGuidGenerator.NewSequentialGuid(SequentialGuidType.SequentialAsString); Trace.WriteLine(string.Format("{0} {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffffff"), id)); } Trace.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffffff")); }
public static void SetAuditableEntiTypeopertyValues( this ChangeTracker changeTracker, IHttpContextAccessor httpContextAccessor, Guid?ionicUserId = null) { var httpContext = httpContextAccessor?.HttpContext; var userAgent = httpContext?.Request?.Headers["User-Agent"].ToString(); var userIp = httpContext?.Connection?.RemoteIpAddress?.ToString(); if (string.IsNullOrEmpty(userIp)) { userIp = "::1"; } var now = DateTimeOffset.UtcNow.IranStandardTimeNow(); var userId = ionicUserId ?? GetUserId(httpContext); var modifiedEntries = changeTracker.Entries() .Where(x => x.State == EntityState.Modified); foreach (var modifiedEntry in modifiedEntries) { SetEntityEntryValue <DateTimeOffset?>(modifiedEntry, ModifiedDateTimeOn, now); SetEntityEntryValue <string>(modifiedEntry, ModifiedByIp, userIp); SetEntityEntryValue <Guid?>(modifiedEntry, ModifiedByUserId, userId); } var addedEntries = changeTracker.Entries() .Where(x => x.State == EntityState.Added); foreach (var addedEntry in addedEntries) { SetEntityEntryValue <DateTimeOffset?>(addedEntry, CreatedDateTimeOn, now); SetEntityEntryValue <string>(addedEntry, CreatedByIp, userIp); SetEntityEntryValue <string>(addedEntry, CreatorIp, userIp); SetEntityEntryValue <string>(addedEntry, CreatorIdentityIp, userIp); SetEntityEntryValue <Guid?>(addedEntry, CreatedByUserId, userId); SetEntityEntryValue <Guid?>(addedEntry, CreatorIdentityId, userId); SetEntityEntryValue <Guid?>(addedEntry, CreatorId, userId); SetEntityEntryValue <Guid>(addedEntry, Id, SequentialGuidGenerator.NewSequentialGuid()); } }
public ActionResult RecuperarPassword(string usuarioid = null, Guid?token = null) { if (User.Identity.IsAuthenticated && usuarioid == null && token == null) { var user = UserManager.FindById(User.Identity.GetUserId()); user.Token = SequentialGuidGenerator.NewSequentialGuid(SequentialGuidType.SequentialAtEnd); user.TokenFechaVencimiento = DateTime.Now.AddDays(5); UserManager.Update(user); var model = new RecuperarPasswordViewModel(); model.Token = user.Token; model.UsuarioId = user.Id; return(View(model)); } else { var model = new RecuperarPasswordViewModel(); model.Token = token.Value; model.UsuarioId = usuarioid; return(View(model)); } }
public StatelessServiceFabricHost(StatelessServiceContext serviceContext) : base(serviceContext) { _serviceContext = serviceContext; _loggerFactory = new LoggerFactory().AddConsole(); _log = _loggerFactory.CreateLogger("StatelessService"); _log.LogTrace("StatelessServiceFabricHost .ctor"); _config = serviceContext.CodePackageActivationContext.GetConfigurationPackageObject("Config").Settings; if (_config == null) { throw new ArgumentException("Configuration package 'Config' not found"); } var rmqConfig = _config.Sections["RabbitMQ"]; if (rmqConfig == null) { throw new ArgumentException("Configuration section 'RabbitMQ' not found"); } var rabbitConfig = new RabbitMQConfiguration { HostNames = rmqConfig.Parameters["hostnames"]?.Value?.Split(';').ToList(), UserName = rmqConfig.Parameters["userName"]?.Value, Password = rmqConfig.Parameters["password"]?.Value, Port = int.Parse(rmqConfig.Parameters["port"]?.Value ?? "5672") }; _asyncBusBroker = new RabbitMQBroker(rabbitConfig, new OperationScopeProvider(), _loggerFactory.CreateLogger("RabbitMQ")); //var warehouse = new WarehouseActor<Citizen>(StaticCitizensWarehouse.ExternalLoader, _loggerFactory.CreateLogger("Warehouse")); _instance = new AccumulatingFactory <Citizen>( SequentialGuidGenerator.GetOrCreateGenerator <Citizen>().NewGuid(), 1, StaticCitizensWarehouse.Version, b => b.GetEntity("exchange/zoo"), x => _loggerFactory.CreateLogger(x?.ToString())); }
/// <summary> /// Transforms a <see cref="ServiceContract.Models.TaskInfo" /> model into a <see cref="TaskInfo" /> domain model. /// </summary> /// <param name="response">The response to transform.</param> /// <param name="storageType">The storage mechanism currently in use - helps generate the correct resource id</param> /// <returns>The resultant domain model.</returns> public static TaskInfo FromTaskInfoResponse(ServiceContract.Models.TaskInfo response, Storage storageType) { var taskInfo = new TaskInfo { ResourceId = response.Id.IsDefault() ? SequentialGuidGenerator.Generate(storageType) : response.Id, AssemblyName = response.AssemblyName, TypeName = response.TypeName, MethodName = response.MethodName, ReturnType = response.ReturnType.FullName, Status = response.Status, FailureDetails = response.FailureDetails, Tags = response.Tags.IsDefault() ? default : string.Join(",", response.Tags) }; // Why don't we do this in the object initializer? // Because the dates haven't been populated, until the TaskInfo has been created! response.DateCreated = taskInfo.DateCreated; response.DateLastUpdated = taskInfo.DateLastUpdated; taskInfo.Data = TaskInfoSerialization.Serialize(response); return(taskInfo); } }
public JsonResult EnviarMailRecuperarPassWord() { string mail = System.Web.HttpContext.Current.Request.Form["mail"]; // string mail = Request.QueryString["mail"].ToString(); UserManager <ApplicationUser> um = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ApplicationDbContext())); var user = um.FindByEmail(mail); //var repositorio = new Repositorio<Supervisor>(db); //var user = repositorio.TraerTodos().SingleOrDefault(a => a.Usuario.UserName == mail); if (user != null) { ViewBag.To = mail; ViewBag.Subject = "Recuperar Usuario"; string link = WebConfigurationManager.AppSettings["Core"] + WebConfigurationManager.AppSettings["RecuperarPasswordLink"]; var newToken = SequentialGuidGenerator.NewSequentialGuid(SequentialGuidType.SequentialAtEnd); user.TokenFechaVencimiento = DateTime.Today.AddDays(7); user.Token = newToken; um.Update(user); try { dynamic email = new Email("EnviarMailRecuperarPassWord"); email.Link = link.Replace("[[token]]", newToken.ToString().ToUpper()).Replace("[[usuarioId]]", user.Id); email.Subject = "Recuperar Usuario"; email.To = mail; email.Send(); } catch (Exception ex) { return(Json("Error: no se ha podido enviar el mail con los pasos a seguir. Intente más tarde.", JsonRequestBehavior.AllowGet)); } return(Json("Se ha enviado un email a su casilla de email con los pasos a seguir", JsonRequestBehavior.AllowGet)); } return(null); }