Пример #1
0
        public void PopulateFacade(TestTreeNodeFacade rfacade)
        {
            try
            {
                if (rfacade == null)
                {
                    throw new ArgumentNullException("rfacade");
                }
                if (this.facade != null)
                {
                    this.facade.Changed -= new ResultEventHandler(rfacade.Changed);
                }

                this.facade          = new RemotedTestTreeNodeFacade();
                this.facade.Changed += new ResultEventHandler(rfacade.Changed);
                foreach (Fixture fixture in this.Explorer.FixtureGraph.Fixtures)
                {
                    foreach (RunPipeStarter starter in fixture.Starters)
                    {
                        starter.Listeners.Add(this.facade);
                        rfacade.AddPipe(starter.Pipe.Identifier);
                    }
                }
            }
            catch (Exception ex)
            {
                ReportException          rex  = ReportException.FromException(ex);
                ReportExceptionException rexe = new ReportExceptionException(
                    "Error while populating facade of " + this.TestAssembly.FullName,
                    rex);
                throw rexe;
            }
        }
Пример #2
0
        public virtual void SetTestFilePath(string testFilePath)
        {
            try
            {
                if (testFilePath == null)
                {
                    throw new ArgumentNullException("testFilePath");
                }
                string fileName = Path.GetFileNameWithoutExtension(testFilePath);

                Assembly testAssembly = Assembly.Load(
                    fileName
                    , this.GetType().Assembly.Evidence
                    );
                if (testAssembly == null)
                {
                    throw new FileNotFoundException(testFilePath);
                }
                SetTestAssembly(testAssembly);
            }
            catch (Exception ex)
            {
                throw new ReportExceptionException(
                          "Failed loading test assembly",
                          ReportException.FromException(ex)
                          );
            }
        }
