public GenericCollection <ServiceOption> GetServiceOptionList(string ServiceLineID, string ServiceID)
        {
            GenericCollection <ServiceOption> ServiceOptionList = new GenericCollection <ServiceOption>();

            try
            {
                SqlParameter[] sqlparams = new SqlParameter[2];
                sqlparams[0] = new SqlParameter("@ServiceLineID", ServiceLineID);
                sqlparams[1] = new SqlParameter("@ServiceID", ServiceID);
                DataSet ds = null;
                ds = SqlHelper.ExecuteDataset(connection, CommandType.StoredProcedure, "Get_ServiceOptionList", sqlparams);
                if (ds != null)
                {
                    if (ds.Tables.Count > 0)
                    {
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            ServiceOption objBE = new ServiceOption();
                            objBE.ServiceOptionID        = Convert.ToInt32(ds.Tables[0].Rows[i]["ServiceOptionID"].ToString());
                            objBE.ServiceOptionName      = ds.Tables[0].Rows[i]["ServiceOptionName"].ToString();
                            objBE.ServiceOptionBriefDesc = ds.Tables[0].Rows[i]["ServiceOptionBriefDesc"].ToString();
                            ServiceOptionList.Add(i, objBE);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(ServiceOptionList);
        }
Beispiel #2
0
        private static void ModifyService(ServiceOption option)
        {
            string commandArgument = "start";

            switch (option)
            {
            case ServiceOption.START:
                break;

            case ServiceOption.STOP:
                commandArgument = "stop";
                break;

            default:
                return;
            }

            var process = new Process {
                StartInfo = { FileName = "net", Arguments = commandArgument + " " + SERVICE_NAME, Verb = "runas" }
            };

            //run as administrator
            process.Start();
            process.WaitForExit();
        }
Beispiel #3
0
        private static void Change(ServiceOption option)
        {
            ServiceController service = new ServiceController(SERVICE_NAME);

            ModifyService(option);
            service.WaitForStatus(option.Corresponding());
        }
Beispiel #4
0
        static async Task Main(string[] args)
        {
            var config = new ConfigurationBuilder().AddCommandLine(args)
                         .AddJsonFile("appsettings.json")
                         .Build();
            var entryAssembly      = Assembly.GetEntryAssembly();
            var executingDirectory = Path.GetDirectoryName(entryAssembly.Location);

            var userId            = config["u"];
            var password          = config["p"];
            var downloadDirectory = config["downloadDirectory"];

            var serviceOption = ServiceOption.FromConfiguration(config);
            var ffmpeg        = new Ffmpeg(Path.Combine(executingDirectory, "ffmpeg.exe"));
            var client        = new ServiceClient(serviceOption, ffmpeg);

            await client.LoginAsync(userId, password);

            var video = await client.GetVideoAsync();

            var filePath = Path.Combine(downloadDirectory, video.FileName);

            if (!File.Exists(filePath))
            {
                await video.DownloadToAsync(filePath);
            }
        }
Beispiel #5
0
        /// <summary>
        /// Convert a dto to the service option
        /// </summary>
        /// <param name="src">source dto</param>
        /// <returns></returns>
        public static ServiceOption MapDtoToServiceOption(IServiceOptionDto src)
        {
            if (src == null)
            {
                return(null);
            }

            ServiceOption serviceOption = new ServiceOption
            {
                BusinessValue           = src.BusinessValue,
                Cost                    = src.Cost,
                Description             = src.Description,
                Details                 = src.Details,
                Id                      = src.Id,
                Included                = src.Included,
                Name                    = src.Name,
                Procurement             = src.Procurement,
                Picture                 = src.Picture,
                PriceMonthly            = src.PriceMonthly,
                PriceUpFront            = src.PriceUpFront,
                PictureMimeType         = src.PictureMimeType,
                Popularity              = src.Popularity,
                ServiceOptionCategoryId = src.ServiceOptionCategoryId,
                Utilization             = src.Utilization,
                BasicRequest            = src.BasicRequest
            };

            return(serviceOption);
        }
Beispiel #6
0
        public dynamic DeleteServiceOption(int OptionID)
        {
            db.Configuration.ProxyCreationEnabled = false;
            ServiceOption findOption = db.ServiceOptions.Find(OptionID);

            findOption.Deleted = true;
            db.SaveChanges();
            return("success");
        }
 GetService <THeader, TPayload, TSignaturer, TJsonSerialization>
     (TSignaturer s, TJsonSerialization j, ServiceOption option)
     where THeader : Header
     where TPayload : Payload
     where TSignaturer : ISignaturer
     where TJsonSerialization : IJSONSerialization
 {
     return(new JwtAuthenticationService <THeader, TPayload, TSignaturer, TJsonSerialization>(s, j));
 }
Beispiel #8
0
 public ReCaptcha(
     IHttpClientFactory httpClientFactory,
     IConfiguration configuration,
     ServiceOption serviceOption,
     ILogger <ReCaptcha> logger)
 {
     httpClientFactory_ = httpClientFactory;
     configuration_     = configuration;
     serviceOption_     = serviceOption;
     logger_            = logger;
 }
Beispiel #9
0
 public dynamic AddServiceOption(ServiceOption Modell)
 {
     try
     {
         db.Configuration.ProxyCreationEnabled = false;
         db.ServiceOptions.Add(Modell);
         db.SaveChanges();
         return("success");
     }
     catch (Exception err)
     {
         return(err.Message);
     }
 }
Beispiel #10
0
 public dynamic UpdateServiceOption(ServiceOption Modell)
 {
     try
     {
         db.Configuration.ProxyCreationEnabled = false;
         ServiceOption findOption = db.ServiceOptions.Where(zz => zz.OptionID == Modell.OptionID).FirstOrDefault();
         findOption.Name     = Modell.Name;
         findOption.Duration = Modell.Duration;
         db.SaveChanges();
         return("success");
     }
     catch (Exception err)
     {
         return(err.Message);
     }
 }
Beispiel #11
0
        public static ServiceOption Inverse(this ServiceOption option)
        {
            switch (option)
            {
            case ServiceOption.STOP:
                return(ServiceOption.START);

            case ServiceOption.START:
                return(ServiceOption.STOP);

            case ServiceOption.RESTART:
                return(ServiceOption.RESTART);

            default:
                return(ServiceOption.STOP);
            }
        }
Beispiel #12
0
        private void RegisterApi(IServiceCollection services)
        {
            var serviceOption = new ServiceOption();

            Configuration.GetSection("ServiceOptions").Bind(serviceOption);

            services.AddRefitClient <IServiceApi>()
            .ConfigureHttpClient(c =>
            {
                c.BaseAddress = new Uri(serviceOption.Server);
                c.Timeout     = TimeSpan.FromSeconds(serviceOption.TimeoutSec);
                c.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue(serviceOption.Scheme, serviceOption.Token);
            })
            .SetHandlerLifetime(TimeSpan.FromMinutes(5))
            .AddPolicyHandler(GetRetryPolicy());
        }
Beispiel #13
0
        public static ServiceControllerStatus Corresponding(this ServiceOption option)
        {
            switch (option)
            {
            case ServiceOption.START:
                return(ServiceControllerStatus.Running);

            case ServiceOption.STOP:
                return(ServiceControllerStatus.Stopped);

            case ServiceOption.RESTART:
                return(ServiceControllerStatus.Running);

            default:
                return(ServiceControllerStatus.Stopped);
            }
        }
 //check config folder for .ovpn files.
 void FindAndListService()
 {
     try
     {
         string[]             serviceFiles = Directory.GetFiles(mainDir + @"\config\", "*.ovpn", SearchOption.AllDirectories);
         List <ServiceOption> serviceList  = new List <ServiceOption>();
         for (int i = 0; i < serviceFiles.Length; i++)
         {
             ServiceOption newOption = new ServiceOption(Path.GetFileName(serviceFiles[i]), serviceFiles[i]);
             serviceList.Add(newOption);
         }
         listBox1.DataSource = serviceList;
     }
     catch (DirectoryNotFoundException)
     {
         consoleTextBox.Text += @"Could not find ..\config directory" + "\r\n";
         consoleTextBox.Text += @"Place your .ovpn and .ca files in 'Main Directory'\config\" + "\r\n";
     }
 }
 public void Start(string[] args, ServiceOption option)
 {
     _serviceOption = option ?? throw new ArgumentNullException(nameof(option));
     _logService.Debug($"Service Name:{_serviceOption.ServiceName} Start");
     try
     {
         var childProc = Path.Combine(AppContext.BaseDirectory, "SampleWinFormsApp.exe");
         var processId = WindowsProcess.Start(childProc, "YanZh", true);
         _logService.Info($"Start SampleWinFormsApp.exe ==>{processId}");
     }
     catch (Win32ErrorCodeException ex)
     {
         _logService.Error($"{ex.Message}==》{ex.Win32ErrorCode}", ex);
     }
     catch (Exception ex)
     {
         _logService.Error($"{ex.Message}", ex);
     }
 }
        public void ServiceOptionRepository_AddValue()
        {
            var repo = new ServiceOptionRepository();

            var key           = "Fake";
            var serviceOption = new ServiceOption
            {
                Code    = "Fake",
                Display = "Fake"
            };

            repo.AddValue(key, serviceOption);

            var value       = repo.GetValue <ServiceOption>(key);
            var containsKey = repo.ContainsKey(key);

            Assert.IsNotNull(value);
            Assert.IsTrue(containsKey);
            Assert.AreEqual("Fake", value.Code);
        }
        public void ServiceOptionRepository_UpdateValue()
        {
            var repo = new ServiceOptionRepository();

            var key           = "ReceiveAt";
            var serviceOption = new ServiceOption
            {
                Code    = "ReceiveAt",
                Display = "Updated Receive At"
            };

            repo.UpdateValue(key, serviceOption);
            var containsKey = repo.ContainsKey(key);

            var value = repo.GetValue <ServiceOption>(key);

            Assert.IsNotNull(value);
            Assert.IsTrue(containsKey);
            Assert.AreEqual("Updated Receive At", value.Display);
        }
Beispiel #18
0
        public FeatureGateStore(
            IConfiguration configuration,
            ILogger <FeatureGateStore> logger,
            ServiceOption serviceOption,
            EventualCloudTableClient storage)
        {
            var slot       = configuration.GetDeploymentSlot().ToString().ToLower();
            var slotName   = slot.ToString().ToLower();
            var connection = configuration.GetValue <string>("SAFeatureGate");

            newGates_ = configuration.GetValue("NewFeatureGates", false);
            var storageAccount = CloudStorageAccount.Parse(connection);
            var tableClient    = TableStorageHelpers.CreateClient(storageAccount);

            Storage = storage.GetTableReference($"{slotName}Gates");
            Storage.CreateIfNotExists();
            logger_    = logger;
            rnd_       = new Random();
            GatesTable = new TableStorage(tableClient, $"{slotName}Gates", true);
            Service    = serviceOption.Service;
        }
        public static async Task RegisterAsync(
            bool isDev,
            IConfiguration configuration,
            ServiceOption serviceOption,
            IHttpClientFactory httpClientFactory)
        {
            if (isDev)
            {
                return;
            }

            string requestSafeString = Regex.Replace(serviceOption.Changeset, "\\@.*$", "");
            string uri = $"https://creypipeline.azurewebsites.net/api/deployed/{serviceOption.Service}/{configuration.GetDeploymentSlot()}/{requestSafeString}";
            // for now it is a basic registration into some function api @Baloo

            var httpClient = httpClientFactory.CreateClient();
            var res        = await httpClient.PostAsync(uri, null);

            var msg = await res.Content.ReadAsStringAsync();

            //Console.WriteLine(msg);
        }
Beispiel #20
0
        private dynamic getOptions(Service Modell)
        {
            List <dynamic> myList = new List <dynamic>();

            foreach (ServiceTypeOption Items in Modell.ServiceTypeOptions)
            {
                dynamic       newObject  = new ExpandoObject();
                ServiceOption findOption = db.ServiceOptions.Where(zz => zz.OptionID == Items.OptionID).FirstOrDefault();
                newObject.Option   = findOption.Name;
                newObject.OptionID = Items.OptionID;
                List <dynamic> ServicePrices = new List <dynamic>();
                foreach (ServicePrice PriceItem in Items.ServicePrices)
                {
                    dynamic PriceObject = new ExpandoObject();
                    PriceObject.Price = PriceItem.Price;

                    ServicePrices.Add(PriceObject);
                }
                newObject.ServicePrices = ServicePrices;
                myList.Add(newObject);
            }

            return(myList);
        }
        public void StartService()
        {
            try
            {
                p = new Process();
                ServiceOption s = (ServiceOption)listBox1.SelectedItem;
                p.StartInfo.FileName  = oVPNCat + @"\bin\openvpn.exe";
                p.StartInfo.Arguments = @"--config " + '"' + s.Value + '"' + " --management 127.0.0.1 " + defaultPort;
                consoleTextBox.Text  += p.StartInfo.Arguments + "\r\n";
                //consoleTextBox.Text += s.Ca + "\r\n";
                p.StartInfo.Verb                   = "runas";
                p.StartInfo.UseShellExecute        = false;
                p.StartInfo.CreateNoWindow         = true;
                p.StartInfo.RedirectStandardError  = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardInput  = true;

                p.OutputDataReceived += p_OutputDataReceived;
                p.ErrorDataReceived  += p_OutputDataReceived;

                p.Start();
                p.BeginErrorReadLine();
                p.BeginOutputReadLine();
                if (!oVPNWin.IsDisposed && !oVPNWin.Visible)
                {
                    oVPNWin.Visible = true;
                }
                output = p.StandardInput;
            }
            catch (Win32Exception e)
            {
                consoleTextBox.Text += "Error!" + "\r\n";
                consoleTextBox.Text += e.Message + "\r\n";
                consoleTextBox.Text += "Make sure you have a choosen the correct main directory for OpenVPN" + "\r\n";
            }
        }
Beispiel #22
0
        public async Task MigrateFeatureGatesToCosmos(
            [FromServices] EventualCloudTableClient storage,
            [FromServices] IConfiguration configuration,
            [FromServices] ServiceOption serviceOption)
        {
            // data is small and not online, so next tech is ok for this
            // also it is out of azcontext code, so just do it here
            var slot           = configuration.GetDeploymentSlot().ToString().ToLower();
            var slotName       = slot.ToString().ToLower();
            var connection     = configuration.GetValue <string>("SAFeatureGate");
            var storageAccount = CloudStorageAccount.Parse(connection);
            var tableClient    = TableStorageHelpers.CreateClient(storageAccount);
            var newTable       = storage.GetTableReference($"{slotName}Gates");
            await newTable.CreateIfNotExistsAsync();

            var gatesTable = new TableStorage(tableClient, $"{slotName}Gates", true);
            var data       = await gatesTable.ExecuteQueryAsync(new TableQuery <LegacyFeatureEntry>());

            foreach (var item in data)
            {
                var newEntry = new FeatureEntryTableEntity {
                    AllowedIPs    = item.AZAllowedIPs,
                    Continents    = item.AZContinents,
                    Countries     = item.AZCountries,
                    Description   = item.Description,
                    Disabled      = item.Disabled.ToString(),
                    PartitionKey  = item.PartitionKey,
                    Issuer        = item.Issuer,
                    ReleaseDate   = item.ReleaseDate,
                    RequiredRoles = item.AZRequiredRoles,
                    RowKey        = item.RowKey,
                    Users         = item.AZUsers,
                };
                await newTable.InsertOrMergeAsync(newEntry);
            }
        }
Beispiel #23
0
 public ProvidedService(IConfiguration configuration, ServiceOption serviceOption)
 {
     configuration_ = configuration;
     serviceOption_ = serviceOption;
 }
Beispiel #24
0
 public ServiceAttribute(ServiceOption option)
 {
     Option = option;
 }
Beispiel #25
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            ServiceOption = new ServiceOption(Configuration, IAMDefaults.SERVICE_NAME);
            services.AddSingleton(Configuration);
            ServiceOption.AddServiceOptionAccessor(services);

            services.AddSingletonCreyService <IProvidedService, ProvidedService>();
            services.AddCreyApplicationInsights(Configuration);

            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(30);
            });
            services.AddMemoryCache();

            // while we have no connection string let's use the auth.
            // to be removed after auth/iam db split.
            string dbConnectionString;
            var    isDBMigrated = Configuration.GetValue <bool>("IsDBMigrated", false);

            if (isDBMigrated)
            {
                dbConnectionString = ServiceOption.GetSqlCns();
            }
            else
            {
                dbConnectionString = GetAuthSqlConnectionStringAsync().Result;
            }

            services.AddInstrumentedDbContext <ApplicationDbContext>(ServiceOption, options =>
                                                                     options.UseSqlServer(dbConnectionString, builder => { builder.EnableRetryOnFailure(); }));
            services
            .AddDefaultIdentity <ApplicationUser>(options =>
            {
                // Password settings
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 6; // $$$ get value from config
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequiredUniqueChars    = 0;

                // Lockout settings
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(30);
                options.Lockout.MaxFailedAccessAttempts = 10;
                options.Lockout.AllowedForNewUsers      = true;

                // User settings
                options.User.AllowedUserNameCharacters += " ";
                options.User.RequireUniqueEmail         = true;

                // SignIn settings
                options.SignIn.RequireConfirmedEmail       = false;
                options.SignIn.RequireConfirmedPhoneNumber = false;
            })
            .AddSignInManager <CreySignInManager>()
            .AddRoles <IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>();
            services.AddRazorPages().AddMvcOptions(options =>
            {
                options.Filters.Add(typeof(CreyTrackingIdFilter));
                options.MaxModelValidationErrors = 50;
                options.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor(
                    _ => "Required field");
            });

            services.AddScoped <CreyTrackingIdFilter>();

            services.AddIDInfoAccessor();
            services.AddCreyRestClientFactory();
            services.AddServiceBusTopicBrokerAsync <IAccountServiceBusMessage>(Configuration).Wait();
            if (!Configuration.GetValue <bool>("CodeFirstServiceBus", false))
            {
                services.AddSingleton(new AccountMessageFactory());
            }
            services.AddServiceBusTopicSubscriberAsync <AccountMessageFactory, IAccountServiceBusMessage>(Configuration, IAMDefaults.SERVICE_NAME).Wait();
            services.AddFeatureGates();
            services.AddRateLimiting(Configuration);
            services.TryAddScoped <AnalyticsClient>();

            services.AddScopedCreyServiceInternal <RegistrationHandler>();
            services.AddScoped <AfterRegistrationHandler>();
            services.AddScopedCreyServiceInternal <SessionRepository>();
            services.AddScopedCreyServiceInternal <AccountRepository>();
            services.AddScopedCreyServiceInternal <SessionTokenRepository>();
            services.AddScopedCreyServiceInternal <SingleAccessKeyRepository>();
            services.AddScopedCreyServiceInternal <PersistentTokenRepository>();
            services.AddScopedCreyServiceInternal <EmailSender>();
            services.AddScopedCreyServiceInternal <OAuthRepository>();
            services.AddScoped <SignatureFlowService>();

            services.AddReCaptcha();
            services.AddCreyModeratorClient();
            services.TryAddSingleton(serviceProvider => new MandrillApi(Configuration.GetValue <string>("MandrillCns")));

            services.AddKenticoClient();

            services.AddScopedCreyServiceInternal <GeoLocationQuery>();
            services.AddScopedCreyServiceInternal <FeatureManagerRepository>();

            services.AddCreySwagger("iam", Configuration.GetDeploymentSlot());

            services.ConfigureApplicationCookie(options =>
            {
                options.ForwardDefaultSelector = ctx => SessionCookieAuthenticationDefaults.AuthenticationScheme;
            });

            AddDataProtectionAsync(services, Configuration).Wait();

            services
            .AddCreyClientAuthenticationAndAuthorization(Configuration, new SessionCookieOptions(
                                                             new IdentityToSessionCookieAuthenticationEvents(),
                                                             IdentityConstants.ApplicationScheme,
                                                             "/Identity/Account/Login",
                                                             "/Identity/Account/Logout"
                                                             ))
            .AddFacebook(facebookOptions =>
            {
                facebookOptions.AppId     = Configuration.GetValue <string>("Facebook:AppId");
                facebookOptions.AppSecret = Configuration.GetValue <string>("Facebook:AppSecret");
                facebookOptions.Events.OnRemoteFailure = HandleRemoteFailure;
            })
            .AddGoogle(googleOptions =>
            {
                googleOptions.ClientId               = Configuration.GetValue <string>("Google:ClientId");
                googleOptions.ClientSecret           = Configuration.GetValue <string>("Google:ClientSecret");
                googleOptions.Events.OnRemoteFailure = HandleRemoteFailure;
            });
            services.EnableCreyCors(Configuration);
        }
        //check config folder for .ovpn files.
        void FindAndListService()
        {
            try
            {
                string[] serviceFiles = Directory.GetFiles(mainDir + @"\config\", "*.ovpn", SearchOption.AllDirectories);
                List<ServiceOption> serviceList = new List<ServiceOption>();
                for (int i = 0; i < serviceFiles.Length; i++)
                {
                    ServiceOption newOption = new ServiceOption(Path.GetFileName(serviceFiles[i]), serviceFiles[i]);
                    serviceList.Add(newOption);
                }
                listBox1.DataSource = serviceList;

            }
            catch(DirectoryNotFoundException)
            {
                consoleTextBox.Text += @"Could not find ..\config directory"+"\r\n";
                consoleTextBox.Text += @"Place your .ovpn and .ca files in 'Main Directory'\config\"+"\r\n";
            }
        }
Beispiel #27
0
 public RecursiveExecutionService(ILogger <RecursiveExecutionService> logger, ServiceOption serviceOption)
 {
     _logger        = logger ?? throw new ArgumentNullException(nameof(logger));
     _serviceOption = serviceOption ?? throw new ArgumentNullException(nameof(serviceOption));
 }
Beispiel #28
0
        public static void Prompt(string[] args)
        {
            ServiceController       service = new ServiceController(SERVICE_NAME);
            ServiceControllerStatus status  = service.Status;


            ServiceOption option = ServiceOption.START;

            string input = "";

            if (args.Length != 0)
            {
                input = args[0];
            }

            bool optionSelected = false;

            while (!optionSelected)
            {
                switch (input)
                {
                case "r":
                    option         = ServiceOption.RESTART;
                    optionSelected = true;
                    break;

                case "s":
                    option         = ServiceOption.STOP;
                    optionSelected = true;
                    break;

                case "t":
                    option         = ServiceOption.START;
                    optionSelected = true;
                    break;

                case "q":
                    Console.WriteLine("Quitting...");
                    optionSelected = true;
                    return;

                default:
                    Console.WriteLine("The " + service.DisplayName + " is currently: " + service.Status);
                    Console.Write("Do you want to Stop(s), Start(t), Restart(r) the Service? OR Quit(q): ");
                    input = Console.ReadLine().ToLower();
                    // Console.WriteLine("The input: " + input + " is not a valid option.");
                    break;
                }
            }

            Console.WriteLine("You selected: " + option);

            if (option == ServiceOption.RESTART)
            {
                if (status == ServiceControllerStatus.Running)
                {
                    Change(ServiceOption.STOP);
                    service.WaitForStatus(ServiceControllerStatus.Stopped);
                    Change(ServiceOption.START);
                    Console.WriteLine("The Service has been restarted.");
                }
                else
                {
                    Console.WriteLine("The Service is not running so cannot be restarted.");
                }
            }

            if (option == ServiceOption.STOP)
            {
                if (status == ServiceControllerStatus.Running)
                {
                    Change(option);
                    Console.WriteLine("The service was stopped successfully");
                }
                else
                {
                    Console.WriteLine("The Service was already stopped.");
                }
            }

            if (option == ServiceOption.START)
            {
                if (status == ServiceControllerStatus.Stopped)
                {
                    Change(option);
                    Console.WriteLine("The service was started successfully.");
                }
                else
                {
                    Console.WriteLine("The service was already running.");
                }
            }

            Thread.Sleep(3000);
        }
Beispiel #29
0
        /// <summary>
        /// Creates the options metadata available for restore operations
        /// </summary>
        /// <returns></returns>
        public static ServiceOption[] CreateRestoreOptions()
        {
            ServiceOption[] options = new ServiceOption[]
            {
                new ServiceOption
                {
                    Name         = RestoreOptionsHelper.KeepReplication,
                    DisplayName  = "Keep Replication",
                    Description  = "Preserve the replication settings (WITH KEEP_REPLICATION)",
                    ValueType    = ServiceOption.ValueTypeBoolean,
                    IsRequired   = false,
                    GroupName    = "Restore options",
                    DefaultValue = "false"
                },
                new ServiceOption
                {
                    Name         = RestoreOptionsHelper.ReplaceDatabase,
                    DisplayName  = "ReplaceDatabase",
                    Description  = "Overwrite the existing database (WITH REPLACE)",
                    ValueType    = ServiceOption.ValueTypeBoolean,
                    IsRequired   = false,
                    GroupName    = "Restore options",
                    DefaultValue = "false"
                },
                new ServiceOption
                {
                    Name         = RestoreOptionsHelper.SetRestrictedUser,
                    DisplayName  = "SetRestrictedUser",
                    Description  = "Restrict access to the restored database (WITH RESTRICTED_USER)",
                    ValueType    = ServiceOption.ValueTypeBoolean,
                    IsRequired   = false,
                    GroupName    = "Restore options",
                    DefaultValue = "false"
                },
                new ServiceOption
                {
                    Name           = RestoreOptionsHelper.RecoveryState,
                    DisplayName    = "Recovery State",
                    Description    = "Recovery State",
                    ValueType      = ServiceOption.ValueTypeCategory,
                    IsRequired     = false,
                    GroupName      = "Restore options",
                    CategoryValues = new CategoryValue[]
                    {
                        new CategoryValue
                        {
                            Name        = "WithRecovery",
                            DisplayName = "RESTORE WITH RECOVERTY"
                        },
                        new CategoryValue
                        {
                            Name        = "WithNoRecovery",
                            DisplayName = "RESTORE WITH NORECOVERTY"
                        },
                        new CategoryValue
                        {
                            Name        = "WithStandBy",
                            DisplayName = "RESTORE WITH STANDBY"
                        }
                    },
                    DefaultValue = "WithRecovery"
                },
                new ServiceOption
                {
                    Name        = RestoreOptionsHelper.StandbyFile,
                    DisplayName = "Standby file",
                    Description = "Standby file",
                    ValueType   = ServiceOption.ValueTypeString,
                    IsRequired  = false,
                    GroupName   = "Restore options"
                },
                new ServiceOption
                {
                    Name         = RestoreOptionsHelper.BackupTailLog,
                    DisplayName  = "Backup Tail Log",
                    Description  = "Take tail-log backup before restore",
                    ValueType    = ServiceOption.ValueTypeBoolean,
                    IsRequired   = false,
                    DefaultValue = "true",
                    GroupName    = "Tail-Log backup"
                },
                new ServiceOption
                {
                    Name         = RestoreOptionsHelper.BackupTailLog,
                    DisplayName  = "Backup Tail Log",
                    Description  = "Take tail-log backup before restore",
                    ValueType    = ServiceOption.ValueTypeBoolean,
                    IsRequired   = false,
                    DefaultValue = "true",
                    GroupName    = "Tail-Log backup"
                },
                new ServiceOption
                {
                    Name        = RestoreOptionsHelper.TailLogBackupFile,
                    DisplayName = "Tail Log Backup File",
                    Description = "Tail Log Backup File",
                    ValueType   = ServiceOption.ValueTypeString,
                    IsRequired  = false,
                    GroupName   = "Tail-Log backup"
                },
                new ServiceOption
                {
                    Name        = RestoreOptionsHelper.TailLogWithNoRecovery,
                    DisplayName = "Tail Log With NoRecovery",
                    Description = "Leave source database in the restoring state(WITH NORECOVERTY)",
                    ValueType   = ServiceOption.ValueTypeBoolean,
                    IsRequired  = false,
                    GroupName   = "Tail-Log backup"
                },
                new ServiceOption
                {
                    Name        = RestoreOptionsHelper.CloseExistingConnections,
                    DisplayName = "Close Existing Connections",
                    Description = "Close existing connections to destination database",
                    ValueType   = ServiceOption.ValueTypeBoolean,
                    IsRequired  = false,
                    GroupName   = "Server connections"
                },
                new ServiceOption
                {
                    Name         = RestoreOptionsHelper.RelocateDbFiles,
                    DisplayName  = "Relocate all files",
                    Description  = "Relocate all files",
                    ValueType    = ServiceOption.ValueTypeBoolean,
                    IsRequired   = false,
                    GroupName    = "Restore database files as",
                    DefaultValue = "false"
                },
                new ServiceOption
                {
                    Name        = RestoreOptionsHelper.DataFileFolder,
                    DisplayName = "Data file folder",
                    Description = "Data file folder",
                    ValueType   = ServiceOption.ValueTypeString,
                    IsRequired  = false,
                    GroupName   = "Restore database files as"
                },
                new ServiceOption
                {
                    Name        = RestoreOptionsHelper.LogFileFolder,
                    DisplayName = "Log file folder",
                    Description = "Log file folder",
                    ValueType   = ServiceOption.ValueTypeString,
                    IsRequired  = false,
                    GroupName   = "Restore database files as"
                }
            };

            return(options);
        }
        internal void AddServiceOptions()
        {
            var dbContext = new CorierServiceContext();

            var servOption1 = new ServiceOption()
            {
                Weight       = 5,
                Price        = 8.99m,
                TimeDuration = 3,
                ServicesType = dbContext.ServicesTypes.Find(1)
            };

            var servOption2 = new ServiceOption()
            {
                Weight       = 10,
                Price        = 15.60m,
                TimeDuration = 3,
                ServicesType = dbContext.ServicesTypes.Find(1)
            };

            var servOption3 = new ServiceOption()
            {
                Weight       = 15,
                Price        = 22.30m,
                TimeDuration = 3,
                ServicesType = dbContext.ServicesTypes.Find(1)
            };

            var servOption4 = new ServiceOption()
            {
                Weight       = 5,
                Price        = 16.30m,
                TimeDuration = 2,
                ServicesType = dbContext.ServicesTypes.Find(2)
            };

            var servOption5 = new ServiceOption()
            {
                Weight       = 10,
                Price        = 34.80m,
                TimeDuration = 2,
                ServicesType = dbContext.ServicesTypes.Find(2)
            };

            var servOption6 = new ServiceOption()
            {
                Weight       = 15,
                Price        = 60.28m,
                TimeDuration = 1,
                ServicesType = dbContext.ServicesTypes.Find(2)
            };

            var servOption7 = new ServiceOption()
            {
                Weight       = 5,
                Price        = 7.80m,
                TimeDuration = 5,
                ServicesType = dbContext.ServicesTypes.Find(3)
            };

            var servOption8 = new ServiceOption()
            {
                Weight       = 10,
                Price        = 11.20m,
                TimeDuration = 5,
                ServicesType = dbContext.ServicesTypes.Find(3)
            };

            var servOption9 = new ServiceOption()
            {
                Weight       = 15,
                Price        = 18.46m,
                TimeDuration = 5,
                ServicesType = dbContext.ServicesTypes.Find(3)
            };

            dbContext.ServiceOptions.Add(servOption1);
            dbContext.ServiceOptions.Add(servOption2);
            dbContext.ServiceOptions.Add(servOption3);
            dbContext.ServiceOptions.Add(servOption4);
            dbContext.ServiceOptions.Add(servOption5);
            dbContext.ServiceOptions.Add(servOption6);
            dbContext.ServiceOptions.Add(servOption7);
            dbContext.ServiceOptions.Add(servOption8);
            dbContext.ServiceOptions.Add(servOption9);

            dbContext.SaveChanges();
        }