public async Task AppSettingsManager_DecimalAsync_NoEncryption()
        {
            for (var i = 0; i < _TestRandomRound; i++)
            {
                var randomKey   = Generator.RandomString();
                var randomValue = Generator.RandomDecimal();

                Assert.Null(await AppSettingsManager.GetDecimalAsync(randomKey));

                Assert.True(await AppSettingsManager.SetDecimalAsync(randomKey, randomValue));

                Assert.Equal(randomValue, await AppSettingsManager.GetDecimalAsync(randomKey));
            }
        }
        public void AppSettingsManager_String_GotEncryption()
        {
            for (var i = 0; i < _TestRandomRound; i++)
            {
                var randomKey   = Generator.RandomString();
                var randomValue = Generator.RandomString();

                Assert.Null(AppSettingsManager.GetString(randomKey, true));

                Assert.True(AppSettingsManager.SetString(randomKey, randomValue, true));

                Assert.Equal(randomValue, AppSettingsManager.GetString(randomKey, true));
            }
        }
        public async Task AppSettingsManager_BooleanAsync_GotEncryption()
        {
            for (var i = 0; i < _TestRandomRound; i++)
            {
                var randomKey   = Generator.RandomString();
                var randomValue = Generator.RandomBoolean();

                Assert.Null(await AppSettingsManager.GetBooleanAsync(randomKey, true));

                Assert.True(await AppSettingsManager.SetBooleanAsync(randomKey, randomValue, true));

                Assert.Equal(randomValue, await AppSettingsManager.GetBooleanAsync(randomKey, true));
            }
        }
        static AppSettingsManagerTests_ProtocolBufferProvider_NotDefaultLocation()
        {
            ProtocolBufferConfiguration.Location = ".\\settings-alt.bin";

            if (File.Exists(ProtocolBufferConfiguration.Location))
            {
                File.Delete(ProtocolBufferConfiguration.Location);
            }

            Engine.Unregister <IAppSettingsProvider>();
            Engine.Register <IAppSettingsProvider, ProtocolBufferProvider>();
            ProtocolBufferConfiguration.EncryptionKeyPair = EncryptionManager.Aes.GenerateKeyPair();
            AppSettingsManager.ResetProvider();
        }
예제 #5
0
        /// <summary>
        /// The InitFactory.
        /// </summary>
        public void InitFactory()
        {
            if (_factory == null)
            {
                var host               = AppSettingsManager.Get("MQSetting:Host");
                var port               = AppSettingsManager.Get("MQSetting:Port");
                var userName           = AppSettingsManager.Get("MQSetting:UserName");
                var password           = AppSettingsManager.Get("MQSetting:Password");
                var requestedHeartbeat = AppSettingsManager.Get("MQSetting:RequestedHeartbeat");
                var mqUri              = AppSettingsManager.Get("MQSetting:MQUri");
                var sslUril            = AppSettingsManager.Get("MQSetting:SSLUri");

                _factory = new ConnectionFactory()
                {
                    HostName = host,
                    Port     = Convert.ToInt32(port),
                    UserName = userName,
                    Password = password,
                    //Endpoint = new AmqpTcpEndpoint(new Uri(host)),
                };

                if (!string.IsNullOrWhiteSpace(requestedHeartbeat))
                {
                    _factory.RequestedHeartbeat = (ushort)Convert.ToInt32(requestedHeartbeat);
                }
                if (!string.IsNullOrWhiteSpace(mqUri))
                {
                    _factory.Uri = new Uri(mqUri);
                }

                // connection
                if (_connection == null || !_connection.IsOpen)
                {
                    _connection = _factory.CreateConnection();
                    _connection.ConnectionShutdown += (sender, args) =>
                    {
                        try
                        {
                            //清除连接及频道
                            CleanupResource();
                            _logger.LogWarning($"mq连接已停止,占用资源已释放");
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(exception: ex, "尝试连接RabbitMQ服务器出现错误");
                        }
                    };
                }
            }
        }
