protected void Page_Load(object sender, EventArgs e)
 {
     try
     {
         webAppResult = ES.Services.WebApplicationGallery.GetGalleryApplicationDetails(PanelSecurity.PackageId, PanelRequest.ApplicationID);
         //
         if (!webAppResult.IsSuccess)
         {
             messageBox.ShowMessage(webAppResult, "WAG_NOT_AVAILABLE", "ModuleWAG");
             return;
         }
         //
         if (!IsPostBack)
         {
             DeploymentParametersResult appParamsResult =
                 ES.Services.WebApplicationGallery.GetGalleryApplicationParams(PanelSecurity.PackageId, PanelRequest.ApplicationID);
             //
             if (!appParamsResult.IsSuccess)
             {
                 messageBox.ShowMessage(appParamsResult, "WAG_NOT_AVAILABLE", "ModuleWAG");
                 return;
             }
             //
             BindWebSites();
             BindDatabaseVersions(appParamsResult.Value);
             BindParams(appParamsResult.Value);
             ToggleControls();
         }
     }
     catch (Exception ex)
     {
         ShowErrorMessage("WEB_GALLERY_INSTALLER_INIT_FORM", ex);
     }
 }
Esempio n. 2
0
        private void BindApplicationDetails()
        {
            try
            {
                GalleryApplicationResult appResult = ES.Services.WebApplicationGallery.GetGalleryApplicationDetails(PanelSecurity.PackageId,
                                                                                                                    PanelRequest.ApplicationID);
                // check for errors
                if (!appResult.IsSuccess)
                {
                    messageBox.ShowMessage(appResult, "WAG_NOT_AVAILABLE", "WebAppGallery");
                    return;
                }

                // bind details
                if (appResult.Value != null)
                {
                    appHeader.BindApplicationDetails(appResult.Value);
                }

                // check for warnings
                if (appResult.ErrorCodes.Count > 0)
                {
                    // app does not meet requirements
                    messageBox.ShowMessage(appResult, "WAG_CANNOT_INSTALL_APPLICATION", "WebAppGallery");
                    btnInstall.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage("GET_GALLERY_APPLIACTION_DETAILS", ex);
            }
        }
        private void InstallApplication()
        {
            List <DeploymentParameter> parameters = GetParameters();

            ResultObject res = ES.Services.WebApplicationGallery.Install(PanelSecurity.PackageId,
                                                                         PanelRequest.ApplicationID,
                                                                         ddlWebSite.SelectedItem.Text,
                                                                         directoryName.Text,
                                                                         parameters.ToArray());

            messageBox.ShowMessage(res, "WEB_APPLICATION_GALLERY_INSTALLED", "INSTALL_WEB_APPLICATION");
            if (res.IsSuccess)
            {
                secAppSettings.Visible = false;
                secDatabase.Visible    = false;
                secLocation.Visible    = false;
                btnCancel.Visible      = false;
                btnInstall.Visible     = false;
                btnOK.Visible          = true;
                applicationUrl.Visible = true;
                try
                {
                    GalleryApplicationResult appResult =
                        ES.Services.WebApplicationGallery.GetGalleryApplicationDetails(PanelSecurity.PackageId,
                                                                                       PanelRequest.ApplicationID);
                    //
                    GalleryApplication application = appResult.Value;
                    //
                    if (application != null)
                    {
                        string url = "http://" + ddlWebSite.SelectedItem.Text;

                        url = Path.Combine(url, directoryName.Text);
                        if (Path.IsPathRooted(application.StartPage))
                        {
                            if (application.StartPage != "/")
                            {
                                url = Path.Combine(url, application.StartPage.Substring(1));
                            }
                        }
                        else
                        {
                            url = Path.Combine(url, application.StartPage);
                        }

                        hlApplication.NavigateUrl = url;
                    }
                }
                catch (Exception ex)
                {
                    ShowErrorMessage("GET_GALLERY_APPLIACTION_DETAILS", ex);
                }
            }
        }
Esempio n. 4
0
 public GalleryApplicationResult GetGalleryApplication(string id)
 {
     try
     {
         Log.WriteStart("'{0}' GetGalleryApplication", ProviderSettings.ProviderName);
         GalleryApplicationResult result = WebProvider.GetGalleryApplication(id);
         Log.WriteEnd("'{0}' GetGalleryApplication", ProviderSettings.ProviderName);
         return(result);
     }
     catch (Exception ex)
     {
         Log.WriteError(String.Format("'{0}' GetGalleryApplication", ProviderSettings.ProviderName), ex);
         throw;
     }
 }
Esempio n. 5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                return;
            }

            try
            {
                // load application details
                appResult = ES.Services.WebApplicationGallery.GetGalleryApplicationDetails(PanelSecurity.PackageId, PanelRequest.ApplicationID);

                if (!appResult.IsSuccess)
                {
                    messageBox.ShowMessage(appResult, "WAG_NOT_AVAILABLE", "WebAppGallery");
                    return;
                }

                // bind app details
                appHeader.BindApplicationDetails(appResult.Value);

                //// check for warnings
                //if (appResult.ErrorCodes.Count > 0)
                //{
                //    // app does not meet requirements
                //    messageBox.ShowMessage(appResult, "WAG_CANNOT_INSTALL_APPLICATION", "WebAppGallery");
                //    //btnInstall.Enabled = false;
                //}

                // bind app parameters
                List <DeploymentParameter> parameters = GetApplicationParameters();
                if (parameters == null)
                {
                    return;
                }

                //
                BindWebSites();
                BindDatabaseEngines(parameters);
            }
            catch (Exception ex)
            {
                ShowErrorMessage("WAG_NOT_AVAILABLE", ex);
                DisableForm();
            }
        }
		protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
                return;

            try
            {
                // load application details
                appResult = ES.Services.WebApplicationGallery.GetGalleryApplicationDetails(PanelSecurity.PackageId, PanelRequest.ApplicationID);
                
                if (!appResult.IsSuccess)
                {
                    messageBox.ShowMessage(appResult, "WAG_NOT_AVAILABLE", "WebAppGallery");
                    return;
                }

                // bind app details
                appHeader.BindApplicationDetails(appResult.Value);

                // check for warnings
                if (appResult.ErrorCodes.Count > 0)
                {
                    // app does not meet requirements
                    messageBox.ShowMessage(appResult, "WAG_CANNOT_INSTALL_APPLICATION", "WebAppGallery");
                    btnInstall.Enabled = false;
                }

                // bind app parameters
                List<DeploymentParameter> parameters = GetApplicationParameters();
                if (parameters == null)
                    return;

				//
                BindWebSites();
                BindDatabaseEngines(parameters);                
            }
            catch (Exception ex)
            {
                ShowErrorMessage("WAG_NOT_AVAILABLE", ex);
                DisableForm();
            }
        }
