/// <inheritdoc />
        public async Task <string> QueryEntityNameAsync(TObjectGuidType guid, CancellationToken token = default)
        {
            if (guid == null)
            {
                throw new ArgumentNullException(nameof(guid));
            }

            if (!QueryServices.ContainsKey(guid.ObjectType))
            {
                return(UKNOWN_NAME_VALUE);
            }

            if (CachedNames.TryGetValue(guid, out var value))
            {
                return(value);
            }

            //Don't lock around the query call because it will
            //cause significant delays for no reason, only lock when adding
            EntityNameQueryResponse response = await QueryServices[guid.ObjectType].QueryEntityNameAsync(guid, token);

            //We also don't cache failed results.
            if (response.isSuccessful)
            {
                //We don't have to bother checking if it exists (techncially a race condition)
                //because we should be replacing it with an identical response
                CachedNames.TryAdd(guid, response.Result);
                return(response.Result);
            }
            else
            {
                return(UKNOWN_NAME_VALUE);
            }
        }
Esempio n. 2
0
        public ActionResult DoQuery(QueryViewModel model)
        {
            try
            {
                QueryWeatherRequest request = new QueryWeatherRequest();
                //request.GPSLocationInfo = gpsLocationInfo;
                request.WCCode        = model.WCCode;
                request.QueryDateTime = DateTime.Now;
                QueryWeatherResponse response = QueryServices.GetWeatherInfo(request);
                response.CurrentDay.QueryDate   = request.QueryDateTime.ToString("yyyy/MM/dd");
                response.CurrentDay.AreaCode    = model.AreaCode;
                response.CurrentDay.AreaName    = CityAndAreaConfig.Instance.getAreaNameByAreaCode(model.AreaCode);
                response.CurrentDay.WCCode      = model.WCCode;
                response.CurrentDay.CountryName = CityAndAreaConfig.Instance.getWCCountryNameByWCCode(model.WCCode);
                ViewBag.CurrentDay = response.CurrentDay;
                ViewBag.OtherDays  = response.OthreDays;
            }
            catch (System.Exception ex)
            {
                return(View("Error"));
            }

            return(View("Result"));
            //return RedirectToAction("Result");
        }
Esempio n. 3
0
        public JsonResult QueryWeatherInfo(string weatherCountyCode, string Date)
        {
            QueryWeatherRequest request = new QueryWeatherRequest();

            request.WCCode = weatherCountyCode;
            QueryWeatherResponse response = QueryServices.GetWeatherInfo(request);

            return(Json(new { WeatherInfo = response, IsSuccess = true, Msg = "" }));
        }
Esempio n. 4
0
        public ActionResult DoQuery(QueryViewModel model)
        {
            try
            {
                if (model == null)
                {
                    throw new ArgumentNullException("model");
                }

                //GPSLocation gpsLocationInfo = GPSLocationService.GetClientGPSLocationInfo();

                QueryWeatherRequest request = new QueryWeatherRequest();
                //request.GPSLocationInfo = gpsLocationInfo;
                request.AreaCode      = model.AreaCode;
                request.WCCode        = model.WCCode;
                request.QueryDateTime = DateTime.Now;
                QueryWeatherResponse response = QueryServices.GetWeatherInfo(request);
                response.CurrentDay.QueryDate   = request.QueryDateTime.ToString("yyyy/MM/dd");
                response.CurrentDay.AreaCode    = model.AreaCode;
                response.CurrentDay.AreaName    = CityAndAreaConfig.Instance.getAreaNameByAreaCode(model.AreaCode);
                response.CurrentDay.WCCode      = model.WCCode;
                response.CurrentDay.CountryName = CityAndAreaConfig.Instance.getWCCountryNameByWCCode(model.WCCode);
                ViewBag.CurrentDay = response.CurrentDay;
                if (response == null || response.CurrentDay == null)
                {
                    ViewData["NoData"] = "true";
                    return(View("Index"));
                }
                else
                {
                    ViewData["NoData"] = "false";
                    return(View("Result"));
                }
            }
            catch (System.Net.WebException ex)
            {
                //ViewBag.ErrMsg = "網路斷線或遠端伺服器錯誤,請通知管理者";
                ErrorPageModel errModel = new ErrorPageModel {
                    ErrorTitle = "Network Error",
                    ErrorMsg   = "網路斷線或遠端伺服器錯誤,請通知管理者"
                };

                return(View("Error", errModel));
            }
            catch (System.Exception ex)
            {
                return(View("Error"));
            }


            //return RedirectToAction("Result");
        }
 private void WindowMain_Load(object sender, EventArgs e)
 {
     query = new QueryServices();
     query.RegisterObs(this);
     SetStarComboBoxServerTypValue();
     selectServiceComBox.SelectedItem    = 0;
     selectServerTypComBox.SelectedIndex = 0;
     cancelBtn.Enabled  = false;
     startBtn.Enabled   = false;
     DisableBtn.Enabled = false;
     stopBtn.Enabled    = false;
     EnableBtn.Enabled  = false;
 }
