/// <summary>
    /// Try to set new license for actual domain.
    /// </summary>
    public void SetLicenseKey()
    {
        if (txtLicense.Text == "")
        {
            throw new Exception(ResHelper.GetFileString("Install.LicenseEmpty"));
        }

        LicenseKeyInfo lki = new LicenseKeyInfo();
        lki.LoadLicense(txtLicense.Text, FullHostName);

        switch (lki.ValidationResult)
        {
            case LicenseValidationEnum.Expired:
                throw new Exception(ResHelper.GetFileString("Install.LicenseNotValid.Expired"));
            case LicenseValidationEnum.Invalid:
                throw new Exception(ResHelper.GetFileString("Install.LicenseNotValid.Invalid"));
            case LicenseValidationEnum.NotAvailable:
                throw new Exception(ResHelper.GetFileString("Install.LicenseNotValid.NotAvailable"));
            case LicenseValidationEnum.WrongFormat:
                throw new Exception(ResHelper.GetFileString("Install.LicenseNotValid.WrongFormat"));
            case LicenseValidationEnum.Valid:
                // Try to store license into database
                if ((FullHostName == "localhost") || (FullHostName == "127.0.0.1") || (lki.Domain == FullHostName))
                {
                    LicenseKeyInfoProvider.SetLicenseKeyInfo(lki);
                }
                else
                {
                    throw new Exception(ResHelper.GetFileString("Install.LicenseForDifferentDomain"));
                }
                break;
        }
    }
 /// <summary>
 /// Check if license for current domain is valid. Try to add trial license if possible.
 /// </summary>
 private void CheckLicense()
 {
     // Try to add trial license
     if (CreateDBObjects)
     {
         if (AddTrialLicenseKeys())
         {
             if (hostName != "localhost" && hostName != "127.0.0.1")
             {
                 // Check if license key for current domain is present
                 LicenseKeyInfo lki = LicenseKeyInfoProvider.GetLicenseKeyInfo(hostName);
                 wzdInstaller.ActiveStepIndex = (lki == null) ? 4 : 5;
             }
             else
             {
                 wzdInstaller.ActiveStepIndex = 5;
             }
         }
         else
         {
             wzdInstaller.ActiveStepIndex = 4;
             ucLicenseDialog.SetLicenseExpired();
         }
     }
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Setup page title text and image
        CurrentMaster.Title.TitleText  = GetString("Licenses_License_View.Title");
        CurrentMaster.Title.TitleImage = GetImageUrl("Objects/CMS_LicenseKey/object.png");

        lblLicenseKey.Text      = GetString("Licenses_License_View.LicenseKey");
        string[,] pageTitleTabs = new string[2, 3];
        pageTitleTabs[0, 0]     = GetString("Licenses_License_View.LicenseList");
        pageTitleTabs[0, 1]     = "~/CMSModules/Licenses/Pages/License_List.aspx";
        pageTitleTabs[0, 2]     = "";
        pageTitleTabs[1, 0]     = "";
        pageTitleTabs[1, 1]     = "";
        pageTitleTabs[1, 2]     = "";

        if (ValidationHelper.GetInteger(Request.QueryString["licenseid"], 0) != 0)
        {
            LicenseKeyInfo lki = LicenseKeyInfoProvider.GetLicenseKeyInfo(ValidationHelper.GetInteger(Request.QueryString["licenseid"], 0));
            if (lki != null)
            {
                pageTitleTabs[1, 0]       = lki.Domain;
                lblLicenseKeyContent.Text = lki.Key;
            }
        }

        CurrentMaster.Title.Breadcrumbs = pageTitleTabs;
    }
Example #4
0
    protected void btnOK_Click(object sender, EventArgs e)
    {
        errorOccured = false;
        try
        {
            LicenseKeyInfo lk = new LicenseKeyInfo();
            lk.LoadLicense(tbLicenseKey.Text.Trim(), "");

            if (lk != null)
            {
                switch (lk.ValidationResult)
                {
                case LicenseValidationEnum.Expired:
                    ShowError(GetString("Licenses_License_New.LicenseNotValid.Expired"));
                    break;

                case LicenseValidationEnum.Invalid:
                    ShowError(GetString("Licenses_License_New.LicenseNotValid.Invalid"));
                    break;

                case LicenseValidationEnum.NotAvailable:
                    ShowError(GetString("Licenses_License_New.LicenseNotValid.NotAvailable"));
                    break;

                case LicenseValidationEnum.WrongFormat:
                    ShowError(GetString("Licenses_License_New.LicenseNotValid.WrongFormat"));
                    break;

                case LicenseValidationEnum.Valid:
                    if (LicenseKeyInfoProvider.IsLicenseExistForDomain(lk))
                    {
                        // License for domain already exist
                        ShowError(GetString("Licenses_License_New.DomainAlreadyExists").Replace("%%name%%", lk.Domain));
                    }
                    else
                    {
                        // Insert license
                        LicenseKeyInfoProvider.SetLicenseKeyInfo(lk);
                        UserInfoProvider.ClearLicenseValues();
                        Functions.ClearHashtables();
                    }
                    break;
                }
            }
        }
        catch (Exception ex)
        {
            EventLogProvider.LogException("License", "NEW", ex);
            ShowError(GetString("general.saveerror"), ex.Message, null);
        }

        if (!errorOccured)
        {
            URLHelper.Redirect("License_List.aspx");
        }
    }
    protected void btnOK_Click(object sender, EventArgs e)
    {
        errorOccured = false;
        try
        {
            LicenseKeyInfo lk = new LicenseKeyInfo();
            lk.LoadLicense(tbLicenseKey.Text.Trim(), "");

            if (lk != null)
            {
                switch (lk.ValidationResult)
                {
                    case LicenseValidationEnum.Expired:
                        ShowError(GetString("Licenses_License_New.LicenseNotValid.Expired"));
                        break;

                    case LicenseValidationEnum.Invalid:
                        ShowError(GetString("Licenses_License_New.LicenseNotValid.Invalid"));
                        break;

                    case LicenseValidationEnum.NotAvailable:
                        ShowError(GetString("Licenses_License_New.LicenseNotValid.NotAvailable"));
                        break;

                    case LicenseValidationEnum.WrongFormat:
                        ShowError(GetString("Licenses_License_New.LicenseNotValid.WrongFormat"));
                        break;

                    case LicenseValidationEnum.Valid:
                        if (LicenseKeyInfoProvider.IsLicenseExistForDomain(lk))
                        {
                            // License for domain already exist
                            ShowError(GetString("Licenses_License_New.DomainAlreadyExists").Replace("%%name%%", lk.Domain));
                        }
                        else
                        {
                            // Insert license
                            LicenseKeyInfoProvider.SetLicenseKeyInfo(lk);
                            UserInfoProvider.ClearLicenseValues();
                            Functions.ClearHashtables();
                        }
                        break;
                }
            }
        }
        catch (Exception ex)
        {
            EventLogProvider.LogException("License", "NEW", ex);
            ShowError(GetString("general.saveerror"), ex.Message, null);
        }

        if (!errorOccured)
        {
            URLHelper.Redirect("License_List.aspx");
        }
    }
    /// <summary>
    /// Returns system information.
    /// </summary>
    private static string GetSystemInformation()
    {
        StringBuilder sb = new StringBuilder();

        sb.AppendFormat("CMS version: {0} Build: {1}",
                        CMSVersion.MainVersion,
                        CMSVersion.GetVersion(true, true, true, true));
        sb.AppendLine();

        sb.AppendFormat("OS version: {0}", Environment.OSVersion);
        sb.AppendLine();

        LicenseKeyInfo licenseKey = null;

        if (SiteContext.CurrentSite != null)
        {
            licenseKey = LicenseKeyInfoProvider.GetLicenseKeyInfo(SiteContext.CurrentSite.DomainName);
        }

        if (licenseKey != null)
        {
            sb.AppendFormat("License info: {0}, {1}, {2}, {3}",
                            licenseKey.Domain,
                            licenseKey.Edition,
                            licenseKey.ExpirationDateReal.ToString(DateTimeHelper.DefaultIFormatProvider),
                            licenseKey.Version);

            string packages = ValidationHelper.GetString(licenseKey.GetValue("LicensePackages"), string.Empty);
            if (!string.IsNullOrEmpty(packages))
            {
                sb.AppendFormat(", {0}", packages);
            }
        }

        int eventId = QueryHelper.GetInteger("eventid", 0);

        if (eventId > 0)
        {
            EventLogInfo ev = EventLogProvider.GetEventLogInfo(eventId);
            if (ev != null)
            {
                sb.AppendLine();
                sb.Append(HttpUtility.HtmlDecode(EventLogHelper.GetEventText(ev)));
            }
        }

        return(sb.ToString());
    }
    private void Control_OnAfterValidate(object sender, EventArgs e)
    {
        try
        {
            string         licenseKey = ValidationHelper.GetString(Control.GetFieldValue("LicenseKey"), String.Empty).Trim();
            LicenseKeyInfo lk         = new LicenseKeyInfo();
            lk.LoadLicense(licenseKey, "");

            switch (lk.ValidationResult)
            {
            case LicenseValidationEnum.Valid:
                using (new CMSActionContext {
                    AllowLicenseRedirect = false
                })
                {
                    UserInfoProvider.ClearLicenseValues();
                    Functions.ClearHashtables();
                }
                return;

            case LicenseValidationEnum.Expired:
                Control.ValidationErrorMessage = ResHelper.GetString("Licenses_License_New.LicenseNotValid.Expired");
                break;

            case LicenseValidationEnum.Invalid:
                Control.ValidationErrorMessage = ResHelper.GetString("Licenses_License_New.LicenseNotValid.Invalid");
                break;

            case LicenseValidationEnum.NotAvailable:
                Control.ValidationErrorMessage = ResHelper.GetString("Licenses_License_New.LicenseNotValid.NotAvailable");
                break;

            case LicenseValidationEnum.WrongFormat:
                Control.ValidationErrorMessage = ResHelper.GetString("Licenses_License_New.LicenseNotValid.WrongFormat");
                break;
            }

            Control.StopProcessing             = true;
            Control.ShowValidationErrorMessage = true;
        }
        catch (Exception ex)
        {
            EventLogProvider.LogException("License", "NEW", ex);
            Control.ValidationErrorMessage = ResHelper.GetString("general.saveerror");
        }
    }
