Пример #1
0
        protected override void OnStart(string[] args)
        {
            try
            {
                _reg.Run();

                #region backgroundWorkerSignalR
                var backgroundWorkerSignalR = new BackgroundWorker
                {
                    WorkerReportsProgress      = true,
                    WorkerSupportsCancellation = true
                };
                backgroundWorkerSignalR.DoWork += (sender, eventArgs) =>
                {
                    var url = ConfigurationManager.AppSettings["SignalRUrl"];
                    WebApp.Start(url);
                };

                if (!backgroundWorkerSignalR.IsBusy)
                {
                    // Start the asynchronous operation.
                    backgroundWorkerSignalR.RunWorkerAsync();
                }

                #endregion

                _diagnosticService.Info("Service start");
            }
            catch (Exception ex)
            {
                _diagnosticService.Error(ex);
            }
        }
Пример #2
0
        public bool SignIn(string userName, string password, bool rememberMe, string deploymentMode)
        {
            // encript pasword

            var claims = ClaimsManager.CreateClaims(userName, password).ToList();
            var user   = ClaimsManager.ValidateQuickspatchUserLogin(claims);

            if (user == null || !user.IsQuickspatchUser)
            {
                var claimException = new InvalidClaimsException("InvalidUserAndPasswordText")
                {
                    QuickspatchUserName = (user != null) ? user.UserName : string.Empty
                };
                _diagnosticService.Error(SystemMessageLookup.GetMessage("InvalidUserAndPasswordText"));
                _diagnosticService.Error("UserName:"******"LoginWithInacticeUser");
                _diagnosticService.Error(SystemMessageLookup.GetMessage("LoginWithInacticeUser"));
                _diagnosticService.Error("UserName:"******"Camino" && user.Courier != null)
            {
                var claimException = new UserVisibleException("LoginWithCourierUser");
                _diagnosticService.Error(SystemMessageLookup.GetMessage("LoginWithCourierUser"));
                _diagnosticService.Error("UserName:" + userName);
                throw claimException;
            }

            var principal = CreatePrincipalFromClaimsAndUser(user, claims);

            FormAuthenticationService.SignIn(principal, true, principal.AuthToken,
                                             DateTime.UtcNow.AddMinutes(MaxSessionDuration));
            return(true);
        }
Пример #3
0
        protected override void DoWork(object state)
        {
            try
            {
                var tasks          = new List <Task>();
                var deploymentJobs = _deploymentJobService.Get(p => p.Server.Code == ServerId &&
                                                               (p.IsCopySourceDone ?? false) &&
                                                               p.JobType == (int)JobType.WindowService &&
                                                               (p.IsStart ?? false) &&
                                                               !(p.IsDone ?? false))
                                     .OrderBy(p => p.FailCount)
                                     .Take(3).ToList();

                if (!deploymentJobs.Any())
                {
                    return;
                }

                var listJobUpdated = new List <DeploymentJob>();

                foreach (var job in deploymentJobs)
                {
                    var localJob = job;
                    var t        = Task.Factory.StartNew(() =>
                    {
                        #region job implement
                        try
                        {
                            var serviceDest   = localJob.Configuration.DestinationWindowServicePath;
                            var dbName        = localJob.Configuration.DatabaseName;
                            var loginName     = localJob.Configuration.DatabaseUsername;
                            var loginPassword = EncryptHelper.Decrypt(localJob.Configuration.DatabasePassword);

                            var con =
                                new SqlConnectionStringBuilder(
                                    ConfigurationManager.ConnectionStrings["MainDb"].ConnectionString);
                            var connStringWeb =
                                string.Format(
                                    "Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3};MultipleActiveResultSets=True",
                                    con.DataSource, dbName, loginName, loginPassword);

                            //service
                            var configService =
                                OpenConfigFile(serviceDest + @"\" + localJob.Configuration.ServiceFileName + ".config");
                            if (configService.HasFile)
                            {
                                var sectionService =
                                    (ConnectionStringsSection)configService.GetSection("connectionStrings");
                                if (sectionService.ConnectionStrings["AdminDb"] != null)
                                {
                                    sectionService.ConnectionStrings["AdminDb"].ConnectionString = connStringWeb;
                                }

                                if (configService.AppSettings.Settings["ServiceName"] == null)
                                {
                                    configService.AppSettings.Settings.Add("ServiceName", localJob.Configuration.ServiceName);
                                }
                                else
                                {
                                    configService.AppSettings.Settings["ServiceName"].Value = localJob.Configuration.ServiceName;
                                }

                                foreach (var additionConfig in localJob.AdditionConfigs)
                                {
                                    if (configService.AppSettings.Settings[additionConfig.KeyConfigValue] != null)
                                    {
                                        configService.AppSettings.Settings[additionConfig.KeyConfigValue].Value = additionConfig.ReplaceByValue;
                                    }
                                }
                                configService.Save();
                            }

                            StartService(serviceDest + @"\" + localJob.Configuration.ServiceFileName,
                                         localJob.Configuration.ServiceName);
                            localJob.IsDone = true;
                        }
                        catch (Exception ex)
                        {
                            localJob.FailCount = (localJob.FailCount ?? 0) + 1;
                            _diagnosticService.Error(ex);
                        }
                        #endregion

                        listJobUpdated.Add(localJob);
                    });

                    tasks.Add(t);
                }

                Task.WaitAll(tasks.ToArray());
                _deploymentJobService.UpdateListJobs(listJobUpdated);
            }
            catch (Exception ex)
            {
                _diagnosticService.Error(ex);
            }
        }
Пример #4
0
        protected override void DoWork(object state)
        {
            var mainCancellationTokenSource = new CancellationToken();
            try
            {
                var tasks = new List<Task>();
                var deploymentJobs = _deploymentJobService.Get(p => p.Server.Code == ServerId
                    && !(p.IsCopySourceDone ?? false)
                    && (p.IsStart ?? false))
                    .OrderBy(p => p.FailCount)
                    .Take(3).ToList();

                if (!deploymentJobs.Any()) return;

                var listJobUpdated = new List<DeploymentJob>();

                foreach (var job in deploymentJobs)
                {
                    var localJob = job;
                    var t = Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            //source
                            var serviceSource = localJob.Configuration.SourceWindowServicePath;
                            var webSource = localJob.Configuration.SourceWebPath;
                            var webApiSource = localJob.Configuration.SourceWebApiPath;

                            //destination
                            var serviceDest = localJob.Configuration.DestinationWindowServicePath;
                            var webDest = localJob.Configuration.DestinationWebPath;
                            var webDestApi = localJob.Configuration.DestinationWebApiPath;

                            if (localJob.JobType == (int)JobType.WebApp)
                            {
                                if (!Directory.Exists(webDest)) Directory.CreateDirectory(webDest);
                                FileAndFolderHelper.DirectoryCopy(webSource, webDest);
                            }
                            if (localJob.JobType == (int)JobType.WebApi)
                            {
                                if (!Directory.Exists(webDestApi)) Directory.CreateDirectory(webDestApi);
                                FileAndFolderHelper.DirectoryCopy(webApiSource, webDestApi);

                            }
                            if (localJob.JobType == (int)JobType.WindowService)
                            {
                                if (!Directory.Exists(serviceDest)) Directory.CreateDirectory(serviceDest);
                                FileAndFolderHelper.DirectoryCopy(serviceSource, serviceDest);
                            }
                            localJob.IsCopySourceDone = true;
                        }
                        catch (Exception ex)
                        {
                            localJob.FailCount = (localJob.FailCount ?? 0) + 1;
                            _diagnosticService.Error(ex);
                        }

                        //localJob.ServiceProcessing = false;
                        listJobUpdated.Add(localJob);
                    }, mainCancellationTokenSource);

                    tasks.Add(t);
                }

                Task.WaitAll(tasks.ToArray(), mainCancellationTokenSource);
                _deploymentJobService.UpdateListJobs(listJobUpdated);
            }
            catch (Exception ex)
            {
                _diagnosticService.Error(ex);
            }
        }
