public static void Error(Exception exception)
 {
     if (exception != null)
     {
         ErrorAction?.Invoke(exception.ToString());
     }
 }
Пример #2
0
 public SmartFormatter(ErrorAction errorAction = ErrorAction.Ignore)
 {
     Parser              = new Parser(errorAction);
     ErrorAction         = errorAction;
     SourceExtensions    = new List <ISource>();
     FormatterExtensions = new List <IFormatter>();
 }
Пример #3
0
        public AuthOutputDto Register(UsersInputDto user)
        {
            User userToRegister = new User();

            foreach (PropertyInfo propertyInfo in user.GetType().GetProperties())
            {
                string propertyName = propertyInfo.Name;
                string value        = (string)user.GetType().GetProperty(propertyName).GetValue(user, null);

                if (value == "" || value == null)
                {
                    ErrorAction error = new ErrorAction(1, Messages.Messages.CampoObrigatorio.Replace("{0}", propertyName));
                    throw error;
                }

                userToRegister.GetType().GetProperty(propertyName).SetValue(userToRegister, value);
            }

            userToRegister.Password = _cryptyService.GenerateHashKey(user.Password);

            User userData = _authRepository.Register(userToRegister);

            AuthInputDto login = new AuthInputDto {
                Email = userData.Email, Password = user.Password
            };

            return(this.Login(login));
        }
        public void SkipTest(int failedAttempts, ErrorAction expectedAction)
        {
            var action = _policy.HandleError(new InboundMessage {
                Message = new TestEventOne(), FailedAttempts = failedAttempts
            }, new Exception("test"));

            action.Should().Be(expectedAction);
        }
Пример #5
0
 public void Validate(bool everyDataPoint, ErrorAction action = ErrorAction.ShowErrorOnPlot)
 {
     ValidateEveryPoint    = everyDataPoint;
     ValidationErrorAction = action;
     if (everyDataPoint)
     {
         Debug.WriteLine("WARNING: every data point will be validated on each render, reducing performance");
     }
 }
Пример #6
0
        public override void Begin(Func <CancellationToken, Task> action = null, Action <Exception> onError = null)
        {
            ThrowIfDisposed();

            lock (Sync)
            {
                if (IsActive)
                {
                    return;
                }

                IsActive = true;

                Cts?.Dispose();

                Cts = new CancellationTokenSource();
            }

            if (action != null)
            {
                Action = action;
            }

            if (onError != null)
            {
                ErrorAction = onError;
            }

            Task = Task.Run(async() =>
            {
                while (!Cts.IsCancellationRequested)
                {
                    try { await Action(Cts.Token).ConfigureAwait(false); }
                    catch (OperationCanceledException) { /* ignored */ }
                    catch (Exception e)
                    {
                        if (!Cts.IsCancellationRequested)
                        {
                            try { ErrorAction?.Invoke(e); }
                            catch { /* ignored */ }

                            OnError(e);
                        }
                    }

                    try
                    {
                        if (!Cts.IsCancellationRequested)
                        {
                            await DelayAsync(Cts.Token).ConfigureAwait(false);
                        }
                    }
                    catch { /* ignored */ }
                }
            });
        }
Пример #7
0
 public ErrorHandler(IWebContext context, ISecurityManager security, InstallationManager installer,
     EngineSection config, EditSection editConfig)
     : this(context, security, installer)
 {
     this.editConfig = editConfig;
     action = config.Errors.Action;
     mailTo = config.Errors.MailTo;
     mailFrom = config.Errors.MailFrom;
     maxErrorReportsPerHour = config.Errors.MaxErrorReportsPerHour;
     handleWrongClassException = config.Errors.HandleWrongClassException;
     mailSender = new SmtpMailSender();
 }
Пример #8
0
        public void SkipTest(int failedAttempts, ErrorAction expectedAction)
        {
            var action = _policy.HandleError(new[]
            {
                new InboundMessage(
                    new byte[1],
                    new[] { new MessageHeader(MessageHeader.FailedAttemptsKey, failedAttempts.ToString()) },
                    null, TestEndpoint.GetDefault(), true)
            }, new Exception("test"));

            action.Should().Be(expectedAction);
        }
