private void ProcessNewWorkOrders() { ProcessingNewWorkOrders = true; BrokeredMessage newWorkOrderMessage = null; newWorkOrderMessage = NewWorkOrders.Receive(); while (newWorkOrderMessage != null) { // Process the message Trace.WriteLine("Processing", newWorkOrderMessage.SequenceNumber.ToString()); using (WorkOrder wo = WorkOrder.Populate(newWorkOrderMessage.GetBody <int>())) { try { wo.WorkOrderStatus = ""; wo.SlaveWorkerId = BusinessLayer.Scheduler.GetAvailableSlave(wo.ApplicationId, wo.DeviceId).DeviceId; wo.SlaveWorkerSubmit = DateTime.Now; wo.Save(); using (CommunicationPackage cp = CommunicationPackage.CreateCommunication((int)wo.SlaveWorkerId, CommunicationPackage.UpdateType.NewWorkOrder, wo.WorkOrderId)) { ProcessCommunication(cp); } } catch { // No device available requeue the work order. NewWorkOrders.Send(new BrokeredMessage(wo.WorkOrderId)); } } newWorkOrderMessage.Complete(); newWorkOrderMessage = NewWorkOrders.Receive(); } ProcessingNewWorkOrders = false; }
public void Test_CommunicationPackage_Is_Initialized_Properly_For_GameEventType() { var cp = new CommunicationPackage(GameEventType.Activated); Assert.Equal(GameEventType.Activated, cp.GameEventType); Assert.Null(cp.PlayerActionType); }
private void CheckForUpdates() { while (_isRunning) { _serverInfo._communicationsToRemove.Clear(); _serverInfo._communications.ForEach(communication => { if (!communication.IsConnected) { communication.Stop(); _serverInfo._communicationsToRemove.Add(communication); } else if (communication.IsDataAvailable()) { var data = communication.Receive(); var communicationPackage = new CommunicationPackage(communication, data); _queue.Push(communicationPackage); } }); if (_serverInfo._communicationsToRemove.Count > 0) { _disconnectionHandler.RemoveFromLobby(); } Thread.Sleep(1); } }
public Int32 CreateNotificacao(NOTIFICACAO noti, USUARIO usuarioLogado) { try { //Completa campos USUARIO adm = _usuarioService.GetAdministrador(usuarioLogado.ASSI_CD_ID); noti.ASSI_CD_ID = usuarioLogado.ASSI_CD_ID; noti.CANO_CD_ID = 1; noti.NOTI_DT_EMISSAO = DateTime.Today.Date; noti.NOTI_DT_VALIDADE = DateTime.Today.Date.AddDays(30); noti.NOTI_DT_VISTA = null; noti.NOTI_IN_ATIVO = 1; noti.NOTI_IN_STATUS = 1; noti.NOTI_IN_NIVEL = 1; noti.NOTI_IN_VISTA = 0; noti.NOTI_NM_TITULO = "Solicição de Alteração de Cadastro"; noti.USUA_CD_ID = adm.USUA_CD_ID; // Gera Notificação Int32 volta = _notiService.Create(noti); // Recupera template e-mail String header = _usuarioService.GetTemplate("SOLCAD").TEMP_TX_CABECALHO; String body = _usuarioService.GetTemplate("SOLCAD").TEMP_TX_CORPO; String data = _usuarioService.GetTemplate("SOLCAD").TEMP_TX_DADOS; // Prepara dados do e-mail header = header.Replace("{Nome}", adm.USUA_NM_NOME); data = data.Replace("{Data}", DateTime.Today.Date.ToLongDateString()); data = data.Replace("{Usuario}", usuarioLogado.USUA_NM_NOME); data = data.Replace("{Solicitacao}", noti.NOTI_TX_TEXTO); // Concatena String emailBody = header + body + data; // Prepara e-mail e enviar CONFIGURACAO conf = _usuarioService.CarregaConfiguracao(usuarioLogado.ASSI_CD_ID); Email mensagem = new Email(); mensagem.ASSUNTO = "Solicitacao de Alteracao Cadastral"; mensagem.CORPO = emailBody; mensagem.DEFAULT_CREDENTIALS = false; mensagem.EMAIL_DESTINO = adm.USUA_NM_EMAIL; mensagem.EMAIL_EMISSOR = conf.CONF_NM_EMAIL_EMISSOO; mensagem.ENABLE_SSL = true; mensagem.NOME_EMISSOR = "Sistema"; mensagem.PORTA = conf.CONF_NM_PORTA_SMTP; mensagem.PRIORIDADE = System.Net.Mail.MailPriority.High; mensagem.SENHA_EMISSOR = conf.CONF_NM_SENHA_EMISSOR; mensagem.SMTP = conf.CONF_NM_HOST_SMTP; // Envia e-mail Int32 voltaMail = CommunicationPackage.SendEmail(mensagem); return(volta); } catch (Exception ex) { throw; } }
public async Task CommunicateWithPlayerAsync(CommunicationPackage communicationPackage) { Console.WriteLine($"{PlayerName}: {communicationPackage}"); if (communicationPackage.GameEventType == GameEventType.State) { LatestGameState = communicationPackage.GameState; } }
public void Test_CommunicationPackage_Is_Initialized_Properly_For_GameState() { var gs = new GameState(new byte[] { 2, 4 }, 3, 29, 8, 4, true, 14, 13); var cp = new CommunicationPackage(gs); Assert.Equal(GameEventType.State, cp.GameEventType); Assert.Equal(gs, cp.GameState); }
private static IEnumerator CreateCommunicatorCoroutine(float timeToCommunicate, HumanoidTargeter reciever, CommunicationPackage package) { yield return(new WaitForSeconds(timeToCommunicate)); reciever.RecieveCommunication(package); }
private void ProcessCommunication(CommunicationPackage cp) { try { // CommunicationPackage cp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommunicationPackage>(cpSerialized); UserDevice ud = UserDevice.Populate(cp.TargetDeviceId); ActiveDevice ad; // Have to try and catch the exception, since might not exist in the current context try { ad = ActiveDevice.Populate(ud.DeviceId); } catch (Exception) { ad = null; } CommunicationPackage fetchRequest = CommunicationPackage.CreateFetchRequest(cp.TargetDeviceId); // If last fetch from device was less than 3 mins ago, don't send GCM if (ad != null && ad.LastFetch < DateTime.Now.AddMinutes(-1)) { // Send GCM if (fetchRequest.SendAttempts < 3 && fetchRequest.SubmitDate < DateTime.Now.AddSeconds(-30)) { Pusher.SendNotification(ud.GCMCode, fetchRequest.Serialize()); fetchRequest.SubmitDate = DateTime.Now; fetchRequest.SendAttempts++; fetchRequest.Save(); } else if (fetchRequest.SendAttempts >= 3 && fetchRequest.SubmitDate < DateTime.Now.AddSeconds(-40)) { // Device might not be active, delete it from the active device list. try { ad.Delete(); } catch { } // If not results, re-arrange WO List <int?> workOrdersToBeRearranged = ud.CommunicationPackages.Where(x => x.Status == null && x.Response == null && x.CommunicationType != (int)CommunicationPackage.UpdateType.Result).Select(x => x.WorkOrderId).ToList(); // Delete current Comm Packages to the device if they are requests for work. ud.DeleteOutstandingSlaveCommPackages(); // Rearange work orders foreach (int?woId in workOrdersToBeRearranged) { if (woId.HasValue) { NewWorkOrders.Send(new BrokeredMessage(woId.Value)); } } } } // handle if less than 10 ... etc.. } catch (Exception e) { Debug.WriteLine(e.Message); } }
/// <summary> /// Executes the changeset. Operation is persisting changes to database. /// </summary> /// <param name="changeset">The changeset that is persisted.</param> public override void ExecuteChangeset(Makolab.Fractus.Communication.DBLayer.DBXml changeset) { //remove valuations that link to lines marked as deleted if (changeset.Table("warehouseDocumentValuation") != null && changeset.Table("warehouseDocumentLine") != null) { List <DBRow> deletedValuations = new List <DBRow>(); foreach (var line in changeset.Table("warehouseDocumentLine").Rows.Where(l => l.Action == DBRowState.Delete)) { foreach (var valuation in changeset.Table("warehouseDocumentValuation").Rows) { if (valuation.Element("incomeWarehouseDocumentLineId").Value.Equals(line.Element("id").Value, StringComparison.OrdinalIgnoreCase) || valuation.Element("outcomeWarehouseDocumentLineId").Value.Equals(line.Element("id").Value, StringComparison.OrdinalIgnoreCase)) { deletedValuations.Add(valuation); } } } deletedValuations.ForEach(v => v.Remove()); } //TODO kod dodany by wykorzystywac mechanizm savepointow, ale dziwia warunki na korekte pz/wz //TODO nalezy sprawdzi czy zmiana wycen rusza wersje obiektu glownego bo wyglda na to ze nie var docType = Makolab.Fractus.Kernel.Mappers.DictionaryMapper.Instance.GetDocumentType( new Guid(this.CurrentPackage.Table(this.MainObjectTag).FirstRow().Element("documentTypeId").Value)); if ((docType.DocumentCategory == Makolab.Fractus.Kernel.Enums.DocumentCategory.IncomeWarehouseCorrection || docType.DocumentCategory == Makolab.Fractus.Kernel.Enums.DocumentCategory.OutcomeWarehouseCorrection) && changeset.Table("warehouseDocumentValuation") != null) { var warehouseValuationTable = changeset.Table("warehouseDocumentValuation"); warehouseValuationTable.Remove(); DBXml valuationXml = new DBXml(); valuationXml.AddTable(warehouseValuationTable); this.Repository.ExecuteOperations(changeset); WarehouseDocumentValuation valuationProcessor = new WarehouseDocumentValuation(this.UnitOfWork, this.ExecutionController, this.IsHeadquarter); valuationProcessor.Log = this.Log; valuationProcessor.LocalTransactionId = this.LocalTransactionId; CommunicationPackage valuationPackage = new CommunicationPackage(new XmlTransferObject() { Content = valuationXml.Xml.ToString(SaveOptions.DisableFormatting) }); valuationPackage.DatabaseId = this.package.DatabaseId; valuationPackage.XmlData.LocalTransactionId = this.package.XmlData.LocalTransactionId; valuationPackage.XmlData.DeferredTransactionId = this.package.XmlData.DeferredTransactionId; valuationProcessor.ExecutePackage(valuationPackage, 0); } else { this.Repository.ExecuteOperations(changeset); } }
public CommunicationPackage RecievedBy(HumanoidTargeter newIssuer) { CommunicationPackage newPackage = new CommunicationPackage( new HashSet <CommunicatableEnemyMarker>(this.payload), newIssuer ); // Debug.Log("Inside RecievedBy of issuer " + newIssuer.gameObject.name + " " + newPackage.GetPayload().Count); newPackage.alreadyCommunicated = new HashSet <HumanoidTargeter>( this.alreadyCommunicated ); newPackage.alreadyCommunicated.Add(newIssuer); return(newPackage); }
private void ForwardPackage(ICommunicationPackage communicationPackage, Guid targetBranchId) { XmlTransferObject forwardedPkgData = new XmlTransferObject { DeferredTransactionId = communicationPackage.XmlData.DeferredTransactionId, Id = Guid.NewGuid(), LocalTransactionId = Guid.NewGuid(), XmlType = "CommercialDocumentSnapshotEx", Content = this.CurrentPackage.Xml.ToString(System.Xml.Linq.SaveOptions.DisableFormatting) }; ICommunicationPackage pkg = new CommunicationPackage(forwardedPkgData); pkg.DatabaseId = Makolab.Fractus.Kernel.Mappers.DictionaryMapper.Instance.GetBranch(targetBranchId).DatabaseId; CommunicationPackageRepository pkgRepo = new CommunicationPackageRepository(this.UnitOfWork); pkgRepo.PutToOutgoingQueue(pkg); }
/// <summary> /// Process communication package persisting it's data to database. /// </summary> /// <param name="communicationPackage">The communication package to execute.</param> /// <returns> /// <c>true</c> if execution succeeded; otherwise, <c>false</c> /// </returns> public override bool ExecutePackage(ICommunicationPackage communicationPackage) { if (base.ExecutePackage(communicationPackage) == false) { return(false); } CommunicationPackage payment = PackageExecutionHelper.ExtractPaymentPackage(this.CurrentPackage, communicationPackage); if (payment != null) { payment.XmlData.LocalTransactionId = this.LocalTransactionId; var pkgRepo = new CommunicationPackageRepository(this.UnitOfWork); var forwarder = Makolab.Fractus.Commons.DependencyInjection.IoC.Get <IPackageForwarder>(); forwarder.Log = this.Log; forwarder.ForwardPackage(payment, pkgRepo); } return(true); }
/// <summary> /// Creates the communication package.. /// </summary> /// <param name="data">The object with communication package data.</param> /// <returns>Created communication package.</returns> public ICommunicationPackage CreatePackage(object data) { CommunicationPackage package = null; XElement xml = data as XElement; if (xml == null) { throw new ArgumentException("Invalid object type", "data"); } XmlTransferObject xmlData = new XmlTransferObject(); xmlData.Id = new Guid(xml.Element("id").Value); xmlData.LocalTransactionId = new Guid(xml.Element("localTransactionId").Value); xmlData.DeferredTransactionId = new Guid(xml.Element("deferredTransactionId").Value); xmlData.Content = xml.Element("xml").FirstNode.ToString(SaveOptions.DisableFormatting); try { xmlData.XmlType = xml.Element("type").Value; } catch (ArgumentException) { xmlData.XmlType = "Unknown"; } package = new CommunicationPackage(xmlData); package.OrderNumber = Int32.Parse(xml.Element("order").Value, CultureInfo.InvariantCulture); XElement databaseId = xml.Element("databaseId"); if (databaseId == null) { throw new InvalidDataException("DatabaseId cannot be null"); } package.DatabaseId = new Guid(databaseId.Value); return(package); }
public void RecieveCommunication(CommunicationPackage package) { //Debug.Log("Sent by: " + package.GetIssuer().gameObject.name + " to " + this.gameObject.name + " for package " + package.id); HashSet <CommunicatableEnemyMarker> markerPayload = package.GetPayload(); foreach (CommunicatableEnemyMarker marker in markerPayload) { if (marker.IsValid()) { if (NoMarkerTooCloseTo(marker)) { AddHiddenEnemy(marker.GetNewMarker()); } } else { RemoveHiddenEnemy(marker); } } HumanoidTargeterCommunication.Communicate(package.RecievedBy(this)); }
private void ExecuteIncomeShift() { CommunicationPackage statusPkg = GenerateShiftDocumentStatusPackage(); string oppositeWarehouseFieldId = DictionaryMapper.Instance.GetDocumentField(Makolab.Fractus.Kernel.Enums.DocumentFieldName.ShiftDocumentAttribute_OppositeWarehouseId).Id.Value.ToString().ToUpperInvariant(); string oppositeWarehouseId = this.CurrentPackage.Xml.Root.Element("documentAttrValue").Elements() .Where(row => row.Element("documentFieldId").Value.Equals(oppositeWarehouseFieldId)) .Select(row => row.Element("textValue").Value) .SingleOrDefault(); if (oppositeWarehouseId == null) { throw new InvalidDataException("Missing opposite warehouse id in document attributes"); } Warehouse w = DictionaryMapper.Instance.GetWarehouse(new Guid(oppositeWarehouseId)); statusPkg.DatabaseId = DictionaryMapper.Instance.GetBranch(w.BranchId).DatabaseId; CommunicationPackageRepository pkgRepo = new CommunicationPackageRepository(this.UnitOfWork); pkgRepo.PutToOutgoingQueue(statusPkg); }
private static void ForwardValuations(ICommunicationPackage communicationPackage, XDocument commPkg, ICommunicationPackageRepository repository) { var distributedLines = commPkg.Root.Element("warehouseDocumentValuation").Elements("entry") .Where( row => row.Element("isDistributed") != null && row.Element("isDistributed").Value.Equals("True", StringComparison.OrdinalIgnoreCase) && row.Element("warehouseDocumentHeaderId") != null && (row.Attribute("action") == null || row.Attribute("action").Value.Equals("delete", StringComparison.OrdinalIgnoreCase) == false)) .GroupBy(row => row.Element("warehouseDocumentHeaderId").Value); //this valuation is not for shift document, so we don't forward it if (distributedLines.Count() == 0) { return; } XDocument valuationTemplate = XDocument.Parse("<root><warehouseDocumentValuation /></root>"); Guid localTransactionId = Guid.NewGuid(); using (var wrapper = repository.Context.ConnectionManager.SynchronizeConnection()) { SqlConnectionManager.Instance.SetConnection(wrapper.Connection, (SqlTransaction)repository.Context.Transaction); } using (var whDocCoord = new DocumentCoordinator(false, false)) { foreach (var warehouseDocGroup in distributedLines) { WarehouseDocument shift = null; try { shift = (WarehouseDocument)whDocCoord.LoadBusinessObject(Makolab.Fractus.Kernel.Enums.BusinessObjectType.WarehouseDocument, new Guid(warehouseDocGroup.Key)); } catch (ClientException) { } //there is a valuated document in database so we can forward valuation - no document = skip valuations for this doc if (shift != null) { string oppositeWarehouseId = (shift.Attributes.Count() > 0 && shift.Attributes.Children.Any(attr => attr.DocumentFieldName == DocumentFieldName.ShiftDocumentAttribute_OppositeWarehouseId)) ? shift.Attributes[DocumentFieldName.ShiftDocumentAttribute_OppositeWarehouseId].Value.Value : null; if (oppositeWarehouseId != null) { Warehouse oppositeWarehouse = DictionaryMapper.Instance.GetWarehouse(new Guid(oppositeWarehouseId)); Warehouse warehouse = DictionaryMapper.Instance.GetWarehouse(shift.WarehouseId); //skip local shift document valuations if (warehouse.BranchId == oppositeWarehouse.BranchId) { continue; } foreach (var valuation in warehouseDocGroup) { var whDocLine = shift.Lines.Children.Where(line => line.Id.ToString() .Equals(valuation.Element("outcomeWarehouseDocumentLineId").Value, StringComparison.OrdinalIgnoreCase)) .SingleOrDefault(); valuation.Add(new XAttribute("outcomeShiftOrdinalNumber", whDocLine.OrdinalNumber)); } var valuationPkg = new XDocument(valuationTemplate); valuationPkg.Root.Element("warehouseDocumentValuation").Add(new XAttribute("outcomeShiftId", shift.Id)); valuationPkg.Root.Element("warehouseDocumentValuation").Add(warehouseDocGroup); XmlTransferObject valuationData = new XmlTransferObject { DeferredTransactionId = communicationPackage.XmlData.DeferredTransactionId, Id = Guid.NewGuid(), LocalTransactionId = localTransactionId, XmlType = "WarehouseDocumentValuation", Content = valuationPkg.ToString(SaveOptions.DisableFormatting) }; ICommunicationPackage pkg = new CommunicationPackage(valuationData); pkg.DatabaseId = DictionaryMapper.Instance.GetBranch(oppositeWarehouse.BranchId).DatabaseId; repository.PutToOutgoingQueue(pkg); } } } } }
public virtual async Task CommunicateWithPlayerAsync(CommunicationPackage communicationPackage) { Console.WriteLine(communicationPackage); }
public static void Communicate(CommunicationPackage package) { bool communicatedByMouth = false; bool communicatedByRadio = false; HumanoidTargeter issuer = package.GetIssuer(); List <IEnumerator> communicatorCoroutines = new List <IEnumerator>(); foreach (HumanoidTargeter targeter in instance.targeters) { if (targeter != issuer && !package.AlreadyCommunicated(targeter)) { if (issuer.CanCommunicate(targeter)) { package.AddToCommunicated(targeter); // Debug.Log("beginning communication from " + issuer.gameObject.name + " to " + targeter.gameObject.name); IEnumerator newCoroutine = CreateCommunicatorCoroutine( issuer.GetTimeToCommunicateByMouth(), targeter, package ); communicatorCoroutines.Add(newCoroutine); instance.StartCoroutine(newCoroutine); communicatedByMouth = true; } else if (targeter.HasRadio() && issuer.HasRadio()) { package.AddToCommunicated(targeter); IEnumerator newCoroutine = CreateCommunicatorCoroutine( issuer.GetTimeToCommunicateByRadio(), targeter, package ); communicatorCoroutines.Add(newCoroutine); instance.StartCoroutine(newCoroutine); communicatedByRadio = true; } } } if (communicatorCoroutines.Count != 0) { Communicator communicator = new Communicator( issuer, communicatorCoroutines ); instance.communicators.Add(communicator); float timeBeforeRemoveCommunicator = 0f;; if (communicatedByMouth && communicatedByRadio) { timeBeforeRemoveCommunicator = Mathf.Max( issuer.GetTimeToCommunicateByMouth() , issuer.GetTimeToCommunicateByRadio() ); } else if (communicatedByMouth) { timeBeforeRemoveCommunicator = issuer.GetTimeToCommunicateByMouth(); } else if (communicatedByRadio) { timeBeforeRemoveCommunicator = issuer.GetTimeToCommunicateByRadio(); } IEnumerator removeCoroutine = GetRemoveFromCommunicatorList( timeBeforeRemoveCommunicator, communicator ); instance.StartCoroutine(removeCoroutine); } }
public Int32 ValidateCreateMensagem(FORNECEDOR_MENSAGEM item, USUARIO usuario) { try { // Completa registro item.FOME_IN_ATIVO = 1; // Monta log String registro = item.FORNECEDOR.FORN_NM_NOME + " - " + item.TIPO_MENSAGEM.TIME_NM_NOME + " - " + item.FOME_DT_ENVIO.ToShortDateString() + " - " + item.FOME_DS_TEXTO; LOG log = new LOG(); log.LOG_DT_DATA = DateTime.Now; log.LOG_NM_OPERACAO = "FornMSG"; log.ASSI_CD_ID = usuario.ASSI_CD_ID; log.LOG_TX_REGISTRO = registro; log.LOG_IN_ATIVO = 1; // Processa e-mail if (item.TIME_CD_ID == 1) { // Recupera template e-mail String header = _baseService.GetTemplate("MSGFOR").TEMP_TX_CABECALHO; String body = _baseService.GetTemplate("MSGFOR").TEMP_TX_CORPO; String data = _baseService.GetTemplate("MSGFOR").TEMP_TX_DADOS; // Prepara dados do e-mail header = header.Replace("{Nome}", item.FORNECEDOR.FORN_NM_NOME); body = body.Replace("{Texto}", item.FOME_DS_TEXTO); body = body.Replace("{Condominio}", item.USUARIO.ASSINANTE.ASSI_NM_NOME); data = data.Replace("{Data}", item.FOME_DT_ENVIO.ToLongDateString()); data = data.Replace("{Usuario}", item.USUARIO.USUA_NM_NOME); // Concatena String emailBody = header + body + data; // Prepara e-mail e enviar CONFIGURACAO conf = _baseService.CarregaConfiguracao(usuario.ASSI_CD_ID); Email mensagem = new Email(); mensagem.ASSUNTO = "Mensagem para Fornecedor - " + item.FORNECEDOR.FORN_NM_NOME; mensagem.CORPO = emailBody; mensagem.DEFAULT_CREDENTIALS = false; mensagem.EMAIL_DESTINO = item.FORNECEDOR.FORN_NM_EMAIL; mensagem.EMAIL_EMISSOR = conf.CONF_NM_EMAIL_EMISSOO; mensagem.ENABLE_SSL = true; mensagem.NOME_EMISSOR = usuario.USUA_NM_NOME; mensagem.PORTA = conf.CONF_NM_PORTA_SMTP; mensagem.PRIORIDADE = System.Net.Mail.MailPriority.High; mensagem.SENHA_EMISSOR = conf.CONF_NM_SENHA_EMISSOR; mensagem.SMTP = conf.CONF_NM_HOST_SMTP; // Envia e-mail Int32 voltaMail = CommunicationPackage.SendEmail(mensagem); } else if (item.TIME_CD_ID == 2) { // Processa SMS } else { // Processa WhatsApp } // Persiste item.FOME_IN_ENVIADO = 1; Int32 volta = _baseService.CreateMensagem(item); return(volta); } catch (Exception ex) { throw; } }
public Int32 GenerateNewPassword(String email, Int32?idAss) { // Checa email if (!ValidarItensDiversos.IsValidEmail(email)) { return(1); } USUARIO usuario = _usuarioService.RetriveUserByEmail(email); if (usuario == null) { return(2); } // Verifica se usuário está ativo if (usuario.USUA_IN_ATIVO == 0) { return(3); } // Verifica se usuário não está bloqueado if (usuario.USUA_IN_BLOQUEADO == 1) { return(4); } // Gera nova senha String senha = Cryptography.GenerateRandomPassword(6); // Atauliza objeto //usuario.USUA_NM_SENHA = Cryptography.Encode(senha); usuario.USUA_NM_SENHA = senha; usuario.USUA_IN_PROVISORIA = 1; usuario.USUA_DT_ALTERACAO = DateTime.Now; usuario.USUA_DT_TROCA_SENHA = DateTime.Now; usuario.USUA_IN_LOGIN_PROVISORIO = 0; // Recupera template e-mail String header = _usuarioService.GetTemplate("NEWPWD").TEMP_TX_CABECALHO; String body = _usuarioService.GetTemplate("NEWPWD").TEMP_TX_CORPO; String data = _usuarioService.GetTemplate("NEWPWD").TEMP_TX_DADOS; // Prepara dados do e-mail header = header.Replace("{Nome}", usuario.USUA_NM_NOME); data = data.Replace("{Data}", usuario.USUA_DT_TROCA_SENHA.Value.ToLongDateString()); data = data.Replace("{Senha}", usuario.USUA_NM_SENHA); // Concatena String emailBody = header + body + data; // Monta e-mail Email mensagem = new Email(); CONFIGURACAO conf = _usuarioService.CarregaConfiguracao(idAss); mensagem.ASSUNTO = "Geração de Nova Senha"; mensagem.CORPO = emailBody; mensagem.DEFAULT_CREDENTIALS = false; mensagem.EMAIL_DESTINO = usuario.USUA_NM_EMAIL; mensagem.EMAIL_EMISSOR = conf.CONF_NM_EMAIL_EMISSOR; mensagem.ENABLE_SSL = true; mensagem.NOME_EMISSOR = "ERP_Condominio "; mensagem.PORTA = conf.CONF_NM_PORTA_SMTP; mensagem.PRIORIDADE = System.Net.Mail.MailPriority.High; mensagem.SENHA_EMISSOR = conf.CONF_NM_SENHA_EMAIL_EMISSOR; mensagem.SMTP = conf.CONF_NM_HOST_SMTP; // Envia e-mail Int32 voltaMail = CommunicationPackage.SendEmail(mensagem); // Atualiza usuario Int32 volta = _usuarioService.EditUser(usuario); // Retorna sucesso return(0); }
public Int32 ValidateCreate(USUARIO usuario, USUARIO usuarioLogado) { try { // Verifica senhas if (usuario.USUA_NM_SENHA != usuario.USUA_NM_SENHA_CONFIRMA) { return(1); } // Verifica Email if (!ValidarItensDiversos.IsValidEmail(usuario.USUA_NM_EMAIL)) { return(2); } // Verifica existencia prévia if (_usuarioService.GetByEmail(usuario.USUA_NM_EMAIL) != null) { return(3); } if (_usuarioService.GetByLogin(usuario.USUA_NM_LOGIN) != null) { return(4); } // Verifica admissão e demissão if (usuario.USUA_DT_ENTRADA != null) { if (usuario.USUA_DT_ENTRADA.Value > DateTime.Today.Date) { return(5); } } if (usuario.USUA_DT_SAIDA != null) { if (usuario.USUA_DT_SAIDA.Value > DateTime.Today.Date) { return(6); } if (usuario.USUA_DS_MOTIVO_SAIDA == null) { return(7); } } if (usuario.USUA_IN_RESPONSAVEL == 1) { if (_usuarioService.GetResponsavel(usuario) != null) { return(8); } } //Completa campos de usuários String senha = Cryptography.GenerateRandomPassword(6); usuario.USUA_NM_SENHA = senha; usuario.USUA_NM_LOGIN = usuario.USUA_NM_NOME.Substring(0, 4); //usuario.USUA_NM_SENHA = Cryptography.Encode(usuario.USUA_NM_SENHA); usuario.USUA_IN_BLOQUEADO = 0; usuario.USUA_IN_PROVISORIO = 0; usuario.USUA_IN_LOGIN_PROVISORIO = 0; usuario.USUA_NR_ACESSOS = 0; usuario.USUA_NR_FALHAS = 0; usuario.USUA_DT_ALTERACAO = null; usuario.USUA_DT_BLOQUEADO = null; usuario.USUA_DT_TROCA_SENHA = null; usuario.USUA_DT_ACESSO = DateTime.Now; usuario.USUA_DT_CADASTRO = DateTime.Today.Date; usuario.USUA_IN_ATIVO = 1; usuario.USUA_DT_ULTIMA_FALHA = DateTime.Now; usuario.ASSI_CD_ID = usuarioLogado.ASSI_CD_ID; usuario.USUA_DS_MOTIVO_SAIDA = null; usuario.USUA_IN_LOGADO = 0; usuario.USUA_NR_MATRICULA = null; // Monta Log LOG log = new LOG { LOG_DT_DATA = DateTime.Now, USUA_CD_ID = usuarioLogado.USUA_CD_ID, ASSI_CD_ID = usuarioLogado.ASSI_CD_ID, LOG_NM_OPERACAO = "AddUSUA", LOG_TX_REGISTRO = Serialization.SerializeJSON <USUARIO>(usuario), LOG_IN_ATIVO = 1 }; // Persiste Int32 volta = _usuarioService.CreateUser(usuario, log); // Gerar Notificação NOTIFICACAO noti = new NOTIFICACAO(); noti.CANO_CD_ID = 1; noti.ASSI_CD_ID = usuario.ASSI_CD_ID; noti.NOTI_DT_EMISSAO = DateTime.Today; noti.NOTI_DT_VALIDADE = DateTime.Today.Date.AddDays(30); noti.NOTI_IN_VISTA = 0; noti.NOTI_NM_TITULO = "Criação de Usuário"; noti.NOTI_IN_ATIVO = 1; noti.NOTI_IN_NIVEL = 1; noti.NOTI_TX_TEXTO = "ATENÇÃO: Usuário" + usuario.USUA_NM_NOME + " criado em " + DateTime.Today.Date.ToLongDateString() + ". Perfil: " + usuario.PERFIL.PERF_NM_NOME + ". Login: "******". Senha: " + usuario.USUA_NM_SENHA + ". Essa senha é provisória e poderá ser usada apenas uma vez, devendo ser alterada após o primeiro login."; noti.USUA_CD_ID = usuario.USUA_CD_ID; noti.NOTI_IN_STATUS = 1; Int32 volta1 = _notiService.Create(noti); // Recupera template e-mail TEMPLATE template = _usuarioService.GetTemplate("NEWUSR"); String header = template.TEMP_TX_CABECALHO; String body = template.TEMP_TX_CORPO; String data = template.TEMP_TX_DADOS; // Prepara dados do e-mail data = data.Replace("{Nome}", usuario.USUA_NM_NOME); data = data.Replace("{Unidade}", usuario.UNIDADE.UNID_NM_EXIBE); data = data.Replace("{Perfil}", usuario.PERFIL.PERF_NM_NOME); data = data.Replace("{Data}", usuario.USUA_DT_CADASTRO.Value.ToLongDateString()); data = data.Replace("{Login}", usuario.USUA_NM_LOGIN); data = data.Replace("{Senha}", usuario.USUA_NM_SENHA); // Concatena String emailBody = header + body + data; // Prepara e-mail e enviar CONFIGURACAO conf = _usuarioService.CarregaConfiguracao(usuario.ASSI_CD_ID); Email mensagem = new Email(); mensagem.ASSUNTO = "Inclusão de Usuário"; mensagem.CORPO = emailBody; mensagem.DEFAULT_CREDENTIALS = false; mensagem.EMAIL_DESTINO = usuario.USUA_NM_EMAIL; mensagem.EMAIL_EMISSOR = conf.CONF_NM_EMAIL_EMISSOO; mensagem.ENABLE_SSL = true; mensagem.NOME_EMISSOR = "Sistema"; mensagem.PORTA = conf.CONF_NM_PORTA_SMTP; mensagem.PRIORIDADE = System.Net.Mail.MailPriority.High; mensagem.SENHA_EMISSOR = conf.CONF_NM_SENHA_EMISSOR; mensagem.SMTP = conf.CONF_NM_HOST_SMTP; // Envia e-mail Int32 voltaMail = CommunicationPackage.SendEmail(mensagem); return(volta); } catch (Exception ex) { throw; } }
private void ProcessUpdatedWorkOrders() { ProcessingUpdatedWorkOrders = true; BrokeredMessage updatedWorkOrderMessage = null; updatedWorkOrderMessage = UpdatedWorkOrders.Receive(); try { while (updatedWorkOrderMessage != null) { // Process the message SharedClasses.WorkOrderUpdate wou = updatedWorkOrderMessage.GetBody <SharedClasses.WorkOrderUpdate>(); using (WorkOrder wo = WorkOrder.Populate(wou.WorkOrderId)) { Trace.WriteLine("Processing Update", wou.WorkOrderId.ToString()); switch (wou.WorkOrderUpdateType) { case SharedClasses.WorkOrderUpdate.UpdateType.Acknowledge: // Update database with last spoke time and message wo.SlaveWorkOrderLastCommunication = DateTime.Now; wo.WorkOrderStatus = "SLAVE_ACKNOWLEDGED"; wo.Save(); break; case SharedClasses.WorkOrderUpdate.UpdateType.Cancel: if (wo.WorkOrderStatus == "SLAVE_ACKNOWLEDGED") { // Send message to cancel CommunicationPackage.CreateCommunication(wo.SlaveWorkerId.Value, CommunicationPackage.UpdateType.Cancel, wo.WorkOrderId); } if (wo.CommunicationPackages.Count() > 0) { // Have to notify device to cancel foreach (CommunicationPackage cp in wo.CommunicationPackages.Where(x => x.CommunicationType != (int)CommunicationPackage.UpdateType.Cancel)) { if (cp.Response == null && cp.Status == null) { // Cancel using (CommunicationPackage oCp = CommunicationPackage.Populate(cp.CommunicationId)) { oCp.Status = "USER_CANCELLED"; oCp.Save(); } } } wo.WorkOrderStatus = "USER_CANCELLED"; } else { wo.WorkOrderStatus = "CANCELLED"; } wo.Save(); break; case SharedClasses.WorkOrderUpdate.UpdateType.SubmitResult: // Update database with result. wo.SlaveWorkOrderLastCommunication = DateTime.Now; wo.WorkOrderResultJson = wou.ResultJson; wo.WorkOrderStatus = "RESULT_RECEIVED"; wo.StartComputationTime = wou.ComputationStartTime; wo.EndComputationTime = wou.ComputationEndTime; wo.DeserialiationTime = wou.RequestDeserialisationTime; wo.SerialisationTime = wou.ResultSerialisationTime; wo.Save(); // Send result to requesting device CommunicationPackage.CreateCommunication(wo.DeviceId, CommunicationPackage.UpdateType.Result, wo.WorkOrderId); // CommunicationPackages.Send(new BrokeredMessage(cp.Serialize())); break; case SharedClasses.WorkOrderUpdate.UpdateType.MarkBeingComputed: // Update database wo.SlaveWorkOrderLastCommunication = DateTime.Now; wo.WorkOrderStatus = "BEING_COMPUTED"; wo.Save(); break; } } updatedWorkOrderMessage.Complete(); updatedWorkOrderMessage = UpdatedWorkOrders.Receive(); } } catch (Exception e) { Debug.WriteLine(e.Message); } ProcessingUpdatedWorkOrders = false; }
public Int32 GenerateNewPassword(String email) { // Checa email if (!ValidarItensDiversos.IsValidEmail(email)) { return(1); } USUARIO usuario = _usuarioService.RetriveUserByEmail(email); if (usuario == null) { return(2); } // Verifica se usuário está ativo if (usuario.USUA_IN_ATIVO == 0) { return(3); } // Verifica se usuário não está bloqueado if (usuario.USUA_IN_BLOQUEADO == 1) { return(4); } // Gera nova senha String senha = Cryptography.GenerateRandomPassword(6); // Atauliza objeto //usuario.USUA_NM_SENHA = Cryptography.Encode(senha); usuario.USUA_NM_SENHA = senha; usuario.USUA_IN_PROVISORIO = 1; usuario.USUA_DT_ALTERACAO = DateTime.Now; usuario.USUA_DT_TROCA_SENHA = DateTime.Now; usuario.USUA_IN_LOGIN_PROVISORIO = 0; // Monta log LOG log = new LOG(); log.LOG_DT_DATA = DateTime.Now; log.LOG_NM_OPERACAO = "NewPWD"; log.ASSI_CD_ID = usuario.ASSI_CD_ID; log.LOG_TX_REGISTRO = senha; log.LOG_IN_ATIVO = 1; // Gera Notificação NOTIFICACAO noti = new NOTIFICACAO(); noti.CANO_CD_ID = 1; noti.ASSI_CD_ID = usuario.ASSI_CD_ID; noti.NOTI_DT_EMISSAO = DateTime.Today; noti.NOTI_DT_VALIDADE = DateTime.Today.Date.AddDays(30); noti.NOTI_IN_VISTA = 0; noti.NOTI_NM_TITULO = "Geração de Nova Senha"; noti.NOTI_IN_ATIVO = 1; noti.NOTI_TX_TEXTO = "ATENÇÃO: Sua solicitação de nova senha foi atendida em " + DateTime.Today.Date.ToLongDateString() + ". Verifique no seu e-mail cadastrado no sistema."; noti.USUA_CD_ID = usuario.USUA_CD_ID; noti.NOTI_IN_STATUS = 1; Int32 volta1 = _notiService.Create(noti); // Recupera template e-mail String header = _usuarioService.GetTemplate("NEWPWD").TEMP_TX_CABECALHO; String body = _usuarioService.GetTemplate("NEWPWD").TEMP_TX_CORPO; String data = _usuarioService.GetTemplate("NEWPWD").TEMP_TX_DADOS; // Prepara dados do e-mail header = header.Replace("{Nome}", usuario.USUA_NM_NOME); data = data.Replace("{Data}", usuario.USUA_DT_TROCA_SENHA.Value.ToLongDateString()); data = data.Replace("{Senha}", usuario.USUA_NM_SENHA); // Concatena String emailBody = header + body + data; // Prepara e-mail e enviar CONFIGURACAO conf = _usuarioService.CarregaConfiguracao(usuario.ASSI_CD_ID); Email mensagem = new Email(); mensagem.ASSUNTO = "Geração de Nova Senha"; mensagem.CORPO = emailBody; mensagem.DEFAULT_CREDENTIALS = false; mensagem.EMAIL_DESTINO = usuario.USUA_NM_EMAIL; mensagem.EMAIL_EMISSOR = conf.CONF_NM_EMAIL_EMISSOO; mensagem.ENABLE_SSL = true; mensagem.NOME_EMISSOR = "Sistema"; mensagem.PORTA = conf.CONF_NM_PORTA_SMTP; mensagem.PRIORIDADE = System.Net.Mail.MailPriority.High; mensagem.SENHA_EMISSOR = conf.CONF_NM_SENHA_EMISSOR; mensagem.SMTP = conf.CONF_NM_HOST_SMTP; // Envia e-mail Int32 voltaMail = CommunicationPackage.SendEmail(mensagem); // Atualiza usuario Int32 volta = _usuarioService.EditUser(usuario); // Retorna sucesso return(0); }
/// <summary> /// Process communication package persisting it's data to database. /// </summary> /// <param name="communicationPackage">The communication package to execute.</param> /// <returns> /// <c>true</c> if execution succeeded; otherwise, <c>false</c> /// </returns> public override bool ExecutePackage(ICommunicationPackage communicationPackage) { try { SessionManager.VolatileElements.DeferredTransactionId = communicationPackage.XmlData.DeferredTransactionId; SessionManager.VolatileElements.LocalTransactionId = this.LocalTransactionId; bool result = base.ExecutePackage(communicationPackage); if (result == false) { return(false); } //skip local shift documents if (IsLocal(this.CurrentPackage) == true) { return(true); } using (var wrapper = this.UnitOfWork.ConnectionManager.SynchronizeConnection()) { SqlConnectionManager.Instance.SetConnection(wrapper.Connection, this.UnitOfWork.Transaction as SqlTransaction); } bool isOutcomeshift = IsOutcomeshift(this.CurrentPackage); bool isIncomeShift = IsIncomeshift(this.CurrentPackage); bool isTargetBranch = IsTargetBranch(this.CurrentPackage); bool isSourceBranch = IsSourceBranch(this.CurrentPackage); if (isOutcomeshift == true) { if (isTargetBranch == true) { if (this.IsHeadquarter == false) { DBXml series = new DBXml(); series.AddTable(this.CurrentPackage.Table("series")); SeriesScript seriesProcessor = new SeriesScript(this.UnitOfWork, this.ExecutionController); seriesProcessor.Log = this.Log; seriesProcessor.LocalTransactionId = this.LocalTransactionId; CommunicationPackage seriesPackage = new CommunicationPackage(new XmlTransferObject() { Content = series.Xml.ToString(SaveOptions.DisableFormatting) }); seriesPackage.DatabaseId = communicationPackage.DatabaseId; seriesPackage.XmlData.LocalTransactionId = communicationPackage.XmlData.LocalTransactionId; seriesPackage.XmlData.DeferredTransactionId = communicationPackage.XmlData.DeferredTransactionId; seriesProcessor.ExecutePackage(seriesPackage); } this.ExecutionController.ExecuteCommand(() => ExecuteOutcomeShift()); if (this.CurrentPackage.Xml.Root.Attribute("skipPackage") == null) { this.CurrentPackage.Xml.Root.Add(new XAttribute("skipPackage", true)); } } if (this.IsHeadquarter && isTargetBranch == false) { DBXml series = this.Repository.FindSeries(new Guid(this.CurrentPackage.Table("warehouseDocumentHeader").FirstRow().Element("seriesId").Value)); this.CurrentPackage.AddTable(series.Table("series")); } if (this.IsHeadquarter == false && isTargetBranch == false && isSourceBranch == false) { throw new InvalidOperationException("ShiftDocumentSnapshot is in invalid branch."); } } else if (isIncomeShift == true && this.IsHeadquarter == true && (isTargetBranch || IsNewOrChanged(this.CurrentPackage, this.previousDocument))) { this.ExecutionController.ExecuteCommand(() => ExecuteIncomeShift()); } communicationPackage.XmlData.Content = this.CurrentPackage.Xml.ToString(SaveOptions.DisableFormatting); return(result); } catch (SqlException e) { if (e.Number == 50012) // Conflict detection { throw new ConflictException("Conflict detected while changing " + this.MainObjectTag); } else { this.Log.Error("ShiftDocumentSnapshot:ExecutePackage " + e.ToString()); return(false); } } }