Example #8
0
            private void FakeEMSLicense()
            {
                var licenseFakeProvider = Fake <LicenseKeyInfo, LicenseKeyInfoProvider>();
                var license             = new LicenseKeyInfo();

                license.SetValue("LicenseDomain", "testdomain");
                license.SetValue("LicenseExpiration", LicenseKeyInfo.TIME_UNLIMITED_LICENSE);
                license.SetValue("LicenseServers", 0);
                license.SetValue("LicenseEdition", 'X');
                license.SetValue("LicenseKey",
                                 @"DOMAIN:testdomain
PRODUCT:CX12
EXPIRATION:00000000
SERVERS:0
abcdefghijklmnopqrstuvwxyz==");
                licenseFakeProvider.WithData(license);
            }
    protected void Page_Load(object sender, EventArgs e)
    {
        string domain = QueryHelper.GetText("domainname", String.Empty);

        if (domain != String.Empty)
        {
            LicenseKeyInfo lki = LicenseKeyInfoProvider.GetLicenseKeyInfo(domain);
            if (lki != null)
            {
                string feature = QueryHelper.GetText("feature", String.Empty);

                if (feature != String.Empty)
                {
                    LabelMessage.Text = String.Format(GetString("general.specifiedFeatureNotAvailable"), feature);

                    // Log message to event log
                    EventLogProvider.LogEvent(
                        EventType.WARNING,
                        "Feature not available page",
                        "FeatureNotAvailable",
                        "Feature '" + feature + "' is not available in the CMS edition you are using: " + LicenseHelper.GetEditionName(lki.Edition),
                        RequestContext.CurrentURL
                        );
                }
                else
                {
                    LabelMessage.Text = GetString("general.FeatureNotAvailable");

                    // Log message to event log
                    EventLogProvider.LogEvent(
                        EventType.WARNING,
                        "Feature not available page",
                        "FeatureNotAvailable",
                        "The requested feature is not available in the CMS edition you are using: " + LicenseHelper.GetEditionName(lki.Edition),
                        RequestContext.CurrentURL
                        );
                }
            }
            else
            {
                LabelMessage.Text = GetString("general.licensenotfound").Replace("%%name%%", domain);
            }
        }
        titleElem.TitleText = GetString("general.AccessDenied");
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        string domain = QueryHelper.GetText("domainname", String.Empty);

        if (domain != String.Empty)
        {
            LicenseKeyInfo lki = LicenseKeyInfoProvider.GetLicenseKeyInfo(domain);
            if (lki != null)
            {
                LabelMessage.Text = GetString("CMSSiteManager.FeatureNotAvailable").Replace("%%name%%", LicenseHelper.GetEditionName(lki.Edition));
            }
            else
            {
                LabelMessage.Text = GetString("CMSSiteManager.LicenseNotFound").Replace("%%name%%", domain);
            }
        }
        this.titleElem.TitleText  = GetString("CMSSiteManager.AccesDenied");
        this.titleElem.TitleImage = GetImageUrl("Others/Messages/denied.png");
    }
    /// <summary>
    /// External data binding handler.
    /// </summary>
    private object Control_OnExternalDataBound(object sender, string sourcename, object parameter)
    {
        switch (sourcename.ToLowerCSafe())
        {
        case "editionname":
            string edition = ValidationHelper.GetString(parameter, "").ToUpperCSafe();
            try
            {
                return(LicenseHelper.GetEditionName(EnumStringRepresentationExtensions.ToEnum <ProductEditionEnum>(edition)));
            }
            catch
            {
                return("#UNKNOWN#");
            }

        case "expiration":
            var            row         = (DataRowView)parameter;
            LicenseKeyInfo licenseInfo = new LicenseKeyInfo();
            licenseInfo.LoadLicense(ValidationHelper.GetString(row["LicenseKey"], string.Empty), ValidationHelper.GetString(row["LicenseDomain"], string.Empty));
            if (licenseInfo.LicenseGuid == null)
            {
                return(ResHelper.GetString(Convert.ToString(row["LicenseExpiration"])));
            }
            else
            {
                // subtract grace period for subscription license
                return(licenseInfo.ExpirationDateReal.AddDays(-SUBSCRIPTION_LICENSE_EXPIRATION_GRACE_DAYS).ToString(LicenseKeyInfo.LICENSE_EXPIRATION_DATE_FORMAT, CultureInfo.InvariantCulture));
            }

        case "licenseservers":
            int count = ValidationHelper.GetInteger(parameter, -1);
            if (count == LicenseKeyInfo.SERVERS_UNLIMITED)
            {
                return(ResHelper.GetString("general.unlimited"));
            }
            if (count > 0)
            {
                return(count.ToString());
            }
            return(String.Empty);
        }
        return(parameter);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        string domain = QueryHelper.GetText("domainname", String.Empty);

        if (domain != String.Empty)
        {
            LicenseKeyInfo lki = LicenseKeyInfoProvider.GetLicenseKeyInfo(domain);
            if (lki != null)
            {
                string feature = QueryHelper.GetText("feature", String.Empty);

                var logService = Service.Resolve <IEventLogService>();

                if (feature != String.Empty)
                {
                    LabelMessage.Text = String.Format(GetString("general.specifiedFeatureNotAvailable"), feature);

                    // Log message to event log
                    logService.LogWarning(
                        "Feature not available page",
                        "FeatureNotAvailable",
                        String.Format(GetString("license.featurelog.detail"), feature, LicenseHelper.GetEditionName(lki.Edition))
                        );
                }
                else
                {
                    LabelMessage.Text = GetString("general.FeatureNotAvailable");

                    // Log message to event log
                    logService.LogWarning(
                        "Feature not available page",
                        "FeatureNotAvailable",
                        String.Format(GetString("license.featurelog"), LicenseHelper.GetEditionName(lki.Edition))
                        );
                }
            }
            else
            {
                LabelMessage.Text = GetString("general.licensenotfound").Replace("%%name%%", domain);
            }
        }
        titleElem.TitleText = GetString("general.AccessDenied");
    }
Example #13
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (LicenseHelper.ApplicationExpires != DateTime.MinValue)
        {
            trialHeight  = "17";
            trialExpires = "?appexpires=" + LicenseHelper.ApplicationExpires.Subtract(DateTime.Now).Days;
        }
        // Check the license key for trial version
        else if (DataHelper.GetNotEmpty(URLHelper.GetCurrentDomain(), string.Empty) != string.Empty)
        {
            LicenseKeyInfo lki = LicenseKeyInfoProvider.GetLicenseKeyInfo(URLHelper.GetCurrentDomain());
            if ((lki != null) && (lki.Key.Length == LicenseKeyInfo.TRIAL_KEY_LENGTH) && (lki.ExpirationDateReal != LicenseKeyInfo.TIME_UNLIMITED_LICENSE))
            {
                trialHeight  = "17";
                trialExpires = "?expirationdate=" + lki.ExpirationDateReal.Subtract(DateTime.Now).Days;
            }
            else
            {
                trialHeight  = "0";
                trialExpires = "";
            }

            if (lki != null)
            {
                // Check the number of users for free edition
                if (lki.Edition == ProductEditionEnum.Free)
                {
                    UserInfoProvider.LicenseController();
                }
            }
        }

        // Display the techPreview frame if there is a key in the web.config
        if (ValidationHelper.GetBoolean(SettingsHelper.AppSettings["CMSUseTechnicalPreview"], false))
        {
            techPreviewHeight  = "17";
            techPreviewPageURL = ResolveUrl("~/CMSSiteManager/techpreview.aspx");
        }

        trialPageURL  = ResolveUrl("~/CMSSiteManager/trialversion.aspx");
        headerPageURL = ResolveUrl("~/CMSDesk/Header.aspx");
    }
