public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (!(value is DateTime)) { return; } string str = WebApiUtils.FormatDateTime((DateTime)value); writer.WriteValue(str); }
public static JsonSerializer GetDefaultJsonSerializer() { if (_defaultJsonSerializer == null) { _defaultJsonSerializer = JsonSerializer.Create(new JsonSerializerSettings() { Converters = new List <JsonConverter>(WebApiUtils.GetDefaultJsonConverters()) }); } return(_defaultJsonSerializer); }
public async override Task <IEnumerable <DockerContainerItem> > GetItemsAsync(bool forceRefresh = false) { //登录 await WebApiUtils.EnsureLogin(client, siteItem); //获取容器列表 var items = await WebApiUtils.GetContainerItems(client, siteItem); //退出登录 await WebApiUtils.Logout(client, siteItem); return(items); }
public async Task <bool> PostReview(ReviewViewModel review) { var apiUrl = _configuration.GetSection("AppSettings:ApiUrl"); var model = new ReviewModel { ProductId = review.ProductId, Rating = review.Rating, Comment = review.Comment, UserId = review.UserId }; var result = await WebApiUtils.PostWebApi(apiUrl.Value + $"/{WebApiConfig.ApiPostReview}", model); return(result); }
public async Task <IEnumerable <ProductViewModel> > GetProductsByBrandId(int brandId) { var apiUrl = _configuration.GetSection("AppSettings:ApiUrl"); var products = await WebApiUtils.GetWebApi <List <ProductModel> >(apiUrl.Value + $"/{WebApiConfig.ApiGetProductsByBrandId}/{brandId}"); var brands = await WebApiUtils.GetWebApi <List <BrandModel> >(apiUrl.Value + $"/{WebApiConfig.ApiGetBrands}"); return(products.OrderBy(x => x.DateCreated).Take(10).Join(brands, p => p.BrandId, b => b.Id, (p, b) => new ProductViewModel() { Id = p.Id, ProductName = p.ProductName, Description = p.Description, BrandName = b.Name })); }
public async Task <UserViewModel> GetUserbyEmail(string email) { var apiUrl = _configuration.GetSection("AppSettings:ApiUrl"); var result = await WebApiUtils.GetWebApi <UserModel>(apiUrl.Value + $"/{WebApiConfig.ApiGetUserbyEmail}/{email}"); if (result == null) { return(null); } return(new UserViewModel { Id = result.Id, Email = result.Email }); }
public async Task <IEnumerable <ProductViewModel> > GetProducts() { var apiUrl = _configuration.GetSection("AppSettings:ApiUrl"); var products = await WebApiUtils.GetWebApi <List <ProductModel> >(apiUrl.Value + $"/{WebApiConfig.ApiGetProducts}"); var brands = await WebApiUtils.GetWebApi <List <BrandModel> >(apiUrl.Value + $"/{WebApiConfig.ApiGetBrands}"); var reviews = await WebApiUtils.GetWebApi <List <ReviewModel> >(apiUrl.Value + $"/{WebApiConfig.ApiGetReviews}"); var users = await WebApiUtils.GetWebApi <List <UserModel> >(apiUrl.Value + $"/{WebApiConfig.ApiGetUsers}"); var vm = products.OrderBy(x => x.DateCreated).Take(10).Join(brands, p => p.BrandId, b => b.Id, (p, b) => new ProductViewModel { Id = p.Id, ProductName = p.ProductName, Description = p.Description, BrandName = b.Name }); var rw = reviews.Join(users, r => r.UserId, u => u.Id, (r, u) => new ReviewViewModel { Id = r.Id, UserName = u.UserName, Comment = r.Comment, Rating = r.Rating, ProductId = r.ProductId }); var result = from l1 in vm join l2 in rw on l1.Id equals l2.ProductId into all from m in all.DefaultIfEmpty() //select new { x = l1, y = m }; select new ProductViewModel { Id = l1.Id, ProductName = l1.ProductName, Description = l1.Description, BrandName = l1.BrandName, UserName = m?.UserName ?? null, Comment = m?.Comment ?? null, Rating = m?.Rating ?? 0 }; return(result); }
public async Task <ProductViewModel> GetProductById(int id) { var apiUrl = _configuration.GetSection("AppSettings:ApiUrl"); var product = await WebApiUtils.GetWebApi <ProductModel>(apiUrl.Value + $"/{WebApiConfig.ApiGetProductById}/{id}"); if (product != null) { var brandId = product.BrandId; var brand = await WebApiUtils.GetWebApi <BrandModel>(apiUrl.Value + $"/{WebApiConfig.ApiGetBrandById}/{brandId}"); return(new ProductViewModel { Id = product.Id, ProductName = product.ProductName, Description = product.Description, BrandName = brand.Name }); } return(null); }
async Task ExecuteRefreshCommand() { IsBusy = true; BusyText = "正在刷新..."; try { //登录 await WebApiUtils.EnsureLogin(client, SiteItem); var newItem = await WebApiUtils.GetContainerInfo(client, SiteItem, DockerContainerItem.Id); JsonConvert.PopulateObject(JsonConvert.SerializeObject(newItem), DockerContainerItem); OnPropertyChanged(nameof(DockerContainerItem)); //退出登录 await WebApiUtils.Logout(client, SiteItem); } catch (Exception ex) { DependencyService.Get <IMessage>().LongAlert("启动容器失败,原因:" + ex.Message); } IsBusy = false; }
protected override void Importing(ProtectionSettingsPart part, ImportContentContext context) { base.Importing(part, context); var root = context.Data.Element(part.PartDefinition.Name); if (root == null) { return; } var settings = new List <ExternalApplication>(); var webApiUtils = new WebApiUtils(); settings.AddRange(part.ExternalApplicationList.ExternalApplications); var externalApps = root.Elements("ExternalApplication"); foreach (var app in externalApps) { var name = app.Attribute("Name") != null?app.Attribute("Name").Value : ""; var externalApp = settings.FirstOrDefault(x => x.Name == name); if (externalApp == null) { externalApp = new ExternalApplication { Name = name }; settings.Add(externalApp); } externalApp.ApiKey = app.Attribute("ApiKey") != null?app.Attribute("ApiKey").Value : webApiUtils.RandomString(22); externalApp.EnableTimeStampVerification = app.Attribute("EnableTimeStampVerification") != null?bool.Parse(app.Attribute("EnableTimeStampVerification").Value) : true; // default value: true externalApp.Validity = app.Attribute("Validity") != null?int.Parse(app.Attribute("Validity").Value) : 10; // default value: 10 } part.ExternalApplicationList = new ExternalApplicationList { ExternalApplications = settings }; }
async Task ExecuteStartCommand() { IsBusy = true; BusyText = "正在启动容器..."; try { //登录 await WebApiUtils.EnsureLogin(client, SiteItem); await WebApiUtils.StartContainer(client, SiteItem, DockerContainerItem); //退出登录 await WebApiUtils.Logout(client, SiteItem); DependencyService.Get <IMessage>().LongAlert("启动容器成功!"); } catch (Exception ex) { DependencyService.Get <IMessage>().LongAlert("启动容器失败,原因:" + ex.Message); } IsBusy = false; //刷新 await ExecuteRefreshCommand(); }
public string GetParamJson() { return(JsonConvert.SerializeObject(this, WebApiUtils.GetJsonConverters())); }
private async Task <IReadOnlyList <IText> > CreateTextsAsync(IEnumerable <string> projects, TextCorpusType type) { StringTokenizer wordTokenizer = new LatinWordTokenizer(); IMongoDatabase sfDatabase = _mongoClient.GetDatabase("scriptureforge"); IMongoDatabase realtimeDatabase = _mongoClient.GetDatabase("realtime"); IMongoCollection <BsonDocument> projectsColl = sfDatabase.GetCollection <BsonDocument>("projects"); var texts = new List <IText>(); foreach (string projectId in projects) { Project project = await _projectRepo.GetAsync(projectId); if (project == null) { continue; } string segmentType = null; string suffix = null; switch (type) { case TextCorpusType.Source: suffix = "source"; segmentType = project.SourceSegmentType; break; case TextCorpusType.Target: suffix = "target"; segmentType = project.TargetSegmentType; break; } StringTokenizer segmentTokenizer = null; if (segmentType != null) { segmentTokenizer = WebApiUtils.CreateSegmentTokenizer(segmentType); } FilterDefinition <BsonDocument> filter = Builders <BsonDocument> .Filter.Eq("_id", ObjectId.Parse(projectId)); BsonDocument projectDoc = await projectsColl.Find(filter).FirstOrDefaultAsync(); if (projectDoc == null) { continue; } var code = "sf_" + (string)projectDoc["projectCode"]; var isScripture = (bool)projectDoc["config"]["isTranslationDataScripture"]; IMongoCollection <BsonDocument> projectColl = realtimeDatabase.GetCollection <BsonDocument>(code); IMongoDatabase projectDatabase = _mongoClient.GetDatabase(code); IMongoCollection <BsonDocument> translateColl = projectDatabase.GetCollection <BsonDocument>("translate"); filter = Builders <BsonDocument> .Filter.Eq("isDeleted", false); using (IAsyncCursor <BsonDocument> cursor = await translateColl.Find(filter).ToCursorAsync()) { while (await cursor.MoveNextAsync()) { foreach (BsonDocument docInfo in cursor.Current) { var id = (ObjectId)docInfo["_id"]; filter = Builders <BsonDocument> .Filter.Eq("_id", $"{id}:{suffix}"); BsonDocument doc = await projectColl.Find(filter).FirstAsync(); if (isScripture) { texts.Add(new XForgeScriptureText(wordTokenizer, project.Id, doc)); } else { texts.Add(new XForgeRichText(segmentTokenizer, wordTokenizer, project.Id, doc)); } } } } } return(texts); }
private async Task <T> DoExecuteAsync <T>(IRequest <T> request, string accessToken, DateTime timestamp) where T : BaseResponse { T result; try { request.Validate(); } catch (WebApiException ex) { result = this.createErrorResponse <T>(ex.ErrorCode, ex.ErrorMsg); return(result); } IWebApiDictionary webApiDictionary = new IWebApiDictionary(); webApiDictionary.Add("param_json", request.GetParamJson()); webApiDictionary.Add("method", request.ApiName); webApiDictionary.Add("v", "1.0"); webApiDictionary.Add("app_key", this.appKey); webApiDictionary.Add("timestamp", timestamp.ToUnixTime()); webApiDictionary.Add("access_token", accessToken); webApiDictionary.Add("sign", WebApiUtils.SignYrqRequest(webApiDictionary, this.appSecret)); string value = this.webUtils.BuildGetUrl(this.serverUrl, webApiDictionary); try { string text; if (request is IUploadRequest <T> ) { IDictionary <string, FileItem> fileParams = WebApiUtils.CleanupDictionary(((IUploadRequest <T>)request).GetFileParameters()); text = await this.webUtils.DoPostAsync(this.serverUrl, webApiDictionary, fileParams); } else { text = await this.webUtils.DoPostAsync(this.serverUrl, webApiDictionary); } T t; if (this.disableParser) { t = Activator.CreateInstance <T>(); t.Body = text; } else if ("json".Equals(this.format)) { IParser <T> var_7_2B3 = new JsonParser <T>(); if (request is ICustomRequest <T> ) { t = ((ICustomRequest <T>)request).PareseResponse(text); } else { t = var_7_2B3.Parse(text); } } else { t = new XmlParser <T>().Parse(text); } result = t; } catch (Exception var_8_2F5) { if (!this.disableTrace) { object var_9_325 = new StringBuilder(value).Append(" request error!\r\n").Append(var_8_2F5.StackTrace); this.topLogger.Error(var_9_325.ToString()); } throw var_8_2F5; } return(result); }
public SegmentTokenizer(string segmentType) { _tokenizer = WebApiUtils.CreateSegmentTokenizer(segmentType); }
public ActionResult Index() { IResponse response; try { string appKey = null; string key = null; string str = null; string strB = null; string accessToken = null; DateTime dateTime = DateTime.MinValue; NameValueCollection form = this.Request.Form; Dictionary <string, string> dictionary = new Dictionary <string, string>(); foreach (string allKey in form.AllKeys) { string s = form[allKey]; switch (allKey) { case "app_key": appKey = s; break; case "param_json": str = s; break; case "method": key = s; break; case "timestamp": long result; if (long.TryParse(s, out result)) { dateTime = new DateTime(1970, 1, 1).ToLocalTime().AddMilliseconds((double)result); break; } break; case "sign": strB = s; break; case "access_token": accessToken = s; break; } if (allKey != "sign") { dictionary.Add(allKey, s); } } if (dateTime < DateTime.Now.AddMinutes(-15.0)) { response = new BaseResponse() { ErrCode = "005" }; } else { AppInfo app = ServiceHelper.LoadService <IAppService>().GetApp(appKey); if (app != null) { if (string.Compare(WebApiUtils.SignYrqRequest(dictionary, app.AppSecret), strB, true) == 0) { Dictionary <string, ApiMethodInfo> apiMethods = Util.Utils.GetApiMethods(); if (apiMethods.ContainsKey(key)) { ApiMethodInfo apiMethodInfo = apiMethods[key]; IRequest <IResponse> request = (IRequest <IResponse>)JsonConvert.DeserializeObject(str ?? "{}", apiMethodInfo.RequestType, WebApiUtils.GetJsonConverters()); request.Validate(); this.Context.AppId = app.AppId; if (request is ICraftsReqeust) { ServiceHelper.LoadService <ICraftDbFactory>().CraftNO = ((ICraftsReqeust)request).CraftNO; } if (request is IUploadRequest) { IUploadRequest uploadRequest = (IUploadRequest)request; IDictionary <string, FileItem> fileParameters = new Dictionary <string, FileItem>(); foreach (string allKey in this.Request.Files.AllKeys) { HttpPostedFileBase httpPostedFileBase = this.Request.Files[allKey]; byte[] numArray = new byte[httpPostedFileBase.InputStream.Length]; httpPostedFileBase.InputStream.Read(numArray, 0, numArray.Length); fileParameters.Add(allKey, new FileItem(httpPostedFileBase.FileName, numArray)); httpPostedFileBase.InputStream.Dispose(); } uploadRequest.SetFileParamaters(fileParameters); } if (apiMethodInfo.IsCheckSession) { AuthInfo auth = ServiceHelper.LoadService <IAuthService>().GetAuth(accessToken); if (auth != null && auth.AppId == this.Context.AppId) { this.Context.AuthId = auth.AppId; this.Context.UserId = auth.UserId; response = (IResponse)apiMethodInfo.Method.Invoke(this, new object[1] { request }); } else { response = new BaseResponse() { ErrCode = "004" } }; } else { response = (IResponse)apiMethodInfo.Method.Invoke(this, new object[1] { request }); } } else { response = new BaseResponse() { ErrCode = "003" } }; } else { response = new BaseResponse() { ErrCode = "002" } }; } else { response = new BaseResponse() { ErrCode = "008" } }; } } catch (TargetInvocationException ex) { LogUtil.LogError("处理请求异常", ex.GetBaseException()); response = new BaseResponse() { ErrCode = "001", ErrMsg = ex.GetBaseException().Message }; } catch (Exception ex) { LogUtil.LogError("处理请求异常", ex); response = new BaseResponse() { ErrCode = "001", ErrMsg = ex.Message }; } return(Content(JsonConvert.SerializeObject(response, WebApiUtils.GetJsonConverters()))); }