Пример #3
0
        private void ReportException(Exception ex)
        {
            DataClasses1DataContext DB = new DataClasses1DataContext();

#if OFFICE
            DB.Connection.ConnectionString = @"Data Source=" + DataSettings.Default.ServerName + @"\;Initial Catalog=JianLi;User ID=bee;Password=beegee";
#endif
#if HOME
            DB.Connection.ConnectionString = @"Data Source=" + DataSettings.Default.ServerName + @"\;Initial Catalog=JianLi;Integrated Security=True";
#endif
            ReportException ep = new ReportException();
            ep.Message         = ex.Message;
            ep.UserID          = DataSettings.Default.User.UserID;
            ep.StackTrace      = ex.StackTrace;
            ep.ReportID        = Guid.NewGuid();
            ep.UserWords       = "";
            ep.Date            = DateTime.Now;
            ep.State           = 0;
            ep.SoftwareName    = "JianLi3";
            ep.SoftwareVersion = version;

            DB.ReportExceptions.InsertOnSubmit(ep);

            DB.SubmitChanges();

            MessageBox.Show("出现未知错误,程序将关闭。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
Пример #4
0
        public void AddException(ReportException ex)
        {
            this.exceptionTreeView.Nodes.Clear();

            // adding recursively the exceptions
            ReportException current = ex;
            TreeNode        parent  = null;

            while (current != null)
            {
                TreeNode node = new TreeNode(current.Type);
                node.Tag = current;

                if (parent == null)
                {
                    this.exceptionTreeView.Nodes.Add(node);
                    this.exceptionTreeView.SelectedNode = node;
                    parent = node;
                }
                else
                {
                    parent.Nodes.Add(node);
                    parent = node;
                }

                current = current.Exception;
            }

            this.exceptionTreeView.ExpandAll();
            this.RefreshException();
            this.Refresh();
        }
Пример #5
0
        public void RefreshException()
        {
            this.textBox1.Text = "";
            if (this.exceptionTreeView.SelectedNode == null)
            {
                this.textBox1.Text = "";
                return;
            }

            ReportException ex       = (ReportException)this.exceptionTreeView.SelectedNode.Tag;
            Font            boldFont = new Font(this.Font.FontFamily, this.Font.SizeInPoints, FontStyle.Bold);
            Font            font     = new Font(this.Font.FontFamily, this.Font.SizeInPoints);

            // adding name
            this.textBox1.SelectionFont = boldFont;
            this.textBox1.SelectedText  = String.Format("Message: {0}\n\n", ex.Message);
            this.textBox1.SelectionFont = font;
            this.textBox1.SelectedText  = String.Format("Type: {0}\n", ex.Type);
            this.textBox1.SelectedText  = String.Format("Source: {0}\n", ex.Source);
            foreach (ReportProperty property in ex.Properties)
            {
                this.textBox1.SelectedText = String.Format("{0}: {1}\n", property.Name, property.Value);
            }
            this.textBox1.SelectedText = String.Format("Stack:");
            this.textBox1.SelectedText = String.Format("{0}", ex.StackTrace);
        }
Пример #6
0
        public bool ShowException(string errorText, ReportException report)
        {
            bool posted = false;

            Window = new ReportFormUI {
                txtError = { Text = errorText }
            };
            Window.btnPost.Click +=
                (sender, args) =>
            {
                try
                {
                    var text = Window.txtDescription == null ? "" : Window.txtDescription.Text;
                    report(text);
                    posted = true;
                    Window.Close();
                }
                catch (System.Exception)
                {
                    //failure
                    //Nothing relevant to report.
                }
            };

            Window.Topmost = true;
            Window.ShowDialog();

            Window = null;
            return(posted);
        }
Пример #7
0
        void RenderSetUpOrTearDownFailure(string context, ReportSetUpAndTearDown setup)
        {
            TestResult summary = new TestResult();

            switch (setup.Result)
            {
            case ReportRunResult.Failure:
                summary.State = TDF.TestState.Failed;
                break;

            case ReportRunResult.Success:
                summary.State = TDF.TestState.Passed;
                break;
            }

            summary.TotalTests = this.testCount;
            summary.Name       = String.Format("{0} {1}", context, setup.Name);
            summary.TimeSpan   = new TimeSpan(0, 0, 0, 0, (int)(setup.Duration * 1000));
            if (setup.Exception != null)
            {
                summary.Message = setup.Exception.Message;

                StringWriter    sw = new StringWriter();
                ReportException ex = setup.Exception;
                summary.StackTrace = ex.ToString();
            }

            this.testListener.TestFinished(summary);
        }
Пример #8
0
 public ReportExceptionException(string message, ReportException exception)
     : base(message)
 {
     if (exception == null)
     {
         throw new ArgumentNullException("exception");
     }
     this.exception = exception;
 }
Пример #9
0
        public void SerializeCustomProperty()
        {
            DummyException  ex  = new DummyException();
            ReportException rex = ReportException.FromException(ex);

            foreach (ReportProperty p in rex.Properties)
            {
                if (p.Name == "Dummy")
                {
                    Assert.AreEqual(p.Value, ex.Dummy);
                    return;
                }
            }
            Assert.Fail("Dummy property not found");
        }
 private bool CheckSettings(out ReportException ex)
 {
     ex = new ReportException();
     if (string.IsNullOrEmpty(this.ReportSettings.ReportServer))
     {
         ex = new ReportException("Please set ReportServer.");
         return(false);
     }
     if (!System.Uri.IsWellFormedUriString(this.ReportSettings.ReportServer, System.UriKind.Absolute))
     {
         ex = new ReportException("Please check whether the ReportServer is correct.");
         return(false);
     }
     return(true);
 }
Пример #11
0
        public void SerializeData()
        {
            string    key   = "DummyData";
            string    value = "value";
            Exception ex    = new Exception();
            //ex.Data.Add(key,value);
            ReportException rex = ReportException.FromException(ex);

            foreach (ReportProperty p in rex.Properties)
            {
                if (p.Name == key)
                {
                    Assert.AreEqual(p.Value, value);
                    return;
                }
            }
            Assert.Fail("Dummy property not found");
        }
Пример #12
0
 public virtual void Populate()
 {
     try
     {
         this.explorer.Explore();
         this.LoadPipes();
     }
     catch (Exception ex)
     {
         ReportException          rex  = ReportException.FromException(ex);
         ReportExceptionException rexe = new ReportExceptionException(
             String.Format("Error while loading tests in {0}: {1}",
                           this.testAssembly.FullName,
                           ex.Message
                           ),
             rex);
         throw rexe;
     }
 }
Пример #13
0
        public static void YearReport()
        {
            var ex = new ReportException();

            try
            {
                throw ex;

                Debug.WriteLine("TRY");
            }
            catch(FormatException)
            {
                Debug.WriteLine("CATCH");
            }
            finally
            {
                Debug.WriteLine("FINALLY");
            }

            Debug.WriteLine("AFTER FINALLY");
        }
Пример #14
0
        public static void YearReport()
        {
            var ex = new ReportException();

            try
            {
                throw ex;

                Debug.WriteLine("TRY");
            }
            catch (FormatException)
            {
                Debug.WriteLine("CATCH");
            }
            finally
            {
                Debug.WriteLine("FINALLY");
            }

            Debug.WriteLine("AFTER FINALLY");
        }
            private static ExceptionData GetExceptionDataFromReportException(ReportException ex)
            {
                PropertySet properties = null;

                foreach (object obj in ex.Properties)
                {
                    ReportProperty property = obj as ReportProperty;
                    if (property != null && property.Value != null)
                    {
                        if (properties == null)
                        {
                            properties = new PropertySet();
                        }
                        properties[property.Name] = property.Value;
                    }
                }

                return(new ExceptionData(ex.Type ?? "", ex.Message ?? "", ex.StackTrace ?? "",
                                         properties ?? ExceptionData.NoProperties,
                                         ex.Exception != null ? GetExceptionDataFromReportException(ex.Exception) : null));
            }
Пример #16
0
        static ExceptionInfo GetExceptionInfo(ReportException reportException)
        {
            if (reportException == null)
            {
                return(null);
            }

            ExceptionInfo exceptionInfo = new ExceptionInfo();

            exceptionInfo.Type       = reportException.Type;
            exceptionInfo.Message    = reportException.Message;
            exceptionInfo.Source     = reportException.Source;
            exceptionInfo.StackTrace = reportException.StackTrace;

            if (reportException.Exception != null)
            {
                exceptionInfo.InnerException = GetExceptionInfo(reportException.Exception);
            }

            return(exceptionInfo);
        }
Пример #17
0
        void TestEngineFailure(ReportRun run)
        {
            this.failureCount++;

            TestResult summary = new TestResult();

            summary.State      = TDF.TestState.Failed;
            summary.TotalTests = this.testCount;
            summary.Name       = run.Name;
            summary.TimeSpan   = new TimeSpan(0, 0, 0, 0, (int)(run.Duration * 1000));

            if (run.Exception != null)
            {
                ReportException ex = run.Exception;

                summary.Message    = run.Exception.Message;
                summary.StackTrace = ex.ToString();
            }

            testListener.WriteLine(String.Format("[failure] {0}", run.Name), Category.Info);
            this.testListener.TestFinished(summary);
        }
Пример #18
0
        public virtual void CreateAssembly()
        {
            try
            {
                this.options.ReferencedAssemblies.Clear();
                this.options.ReferencedAssemblies.Add("MbUnit.Framework.dll");
                this.options.ReferencedAssemblies.Add("TestFu.dll");

                foreach (string referencedAssembly in this.referencedAssemblies)
                {
                    this.options.ReferencedAssemblies.Add(referencedAssembly);
                }

                string[] srs = new string[this.sources.Count];
                this.sources.CopyTo(srs, 0);

                this.compilerResults = this.compiler.CompileAssemblyFromSourceBatch(options, srs);
                if (this.compilerResults.Errors.HasErrors)
                {
                    Console.WriteLine("Compilation has errors");
                    foreach (CompilerError error in this.compilerResults.Errors)
                    {
                        Console.WriteLine("Error: {0}", error);
                    }
                    throw new CompilationException(
                              this.compiler,
                              this.options,
                              this.compilerResults,
                              srs
                              );
                }
            }
            catch (Exception ex)
            {
                ReportException rex = ReportException.FromException(ex);
                throw new ReportExceptionException("Compilation failed", rex);
            }
            this.SetTestAssembly(this.compilerResults.CompiledAssembly);
        }
Пример #19
0
        void TestEngineSkip(ReportRun run)
        {
            this.skipCount++;

            TestResult summary = new TestResult();

            summary.State      = TDF.TestState.Ignored;
            summary.TotalTests = this.testCount;
            summary.Name       = run.Name;
            summary.TimeSpan   = new TimeSpan(0, 0, 0, 0, 0);

            if (run.Exception != null)
            {
                ReportException ex = run.Exception;

                summary.Message    = run.Exception.Message;
                summary.StackTrace = ex.ToString();
            }

            testListener.WriteLine(String.Format("[skipped] {0}", run.Name), Category.Info);
            this.testListener.TestFinished(summary);
        }
Пример #20
0
        private void BworkerDoWork()
        {
            Host currentHost = null;

            try
            {
                foreach (var selectedMaster in _mastersToUpgrade)
                {
                    if (_cancel)
                    {
                        return;
                    }
                    Pool pool = Helpers.GetPoolOfOne(selectedMaster.Connection);
                    foreach (var host in pool.HostsToUpgrade)
                    {
                        log.InfoFormat("Host '{0}' upgrading from version '{1}'", host.Name, host.LongProductVersion);
                        currentHost = host;
                        bool allactionsDone = true;
                        foreach (var planAction in _planActions[host])
                        {
                            try
                            {
                                string hostVersion = host.LongProductVersion;
                                ReportRunning(this, new ReportRunningArgs(planAction, host));
                                planAction.Run();
                                if (_cancel)
                                {
                                    return;
                                }
                                if (planAction is UpgradeHostPlanAction)
                                {
                                    Host hostAfterReboot = host.Connection.Resolve(new XenRef <Host>(host.opaque_ref));
                                    if (Helpers.SameServerVersion(hostAfterReboot, hostVersion))
                                    {
                                        log.ErrorFormat("Host '{0}' rebooted with the same version '{1}'", hostAfterReboot.Name, hostAfterReboot.LongProductVersion);
                                        ReportException.Raise(this,
                                                              new ReportExceptionArgs(
                                                                  new Exception(Messages.REBOOT_WITH_SAME_VERSION),
                                                                  planAction, host));
                                        allactionsDone = false;
                                        if (hostAfterReboot.IsMaster())
                                        {
                                            _cancel = true;
                                        }
                                    }
                                    log.InfoFormat("Host '{0}' upgraded with version '{1}'", hostAfterReboot.Name, hostAfterReboot.LongProductVersion);
                                }
                            }
                            catch (Exception e)
                            {
                                ReportException.Raise(this, new ReportExceptionArgs(e, planAction, host));
                                allactionsDone = false;
                                _cancel        = true;
                            }
                            if (_cancel)
                            {
                                return;
                            }
                        }
                        if (allactionsDone)
                        {
                            ReportHostDone.Raise(this, new ReportHostDoneArgs(host));
                        }
                    }
                }
            }
            catch (Exception excep)
            {
                log.Error("Upgrade thread error: ", excep);
            }
            finally
            {
                //Revert resolved prechecks
                try
                {
                    log.Debug("Reverting prechecks");
                    ReportRunning.Raise(this, () => new ReportRunningArgs(_revertAction, currentHost));
                    _revertAction.Run();
                    ReportRevertDone.Raise(this, () => new ReportRevertDoneArgs(_revertAction));
                }
                catch (Exception excep)
                {
                    log.Error("Exception reverting prechecks", excep);
                    ReportException.Raise(this, () => new ReportExceptionArgs(excep, _revertAction, currentHost));
                }

                Completed.Raise(this);
            }


            Completed.Raise(this);
        }
Пример #21
0
        public void FtpUpload(Report report, FTPSettings settings)
        {
            var reportName = report?.Name ?? null;

            try
            {
                if (String.IsNullOrEmpty(reportName))
                {
                    throw new Exception("The report has no filename.");
                }

                var targetPath = settings?.RemotePath?.Trim() ?? null;
                if (targetPath == null)
                {
                    var message = $"No target ftp path for report '{reportName}' found.";
                    logger.Error(message);
                    JobResult.Exception = ReportException.GetException(message);
                    JobResult.Status    = TaskStatusInfo.ERROR;
                    Results.Add(new FTPResult()
                    {
                        Success     = false,
                        ReportState = "ERROR",
                        TaskName    = JobResult.TaskName,
                        Message     = message,
                        ReportName  = reportName
                    });
                    return;
                }

                var ftpClient         = new FtpClient(settings.Host, settings.Port, settings.Username, settings.Password);
                var ftpEncryptionMode = FtpEncryptionMode.None;
                if (settings?.EncryptionMode != null)
                {
                    ftpEncryptionMode = (FtpEncryptionMode)Enum.Parse(typeof(FtpEncryptionMode), settings.EncryptionMode);
                }
                ftpClient.EncryptionMode         = ftpEncryptionMode;
                ftpClient.ValidateAnyCertificate = settings.UseSsl;
                ftpClient.Connect();

                var fileCount = 0;
                foreach (var reportPath in report.Paths)
                {
                    if (report.Paths.Count > 1)
                    {
                        fileCount++;
                    }
                    var fileData      = report.Data.FirstOrDefault(f => f.Filename == Path.GetFileName(reportPath));
                    var targetFtpFile = $"{targetPath}/{NormalizeReportName(reportName)}{Path.GetExtension(reportPath)}";
                    if (fileCount > 0)
                    {
                        targetFtpFile = $"{targetPath}/{NormalizeReportName(reportName)}_{fileCount}{Path.GetExtension(reportPath)}";
                    }
                    logger.Debug($"ftp distibute mode {settings.Mode}");

                    var ftpRemoteExists = FtpRemoteExists.Overwrite;
                    switch (settings.Mode)
                    {
                    case DistributeMode.CREATEONLY:
                        ftpRemoteExists = FtpRemoteExists.Skip;
                        break;

                    case DistributeMode.DELETEALLFIRST:
                        logger.Debug($"The FTP file '{targetFtpFile}' could not deleted.");
                        if (ftpClient.FileExists(targetFtpFile))
                        {
                            ftpClient.DeleteFile(targetFtpFile);
                        }
                        ftpRemoteExists = FtpRemoteExists.Skip;
                        break;

                    case DistributeMode.OVERRIDE:
                        ftpRemoteExists = FtpRemoteExists.Overwrite;
                        break;

                    default:
                        throw new Exception($"Unkown distribute mode {settings.Mode}");
                    }

                    // Create FTP Folder
                    var folderObject = ftpClient.GetObjectInfo(targetPath);
                    if (folderObject == null)
                    {
                        ftpClient.CreateDirectory(targetPath, true);
                    }

                    // Upload File
                    var ftpStatus = ftpClient.UploadFile(reportPath, targetFtpFile, ftpRemoteExists);
                    if (ftpStatus == FtpStatus.Success)
                    {
                        Results.Add(new FTPResult()
                        {
                            Success     = true,
                            ReportState = GetFormatedState(),
                            ReportName  = reportName,
                            TaskName    = JobResult.TaskName,
                            Message     = "FTP upload was executed successfully.",
                            FtpPath     = $"ftp://{settings.Host}{targetFtpFile}"
                        });
                    }
                    else
                    {
                        throw new Exception($"The FTP File '{targetFtpFile}' upload failed.");
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex, "The delivery via 'ftp' failed.");
                JobResult.Exception = ReportException.GetException(ex);
                JobResult.Status    = TaskStatusInfo.ERROR;
                Results.Add(new FTPResult()
                {
                    Success     = false,
                    ReportState = "ERROR",
                    TaskName    = JobResult.TaskName,
                    Message     = ex.Message,
                    ReportName  = reportName
                });
            }
        }
Пример #22
0
 protected ReportExceptionException(SerializationInfo info, StreamingContext context)
     : base(info, context)
 {
     this.exception = (ReportException)info.GetValue("Exception", typeof(ReportException));
 }
Пример #23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="JPushClient" /> class.
 /// </summary>
 /// <param name="appKey">The application key.</param>
 /// <param name="masterSecret">The master secret.</param>
 /// <param name="pushResultUpdate">The update push message status delegate.</param>
 /// <param name="pushTrackingInitialize">The initialize delegate.</param>
 /// <param name="exceptionReport">The exception delegate.</param>
 /// <param name="threadInterval">The interval in second.</param>
 public JPushHandler(string appKey, string masterSecret, int threadInterval = 60, UpdatePushResult pushResultUpdate = null, InitializePushTracking pushTrackingInitialize = null, ReportException exceptionReport = null)
 {
     JPushClient = new JPushClient(appKey, masterSecret, true);
     if (threadInterval < 1)
         threadInterval = 60;
     this.ThreadInterval = threadInterval;
     this.PushTrackings = new List<Tracking>();
     this.DataLocker = new object();
     this.PushResultUpdate = pushResultUpdate;
     this.PushTrackingInitialize = pushTrackingInitialize;
     this.ExceptionReport = exceptionReport;
     this.InitializeMonitorThreadInBackground();
 }
Пример #24
0
        public virtual void Run(
            FixtureExplorer explorer,
            ReportListener reportListener
            )
        {
            if (explorer == null)
            {
                throw new ArgumentNullException("explorer");
            }
            if (reportListener == null)
            {
                throw new ArgumentNullException("reportListener");
            }

            this.explorer     = explorer;
            this.report       = reportListener;
            this.abortPending = false;

            try
            {
                // start reporting
                this.Report.StartTests();

                if (this.IsAbortPending)
                {
                    return;
                }

                // assembly setup
                if (!this.RunAssemblySetUp())
                {
                    return;
                }

                if (this.IsAbortPending)
                {
                    return;
                }

                try
                {
                    RunFixtures();
                }
                finally
                {
                    this.RunAssemblyTearDown();
                }
            }
            catch (Exception ex)
            {
                ReportException          rex  = ReportException.FromException(ex);
                ReportExceptionException rexe = new ReportExceptionException(
                    "Internal error while running tests in " +
                    this.Explorer.AssemblyName, rex);
                throw rexe;
            }
            finally
            {
                this.Report.FinishTests();

                this.explorer = null;
                this.report   = null;
            }
        }
Пример #25
0
 public DocumentRepository(IMContext context, ReportException exHandler) : base(context, exHandler)
 {
 }
Пример #26
0
 public GroupRepository(IMContext context, ReportException exHandler)
     : base(context, exHandler)
 {
 }
        public void CopyFile(Report report, FileSettings settings, Connection socketConnection)
        {
            var reportName = report?.Name ?? null;

            try
            {
                if (String.IsNullOrEmpty(reportName))
                {
                    throw new Exception("The report filename is empty.");
                }

                var target = settings?.Target?.Trim() ?? null;
                if (target == null)
                {
                    var message = $"No target file path for report '{reportName}' found.";
                    logger.Error(message);
                    JobResult.Exception = ReportException.GetException(message);
                    JobResult.Status    = TaskStatusInfo.ERROR;
                    Results.Add(new FileResult()
                    {
                        Success     = false,
                        ReportState = "ERROR",
                        TaskName    = JobResult.TaskName,
                        Message     = message,
                        ReportName  = reportName
                    });
                    return;
                }

                if (!target.ToLowerInvariant().StartsWith("lib://") && socketConnection != null)
                {
                    var message = $"Target value '{target}' is not a 'lib://' connection.";
                    logger.Error(message);
                    JobResult.Exception = ReportException.GetException(message);
                    JobResult.Status    = TaskStatusInfo.ERROR;
                    Results.Add(new FileResult()
                    {
                        Success     = false,
                        ReportState = "ERROR",
                        Message     = message,
                        TaskName    = JobResult.TaskName,
                        ReportName  = reportName
                    });
                    return;
                }

                var targetPath = String.Empty;
                if (PathCache.ContainsKey(target))
                {
                    targetPath = PathCache[target];
                }
                else
                {
                    targetPath = ResolveLibPath(target, socketConnection);
                    PathCache.Add(target, targetPath);
                }

                logger.Info($"Use the following resolved path '{targetPath}'...");

                var fileCount = 0;
                foreach (var reportPath in report.Paths)
                {
                    var targetFile = Path.Combine(targetPath, $"{NormalizeReportName(reportName)}{Path.GetExtension(reportPath)}");
                    if (report.Paths.Count > 1)
                    {
                        fileCount++;
                        targetFile = Path.Combine(targetPath, $"{NormalizeReportName(reportName)}_{fileCount}{Path.GetExtension(reportPath)}");
                    }

                    var fileData = report.Data.FirstOrDefault(f => f.Filename == Path.GetFileName(reportPath));
                    logger.Info($"Copy with distibute mode '{settings.Mode}'...");
                    switch (settings.Mode)
                    {
                    case DistributeMode.OVERRIDE:
                        Directory.CreateDirectory(targetPath);
                        File.WriteAllBytes(targetFile, fileData.DownloadData);
                        break;

                    case DistributeMode.DELETEALLFIRST:
                        if (File.Exists(targetFile))
                        {
                            File.Delete(targetFile);
                        }
                        Directory.CreateDirectory(targetPath);
                        File.WriteAllBytes(targetFile, fileData.DownloadData);
                        break;

                    case DistributeMode.CREATEONLY:
                        if (File.Exists(targetFile))
                        {
                            throw new Exception($"The file '{targetFile}' does not exist.");
                        }
                        File.WriteAllBytes(targetFile, fileData.DownloadData);
                        break;

                    default:
                        throw new Exception($"Unkown distribute mode {settings.Mode}");
                    }
                    logger.Info($"The file '{targetFile}' was copied...");
                    Results.Add(new FileResult()
                    {
                        Success     = true,
                        ReportState = GetFormatedState(),
                        TaskName    = JobResult.TaskName,
                        ReportName  = reportName,
                        Message     = "Report was successful created.",
                        CopyPath    = targetFile
                    });
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex, "The delivery process for 'files' failed.");
                JobResult.Exception = ReportException.GetException(ex);
                JobResult.Status    = TaskStatusInfo.ERROR;
                Results.Add(new FileResult()
                {
                    Success     = false,
                    ReportState = "ERROR",
                    TaskName    = JobResult.TaskName,
                    Message     = ex.Message,
                    ReportName  = reportName
                });
            }
            finally
            {
                PathCache.Clear();
                if (socketConnection != null)
                {
                    socketConnection.IsFree = true;
                }
            }
        }
Пример #28
0
        public void SendMails()
        {
            try
            {
                logger.Debug("Summarized mails...");
                foreach (var mailcache in MailCaches)
                {
                    var summarizedMail = GetMailFromSummarizedMailList(mailcache.Settings);
                    if (summarizedMail == null)
                    {
                        logger.Debug("Create new mail for summarized mail list...");
                        var mailTo   = mailcache.Settings?.To?.Replace(";", ",")?.TrimEnd(',') ?? "No mail recipient was specified.";
                        var mailFrom = mailcache.Settings?.MailServer?.From ?? "No sender was specified.";
                        summarizedMail = new MailMessage(mailFrom, mailTo)
                        {
                            BodyEncoding    = Encoding.UTF8,
                            SubjectEncoding = Encoding.UTF8,
                            Subject         = mailcache.Settings?.Subject?.Trim() ?? "No subject was specified.",
                        };

                        var ccAddresses = mailcache.Settings?.Cc?.Replace(";", ",")?.TrimEnd(',');
                        if (!String.IsNullOrEmpty(ccAddresses))
                        {
                            summarizedMail.CC.Add(ccAddresses);
                        }

                        var bccAddresses = mailcache.Settings?.Bcc?.Replace(";", ",")?.TrimEnd(',');
                        if (!String.IsNullOrEmpty(bccAddresses))
                        {
                            summarizedMail.Bcc.Add(bccAddresses);
                        }

                        var msgBody = mailcache.Settings?.Message?.Trim() ?? String.Empty;
                        switch (mailcache.Settings?.MailType ?? EMailType.TEXT)
                        {
                        case EMailType.TEXT:
                            msgBody = msgBody.Replace("{n}", Environment.NewLine);
                            break;

                        case EMailType.HTML:
                            summarizedMail.IsBodyHtml = true;
                            break;

                        case EMailType.MARKDOWN:
                            summarizedMail.IsBodyHtml = true;
                            msgBody = Markdown.ToHtml(msgBody);
                            break;

                        default:
                            throw new Exception($"Unknown mail type {mailcache.Settings?.MailType}.");
                        }
                        msgBody = msgBody.Trim();
                        logger.Debug($"Set mail body '{msgBody}'...");
                        summarizedMail.Body = msgBody;
                        if (mailcache.Settings.SendAttachment)
                        {
                            logger.Debug($"Attachment report files...");
                            AddReportstoMail(summarizedMail, mailcache.Report);
                        }
                        else
                        {
                            logger.Debug($"Use no mail attachment...");
                        }
                        SummarizedMails.Add(summarizedMail);
                    }
                    else
                    {
                        logger.Debug("Duplicate Mail settings was found in summarized mail list...");
                        if (mailcache.Settings.SendAttachment)
                        {
                            logger.Debug($"Attachment report files...");
                            AddReportstoMail(summarizedMail, mailcache.Report);
                        }
                        else
                        {
                            logger.Debug($"Use no mail attachment...");
                        }
                    }
                }

                var mailServers = MailCaches.Select(c => c.Settings).Select(s => s.MailServer).GroupBy(s => s.Host).Select(s => s.First()).ToList();
                logger.Debug($"Send {SummarizedMails.Count} Mails over {MailCaches.Count} mail servers...");
                foreach (var mailServer in mailServers)
                {
                    var mailResult = new MailResult();

                    try
                    {
                        foreach (var summarizedMail in SummarizedMails)
                        {
                            using var client = new SmtpClient(mailServer.Host, mailServer.Port);
                            var priateKeyPath = HelperUtilities.GetFullPathFromApp(mailServer.PrivateKey);
                            if (!File.Exists(priateKeyPath))
                            {
                                logger.Debug("No private key path found...");
                            }

                            if (!String.IsNullOrEmpty(mailServer.Username) && !String.IsNullOrEmpty(mailServer.Password))
                            {
                                logger.Debug($"Set mail server credential for user '{mailServer.Username}'...");
                                var password = mailServer.Password;
                                if (mailServer.UseBase64Password && File.Exists(priateKeyPath))
                                {
                                    logger.Debug($"Use private key path {priateKeyPath}...");
                                    var textCrypter = new TextCrypter(priateKeyPath);
                                    password = textCrypter.DecryptText(password);
                                }
                                client.Credentials = new NetworkCredential(mailServer.Username, password);
                            }
                            else
                            {
                                logger.Debug($"No mail server credential found...");
                            }

                            if (mailServer.UseSsl)
                            {
                                logger.Debug($"Use SSL for mail sending...");
                                client.EnableSsl = true;
                            }

                            if (mailServer.UseCertificate && File.Exists(priateKeyPath))
                            {
                                var certifcateFolder = Path.GetDirectoryName(priateKeyPath);
                                logger.Info($"Search for email certificates with name 'mailcert.*' in folder '{certifcateFolder}'...");
                                var certFiles = Directory.GetFiles(certifcateFolder, "mailcert.*", SearchOption.TopDirectoryOnly);
                                foreach (var certFile in certFiles)
                                {
                                    logger.Debug($"Load certificate '{certFile}'.");
                                    var x509File = new X509Certificate2(certFile);
                                    logger.Debug($"Add certificate '{certFile}'.");
                                    client.ClientCertificates.Add(x509File);
                                }
                            }

                            if (summarizedMail.To.Count > 0)
                            {
                                var delay = 0;
                                if (mailServer.SendDelay > 0)
                                {
                                    delay = mailServer.SendDelay * 1000;
                                    logger.Debug($"Wait {delay} milliseconds for the mail to be sent...");
                                }

                                Task.Delay(delay).ContinueWith(r =>
                                {
                                    logger.Debug("Send mail package...");
                                    client.Send(summarizedMail);

                                    mailResult.Message     = "The mail was sent successfully.";
                                    mailResult.Success     = true;
                                    mailResult.TaskName    = JobResult.TaskName;
                                    mailResult.ReportState = GetFormatedState();
                                }).Wait();
                            }
                            else
                            {
                                mailResult.Message = "Mail without mail Address could not be sent.";
                                logger.Error(mailResult.Message);
                                mailResult.Success     = false;
                                mailResult.TaskName    = JobResult.TaskName;
                                mailResult.ReportState = "ERROR";
                                JobResult.Exception    = ReportException.GetException(mailResult.Message);
                                JobResult.Status       = TaskStatusInfo.ERROR;
                            }

                            client.Dispose();
                            Results.Add(mailResult);
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex, $"The delivery via 'Mail' failed with server '{mailServer.Host}'.");
                        JobResult.Exception    = ReportException.GetException(ex);
                        JobResult.Status       = TaskStatusInfo.ERROR;
                        mailResult.Success     = false;
                        mailResult.ReportState = "ERROR";
                        mailResult.TaskName    = JobResult.TaskName;
                        mailResult.Message     = JobResult?.Exception?.FullMessage ?? null;
                        Results.Add(mailResult);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex, "The delivery via 'Mail' failed.");
                JobResult.Exception = ReportException.GetException(ex);
                JobResult.Status    = TaskStatusInfo.ERROR;
                var errorResult = new MailResult()
                {
                    Success     = false,
                    ReportState = "ERROR",
                    TaskName    = JobResult?.TaskName ?? "Unknown Task",
                    Message     = JobResult?.Exception?.FullMessage ?? null
                };
                Results.Add(errorResult);
            }
        }
            private static ExceptionData GetExceptionDataFromReportException(ReportException ex)
            {
                PropertySet properties = null;

                foreach (object obj in ex.Properties)
                {
                    ReportProperty property = obj as ReportProperty;
                    if (property != null && property.Value != null)
                    {
                        if (properties == null)
                            properties = new PropertySet();
                        properties[property.Name] = property.Value;
                    }
                }

                return new ExceptionData(ex.Type ?? "", ex.Message ?? "", ex.StackTrace ?? "",
                    properties ?? ExceptionData.NoProperties,
                    ex.Exception != null ? GetExceptionDataFromReportException(ex.Exception) : null);
            }
Пример #30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="JPushClient" /> class.
 /// </summary>
 /// <param name="appKey">The application key.</param>
 /// <param name="masterSecret">The master secret.</param>
 /// <param name="pushResultUpdate">The update push message status delegate.</param>
 /// <param name="pushTrackingInitialize">The initialize delegate.</param>
 /// <param name="exceptionReport">The exception delegate.</param>
 /// <param name="threadInterval">The interval in second.</param>
 public JPushHandler(string appKey, string masterSecret, int threadInterval = 60, UpdatePushResult pushResultUpdate = null, InitializePushTracking pushTrackingInitialize = null, ReportException exceptionReport = null)
 {
     JPushClient = new JPushClient(appKey, masterSecret, true);
     if (threadInterval < 1)
     {
         threadInterval = 60;
     }
     this.ThreadInterval         = threadInterval;
     this.PushTrackings          = new List <Tracking>();
     this.DataLocker             = new object();
     this.PushResultUpdate       = pushResultUpdate;
     this.PushTrackingInitialize = pushTrackingInitialize;
     this.ExceptionReport        = exceptionReport;
     this.InitializeMonitorThreadInBackground();
 }
 public GenericRepository(IMContext context, ReportException exHandler)
 {
     this.context   = context;
     this.exHandler = exHandler;
     this.dbSet     = context.Set <TEntity>();
 }
        private void BworkerDoWork()
        {
            Host currentHost = null;

            try
            {
                List <Host> hosts = GetAllHosts(_mastersToUpgrade);

                bool   currentMasterFailed      = false;
                string poolHigherProductVersion = string.Empty;
                for (int i = 0; i < hosts.Count; i++)
                {
                    if (_cancel)
                    {
                        return;
                    }
                    //Skip hosts already upgraded
                    var host = currentHost = hosts[i];
                    if (host.IsMaster())
                    {
                        poolHigherProductVersion = host.LongProductVersion;
                        if (CheckMasterIsUpgraded(hosts, i))
                        {
                            log.Debug(string.Format("Skipping master '{0}' because it is upgraded", host.Name));
                            continue;
                        }
                    }
                    else if (host.LongProductVersion == poolHigherProductVersion)
                    {
                        log.Debug(string.Format("Skipping host '{0}' because it is upgraded", host.Name));
                        continue;
                    }
                    log.Debug(string.Format("Starting to upgrade host '{0}'", host.Name));
                    //Add subtasks for the current host
                    bool allActionsDone = true;
                    foreach (var planAction in _planActions[host])
                    {
                        //if the wizard has been cancelled, skip this action, unless it is a BringBabiesBackAction
                        if (_cancel && !(planAction is BringBabiesBackAction))
                        {
                            continue;
                        }

                        PlanAction action = planAction;
                        ReportRunning.Raise(this, () => new ReportRunningArgs(action, host));
                        try
                        {
                            if (planAction is UpgradeManualHostPlanAction)
                            {
                                var upgradeAction = (UpgradeManualHostPlanAction)planAction;
                                ManageSemiAutomaticPlanAction.Raise(this, () => new ManageSemiAutomaticPlanActionArgs(upgradeAction));
                                if (host.IsMaster())
                                {
                                    poolHigherProductVersion = upgradeAction.Host.LongProductVersion;
                                }
                            }
                            else
                            {
                                planAction.Run();
                            }
                        }
                        catch (Exception excep)
                        {
                            log.Error(string.Format("Exception in host '{0}' while it was upgraded", host.Name), excep);
                            PlanAction action1 = planAction;
                            ReportException.Raise(this, () => new ReportExceptionArgs(excep, action1, host));
                            if (host.IsMaster())
                            {
                                currentMasterFailed = true;
                            }
                            allActionsDone = false;
                            break;
                        }
                    }

                    if (allActionsDone)
                    {
                        ReportHostDone.Raise(this, () => new ReportHostDoneArgs(host));
                    }

                    //Skip slaves if master failed
                    if (currentMasterFailed)
                    {
                        i = SkipSlaves(hosts, i);
                    }
                }
            }
            catch (Exception excep)
            {
                log.Error("Upgrade thread error: ", excep);
            }
            finally
            {
                //Revert resolved prechecks
                try
                {
                    log.Debug("Reverting prechecks");
                    ReportRunning.Raise(this, () => new ReportRunningArgs(_revertAction, currentHost));
                    _revertAction.Run();
                    ReportRevertDone.Raise(this, () => new ReportRevertDoneArgs(_revertAction));
                }
                catch (Exception excep)
                {
                    log.Error("Exception reverting prechecks", excep);
                    ReportException.Raise(this, () => new ReportExceptionArgs(excep, _revertAction, currentHost));
                }

                Completed.Raise(this);
            }
        }
Пример #33
0
        public void UploadToHub(Report report, HubSettings settings, Connection socketConnection)
        {
            var reportName = report?.Name ?? null;

            if (String.IsNullOrEmpty(reportName))
            {
                throw new Exception("The report filename is empty.");
            }

            if (String.IsNullOrEmpty(settings.Owner))
            {
                throw new Exception("No owner for shared content found.");
            }

            //Delete reports from hub before uploaded!
            if (settings.Mode == DistributeMode.DELETEALLFIRST)
            {
                DeleteReportsFromHub(report, settings, socketConnection);
            }

            foreach (var reportPath in report.Paths)
            {
                try
                {
                    var fileData    = report.Data.FirstOrDefault(f => f.Filename == Path.GetFileName(reportPath));
                    var contentName = GetContentName(reportName, fileData);

                    // Copy with report name - Important for other delivery options.
                    var uploadCopyReportPath = Path.Combine(Path.GetDirectoryName(reportPath), $"{reportName}{Path.GetExtension(reportPath)}");
                    File.Copy(reportPath, uploadCopyReportPath, true);

                    if (settings.Mode == DistributeMode.OVERRIDE ||
                        settings.Mode == DistributeMode.CREATEONLY)
                    {
                        var uploadResult = new HubResult()
                        {
                            ReportName = reportName,
                        };

                        HubInfo hubInfo   = null;
                        Guid?   hubUserId = null;

                        var qrsApi = GetQrsApiConnection(socketConnection);
                        logger.Debug($"Use the following Qlik user '{settings.Owner}'...");
                        var hubUser = new DomainUser(settings.Owner, true);
                        var filter  = $"userId eq '{hubUser.UserId}' and userDirectory eq '{hubUser.UserDirectory}'";
                        logger.Debug($"Use Filter '{filter}'...");
                        var result = qrsApi.SendRequestAsync("user", HttpMethod.Get, null, filter).Result;
                        logger.Debug($"QRS Result for user: '******'");
                        if (result == null || result == "[]")
                        {
                            throw new Exception($"Qlik user {settings.Owner} was not found or session not connected (QRS).");
                        }
                        var userObject = JArray.Parse(result);
                        if (userObject.Count > 1)
                        {
                            throw new Exception($"Too many User found. {result}");
                        }
                        else if (userObject.Count == 1)
                        {
                            hubUserId = new Guid(userObject.First()["id"].ToString());
                        }
                        logger.Debug($"hubUser id is '{hubUserId}'.");

                        var sharedContent = GetSharedContentFromUser(contentName, hubUser, qrsApi);
                        if (sharedContent == null)
                        {
                            var createRequest = new HubCreateRequest()
                            {
                                Name        = contentName,
                                ReportType  = settings.SharedContentType,
                                Description = "Created by Analytics Gate",
                                Tags        = new List <Tag>()
                                {
                                    new Tag()
                                    {
                                        Name         = "SER",
                                        CreatedDate  = DateTime.Now,
                                        ModifiedDate = DateTime.Now
                                    }
                                },
                                Data = new ContentData()
                                {
                                    ContentType  = $"application/{Path.GetExtension(fileData.Filename).Trim('.')}",
                                    ExternalPath = Path.GetFileName(uploadCopyReportPath),
                                    FileData     = fileData.DownloadData,
                                }
                            };

                            logger.Debug($"Create request '{JsonConvert.SerializeObject(createRequest)}'");
                            hubInfo = qrsApi.CreateSharedContentAsync(createRequest).Result;
                            logger.Debug($"Create response '{JsonConvert.SerializeObject(hubInfo)}'");
                        }
                        else
                        {
                            if (settings.Mode == DistributeMode.OVERRIDE)
                            {
                                var tag = sharedContent?.Tags?.FirstOrDefault(t => t.Name == "SER") ?? null;
                                if (tag != null)
                                {
                                    tag.CreatedDate  = DateTime.Now;
                                    tag.ModifiedDate = DateTime.Now;
                                }
                                var updateRequest = new HubUpdateRequest()
                                {
                                    Info = sharedContent,
                                    Data = new ContentData()
                                    {
                                        ContentType  = $"application/{Path.GetExtension(fileData.Filename).Trim('.')}",
                                        ExternalPath = Path.GetFileName(uploadCopyReportPath),
                                        FileData     = fileData.DownloadData,
                                    }
                                };

                                logger.Debug($"Update request '{JsonConvert.SerializeObject(updateRequest)}'");
                                hubInfo = qrsApi.UpdateSharedContentAsync(updateRequest).Result;
                                logger.Debug($"Update response '{JsonConvert.SerializeObject(hubInfo)}'");
                            }
                            else
                            {
                                throw new Exception($"The shared content '{contentName}' already exist.");
                            }
                        }

                        if (hubUserId != null)
                        {
                            //change shared content owner
                            logger.Debug($"Change shared content owner '{hubUserId}' (User: '******').");
                            var newHubInfo = new HubInfo()
                            {
                                Id    = hubInfo.Id,
                                Type  = settings.SharedContentType,
                                Owner = new Owner()
                                {
                                    Id            = hubUserId.ToString(),
                                    UserId        = hubUser.UserId,
                                    UserDirectory = hubUser.UserDirectory,
                                    Name          = hubUser.UserId,
                                }
                            };

                            var changeRequest = new HubUpdateRequest()
                            {
                                Info = newHubInfo,
                            };
                            logger.Debug($"Update Owner request '{JsonConvert.SerializeObject(changeRequest)}'");
                            var ownerResult = qrsApi.UpdateSharedContentAsync(changeRequest).Result;
                            logger.Debug($"Update Owner response '{JsonConvert.SerializeObject(ownerResult)}'");
                        }

                        // Get fresh shared content infos
                        var filename = Path.GetFileName(uploadCopyReportPath);
                        filename = filename.Replace("+", " ");
                        hubInfo  = GetSharedContentFromUser(contentName, hubUser, qrsApi);
                        logger.Debug("Get shared content link.");
                        var link = hubInfo?.References?.FirstOrDefault(r => r.LogicalPath.Contains($"/{filename}"))?.ExternalPath ?? null;
                        if (link == null)
                        {
                            throw new Exception($"The download link is empty. Please check the security rules. (Name: {filename} - References: {hubInfo?.References?.Count}) - User: {hubUser}.");
                        }

                        Results.Add(new HubResult()
                        {
                            Success     = true,
                            ReportState = GetFormatedState(),
                            TaskName    = JobResult.TaskName,
                            Message     = "Upload to the hub was successful.",
                            Link        = link,
                            ReportName  = contentName,
                            FullLink    = GetFullLink(qrsApi.ConnectUri, link)
                        });
                    }
                    else
                    {
                        throw new Exception($"Unknown hub mode {settings.Mode}");
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex, "The delivery via 'Hub' failed.");
                    JobResult.Exception = ReportException.GetException(ex);
                    JobResult.Status    = TaskStatusInfo.ERROR;
                    Results.Add(new HubResult()
                    {
                        Success     = false,
                        ReportState = "ERROR",
                        TaskName    = JobResult.TaskName,
                        Message     = ex.Message
                    });
                }
                finally
                {
                    socketConnection.IsFree = true;
                }
            }
        }