Example #14
0
        /// <summary>
        /// Gets days until the license for current domain expires.
        /// </summary>
        /// <returns>Days until the license for current domain expires</returns>
        private static int GetLicensesRemainingDays()
        {
            int remainingDays = 0;

            // Check current domain
            if (DataHelper.GetNotEmpty(RequestContext.CurrentDomain, string.Empty) != string.Empty)
            {
                // Get license key info for current domain
                LicenseKeyInfo lki = LicenseKeyInfoProvider.GetLicenseKeyInfo(RequestContext.CurrentDomain);
                if ((lki != null) && (lki.ExpirationDateReal != LicenseKeyInfo.TIME_UNLIMITED_LICENSE))
                {
                    // Substract days for correct days substraction - last day is not a valid day
                    TimeSpan expiration = lki.ExpirationDateReal.Subtract(DateTime.Now.AddDays(-1));
                    if (expiration.Days <= 60)
                    {
                        remainingDays = expiration.Days;
                    }
                }
            }
            return(remainingDays);
        }
    /// <summary>
    /// Try to set new license for actual domain.
    /// </summary>
    public void SetLicenseKey()
    {
        if (txtLicense.Text == "")
        {
            throw new InvalidOperationException(ResHelper.GetFileString("Install.LicenseEmpty"));
        }

        LicenseKeyInfo lki = new LicenseKeyInfo();

        lki.LoadLicense(txtLicense.Text, FullHostName);

        switch (lki.ValidationResult)
        {
        case LicenseValidationEnum.Expired:
            throw new InvalidOperationException(ResHelper.GetFileString("Install.LicenseNotValid.Expired"));

        case LicenseValidationEnum.Invalid:
            throw new InvalidOperationException(ResHelper.GetFileString("Install.LicenseNotValid.Invalid"));

        case LicenseValidationEnum.NotAvailable:
            throw new InvalidOperationException(ResHelper.GetFileString("Install.LicenseNotValid.NotAvailable"));

        case LicenseValidationEnum.WrongFormat:
            throw new InvalidOperationException(ResHelper.GetFileString("Install.LicenseNotValid.WrongFormat"));

        case LicenseValidationEnum.Valid:
            // Try to store license into database
            if ((FullHostName == "localhost") || (FullHostName == "127.0.0.1") || (lki.Domain == FullHostName))
            {
                LicenseKeyInfoProvider.SetLicenseKeyInfo(lki);
            }
            else
            {
                throw new InvalidOperationException(ResHelper.GetFileString("Install.LicenseForDifferentDomain"));
            }

            break;
        }
    }
    private void Control_OnAfterValidate(object sender, EventArgs e)
    {
        try
        {
            string         licenseKey = ValidationHelper.GetString(Control.GetFieldValue("LicenseKey"), String.Empty).Trim();
            LicenseKeyInfo lk         = new LicenseKeyInfo();
            lk.LoadLicense(licenseKey, "");

            switch (lk.ValidationResult)
            {
            case LicenseValidationEnum.Valid:
                return;

            case LicenseValidationEnum.Expired:
                Control.ValidationErrorMessage = ResHelper.GetString("Licenses_License_New.LicenseNotValid.Expired");
                break;

            case LicenseValidationEnum.Invalid:
                Control.ValidationErrorMessage = ResHelper.GetString("Licenses_License_New.LicenseNotValid.Invalid");
                break;

            case LicenseValidationEnum.NotAvailable:
                Control.ValidationErrorMessage = ResHelper.GetString("Licenses_License_New.LicenseNotValid.NotAvailable");
                break;

            case LicenseValidationEnum.WrongFormat:
                Control.ValidationErrorMessage = ResHelper.GetString("Licenses_License_New.LicenseNotValid.WrongFormat");
                break;
            }

            Control.StopProcessing             = true;
            Control.ShowValidationErrorMessage = true;
        }
        catch (Exception ex)
        {
            Service.Resolve <IEventLogService>().LogException("License", "NEW", ex);
            Control.ValidationErrorMessage = ResHelper.GetString("general.saveerror");
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        string domain = QueryHelper.GetText("domainname", String.Empty);

        if (domain != String.Empty)
        {
            LicenseKeyInfo lki = LicenseKeyInfoProvider.GetLicenseKeyInfo(domain);
            if (lki != null)
            {
                LabelMessage.Text = GetString("CMSSiteManager.FeatureNotAvailable");

                // Log message to event log
                EventLogProvider eventLog = new EventLogProvider();
                eventLog.LogEvent(EventLogProvider.EVENT_TYPE_WARNING, DateTime.Now, "Feature not available page", "FeatureNotAvailable", URLHelper.CurrentURL, "The requested feature is not available in the CMS edition you are using: " + LicenseHelper.GetEditionName(lki.Edition));
            }
            else
            {
                LabelMessage.Text = GetString("CMSSiteManager.LicenseNotFound").Replace("%%name%%", domain);
            }
        }
        titleElem.TitleText  = GetString("CMSSiteManager.AccesDenied");
        titleElem.TitleImage = GetImageUrl("Others/Messages/denied.png");
    }
Example #18
0
    /// <summary>
    /// Gets the limit of objects for given license and feature.
    /// </summary>
    /// <param name="license">License</param>
    /// <param name="feature">Feature</param>
    public static int GetLimit(LicenseKeyInfo license, FeatureEnum feature)
    {
        if (license == null)
        {
            return(0);
        }

        // If feature not available, no objects allowed
        if (!LicenseKeyInfoProvider.IsFeatureAvailable(license, feature))
        {
            return(0);
        }

        // Get version limit
        int limit = LicenseKeyInfoProvider.VersionLimitations(license, feature);

        if (limit == 0)
        {
            return(int.MaxValue);
        }

        return(limit);
    }
    /// <summary>
    /// Returns system information.
    /// </summary>
    private static string GetSystemInformation()
    {
        StringBuilder sb = new StringBuilder();

        sb.AppendFormat("CMS version: {0} Build: {1}",
                        CMSContext.SYSTEM_VERSION,
                        typeof(TreeProvider).Assembly.GetName().Version.ToString(3));
        sb.AppendLine();

        sb.AppendFormat("OS version: {0}", Environment.OSVersion);
        sb.AppendLine();

        LicenseKeyInfo licenseKey = null;

        if (CMSContext.CurrentSite != null)
        {
            licenseKey = LicenseKeyInfoProvider.GetLicenseKeyInfo(CMSContext.CurrentSite.DomainName);
        }

        if (licenseKey != null)
        {
            sb.AppendFormat("License info: {0}, {1}, {2}, {3}",
                            licenseKey.Domain,
                            licenseKey.Edition,
                            licenseKey.ExpirationDateReal.ToString(DateTimeHelper.DefaultIFormatProvider),
                            licenseKey.Version);

            string packages = ValidationHelper.GetString(licenseKey.GetValue("LicensePackages"), string.Empty);
            if (!string.IsNullOrEmpty(packages))
            {
                sb.AppendFormat(", {0}", packages);
            }
        }

        return(sb.ToString());
    }
Example #20
0
    private void InitializeControls()
    {
        string version = CMSContext.SYSTEM_VERSION.Replace(".", "_");

        this.ltlTitle.Text     = GetString("splashscreen.title");
        this.imgTitle.ImageUrl = GetImageUrl("Others/SplashScreen/title.png");

        this.chkDontShowAgain.Text = GetString("splashscreen.donotshowagain");
        this.btnContinue.Text      = GetString("general.continue") + " >";
        this.lnkKenticoCom.Text    = "<a href=\"http://www.kentico.com\" target=\"_blank\">www.kentico.com</a>";

        // Licensing section initialization
        this.imgLicensing.ImageUrl = GetImageUrl("Others/SplashScreen/licensing.png");

        string linkBuy          = "<a href=\"http://www.kentico.com/Purchase\" target=\"_blank\">www.kentico.com/Purchase</a>";
        string linkEnterLicense = "<a href=\"" + ResolveUrl("~/CMSModules/Licenses/Pages/License_New.aspx") + "\" target=\"_blank\">" + GetString("splashscreen.here") + "</a>";

        // If license for the current domain exist and is valid
        LicenseKeyInfo lki = LicenseKeyInfoProvider.GetLicenseKeyInfo(URLHelper.GetCurrentDomain());

        if (lki != null)
        {
            TimeSpan dt = lki.ExpirationDate - CMSContext.CurrentUser.DateTimeNow;

            if (dt.Days > 0)
            {
                this.ltlLicensingLn1.Text = string.Format(GetString("splashscreen.licensing.text.trial"), dt.Days.ToString());
            }
            else
            {
                this.ltlLicensingLn1.Text = GetString("splashscreen.licensing.text.trialexpired");
            }
            this.ltlLicensingLn2.Text = string.Format(GetString("splashscreen.licensing.textLn2"), linkBuy);
            this.ltlLicensingLn3.Text = string.Format(GetString("splashscreen.licensing.textLn3"), linkEnterLicense);
        }

        // Support and help initialization
        string documentation = "<a href=\"http://devnet.kentico.com/Documentation/" + version + ".aspx\" target=\"_blank\">http://devnet.kentico.com/Documentation/" + version + ".aspx</a>";

        this.imgDocumentation.ImageUrl = GetImageUrl("Others/SplashScreen/documentation.png");
        this.ltlDocumentation.Text     = string.Format(GetString("splashscreen.documentation.text"), documentation);

        this.imgOnlineHelp.ImageUrl = GetImageUrl("Others/SplashScreen/help.png");
        this.ltlOnlineHelp.Text     = GetString("splashscreen.onlinehelp.text");

        this.imgSupport.ImageUrl = GetImageUrl("Others/SplashScreen/support.png");
        this.ltlSupport.Text     = string.Format(GetString("splashscreen.support.text"), "<a href=\"http://www.kentico.com/Support\" target=\"_blank\">www.kentico.com/Support</a>");

        this.imgDevNet.ImageUrl = GetImageUrl("Others/SplashScreen/devnet.png");
        this.ltlDevNet.Text     = string.Format(GetString("splashscreen.devnet.text"), "<a href=\"http://devnet.kentico.com\" target=\"_blank\">devnet.kentico.com</a>");

        if (CurrentUser.IsGlobalAdministrator)
        {
            try
            {
                if (CMS.IO.File.Exists(Server.MapPath("~/CMSAPIExamples/Default.aspx")))
                {
                    this.plcApiExample.Visible   = true;
                    this.imgApiExamples.ImageUrl = GetImageUrl("General/Code.png");
                    this.ltlApiExamples.Text     = string.Format(GetString("splashscreen.apiexamples.text"), ResolveUrl("~/CMSAPIExamples/Default.aspx"));
                }
            }
            catch { }
        }

        // Gettingstarted initialization
        string quickstartguide = "<a href=\"http://devnet.kentico.com/docs/" + version + "/kenticocms_quickguide.pdf\" target=\"_blank\">" + GetString("splashscreen.gettingstarted.quickstartguide") + "</a>";
        string tutorial        = "<a href=\"http://devnet.kentico.com/docs/" + version + "/KenticoCMS_Tutorial.pdf\" target=\"_blank\">" + GetString("splashscreen.gettingstarted.tutorial") + "</a>";
        string tutorialASPX    = string.Format(GetString("splashscreen.gettingstarted.tutorialaspx"), "<a href=\"http://devnet.kentico.com/docs/" + version + "/KenticoCMS_Tutorial_aspx.pdf\" target=\"_blank\">" + GetString("splashscreen.here") + "</a>");

        this.imgGettingStartedQuick.ImageUrl = GetImageUrl("Others/SplashScreen/quickstart.png");
        this.ltlGettingStartedQuick.Text     = quickstartguide;

        this.imgGettingStartedTutorial.ImageUrl = GetImageUrl("Others/SplashScreen/stepbystep.png");
        this.ltlGettingStartedTutorial.Text     = tutorial + " " + tutorialASPX;
    }
Example #21
0
    /// <summary>
    /// Creates requested license keys. Returns false if something fail.
    /// </summary>
    /// <param name="connectionString">Connection string</param>
    public bool ProcessRegistration(string connectionString)
    {
        string result = "";
        string lickey = "";

        // Delete all existing license keys
        DataSet ds = LicenseKeyInfoProvider.GetAllLicenseKeys();

        if (!DataHelper.DataSourceIsEmpty(ds))
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                LicenseKeyInfo lki = new LicenseKeyInfo(dr);
                if (lki != null)
                {
                    LicenseKeyInfoProvider.DeleteLicenseKeyInfo(lki.LicenseKeyID);
                }
            }
        }

        // Create license keys for localhost and 127.0.0.1
        LicenseKeyInfo flki = new LicenseKeyInfo();

        flki.LoadLicense(@"DOMAIN:localhost
PRODUCT:CF07
EXPIRATION:00000000
PACKAGES:
SERVERS:1
p8NrcXDSRiiEdH6Paef6MFISFY4Mihhwz9E+75fDKp1srPgxhTxEoLt0P2XXMkmCRSwhQk85/zjp017iCUIpwHhfgNQv/83ILVx3bIAEIZReY2Grs4Lah5jHSLlq3RUCX6d5ZL2Q2lxhKckPxMWjVhBlvDKLMttek+56QZmMp8oQlEMlqGYCIV+HMgD66Ob5ukdKYKvCw0Zcd2nhi+7W2KqJcWCRtRVxIY/Xi69ZgpT/Mae/8cxEfxZ+xzfw0Tn81Qf5vxVUkfG5UwVdmBQ1NFMqA6OTvx60kkRjGkUFNbsJVogsJ+WdMXr/MNhHx+qFAuMLdCOL13h4WMr/y8M+yA==", "localhost");
        LicenseKeyInfoProvider.SetLicenseKeyInfo(flki);
        flki = new LicenseKeyInfo();
        flki.LoadLicense(@"DOMAIN:127.0.0.1
PRODUCT:CF07
EXPIRATION:00000000
PACKAGES:
SERVERS:1
4499yoWyus2S1g0D45bHh+OoGIS3pTC9UXm1L0Q/ElZj/II0BiebhvgWI0bLj+HMlPMl5xLRM3OJOId2IlAX/4yO4rH7YWa3ftzMX7g/sKrmmCmYXWeNDEKD0jeCKr30qaGFc6+xkI2YwULt+5lyyEVcVMGKeZd2QgIbb6i9nRfuUaww4f3JlS8FHxmUJGR1HjJ+FVZlCQFRDsb59tw2OAWSF5FKrBK3BFkIoCjEtuvoOyfvx3nUEC4OnnsqtguhjFygG7RBgRBjEyL0BXhNkhBFxZg/AZsdUDxBwwkPhrXDjJ6Dsl+DQF83qTZ+vvphOpajQ0UgB7Raep1Xul4Gqw==", "127.0.0.1");
        LicenseKeyInfoProvider.SetLicenseKeyInfo(flki);

        // Create free license keys for user defined domain
        string domainName = URLHelper.CorrectDomainName(txtUserDomain.Text.Trim());
        string firstName  = txtUserFirstName.Text.Trim();
        string lastName   = txtUserLastName.Text.Trim();
        string email      = txtUserEmail.Text.Trim();

        bool userForm = !String.IsNullOrEmpty(firstName) || !String.IsNullOrEmpty(lastName) ||
                        !String.IsNullOrEmpty(email) || !String.IsNullOrEmpty(txtPassword.Text);

        // Ignore localhost/127.0.0.1 licenses
        if ((String.Compare(domainName, "localhost", true) == 0) || (String.Compare(domainName, "127.0.0.1") == 0))
        {
            domainName = "";
        }

        // Do not modify anything if form is blank
        if (!String.IsNullOrEmpty(domainName) || userForm)
        {
            if (userForm)
            {
                result = new Validator().NotEmpty(firstName, ResHelper.GetString(strPrefix + "firstnamerequired"))
                         .NotEmpty(lastName, ResHelper.GetString(strPrefix + "lastnamerequired"))
                         .NotEmpty(email, ResHelper.GetString(strPrefix + "emailrequired"))
                         .IsEmail(email, ResHelper.GetString(strPrefix + "emailinvalidformat"))
                         .Result;

                if (String.IsNullOrEmpty(result) && plcPass.Visible && String.IsNullOrEmpty(txtPassword.Text))
                {
                    result = ResHelper.GetString(strPrefix + "passwordrequired");
                }
            }

            if (String.IsNullOrEmpty(result))
            {
                if (userForm)
                {
                    LS.CMSLicenseService ls = new LS.CMSLicenseService();

                    if (ls.UserExists(email))
                    {
                        // If user with specified name (e-mail) already exist ask for her password
                        if (!plcPass.Visible)
                        {
                            plcPass.Visible = true;
                            result          = ResHelper.GetString(strPrefix + "passwordrequired");
                        }
                        else
                        {
                            lickey = ls.GetFreeEditionKeyGeneral(domainName, firstName, lastName, email, txtPassword.Text, 7);
                        }
                    }
                    else
                    {
                        // Register new user and get license key
                        lickey = ls.GetFreeEditionKeyGeneral(domainName, firstName, lastName, email, UserInfoProvider.GenerateNewPassword(), 7);
                    }
                }

                if (String.IsNullOrEmpty(result) && !lickey.StartsWith("DOMAIN"))
                {
                    result = lickey;
                }
            }

            if (String.IsNullOrEmpty(result))
            {
                if (!String.IsNullOrEmpty(lickey))
                {
                    LicenseKeyInfo lki = new LicenseKeyInfo();
                    lki.LoadLicense(lickey, "");
                    LicenseKeyInfoProvider.SetLicenseKeyInfo(lki);
                }
            }
        }

        if (!String.IsNullOrEmpty(result))
        {
            lblError.Visible = true;
            lblError.Text    = result;
        }

        return(String.IsNullOrEmpty(result));
    }
Example #22
0
    private void CheckTrial()
    {
        // Hide message if requested by user
        if (!CheckWarningMessage(SESSION_KEY_TRIAL))
        {
            pnlTrial.Visible = false;
            return;
        }

        string info = null;

        if (LicenseHelper.ApplicationExpires != DateTime.MinValue)
        {
            TimeSpan appExpiration = LicenseHelper.ApplicationExpires.Subtract(DateTime.Now);

            // Application expires
            if (CMSVersion.IsBetaVersion())
            {
                if (appExpiration.Ticks <= 0)
                {
                    info = GetString("Beta.AppExpired");
                }
                else
                {
                    info = string.Format(GetString("Beta.AppExpiresIn"), GetExpirationString(appExpiration.Days));
                }
            }
            else
            {
                if (appExpiration.Ticks <= 0)
                {
                    info = string.Format(GetString("Preview.AppExpired"), CMSVersion.VersionSuffix);
                }
                else
                {
                    info = string.Format(GetString("Preview.AppExpiresIn"), CMSVersion.VersionSuffix, GetExpirationString(appExpiration.Days));
                }
            }
        }
        // Check the license key for trial or free version
        else if (DataHelper.GetNotEmpty(RequestContext.CurrentDomain, string.Empty) != string.Empty)
        {
            LicenseKeyInfo lki = LicenseKeyInfoProvider.GetLicenseKeyInfo(RequestContext.CurrentDomain);
            if ((lki != null) && (lki.Key.Length == LicenseKeyInfo.TRIAL_KEY_LENGTH) && (lki.ExpirationDateReal != LicenseKeyInfo.TIME_UNLIMITED_LICENSE))
            {
                TimeSpan expiration = lki.ExpirationDateReal.Subtract(DateTime.Now.AddDays(-1));
                // Trial version expiration date
                if (expiration.Ticks <= 0)
                {
                    info = GetString("Trial.Expired");
                }
                else
                {
                    info = string.Format(GetString("Trial.ExpiresIn"), GetExpirationString(expiration.Days));
                }
            }
            else if ((lki != null) && (lki.Edition == ProductEditionEnum.Free))
            {
                info = GetString("header.freeedition");
            }
        }

        ltlText.Text     = info;
        pnlTrial.Visible = !string.IsNullOrEmpty(ltlText.Text);
    }
Example #23
0
    void Login1_LoggedIn(object sender, EventArgs e)
    {
        // Ensure response cookie
        CookieHelper.EnsureResponseCookie(FormsAuthentication.FormsCookieName);

        // Set cookie expiration
        if (Login1.RememberMeSet)
        {
            CookieHelper.ChangeCookieExpiration(FormsAuthentication.FormsCookieName, DateTime.Now.AddYears(1), false);
        }
        else
        {
            // Extend the expiration of the authentication cookie if required
            if (!UserInfoProvider.UseSessionCookies && (HttpContext.Current != null) && (HttpContext.Current.Session != null))
            {
                CookieHelper.ChangeCookieExpiration(FormsAuthentication.FormsCookieName, DateTime.Now.AddMinutes(Session.Timeout), false);
            }
        }

        // Current username
        string userName = Login1.UserName;

        // Get info on the authenticated user
        UserInfo ui = UserInfoProvider.GetUserInfo(userName);

        // Check whether safe user name is required and if so get safe username
        if (RequestHelper.IsMixedAuthentication() && UserInfoProvider.UseSafeUserName && (ui == null))
        {
            userName = ValidationHelper.GetSafeUserName(this.Login1.UserName, CMSContext.CurrentSiteName);
            CMSContext.AuthenticateUser(userName, this.Login1.RememberMeSet);
        }

        // Set culture
        DropDownList drpCulture = (DropDownList)Login1.FindControl("drpCulture");

        if (drpCulture != null)
        {
            string selectedCulture = drpCulture.SelectedValue;

            // Not the default culture
            if (selectedCulture != "")
            {
                // Update the user
                ui.PreferredUICultureCode = selectedCulture;
                UserInfoProvider.SetUserInfo(ui);

                // Update current user
                CMSContext.CurrentUser.PreferredUICultureCode = selectedCulture;
            }
        }

        // Splash screen handling
        bool           splashScreenEnabled = false;
        LicenseKeyInfo lki = LicenseKeyInfoProvider.GetLicenseKeyInfo(URLHelper.GetCurrentDomain());

        if ((lki != null) && lki.IsTrial && ui.UserSettings.UserShowSplashScreen)
        {
            if (lki.ExpirationDate != DateTimeHelper.ZERO_TIME)
            {
                // Display splash screen only if using trial license
                splashScreenEnabled = true;
            }
        }

        // Splash screen
        string returnUrl = ReturnUrl;

        // Return url is not specified or is relative path or hash is valid
        if (string.IsNullOrEmpty(returnUrl) || returnUrl.StartsWith("~") || returnUrl.StartsWith("/") || QueryHelper.ValidateHash("hash"))
        {
            if (splashScreenEnabled && ui.UserSettings.UserShowSplashScreen && SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSShowSplashScreen"))
            {
                if ((!String.IsNullOrEmpty(CMSContext.CurrentSiteName)) && (returnUrl.Contains("cmsdesk") || IsSiteManager))
                {
                    URLHelper.Redirect(ResolveUrl("~/CMSSiteManager/SplashScreen.aspx?continueurl=" + returnUrl));
                }
            }

            // Destination page URL
            if (returnUrl.Contains("restorepost"))
            {
                // Delete the saved state
                SavedFormState state = FormStateHelper.GetSavedState();
                if (state != null)
                {
                    state.Delete();
                }

                returnUrl = URLHelper.RemoveParameterFromUrl(returnUrl, "restorepost");
                URLHelper.Redirect(ResolveUrl(returnUrl));
            }
        }
        else
        {
            URLHelper.Redirect(ResolveUrl("~/CMSMessages/Error.aspx?title=" + ResHelper.GetString("general.badhashtitle") + "&text=" + ResHelper.GetString("general.badhashtext")));
        }
    }
 internal LicenseInternal()
 {
     I             = default(LicenseKeyInfo);
     I.CheckResult = -1;
 }
    protected void btnHiddenNext_onClick(object sender, EventArgs e)
    {
        StepOperation = 1;
        StepIndex++;

        switch (wzdInstaller.ActiveStepIndex)
        {
        case 0:
            // Set the authentication type
            AuthenticationType = userServer.WindowsAuthenticationChecked ? SQLServerAuthenticationModeEnum.WindowsAuthentication : SQLServerAuthenticationModeEnum.SQLServerAuthentication;

            // Check the server name
            if (String.IsNullOrEmpty(userServer.ServerName))
            {
                HandleError(ResHelper.GetFileString("Install.ErrorServerEmpty"));
                return;
            }

            // Do not allow to use empty user name or password
            bool isSQLAuthentication = AuthenticationType == SQLServerAuthenticationModeEnum.SQLServerAuthentication;
            if (isSQLAuthentication && (String.IsNullOrEmpty(userServer.DBUsername) || String.IsNullOrEmpty(userServer.DBPassword)))
            {
                HandleError(ResHelper.GetFileString("Install.ErrorUserNamePasswordEmpty"));
                return;
            }

            Password = userServer.DBPassword;

            // Check if it is possible to connect to the database
            string res = ConnectionHelper.TestConnection(AuthenticationType, userServer.ServerName, String.Empty, userServer.DBUsername, Password);
            if (!String.IsNullOrEmpty(res))
            {
                HandleError(res, "Install.ErrorSqlTroubleshoot", HELP_TOPIC_SQL_ERROR_LINK);
                return;
            }

            // Set credentials for the next step
            databaseDialog.AuthenticationType = AuthenticationType;
            databaseDialog.Password           = Password;
            databaseDialog.Username           = userServer.DBUsername;
            databaseDialog.ServerName         = userServer.ServerName;

            // Move to the next step
            wzdInstaller.ActiveStepIndex = 1;
            break;

        case 1:
        case COLLATION_DIALOG_INDEX:
            // Get database name
            Database = TextHelper.LimitLength(databaseDialog.CreateNewChecked ? databaseDialog.NewDatabaseName : databaseDialog.ExistingDatabaseName, 100);

            if (String.IsNullOrEmpty(Database))
            {
                HandleError(ResHelper.GetFileString("Install.ErrorDBNameEmpty"));
                return;
            }

            // Set up the connection string
            if (ConnectionHelper.IsConnectionStringInitialized)
            {
                ConnectionString = ConnectionHelper.ConnectionString;
            }
            else
            {
                ConnectionString = ConnectionHelper.BuildConnectionString(AuthenticationType, userServer.ServerName, Database, userServer.DBUsername, Password, SqlInstallationHelper.DB_CONNECTION_TIMEOUT);
            }

            // Check if existing DB has the same version as currently installed CMS
            if (databaseDialog.UseExistingChecked && !databaseDialog.CreateDatabaseObjects)
            {
                string dbVersion = null;
                try
                {
                    dbVersion = SqlInstallationHelper.GetDatabaseVersion(ConnectionString);
                }
                catch
                {
                }

                if (String.IsNullOrEmpty(dbVersion))
                {
                    // Unable to get DB version => DB objects missing
                    HandleError(ResHelper.GetFileString("Install.DBObjectsMissing"));
                    return;
                }

                if (dbVersion != CMSVersion.MainVersion)
                {
                    // Get wrong version number
                    HandleError(ResHelper.GetFileString("Install.WrongDBVersion"));
                    return;
                }
            }

            Info.LogContext = ctlAsyncDB.LogContext;

            // Use existing database
            if (databaseDialog.UseExistingChecked)
            {
                // Check if DB exists
                if (!DatabaseHelper.DatabaseExists(ConnectionString))
                {
                    HandleError(String.Format(ResHelper.GetFileString("Install.ErrorDatabseDoesntExist"), Database));
                    return;
                }

                // Get collation of existing DB
                string collation = DatabaseHelper.GetDatabaseCollation(ConnectionString);
                DatabaseHelper.DatabaseCollation = collation;

                if (wzdInstaller.ActiveStepIndex != COLLATION_DIALOG_INDEX)
                {
                    // Check target database collation and inform the user if it is not fully supported
                    if (!DatabaseHelper.IsSupportedDatabaseCollation(collation))
                    {
                        ucCollationDialog.IsSqlAzure = AzureHelper.IsSQLAzureServer(userServer.ServerName);
                        ucCollationDialog.Collation  = collation;
                        ucCollationDialog.InitControls();

                        // Move to "collation dialog" step
                        wzdInstaller.ActiveStepIndex = COLLATION_DIALOG_INDEX;
                        return;
                    }
                }
                else
                {
                    // Change database collation for regular database
                    if (ucCollationDialog.ChangeCollationRequested)
                    {
                        DatabaseHelper.ChangeDatabaseCollation(ConnectionString, Database, DatabaseHelper.DEFAULT_DB_COLLATION);
                    }
                }
            }
            else
            {
                // Create a new database
                if (!CreateDatabase(null))
                {
                    HandleError(String.Format(ResHelper.GetFileString("Install.ErrorCreateDB"), databaseDialog.NewDatabaseName));
                    return;
                }

                databaseDialog.ExistingDatabaseName = databaseDialog.NewDatabaseName;
                databaseDialog.CreateNewChecked     = false;
                databaseDialog.UseExistingChecked   = true;
            }

            if ((!SystemContext.IsRunningOnAzure && writePermissions) || ConnectionHelper.IsConnectionStringInitialized)
            {
                if (databaseDialog.CreateDatabaseObjects)
                {
                    if (DBInstalled && DBCreated)
                    {
                        ctlAsyncDB.RaiseFinished(this, EventArgs.Empty);
                    }
                    else
                    {
                        // Run SQL installation
                        RunSQLInstallation();
                    }
                }
                else
                {
                    CreateDBObjects = false;

                    // Set connection string
                    if (SettingsHelper.SetConnectionString(ConnectionHelper.ConnectionStringName, ConnectionString))
                    {
                        // Set the application connection string
                        SetAppConnectionString();

                        // Check if license key for current domain is present
                        LicenseKeyInfo lki = LicenseKeyInfoProvider.GetLicenseKeyInfo(hostName);
                        wzdInstaller.ActiveStepIndex = (lki == null) ? 4 : 5;
                        ucLicenseDialog.SetLicenseExpired();
                    }
                    else
                    {
                        ManualConnectionStringInsertion();
                    }
                }
            }
            else
            {
                ManualConnectionStringInsertion();
            }

            break;

        // After connection string save error
        case 2:
            // Check whether connection string is defined
            if (String.IsNullOrWhiteSpace(Service.Resolve <IConnectionStringService>()[ConnectionHelper.ConnectionStringName]))
            {
                HandleError(ResHelper.GetFileString("Install.ErrorAddConnString"));
                return;
            }

            ConnectionString = Service.Resolve <IConnectionStringService>()[ConnectionHelper.ConnectionStringName];

            if (CreateDBObjects)
            {
                if (DBInstalled)
                {
                    FinalizeDBInstallation();
                }
                else
                {
                    // Run SQL installation
                    RunSQLInstallation();
                }
            }
            else
            {
                // If this is installation to existing DB and objects are not created
                if ((hostName != "localhost") && (hostName != "127.0.0.1"))
                {
                    wzdInstaller.ActiveStepIndex = 4;
                }
                else
                {
                    wzdInstaller.ActiveStepIndex = 5;
                }
            }
            break;

        // After DB install
        case 3:
            break;

        // After license entering
        case 4:
            try
            {
                if (ucLicenseDialog.Visible)
                {
                    ucLicenseDialog.SetLicenseKey();
                    wzdInstaller.ActiveStepIndex = 5;
                }
                else if (ucWagDialog.ProcessRegistration(ConnectionString))
                {
                    wzdInstaller.ActiveStepIndex = 5;
                }
            }
            catch (Exception ex)
            {
                HandleError(ex.Message);
            }
            break;

        default:
            wzdInstaller.ActiveStepIndex++;
            break;
        }
    }
    protected void btnOK_Click(object sender, EventArgs e)
    {
        lblError.Text = "";

        try
        {
            LicenseKeyInfo lk = new LicenseKeyInfo();
            lk.LoadLicense(tbLicenseKey.Text.Trim(), "");

            if (lk != null)
            {
                switch (lk.ValidationResult)
                {
                    case LicenseValidationEnum.Expired:
                        lblError.Text = GetString("Licenses_License_New.LicenseNotValid.Expired");
                        break;

                    case LicenseValidationEnum.Invalid:
                        lblError.Text = GetString("Licenses_License_New.LicenseNotValid.Invalid");
                        break;

                    case LicenseValidationEnum.NotAvailable:
                        lblError.Text = GetString("Licenses_License_New.LicenseNotValid.NotAvailable");
                        break;

                    case LicenseValidationEnum.WrongFormat:
                        lblError.Text = GetString("Licenses_License_New.LicenseNotValid.WrongFormat");
                        break;

                    case LicenseValidationEnum.Valid:
                        if (LicenseKeyInfoProvider.IsLicenseExistForDomain(lk))
                        {
                            // License for domain already exist
                            lblInfo.Visible = false;
                            lblError.Visible = true;
                            lblError.Text = GetString("Licenses_License_New.DomainAlreadyExists").Replace("%%name%%", lk.Domain);
                        }
                        else
                        {
                            // Insert license
                            LicenseKeyInfoProvider.SetLicenseKeyInfo(lk);
                            CMS.SiteProvider.UserInfoProvider.ClearLicenseValues();
                            Functions.ClearHashtables();
                            URLHelper.Redirect("License_List.aspx");
                        }
                        break;
                }
            }

            if (lblError.Text != "")
            {
                lblInfo.Visible = false;
                lblError.Visible = true;
            }
        }
        catch (Exception ex)
        {
            lblInfo.Visible = false;
            lblError.Visible = true;
            lblError.Text = ex.Message;
        }
    }
Example #27
0
    /// <summary>
    /// Gets the limit of objects for given license and feature.
    /// </summary>
    /// <param name="license">License</param>
    /// <param name="feature">Feature</param>
    public static int GetLimit(LicenseKeyInfo license, FeatureEnum feature)
    {
        if (license == null)
        {
            return 0;
        }

        // If feature not available, no objects allowed
        if (!LicenseKeyInfoProvider.IsFeatureAvailable(license, feature))
        {
            return 0;
        }

        // Get version limit
        int limit = LicenseKeyInfoProvider.VersionLimitations(license, feature);
        if (limit == 0)
        {
            return int.MaxValue;
        }

        return limit;
    }
Example #28
0
    /// <summary>
    /// Checks the license for selected objects.
    /// </summary>
    public static string CheckLicenses(SiteImportSettings settings)
    {
        string result = null;

        object[,] checkFeatures = new object[,] {
            { FeatureEnum.Unknown, "", false },
            { FeatureEnum.BizForms, FormObjectType.BIZFORM, true },
            { FeatureEnum.Forums, PredefinedObjectType.FORUM, true },
            { FeatureEnum.Newsletters, PredefinedObjectType.NEWSLETTER, true },
            { FeatureEnum.Subscribers, PredefinedObjectType.NEWSLETTERUSERSUBSCRIBER + ";" + PredefinedObjectType.NEWSLETTERROLESUBSCRIBER + ";" + PredefinedObjectType.NEWSLETTERSUBSCRIBER, true },
            { FeatureEnum.Staging, SynchronizationObjectType.STAGINGSERVER, true },
            { FeatureEnum.Ecommerce, PredefinedObjectType.SKU, false },
            { FeatureEnum.Polls, PredefinedObjectType.POLL, false },
            { FeatureEnum.Webfarm, WebFarmObjectType.WEBFARMSERVER, false },
            { FeatureEnum.SiteMembers, SiteObjectType.USER, false },
            { FeatureEnum.WorkflowVersioning, PredefinedObjectType.WORKFLOW, false }
            };

        // Get imported licenses
        DataSet ds = ImportProvider.LoadObjects(settings, LicenseObjectType.LICENSEKEY, false);

        string domain = string.IsNullOrEmpty(settings.SiteDomain) ? URLHelper.GetCurrentDomain().ToLower() : URLHelper.RemovePort(settings.SiteDomain).ToLower();

        // Remove application path
        int slashIndex = domain.IndexOf("/");
        if (slashIndex > -1)
        {
            domain = domain.Substring(0, slashIndex);
        }

        bool anyDomain = ((domain == "localhost") || (domain == "127.0.0.1"));

        // Check all features
        for (int i = 0; i <= checkFeatures.GetUpperBound(0); i++)
        {
            string[] objectTypes = ((string)checkFeatures[i, 1]).Split(';');
            bool siteObject = (bool)checkFeatures[i, 2];
            string objectType = objectTypes[0];

            // Check objects
            int count = (objectType != "") ? 0 : 1;
            for (int j = 0; j < objectTypes.Length; ++j)
            {
                objectType = objectTypes[j];
                if (objectType != "")
                {
                    ArrayList codenames = settings.GetSelectedObjects(objectType, siteObject);
                    count += (codenames == null) ? 0 : codenames.Count;
                }
            }

            // Check a special case for Workflows
            if (objectType.Equals(PredefinedObjectType.WORKFLOW))
            {
                // Check workflows
                bool includeWorkflowScopes = ValidationHelper.GetBoolean(settings.GetSettings(ImportExportHelper.SETTINGS_WORKFLOW_SCOPES), false);
                if (includeWorkflowScopes)
                {
                    // Check if there are any workflow scopes in the imported package and if there are, increase the count.
                    DataSet dsScopes = ImportProvider.LoadObjects(settings, PredefinedObjectType.WORKFLOWSCOPE, true);
                    if (!DataHelper.DataSourceIsEmpty(dsScopes))
                    {
                        count++;
                    }
                }
            }

            if (count > 0)
            {
                FeatureEnum feature = (FeatureEnum)checkFeatures[i, 0];

                // Get best available license from DB
                LicenseKeyInfo bestLicense = LicenseKeyInfoProvider.GetLicenseKeyInfo(domain, feature);
                if ((bestLicense != null) && (bestLicense.ValidationResult != LicenseValidationEnum.Valid))
                {
                    bestLicense = null;
                }

                // Check new licenses
                LicenseKeyInfo bestSelected = null;
                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        LicenseKeyInfo lki = new LicenseKeyInfo(dr);
                        // Use license only if selected
                        if ((settings.IsSelected(LicenseObjectType.LICENSEKEY, lki.Domain, false)) && (anyDomain || (lki.Domain.ToLower() == domain)) && LicenseKeyInfoProvider.IsBetterLicense(lki, bestSelected, feature))
                        {
                            bestSelected = lki;
                            if (bestSelected.Domain.ToLower() == domain)
                            {
                                break;
                            }
                        }
                    }
                }

                // Check the license
                if (feature == FeatureEnum.Unknown)
                {
                    if ((bestLicense == null) && (bestSelected == null))
                    {
                        return ResHelper.GetString("Import.NoLicense");
                    }
                }
                else
                {
                    // Check the limit
                    int limit = GetLimit(bestLicense, feature);

                    // Use a database license if it is better than the one which is being imported
                    if (LicenseKeyInfoProvider.IsBetterLicense(bestLicense, bestSelected, feature))
                    {
                        bestSelected = bestLicense;
                    }

                    int selectedLimit = GetLimit(bestSelected, feature);
                    if (bestSelected != null)
                    {
                        if (bestSelected.ValidationResult == LicenseValidationEnum.Valid)
                        {
                            if (!anyDomain || (bestSelected.Domain.ToLower() == domain))
                            {
                                limit = selectedLimit;
                            }
                            else
                            {
                                // If selected better, take the selected
                                if (selectedLimit > limit)
                                {
                                    limit = selectedLimit;
                                }
                            }
                        }
                        else
                        {
                            if (!anyDomain || (bestSelected.Domain.ToLower() == domain))
                            {
                                limit = 0;
                            }
                        }
                    }
                    if (limit < count)
                    {
                        if (limit <= 0)
                        {
                            result += String.Format(ResHelper.GetString("Import.LimitZero"), ResHelper.GetString("ObjectTasks." + objectType.Replace(".", "_")));
                        }
                        else
                        {
                            result += String.Format(ResHelper.GetString("Import.LimitExceeded"), ResHelper.GetString("ObjectTasks." + objectType.Replace(".", "_")), limit);
                        }

                        // If better license
                        if ((bestLicense != null) && (bestSelected != null) && LicenseKeyInfoProvider.IsBetterLicense(bestLicense, bestSelected, feature))
                        {
                            result += " " + ResHelper.GetString("Import.BetterLicenseExists");
                        }

                        result += "<br />";
                    }
                }
            }
        }

        return result;
    }
