Beispiel #1
0
        /// <summary>
        /// 记录异常日志
        /// </summary>
        /// <param name="ex"></param>
        private void WriteAppErrorLog(Exception ex)
        {
            ex.Data.Add("category", LogCategory.APP_ERROR);
            if (ex is FaultException)
            {
                FaultException fault = ex as FaultException;
                ex.Data.Add("errorCode", fault.ErrorCode);
                ex.Data.Add("errorMessage", fault.ErrorMsg);
            }
            else
            {
                ex.Data.Add("errorCode", "99999");
                ex.Data.Add("errorMessage", "未定义的异常及错误!");
            }

            CertificateResult certificateResult = CallContext.GetData("Certificate") as CertificateResult;

            ex.Data.Add("systemCode", certificateResult != null ? certificateResult.SystemCode : string.Empty);
            ex.Data.Add("orgCode", certificateResult != null ? certificateResult.OrgCode : string.Empty);

            bool rethrow = ExceptionPolicy.HandleException(ex, "Zysoft Exception Policy");

            if (rethrow)
            {
                throw ex;
            }
        }
Beispiel #2
0
        public static async Task WriteToFile(this CertificateResult certificate, string outputPath = null)
        {
            var path = "";

            if (!string.IsNullOrWhiteSpace(outputPath))
            {
                path = outputPath;
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }

            //Write Cert
            var certFilePath = Path.Combine(path, $"{certificate.Domain}.pem");

            await using (var writer = File.CreateText(certFilePath))
            {
                await writer.WriteLineAsync(certificate.Cert);

                Console.WriteLine($"Certificate writed to {certFilePath}");
            }

            //Write Key
            var keyFilePath = Path.Combine(path, $"{certificate.Domain}.key");

            await using (var writer = File.CreateText(keyFilePath))
            {
                await writer.WriteLineAsync(certificate.Key);

                Console.WriteLine($"Key writed to {keyFilePath}");
            }
        }
Beispiel #3
0
        public bool Generate()
        {
            using (var dlg = new SaveFileDialog())
            {
                dlg.Filter =
                    @"X.509 Certificate files (*.cer;*.crt;*.cert;*.pem)|*.cer;*.crt;*.cert;*.pem|Pem files (*.pem)|*.pem|Crt files (*.crt)|*.crt|All files (*.*)|*.*";
                dlg.FilterIndex      = 0;
                dlg.RestoreDirectory = true;

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    var certificateGenerator = new DefaultServerCertificateGenerator(new DefaultUrlEvaluator());

                    DateTime beginDate = View.From;
                    DateTime endDate   = beginDate.AddDays(View.Duration);


                    X509Certificate         caFile         = IOPEMUtils.LoadPemCertificate(View.CAFile);
                    AsymmetricCipherKeyPair caPriveKeyFile = IOPEMUtils.LoadPemPrivateKey(View.CAPrivateKeyFile);


                    CertificateResult result = certificateGenerator.Create(
                        View.Algoritm,
                        View.KeyLength,
                        View.Subject,
                        View.AlternateNames,
                        beginDate,
                        endDate,
                        View.KeyUsage,
                        View.Purpose,
                        caFile,
                        caPriveKeyFile,
                        new CertificateEndPoints
                    {
                        CaDistributionEndPoint  = View.CaUri,
                        CrlDistributionEndPoint = View.CrlUri,
                        OcspEndPoint            = View.OcspUri
                    }
                        );

                    ResultFileNames files = IOPEMUtils.SaveCertificateAndPrivateKey(result.Certificate, result.KeyPair,
                                                                                    dlg.FileName);

                    MessageBox.Show(
                        String.Format("Foram gravados os ficheiros:\nCertificado como '{0}'\nChave privada como '{1}'",
                                      files.Certificate,
                                      files.PrivateKey), @"Informação",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information
                        );

                    return(true);
                }

                return(false);
            }
        }