Пример #9
0
 public ErrorHandler(IWebContext context, ISecurityManager security, InstallationManager installer,
                     EngineSection config, EditSection editConfig)
     : this(context, security, installer)
 {
     this.editConfig           = editConfig;
     action                    = config.Errors.Action;
     mailTo                    = config.Errors.MailTo;
     mailFrom                  = config.Errors.MailFrom;
     maxErrorReportsPerHour    = config.Errors.MaxErrorReportsPerHour;
     handleWrongClassException = config.Errors.HandleWrongClassException;
     mailSender                = new SmtpMailSender();
 }
Пример #10
0
        public ErrorHandler(IErrorNotifier notifier, IWebContext context, InstallationManager installer, IMailSender mailSender, 
            ConfigurationManagerWrapper configuration)
        {
            this.notifier = notifier;
            this.context = context;
            this.installer = installer;
            this.mailSender = mailSender;

            beginUrl = configuration.Sections.Management.Installer.WelcomeUrl;
            action = configuration.Sections.Engine.Errors.Action;
            mailTo = configuration.Sections.Engine.Errors.MailTo;
            mailFrom = configuration.Sections.Engine.Errors.MailFrom;
            maxErrorReportsPerHour = configuration.Sections.Engine.Errors.MaxErrorReportsPerHour;
            handleWrongClassException = configuration.Sections.Engine.Errors.HandleWrongClassException;
            mailSender = new SmtpMailSender();
        }
Пример #11
0
        public ErrorHandler(IErrorNotifier notifier, IWebContext context, InstallationManager installer, IMailSender mailSender,
                            ConfigurationManagerWrapper configuration)
        {
            this.notifier   = notifier;
            this.context    = context;
            this.installer  = installer;
            this.mailSender = mailSender;

            beginUrl = configuration.Sections.Management.Installer.WelcomeUrl;
            action   = configuration.Sections.Engine.Errors.Action;
            mailTo   = configuration.Sections.Engine.Errors.MailTo;
            mailFrom = configuration.Sections.Engine.Errors.MailFrom;
            maxErrorReportsPerHour    = configuration.Sections.Engine.Errors.MaxErrorReportsPerHour;
            handleWrongClassException = configuration.Sections.Engine.Errors.HandleWrongClassException;
            mailSender = new SmtpMailSender();
        }
        /// <inheritdoc />
        /// <summary>
        /// Determines whether the specified line is a match for this command type.
        /// </summary>
        /// <param name="line">The line.</param>
        /// <returns>
        ///   <c>true</c> if the specified line is match; otherwise, <c>false</c>.
        /// </returns>
        public bool IsMatch(string line)
        {
            var m = this.commandRegex.Match(line);

            if (!m.Success)
            {
                return(false);
            }

            var action = m.Groups["action"].Value;

            // Will throw if action value isn't an enum name
            this.ErrorAction = (ErrorAction)Enum.Parse(typeof(ErrorAction), action, true);

            return(true);
        }
Пример #13
0
        public static void LogError(Exception ex, ErrorAction actionTaken, object parameters)
        {
            try
            {
                var errorDetails = Create(ex, ex.Message, ex.StackTrace, actionTaken, parameters);

                LogToNewRelic(errorDetails);
            }
            catch (Exception exception)
            {
                Trace.TraceError(
                        string.Format(
                                "[{0}] Error: Logging to NewRelic Failed. {1}",
                                "NewRelicLogger",
                                exception.Message));
            }
        }
Пример #14
0
        public static void LogError(Exception ex, ErrorAction actionTaken, object parameters)
        {
            try
            {
                var errorDetails = Create(ex, ex.Message, ex.StackTrace, actionTaken, parameters);

                LogToNewRelic(errorDetails);
            }
            catch (Exception exception)
            {
                Trace.TraceError(
                    string.Format(
                        "[{0}] Error: Logging to NewRelic Failed. {1}",
                        "NewRelicLogger",
                        exception.Message));
            }
        }