Example #29
0
    protected void btnOK_Click(object sender, EventArgs e)
    {
        lblError.Text = "";

        try
        {
            LicenseKeyInfo lk = new LicenseKeyInfo();
            lk.LoadLicense(tbLicenseKey.Text.Trim(), "");

            if (lk != null)
            {
                switch (lk.ValidationResult)
                {
                case LicenseValidationEnum.Expired:
                    lblError.Text = GetString("Licenses_License_New.LicenseNotValid.Expired");
                    break;

                case LicenseValidationEnum.Invalid:
                    lblError.Text = GetString("Licenses_License_New.LicenseNotValid.Invalid");
                    break;

                case LicenseValidationEnum.NotAvailable:
                    lblError.Text = GetString("Licenses_License_New.LicenseNotValid.NotAvailable");
                    break;

                case LicenseValidationEnum.WrongFormat:
                    lblError.Text = GetString("Licenses_License_New.LicenseNotValid.WrongFormat");
                    break;

                case LicenseValidationEnum.Valid:
                    if (LicenseKeyInfoProvider.IsLicenseExistForDomain(lk))
                    {
                        // License for domain already exist
                        lblInfo.Visible  = false;
                        lblError.Visible = true;
                        lblError.Text    = GetString("Licenses_License_New.DomainAlreadyExists").Replace("%%name%%", lk.Domain);
                    }
                    else
                    {
                        // Insert license
                        LicenseKeyInfoProvider.SetLicenseKeyInfo(lk);
                        CMS.SiteProvider.UserInfoProvider.ClearLicenseValues();
                        Functions.ClearHashtables();
                        URLHelper.Redirect("License_List.aspx");
                    }
                    break;
                }
            }

            if (lblError.Text != "")
            {
                lblInfo.Visible  = false;
                lblError.Visible = true;
            }
        }
        catch (Exception ex)
        {
            lblInfo.Visible  = false;
            lblError.Visible = true;
            lblError.Text    = ex.Message;
        }
    }