Esempio n. 7
0
 public static GalleryWebAppStatus GetGalleryApplicationStatus(int packageId, string webAppId)
 {
     try
     {
         WebServer webServer = GetAssociatedWebServer(packageId);
         //
         if (!webServer.IsMsDeployInstalled())
         {
             throw new ApplicationException(WAG_MODULE_NOT_AVAILABLE <StringResultObject>().ErrorCodes[0]);
         }
         //
         GalleryWebAppStatus appStatus = webServer.GetGalleryApplicationStatus(webAppId);
         //
         if (appStatus == GalleryWebAppStatus.NotDownloaded)
         {
             GalleryApplicationResult appResult = webServer.GetGalleryApplication(webAppId);
             // Start app download in new thread
             WebAppGalleryAsyncWorker async = new WebAppGalleryAsyncWorker();
             async.GalleryApp = appResult.Value;
             async.WebAppId   = webAppId;
             async.PackageId  = packageId;
             async.UserId     = SecurityContext.User.UserId;
             async.DownloadGalleryWebApplicationAsync();
             //
             return(GalleryWebAppStatus.Downloading);
         }
         //
         return(appStatus);
     }
     catch (Exception ex)
     {
         Trace.TraceError(ex.StackTrace);
         //
         return(GalleryWebAppStatus.Failed);
     }
 }
Esempio n. 8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    GalleryApplicationResult appResult =
                        ES.Services.WebApplicationGallery.GetGalleryApplicationDetails(PanelSecurity.PackageId,
                                                                                       PanelRequest.ApplicationID);
                    //
                    if (!appResult.IsSuccess)
                    {
                        messageBox.ShowMessage(appResult, "WAG_NOT_AVAILABLE", "ModuleWAG");
                        return;
                    }
                    //
                    GalleryApplication application = appResult.Value;
                    if (application != null)
                    {
                        lblVersion.Text     = application.Version;
                        lblDescription.Text = application.Description;
                        lblTitle.Text       = application.Title;
                        lblSize.Text        = application.Size;
                        imgLogo.ImageUrl    = "~/DesktopModules/WebsitePanel/resizeimage.ashx?url=" + Server.UrlEncode(application.IconUrl) +
                                              "&width=250&height=250";

                        hlAuthor.Text        = application.AuthorName;
                        hlAuthor.NavigateUrl = application.AuthorUrl;
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage("GET_GALLERY_APPLIACTION_DETAILS", ex);
            }
        }