예제 #6
0
 protected override void OnLoad(EventArgs e)
 {
     base.OnLoad(e);
     if (!Presenter.AppConfigExists())
     {
         SetInstallationPathForm installationPathForm = new SetInstallationPathForm(styleManager);
         if (installationPathForm.ShowDialog() == DialogResult.OK)
         {
             Presenter.InitializeAppConfig(installationPathForm.InstallationPath);
         }
     }
     Presenter.LoadSettings();
     ReloadStyles(AppSettingsManager.IsDarkMode());
     Presenter.LoadScripts();
 }
예제 #7
0
        public void Emit(LogEvent logEvent)
        {
            if (logEvent.Level >= AppSettingsManager.GetConsoleMinLogLevel())
            {
                var        t   = logEvent.Timestamp;
                LogMessage msg = new LogMessage()
                {
                    Text      = logEvent.RenderMessage(),
                    Lvl       = logEvent.Level,
                    TimeStamp = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.fff") + " -" + t.Offset.ToString(@"hh\:mm"),
                    Exception = logEvent.Exception
                };

                LogEmitted?.Invoke(msg);
            }
        }
예제 #8
0
        public override string GetConnectionString()
        {
            if (_serviceProvider == null)
            {
                string str = AppSettingsManager.Get("OSharp:DbContexts:MySql:ConnectionString");
                return(str);
            }
            OSharpOptions          options        = _serviceProvider.GetOSharpOptions();
            OSharpDbContextOptions contextOptions = options.GetDbContextOptions(typeof(DefaultDbContext));

            if (contextOptions == null)
            {
                throw new OsharpException($"上下文“{typeof(DefaultDbContext)}”的配置信息不存在");
            }
            return(contextOptions.ConnectionString);
        }
예제 #9
0
        static void DBStringTest()
        {
            string str = "Server = myServerAddress;Database = myDataBase;User ID = myUsername;Password = myPassword;Trusted_Connection = False;";

            str = AppSettingsManager.BuildDBConnString(str);
            Console.WriteLine("db string = {0}", str);

            str = "Data Source=10.1.20.57;Initial Catalog=EStandardAccountLog_V3;persist security info=True;MultipleActiveResultSets=true;user id=Finance_Admin;password=Finance_AdminAdmin;Max Pool Size=512;";
            str = AppSettingsManager.BuildDBConnString(str);
            Console.WriteLine("db string = {0}", str);

            str = "metadata=res://*/PortalModel.CreditPotal.csdl|res://*/PortalModel.CreditPotal.ssdl|res://*/PortalModel.CreditPotal.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=10.1.20.126;initial catalog=CreditFront;persist security info=True;user id=Finance_Admin;password=Finance_AdminAdmin;MultipleActiveResultSets=True;Max Pool Size=512&quot;";
            str = AppSettingsManager.BuildDBConnString(str);
            Console.WriteLine("db string = {0}", str);
            Console.WriteLine();
        }
예제 #10
0
        public void IsValid_Given_Correct_Parameters_When_IsValid_Then_ReturnTrue_Test()
        {
            //given
            IOptions <AppSettings> appSettings        = Options.Create(new AppSettings());
            IAppSettingsManager    appSettingsManager = new AppSettingsManager(appSettings);
            var fieldFilters = new List <FieldFilter>()
            {
                new FieldFilter("Latitude", "99.452"), new FieldFilter("Longitude", "35.3333")
            };
            //when
            IQueryBuilder queryBuilder = new WithinQueryBuilder(appSettingsManager);
            bool          result       = queryBuilder.IsValid(fieldFilters);

            //then
            result.Should().BeTrue();
        }