Beispiel #4
0
        /// <summary>
        /// 记录调用日志
        /// </summary>
        /// <param name="callTimeStart"></param>
        /// <param name="callTimeEnd"></param>
        private void WriteServiceCallLog(string introduction, DateTime callTimeStart, DateTime callTimeEnd)
        {
            LogEntry log = new LogEntry();

            log.EventId = 100;
            log.Title   = introduction;
            log.Categories.Add(LogCategory.SERVICE_CALL);
            log.ExtendedProperties.Add("category", LogCategory.SERVICE_CALL);
            log.ExtendedProperties.Add("callTimeStart", callTimeStart.ToTimeString());
            log.ExtendedProperties.Add("callTimeEnd", callTimeEnd.ToTimeString());
            log.ExtendedProperties.Add("callInterval", (callTimeEnd - callTimeStart).TotalMilliseconds);

            CertificateResult certificateResult = CallContext.GetData("Certificate") as CertificateResult;

            log.ExtendedProperties.Add("systemCode", certificateResult != null ? certificateResult.SystemCode : string.Empty);
            log.ExtendedProperties.Add("orgCode", certificateResult != null ? certificateResult.OrgCode : string.Empty);
            Logger.Write(log);
        }
        public bool Generate()
        {
            using (var dlg = new SaveFileDialog())
            {
                dlg.Filter =
                    @"X.509 Certificate files (*.cer;*.crt;*.cert;*.pem)|*.cer;*.crt;*.cert;*.pem|Pem files (*.pem)|*.pem|Crt files (*.crt)|*.crt|All files (*.*)|*.*";
                dlg.FilterIndex      = 0;
                dlg.RestoreDirectory = true;

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    var certificateGenerator = new DefaultSelfSignedCertificateGenerator();

                    DateTime          beginDate = View.From;
                    DateTime          endDate   = beginDate.AddDays(View.Duration);
                    CertificateResult result    = certificateGenerator.Create(
                        View.Algoritm,
                        View.KeyLength,
                        View.Subject,
                        beginDate,
                        endDate,
                        View.KeyUsage,
                        View.Purpose
                        );

                    ResultFileNames files = IOPEMUtils.SaveCertificateAndPrivateKey(result.Certificate, result.KeyPair,
                                                                                    dlg.FileName);

                    MessageBox.Show(
                        String.Format("Foram gravados os ficheiros:\nCertificado como '{0}'\nChave privada como '{1}'",
                                      files.Certificate,
                                      files.PrivateKey), @"Informação",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information
                        );

                    return(true);
                }
            }

            return(false);
        }
        public CertificateResult GetPage(string filter, int?draw, int?initialPage, int?pageSize, string sortDir, string sortBy)
        {
            using (SATEntities db = new SATEntities())
            {
                var data = db.tb_Certificate.ToList();

                int recordsTotal = data.Count();

                if (!string.IsNullOrEmpty(filter))
                {
                    data = data.Where(x => x.CerName.Contains(filter)).ToList();
                }

                int recordsFiltered = data.Count();

                switch (sortBy)
                {
                case "CerName":
                    data = (sortDir == "asc") ? data.OrderBy(x => x.CerName).ToList() : data.OrderByDescending(x => x.CerName).ToList();
                    break;
                }

                int start  = initialPage.HasValue ? (int)initialPage / (int)pageSize : 0;
                int length = pageSize ?? 10;

                var list = data.Select((s, i) => new CertificateViewModel()
                {
                    RowNumber = i + 1,
                    CerID     = s.CerId,
                    CerName   = s.CerName
                }).Skip(start * length).Take(length).ToList();

                CertificateResult result = new CertificateResult();
                result.draw            = draw ?? 0;
                result.recordsTotal    = recordsTotal;
                result.recordsFiltered = recordsFiltered;
                result.data            = list;

                return(result);
            }
        }
Beispiel #7
0
        public override void Compare(string firstRunId, string secondRunId)
        {
            try
            {
                if (firstRunId == null)
                {
                    throw new ArgumentNullException("firstRunId");
                }
                if (secondRunId == null)
                {
                    throw new ArgumentNullException("secondRunId");
                }


                var addObjects = new List <CertificateResult>();
                var cmd        = new SqliteCommand(SELECT_INSERTED_SQL, DatabaseManager.Connection, DatabaseManager.Transaction);
                cmd.Parameters.AddWithValue("@first_run_id", firstRunId);
                cmd.Parameters.AddWithValue("@second_run_id", secondRunId);
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var obj = new CertificateResult()
                        {
                            BaseRunId     = firstRunId,
                            CompareRunId  = secondRunId,
                            CompareRowKey = reader["row_key"].ToString(),
                            Compare       = new CertificateObject()
                            {
                                StoreLocation         = reader["store_location"].ToString(),
                                StoreName             = reader["store_name"].ToString(),
                                CertificateHashString = reader["hash"].ToString(),
                                Subject = reader["cn"].ToString()
                            },
                            ChangeType = CHANGE_TYPE.CREATED,
                            ResultType = RESULT_TYPE.CERTIFICATE
                        };
                        addObjects.Add(obj);
                        InsertResult(obj);
                    }
                }
                Results["certs_add"] = addObjects;

                Log.Information("Found {0} Created", addObjects.Count);

                var removeObjects = new List <string>();
                cmd = new SqliteCommand(SELECT_DELETED_SQL, DatabaseManager.Connection, DatabaseManager.Transaction);
                cmd.Parameters.AddWithValue("@first_run_id", firstRunId);
                cmd.Parameters.AddWithValue("@second_run_id", secondRunId);
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var obj = new CertificateResult()
                        {
                            BaseRunId     = firstRunId,
                            CompareRunId  = secondRunId,
                            CompareRowKey = reader["row_key"].ToString(),
                            Base          = new CertificateObject()
                            {
                                StoreLocation         = reader["store_location"].ToString(),
                                StoreName             = reader["store_name"].ToString(),
                                CertificateHashString = reader["hash"].ToString(),
                                Subject = reader["cn"].ToString()
                            },
                            ChangeType = CHANGE_TYPE.DELETED,
                            ResultType = RESULT_TYPE.CERTIFICATE
                        };
                        addObjects.Add(obj);
                        InsertResult(obj);
                    }
                }
                Results["certs_remove"] = removeObjects;

                Log.Information("Found Deleted {0} Results", addObjects.Count);
            }
            catch (Exception e)
            {
                Log.Debug(e.StackTrace);
                Log.Debug(e.Message);
                Telemetry.TrackTrace(Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Error, e);
            }
        }