Example #30
0
    /// <summary>
    /// Creates requested license keys. Returns false if something fail.
    /// </summary>
    /// <param name="connectionString">Connection string</param>
    public bool ProcessRegistration(string connectionString)
    {
        string result = "";
        string lickey = "";

        // Delete all existing license keys
        DataSet ds = LicenseKeyInfoProvider.GetAllLicenseKeys();
        if (!DataHelper.DataSourceIsEmpty(ds))
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                LicenseKeyInfo lki = new LicenseKeyInfo(dr);
                if (lki != null)
                {
                    LicenseKeyInfoProvider.DeleteLicenseKeyInfo(lki.LicenseKeyID);
                }
            }
        }

        // Create license keys for localhost and 127.0.0.1
        LicenseKeyInfo flki = new LicenseKeyInfo();
        flki.LoadLicense("DOMAIN:localhost\nPRODUCT:CF06\nEXPIRATION:00000000\nPACKAGES:\nSERVERS:1\n" +
            "DH0g3D1mDvNiMgqujyU5TspX3oB3TlsFUgSgR2p3MHe3VY+xgQvsn1kMRA6w+ZOLwLFbjjziznLX73V2DAzBXBBxQH1sSP6pnvua1qYyPXN5Mb3v9bd53nT1wgwiPvJSGLEKzsV/sf0RgtsrcBJTlGNSOAUG9qnkrSQlrLRkSdUzfZl4HdAidy53yZB4ydmGstxDOZWjCZvl7pOSL+PrOsYv5QbXz3eC4/dQJDNKG+lJkeuq/wXyMmhz/jj+JkSJQnvr9DIuEiYAqp1j4YNRVvGPv7FQqfPIixwQPXn73K7dBGwzUmmGzFUSXR0gLPpdG4nD5eoTOp1qaeKo4qy68A==", "localhost");
        LicenseKeyInfoProvider.SetLicenseKeyInfo(flki);
        flki = new LicenseKeyInfo();
        flki.LoadLicense("DOMAIN:127.0.0.1\nPRODUCT:CF06\nEXPIRATION:00000000\nPACKAGES:\nSERVERS:1\n" +
            "Mo0XU+buTy0eaW57psUxemEkBfo5pNAzGupE05V+LZmfykV75XnfFxX4Ac5O6kD4QQwDBKMBYf4qNYxOMI6JAXe0j3Qv8W9FJ6TG7TLD4ga/Ru9OOapXH6R86wepeLSdG0PKDL96JR4QNsUz1fZbRodxdOhvIEy8FvpF1JHUj04rc8DVFCJvkcrvmbfd+ZlfjGxo7GnfMOXE4FRlf3joK13jxiJypiGe4Tu71LiQgRlFFIWfXTm/WKgMT+wpQnIm/lUnWug5g0N2CkcEZ/dNfCOGBUqU4ImPjWGKdyfcYyS+F1FgvPI2sdzxIUnLtYu834fqgoEUzBsIuME3tNr8UQ==", "127.0.0.1");
        LicenseKeyInfoProvider.SetLicenseKeyInfo(flki);

        // Create free license keys for user defined domain
        string domainName = URLHelper.CorrectDomainName(txtUserDomain.Text.Trim());
        string firstName = txtUserFirstName.Text.Trim();
        string lastName = txtUserLastName.Text.Trim();
        string email = txtUserEmail.Text.Trim();

        bool userForm = !String.IsNullOrEmpty(firstName) || !String.IsNullOrEmpty(lastName) ||
            !String.IsNullOrEmpty(email) || !String.IsNullOrEmpty(txtPassword.Text);

        // Ignore localhost/127.0.0.1 licenses
        if ((String.Compare(domainName, "localhost", true) == 0) || (String.Compare(domainName, "127.0.0.1") == 0))
        {
            domainName = "";
        }

        // Do not modify anything if form is blank
        if (!String.IsNullOrEmpty(domainName) || userForm)
        {
            if (userForm)
            {
                result = new Validator().NotEmpty(firstName, ResHelper.GetString(strPrefix + "firstnamerequired"))
                    .NotEmpty(lastName, ResHelper.GetString(strPrefix + "lastnamerequired"))
                    .NotEmpty(email, ResHelper.GetString(strPrefix + "emailrequired"))
                    .IsEmail(email, ResHelper.GetString(strPrefix + "emailinvalidformat"))
                    .Result;

                if (String.IsNullOrEmpty(result) && plcPass.Visible && String.IsNullOrEmpty(txtPassword.Text))
                {
                    result = ResHelper.GetString(strPrefix + "passwordrequired");
                }
            }

            if (String.IsNullOrEmpty(result))
            {
                LS.CMSLicenseService ls = new LS.CMSLicenseService();
                if (userForm)
                {
                    if (ls.UserExists(email))
                    {
                        // If user with specified name (e-mail) already exist ask for her password
                        if (!plcPass.Visible)
                        {
                            plcPass.Visible = true;
                            result = ResHelper.GetString(strPrefix + "passwordrequired");
                        }
                        else
                        {
                            lickey = ls.GetFreeEditionKeyGeneral(domainName, firstName, lastName, email, txtPassword.Text, 6);
                        }
                    }
                    else
                    {
                        // Register new user and get license key
                        lickey = ls.GetFreeEditionKeyGeneral(domainName, firstName, lastName, email, UserInfoProvider.GenerateNewPassword(), 6);
                    }
                }
                else
                {
                    lickey = ls.GetFreeEditionKeyGeneral(domainName, null, null, null, null, 6);
                }

                if (String.IsNullOrEmpty(result) && !lickey.StartsWith("DOMAIN"))
                {
                    result = lickey;
                }
            }

            if (String.IsNullOrEmpty(result))
            {
                if (!String.IsNullOrEmpty(lickey))
                {
                    LicenseKeyInfo lki = new LicenseKeyInfo();
                    lki.LoadLicense(lickey, "");
                    LicenseKeyInfoProvider.SetLicenseKeyInfo(lki);
                }
            }
        }

        if (!String.IsNullOrEmpty(result))
        {
            lblError.Visible = true;
            lblError.Text = result;
        }

        return String.IsNullOrEmpty(result);
    }
    /// <summary>
    /// Inserts license to database.
    /// </summary>
    /// <param name="license">License to insert</param>
    private void InsertLicense(string license)
    {
        string         error  = string.Empty;
        string         exists = string.Empty;
        LicenseKeyInfo lk     = new LicenseKeyInfo();

        try
        {
            // Load license
            lk.LoadLicense(license.Trim(), "");
            switch (lk.ValidationResult)
            {
            case LicenseValidationEnum.Expired:
                error = GetString("Licenses_License_New.LicenseNotValid.Expired");
                break;

            case LicenseValidationEnum.Invalid:
                error = GetString("Licenses_License_New.LicenseNotValid.Invalid");
                break;

            case LicenseValidationEnum.NotAvailable:
                error = GetString("Licenses_License_New.LicenseNotValid.NotAvailable");
                break;

            case LicenseValidationEnum.WrongFormat:
                error = GetString("Licenses_License_New.LicenseNotValid.WrongFormat");
                break;

            case LicenseValidationEnum.Valid:

                if (!LicenseKeyInfoProvider.IsLicenseExistForDomain(lk))
                {
                    LicenseKeyInfoProvider.SetLicenseKeyInfo(lk);
                }
                else
                {
                    // If override
                    if (chkOverrideExisting.Checked)
                    {
                        // Get old license
                        lk = LicenseKeyInfoProvider.GetLicenseKeyInfo(lk.Domain);
                        if (lk != null)
                        {
                            // Delete old license
                            LicenseKeyInfoProvider.DeleteLicenseKeyInfo(lk);

                            // Create new and load
                            lk = new LicenseKeyInfo();
                            lk.LoadLicense(license.Trim(), "");

                            // Save
                            switch (lk.ValidationResult)
                            {
                            case LicenseValidationEnum.Valid:
                                LicenseKeyInfoProvider.SetLicenseKeyInfo(lk);
                                break;
                            }
                        }
                    }
                    else
                    {
                        exists = GetString("license.import.skipped") + " " + GetString("Licenses_License_New.DomainAlreadyExists").Replace("%%name%%", lk.Domain);
                    }
                }

                break;
            }
        }
        catch (Exception)
        {
            error = GetString("license.import.failed");
        }

        // Result
        if (!string.IsNullOrEmpty(error))
        {
            string msg = "";
            if (string.IsNullOrEmpty(lk.Domain))
            {
                msg = GetString("license.import.failed");
            }
            else
            {
                msg = string.Format(GetString("license.import.faileddomain"), lk.Domain);
            }

            msg += ResHelper.Colon + " " + error;
            msg  = "<span class=\"LineErrorLabel\">" + msg + "</span>";
            ImportManager.Settings.LogProgressState(LogStatusEnum.Info, msg);
        }
        else if (!string.IsNullOrEmpty(exists))
        {
            ImportManager.Settings.LogProgressState(LogStatusEnum.Info, exists);
        }
        else
        {
            ImportManager.Settings.LogProgressState(LogStatusEnum.Info, string.Format(GetString("license.import.success"), lk.Domain));
        }
    }
    /// <summary>
    /// Inserts license to database.
    /// </summary>
    /// <param name="license">License to insert</param>
    private void InsertLicense(string license)
    {
        string error = string.Empty;
        string exists = string.Empty;
        LicenseKeyInfo lk = new LicenseKeyInfo();
        try
        {
            // Load license
            lk.LoadLicense(license.Trim(), "");
            switch (lk.ValidationResult)
            {
                case LicenseValidationEnum.Expired:
                    error = GetString("Licenses_License_New.LicenseNotValid.Expired");
                    break;

                case LicenseValidationEnum.Invalid:
                    error = GetString("Licenses_License_New.LicenseNotValid.Invalid");
                    break;

                case LicenseValidationEnum.NotAvailable:
                    error = GetString("Licenses_License_New.LicenseNotValid.NotAvailable");
                    break;

                case LicenseValidationEnum.WrongFormat:
                    error = GetString("Licenses_License_New.LicenseNotValid.WrongFormat");
                    break;

                case LicenseValidationEnum.Valid:

                    if(!LicenseKeyInfoProvider.IsLicenseExistForDomain(lk))
                    {
                        LicenseKeyInfoProvider.SetLicenseKeyInfo(lk);
                    }
                    else
                    {
                        // If override
                        if (chkOverrideExisting.Checked)
                        {
                            // Get old license
                            lk = LicenseKeyInfoProvider.GetLicenseKeyInfo(lk.Domain);
                            if (lk != null)
                            {
                                // Delete old license
                                LicenseKeyInfoProvider.DeleteLicenseKeyInfo(lk);

                                // Create new and load
                                lk = new LicenseKeyInfo();
                                lk.LoadLicense(license.Trim(), "");

                                // Save
                                switch (lk.ValidationResult)
                                {
                                    case LicenseValidationEnum.Valid:
                                        LicenseKeyInfoProvider.SetLicenseKeyInfo(lk);
                                        break;
                                }
                            }
                        }
                        else
                        {
                            exists = GetString("license.import.skipped") + " " + GetString("Licenses_License_New.DomainAlreadyExists").Replace("%%name%%", lk.Domain);
                        }
                    }

                    break;
            }
        }
        catch (Exception)
        {
            error = GetString("license.import.failed");
        }

        // Result
        if (!string.IsNullOrEmpty(error))
        {
            string msg = "";
            if (string.IsNullOrEmpty(lk.Domain))
            {
                msg = GetString("license.import.failed") ;
            }
            else
            {
                msg = string.Format(GetString("license.import.faileddomain"), lk.Domain) ;
            }

            msg += ResHelper.Colon + " " + error;
            msg = "<span class=\"LineErrorLabel\">" + msg + "</span>";
            ImportManager.Settings.LogProgressState(LogStatusEnum.Info, msg);
        }
        else if (!string.IsNullOrEmpty(exists))
        {
            ImportManager.Settings.LogProgressState(LogStatusEnum.Info, exists);
        }
        else
        {
            ImportManager.Settings.LogProgressState(LogStatusEnum.Info, string.Format(GetString("license.import.success"), lk.Domain));
        }
    }