Пример #15
0
        public ErrorHandler(IErrorNotifier notifier, IWebContext context, InstallationManager installer, IExceptionFilter exceptionFilter, IMailSender mailSender,
                            ConfigurationManagerWrapper configuration)
        {
            this.notifier        = notifier;
            this.context         = context;
            this.installer       = installer;
            this.exceptionFilter = exceptionFilter;
            this.mailSender      = mailSender;

            beginUrl = configuration.Sections.Management.Installer.WelcomeUrl;
            action   = configuration.Sections.Engine.Errors.Action;
            mailTo   = configuration.Sections.Engine.Errors.MailTo;
            mailFrom = configuration.Sections.Engine.Errors.MailFrom;
            maxErrorReportsPerHour    = configuration.Sections.Engine.Errors.MaxErrorReportsPerHour;
            handleWrongClassException = configuration.Sections.Engine.Errors.HandleWrongClassException;
            handleSqlException        = configuration.Sections.Engine.Errors.SqlExceptionHandling == ExceptionResolutionMode.RefreshGet;
        }
 private void InitSessionFormsAuthentication(ActionExecutingContext filterContext)
 {
     ActionStartTime            = DateTime.Now;
     ViewData["ExecutingDate"]  = DateTime.Now.ToString("yy-MM-dd hh:mm:ss");
     ViewData["ControllerName"] = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
     ViewData["ActionName"]     = filterContext.ActionDescriptor.ActionName;
     ViewData["ActionParam"]    = filterContext.ActionDescriptor.GetParameters();
     SetUserItem();
     errorAction = new ErrorAction()
     {
         Request = Request, TempData = TempData, userItem = userItem, Session = Session
     };
     if (errorAction.NotLoginActionInfo() != null)
     {
         FormsAuthentication.SignOut();
     }
 }
Пример #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ViewModelError"/> class.
        /// </summary>
        /// <param name="title">The title.</param>
        /// <param name="description">The description.</param>
        /// <param name="errorAction">The error action.</param>
        /// <param name="errorSeverity">The error severity.</param>
        /// <param name="errorItems">The error items.</param>
        /// <param name="exception">The exception.</param>
        /// <param name="viewModelType"></param>
        /// <param name="errors"></param>
        public ViewModelError(string title, string description, ErrorAction errorAction,
                              ErrorSeverity errorSeverity, List <string> errorItems = null, Exception exception = null, string viewModelType = "", ReadOnlyDictionary <string, ReadOnlyCollection <string> > errors = null)
        {
            if (exception != null && exception.HasInnerExceptions())
            {
                description = exception.Message == description?exception.GetInnermostExceptionMessage() : description;
            }

            Title         = title;
            Description   = description;
            Action        = errorAction;
            Severity      = errorSeverity;
            ErrorItems    = errorItems;
            Exception     = exception;
            ViewModelType = viewModelType;
            Errors        = errors;
        }
        public static void Initialize(ICurrentEnvironment env)
        {
            Stream    defaultConfigStream = Assembly.GetExecutingAssembly().LoadStream("Chrome.BookmarkSearch.default.json");
            SetRecord defaultConfig       = Converter.ReadJson(defaultConfigStream) as SetRecord;

            string configPath = env.ConfigDirectory + "\\bookmarksearch.json";

            if (File.Exists(configPath))
            {
                try
                {
                    Stream    userConfigStream = File.OpenRead(configPath);
                    SetRecord userConfig       = Converter.ReadJson(userConfigStream) as SetRecord;
                    userConfigStream.Dispose();
                    defaultConfig.Combine(userConfig);
                }
                catch
                {
                }
            }
            else
            {
                try
                {
                    defaultConfigStream.Seek(0, SeekOrigin.Begin);
                    FileStream configStream = File.Create(configPath);
                    defaultConfigStream.CopyTo(configStream);
                    configStream.Flush();
                    configStream.Dispose();
                }
                catch
                {
                }
            }
            defaultConfigStream.Dispose();
            ConfigurationRecord = defaultConfig;
            Config = new SearchConfig()
            {
                SearchUrl    = ConfigurationRecord.ReadAs <bool>("allow_url_search"),
                EnableSearch = ConfigurationRecord.ReadAs <bool>("enable")
            };

            Bookmarks = BookmarkCollection.Retrive();
            SearchPatternErrorAction = new ErrorAction(null, "搜索模式错误", "搜索模式错误");
        }