Пример #5
0
        protected override void DoWork(object state)
        {
            var mainCancellationTokenSource = new CancellationToken();

            try
            {
                var certString       = ConfigurationManager.AppSettings["CertString"];
                var isUrlWebAppHttps = false;
                var tasks            = new List <Task>();
                var deploymentJobs   = _deploymentJobService.Get(p => p.Server.Code == ServerId &&
                                                                 (p.IsCopySourceDone ?? false) &&
                                                                 (p.JobType == (int)JobType.WebApi || p.JobType == (int)JobType.WebApp) &&
                                                                 (p.IsStart ?? false) &&
                                                                 !(p.IsDone ?? false))
                                       .OrderBy(p => p.FailCount)
                                       .Take(2).ToList();

                var listJobUpdated = new List <DeploymentJob>();

                var timeout = new TimeSpan(0, 5, 0);
                foreach (var job in deploymentJobs)
                {
                    var localJob = job;
                    var t        = Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            #region process data
                            var dbName        = localJob.Configuration.DatabaseName;
                            var loginName     = localJob.Configuration.DatabaseUsername;
                            var loginPassword = EncryptHelper.Decrypt(localJob.Configuration.DatabasePassword);
                            var istenant      = localJob.Deployment != null && localJob.Deployment.Product != null &&
                                                (localJob.Deployment.Product.IsTenant ?? false);
                            var tempWebDomainName    = localJob.Configuration.WebDomainName ?? "";
                            var tempWebApiDomainName = localJob.Configuration.WebApiDomainName ?? "";

                            if (!tempWebDomainName.Contains("http") && !tempWebDomainName.Contains("https"))
                            {
                                tempWebDomainName = "http://" + tempWebDomainName + "/";
                            }
                            else
                            {
                                tempWebDomainName = tempWebDomainName + "/";
                            }

                            if (tempWebDomainName.Contains("https"))
                            {
                                isUrlWebAppHttps = true;
                            }


                            if (!tempWebApiDomainName.Contains("http"))
                            {
                                tempWebApiDomainName = "http://" + tempWebApiDomainName + "/";
                            }
                            else
                            {
                                tempWebApiDomainName = tempWebApiDomainName + "/";
                            }

                            // Get host name for SignupDomain
                            var hostDomain = new Uri(tempWebDomainName).Host;
                            if (hostDomain.StartsWith("www"))
                            {
                                hostDomain = hostDomain.Remove(0, 4);
                            }
                            hostDomain        = "." + hostDomain;
                            var con           = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MainDb"].ConnectionString);
                            var connStringWeb =
                                string.Format(
                                    "Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3};MultipleActiveResultSets=True",
                                    con.DataSource, dbName, loginName, loginPassword);
                            #endregion

                            #region add web app (AdminDb/FranchiseeDb)
                            if (localJob.JobType == (int)JobType.WebApp)
                            {
                                try
                                {
                                    var configWeb = OpenConfigFile(localJob.Configuration.DestinationWebPath + @"\\Web.config");
                                    if (configWeb != null && configWeb.HasFile)
                                    {
                                        var sectionWebConn = (ConnectionStringsSection)configWeb.GetSection("connectionStrings");
                                        if (sectionWebConn != null && sectionWebConn.ConnectionStrings["AdminDb"] != null)
                                        {
                                            sectionWebConn.ConnectionStrings["AdminDb"].ConnectionString = connStringWeb;
                                        }
                                        // get SignupDomain
                                        if (configWeb.AppSettings.Settings["SignupDomain"] != null)
                                        {
                                            configWeb.AppSettings.Settings["SignupDomain"].Value = hostDomain;
                                        }
                                        // get productId
                                        if (configWeb.AppSettings.Settings["ProductDeploymentId"] != null)
                                        {
                                            configWeb.AppSettings.Settings["ProductDeploymentId"].Value = localJob.Deployment.ProductId.ToString();
                                        }
                                        if (configWeb.AppSettings.Settings["Url"] != null)
                                        {
                                            configWeb.AppSettings.Settings["Url"].Value = tempWebDomainName;
                                        }
                                        if (configWeb.AppSettings.Settings["EmailFromDisplayName"] != null)
                                        {
                                            configWeb.AppSettings.Settings["EmailFromDisplayName"].Value = localJob.Deployment.Product.Name;
                                        }

                                        if (localJob.Deployment != null && localJob.Deployment.Product != null && (localJob.Deployment.Product.IsTenant ?? false))
                                        {
                                            if (localJob.Deployment.DeploymentType == (int)DeploymentType.Franchisee)
                                            {
                                                var product   = localJob.Deployment.Product;
                                                var apiDomain = SuggestionNameHelper.GetWebApiDomainName(product.Domain, true, (int)DeploymentType.Admin, "", "");

                                                var deploymentAdmin = product.Deployments.Where(p => p.DeploymentType == (int)DeploymentType.Admin).ToList();
                                                if (deploymentAdmin.Any() && deploymentAdmin.First().DeploymentJobs.Any(p => p.JobType == (int)JobType.WebApi))
                                                {
                                                    apiDomain =
                                                        deploymentAdmin.First()
                                                        .DeploymentJobs.First(p => p.JobType == (int)JobType.WebApi)
                                                        .Configuration.WebApiDomainName;
                                                }
                                                if (apiDomain.Substring(apiDomain.Length - 1, 1) != @"/")
                                                {
                                                    apiDomain = apiDomain + @"/";
                                                }
                                                if (configWeb.AppSettings.Settings["WebApiUrl"] != null)
                                                {
                                                    configWeb.AppSettings.Settings["WebApiUrl"].Value = apiDomain;
                                                }
                                            }

                                            if (tempWebApiDomainName.Substring(tempWebApiDomainName.Length - 1, 1) != @"/")
                                            {
                                                tempWebApiDomainName = tempWebApiDomainName + @"/";
                                            }
                                            if (configWeb.AppSettings.Settings["WebApiUrlFranchisee"] != null)
                                            {
                                                configWeb.AppSettings.Settings["WebApiUrlFranchisee"].Value = tempWebApiDomainName;
                                            }
                                        }
                                        else
                                        {
                                            if (configWeb.AppSettings.Settings["WebApiUrl"] != null)
                                            {
                                                configWeb.AppSettings.Settings["WebApiUrl"].Value = tempWebApiDomainName + "/";
                                            }
                                        }

                                        if (!string.IsNullOrEmpty(localJob.Configuration.EmailAddress) && configWeb.AppSettings.Settings["EmailFrom"] != null)
                                        {
                                            configWeb.AppSettings.Settings["EmailFrom"].Value = localJob.Configuration.EmailAddress;
                                        }
                                        if (!string.IsNullOrEmpty(localJob.Configuration.EmailPassword) && configWeb.AppSettings.Settings["Password"] != null)
                                        {
                                            configWeb.AppSettings.Settings["Password"].Value = EncryptHelper.Decrypt(localJob.Configuration.EmailPassword);
                                        }
                                        if (!string.IsNullOrEmpty(localJob.Configuration.EmailHost) && configWeb.AppSettings.Settings["Host"] != null)
                                        {
                                            configWeb.AppSettings.Settings["Host"].Value = localJob.Configuration.EmailHost;
                                        }
                                        if (localJob.Configuration.EmailPort != null && localJob.Configuration.EmailPort != 0 && configWeb.AppSettings.Settings["Port"] != null)
                                        {
                                            configWeb.AppSettings.Settings["Port"].Value = localJob.Configuration.EmailPort.ToString();
                                        }

                                        if (istenant && localJob.Deployment.DeploymentType == (int)DeploymentType.Franchisee)
                                        {
                                            if (configWeb.AppSettings.Settings["DeploymentMode"] != null)
                                            {
                                                configWeb.AppSettings.Settings["DeploymentMode"].Value = "franchisee";
                                            }
                                            if (sectionWebConn.ConnectionStrings["FranchiseeDb"] != null)
                                            {
                                                sectionWebConn.ConnectionStrings["FranchiseeDb"].ConnectionString = connStringWeb;
                                            }
                                        }
                                        else if (istenant && localJob.Deployment.DeploymentType == (int)DeploymentType.Admin)
                                        {
                                            if (configWeb.AppSettings.Settings["DeploymentMode"] != null)
                                            {
                                                configWeb.AppSettings.Settings["DeploymentMode"].Value = "camino";
                                            }
                                        }

                                        configWeb.Save();
                                    }
                                }
                                catch { }

                                var uri = new Uri(tempWebDomainName);
                                if (localJob.Configuration.IsCreateDomain ?? false)
                                {
                                    _iisHostingHelper.RemoveHost(uri.Host);
                                }
                                //_iisHostingHelper.AddHost(uri.Host, uri.Host, localJob.Configuration.DestinationWebPath, 80, timeout, false, !string.IsNullOrEmpty(uri.Scheme) && uri.Scheme.ToLower() == "https", certString);
                                _iisHostingHelper.AddHost(uri.Host, uri.Host, localJob.Configuration.DestinationWebPath, 80, timeout, false, isUrlWebAppHttps, certString);
                            }
                            #endregion

                            #region add webapi host
                            if (localJob.JobType == (int)JobType.WebApi)
                            {
                                try
                                {
                                    var configWebApi = OpenConfigFile(localJob.Configuration.DestinationWebApiPath + @"\\Web.config");
                                    if (configWebApi != null && configWebApi.HasFile)
                                    {
                                        var sectionWebApiConn = (ConnectionStringsSection)configWebApi.GetSection("connectionStrings");
                                        if (sectionWebApiConn != null)
                                        {
                                            sectionWebApiConn.ConnectionStrings["AdminDb"].ConnectionString = connStringWeb;
                                        }
                                        if (configWebApi.AppSettings.Settings["Url"] != null)
                                        {
                                            configWebApi.AppSettings.Settings["Url"].Value = tempWebApiDomainName;
                                        }
                                        if (configWebApi.AppSettings.Settings["EmailFromDisplayName"] != null)
                                        {
                                            configWebApi.AppSettings.Settings["EmailFromDisplayName"].Value = localJob.Deployment.Product.Name;
                                        }
                                        if (!string.IsNullOrEmpty(localJob.Configuration.EmailAddress) && configWebApi.AppSettings.Settings["EmailFrom"] != null)
                                        {
                                            configWebApi.AppSettings.Settings["EmailFrom"].Value = localJob.Configuration.EmailAddress;
                                        }
                                        if (!string.IsNullOrEmpty(localJob.Configuration.EmailPassword) && configWebApi.AppSettings.Settings["Password"] != null)
                                        {
                                            configWebApi.AppSettings.Settings["Password"].Value = EncryptHelper.Decrypt(localJob.Configuration.EmailPassword);
                                        }
                                        if (!string.IsNullOrEmpty(localJob.Configuration.EmailHost) && configWebApi.AppSettings.Settings["Host"] != null)
                                        {
                                            configWebApi.AppSettings.Settings["Host"].Value = localJob.Configuration.EmailHost;
                                        }
                                        if (localJob.Configuration.EmailPort != null && localJob.Configuration.EmailPort != 0 && configWebApi.AppSettings.Settings["Port"] != null)
                                        {
                                            configWebApi.AppSettings.Settings["Port"].Value = localJob.Configuration.EmailPort.ToString();
                                        }

                                        var product         = localJob.Deployment.Product;
                                        var deploymentAdmin = product.Deployments.Where(p => p.DeploymentType == (int)DeploymentType.Admin).ToList();
                                        var apiDomain       = SuggestionNameHelper.GetWebApiDomainName(product.Domain, true, (int)DeploymentType.Admin, "", "");
                                        if (deploymentAdmin.Any() && deploymentAdmin.First().DeploymentJobs.Any(p => p.JobType == (int)JobType.WebApi))
                                        {
                                            apiDomain =
                                                deploymentAdmin.First()
                                                .DeploymentJobs.First(p => p.JobType == (int)JobType.WebApi)
                                                .Configuration.WebApiDomainName;
                                        }
                                        if (apiDomain.Substring(apiDomain.Length - 1, 1) != @"/")
                                        {
                                            apiDomain = apiDomain + @"/";
                                        }
                                        if (configWebApi.AppSettings.Settings["WebApiUrl"] != null)
                                        {
                                            configWebApi.AppSettings.Settings["WebApiUrl"].Value = apiDomain;
                                        }
                                        configWebApi.Save();
                                    }
                                }
                                catch { }
                                var uri = new Uri(tempWebApiDomainName);
                                if (localJob.Configuration.IsCreateDomain ?? false)
                                {
                                    _iisHostingHelper.RemoveHost(uri.Host);
                                }
                                _iisHostingHelper.AddHost(uri.Host, uri.Host, localJob.Configuration.DestinationWebApiPath, 80, timeout, true, !string.IsNullOrEmpty(uri.Scheme) && uri.Scheme.ToLower() == "https");
                            }
                            #endregion

                            #region other config
                            foreach (var additionConfig in localJob.AdditionConfigs)
                            {
                                try
                                {
                                    var otherConfig =
                                        OpenConfigFile(localJob.Configuration.DestinationWebApiPath + @"\\Web.config");
                                    if (otherConfig != null && otherConfig.HasFile)
                                    {
                                        if (otherConfig.AppSettings.Settings[additionConfig.KeyConfigValue] != null)
                                        {
                                            otherConfig.AppSettings.Settings[additionConfig.KeyConfigValue].Value =
                                                additionConfig.ReplaceByValue;
                                        }
                                    }
                                    otherConfig.Save();
                                }
                                catch { }
                            }

                            #endregion

                            //confirm
                            localJob.IsDone = true;
                        }
                        catch (Exception ex)
                        {
                            localJob.FailCount = (localJob.FailCount ?? 0) + 1;
                            _diagnosticService.Error(ex);
                        }

                        listJobUpdated.Add(localJob);
                    }, mainCancellationTokenSource);

                    tasks.Add(t);
                }

                Task.WaitAll(tasks.ToArray(), mainCancellationTokenSource);
                _deploymentJobService.UpdateListJobs(listJobUpdated);
            }
            catch (Exception ex)
            {
                _diagnosticService.Error(ex);
            }
        }