예제 #11
0
        public void IsValid_Given_Only_Latitude_When_IsValid_Then_ReturnFalse_Test()
        {
            //given
            IOptions <AppSettings> appSettings        = Options.Create(new AppSettings());
            IAppSettingsManager    appSettingsManager = new AppSettingsManager(appSettings);
            var fieldFilters = new List <FieldFilter>()
            {
                new FieldFilter("Latitude", "99.452")
            };
            //when
            IQueryBuilder queryBuilder = new WithinQueryBuilder(appSettingsManager);
            bool          result       = queryBuilder.IsValid(fieldFilters);

            //then
            result.Should().BeFalse();
        }
예제 #12
0
        public void LoadApplications(String working_dir_p)
        {
            app_settings_manager_l = new AppSettingsManager(working_dir_p, ApplicatoinItems);
            app_settings_manager_l.LoadAppItems();

            for (int count = 0; count < app_settings_manager_l.AppItems.Count; count++)
            {
                AppItem temp_app_item = app_settings_manager_l.AppItems[count];

                AddApplicationItemToList(temp_app_item);
            }

            foreach (AppListBoxItem app_list_box_item in ApplicatoinItems)
            {
                LaunchApplication(app_list_box_item.AppPath, app_list_box_item.AppItemData.AppArgs);
            }
        }
        public async Task AppSettingsManager_EnumAsync_NoEncryption()
        {
            for (var i = 0; i < _TestRandomRound; i++)
            {
                var randomKey          = Generator.RandomString();
                var randomDefaultValue = (EnumGender)Generator.RandomInt(0, Enum.GetValues(typeof(EnumGender))
                                                                         .Length);
                var randomValue = (EnumGender)Generator.RandomInt(0, Enum.GetValues(typeof(EnumGender))
                                                                  .Length);

                Assert.Equal(randomDefaultValue, await AppSettingsManager.GetEnumAsync(randomKey, randomDefaultValue));

                Assert.True(await AppSettingsManager.SetEnumAsync(randomKey, randomValue));

                Assert.Equal(randomValue, await AppSettingsManager.GetEnumAsync(randomKey, randomDefaultValue));
            }
        }
        public void AppSettingsManager_Enum_GotEncryption()
        {
            for (var i = 0; i < _TestRandomRound; i++)
            {
                var randomKey          = Generator.RandomString();
                var randomDefaultValue = (EnumGender)Generator.RandomInt(0, Enum.GetValues(typeof(EnumGender))
                                                                         .Length);
                var randomValue = (EnumGender)Generator.RandomInt(0, Enum.GetValues(typeof(EnumGender))
                                                                  .Length);

                Assert.Equal(randomDefaultValue, AppSettingsManager.GetEnum(randomKey, randomDefaultValue, true));

                Assert.True(AppSettingsManager.SetEnum(randomKey, randomValue, true));

                Assert.Equal(randomValue, AppSettingsManager.GetEnum(randomKey, randomDefaultValue, true));
            }
        }
예제 #15
0
        public string ToArtifact(object value, PropertyType propertyType, ICollection <ArtifactDependency> dependencies)
        {
            if (AppSettingsManager.GetDisableUmbracoCloudSync())
            {
                return(null);
            }

            var svalue = value as string;

            if (string.IsNullOrWhiteSpace(svalue) || !svalue.DetectIsJson())
            {
                return(svalue);
            }

            var rootLinks = ParseLinks(JArray.Parse(svalue), dependencies);

            return(rootLinks.ToString(Formatting.None));
        }
예제 #16
0
        public static void InstanceLogger()
        {
            _consoleLogSink = new LogSink();
            _levelSwitch    = new LoggingLevelSwitch(AppSettingsManager.GetFileMinLogLevel());
            string baseDirectory = AppSettingsManager.GetAppConfigDirectory();

            CreateLogDirectory(baseDirectory);
            var loggerConfiguration = new LoggerConfiguration()
                                      .MinimumLevel.ControlledBy(_levelSwitch)
                                      .MinimumLevel.Override(QUARTZ_SERILOG, LogEventLevel.Warning)
                                      .MinimumLevel.Override(MICROSOFT_SERILOG, LogEventLevel.Warning);

            loggerConfiguration
            .WriteTo.Console()
            .WriteTo.File(Path.Combine(baseDirectory, LOG_FOLDER, LOG_FILE_NAME))
            .WriteTo.Sink(_consoleLogSink);

            Log.Logger = loggerConfiguration.CreateLogger();
        }
