/// <summary>Refreshes the license file.</summary> /// <returns>Returns true if the license file was refreshed successfully. If false is returned, see the <see cref="License.LastError"/> property for details.</returns> internal bool RefreshLicense(XmlLicenseFileService webservice) { if (null == webservice) { LastError = new LicenseError(LicenseError.ERROR_WEBSERVICE_INVALID_CONFIGURATION); return(false); } string licenseContent = ""; if (!base.RefreshLicense(webservice, ref licenseContent)) { if (SampleLicense.ShouldLicenseBeRevoked(LastError.ExtendedErrorNumber)) { if (!RemoveLicense()) { return(false); } } return(false); } //try to save the license file to the file system if (!SaveLicenseFile(licenseContent)) { return(false); } return(true); }
/// <summary>Refreshes the license file.</summary> /// <returns>Returns true if the license file was refreshed successfully. If false is returned, see the <see cref="License.LastError"/> property for details.</returns> internal bool RefreshLicense() { string licenseContent = ""; //initialize the object used for calling the web service method using (XmlLicenseFileService ws = m_Settings.CreateNewXmlLicenseFileServiceObject()) { if (null == ws) { LastError = new LicenseError(LicenseError.ERROR_WEBSERVICE_INVALID_CONFIGURATION); return(false); } if (!base.RefreshLicense(ws, ref licenseContent)) { if (SampleLicense.ShouldLicenseBeRevoked(LastError.ExtendedErrorNumber)) { RemoveLicense(); } return(false); } } //try to save the license file to the file system if (!SaveLicenseFile(licenseContent, false)) { return(false); } return(true); }
private bool ValidateVersion() { List <int> productVersions = new List <int>() { 362368, 362392, 358384 }; LicenseError err = null; //Tries to validate the 3 different versions, if the product id of the license does not equal any of the versions available then return false foreach (int productVersion in productVersions) { LicenseProductValidation validation = new LicenseProductValidation(this, productVersion); if (validation.Validate()) { ThisProductID = productVersion; return(true); } else { err = validation.LastError; } } LastError = err; return(false); }
private Activation GetSavedActivation() { Activation result = null; var encodedString = ReadActivationString(); if (!string.IsNullOrWhiteSpace(encodedString)) { var decoded = Decode(encodedString); if (decoded != null) { var couldParse = _parser.TryParse(decoded); if (couldParse) { result = _parser.ParsedActivation; } else { Error = LicenseError.ParseFailed; } } else { Error = LicenseError.DecodeFailed; } } else { Error = LicenseError.NoActivation; } return(result); }
public LicenseStatus(LicenseError errorType, bool isRegistered, LicenseInformation info, string errorMessage) { _info = info; _isRegistered = isRegistered; _errorType = errorType; _errorMessage = errorMessage; }
/// <summary>Updates the LicenseStatus property.</summary> public void UpdateLicenseStatusProperty() { StringBuilder status = new StringBuilder(); switch (m_License.LastError.ErrorNumber) { case LicenseError.ERROR_COULD_NOT_LOAD_LICENSE: status.Append(m_License.LastError.ErrorNumber); status.Append(": "); status.Append("License not found - activation is required."); break; case LicenseError.ERROR_LICENSE_NOT_EFFECTIVE_YET: status.Append(m_License.LastError.ErrorNumber); status.Append(": "); status.Append("License not effective until "); DateTime local = m_License.EffectiveStartDate.ToLocalTime(); int daysUntilEffective = (int)local.Subtract(DateTime.Now.Date).TotalDays; if (1 < daysUntilEffective) { status.Append(local.ToLongDateString()); status.Append(" ("); status.Append(daysUntilEffective); status.Append(" days)."); } else if (1 == daysUntilEffective) { status.Append("tomorrow."); } else { status.Append(local.ToShortTimeString() + " today."); } break; case LicenseError.ERROR_LICENSE_EXPIRED: status.Append(m_License.LastError.ErrorNumber); status.Append(": "); status.Append("License invalid or expired."); break; case LicenseError.ERROR_WEBSERVICE_RETURNED_FAILURE: //Web service error message. status.Append(m_License.LastError.ExtendedErrorNumber); status.Append(": "); status.Append(LicenseError.GetWebServiceErrorMessage(m_License.LastError.ExtendedErrorNumber)); break; default: //Show a standard error message. status.Append(m_License.LastError.ErrorNumber); status.Append(": "); status.Append(m_License.LastError.ToString()); break; } LicenseStatus = status.ToString(); }
/// <summary>Validates the license</summary> /// <returns>Returns true if the license is valid, false otherwise.</returns> internal bool Validate() { //If OptionType is Downloadable or Volume, return error. if (ProductOption.OptionType == LicenseProductOption.ProductOptionType.DownloadableLicenseWithTriggerCodeValidation || ProductOption.OptionType == LicenseProductOption.ProductOptionType.VolumeLicense) { LastError = new LicenseError(LicenseError.ERROR_INVALID_LICENSE_TYPE); return(false); } //Refresh the license if date difference is greater than m_RefreshLicenseAttemptFrequency (days) if (this.IsRefreshLicenseAttemptDue) { //If refresh license fails and date difference is greater than m_RefreshLicenseRequireFrequency (days) set license as invalid if (!RefreshLicense() && (LastError.ErrorNumber != LicenseError.ERROR_WEBSERVICE_CALL_FAILED || IsRefreshLicenseRequired)) { return(false); } } //Create a list of validations to perform. List <SystemValidation> validations = new List <SystemValidation>(); //Make sure there is no active system clock tampering occurring. validations.Add(new SystemClockValidation()); //Validate the Product ID authorized in the license to make sure the license file was issued for this application. validations.Add(new LicenseProductValidation(this, ThisProductID)); //Validate the current identifiers. validations.Add(new SystemIdentifierValidation( AuthorizedIdentifiers, CurrentIdentifiers, SystemIdentifierValidation.REQUIRE_EXACT_MATCH)); //Add a validation to make sure this system is authorized to use the activated license. (This implements copy-protection.) if (TypeOfLicense == LicenseTypes.TimeLimited) { //If the license is time-limited, make sure it is within its effective date/time period. validations.Add(new LicenseEffectiveDateValidation(this)); } //Run all of the validations (in the order they were added), and make sure all of them succeed. foreach (SystemValidation validation in validations) { if (!validation.Validate()) { LastError = validation.LastError; return(false); } } //If we got this far, all validations were successful, so return true to indicate success and a valid license. return(true); }
/// <summary>Loads the volume license file.</summary> /// <param name="path">The absolute path to the volume license file.</param> /// <returns>Returns true if successful. If false is returned, check the <see cref="License.LastError"/> property for details.</returns> public bool LoadVolumeLicenseFile(string path) { bool successful = base.LoadFile(path); if (!successful && LastError.ErrorNumber == LicenseError.ERROR_COULD_NOT_LOAD_LICENSE) { LastError = new LicenseError(LicenseError.ERROR_COULD_NOT_LOAD_VOLUME_DOWNLOADABLE_LICENSE, LastError.ErrorException); } return(successful); }
static void CheckLicense(string licenseItem) { LicenseError error = LicenseManager.Check(licenseItem); if (error == null) { Console.WriteLine(string.Format(string.Format("{0} licensed successfully.", licenseItem))); } else { OutputError(licenseItem, error); } }
private static void OutputLicenseItemValidation(string licenseItemName) { LicenseError licenseError = LicenseManager.Check(licenseItemName); Console.Write(licenseItemName + ": "); if (licenseError == null) { Console.WriteLine("A valid license granted"); } else { Console.WriteLine(string.Format("Cannot grant a valid license, reason=\"{0}\", message=\"{1}\"", licenseError.Reason, licenseError.Message)); } }
/// <summary>Saves a new license file to the file system.</summary> /// <param name="licenseContent">The new license file content to save to disk.</param> /// <param name="forceAliasUpdates">Whether or not aliases should be updated even when the system clock appears to have been back-dated. This parameter is ignored with read-only licenses.</param> /// <returns>Returns true if the license file was saved successfully. If false is returned, check the <see cref="License.LastError"/> property for details.</returns> internal bool SaveLicenseFile(string licenseContent, bool forceAliasUpdates) { try { File.WriteAllText(LicenseConfiguration.LicenseFilePath, licenseContent); } catch (Exception ex) { LastError = new LicenseError(LicenseError.ERROR_COULD_NOT_SAVE_LICENSE, ex); return(false); } return(true); }
/// <summary>Deletes the license file from the Path where it is stored.</summary> /// <returns>Returns true if File deletion was successful, false otherwise</returns> internal bool RemoveLicense() { bool successful = true; try { File.Delete(LicenseConfiguration.LicenseFilePath); } catch (Exception ex) { LastError = new LicenseError(LicenseError.ERROR_COULD_NOT_DELETE_FILE, ex); successful = false; } return(successful); }
// ================================FUNCTION IMPLEMENTATION START================================ \\ public Activation GetActivation() { var savedActivation = GetSavedActivation(); if (savedActivation != null && savedActivation.IsActivationStillValid()) { return(savedActivation); } var key = savedActivation?.Key ?? ReadKey(); if (string.IsNullOrWhiteSpace(key)) { Error = LicenseError.NoLicenseKey; return(null); } var couldConnect = _connection.TryGetServerResponse(key); if (!couldConnect) { Error = LicenseError.NoServerConnection; return(null); } var licenseStringFromServer = _connection.Response; var couldParse = _parser.TryParse(licenseStringFromServer); if (!couldParse) { Error = LicenseError.ParseFailed; return(null); } var activationFromServer = _parser.ParsedActivation; if (!HasValidActivationTime(activationFromServer)) { Error = LicenseError.InvalidActivationTime; return(null); } SaveActivation(activationFromServer); return(activationFromServer); }
static int Main(string[] args) { string errorMessage = LicenseConsoleData.Initialize(); if (errorMessage != null) { MessageBox.Show(errorMessage); return(0); } LicenseError licenseError = DevZest.Licensing.LicenseManager.Check(".Net Licensing", typeof(LicenseClient)); if (licenseError != null) { MessageBox.Show(licenseError.ExceptionMessage); return(-1); } App.Main(); return(0); }
public List <LicenseError> GetLicensesWithErrors() { var listOfLicensesWithErrors = new List <LicenseError>(); var licenseIdsWithErrors = _licenseRepository.GetAllLicenseIdsWithErrors(); var listOfLicenseErrors = new List <License>(); foreach (var errorLicenseId in licenseIdsWithErrors) { listOfLicenseErrors.Add(_licenseRepository.GetLite(errorLicenseId)); } foreach (var license in listOfLicenseErrors) { var newLicenseErrorEntry = new LicenseError(); newLicenseErrorEntry.License = license; newLicenseErrorEntry.LicenseErrorInfo = _backDateLicenseChangedRepository.GetLicenseChangedForLicenseIdFull(license.LicenseId); listOfLicensesWithErrors.Add(newLicenseErrorEntry); } return(listOfLicensesWithErrors); }
public LicenseException(LicenseError code, string message, Exception inner) : base(message, inner) { _code = code; }
/// <summary>Since self-signed licenses are only used for un-activated, evaluation license in the "SelfSignedTrial" samples, a refresh is not supported for this license implementation.</summary> /// <returns>Always returns false.</returns> public bool RefreshLicense() { LastError = new LicenseError(LicenseError.ERROR_INVALID_LICENSE_TYPE); return(false); }
/////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// public LicenseException(LicenseError code) { _code = code; }
public LicenseException(LicenseError code, string message) : base(message) { _code = code; }
/// <summary>Validates a volume license.</summary> /// <returns>Returns true if successful. If false is returned, check the <see cref="License.LastError"/> property for details.</returns> internal bool ValidateVolumeLicense() { VolumeLicense vlic = new VolumeLicense(); if (!vlic.LoadVolumeLicenseFile(LicenseConfiguration.VolumeLicenseFilePath)) { LastError = vlic.LastError; return(false); } if (LicenseID != vlic.LicenseID) { LastError = new LicenseError(LicenseError.ERROR_LICENSE_SYSTEM_IDENTIFIERS_DONT_MATCH); return(false); } if (!vlic.Validate()) { LastError = vlic.LastError; return(false); } //TODO: Uncomment the block of code below if you wish to have volume licenses attempt to refresh with SOLO Server. // Note that this can cause the application to experience some delay while the refresh is being attempted, // which is especially noticeable when SOLO Server cannot be reached. /*if (!string.IsNullOrEmpty(vlic.InstallationID) && * LicenseTypes.Unlicensed != vlic.TypeOfLicense && * LicenseMethods.IsRefreshLicenseAttemptDue(vlic.SignatureDate)) * { * using (XmlLicenseFileService ws = m_Settings.CreateNewXmlLicenseFileServiceObject()) * { * //If a refresh attempt should be made, try to perform a license refresh with SOLO Server. * if (!vlic.RefreshLicense(ws) && * (vlic.LastError.ErrorNumber != LicenseError.ERROR_WEBSERVICE_CALL_FAILED || LicenseMethods.IsRefreshLicenseRequired(vlic.SignatureDate))) * { * //The refresh failed and was required, or SOLO Server returned an error. * LastError = vlic.LastError; * return false; * } * } * }*/ //Create a list of validations to perform. List <SystemValidation> validations = new List <SystemValidation>(); //Add a validation to make sure there is no active system clock tampering taking place. validations.Add(new SystemClockValidation()); //Only validate the system identifiers if we activated using trigger codes. (Ignore this validation if it is a volume license.) if (ProductOption.OptionType == LicenseProductOption.ProductOptionType.DownloadableLicenseWithTriggerCodeValidation) { //Add a validation to make sure this system is authorized to use the activated license. validations.Add(new SystemIdentifierValidation( AuthorizedIdentifiers, CurrentIdentifiers, SystemIdentifierValidation.REQUIRE_EXACT_MATCH)); } //Run all of the validations (in the order they were added), and make sure all of them succeed. foreach (SystemValidation validation in validations) { if (!validation.Validate()) { LastError = validation.LastError; return(false); } } return(true); }
/// <summary>Validates the license.</summary> /// <returns>Returns true if validation is successful and the license is valid. If false is returned, check the <see cref="License.LastError"/> property for details.</returns> internal bool Validate() { //If this is a downloadable license which has not been validated with a trigger code, force validation to fail with the appropriate error. if (ProductOption.OptionType == LicenseProductOption.ProductOptionType.DownloadableLicenseWithTriggerCodeValidation && DateTime.MinValue == DateDownloadableLicenseValidated) { LastError = new LicenseError(LicenseError.ERROR_LICENSE_NOT_EFFECTIVE_YET); return(false); } //If this is a downloadable or volume license, validate it differently using the ValidateVolumeLicense method. if (ProductOption.OptionType == LicenseProductOption.ProductOptionType.VolumeLicense || ProductOption.OptionType == LicenseProductOption.ProductOptionType.DownloadableLicenseWithTriggerCodeValidation) { return(ValidateVolumeLicense()); } //Validate the aliases. LicenseAliasValidation aliasValidation = new LicenseAliasValidation(this); bool refreshRequiredForAliases = false; LicenseError aliasError = null; if (!aliasValidation.Validate()) { if (!LicenseConfiguration.RefreshLicenseEnabled || string.IsNullOrEmpty(InstallationID) || TypeOfLicense == LicenseTypes.Unlicensed) { //Alias validation failed, and license refreshing is not enabled (meaning we cannot recover via a refresh), //so just return the validation error. LastError = aliasValidation.LastError; return(false); } //Alias validation failed, and license refreshing is enabled, so take note so we can try updating the license //via a refresh with SOLO Server. TODO: If you do not wish to require phoning-home with SOLO Server when alias //validation fails, comment-out the two lines below this comment. refreshRequiredForAliases = true; aliasError = aliasValidation.LastError; } if (!string.IsNullOrEmpty(InstallationID) && LicenseTypes.Unlicensed != TypeOfLicense && (refreshRequiredForAliases || IsRefreshLicenseAttemptDue)) { //If a refresh attempt should be made, try to perform a license refresh with SOLO Server. if (!RefreshLicense() && (LastError.ErrorNumber != LicenseError.ERROR_WEBSERVICE_CALL_FAILED || refreshRequiredForAliases || IsRefreshLicenseRequired)) { //The refresh failed and was required, or SOLO Server returned an error. if (aliasError != null) { LastError = aliasError; } return(false); } } //Create a list of validations to perform. List <SystemValidation> validations = new List <SystemValidation>(); //Add a validation to make sure there is no active system clock tampering taking place. validations.Add(new SystemClockValidation()); //Validate the Product ID authorized in the license to make sure the license file was issued for this application. validations.Add(new LicenseProductValidation(this, ThisProductID)); //Add a validation to make sure this system is authorized to use the activated license. (This implements copy-protection.) validations.Add(GenerateIdentifierValidation()); if (LicenseTypes.TimeLimited == TypeOfLicense || LicenseTypes.Unlicensed == TypeOfLicense) { //If the license is time-limited or an evaluation, make sure it is within its effective date/time period. validations.Add(new LicenseEffectiveDateValidation(this)); //Validate the system date and time using Network Time Protocol (un-comment the SystemDateTimeValidation below). //IMPORTANT: Read the documentation for more details about using NTP! Do NOT use the NTP servers shown in the // sample code immediately below this comment block. //-------------------------------------------------------------------------------------------------------------- //SystemDateTimeValidation ntpValidation = new SystemDateTimeValidation(); //ntpValidation.AddTimeServerCheck("time.windows.com"); //ntpValidation.AddTimeServerCheck("time.nist.gov"); //validations.Add(ntpValidation); } //Run all of the validations (in the order they were added), and make sure all of them succeed. foreach (SystemValidation validation in validations) { if (!validation.Validate()) { LastError = validation.LastError; return(false); } } //If we got this far, all validations were successful, so return true to indicate success and a valid license. return(true); }
/// <summary>Returns true if the license is valid</summary> /// <returns>bool</returns> public bool IsValid() { // we only check if it's valid every 20 runs LicenseError tmpError = new LicenseError(LicenseError.ERROR_NONE); ; // this.m_effectiveEndDate = DateTime.Today.AddDays(1); if (!this.CheckInstallationStatus()) { //only return an error if the check failed when the web service call was made successfully, // implying the web service likely found the installation's status to be invalid. if (m_lastError.ErrorNumber == LicenseError.ERROR_WEBSERVICE_RETURNED_FAILURE) return false; } //return true if we have enough matching system identifiers if (this.NumberOfMatchingIdentifiers < m_minIdentifierMatches) { m_lastError = new LicenseError(LicenseError.ERROR_LICENSE_SYSTEM_IDENTIFIERS_DONT_MATCH); return false; } // Env.SetConfigVar("run_count", run_count + 1); return true; }
/// <summary>Generates a string containing a description of a license error.</summary> /// <remarks><para>This method is called from <see cref="GenerateLicenseStatusEntry"/>.</para></remarks> /// <returns>Returns a string containing the description of a license error.</returns> internal string GenerateLicenseErrorString() { StringBuilder status = new StringBuilder(); switch (LastError.ErrorNumber) { case LicenseError.ERROR_COULD_NOT_LOAD_LICENSE: status.Append(LastError.ErrorNumber); status.Append(": "); status.Append("License not found - activation is required."); break; case LicenseError.ERROR_COULD_NOT_LOAD_VOLUME_DOWNLOADABLE_LICENSE: status.Append(LastError.ErrorNumber); status.Append(": "); status.Append((ProductOption.OptionType == LicenseProductOption.ProductOptionType.VolumeLicense) ? "Volume" : "Downloadable"); status.Append(" license not found."); break; case LicenseError.ERROR_LICENSE_NOT_EFFECTIVE_YET: status.Append(LastError.ErrorNumber); status.Append(": "); if (ProductOption.OptionType == LicenseProductOption.ProductOptionType.DownloadableLicenseWithTriggerCodeValidation) { status.Append("Activation required."); break; } status.Append("License not effective until "); DateTime local = EffectiveStartDate.ToLocalTime(); int daysUntilEffective = (int)local.Subtract(DateTime.Now.Date).TotalDays; if (1 < daysUntilEffective) { status.Append(local.ToLongDateString()); status.Append(" ("); status.Append(daysUntilEffective); status.Append(" days)."); } else if (1 == daysUntilEffective) { status.Append("tomorrow."); } else { status.Append(local.ToShortTimeString() + " today."); } break; case LicenseError.ERROR_LICENSE_EXPIRED: status.Append(LastError.ErrorNumber); status.Append(": "); status.Append("License invalid or expired."); break; case LicenseError.ERROR_WEBSERVICE_RETURNED_FAILURE: //Web service error message. status.Append(LastError.ExtendedErrorNumber); status.Append(": "); status.Append(LicenseError.GetWebServiceErrorMessage(LastError.ExtendedErrorNumber)); break; default: //Show a standard error message. status.Append(LastError.ErrorNumber); status.Append(": "); status.Append(LastError.ToString()); break; } return(status.ToString()); }
/// <summary> /// 把License错误码转换成Smc错误码 /// </summary> /// <param name="errNo"></param> /// <returns></returns> private SmcErr Convert2ErrNo(uint errNo) { LicenseError err = new LicenseError(errNo); return(err); }
/// <summary>Validates the license.</summary> /// <returns>Returns true if validation is successful and the license is valid. If false is returned, check the <see cref="License.LastError"/> property for details.</returns> internal bool Validate() { //Make sure the option type is supported. if (ProductOption.OptionType == LicenseProductOption.ProductOptionType.DownloadableLicenseWithTriggerCodeValidation) { LastError = new LicenseError(LicenseError.ERROR_INVALID_LICENSE_TYPE); return(false); } //TODO: If you wish to have your volume licenses automatically refresh with SOLO Server, you may // enable this by removing the second expression in the 'if' statement immediately below. if (IsRefreshLicenseAttemptDue && ProductOption.OptionType != LicenseProductOption.ProductOptionType.VolumeLicense) { //If a refresh attempt should be made, try to perform a license refresh with SOLO Server. if (!RefreshLicense() && (LastError.ErrorNumber != LicenseError.ERROR_WEBSERVICE_CALL_FAILED || IsRefreshLicenseRequired)) { //The refresh failed and was required, or SOLO Server returned an error. return(false); } } //Create a list of validations to perform. List <SystemValidation> validations = new List <SystemValidation>(); //Add a validation to make sure there is no active system clock tampering taking place. validations.Add(new SystemClockValidation()); //Validate the Product ID authorized in the license to make sure the license file was issued for this application. validations.Add(new LicenseProductValidation(this, ThisProductID)); //Validate the current identifiers by default. List <SystemIdentifier> validationIdentifiers = CurrentIdentifiers; if (ProductOption.OptionType == LicenseProductOption.ProductOptionType.VolumeLicense) { //This is a volume license, so only validate a single identifier for the License ID. LicenseIDIdentifierAlgorithm alg = new LicenseIDIdentifierAlgorithm(); validationIdentifiers = alg.GetIdentifier(LicenseID); } //Add a validation to make sure this system is authorized to use the activated license. (This implements copy-protection.) validations.Add(new SystemIdentifierValidation( AuthorizedIdentifiers, validationIdentifiers, SystemIdentifierValidation.REQUIRE_EXACT_MATCH)); if (TypeOfLicense == LicenseTypes.TimeLimited) { //If the license is time-limited, make sure it is within its effective date/time period. validations.Add(new LicenseEffectiveDateValidation(this)); } //Run all of the validations (in the order they were added), and make sure all of them succeed. foreach (SystemValidation validation in validations) { if (!validation.Validate()) { LastError = validation.LastError; return(false); } } //If we got this far, all validations were successful, so return true to indicate success and a valid license. return(true); }
/// <summary>Since self-signed licenses are only used for un-activated, evaluation license in the "SelfSignedTrial" samples, deactivation is not supported for this license implementation.</summary> /// <returns>Always returns false.</returns> public bool DeactivateOnline() { LastError = new LicenseError(LicenseError.ERROR_INVALID_LICENSE_TYPE); return(false); }
/// <summary>Processes a Protection PLUS 4 compatible trigger code.</summary> /// <param name="licenseID">The License ID entered by the user.</param> /// <param name="password">The password entered by the user.</param> /// <param name="triggerCodeNumber">The trigger code number to process.</param> /// <param name="triggerCodeEventData">The trigger code event data.</param> /// <returns>Returns true if the trigger code was processed successfully.</returns> internal bool ProcessTriggerCode(int licenseID, string password, int triggerCodeNumber, int triggerCodeEventData) { bool isValidTriggerCodeNumber = true; bool isValidTriggerCodeEventData = true; //Save the License ID entered by the user in the license file. if (licenseID > 0) { LicenseID = licenseID; } switch (triggerCodeNumber) { case 1: case 28: //Activates a full/non-expiring license. //If we are changing the type of license, clear the details for the prior activation so we don't end up //overwriting the new license type after doing a refresh in the future. if (TypeOfLicense != LicenseTypes.FullNonExpiring) { ClearActivationDetails(); } //This sample uses the TriggerCode property to determine the type of license issued, so set it accordingly. TriggerCode = (int)LicenseTypes.FullNonExpiring; //Remove any volume license data RemoveVolumeLicense(); //Now try to write all of the aliases and the license file. SaveLicenseFile(); break; case 10: case 11: case 29: //Activates a time-limited/periodic license. if (triggerCodeEventData < 1) { isValidTriggerCodeEventData = false; break; } //If we are changing the type of license, clear the details for the prior activation so we don't end up //overwriting the new license type after doing a refresh in the future. if (TypeOfLicense != LicenseTypes.TimeLimited) { ClearActivationDetails(); } //This sample uses the TriggerCode property to determine the type of license issued, so set it accordingly. TriggerCode = (int)LicenseTypes.TimeLimited; //Calculate the new effective end date. This extends a non-expired licenses from their existing expiration //date when the trigger code number is not 11. Otherwise, if the trigger code number is 11, the new //expiration date is *always* calculated from the current date. EffectiveEndDate = CalculateNewEffectiveEndDate(triggerCodeEventData, (11 != triggerCodeNumber)); //Remove any volume license data RemoveVolumeLicense(); SaveLicenseFile(); break; case 18: //Activates a downloadable license //This sample uses the TriggerCode property to determine the type of license issued, so set it accordingly. TriggerCode = (int)LicenseTypes.FullNonExpiring; //Store the date and time the license was verified. DateDownloadableLicenseValidated = DateTime.UtcNow; //Now try to write all of the aliases and the license file. SaveLicenseFile(); break; case 20: //Extends an evaluation. if (triggerCodeEventData < 1) { isValidTriggerCodeEventData = false; break; } //Create the new evaluation. CreateEvaluation(triggerCodeEventData, false, true); break; default: isValidTriggerCodeNumber = false; break; } if (!isValidTriggerCodeNumber) { LastError = new LicenseError(LicenseError.ERROR_TRIGGER_CODE_INVALID); return(false); } if (!isValidTriggerCodeEventData) { LastError = new LicenseError(LicenseError.ERROR_TRIGGER_CODE_EVENT_DATA_INVALID); return(false); } return(true); }
/// <summary>The Check-In button click event handler</summary> /// <param name="sender">Sender object</param> /// <param name="e">Event arguments</param> private void checkInButton_Click(object sender, EventArgs e) { if (!m_NetworkSession.Certificate.CheckedOut) { MessageBox.Show(this, "Your network session must be checked out before you can check it back in.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } //call the web service using (XmlNetworkFloatingService webservice = new XmlNetworkFloatingService()) { webservice.Url = ConfigurationManager.AppSettings["NetworkFloatingServiceEndpointUrl"]; if (!m_NetworkSession.CheckinSession(webservice)) { if (ShouldLastResponseRevokeSession()) { MessageBox.Show(this, "The session will be closed. Reason: " + LicenseError.GetWebServiceErrorMessage(m_NetworkSession.LastError.ExtendedErrorNumber), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); closeSessionButton_Click(sender, e); return; } MessageBox.Show(this, "The session could not be checked in. " + m_NetworkSession.LastError.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } } this.RefreshSessionInformation(); }
/// <summary>The Check-Out button click event handler</summary> /// <param name="sender">Sender object</param> /// <param name="e">Event arguments</param> private void checkoutButton_Click(object sender, EventArgs e) { if (m_NetworkSession.Certificate.CheckedOut) { MessageBox.Show(this, "Your network session has already been checked out.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } if (File.Exists(m_CertificatePath)) { MessageBox.Show(this, "Another process has checked out a network session. You may only check out from one instance of this application at a time.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } decimal requestedCheckoutDuration = 0; if (string.IsNullOrEmpty(checkoutDurationTextBox.Text) || !decimal.TryParse(checkoutDurationTextBox.Text, out requestedCheckoutDuration)) { MessageBox.Show(this, "Please enter a properly-formatted number of hours for which you would like to have this session checked out.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); checkoutDurationTextBox.Focus(); return; } if (requestedCheckoutDuration < m_NetworkSession.Certificate.CheckoutDurationMinimum || requestedCheckoutDuration > m_NetworkSession.Certificate.CheckoutDurationMaximum) { if (m_NetworkSession.Certificate.CheckoutDurationMinimum == m_NetworkSession.Certificate.CheckoutDurationMaximum) { MessageBox.Show(this, "You may only request to check out the session for " + m_NetworkSession.Certificate.CheckoutDurationMinimum.ToString() + " hours.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { MessageBox.Show(this, "You may only request to check out the session for between " + m_NetworkSession.Certificate.CheckoutDurationMinimum.ToString() + " and " + m_NetworkSession.Certificate.CheckoutDurationMaximum.ToString() + " hours.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } checkoutDurationTextBox.Focus(); return; } //call the web service using (XmlNetworkFloatingService webservice = new XmlNetworkFloatingService()) { webservice.Url = ConfigurationManager.AppSettings["NetworkFloatingServiceEndpointUrl"]; if (!m_NetworkSession.CheckoutSession(requestedCheckoutDuration, webservice)) { if (ShouldLastResponseRevokeSession()) { MessageBox.Show(this, "The session will be closed. Reason: " + LicenseError.GetWebServiceErrorMessage(m_NetworkSession.LastError.ExtendedErrorNumber), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); closeSessionButton_Click(sender, e); return; } MessageBox.Show(this, "The session could not be checked out. " + m_NetworkSession.LastError.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } } this.RefreshSessionInformation(); }
/// <summary>Processes a Protection PLUS compatible trigger code.</summary> /// <param name="tcLicenseID">The License ID entered by the user.</param> /// <param name="tcPassword">The password entered by the user.</param> /// <param name="tcNumber">The trigger code number to process</param> /// <param name="tcEventData">The trigger code event data</param> /// <returns>Returns true if successful. If false is returned, check the <see cref="License.LastError"/> property for details.</returns> internal bool ProcessTriggerCode(int tcLicenseID, string tcPassword, int tcNumber, int tcEventData) { //Trigger codes are not supported with read-only licenses, so return false. LastError = new LicenseError(LicenseError.ERROR_TRIGGER_CODE_INVALID); return(false); }
/// <summary>Returns true if the license is valid</summary> /// <returns>bool</returns> public bool IsValid() { //Check the aliases... int aliasesToCheck, validAliases; bool aliasesValid = false; LicenseError aliasesError; //Check the aliases (which initializes information about them) aliasesValid = this.CheckAliases(out aliasesToCheck, out validAliases); aliasesError = this.m_lastError; //make sure the last date the license was updated isn't in the future try { if (this.LastUpdated > DateTime.UtcNow) { m_lastError = new LicenseError(LicenseError.ERROR_LICENSE_EXPIRED); return false; } } catch (Exception ex) { m_lastError = new LicenseError(LicenseError.ERROR_LICENSE_ALIAS_VALIDATION_TIME_MISMATCH, ex); return false; } //Now that alias data is initialized, see if we need to overwrite the license file with a more recent alias LicenseAlias mostRecent = LicenseAlias.GetMostCurrentAlias(this.Aliases); if (mostRecent.LastUpdated > this.LastUpdated) { this.WriteAliasToLicenseFile(mostRecent, m_trialLicenseFilePath); int aliasesToWrite, aliasesWritten; this.WriteAliases(out aliasesToWrite, out aliasesWritten); } //Now also check the alias validation results if (!aliasesValid) { if (validAliases < m_aliasesRequired || aliasesError.ErrorNumber == LicenseError.ERROR_LICENSE_ALIAS_VALIDATION_TIME_MISMATCH) { m_lastError = aliasesError; return false; } } //make sure the current date isn't before the effective start date try { if (DateTime.Now.Date < m_effectiveStartDate.Date) { m_lastError = new LicenseError(LicenseError.ERROR_LICENSE_NOT_EFFECTIVE_YET); return false; } } catch (Exception ex) { m_lastError = new LicenseError(LicenseError.ERROR_INVALID_DATA, ex); return false; } //make sure the current date isn't after the effective end date try { if (DateTime.Now.Date > m_effectiveEndDate.Date) { m_lastError = new LicenseError(LicenseError.ERROR_LICENSE_EXPIRED); return false; } } catch (Exception ex) { m_lastError = new LicenseError(LicenseError.ERROR_INVALID_DATA, ex); return false; } //make sure the current system date/time is valid if (!this.CheckTimeAgainstServers()) { //allow the NTP check to fail because it couldn't reach the time servers if (this.m_lastError.ErrorNumber == LicenseError.ERROR_SYSTEM_TIME_INVALID) { return false; } } //return true if we have enough matching system identifiers if (this.NumberOfMatchingIdentifiers < m_minIdentifierMatches) { m_lastError = new LicenseError(LicenseError.ERROR_LICENSE_SYSTEM_IDENTIFIERS_DONT_MATCH); return false; } return true; }
private static void OutputError(string feature, LicenseError error) { Console.WriteLine(string.Format("Cannot grant a valid license to {0}, reason=\"{1}\", message=\"{2}\"", feature, error.Reason, error.Message)); }
/// <summary>Saves a new license file to the file system</summary> /// <param name="lfContent">string</param> /// <returns>bool</returns> public bool SaveLicenseFile(string lfContent) { //try to save the license file to the file system try { File.WriteAllText(m_licenseFilePath, lfContent); } catch (Exception ex) { m_lastError = new LicenseError(LicenseError.ERROR_COULD_NOT_SAVE_LICENSE, ex); return false; } return true; }