Пример #19
0
        private static ErrorDetails Create(
            Exception ex,
            string errorMessage,
            string stackTrace,
            ErrorAction actionTaken,
            object parameters)
        {
            var args = parameters as Dictionary <string, string> ?? parameters.ToParametersDictionary();

            return(new ErrorDetails
            {
                ActionTaken = actionTaken,
                Args = args,
                Error = ex,
                ErrorMessage = errorMessage,
                StackTrace = stackTrace,
                OccurrenceTimeStamp = DateTime.UtcNow
            });
        }
Пример #20
0
        private static ErrorDetails Create(
                Exception ex,
                string errorMessage,
                string stackTrace,
                ErrorAction actionTaken,
                object parameters)
        {
            var args = parameters as Dictionary<string, string> ?? parameters.ToParametersDictionary();

            return new ErrorDetails
                   {
                           ActionTaken = actionTaken,
                           Args = args,
                           Error = ex,
                           ErrorMessage = errorMessage,
                           StackTrace = stackTrace,
                           OccurrenceTimeStamp = DateTime.UtcNow
                   };
        }
Пример #21
0
        private async void ExecuteSavePlace(object obj)
        {
            _place.LastEdit    = DateTimeOffset.Now;
            _place.Name        = Name;
            _place.Description = Description;
            _place.Rating      = short.Parse(Rating);
            _place.Type        = SelectedPlaceType;
            var result = await PlaceStore.UpdateItemAsync(_place);

            if (result == null)
            {
                ErrorAction?.Invoke($"Update Place '{_place.Name}' failed:");
                App.LogOutLn($"Update Place '{_place.Name}' failed.");
                UpdateReady?.Invoke(false);
            }
            else
            {
                UpdateReady?.Invoke(true);
            }
        }
Пример #22
0
        public override void Begin()
        {
            ThrowIfDisposed();

            if (IsActive)
            {
                throw new InvalidOperationException($"{nameof(RetryTaskController)} - Task already running, use {nameof(CancelAsync)} to abort.");
            }

            IsActive = true;

            Cts = new CancellationTokenSource();

            Task = Task.Run(async() =>
            {
                while (!Cts.IsCancellationRequested)
                {
                    try { await Action(Cts.Token).ConfigureAwait(false); }
                    catch (OperationCanceledException) { }
                    catch (Exception e)
                    {
                        if (!Cts.IsCancellationRequested)
                        {
                            try
                            {
                                ErrorAction?.Invoke(e);
                                OnError(e);
                            }
                            catch { /* ignored */ }
                        }
                    }

                    if (!Cts.IsCancellationRequested)
                    {
                        await Task.Delay(RetryDelayMilliseconds, Cts.Token)
                        .ConfigureAwait(false);
                    }
                }
            });
        }
Пример #23
0
        public AuthOutputDto Login(AuthInputDto login)
        {
            string passwordHashed = _cryptyService.GenerateHashKey(login.Password);

            User userLoged = _authRepository.FindByUserOrEmail(login.Email);

            if (userLoged == null || !passwordHashed.Equals(userLoged.Password))
            {
                ErrorAction error = new ErrorAction(1, Messages.Messages.UsuarioNaoEncontrado.Replace("{0}", login.Email));
                throw error;
            }

            string token = _dataAgent.GenerateToken(userLoged);


            EnterpriseOutputDto userOutput = _mapper.Map <EnterpriseOutputDto>(userLoged);

            AuthOutputDto authOutput = new AuthOutputDto {
                Token = token, User = userOutput
            };

            return(_mapper.Map <AuthOutputDto>(authOutput));
        }
