protected T getDomainObjectById <T>(int Id) where T : Model.ModelEntity, new() { if (Id == 0) { return(new T()); } using (var om = new OperationManager()) { try { var session = om.BeginOperation(); var entity = (from o in session.Query <T>() where o.Id == Id select o).Single(); om.CommitOperation(); return(entity); } catch (Exception ex) { om.RollbackOperation(); string msg = "Impossibile recuperare l'oggetto " + typeof(T).ToString() + " con id = " + Id; logger.ErrorException(msg, ex); throw new Exception(msg, ex); } } }
public void Save(Tappa tappa) { using (var om = new OperationManager()) { try { om.BeginOperation(); var destinazione = tappa.Viaggio.Tappe.Where(t => t.Tipo == TipoTappa.DESTINAZIONE).SingleOrDefault(); if (destinazione != null) { logger.Debug("L'ordinamento della destinazione verrà incrementato di 1 per fare posto alla nuova tappa"); destinazione.Ordinamento = tappa.Ordinamento + 1; base.update <Tappa>(destinazione); } base.update <Tappa>(tappa); om.CommitOperation(); logger.Info("Dati della tappa {0} salvati con successo", tappa); } catch (Exception ex) { om.RollbackOperation(); string msg = "Errore nel salvataggio della tappa"; logger.ErrorException(msg, ex); throw new Exception(msg, ex); } } }
private async Task InvokeMethodAsync(MethodInfo method, CancellationToken cancellationToken) { using (Operation op = _operations.BeginOperation("Invoking scheduled method {scheduledMethod}", method.ToString())) { try { var impl = op.ServiceProvider.GetService <TService>(); var parameters = method.GetParameters(); Task result; if (parameters.Length == 1 && parameters[0].ParameterType == typeof(CancellationToken)) { result = (Task)method.Invoke(impl, new object[] { cancellationToken }) !; } else { result = (Task)method.Invoke(impl, Array.Empty <object>()) !; } await result; } catch (OperationCanceledException ocex) when(ocex.CancellationToken == cancellationToken) { //ignore } catch (Exception ex) { _logger.LogError(ex, "Exception processing scheduled method {scheduledMethod}", method.ToString()); } } }
protected void DeleteById<T>(int domainModelObjectId) where T : Model.ModelEntity { using (var om = new OperationManager()) { try { var queryString = string.Format("delete {0} where ID = :id", typeof(T)); var session = om.BeginOperation(); session.CreateQuery(queryString) .SetParameter("id", domainModelObjectId) .ExecuteUpdate(); logger.Info("Object " + typeof(T).ToString() + " with id = " + domainModelObjectId + " successfully deleted"); om.CommitOperation(); } catch (Exception ex) { om.RollbackOperation(); string msg = string.Format("Error deleting object {0} with id = {1}", typeof(T).ToString(), domainModelObjectId); logger.ErrorException(msg, ex); throw new Exception(msg, ex); } } }
public IList <Viaggio> GetProposteAgenzia(Agenzia agenzia) { var ar = new AgenziaRepository(); using (var om = new OperationManager()) { try { var session = om.BeginOperation(); logger.Info("Recupero dei viaggi proposti dall'agenzia {0}", agenzia); var viaggi = session.Query <Viaggio>() .Where(v => v.Agenzia.Id == agenzia.Id) .ToList(); logger.Debug("Viaggi proposti: {0}", viaggi.Count); om.CommitOperation(); return(viaggi); } catch (Exception ex) { om.RollbackOperation(); string msg = String.Format("Impossibile recuperare i viaggi proposti dall'agenzia {0}", agenzia); logger.ErrorException(msg, ex); throw new Exception(msg, ex); } } }
public async Task <MergePolicyEvaluationResult> EvaluateAsync( IPullRequest pr, IRemote darc, IReadOnlyList <MergePolicyDefinition> policyDefinitions) { var context = new MergePolicyEvaluationContext(pr, darc); foreach (MergePolicyDefinition definition in policyDefinitions) { if (MergePolicies.TryGetValue(definition.Name, out MergePolicy policy)) { using (_operations.BeginOperation("Evaluating Merge Policy {policyName}", policy.Name)) { context.CurrentPolicy = policy; await policy.EvaluateAsync(context, new MergePolicyProperties(definition.Properties)); } } else { context.CurrentPolicy = null; context.Fail($"Unknown Merge Policy: '{definition.Name}'"); } } return(context.Result); }
/// <summary> /// Download and install git to the a temporary location. /// Git is used by DarcLib, and the Service Fabric nodes do not have it installed natively. /// /// The file is assumed to be on a public endpoint. /// We return the git client executable so that this call may be easily wrapped in RetryAsync /// </summary> public async Task <string> GetPathToLocalGitAsync() { // Determine whether we need to do any downloading at all. if (!string.IsNullOrEmpty(_gitExecutable)) { return(_gitExecutable); } await _semaphoreSlim.WaitAsync(); try { // Determine whether another thread ended up getting the lock and downloaded git // in the meantime. if (string.IsNullOrEmpty(_gitExecutable)) { using (_operations.BeginOperation($"Installing a local copy of git")) { string gitLocation = _configuration.GetValue <string>("GitDownloadLocation", null); string[] pathSegments = new Uri(gitLocation, UriKind.Absolute).Segments; string remoteFileName = pathSegments[pathSegments.Length - 1]; string gitRoot = _tempFiles.GetFilePath("git-portable"); string targetPath = Path.Combine(gitRoot, Path.GetFileNameWithoutExtension(remoteFileName)); string gitZipFile = Path.Combine(gitRoot, remoteFileName); _logger.LogInformation($"Downloading git from '{gitLocation}' to '{gitZipFile}'"); Directory.CreateDirectory(targetPath); using (HttpClient client = new HttpClient()) using (FileStream outStream = new FileStream(gitZipFile, FileMode.Create, FileAccess.Write)) using (var inStream = await client.GetStreamAsync(gitLocation)) { await inStream.CopyToAsync(outStream); } _logger.LogInformation($"Extracting '{gitZipFile}' to '{targetPath}'"); ZipFile.ExtractToDirectory(gitZipFile, targetPath, overwriteFiles: true); _gitExecutable = Path.Combine(targetPath, "bin", "git.exe"); } } } finally { _semaphoreSlim.Release(); } return(_gitExecutable); }
public async Task <TimeSpan> RunAsync(CancellationToken cancellationToken) { IReliableConcurrentQueue <DependencyUpdateItem> queue = await StateManager.GetOrAddAsync <IReliableConcurrentQueue <DependencyUpdateItem> >("queue"); try { using (ITransaction tx = StateManager.CreateTransaction()) { ConditionalValue <DependencyUpdateItem> maybeItem = await queue.TryDequeueAsync( tx, cancellationToken); if (maybeItem.HasValue) { DependencyUpdateItem item = maybeItem.Value; using (_operations.BeginOperation( "Processing dependency update for build {buildId} in channel {channelId}", item.BuildId, item.ChannelId)) { await UpdateDependenciesAsync(item.BuildId, item.ChannelId); } } await tx.CommitAsync(); } } catch (TaskCanceledException tcex) when(tcex.CancellationToken == cancellationToken) { return(TimeSpan.MaxValue); } catch (Exception ex) { Logger.LogError(ex, "Processing queue messages"); } return(TimeSpan.FromSeconds(1)); }
public async Task <IRemote> GetRemoteAsync(string repoUrl, ILogger logger) { using (_operations.BeginOperation($"Getting remote for repo {repoUrl}.")) { // Normalize the url with the AzDO client prior to attempting to // get a token. When we do coherency updates we build a repo graph and // may end up traversing links to classic azdo uris. string normalizedUrl = AzureDevOpsClient.NormalizeUrl(repoUrl); Uri normalizedRepoUri = new Uri(normalizedUrl); // Look up the setting for where the repo root should be held. Default to empty, // which will use the temp directory. string temporaryRepositoryRoot = _configuration.GetValue <string>("DarcTemporaryRepoRoot", null); if (string.IsNullOrEmpty(temporaryRepositoryRoot)) { temporaryRepositoryRoot = _tempFiles.GetFilePath("repos"); } IGitRepo gitClient; long installationId = await _context.GetInstallationId(normalizedUrl); var gitExe = await ExponentialRetry.RetryAsync( async() => await _localGit.GetPathToLocalGitAsync(), ex => logger.LogError(ex, $"Failed to install git to local temporary directory."), ex => true); switch (normalizedRepoUri.Host) { case "github.com": if (installationId == default) { throw new GithubApplicationInstallationException($"No installation is avaliable for repository '{normalizedUrl}'"); } gitClient = new GitHubClient(gitExe, await _gitHubTokenProvider.GetTokenForInstallationAsync(installationId), logger, temporaryRepositoryRoot, _cache.Cache); break; case "dev.azure.com": gitClient = new AzureDevOpsClient(gitExe, await _azureDevOpsTokenProvider.GetTokenForRepository(normalizedUrl), logger, temporaryRepositoryRoot); break; default: throw new NotImplementedException($"Unknown repo url type {normalizedUrl}"); } ; return(new Remote(gitClient, new MaestroBarClient(_context), logger)); } }
public void Delete(Flyer flyer) { using (var manager = new OperationManager()) { try { manager.BeginOperation(); base.delete <Flyer>(flyer); manager.CommitOperation(); logger.Info("Flyer {0} eliminato con successo", flyer.Id); } catch (Exception ex) { string message = "Errore nella cancellazione del flyer"; logger.ErrorException(message, ex); throw new Exception(message, ex); } } }
protected IQueryable <T> getAll <T>() where T : Model.ModelEntity { using (var om = new OperationManager()) { try { var session = om.BeginOperation(); var items = session.Query <T>(); om.CommitOperation(); return(items); } catch (Exception ex) { om.RollbackOperation(); logger.ErrorException("Errore nel recupero degli oggetti " + typeof(T).ToString(), ex); return(null); } } }
protected IQueryable<T> GetAll<T>() where T : Model.ModelEntity { using (var om = new OperationManager()) { try { var session = om.BeginOperation(); var items = session.Query<T>(); om.CommitOperation(); return items; } catch (Exception ex) { om.RollbackOperation(); logger.ErrorException("Error retrieving objects " + typeof(T).ToString(), ex); return null; } } }
public IList <Viaggio> GetApproved() { using (var om = new OperationManager()) { try { var session = om.BeginOperation(); var result = GetViaggiApprovati().ToList(); om.CommitOperation(); return(result); } catch (Exception ex) { om.RollbackOperation(); string msg = String.Format("Errore durante il recupero dei viaggi approvati"); logger.ErrorException(msg, ex); throw new Exception(msg, ex); } } }
public Model.DynamicBoard GetById(int Id) { using (var om = new OperationManager()) { try { var session = om.BeginOperation(); var board = dbr.GetById(Id); om.CommitOperation(); return(board); } catch (Exception ex) { om.RollbackOperation(); string msg = String.Format("Error {0}", null); logger.ErrorException(msg, ex); throw new Exception(msg, ex); } } }
public IList <Model.DynamicBoard> GetAll() { using (var om = new OperationManager()) { try { var session = om.BeginOperation(); var boardList = dbr.GetAll().ToList(); om.CommitOperation(); return(boardList); } catch (Exception ex) { om.RollbackOperation(); string msg = "Error retrieving the list of available boards"; logger.ErrorException(msg, ex); throw new Exception(msg, ex); } } }
public IList <Viaggio> GetListaViaggiByAgenzia(Agenzia agenzia) { using (var om = new OperationManager()) { try { var session = om.BeginOperation(); var result = GetViaggiVisibili(agenzia).ToList(); om.CommitOperation(); return(result); } catch (Exception ex) { om.RollbackOperation(); string msg = String.Format("Errore durante il recupero dei viaggi dell'agenzia {0}", agenzia.ToString()); logger.ErrorException(msg, ex); throw new Exception(msg, ex); } } }
public void Save(Flyer flyer) { using (var om = new OperationManager()) { try { om.BeginOperation(); base.update <Flyer>(flyer); om.CommitOperation(); logger.Info("Dati del flyer {0} salvati con successo", flyer.Id); } catch (Exception ex) { om.RollbackOperation(); string msg = "Errore nel salvataggio del flyer"; logger.ErrorException(msg, ex); throw new Exception(msg, ex); } } }
/// <summary> /// Gets all Agenzia where isTourOperator is false. /// </summary> /// <param name="maximumRows">The maximum rows.</param> /// <param name="startRowIndex">Start index of the row.</param> /// <returns></returns> public IList <Agenzia> GetAllAdV(int maximumRows, int startRowIndex) { using (var manager = new OperationManager()) { try { var session = manager.BeginOperation(); var res = session.Query <Agenzia>() .Where(c => !c.IsTourOperator).ToList(); manager.CommitOperation(); return(res); } catch (Exception ex) { manager.RollbackOperation(); string message = String.Format("Impossibile recuperare la lista delle AdV"); logger.ErrorException(message, ex); throw new Exception(message, ex); } } }
public Agenzia GetByEmail(string email) { using (var manager = new OperationManager()) { try { var session = manager.BeginOperation(); var res = session.Query <Agenzia>() .Where(u => u.Email.ToLower().Equals(email)).SingleOrDefault(); manager.CommitOperation(); return(res); } catch (Exception ex) { manager.RollbackOperation(); string message = String.Format("Impossibile recuperare l'agenzia con email = {0}", email); logger.ErrorException(message, ex); throw new Exception(message, ex); } } }
protected int Save<T>(T domainModelObject) where T : Model.ModelEntity { using (var om = new OperationManager()) { try { var session = om.BeginOperation(); session.SaveOrUpdate(domainModelObject); om.CommitOperation(); logger.Info("Object " + domainModelObject.GetType().ToString() + " with id = " + domainModelObject.Id + " successfully saved"); } catch (Exception ex) { om.RollbackOperation(); logger.ErrorException("Error saving object " + domainModelObject.GetType().ToString() + " with id = " + domainModelObject.Id, ex); throw; } return domainModelObject.Id; } }
protected int update <T>(T domainModelObject) where T : Model.ModelEntity { using (var om = new OperationManager()) { try { var session = om.BeginOperation(); session.SaveOrUpdate(domainModelObject); om.CommitOperation(); logger.Info("Salvataggio dell'oggetto " + domainModelObject.GetType().ToString() + " con id = " + domainModelObject.Id + " avvenuto con successo"); } catch (Exception ex) { om.RollbackOperation(); logger.ErrorException("Errore nel salvataggio dell'oggetto " + domainModelObject.GetType().ToString() + " con id = " + domainModelObject.Id, ex); throw; } return(domainModelObject.Id); } }
protected int countEntityOccurrences <T>() where T : Model.ModelEntity { using (var om = new OperationManager()) { try { var session = om.BeginOperation(); var result = session.Query <T>().Count(); om.CommitOperation(); logger.Debug("Numero entità {0} presenti = {1}", typeof(T).ToString(), result); return(result); } catch (Exception ex) { om.RollbackOperation(); string msg = "Errore nel conteggio delle entità " + typeof(T).ToString(); logger.ErrorException(msg, ex); throw new Exception(msg, ex); } } }
internal IQueryable <Viaggio> GetViaggiNonApprovati() { using (var om = new OperationManager()) { try { var session = om.BeginOperation(); var result = GetViaggi() .Where(c => !c.Approvato); om.CommitOperation(); return(result); } catch (Exception ex) { om.RollbackOperation(); string msg = String.Format("Errore durante il recupero dei viaggi non approvati"); logger.ErrorException(msg, ex); throw new Exception(msg, ex); } } }
/// <summary> /// Gets the flyers per agenzia pubblicati. /// </summary> /// <param name="idAgenzia">The id agenzia.</param> /// <param name="isPubblicato">if set to <c>true</c> [is pubblicato].</param> /// <returns></returns> /// <exception cref="System.Exception"></exception> public IList <Flyer> GetFlyersPerAgenzia(int idAgenzia, bool isPubblicato) { using (var om = new OperationManager()) { try { var session = om.BeginOperation(); var flyers = session.Query <Flyer>().Where(p => p.Agenzia.Id == idAgenzia && p.IsPubblicato == isPubblicato).OrderByDescending(p => p.Id).ToList(); om.CommitOperation(); logger.Debug("Per l'agenzia {0} sono state trovate {1} flyers", idAgenzia, flyers.Count); return(flyers); } catch (Exception ex) { om.RollbackOperation(); string msg = String.Format("Impossibile recuperare i flyers per l'agenzia {0}", idAgenzia); logger.ErrorException(msg, ex); throw new Exception(msg, ex); } } }
/// <summary> /// Prende tutti i viaggi pubblicati o proposti dall'agenzia dell'utente loggato /// </summary> /// <returns></returns> internal IQueryable <Viaggio> GetViaggiVisibili(Agenzia agenzia) { using (var om = new OperationManager()) { try { var session = om.BeginOperation(); var result = GetViaggi() .Where(v => v.Agenzia.Id == agenzia.Id); om.CommitOperation(); return(result); } catch (Exception ex) { om.RollbackOperation(); string msg = String.Format("Errore durante il recupero dei viaggi pubblicati o proposti dall'agenzia {0}", agenzia); logger.ErrorException(msg, ex); throw new Exception(msg, ex); } } }
protected void Delete<T>(T domainModelObject) where T : Model.ModelEntity { using (var om = new OperationManager()) { try { var session = om.BeginOperation(); session.Delete(domainModelObject); logger.Info("Object " + domainModelObject.GetType().ToString() + " with id = " + domainModelObject.Id + " successfully deleted"); om.CommitOperation(); } catch (Exception ex) { om.RollbackOperation(); string msg = string.Format("Error deleting object {0} with id = {1}", domainModelObject.GetType().ToString(), domainModelObject.Id); logger.ErrorException(msg, ex); throw new Exception(msg, ex); } } }
protected void delete <T>(T domainModelObject) where T : Model.ModelEntity { using (var om = new OperationManager()) { try { var session = om.BeginOperation(); session.Delete(domainModelObject); logger.Info("Eliminazione dell'oggetto " + domainModelObject.GetType().ToString() + " con id = " + domainModelObject.Id + " avvenuta con successo"); om.CommitOperation(); } catch (Exception ex) { om.RollbackOperation(); string msg = string.Format("Impossibile eliminare l'oggetto {0} con id={1}", domainModelObject.GetType().ToString(), domainModelObject.Id); logger.ErrorException(msg, ex); throw new Exception(msg, ex); } } }
public async Task <IRemote> GetRemoteAsync(string repoUrl, ILogger logger) { using (_operations.BeginOperation($"Getting remote for repo {repoUrl}.")) { // Normalize the url with the AzDO client prior to attempting to // get a token. When we do coherency updates we build a repo graph and // may end up traversing links to classic azdo uris. string normalizedUrl = AzureDevOpsClient.NormalizeUrl(repoUrl); Uri normalizedRepoUri = new Uri(normalizedUrl); IGitRepo gitClient; long installationId = await Context.GetInstallationId(normalizedUrl); switch (normalizedRepoUri.Host) { case "github.com": if (installationId == default) { throw new GithubApplicationInstallationException($"No installation is available for repository '{normalizedUrl}'"); } gitClient = new GitHubClient(null, await GitHubTokenProvider.GetTokenForInstallationAsync(installationId), logger, null, Cache.Cache); break; case "dev.azure.com": gitClient = new AzureDevOpsClient(null, await AzureDevOpsTokenProvider.GetTokenForRepository(normalizedUrl), logger, null); break; default: throw new NotImplementedException($"Unknown repo url type {normalizedUrl}"); } ; return(new Remote(gitClient, new MaestroBarClient(Context, KustoClientProvider), logger)); } }
/* * public void DeleteDepliant(int idDepliant) * { * logger.Debug("Richiesta di eliminazione del depliant {0}", idDepliant); * using (var om = new OperationManager()) * { * try * { * var session = om.BeginOperation(); * var viaggio = GetViaggioByDepliant(idDepliant); * logger.Debug("Il viaggio da cui il depliant {0} sarà rimosso è {1}", idDepliant, viaggio); * var depliant = viaggio.Depliant; * viaggio.Depliant = null; * DeleteAllegato(viaggio, depliant); * om.CommitOperation(); * logger.Info("Il depliant {0} relativo al viaggio {1} è stato eliminato", idDepliant, viaggio); * } * catch (Exception ex) * { * om.RollbackOperation(); * string msg = String.Format("Impossibile eliminare il depliant {0}", idDepliant); * logger.ErrorException(msg, ex); * throw new Exception(msg, ex); * } * } * * } * * private void DeleteAllegato(Viaggio viaggio, AllegatoViaggio targetAllegato) * { * using (var om = new OperationManager()) * { * try * { * var session = om.BeginOperation(); * var fullImgPath = targetAllegato.FullName; * System.IO.File.Delete(fullImgPath); * vr.Save(viaggio); * vr.deleteAllegato(targetAllegato); * om.CommitOperation(); * } * catch (Exception ex) * { * om.RollbackOperation(); * string msg = String.Format("Impossibile eliminare l'allegato {0}", targetAllegato.Id); * logger.ErrorException(msg, ex); * throw new Exception(msg, ex); * } * } * } * * public void DeletePromoImage(int idPromoImage) * { * logger.Debug("Richiesta di eliminazione dell'immagine promozionale {0}", idPromoImage); * using (var om = new OperationManager()) * { * try * { * var session = om.BeginOperation(); * var viaggio = GetViaggioByPromoImage(idPromoImage); * logger.Debug("Il viaggio da cui l'immagine promozionale {0} sarà rimossa è {1}", idPromoImage, viaggio); * var promoImg = viaggio.PromoImage; * viaggio.PromoImage = null; * DeleteAllegato(viaggio, promoImg); * om.CommitOperation(); * logger.Info("L'immagine promozionale {0} relativa al viaggio {1} è stata eliminato", idPromoImage, viaggio); * } * catch (Exception ex) * { * om.RollbackOperation(); * string msg = String.Format("Impossibile eliminare l'immagine promozionale {0}", idPromoImage); * logger.ErrorException(msg, ex); * throw new Exception(msg, ex); * } * } * * } * * public Boolean isValidDepliantMimeType(string fileName) * { * var result = false; * result = (fileName.ToLower().EndsWith(".pdf")) || (fileName.ToLower().EndsWith(".doc")); * logger.Debug("Il file {0} non è stato ritenuto valido come depliant", fileName); * return result; * } * * public bool isValidImageMimeType(string fileName) * { * var result = false; * result = (fileName.ToLower().EndsWith(".gif")) || (fileName.ToLower().EndsWith(".jpg")) || (fileName.ToLower().EndsWith(".png")); || logger.Debug("Il file {0} non è stato ritenuto valido come immagine", fileName); || return result; ||} */ public void DeleteTappa(int idTappa) { using (var om = new OperationManager()) { try { var session = om.BeginOperation(); var tappa = vr.GetTappaById(idTappa); var viaggio = tappa.Viaggio; viaggio.Tappe.Remove(tappa); vr.deleteTappa(tappa); Reorder(viaggio.Tappe); vr.Save(viaggio); om.CommitOperation(); } catch (Exception ex) { om.RollbackOperation(); string msg = String.Format("Errore durante l'eliminazione della tappa {0}", idTappa); logger.ErrorException(msg, ex); throw new Exception(msg, ex); } } }
protected IList <T> getAll <T>(int maximumRows, int startRowIndex) where T : Model.ModelEntity { logger.Debug("Elementi da recuperare: {0} - Elementi da saltare: {1}", maximumRows, startRowIndex); using (var om = new OperationManager()) { try { var session = om.BeginOperation(); var items = session.Query <T>() .Skip(startRowIndex) .Take(maximumRows) .ToList(); om.CommitOperation(); return(items); } catch (Exception ex) { om.RollbackOperation(); logger.ErrorException("Errore nel recupero degli oggetti " + typeof(T).ToString() + " alla pagina " + Decimal.ToInt32(Decimal.Ceiling((startRowIndex / maximumRows))), ex); return(null); } } }