static void ApplyTemplate(ApiModel item, string outputDirectory, TemplateEngine templateEngine, string templateName) { var outputPath = Path.Combine(outputDirectory, TemplateCallbacks.GetApiClassName(item) + ".cs"); if (File.Exists(outputPath)) File.Delete(outputPath); File.WriteAllText(outputPath, templateEngine.ApplyByName(templateName, item)); }
/// <summary> /// Declares structures in an API model based on the contents of a JSON tree. /// </summary> /// <param name="root">The root of the API JSON tree.</param> /// <param name="api">The API model being constructed.</param> static void DeclareStructures(JObject root, ApiModel api) { JToken items; if (root.TryGetValue("structures", out items)) { foreach (var item in items) api.AddStructure((string)item["key"]); } }
static void BuildTrampolineAssembly(ApiModel api, string outputDirectory, string outputFile) { MarshallingService marshaller = new MarshallingService(); TrampolineAssemblyBuilder trampolineBuilder = new TrampolineAssemblyBuilder(); foreach (var interfaceModel in api.Interfaces) { foreach (var methodModel in interfaceModel.Methods) { var methodType = marshaller.ResolveType(methodModel.Type); if (methodType == null) throw new InvalidOperationException(string.Format("Could not resolve return type for method '{0}.'", methodModel.Name)); var parameters = new List<TrampolineParameter>(); foreach (var parameterModel in methodModel.Parameters) { var parameterType = marshaller.ResolveType(parameterModel); if (parameterType == null) throw new InvalidOperationException(string.Format("Could not resolve type for parameter '{0}.'", parameterModel.Name)); TrampolineParameterFlags flags = TrampolineParameterFlags.Default; if (parameterModel.Flags.HasFlag(ParameterModelFlags.IsOutput) && marshaller.ResolveBehavior(parameterModel) != MarshalBehavior.Structure && marshaller.ResolveBehavior(parameterModel) != MarshalBehavior.Enumeration && marshaller.ResolveBehavior(parameterModel) != MarshalBehavior.Array) flags |= TrampolineParameterFlags.Reference; parameters.Add(parameterModel.Type == ApiModel.VoidModel ? new TrampolineParameter(typeof(IntPtr), flags) : new TrampolineParameter(parameterType, flags)); } trampolineBuilder.Add(new Trampoline(true, methodType, parameters.ToArray())); } } foreach (var functionModel in api.Functions) { var methodType = marshaller.ResolveType(functionModel.Type); if (methodType == null) throw new InvalidOperationException(string.Format("Could not resolve return type for method '{0}.'", functionModel.Name)); var parameters = new List<TrampolineParameter>(); foreach (var parameterModel in functionModel.Parameters) { var parameterType = marshaller.ResolveType(parameterModel); if (parameterType == null) throw new InvalidOperationException(string.Format("Could not resolve type for parameter '{0}.'", parameterModel.Name)); TrampolineParameterFlags flags = TrampolineParameterFlags.Default; if (parameterModel.Flags.HasFlag(ParameterModelFlags.IsOutput)) flags |= TrampolineParameterFlags.Reference; parameters.Add(parameterModel.Type == ApiModel.VoidModel ? new TrampolineParameter(typeof(IntPtr), flags) : new TrampolineParameter(parameterType, flags)); } trampolineBuilder.Add(new Trampoline(false, methodType, parameters.ToArray())); } trampolineBuilder.CreateAssembly(outputDirectory, outputFile); }
/// <summary> /// Declares interfaces in an API model based on the contents of a JSON tree. /// </summary> /// <param name="root">The root of the API JSON tree.</param> /// <param name="api">The API model being constructed.</param> static void DeclareInterfaces(JObject root, ApiModel api) { JToken items; if (root.TryGetValue("interfaces", out items)) { foreach (var item in items) { var key = (string)item["key"]; var guid = new Guid((string)item["guid"]); api.AddInterface(key, guid); } } }
public async Task <IActionResult> Register([FromBody] RegisterModel model) { if (!ModelState.IsValid) { return(this.BadRequest(this.ModelState.AsApiModel(model))); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await userManager.CreateAsync(user, model.Password); if (!result.Succeeded) { return(BadRequest(result.AsApiModel(model))); } // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); //await _emailSender.SendEmailAsync(model.Email, "Confirm your account", // $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>"); await signInManager.SignInAsync(user, isPersistent : true); logger.LogInformation(3, "User created a new account with password."); //var tokens = this.antiForgery.GetAndStoreTokens(this.HttpContext); //if (!string.IsNullOrWhiteSpace(tokens.RequestToken)) //{ // var cookieOptions = new CookieOptions // { // HttpOnly = false, // Secure = this.Request.IsHttps // }; // this.Response.Cookies.Append(Constants.AntiForgeryCookieName, tokens.RequestToken, cookieOptions); //} return(Ok(ApiModel.AsSuccess <RegisterModel>(null))); }
// [ValidateAntiForgeryToken] public IActionResult GetAll(int start = 0, int take = 50, CancellationToken cancellationToken = default(CancellationToken)) { var result = _userManager.Users; var count = result.Count(); var values = result.Skip(start).Take(take).ToArray().Select((i) => _mapper.Map <UserDto>(i)); var controllerName = nameof(UserController).ToLowerInvariant().Replace("controller", ""); var listResult = new FindResult <UserDto> { Count = count, Start = start, Take = take, Values = values }; var hasnext = count > (start + take); if (hasnext) { listResult.Next = Url.Action( action: nameof(GetAll), controller: controllerName, values: new { start = start + take, take = take }, protocol: Request.Scheme, host: Request.Host.Value); } var hasPrevious = start > 0; if (hasPrevious) { listResult.Previous = Url.Action( action: nameof(GetAll), controller: controllerName, values: new { start = Math.Max(start - take, 0), take = Math.Min(start, take) }, protocol: Request.Scheme, host: Request.Host.Value); } return(Ok(ApiModel.AsSuccess(listResult))); }
// [ValidateAntiForgeryToken] public async Task <IActionResult> AuthenticateAsync([FromBody] AuthenticateBindings userDto, string returnUrl = null) { var username = _userManager.NormalizeKey(userDto.UserName); var result = await _signInManager.PasswordSignInAsync(username, userDto.Password, userDto.RememberMe, lockoutOnFailure : false); if (result.Succeeded) { var user = await _userManager.FindByNameAsync(username); if (user == null) { throw new AppException($"impossible to find the user {userDto.UserName} after successfull login using this username"); } _logger.LogInformation("User logged in."); var resultDto = _mapper.Map <AccountDto>(user); resultDto.Token = await _GenerateTokenAsync(user); resultDto.IsAuthenticated = true; return(Ok(ApiModel.AsSuccess(resultDto))); } if (result.RequiresTwoFactor) { return(RedirectToAction(nameof(LoginWith2fa), new { returnUrl, userDto.RememberMe })); } if (result.IsLockedOut) { _logger.LogWarning("User account locked out."); return(Ok(ApiModel.AsError(userDto, "User account locked out."))); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return(Ok(ApiModel.AsError(userDto, "Invalid login attempt."))); } }
public async Task <HttpResponseMessage> GetInsurance(ApiModel inputmodel) { //ask whether this will be a PatientInsurance List <Insurance> data = new List <Insurance>(); try { ApiResponseModel <List <Insurance> > model = new ApiResponseModel <List <Insurance> >() { }; var client = ServiceFactory.GetService(typeof(Insurance)); data = await client.getInsurance(inputmodel.insuranceName, inputmodel.insuranceId); model.data.records = data; return(Response.Success <List <Insurance> >(model)); } catch (Exception ex) { return(Response.Exception(ex)); } }
public async Task <IActionResult> ExportCsvAsync([FromBody] Filter filter = null, [FromQuery] string sort = null, CancellationToken cancellationToken = default(CancellationToken)) { var sorts = sort?.Split(',').Where(s => !string.IsNullOrEmpty(s)); var results = await service.FindAsync(filter, sorts, cancellationToken : cancellationToken); var implementationType = this.GetType(); var controllerName = implementationType.Name.ToLowerInvariant().Replace("controller", ""); var dtos = results.Select(r => _mapper.Map <ClientDto>(r)); var csvString = ""; using (var writer = new StringWriter()) using (var csv = new CsvWriter(writer)) { csv.WriteRecords(dtos); csvString = writer.ToString(); } return(Ok(ApiModel.AsSuccess(csvString))); }
void CreateApi(ApiModel model) { try { if (model.Service == ServiceType.FileSystem) { model.Service = ServiceType.OneDrive; } var apiType = ApiServiceTypes[model.Service]; var api = Activator.CreateInstance(apiType, model.Id.ToString(), CreateHandler()) as SimpleAuth.Api; api.DeviceId = model.DeviceId; api.ExtraDataString = model.ExtraData; var provider = CreateProvider(api); Collection.Add(model.Id.ToString(), provider); } catch (Exception ex) { LogManager.Shared.Report(ex); } }
public async Task <IHttpActionResult> GetAllApis() { IApiExplorer apiExplorer = Configuration.Services.GetApiExplorer();; return(await Task.Run(() => { var apiModel = new ApiModel { Application = "uManage", Version = Assembly.GetExecutingAssembly().GetName().Version.ToString(), Links = new Dictionary <string, string>() }; foreach (var api in apiExplorer.ApiDescriptions) { apiModel.Links.Add(api.ActionDescriptor.ActionName, api.RelativePath); } return Ok(apiModel); })); }
/// <summary> /// 修改备注值1 /// </summary> /// <param name="data"></param> /// <returns></returns> public string UpdateChuckInfoRemake1(string data) { string res = string.Empty; try { ApiModel apimodel = TDCommom.ObjectExtensions.FromJsonString <ApiModel>(data); int i = caidb.UpdateChuckInfoRemake1(apimodel.id, apimodel.Data); res = TDCommom.ObjectExtensions.ToJsonString(new ApiModel() { ResultCode = i }); TDCommom.Logs.Info(string.Format("修改备注值1:接收参数:{0} \r\n 返回数据:{1}\r\n", data, res)); return(res); } catch (Exception ex) { TDCommom.Logs.Error(string.Format("修改备注值1异常:接收参数:{0} \r\n 异常信息:{1}\r\n", data, ex.Message)); return(res); } }
public string UpdateTaskStepById(string data) { string res = string.Empty; try { ApiModel model = TDCommom.ObjectExtensions.FromJsonString <ApiModel>(data); int i = db.UpdateTaskStepById(model.id, model.Type); res = TDCommom.ObjectExtensions.ToJsonString(new ApiModel() { ResultCode = i }); TDCommom.Logs.Info(string.Format("修改任务步骤 :接收数据:{0} \r\n 返回数据:{1}", data, res)); return(res); } catch (Exception ex) { TDCommom.Logs.Error(string.Format("修改任务步骤异常 :接收数据:{0} \r\n 异常信息:{1}", data, ex.Message)); return(res); } }
public string GetPageList(string data) { try { ApiModel model = JsonConvert.DeserializeObject <ApiModel>(data); long AllRowsCount = model.AllRowsCount; List <UsersModel> res1 = TDDB.UsersModelDB.usersModelDB.PageList(model.PageIndex, model.PageSize, out AllRowsCount); string apiInfo = JsonConvert.SerializeObject(new ApiModel() { AllRowsCount = AllRowsCount, ResultData = res1 }); TDCommom.Logs.Info(string.Format(" 查询所有分页数据接收数据:{0} \r\n 查询所有分页返回数据:{1}\r\n", data, apiInfo)); return(apiInfo); } catch (Exception ex) { TDCommom.Logs.Error(string.Format("查询所有分页数据接收数据:{0} \r\n 异常信息:{1}\r\n", data, ex.Message)); return(null); } }
public async Task <HttpResponseMessage> sendPanicResult(ApiModel inputmodel) { bool data = false; try { ApiResponseModel <string> model = new ApiResponseModel <string>() { }; var client = ServiceFactory.GetService(typeof(PatientOrder)); data = client.sendPanicResult(inputmodel.orderId, inputmodel.message); model.data.records = data.ToString(); return(Response.Success <string>(model)); } catch (Exception ex) { return(Response.Exception(ex)); } }
public string GetInfoByState(string data) { string res = string.Empty; try { ApiModel apimodel = TDCommom.ObjectExtensions.FromJsonString <ApiModel>(data); List <ChuckingApplianceInfoModel> list = caidb.GetInfoByState(apimodel.State, apimodel.Data); if (list.Count > 0) { res = TDCommom.ObjectExtensions.ToJsonString(list); } TDCommom.Logs.Info(string.Format("根据状态查询夹具数据:接收参数:{0} \r\n 返回数据:{1}\r\n", data, res)); return(res); } catch (Exception ex) { TDCommom.Logs.Error(string.Format("根据状态查询夹具数据异常:接收参数:{0} \r\n 异常信息:{1}\r\n", data, ex.Message)); return(res); } }
public async Task <HttpResponseMessage> cancelAppointmentOrder(ApiModel inputmodel) { bool data = false; try { ApiResponseModel <string> model = new ApiResponseModel <string>() { }; var client = ServiceFactory.GetService(typeof(PatientOrder)); data = client.cancelAppointmentOrder(inputmodel.orderId, inputmodel.CaseId, inputmodel.ParamsValues); model.data.records = data.ToString(); return(Response.Success <string>(model)); } catch (Exception ex) { return(Response.Exception(ex)); } }
public async Task <HttpResponseMessage> executeStatusManagerAction(ApiModel apiModel) { bool data = false; try { ApiResponseModel <string> model = new ApiResponseModel <string>() { }; var client = ServiceFactory.GetService(typeof(StatusManager)); data = client.executeAction(apiModel.statusManagerDetailsId, apiModel.orderId, apiModel.patientEncounterId, apiModel.ParamsValues); model.data.records = data.ToString(); return(Response.Success <string>(model)); } catch (Exception ex) { return(Response.Exception(ex)); } }
public async Task <IActionResult> CashboxAsync(CancellationToken cancellationToken = default(CancellationToken)) { var filter = Filter.Ne("Archived", true); var results = await service.FindAsync(filter, cancellationToken : cancellationToken); var cashbox = results .Where(m => !string.IsNullOrEmpty(m.ShopId)) .GroupBy(m => m.ShopId) .ToDictionary( shop => shop.Key, shop => shop.GroupBy(m => m.Currency).ToDictionary( currency => currency.Key, currency => currency.Sum(m => m.Amount) ) ); return(Ok(ApiModel.AsSuccess(cashbox))); }
/// <summary> /// 根据ID查询夹具信息 /// </summary> /// <param name="data"></param> /// <returns></returns> public string GetChuckInfoByid(string data) { string res = string.Empty; try { ApiModel apimodel = TDCommom.ObjectExtensions.FromJsonString <ApiModel>(data); ChuckingApplianceInfoModel list = caidb.GetChuckInfoByid(apimodel.id); if (list != null) { res = TDCommom.ObjectExtensions.ToJsonString(list); } TDCommom.Logs.Info(string.Format("根据ID查询夹具信息:接收参数:{0} \r\n 返回数据:{1}\r\n", data, res)); return(res); } catch (Exception ex) { TDCommom.Logs.Error(string.Format("根据ID查询夹具信息异常:接收参数:{0} \r\n 异常信息:{1}\r\n", data, ex.Message)); return(res); } }
public SearchListResponse PlaylistsForChannel(ApiModel model) { //Convert string orderby to the enum that we expect try { var order = (SearchResource.ListRequest.OrderEnum)Enum.Parse(typeof(SearchResource.ListRequest.OrderEnum), model.OrderBy, true); //Go & get the videos var channelVideos = YouTubeHelper.GetPlaylistsForChannel(model.PageToken, model.ChannelId, model.SearchQuery, order); //Return the response from YouTube API return(channelVideos); } catch (ArgumentException) { var message = new HttpResponseMessage(HttpStatusCode.BadRequest); message.Content = new StringContent("Order by cannot be converted to the enum"); throw new HttpResponseException(message); } }
public string GetViewsByTime(string data) { try { ApiModel apimodel = JsonConvert.DeserializeObject <ApiModel>(data); long AllRowsCount = apimodel.AllRowsCount; List <View_GetHistoryAlarmModel> list = historyViewDB.GetViewsByTime(apimodel.PageIndex, apimodel.PageSize, out AllRowsCount, apimodel.StartTime, apimodel.EndTime); string res = JsonConvert.SerializeObject(new ApiModel() { AllRowsCount = AllRowsCount, ResultData = list }); TDCommom.Logs.Info(string.Format("分页查询历史报警(报警时间):接收数据:{0}\r\n 返回数据:{1} \r\n", data, res)); return(res); } catch (Exception ex) { TDCommom.Logs.Error(string.Format("分页查询历史报警(报警时间)异常:接收数据:{0}\r\n 异常信息 :{1} \r\n", data, ex.Message)); return(null); } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.RemarkUpdatelayout); var toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.app_bar); SetSupportActionBar(toolbar); SupportActionBar.SetTitle(Resource.String.app_name); SupportActionBar.SetDisplayHomeAsUpEnabled(true); //SupportActionBar.SetDisplayShowHomeEnabled(true); SupportActionBar.SetHomeButtonEnabled(true); btnSaveUpdate = FindViewById <Button>(Resource.Id.btnCheckListUpdate); edUpdateRemark = FindViewById <EditText>(Resource.Id.txt_UpdateRemark); ListData = JsonConvert.DeserializeObject <ApiModel>(Intent.GetStringExtra("RemarkUpdate") ?? "Data not available"); btnSaveUpdate.Click += BtnSaveUpdate_Click; }
public string GetCellInfoByCode(string data) { string res = string.Empty; try { ApiModel model = TDCommom.ObjectExtensions.FromJsonString <ApiModel>(data); CellInfoModel cellinfo = cellDB.GetCellInfoByCode(model.Data); if (cellinfo != null) { res = TDCommom.ObjectExtensions.ToJsonString(cellinfo); } TDCommom.Logs.Info(string.Format("根据电芯条码查找电芯信息:接收参数:{0}\r\\n 返回参数:{1} \r\n", data, res)); return(res); } catch (Exception ex) { TDCommom.Logs.Error(string.Format("根据电芯条码查找电芯信息异常:接收参数:{0}\r\\n 异常信息:{1} \r\n", data, ex.Message)); return(res); } }
public async Task<IHttpActionResult> GetAllApis() { IApiExplorer apiExplorer = Configuration.Services.GetApiExplorer(); ; return await Task.Run(() => { var apiModel = new ApiModel { Application = "uManage", Version = Assembly.GetExecutingAssembly().GetName().Version.ToString(), Links = new Dictionary<string, string>() }; foreach (var api in apiExplorer.ApiDescriptions) { apiModel.Links.Add(api.ActionDescriptor.ActionName, api.RelativePath); } return Ok(apiModel); }); }
public string GetCellInfoBystate(string data) { string res = string.Empty; try { ApiModel model = TDCommom.ObjectExtensions.FromJsonString <ApiModel>(data); List <CellInfoModel> list = cellDB.GetCellInfoBystate(model.Data); if (list.Count > 0) { res = TDCommom.ObjectExtensions.ToJsonString(list); } TDCommom.Logs.Info(string.Format("根据状态查找电芯信息:接收参数:{0}\r\\n 返回参数:{1} \r\n", data, res)); return(res); } catch (Exception ex) { TDCommom.Logs.Error(string.Format("根据状态查找电芯信息异常:接收参数:{0}\r\\n 异常信息:{1} \r\n", data, ex.Message)); return(res); } }
// [AllowAnonymous] // [ValidateAntiForgeryToken] public async Task <IActionResult> ResetPassword([FromBody] ResetPasswordBindings bindings) { var id = bindings.Id; var resetFormURL = bindings.resetFormURL ?? ""; // TODO: validate model here or with a filter ? // TODO: do we really need the email confirmation ? var user = await _userManager.FindByIdAsync(id); if (user == null) // || !(await _userManager.IsEmailConfirmedAsync(user)) { _logger.LogWarning("Invalid forgot password attempt."); // Don't reveal that the user does not exist or is not confirmed return(Ok(ApiModel.AsError <string>(null, "user does not exist"))); } // For more information on how to enable account confirmation and password reset please // visit https://go.microsoft.com/fwlink/?LinkID=532713 var code = await _userManager.GeneratePasswordResetTokenAsync(user); var values = new { id = user.Id, code = code }; var callbackUrl = Url.Action( action: nameof(AccountController.ResetPassword), controller: nameof(AccountController).ToLowerInvariant().Replace("controller", ""), values: values, protocol: Request.Scheme, host: Request.Host.Value); var encodedCallback = WebUtility.UrlEncode(callbackUrl); var link = $"{resetFormURL}?action={encodedCallback}"; var result = new ResetPasswordResult { Id = id, Code = code, Link = link, Username = user.UserName }; result.sent = bindings.email && await _emailSender.SendEmailAsync(user.Email, "Reset Password", $"Please reset your password by clicking here: <a href='{link}'>link</a>"); return(Ok(ApiModel.AsSuccess <ResetPasswordResult>(result))); }
public async Task <HttpResponseMessage> createRescheduleRequest(ApiModel inputmodel) { bool data = false; try { ApiResponseModel <bool> model = new ApiResponseModel <bool>() { }; var client = ServiceFactory.GetService(typeof(PatientVisitAppointment)); data = await client.createRescheduleRequest(inputmodel.workOrderId, inputmodel.startDate, inputmodel.endDate); model.data.records = data; return(Response.Success <bool>(model)); } catch (Exception ex) { return(Response.Exception(ex)); } }
// [ValidateAntiForgeryToken] public async Task <IActionResult> ChangePassword([FromBody] ChangePasswordBindings bindings) { var username = HttpContext.User.Identity.Name; if (string.IsNullOrEmpty(username)) { return(Ok(ApiModel.AsError <AccountDto>(null, "no user claims in request, did you forget to set the auth header ?"))); } var user = await _userManager.FindByNameAsync(username); if (user == null) { return(Ok(ApiModel.AsError <AccountDto>(null, $"impossible to find a user with the username '{username}'"))); } var result = await _userManager.ChangePasswordAsync(user, bindings.currentPassword, bindings.newPassword); var userDto = _mapper.Map <AccountDto>(user); return(Ok(ApiModel.FromIdentityResult <AccountDto>(userDto, result))); }
public SearchListResponse VideosForChannel(ApiModel model) { //Convert string orderby to the enum that we expect try { var order = (SearchResource.ListRequest.OrderEnum)Enum.Parse(typeof(SearchResource.ListRequest.OrderEnum), model.OrderBy, true); //Go & get the videos var channelVideos = YouTubeHelper.GetVideosForChannel(model.PageToken, model.ChannelId, model.SearchQuery, order); //Return the response from YouTube API return channelVideos; } catch (ArgumentException) { var message = new HttpResponseMessage(HttpStatusCode.BadRequest); message.Content = new StringContent("Order by cannot be converted to the enum"); throw new HttpResponseException(message); } }
public async Task <HttpResponseMessage> getPateintProcedure(ApiModel inputmodel) { List <PatientProcedure> data = new List <PatientProcedure>(); int CurrentPage = Convert.ToInt32(inputmodel.currentpage); if (CurrentPage < 0) { return(Response.Error("App", "current page is not valid")); } try { ApiResponseModel <List <PatientProcedure> > model = new ApiResponseModel <List <PatientProcedure> >() { }; var client = ServiceFactory.GetService(typeof(PatientProcedure)); data = await client.getPatientOrder(inputmodel.patientId, inputmodel.patientEncounterId, inputmodel.SearchFilters, inputmodel.searchOrder, inputmodel.startDate, inputmodel.endDate, inputmodel.forFulfillment, inputmodel.orderId, inputmodel.CaseId, true, CurrentPage); if (data != null) { //if (!string.IsNullOrEmpty(inputmodel.patientEncounterId)) //model.data.hasDiagnosis = new PatientDiagnosis().hasDiagnosis(inputmodel.patientEncounterId); if (data.Count > 0) { model.data.dateRange.startDate = String.Format("{0:yyyy-MM-dd}", data.Last <PatientProcedure>().CreatedOn); model.data.dateRange.endDate = String.Format("{0:yyyy-MM-dd}", data.First <PatientProcedure>().CreatedOn); } model.data.records = data; model.data.pagination.currentPage = CurrentPage.ToString(); model.data.pagination.totalCount = Pagination.totalCount.ToString(); } return(Response.Success <List <PatientProcedure> >(model)); } catch (Exception ex) { return(Response.Exception(ex)); } }
public async Task <HttpResponseMessage> getVisitTrackingDetails(ApiModel inputmodel) { PatientVisitTracking data = null; try { ApiResponseModel <PatientVisitTracking> model = new ApiResponseModel <PatientVisitTracking>() { }; var client = ServiceFactory.GetService(typeof(PatientVisitTracking)); data = await client.getVisitTrackingDetails(inputmodel.workOrderId); model.data.records = data; return(Response.Success <PatientVisitTracking>(model)); } catch (Exception ex) { return(Response.Exception(ex)); } }
/* * Api - ApiModel */ public static Api ToEntity(this ApiModel model) { if (model == null) { return(null); } return(new Api { Id = string.IsNullOrEmpty(model.Id) ? 0 : int.Parse(model.Id), HttpMethod = model.HttpMethod, Name = model.Name, ServiceId = int.Parse(model.ServiceId), Url = model.Url, OwnerKeyId = int.Parse(model.OwnerKeyId), CustomHeaders = model.CustomHeaders.ToJson(), CreateDate = model.CreateDate.ToDbTime(), ModifiedDate = model.ModifiedDate.ToDbTime() }); }
public static ApiModel Parse(JObject root, IEnumerable<string> searchPaths) { var name = (string)root["name"]; var api = new ApiModel(name, ParseDependencies(root, searchPaths)); // Translations and enumerations only need a single processing phase. ParseTranslations(root, api); ParseEnumerations(root, api); // Structure and interface models must be declared first, and // then defined in a second pass to prevent definition order problems. DeclareStructures(root, api); DeclareInterfaces(root, api); DefineStructures(root, api); DefineInterfaces(root, api); // Functions may reference any of the above, but cannot be referenced themselves, // and so can be parsed in one pass at the end. ParseFunctions(root, api); return api; }
public string ToMarkdown(string fileContent, string author = "niltor") { var localSettings = ApplicationData.Current.LocalSettings; author = localSettings.Values["Author"] as string; var LocalUrl = localSettings.Values["LocalUrl"] as string; var ActualUrl = localSettings.Values["ActualUrl"] as string; string result = null; try { var model = PostManJson.FromJson(fileContent); var api = new ApiModel { Name = model.Info.Name, Email = $"{author}@msdev.cc", Author = author, LocalUrl = LocalUrl, ReplaceUrl = ActualUrl }; //设置说明内容 api.Introduction = @""; //设置环境变量 api.Env = new Dictionary <string, string> { { "{{header_token}}", "Access-Token" }, { "{{header_uuid}}", "UUID" } }; result = api.ToMarkdown(model.Item); } catch (Exception e) { //Console.WriteLine("内容解析出错"); var dialog = new MessageDialog("内容解析出错"); dialog.ShowAsync(); } return(result); }
public IActionResult UpdateContest([FromBody] ApiModel body) { Contest updateData = JsonConvert .DeserializeObject <Contest>(body.Content); Contest editedContest = dbContext.Contests .SingleOrDefault(c => c.ContestID == updateData.ContestID); editedContest.Title = updateData.Title; if (IsPowerOfTwo(updateData.MaxContestants)) { editedContest.MaxContestants = updateData.MaxContestants; } editedContest.UpdatedAt = DateTime.Now; dbContext.SaveChanges(); var res = new { success = true, editedContest }; return(Json(res)); }
public string GetInstoveSimcard(string data) { try { string res = string.Empty; ApiModel apimodel = TDCommom.ObjectExtensions.FromJsonString <ApiModel>(data); HighTemperatureDetailModel model = htd.GetInstoveSimcard(apimodel.id, apimodel.Data, apimodel.Type); if (model != null) { res = TDCommom.ObjectExtensions.ToJsonString(model); } TDCommom.Logs.Info(string.Format("入炉获取门号 接收数据:{0} \r\n 返回数据:{1} \r\n", data, res)); return(res); } catch (Exception ex) { TDCommom.Logs.Error(string.Format("入炉获取门号异常 接收数据:{0} \r\n 异常信息:{1} \r\n", data, ex.Message)); return(null); } }
/// <summary> /// Parses interface method model definitions within a JSON tree. /// </summary> /// <param name="root">The root of the JSON tree for the interface.</param> /// <param name="api">The API model being constructed.</param> /// <returns>A list of interface method models.</returns> static List<MethodModel> ParseInterfaceMethods(JObject root, ApiModel api) { var results = new List<MethodModel>(); JToken items; if (root.TryGetValue("methods", out items)) { foreach (var item in items) { var key = (string)item["key"]; var type = api.FindType((string)item["type"]); var index = int.Parse(item["index"].Value<string>()); var model = new MethodModel(api, key, type, index); foreach (var parameter in ParseFunctionParameters(item as JObject, api)) model.AddParameter(parameter); results.Add(model); } } return results; }
/// <summary> /// Parses function model definitions within a JSON tree. /// </summary> /// <param name="root">The root of the API JSON tree.</param> /// <param name="api">The API model being constructed.</param> static void ParseFunctions(JObject root, ApiModel api) { JToken items; if (root.TryGetValue("functions", out items)) { foreach (var item in items) { var key = (string)item["key"]; var type = api.FindType((string)item["type"]); var model = api.AddFunction(key, type); foreach (var parameter in ParseFunctionParameters(item as JObject, api)) model.AddParameter(parameter); } } }
/// <summary> /// Parses method parameter model definitions within a JSON tree. /// </summary> /// <param name="root">The root of the JSON tree for the method.</param> /// <param name="api">The API model being constructed.</param> /// <returns>A list of method parameter models.</returns> static IEnumerable<ParameterModel> ParseFunctionParameters(JObject root, ApiModel api) { var results = new List<ParameterModel>(); JToken items; if (root.TryGetValue("parameters", out items)) { foreach (var item in items) { var key = (string)item["key"]; var type = api.FindType((string)item["type"]); var flags = ParseInterfaceMethodParameterFlags(item as JObject); JToken indirection; (item as JObject).TryGetValue("indirection", out indirection); JToken length; (item as JObject).TryGetValue("size", out length); results.Add(new ParameterModel( key, type, indirection != null ? (int)indirection : 0, flags, length != null ? (string)length : null )); } } return results; }
/// <summary> /// Parses enumeration model definitions within a JSON tree. /// </summary> /// <param name="root">The root of the API JSON tree.</param> /// <param name="api">The API model being constructed.</param> static void ParseEnumerations(JObject root, ApiModel api) { JToken items; if (root.TryGetValue("enumerations", out items)) { foreach (var item in items) { var key = (string)item["key"]; var model = api.AddEnumeration(key); foreach (var value in ParseEnumerationValues(item as JObject)) model.AddValue(value); } } }
/// <summary> /// Defines structures in an API model based on the contents of a JSON tree. /// </summary> /// <param name="root">The root of the JSON tree for the API.</param> /// <param name="api">The API model being constructed.</param> static void DefineStructures(JObject root, ApiModel api) { JToken items; if (root.TryGetValue("structures", out items)) { foreach (var item in items) { var key = (string)item["key"]; var model = (StructureModel)api.FindType(key); foreach (var value in ParseStructureMembers(item as JObject, api)) model.AddMember(value); } } }
public static string GetApiClassName(ApiModel api) { return api.Name.Split('.').Last(); }
internal StructureModel(ApiModel api, string key) : base(api, key, key) { }
/// <summary> /// Parses translation model definitions within a JSON tree. /// </summary> /// <param name="root">The root of the API JSON tree.</param> /// <param name="api">The API model being constructed.</param> static void ParseTranslations(JObject root, ApiModel api) { var results = new List<TranslationModel>(); JToken items; if (root.TryGetValue("translations", out items)) { foreach (var item in items) { var key = (string)item["key"]; var target = (string)item["target"]; api.AddTranslation(key, null, target); } } }
private async Task<ApiModel> OnAddApi(ApiCollectionModel parent) { var api = Api.Create(); if (parent == null) await Repository.AddItem(api); var model = new ApiModel(this, parent, api); if (parent == null) Items.Add(model); else parent.Items.Add(model); SelectedItem = model; return model; }
public FunctionModel(ApiModel api, string name, TypeModel returnType) { Api = api; Name = name; Type = returnType; }
protected TypeModel(ApiModel api, string key, string name) { Api = api; Key = key; Name = name; }
/// <summary> /// Parses structure member model definitions within a JSON tree. /// </summary> /// <param name="root">The root of the JSON tree for the structure.</param> /// <param name="api">The API model being constructed.</param> /// <returns>A list of structure member models.</returns> static List<StructureMemberModel> ParseStructureMembers(JObject root, ApiModel api) { var results = new List<StructureMemberModel>(); JToken items; if (root.TryGetValue("members", out items)) { foreach (var item in items) { var key = (string)item["key"]; var type = api.FindType((string)item["type"]); results.Add(new StructureMemberModel(key, type)); } } return results; }
public MethodModel(ApiModel api, string name, TypeModel returnType, int index) : base(api, name, returnType) { Index = index; }
internal InterfaceModel(ApiModel api, string key, Guid guid) : base(api, key, key) { Guid = guid; }
static void RunGenerator(ApiModel api, Configuration configuration) { var templateDirectory = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Templates"); var templateEngine = new TemplateEngine(new[] { templateDirectory }); templateEngine.RegisterCallback("ApiNamespace", (e, s) => api.Name); templateEngine.RegisterCallback("ApiName", (e, s) => TemplateCallbacks.GetApiClassName(api)); templateEngine.RegisterCallback("ApiDll", (e, s) => TemplateCallbacks.GetApiDllName(api)); templateEngine.RegisterCallbacks(typeof(TemplateCallbacks)); var outputDirectory = configuration.GeneratorOutputPath; if (!Directory.Exists(outputDirectory)) Directory.CreateDirectory(outputDirectory); ApplyTemplate(api, outputDirectory, templateEngine, "Api"); ApplyTemplate(api.Enumerations, outputDirectory, templateEngine, "Enumeration"); ApplyTemplate(api.Structures, outputDirectory, templateEngine, "Structure"); ApplyTemplate(api.Interfaces, outputDirectory, templateEngine, "Interface"); BuildTrampolineAssembly(api, outputDirectory, string.Format("{0}.Trampoline", api.Name)); }
internal EnumerationModel(ApiModel api, string key) : base(api, key, key) { }
/// <summary> /// Defines interfaces in an API model based on the contents of a JSON tree. /// </summary> /// <param name="root">The root of the JSON tree for the API.</param> /// <param name="api">The API model being constructed.</param> static void DefineInterfaces(JObject root, ApiModel api) { JToken items; if (root.TryGetValue("interfaces", out items)) { foreach (var item in items) { var key = (string)item["key"]; var model = (InterfaceModel)api.FindType(key); JToken parent = null; if ((item as JObject).TryGetValue("type", out parent)) model.Parent = api.FindType((string)parent); foreach (var method in ParseInterfaceMethods(item as JObject, api)) model.AddMethod(method); } } }
public static string GetApiDllName(ApiModel api) { switch (api.Name) { case "SlimDX.DXGI": return "dxgi.dll"; case "SlimDX.Direct3D11": return "d3d11.dll"; case "SlimDX.ShaderCompiler": return "d3dcompiler_43.dll"; default: return string.Empty; } }