public override bool Upgrade(PackageSession session, ILogger log, Package dependentPackage, PackageDependency dependency, Package dependencyPackage, IList<PackageLoadingAssetFile> assetFiles) { // Paradox 1.1 projects didn't have their dependency properly updated (they might have been marked as 1.0). // We know they are 1.1 only because there is a .props file. // This check shouldn't be necessary from 1.2. var packagePath = dependentPackage.FullPath; var propsFilePath = UPath.Combine(packagePath.GetParent(), (UFile)(packagePath.GetFileName() + ".props")); if (!File.Exists(propsFilePath) && dependency.Version.MinVersion < new PackageVersion("1.1.0-beta")) { log.Error("Can't upgrade old projects from {0} 1.0 to 1.1", dependency.Name); return false; } // Nothing to do for now, most of the work is already done by individual asset upgraders // We can later add logic here for package-wide upgrades (i.e. GameSettingsAsset) if (dependency.Version.MinVersion < new PackageVersion("1.2.0-beta")) { // UIImageGroups and SpriteGroups asset have been merged into a single SpriteSheet => rename the assets and modify the tag var uiImageGroups = assetFiles.Where(f => f.FilePath.GetFileExtension() == ".pdxuiimage"); var spitesGroups = assetFiles.Where(f => f.FilePath.GetFileExtension() == ".pdxsprite"); RenameAndChangeTag(assetFiles, uiImageGroups, "!UIImageGroup"); RenameAndChangeTag(assetFiles, spitesGroups, "!SpriteGroup"); } return true; }
/// <summary> /// 添加运行记录 /// </summary> /// <param name="taskId">任务编号</param> /// <param name="name">任务名称</param> /// <param name="identity">任务标识</param> /// <returns>是否上报成功</returns> public bool Add(string taskId, string name, string identity) { if (string.IsNullOrWhiteSpace(taskId) || string.IsNullOrWhiteSpace(identity) || !Env.HubService) { return(true); } try { var retryTimesPolicy = Policy.Handle <Exception>().Retry(10, (ex, count) => { _logger?.Error($"Try to add execute record failed [{count}]: {ex}", LogUtil.Identity); Thread.Sleep(5000); }); retryTimesPolicy.Execute(() => { NetworkCenter.Current.Execute("executeRecord", () => { var response = HttpClientDownloader.Default.GetAsync($"{Env.HubServiceTaskApiUrl}/{taskId}?action=increase").Result; response.EnsureSuccessStatusCode(); }); }); return(true); } catch (Exception e) { _logger?.Error($"Add execute record failed: {e}", identity); return(false); } }
internal void RenewTransactionCallback(object state) { try { if (_saveQueue.IsEmpty) { return; } var sw = Stopwatch.StartNew(); using (var cn = DbConnection()) { cn.Open(); using (var trans = cn.BeginTransaction()) { while (_saveQueue.TryDequeue(out WallPostDataChunk chunk)) { cn.Query(@"INSERT INTO WallPosts (GroupId, CompressedData) VALUES (@GroupId, @CompressedData);", chunk); } trans.Commit(); } } _log?.Verbose($"Commitinf transaction takes {sw.ElapsedMilliseconds} ms"); } catch (Exception ex) { _log?.Error(ex, ex.Message); } }
/// <summary> /// Merges the <paramref name="contact"/> with the existing one on the Bot's agenda /// </summary> /// <param name="identity"></param> /// <param name="contact"></param> /// <param name="cancellationToken"></param> /// <param name="logger"><c>ILogger</c> from <c>Serilog</c> to log useful information</param> /// <returns>Lime <c>Command</c> response object</returns> /// <exception cref="BlipHttpClientException">Failure merging the contact</exception> /// <exception cref="Exception">Unknown error</exception> public async Task <Command> MergeAsync(Identity identity, Contact contact, CancellationToken cancellationToken, ILogger logger) { try { var command = new Command() { Method = CommandMethod.Merge, Uri = new LimeUri("/contacts"), Resource = contact }; logger?.Information("[MergeContact] Trying merge contact using {@identity} and {@contact}", identity, contact); var contactResponse = await _sender.ProcessCommandAsync(command, cancellationToken); if (contactResponse.Status != CommandStatus.Success) { throw new BlipHttpClientException($"Failed to merge contact on BLiP's agenda using {identity} and {contact}", contactResponse); } logger?.Information("[MergeContact] Successfully merged contact using {@identity} and {@contact}", identity, contact); return(contactResponse); } catch (BlipHttpClientException bex) { logger?.Error(bex, "[MergeContact] Failed to merge contact using {@identity} and {@contact}", identity, contact); throw; } catch (Exception ex) { logger?.Error(ex, "[MergeContact] Failed to merge contact using {@identity} and {@contact}", identity, contact); throw; } }
/// <summary> /// Sets the <paramref name="contact"/> on the Bot's agenda /// </summary> /// <param name="contact"></param> /// <param name="cancellationToken"></param> /// <param name="logger">Optional <c>ILogger</c> from <c>Serilog</c> to log useful information</param> /// <returns>Lime <c>Command</c> response object</returns> /// <example> /// <code> /// Command x = await _contactService.SetContactAsync(contact, cancellationToken, logger) /// </code> /// </example> /// <exception cref="BlipHttpClientException">Failure setting the contact</exception> /// <exception cref="Exception">Unknown error</exception> public async Task <Command> SetAsync(Contact contact, CancellationToken cancellationToken, ILogger logger) { try { var command = new Command() { Method = CommandMethod.Set, Uri = new LimeUri("/contacts"), Resource = contact }; logger?.Information("[SetContact] Trying set contact {@contact}", contact); var contactResponse = await _sender.ProcessCommandAsync(command, cancellationToken); if (contactResponse.Status != CommandStatus.Success) { throw new BlipHttpClientException("Failed to set contact on BLiP's agenda.", contactResponse); } logger?.Information("[SetContact] Set contact {@contact}", contact); return(contactResponse); } catch (BlipHttpClientException bex) { logger?.Error(bex, "[SetContact] Failed to set contact {@contact}", contact); throw; } catch (Exception ex) { logger?.Error(ex, "[SetContact] Failed to set contact {@contact}", contact); throw; } }
/// <summary> /// Gets the Bot's Contact using the <paramref name="identity"/> param /// </summary> /// <param name="identity">User identifier whose contact must be recovered</param> /// <param name="cancellationToken"></param> /// <param name="logger">Optional <c>ILogger</c> from <c>Serilog</c> to log useful information</param> /// <returns>Lime <c>Contact</c> response object</returns> /// <example> /// <code> /// Contact x = await _contactService.GetContactAsync(contact, cancellationToken, logger) /// </code> /// </example> /// <exception cref="BlipHttpClientException">Failure getting the contact</exception> /// <exception cref="Exception">Unknown error</exception> public async Task <Contact> GetAsync(Identity identity, CancellationToken cancellationToken, ILogger logger) { try { var command = new Command() { Method = CommandMethod.Get, Uri = new LimeUri($"/contacts/{identity}") }; logger?.Information("[GetContact] Trying get contact using {@identity}'s", identity); var contactResponse = await _sender.ProcessCommandAsync(command, cancellationToken); if (contactResponse.Status != CommandStatus.Success) { throw new BlipHttpClientException("Failed to get contact from BLiP's agenda.", contactResponse); } logger?.Information("[GetContact] Got contact using {@identity}'s contact: {@contact}", identity, contactResponse.Resource as Contact); return(contactResponse.Resource as Contact); } catch (BlipHttpClientException bex) { logger?.Error(bex, "[GetContact] Failed to get contact using {@identity}'s contact", identity); throw; } catch (Exception ex) { logger?.Error(ex, "[GetContact] Failed to get contact using {@identity}'s contact", identity); throw; } }
public void Process(MethodInterceptionArgs args, ILogger log) { try { args.Proceed(); } catch (DefaultException ex) { log.Error(string.Format("Mensaje: {0} Trace: {1}", ex.Message, ex.StackTrace)); var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext); var url = urlHelper.Action("OperationError", "Error", new { area = "" }); url += "/" + ex.Message; var result = new RedirectResult(url); args.ReturnValue = result; } catch (Exception ex) { log.Error(string.Format("Mensaje: {0} Trace: {1}", ex.Message, ex.StackTrace)); var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext); var url = urlHelper.Action("Index", "Error", new { area = "" }); var result = new RedirectResult(url); args.ReturnValue = result; } }
private IObservable <T> CreateConsumerObservable <T>(string queueName, bool autoAck = true, Action <T, ulong> callback = null) { return(Observable.Create <T>(observer => { lock (_model) { DeclareQueue(queueName); _model.QueueBind(queueName, _EXCHANGE_NAME, queueName); } _logger?.Debug("Creating consumer. queue-name={QueueName}", queueName); var consumer = new EventingBasicConsumer(_model); string consumerTag; lock (_model) { consumerTag = _model.BasicConsume(queueName, autoAck, consumer); } void OnReceived(object sender, BasicDeliverEventArgs args) { try { var json = _encoding.GetString(args.Body); var message = JsonConvert.DeserializeObject <T>(json); callback?.Invoke(message, args.DeliveryTag); observer.OnNext(message); } catch (Exception ex) { _logger?.Error(ex, "Error during receiving a message via RabbitMQ"); if (!autoAck) { lock (_model) { _model.BasicAck(args.DeliveryTag, false); } } } } consumer.Received += OnReceived; return new DelegatingDisposable(_logger, () => { _logger?.Debug("Disposing consumer. queue-name={QueueName}", queueName); consumer.Received -= OnReceived; lock (_model) { _model.BasicCancel(consumerTag); } }); })); }
public ReaderResult Read(string resource, ILogger logger) { var result = new ReaderResult { Source = Source.File }; var queryStringIndex = resource.IndexOf('?'); if (queryStringIndex > 0) { result.Parameters = HttpUtility.ParseQueryString(resource.Substring(queryStringIndex+1)); resource = resource.Substring(0, queryStringIndex); } if (Path.HasExtension(resource)) { if (!Path.IsPathRooted(resource)) { resource = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, resource); } var fileInfo = new FileInfo(resource); try { result.Content = File.ReadAllText(fileInfo.FullName); } catch (Exception ex) { logger.Error("Can not read file. {0}", ex.Message); result.Source = Source.Error; } } else { logger.Error("Invalid file name: {0}. File must have an extension (e.g. xml, json, etc)", resource); result.Source = Source.Error; } return result; }
public void Close() { if ((_workers?.Length ?? 0) == 0) { return; } for (int i = 0; i < _workers.Length; i++) { try { if (_workers[i]?.ThreadState == ThreadState.Running) { _workers[i]?.Join(); } _workers[i] = null; //_logger?.Write($"Close thread {i}"); } catch (Exception ex) { _logger?.Error($"Close thread {i} failed", ex); } } }
private void AnnounceBlock(IBlock block) { if (block?.Header == null) { _logger?.Error("Block or block header is null."); return; } if (_peers == null || !_peers.Any()) { return; } try { Announce anc = new Announce { Height = (int)block.Header.Index, Id = ByteString.CopyFrom(block.GetHashBytes()) }; BroadcastMessage(AElfProtocolMsgType.Announcement, anc.ToByteArray()); } catch (Exception e) { _logger?.Error(e, "Error while announcing block."); } }
public async Task <ValidationResult> ValidatePolicy(string protocolMessageRedirectUri) { try { await _myService.ValidatePolicies(protocolMessageRedirectUri); return(new ValidationResult { AllPoliciesValid = true }); } catch (ServerException e) { return(HandleValidationResponse(e)); } catch (AggregateException ex) { if (ex.InnerException is ServerException e) { return(HandleValidationResponse(e)); } _logger?.Error(ex); } catch (Exception ex) { _logger?.Error(ex); } return(new ValidationResult { AllPoliciesValid = true }); }
private SchedulerHost(bool isPrimary, Func<Type,object> containerResolve, Func<IAppConfigRepository> repositoryResolve) { _traceSource = new VirtoCommerceTraceSource("VirtoCommerce.ScheduleService.Trace"); Trace.TraceInformation("SchedulerHost constructor started"); try { _jobScheduler = new JobScheduler(isPrimary, t => { object o; try { o = containerResolve(t); } catch (Exception ex) { _traceSource.Error(ex.ToString()); throw; } return (IJobActivity)o; }, repositoryResolve,_traceSource ); // reuse host container } catch (Exception ex) { _traceSource.Error(ex.ToString()); throw; } _traceSource.Info("SchedulerHost constructor finished"); }
public ReaderResult Read(string resource, ILogger logger) { var result = new ReaderResult { Source = Source.Url }; try { var uri = new Uri(resource); if (!string.IsNullOrEmpty(uri.Query)) { result.Parameters = HttpUtility.ParseQueryString(uri.Query.Substring(1)); } var request = (HttpWebRequest)WebRequest.Create(uri); request.Method = "GET"; using (var response = (HttpWebResponse)request.GetResponse()) { using (var responseStream = response.GetResponseStream()) { if (responseStream == null) { } else { if (response.StatusCode == HttpStatusCode.OK) { var reader = new StreamReader(responseStream); result.Content = reader.ReadToEnd(); } else { logger.Error("Response code was {0}. {1}", response.StatusCode, response.StatusDescription); result.Source = Source.Error; } } } } } catch (Exception ex) { logger.Error("Can not read url. {0}", ex.Message); result.Source = Source.Error; } return result; }
public void Close() { try { if (bindSocket != null) { bindSocket.Shutdown(SocketShutdown.Both); bindSocket.Close(); bindSocket = null; } } catch (ObjectDisposedException) { } catch (Exception ex) { logger?.Error("关闭客户端Socket连接出错[客户端" + this.ClientIpAndPort + "]", ex); } //finally //{ // try // { // ConnectionClosed?.Invoke(this, EventArgs.Empty); // } // catch (Exception ex) // { // logger?.Error("ServerConnection 发送连接关闭事件时出现异常", ex); // } //} }
void LogException(Exception ex) { if (Debugger.IsAttached) { Debugger.Break(); } SetProgress(ex.Message); try { _core.Logger.Error(this, ex.Message); } catch { } if (ex == null) { return; } int tries = 0; while (tries < 3) { tries++; try { var ravenClient = new RavenClient("https://[email protected]/1489869"); AsyncHelpers.RunSync(() => ravenClient.CaptureAsync(new SentryEvent(ex)), 7000); tries = 10; _logger?.Error("App", ex.Message); _logger?.Error("App", ex.StackTrace); } catch { AsyncHelpers.RunSync(async() => await Task.Delay(3000), 4000); } } }
protected void DeclareAndBind() { Dictionary <string, object> arguments = null; if (Configuration.QueueExpiration == TimeSpan.Zero) { Logger?.Verbose("Declaring queue. exchange-name={ExchangeName}, queue-name={QueueName}, channel-id={ChannelId}", Exchange, QueueName, ChannelId); } else { Logger?.Verbose("Declaring queue. exchange-name={ExchangeName}, queue-name={QueueName}, channel-id={ChannelId}, expiration={QueueExpiration}", Exchange, QueueName, ChannelId, Configuration.QueueExpiration); arguments = new Dictionary <string, object>() { ["x-expires"] = (int)Configuration.QueueExpiration.TotalMilliseconds }; } try { _model.QueueDeclare(QueueName, true, false, false, arguments); _model.QueueBind(QueueName, Exchange, RoutingKey); } catch (Exception ex) { Logger?.Error(ex, "Declaring queue failed - possible expiration change. exchange-name={ExchangeName}, queue-name={QueueName}, channel-id={ChannelId}", Exchange, QueueName, ChannelId); throw; } }
public bool Process(ILogger logger, IEnumerable<string> args, MetaProjectPersistence metaProject, ComponentsList components, string packagesOutputDirectory) { var nugetNamePattern = args.FirstOrDefault(); if (nugetNamePattern == null || nugetNamePattern.StartsWith("-") || nugetNamePattern.EndsWith("\"")) { logger.Error("No nuget pattern specified"); return true; } var nugetComponent = components.FindComponent<INugetSpec>(nugetNamePattern); if (nugetComponent == null) return true; logger.Info("== Nuget to add: {0}", nugetComponent); var componentNamePattern = args.LastOrDefault(); if (componentNamePattern == null || componentNamePattern.StartsWith("-") || componentNamePattern.EndsWith("\"")) { logger.Error("No component pattern specified"); return true; } var specificComponent = components.FindComponent<IProject>(componentNamePattern); if (specificComponent == null) return true; logger.Info("== Component to reference nuget: {0}", specificComponent); if (specificComponent == nugetComponent) { logger.Error("Nuget can't be added to itself"); return true; } specificComponent.AddNuget(logger, nugetComponent, components, packagesOutputDirectory); return true; }
public bool IsSqlServiceRunning(string sqlStoreConnectionString, ILogger logger = null) { if (string.IsNullOrEmpty(sqlStoreConnectionString)) { return(false); } try { var dbName = sqlStoreConnectionString.Split(';').ToList().FirstOrDefault(p => p.Contains("Database"))?.Split('=')[1]; var connection = new Npgsql.NpgsqlConnection(sqlStoreConnectionString); connection.Open(); var cmd = new Npgsql.NpgsqlCommand($"SELECT datname FROM pg_database where datname = '{dbName}';", connection); cmd.ExecuteReader(); connection.Close(); logger?.Information("SQL STORE WORKING."); } catch (Exception e) { logger?.Error("SQL STORE DOWN. SERVICE DISABLED AUTOMATICALLY."); logger?.Error(e, $"ERROR: {1}", e); return(false); } return(true); }
/// <summary> /// Initializes a new <see cref="DNXSolution"/>. /// </summary> /// <param name="path">Path of the directory that contains the project.json file.</param> /// <param name="logger">Logger to use. Must not be null.</param> /// <param name="projectFilter">Optional project filter.</param> public DNXSolution( string path, ILogger logger, Func<DNXProjectFile, bool> projectFilter = null ) { if( path == null ) throw new ArgumentNullException( nameof( path ) ); if( logger == null ) throw new ArgumentNullException( nameof( logger ) ); _logger = logger; _solutionDir = FindDirectoryFrom( path, ".git" ); if( _solutionDir == null ) _logger.Error( ".git directory not found." ); else { _solutionDir = _solutionDir.Remove( _solutionDir.Length - 4 ); _projects = Directory.EnumerateFiles( _solutionDir, "project.json", SearchOption.AllDirectories ) .Where( p => p.IndexOf( @"\bin\", _solutionDir.Length ) < 0 ) .Select( p => new DNXProjectFile( this, p ) ) .Where( p => projectFilter == null || projectFilter( p ) ) .ToArray(); var dup = _projects.GroupBy( p => p.ProjectName, StringComparer.OrdinalIgnoreCase ) .Where( g => g.Count() > 1 ); if( dup.Any() ) { _logger.Error( String.Format( "Duplicate names found for projects: {0}.", String.Join( ", ", dup.SelectMany( g => g.Select( p => p.RelativeProjectFilePath ) ) ) ) ); _projects = null; } } }
public virtual ApiResult Process(Action action, bool needRetry = false, int retryCount = 50, Func <Exception, string> getExceptionMessage = null) { ApiResult apiResult = null; getExceptionMessage = getExceptionMessage ?? GetExceptionMessage; do { try { action(); apiResult = new ApiResult(); needRetry = false; } catch (Exception ex) { if (!(ex is OptimisticConcurrencyException) || !needRetry) { var baseException = ex.GetBaseException(); if (baseException is DomainException) { var sysException = baseException as DomainException; apiResult = new ApiResult(sysException.ErrorCode, getExceptionMessage(sysException)); Logger?.Warn(ex); } else { apiResult = new ApiResult(ErrorCode.UnknownError, getExceptionMessage(ex)); Logger?.Error(ex); } needRetry = false; } } } while (needRetry && retryCount-- > 0); return(apiResult); }
public IOnPremiseConnectorRequest HandleRequest(IOnPremiseConnectorRequest request, HttpRequestMessage message, IPrincipal clientUser, out HttpResponseMessage immediateResponse) { immediateResponse = null; if (_requestInceptor == null) { return(request); } _logger?.Verbose("Handling request. request-id={RequestId}", request.RequestId); try { var interceptedRequest = CreateInterceptedRequest(request, message, clientUser); immediateResponse = _requestInceptor.OnRequestReceived(interceptedRequest); if (immediateResponse != null) { immediateResponse.RequestMessage = message; } return(interceptedRequest); } catch (Exception ex) { _logger?.Error(ex, "Error while executing the request interceptor. type-name={InterceptorType}, request-id={RequestId}", _requestInceptor?.GetType().Name, request.RequestId); } return(request); }
/// <summary> /// Set a <paramref name="document"/> on BLiP's Resources using a given <paramref name="id"/> /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id"></param> /// <param name="document"></param> /// <param name="logger"></param> /// <param name="expiration"></param> /// <param name="cancellationToken"></param> /// <returns><c>Command</c> with BLiP's response</returns> public async Task <Command> SetAsync <T>(string id, T document, ILogger logger, TimeSpan expiration = default, CancellationToken cancellationToken = default) where T : Document { try { var command = new Command() { Method = CommandMethod.Set, Uri = new LimeUri($"/resources/{id}"), Resource = document }; logger?.Information("[SetResource] Trying to set resource [{@document}] with id {@id}", document, id); var resourceResponse = await _sender.ProcessCommandAsync(command, cancellationToken); if (resourceResponse.Status != CommandStatus.Success) { throw new BlipHttpClientException("Failed to set resource on BLiP", resourceResponse); } logger?.Information("[SetResource] Successfully set resource with id {@id}", id); return(resourceResponse); } catch (BlipHttpClientException bex) { logger?.Error(bex, "Failed to set resource [{@document}] with id {@id} on BLiP", document, id); throw; } catch (Exception ex) { logger?.Error(ex, "Failed to set resource [{@document}] with id {@id} on BLiP", document, id); throw; } }
/// <summary> /// Recovers a given number of Resource IDs /// </summary> /// <param name="logger"></param> /// <param name="skip"></param> /// <param name="take"></param> /// <param name="cancellationToken"></param> /// <returns><c>DocumentCollection</c> with the resource IDs recovered</returns> public async Task <DocumentCollection> GetIdsAsync(ILogger logger, int skip = 0, int take = 100, CancellationToken cancellationToken = default(CancellationToken)) { try { var command = new Command() { Method = CommandMethod.Get, Uri = new LimeUri($"/resources") }; logger?.Information("[GetResource] Trying to get resource ids"); var resourceResponse = await _sender.ProcessCommandAsync(command, cancellationToken).ConfigureAwait(false); if (resourceResponse.Status != CommandStatus.Success) { throw new BlipHttpClientException("Failed to get resource IDs from BLiP", resourceResponse); } logger?.Information("[GetResource] Got resource ids", resourceResponse.Resource as DocumentCollection); return(resourceResponse.Resource as DocumentCollection); } catch (BlipHttpClientException bex) { logger?.Error(bex, "[GetResource] Failed to get resource ids"); throw; } catch (Exception ex) { logger?.Error(ex, "[GetResource] Failed to get resource ids"); throw; } }
private IEnumerable <RhinoTestCase> GetTests(string issueKey) { // get issue type var issueType = jiraClient.GetIssueType(issueKey); var capability = string.Empty; var typeEntry = capabilities.Where(i => $"{i.Value}".Equals(issueType, Compare)); if (typeEntry.Any()) { capability = $"{typeEntry.ElementAt(0).Key}"; } // get fetching method var method = GetType() .GetMethods(BindingFlags.Instance | BindingFlags.NonPublic) .Where(i => i.GetCustomAttribute <DescriptionAttribute>() != null) .FirstOrDefault(i => i.GetCustomAttribute <DescriptionAttribute>().Description.Equals(capability, Compare)); // exit conditions if (method == default) { logger?.Error($"Get-Tests -By [{issueType}] = false"); return(Array.Empty <RhinoTestCase>()); } // invoke and return results return(method.Invoke(this, new object[] { issueKey }) as IEnumerable <RhinoTestCase>); }
internal void PushDataToDataBase(IList <DataChunk> chunkList) { try { if ((chunkList?.Count() ?? 0) == 0) { return; } _log?.Verbose($"Saving {chunkList.Count()} records"); using (var cn = DbConnection()) { cn.Open(); using (var trans = cn.BeginTransaction()) { foreach (var chunk in chunkList) { cn.Query(@"INSERT INTO UserGets (VkontakteUserId, Timestamp, CompressedUserGet) VALUES (@VkontakteUserId, @Timestamp, @CompressedUserGet);", chunk); } trans.Commit(); } } } catch (Exception ex) { _log?.Error(ex, ex.Message); } }
/// <summary> /// Gets a Resource by its <paramref name="id"/> /// </summary> /// <typeparam name="T">Type of the resource to be recovered</typeparam> /// <param name="id">Unique id for the resource to be recovered</param> /// <param name="logger"></param> /// <param name="cancellationToken"></param> /// <returns>Recovered resource of type <c>T</c></returns> public async Task <T> GetAsync <T>(string id, ILogger logger, CancellationToken cancellationToken = default(CancellationToken)) where T : Document { try { var command = new Command() { Method = CommandMethod.Get, Uri = new LimeUri($"/resources/{id}") }; logger?.Information("[GetResource] Trying to get resource using id {@id}", id); var resourceResponse = await _sender.ProcessCommandAsync(command, cancellationToken).ConfigureAwait(false); if (resourceResponse.Status != CommandStatus.Success) { throw new BlipHttpClientException("Failed to get resource from BLiP", resourceResponse); } logger?.Information("[GetResource] Got resource using {@id}: {@resource}", id, resourceResponse.Resource as T); return(resourceResponse.Resource as T); } catch (BlipHttpClientException bex) { logger?.Error(bex, "[GetResource] Failed to get resource using {@id}", id); throw; } catch (Exception ex) { logger?.Error(ex, "[GetResource] Failed to get contact using {@id}", id); throw; } }
/// <summary> /// 开启服务 /// </summary> public void StartServer() { try { //实例化套接字 _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //创建网络端点,包括ip和port IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, _port); //将socket与本地端点绑定 _socket.Bind(endPoint); //设置最大监听数 _socket.Listen(maxListenConnect); _ip = endPoint.Address.ToString(); _serverLocation = string.Format("ws://{0}:{1}", _ip, _port); //logger?.Log(string.Format("聊天服务器启动。监听地址:{0}, 端口:{1}", endPoint.Address.ToString(), _port)); logger?.Info(string.Format("WebSocket服务器地址: ws://{0}:{1}", endPoint.Address.ToString(), _port)); //开始监听客户端 Thread thread = new Thread(ListenClientConnect); thread.Start(); } catch (Exception ex) { logger?.Error("启动监听出错", ex); } }
public bool IsNoSqlServiceRunning(string url, string username, string password, ILogger logger = null) { if (string.IsNullOrEmpty(url)) { return(false); } try { var store = new Raven.Client.Documents.DocumentStore { Urls = new[] { url } }; store.Initialize(); store.Maintenance.Server.Send(new GetBuildNumberOperation()); logger?.Information("NO-SQL STORE WORKING."); } catch (Exception e) { logger?.Error("DOCUMENT STORE DOWN. SERVICE DISABLED AUTOMATICALLY."); logger?.Error(e, $"ERROR: {1}", e); return(false); } return(true); }
/// <inheritdoc /> public void LogError <T>(T value) { if (IsErrorLoggingEnabled) { _logger?.Error(value); } }
/// <summary> /// /// </summary> /// <param name="dir"></param> /// <param name="log"></param> public static void Clear(this DirectoryInfo dir, ILogger log = null) { foreach (var file in dir.EnumerateFiles()) { try { file.Delete(); log?.Trace($"{file.FullName} deleted"); } catch (Exception) { log?.Error($"failed to delete {file.FullName}"); throw; } } foreach (var d in dir.EnumerateDirectories()) { int retryCount = 1; while (retryCount > 0) { d.Clear(log); try { d.Delete(); log?.Trace($"{d.FullName} deleted"); } catch (Exception) { log?.Error($"failed to delete {d.FullName}"); Thread.Sleep(2000); --retryCount; } } } }
public static Message parse(byte[] data, ILogger logger) { if (data.Length < 4) { logger.Error("[parse(byte[])] Really to short"); return null; } long len = uIntToLong(data[0], data[1], data[2], data[3]); //Message not fully read if (data.Length < len + 4) { logger.Error("[parse(byte[])] not enough data for len: " + len); return null; } //drops 4 bytes (length information) byte[] messageData = new byte[len]; Array.Copy(data, 4, messageData, 0, len); Message msg = deserializeBinary(messageData); msg._logger = logger; msg._data = data; return msg; }
internal async Task ConnectSocketAsync(IPAddress address, int port) { InitClient(); #if NET46 var connectTask = Task.Factory.FromAsync(_client.BeginConnect, _client.EndConnect, address, port, null); #else var connectTask = _client.ConnectAsync(address, port); #endif var finishedTask = await Task.WhenAny(connectTask, Task.Delay(_connectionTimeout)).ConfigureAwait(false); if (connectTask != finishedTask) // timed out { try { // close client immediately when failed to connect within timeout await DisconnectAsync().ConfigureAwait(false); } catch (Exception e) { _logger?.Error(e, $"Failed to close connect to the server {address}:{port}" + $" after connection timed out {_connectionTimeout.TotalMilliseconds}ms."); } throw new OperationCanceledException( $"Failed to connect to server {address}:{port} within {_connectionTimeout.TotalMilliseconds}ms."); } await connectTask.ConfigureAwait(false); }
private void CleanUp(CancellationToken cancellationToken) { var timeout = DateTime.UtcNow.Add(-_storagePeriod); _logger?.Verbose("Cleaning up old stored temporary data (files). timeout={CreationTimeout}", timeout); try { foreach (var fileName in Directory.GetFiles(_path)) { if (cancellationToken.IsCancellationRequested) { return; } try { if (File.GetCreationTimeUtc(fileName) < timeout) { File.Delete(fileName); } } catch (Exception ex) { _logger?.Error(ex, "File store cleanup process could not delete file. file-name={FileName}", fileName); } } } catch (Exception ex) { _logger?.Error(ex, "Error during file store cleanup process"); } }
internal async Task ConnectSocketAsync(IPAddress address, int port) { InitClient(); #if NET46 var connectTask = Task.Factory.FromAsync(_client.BeginConnect, _client.EndConnect, address, port, null); #else var connectTask = _client.ConnectAsync(address, port); #endif try { await connectTask .Timeout(_connectionTimeout, CancellationToken.None) .ConfigureAwait(false); } catch (Exception ex) when(ex is OperationCanceledException or TimeoutException) { try { // close client immediately when failed to connect within timeout await DisconnectAsync().ConfigureAwait(false); } catch (Exception e) { _logger?.Error(e, $"Failed to close connect to the server {address}:{port}" + $" after connection timed out {_connectionTimeout.TotalMilliseconds}ms."); } throw new OperationCanceledException( $"Failed to connect to server {address}:{port} within {_connectionTimeout.TotalMilliseconds}ms."); } }
public bool Process(ILogger logger, IEnumerable<string> args, MetaProjectPersistence metaProject, ComponentsList components, string packagesOutputDirectory) { // BIG TODO: reengineer command parsing var componentNamePattern = args.LastOrDefault(); if (componentNamePattern == null || componentNamePattern.StartsWith("-") || componentNamePattern.EndsWith("\"")) { logger.Error("No component pattern specified"); return true; } string tags = args.ParseStringParameter("tags"); string licenseUrl = args.ParseStringParameter("licenseUrl"); string projectUrl = args.ParseStringParameter("projectUrl"); string iconUrl = args.ParseStringParameter("iconUrl"); string copyright = args.ParseStringParameter("copyright"); bool requireLicenseAcceptance = args.Contains("-r"); if (licenseUrl == null && requireLicenseAcceptance) { logger.Error("Requiring license acceptance demands a license url"); return true; } var specificComponent = components.FindComponent<IProject>(componentNamePattern, c => c.CanBecomeNugget); if (specificComponent == null) return true; if (specificComponent.PromoteToNuget(logger, packagesOutputDirectory, tags, licenseUrl, projectUrl, iconUrl, copyright, requireLicenseAcceptance) != null) ScanCommand.Rescan(logger, metaProject, components); return true; }
public static bool VerifyNamespaces(this Topology topology, ILogger logger, string prefix) { if (string.IsNullOrEmpty(prefix)) return true; var exchanges = topology.Exchanges.Where(e => !Matches(e.Name, prefix)).ToList(); var queues = topology.Queues.Where(q => !Matches(q.Name, prefix)).ToList(); if (exchanges.Count > 0 && queues.Count > 0) { logger.Error(Strings.LogInvalidNamespacesExchangeQueue, prefix, exchanges.Select(e => e.Name).ToArray(), queues.Select(q => q.Name).ToArray()); return false; } if (exchanges.Count > 0) { logger.Error(Strings.LogInvalidNamespacesExchange, prefix, exchanges.Select(e => e.Name).ToArray()); return false; } // ReSharper disable once InvertIf - hurts readability in this case in my opinion if (queues.Count > 0) { logger.Error(Strings.LogInvalidNamespacesQueue, prefix, queues.Select(q => q.Name).ToArray() ); return false; } return true; }
private async Task <TokenResponse> GetAuthorizationTokenAsync() { var client = new OAuth2Client(new Uri(Uri, "/token")); while (!_stopRequested) { try { _logger?.Verbose("Requesting authorization token. relay-server={RelayServerUri}, relay-server-connection-instance-id={RelayServerConnectionInstanceId}", Uri, RelayServerConnectionInstanceId); var response = await client.RequestResourceOwnerPasswordAsync(_userName, _password).ConfigureAwait(false); if (response.IsError) { throw new AuthenticationException(response.HttpErrorReason ?? response.Error); } _logger?.Verbose("Received token. relay-server={RelayServerUri}, relay-server-connection-instance-id={RelayServerConnectionInstanceId}", Uri, RelayServerConnectionInstanceId); return(response); } catch (Exception ex) { var randomWaitTime = GetRandomWaitTime(); _logger?.Error(ex, "Could not authenticate with RelayServer - re-trying in {RetryWaitTime} seconds. relay-server={RelayServerUri}, relay-server-connection-instance-id={RelayServerConnectionInstanceId}", randomWaitTime.TotalSeconds, Uri, RelayServerConnectionInstanceId); await Task.Delay(randomWaitTime, _cts.Token).ConfigureAwait(false); } } return(null); }
private Assembly LoadAssembly() { if (_configuration.CustomCodeAssemblyPath == null) { return(null); } try { _logger?.Debug("Trying to load custom code assembly. assembly-path={CustomCodeAssemblyPath}", _configuration.CustomCodeAssemblyPath); var assembly = Assembly.LoadFrom(_configuration.CustomCodeAssemblyPath); _logger?.Information("Successfully loaded custom code assembly from {CustomCodeAssemblyPath}", _configuration.CustomCodeAssemblyPath); return(assembly); } catch (Exception ex) { _logger?.Error(ex, "There was an error loading the custom code assembly. assembly-path={CustomCodeAssemblyPath}", _configuration.CustomCodeAssemblyPath); _configuration.CustomCodeAssemblyPath = null; _assembly = null; } return(null); }
public PostImporter() { _checkpoint = new FileCheckpoint("postsLoaded"); _logger = new EventStore.ClientAPI.Common.Log.ConsoleLogger(); var _connectionSettings = ConnectionSettings.Create() .UseConsoleLogger() .KeepReconnecting() .KeepRetrying() .OnConnected(_ => _logger.Info("Event Store Connected")) .OnDisconnected(_ => _logger.Error("Event Store Disconnected")) .OnReconnecting(_ => _logger.Info("Event Store Reconnecting")) .OnErrorOccurred((c, e) => _logger.Error(e, "Event Store Error :(")); _connection = EventStoreConnection.Create(_connectionSettings, new IPEndPoint(IPAddress.Parse("192.81.222.61"), 1113)); _connection.Connect(); ThreadPool.SetMaxThreads(20, 20); ThreadPool.SetMinThreads(20, 20); //ServicePointManager.DefaultConnectionLimit = 1000; ServicePointManager.Expect100Continue = false; ServicePointManager.ServerCertificateValidationCallback = Validator; //ServicePointManager.EnableDnsRoundRobin = false; //ServicePointManager.DnsRefreshTimeout = Int32.MaxValue; }
public static bool ExecuteTool(ILogger logger, string toolName, string arguments, string workingDirectory, Action<ILogger, string> processToolOutput = null) { try { if (processToolOutput == null) processToolOutput = (l, s) => l.Info(s); Process p = new Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardError = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.FileName = toolName.FindInPathEnvironmentVariable(); p.StartInfo.Arguments = arguments; p.StartInfo.WorkingDirectory = workingDirectory; p.StartInfo.CreateNoWindow = true; if (logger != null) { p.OutputDataReceived += (object sender, DataReceivedEventArgs e) => processToolOutput(logger, e.Data); p.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => logger.Error(e.Data); } var debugLine = "Executing: " + p.StartInfo.FileName + " " + arguments; logger.Debug(debugLine); p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); p.WaitForExit(); return p.ExitCode == 0; } catch (Exception e) { logger.Error(e); } return false; }
public HttpResponseMessage ConvertToErrorResponse(Exception exception, HttpRequestMessage request) { if (exception != null) { _logger?.Error(exception); } return(null); }
public void Execute(ILogger logger) { logger.Info("AdoInspector: Starting to replace DbProviderFactory"); //This forces the creation try { DbProviderFactories.GetFactory("Anything"); } catch (ArgumentException ex) { } //Find the registered providers var table = Support.FindDbProviderFactoryTable(); //Run through and replace providers foreach (var row in table.Rows.Cast<DataRow>().ToList()) { DbProviderFactory factory; try { factory = DbProviderFactories.GetFactory(row); logger.Info("AdoInspector: Successfully retrieved factory - {0}", row["Name"]); } catch (Exception) { logger.Error("AdoInspector: Failed to retrieve factory - {0}", row["Name"]); continue; } //Check that we haven't already wrapped things up if (factory is GlimpseDbProviderFactory) { logger.Error("AdoInspector: Factory is already wrapped - {0}", row["Name"]); continue; } var proxyType = typeof(GlimpseDbProviderFactory<>).MakeGenericType(factory.GetType()); var newRow = table.NewRow(); newRow["Name"] = row["Name"]; newRow["Description"] = row["Description"]; newRow["InvariantName"] = row["InvariantName"]; newRow["AssemblyQualifiedName"] = proxyType.AssemblyQualifiedName; table.Rows.Remove(row); table.Rows.Add(newRow); logger.Info("AdoInspector: Successfully replaced - {0}", newRow["Name"]); } logger.Info("AdoInspector: Finished replacing DbProviderFactory"); }
public static void Run(AssetItem assetItem, ILogger log, AssetAnalysisParameters parameters) { if (assetItem == null) throw new ArgumentNullException(nameof(assetItem)); if (log == null) throw new ArgumentNullException(nameof(log)); if (parameters == null) throw new ArgumentNullException(nameof(parameters)); if (assetItem.Package == null) { throw new InvalidOperationException("AssetItem must belong to an existing package"); } var package = assetItem.Package; // Check that there is no duplicate in assets if (package.Session != null) { var packages = package.FindDependencies(); foreach (var otherPackage in packages) { var existingAsset = otherPackage.Assets.Find(assetItem.Id); if (existingAsset != null) { log.Error("Assets [{0}] with id [{1}] from Package [{2}] is already loaded from package [{3}]", existingAsset.FullPath, existingAsset.Id, package.FullPath, existingAsset.Package.FullPath); } else { existingAsset = otherPackage.Assets.Find(assetItem.Location); if (existingAsset != null) { log.Error("Assets [{0}] with location [{1}] from Package [{2}] is already loaded from package [{3}]", existingAsset.FullPath, existingAsset.Location, package.FullPath, existingAsset.Package.FullPath); } } } } var assetReferences = AssetReferenceAnalysis.Visit(assetItem.Asset); if (package.Session != null && parameters.IsProcessingAssetReferences) { UpdateAssetReferences(assetItem, assetReferences, log, parameters); } // Update paths for asset items if (parameters.IsProcessingUPaths) { // Find where this asset item was previously stored (in a different package for example) CommonAnalysis.UpdatePaths(assetItem, assetReferences.Where(link => link.Reference is UPath), parameters); // Source hashes are not processed by analysis, we need to manually indicate them to update SourceHashesHelper.UpdateUPaths(assetItem.Asset, assetItem.FullPath.GetParent(), parameters.ConvertUPathTo); } }
public Source Detect(string resource, ILogger logger) { if (resource == null) { logger.Error("The configuration passed in is null."); return Source.Error; } resource = resource.Trim(); if (resource == string.Empty) { logger.Error("The configuration passed in is empty"); return Source.Error; } if (resource.StartsWith("<", StringComparison.Ordinal)) return Source.Xml; if (resource.StartsWith("{", StringComparison.Ordinal)) return Source.Json; try { return new Uri(resource).IsFile ? Source.File : Source.Url; } catch (Exception) { var queryStringIndex = resource.IndexOf('?'); if (queryStringIndex > 0) { resource = resource.Substring(0, queryStringIndex); } var fileName = Path.GetFileName(resource); if (fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { logger.Error("Your configuration contains invalid characters"); return Source.Error; } if (!Path.HasExtension(resource)) { logger.Error("Your file needs an extension."); return Source.Error; } if (!Path.IsPathRooted(resource)) { resource = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, resource); } if (new FileInfo(resource).Exists) { return Source.File; } logger.Error("This source detector cannot detect your configuration source. The configuration you passed in does not appear to be JSON, XML, a Uri, or a file name."); return Source.Error; } }
internal static void LogResult(JobResult result, ILogger logger, string jobName) { if (result != null) { if (result.IsCancelled) logger.Warn(result.Error, "Job run \"{0}\" cancelled: {1}", jobName, result.Message); else if (!result.IsSuccess) logger.Error(result.Error, "Job run \"{0}\" failed: {1}", jobName, result.Message); else if (!String.IsNullOrEmpty(result.Message)) logger.Info("Job run \"{0}\" succeeded: {1}", jobName, result.Message); else logger.Trace("Job run \"{0}\" succeeded.", jobName); } else { logger.Error("Null job run result for \"{0}\".", jobName); } }
public async static Task<bool> Log( string storageAccountName, string storageAccountKey, string contactTableName, string name, string email, string phone, string department, string message, string result, ILogger logger = null) { DateTime dt = DateTime.UtcNow; try { StorageCredentials storageCredentials = new StorageCredentials(storageAccountName, storageAccountKey); CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true); CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); tableClient.DefaultRequestOptions.RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(1), 10); CloudTable table_Contact = tableClient.GetTableReference(contactTableName); await table_Contact.CreateIfNotExistsAsync(); ContactLog entity = new ContactLog((DateTime.MaxValue - dt).ToString()); entity.DT = dt; entity.MachineName = Environment.MachineName; entity.Application = Assembly.GetEntryAssembly().GetName().Name; entity.Name = name; entity.Email = email; entity.Phone = phone; entity.Department = department; entity.Message = message; entity.Result = result; TableResult operationResult = await table_Contact.ExecuteAsync(TableOperation.Insert(entity)); if (operationResult.HttpStatusCode != 204 && logger != null) { logger.Error(operationResult.HttpStatusCode.ToString() + " " + operationResult.Result.ToString()); } return operationResult.HttpStatusCode == 204 ? true : false; } catch (Exception ex) { if (logger != null) { logger.Error(ex.ToString()); } Console.WriteLine(dt.ToString() + " " + Environment.MachineName + ":" + Assembly.GetEntryAssembly().GetName().Name + ": " + ex.ToString()); return false; } }
public virtual void Execute(JobExecutionContext context) { Logger = new ServiceLogger(context.JobDetail.Name); if (Monitor.TryEnter(SYNC_LOCK, 3000) == false) { Logger.Debug("上一次调度未完成,本次调度放弃运行"); return; } try { Logger.Info("调度开始执行"); InnerExecute(context); Logger.Info("调度正常结束"); } catch (Exception e) { Logger.Error("调度执行时发生异常: " + e); } finally { Monitor.Exit(SYNC_LOCK); } }
public static async Task<bool> CompleteEventPostAsync(this IFileStorage storage, string path, string projectId, DateTime created, ILogger logger, bool shouldArchive = true) { if (String.IsNullOrEmpty(path)) return false; await storage.SetNotActiveAsync(path, logger).AnyContext(); // don't move files that are already in the archive if (path.StartsWith("archive")) return true; string archivePath = $"archive\\{projectId}\\{created.ToString("yy\\\\MM\\\\dd")}\\{Path.GetFileName(path)}"; try { if (shouldArchive && !await storage.ExistsAsync(archivePath)) { if (!await storage.RenameFileAsync(path, archivePath).AnyContext()) return false; } else { if (!await storage.DeleteFileAsync(path).AnyContext()) return false; } } catch (Exception ex) { logger.Error(ex, "Error archiving event post data \"{0}\".", path); return false; } return true; }
/// <summary> /// Generates the URI template. /// </summary> /// <param name="resource">The resource.</param> /// <param name="baseUri">The base URI.</param> /// <param name="logger">The logger.</param> /// <returns>A Uri template a client can expand to invoke a resource.</returns> /// <exception cref="System.ArgumentNullException">Throws and exception if <paramref name="resource"/> or <paramref name="logger"/> is <c>null</c>.</exception> public string GenerateUriTemplate(IResource resource, string baseUri, ILogger logger) { if (resource == null) { throw new ArgumentNullException("resource"); } if (logger == null) { throw new ArgumentNullException("logger"); } string result = null; try { result = GenerateUriTemplate(resource.Name, baseUri, resource.Parameters, logger); } catch (Exception exception) { logger.Error(Resources.GenerateUriExecutionError, exception, GetType()); } if (result != null) { return result; } return string.Empty; }
public IEnumerable<ChannelInfo> GetChannels(Stream stream, IJsonSerializer json,ILogger logger) { var root = json.DeserializeFromStream<RootObject>(stream); if (root.channelsJSONObject.rtn != null && root.channelsJSONObject.rtn.Error) { logger.Error(root.channelsJSONObject.rtn.Message ?? "Failed to download channel information."); throw new ApplicationException(root.channelsJSONObject.rtn.Message ?? "Failed to download channel information."); } if (root.channelsJSONObject != null && root.channelsJSONObject.Channels != null) { UtilsHelper.DebugInformation(logger,string.Format("[NextPvr] ChannelResponse: {0}", json.SerializeToString(root))); return root.channelsJSONObject.Channels.Select(i => new ChannelInfo { Name = i.channel.channelName, Number = i.channel.channelFormattedNumber.ToString(_usCulture), Id = i.channel.channelOID.ToString(_usCulture), ImageUrl = string.IsNullOrEmpty(i.channel.channelIcon) ? null : (_baseUrl + "/" + i.channel.channelIcon), HasImage = !string.IsNullOrEmpty(i.channel.channelIcon) }); } return new List<ChannelInfo>(); }
public void Initialize(ILogger logger, ICommandController commandController, ITaskController taskController, TaskResultView taskResultView) { if (logger == null) throw new ArgumentNullException("logger"); if (commandController == null) throw new ArgumentNullException("commandController"); if (taskController == null) throw new ArgumentNullException("taskController"); if (taskResultView == null) throw new ArgumentNullException("taskResultView"); this.logger = logger; this.commandController = commandController; this.taskController = taskController; this.taskResultView = taskResultView; try { commandItemContainer.ItemsSource = commandController.Commands; } catch (Exception ex) { logger.Error(" CommandView.Initialize", ex); } }
public async static void Log( string storageAccountName, string storageAccountKey, string exceptionsTableName, string exceptionSource, string exceptionDescription, ILogger logger = null) { DateTime dt = DateTime.UtcNow; try { StorageCredentials storageCredentials = new StorageCredentials(storageAccountName, storageAccountKey); CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true); CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); tableClient.DefaultRequestOptions.RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(1), 10); CloudTable table_AppExceptions = tableClient.GetTableReference(exceptionsTableName); await table_AppExceptions.CreateIfNotExistsAsync(); ExceptionLog entity = new ExceptionLog((DateTime.MaxValue - dt).ToString()); entity.DT = dt; entity.MachineName = Environment.MachineName; entity.Application = Assembly.GetEntryAssembly().GetName().Name; entity.Source = exceptionSource; entity.Description = exceptionDescription; await table_AppExceptions.ExecuteAsync(TableOperation.Insert(entity)); } catch (System.Exception ex) { if (logger != null) { logger.Error(exceptionSource + ":" + exceptionDescription + ": " + ex.ToString()); } Console.WriteLine(dt.ToString() + " " + Environment.MachineName + ":" + Assembly.GetEntryAssembly().GetName().Name + ":" + exceptionSource + ":" + exceptionDescription + ": " + ex.ToString()); } }
private bool ProcessMoved(RemotingPackageManifestEntry action, ILogger logger) { var database = Factory.GetDatabase(action.Database); Assert.IsNotNull(database, "Invalid database " + action.Database); var currentItem = database.GetItem(new ID(action.ItemId)); if (currentItem == null) { logger.Error("Cannot move {0} because it has been deleted.".FormatWith(action.ItemPath)); return false; } var newParentPath = action.ItemPath.Substring(0, action.ItemPath.LastIndexOf('/')); var newParent = database.GetItem(newParentPath); if (newParent == null) { logger.Error("Cannot move {0} because the new parent path {1} is not a valid item.".FormatWith(action.OldItemPath, newParentPath)); return false; } currentItem.MoveTo(newParent); logger.Info("[M] {0} to {1} [remoting]".FormatWith(new SitecoreSourceItem(currentItem).DisplayIdentifier, new SitecoreSourceItem(newParent).DisplayIdentifier)); return true; }
public static Container CreateContainer(ILoggerFactory loggerFactory, ILogger logger, bool includeInsulation = true) { var container = new Container(); container.Options.AllowOverridingRegistrations = true; Bootstrapper.RegisterServices(container, loggerFactory); if (!includeInsulation) return container; Assembly insulationAssembly = null; try { insulationAssembly = Assembly.Load("Samples.Insulation"); } catch (Exception ex) { logger.Error().Message("Unable to load the insulation assembly.").Exception(ex).Write(); } if (insulationAssembly != null) { var bootstrapperType = insulationAssembly.GetType("Samples.Insulation.Bootstrapper"); if (bootstrapperType == null) return container; bootstrapperType.GetMethod("RegisterServices", BindingFlags.Public | BindingFlags.Static).Invoke(null, new object[] { container, loggerFactory }); } return container; }
public bool Process(ILogger logger, IEnumerable<string> args, MetaProjectPersistence metaProject, ComponentsList components, string packagesOutputDirectory) { var destination = args.ParseStringParameter("to", metaProject.LastPublishedTo); if (string.IsNullOrWhiteSpace(destination)) return true; if (!Directory.Exists(destination)) { logger.Error("Could not find destination folder: '{0}'", destination); return true; } metaProject.LastPublishedTo = destination; var componentNamePattern = args.FirstOrDefault(s => !s.StartsWith("-")) ?? ".*"; var list = components.FilterBy(componentNamePattern, nugets: true); var listIsOk = true; foreach (var component in list) if (component is INugetSpec) if (!BuildHelper.PackageExists(component as INugetSpec, packagesOutputDirectory)) { listIsOk = false; logger.ErrorDetail("There is no built package for nuget '{0}'", component.Name); } if (listIsOk) foreach (var component in list) if (component is INugetSpec) BuildHelper.CopyIfNew(logger, component as INugetSpec, packagesOutputDirectory, destination); return true; }
protected virtual string GetUploadFolder() { string folder = System.Configuration.ConfigurationManager.AppSettings["UploadFolder"]; if (string.IsNullOrEmpty(folder)) folder = "Upload"; if (Directory.Exists(folder) == true) { } else { //根目录,相对位置; folder = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(@HostingEnvironment.ApplicationPhysicalPath), "BackUp"); try { Directory.CreateDirectory(folder); } catch (Exception ex) { logger = LogManager.GetLogger("创建备份目录"); logger.Error("创建备份出错:" + ex.ToString()); } } return folder; }
public GoogleOAuth2Authorization(ILogger log) : base(log) { Func<string, string> getConfigVal = (value) => (ConfigurationManager.AppSettings.Get(value) ?? WebConfigurationManager.AppSettings.Get(value) ?? KeyStorage.Get(value)); try { ClientID = getConfigVal("mail.googleClientID"); ClientSecret = getConfigVal("mail.googleClientSecret"); if (String.IsNullOrEmpty(ClientID)) throw new ArgumentNullException("ClientID"); if (String.IsNullOrEmpty(ClientSecret)) throw new ArgumentNullException("ClientSecret"); } catch (Exception ex) { log.Error("GoogleOAuth2Authorization() Exception:\r\n{0}\r\n", ex.ToString()); } RedirectUrl = "urn:ietf:wg:oauth:2.0:oob"; ServerDescription = new AuthorizationServerDescription { AuthorizationEndpoint = new Uri("https://accounts.google.com/o/oauth2/auth?access_type=offline"), TokenEndpoint = new Uri("https://accounts.google.com/o/oauth2/token"), ProtocolVersion = DotNetOpenAuth.OAuth2.ProtocolVersion.V20, }; Scope = new List<string> { "https://mail.google.com/" }; }
public static bool IsAllowedPath(ILogger log, string path, IEnumerable<Share> shares) { try { // non-existent files don't yield results anyway, we might need to have them existent for the checks here later if (!File.Exists(path) && !Directory.Exists(path)) return false; // do not allow non-rooted parts for security if (!Path.IsPathRooted(path)) return false; // only check on directory if (File.Exists(path)) path = Path.GetDirectoryName(path); foreach (Share share in shares) { if (!Directory.Exists(share.Path)) continue; if (IsSubdir(share.Path, path)) return true; } } catch (Exception e) { log.Error(String.Format("Exception during IsAllowedPath with path = {0}", path), e); } return false; }
private static Command GetCommand(string[] args, ILogger logger) { try { var parser = new CommandLineParser<RasDialOptions>(); var options = parser.Parse(args); var commandType = typeof(Command).Assembly .GetTypes() .SingleOrDefault(x => x.Name.Equals(options.Action, StringComparison.InvariantCultureIgnoreCase)); if (commandType == null) { throw new ArgumentException(string.Format("No action found for {0}.", options.Action)); } return (Command)Activator.CreateInstance(commandType, new object[] { options, logger }); } catch (Exception e) { logger.Error("Failed to find command.", e); } return null; }