Example #33
0
    /// <summary>
    /// Checks the license for selected objects.
    /// </summary>
    public static string CheckLicenses(SiteImportSettings settings)
    {
        string result = null;

        object[,] checkFeatures = new object[, ] {
            { FeatureEnum.Unknown, "", false },
            { FeatureEnum.BizForms, FormObjectType.BIZFORM, true },
            { FeatureEnum.Forums, PredefinedObjectType.FORUM, true },
            { FeatureEnum.Newsletters, PredefinedObjectType.NEWSLETTER, true },
            { FeatureEnum.Subscribers, PredefinedObjectType.NEWSLETTERUSERSUBSCRIBER + ";" + PredefinedObjectType.NEWSLETTERROLESUBSCRIBER + ";" + PredefinedObjectType.NEWSLETTERSUBSCRIBER, true },
            { FeatureEnum.Staging, SynchronizationObjectType.STAGINGSERVER, true },
            { FeatureEnum.Ecommerce, PredefinedObjectType.SKU, false },
            { FeatureEnum.Polls, PredefinedObjectType.POLL, false },
            { FeatureEnum.Webfarm, WebFarmObjectType.WEBFARMSERVER, false },
            { FeatureEnum.SiteMembers, SiteObjectType.USER, false },
            { FeatureEnum.WorkflowVersioning, PredefinedObjectType.WORKFLOW, false }
        };

        // Get imported licenses
        DataSet ds = ImportProvider.LoadObjects(settings, LicenseObjectType.LICENSEKEY, false);

        string domain = string.IsNullOrEmpty(settings.SiteDomain) ? URLHelper.GetCurrentDomain().ToLower() : URLHelper.RemovePort(settings.SiteDomain).ToLower();

        // Remove application path
        int slashIndex = domain.IndexOf("/");

        if (slashIndex > -1)
        {
            domain = domain.Substring(0, slashIndex);
        }

        bool anyDomain = ((domain == "localhost") || (domain == "127.0.0.1"));

        // Check all features
        for (int i = 0; i <= checkFeatures.GetUpperBound(0); i++)
        {
            string[] objectTypes = ((string)checkFeatures[i, 1]).Split(';');
            bool     siteObject  = (bool)checkFeatures[i, 2];
            string   objectType  = objectTypes[0];

            // Check objects
            int count = (objectType != "") ? 0 : 1;
            for (int j = 0; j < objectTypes.Length; ++j)
            {
                objectType = objectTypes[j];
                if (objectType != "")
                {
                    ArrayList codenames = settings.GetSelectedObjects(objectType, siteObject);
                    count += (codenames == null) ? 0 : codenames.Count;
                }
            }

            // Check a special case for Workflows
            if (objectType.Equals(PredefinedObjectType.WORKFLOW))
            {
                // Check workflows
                bool includeWorkflowScopes = ValidationHelper.GetBoolean(settings.GetSettings(ImportExportHelper.SETTINGS_WORKFLOW_SCOPES), false);
                if (includeWorkflowScopes)
                {
                    // Check if there are any workflow scopes in the imported package and if there are, increase the count.
                    DataSet dsScopes = ImportProvider.LoadObjects(settings, PredefinedObjectType.WORKFLOWSCOPE, true);
                    if (!DataHelper.DataSourceIsEmpty(dsScopes))
                    {
                        count++;
                    }
                }
            }

            if (count > 0)
            {
                FeatureEnum feature = (FeatureEnum)checkFeatures[i, 0];

                // Get best available license from DB
                LicenseKeyInfo bestLicense = LicenseKeyInfoProvider.GetLicenseKeyInfo(domain, feature);
                if ((bestLicense != null) && (bestLicense.ValidationResult != LicenseValidationEnum.Valid))
                {
                    bestLicense = null;
                }

                // Check new licenses
                LicenseKeyInfo bestSelected = null;
                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        LicenseKeyInfo lki = new LicenseKeyInfo(dr);
                        // Use license only if selected
                        if ((settings.IsSelected(LicenseObjectType.LICENSEKEY, lki.Domain, false)) && (anyDomain || (lki.Domain.ToLower() == domain)) && LicenseKeyInfoProvider.IsBetterLicense(lki, bestSelected, feature))
                        {
                            bestSelected = lki;
                            if (bestSelected.Domain.ToLower() == domain)
                            {
                                break;
                            }
                        }
                    }
                }

                // Check the license
                if (feature == FeatureEnum.Unknown)
                {
                    if ((bestLicense == null) && (bestSelected == null))
                    {
                        return(ResHelper.GetString("Import.NoLicense"));
                    }
                }
                else
                {
                    // Check the limit
                    int limit = GetLimit(bestLicense, feature);

                    // Use a database license if it is better than the one which is being imported
                    if (LicenseKeyInfoProvider.IsBetterLicense(bestLicense, bestSelected, feature))
                    {
                        bestSelected = bestLicense;
                    }

                    int selectedLimit = GetLimit(bestSelected, feature);
                    if (bestSelected != null)
                    {
                        if (bestSelected.ValidationResult == LicenseValidationEnum.Valid)
                        {
                            if (!anyDomain || (bestSelected.Domain.ToLower() == domain))
                            {
                                limit = selectedLimit;
                            }
                            else
                            {
                                // If selected better, take the selected
                                if (selectedLimit > limit)
                                {
                                    limit = selectedLimit;
                                }
                            }
                        }
                        else
                        {
                            if (!anyDomain || (bestSelected.Domain.ToLower() == domain))
                            {
                                limit = 0;
                            }
                        }
                    }
                    if (limit < count)
                    {
                        if (limit <= 0)
                        {
                            result += String.Format(ResHelper.GetString("Import.LimitZero"), ResHelper.GetString("ObjectTasks." + objectType.Replace(".", "_")));
                        }
                        else
                        {
                            result += String.Format(ResHelper.GetString("Import.LimitExceeded"), ResHelper.GetString("ObjectTasks." + objectType.Replace(".", "_")), limit);
                        }

                        // If better license
                        if ((bestLicense != null) && (bestSelected != null) && LicenseKeyInfoProvider.IsBetterLicense(bestLicense, bestSelected, feature))
                        {
                            result += " " + ResHelper.GetString("Import.BetterLicenseExists");
                        }

                        result += "<br />";
                    }
                }
            }
        }

        return(result);
    }