Пример #24
0
        private async void Execute(object obj)
        {
            try
            {
                PasswordHelper.CreatePasswordHash(Password, out var hash, out var salt);
                var user = new User
                {
                    Id       = Guid.NewGuid(),
                    Email    = Email,
                    Hash     = hash,
                    Salt     = salt,
                    Created  = DateTimeOffset.Now,
                    LastEdit = DateTimeOffset.Now,
                    Name     = Username
                };

                var result = await UserStore.AddItemAsync(user);

                if (result == null)
                {
                    ErrorAction?.Invoke(Strings.ERROR_OCCURED_WHILE_CREATING_NEW_USER);
                    NewUserSucceeded?.Invoke(false);
                }
                else
                {
                    AppStore.Instance.User = user;
                    NewUserSucceeded?.Invoke(true);
                }
            }
            catch (Exception ex)
            {
                ErrorAction?.Invoke(Strings.ERROR_OCCURED_WHILE_CREATING_NEW_USER);
                App.LogOutLn(ex.Message, GetType().Name);
                NewUserSucceeded?.Invoke(false);
            }
        }
Пример #25
0
        public void PrintString(string info, UserLevel Level, ErrorAction erroraction)
        {
            if (erroraction == ErrorAction.Updating)
            {
                return;
            }

            Color textcolor = Color.Black;

            // Set the color of the item text.
            if (erroraction == ErrorAction.UserResume)
            {
                textcolor = Color.Green;
            }
            else if (erroraction == ErrorAction.Warning)
            {
                textcolor = Color.Purple;
            }
            else
            {
                textcolor = Color.Red;
            }
            PrintJobInfomation(info, textcolor);
        }
Пример #26
0
 static void SetErrorAction(ErrorAction act)
 {
     NativeMethods.CmsErrorAction ((int) act);
 }
