private void frmMain_Shown(object sender, EventArgs e) { CheckLicense c = new CheckLicense(); _certPubicKeyData = c.ActivateLicense(); if (!c.IsLicenseExists()) { //_certPubicKeyData = c.ActivateLicense(); using (frmActivation frm = new frmActivation()) { frm.CertificatePublicKeyData = _certPubicKeyData; frm.ShowDialog(); //Exit the application after activation to reload the license file //Actually it is not nessessary, you may just call the API to reload the license file //Here just simplied the demo process } } else { MyLicense _lic = c.GetLicense(_certPubicKeyData); licInfo.ShowLicenseInfo(_lic); } }
public static void InitLicense() { MemoryStream mem = new MemoryStream(); Assembly.GetExecutingAssembly().GetManifestResourceStream("PrivateWin10.LicenseVerify.cer").CopyTo(mem); byte[] certPubicKeyData = mem.ToArray(); string msg = string.Empty; LicenseStatus status = LicenseStatus.UNDEFINED; if (File.Exists("license.lic")) { lic = (MyLicense)LicenseHandler.ParseLicenseFromBASE64String(typeof(MyLicense), File.ReadAllText("license.lic"), certPubicKeyData, out status, out msg); } else { msg = "Your copy of this application is not activated"; } if (lic == null) { lic = new MyLicense(); // we always want this object } lic.LicenseStatus = status; if (status != LicenseStatus.VALID && msg.Length == 0) { msg = "Your license file is invalid or broken"; } if (status == LicenseStatus.INVALID || status == LicenseStatus.CRACKED) { MessageBox.Show(msg, App.mName, MessageBoxButton.OK, MessageBoxImage.Error); } Console.WriteLine(msg); }
private void FormMain_Shown(object sender, EventArgs e) { MyLicense license = LicenseHandler.ReadLicenseFile(out LicenseStatus licStatus, out string validationMsg); switch (licStatus) { case LicenseStatus.Undefined: MessageBox.Show("Brak pliku z licencją!\nIdentyfikator komputera: " + LicenseHandler.GenerateUid("BlobLoader"), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); break; case LicenseStatus.Valid: toolStripStatusLabel.Text = $"Licencja typu: '{license.Type}', ważna do: {license.LicenseEnd}"; break; case LicenseStatus.Invalid: case LicenseStatus.Cracked: case LicenseStatus.Expired: MessageBox.Show(validationMsg, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); break; default: throw new ArgumentOutOfRangeException(); } }
private void frmMain_Shown(object sender, EventArgs e) { //Initialize variables with default values MyLicense _lic = null; var _msg = string.Empty; LicenseStatus _status; //Read public key from resources _certPubicKeyData = DemoLicense.Properties.Resource.Licensing; //Check if the XML license file exists if (File.Exists("license.lic")) { _lic = (MyLicense)LicenseHandler.ParseLicenseFromBASE64String( typeof(MyLicense), File.ReadAllText("license.lic"), _certPubicKeyData, out _status); } else { _status = LicenseStatus.INVALID; _msg = "Your copy of this application is not activated"; } switch (_status) { case LicenseStatus.VALID: //TODO: If license is valid, you can do extra checking here //TODO: E.g., check license expiry date if you have added expiry date property to your license entity //TODO: Also, you can set feature switch here based on the different properties you added to your license entity //Here for demo, just show the license information and RETURN without additional checking licInfo.ShowLicenseInfo(_lic); return; default: //for the other status of license file, show the warning message //and also popup the activation form for user to activate your application MessageBox.Show(_msg, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Warning); using (var frm = new frmActivation()) { frm.CertificatePublicKeyData = _certPubicKeyData; frm.ShowDialog(); //Exit the application after activation to reload the license file //Actually it is not nessessary, you may just call the API to reload the license file //Here just simplied the demo process Application.Exit(); } break; } }
public void CreateNewLicense(string licenseFile, DateTime expiryDate, String name = null, String otherMetadata = null) { MyLicense thisLicense = new MyLicense(); thisLicense.Data.Created = DateTime.UtcNow; thisLicense.Data.Expiry = expiryDate; thisLicense.Data.ExtraData = otherMetadata; thisLicense.Data.Name = name; CreateNewLicense(licenseFile, thisLicense); }
private void CheckLicense() { //Initialize variables with default values MyLicense _lic = null; string _msg = string.Empty; LicenseStatus _status = LicenseStatus.UNDEFINED; //Read public key from assembly Assembly _assembly = Assembly.GetExecutingAssembly(); using (MemoryStream _mem = new MemoryStream()) { _assembly.GetManifestResourceStream("TMF_ftp.LicenseVerify.cer").CopyTo(_mem); _certPubicKeyData = _mem.ToArray(); } //Check if the XML license file exists if (File.Exists("license.lic")) { _lic = (MyLicense)LicenseHandler.ParseLicenseFromBASE64String( typeof(MyLicense), File.ReadAllText("license.lic"), _certPubicKeyData, out _status, out _msg); } else { _status = LicenseStatus.INVALID; _msg = "This application is not activated"; } switch (_status) { case LicenseStatus.VALID: //TODO: If license is valid, you can do extra checking here //TODO: E.g., check license expiry date if you have added expiry date property to your license entity //TODO: Also, you can set feature switch here based on the different properties you added to your license entity return; default: MessageBox.Show(_msg, "TMF ftp", MessageBoxButtons.OK, MessageBoxIcon.Warning); using (frmActivation frm = new frmActivation()) { frm.CertificatePublicKeyData = _certPubicKeyData; frm.ShowDialog(); Application.Exit(); } break; } }
//许可证 public JsonResult LicenseGet() { var item = dbhelper.GetAll(u => u.id).FirstOrDefault(); if (item != null) { } else { item = new Models.a_systeminfo(); item.system_id = Guid.NewGuid().ToString().ToUpper(); item.system_name = ""; item.system_worksitename = ""; item.company_name = ""; item.company_linkman = ""; item.company_tel = ""; item.company_address = ""; item.system_licenseno = "未授权"; item.system_effdate_e = "未授权"; item.system_effdate_s = "未授权"; } string directoryPath = Server.MapPath("~/LicenseFile/"); string filepath = directoryPath + "License.lic"; MyLicense license = MyLicenseHelper.Get(filepath); if (license.licenseno == "") { item.system_licenseno = "未授权"; item.system_effdate_e = "未授权"; item.system_effdate_s = "未授权"; } else { item.system_licenseno = license.licenseno; item.system_effdate_s = license.licensedatestart.ToString("yyyy-MM-dd"); item.system_effdate_e = license.licensedateend.ToString("yyyy-MM-dd"); } LinenceMap linenceMap = new LinenceMap(); linenceMap.system_licenseno = item.system_licenseno; linenceMap.system_effdate_s = item.system_effdate_s; linenceMap.system_effdate_e = item.system_effdate_e; string hardcode = Computer.GetBIOSInfo().ToUpper(); hardcode = DESEncrypt.md5(hardcode, 32).ToUpper(); linenceMap.system_hardwarecode = hardcode; return(Json(linenceMap, JsonRequestBehavior.AllowGet)); }
// // GET: /Admin/Systemlicense/ public ActionResult Index() { var item = new Models.a_systeminfo(); var list = dbhelper.GetAll(u => u.id); if (list.Count > 0) { item = list.FirstOrDefault(); } else { item = new Models.a_systeminfo(); item.system_id = Guid.NewGuid().ToString().ToUpper(); item.system_name = ""; item.system_worksitename = ""; item.company_name = ""; item.company_linkman = ""; item.company_tel = ""; item.company_address = ""; item.system_licenseno = "未授权"; item.system_effdate_e = "未授权"; item.system_effdate_s = "未授权"; } string directoryPath = Server.MapPath("~/LicenseFile/"); string filepath = directoryPath + "License.lic"; MyLicense license = MyLicenseHelper.Get(filepath); if (license.licenseno == "") { item.system_licenseno = "未授权"; item.system_effdate_e = "未授权"; item.system_effdate_s = "未授权"; } else { item.system_licenseno = license.licenseno; item.system_effdate_s = license.licensedatestart.ToString("yyyy-MM-dd"); item.system_effdate_e = license.licensedateend.ToString("yyyy-MM-dd"); } ViewBag.entity = item; string hardcode = Computer.GetBIOSInfo().ToUpper(); hardcode = DESEncrypt.md5(hardcode, 32).ToUpper(); ViewBag.system_hardwarecode = hardcode; return(View()); }
public static string LicenseToXmlString(MyLicense license) { XmlSerializer xsSubmit = new XmlSerializer(typeof(MyLicense)); using (var sww = new StringWriter()) { using (XmlWriter writer = XmlWriter.Create(sww)) { xsSubmit.Serialize(writer, license); return(sww.ToString()); } } }
private void ButtonGeneruj_Click(object sender, EventArgs e) { MyLicense licencja = new MyLicense { LicenseOwner = textBoxOwner.Text, CreateDateTime = DateTime.Now, LicenseNumber = textBoxLicenseNumber.Text, LicenseEnd = new DateTime(dateTimePickerKoniec.Value.Year, dateTimePickerKoniec.Value.Month, dateTimePickerKoniec.Value.Day, 23, 59, 59), Atr1 = textBoxAtr1.Text }; using (MemoryStream ms = new MemoryStream()) using (Bitmap bitmap = new Bitmap(pictureBoxLogo.Image)) { bitmap.Save(ms, ImageFormat.Png); licencja.LogoOwner = Convert.ToBase64String(ms.GetBuffer()); } if (radioButtonSingle.Checked) { if (LicenseHandler.ValidateUidFormat(textBoxUid.Text.Trim())) { licencja.Type = LicenseTypes.Single; licencja.Uid = textBoxUid.Text.Trim(); } else { MessageBox.Show(@"Błędny lub pusty identyfikator licencji", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } } else if (radioButtonVolume.Checked) { licencja.Type = LicenseTypes.Volume; licencja.Uid = string.Empty; } byte[] certPrivateKeyData; Assembly assembly = Assembly.GetExecutingAssembly(); using (MemoryStream memoryStream = new MemoryStream()) { assembly.GetManifestResourceStream("LicenseGenerator.LicenseSign.pfx")?.CopyTo(memoryStream); certPrivateKeyData = memoryStream.ToArray(); } textBoxLicencja.Text = LicenseHandler.GenerateLicense(licencja, certPrivateKeyData, _certPwd); }
private void ButtonReadLicense_Click(object sender, EventArgs e) { byte[] certPublicKeyData; Assembly assembly = Assembly.GetExecutingAssembly(); using (MemoryStream memoryStream = new MemoryStream()) { assembly.GetManifestResourceStream("LicenseGenerator.LicenseVerify.cer")?.CopyTo(memoryStream); certPublicKeyData = memoryStream.ToArray(); } MyLicense license = (MyLicense)LicenseHandler.ReadLicense(typeof(MyLicense), textBoxLicencja.Text, certPublicKeyData, out LicenseStatus status, out string msg); switch (status) { case LicenseStatus.Undefined: MessageBox.Show(@"By używać tej aplikacji musisz posiadać ważną licencję", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); break; case LicenseStatus.Invalid: case LicenseStatus.Cracked: MessageBox.Show(msg, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); break; case LicenseStatus.Valid: case LicenseStatus.Expired: textBoxUid.Text = license.Uid; textBoxLicenseNumber.Text = license.LicenseNumber; textBoxOwner.Text = license.LicenseOwner.Replace("\n", Environment.NewLine); dateTimePickerKoniec.Value = license.LicenseEnd; using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(license.LogoOwner))) { Bitmap bm = new Bitmap(ms); pictureBoxLogo.Image = bm; } break; default: throw new ArgumentOutOfRangeException(); } }
public static void InitLicense() { MemoryStream mem = new MemoryStream(); Assembly.GetExecutingAssembly().GetManifestResourceStream("PrivateWin10.LicenseVerify.cer").CopyTo(mem); byte[] certPubicKeyData = mem.ToArray(); string msg = string.Empty; LicenseStatus status = LicenseStatus.UNDEFINED; if (File.Exists("license.lic")) { lic = (MyLicense)LicenseHandler.ParseLicenseFromBASE64String(typeof(MyLicense), File.ReadAllText(App.appPath + @"\license.lic"), certPubicKeyData, out status, out msg); } else { msg = "Your copy of this application is not activated"; } if (lic == null) { lic = new MyLicense(); // we always want this object } lic.LicenseStatus = status; if (status != LicenseStatus.VALID && msg.Length == 0) { msg = "Your license file is invalid or broken"; } if (status == LicenseStatus.INVALID || status == LicenseStatus.CRACKED) { MessageBox.Show(msg, App.Title, MessageBoxButton.OK, MessageBoxImage.Error); } Console.WriteLine(msg); if (status != LicenseStatus.VALID) { string use = App.GetConfig("Startup", "Usage", ""); if (use.Equals("business", StringComparison.OrdinalIgnoreCase) || use.Equals("commertial", StringComparison.OrdinalIgnoreCase)) { lic.CommercialUse = true; if (IsEvaluationExpired()) { MessageBox.Show("The commercial evaluation period of PrivateWin10 has expired, please purchase an appropriate license.", string.Empty, MessageBoxButton.OK, MessageBoxImage.Warning); } } } }
public JsonResult GetLicense() { string directoryPath = Server.MapPath("~/LicenseFile/"); string filepath = directoryPath + "/" + "License.lic"; MyLicense license = MyLicenseHelper.Get(filepath); return(Json(new { LicenseNo = license.licenseno, LicenseEffdateStart = license.licensedatestart.ToString("yyyy-MM-dd"), LicenseEffdateEnd = license.licensedateend.ToString("yyyy-MM-dd") }, JsonRequestBehavior.AllowGet)); }
public bool VerifyLicense(MyLicense license) { RSA rsa = RSA.Create(); rsa.ImportParameters(license.Key); if (rsa.VerifyData(license.getData, license.Signature, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1)) { if (license.Data.Expiry < DateTime.Now) { return(false); } return(true); } return(false); }
//系统信息 public JsonResult SystemInfoData() { var item = new Models.a_systeminfo(); var list = dbhelper.GetAll(u => u.id); if (list.Count > 0) { item = list.FirstOrDefault(); } else { item = new Models.a_systeminfo(); item.system_id = Guid.NewGuid().ToString().ToUpper(); item.system_name = ""; item.system_worksitename = ""; item.company_name = ""; item.company_linkman = ""; item.company_tel = ""; item.company_address = ""; item.system_licenseno = "未授权"; item.system_effdate_e = "未授权"; item.system_effdate_s = "未授权"; } string directoryPath = Server.MapPath("~/LicenseFile/"); string filepath = directoryPath + "/" + "License.lic"; MyLicense license = MyLicenseHelper.Get(filepath); if (license.licenseno == "") { item.system_licenseno = "未授权"; item.system_effdate_e = "未授权"; item.system_effdate_s = "未授权"; } else { item.system_licenseno = license.licenseno; item.system_effdate_s = license.licensedatestart.ToString("yyyy-MM-dd"); item.system_effdate_e = license.licensedateend.ToString("yyyy-MM-dd"); } return(Json(item, JsonRequestBehavior.AllowGet)); }
public DemoLicense.MyLicense GetLicense(byte[] certpublickeydata) { MyLicense _lic = null; string _msg = string.Empty; LicenseStatus _status = LicenseStatus.UNDEFINED; if (File.Exists("license.lic")) { _lic = (MyLicense)LicenseHandler.ParseLicenseFromBASE64String( typeof(MyLicense), File.ReadAllText("license.lic"), certpublickeydata, out _status, out _msg); } return(_lic); }
public override License GetLicense(LicenseContext context, Type type, object instance, bool allowExceptions) { MyLicense license = null; string cpuid = GetCpuID(); cpuid = DESLicense.Encrypt(cpuid);//加密 if (context != null) { if (context.UsageMode == LicenseUsageMode.Runtime) { String savedLicenseKey = context.GetSavedLicenseKey(type, null); if (cpuid.Equals(savedLicenseKey)) { return(new MyLicense(this, cpuid)); } } if (license != null) { return(license); } // 打开License文件 'MyLicense.dat' if (Validation(cpuid)) { license = new MyLicense(this, cpuid); } if (license != null) { context.SetSavedLicenseKey(type, cpuid); } } if (license == null) { //System.Windows.Forms.MessageBox.Show("!!!尚未注册!!!"); throw new LicenseException(type, instance, "Your license is invalid");; //return new MyLicense(this,"no"); } return(license); }
private void ButtonGeneruj_Click(object sender, EventArgs e) { MyLicense licencja = new MyLicense { LicenseOwner = textBoxOwner.Text, CreateDateTime = DateTime.Now, LicenseNumber = textBoxLicenseNumber.Text, LicenseEnd = new DateTime(dateTimePickerKoniec.Value.Year, dateTimePickerKoniec.Value.Month, dateTimePickerKoniec.Value.Day, 23, 59, 59) }; using (MemoryStream ms = new MemoryStream()) using (Bitmap bitmap = new Bitmap(_logoPath)) { bitmap.Save(ms, ImageFormat.Png); licencja.LogoOwner = Convert.ToBase64String(ms.GetBuffer()); } if (radioButtonSingle.Checked) { if (LicenseHandler.ValidateUidFormat(textBoxUid.Text.Trim())) { licencja.Type = LicenseTypes.Single; licencja.Uid = textBoxUid.Text.Trim(); } else { MessageBox.Show(@"Błędny lub pusty identyfikator licencji", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } } else if (radioButtonVolume.Checked) { licencja.Type = LicenseTypes.Volume; licencja.Uid = string.Empty; } textBoxLicencja.Text = LicenseHandler.GenerateLicense(licencja, _certPrivateKeyData, _certPwd); }
public void ProcessRequest(HttpContext context) { string directoryPath = context.Server.MapPath("~/LicenseFile/"); string filepath = directoryPath + "/" + "License.lic"; MyLicense license = MyLicenseHelper.Get(filepath); if (license.licenseno == "") { //item.system_licenseno = "未授权"; //item.system_effdate_e = "未授权"; //item.system_effdate_s = "未授权"; } else { //item.system_licenseno = license.licenseno; //item.system_effdate_s = license.licensedatestart.ToString("yyyy-MM-dd"); //item.system_effdate_e = license.licensedateend.ToString("yyyy-MM-dd"); } string strXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"; strXml += "<License>"; // strXml += "<hardwarecode><![CDATA[" + license.hardwarecode + "]]></hardwarecode>"; strXml += "<licenseno><![CDATA[" + license.licenseno + "]]></licenseno>"; strXml += "<licensedatestart><![CDATA[" + license.licensedatestart.ToString("yyyy-MM-dd") + "]]></licensedatestart>"; strXml += "<licensedateend><![CDATA[" + license.licensedateend.ToString("yyyy-MM-dd") + "]]></licensedateend>"; // strXml += "</License>"; context.Response.ContentType = "text/plain"; context.Response.ContentEncoding = System.Text.Encoding.UTF8; context.Response.Write(strXml); }
public static void Main(string[] args) { ConsoleColor defaultColor = Console.ForegroundColor; Console.WriteLine(Assembly.GetExecutingAssembly().GetName().Name + " " + Assembly.GetExecutingAssembly().GetName().Version); Console.WriteLine("Copyright (c) 2020 GISNET\n"); MyLicense license = LicenseHandler.ReadLicense(out LicenseStatus licStatus, out string validationMsg); switch (licStatus) { case LicenseStatus.Undefined: Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Brak pliku z licencją!!!\n"); Console.ForegroundColor = defaultColor; Console.WriteLine("Identyfikator komputera: " + LicenseHandler.GenerateUid("ReadOpXML") + '\n'); LogFile.SaveMessage("Brak pliku z licencją: " + LicenseHandler.GenerateUid("ReadOpXML")); Console.ReadKey(false); Environment.Exit(0); break; case LicenseStatus.Valid: Console.WriteLine("Właściciel licencji:"); Console.WriteLine(license.LicenseOwner + "\n"); Console.WriteLine("Licencja dla powiatu: " + license.Atr1 + '\n'); Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine($"Licencja typu: '{license.Type}', ważna do: {license.LicenseEnd}\n"); Console.ForegroundColor = defaultColor; System.Threading.Thread.Sleep(1000); break; case LicenseStatus.Invalid: case LicenseStatus.Cracked: Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(validationMsg); Console.ForegroundColor = defaultColor; Console.ReadKey(false); Environment.Exit(0); break; case LicenseStatus.Expired: Console.WriteLine("Właściciel licencji:"); Console.WriteLine(license.LicenseOwner + "\n"); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(validationMsg); Console.ForegroundColor = defaultColor; Console.ReadKey(false); Environment.Exit(0); break; default: throw new ArgumentOutOfRangeException(); } string startupPath = string.Empty; bool poprawa = false; bool walidacja = false; Parser.Default.ParseArguments <Options>(args).WithParsed(RunOptions).WithNotParsed(HandleParseError); void RunOptions(Options opts) { startupPath = opts.StarupPath; poprawa = opts.Poprawa; walidacja = opts.Walidacja; } void HandleParseError(IEnumerable <Error> errs) { Console.ReadKey(false); Environment.Exit(0); } Console.WriteLine("Wyszukiwanie plików XML w katalogu {0}...", startupPath); List <string> xmlFiles = Directory.EnumerateFiles(startupPath ?? throw new InvalidOperationException(), "*.xml", SearchOption.AllDirectories).ToList(); Console.WriteLine("Znaleziono {0} plików XML.\n", xmlFiles.Count); bool isError = false; foreach (string xmlFile in xmlFiles) { if (license.Atr1 != "0000") { // ReSharper disable once PossibleNullReferenceException if (!Path.GetFileNameWithoutExtension(xmlFile).StartsWith($"P.{license.Atr1}")) { Console.WriteLine(xmlFile + " => " + "błędne oznaczenie powiatu."); ErrorLogFile.SaveMessage(Path.Combine(startupPath, "syntaktyka.log"), xmlFile + " => " + "błędne oznaczenie powiatu."); isError = true; } } } if (isError) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("\nWe wskazanym katalogu znajdują się pliki XML, które nie pasują do schematu XSD (zły powiat)!"); Console.ForegroundColor = defaultColor; Console.ReadKey(true); Environment.Exit(0); } Console.WriteLine("Walidacja syntaktyczna plików XML...\n"); foreach (string xmlFile in xmlFiles) { try { XmlDocument doc = new XmlDocument { PreserveWhitespace = true }; doc.Load(xmlFile); } catch (XmlException e) { Console.WriteLine($@"{xmlFile}: {e.Message}"); ErrorLogFile.SaveMessage(Path.Combine(startupPath, "syntaktyka.log"), xmlFile + " => " + e.Message); isError = true; } } if (isError) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("\nMusisz ręcznie poprawić wskazane błedy by zaczytać pliki XML!"); Console.ForegroundColor = defaultColor; Console.ReadKey(true); Environment.Exit(0); } if (poprawa) { Console.WriteLine("Automatyczna poprawa plików XML...\n"); foreach (string xmlFile in xmlFiles) { XmlDocument doc = new XmlDocument { PreserveWhitespace = true }; doc.Load(xmlFile); doc.FixErrors(); doc.Save(xmlFile); } } Console.WriteLine(walidacja ? "Wczytywanie i walidacja plików XML...\n" : "Wczytywanie plików XML...\n"); Dictionary <int, PzgMaterialZasobu> pzgMaterialZasobuDict = new Dictionary <int, PzgMaterialZasobu>(); List <PzgCel> pzgMaterialZasobuCelList = new List <PzgCel>(); List <CelArchiwalny> pzgMaterialZasobuCelArchList = new List <CelArchiwalny>(); List <DzialkaPrzed> pzgMaterialZasobuDzialkaPrzedList = new List <DzialkaPrzed>(); List <DzialkaPo> pzgMaterialZasobuDzialkaPoList = new List <DzialkaPo>(); Dictionary <int, PzgZgloszenie> pzgZgloszenieDict = new Dictionary <int, PzgZgloszenie>(); List <PzgCel> pzgZgloszenieCelList = new List <PzgCel>(); List <CelArchiwalny> pzgZgloszenieCelArchList = new List <CelArchiwalny>(); List <OsobaUprawniona> pzgZgloszenieOsobaUprawnionaList = new List <OsobaUprawniona>(); XmlReaderSettings settings = new XmlReaderSettings(); if (walidacja) { settings.Schemas.Add("http://www.w3.org/2001/XMLSchema", ".\\xsd\\schemat.xsd"); settings.ValidationType = ValidationType.Schema; settings.ValidationFlags = XmlSchemaValidationFlags.AllowXmlAttributes | XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ReportValidationWarnings; settings.ValidationEventHandler += ValidationEventHandler; } int idFile = 0; foreach (string xmlFile in xmlFiles) { idFile++; XmlReader reader = XmlReader.Create(xmlFile, settings); XmlDocument doc = new XmlDocument { PreserveWhitespace = true }; doc.Load(reader); XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("xmls", "http://www.w3.org/2001/XMLSchema"); PzgMaterialZasobu pzgMaterialZasobu = new PzgMaterialZasobu { IdFile = idFile, XmlPath = xmlFile, IdMaterialu = Path.GetFileNameWithoutExtension(xmlFile) }; pzgMaterialZasobu.IdMaterialuPierwszyCzlon = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_IdMaterialu", "pierwszyCzlon"); pzgMaterialZasobu.IdMaterialuDrugiCzlon = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_IdMaterialu", "drugiCzlon"); pzgMaterialZasobu.IdMaterialuTrzeciCzlon = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_IdMaterialu", "trzeciCzlon"); pzgMaterialZasobu.IdMaterialuCzwartyCzlon = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_IdMaterialu", "czwartyCzlon"); pzgMaterialZasobu.PzgDataPrzyjecia = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_dataPrzyjecia"); pzgMaterialZasobu.DataWplywu = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "dataWplywu"); pzgMaterialZasobu.PzgNazwa = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_nazwa"); pzgMaterialZasobu.PzgPolozenieObszaru = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_polozenieObszaru"); pzgMaterialZasobu.Obreb = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "obreb"); pzgMaterialZasobu.PzgTworcaOsobaId = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_tworca", "osoba_id"); pzgMaterialZasobu.PzgTworcaNazwa = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_tworca", "nazwa"); pzgMaterialZasobu.PzgTworcaRegon = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_tworca", "REGON"); pzgMaterialZasobu.PzgTworcaPesel = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_tworca", "PESEL"); pzgMaterialZasobu.PzgSposobPozyskania = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_sposobPozyskania"); pzgMaterialZasobu.PzgPostacMaterialu = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_postacMaterialu"); pzgMaterialZasobu.PzgRodzNosnika = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_rodzNosnika"); pzgMaterialZasobu.PzgDostep = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_dostep"); pzgMaterialZasobu.PzgPrzyczynyOgraniczen = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_przyczynyOgraniczen"); pzgMaterialZasobu.PzgTypMaterialu = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_typMaterialu"); pzgMaterialZasobu.PzgKatArchiwalna = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_katArchiwalna"); pzgMaterialZasobu.PzgJezyk = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_jezyk"); pzgMaterialZasobu.PzgOpis = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_opis"); pzgMaterialZasobu.PzgOznMaterialuZasobu = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_oznMaterialuZasobu"); pzgMaterialZasobu.OznMaterialuZasobuTyp = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "oznMaterialuZasobuTyp"); pzgMaterialZasobu.OznMaterialuZasobuJedn = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "oznMaterialuZasobuJedn"); pzgMaterialZasobu.OznMaterialuZasobuNr = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "oznMaterialuZasobuNr"); pzgMaterialZasobu.OznMaterialuZasobuRok = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "oznMaterialuZasobuRok"); pzgMaterialZasobu.OznMaterialuZasobuTom = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "oznMaterialuZasobuTom"); pzgMaterialZasobu.OznMaterialuZasobuSepJednNr = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "oznMaterialuZasobuSepJednNr"); pzgMaterialZasobu.OznMaterialuZasobuSepNrRok = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "oznMaterialuZasobuSepNrRok"); pzgMaterialZasobu.PzgDokumentWyl = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_dokumentWyl"); pzgMaterialZasobu.PzgDataWyl = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_dataWyl"); pzgMaterialZasobu.PzgDataArchLubBrak = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_dataArchLubBrak"); pzgMaterialZasobu.PzgCelList = doc.GetXmlValueList(nsmgr, "PZG_MaterialZasobu", "pzg_cel"); pzgMaterialZasobu.CelArchiwalnyList = doc.GetXmlValueList(nsmgr, "PZG_MaterialZasobu", "celArchiwalny"); pzgMaterialZasobu.DzialkaPrzedList = doc.GetXmlValueList(nsmgr, "PZG_MaterialZasobu", "dzialkaPrzed"); pzgMaterialZasobu.DzialkaPoList = doc.GetXmlValueList(nsmgr, "PZG_MaterialZasobu", "dzialkaPo"); pzgMaterialZasobu.Opis2 = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "opis2"); pzgMaterialZasobuDict.Add(pzgMaterialZasobu.IdFile, pzgMaterialZasobu); XmlNodeList nodeList = doc.DocumentElement?.SelectNodes("/xmls:schema/xmls:PZG_MaterialZasobu/xmls:pzg_cel", nsmgr); if (nodeList != null) { pzgMaterialZasobuCelList.AddRange(from XmlNode node in nodeList select new PzgCel { IdFile = idFile, XmlPath = xmlFile, IdMaterialu = Path.GetFileNameWithoutExtension(xmlFile), Value = string.IsNullOrEmpty(node.InnerText) ? "--brak wartosci--" : node.InnerText }); } nodeList = doc.DocumentElement?.SelectNodes("/xmls:schema/xmls:PZG_MaterialZasobu/xmls:celArchiwalny", nsmgr); if (nodeList != null) { pzgMaterialZasobuCelArchList.AddRange(from XmlNode node in nodeList select new CelArchiwalny { IdFile = idFile, XmlPath = xmlFile, IdMaterialu = Path.GetFileNameWithoutExtension(xmlFile), Value = string.IsNullOrEmpty(node.InnerText) ? "--brak wartosci--" : node.InnerText }); } nodeList = doc.DocumentElement?.SelectNodes("/xmls:schema/xmls:PZG_MaterialZasobu/xmls:dzialkaPrzed", nsmgr); if (nodeList != null) { pzgMaterialZasobuDzialkaPrzedList.AddRange(from XmlNode node in nodeList select new DzialkaPrzed { IdFile = idFile, XmlPath = xmlFile, IdMaterialu = Path.GetFileNameWithoutExtension(xmlFile), Value = string.IsNullOrEmpty(node.InnerText) ? "--brak wartosci--" : node.InnerText }); } nodeList = doc.DocumentElement?.SelectNodes("/xmls:schema/xmls:PZG_MaterialZasobu/xmls:dzialkaPo", nsmgr); if (nodeList != null) { pzgMaterialZasobuDzialkaPoList.AddRange(from XmlNode node in nodeList select new DzialkaPo { IdFile = idFile, XmlPath = xmlFile, IdMaterialu = Path.GetFileNameWithoutExtension(xmlFile), Value = string.IsNullOrEmpty(node.InnerText) ? "--brak wartosci--" : node.InnerText }); } PzgZgloszenie pzgZgloszenie = new PzgZgloszenie { IdFile = idFile, XmlPath = xmlFile, IdMaterialu = Path.GetFileNameWithoutExtension(xmlFile) }; pzgZgloszenie.PzgOznMaterialuZasobu = pzgMaterialZasobu.PzgOznMaterialuZasobu; pzgZgloszenie.PzgIdZgloszenia = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "pzg_idZgloszenia"); pzgZgloszenie.IdZgloszeniaJedn = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "idZgloszeniaJedn"); pzgZgloszenie.IdZgloszeniaNr = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "idZgloszeniaNr"); pzgZgloszenie.IdZgloszeniaRok = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "idZgloszeniaRok"); pzgZgloszenie.IdZgloszeniaEtap = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "idZgloszeniaEtap"); pzgZgloszenie.IdZgloszeniaSepJednNr = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "idZgloszeniaSepJednNr"); pzgZgloszenie.IdZgloszeniaSepNrRok = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "idZgloszeniaSepNrRok"); pzgZgloszenie.PzgDataZgloszenia = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "pzg_dataZgloszenia"); pzgZgloszenie.PzgPolozenieObszaru = doc.GetXmlValue(nsmgr, "PZG_MaterialZasobu", "pzg_polozenieObszaru"); pzgZgloszenie.Obreb = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "obreb"); pzgZgloszenie.PzgPodmiotZglaszajacyOsobaId = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "pzg_podmiotZglaszajacy", "osoba_id"); pzgZgloszenie.PzgPodmiotZglaszajacyNazwa = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "pzg_podmiotZglaszajacy", "nazwa"); pzgZgloszenie.PzgPodmiotZglaszajacyRegon = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "pzg_podmiotZglaszajacy", "REGON"); pzgZgloszenie.PzgPodmiotZglaszajacyPesel = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "pzg_podmiotZglaszajacy", "PESEL"); pzgZgloszenie.OsobaUprawnionaList = doc.GetXmlValueList(nsmgr, "PZG_Zgloszenie", "osobaUprawniona"); pzgZgloszenie.PzgCelList = doc.GetXmlValueList(nsmgr, "PZG_Zgloszenie", "pzg_cel"); pzgZgloszenie.CelArchiwalnyList = doc.GetXmlValueList(nsmgr, "PZG_Zgloszenie", "celArchiwalny"); pzgZgloszenie.PzgRodzaj = doc.GetXmlValue(nsmgr, "PZG_Zgloszenie", "pzg_rodzaj"); pzgZgloszenieDict.Add(pzgZgloszenie.IdFile, pzgZgloszenie); nodeList = doc.DocumentElement?.SelectNodes("/xmls:schema/xmls:PZG_Zgloszenie/xmls:pzg_cel", nsmgr); if (nodeList != null) { pzgZgloszenieCelList.AddRange(from XmlNode node in nodeList select new PzgCel { IdFile = idFile, XmlPath = xmlFile, IdMaterialu = Path.GetFileNameWithoutExtension(xmlFile), Value = string.IsNullOrEmpty(node.InnerText) ? "--brak wartosci--" : node.InnerText }); } nodeList = doc.DocumentElement?.SelectNodes("/xmls:schema/xmls:PZG_Zgloszenie/xmls:celArchiwalny", nsmgr); if (nodeList != null) { pzgZgloszenieCelArchList.AddRange(from XmlNode node in nodeList select new CelArchiwalny { IdFile = idFile, XmlPath = xmlFile, IdMaterialu = Path.GetFileNameWithoutExtension(xmlFile), Value = string.IsNullOrEmpty(node.InnerText) ? "--brak wartosci--" : node.InnerText }); } nodeList = doc.DocumentElement?.SelectNodes("/xmls:schema/xmls:PZG_Zgloszenie/xmls:osobaUprawniona", nsmgr); if (nodeList != null) { foreach (XmlNode node in nodeList) { XmlDocument docosoba = new XmlDocument(); docosoba.LoadXml(node.OuterXml); string imie = docosoba.SelectSingleNode("/xmls:osobaUprawniona/xmls:imie", nsmgr)?.InnerText; string nazwisko = docosoba.SelectSingleNode("/xmls:osobaUprawniona/xmls:nazwisko", nsmgr)?.InnerText; string numerUprawnien = docosoba.SelectSingleNode("/xmls:osobaUprawniona/xmls:numer_uprawnien", nsmgr)?.InnerText; if (string.IsNullOrEmpty(imie)) { imie = "--brak wartosci--"; } if (string.IsNullOrEmpty(nazwisko)) { nazwisko = "--brak wartosci--"; } if (string.IsNullOrEmpty(numerUprawnien)) { numerUprawnien = "--brak wartosci--"; } OsobaUprawniona osobaUprawniona = new OsobaUprawniona { IdFile = idFile, XmlPath = xmlFile, IdMaterialu = Path.GetFileNameWithoutExtension(xmlFile), Imie = imie, Nazwisko = nazwisko, NumerUprawnien = numerUprawnien }; pzgZgloszenieOsobaUprawnionaList.Add(osobaUprawniona); } } } // ------------------------------------------------------------------------------------------- // Badanie zgodności operatów i zgłoszeń z modelem danych if (walidacja) { if (WalidationLogList.Count > 0) { Console.WriteLine(""); } Console.WriteLine("Weryfikacja poprawności operatów z modelem danych..."); foreach (PzgMaterialZasobu operat in pzgMaterialZasobuDict.Values) { string oznMaterialuZasobu = GetPzgOznMaterialuZasobu(operat); if (operat.PzgOznMaterialuZasobu != oznMaterialuZasobu) { Console.WriteLine($"Błąd: {operat.XmlPath} - Nazwa operatu nie pasuje do jego składowych."); ModelErrorLogList.Add(new ModelErrorLog(operat.IdFile, operat.XmlPath, "Błąd", "pzg_oznMaterialuZasobu", operat.PzgOznMaterialuZasobu, "Nazwa operatu nie pasuje do jego składowych.")); } int operatCount = pzgMaterialZasobuDict.Values.Count(o => o.PzgOznMaterialuZasobu == operat.PzgOznMaterialuZasobu && o.Obreb == operat.Obreb); if (operatCount > 1) { Console.WriteLine($"Błąd: {operat.XmlPath} - Duplikat pzg_oznMaterialuZasobu."); ModelErrorLogList.Add(new ModelErrorLog(operat.IdFile, operat.XmlPath, "Błąd", "pzg_oznMaterialuZasobu", operat.PzgOznMaterialuZasobu, "Duplikat pzg_oznMaterialuZasobu.")); } string idMaterialu = $"{operat.IdMaterialuPierwszyCzlon}.{operat.IdMaterialuDrugiCzlon}.{operat.IdMaterialuTrzeciCzlon}.{operat.IdMaterialuCzwartyCzlon}"; if (operat.IdMaterialu != idMaterialu) { Console.WriteLine($"Błąd: {operat.XmlPath} - ID operatu nie pasuje do jego składowych."); ModelErrorLogList.Add(new ModelErrorLog(operat.IdFile, operat.XmlPath, "Błąd", "pzg_IdMaterialu", operat.IdMaterialu, "ID operatu nie pasuje do jego składowych.")); } operatCount = pzgMaterialZasobuDict.Values.Count(o => o.IdMaterialu == operat.IdMaterialu); if (operatCount > 1) { Console.WriteLine($"Błąd: {operat.XmlPath} - Duplikat pzg_IdMaterialu."); ModelErrorLogList.Add(new ModelErrorLog(operat.IdFile, operat.XmlPath, "Błąd", "pzg_IdMaterialu", operat.IdMaterialu, "Duplikat pzg_IdMaterialu.")); } } Console.WriteLine(""); // ------------------------------------------------------------------------------------------- Console.WriteLine("Weryfikacja poprawności zgłoszeń z modelem danych..."); foreach (PzgZgloszenie zgloszenie in pzgZgloszenieDict.Values) { string pzgIdZgloszenia = GetPzgIdZgloszenia(zgloszenie); if (zgloszenie.PzgIdZgloszenia == "--brak znacznika--") { Console.WriteLine($"Błąd: {zgloszenie.XmlPath}: Brak zgłoszenia dla operatu."); ModelErrorLogList.Add(new ModelErrorLog(zgloszenie.IdFile, zgloszenie.XmlPath, "Ostrzeżenie", "pzg_IdZgloszenia", zgloszenie.PzgIdZgloszenia, "Brak zgłoszenia dla operatu.")); } else { if (zgloszenie.PzgIdZgloszenia != pzgIdZgloszenia) { Console.WriteLine($"Błąd: {zgloszenie.XmlPath}: Nazwa zgłoszenia nie pasuje do jego składowych."); ModelErrorLogList.Add(new ModelErrorLog(zgloszenie.IdFile, zgloszenie.XmlPath, "Błąd", "pzg_IdZgloszenia", zgloszenie.PzgIdZgloszenia, "Nazwa zgłoszenia nie pasuje do jego składowych.")); } int zgloszenieCount = pzgZgloszenieDict.Values.Count(o => o.PzgIdZgloszenia == zgloszenie.PzgIdZgloszenia); if (zgloszenieCount > 1) { int zgloszenieMultiAttributesCount = pzgZgloszenieDict.Values.Count(z => z.PzgIdZgloszenia == zgloszenie.PzgIdZgloszenia && z.PzgDataZgloszenia == zgloszenie.PzgDataZgloszenia && z.Obreb == zgloszenie.Obreb && z.PzgPodmiotZglaszajacyOsobaId == zgloszenie.PzgPodmiotZglaszajacyOsobaId && z.PzgPodmiotZglaszajacyNazwa == zgloszenie.PzgPodmiotZglaszajacyNazwa && z.PzgPodmiotZglaszajacyRegon == zgloszenie.PzgPodmiotZglaszajacyRegon && z.PzgPodmiotZglaszajacyPesel == zgloszenie.PzgPodmiotZglaszajacyPesel && z.OsobaUprawnionaList == zgloszenie.OsobaUprawnionaList && z.PzgCelList == zgloszenie.PzgCelList && z.CelArchiwalnyList == zgloszenie.CelArchiwalnyList && z.PzgRodzaj == zgloszenie.PzgRodzaj); if (zgloszenieMultiAttributesCount == zgloszenieCount) { Console.WriteLine($"Ostrzeżenie: {zgloszenie.XmlPath}: Powielony numer zgłoszenia dla operatu."); ModelErrorLogList.Add(new ModelErrorLog(zgloszenie.IdFile, zgloszenie.XmlPath, "Ostrzeżenie", "pzg_IdZgloszenia", zgloszenie.PzgIdZgloszenia, "Powielony numer zgłoszenia dla operatu.")); } else { Console.WriteLine($"Błąd: {zgloszenie.XmlPath}: Duplikat nazwy zgłoszenia."); ModelErrorLogList.Add(new ModelErrorLog(zgloszenie.IdFile, zgloszenie.XmlPath, "Błąd", "pzg_IdZgloszenia", zgloszenie.PzgIdZgloszenia, "Duplikat nazwy zgłoszenia.")); } } } } Console.WriteLine(""); } Console.WriteLine("Zapis plików WKT z XML..."); foreach (PzgMaterialZasobu pzgMaterialZasobu in pzgMaterialZasobuDict.Values) { string wktName = pzgMaterialZasobu.XmlPath.Replace(".xml", ".wkt"); File.WriteAllText(wktName, pzgMaterialZasobu.PzgPolozenieObszaru, Encoding.UTF8); } foreach (PzgZgloszenie pzgZgloszenie in pzgZgloszenieDict.Values) { string wktName = pzgZgloszenie.XmlPath.Replace(".xml", "_zgl.wkt"); File.WriteAllText(wktName, pzgZgloszenie.PzgPolozenieObszaru, Encoding.UTF8); } // ------------------------------------------------------------------------------------------- using (ExcelPackage excelPackage = new ExcelPackage()) { excelPackage.Workbook.Properties.Author = "GISNET Grzegorz Gogolewski i Wspólnicy Spółka Jawna"; excelPackage.Workbook.Properties.Company = "GISNET Grzegorz Gogolewski i Wspólnicy Spółka Jawna"; excelPackage.Workbook.Properties.Manager = "Grzegorz Gogolewski"; excelPackage.Workbook.Properties.Title = "Raport z danymi wczytanymi z plików XML dla operatów i zgłoszeń"; excelPackage.Workbook.Properties.Keywords = "xml, xsd, operat, zgłoszenie"; string[] arkusze = { "operaty", "operaty_cel", "operaty_cel_arch", "operaty_dzialka_przed", "operaty_dzialka_po", "zgłoszenia", "zgłoszenia_cel", "zgłoszenia_cel_arch", "zgłoszenia_osoba_uprawniona", "walidacja", "model" }; if (ModelErrorLogList.Count > 0 || WalidationLogList.Count > 0) { Console.WriteLine(""); } foreach (string arkusz in arkusze) { Console.WriteLine($"Eksport danych do XLS [{arkusz}]..."); ExcelWorksheet sheet = excelPackage.Workbook.Worksheets.Add(arkusz); switch (arkusz) { case "operaty": sheet.Cells[1, 1].LoadFromCollection(pzgMaterialZasobuDict, true); Console.WriteLine("\nWeryfikacja pzg_polozenieObszaru..."); for (int i = 2; i < sheet.Dimension.End.Row; i++) { if (sheet.Cells[$"K{i}"].Text.Length > 32767) { sheet.Cells[$"K{i}"].Value = sheet.Cells[$"K{i}"].Text.Substring(0, 32766); Console.WriteLine(sheet.Cells[$"B{i}"].Text + ": pzg_polozenieObszaru przekracza rozmiar komórki Excel!"); } } Console.WriteLine("\nWeryfikacja dzialkaPrzed..."); for (int i = 2; i < sheet.Dimension.End.Row; i++) { if (sheet.Cells[$"AM{i}"].Text.Length > 32767) { sheet.Cells[$"AM{i}"].Value = sheet.Cells[$"AM{i}"].Text.Substring(0, 32766); Console.WriteLine(sheet.Cells[$"B{i}"].Text + ": dzialkaPrzed przekracza rozmiar komórki Excel!"); } } Console.WriteLine("\nWeryfikacja dzialkaPo..."); for (int i = 2; i < sheet.Dimension.End.Row; i++) { if (sheet.Cells[$"AN{i}"].Text.Length > 32767) { sheet.Cells[$"AN{i}"].Value = sheet.Cells[$"AN{i}"].Text.Substring(0, 32766); Console.WriteLine(sheet.Cells[$"B{i}"].Text + ": dzialkaPo przekracza rozmiar komórki Excel!"); } } Console.WriteLine(""); break; case "operaty_cel": sheet.Cells[1, 1].LoadFromCollection(pzgMaterialZasobuCelList, true); break; case "operaty_cel_arch": sheet.Cells[1, 1].LoadFromCollection(pzgMaterialZasobuCelArchList, true); break; case "operaty_dzialka_przed": sheet.Cells[1, 1].LoadFromCollection(pzgMaterialZasobuDzialkaPrzedList, true); break; case "operaty_dzialka_po": sheet.Cells[1, 1].LoadFromCollection(pzgMaterialZasobuDzialkaPoList, true); break; case "zgłoszenia": sheet.Cells[1, 1].LoadFromCollection(pzgZgloszenieDict.Values, true); Console.WriteLine("\nWeryfikacja pzg_polozenieObszaru..."); for (int i = 2; i < sheet.Dimension.End.Row; i++) { if (sheet.Cells[$"F{i}"].Text.Length > 32767) { sheet.Cells[$"F{i}"].Value = sheet.Cells[$"F{i}"].Text.Substring(0, 32766); string xmlPath = sheet.Cells[$"B{i}"].Text; Console.WriteLine(xmlPath + ": pzg_polozenieObszaru przekracza rozmiar komórki Excel!"); } } Console.WriteLine(""); break; case "zgłoszenia_cel": sheet.Cells[1, 1].LoadFromCollection(pzgZgloszenieCelList, true); break; case "zgłoszenia_cel_arch": sheet.Cells[1, 1].LoadFromCollection(pzgZgloszenieCelArchList, true); break; case "zgłoszenia_osoba_uprawniona": sheet.Cells[1, 1].LoadFromCollection(pzgZgloszenieOsobaUprawnionaList, true); break; case "walidacja": sheet.Cells[1, 1].LoadFromCollection(WalidationLogList, true); break; case "model": sheet.Cells[1, 1].LoadFromCollection(ModelErrorLogList, true); break; } int rowsCount = sheet.Dimension.Rows; int columnsCount = sheet.Dimension.Columns; sheet.View.FreezePanes(2, 1); sheet.Cells[1, 1, rowsCount, columnsCount].Style.Numberformat.Format = "@"; ExcelRange range = sheet.Cells[1, 1, sheet.Dimension.End.Row, sheet.Dimension.End.Column]; sheet.Tables.Add(range, arkusz); sheet.Cells.AutoFitColumns(10, 50); } // ------------------------------------------------------------------------------- try { FileStream fileStream = new FileStream(Path.Combine(startupPath, "xml.xlsx"), FileMode.Create); Console.WriteLine("\nZapis pliku XLS..."); excelPackage.SaveAs(fileStream); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("\nPlik zapisano pomyślnie."); Console.ForegroundColor = defaultColor; } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine('\n' + e.Message); Console.ForegroundColor = defaultColor; } } Console.ReadKey(true); }
public void CreateNewLicense(string licenseFile, MyLicense license) { license.Signature = _rsa.SignData(license.getData, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1); license.Key = _rsa.ExportParameters(false); File.WriteAllText(licenseFile, LicenseExtensions.LicenseToXmlString(license)); }
private void frmLisans_Shown(object sender, EventArgs e) { //Initialize variables with default values MyLicense _lic = null; string _msg = string.Empty; LicenseStatus _status = LicenseStatus.UNDEFINED; //Read public key from assembly Assembly _assembly = Assembly.GetExecutingAssembly(); using (MemoryStream _mem = new MemoryStream()) { _assembly.GetManifestResourceStream("EtikeTAP.LicenseVerify.cer").CopyTo(_mem); _certPubicKeyData = _mem.ToArray(); } //Check if the XML license file exists if (File.Exists("license.lic")) { _lic = (MyLicense)LicenseHandler.ParseLicenseFromBASE64String( typeof(MyLicense), File.ReadAllText("license.lic"), _certPubicKeyData, out _status, out _msg); } else { _status = LicenseStatus.INVALID; _msg = "Programınızın lisansı yok. Lütfen lisanslama için arayın. 0506 946 86 93"; } switch (_status) { case LicenseStatus.VALID: //TODO: If license is valid, you can do extra checking here //TODO: E.g., check license expiry date if you have added expiry date property to your license entity //TODO: Also, you can set feature switch here based on the different properties you added to your license entity //Here for demo, just show the license information and RETURN without additional checking licInfo.ShowLicenseInfo(_lic); return; default: //for the other status of license file, show the warning message //and also popup the activation form for user to activate your application MessageBox.Show(_msg, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Warning); using (frmActivation frm = new frmActivation()) { frm.CertificatePublicKeyData = _certPubicKeyData; frm.ShowDialog(); //Exit the application after activation to reload the license file //Actually it is not nessessary, you may just call the API to reload the license file //Here just simplied the demo process Application.Exit(); } break; } }
public MainWindow() { InitializeComponent(); var border1 = (resultStack.Parent as ScrollViewer).Parent as Border; border1.Visibility = Visibility.Hidden; //Initialize variables with default values MyLicense _lic = null; string _msg = string.Empty; LicenseStatus _status = LicenseStatus.UNDEFINED; //Read public key from assembly Assembly _assembly = Assembly.GetExecutingAssembly(); using (MemoryStream _mem = new MemoryStream()) { _assembly.GetManifestResourceStream("EleganteLetras.LicenseSignLetras.cer").CopyTo(_mem); _certPubicKeyData = _mem.ToArray(); } //Check if the XML license file exists if (File.Exists("license.lic")) { _lic = (MyLicense)LicenseHandler.ParseLicenseFromBASE64String( typeof(MyLicense), File.ReadAllText("license.lic"), _certPubicKeyData, out _status, out _msg); } else { _status = LicenseStatus.INVALID; _msg = "Tu copia de esta instalación no está activada"; } switch (_status) { case LicenseStatus.VALID: //TODO: If license is valid, you can do extra checking here //TODO: E.g., check license expiry date if you have added expiry date property to your license entity //TODO: Also, you can set feature switch here based on the different properties you added to your license entity //Here for demo, just show the license information and RETURN without additional checking //licInfo.ShowLicenseInfo(_lic); return; default: //for the other status of license file, show the warning message //and also popup the activation form for user to activate your application //System.Windows.MessageBox.Show(_msg); using (Activation frm = new Activation()) { frm.CertificatePublicKeyData = _certPubicKeyData; frm.ShowDialog(); //Exit the application after activation to reload the license file //Actually it is not nessessary, you may just call the API to reload the license file //Here just simplied the demo process //Application.Exit(); System.Windows.Application.Current.Shutdown(); } break; } var border = (resultStack.Parent as ScrollViewer).Parent as Border; border.Visibility = Visibility.Collapsed; try { Datos.Tablas tablas = new Datos.Tablas(); tablas.VerificarTablaLetras(); //MessageBox.Show("Tablas Verificadas"); } catch (Exception err) { MessageBox.Show(err.Message); } }
private void FrmMain_Load(object sender, EventArgs e) { string msg = string.Empty; LicenseStatus status = LicenseStatus.Undefined; Assembly assembly = Assembly.GetExecutingAssembly(); using (MemoryStream memoryStream = new MemoryStream()) { assembly.GetManifestResourceStream("ScanHelper.LicenseVerify.cer")?.CopyTo(memoryStream); _certPublicKeyData = memoryStream.ToArray(); } if (File.Exists("license.lic")) { _license = (MyLicense)LicenseHandler.ReadLicense(typeof(MyLicense), File.ReadAllText("license.lic"), _certPublicKeyData, out status, out msg); } else { FormLicense frm = new FormLicense(); frm.ShowDialog(this); } switch (status) { case LicenseStatus.Undefined: MessageBox.Show(@"By używać tej aplikacji musisz posiadać aktualną licencję", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); break; case LicenseStatus.Invalid: case LicenseStatus.Cracked: case LicenseStatus.Expired: MessageBox.Show(msg, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); break; case LicenseStatus.Valid: string licenseOwner = _license?.LicenseOwner; statusStripLicense.Text = $"Licencja: {_license?.Type}. Licencja ważna do: {_license?.LicenseEnd}"; Text = Application.ProductName + ' ' + Application.ProductVersion + @" - " + licenseOwner?.Split('\n').First(); Location = new Point(Convert.ToInt32(Functions.IniParser.ReadIni("FormMain", "X")), Convert.ToInt32(Functions.IniParser.ReadIni("FormMain", "Y"))); using (FileStream stream = new FileStream(AppDomain.CurrentDomain.BaseDirectory + @"ScanHelper.jpg", FileMode.Open, FileAccess.Read)) { _activeImage = Image.FromStream(stream); } pictureBoxView.Image = ImageZoom(_activeImage, 0); pictureBoxView.Left = 0; pictureBoxView.Top = 0; pictureBoxView.Location = new Point((panelView.ClientSize.Width / 2) - (pictureBoxView.Image.Width / 2), (panelView.ClientSize.Height / 2) - (pictureBoxView.Height / 2)); trackBarZoom.Value = 0; _zoom = 0; break; default: throw new ArgumentOutOfRangeException(); } }
public static void Main(string[] args) { ConsoleColor defaultColor = Console.ForegroundColor; MyLicense license = LicenseHandler.ReadLicenseFile(out LicenseStatus licStatus, out string validationMsg); switch (licStatus) { case LicenseStatus.Undefined: Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Brak pliku z licencją!!!\n"); Console.ForegroundColor = defaultColor; Assembly assembly = Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); Console.WriteLine("Identyfikator komputera: " + LicenseHandler.GenerateUid(fvi.ProductName) + '\n'); Console.ReadKey(false); Environment.Exit(0); break; case LicenseStatus.Valid: Console.WriteLine("Właściciel licencji:\n"); Console.WriteLine(license.LicenseOwner + "\n"); Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine($"Licencja typu: '{license.Type}', ważna do: {license.LicenseEnd}\n"); Console.ForegroundColor = defaultColor; Thread.Sleep(1000); break; case LicenseStatus.Invalid: case LicenseStatus.Cracked: Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(validationMsg); Console.ForegroundColor = defaultColor; Console.ReadKey(false); Environment.Exit(0); break; case LicenseStatus.Expired: Console.WriteLine("Właściciel licencji:"); Console.WriteLine(license.LicenseOwner + "\n"); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(validationMsg); Console.ForegroundColor = defaultColor; Console.ReadKey(false); Environment.Exit(0); break; default: throw new ArgumentOutOfRangeException(); } // -------------------------------------------------------------------------------------------- // podłączenie bibiotek SQL Server do obsługi geometrii SqlServerTypes.Utilities.LoadNativeAssemblies(AppDomain.CurrentDomain.BaseDirectory); // -------------------------------------------------------------------------------------------- // folder startowy dla danych analizowanych przez aplikację string startupPath = string.Empty; void RunOptions(Options opts) { startupPath = opts.StarupPath; } void HandleParseError(IEnumerable <Error> errs) { Console.ReadKey(false); Environment.Exit(0); } Parser.Default.ParseArguments <Options>(args).WithParsed(RunOptions).WithNotParsed(HandleParseError); // -------------------------------------------------------------------------------------------- Console.WriteLine("Pobieranie listy folerów..."); // pobierz wszystkie katalogi i podkatalogi string[] allDirectories = Directory.GetDirectories(startupPath, "*", SearchOption.AllDirectories); Console.WriteLine($"Pobrano {allDirectories.Length} folderów.\n"); Console.WriteLine("Analizowanie folderów..."); // sortowanie nazw katalogów zgodnie z sortowaniem naturalnym Array.Sort(allDirectories, new NaturalStringComparer()); // lista "ostatnich" podfolderów - folder końcowy w którym powinny być dane List <string> wktDirectories = new List <string>(); // analiza podkatalogów pod kątem tego czy są ostatnimi folderami w ścieżce foreach (string dir in allDirectories) { DirectoryInfo directory = new DirectoryInfo(dir); // pobierz informacje o danym folderze DirectoryInfo[] subdirs = directory.GetDirectories(); // pobierz list podfolderów dla danego folderu if (subdirs.Length == 0) { wktDirectories.Add(dir); // jeśli dany katalog nie ma podfolderów dodaj go do listy katalogów z wkt } } Console.WriteLine("Zliczanie plików..."); FileInfo[] files = new DirectoryInfo(startupPath).GetFiles("*.wkt", SearchOption.AllDirectories); Console.WriteLine($"Koniec analizy folderów. Pozostało {wktDirectories.Count} folderów. Plików WKT: {files.Length}\n"); int filesCounter = 1; Timer timer = new Timer(TimerCallback, null, 0, 1000); void TimerCallback(Object o) { Console.WriteLine($"ID: {filesCounter, 6} / {files.Length}"); } WktFeatures wktFeatures = new WktFeatures(); foreach (string wktDirectory in wktDirectories) { List <string> wktFileNames = Directory.GetFiles(wktDirectory, "*.wkt", SearchOption.TopDirectoryOnly).ToList(); foreach (string wktFileName in wktFileNames) { WktFile wktFile = new WktFile(wktFileName); if (!wktFile.IsValid()) { Console.WriteLine($"ID: {filesCounter, 6} => {Path.GetFileName(wktFileName), 40}: {wktFile.ValidationStatus}"); } wktFeatures.Add(filesCounter++, wktFile); } } timer.Dispose(); string outputFile = Path.Combine(startupPath, "wkt.xlsm"); Console.WriteLine($"\nZapisywanie wyników do pliku {outputFile}..."); File.Delete(outputFile); using (ExcelPackage excelPackage = new ExcelPackage()) { ExcelWorksheet arkusz = excelPackage.Workbook.Worksheets.Add("WKT"); arkusz.Cells[1, 1].LoadFromCollection(wktFeatures.Values, true); arkusz.Cells["A1:G1"].AutoFilter = true; arkusz.View.FreezePanes(2, 1); arkusz.Cells.AutoFitColumns(8.43, 40); // -------------------------------------------------------------------------------- // Dodanie kodu makra // -------------------------------------------------------------------------------- excelPackage.Workbook.CreateVBAProject(); excelPackage.Workbook.VbaProject.Modules.AddModule("mdlMain").Code = VbResource.GetVbText("mdlMain.txt"); excelPackage.SaveAs(new FileInfo(outputFile)); } Console.WriteLine("\nKoniec!"); Console.ReadKey(false); }
public FrmAbout(MyLicense license) { InitializeComponent(); _license = license; }
// http://stackoverflow.com/a/17227764/19020 // http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2 public static void Ini(IAppBuilder appBuilder) { //DateTime dt = DateTime.Parse("2017-01-02"); //try //{ // DateTime dt = GetNetTime.GetStandardTime(); // SetNetTime.SetTime(GetNetTime.GetStandardTime()); //} //catch (Exception ex) //{ // AutoNLog.Log4Info("同步时间失败" + ex); //} //string authKey = System.Configuration.ConfigurationManager.ConnectionStrings[WebApiGlobal._AUTHKEY].ConnectionString; try { //DateTime dt = GetNetTime.GetStandardTime(); //SetNetTime.SetTime(dt); MyLicense lic = ReadFromLic.ReadLic(AuthKeys._AuthFileKEY, AuthKeys._AuthFilePath); if (lic == null) { throw new Exception("未解密Lic"); } string CpuID = GetComputerInfo.GetCpuID(); string HDid = GetComputerInfo.GetHDid(); string ComputerInfo = CpuID + HDid + lic.PeriodDate.ToStringEx() + "4x}ty#N3*w[2bXK2ne(DRLKov%NhmJ#Z"; RSAAuth _RSA = new RSAAuth(); string _PublicKey = _RSA.ReadPublicKey(AuthKeys._PublicKeyPath); string Hash1 = _RSA.GetSHA512Hash(ComputerInfo); string Hash4Validate = _RSA.GetSHA512Hash(Hash1); if (_RSA.SignatureDeformatter(_PublicKey, Hash4Validate, lic.SignValue.ToStringEx())) { if (DateTime.Parse(lic.PeriodDate) < DateTime.Now) { throw new Exception("已过期,PeriodDate:" + lic.PeriodDate.ToStringEx() + "SignValue:" + lic.SignValue.ToStringEx()); } } else { throw new Exception("非法使用,PeriodDate:" + lic.PeriodDate.ToStringEx() + "SignValue:" + lic.SignValue.ToStringEx()); } } catch (Exception ex) { AutoNLog.Log4Info("检验错误" + ex.Message.ToStringEx() + ex); throw ex; } Type RAMCacheController = typeof(WebApi.Controller.RAMCacheController); Type web_Api_HelperController = typeof(WebApi.Controller.web_Api_HelperController); Type tb_TMS_DDController = typeof(WebApi.Controller.TMS_DDController); HttpConfiguration config = new HttpConfiguration(); config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented; config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; config.Formatters.JsonFormatter.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm"; config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; appBuilder.Use((context, next) => { context.Response.Headers.Remove("Server"); return(next.Invoke()); }); appBuilder.UseStageMarker(PipelineStage.PostAcquireState); // // List of delegating handlers. // DelegatingHandler[] handlers = new DelegatingHandler[] { // new MessageHandler3() // }; // // Create a message handler chain with an end-point. // var routeHandlers = HttpClientFactory.CreatePipeline( // new HttpControllerDispatcher(config), handlers); // Web API 配置和服务 // 将 Web API 配置为仅使用不记名令牌身份验证。 config.SuppressDefaultHostAuthentication(); //config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); //config.MapHttpAttributeRoutes(); //可将路由放到基类中 config.MapHttpAttributeRoutes(new CustomDirectRouteProvider()); //没有action,则两个方法都是Get开头会报错,改为api/{controller}/{action}/{id} config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } //constraints: null, //handler: new MessageHandler1() //handler: routeHandlers ); config.Filters.Add(new MyActionFilterAttribute()); config.Filters.Add(new MyExceptionHandlingAttribute()); //var traceWriter = new SystemDiagnosticsTraceWriter() //{ // IsVerbose = true //}; ////config.Services.Replace(typeof(ITraceWriter), traceWriter); //config.EnableSystemDiagnosticsTracing(); //config.MessageHandlers.Add(new ThrottlingHandler() //{ // Policy = new ThrottlePolicy(perSecond: 1, perMinute: 30) // { // //Ip限流,访问api/values后,所有后续访问api/values/xxx的请求都会被拒绝掉 // IpThrottling = true, // //IpWhitelist = new List<string> { "::1", "192.168.0.0/24" }, // IpRules = new Dictionary<string, RateLimits> // { // { "192.168.1.1", new RateLimits { PerSecond = 2 } }, // { "192.168.2.0/24", new RateLimits { PerMinute = 30, PerHour = 30*60, PerDay = 30*60*24 } } // }, // //如果同一个ip,在同一秒内,调用了2次api/values,其最后一次的调用将会被拒绝掉。 // //如果想接口通过唯一key去识别限制客户端,忽略客户端的ip地址限制,应该配置IpThrottling为false。 // ClientThrottling = true, // ClientWhitelist = new List<string> { "admin-key" }, // ClientRules = new Dictionary<string, RateLimits> // { // { "api-client-key-1", new RateLimits { PerMinute = 40, PerHour = 400 } }, // { "api-client-key-9", new RateLimits { PerDay = 2000 } } // }, // EndpointRules = new Dictionary<string, RateLimits> // { // { "api/RAM/Mgr/RefreshUserKey", new RateLimits { PerSecond = 2, PerMinute = 100, PerHour = 1000 } } // }, // //拒绝累加技术 // StackBlockedRequests = true, // //Ip端点限流,同一秒内你也访问api/values/1了,请求将不会被拒绝,因为它们走的是不同的路由。 // EndpointThrottling = true // }, // //如果是owin寄宿,替换成PolicyMemoryCacheRepository // //PolicyRepository= new PolicyMemoryCacheRepository(), // //policyRepository: new PolicyCacheRepository(), // //自寄宿在Owin上的WebApi用MemoryCacheRepository // Repository = new MemoryCacheRepository(), // Logger= new TracingThrottleLogger(traceWriter) // //Repository = new CacheRepository()//CacheRepository使用的是Asp.net版本的缓存。 //} //); ////config.MessageHandlers.Add(new CustomHeaderHandler()); ////config.MessageHandlers.Add(new MessageHandler1()); ////config.MessageHandlers.Add(new RemoveHttpHeadersModule()); appBuilder.UseWebApi(config); //config.Formatters.Remove(config.Formatters.XmlFormatter); config.MessageHandlers.Add(new NLogHandler()); //config.MapHttpAttributeRoutes(new CustomDirectRouteProvider()); //HelpPageConfig.Register(config); //SwaggerNet.PreStart(); var jsonFormatter = new JsonMediaTypeFormatter(); //optional: set serializer settings here config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter)); //AutoNLog.Log4Info("正在启动WebApiServer"); }