Пример #6
0
        protected bool HandleException(Exception ex, out ExceptionHandlingResult exceptionHandlingResult)
        {
            exceptionHandlingResult = new ExceptionHandlingResult();
            bool shouldRethrow;

            _diagnosticService.Error(ex);
            _diagnosticService.Error(ex.StackTrace);
            var isProductionMode = IsProductionMode;

            var commonErrorMessage = SystemMessageLookup.GetMessage("GeneralExceptionMessageText");

            //  if production mode then show generic error
            if (isProductionMode)
            {
                exceptionHandlingResult.ErrorMessage = commonErrorMessage;
                exceptionHandlingResult.StackTrace   = string.Empty;
            }
            else //  else: show all exception
            {
                exceptionHandlingResult.ErrorMessage = ex.Message;
                exceptionHandlingResult.StackTrace   = ex.StackTrace;
            }
            var innerError = ex.InnerException;

            if (innerError != null && !isProductionMode)
            {
                // Check if the error message not is the message from error in the entity framework( this is the error that we can handle, not show to user)
                if (innerError.Message != "Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.")
                {
                    exceptionHandlingResult.AddModelStateErrors(innerError.Message);
                }
            }
            if (ex is BusinessLogicException)
            {
                //all business exception be showed to client
                exceptionHandlingResult.ErrorMessage = ex.Message;
                shouldRethrow = false;
            }
            else if (ex is UserVisibleException)
            {
                //exception has been transformed
                exceptionHandlingResult.ErrorMessage = ex.Message;

                shouldRethrow = true;
            }
            else if (ex is DataBadSqlException)
            {
                shouldRethrow = false;
            }
            else if (ex is DataCannotSerializeTransactionException)
            {
                shouldRethrow = false;
            }
            else if (ex is DataDeadlockException)
            {
                shouldRethrow = false;
            }
            else if (ex is DataIntegrityViolationException)
            {
                shouldRethrow = false;
            }
            else if (ex is DataLockingFailureException)
            {
                //exceptionHandlingResult.ErrorMessage =
                //    TranslationService.TranslateString("ConcurrencyExceptionMessageText");

                shouldRethrow = false;
            }

            else if (ex is DataObjectRetrievalFailureException)
            {
                shouldRethrow = false;
            }
            else if (ex is DataPermissionDeniedException)
            {
                shouldRethrow = true;
            }
            else if (ex is DataAccessException)
            {
                shouldRethrow = true;
            }
            else //all other exception
            {
                shouldRethrow = true;
            }

            return(shouldRethrow);
        }
