/// <summary> /// Download media updates. /// </summary> static void DownloadMediaUpdates(object sender, GXAsyncWork work, object[] parameters) { IGXUpdater updater = (IGXUpdater)parameters[0]; Assembly asm = (Assembly)parameters[1]; GXExternalMediaForm.CheckUpdates(updater, asm); }
/// <summary> /// Constructor. /// </summary> /// <param name="certificateFolder"></param> /// <param name="title"></param> /// <param name="systemTitle">If system title is not null this certificate is selected.</param> public GXCertificateForm(IGXUpdater updater, string address, string certificateFolder, string title, byte[] systemTitle) { InitializeComponent(); _updater = updater; _address = address; string st = null; if (systemTitle != null && systemTitle.Length == 8) { st = GXAsn1Converter.SystemTitleToSubject(systemTitle); } Certificates = new GXx509CertificateCollection(); CertificateFolder = certificateFolder; Title = title; foreach (string p in Directory.GetFiles(CertificateFolder)) { string ext = Path.GetExtension(p); if (string.Compare(ext, ".pem", true) == 0 || string.Compare(ext, ".cer", true) == 0) { try { GXx509Certificate cert = GXx509Certificate.Load(p); AddCertificate(cert, p, st); } catch (Exception ex) { ListViewItem li = new ListViewItem(new string[] { ex.Message, "", "", "", "", Path.GetFileNameWithoutExtension(p) }); li.Tag = p; li.BackColor = Color.Red; CertificatesList.Items.Add(li); } } } }
/// <summary> /// Download missing medias. /// </summary> static void DownloadMedias(object sender, GXAsyncWork work, object[] parameters) { string[] list = (string[])parameters[0]; string initDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "GXDLMSDirector"); string medias = Path.Combine(initDir, "Medias"); foreach (string it in list) { IGXUpdater updater = null; string path = Path.Combine(medias, Path.GetFileName(it)); Assembly asm = null; //Check is there new version from the media. if (File.Exists(path)) { asm = Assembly.LoadFile(path); foreach (Type type in asm.GetTypes()) { if (!type.IsAbstract && type.IsClass && typeof(IGXUpdater).IsAssignableFrom(type)) { updater = Activator.CreateInstance(type) as IGXUpdater; break; } } if (updater != null && GXExternalMediaForm.CheckUpdates(updater, asm)) { //TODO: Show that there are new updates. } } else { //If external media is missing. GXExternalMediaForm.DownLoadMedia(it); } } }
private void CheckUpdatesBtn_Click(object sender, EventArgs e) { try { if (MediaList.SelectedItems.Count != 1) { throw new Exception("Update check failed. Selected media to check updates."); } Assembly asm = (Assembly)MediaList.SelectedItems[0].Tag; IGXUpdater updater = null; foreach (Type type in asm.GetTypes()) { if (!type.IsAbstract && type.IsClass && typeof(IGXUpdater).IsAssignableFrom(type)) { updater = Activator.CreateInstance(type) as IGXUpdater; break; } } if (updater == null) { throw new Exception("Update check failed. Update checker is not supported."); } checkUpdates = new GXAsyncWork(this, OnAsyncStateChange, CheckUpdates, OnError, null, new object[] { updater, asm }); checkUpdates.Start(); } catch (Exception Ex) { GXDLMS.Common.Error.ShowError(this, Ex); } }
void CheckUpdates(object sender, GXAsyncWork work, object[] parameters) { IGXUpdater updater = (IGXUpdater)parameters[0]; Assembly asm = (Assembly)parameters[1]; if (!GXExternalMediaForm.CheckUpdates(updater, asm)) { // There's nothing to update MessageBox.Show(Properties.Resources.ExternalMediaNoUpdates, Properties.Resources.GXDLMSDirectorTxt, MessageBoxButtons.OK); } else { if (MessageBox.Show("You need to restart application. Do you want to do it now?", Properties.Resources.GXDLMSDirectorTxt, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes) { Application.Restart(); } } }
/// <summary> /// Check if there are updates and download them to updates folder. /// </summary> /// <param name="updater"></param> /// <param name="asm"></param> /// <returns></returns> public static bool CheckUpdates(IGXUpdater updater, Assembly asm) { //This will fix the error: request was aborted could not create ssl/tls secure channel. //For Net45 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; foreach (GXUpdateItem target in updater.CheckUpdates()) { WebRequest req = WebRequest.Create(target.Source); IWebProxy proxy = WebRequest.GetSystemWebProxy(); if (proxy != null && proxy.Credentials != null) { req.Proxy = proxy; } using (HttpWebResponse response = req.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) { throw new Exception(String.Format ("Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription)); } int length = 0; var d = response.Headers["Content-Length"]; if (d != null) { length = int.Parse(d.ToString()); } MemoryStream ms = new MemoryStream(length); Stream stream = response.GetResponseStream(); byte[] buffer = new byte[length == 0 || length > 1024 ? 1024 : length]; IAsyncResult read = stream.BeginRead(buffer, 0, buffer.Length, null, null); while (true) { // wait for the read operation to complete read.AsyncWaitHandle.WaitOne(); int count = stream.EndRead(read); ms.Write(buffer, 0, count); // If read is done. if (ms.Position == length || count == 0) { break; } read = stream.BeginRead(buffer, 0, buffer.Length, null, null); } ms.Position = 0; string name = Path.Combine(Path.GetTempPath(), target.FileName); using (FileStream w = File.Create(name, length)) { w.Write(ms.GetBuffer(), 0, length); w.Close(); } AssemblyName current = asm.GetName(); AssemblyName updated = AssemblyName.GetAssemblyName(name); // Compare both versions if (updated.Version.CompareTo(current.Version) <= 0) { return(false); } string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "GXDLMSDirector"); path = Path.Combine(path, "Updates"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } File.Copy(name, Path.Combine(path, target.FileName), true); } } return(true); }
public GXKeyForm(IGXUpdater updater, string address, string keyFolder, string certificateFolder, string title, SecuritySuite securitySuite, byte[] systemTitle) { InitializeComponent(); _updater = updater; _address = address; _certificateFolder = certificateFolder; _systemTitle = systemTitle; privateKeys = new GXPkcs8Collection(); KeyFolder = keyFolder; Title = title; foreach (string p in Directory.GetFiles(keyFolder)) { string ext = Path.GetExtension(p); if (string.Compare(ext, ".pem", true) == 0 || string.Compare(ext, ".cer", true) == 0) { try { GXPkcs8 cert = GXPkcs8.Load(p); AddKey(cert, p); } catch (Exception) { Debug.WriteLine("Failed to open " + p); } } } if (_systemTitle != null) { string path = Path.Combine(KeyFolder, "D" + GXDLMSTranslator.ToHex(_systemTitle, false)) + ".pem"; //Generate private key for digital signature. GXPkcs8 digitalSignature = new GXPkcs8(GXEcdsa.GenerateKeyPair(securitySuite == SecuritySuite.Suite1 ? Ecc.P256 : Ecc.P384)); digitalSignature.Save(path); AddKey(digitalSignature, path); path = Path.Combine(KeyFolder, "A" + GXDLMSTranslator.ToHex(_systemTitle, false)) + ".pem"; //Generate private key for Key agreement. GXPkcs8 keyAgreement = new GXPkcs8(GXEcdsa.GenerateKeyPair(Ecc.P256)); keyAgreement.Save(path); AddKey(keyAgreement, path); //Get CRS. KeyValuePair <GXPublicKey, GXPrivateKey> kp = new KeyValuePair <GXPublicKey, GXPrivateKey>(digitalSignature.PublicKey, digitalSignature.PrivateKey); //Generate certificate request and ask new x509Certificate. //Note! There is a limit how many request you can do in a day. List <GXCertificateRequest> certifications = new List <GXCertificateRequest>(); GXCertificateRequest it = new GXCertificateRequest(); it.Certificate = GXPkcs10.CreateCertificateSigningRequest(kp, GXAsn1Converter.SystemTitleToSubject(_systemTitle)); it.CertificateType = CertificateType.DigitalSignature; certifications.Add(it); it = new GXCertificateRequest(); it.Certificate = GXPkcs10.CreateCertificateSigningRequest(kp, GXAsn1Converter.SystemTitleToSubject(_systemTitle)); it.CertificateType = CertificateType.KeyAgreement; certifications.Add(it); GXx509Certificate[] certificates = GXPkcs10.GetCertificate(address, certifications); foreach (GXx509Certificate cert in certificates) { if (cert.KeyUsage == KeyUsage.DigitalSignature) { path = "D" + GXDLMSTranslator.ToHex(_systemTitle, false); } else if (cert.KeyUsage == KeyUsage.KeyAgreement) { path = "A" + GXDLMSTranslator.ToHex(_systemTitle, false); } else if (cert.KeyUsage == (KeyUsage.KeyAgreement | KeyUsage.DigitalSignature)) { path = "T" + GXDLMSTranslator.ToHex(_systemTitle, false); } else { path = "O" + GXDLMSTranslator.ToHex(_systemTitle, false); } path = Path.Combine(_certificateFolder, path) + ".pem"; cert.Save(path); } } }
/// <summary> /// Check if there are updates and download them to updates folder. /// </summary> /// <param name="updater"></param> /// <param name="asm"></param> /// <returns></returns> public static bool CheckUpdates(IGXUpdater updater, Assembly asm) { foreach (GXUpdateItem target in updater.CheckUpdates()) { WebRequest req = WebRequest.Create(target.Source); using (HttpWebResponse response = req.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) { throw new Exception(String.Format ("Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription)); } int length = 0; var d = response.Headers["Content-Length"]; if (d != null) { length = int.Parse(d.ToString()); } MemoryStream ms = new MemoryStream(length); Stream stream = response.GetResponseStream(); byte[] buffer = new byte[length == 0 || length > 1024 ? 1024 : length]; IAsyncResult read = stream.BeginRead(buffer, 0, buffer.Length, null, null); while (true) { // wait for the read operation to complete read.AsyncWaitHandle.WaitOne(); int count = stream.EndRead(read); ms.Write(buffer, 0, count); // If read is done. if (ms.Position == length || count == 0) { break; } read = stream.BeginRead(buffer, 0, buffer.Length, null, null); } ms.Position = 0; using (FileStream w = File.Create(target.FileName, length)) { w.Write(ms.GetBuffer(), 0, length); w.Close(); } AssemblyName current = asm.GetName(); AssemblyName updated = AssemblyName.GetAssemblyName(target.FileName); // Compare both versions if (updated.Version.CompareTo(current.Version) <= 0) { return(false); } asm = System.Reflection.Assembly.GetExecutingAssembly(); string path = Path.Combine(Path.GetDirectoryName(asm.Location), "Updates"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } File.Copy(target.FileName, Path.Combine(path, target.FileName), true); } } return(true); }