예제 #17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceCollection ConfigureServicesSlime(IServiceCollection services)
        {
            services.AddDbContext <SlimeDbContext>(options =>
                                                   options.UseSqlServer(
                                                       Configuration.GetConnectionString("DefaultConnection")));
            services.AddIdentity <ApplicationUser, ApplicationRole>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores <SlimeDbContext>()
            .AddDefaultTokenProviders();
            services.AddMvcCore().AddControllersAsServices()
            .AddRazorPages();
            //services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
            //  .AddEntityFrameworkStores<SlimeDbContext>();
            //this.extensionsPath = Path.Combine(hostingEnvironment.ContentRootPath, configuration["Extensions:Path"]);


            this.extensionsPath = Path.Combine(FileSystemManager.GetAppRootBinaryFolderAbsolutePath(), AppSettingsManager.GetExtetionPath());

            //Configuration["Extensions:Path"];
            if (string.IsNullOrWhiteSpace(extensionsPath) == false)
            {
                services.AddExtCore(this.extensionsPath);
            }
            services.Configure <StorageContextOptions>(options =>
            {
                // options.MigrationsAssembly = typeof(DesignTimeStorageContextFactory).GetTypeInfo().Assembly.FullName;
            });
            services.AddScoped <IStorageContext, SlimeDbContext>();
            //services.AddSingleton<IStorageContext, SlimeDbContext>();
            //   DesignTimeStorageContextFactory.Initialize(services.BuildServiceProvider());

            services.AddSingleton <IEmailSender, EmailSender>();
            Direcotrybrowse = AppSettingsManager.GetAllowDirectoryBrowseSetting();
            if (Direcotrybrowse)
            {
                services.AddDirectoryBrowser();
            }

            services.Configure <KestrelServerOptions>(
                Configuration.GetSection("Kestrel"));

            return(services);
        }
예제 #18
0
        public void Build_Given_Correct_Parameters_When_Build_Then_ReturnCorrectQuery_Test()
        {
            //given
            const string           query       = "within_circle(location, 37.7678524427181, -122.416104892532, 500)";
            IOptions <AppSettings> appSettings = Options.Create(new AppSettings()
            {
                RadiusOfCentralCoordinateInMeters = 500
            });
            IAppSettingsManager appSettingsManager = new AppSettingsManager(appSettings);
            var fieldFilters = new List <FieldFilter>()
            {
                new FieldFilter("Latitude", "37.7678524427181"), new FieldFilter("Longitude", "-122.416104892532")
            };
            //when
            IQueryBuilder queryBuilder = new WithinQueryBuilder(appSettingsManager);
            string        result       = queryBuilder.Build(fieldFilters);

            //then
            result.Should().Be(query);
        }
        public bool SetAppToRunAtStartup()
        {
            string exePath = Path.Combine(AppSettingsManager.GetProjectInstallationPath(), APP_EXE_NAME);
            string args    = APP_HIDE_ARG;
            bool   result  = true;

            try
            {
                Registry.SetValue(WINDOWS_REGISTRY_STARTUP_PATH,
                                  WINDOWS_REGISTRY_STARTUP_KEY,
                                  exePath + " " + args);
            }
            catch (Exception e)
            {
                Log.Error(e, "Error while saving the windows registry.");
                result = false;
            }

            return(result);
        }