Esempio n. 9
0
        private void InstallApplication()
        {
            if (!Page.IsValid)
            {
                return; // server-side validation
            }
            // collect parameters
            List <DeploymentParameter> parameters = GetParameters();

            string language = (string)Session["WebApplicationGaleryLanguage"];
            // install application
            StringResultObject res = ES.Services.WebApplicationGallery.Install(PanelSecurity.PackageId,
                                                                               PanelRequest.ApplicationID,
                                                                               ddlWebSite.SelectedItem.Text,
                                                                               directoryName.Text.Trim(),
                                                                               parameters.ToArray(),
                                                                               language
                                                                               );

            InstallLogPanel.Visible = true;
            InstallLog.InnerText    = res.Value;

            // show message box with results
            if (res.IsSuccess)
            {
                messageBox.ShowMessage(res, "WEB_APPLICATION_GALLERY_INSTALLED", "WebAppGallery");
            }
            else
            {
                messageBox.ShowMessage(res, null, null);
            }

            // toggle controls if there are no errors
            if (res.ErrorCodes.Count == 0)
            {
                secAppSettings.Visible = false;
                btnCancel.Visible      = false;
                btnInstall.Visible     = false;
                btnOK.Visible          = true;
                urlPanel.Visible       = true;
                try
                {
                    GalleryApplicationResult appResult =
                        ES.Services.WebApplicationGallery.GetGalleryApplicationDetails(PanelSecurity.PackageId,
                                                                                       PanelRequest.ApplicationID);
                    //
                    GalleryApplication application = appResult.Value;
                    //
                    if (application != null)
                    {
                        // change "Launch" link
                        hlApplication.Text = String.Format(GetLocalizedString("LaunchApplication.Text"), application.Title);

                        // set "main" application URL
                        hlApplication.NavigateUrl = GetAppLaunchUrl(application, ddlWebSite.SelectedItem.Text);

                        // set "temp" application URL if required
                        DomainInfo[] domains = ES.Services.WebServers.GetWebSitePointers(Int32.Parse(ddlWebSite.SelectedValue));
                        foreach (DomainInfo domain in domains)
                        {
                            if (domain.IsInstantAlias)
                            {
                                // show temp URL
                                tempUrlPanel.Visible = true;

                                // set URL text
                                tempUrl.Text = String.Format(GetLocalizedString("LaunchApplicationTemp.Text"), GetAppLaunchUrl(application, domain.DomainName));
                                break;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    ShowErrorMessage("GET_GALLERY_APPLIACTION_DETAILS", ex);
                }
            }
        }
Esempio n. 10
0
		public GalleryApplicationResult GetGalleryApplication(string id)
		{
			GalleryApplicationResult result = new GalleryApplicationResult();
			//
			try
			{
				WebApplicationGallery module = new WebApplicationGallery(GalleryXmlFeedUrl);
				//
				result.Value = module.GetApplicationByProductId(id);
				result.IsSuccess = true;
			}
			catch (Exception ex)
			{
				result.IsSuccess = false;
				result.AddError(GalleryErrors.ProcessingFeedXMLError, ex);
			}
			//
			return result;
		}
Esempio n. 11
0
        public static StringResultObject Install(int packageId, string webAppId, string siteName, string virtualDir, List <DeploymentParameter> updatedParameters)
        {
            StringResultObject result = new StringResultObject();
            //
            int                 dbItemResult = -1, dbUserResult = -1;
            WebSite             webSite       = default(WebSite);
            WebVirtualDirectory webVirtualDir = default(WebVirtualDirectory);
            WebVirtualDirectory iisAppNode    = default(WebVirtualDirectory);

            //
            try
            {
                SecurityContext.SetThreadSupervisorPrincipal();
                //
                TaskManager.StartTask(TASK_MANAGER_SOURCE, "INSTALL_WEB_APP");
                //
                TaskManager.WriteParameter("Package ID", packageId);
                TaskManager.WriteParameter("Site Name", siteName);

                //
                WebServer webServer = GetAssociatedWebServer(packageId);

                // ERROR: WAG is not available
                if (!webServer.IsMsDeployInstalled())
                {
                    return(WAG_MODULE_NOT_AVAILABLE <StringResultObject>());
                }

                //
                GalleryApplicationResult appResult = webServer.GetGalleryApplication(webAppId);

                #region Preparations and tracing
                // Trace at least Web Application Id for troubleshooting purposes
                if (!appResult.IsSuccess || appResult.Value == null)
                {
                    TaskManager.WriteError("Could not find an application to install with ID: {0}.", webAppId);
                    //
                    return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                }
                // Assign web app pack title to the currently running task
                TaskManager.ItemName = appResult.Value.Title;
                // Trace additional details from the feed
                TraceGalleryAppPackInfo(appResult.Value);

                // Trace out all deployment parameters
                Array.ForEach <DeploymentParameter>(updatedParameters.ToArray(), p => TaskManager.WriteParameter(p.Name, p.Value));
                // Check account
                int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
                if (accountCheck < 0)
                {
                    TaskManager.WriteError("Account check has been failed. Status: {0};", accountCheck.ToString());
                    //
                    return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                }
                // Check package
                int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive);
                if (packageCheck < 0)
                {
                    TaskManager.WriteError("Package check has been failed. Status: {0};", packageCheck.ToString());
                    //
                    return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                }
                // Check web site for existence
                webSite = WebServerController.GetWebSite(packageId, siteName);
                if (webSite == null)
                {
                    TaskManager.WriteError("Web site check has been failed. Status: {0};", BusinessErrorCodes.ERROR_WEB_INSTALLER_WEBSITE_NOT_EXISTS.ToString());
                    //
                    return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                }
                #endregion

                DeploymentParametersResult appParamsResult = GetGalleryApplicationParamsInternally(packageId, webAppId);

                //
                if (!appParamsResult.IsSuccess)
                {
                    foreach (string errorMessage in appParamsResult.ErrorCodes)
                    {
                        TaskManager.WriteError(errorMessage);
                    }
                    //
                    return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                }

                List <DeploymentParameter> origParams = appParamsResult.Value;
                //
                if (Array.Exists <DeploymentParameter>(origParams.ToArray(),
                                                       p => MatchParameterTag(p, DeploymentParameter.SQL_PARAM_TAG) ||
                                                       MatchParameterTag(p, DeploymentParameter.MYSQL_PARAM_TAG)))
                {
                    // Match input parameters from the client
                    DeploymentParameter dbNameParam = Array.Find <DeploymentParameter>(updatedParameters.ToArray(),
                                                                                       p => MatchParameterByNames(p, DeploymentParameter.DATABASE_NAME_PARAMS) ||
                                                                                       MatchParameterTag(p, DeploymentParameter.DB_NAME_PARAM_TAG));
                    //
                    DeploymentParameter dbUserParam = Array.Find <DeploymentParameter>(updatedParameters.ToArray(),
                                                                                       p => MatchParameterByNames(p, DeploymentParameter.DATABASE_USERNAME_PARAMS) ||
                                                                                       MatchParameterTag(p, DeploymentParameter.DB_USERNAME_PARAM_TAG));
                    //
                    DeploymentParameter dbUserPwParam = Array.Find <DeploymentParameter>(updatedParameters.ToArray(),
                                                                                         p => MatchParameterByNames(p, DeploymentParameter.DATABASE_USERPWD_PARAMS) ||
                                                                                         MatchParameterTag(p, DeploymentParameter.DB_PASSWORD_PARAM_TAG));

                    #region Pre-conditions verification...
                    //
                    if (dbNameParam == null)
                    {
                        //
                        TaskManager.WriteError(PARAMETER_IS_NULL_OR_EMPTY, DeploymentParameter.DATABASE_NAME_PARAM);
                        //
                        return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                    }
                    //
                    if (String.IsNullOrEmpty(dbNameParam.Tags))
                    {
                        //
                        TaskManager.WriteError("{0} parameter tags does not contain information about the database resource group should be used", DeploymentParameter.DATABASE_NAME_PARAM);
                        //
                        return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                    }
                    //
                    int dbServiceId = PackageController.GetPackageServiceId(packageId, dbNameParam.Tags);
                    //
                    if (dbServiceId <= 0)
                    {
                        //
                        TaskManager.WriteError("{0} parameter tags contains wrong information about the database resource group should be used. Resource group: " + dbNameParam.Tags, DeploymentParameter.DATABASE_NAME_PARAM);
                        //
                        return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                    }
                    #endregion
                    //
                    DeploymentParameter dbServerParam = Array.Find <DeploymentParameter>(origParams.ToArray(),
                                                                                         p => MatchParameterByNames(p, DeploymentParameter.DB_SERVER_PARAMS) ||
                                                                                         MatchParameterTag(p, DeploymentParameter.DB_SERVER_PARAM_TAG));
                    //
                    DeploymentParameter dbAdminParam = Array.Find <DeploymentParameter>(origParams.ToArray(),
                                                                                        p => MatchParameterByNames(p, DeploymentParameter.DB_ADMIN_PARAMS) ||
                                                                                        MatchParameterTag(p, DeploymentParameter.DB_ADMIN_USERNAME_PARAM_TAG));
                    //
                    DeploymentParameter dbAdminPwParam = Array.Find <DeploymentParameter>(origParams.ToArray(),
                                                                                          p => MatchParameterByNames(p, DeploymentParameter.DB_ADMINPWD_PARAMS) ||
                                                                                          MatchParameterTag(p, DeploymentParameter.DB_ADMIN_PASSWORD_PARAM_TAG));

                    #region Pre-conditions verification...
                    //
                    if (dbAdminParam == null)
                    {
                        //
                        TaskManager.WriteError(NO_DB_PARAMETER_MATCHES_MSG, NAMES_MATCH,
                                               String.Join(", ", DeploymentParameter.DB_ADMIN_PARAMS));
                        //
                        return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                    }
                    //
                    if (dbServerParam == null)
                    {
                        //
                        TaskManager.WriteError(NO_DB_PARAMETER_MATCHES_MSG, NAMES_MATCH,
                                               String.Join(", ", DeploymentParameter.DB_SERVER_PARAMS));
                        //
                        return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                    }
                    //
                    if (dbAdminPwParam == null)
                    {
                        //
                        TaskManager.WriteError(NO_DB_PARAMETER_MATCHES_MSG, NAMES_MATCH,
                                               String.Join(", ", DeploymentParameter.DB_ADMINPWD_PARAMS));
                        //
                        return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                    }
                    #endregion

                    #region Read & substitute database server settings
                    //
                    StringDictionary dbSettings = ServerController.GetServiceSettingsAdmin(dbServiceId);

                    // InternalAddress setting is common for all DB service providers
                    dbServerParam.Value = dbSettings["InternalAddress"];
                    // Set database administrator login
                    if (!String.IsNullOrEmpty(dbSettings["RootLogin"]))
                    {
                        dbAdminParam.Value = dbSettings["RootLogin"];
                    }
                    else if (!String.IsNullOrEmpty(dbSettings["SaLogin"]))
                    {
                        dbAdminParam.Value = dbSettings["SaLogin"];
                    }
                    else
                    {
                        //
                        TaskManager.WriteError(CANNOT_SET_PARAMETER_VALUE, dbAdminParam.Name);
                        //
                        return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                    }
                    // Set database administrator password
                    if (!String.IsNullOrEmpty(dbSettings["RootPassword"]))
                    {
                        dbAdminPwParam.Value = dbSettings["RootPassword"];
                    }
                    else if (!String.IsNullOrEmpty(dbSettings["SaPassword"]))
                    {
                        dbAdminPwParam.Value = dbSettings["SaPassword"];
                    }
                    else
                    {
                        //
                        TaskManager.WriteError(CANNOT_SET_PARAMETER_VALUE, dbAdminPwParam.Name);
                        //
                        return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                    }
                    #endregion

                    //
                    updatedParameters.AddRange(new List <DeploymentParameter> {
                        dbServerParam, dbAdminParam, dbAdminPwParam
                    });

                    #region Create database and db user account if new selected
                    //
                    SqlDatabase db = PackageController.GetPackageItemByName(packageId, dbNameParam.Value,
                                                                            typeof(SqlDatabase)) as SqlDatabase;
                    //
                    if (db == null)
                    {
                        db           = new SqlDatabase();
                        db.PackageId = packageId;
                        db.Name      = dbNameParam.Value;
                        //
                        dbItemResult = DatabaseServerController.AddSqlDatabase(db, dbNameParam.Tags);
                        //
                        if (dbItemResult < 0)
                        {
                            // Put specific error message into the trace log
                            TaskManager.WriteError("Could not create {0} database. Error code: {1}.", dbNameParam.Tags, dbItemResult.ToString());
                            // Return generic error
                            return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                        }
                    }

                    //
                    SqlUser user = PackageController.GetPackageItemByName(packageId, dbUserParam.Value,
                                                                          typeof(SqlUser)) as SqlUser;
                    //
                    if (user == null)
                    {
                        user           = new SqlUser();
                        user.PackageId = packageId;
                        user.Name      = dbUserParam.Value;
                        user.Databases = new string[] { dbNameParam.Value };
                        user.Password  = dbUserPwParam.Value;
                        //
                        dbUserResult = DatabaseServerController.AddSqlUser(user, dbNameParam.Tags);
                        //
                        if (dbUserResult < 0)
                        {
                            // Rollback and remove db if created
                            if (dbItemResult > 0)
                            {
                                DatabaseServerController.DeleteSqlDatabase(dbItemResult);
                            }
                            // Put specific error message into the trace log
                            TaskManager.WriteError("Could not create {0} user account. Error code: {1}.", dbNameParam.Tags, dbUserResult.ToString());
                            // Return generic error
                            return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
                        }
                    }
                    #endregion
                }

                //
                DeploymentParameter appPathParam = Array.Find <DeploymentParameter>(origParams.ToArray(),
                                                                                    p => MatchParameterName(p, DeploymentParameter.APPICATION_PATH_PARAM) ||
                                                                                    MatchParameterTag(p, DeploymentParameter.IISAPP_PARAM_TAG));
                //
                if (String.IsNullOrEmpty(virtualDir))
                {
                    appPathParam.Value = siteName;
                }
                else
                {
                    appPathParam.Value = String.Format("{0}/{1}", siteName, virtualDir);
                }
                //
                updatedParameters.Add(appPathParam);

                //
                result = webServer.InstallGalleryApplication(webAppId, updatedParameters.ToArray());
                //
                #region Rollback in case of failure
                // Rollback - remove resources have been created previously
                if (!result.IsSuccess)
                {
                    //
                    if (dbUserResult > 0)
                    {
                        DatabaseServerController.DeleteSqlUser(dbUserResult);
                    }
                    //
                    if (dbItemResult > 0)
                    {
                        DatabaseServerController.DeleteSqlDatabase(dbItemResult);
                    }
                    //
                    foreach (string errorCode in result.ErrorCodes)
                    {
                        TaskManager.WriteError(errorCode);
                    }
                    //
                    return(result);
                }
                #endregion

                // Reload web site details
                webSite = WebServerController.GetWebSite(packageId, siteName);
                // Reload virtual directory defaults
                if (!String.IsNullOrEmpty(virtualDir))
                {
                    webVirtualDir = WebServerController.GetVirtualDirectory(webSite.Id, virtualDir);
                }

                // We are going to install application on website or virtual directory
                iisAppNode = (webVirtualDir != null) ? webVirtualDir : webSite;
                // Put correct ASP.NET version depending on a web server's version
                iisAppNode.AspNetInstalled = (iisAppNode.IIs7) ? "2I" : "2";

                //
                if (MatchParticularAppDependency(appResult.Value.Dependency, SupportedAppDependencies.PHP_SCRIPTING))
                {
                    // Enable PHP 5 extensions for web site
                    iisAppNode.PhpInstalled = "5";
                    // Set the correct default document for PHP apps
                    if (iisAppNode.DefaultDocs.IndexOf("index.php", StringComparison.InvariantCultureIgnoreCase) == -1)
                    {
                        iisAppNode.DefaultDocs += ",index.php";
                    }
                    //
                    int docsResult = 0;
                    //
                    if (webVirtualDir == null)
                    {
                        docsResult = WebServerController.UpdateWebSite(webSite);
                    }
                    else
                    {
                        docsResult = WebServerController.UpdateVirtualDirectory(webSite.Id, webVirtualDir);
                    }
                    //
                    if (docsResult < 0)
                    {
                        TaskManager.WriteWarning("Could not update website/virtual directory default documents with the value of index.php. Result code: {0}", docsResult.ToString());
                    }
                }
                //
                if (MatchParticularAppDependency(appResult.Value.Dependency, SupportedAppDependencies.ASPNET_SCRIPTING))
                {
                    // Set the correct default document for ASP.NET apps
                    if (iisAppNode.DefaultDocs.IndexOf("Default.aspx", StringComparison.InvariantCultureIgnoreCase) == -1)
                    {
                        iisAppNode.DefaultDocs += ",Default.aspx";
                    }
                    //
                    int aspnetResult = 0;
                    //
                    if (webVirtualDir == null)
                    {
                        aspnetResult = WebServerController.UpdateWebSite(webSite);
                    }
                    else
                    {
                        aspnetResult = WebServerController.UpdateVirtualDirectory(webSite.Id, webVirtualDir);
                    }
                    //
                    if (aspnetResult < 0)
                    {
                        TaskManager.WriteWarning("Could not set default documents/enable ASP.NET 2.0 (Integrated Mode) for website/virtual directory. Result code: {0}", aspnetResult.ToString());
                    }
                }

                //
                return(result);
            }
            catch (Exception ex)
            {
                //
                TaskManager.WriteError(ex);
                //
                return(WAG_INSTALL_GENERIC_MODULE_ERROR <StringResultObject>());
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        public static StringResultObject Install(int packageId, string webAppId, string siteName, string virtualDir, List <DeploymentParameter> parameters)
        {
            StringResultObject result = new StringResultObject();

            try
            {
                // database operation results
                int databaseResult     = -1;
                int databaseUserResult = -1;

                // initialize task manager
                TaskManager.StartTask(TASK_MANAGER_SOURCE, "INSTALL_WEB_APP");
                TaskManager.WriteParameter("Package ID", packageId);
                TaskManager.WriteParameter("Site Name", siteName);

                #region Check Space and Account
                // Check account
                int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
                if (accountCheck < 0)
                {
                    return(Warning <StringResultObject>((-accountCheck).ToString()));
                }

                // Check space
                int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive);
                if (packageCheck < 0)
                {
                    return(Warning <StringResultObject>((-packageCheck).ToString()));
                }
                #endregion

                #region Check MS Deploy, web site and application pack
                // get target web server
                WebServer webServer = GetAssociatedWebServer(packageId);

                // Check if Web App Gallery is installed
                if (!webServer.IsMsDeployInstalled())
                {
                    return(Error <StringResultObject>(GalleryErrors.MsDeployIsNotInstalled));
                }

                // Check web site for existence
                WebSite webSite = WebServerController.GetWebSite(packageId, siteName);
                if (webSite == null)
                {
                    return(Error <StringResultObject>(GalleryErrors.WebSiteNotFound, siteName));
                }

                // get application pack details
                GalleryApplicationResult app = webServer.GetGalleryApplication(webAppId);
                if (!app.IsSuccess)
                {
                    return(Error <StringResultObject>(app, GalleryErrors.GeneralError));
                }
                if (app.Value == null)
                {
                    return(Error <StringResultObject>(GalleryErrors.WebApplicationNotFound, webAppId));
                }
                #endregion

                #region Trace app details

                // Assign web app pack title to the currently running task
                TaskManager.ItemName = app.Value.Title;

                // Trace additional details from the feed
                TaskManager.WriteParameter("Title", app.Value.Title);
                TaskManager.WriteParameter("Version", app.Value.Version);
                TaskManager.WriteParameter("Download URL", app.Value.DownloadUrl);
                TaskManager.WriteParameter("Author", app.Value.AuthorName);
                TaskManager.WriteParameter("Last Updated", app.Value.LastUpdated);

                // Trace out all deployment parameters
                Array.ForEach <DeploymentParameter>(parameters.ToArray(), p => TaskManager.WriteParameter(p.Name, p.Value));
                #endregion

                // elevate security context
                SecurityContext.SetThreadSupervisorPrincipal();

                #region Set AppPath
                // set correct application path
                DeploymentParameter appPath = FindParameterByTag(parameters, DeploymentParameterWellKnownTag.IisApp);
                if (appPath == null)
                {
                    return(Error <StringResultObject>(GalleryErrors.AppPathParameterNotFound));
                }

                appPath.Value = String.IsNullOrEmpty(virtualDir) ? siteName : String.Format("{0}/{1}", siteName, virtualDir);
                #endregion

                // database context
                // find database resource parameter
                DeploymentParameter databaseResoure = parameters.Find(p =>
                {
                    return(p.Name == DeploymentParameter.ResourceGroupParameterName);
                });

                // database is required for this application
                if (databaseResoure != null)
                {
                    // try to get database service
                    int dbServiceId = PackageController.GetPackageServiceId(packageId, databaseResoure.Value);
                    if (dbServiceId == 0)
                    {
                        return(Error <StringResultObject>(GalleryErrors.DatabaseServiceIsNotAvailable));
                    }

                    #region Setup Database server and DB Admin credentials
                    // get database service settings
                    StringDictionary dbSettings = ServerController.GetServiceSettingsAdmin(dbServiceId);

                    // database server
                    DeploymentParameter databaseServer = FindParameterByTag(parameters, DeploymentParameterWellKnownTag.DBServer);
                    if (databaseServer != null)
                    {
                        databaseServer.Value = dbSettings["ExternalAddress"];
                        if (String.IsNullOrEmpty(databaseServer.Value))
                        {
                            return(Error <StringResultObject>(GalleryErrors.DatabaseServerExternalAddressIsEmpty));
                        }
                    }

                    // database admin
                    DeploymentParameter databaseAdminUsername = FindParameterByTag(parameters, DeploymentParameterWellKnownTag.DBAdminUserName);
                    if (databaseAdminUsername != null)
                    {
                        databaseAdminUsername.Value = dbSettings["RootLogin"];
                        if (String.IsNullOrEmpty(databaseAdminUsername.Value))
                        {
                            databaseAdminUsername.Value = dbSettings["SaLogin"];
                        }

                        // raise error if database service is in Integrated Security mode (for SQL Server)
                        // or DB Admin username is not provided
                        if (String.IsNullOrEmpty(databaseAdminUsername.Value))
                        {
                            return(Error <StringResultObject>(GalleryErrors.DatabaseAdminUsernameNotSpecified));
                        }
                    }

                    // database admin password
                    DeploymentParameter databaseAdminPassword = FindParameterByTag(parameters, DeploymentParameterWellKnownTag.DBAdminPassword);
                    if (databaseAdminPassword != null)
                    {
                        databaseAdminPassword.Value = dbSettings["RootPassword"];
                        if (String.IsNullOrEmpty(databaseAdminPassword.Value))
                        {
                            databaseAdminPassword.Value = dbSettings["SaPassword"];
                        }

                        // raise error if database service is in Integrated Security mode (for SQL Server)
                        // or DB Admin password is not provided
                        if (String.IsNullOrEmpty(databaseAdminPassword.Value))
                        {
                            return(Error <StringResultObject>(GalleryErrors.DatabaseAdminPasswordNotSpecified));
                        }
                    }
                    #endregion

                    #region Create database and db user account if new selected

                    // create database
                    DeploymentParameter databaseName = FindParameterByTag(parameters, DeploymentParameterWellKnownTag.DBName);
                    if (databaseName != null)
                    {
                        SqlDatabase db = PackageController.GetPackageItemByName(packageId, databaseResoure.Value, databaseName.Value, typeof(SqlDatabase)) as SqlDatabase;

                        if (db == null)
                        {
                            try
                            {
                                db           = new SqlDatabase();
                                db.PackageId = packageId;
                                db.Name      = databaseName.Value;

                                // create
                                databaseResult = DatabaseServerController.AddSqlDatabase(db, databaseResoure.Value);
                                if (databaseResult < 0)
                                {
                                    result.ErrorCodes.Add((-databaseResult).ToString());
                                    return(Error <StringResultObject>(result, GalleryErrors.DatabaseCreationError));
                                }
                            }
                            catch (Exception ex)
                            {
                                // log exception
                                TaskManager.WriteError(ex);

                                // return error
                                return(Error <StringResultObject>(GalleryErrors.DatabaseCreationException));
                            }
                        }
                    }

                    // create database user
                    DeploymentParameter databaseUsername     = FindParameterByTag(parameters, DeploymentParameterWellKnownTag.DBUserName);
                    DeploymentParameter databaseUserPassword = FindParameterByTag(parameters, DeploymentParameterWellKnownTag.DBUserPassword);

                    if (databaseUsername != null && databaseUserPassword != null)
                    {
                        SqlUser user = PackageController.GetPackageItemByName(packageId, databaseResoure.Value, databaseUsername.Value, typeof(SqlUser)) as SqlUser;
                        //
                        if (user == null)
                        {
                            // create new user account
                            try
                            {
                                user           = new SqlUser();
                                user.PackageId = packageId;
                                user.Name      = databaseUsername.Value;
                                user.Databases = (databaseName != null) ? new string[] { databaseName.Value } : new string[0];
                                user.Password  = databaseUserPassword.Value;

                                // create
                                databaseUserResult = DatabaseServerController.AddSqlUser(user, databaseResoure.Value);

                                // check results
                                if (databaseUserResult < 0)
                                {
                                    // Rollback and remove db if created
                                    if (databaseResult > 0)
                                    {
                                        DatabaseServerController.DeleteSqlDatabase(databaseResult);
                                    }

                                    // raise error
                                    result.ErrorCodes.Add((-databaseUserResult).ToString());
                                    return(Error <StringResultObject>(result, GalleryErrors.DatabaseUserCreationError));
                                }
                            }
                            catch (Exception ex)
                            {
                                // log exception
                                TaskManager.WriteError(ex);

                                // return error
                                return(Error <StringResultObject>(GalleryErrors.DatabaseUserCreationException, ex.Message));
                            }
                        }
                        else
                        {
                            // check existing user account
                            DatabaseServer databaseService = DatabaseServerController.GetDatabaseServer(dbServiceId);
                            if (!databaseService.CheckConnectivity(databaseName.Value, databaseUsername.Value, databaseUserPassword.Value))
                            {
                                return(Error <StringResultObject>(GalleryErrors.DatabaseUserCannotAccessDatabase, databaseUsername.Value));
                            }
                        }
                    }
                    #endregion

                    // remove database resource parameter from the list
                    // before calling "install" method
                    parameters.Remove(databaseResoure);
                }

                // install application
                result = webServer.InstallGalleryApplication(webAppId, parameters.ToArray());

                #region Rollback in case of failure
                // Rollback - remove resources have been created previously
                if (!result.IsSuccess)
                {
                    // delete database
                    if (databaseUserResult > 0)
                    {
                        DatabaseServerController.DeleteSqlUser(databaseUserResult);
                    }

                    // delete database user
                    if (databaseResult > 0)
                    {
                        DatabaseServerController.DeleteSqlDatabase(databaseResult);
                    }

                    // exit with errors
                    return(Error <StringResultObject>(result, GalleryErrors.ApplicationInstallationError));
                }
                #endregion

                #region Update Web Application settings

                WebVirtualDirectory iisApp = null;
                if (String.IsNullOrEmpty(virtualDir))
                {
                    // load web site
                    iisApp = WebServerController.GetWebSite(packageId, siteName);
                }
                else
                {
                    // load virtual directory
                    iisApp = WebServerController.GetVirtualDirectory(webSite.Id, virtualDir);
                }

                // put correct extensions
                if ((app.Value.WellKnownDependencies & GalleryApplicationWellKnownDependency.AspNet20) == GalleryApplicationWellKnownDependency.AspNet20)
                {
                    // ASP.NET 2.0
                    iisApp.AspNetInstalled = (iisApp.IIs7) ? "2I" : "2";
                    AddDefaultDocument(iisApp, "default.aspx");
                }
                else if ((app.Value.WellKnownDependencies & GalleryApplicationWellKnownDependency.AspNet40) == GalleryApplicationWellKnownDependency.AspNet40)
                {
                    // ASP.NET 4.0
                    iisApp.AspNetInstalled = (iisApp.IIs7) ? "4I" : "4";
                    AddDefaultDocument(iisApp, "default.aspx");
                }
                else if ((app.Value.WellKnownDependencies & GalleryApplicationWellKnownDependency.PHP) == GalleryApplicationWellKnownDependency.PHP)
                {
                    // PHP 5
                    iisApp.PhpInstalled = "5";
                    AddDefaultDocument(iisApp, "index.php");
                }

                // update web site or virtual directory
                int updateResult = 0;
                if (String.IsNullOrEmpty(virtualDir))
                {
                    // update web site
                    updateResult = WebServerController.UpdateWebSite(iisApp as WebSite);
                }
                else
                {
                    // update virtual directory
                    updateResult = WebServerController.UpdateVirtualDirectory(webSite.Id, iisApp);
                }

                if (updateResult < 0)
                {
                    TaskManager.WriteWarning("Cannot update website or virtual directory programming extensions and default documents. Result code: {0}", updateResult.ToString());
                }

                #endregion

                return(result);
            }
            catch (Exception ex)
            {
                // log error
                TaskManager.WriteError(ex);

                // exit with error code
                return(Error <StringResultObject>(GalleryErrors.GeneralError));
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        public static GalleryApplicationResult GetGalleryApplicationDetails(int packageId, string applicationId)
        {
            GalleryApplicationResult result;

            //
            try
            {
                TaskManager.StartTask(TASK_MANAGER_SOURCE, GET_GALLERY_APP_DETAILS_TASK);

                // check if WAG is installed
                WebServer webServer = GetAssociatedWebServer(packageId);
                if (!webServer.IsMsDeployInstalled())
                {
                    return(Error <GalleryApplicationResult>(GalleryErrors.MsDeployIsNotInstalled));
                }

                // get application details
                result = webServer.GetGalleryApplication(applicationId);

                if (!result.IsSuccess)
                {
                    return(Error <GalleryApplicationResult>(result, GalleryErrors.GetApplicationError));
                }

                // check application requirements
                PackageContext context = PackageController.GetPackageContext(packageId);

                GalleryApplication app = result.Value;

                // ASP.NET 2.0
                if ((app.WellKnownDependencies & GalleryApplicationWellKnownDependency.AspNet20) == GalleryApplicationWellKnownDependency.AspNet20 &&
                    context.Quotas.ContainsKey(Quotas.WEB_ASPNET20) && context.Quotas[Quotas.WEB_ASPNET20].QuotaAllocatedValue < 1)
                {
                    result.ErrorCodes.Add(GalleryErrors.AspNet20Required);
                }

                // ASP.NET 4.0
                else if ((app.WellKnownDependencies & GalleryApplicationWellKnownDependency.AspNet40) == GalleryApplicationWellKnownDependency.AspNet40 &&
                         context.Quotas.ContainsKey(Quotas.WEB_ASPNET40) && context.Quotas[Quotas.WEB_ASPNET40].QuotaAllocatedValue < 1)
                {
                    result.ErrorCodes.Add(GalleryErrors.AspNet40Required);
                }

                // PHP
                else if ((app.WellKnownDependencies & GalleryApplicationWellKnownDependency.PHP) == GalleryApplicationWellKnownDependency.PHP &&
                         context.Quotas.ContainsKey(Quotas.WEB_PHP4) && context.Quotas[Quotas.WEB_PHP4].QuotaAllocatedValue < 1 &&
                         context.Quotas.ContainsKey(Quotas.WEB_PHP5) && context.Quotas[Quotas.WEB_PHP5].QuotaAllocatedValue < 1)
                {
                    result.ErrorCodes.Add(GalleryErrors.PhpRequired);
                }

                // any database
                GalleryApplicationWellKnownDependency anyDatabaseFlag = GalleryApplicationWellKnownDependency.SQL | GalleryApplicationWellKnownDependency.MySQL;
                if ((app.WellKnownDependencies & anyDatabaseFlag) == anyDatabaseFlag &&
                    !(context.Groups.ContainsKey(ResourceGroups.MsSql2000) ||
                      context.Groups.ContainsKey(ResourceGroups.MsSql2005) ||
                      context.Groups.ContainsKey(ResourceGroups.MsSql2008) ||
                      context.Groups.ContainsKey(ResourceGroups.MySql4) ||
                      context.Groups.ContainsKey(ResourceGroups.MySql5)))
                {
                    result.ErrorCodes.Add(GalleryErrors.DatabaseRequired);
                }

                // SQL Server
                else if ((app.WellKnownDependencies & GalleryApplicationWellKnownDependency.SQL) == GalleryApplicationWellKnownDependency.SQL &&
                         !(context.Groups.ContainsKey(ResourceGroups.MsSql2000) ||
                           context.Groups.ContainsKey(ResourceGroups.MsSql2005) ||
                           context.Groups.ContainsKey(ResourceGroups.MsSql2008)))
                {
                    result.ErrorCodes.Add(GalleryErrors.SQLRequired);
                }

                // MySQL
                else if ((app.WellKnownDependencies & GalleryApplicationWellKnownDependency.MySQL) == GalleryApplicationWellKnownDependency.MySQL &&
                         !(context.Groups.ContainsKey(ResourceGroups.MySql4) ||
                           context.Groups.ContainsKey(ResourceGroups.MySql5)))
                {
                    result.ErrorCodes.Add(GalleryErrors.MySQLRequired);
                }

                if (result.ErrorCodes.Count > 0)
                {
                    GalleryApplicationResult warning = Warning <GalleryApplicationResult>(result, GalleryErrors.PackageDoesNotMeetRequirements);
                    warning.Value = app;
                    return(warning);
                }
            }
            catch (Exception ex)
            {
                TaskManager.WriteError(ex);
                return(Error <GalleryApplicationResult>(GalleryErrors.GeneralError, ex.Message));
            }
            finally
            {
                TaskManager.CompleteTask();
            }
            //
            return(result);
        }