Example #34
0
    /// <summary>
    /// Creates requested license keys. Returns false if something fail.
    /// </summary>
    /// <param name="connectionString">Connection string</param>
    public bool ProcessRegistration(string connectionString)
    {
        string result = "";
        string lickey = "";

        // Delete all existing license keys
        DataSet ds = LicenseKeyInfoProvider.GetAllLicenseKeys();

        if (!DataHelper.DataSourceIsEmpty(ds))
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                LicenseKeyInfo lki = new LicenseKeyInfo(dr);
                if (lki != null)
                {
                    LicenseKeyInfoProvider.DeleteLicenseKeyInfo(lki.LicenseKeyID);
                }
            }
        }

        // Create license keys for localhost and 127.0.0.1
        LicenseKeyInfo flki = new LicenseKeyInfo();

        flki.LoadLicense("DOMAIN:localhost\nPRODUCT:CF06\nEXPIRATION:00000000\nPACKAGES:\nSERVERS:1\n" +
                         "DH0g3D1mDvNiMgqujyU5TspX3oB3TlsFUgSgR2p3MHe3VY+xgQvsn1kMRA6w+ZOLwLFbjjziznLX73V2DAzBXBBxQH1sSP6pnvua1qYyPXN5Mb3v9bd53nT1wgwiPvJSGLEKzsV/sf0RgtsrcBJTlGNSOAUG9qnkrSQlrLRkSdUzfZl4HdAidy53yZB4ydmGstxDOZWjCZvl7pOSL+PrOsYv5QbXz3eC4/dQJDNKG+lJkeuq/wXyMmhz/jj+JkSJQnvr9DIuEiYAqp1j4YNRVvGPv7FQqfPIixwQPXn73K7dBGwzUmmGzFUSXR0gLPpdG4nD5eoTOp1qaeKo4qy68A==", "localhost");
        LicenseKeyInfoProvider.SetLicenseKeyInfo(flki);
        flki = new LicenseKeyInfo();
        flki.LoadLicense("DOMAIN:127.0.0.1\nPRODUCT:CF06\nEXPIRATION:00000000\nPACKAGES:\nSERVERS:1\n" +
                         "Mo0XU+buTy0eaW57psUxemEkBfo5pNAzGupE05V+LZmfykV75XnfFxX4Ac5O6kD4QQwDBKMBYf4qNYxOMI6JAXe0j3Qv8W9FJ6TG7TLD4ga/Ru9OOapXH6R86wepeLSdG0PKDL96JR4QNsUz1fZbRodxdOhvIEy8FvpF1JHUj04rc8DVFCJvkcrvmbfd+ZlfjGxo7GnfMOXE4FRlf3joK13jxiJypiGe4Tu71LiQgRlFFIWfXTm/WKgMT+wpQnIm/lUnWug5g0N2CkcEZ/dNfCOGBUqU4ImPjWGKdyfcYyS+F1FgvPI2sdzxIUnLtYu834fqgoEUzBsIuME3tNr8UQ==", "127.0.0.1");
        LicenseKeyInfoProvider.SetLicenseKeyInfo(flki);

        // Create free license keys for user defined domain
        string domainName = URLHelper.CorrectDomainName(txtUserDomain.Text.Trim());
        string firstName  = txtUserFirstName.Text.Trim();
        string lastName   = txtUserLastName.Text.Trim();
        string email      = txtUserEmail.Text.Trim();

        bool userForm = !String.IsNullOrEmpty(firstName) || !String.IsNullOrEmpty(lastName) ||
                        !String.IsNullOrEmpty(email) || !String.IsNullOrEmpty(txtPassword.Text);

        // Ignore localhost/127.0.0.1 licenses
        if ((String.Compare(domainName, "localhost", true) == 0) || (String.Compare(domainName, "127.0.0.1") == 0))
        {
            domainName = "";
        }

        // Do not modify anything if form is blank
        if (!String.IsNullOrEmpty(domainName) || userForm)
        {
            if (userForm)
            {
                result = new Validator().NotEmpty(firstName, ResHelper.GetString(strPrefix + "firstnamerequired"))
                         .NotEmpty(lastName, ResHelper.GetString(strPrefix + "lastnamerequired"))
                         .NotEmpty(email, ResHelper.GetString(strPrefix + "emailrequired"))
                         .IsEmail(email, ResHelper.GetString(strPrefix + "emailinvalidformat"))
                         .Result;

                if (String.IsNullOrEmpty(result) && plcPass.Visible && String.IsNullOrEmpty(txtPassword.Text))
                {
                    result = ResHelper.GetString(strPrefix + "passwordrequired");
                }
            }

            if (String.IsNullOrEmpty(result))
            {
                LS.CMSLicenseService ls = new LS.CMSLicenseService();
                if (userForm)
                {
                    if (ls.UserExists(email))
                    {
                        // If user with specified name (e-mail) already exist ask for her password
                        if (!plcPass.Visible)
                        {
                            plcPass.Visible = true;
                            result          = ResHelper.GetString(strPrefix + "passwordrequired");
                        }
                        else
                        {
                            lickey = ls.GetFreeEditionKeyGeneral(domainName, firstName, lastName, email, txtPassword.Text, 6);
                        }
                    }
                    else
                    {
                        // Register new user and get license key
                        lickey = ls.GetFreeEditionKeyGeneral(domainName, firstName, lastName, email, UserInfoProvider.GenerateNewPassword(), 6);
                    }
                }
                else
                {
                    lickey = ls.GetFreeEditionKeyGeneral(domainName, null, null, null, null, 6);
                }

                if (String.IsNullOrEmpty(result) && !lickey.StartsWith("DOMAIN"))
                {
                    result = lickey;
                }
            }

            if (String.IsNullOrEmpty(result))
            {
                if (!String.IsNullOrEmpty(lickey))
                {
                    LicenseKeyInfo lki = new LicenseKeyInfo();
                    lki.LoadLicense(lickey, "");
                    LicenseKeyInfoProvider.SetLicenseKeyInfo(lki);
                }
            }
        }

        if (!String.IsNullOrEmpty(result))
        {
            lblError.Visible = true;
            lblError.Text    = result;
        }

        return(String.IsNullOrEmpty(result));
    }
    protected void btnOK_Click(object sender, EventArgs e)
    {
        string result = new Validator().NotEmpty(rfvDisplayName, rfvDisplayName.ErrorMessage).NotEmpty(rfvCodeName, rfvCodeName.ErrorMessage).NotEmpty(rfvURL, rfvURL.ErrorMessage)
                        .IsCodeName(txtCodeName.Text, GetString("general.invalidcodename"))
                        .Result;

        // Get the object
        WebFarmServerInfo wi = WebFarmServerInfoProvider.GetWebFarmServerInfo(serverid) ?? new WebFarmServerInfo();

        // Check license web farm server limit
        if (String.IsNullOrEmpty(result))
        {
            LicenseKeyInfo lki = LicenseHelper.CurrentLicenseInfo;
            if (lki == null)
            {
                return;
            }

            // Only if server is enabled
            if (chkEnabled.Checked)
            {
                // Enabling or new server as action insert
                VersionActionEnum action = ((wi.ServerID > 0) && wi.ServerEnabled) ? VersionActionEnum.Edit : VersionActionEnum.Insert;
                if (!lki.CheckServerCount(WebSyncHelperClass.ServerCount, action))
                {
                    result = GetString("licenselimitation.infopagemessage");
                }

                // Log the message
                if (!String.IsNullOrEmpty(result))
                {
                    EventLogProvider eventLog = new EventLogProvider();
                    string           message  = GetString("licenselimitation.serversexceeded");
                    eventLog.LogEvent(EventLogProvider.EVENT_TYPE_WARNING, DateTime.Now, "WebFarms", LicenseHelper.LICENSE_LIMITATION_EVENTCODE, URLHelper.CurrentURL, message);
                }
            }
        }


        if (result == "")
        {
            wi.ServerID          = serverid;
            wi.ServerDisplayName = txtDisplayName.Text;
            wi.ServerName        = txtCodeName.Text;
            wi.ServerURL         = txtURL.Text;
            wi.ServerEnabled     = chkEnabled.Checked;
            try
            {
                WebFarmServerInfoProvider.SetWebFarmServerInfo(wi);
                // Clear server list
                URLHelper.Redirect("WebFarm_Server_Edit.aspx?serverid=" + wi.ServerID + "&saved=1");
            }
            catch (Exception ex)
            {
                lblError.Text    = ex.Message.Replace("%%name%%", wi.ServerName);
                lblError.Visible = true;
                lblInfo.Visible  = false;
            }
        }
        else
        {
            lblError.Text    = result;
            lblError.Visible = true;
            lblInfo.Visible  = false;
        }
    }