Esempio n. 6
0
 public void GetWeatherInfo_Null_Test()
 {
     QueryServices.GetWeatherInfo(null);
 }
Esempio n. 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            DataAccessLayerBase.Configuration = Configuration;

            services.AddHttpContextAccessor();
            services.AddSingleton <IActionContextAccessor, ActionContextAccessor>();

            services.Configure <TokenSettings>(Configuration.GetSection("tokenSettings"));

            var token  = Configuration.GetSection("tokenSettings").Get <TokenSettings>();
            var secret = Encoding.ASCII.GetBytes(token.Secret);

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(token.Secret)),
                    ValidIssuer      = token.Issuer,
                    ValidAudience    = token.Audience,
                    ValidateIssuer   = false,
                    ValidateAudience = false
                };
            });

            services.AddMvc(options =>
            {
                options.Filters.Add <ApiExceptionFilter>();
            }).AddJsonOptions(x =>
            {
                x.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
                x.SerializerSettings.NullValueHandling     = NullValueHandling.Ignore;
                x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                x.SerializerSettings.Formatting            = Formatting.Indented;
                x.SerializerSettings.ContractResolver      = new DefaultContractResolver();
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddCors(c => c.AddPolicy("AllowAllHeaders", builder =>
            {
                builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            }));

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc(nameof(v1), new Info()
                {
                    Title       = $"Roulette Api {nameof(v1)}",
                    Description = "Service for managing virtual roulette game",
                    Version     = nameof(v1)
                });

                var currentDir = new DirectoryInfo(AppContext.BaseDirectory);
                foreach (var xmlCommentFile in currentDir.EnumerateFiles("Roulette.*.xml"))
                {
                    c.IncludeXmlComments(xmlCommentFile.FullName);
                }
                c.DescribeAllEnumsAsStrings();

                c.AddSecurityDefinition("Bearer", new ApiKeyScheme {
                    In = "header", Description = "Please enter JWT with Bearer into field", Name = "Authorization", Type = "apiKey"
                });
                c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > {
                    { "Bearer", Enumerable.Empty <string>() },
                });
            });

            services.AddTransient <IDBProvider, DBProvider>();
            services.AddTransient <ISignInManager, SignInManager>();

            var container = new ContainerBuilder();

            CommandServices.RegisterServices(container, services);
            QueryServices.RegisterServices(container, services);

            container.Populate(services);

            return(new AutofacServiceProvider(container.Build()));
        }