Пример #27
0
        public static void displayError(string message, ErrorCode code, ErrorAction type, Exception ex)
        {
           
            string dir = @"C:\Inventory\Error log";
            int max_logs = 10;
            string file = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString().Replace(':', '.');
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            else
            {
                DirectoryInfo directory = new DirectoryInfo(dir);
                FileInfo[] log_files = directory.GetFiles("*.log").OrderByDescending(f => f.LastWriteTime).ToArray();
                if (log_files.Length >= max_logs)
                {
                    log_files.Last().Delete();
                }
            }
            string path= (dir + @"\" + file + ".log");
            string contents = "Error Code: " + code.error_code;
            if (ex != null)
            {
                contents += "\n\nMain Exception\n" + ex.Message + "\nStackTrace\n" + ex.StackTrace;
                if (ex.InnerException != null)
                {
                   contents+="\n\nInner Exception\n" + ex.InnerException.Message + "\nStackTrace\n" + ex.InnerException.StackTrace;
                }
                if(ex.GetBaseException()!=null)
                {
                    contents += "\n\nBase Exception\n" + ex.GetBaseException().Message + "\nStackTrace\n" + ex.GetBaseException().StackTrace;
                }
                contents+= "\n\nData\n" + ex.Data + "\n\nHresult: " + ex.HResult + "\n\nMethod\n" + ex.TargetSite;
            }


                
            File.WriteAllText(path,contents);

            if (type == ErrorAction.Exit)
            {
                MessageBox.Show(message + "\nError Code: " + code.error_code + "\n" + "Click ok to exit the application.\n" + ex.Message, "An Error Occured");
                if (System.Windows.Forms.Application.MessageLoop)
                {
                    // WinForms app
                    System.Windows.Forms.Application.Exit();
                }
                else
                {
                    // Console app
                    System.Environment.Exit(1);
                }
            }
            else if (type == ErrorAction.Restart)
            {
                MessageBox.Show(message + "\nError Code: " + code.error_code + "\n" + "Click ok to restart the application.\n" + ex.Message, "An Error Occured");
                Application.Exit();
                System.Diagnostics.Process.Start(Application.ExecutablePath);
            }
            else
            {
                MessageBox.Show(message + "\nError Code: " + code.error_code + "\n" + ex.Message, "An Error Occured");

            }



        }
Пример #28
0
 public Parser(ErrorAction errorAction = ErrorAction.Ignore)
 {
     Settings.ParseErrorAction = errorAction;
 }
Пример #29
0
 public Parser(ErrorAction errorAction)
 {
     ErrorAction = errorAction;
 }
Пример #30
0
 public void Error(string message)
 {
     ErrorAction?.Invoke(message);
 }
Пример #31
0
 void InstrumentServ_OnError(string ErrorMessage, int ErrorCode, int Choices, ref ErrorAction Action)
 {
     //This is vital and I believe means that the dang thing will no longer throw
     //a dialog box up, thus blocking the code (which of course would be unknown to the other programs)
     Action = ErrorAction.Abort;
     LastCommandResult = new CommandResult(ErrorMessage);
     PulseObject();
     //by setting the action I effectively make a decision, I expect this program to usually work
     //and so am always going to abort, in the future I could try the default options, or ok, or whatever
 }
Пример #32
0
		public Parser(ErrorAction errorAction = ErrorAction.Ignore)
		{
			ErrorAction = errorAction;
		}
Пример #33
0
 public Parser(ErrorAction errorAction)
 {
     ErrorAction = errorAction;
 }
Пример #34
0
 static void SetErrorAction(ErrorAction act)
 {
     NativeMethods.CmsErrorAction((int)act);
 }
Пример #35
0
        private Task <byte[]> DoHttpRequestTask()
        {
            byte[] resultBytes = null;
            TaskCompletionSource <byte[]> task = new TaskCompletionSource <byte[]>();
            AsyncCallback getResponseCallBack  = (ar) =>
            {
                try
                {
                    var             re       = (HttpWebRequest)ar.AsyncState;
                    HttpWebResponse response = (HttpWebResponse)re.EndGetResponse(ar);
                    //状态码200
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        resultBytes = GetByteArray(response);
                    }
                    else
                    {
                        //未获取到请求结果
                        Debug.WriteLine("can't get response data:" + Request.RequestUri.AbsolutePath);
                    }
                }
                catch (Exception e)
                {
                    ErrorAction?.Invoke(this);
                    Debug.WriteLine(Request.RequestUri.AbsolutePath + ":" + e.Message);
                }
                finally
                {
                    _stopTimer = true;//停止计时器
                    //设置TaskResult通知调用线程已获取到请求结果
                    task.SetResult(resultBytes);
                }
            };
            AsyncCallback getRequestCallBack = (ar) =>
            {
                try
                {
                    var re = (WebRequest)ar.AsyncState;

                    //TODO:设置request header
                    // Just here
                    //----------------------

                    //TODO:设置要发送的网络请求报文体
                    if (!string.IsNullOrEmpty(Body))
                    {
                        var bytes = Encoding.UTF8.GetBytes(Body);
                        using (var stream = Request.EndGetRequestStream(ar))
                        {
                            stream.Write(bytes, 0, bytes.Length);
                        }
                    }
                    //------------------------------

                    re.BeginGetResponse(getResponseCallBack, re);
                }
                catch (Exception e)
                {
                    _stopTimer = true;//停止计时器
                    ErrorAction?.Invoke(this);
                    Debug.WriteLine(Request.RequestUri.AbsolutePath + ":" + e.Message);
                    task.SetResult(null);
                }
            };

            if (Request.Method.ToUpper().Equals("POST"))
            {
                Request.BeginGetRequestStream(getRequestCallBack, Request);
            }
            else if (Request.Method.ToUpper().Equals("GET"))
            {
                Request.BeginGetResponse(getResponseCallBack, Request);
            }
            //if (IsEnableTimeOut)
            //    StartTimer();//启用超时计时器
            return(task.Task);
        }
Пример #36
0
		public ErrorHandler(IErrorNotifier notifier, IWebContext context, InstallationManager installer, IExceptionFilter exceptionFilter, IMailSender mailSender, 
			ConfigurationManagerWrapper configuration)
		{
			this.notifier = notifier;
			this.context = context;
			this.installer = installer;
			this.exceptionFilter = exceptionFilter;
			this.mailSender = mailSender;

			beginUrl = configuration.Sections.Management.Installer.WelcomeUrl;
			action = configuration.Sections.Engine.Errors.Action;
			mailTo = configuration.Sections.Engine.Errors.MailTo;
			mailFrom = configuration.Sections.Engine.Errors.MailFrom;
			maxErrorReportsPerHour = configuration.Sections.Engine.Errors.MaxErrorReportsPerHour;
			handleWrongClassException = configuration.Sections.Engine.Errors.HandleWrongClassException;
			handleSqlException = configuration.Sections.Engine.Errors.SqlExceptionHandling == ExceptionResolutionMode.RefreshGet;
		}