Пример #7
0
 public virtual ActionResult UnAuthorizedAccess(Exception exception)
 {
     _diagnosticService.Error(exception);
     return(View("~/Views/Error/UnAuthorizedAccess.cshtml", exception as UnAuthorizedAccessException));
 }
Пример #8
0
        protected override void DoWork(object state)
        {
            var mainCancellationTokenSource = new CancellationToken();

            try
            {
                var tasks          = new List <Task>();
                var deploymentJobs = _deploymentJobService.Get(p => p.Server.Code == ServerId &&
                                                               p.JobType == (int)JobType.Database &&
                                                               (p.IsCopySourceDone ?? false) &&
                                                               (p.IsStart ?? false) &&
                                                               !(p.IsDone ?? false))
                                     .OrderBy(p => p.FailCount)
                                     .Take(2).ToList();

                var listJobUpdated = new List <DeploymentJob>();

                foreach (var job in deploymentJobs)
                {
                    var localJob = job;
                    var t        = Task.Factory.StartNew(() =>
                    {
                        var dbName        = localJob.Configuration.DatabaseName;
                        var loginName     = localJob.Configuration.DatabaseUsername;
                        var loginPassword = EncryptHelper.Decrypt(localJob.Configuration.DatabasePassword);
                        var pass          = PasswordHelper.HashString("123456", "camino");

                        var conn   = new SqlConnection(ConfigurationManager.ConnectionStrings["MainDb"].ConnectionString);
                        var file   = new FileInfo(localJob.Configuration.SqlScriptPath);
                        var script = file.OpenText().ReadToEnd();
                        script     = script.Replace("{{DATABASE_NAME}}", dbName)
                                     .Replace("{{FRANCHISEE_ADMIN_NAME}}", "camino")
                                     .Replace("{{FRANCHISEE_ADMIN_PASSWORD}}", pass)
                                     .Replace("{{FRANCHISEE_ADMIN_EMAIL}}", "*****@*****.**");


                        var server = new Server(new ServerConnection(conn));

                        try
                        {
                            server.ConnectionContext.ExecuteNonQuery(script);
                            using (var scope = new TransactionScope())
                            {
                                var db    = server.Databases[dbName];
                                var login = server.Logins[loginName];
                                if (login == null)
                                {
                                    // Creating Logins
                                    login = new Login(server, loginName)
                                    {
                                        LoginType = LoginType.SqlLogin, PasswordPolicyEnforced = false
                                    };
                                    login.Create(loginPassword);
                                    login.DefaultDatabase = dbName;
                                    login.Alter();
                                }

                                // Creating Users in the database for the logins created
                                if (db.Users[loginName] != null)
                                {
                                    return;
                                }
                                var dbUser = new User(db, loginName)
                                {
                                    UserType = UserType.SqlLogin,
                                    Login    = login.Name,
                                };
                                dbUser.Create();
                                dbUser.AddToRole("db_owner");

                                localJob.IsDone = true;
                                scope.Complete();
                            }
                        }
                        catch (Exception exception)
                        {
                            server = new Server(new ServerConnection(conn));
                            server.KillAllProcesses(dbName);
                            server.KillDatabase(dbName);
                            var db = server.Databases[dbName];
                            db.Drop();
                            localJob.IsDone    = false;
                            localJob.FailCount = (localJob.FailCount ?? 0) + 1;
                            _diagnosticService.Error(exception);
                        }

                        listJobUpdated.Add(localJob);
                    }, mainCancellationTokenSource);

                    tasks.Add(t);
                }

                Task.WaitAll(tasks.ToArray(), mainCancellationTokenSource);
                _deploymentJobService.UpdateListJobs(listJobUpdated);
            }
            catch (Exception ex)
            {
                _diagnosticService.Error(ex);
            }
        }