Esempio n. 8
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(op =>
            {
                op.Filters.Add <ValidationFilter>();
                op.RespectBrowserAcceptHeader = true;
            })
            .AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore)
            .AddXmlSerializerFormatters();

            services.AddTransient <TokenService, TokenService>();
            services.AddTransient <TaxAndShippingCalculationService, TaxAndShippingCalculationService>();

            services.AddSwaggerGen(x =>
            {
                x.ExampleFilters();

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                x.IncludeXmlComments(xmlPath);

                x.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {
                    Name = "Authorization",
                    Type = SecuritySchemeType.ApiKey,
                    In   = ParameterLocation.Header,
                });
                x.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            }
                        },
                        new string[] {}
                    }
                });
            });

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer   = true,
                    ValidateAudience = true,
                    ValidAudience    = Configuration["Jwt:Audience"],
                    ValidIssuer      = Configuration["Jwt:Issuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                };
            });


            services.AddSwaggerExamplesFromAssemblyOf <Startup>();

            services.AddMvc(op =>
            {
                op.Filters.Add <ApiExceptionAttribute>();
            })
            .AddFluentValidation(fvc => fvc.RegisterValidatorsFromAssemblyContaining <Startup>());

            services.AddAutoMapper(typeof(Startup));

            services.AddDbContext <ApplicationContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            var container = new ContainerBuilder();

            CommandServices.RegisterServices(container, services);
            QueryServices.RegisterServices(container, services);

            container.Populate(services);

            return(new AutofacServiceProvider(container.Build()));
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            DateTime starttime;
            DateTime endtime;
            TimeSpan spentime;
            int      index = 1;

            List <WCCountry> wccountries = CityAndAreaConfig.Instance.getWCCountryList();

            try
            {
                Console.WriteLine("==============================================================================");
                starttime = DateTime.Now;
                Console.WriteLine(string.Format("Program start : Time =>{0}", starttime.ToString("yyyy/MM/dd HH:mm:ss")));
                Console.WriteLine("==============================================================================");
                foreach (var item in wccountries)
                {
                    Console.WriteLine("");
                    Console.WriteLine("==============================================================================");
                    Console.WriteLine(string.Format("Index = {0} , WCCode = {1} , AreaName = {2} , Name ={3}",
                                                    index, item.WCCode, CityAndAreaConfig.Instance.getAreaNameByAreaCode(item.AreaCode), item.Name));

                    QueryWeatherRequest request = new QueryWeatherRequest {
                        WCCode = item.WCCode, AreaCode = item.AreaCode
                    };
                    QueryWeatherResponse response = QueryServices.GetWeatherInfo(request);

                    if (response != null && response.CurrentDay != null)
                    {
                        Console.WriteLine(string.Format("天氣狀況:{0} , 地點:{1} , 溫度:{2} , 舒適度:{3} , 溫度範圍:{4} ~ {5} , 濕度:{6} , 風速:{7} , 觀測時間:{8}"
                                                        , response.CurrentDay.WeatherStatus
                                                        , CityAndAreaConfig.Instance.getAreaNameByAreaCode(item.AreaCode) + " - " + CityAndAreaConfig.Instance.getWCCountryNameByWCCode(item.WCCode)
                                                        , response.CurrentDay.Temperature
                                                        , response.CurrentDay.Feelslike
                                                        , response.CurrentDay.Low
                                                        , response.CurrentDay.High
                                                        , response.CurrentDay.Humidity
                                                        , response.CurrentDay.Windspeed
                                                        , response.CurrentDay.Observationtime
                                                        ));

                        WeatherDataDAO.NewWeatherData(response.CurrentDay);

                        //WeatherDataDAO.AddForeseeWeatherData(response.OthreDays);
                    }
                    index++;
                    Console.WriteLine("==============================================================================");
                }
                Console.WriteLine("");
                Console.WriteLine("==============================================================================");
                endtime = DateTime.Now;
                Console.WriteLine(string.Format("Program End : Time =>{0}", endtime.ToString("yyyy/MM/dd HH:mm:ss")));
                spentime = endtime - starttime;
                Console.WriteLine("Count : {0} , Spend Time:{1} 分  {2} 秒", index, spentime.Minutes, spentime.Seconds);
                Console.WriteLine("==============================================================================");
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(string.Format("System Error : {0}", ex.ToString()));
            }
        }