예제 #20
0
        public async Task <AntiCaptchaResultJson> CheckStatus(int taskId)
        {
            var getTask = "{\"clientKey\":\"" + AppSettingsManager.GetAntiCaptchaKey() + "\",\"taskId\": " + taskId + "}";

            try
            {
                var result = await httpClient.PostAsync("https://api.anti-captcha.com/getTaskResult", new StringContent(getTask, Encoding.UTF8, "application/json"));

                var resultString = await result.Content.ReadAsStringAsync();

                return(JsonConvert.DeserializeObject <AntiCaptchaResultJson>(resultString));
            }
            catch (Exception e)
            {
                return(new AntiCaptchaResultJson()
                {
                    errorId = 999, errorDescription = e.Message
                });
            }
        }
예제 #21
0
        private static JArray ParseLinks(JArray links, ICollection <ArtifactDependency> dependencies)
        {
            foreach (var link in links)
            {
                if (!AppSettingsManager.GetDisableUmbracoCloudDependencySync())
                {
                    var validUdi = GuidUdi.TryParse(link.Value <string>("udi"), out var guidUdi);
                    if (validUdi)
                    {
                        dependencies.Add(new ArtifactDependency(guidUdi, false, ArtifactDependencyMode.Exist));
                    }
                }

                var children = link.Value <JArray>("children");
                if (children != null)
                {
                    link["children"] = ParseLinks(children, dependencies);
                }
            }

            return(links);
        }
예제 #22
0
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext == null || actionContext.Request == null)
            {
                return;
            }

            try
            {
                Log = new LogApi();
                Log.Watch.Start();

                Log.ServiceDescription   = AppSettingsManager.Get <string>(AppSettingsConstants.KEY_SERVICE_DESCRIPTION);
                Log.FromHost             = GetCLientIpAddress(actionContext.Request);
                Log.OperationDescription = GetOperation(actionContext);
                Log.Request    = GetRequestString(actionContext);
                Log.ToEndPoint = GetServiceEndPoint(actionContext);
            }
            catch (Exception)
            {
            }
        }
예제 #23
0
        /// <summary>
        /// Sets up the database connection and migration engine
        /// </summary>
        private void SetupDatabaseConnection()
        {
            // read all settings from the db
            var settings = AppSettingsManager.ReadAllSettings();

            try
            {
                // Create the connection.
                DatabaseSession.Instance.CreateConnector(settings["dbhost"], settings["dbport"], settings["dbname"], settings["dbuser"], settings["dbpassword"]);
            }
            catch (Exception ex)
            {
                throw new HttpRequestException(string.Format("The connection to database could not be made: {0}", ex.Message));
            }

#if DEBUG
            // when debugging reset the full database
            MigrationEngine.Reset();
#endif
            // perform the migration
            MigrationEngine.Migrate();
        }
예제 #24
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //return View();



            //
            base.ConfigureSlime(app, env);
            bool errorshowing = AppSettingsManager.GetForceErrorShowingSetting();

            if (env.IsDevelopment() || errorshowing == true)
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            //app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();


            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }
예제 #25
0
        public async Task <AntiCaptchaResultJson> PrepareAntiCaptchaAsync()
        {
            var proxy = GetProxy();


            var createTask = JsonConvert.SerializeObject(new AntiCaptchaCreateTaskJson()
            {
                clientKey = AppSettingsManager.GetAntiCaptchaKey(),
                task      = new AntiCaptchaCreateTaskJson.Task()
                {
                    type             = "FunCaptchaTask",
                    websiteURL       = WebsiteURL,
                    websitePublicKey = WebsiteKey,
                    proxyType        = "http",
                    proxyAddress     = proxy.Split(':')[0],
                    proxyPort        = int.Parse(proxy.Split(':')[1]),
                    proxyLogin       = proxy.Split(':')[2],
                    proxyPassword    = proxy.Split(':')[3],
                    userAgent        = HttpClientEx.UserAgent
                }
            });

            try
            {
                var result = await httpClient.PostAsync("https://api.anti-captcha.com/createTask", new StringContent(createTask, Encoding.UTF8, "application/json"));

                var resultString = await result.Content.ReadAsStringAsync();

                return(JsonConvert.DeserializeObject <AntiCaptchaResultJson>(resultString));
            }
            catch (Exception e)
            {
                return(new AntiCaptchaResultJson()
                {
                    errorCode = "999", errorDescription = e.Message
                });
            }
        }