Пример #9
0
        protected override void DoWork(object state)
        {
            var mainCancellationTokenSource = new CancellationToken();

            try
            {
                var tasks          = new List <Task>();
                var deploymentJobs = _deploymentJobService.Get(p => p.Server.Code == ServerId &&
                                                               (p.MarkToRemove ?? false) &&
                                                               !(p.IsRemoveDone ?? false)).Take(3).ToList();

                if (!deploymentJobs.Any())
                {
                    return;
                }

                var listJobUpdated = new List <DeploymentJob>();

                foreach (var job in deploymentJobs)
                {
                    var localJob = job;
                    var t        = Task.Factory.StartNew(() =>
                    {
                        //path
                        var serviceDest = localJob.Configuration.DestinationWindowServicePath;
                        var webDest     = localJob.Configuration.DestinationWebPath;
                        var webDestApi  = localJob.Configuration.DestinationWebApiPath;

                        //uninstall servie
                        if (localJob.JobType == (int)JobType.WindowService && Directory.Exists(serviceDest))
                        {
                            try
                            {
                                StopService(localJob.Configuration.ServiceName, serviceDest + @"\" + localJob.Configuration.ServiceFileName);
                                if (Directory.Exists(serviceDest))
                                {
                                    Directory.Delete(serviceDest, true);
                                }
                            }
                            catch (Exception exception)
                            {
                                _diagnosticService.Error(exception);
                            }
                        }

                        //unstall host
                        if (localJob.JobType == (int)JobType.WebApp)
                        {
                            if (!localJob.Configuration.WebDomainName.Contains("http"))
                            {
                                localJob.Configuration.WebDomainName = "http://" + localJob.Configuration.WebDomainName + "/";
                            }

                            var uri = new Uri(localJob.Configuration.WebDomainName);
                            _iisHostingHelper.RemoveHost(uri.Host);
                            if (Directory.Exists(webDest))
                            {
                                Directory.Delete(webDest, true);
                            }
                        }
                        if (localJob.JobType == (int)JobType.WebApi)
                        {
                            if (!localJob.Configuration.WebApiDomainName.Contains("http"))
                            {
                                localJob.Configuration.WebApiDomainName = "http://" + localJob.Configuration.WebApiDomainName + "/";
                            }

                            var uri = new Uri(localJob.Configuration.WebApiDomainName);
                            _iisHostingHelper.RemoveHost(uri.Host);
                            if (Directory.Exists(webDestApi))
                            {
                                Directory.Delete(webDestApi, true);
                            }
                        }

                        //delete database
                        if (localJob.JobType == (int)JobType.Database)
                        {
                            var conn   = new SqlConnection(ConfigurationManager.ConnectionStrings["MainDb"].ConnectionString);
                            var server = new Server(new ServerConnection(conn));
                            var db     = server.Databases[localJob.Configuration.DatabaseName];
                            if (db != null)
                            {
                                server.KillAllProcesses(localJob.Configuration.DatabaseName);
                                server.KillDatabase(localJob.Configuration.DatabaseName);
                                db.Drop();
                            }
                            var login = server.Logins[localJob.Configuration.DatabaseUsername];
                            if (login != null)
                            {
                                login.Drop();
                            }
                        }

                        localJob.IsCopySourceDone = false;
                        localJob.IsRemoveDone     = true;

                        listJobUpdated.Add(localJob);
                    }, mainCancellationTokenSource);

                    tasks.Add(t);
                }

                Task.WaitAll(tasks.ToArray(), mainCancellationTokenSource);
                _deploymentJobService.UpdateListJobs(listJobUpdated);
            }
            catch (Exception ex)
            {
                _diagnosticService.Error(ex);
            }
        }