public void Load(string extraDataKey) { _dynamicExpressionQuery = ObjectFactory.GetInstance<IDynamicExpressionQuery>(); _repository = ObjectFactory.GetNamedInstance<IRepository>("NoFiltersOrInterceptor"); _securityDataService = ObjectFactory.GetInstance<ISecurityDataService>(); _repository.Initialize(); createUser(); _repository.Commit(); }
private static void SetUpSimpleDiffContext(IRepository repo) { var fullpath = Touch(repo.Info.WorkingDirectory, "file.txt", "hello\n"); repo.Index.Stage(fullpath); repo.Commit("Initial commit", Constants.Signature, Constants.Signature); File.AppendAllText(fullpath, "world\n"); repo.Index.Stage(fullpath); File.AppendAllText(fullpath, "!!!\n"); }
public void SaveForm(string keyValue, App_ProjectEntity entity, List <App_TemplatesEntity> entryList) { IRepository db = this.BaseRepository().BeginTrans(); try { if (!string.IsNullOrEmpty(keyValue)) { //主表 //entity.Modify(keyValue); //entity.F_Templates = null; //明细 db.ExecuteBySql("delete from App_Templates where F_ProjectId='" + keyValue + "'"); db.ExecuteBySql("update [App_Project] set F_Name='" + entity.F_Name + "',F_Icon='" + entity.F_Icon + "',F_IsTabed=" + entity.F_IsTabed + ",F_Description='" + entity.F_Description + "' where F_Id='" + keyValue + "'"); foreach (App_TemplatesEntity item in entryList) { item.Create(); item.F_ProjectId = keyValue; //db.Insert(item); db.ExecuteBySql("insert into App_Templates([F_Id],[F_ProjectId],[F_Name],[F_Value],[F_Type],[F_Parent],[F_level],[F_img],[F_Content],[F_CreateDate],[F_CreateUserId],[F_CreateUserName]) values('" + item.F_Id + "','" + item.F_ProjectId + "','" + item.F_Name + "','" + item.F_Value + "','" + item.F_Type + "','" + item.F_Parent + "'," + item.F_level + ",'" + item.F_img + "','" + item.F_Content + "','" + item.F_CreateDate + "','" + item.F_CreateUserId + "','" + item.F_CreateUserName + "')"); } } else { //主表 entity.Create(); entity.F_Templates = null; db.Insert(entity); //明细 foreach (App_TemplatesEntity item in entryList) { item.Create(); item.F_ProjectId = entity.F_Id; db.ExecuteBySql("insert into App_Templates([F_Id],[F_ProjectId],[F_Name],[F_Value],[F_Type],[F_Parent],[F_level],[F_img],[F_Content],[F_CreateDate],[F_CreateUserId],[F_CreateUserName]) values('" + item.F_Id + "','" + item.F_ProjectId + "','" + item.F_Name + "','" + item.F_Value + "','" + item.F_Type + "','" + item.F_Parent + "'," + item.F_level + ",'" + item.F_img + "','" + item.F_Content + "','" + item.F_CreateDate + "','" + item.F_CreateUserId + "','" + item.F_CreateUserName + "')"); } } db.Commit(); } catch (Exception) { db.Rollback(); throw; } }
public CommandContracts.Common.CommandResult Handle(InsertarActualizarVehiculoInspeccionCommand command) { if (command == null) { throw new ArgumentException("Tiene que ingresar una etapa"); } VehiculoInspeccion dominio = null; if (command.idvehiculoinspeccion.HasValue) { dominio = _VehiculoInspeccionRepository.Get(x => x.idvehiculoinspeccion == command.idvehiculoinspeccion).LastOrDefault(); } else { dominio = new VehiculoInspeccion(); } dominio.checkeado = command.checkeado; dominio.idinspeccion = command.idinspeccion; dominio.idvehiculo = command.idvehiculo; try { if (!command.idvehiculoinspeccion.HasValue) { _VehiculoInspeccionRepository.Add(dominio); } _VehiculoInspeccionRepository.Commit(); return(new InsertarActualizarVehiculoOutput() { idvehiculo = dominio.idvehiculoinspeccion }); } catch (Exception ex) { // _ValortablaRepository.Delete(dominio); //_ValortablaRepository.Commit(); throw; } }
public CommandContracts.Common.CommandResult Handle(InsertarActualizarDetalleValijaCommand command) { if (command == null) { throw new ArgumentException("Tiene que ingresar una cliente"); } DetalleValija dominio = null; if (command.iddespachovalija.HasValue) { dominio = _DetalleValijaRepository.Get(x => x.iddespachovalija == command.iddespachovalija).LastOrDefault(); } else { dominio = new DetalleValija(); } dominio.iddespacho = command.iddespacho; dominio.idordentransporte = command.idordentransporte; try { if (!command.iddespachovalija.HasValue) { _DetalleValijaRepository.Add(dominio); } _DetalleValijaRepository.Commit(); return(new InsertarActualizarDetalleValijaOutput() { iddespachovalija = dominio.iddespachovalija }); } catch (Exception ex) { // _ValortablaRepository.Delete(dominio); //_ValortablaRepository.Commit(); throw; } }
public UserDTO Register(UserRegisterDTO user) { try { var newUser = _mapper.Map <User>(user); newUser.Password = HashPassword(newUser.Password); _userRepository.Insert(newUser); _userRepository.Commit(); var userDto = _mapper.Map <UserDTO>(newUser); return(userDto); } catch (Exception) { throw; } }
/// <summary> /// 删除工作流实例进程(删除草稿使用) /// </summary> /// <param name="keyValue">主键</param> /// <returns></returns> public int DeleteProcess(string keyValue) { IRepository db = this.BaseRepository().BeginTrans(); try { WFProcessInstanceEntity entity = this.BaseRepository().FindEntity <WFProcessInstanceEntity>(keyValue); db.Delete <WFProcessSchemeEntity>(entity.ProcessSchemeId); db.Delete <WFProcessInstanceEntity>(keyValue); db.Commit(); return(1); } catch { db.Rollback(); throw; } }
public async Task <bool> CreateUser(UserCreation userCreation) { var exists = await _repo.Get <User>(x => x.Username.ToLower() == userCreation.Username.ToLower()).FirstOrDefaultAsync(); if (exists != null) { return(false); } var password = _passwordService.GeneratePassword(userCreation.Password); _repo.Add <User>(new User { Username = userCreation.Username.ToLower(), Password = password }); await _repo.Commit(); return(true); }
public static DateTime Commit(this IRepository repository, string path, string comment, IEnumerable <LogPropertyInfo> properties, Authentication authentication, string eventLog) { var props = new List <LogPropertyInfo> { new LogPropertyInfo() { Key = LogPropertyInfo.EventLogKey, Value = eventLog, }, new LogPropertyInfo() { Key = LogPropertyInfo.UserIDKey, Value = authentication.ID, } }; props.AddRange(properties ?? Enumerable.Empty <LogPropertyInfo>()); return(repository.Commit(path, comment, props)); }
public void Setup() { var repositoryFactory = new MockRepositoryFactory(); _logController = LogController(repositoryFactory); _repository = repositoryFactory.Create(); _repository.Add(new Log { Message = "First message" }); _repository.Add(new Log { Message = "Second message" }); _repository.Add(new Log { Message = "Third message" }); _repository.Commit(); }
public void DeletePerformer(int id) { CheckPerformerNullValue(id); IList <Performance> performances = _performanceContext.Collection() .Where(p => p.PerformerId == id).ToList(); // performer.IsActive = false; foreach (var performance in performances) { _performanceContext.Delete(performance.Id); _performanceContext.Commit(); } _context.Delete(id); _context.Commit(); }
public void CreateOrder(Order baseOrder, List <ShoppingCartItemViewModel> shoppingCartItems) { //iterate through our basket item and then add it to the baseOrder foreach (var item in shoppingCartItems) { baseOrder.OrderItems.Add(new OrderItem() { ProductId = item.Id, image = item.Image, Price = item.Price, ProductName = item.ProductName, Quantity = item.Quantity }); } //Insert our base order and the save the changes orderContext.Insert(baseOrder); orderContext.Commit(); }
private CommandResult CreateRole(string data) { var existingRole = repository.Read(x => x.Name.Equals(data)).FirstOrDefault(); if (existingRole != null) { return(new CommandResult($"Error: Unable to create role, \"{data}\" already exists.")); } repository.Create(new UserRole(data)); repository.Commit(); return(new CommandResult($"Role \"{data}\" created successfully!")); }
public object AddAttachment(IRepository <Attachment> attachmentContext, string data, HttpPostedFileBase file) { { var attachment = JsonConvert.DeserializeObject <Attachment>(data); string fileLocation = attachment.Location; System.IO.Directory.CreateDirectory(fileLocation); if (file != null && file.ContentLength > 0) { try { string fileName = Path.GetFileName(file.FileName); fileName = Helpers.AppUtils.getNextFileName(fileLocation, fileName); if (fileName != "") { file.SaveAs(Path.Combine(fileLocation, fileName)); attachmentContext.Insert(attachment); attachmentContext.Commit(); // send response object return(new { Successful = true, Message = "Attachment added.", AttachmentId = attachment.Id }); } else { // log error; Console.WriteLine("Invalid file name or location."); return(new { Successful = false, Message = "Attachment failed to add." }); } } catch (Exception ex) { // log error; Console.WriteLine(ex); // send response object error return(new { Successful = false, Message = "Attachment failed to add." }); } } else { return(new { Successful = false, Message = "Attachment was not received by server." }); } } }
public CommandContracts.Common.CommandResult Handle(InsertarActualizarProveedorClienteCommand command) { if (command == null) { throw new ArgumentException("Tiene que ingresar una cliente"); } ProveedorCliente dominio = null; if (command.idproveedorcliente.HasValue) { dominio = _ProveedorClienteRepository.Get(x => x.idproveedorcliente == command.idproveedorcliente).LastOrDefault(); } else { dominio = new ProveedorCliente(); } dominio.idcliente = command.idcliente; dominio.idproveedor = command.idproveedor; try { if (!command.idproveedorcliente.HasValue) { _ProveedorClienteRepository.Add(dominio); } _ProveedorClienteRepository.Commit(); return(new InsertarActualizarClienteOutput() { idcliente = dominio.idcliente }); } catch (Exception ex) { // _ValortablaRepository.Delete(dominio); //_ValortablaRepository.Commit(); throw; } }
public CommandContracts.Common.CommandResult Handle(InsertarActualizarPrecintoCommand command) { if (command == null) { throw new ArgumentException("Tiene que ingresar una Chofer"); } Precinto dominio = null; if (command.idprecinto.HasValue) { dominio = _PrecintoRepository.Get(x => x.idprecinto == command.idprecinto).LastOrDefault(); } else { dominio = new Precinto(); } //dominio.iddireccion = command.iddireccion; dominio.precinto = command.precinto; try { if (!command.idprecinto.HasValue) { _PrecintoRepository.Add(dominio); } _PrecintoRepository.Commit(); return(new InsertarActualizarChoferOutput() { idchofer = dominio.idprecinto }); } catch (Exception ex) { // _ValortablaRepository.Delete(dominio); //_ValortablaRepository.Commit(); throw; } }
public object DeleteLayaway(IRepository <Layaway> layawayContext, string Id) { try { layawayContext.Delete(Id); layawayContext.Commit(); // send response object return(new { Successful = true, Message = "Layaway deleted." }); } catch (Exception ex) { // log error; Console.WriteLine(ex); // send response object error return(new { Successful = false, Message = "Layaway failed to delete." }); } }
public ResultEntity <bool> AddDealer(AddDealerDto addDealerDto) { //内存中组织对象 var dealerid = Guid.NewGuid(); var dealercontact = new List <Contact>(); for (int i = 0; i < addDealerDto.ContactName.Count; i++) { var dealercontactmodel = new Contact().CreateContact(dealerid, addDealerDto.ContactName[i], addDealerDto.ContactTel[i], addDealerDto.ContactSheng[i], addDealerDto.ContactShi[i], addDealerDto.ContactQu[i], addDealerDto.ContactJiedao[i], addDealerDto.ContactIsDefault[i] ); dealercontact.Add(dealercontactmodel); } var dealer = new Dealers(_dealerRepository).RegisterDealers(dealerid, addDealerDto.Name, addDealerDto.Tel, addDealerDto.EleMoney, dealercontact, addDealerDto.Parentid); var login = new Login().CreateLogin(dealer.Tel, dealerid); //实际持续化到数据库中 try { using (_repository) { _dealerRepository.CreateDealer(dealer); if (addDealerDto.Parentid != null) { _dealerRepository.SubParentEleMoney((Guid)addDealerDto.Parentid, addDealerDto.EleMoney); } _dealerRepository.AddParentSubCount(addDealerDto.Parentid); _loginRepository.CreateLogin(login); _repository.Commit(); } return(GetResultEntity(true)); } catch (Exception ex) { throw ex; } }
public object DeletePayment(IRepository <Payment> paymentContext, string Id) { try { paymentContext.Delete(Id); paymentContext.Commit(); // send response object return(new { Successful = true, Message = "Payment deleted." }); } catch (Exception ex) { // log error; Console.WriteLine(ex); // send response object error return(new { Successful = false, Message = "Payment failed to delete." }); } }
public CommandContracts.Common.CommandResult Handle(InsertarActualizarDiagnosticoxTipoProductoCommand command) { if (command == null) { throw new ArgumentException("Tiene que ingresar una cliente"); } DiagnosticoxTipoProducto dominio = null; if (command.iddiagnosticotipoproducto.HasValue) { dominio = _DiagnosticoxTipoProductoRepository.Get(x => x.iddiagnosticotipoproducto == command.iddiagnosticotipoproducto).LastOrDefault(); } else { dominio = new DiagnosticoxTipoProducto(); } dominio.idtipoproducto = command.idtipoproducto; dominio.iddiagnosticosmartway = command.iddiagnosticosmartway; try { if (!command.iddiagnosticotipoproducto.HasValue) { _DiagnosticoxTipoProductoRepository.Add(dominio); } _DiagnosticoxTipoProductoRepository.Commit(); return(new InsertarActualizarDiagnosticoxTipoProductoOutput() { iddiagnosticotipoproducto = dominio.iddiagnosticotipoproducto }); } catch (Exception ex) { // _ValortablaRepository.Delete(dominio); //_ValortablaRepository.Commit(); throw; } }
/// <summary> /// 自动分配拼多多pid /// </summary> public dm_userEntity AutoAssignPDDPID(dm_userEntity dm_UserEntity) { IRepository db = null; try { dm_pidEntity dm_PidEntity = this.BaseRepository("dm_data").FindEntity <dm_pidEntity>("select * from dm_pid where usestate=0 and type=3 limit 1", null); if (dm_PidEntity == null) { throw new Exception("无可用拼多多PID,请联系客服!"); } dm_UserEntity.pdd_pid = dm_PidEntity.pid; dm_UserEntity.Modify(dm_UserEntity.id); dm_PidEntity.user_id = dm_UserEntity.id; dm_PidEntity.usestate = 1; dm_PidEntity.usetime = DateTime.Now; db = this.BaseRepository("dm_data").BeginTrans(); db.Update(dm_UserEntity); db.Update(dm_PidEntity); db.Commit(); return(dm_UserEntity); } catch (Exception ex) { if (db != null) { db.Rollback(); } if (ex is ExceptionEx) { throw; } else { throw ExceptionEx.ThrowServiceException(ex); } } }
public object DeleteInvoice(IRepository <Invoice> invoiceContext, string Id) { try { invoiceContext.Delete(Id); invoiceContext.Commit(); // send response object return(new { Successful = true, Message = "Invoice deleted." }); } catch (Exception ex) { // log error; Console.WriteLine(ex); // send response object error return(new { Successful = false, Message = "Invoice failed to delete." }); } }
/// <summary> /// 更新流程实例 审核节点用 /// </summary> /// <param name="sql"></param> /// <param name="dbbaseId"></param> /// <param name="processInstanceEntity"></param> /// <param name="processSchemeEntity"></param> /// <param name="processOperationHistoryEntity"></param> /// <param name="delegateRecordEntityList"></param> /// <param name="processTransitionHistoryEntity"></param> /// <returns></returns> public int SaveProcess(string sql, string dbbaseId, WFProcessInstanceEntity processInstanceEntity, WFProcessSchemeEntity processSchemeEntity, WFProcessOperationHistoryEntity processOperationHistoryEntity, List <WFDelegateRecordEntity> delegateRecordEntityList, WFProcessTransitionHistoryEntity processTransitionHistoryEntity = null) { IRepository db = this.BaseRepository().BeginTrans(); try { processInstanceEntity.Modify(processInstanceEntity.Id); db.Update(processSchemeEntity); db.Update(processInstanceEntity); processOperationHistoryEntity.Create(); processOperationHistoryEntity.ProcessId = processInstanceEntity.Id; db.Insert(processOperationHistoryEntity); if (processTransitionHistoryEntity != null) { processTransitionHistoryEntity.Create(); processTransitionHistoryEntity.ProcessId = processInstanceEntity.Id; db.Insert(processTransitionHistoryEntity); } if (delegateRecordEntityList != null) { foreach (var item in delegateRecordEntityList) { item.Create(); item.ProcessId = processInstanceEntity.Id; db.Insert(item); } } //if (!string.IsNullOrEmpty(dbbaseId) && !string.IsNullOrEmpty(sql))//测试环境不允许执行sql语句 //{ // DataBaseLinkEntity dataBaseLinkEntity = dataBaseLinkService.GetEntity(dbbaseId);//获取 // this.BaseRepository(dataBaseLinkEntity.DbConnection).ExecuteBySql(sql.Replace("{0}", processInstanceEntity.Id)); //} db.Commit(); return(1); } catch { db.Rollback(); throw; } }
public object DeleteCustomerNote(IRepository <CustomerNote> customernoteContext, string Id) { try { customernoteContext.Delete(Id); customernoteContext.Commit(); // send response object return(new { Successful = true, Message = "Note deleted." }); } catch (Exception ex) { // log error; Console.WriteLine(ex); // send response object error return(new { Successful = false, Message = "Note failed to delete." }); } }
public ActionResult Edit(OrderItem orderItem, string Id) { ViewBag.IsIndexHome = false; OrderItem orderItemToEdit = orderItemsContext.Find(Id); if (orderItem == null) { return(HttpNotFound()); } else { if (!ModelState.IsValid) { return(View(orderItem)); } orderItemsContext.Commit(); //Email Customer string CustomerEmail = User.Identity.Name;; var subject = "Shop.MyRockies.Network you Order has been Shipped: " + orderItem.OrderId; var fromAddress = "*****@*****.**"; var toAddress = CustomerEmail; var emailBody = "Email From: Store.com Message: the answer to your order: "; var smtp = new SmtpClient(); { smtp.Host = "smtp.myrockies.network"; smtp.Port = 587; smtp.EnableSsl = false; smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; smtp.Credentials = new NetworkCredential("*****@*****.**", "bdFawHs7"); smtp.Timeout = 20000; } smtp.Send(fromAddress, toAddress, subject, emailBody); return(RedirectToAction("OrderItemsDetails")); } }
public static Commit CreateFileAndCommit(this IRepository repository, string relativeFileName, string commitMessage = null) { var randomFile = Path.Combine(repository.Info.WorkingDirectory, relativeFileName); if (File.Exists(randomFile)) { File.Delete(randomFile); } var totalWidth = 36 + (_pad++ % 10); var contents = Guid.NewGuid().ToString().PadRight(totalWidth, '.'); File.WriteAllText(randomFile, contents); Commands.Stage(repository, randomFile); return(repository.Commit(string.Format("Test Commit for file '{0}' - {1}", relativeFileName, commitMessage), Generate.SignatureNow(), Generate.SignatureNow())); }
public ActionResult AddApartment(Apartment Apartment, string Create, string prefix, bool isStreet = false, string cityPrefix = null, string streetPrefix = null) { if (!string.IsNullOrEmpty(Create)) { if (!ModelState.IsValid) { return(View(Apartment)); } else { if (User.Identity.IsAuthenticated) { var Id = User.Identity.GetUserId(); Apartment.UserId = Id; } Apartment.State = "ישראל"; apartments.Insert(Apartment); apartments.Commit(); return(RedirectToAction("Index")); } } else { dynamic AdreessType; if (isStreet) { string CityChosen = cityPrefix; AdreessType = (from C in streets.Collection() where C.Name_He.ToLower().StartsWith(prefix.ToLower()) && C.CityName.Equals(CityChosen) select new { C.Name_He }); } else { AdreessType = (from C in cities.Collection() where C.Name_He.ToLower().StartsWith(prefix.ToLower()) select new { C.Name_He }); } return(Json(AdreessType)); } }
public void CheckAppPartnersRecord(dm_apply_partners_recordEntity entity) { IRepository db = null; try { if (entity.status == 1) { dm_apply_partners_recordEntity dm_Apply_Partners_RecordEntity = GetEntity(entity.id); dm_userEntity dm_UserEntity = new dm_userEntity(); dm_UserEntity.partnersstatus = 2; dm_UserEntity.partners = 20000 + dm_Apply_Partners_RecordEntity.user_id; dm_UserEntity.id = dm_Apply_Partners_RecordEntity.user_id; dm_Apply_Partners_RecordEntity.status = entity.status; db = this.BaseRepository("dm_data").BeginTrans(); db.Update(dm_UserEntity); entity.Modify(entity.id); db.Update(entity); db.Commit(); } } catch (Exception ex) { if (db != null) { db.Rollback(); } if (ex is ExceptionEx) { throw; } else { throw ExceptionEx.ThrowServiceException(ex); } } }
public CommandContracts.Common.CommandResult Handle(InsertarActualizarZonaCommand command) { if (command == null) { throw new ArgumentException("Tiene que ingresar una cliente"); } Zona dominio = null; if (command.idzona.HasValue) { dominio = _ZonaRepository.Get(x => x.idzona == command.idzona).LastOrDefault(); } else { dominio = new Zona(); } dominio.zona = command.zona; try { if (!command.idzona.HasValue) { _ZonaRepository.Add(dominio); } _ZonaRepository.Commit(); return(new InsertarActualizarZonaOutput() { idzona = dominio.idzona }); } catch (Exception ex) { // _ValortablaRepository.Delete(dominio); //_ValortablaRepository.Commit(); throw; } }
public CommandContracts.Common.CommandResult Handle(InsertarActualizarRepuestoxReparacionCommand command) { if (command == null) { throw new ArgumentException("Tiene que ingresar una cliente"); } RepuestoxReparacion dominio = null; if (command.idrepuestoreparacion.HasValue) { dominio = _RepuestoxReparacionRepository.Get(x => x.idrepuestoreparacion == command.idrepuestoreparacion).LastOrDefault(); } else { dominio = new RepuestoxReparacion(); } dominio.idreparacion = command.idreparacion; dominio.idrepuesto = command.idrepuesto; try { if (!command.idrepuestoreparacion.HasValue) { _RepuestoxReparacionRepository.Add(dominio); } _RepuestoxReparacionRepository.Commit(); return(new InsertarActualizarRepuestoxReparacionOutput() { idrepuestoreparacion = dominio.idrepuestoreparacion }); } catch (Exception ex) { // _ValortablaRepository.Delete(dominio); //_ValortablaRepository.Commit(); throw; } }
public void CheckCertificationRecord(dm_certifica_recordEntity entity) { IRepository db = null; try { if (entity.realstatus == 1) { dm_userEntity dm_UserEntity = new dm_userEntity(); dm_UserEntity.isreal = 1; dm_UserEntity.id = entity.user_id; dm_UserEntity.realname = entity.realname; dm_UserEntity.frontcard = entity.frontcard; dm_UserEntity.facecard = entity.facecard; db = this.BaseRepository("dm_data").BeginTrans(); db.Update(dm_UserEntity); db.Update(entity); db.Commit(); } else if (entity.realstatus == 2) { this.BaseRepository("dm_data").Update <dm_certifica_recordEntity>(entity); } } catch (Exception ex) { if (db != null) { db.Rollback(); } if (ex is ExceptionEx) { throw; } else { throw ExceptionEx.ThrowServiceException(ex); } } }
/// <summary> /// Ends the current tournament, saves the results, and schedules the next one. /// </summary> public void EndTournament(bool broadcasting) { if (CurrentTournament != null) { TournamentResults.Create(CurrentTournament); TournamentResults.Commit(); DateTime?next; if (broadcasting) { next = CurrentTournament.Date.AddMinutes(Settings.FishingTournamentDuration + Settings.FishingTournamentInterval); } else { next = null; } NextTournament = next; TournamentEnded?.Invoke(CurrentTournament, next); CurrentTournament = null; } }
private static Commit AddCommitToRepo(IRepository repo) { string relativeFilepath = "test.txt"; Touch(repo.Info.WorkingDirectory, relativeFilepath, content); repo.Index.Stage(relativeFilepath); var ie = repo.Index[relativeFilepath]; Assert.NotNull(ie); Assert.Equal("9daeafb9864cf43055ae93beb0afd6c7d144bfa4", ie.Id.Sha); var author = new Signature("nulltoken", "*****@*****.**", DateTimeOffset.Parse("Wed, Dec 14 2011 08:29:03 +0100")); var commit = repo.Commit("Initial commit", author, author); relativeFilepath = "big.txt"; var zeros = new string('0', 32*1024 + 3); Touch(repo.Info.WorkingDirectory, relativeFilepath, zeros); repo.Index.Stage(relativeFilepath); ie = repo.Index[relativeFilepath]; Assert.NotNull(ie); Assert.Equal("6518215c4274845a759cb498998fe696c42e3e0f", ie.Id.Sha); return commit; }
private Commit AddFileCommitToRepo(IRepository repository, string filename, string content = null) { Touch(repository.Info.WorkingDirectory, filename, content); repository.Index.Stage(filename); return repository.Commit("New commit", Constants.Signature, Constants.Signature); }
private Commit AddCommitToRepo(IRepository repository) { string random = Path.GetRandomFileName(); string filename = random + ".txt"; Touch(repository.Info.WorkingDirectory, filename, random); Commands.Stage(repository, filename); return repository.Commit("New commit", Constants.Signature, Constants.Signature); }
/// <summary> /// Helper method to populate a simple repository with /// a single file and two branches. /// </summary> /// <param name="repo">Repository to populate</param> private void PopulateBasicRepository(IRepository repo) { // Generate a .gitignore file. string gitIgnoreFilePath = Touch(repo.Info.WorkingDirectory, ".gitignore", "bin"); repo.Stage(gitIgnoreFilePath); string fullPathFileA = Touch(repo.Info.WorkingDirectory, originalFilePath, originalFileContent); repo.Stage(fullPathFileA); repo.Commit("Initial commit", Constants.Signature, Constants.Signature); repo.CreateBranch(otherBranchName); }
public static Commit CommitFile(IRepository repo, string filePath, string comment) { repo.Stage(filePath); return repo.Commit(comment, SignatureNow(), SignatureNow()); }
internal async Task<ChangeSet> Sync(DropboxInfo dropboxInfo, string branch, IRepository repository) { DropboxDeployInfo deployInfo = dropboxInfo.DeployInfo; ResetStats(); if (_settings.GetValue(CursorKey) != deployInfo.OldCursor) { throw new InvalidOperationException(Resources.Error_MismatchDropboxCursor); } // initial sync, remove default content // for simplicity, we do it blindly whether or not in-place // given the end result is the same if (String.IsNullOrEmpty(deployInfo.OldCursor) && DeploymentHelper.IsDefaultWebRootContent(_environment.WebRootPath)) { string hoststarthtml = Path.Combine(_environment.WebRootPath, Constants.HostingStartHtml); FileSystemHelpers.DeleteFileSafe(hoststarthtml); } if (!repository.IsEmpty()) { // git checkout --force <branch> repository.Update(branch); } ChangeSet changeSet = null; string message = null; try { using (_tracer.Step("Sync with Dropbox")) { if (dropboxInfo.OAuthVersion == 2) { // Fetch the deltas await UpdateDropboxDeployInfo(deployInfo); } // Sync dropbox => repository directory await ApplyChanges(dropboxInfo, useOAuth20: dropboxInfo.OAuthVersion == 2); } message = String.Format(CultureInfo.CurrentCulture, Resources.Dropbox_Synchronized, deployInfo.Deltas.Count); } catch (Exception) { message = String.Format(CultureInfo.CurrentCulture, Resources.Dropbox_SynchronizedWithFailure, _successCount, deployInfo.Deltas.Count, _failedCount); throw; } finally { Logger.Log(message); Logger.Log(String.Format("{0} downloaded files, {1} successful retries.", _fileCount, _retriedCount)); IDeploymentStatusFile statusFile = _status.Open(dropboxInfo.TargetChangeset.Id); statusFile.UpdateMessage(message); statusFile.UpdateProgress(String.Format(CultureInfo.CurrentCulture, Resources.Dropbox_Committing, _successCount)); // Commit anyway even partial change if (repository.Commit(message, String.Format("{0} <{1}>", deployInfo.UserName, deployInfo.Email ?? deployInfo.UserName))) { changeSet = repository.GetChangeSet("HEAD"); } } // Save new dropboc cursor LogInfo("Update dropbox cursor"); _settings.SetValue(CursorKey, deployInfo.NewCursor); return changeSet; }
internal ChangeSet Sync(DropboxHandler.DropboxInfo deploymentInfo, string branch, ILogger logger, IRepository repository) { DropboxDeployInfo info = deploymentInfo.DeployInfo; _logger = logger; _successCount = 0; _fileCount = 0; _failedCount = 0; _retriedCount = 0; if (_settings.GetValue(CursorKey) != info.OldCursor) { throw new InvalidOperationException(Resources.Error_MismatchDropboxCursor); } if (!repository.IsEmpty()) { // git checkout --force <branch> repository.ClearLock(); repository.Update(branch); } ChangeSet changeSet; string message = null; try { using (_tracer.Step("Synch with Dropbox")) { // Sync dropbox => repository directory ApplyChanges(deploymentInfo); } message = String.Format(CultureInfo.CurrentCulture, Resources.Dropbox_Synchronized, deploymentInfo.DeployInfo.Deltas.Count()); } catch (Exception) { message = String.Format(CultureInfo.CurrentCulture, Resources.Dropbox_SynchronizedWithFailure, _successCount, deploymentInfo.DeployInfo.Deltas.Count(), _failedCount); throw; } finally { _logger.Log(message); _logger.Log(String.Format("{0} downloaded files, {1} successful retries.", _fileCount, _retriedCount)); _status.Open(deploymentInfo.TargetChangeset.Id).UpdateMessage(message); _status.Open(deploymentInfo.TargetChangeset.Id).UpdateProgress(String.Format(CultureInfo.CurrentCulture, Resources.Dropbox_Committing, _successCount)); // Commit anyway even partial change changeSet = repository.Commit(message, String.Format("{0} <{1}>", info.UserName, info.Email)); } // Save new dropboc cursor LogInfo("Update dropbox cursor"); _settings.SetValue(CursorKey, info.NewCursor); return changeSet; }
private static void FeedTheRepository(IRepository repo) { string fullPath = Touch(repo.Info.WorkingDirectory, "a.txt", "Hello\n"); repo.Stage(fullPath); repo.Commit("Initial commit", Constants.Signature, Constants.Signature); repo.ApplyTag("mytag"); File.AppendAllText(fullPath, "World\n"); repo.Stage(fullPath); Signature shiftedSignature = Constants.Signature.TimeShift(TimeSpan.FromMinutes(1)); repo.Commit("Update file", shiftedSignature, shiftedSignature); repo.CreateBranch("mybranch"); repo.Checkout("mybranch"); Assert.False(repo.RetrieveStatus().IsDirty); }
private Commit AddCommitToRepo(IRepository repository) { string random = Guid.NewGuid().ToString(); string filename = random + ".txt"; Touch(repository.Info.WorkingDirectory, filename, random); repository.Index.Stage(filename); return repository.Commit("New commit", Constants.Signature, Constants.Signature); }