// // GET: /NewRequest/ public ActionResult Index() { var model = new NewRequest { Holiday =new Holiday{ StartDate = DateTime.Today, EndDate = DateTime.Today, Number = 0} }; return View(model); }
public static ShelfCompliance ProcessShelfCompliance(NewRequest <SmartDoc> newReq, double threshold) { ShelfCompliance result = DocumentMapper.MapDocument <ShelfCompliance>(newReq.RequestItem); result.DetectionNotes = "Invalid Classification"; var shelfComplianceStep = newReq.RequestItem.CognitivePipelineActions.Where(s => s.StepName == InstructionFlag.ShelfCompliance.ToString()).FirstOrDefault(); if (shelfComplianceStep != null) { var classificationResult = JsonConvert.DeserializeObject <CustomVisionClassification>(shelfComplianceStep.Output); //Get the top classification for compliant and non-compliant tags var topPrediction = classificationResult.Predictions.OrderByDescending(p => p.Probability).FirstOrDefault(); if (topPrediction != null) { if (topPrediction.TagName == "Compliant") { result.IsCompliant = true; } if (topPrediction.Probability >= threshold) { result.Confidence = topPrediction.Probability; result.IsConfidenceAcceptable = true; result.PrimaryClassification = InstructionFlag.ShelfCompliance.ToString(); result.PrimaryClassificationConfidence = topPrediction.Probability; result.DetectionNotes = "Successful Classification"; } else { //Unidentified or low quality picture result.Confidence = -1; result.IsConfidenceAcceptable = false; result.PrimaryClassification = InstructionFlag.ShelfCompliance.ToString(); result.PrimaryClassificationConfidence = topPrediction.Probability; result.DetectionNotes = $"Below ({threshold}) threshold Classification"; } } } return(result); }
public async Task <JsonResult> PostMessage([FromForm] NewRequest newRequest) { if (!ModelState.IsValid) { return(new JsonResult(new Status("bad data"))); } MessageToService messageToService = JsonConvert.DeserializeObject <MessageToService>(newRequest.Message); var message = new Message() { MessageText = messageToService.messageText, Autor = messageToService.autor, Date = DateTime.Now.ToString(), RequestTask = await _repositoryRequest.GetRequestTasksAsync(messageToService.requestTaskId), Pictures = newRequest.Files != null ? await _imageService.SavePictures(newRequest.Files) : null, }; return(new JsonResult(await _repository.CreateMessagesAsync(message))); }
public override async Task GetNew(NewRequest request, IServerStreamWriter <ChatResponse> responseStream, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "Cannot get new messages at this time")); User user = _userService.GetFromToken(request.Token); if (user == null) { throw new RpcException(new Status(StatusCode.Unauthenticated, "Could not validate token")); } List <Chat> chats = _chatService.GetUserChats(user.Id); foreach (Chat c in chats) { ChatResponse cr = new ChatResponse { Id = c.Id, MessageCount = c.MessageCount }; cr.Members.AddRange(c.Members); await responseStream.WriteAsync(cr); } }
void HandleClient(object obj) { Socket client = obj as Socket; while (IsServerWork) { try { byte[] buffer = new byte[6500]; client.Receive(buffer); // Принимаем данные Guid id = Guid.NewGuid(); ActAbstract command = commandParser.ParseCommand(buffer, client); if (sender.ExistUser(client)) { NewRequest?.Invoke(DateTime.Now, command.ToString().Split('.').Last(), id, sender.GetUserID(client)); // Событие нового сообщения } else { NewRequest?.Invoke(DateTime.Now, command.ToString().Split('.').Last(), id, Guid.Empty); // Событие нового сообщения } command.Execute(); NewResponse?.Invoke(DateTime.Now, id); } catch (SocketException) { break; // Выходим из цикла } } // Заканчиваем подключение sender.RemoveUser(client); CliendDisconnect.Invoke(); client.Shutdown(SocketShutdown.Both); client.Disconnect(false); client.Dispose(); }
// This method is called frequently from the KEDA runtime. It is supposed to create and prepare all the resources required // for the GetMetrics service method to be succesful. // Here we create the irc channel client, and we keep it for the lifetime of the scaler. // Ideally, there should be a separate client for every different metric, but we currently we support one. We will change this soon. public override Task <Empty> New(NewRequest request, ServerCallContext context) { _logger.LogInformation($"{DateTime.Now} New Is Called, the problem is between the screen and the chair!"); if (_metricMetadata != null && !_metricMetadata.Equals(request.Metadata)) { _logger.LogInformation($"the _metricMetadata: {_metricMetadata} is not equal to request.Metadata: {request.Metadata}"); } //If this is the first time New is called, or the metadata has changed if (_metricMetadata == null || !_metricMetadata.Equals(request.Metadata)) { var accessToken = request.Metadata["accessToken"]; var twitchUserName = request.Metadata["twitchUserName"]; var channelName = request.Metadata["channelName"]; _logger.LogInformation($"kaboom scaler new: twitchname:{twitchUserName}, channelName:{channelName}"); ConnectionCredentials credentials = new ConnectionCredentials(twitchUserName, accessToken); var clientOptions = new ClientOptions { MessagesAllowedInPeriod = 750, ThrottlingPeriod = TimeSpan.FromSeconds(30) }; WebSocketClient customClient = new WebSocketClient(clientOptions); _client = new TwitchClient(customClient); _client.Initialize(credentials, channelName); _client.OnMessageReceived += Client_OnMessageReceived; _client.OnLog += Client_OnLog; _client.Connect(); //Save the metadata so that we can compare it the the request next time to see if it changed. _metricMetadata = request.Metadata; } return(Task.FromResult(new Empty())); }
public async Task <string> SendNewRequest(NewRequest <T> message, string id, bool IsAsync) { // TODO: Refactor out the pure HTTP calls string result = null; //Obtain Azure Function Uri and Key from the settings var uri = settings.NewReqUri + $"/{id}"; var key = settings.NewReqKey; //Prepare the message to send by converting it to JSON and add it to StringContent var jsonMessage = JsonConvert.SerializeObject(message); //Request has IsAsync which will be passed on to the function to act accordingly //If call is sync, then call the classification function directly //If call is async, queue the new request to trigger the async process var content = new StringContent(jsonMessage, Encoding.UTF8, "application/json"); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("x-functions-key", key); using (HttpResponseMessage response = client.PostAsync(uri, content).Result) using (HttpContent responseContent = response.Content) { if (response.StatusCode == System.Net.HttpStatusCode.OK) { result = await responseContent.ReadAsStringAsync(); } else { //TODO: Handle the non-200 code response messages here } } } return(result); }
public override Task <global::Google.Protobuf.WellKnownTypes.Empty> New(NewRequest request, ServerCallContext context) { string strTargetSize; if (request.Metadata.TryGetValue(_targetSizeKey, out strTargetSize)) { _logger.LogInformation($"New: targetValue string found, and it's :{strTargetSize}"); int.TryParse(strTargetSize, out _targetSize); _logger.LogInformation($"New: after assignment _targetSize now is: {_targetSize}"); } else { _logger.LogWarning($"New: targetSize is not found in the metadat"); } var foundUrl = request.Metadata.TryGetValue("urlOfService", out _urlOfService); _logger.LogInformation($"New called with url: {_urlOfService}"); if (!foundUrl) { throw new RpcException(new Status(StatusCode.InvalidArgument, "There is no urlOfService parameter")); } return(Task.FromResult <Google.Protobuf.WellKnownTypes.Empty>(new Google.Protobuf.WellKnownTypes.Empty())); }
/// <summary> /// Valida os parametros informados para criação de usuário. /// </summary> /// <param name="newUserRequest"></param> /// <returns></returns> private static AuthResult ValidateRequest(NewRequest newUserRequest, bool create = true) { AuthResult authResult = new AuthResult(); if (TextUtils.StringContainsAccents(newUserRequest.Username)) { authResult.AuthStatus = AuthStatus.INVALID_USERNAME; } authResult.AuthStatus = ValidatePassword(newUserRequest.Password) ? AuthStatus.OK : AuthStatus.INVALID_PASSWORD; if (authResult.AuthStatus == AuthStatus.OK && create) { if (!string.IsNullOrWhiteSpace(newUserRequest.Cpf)) { if (!TextUtils.IsValidCpf(newUserRequest.Cpf)) { authResult.AuthStatus = AuthStatus.INVALID_CPF; } } } return(authResult); }
public static void ProcessImageAnalysis(NewRequest <SmartDoc> newReq) { }
public static async Task <IActionResult> CognitivePipelineSyncProcessing(NewRequest <SmartDoc> newSmartDocRequest) { log.LogInformation($"***Starting Sync CognitivePipelineSyncProcessing***"); IActionResult executionResult = null; if (newSmartDocRequest.Instructions.Contains(InstructionFlag.AnalyzeText.ToString())) { var stepName = InstructionFlag.AnalyzeText.ToString(); log.LogInformation($"***Starting {stepName}***"); string funcUri = GlobalSettings.GetKeyValue("FunctionBaseUrl") + "/NewCognitiveOCR"; var content = new StringContent(JsonConvert.SerializeObject(newSmartDocRequest), Encoding.UTF8, "application/json"); try { executionResult = await FunctionExecuter.CallFunction(funcUri, content); if (executionResult is OkObjectResult) { //TODO: Update the request processing step var result = executionResult as OkObjectResult; string updatedDocJson = result.Value.ToString(); NewRequest <SmartDoc> updatedDoc = JsonConvert.DeserializeObject <NewRequest <SmartDoc> >(updatedDocJson); newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(updatedDoc.RequestItem.CognitivePipelineActions[0]); } else { //TODO: Better error information to be implemented newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep { LastUpdatedAt = DateTime.UtcNow, Status = SmartDocStatus.ProcessedUnsuccessfully.ToString(), StepName = stepName }); } } catch (Exception ex) { log.LogError($"***EXCEPTION*** in {stepName}: {ex.Message}, {ex.StackTrace}"); newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep { LastUpdatedAt = DateTime.UtcNow, Status = SmartDocStatus.ProcessedUnsuccessfully.ToString(), StepName = InstructionFlag.AnalyzeText.ToString() }); } } if (newSmartDocRequest.Instructions.Contains(InstructionFlag.FaceAuthentication.ToString())) { var stepName = InstructionFlag.FaceAuthentication.ToString(); log.LogInformation($"***Starting {stepName}***"); CognitivePipeline.SharedModels.Models.User owner = await usersDbClient.GetItemAsync(newSmartDocRequest.OwnerId); string funcUri = GlobalSettings.GetKeyValue("FunctionBaseUrl") + $"/NewCognitiveFaceAuth/{owner.FacePersonId}"; var content = new StringContent(JsonConvert.SerializeObject(newSmartDocRequest), Encoding.UTF8, "application/json"); try { executionResult = await FunctionExecuter.CallFunction(funcUri, content); if (executionResult is OkObjectResult) { //TODO: Update the request processing step var result = executionResult as OkObjectResult; string updatedDocJson = result.Value.ToString(); NewRequest <SmartDoc> updatedDoc = JsonConvert.DeserializeObject <NewRequest <SmartDoc> >(updatedDocJson); newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(updatedDoc.RequestItem.CognitivePipelineActions[0]); } else { //TODO: Better error information to be implemented newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep { LastUpdatedAt = DateTime.UtcNow, Status = SmartDocStatus.ProcessedUnsuccessfully.ToString(), StepName = stepName }); } } catch (Exception ex) { log.LogError($"***EXCEPTION*** in {stepName}: {ex.Message}, {ex.StackTrace}"); newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep { LastUpdatedAt = DateTime.UtcNow, Status = SmartDocStatus.ProcessedUnsuccessfully.ToString(), StepName = stepName }); } } if (newSmartDocRequest.Instructions.Contains(InstructionFlag.ShelfCompliance.ToString())) { var stepName = InstructionFlag.ShelfCompliance.ToString(); log.LogInformation($"***Starting {stepName}***"); string funcUri = GlobalSettings.GetKeyValue("FunctionBaseUrl") + "/NewCognitiveShelfCompliance"; var content = new StringContent(JsonConvert.SerializeObject(newSmartDocRequest), Encoding.UTF8, "application/json"); try { executionResult = await FunctionExecuter.CallFunction(funcUri, content); if (executionResult is OkObjectResult) { //TODO: Update the request processing step var result = executionResult as OkObjectResult; string updatedDocJson = result.Value.ToString(); NewRequest <SmartDoc> updatedDoc = JsonConvert.DeserializeObject <NewRequest <SmartDoc> >(updatedDocJson); newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(updatedDoc.RequestItem.CognitivePipelineActions[0]); } else { //TODO: Better error information to be implemented newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep { LastUpdatedAt = DateTime.UtcNow, Status = SmartDocStatus.ProcessedUnsuccessfully.ToString(), StepName = stepName }); } } catch (Exception ex) { log.LogError($"***EXCEPTION*** in {stepName}: {ex.Message}, {ex.StackTrace}"); newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep { LastUpdatedAt = DateTime.UtcNow, Status = SmartDocStatus.ProcessedUnsuccessfully.ToString(), StepName = stepName }); } } if (newSmartDocRequest.Instructions.Contains(InstructionFlag.Thumbnail.ToString())) { var stepName = InstructionFlag.Thumbnail.ToString(); log.LogInformation($"***Starting {stepName}***"); //Currently the 2 Thumbnail sizes are loaded from Functions settings. var thumbnailConfig = GlobalSettings.GetKeyValue("CognitiveServices-Thumbnail-Config").Split(','); string funcUri = GlobalSettings.GetKeyValue("FunctionBaseUrl") + $"/NewCognitiveThumbnail/{thumbnailConfig[0]}/{thumbnailConfig[1]}/{thumbnailConfig[2]}/{thumbnailConfig[3]}"; var content = new StringContent(JsonConvert.SerializeObject(newSmartDocRequest), Encoding.UTF8, "application/json"); try { executionResult = await FunctionExecuter.CallFunction(funcUri, content); if (executionResult is OkObjectResult) { //TODO: Update the request processing step var result = executionResult as OkObjectResult; string updatedDocJson = result.Value.ToString(); NewRequest <SmartDoc> updatedDoc = JsonConvert.DeserializeObject <NewRequest <SmartDoc> >(updatedDocJson); newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(updatedDoc.RequestItem.CognitivePipelineActions[0]); } else { //TODO: Better error information to be implemented newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep { LastUpdatedAt = DateTime.UtcNow, Status = SmartDocStatus.ProcessedUnsuccessfully.ToString(), StepName = stepName }); } } catch (Exception ex) { log.LogError($"***EXCEPTION*** in {stepName}: {ex.Message}, {ex.StackTrace}"); newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep { LastUpdatedAt = DateTime.UtcNow, Status = SmartDocStatus.ProcessedUnsuccessfully.ToString(), StepName = stepName }); } } if (newSmartDocRequest.Instructions.Contains(InstructionFlag.AnalyzeImage.ToString())) { var stepName = InstructionFlag.AnalyzeImage.ToString(); log.LogInformation($"***Starting {stepName}***"); string funcUri = GlobalSettings.GetKeyValue("FunctionBaseUrl") + $"/NewCognitiveAnalyzeImage"; var content = new StringContent(JsonConvert.SerializeObject(newSmartDocRequest), Encoding.UTF8, "application/json"); try { executionResult = await FunctionExecuter.CallFunction(funcUri, content); if (executionResult is OkObjectResult) { //TODO: Update the request processing step var result = executionResult as OkObjectResult; string updatedDocJson = result.Value.ToString(); NewRequest <SmartDoc> updatedDoc = JsonConvert.DeserializeObject <NewRequest <SmartDoc> >(updatedDocJson); newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(updatedDoc.RequestItem.CognitivePipelineActions[0]); } else { //TODO: Better error information to be implemented newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep { LastUpdatedAt = DateTime.UtcNow, Status = SmartDocStatus.ProcessedUnsuccessfully.ToString(), StepName = InstructionFlag.AnalyzeImage.ToString() }); } } catch (Exception ex) { log.LogError($"***EXCEPTION*** in {stepName}: {ex.Message}, {ex.StackTrace}"); newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep { LastUpdatedAt = DateTime.UtcNow, Status = SmartDocStatus.ProcessedUnsuccessfully.ToString(), StepName = stepName }); } } //Validate cognitive processing and return relevant details log.LogInformation($"***Final Results Processing***"); var processedResult = await CognitivePipelineResultProcessor.ProcessFinalResult(newSmartDocRequest, smartDocsDbClient, usersDbClient); if (!string.IsNullOrEmpty(processedResult)) { return((ActionResult) new OkObjectResult(processedResult)); } else { return((ActionResult) new BadRequestObjectResult(processedResult)); } }
public ActionResult Save(PasswordDTO entity) { var complete = true; try { using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required)) { if (ModelState.IsValid) { UserAccountEntity user = AccountRepository.Instance.GetById(CurrentUserId); if (!entity.NewPassword.Equals(entity.NewPasswordConfirmation)) { Error("As duas senhas digitadas não conferem."); complete = false; } else if (!PasswordUtils.ValidatePassword(entity.CurrentPassword, user.SecurityStamp, user.PasswordHash)) { Error("A senha atual digitada não confere com a vigente."); complete = false; } else { NewRequest request = new NewRequest(); request.Password = entity.NewPassword; request.Username = user.UserName; request.Name = user.UserName; AccountHandler.UpdateUser(request); } if (complete) { Success("Senha atualizada com sucesso."); } scope.Complete(); } else { Warning("Alguns campos são obrigatórios para salvar a senha."); return(View("PasswordEdit", entity)); } } } catch (Exception ex) { Logger.LogException(ex); Error("Ocorreu um erro ao tentar salvar a senha.", ex); } if (complete) { if (IsSystemAdmin) { return(Redirect("/admin/empresas/")); } else { if (CurrentWorkerType.ProfileName.Equals(Profiles.ADMINISTRADOR)) { return(Redirect("/public/dashboard")); } else { return(Redirect("/public/ranking")); } } } else { return(Redirect("/admin/usuario/perfil/editarSenha")); } }
public static async Task <NewRequest <SmartDoc> > CreateNewRequest( string ownerId, bool isAsync, IFormFile doc, ClassificationType docType, IStorageRepository storageRepository, IDocumentDBRepository <SmartDoc> docRepository, IDocumentDBRepository <User> userRepository) { if (doc == null || doc.Length == 0) { throw new InvalidOperationException("No file was selected"); } var owner = await userRepository.GetItemAsync(ownerId); if (owner == null) { throw new InvalidOperationException("Invalid request"); } long size = doc.Length; // To hold the Url for the uploaded document string docName = "NA"; string docUri = null; //Upload the submitted document to Azure Storage if (size > 0) { using (var stream = doc.OpenReadStream()) { var docExtention = doc.FileName.Substring(doc.FileName.LastIndexOf('.')); var docId = Guid.NewGuid(); docName = $"{docType}-{docId}{docExtention}"; docUri = await storageRepository.CreateFile(docName, stream); } } // process uploaded files by creating a new SmartDoc record with the details and save it to CosmosDB var newDoc = new SmartDoc { Id = Guid.NewGuid().ToString(), OwnerId = ownerId, DocType = docType, CreatedAt = DateTime.UtcNow, IsDeleted = false, DocName = docName, DocUrl = docUri, Status = SmartDocStatus.Created.ToString(), Origin = docRepository.Origin }; await docRepository.CreateItemAsync(newDoc); //Prepare the new request that will hold the document along with the processing instructions by the Cognitive Pipeline var newReq = new NewRequest <SmartDoc> { CreatedAt = DateTime.UtcNow, Id = Guid.NewGuid().ToString(), OwnerId = ownerId, IsDeleted = false, Instructions = DocumentInstructionsProcessor.GetInstructions(docType), ItemReferenceId = newDoc.Id, RequestItem = newDoc, Status = SmartDocStatus.Created.ToString(), Origin = docRepository.Origin, IsAsync = isAsync }; return(newReq); }
public async void CheckCase(NewRequest slidt, PcommCore.PcommCore pcommCore) { // mre = new ManualResetEvent(false); if (slidt.Header == null && slidt.TransferCase == null) { MessageBox.Show("xml data not to load"); return; } if (slidt.TransferCase.Count == 0) { MessageBox.Show("no xml data to load"); return; } // IsLoadEnable = true; // IsMatchEnable = false; var p = slidt.TransferCase.FirstOrDefault(); ObservableCollection <ProcessMsg> Logtmp = new ObservableCollection <ProcessMsg>(); //List<Notepad> keywords = dic["Notepad"].ToList(); // gwis operation pcommCore.SkipToHomeScreen <S0017>(); //foreach (var cs in slidt.TransferCase) //{ // _resultList.Add(new CheckResult { Level = "Warn", CaseItem = cs, Meassage = "sj672 exsit key word", Status = true, OperationFlag = "未退信" }); //} try { await STATask.Run(() => { foreach (var cs in slidt.TransferCase) { // gwis match if (!gwisOperation.SearchCase(cs, null)) { ProcessLogProxy.Debug("gwis can't find the member", "Red", 3); } pcommCore.LinkToScreen <S0017>((S0017) => { ProcessLogProxy.Debug("SOO17 screeen Set Company", "Green", 1); S0017.SetCompany((cs.OriSchAcctMemNo.Split('-'))[0].ToCharArray().FirstOrDefault().ToString()); return(S0017.GotoMemberDetails()); }).LinkToScreen <S0018>((S0018) => { ProcessLogProxy.Debug("S0018 screeen Go to MemberSchemeMaint", "Green", 1); return(S0018.GotoMemberSchemeMaint()); }).LinkToScreen <SM794>((SM794) => { ProcessLogProxy.Debug("SM794 screeen Set Identifier", "Green", 1); SM794.SetIdentifier(cs.MemHKIDNo); SM794.SetSelectOption("D"); ProcessLogProxy.Debug("SM794 screeen Set option D", "Green", 1); return(true); }).LinkToScreen <SH795>((SH795) => { ProcessLogProxy.Debug("SH795 Select SechemeId", "Green", 1); //SH795.SelectSchemeID(cs.OriSchAcctMemNo.Split('-')[0]); return(true); }); // go to SM799 SM799 sm799 = pcommCore.GetScreen <SM799>(); var id = cs.MemHKIDNo + "(" + cs.MemHKIDCheckDigit + ")"; var dic = sm799.GetMemberInformation(); var englishName = dic["SURNAME"] + " " + dic["TAI MAN"]; if (dic["BANKRUPTCY"] == "NO" && cs.MemEngName == englishName && id == dic["IDNO"].ToString()) { ProcessLogProxy.Debug("SM799 compare with xml data ", "Green", 1); sm799.SetX(); } else { _resultList.Add(new CheckResult { Level = "Warn", CaseItem = cs, Meassage = "SM799 screen " + dic["MPFCOMPLANT"].ToString() + dic["SENSFLAG"].ToString(), Status = true, OperationFlag = "未退信" }); slidt.TransferCase.Remove(cs); ProcessLogProxy.Debug("SM799 screen " + dic["MPFCOMPLANT"].ToString() + dic["SENSFLAG"].ToString(), "Red", 3); continue; } SM800 sm800 = pcommCore.GetScreen <SM800>(); ProcessLogProxy.Debug("SM800 get Chinese Name ", "Green", 1); if (sm800.GetMemberChineseInformation()["CHINESENAME"].ToString() == cs.MemChiName) { sm800.SendKey(KeyBoard.PF3); } else { _resultList.Add(new CheckResult { Level = "Warn", CaseItem = cs, Meassage = "SM800 screen Chinese Name unmatched" + sm800.GetMemberChineseInformation()["CHINESENAME"].ToString(), Status = true, OperationFlag = "未退信" }); ProcessLogProxy.Debug("SM800 screen Chinese Name unmatched" + sm800.GetMemberChineseInformation()["CHINESENAME"].ToString(), "Red", 3); slidt.TransferCase.Remove(cs); continue; } // return SM799 Screen SM799 s_sm7799 = pcommCore.GetScreen <SM799>(); s_sm7799.Set_F20(); // SJ671 sj671 = pcommCore.GetScreen <SJ671>(); sj671.ClearSchemeID(); sj671.SetPrintALL(); sj671.Enter(21, 69); if (sj671.SelectSchemeID(notepadDic["NotePad"], 10, pcommCore)) { ProcessLogProxy.Debug("sj672 exsit key word ", "Red", 3); _resultList.Add(new CheckResult { Level = "Warn", CaseItem = cs, Meassage = "sj672 exsit key word", Status = true, OperationFlag = "未退信" }); slidt.TransferCase.Remove(cs); continue; } else { pcommCore.SkipToHomeScreen <S0017>(); } } ProcessLogProxy.Debug("xml data check completed ", "Green", 1); pcommCore.SkipToHomeScreen <S0017>(); }); //if (_resultList.Count > 0) //{ // IsEpassEnable = true; // ResultList = _resultList; //} //IsRunEnable = true; } catch (Exception e) { ProcessLogProxy.Debug(e.Message, "Red", 3); } }
public ActionResult Save(WorkerDTO entity, HttpPostedFileBase logoUpload) { try { using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required)) { if (ModelState.IsValid) { ImageEntity imageSaving = new ImageEntity(); if (logoUpload != null && logoUpload.ContentLength > 0) { imageSaving.Status = GenericStatus.ACTIVE; imageSaving.UpdatedBy = CurrentUserId; byte[] cover = null; using (var memoryStream = new MemoryStream()) { logoUpload.InputStream.CopyTo(memoryStream); if (memoryStream.Length > 0) { using (Image image = Bitmap.FromStream(memoryStream)) { logoUpload.InputStream.CopyTo(memoryStream); if (memoryStream.Length > 0) { cover = memoryStream.ToArray(); } } } } //if (entity.LogoId > 0) { //imageSaving.Id = entity.LogoId; } //else { imageSaving = ImageRepository.Instance.CreateImage(imageSaving); } ImageRepository.Instance.SaveOrReplaceLogo(imageSaving.Id, cover); entity.LogoId = imageSaving.Id; } if (entity.IdWorker > 0) { PlayerEngineDTO player = PlayerEngineService.Instance.GetById(entity.ExternalId); WorkerTypeEntity workerType = WorkerTypeRepository.Instance.GetById(entity.WorkerTypeId); UserProfileEntity userProfile = new UserProfileEntity(); userProfile.Id = entity.IdUser; userProfile.Name = entity.Name; userProfile.Email = entity.Email; userProfile.CPF = entity.Cpf.Replace(".", "").Replace("-", ""); userProfile.Phone = entity.Phone; ValidateModel(userProfile); WorkerEntity worker = new WorkerEntity(); worker.Status = GenericStatus.ACTIVE; worker.FirmId = CurrentFirm.Id; worker.ExternalFirmId = CurrentFirm.ExternalId; worker.WorkerTypeId = entity.WorkerTypeId; worker.UserId = entity.IdUser; worker.Id = entity.IdWorker; worker.LogoId = entity.LogoId; worker.UpdatedBy = CurrentUserId; worker.ExternalId = player.Id; ValidateModel(worker); WorkerRepository.Instance.UpdateWorker(worker); UserProfileRepository.Instance.UpdateUserProfile(userProfile); UserAccountEntity acc = AccountRepository.Instance.GetById(entity.IdUser); acc.UserName = userProfile.Email; AccountRepository.Instance.Update(acc); player.Nick = userProfile.Name; player.Role = workerType.ProfileName.ToString(); player.LogoId = worker.LogoId; player.Xp = entity.TotalXp; player.Email = entity.Email; player.Cpf = entity.Cpf; player.LogoPath = CurrentURL + player.LogoId; player.Active = true; player.GameId = CurrentFirm.ExternalId; PlayerEngineService.Instance.CreateOrUpdate(player); Success("Funcionário atualizado com sucesso."); scope.Complete(); } else { WorkerTypeEntity workerType = WorkerTypeRepository.Instance.GetById(entity.WorkerTypeId); NewRequest request = new NewRequest(); AuthResult result = new AuthResult(); request.Cpf = entity.Cpf.Replace("-", "").Replace(".", ""); request.Name = entity.Name; request.Phone = entity.Phone; request.Email = entity.Email; request.Username = entity.Email; request.Password = request.Cpf; result = AccountHandler.CreateFirmUser(request, Roles.WORKER); if (!AuthStatus.OK.Equals(result.AuthStatus)) { Error(AccountHelper.HandleError(result)); ViewBag.Types = GetWorkerTypesToSelect(entity.WorkerTypeId); ModelState.AddModelError("", "Ocorreu um erro ao salvar o funcionário."); return(PartialView("_Edit", entity)); } WorkerEntity worker = new WorkerEntity(); worker.Status = GenericStatus.ACTIVE; worker.FirmId = CurrentFirm.Id; worker.ExternalFirmId = CurrentFirm.ExternalId; worker.UserId = result.UserId; worker.WorkerTypeId = entity.WorkerTypeId; worker.LogoId = entity.LogoId; worker.UpdatedBy = CurrentUserId; ValidateModel(worker); PlayerEngineDTO player = PlayerEngineService.Instance.CreateOrUpdate( new PlayerEngineDTO { GameId = worker.ExternalFirmId, Nick = request.Name, Role = workerType.ProfileName.ToString(), Level = 1, LogoId = worker.LogoId, Cpf = entity.Cpf.Replace(".", "").Replace("-", ""), Email = entity.Email, Xp = 1, LogoPath = CurrentURL + worker.LogoId, Active = true }); worker.ExternalId = player.Id; WorkerRepository.Instance.CreateWorker(worker); Success("Funcionário criado com sucesso."); scope.Complete(); } } else { ViewBag.Types = GetWorkerTypesToSelect(entity.WorkerTypeId); ModelState.AddModelError("", "Alguns campos são obrigatórios para salvar o funcionário."); return(PartialView("_Edit", entity)); } } } catch (Exception ex) { Error("Houve um erro ao salvar funcionário."); Logger.LogException(ex); ModelState.AddModelError("", "Ocorreu um erro ao tentar salvar o funcionário."); ViewBag.Types = GetWorkerTypesToSelect(entity.WorkerTypeId); return(PartialView("_Edit", entity)); } return(new EmptyResult()); }
public async Task <string> Get() { GanymedeHttpResponse s = await NewRequest.ForResource("Get").Send(); return(await s.AsString()); }
public void NavigateByMemeTag(Guid guid) { IEnumerable <Meme> memes = Memes.Where(meme => meme.Tags.FirstOrDefault(m => m.MemeTag.Id == guid) != null); NewRequest?.Invoke(memes); }
public void NavigateByRequest(Func <Meme, bool> func) { IEnumerable <Meme> memes = Memes.Where(func); NewRequest?.Invoke(memes); }
public ActionResult Update(NewRequest model) { return RedirectToAction("Index", "NewRequest"); }
public ActionResult Save(FirmDTO entity, HttpPostedFileBase logoUpload) { try { using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required)) { if (ModelState.IsValid) { ImageEntity imageSaving = new ImageEntity(); if (logoUpload != null && logoUpload.ContentLength > 0) { imageSaving.Status = GenericStatus.ACTIVE; imageSaving.UpdatedBy = CurrentUserId; byte[] cover = null; using (var memoryStream = new MemoryStream()) { logoUpload.InputStream.CopyTo(memoryStream); if (memoryStream.Length > 0) { using (Image image = Bitmap.FromStream(memoryStream)) { logoUpload.InputStream.CopyTo(memoryStream); if (memoryStream.Length > 0) { cover = memoryStream.ToArray(); } } } } if (entity.DataInfo.LogoId > 0) { imageSaving.Id = entity.DataInfo.LogoId; } else { imageSaving = ImageRepository.Instance.CreateImage(imageSaving); } ImageRepository.Instance.SaveOrReplaceLogo(imageSaving.Id, cover); entity.DataInfo.LogoId = imageSaving.Id; } entity.DataInfo.UpdatedBy = CurrentUserId; if (entity.DataInfo.Id > 0) { if (entity.Status == 0) { entity.DataInfo.Status = GenericStatus.INACTIVE; } else { entity.DataInfo.Status = GenericStatus.ACTIVE; } ValidateModel(entity.DataInfo); GameEngineDTO game = new GameEngineDTO { Adress = entity.DataInfo.Adress, City = entity.DataInfo.City, LogoId = entity.DataInfo.LogoId, Name = entity.DataInfo.FirmName, Neighborhood = entity.DataInfo.Neighborhood, Phone = entity.DataInfo.Phone, Id = entity.DataInfo.ExternalId, LogoPath = CurrentURL + entity.DataInfo.LogoId, Description = entity.DataInfo.Cnpj }; try { game = GameEngineService.Instance.CreateOrUpdate(game, "*****@*****.**"); } catch (Exception e) { Logger.LogError(e.Message); } List <WorkerDTO> workers = WorkerRepository.Instance.GetAllFromFirm(entity.DataInfo.Id); if (entity.DataInfo.Status == GenericStatus.ACTIVE) { foreach (WorkerDTO item in workers) { UserAccountEntity acc = AccountRepository.Instance.GetById(item.IdUser); acc.Status = GenericStatus.ACTIVE; AccountRepository.Instance.Update(acc); } } else { foreach (WorkerDTO item in workers) { UserAccountEntity acc = AccountRepository.Instance.GetById(item.IdUser); acc.Status = GenericStatus.INACTIVE; AccountRepository.Instance.Update(acc); } } DataRepository.Instance.UpdateFirm(entity.DataInfo); } else { if (!entity.Password.Equals(entity.PasswordConfirmation)) { Warning("As duas senhas digitadas não conferem."); } NewRequest request = new NewRequest(); AuthResult result = new AuthResult(); request.Cpf = entity.ProfileInfo.CPF; request.Name = entity.ProfileInfo.Name; request.Phone = entity.ProfileInfo.Phone; request.Password = entity.Password; request.Email = entity.ProfileInfo.Email; request.Username = entity.Username; result = AccountHandler.CreateFirmUser(request, Roles.WORKER); if (!AuthStatus.OK.Equals(result.AuthStatus)) { Error(AccountHelper.HandleError(result)); return(View("Create", entity)); } ValidateModel(entity.DataInfo); GameEngineDTO game = new GameEngineDTO { Adress = entity.DataInfo.Adress, City = entity.DataInfo.City, LogoId = entity.DataInfo.LogoId, Name = entity.DataInfo.FirmName, Neighborhood = entity.DataInfo.Neighborhood, Phone = entity.DataInfo.Phone, Id = entity.DataInfo.ExternalId, Description = entity.DataInfo.Cnpj }; game = GameEngineService.Instance.CreateOrUpdate(game, "*****@*****.**"); entity.DataInfo.ExternalId = game.Id; entity.DataInfo.Status = GenericStatus.ACTIVE; entity.DataInfo = DataRepository.Instance.CreateFirm(entity.DataInfo); WorkerEntity worker = new WorkerEntity(); WorkerTypeEntity workerType = new WorkerTypeEntity(); workerType.FirmId = entity.DataInfo.Id; workerType.ProfileName = Profiles.ADMINISTRADOR; workerType.Status = GenericStatus.ACTIVE; workerType.TypeName = "ADMINISTRADOR"; workerType.UpdatedBy = CurrentUserId; workerType = WorkerTypeRepository.Instance.CreateWorkerType(workerType); worker.WorkerTypeId = workerType.Id; worker.UserId = result.UserId; worker.UpdatedBy = CurrentUserId; worker.FirmId = entity.DataInfo.Id; worker.Status = GenericStatus.ACTIVE; worker.LogoId = entity.DataInfo.LogoId; PlayerEngineDTO player = new PlayerEngineDTO { Nick = request.Name, Xp = 1, Level = 1, Role = workerType.TypeName, GameId = game.Id, LogoId = worker.LogoId, Email = entity.ProfileInfo.Email, Cpf = entity.ProfileInfo.CPF, Active = true }; player = PlayerEngineService.Instance.CreateOrUpdate(player, "*****@*****.**"); worker.ExternalId = player.Id; worker.ExternalFirmId = game.Id; worker = WorkerRepository.Instance.CreateWorker(worker); } Success("Empresa salva com sucesso."); scope.Complete(); } else { Warning("Alguns campos são obrigatórios para salvar a empresa."); if (entity.DataInfo.Id > 0) { ViewBag.Status = GetStatusToSelect(entity.DataInfo.Status == GenericStatus.ACTIVE ? 1 : 0); return(View("Edit", entity)); } else { return(View("Create", entity)); } } } } catch (Exception ex) { Logger.LogException(ex); Error("Ocorreu um erro ao tentar salvar a empresa.", ex); if (entity.DataInfo.Id > 0) { ViewBag.Status = GetStatusToSelect(entity.DataInfo.Status == GenericStatus.ACTIVE ? 1 : 0); return(View("Edit", entity)); } else { return(View("Create", entity)); } } return(View("Index")); }
public async Task <IActionResult> SubmitDoc(string ownerId, string docType, bool isAsync, IFormFile doc) { // TODO: Introduce another parameter to identify the needed classification services (like classification, OCR,...) if (doc == null || doc.Length == 0) { return(BadRequest("file not selected")); } var owner = await userRepository.GetItemAsync(ownerId); if (owner == null) { return(BadRequest("Invalid request")); } var proposedDocType = ClassificationType.Unidentified; var isValidType = Enum.TryParse <ClassificationType>(docType, out proposedDocType); if (!isValidType) { return(BadRequest("Invalid document type")); } long size = doc.Length; // full path to file in temp location string docName = "NA"; string docUri = null; if (size > 0) { using (var stream = doc.OpenReadStream()) { var docExtention = doc.FileName.Substring(doc.FileName.LastIndexOf('.')); var docId = Guid.NewGuid(); docName = $"{proposedDocType}-{docId}{docExtention}"; docUri = await storageRepository.CreateFile(docName, stream); } //Sample to upload to local temp storage //var tempFolder = Path.GetTempPath(); //var fileName = Path.GetRandomFileName(); //var filePath = Path.Combine(tempFolder, fileName); //using (var stream = new FileStream(filePath, FileMode.Create)) //{ // await doc.CopyToAsync(stream); //} } // process uploaded files // Don't rely on or trust the FileName property without validation. var newDoc = new SmartDoc { Id = Guid.NewGuid().ToString(), OwnerId = ownerId, DocType = proposedDocType, CreatedAt = DateTime.UtcNow, IsDeleted = false, DocName = docName, DocUrl = docUri, Status = SmartDocStatus.Created.ToString(), Origin = docRepository.Origin }; await docRepository.CreateItemAsync(newDoc); //Call NewReq function background service to start processing the new doc var newReq = new NewRequest <SmartDoc> { CreatedAt = DateTime.UtcNow, Id = Guid.NewGuid().ToString(), OwnerId = ownerId, IsDeleted = false, Instructions = DocumentInstructionsProcessor.GetInstructions(proposedDocType), ItemReferenceId = newDoc.Id, RequestItem = newDoc, Status = SmartDocStatus.Created.ToString(), Origin = docRepository.Origin, IsAsync = isAsync }; var result = await newReqService.SendNewRequest(newReq, newDoc.Id, isAsync); return(Ok(result)); }
public ActionResult SaveWorkersArchive(HttpPostedFileBase workersArchive) { try { string gameId = CurrentFirm.ExternalId; workersArchive.SaveAs(Path.Combine(Server.MapPath("~/App_Data"), workersArchive.FileName)); string path = Path.Combine(Server.MapPath("~/App_Data"), workersArchive.FileName); var archive = new ExcelQueryFactory(path); var rows = from x in archive.WorksheetRange("A1", "E" + rowsCount, "Workers") select x; foreach (var row in rows) { if (!string.IsNullOrWhiteSpace(row[0].ToString()) && !string.IsNullOrWhiteSpace(row[1].ToString()) && !string.IsNullOrWhiteSpace(row[2].ToString()) && !string.IsNullOrWhiteSpace(row[4].ToString())) { NewRequest request = new NewRequest(); AuthResult result = new AuthResult(); request.Cpf = row[3].ToString(); request.Name = row[0].ToString(); request.Phone = row[2].ToString(); request.Password = "******"; request.Email = row[1].ToString(); request.Username = row[1].ToString(); result = AccountHandler.CreateFirmUser(request, Roles.WORKER); WorkerTypeEntity workerType = WorkerTypeRepository.Instance.GetByGameIdAndTypeName(gameId, row[4].ToString()); if (AuthStatus.OK.Equals(result.AuthStatus)) { WorkerEntity worker = new WorkerEntity(); worker.Status = GenericStatus.ACTIVE; worker.FirmId = CurrentFirm.Id; worker.UserId = result.UserId; worker.ExternalFirmId = CurrentFirm.ExternalId; worker.WorkerTypeId = workerType.Id; worker.UpdatedBy = CurrentUserId; ValidateModel(worker); PlayerEngineDTO dto = new PlayerEngineDTO { Level = 1, Xp = 1, Nick = request.Name, Role = workerType.ProfileName.ToString(), GameId = worker.ExternalFirmId, LogoId = worker.LogoId, Cpf = request.Cpf, Email = request.Email, LogoPath = CurrentURL + worker.LogoId, Active = true }; dto = PlayerEngineService.Instance.CreateOrUpdate(dto); worker.ExternalId = dto.Id; worker = WorkerRepository.Instance.CreateWorker(worker); } } } Success("Funcionários criados com sucesso."); } catch (Exception ex) { Logger.LogException(ex); ModelState.AddModelError("", "Ocorreu um erro ao tentar salvar os funcionários via arquivo."); return(PartialView("_WorkersArchive")); } return(new EmptyResult()); }
private async void OnMessageReceived(object sender, MessageEventArgs messageEventArgs) { var message = messageEventArgs.Message; if (message == null) { Logger.Warn("Received null"); return; } Logger.Debug($"Received message from @{message.From.Username}: {message.Text}"); try { if (message.Type == MessageType.Text && message.Text.StartsWith('/')) { // is a command switch (message.Text.Split(' ').First()) { case "/start": case "/help": await _bot.SendTextMessageAsync(message.Chat, $"Welcome!\nDrop a URL, get a PNG + PDF.\nDemo development bot, service not guaranteed.\nSet up yours at https://github.com/Jamesits/ScreenShooter \n\n{Globals.ProgramIdentifier}", replyToMessageId : message.MessageId); break; case "/UserInfo": if (!Administrators.Contains(message.Chat.Id)) { goto default; } await _bot.SendTextMessageAsync(message.Chat, $"User ID: {message.Chat.Id}", replyToMessageId : message.MessageId); break; case "/DiagnosticInfo": if (!Administrators.Contains(message.Chat.Id)) { goto default; } await _bot.SendTextMessageAsync(message.Chat, RuntimeInformation.ToString(), replyToMessageId : message.MessageId); break; case "/ForceGarbageCollection": if (!Administrators.Contains(message.Chat.Id)) { goto default; } var sb = new StringBuilder(); sb.AppendLine($"Before GC: {RuntimeInformation.WorkingSet}Bytes"); GC.Collect(2, GCCollectionMode.Optimized, true, true); sb.AppendLine($"After GC: {RuntimeInformation.WorkingSet}Bytes"); await _bot.SendTextMessageAsync(message.Chat, sb.ToString(), replyToMessageId : message.MessageId); break; default: await _bot.SendTextMessageAsync(message.Chat, "Unknown command. \n\n/help - get help", replyToMessageId : message.MessageId); break; } } else { // get text from message var content = ""; switch (message.Type) { case MessageType.Text: content = message.Text; break; case MessageType.Photo: case MessageType.Video: case MessageType.Audio: case MessageType.Document: content = message.Caption; break; default: content = null; break; } if (content == null) { Logger.Debug($"Received unknown message from @{message.From.Username} type {message.Type}"); await _bot.SendTextMessageAsync(message.Chat, "Unacceptable content", replyToMessageId : message.MessageId); return; } // check if there is any valid url var result = Url.ExtractValidUrls(content).ToList(); // also try if we can extract URLs from entities if (message.Entities != null) { foreach (var e in message.Entities) { switch (e.Type) { case MessageEntityType.Url: Logger.Debug($"Entity type URL: {e.Url}"); if (Url.IsValidUrl(e.Url)) { result.Add(e.Url.Trim()); } break; case MessageEntityType.TextLink: // This is equal to <a> tag in HTML Logger.Debug($"Entity type TextURL: {e.Url}"); if (Url.IsValidUrl(e.Url)) { result.Add(e.Url.Trim()); } break; } } } // remove duplication result = result.Distinct().ToList(); // TODO: if returned multiple URLs? if (result.Count > 0) { // is a valid URL await _bot.SendTextMessageAsync(message.Chat, $"Job enqueued. Sit back and relax - this is going to take minutes. \nRunning: {RuntimeInformation.OnGoingRequests}\nWaiting: {RuntimeInformation.QueuedRequests}\nMax parallel jobs: {Globals.GlobalConfig.ParallelJobs}", replyToMessageId : message.MessageId); NewRequest?.Invoke(this, new UserRequestEventArgs { Url = result[0], RequestContext = message, RequestTypes = new List <UserRequestType> { UserRequestType.Pdf, UserRequestType.Png }, IsPriority = Administrators.Contains(message.Chat.Id) }); } else { // if is not valid URL await _bot.SendTextMessageAsync( message.Chat, "Sorry, this is not a valid URL", replyToMessageId : message.MessageId ); } } } catch (Exception e) { // if we do not process error, the error will be persist when bot restarts. // so we end up here. Logger.Error($"Something happened. Exception:\n{e}"); } }