public async Task GivenLicenseWithUserId_ReturnsLicense() { // Arrange var licenseId = Guid.NewGuid(); var userId = Guid.NewGuid(); var user = new UserEntity { Id = userId }; var license = new LicenseEntity { Id = licenseId, UserId = userId }; _mediator .SetupHandler <GetUserByIdQuery, UserEntity>() .ReturnsAsync(user); _mediator .SetupHandler <GetLicenseByUserIdQuery, LicenseEntity>() .ReturnsAsync(license); // Act var result = await _classUnderTest.GetByUserIdAsync(userId, CancellationToken.None); // Assert Assert.That(result.Id, Is.EqualTo(licenseId)); }
/// <summary> /// 验证参数。 /// </summary> /// <param name="entity"></param> /// <returns></returns> internal static bool ValidateParameters(LicenseEntity entity) { if (string.IsNullOrWhiteSpace(entity.PrivateKey) || string.IsNullOrWhiteSpace(entity.PublicKey)) { MessageBox.Show(LicenseManagerResource.ManagerFormServiceValidateParametersNeedPrivateKeyAndPublicKey, LicenseManagerResource.ManagerFormValidateParametersWarning, MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } if (string.IsNullOrWhiteSpace(entity.MacCode) || !_regex.IsMatch(entity.MacCode)) { MessageBox.Show(LicenseManagerResource.ManagerFormValidateParametersMACAddress, LicenseManagerResource.ManagerFormValidateParametersWarning, MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } if (entity.ExpireTime < DateTime.Now) { MessageBox.Show(LicenseManagerResource.ManagerFormValidateParametersExpireTime, LicenseManagerResource.ManagerFormValidateParametersWarning, MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } if (entity.LicenseTarget == LicenseTarget.None) { MessageBox.Show(LicenseManagerResource.ManagerFormValidateParametersSelectAuthenticationTarget, LicenseManagerResource.ManagerFormValidateParametersWarning, MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } return(true); }
private bool ValidateLicense() { if (string.IsNullOrWhiteSpace(License)) { MessageBox.Show("Please input license", string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } //Check the activation string LicenseStatus _licStatus = LicenseStatus.UNDEFINED; string _msg = string.Empty; LicenseEntity _lic = LicenseHandler.ParseLicenseFromBASE64String(LicenseObjectType, License.Trim(), _certPubicKeyData, out _licStatus, out _msg); switch (_licStatus) { case LicenseStatus.VALID: MessageBox.Show(_msg, "License is valid", MessageBoxButtons.OK, MessageBoxIcon.Information); return(true); case LicenseStatus.CRACKED: case LicenseStatus.INVALID: case LicenseStatus.UNDEFINED: MessageBox.Show(_msg, "License is INVALID", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); default: return(false); } }
public async Task GivenLicenseWithUserId_ReturnsLicense() { // Arrange var cancellationToken = new CancellationToken(); var userId = Guid.NewGuid(); var query = new GetLicenseByUserIdQuery { UserId = userId }; var license = new LicenseEntity { Id = Guid.NewGuid(), UserId = userId }; await _licenseCollection.InsertOneAsync(license, null, cancellationToken); // Act var result = await _classUnderTest.Handle(query, cancellationToken); // Assert Assert.Multiple(() => { Assert.That(result.Id, Is.Not.Null); Assert.That(result.UserId, Is.EqualTo(userId)); CollectionAssert.IsEmpty(result.Products); }); }
/// <summary> /// Get license /// </summary> /// <param name="RequestKey"></param> /// <returns></returns> public LicenseEntity GetLicense(string RequestKey) { try { LicenseEntity objLicense = new LicenseEntity(); SqlParameter[] parameters = new SqlParameter[] { new SqlParameter("@RequestKey", SqlDbType.VarChar, 200) }; parameters[0].Value = RequestKey; DataSet ds = RunProcedure("OP_REQUEST_LICENSEKEY", parameters, "tblDSXeDeCu"); if (ds != null && ds.Tables.Count > 0) { DataRow dr = ds.Tables[0].Rows[0]; objLicense.LicenseKey = dr["LicenseKey"].ToString(); objLicense.FromDate = Convert.ToDateTime(dr["FromDate"].ToString()); objLicense.ToDate = Convert.ToDateTime(dr["ToDate"].ToString()); } return(objLicense); } catch (Exception ex) { return(null); } }
public void ShowLicense(LicenseEntity _lic) { if (_lic != null) { License = _lic; rdoSingleLicense.Checked = rdoVolumeLicense.Checked = chkTimeTrial.Checked = false; dateValidUntil.Value = DateTime.Today; switch (_lic.Type) { case LicenseTypes.Single: rdoSingleLicense.Checked = true; break; case LicenseTypes.Volume: rdoVolumeLicense.Checked = true; break; case LicenseTypes.Unknown: default: break; } if (_lic.IsTimeTrial) { chkTimeTrial.Checked = true; dateValidUntil.Value = _lic.ValidUntil; } txtUID.Text = _lic.UID; pgLicenseSettings.Refresh(); } }
public static void Seeder(IDbSet <LicenseEntity> licenses, IDbSet <LicenseTypeEntity> licenseTypes, IDbSet <CompanyEntity> companies) { var licenseTypesOne = licenseTypes.Find(1); if (licenseTypesOne == null) { throw new Exception("LicenseType One not found"); } var companyOne = companies.Find(1); if (companyOne == null) { throw new Exception("Company One not found"); } var licenseOne = new LicenseEntity() { Code = "SDF&328SDHnls76Dlsaeow", LicenseType = licenseTypesOne, Company = companyOne, ValidTillDate = DateTime.Now.ToString(CultureInfo.InvariantCulture) }; licenses.AddOrUpdate(x => x.Code, licenseOne); }
public static string GenerateLicense(LicenseEntity lic, byte[] certPrivateKeyData, SecureString certFilePwd) { //Serialize license object into XML XmlDocument licenseObject = new XmlDocument(); using (StringWriter writer = new StringWriter()) { XmlSerializer serializer = new XmlSerializer(typeof(LicenseEntity), new[] { lic.GetType() }); serializer.Serialize(writer, lic); licenseObject.LoadXml(writer.ToString()); } //Get RSA key from certificate X509Certificate2 cert = new X509Certificate2(certPrivateKeyData, certFilePwd); RSACryptoServiceProvider rsaKey = (RSACryptoServiceProvider)cert.PrivateKey; //Sign the XML SignXml(licenseObject, rsaKey); //Convert the signed XML into BASE64 string return(Convert.ToBase64String(Encoding.UTF8.GetBytes(licenseObject.OuterXml))); }
public static async Task Main(string[] args) { var configuration = new ConfigurationBuilder() .AddJsonFile(SettingsFileName) .Build(); var databaseSettings = configuration.GetSettings <DatabaseSettings>(); var database = new SubmarineDatabaseBuilder() .WithConnectionString(databaseSettings.ConnectionString) .WithConvention(new EnumRepresentationConvention(BsonType.String)) .Build(); var userCollection = database.GetEntityCollection <UserEntity>(); var licenseCollection = database.GetEntityCollection <LicenseEntity>(); var hashedPassword = BCrypt.Net.BCrypt.HashPassword("password"); var isValidPassword = BCrypt.Net.BCrypt.Verify("password", hashedPassword); Console.WriteLine($"Generated Valid Password: {isValidPassword}"); var user = new UserEntity { Id = Guid.NewGuid(), EmailAddress = "*****@*****.**", Password = hashedPassword, FriendlyName = "Joshua Crowe", UserName = "******", Roles = new List <UserRole> { UserRole.Standard } }; await userCollection.InsertOneAsync(user); var product = new LicenseProductEntity { Name = "Submarine", Expiration = DateTime.UtcNow.AddYears(1) }; var licenseKeyBytes = Encoding.UTF8.GetBytes("licenseKey"); var licenseKey = Convert.ToBase64String(licenseKeyBytes); var hashedLicenseKey = BCrypt.Net.BCrypt.HashPassword(licenseKey); var license = new LicenseEntity { Id = Guid.NewGuid(), UserId = user.Id, Key = hashedLicenseKey, Products = new List <LicenseProductEntity> { product } }; await licenseCollection.InsertOneAsync(license); Console.WriteLine($"Inserted User '{user.Id}' with License '{license.Id}'"); }
public static LicenseDto ToDto(this LicenseEntity license) { return(new LicenseDto { Id = license.Id, Products = license.Products.Select(x => x.ToDto()).ToList() }); }
public Task SetAsync(LicenseEntity license) { using (var db = _databaseContextFactory.CreateDbContext()) { db.Licenses.Add(license); return(db.SaveChangesAsync()); } }
public LicenseEntity ParseLicenseFromBASE64String(Type licenseObjType, string licenseString, out LicenseStatus licStatus, out string validationMsg) { validationMsg = string.Empty; licStatus = LicenseStatus.UNDEFINED; if (string.IsNullOrWhiteSpace(licenseString)) { licStatus = LicenseStatus.CRACKED; return(null); } string _licXML = string.Empty; LicenseEntity _lic = null; try { //Get RSA key from certificate X509Certificate2 cert = new X509Certificate2(CertificatePublicKeyData); RSACryptoServiceProvider rsaKey = (RSACryptoServiceProvider)cert.PublicKey.Key; XmlDocument xmlDoc = new XmlDocument(); // Load an XML file into the XmlDocument object. xmlDoc.PreserveWhitespace = true; xmlDoc.LoadXml(Encoding.UTF8.GetString(Convert.FromBase64String(licenseString))); // Verify the signature of the signed XML. if (VerifyXml(xmlDoc, rsaKey)) { XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Signature"); xmlDoc.DocumentElement.RemoveChild(nodeList[0]); _licXML = xmlDoc.OuterXml; //Deserialize license XmlSerializer _serializer = new XmlSerializer(typeof(LicenseEntity), new Type[] { licenseObjType }); using (StringReader _reader = new StringReader(_licXML)) { _lic = (LicenseEntity)_serializer.Deserialize(_reader); } licStatus = _lic.DoExtraValidation(IsMobileUidInput, out validationMsg); } else { licStatus = LicenseStatus.INVALID; } } catch (Exception exc) { validationMsg = exc.Message; licStatus = LicenseStatus.CRACKED; } return(_lic); }
public static LicenseEntity ReadLicense(Type licenseObjType, string licenseString, byte[] certPubKeyData, out LicenseStatus licStatus, out string validationMsg) { if (string.IsNullOrWhiteSpace(licenseString)) { licStatus = LicenseStatus.Cracked; validationMsg = "Licencja uszkodzona"; return(null); } LicenseEntity license = null; try { //Get RSA key from certificate X509Certificate2 cert = new X509Certificate2(certPubKeyData); RSACryptoServiceProvider rsaKey = (RSACryptoServiceProvider)cert.PublicKey.Key; XmlDocument xmlDoc = new XmlDocument { PreserveWhitespace = true }; // Load an XML file into the XmlDocument object. xmlDoc.LoadXml(Encoding.UTF8.GetString(Convert.FromBase64String(licenseString))); // Verify the signature of the signed XML. if (VerifyXml(xmlDoc, rsaKey)) { XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Signature"); xmlDoc.DocumentElement?.RemoveChild(nodeList[0]); string licXml = xmlDoc.OuterXml; //Deserialize license XmlSerializer serializer = new XmlSerializer(typeof(LicenseEntity), new[] { licenseObjType }); using (StringReader reader = new StringReader(licXml)) { license = (LicenseEntity)serializer.Deserialize(reader); } licStatus = license.DoExtraValidation(out validationMsg); } else { licStatus = LicenseStatus.Invalid; validationMsg = "Nieprawidłowy plik licencji"; } } catch (Exception e) { licStatus = LicenseStatus.Cracked; validationMsg = "Licencja uszkodzona\n" + e.Message; } return(license); }
/// <summary> /// 保存 License 信息。 /// </summary> /// <param name="entity"></param> private void _SaveLicense(LicenseEntity entity) { var repository = RF.ResolveInstance <LicenseEntityRepository>(); repository.Save(entity); this.tbLicenseCode.Text = entity.LicenseCode; this.tbLicenseCode.Focus(); this.tbLicenseCode.Select(0, entity.LicenseCode.Length); Clipboard.SetText(entity.LicenseCode); this.lblLog.Text = LicenseManagerResource.ManagerFormSaveLicenseSuccess; }
public async Task GivenLicenseWithId_ReturnsLicense() { // Arrange var licenseId = Guid.NewGuid(); var query = new GetLicenseByIdQuery { LicenseId = licenseId }; var license = new LicenseEntity { Id = licenseId, Key = "This is a key", Created = DateTime.UtcNow, UserId = Guid.NewGuid(), Products = new List <LicenseProductEntity> { new LicenseProductEntity { Name = "Product Name", Created = DateTime.UtcNow, Expiration = DateTime.UtcNow.AddDays(1) } } }; await _licenseCollection.InsertOneAsync(license, null, CancellationToken.None); // Act var result = await _classUnderTest.Handle(query, CancellationToken.None); // Assert Assert.Multiple(() => { Assert.That(result.Id, Is.EqualTo(licenseId)); Assert.That(result.Key, Is.Not.EqualTo(license.Key)); DiagnoseaAssert.That(result.Created, Is.Not.EqualTo(license.Created)); Assert.That(result.UserId, Is.Not.Null); CollectionAssert.IsNotEmpty(result.Products); Assert.That(result.Products[0].Name, Is.EqualTo(license.Products[0].Name)); DiagnoseaAssert.That(result.Products[0].Created, Is.Not.EqualTo(license.Products[0].Created)); DiagnoseaAssert.That(result.Products[0].Expiration, Is.EqualTo(license.Products[0].Expiration)); }); }
public LicenseEntity GetLicense(string RequestKey) { //RequestKey là số điện thoại của hãng. hoặc mã XN LicenseEntity objLicense = new LicenseEntity(); try { if (CheckAuth()) { } return(objLicense); } catch (Exception ex) { return(objLicense); } }
/// <summary> /// 生成 License Code。 /// </summary> /// <param name="entity"></param> /// <returns></returns> internal static string GeneratorLicenseCode(LicenseEntity entity) { if (entity.LicenseTarget == LicenseTarget.None) { MessageBox.Show(LicenseManagerResource.ManagerFormGetLicenseEntityAuthenticationTargetWarning, LicenseManagerResource.ManagerFormValidateParametersWarning, MessageBoxButtons.OK, MessageBoxIcon.Warning); return(string.Empty); } var authCode = new AuthorizationCode { ExpireTime = entity.ExpireTime, Mac = entity.MacCode, Category = entity.LicenseTarget == LicenseTarget.Development ? 0 : 1 }; var licenseCode = SecurityAuthentication.Encrypt(authCode, LicenseManagerResource.PublicKey); return(licenseCode); }
public bool ValidateLicense() { if (string.IsNullOrWhiteSpace(txtLicense.Text)) { MessageBox.Show("Please input license", string.Empty, MessageBoxButton.OK, MessageBoxImage.Warning); return(false); } //Check the activation string LicenseStatus _licStatus = LicenseStatus.UNDEFINED; string _msg = string.Empty; try { LicenseEntity _lic = LicenseHandler.ParseLicenseFromBASE64String(LicenseObjectType, txtLicense.Text.Trim(), CertificatePublicKeyData, out _licStatus, out _msg); switch (_licStatus) { case LicenseStatus.VALID: if (ShowMessageAfterValidation) { MessageBox.Show(_msg, "License is valid", MessageBoxButton.OK, MessageBoxImage.Information); } return(true); case LicenseStatus.CRACKED: case LicenseStatus.INVALID: case LicenseStatus.UNDEFINED: if (ShowMessageAfterValidation) { MessageBox.Show(_msg, "License is INVALID", MessageBoxButton.OK, MessageBoxImage.Error); } return(false); default: return(false); } } catch (Exception e) { throw e; } }
public bool ValidateLicense(string txtLicense, Type LicenseObjectType, out string message) { message = ""; if (string.IsNullOrWhiteSpace(txtLicense)) { message = "Please input license"; MessageBox.Show(message, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } //Check the activation string LicenseStatus _licStatus = LicenseStatus.UNDEFINED; string _msg = string.Empty; LicenseEntity _lic = ParseLicenseFromBASE64String(LicenseObjectType, txtLicense.Trim(), out _licStatus, out _msg); switch (_licStatus) { case LicenseStatus.VALID: if (ShowMessageAfterValidation) { message = "License is valid ."; MessageBox.Show(_msg, message, MessageBoxButtons.OK, MessageBoxIcon.Information); message += _msg; } LicenseInfo = ShowLicenseInfo(_lic, ""); return(true); case LicenseStatus.CRACKED: case LicenseStatus.INVALID: case LicenseStatus.UNDEFINED: if (ShowMessageAfterValidation) { message = "License is INVALID ."; MessageBox.Show(_msg, message, MessageBoxButtons.OK, MessageBoxIcon.Error); message += _msg; } return(false); default: return(false); } }
public async Task GivenLicenseExists_RespondsWithLicense() { // Arrange var licenseId = Guid.NewGuid(); var url = GetUrl(licenseId); var bearerToken = new TestBearerTokenBuilder() .WithRole(UserRole.Standard) .Build(); var license = new LicenseEntity { Id = licenseId, Key = "This is a key", Created = DateTime.UtcNow, Products = new List <LicenseProductEntity> { new LicenseProductEntity { Name = "Product Name", Created = DateTime.UtcNow, Expiration = DateTime.UtcNow } } }; await _licenseCollection.InsertOneAsync(license); HttpClient.SetBearerToken(bearerToken); // Act var response = await HttpClient.GetAsync(url); // Assert var responseData = await response.Content.ReadFromJsonAsync <LicenseResponse>(); Assert.Multiple(() => { Assert.That(responseData.Id, Is.EqualTo(licenseId)); Assert.That(responseData.Products[0].Name, Is.EqualTo(license.Products[0].Name)); DiagnoseaAssert.That(responseData.Products[0].Expiration, Is.EqualTo(license.Products[0].Expiration)); }); }
/// <summary> /// 保存 License 信息。 /// </summary> /// <param name="entity"></param> private void _SaveLicense(LicenseEntity entity) { var repository = RF.ResolveInstance <LicenseEntityRepository>(); repository.Save(entity); this.tbLicenseCode.Text = entity.LicenseCode; this.tbLicenseCode.Focus(); this.tbLicenseCode.Select(0, entity.LicenseCode.Length); try { Clipboard.SetText(entity.LicenseCode); this.lblLog.Text = LicenseManagerResource.ManagerFormSaveLicenseSuccess; } catch (ExternalException) { MessageBox.Show(@"自动复制到剪贴版失败,请手动复制。", LicenseManagerResource.ManagerFormGetLicenseEntityAuthenticationTargetWarning, MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
public async Task GivenLicenseWithoutId_ReturnsNull() { // Arrange var query = new GetLicenseByIdQuery { LicenseId = Guid.NewGuid() }; var license = new LicenseEntity { Id = Guid.NewGuid() }; await _licenseCollection.InsertOneAsync(license, null, CancellationToken.None); // Act var result = await _classUnderTest.Handle(query, CancellationToken.None); // Assert Assert.That(result, Is.Null); }
/// <summary> /// 获取一个 <see cref="LicenseEntity"/> 对象的实例。 /// </summary> /// <returns></returns> private LicenseEntity _GetLicenseEntity() { this._keys = new[] { this.tbPrivateKey.Text.Trim(), this.tbPublicKey.Text.Trim() }; var mac = this.tbMac.Text.Trim(); var expireTime = this.dtpExpireTime.Value; LicenseTarget authorizationTarget; if (!Enum.TryParse(this.cbxAuthorizationTarget.SelectedValue.ToString(), out authorizationTarget)) { MessageBox.Show(LicenseManagerResource.ManagerFormGetLicenseEntityAuthenticationTargetWarning, LicenseManagerResource.ManagerFormValidateParametersWarning, MessageBoxButtons.OK, MessageBoxIcon.Warning); return(null); } var license = new LicenseEntity { PrivateKey = this._keys[0], PublicKey = this._keys[1], MacCode = mac, ExpireTime = expireTime, LicenseTarget = authorizationTarget, CreateTime = DateTime.Now, PersistenceStatus = PersistenceStatus.New }; if (!ManagerFormService.ValidateParameters(license)) { return(null); } var licenseCode = ManagerFormService.GeneratorLicenseCode(license); if (string.IsNullOrWhiteSpace(licenseCode)) { return(null); } license.LicenseCode = licenseCode; return(license); }
/// <summary> /// Metodo para validar la licencia /// </summary> /// <returns></returns> public bool ValidateLicense() { string richText = new TextRange(txtLicense.Document.ContentStart, txtLicense.Document.ContentEnd).Text; if (string.IsNullOrWhiteSpace(richText)) { MessageBox.Show("¡Por favor ingrese la licencia!"); return(false); } //Check the activation string LicenseStatus _licStatus = LicenseStatus.UNDEFINED; string _msg = string.Empty; LicenseEntity _lic = LicenseHandler.ParseLicenseFromBASE64String(LicenseObjectType, richText.Trim(), CertificatePublicKeyData, out _licStatus, out _msg); switch (_licStatus) { case LicenseStatus.VALID: if (ShowMessageAfterValidation) { MessageBox.Show(_msg, "Felicidades ¡La licencia es VALIDA!"); } return(true); case LicenseStatus.CRACKED: case LicenseStatus.INVALID: case LicenseStatus.UNDEFINED: if (ShowMessageAfterValidation) { MessageBox.Show(_msg, "¡La licencia ingresada es INVALIDA!"); } return(false); default: return(false); } }
private void but_Save_Click(object sender, EventArgs e) { if (txt_Name.Text.Length == 0) { MessageBox.Show("许可证名称不能为空!"); return; } if (txt_AssemblyName.Text.Length == 0) { MessageBox.Show("程序集名称不能为空!"); return; } but_Save.Enabled = false; LicenseEntity license = new LicenseEntity(); license.ID = Guid.NewGuid(); license.Name = txt_Name.Text; license.AssemblyName = txt_AssemblyName.Text; license.PastDate = txt_PastDate.Value.ToString("yyyy-MM-dd"); license.UseNumber = int.Parse(txt_UseNumber.Text); license.InstallNumber = int.Parse(txt_InstallNumber.Text); license.VersionUpgrade = txt_VersionUpgrade.Checked; string context = DESEncrypt.Encrypt(XmlFormatterSerializer.SerializeToXml(license, license.GetType())); string licenseFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "LCL.lic"); if (!File.Exists(licenseFile) == true) { File.Delete(licenseFile); } File.WriteAllText(licenseFile, context); MessageBox.Show("写入成功"); but_Save.Enabled = true; }
public async Task UpdateAsync(LicenseEntity entity) { await Client.PutAsync(entity, "Self", entity).ConfigureAwait(false); }
public void ShowLicenseInfo(LicenseEntity license) { ShowLicenseInfo(license, string.Empty); }
/// <summary> /// Update an existing license. /// </summary> /// <param name="entity">The license to update.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> allowing the operation to be canceled.</param> /// <returns>A task indicating completion.</returns> public async Task UpdateAsync(LicenseEntity entity, CancellationToken cancellationToken = default) { await Client.PutAsync(entity, "Self", entity, cancellationToken : cancellationToken).ConfigureAwait(false); }
private static void AssertCreatedLicense(LicenseEntity license, CreateLicenseRequest request) { DiagnoseaAssert.That(license.Created, Is.EqualTo(DateTime.UtcNow)); Assert.That(BCrypt.Net.BCrypt.Verify(request.UserId.ToString(), license.Key)); Assert.That(license.UserId, Is.EqualTo(request.UserId)); }
public void ShowLicenseInfo(LicenseEntity license, string additionalInfo) { try { StringBuilder _sb = new StringBuilder(512); Type _typeLic = license.GetType(); PropertyInfo[] _props = _typeLic.GetProperties(); object _value = null; string _formatedValue = string.Empty; foreach (PropertyInfo _p in _props) { try { ShowInLicenseInfoAttribute _showAttr = (ShowInLicenseInfoAttribute)Attribute.GetCustomAttribute(_p, typeof(ShowInLicenseInfoAttribute)); if (_showAttr != null && _showAttr.ShowInLicenseInfo) { _value = _p.GetValue(license, null); _sb.Append(_showAttr.DisplayAs); _sb.Append(": "); //Append value and apply the format if (_value != null) { switch (_showAttr.DataFormatType) { case ShowInLicenseInfoAttribute.FormatType.String: _formatedValue = _value.ToString(); break; case ShowInLicenseInfoAttribute.FormatType.Date: if (_p.PropertyType == typeof(DateTime) && !string.IsNullOrWhiteSpace(DateFormat)) { _formatedValue = ((DateTime)_value).ToString(DateFormat); } else { _formatedValue = _value.ToString(); } break; case ShowInLicenseInfoAttribute.FormatType.DateTime: if (_p.PropertyType == typeof(DateTime) && !string.IsNullOrWhiteSpace(DateTimeFormat)) { _formatedValue = ((DateTime)_value).ToString(DateTimeFormat); } else { _formatedValue = _value.ToString(); } break; case ShowInLicenseInfoAttribute.FormatType.EnumDescription: string _name = Enum.GetName(_p.PropertyType, _value); if (_name != null) { FieldInfo _fi = _p.PropertyType.GetField(_name); DescriptionAttribute _dna = (DescriptionAttribute)Attribute.GetCustomAttribute(_fi, typeof(DescriptionAttribute)); if (_dna != null) { _formatedValue = _dna.Description; } else { _formatedValue = _value.ToString(); } } else { _formatedValue = _value.ToString(); } break; } _sb.Append(_formatedValue); } _sb.Append("\r\n"); } } catch { //Ignore exeption } } if (string.IsNullOrWhiteSpace(additionalInfo)) { _sb.Append(additionalInfo.Trim()); } txtLicInfo.Text = _sb.ToString(); } catch (Exception ex) { txtLicInfo.Text = ex.Message; } }
public void ShowLicenseInfo(LicenseEntity license, string additionalInfo) { try { StringBuilder _sb = new StringBuilder(512); Type _typeLic = license.GetType(); PropertyInfo[] _props = _typeLic.GetProperties(); object _value = null; string _formatedValue = string.Empty; foreach (PropertyInfo _p in _props) { try { ShowInLicenseInfoAttribute _showAttr = (ShowInLicenseInfoAttribute)Attribute.GetCustomAttribute(_p, typeof(ShowInLicenseInfoAttribute)); if (_showAttr != null && _showAttr.ShowInLicenseInfo) { _value = _p.GetValue(license, null); _sb.Append(_showAttr.DisplayAs); _sb.Append(": "); //Append value and apply the format if (_value != null) { switch (_showAttr.DataFormatType) { case ShowInLicenseInfoAttribute.FormatType.String: _formatedValue = _value.ToString(); break; case ShowInLicenseInfoAttribute.FormatType.Date: if (_p.PropertyType == typeof(DateTime) && !string.IsNullOrWhiteSpace(DateFormat)) { _formatedValue = ((DateTime)_value).ToString(DateFormat); } else { _formatedValue = _value.ToString(); } break; case ShowInLicenseInfoAttribute.FormatType.DateTime: if (_p.PropertyType == typeof(DateTime) && !string.IsNullOrWhiteSpace(DateTimeFormat)) { _formatedValue = ((DateTime)_value).ToString(DateTimeFormat); } else { _formatedValue = _value.ToString(); } break; case ShowInLicenseInfoAttribute.FormatType.EnumDescription: string _name = Enum.GetName(_p.PropertyType, _value); if (_name != null) { FieldInfo _fi = _p.PropertyType.GetField(_name); DescriptionAttribute _dna = (DescriptionAttribute)Attribute.GetCustomAttribute(_fi, typeof(DescriptionAttribute)); if (_dna != null) _formatedValue = _dna.Description; else _formatedValue = _value.ToString(); } else { _formatedValue = _value.ToString(); } break; } _sb.Append(_formatedValue); } _sb.Append("\r\n"); } } catch { //Ignore exeption } } if (string.IsNullOrWhiteSpace(additionalInfo)) { _sb.Append(additionalInfo.Trim()); } txtLicInfo.Text = _sb.ToString(); } catch (Exception ex) { txtLicInfo.Text = ex.Message; } }