예제 #26
0
 private void ValidateRecentListToolStripMenuItem_Click(object sender, EventArgs e)
 {
     AppSettingsManager.ValidateRecentList();
     PopulateRecentList();
 }
예제 #27
0
        public MainForm(string filename)
        {
            InitializeComponent();

            // For performance https://stackoverflow.com/questions/4255148/how-to-improve-painting-performance-of-datagridview
            grdResult.DoubleBuffered(true);

            _synchronizationContext = SynchronizationContext.Current;

            _codeCompletion = new SqlCodeCompletion(txtSql, imgCodeCompletion);

            if (string.IsNullOrWhiteSpace(filename))
            {
                Disconnect();
            }
            else
            {
                Connect(new ConnectionString(filename));
            }

            txtSql.ActiveTextAreaControl.TextArea.Caret.PositionChanged += (s, e) =>
            {
                if (ActiveTask == null)
                {
                    return;
                }

                ActiveTask.EditorContent = txtSql.Text;
                ActiveTask.SelectedTab   = tabResult.SelectedTab.Name;
                ActiveTask.Position      = new Tuple <int, int>(txtSql.ActiveTextAreaControl.TextArea.Caret.Line,
                                                                txtSql.ActiveTextAreaControl.TextArea.Caret.Column);

                lblCursor.Text =
                    $"Line: {txtSql.ActiveTextAreaControl.Caret.Line + 1} - Column: {txtSql.ActiveTextAreaControl.Caret.Column + 1}";
            };

            // stop all threads
            FormClosing += (s, e) =>
            {
                if (_db != null)
                {
                    Disconnect();
                }
            };

            // set assembly version on window title
            Text += $" (v{typeof(MainForm).Assembly.GetName().Version})";

            // load last db

            if (AppSettingsManager.ApplicationSettings.LoadLastDbOnStartup && AppSettingsManager.IsLastDbExist())
            {
                Connect(AppSettingsManager.ApplicationSettings.LastConnectionStrings);
            }


            // validate recent list
            AppSettingsManager.ValidateRecentList();


            // populate recent db list
            PopulateRecentList();
        }