Example #36
0
    private void CheckTrial()
    {
        string info = null;

        if (LicenseHelper.ApplicationExpires != DateTime.MinValue)
        {
            int appExpiration = LicenseHelper.ApplicationExpires.Subtract(DateTime.Now).Days;

            // Application expires
            if (CMSContext.SYSTEM_VERSION_SUFFIX.Contains("BETA"))
            {
                if (appExpiration <= 0)
                {
                    info = GetString("Beta.AppExpired");
                }
                else
                {
                    info = string.Format(GetString("Beta.AppExpiresIn"), appExpiration);
                }
            }
            else
            {
                if (appExpiration <= 0)
                {
                    info = string.Format(GetString("Preview.AppExpired"), CMSContext.SYSTEM_VERSION_SUFFIX);
                }
                else
                {
                    info = string.Format(GetString("Preview.AppExpiresIn"), CMSContext.SYSTEM_VERSION_SUFFIX, appExpiration);
                }
            }
        }
        // Check the license key for trial version
        else if (DataHelper.GetNotEmpty(URLHelper.GetCurrentDomain(), string.Empty) != string.Empty)
        {
            LicenseKeyInfo lki = LicenseKeyInfoProvider.GetLicenseKeyInfo(URLHelper.GetCurrentDomain());
            if ((lki != null) && (lki.Key.Length == LicenseKeyInfo.TRIAL_KEY_LENGTH) && (lki.ExpirationDateReal != LicenseKeyInfo.TIME_UNLIMITED_LICENSE))
            {
                int expiration = lki.ExpirationDateReal.Subtract(DateTime.Now).Days;
                // Trial version expiration date
                if (expiration <= 0)
                {
                    info = GetString("Trial.Expired");
                }
                else
                {
                    info = string.Format(GetString("Trial.ExpiresIn"), expiration);
                }
            }

            if (lki != null)
            {
                // Check the number of users for free edition
                if (lki.Edition == ProductEditionEnum.Free)
                {
                    UserInfoProvider.LicenseController();
                }
            }
        }

        ltlText.Text     = info;
        pnlTrial.Visible = !string.IsNullOrEmpty(ltlText.Text);
    }