Пример #37
0
 public Parser(ErrorAction errorAction = ErrorAction.Ignore)
 {
     ErrorAction = errorAction;
 }
Пример #38
0
 public RenderingNameConvention(ErrorAction errorAction) : base(errorAction)
 {
 }
Пример #39
0
 public TemplateNamingConvention(string illegalChars, ErrorAction errorAction) : base(errorAction)
 {
     _illegalChars = illegalChars;
 }
Пример #40
0
		static extern void cmsErrorAction (ErrorAction action);
Пример #41
0
        /// <summary>
        /// Publishes the app to the given folder
        /// </summary>
        /// <param name="targetPath">Folder to publsh the project too</param>
        /// <param name="behaviour">Preferred treatment of previous builds</param>
        /// <returns>The collection of results from the output handlers</returns>
        public List <HandlerResponse> PublishApp(string targetPath,
                                                 PublishBehaviour behaviour = PublishBehaviour.CleanFirst)
        {
            var results = InputHandlers.ProcessHandlers(
                new FilePath(ProjectFilePath).GetDirectory().MakeAbsolute(Environment).FullPath, s => Log(s));

            Log(
                $"Completed processing input handlers: {results.Count(r => r.Result == HandlerResult.OK)} OK, {results.Count(r => r.Result == HandlerResult.Error)} errors, {results.Count(r => r.Result == HandlerResult.NotRun)} not run");
            if (results.Any(r => r.Result == HandlerResult.Error))
            {
                throw new HandlerProcessingException(InputHandlers, results);
            }
            string outputPath;

            if (behaviour == PublishBehaviour.DoNotBuild)
            {
                outputPath  = Path.Combine(new FileInfo(ProjectFilePath).Directory.FullName, "bin", Configuration);
                BuildAction = null;
            }
            else
            {
                outputPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString("N"));
                if (!FileSystem.Exist((DirectoryPath)outputPath))
                {
                    FileSystem.GetDirectory(outputPath).Create();
                }
            }
            var props = new Dictionary <string, string>
            {
                { "Configuration", Configuration },
                { "Platform", Platform },
                { "OutputPath", outputPath },
                { "PublishDir", Path.Combine(outputPath, "app.publish") + "\\" }
            };

            BuildSettings = new MSBuildSettings
            {
                Configuration   = Configuration,
                MSBuildPlatform = GetMSBuildPlatform(Platform),
                Verbosity       = Verbosity.Quiet
            };
            BuildSettings.AddTargets(behaviour);
            BuildSettings.AddProperties(props, AdditionalProperties);
            BuildAction?.Invoke(this);
            var publishDir =
                new DirectoryPath(
                    new DirectoryInfo(props["OutputPath"]).GetDirectories()
                    .FirstOrDefault(d => d.Name == "app.publish")
                    .FullName);

            if (GenerateManifest)
            {
                PrepareManifestManager(publishDir, InformationSource.Both);
                ManifestManager.DeployManifest(ManifestManager.CreateAppManifest());
            }
            Log("Processing output handlers");
            var output = OutputHandlers.ProcessHandlers(publishDir.FullPath, s => Log(s));

            Log(
                $"Completed processing output handlers: {output.Count(r => r.Result == HandlerResult.OK)} OK, {output.Count(r => r.Result == HandlerResult.Error)} errors, {output.Count(r => r.Result == HandlerResult.NotRun)} not run");
            if (output.Any(o => o.Result == HandlerResult.Error) && ErrorAction != null)
            {
                Log("Error encountered while processing output handlers. Aborting!");
                ErrorAction?.Invoke(output);
                //throw new HandlerProcessingException(OutputHandlers, output); // in case something goes real wrong
            }
            if (string.IsNullOrWhiteSpace(targetPath))
            {
                return(output);
            }
            Log("Copying publish results to target directory");
            new DirectoryInfo(publishDir.MakeAbsolute(Environment).FullPath).Copy(destDirPath: targetPath,
                                                                                  copySubDirs: true);
            return(output);
        }
Пример #42
0
		private static void SetErrorAction (ErrorAction act)
		{
			cmsErrorAction (act);
		}