예제 #28
0
        public void WikiToArticle()
        {
            ClearData();

            //初始化Freesql.wiki中的数据到article
            string docpath = AppSettingsManager.Get($"PathConfig:InitDocFiles"); // "E:\\GitHub\\FreeSqlCms\\src\\FsCms.Web\\wwwroot\\file\\FreeSql.wiki";

            List <dynamic> rows = new List <dynamic>();

            //判断文件夹是否存在
            if (System.IO.Directory.Exists(docpath))
            {
                string[] alllines = System.IO.File.ReadAllLines(docpath + "/_Sidebar.md");
                for (int i = 0; i < alllines.Length; i++)
                {
                    var row = alllines[i];
                    //判断row的类型  文章还是分类
                    if (row.IndexOf("##") != -1)
                    {
                        var typename = row.Replace("##", "").Trim();
                        rows.Add(new
                        {
                            title    = typename,
                            datatype = 1,
                            level    = 1,
                            url      = "",
                            row      = row
                        });
                    }
                    else if (row.IndexOf("* ") != -1)
                    {
                        var   trimCount = alllines[i].Length - alllines[i].TrimStart().Length;
                        Regex rg        = new Regex(@"(?i)(?<=\[)(.*)(?=\])");
                        var   filename  = rg.Match(alllines[i]).Value;
                        var   url       = "";

                        if (string.IsNullOrEmpty(filename))
                        {
                            //filename = alllines[i].Trim('#').Trim().Trim('*').Trim();
                            filename = row.TrimStart('*').Trim();
                        }
                        else
                        {
                            url = Regex.Replace(alllines[i], @"(.*\()(.*)(\).*)", "$2");
                            int startIndex = url.IndexOf("/FreeSql/wiki/");
                            if (startIndex != -1)
                            {
                                url = url.Substring(startIndex, url.Length - startIndex).Replace("/FreeSql/wiki/", "/FreeSql.wiki/");
                            }
                        }
                        if (url == "")
                        {
                            rows.Add(new { title = filename, datatype = 2, level = Convert.ToInt32(trimCount / 4) + 1, url = "", row = row });
                        }
                        else
                        {
                            rows.Add(new { title = filename, datatype = 3, level = Convert.ToInt32(trimCount / 4) + 1, url = url, row = row });
                        }
                    }
                }
            }
            else
            {
                throw new Exception("配置文件不存在" + docpath);
            }

            long currTypeID = 0;
            int  sortno     = 0;

            foreach (var item in rows)
            {
                sortno++;
                if (level.ContainsKey(item.level) == false)
                {
                    level[item.level] = 0;
                }
                if (item.datatype == 1) //分类
                {
                    currTypeID = level[item.level] = CreateOrUpdateType(item, sortno);
                }
                else
                {
                    article[item.level] = CreateOrUpdateContent(item, currTypeID, sortno);
                }
            }
        }
        public override IEnumerable <string> ValidateField(Form form, Field field, IEnumerable <object> postedValues, HttpContextBase context, IFormStorage formStorage)
        {
            string verifyUrl           = null;
            string verifyPostParameter = null;

            if (ProviderName == Provider.Name.hCaptcha.ToString())
            {
                verifyUrl           = Consts.hCaptcha.VerifyUrl;
                verifyPostParameter = Consts.hCaptcha.VerifyPostParameter;
            }
            else if (ProviderName == Provider.Name.reCaptcha.ToString())
            {
                verifyUrl           = Consts.reCaptcha.VerifyUrl;
                verifyPostParameter = Consts.reCaptcha.VerifyPostParameter;
            }

            if (verifyUrl == null)
            {
                throw new Exception("\"uCaptchaProvider\" is missing or incorrect in AppSettings.");
            }

            string errorMessage;

            if (field.Settings.ContainsKey("ErrorMessage") && !string.IsNullOrEmpty(field.Settings["ErrorMessage"]))
            {
                errorMessage = field.Settings["ErrorMessage"];
            }
            else
            {
                errorMessage = "You must check the \"I am human\" checkbox to continue";
            }
            var returnStrings = new List <string>();

            var secretKey = AppSettingsManager.GetuCaptchaSecretKey();

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
                client.DefaultRequestHeaders.Add("Accept", "*/*");

                var parameters = new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("response", context.Request.Form[verifyPostParameter]),
                    new KeyValuePair <string, string>("secret", secretKey),
                    new KeyValuePair <string, string>("remoteip", context.Request.UserHostAddress)
                };

                var request = new HttpRequestMessage(HttpMethod.Post, verifyUrl)
                {
                    Content = new FormUrlEncodedContent(parameters)
                };

                var response = client.SendAsync(request).Result;

                if (response.IsSuccessStatusCode)
                {
                    var jsonString = response.Content.ReadAsStringAsync();
                    jsonString.Wait();

                    var result = JsonConvert.DeserializeObject <uCaptchaVerifyResponse>(jsonString.Result);

                    if (!result.Success)
                    {
                        returnStrings.Add(errorMessage);
                    }
                }

                if (!response.IsSuccessStatusCode)
                {
                    returnStrings.Add(errorMessage);
                }
            }

            return(returnStrings);
        }
예제 #30
0
 public FileDataContext(PasswordManager passwordManager, AppSettingsManager settingsManager)
 {
     _passwordManager = passwordManager;
     _settingsManager = settingsManager;
     _dataCollection  = new FileHashCollectionDataModel();
 }