//slow function //public bool Add(string path = "") //{ // if (!Initialized) // return false; // string commandline = string.Empty; // if (!string.IsNullOrEmpty(path)) // { // commandline = string.Format(" add \"{0}\" * --force", path); // } // commandline += GetAuthenCmd(); // ProcessCommand(commandline); // return true; //} public bool AddFile(string path = "") { if (!Initialized) { return(false); } string commandline = string.Empty; if (!string.IsNullOrEmpty(path)) { commandline = string.Format(" add \"{0}\" --force", path); } commandline += GetAuthenCmd(); ProcessCommand(commandline); if (OutputResult.Contains("Can't find parent")) { string parent = path.Remove(path.LastIndexOf('\\')); AddFile(parent); } return(true); }
public bool TestSVNConnect() { //if (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(Password)) // return false; string commandline = " up dummy"; string authen = string.Format(" --non-interactive --username {0} --password {1}", UserName, Password); commandline += authen; OutputResult = ProcessCommand(commandline); //if (string.IsNullOrEmpty(OutputResult)) //{ // return false; //} if (OutputResult.Contains("No repository found") || OutputResult.Contains("Authentication realm") || OutputResult.Contains("Authentication error") || OutputResult.Contains("Can't connect to host")) { // UEEngine.UELogMan.LogError("TestSVNConnect error: " + OutputResult); return(false); } return(true); }
public bool Update(string path = "") { if (!Initialized) { return(false); } string commandline; if (string.IsNullOrEmpty(path)) { commandline = " update --accept tf"; } else { commandline = string.Format(" update \"{0}\" --accept tf", path); } commandline += GetAuthenCmd(); OutputResult = ProcessCommand(commandline); if (OutputResult.Contains("Error")) { return(false); } ShowSvnError(OutputResult); return(true); }
public MessageBatchTableEntity(OutputResult result) : this(result.MessageId, result.BatchId) { this.BatchSize = result.Targets?.Count ?? 0; this.State = $"outcome={result.DeliveryResponse.DeliveryOutcome}, delivered={result.Delivered}"; this.LastUpdateTime = DateTime.UtcNow; }
public async Task OnMessageDispatchedAsync(OutputResult outputResult) { // If dispatch failed, update the history table with target -1 if (!outputResult.Delivered) { var historyTable = await GetHistoryTableAsync(outputResult.EngagementAccount); var historyEntity = new MessageHistoryTableEntity(outputResult.EngagementAccount, outputResult.MessageId.ToString()); if (historyEntity == null) { EmailProviderEventSource.Current.Warning(EmailProviderEventSource.EmptyTrackingId, this, nameof(this.OnMessageDispatchedAsync), OperationStates.Dropped, $"Does not find record for messageId={outputResult.MessageId}"); return; } historyEntity.Targets = -1; await MessageHistoryTableEntity.InsertOrMergeAsync(historyTable, historyEntity); } // If succeed, update the in-progress table else { // Insert in-progress table var inProgressEntity = new ReportInProgressTableEntity(outputResult.EngagementAccount, outputResult.MessageId, outputResult.DeliveryResponse.CustomMessageId); await ReportInProgressTableEntity.InsertOrMergeAsync(reportInProgressTable, inProgressEntity); } }
/// <summary> /// Returns a new <see cref="T:iTin.Utilities.Pdf.ComponentModel.OutputResult" /> reference thats represents a one <b>unique zip stream</b> that contains the same entries in <param ref="items"/> /// but compressed individually using the name in <param ref="filenames"/>. /// </summary> /// <param name="items">Items</param> /// <param name="filenames">Item filenames.</param> /// <returns> /// A <see cref="T:iTin.Core.ComponentModel.OutputResult" /> reference that contains action result. /// </returns> public static OutputResult CreateJoinResult(this IEnumerable <PdfInput> items, IEnumerable <string> filenames) { IList <PdfInput> elementList = items as IList <PdfInput> ?? items.ToList(); SentinelHelper.ArgumentNull(elementList, nameof(elementList)); IList <string> filenameList = filenames as IList <string> ?? filenames.ToList(); SentinelHelper.ArgumentNull(filenameList, nameof(filenameList)); try { Stream zippedStream = elementList.ToStreamEnumerable().AsZipStream(filenameList); zippedStream.Position = 0; return (OutputResult.CreateSuccessResult( new OutputResultData { Zipped = true, Configuration = null, UncompressOutputStream = zippedStream })); } catch (Exception e) { return(OutputResult.FromException(e)); } }
public UploadCompletedEventArgs(DateTime time, IUploadable uploadedData, OutputResult outputResult, bool uploaded) { this.UploadTime = time; this.UploadedData = uploadedData; this.UploadedResult = outputResult; this.HasSuccessfulUploaded = uploaded; }
/// <summary> /// Complete Enrolled Module /// </summary> /// <param name="input">Object of Enrollem Module Model</param> /// <returns>Result of Update an enrolled module</returns> public async Task <OutputResult> CompleteEnrolledModule(Input <EnrollModuleModel> input) { try { // Input Validation if (!input.Validate) { return(OutputResult.FailOutputResult(Constant.InvalidInput)); } // Varciable Init var model = input.Arguments; // Retrive Entities var enrollment = UnitOfWork.Enrollments.GetEnrollModule(model.ModuleId, model.EnrollmentId); // Process Entities enrollment.IsCompleted = true; enrollment.LastVisited = DateTime.Now; // Commit Transaction await UnitOfWork.Commit(); // Retrun Success Output return(OutputResult.SuccessOutputResult()); } catch (Exception exception) { // Failed Output in case of exception return(OutputResult.FailOutputResult(Constant.ErrorOccured, description: exception.ToString())); } }
public ConcurrentQueue <RecognitionInfo> MakePrediction(List <String> images) //doesnt check in db context { MessageToUser?.Invoke(this, "If you want to stop recognition press ctrl + C"); CancellationToken token = cancel.Token; try { ParallelOptions po = new ParallelOptions(); po.CancellationToken = token; po.MaxDegreeOfParallelism = Environment.ProcessorCount; var tasks = Parallel.ForEach <string>(images, po, img => { CQ.Enqueue(ProcessImage(img)); OutputResult?.Invoke(this, CQ); }); } catch (OperationCanceledException) { MessageToUser?.Invoke(this, "-----------------Interrupted-----------------"); Trace.WriteLine("-----------------Interrupted-----------------"); } catch (Exception e) when(e is ArgumentException || e is IOException) { Trace.WriteLine(e.Message); }; return(CQ); }
public async Task <IActionResult> GetSegment([FromRoute] int id) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } int tripId = _context.Segments.Where(i => i.Id == id).Select(i => i.TripId).First(); string name = _context.Trips.Where(i => i.Id == tripId).Select(i => i.Name).Single(); var segment = await _context.Segments.FindAsync(id); var item = new OutputResult() { Name = segment.Name, TripName = name, Description = segment.Description }; if (segment == null) { return(NotFound()); } return(Ok(item)); }
public bool CommitForceAdd(string path = "", string message = "autoCommit") { if (!Initialized) { return(false); } string messagestr = "[提交类型][修改说明]" + message + "[相关禅道][所属版本][验证情况]"; string commandline; if (string.IsNullOrEmpty(path)) { commandline = string.Format(" commit -m \"{0}\"", messagestr); } else { commandline = string.Format(" commit \"{0}\" -m \"{1}\"", path, messagestr); } commandline += GetAuthenCmd(); ProcessCommand(commandline); if (OutputResult.Contains("Commit failed")) { if (OutputResult.Contains("not under version control")) { AddFile(path); return(Commit(path, message)); } return(false); } return(true); }
public bool Lock(string filename) { if (!Initialized) { return(false); } string commandline = string.Format(" lock {0} ", filename); commandline += GetAuthenCmd(); ProcessCommand(commandline); if (OutputResult.Contains("is already locked by")) { int pos = 0; pos = OutputResult.IndexOf('\'', pos + 1); pos = OutputResult.IndexOf('\'', pos + 1); int start = OutputResult.IndexOf('\'', pos + 1); int end = OutputResult.IndexOf('\'', start + 1); string name = OutputResult.Substring(start + 1, end - start - 1); if (name != UserName) { UnityEditor.EditorUtility.DisplayDialog("Error", OutputResult, "OK"); return(false); } } OutputResult = ""; return(true); }
/// <summary> /// Add an enrollment /// </summary> /// <param name="input">Object of Enrollment Model</param> /// <returns>Result of Adding an enrollment</returns> public async Task <OutputResult> AddEnrollment(Input <EnrollmentModel> input) { try { // Input validate if (!input.Validate) { return(OutputResult.FailOutputResult(Constant.InvalidInput)); } // Variable init var datetime = DateTime.UtcNow; var model = input.Arguments; // Retrive Entities var enrollment = UnitOfWork.Enrollments.FirstOrDefault(e => e.StudentId == model.StudentId & e.CourseId == model.CourseId); // Validate ENtities if (enrollment != null) { return(OutputResult.FailOutputResult(Constant.AlreadyEnrolled)); } // Process Entities var enrollmentId = Generator.UniqueIdentifier; var course = UnitOfWork.Courses.GetCourse(model.CourseId); var enrollModules = course.Modules.Select(m => new Entities.EnrollModule { ModuleId = m.Id, EnrollmentId = enrollmentId, IsCompleted = false, IsStarted = false }).ToList(); // Adding Enrollment UnitOfWork.Enrollments.Add(new Entities.Enrollment { Id = enrollmentId, CreateBy = input.OperationBy, UpdateBy = input.OperationBy, CreateDate = datetime, UpdateDate = datetime, CourseId = model.CourseId, StudentId = model.StudentId, EnrollModules = enrollModules }); // Commit Transaction await UnitOfWork.Commit(); // Success Output return(OutputResult.SuccessOutputResult()); } catch (Exception exception) { // Failed Output in case of exception return(OutputResult.FailOutputResult(Constant.ErrorOccured, description: exception.ToString())); } }
public string DocumentStatus(HttpListenerContext ct, ActionInfo hi) { OutputResult output = GetRequestObject <OutputResult>(ct); BoolValue bv = new BoolValue(); bv.Value = true; return(GetResponseString <BoolValue>(bv, ct)); }
/// <summary> /// Processes <paramref name="rawAddressData"/> with the RegEx set up in <typeparamref name="TOutputFormat"/>. /// </summary> /// <remarks>The input and output manipulation functions will also be processed.</remarks> /// <param name="rawAddressData">The input string.</param> /// <exception cref="ArgumentNullException"><see cref="IOutputFormat.MatchingRegex"/> must be set up correctly in the generic class.</exception> /// <exception cref="MissingMemberException">Should contain at least one <see cref="RegexGroupAttribute"/>.</exception> /// <example> /// This sample shows how to call the <see cref="AddressSeparationProcessor{TOutputFormat}"/> constructor. /// <code> /// class TestClass /// { /// static int Main() /// { /// var processor = new AddressSeparationProcessor{GermanSimpleOutputFormat}(); /// var result = processor.Process('Teststraße 123a'); /// var address = result.ResolvedAddress; /// /// Console.WriteLine($"Name is {address.StreetName} with number {address.HouseNumber} and affix {address.HouseNumberAffix}"); /// } /// } /// </code> /// </example> /// <returns>The resolved address along with info about the processing.</returns> public OutputResult <TOutputFormat> Process(string rawAddressData) { // sanity check var outputFormatInstance = Activator.CreateInstance(typeof(TOutputFormat)) as IOutputFormat; _ = outputFormatInstance.MatchingRegex ?? throw new ArgumentNullException(nameof(outputFormatInstance.MatchingRegex)); Options = Options ?? new DefaultProcessingOptions(); // create output instance var outputResult = new OutputResult <TOutputFormat>(rawAddressData); // return empty result, if input is empty if (String.IsNullOrWhiteSpace(rawAddressData)) { return(outputResult); } // call user defined input functions rawAddressData = this.ProcessInputManipulationQueue(rawAddressData); // get all properties w/ RegexGroupAttribute and throw exception if there is none var propertyRegexGroupCollection = OutputFormatHelper.GetPropertyRegexGroups(typeof(TOutputFormat)); if (Options.ThrowIfNoRegexGroupPropertyProvided && propertyRegexGroupCollection.Any() == false) { throw new MissingMemberException($"Class {typeof(TOutputFormat).Name} has no property members with {nameof(RegexGroupAttribute)}."); } // assign to Regex bindings var match = outputFormatInstance.MatchingRegex.Match(rawAddressData); if (match.Success) { foreach (var prop in propertyRegexGroupCollection) { // get first matching group value; null, if no group is matching string valueOfGroup = null; do { // get groups one by one and manipulate if necessary var currentGroup = prop.RegexGroupCollection.Dequeue(); valueOfGroup = match.Groups[currentGroup.RegexGroupIndex]?.Value; valueOfGroup = this.ProcessOutputManipulation(valueOfGroup, currentGroup); // set value to instance member this.SetPropertyValue(prop.Property, outputResult.GetInstance(), valueOfGroup); } while (prop.RegexGroupCollection.Count > 0 && String.IsNullOrWhiteSpace(valueOfGroup)); } // set success outputResult.AddressHasBeenResolved = true; } // return filled instance return(outputResult); }
public override void FindModel() { HImage img = InputImg; if (SearchRegion == null || !SearchRegion.IsInitialized()) { SearchRegion = img.GetDomain(); } if (createNewModelID) { if (!CreateNccModel()) { return; } } if (!nCCModel.IsInitialized()) { throw new Exception("无创建的模板"); } HRegion domain = img.GetDomain(); HRegion differentdomain = domain.Difference(SearchRegion); HImage searchImg = img.PaintRegion(differentdomain, 0.0, "fill"); HImage cropImg = searchImg.ReduceDomain(SearchRegion); domain.Dispose(); differentdomain.Dispose(); OutputResult.Reset(); try { double t1, t2; t1 = HSystem.CountSeconds(); HOperatorSet.FindNccModel(cropImg, nCCModel, nCCParam.mStartingAngle, nCCParam.mAngleExtent, nCCParam.MinScore, nCCParam.NumMatches, nCCParam.mMaxOverlap, nCCParam.SubPixel, 0, out OutputResult.Row, out OutputResult.Col, out OutputResult.Angle, out OutputResult.Score); OutputResult.TemplateHand = nCCModel; t2 = HSystem.CountSeconds(); OutputResult.Time = 1000.0 * (t2 - t1); OutputResult.Count = OutputResult.Row.Length; } catch (HOperatorException ex) { if (ex.GetErrorCode() != 9400) { throw ex; } } searchImg.Dispose(); cropImg.Dispose(); }
public void NoManipulation_ReturnCorrectValues(string input, string streetName, short?houseNumber, string houseNumberAffix) { // act OutputResult <GermanSimpleOutputFormat> result = _processor.Process(input); GermanSimpleOutputFormat address = result.ResolvedAddress; // assert Assert.AreEqual(streetName, address.StreetName); Assert.AreEqual(houseNumber, address.HouseNumber); Assert.AreEqual(houseNumberAffix, address.HouseNumberAffix); }
/// <summary> /// Merges all <see cref="XlsxInput"/> entries. /// </summary> /// <returns> /// <para> /// A <see cref="OutputResult"/> reference that contains the result of the operation, to check if the operation is correct, the <b>Success</b> /// property will be <b>true</b> and the <b>Value</b> property will contain the value; Otherwise, the the <b>Success</b> property /// will be false and the <b>Errors</b> property will contain the errors associated with the operation, if they have been filled in. /// </para> /// <para> /// The type of the return value is <see cref="OutputResultData"/>, which contains the operation result /// </para> /// </returns> public OutputResult TryMergeInputs() { Logger.Instance.Debug(""); Logger.Instance.Debug(" Assembly: iTin.Utilities.Xlsx.Writer, Namespace: iTin.Utilities.Xlsx.Writer, Class: XlsxObject"); Logger.Instance.Debug($" Merges all {typeof(XlsxInput)} entries into a new {typeof(XlsxObject)}"); Logger.Instance.Debug($" > Signature: ({typeof(OutputResult)}) TryMergeInputs()"); var items = Items.ToList(); //if (Configuration.UseIndex) //{ // items = items.OrderBy(i => i.Index).ToList(); //} try { MemoryStream outStream = new MemoryStream(); //MergeFiles(items.Select(item => item.ToStream())); if (Configuration.DeletePhysicalFilesAfterMerge) { foreach (var item in items) { var inputType = item.InputType; if (inputType != KnownInputType.Filename) { continue; } if (item.DeletePhysicalFilesAfterMerge) { File.Delete(TypeHelper.ToType <string>(item.Input)); } } } var safeOutAsByteArray = outStream.GetBuffer(); var outputInMegaBytes = (float)safeOutAsByteArray.Length / XlsxObjectConfig.OneMegaByte; var generateOutputAsZip = outputInMegaBytes > Configuration.CompressionThreshold; var zipped = Configuration.AllowCompression && generateOutputAsZip; return (OutputResult.CreateSuccessResult( new OutputResultData { Zipped = zipped, Configuration = Configuration, UncompressOutputStream = safeOutAsByteArray.ToMemoryStream() })); } catch (Exception ex) { return(OutputResult.FromException(ex)); } }
public OutputResult Single(string id) { var student = dbContext.Students.FirstOrDefault(x => x.StudentID == Convert.ToInt64(id)); if (student == null) { return(OutputResult.Failed("不存在此学生")); } return(OutputResult <Student> .Success(student)); }
// Update is called once per frame void Update() { if (phase == 0) { if (Input.GetKeyDown(KeyCode.N)) { PracStartText.SetActive(false); OutputResult.output(0, 0); FixedCrossPart1.SetActive(true); FixedCrossPart2.SetActive(true); phase++; } } else if (phase == 1) { if (nowTrial != nPracTrials) { DoTrial(); } else { FixedCrossPart1.SetActive(false); FixedCrossPart2.SetActive(false); AutoPusher.AKeyDown = false; StartText.SetActive(true); phase++; } } else if (phase == 2) { if (Input.GetKeyDown(KeyCode.N)) { StartText.SetActive(false); FixedCrossPart1.SetActive(true); FixedCrossPart2.SetActive(true); phase++; } } else if (phase == 3) { if (nowTrial != nPracTrials + nTrials) { DoTrial(); } else { FixedCrossPart1.SetActive(false); FixedCrossPart2.SetActive(false); EndText.SetActive(true); phase++; } } }
public async Task <OutputResult <AccessToken> > GetToken([FromBody] UserInfo user) { var result = new OutputResult <AccessToken>(); try { if (string.IsNullOrEmpty(user.UserName)) { throw new ArgumentNullException("UserName", "用户名不能为空!"); } if (string.IsNullOrEmpty(user.Password)) { throw new ArgumentNullException("password", "密码不能为空!"); } //验证用户名和密码 //var userInfo = await _UserService.CheckUserAndPassword(mobile: user, password: password); UserService userService = new UserService(); var userInfo = userService.GetUser(user.UserName, user.Password); var claims = new Claim[] { new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.NameIdentifier, userInfo.Id.ToString()), }; var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Configuration["JwtSecurityKey"])); var expires = DateTime.Now.AddMinutes(1); // var token = new JwtSecurityToken( issuer: Configuration["issuer"], audience: Configuration["audience"], claims: claims, notBefore: DateTime.Now, expires: expires, signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)); //生成Token string jwtToken = new JwtSecurityTokenHandler().WriteToken(token); result.Code = "1"; result.Data = new AccessToken() { Token = jwtToken }; result.Message = "授权成功!"; return(result); } catch (Exception ex) { result.Message = ex.Message; result.Code = "0"; return(result); } }
public JsonResult VerifyStudent([FromBody] StudentModel studentModel) { try { return(Json(StudentService.VerifyStudent(new Input <StudentModel> { Arguments = studentModel }))); } catch (Exception exception) { return(Json(OutputResult.FailOutputResult(exception.Message))); } }
// Update is called once per frame void Update() { SteamVR_TrackedObject trackedObject = GetComponent <SteamVR_TrackedObject>(); var device = SteamVR_Controller.Input((int)trackedObject.index); if (ObjectMotion.phase == 0) { if (device.GetPressDown(SteamVR_Controller.ButtonMask.Touchpad)) { Vector2 touchPosition = device.GetAxis(); if (touchPosition.y > 0) { Debug.Log("Press UP"); } else if (touchPosition.y < 0) { Debug.Log("Press DOWN"); } } else if (device.GetPressDown(SteamVR_Controller.ButtonMask.Trigger)) { Debug.Log("Pull Trigger"); } } if (ObjectMotion.SpaceKeyDown == true) { if (device.GetPressDown(SteamVR_Controller.ButtonMask.Touchpad)) { Vector2 touchPosition = device.GetAxis(); resp = true; ObjectMotion.SpaceKeyDown = false; if (touchPosition.y > 0) { Debug.Log("Press UP"); OutputResult.output(1, 0); } else if (touchPosition.y < 0) { Debug.Log("Press DOWN"); OutputResult.output(1, 1); } } else if (device.GetPressDown(SteamVR_Controller.ButtonMask.Trigger)) { resp = true; ObjectMotion.SpaceKeyDown = false; Debug.Log("Pull Trigger"); OutputResult.output(1, -1); } } }
public static void LimitLength(this OutputResult result, int lengthLimit, string appendMessage = null) { if (result?.Output == null) { return; } appendMessage = result.Output.Length <= lengthLimit ? string.Empty : appendMessage ?? string.Format(ExceededOutputMaxLengthDefaultWarningMessageFormat, lengthLimit); result.Output = result.Output.MaxLength(lengthLimit) + appendMessage; }
public async Task OnDispatchCompleteAsync(OutputResult outputResult) { // If dispatch failed, upate the telemetry if (!outputResult.Delivered && outputResult.Targets != null && outputResult.Targets.Count > 0) { // Update record detail var details = outputResult.Targets.Select(t => new ReportDetail { PhoneNumber = t, MessageId = outputResult.MessageId.ToString(), State = ErrorCodeHelper.ConvertMessageStateFromRequestOutcome(outputResult.DeliveryResponse.DeliveryOutcome), StateDetail = outputResult.DeliveryResponse.DeliveryDetail }).ToList(); var updated = await this.UpdateReportAndDetails(details, outputResult.ConnectorIdentifier); // Update agent meta if agent exist var key = this.GetAgentKey(outputResult.ConnectorIdentifier); if (updated > 0 && !string.IsNullOrEmpty(key) && this.agents.TryGetValue(key, out ReportAgent agent)) { var meta = await this.store.GetAgentMetadataAsync(outputResult.ConnectorIdentifier); if (meta != null) { meta.PendingReceive -= Math.Min(outputResult.Targets.Count, meta.PendingReceive); await this.store.CreateOrUpdateAgentMetadataAsync(meta); if (meta.PendingReceive <= 0) { SmsProviderEventSource.Current.Info(SmsProviderEventSource.EmptyTrackingId, this, nameof(this.OnDispatchCompleteAsync), OperationStates.Succeeded, $"Report agent stopping (complete). connectorName={agent.Credential.ConnectorName} connectorKey={agent.Credential.ConnectorId}"); agent.UnSubscribe(); } } } } // If succeed with custom message Id, update the summary else if (outputResult.Delivered && !string.IsNullOrEmpty(outputResult.DeliveryResponse.CustomMessageId)) { await this.telemetryManager.OnMessageDispatchedAsync( outputResult.EngagementAccount, outputResult.MessageId.ToString(), outputResult.DeliveryResponse.CustomMessageId, outputResult.Targets.ToList(), outputResult.ConnectorIdentifier); } await this.telemetryManager.InsertMessageBatchRecordAsync(outputResult); }
/// <summary> /// Returns a new reference <see cref="OutputResult"/> that complies with what is indicated in its configuration object. By default, this <see cref="XlsxInput"/> will not be zipped. /// </summary> /// <param name="config">The output result configuration.</param> /// <returns> /// <para> /// A <see cref="OutputResult"/> reference that contains the result of the operation, to check if the operation is correct, the <b>Success</b> /// property will be <b>true</b> and the <b>Result</b> property will contain the Result; Otherwise, the the <b>Success</b> property /// will be false and the <b>Errors</b> property will contain the errors associated with the operation, if they have been filled in. /// </para> /// <para> /// The type of the return Result is <see cref="OutputResultData"/>, which contains the operation result /// </para> /// </returns> public OutputResult CreateResult(OutputResultConfig config = null) { OutputResultConfig configToApply = OutputResultConfig.Default; if (config != null) { configToApply = config; configToApply.Filename = NativeIO.Path.ChangeExtension( string.IsNullOrEmpty(config.Filename) ? File.GetUniqueTempRandomFile().Segments.LastOrDefault() : config.Filename, XlsxExtension); } try { if (configToApply.AutoFitColumns) { Set(new SetAutoFitColumns()); } Set(new SetSheetsSettings { Settings = configToApply.GlobalSettings.SheetsSettings }); Set(new SetDocumentSettings { Settings = configToApply.GlobalSettings.DocumentSettings }); if (!configToApply.Zipped) { return(OutputResult.CreateSuccessResult( new OutputResultData { Zipped = false, Configuration = configToApply, UncompressOutputStream = Clone().ToStream() })); } OutputResult zippedOutputResult = OutputResult.CreateSuccessResult(null); // new[] { Clone() }.CreateJoinResult(new[] { configToApply.Filename }); //zippedOutputResult.Result.Configuration = configToApply; return(zippedOutputResult); } catch (Exception e) { return(OutputResult.FromException(e)); } }
public OutputResult Add([FromForm] Student student) { if (dbContext.Students.FirstOrDefault(x => x.StudentID == student.StudentID) != null) { return(OutputResult.Failed("已存在此学号")); } dbContext.Students.Add(student); if (dbContext.SaveChanges() < 1) { return(OutputResult.Failed("添加失败")); } return(OutputResult.Success()); }
public OutputResult List(string id, string domitoryId) { var temp = dbContext.Students.AsEnumerable(); if (!string.IsNullOrEmpty(id)) { temp = temp.Where(x => x.StudentID == Convert.ToInt64(id)); } if (!string.IsNullOrEmpty(domitoryId)) { temp = temp.Where(x => x.RoomNumber == Convert.ToInt64(domitoryId)); } return(OutputResult <List <Student> > .Success(temp.ToList())); }
public JsonResult CompleteEnrollModule([FromBody] EnrollModuleModel enrollModuleModel) { try { return(Json(EnrollmentService.CompleteEnrolledModule(new Input <EnrollModuleModel> { OperationBy = "System", Arguments = enrollModuleModel }))); } catch (Exception exception) { return(Json(OutputResult.FailOutputResult(exception.Message))); } }
/// <summary> /// 记录上传情况:上传时间、上传数据、返回结果 /// </summary> /// <param name="time"></param> /// <param name="data"></param> /// <param name="result"></param> private void SaveUpload(DateTime time, IUploadable data, OutputResult result) { bool is_success = false; string code = result.code; string status = result.data?.SelectToken("status")?.ToString(); if (OutputCode.成功.Equals(code) && AsyncStatus.处理成功.Equals(status)) { is_success = true; } string sql = $"INSERT INTO upload_record ( data_type, data_id, upload_time, is_success, uploaded_data, upload_result, project_name ) VALUES ( '{ data.GetType().Name }', { data.DataId }, '{ time.ToString("yyyy-MM-dd HH:mm:ss") }', { Convert.ToInt32(is_success) }, '{ data.Serialize2JSON() }', '{ result.Serialize2JSON() }', '{ HjApiCaller.ProjectName }' );"; ArDBConnection.ExceuteSQLNoReturn(sql); }