Exemplo n.º 1
0
        public static void ProcessSurvey(List <SurveyCollector> recs, SurveyFilter filter)
        {
            var collGraph = CreateInstance <SurveyCollectorMaint>();
            var action    = filter.Action;

            if (string.IsNullOrEmpty(action))
            {
                throw new PXException(Messages.SurveyActionNotRecognised);
            }
            SurveyProcess surveyProcessGraph = PXGraph.CreateInstance <SurveyProcess>();

            surveyProcessGraph.Filter.Insert(filter);
            var collCache     = collGraph.Collector.Cache;
            var errorOccurred = false;
            var docCount      = 0;

            foreach (var rec in recs)
            {
                var row = (SurveyCollector)collCache.CreateCopy(rec);
                collGraph.Collector.Current = row;
                try {
                    PXProcessing <SurveyCollector> .SetCurrentItem(rec);

                    switch (action)
                    {
                    case SurveyAction.SendNew:
                        collGraph.DoSendNewNotification(row);
                        break;

                    case SurveyAction.RemindOnly:
                        collGraph.DoSendReminder(row, filter.DurationTimeSpan);
                        break;

                    case SurveyAction.ExpireOnly:
                        row.Status  = CollectorStatus.Expired;
                        row.Message = null;
                        collGraph.Collector.Update(row);
                        break;
                    }
                    if (++docCount % 10 == 0)
                    {
                        surveyProcessGraph.Actions.PressSave();
                    }
                    PXProcessing <SurveyCollector> .SetInfo(recs.IndexOf(rec), string.Format("The survey collector {0} has been updated", rec.CollectorID));

                    PXProcessing <SurveyCollector> .SetProcessed();
                } catch (Exception ex) {
                    row.Status  = CollectorStatus.Error;
                    row.Message = ex.Message;
                    surveyProcessGraph.Documents.Update(row);
                    surveyProcessGraph.Actions.PressSave();
                    PXTrace.WriteError(ex);
                    string errorMessage = ex.Message + ": ";
                    if (ex is PXOuterException pex && pex.InnerMessages != null)
                    {
                        foreach (string message in pex.InnerMessages)
                        {
                            errorMessage += message + ", ";
                        }
                    }
Exemplo n.º 2
0
        private static void ProcessMassMailEmails(CRMassMail massMail, IEnumerable <Recipient> recipients)
        {
            var processor = PXGraph.CreateInstance <CRMassMailMaint>();

            processor.EnsureCachePersistence(typeof(Note));

            foreach (Recipient recipient in recipients)
            {
                var cache = processor.Caches[recipient.Entity.GetType()];
                cache.SetStatus(recipient.Entity, PXEntryStatus.Notchanged);

                IEnumerable <CRSMEmail> messages;
                try
                {
                    messages = recipient.GetSender(massMail).Send();
                }
                catch (Exception e)
                {
                    PXTrace.WriteError(new PXException(Messages.FailedToSendMassEmail, e));

                    continue;
                }

                processor.AddSendedMessages(massMail, messages);
            }

            processor.MassMails.Current              = massMail;
            processor.MassMails.Current.Status       = CRMassMailStatusesAttribute.Send;
            processor.MassMails.Current.SentDateTime = DateTime.Now;
            processor.MassMails.UpdateCurrent();
            processor.Actions.PressSave();
        }
Exemplo n.º 3
0
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
        async Task <IHttpActionResult> IWebhookHandler.ProcessRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            using (var scope = GetUserScope()) {
                string collectorToken = "NO_TOKEN";
                try {
                    var _queryParameters = HttpUtility.ParseQueryString(request.RequestUri.Query);
                    collectorToken = _queryParameters.Get(TOKEN_PARAM);
                    if (string.IsNullOrEmpty(collectorToken))
                    {
                        throw new Exception($"The {TOKEN_PARAM} Parameter was not specified in the Query String");
                    }
                    var pageNbrStr = _queryParameters.Get(PAGE_PARAM);
                    var pageNbr    = SurveyUtils.GetPageNumber(pageNbrStr);
                    if (pageNbrStr != null && request.Method == HttpMethod.Post)
                    {
                        SurveyUtils.SubmitSurvey(collectorToken, request, pageNbr);
                        pageNbr = SurveyUtils.GetNextOrPrevPageNbr(request, pageNbr);
                    }
                    var(content, newToken) = GetSurveyPage(collectorToken, pageNbr);
                    if (newToken != null && newToken != collectorToken)
                    {
                        return(new RedirectResult(request.RequestUri, newToken, "Was anonymous"));
                    }
                    else
                    {
                        return(new HtmlActionResult(content, HttpStatusCode.OK));
                    }
                } catch (Exception ex) {
                    PXTrace.WriteError(ex);
                    var content = GetBadRequestPage(collectorToken, $"{ex.Message}:\n{ex.StackTrace}");
                    return(new HtmlActionResult(content, HttpStatusCode.BadRequest));
                }
            }
        }
 public static void Process(IList <KCStore> stores)
 {
     logger.SetRequestId(GetRequestId());
     for (int i = 0; i < stores.Count; i++)
     {
         var tokenSource = new CancellationTokenSource();
         try
         {
             ProcessStore(stores[i], tokenSource.Token);
             PXProcessing <KCStore> .SetInfo(i, KCMessages.BulkUploadSuccess(stores[i].SiteMasterCD));
         }
         catch (Exception exception)
         {
             string log = KCMessages.ProcessException(stores[i].SiteMasterCD, exception.Message, exception.StackTrace);
             PXTrace.WriteError(exception);
             logger.ClearLoggingIds();
             logger.Error(log);
             PXProcessing <KCStore> .SetError(i, new Exception(log));
         }
         finally
         {
             tokenSource.Cancel(true);
             tokenSource.Dispose();
         }
     }
 }
Exemplo n.º 5
0
        protected virtual void CheckMasterOrganizationCalendarDiscrepancy()
        {
            int  messageCount = 0;
            bool isError      = false;

            foreach (Organization organization in PXSelect <Organization> .Select(this))
            {
                foreach (MasterFinPeriod problemPeriod in PXSelectJoin <
                             MasterFinPeriod,
                             LeftJoin <OrganizationFinPeriod,
                                       On <MasterFinPeriod.finPeriodID, Equal <OrganizationFinPeriod.masterFinPeriodID>,
                                           And <OrganizationFinPeriod.organizationID, Equal <Required <OrganizationFinPeriod.organizationID> > > > >,
                             Where <OrganizationFinPeriod.finPeriodID, IsNull> >
                         .Select(this, organization.OrganizationID))
                {
                    isError = true;
                    if (messageCount <= MAX_FINPERIOD_DISCREPANCY_MESSAGE_COUNT)
                    {
                        PXTrace.WriteError(GL.Messages.DiscrepancyPeriod, organization.OrganizationCD, problemPeriod.FinPeriodID);

                        messageCount++;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            if (isError)
            {
                throw new PXSetPropertyException(GL.Messages.DiscrepancyPeriodError);
            }
        }
Exemplo n.º 6
0
        public static void TraceAndThrowException(string message, params object[] args)
        {
            var exception = new PXException(message, args);

            PXTrace.WriteError(exception);
            throw exception;
        }
        /// <summary>
        /// Creates the Acumatica Employee as a Smartsheet User
        /// </summary>
        /// <param name="bAccountID">Employee ID</param>
        /// <param name="smartsheetClient">Smartsheet SDK Client</param>
        /// <returns></returns>
        public User CreateSmartsheetUser(int?bAccountID, SmartsheetClient smartsheetClient)
        {
            BAccount bAccountRecord = PXSelect <BAccount,
                                                Where <BAccount.bAccountID, Equal <Required <BAccount.bAccountID> > > >
                                      .Select(Base, bAccountID);

            PX.Objects.CR.Contact contactRecord = PXSelect <PX.Objects.CR.Contact,
                                                            Where <PX.Objects.CR.Contact.contactID, Equal <Required <PX.Objects.CR.Contact.contactID> > > >
                                                  .Select(Base, bAccountRecord.DefContactID);

            if (contactRecord == null)
            {
                throw new PXException(string.Format(SmartsheetConstants.Messages.ERROR_CONTACT, bAccountRecord.AcctName));
            }

            try
            {
                User ssUserNew = new User();
                ssUserNew.Email                = contactRecord.EMail;
                ssUserNew.FirstName            = contactRecord.FirstName;
                ssUserNew.LastName             = contactRecord.LastName;
                ssUserNew.Admin                = false;
                ssUserNew.LicensedSheetCreator = false;
                User updatedUser = smartsheetClient.UserResources.AddUser(ssUserNew, false, false);

                return(updatedUser);
            }
            catch (Exception e)
            {
                PXTrace.WriteError(e.Message);
                return(null);
            }
        }
Exemplo n.º 8
0
        protected virtual List <PILocks> LoadExistingLocks()
        {
            var dummyGraph       = new PXGraph();
            var statusItemsQuery = new PXSelectReadonly <INPIStatusItem,
                                                         Where <INPIStatusItem.siteID, Equal <Required <INPIStatusItem.siteID> > >,
                                                         OrderBy <Asc <INPIStatusItem.pIID> > >(dummyGraph); // the sorting required for ToPiIdDictionary method

            Dictionary <string, List <INPIStatusItem> > itemLocksByPiId;

            using (new PXFieldScope(statusItemsQuery.View,
                                    typeof(INPIStatusItem.recordID),
                                    typeof(INPIStatusItem.inventoryID),
                                    typeof(INPIStatusItem.pIID),
                                    typeof(INPIStatusItem.excluded),
                                    typeof(INPIStatusItem.active)))
            {
                itemLocksByPiId = ToPiIdDictionary(
                    statusItemsQuery
                    .Select(_siteId)
                    .RowCast <INPIStatusItem>());
            }

            var statusLocQuery = new PXSelectReadonly <INPIStatusLoc,
                                                       Where <INPIStatusLoc.siteID, Equal <Required <INPIStatusLoc.siteID> > >,
                                                       OrderBy <Asc <INPIStatusLoc.pIID> > >(dummyGraph); // the sorting required for ToPiIdDictionary method

            Dictionary <string, List <INPIStatusLoc> > locationLocksByPiId;

            using (new PXFieldScope(statusLocQuery.View,
                                    typeof(INPIStatusLoc.recordID),
                                    typeof(INPIStatusLoc.locationID),
                                    typeof(INPIStatusLoc.pIID),
                                    typeof(INPIStatusLoc.excluded),
                                    typeof(INPIStatusLoc.active)))
            {
                locationLocksByPiId = ToPiIdDictionary(
                    statusLocQuery
                    .Select(_siteId)
                    .RowCast <INPIStatusLoc>());
            }

            if (itemLocksByPiId.Count != locationLocksByPiId.Count)
            {
                PXTrace.WriteError(Messages.PIDBInconsistency);
            }

            var existingLocks = new List <PILocks>();

            foreach (var itemLocksKvp in itemLocksByPiId)
            {
                var piId          = itemLocksKvp.Key;
                var locationLocks = locationLocksByPiId[piId];
                existingLocks.Add(new PILocks(piId, itemLocksKvp.Value, locationLocks));
            }
            return(existingLocks);
        }
Exemplo n.º 9
0
        public virtual IEnumerable importForecast(PXAdapter adapter)
        {
            PXLongOperation.StartOperation(this, delegate()
            {
                //Create needed graphs
                var graph = PXGraph.CreateInstance <AFResultMaint>();

                AFSetup setup = graph.Setup.Current ?? graph.Setup.Select();

                //-----------------------------------------------------------------------------
                //Change for Setup daya
                string bucketName      = setup.AFBucketName;
                string s3DirectoryName = setup.AFOutDirectoryName;
                string accessKey       = setup.AFAccessKey;
                string secretKey       = setup.AFSecretKey;
                //-----------------------------------------------------------------------------

                PXTrace.WriteInformation($"AFAccessKey: {accessKey} AFSecretKey: {secretKey} AFBucketName: {bucketName} AFDirectoryName: {s3DirectoryName}");

                //if (data?.Count == 0) return;


                try
                {
                    AFAmazonTools myUploader = new AFAmazonTools();
                    var result = myUploader.DownloadFromS3(accessKey, secretKey, bucketName, s3DirectoryName);

                    foreach (var line in result)
                    {
                        try
                        {
                            var item          = new AFResult();
                            item.ResultID     = line[0];
                            item.ResultTstamp = DateTime.Parse(line[1], null, System.Globalization.DateTimeStyles.RoundtripKind);
                            item.ResultP10    = Convert.ToDecimal(line[2]);
                            item.ResultE50    = Convert.ToDecimal(line[3]);
                            item.ResultP90    = Convert.ToDecimal(line[4]);

                            graph.AFResultView.Update(item);
                        }
                        catch (Exception e)
                        {
                            PXTrace.WriteError($"Error parsing data ({String.Join(",", line)}): {e.Message}");
                        }
                    }
                    graph.Save.Press();
                }
                catch (Exception e)
                {
                    throw new PXException(e.Message, e);
                }
            });

            return(adapter.Get());
        }
Exemplo n.º 10
0
        public static void GetVATObligationsProc(VATMaint graph, DateTime from, DateTime to, string status = null)
        {
            obligationsRequest req = new obligationsRequest()
            {
                from = from, to = to, status = status
            };
            obligationResponse obligationResponse = null;

            try
            {
                obligationResponse = graph.VATProvider.Obligations(req);
            }
            catch (Exceptions.VATAPIInvalidToken eToken)
            {
                PXTrace.WriteError(eToken);
                graph.signInHMRC.SetEnabled(true);
                throw new PXException(Messages.PleaseAuthorize);
            }
            catch (Exceptions.VATAPIException eApi)
            {
                PXTrace.WriteError(eApi);
                if (eApi.Data.Contains("json"))
                {
                    PXTrace.WriteError(eApi.Data["json"].ToString());
                }
                if (eApi.Code != error.MATCHING_RESOURCE_NOT_FOUND)
                {
                    throw eApi;
                }
            }
            catch (Exception e)
            {
                PXTrace.WriteError(e);
                throw e;
            }

            graph.Obligations.Cache.Clear();
            if (obligationResponse != null)
            {
                foreach (var o in obligationResponse.obligations)
                {
                    graph.Obligations.Insert(new Obligation()
                    {
                        Start     = o.start,
                        End       = o.end,
                        Due       = o.due,
                        Status    = o.status,
                        PeriodKey = o.periodKey,
                        Received  = o.received
                    });
                }
            }
            return;
        }
Exemplo n.º 11
0
        protected virtual void CheckOrganizationCalendarFieldsDiscrepancy()
        {
            int  messageCount = 0;
            bool isError      = false;

            if (EtalonOrganization != null)
            {
                foreach (Organization organization in PXSelect <
                             Organization,
                             Where <Organization.organizationID, NotEqual <Required <Organization.organizationID> > > >
                         .Select(this, EtalonOrganization.OrganizationID))
                {
                    foreach (OrganizationFinPeriod problemPeriod in PXSelectJoin <
                                 OrganizationFinPeriod,
                                 LeftJoin <OrganizationFinPeriodStatus,
                                           On <OrganizationFinPeriodStatus.organizationID, Equal <Required <OrganizationFinPeriodStatus.organizationID> >,
                                               And <OrganizationFinPeriod.finPeriodID, Equal <OrganizationFinPeriodStatus.finPeriodID>,
                                                    And <OrganizationFinPeriod.dateLocked, Equal <OrganizationFinPeriodStatus.dateLocked>,
                                                         And <OrganizationFinPeriod.status, Equal <OrganizationFinPeriodStatus.status>,
                                                              And <OrganizationFinPeriod.aPClosed, Equal <OrganizationFinPeriodStatus.aPClosed>,
                                                                   And <OrganizationFinPeriod.aRClosed, Equal <OrganizationFinPeriodStatus.aRClosed>,
                                                                        And <OrganizationFinPeriod.iNClosed, Equal <OrganizationFinPeriodStatus.iNClosed>,
                                                                             And <OrganizationFinPeriod.cAClosed, Equal <OrganizationFinPeriodStatus.cAClosed>,
                                                                                  And <OrganizationFinPeriod.fAClosed, Equal <OrganizationFinPeriodStatus.fAClosed> > > > > > > > > > >,
                                 Where <OrganizationFinPeriodStatus.finPeriodID, IsNull,
                                        And <OrganizationFinPeriod.organizationID, Equal <Required <OrganizationFinPeriod.organizationID> > > > >
                             .Select(this, organization.OrganizationID, EtalonOrganization.OrganizationID))
                    {
                        isError = true;
                        if (messageCount <= MAX_FINPERIOD_DISCREPANCY_MESSAGE_COUNT)
                        {
                            string problemFields = GetProblemFields(organization, problemPeriod);

                            PXTrace.WriteError(GL.Messages.DiscrepancyField,
                                               EtalonOrganization.OrganizationCD,
                                               organization.OrganizationCD,
                                               problemFields,
                                               problemPeriod.FinPeriodID);

                            messageCount++;
                        }
                        else
                        {
                            break;
                        }
                    }
                }

                if (isError)
                {
                    throw new PXSetPropertyException(GL.Messages.DiscrepancyFieldError);
                }
            }
        }
Exemplo n.º 12
0
        public override void Initialize()
        {
            try
            {
                var fullName = Base.GetType().Namespace + '.' + Base.GetType().Name;

                //if (Base.GetType().Name == "CustomerMaint") {

                PowerTabAssignment.Current = PowerTabAssignment.Select(fullName);

                if (PowerTabAssignment.Current != null)
                {
                    var paramMap = PowerTabMapping.Select();

                    if (paramMap != null)
                    {
                        var ptParams = new Dictionary <string, string>();

                        foreach (GIMappingLine param in paramMap)
                        {
                            //var cleanName = param.FieldName.Split('.').Last();
                            ptParams.Add(param.ParamName, param.FieldName);
                        }

                        //PowerTabSource.Current = new PTSource();
                        //PowerTabSource.Current.PowerTabUrl = BuildSource("GI", PowerTabAssignment.Current.DesignID, ptParams);

                        // ptParams.Add("CustomerAccountID", "AcctCD");
                        //BuildSource("DB", "DB000031", ptParams);

                        Base.RowSelected.AddHandler(Base.PrimaryView, (cache, args) =>
                        {
                            if (PowerTabSource?.Current == null)
                            {
                                PowerTabSource.Current = new PTSource();
                            }
                            PowerTabAssignment.Current = PowerTabAssignment.Select(fullName);
                            var giName = ((GIDesign)PXSelectorAttribute.SelectAll <GIMapping.designID>(PowerTabAssignment.Cache, PowerTabAssignment.Current).Find(map => ((GIDesign)map).DesignID == PowerTabAssignment.Current.DesignID))?.Name;

                            PowerTabSource.Current.PowerTabUrl = BuildSource("GI", giName, ptParams);
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                PXTrace.WriteError(ex);
            }
        }
        public virtual void Persist(Action persist)
        {
            if (!ExtractionIsActive)
            {
                persist();
                return;
            }

            Action revertCallback       = null;
            FormatExceptionBehaviour?eh = null;

            ImageExtractor.Base64FormatException ex = null;
            try
            {
                ExtractEmbeddedImages(out revertCallback);
                ProcessWhenNoExceptionThrown();
            }
            catch (ImageExtractor.Base64FormatException b64e)
            {
                PXTrace.WriteError(b64e);

                if (revertCallback != null)
                {
                    revertCallback();
                    revertCallback = null;
                }

                eh = ProcessBase64FormatException(b64e);
                if (eh == FormatExceptionBehaviour.Throw)
                {
                    throw new PXSetPropertyException(b64e, PXErrorLevel.Error, Messages.CannotDecodeBase64ContentExplicit);
                }
                ex = b64e;
            }

            try
            {
                persist();
            }
            catch
            {
                revertCallback?.Invoke();
                throw;
            }
            if (ex != null && eh == FormatExceptionBehaviour.ThrowWarningAfterPersist)
            {
                throw new PXSetPropertyException(ex, PXErrorLevel.Warning, Messages.CannotDecodeBase64Content);
            }
        }
Exemplo n.º 14
0
        public static void HandleAggregateException(AggregateException aggregateException, HttpStatusCode codeToHandle, Action <Exception> action)
        {
            aggregateException.Handle((e) =>
            {
                PXTrace.WriteError(e);
                var boxException = e as BoxException;
                if (boxException != null && boxException.StatusCode == codeToHandle)
                {
                    action(e);
                    return(true);
                }

                return(false);
            });
        }
Exemplo n.º 15
0
            private IEnumerable <KeyValuePair <string, Guid> > CreateAttachments(ICollection <string> allowedExtensions)
            {
                var images = new List <KeyValuePair <string, Guid> >();

                foreach (Entity c in _email.Message.Attachments)
                {
                    var newFileId = Guid.NewGuid();
                    var name      = c.ContentDisposition?.Param_FileName ?? c.ContentType?.Param_Name;
                    if (name == null)
                    {
                        continue;
                    }

                    name = name.Trim();
                    if (string.IsNullOrEmpty(name))
                    {
                        name = "untitled";
                    }

                    string ext;
                    try
                    {
                        ext = Path.GetExtension(name);
                    }
                    catch (ArgumentException ae)
                    {
                        PXTrace.WriteError(new Exception("Cannot parse extension of the attachment name. Name contains invalid symbols.", ae));
                        ext = null;
                    }
                    if (!string.IsNullOrEmpty(ext))
                    {
                        ext = ext.Substring(1).ToLower();
                    }
                    if (allowedExtensions != null && !allowedExtensions.Contains(ext))
                    {
                        continue;
                    }

                    var content = ((BodySinglepartBase)c.Body).Data;
                    CreateFile(_activityMessage.NoteID.Value, newFileId, name, content);

                    if (!string.IsNullOrEmpty(c.ContentID))
                    {
                        images.Add(new KeyValuePair <string, Guid>(c.ContentID, newFileId));
                    }
                }
                return(images);
            }
            private protected override FormatExceptionBehaviour ProcessBase64FormatException(ImageExtractor.Base64FormatException e)
            {
                var cache  = Base.Caches <TDocument>();
                var entity = cache.Current;

                if (entity == null)
                {
                    // shouldn't ever happen
                    return(base.ProcessBase64FormatException(e));
                }

                var value = cache.GetValue <TExceptionField>(entity) as string;

                if (!value.IsNullOrEmpty())
                {
                    try
                    {
                        var doc = new HtmlDocument();
                        doc.LoadHtml(value);
                        if (doc.DocumentNode
                            .Descendants(ExceptionHtmlConsts.Tag)
                            .Where(el => el.Attributes[ExceptionHtmlConsts.PXExceptionDataTag]?.Value == ExceptionHtmlConsts.Base64FormatExceptionDataTagValue)
                            .Any())
                        {
                            // do nothing - exception already exists
                            return(FormatExceptionBehaviour.DontThrow);
                        }

                        value += "<br><br>"
                                 + string.Format(ExceptionHtmlConsts.HtmlExceptionTag,
                                                 PXMessages.LocalizeNoPrefix(Messages.CannotDecodeBase64ContentExplicit));
                    }
                    catch (Exception ex)
                    {
                        PXTrace.WriteError(ex);
                    }
                }
                else
                {
                    value = string.Format(ExceptionHtmlConsts.HtmlExceptionTag,
                                          PXMessages.LocalizeNoPrefix(Messages.CannotDecodeBase64ContentExplicit));
                }

                cache.SetValue <TExceptionField>(entity, value);

                return(FormatExceptionBehaviour.DontThrow);
            }
Exemplo n.º 17
0
        public virtual IEnumerable UploadFile(PXAdapter adapter)
        {
            this.Save.Press();

            if (this.NewFacePanel.AskExt() == WebDialogResult.OK)
            {
                var person = this.Persons.Current;

                if (person != null)
                {
                    const string PanelSessionKey = "FaceFile";

                    var info = PXContext.SessionTyped <PXSessionStatePXData>().FileInfo[PanelSessionKey] as PX.SM.FileInfo;

                    try
                    {
                        var faceId = Api.AddPersonFace(person, info.BinData);

                        info.UID = faceId;

                        try
                        {
                            info.UID = faceId;

                            SaveFile(info);
                        }
                        catch (Exception ex)
                        {
                            PXTrace.WriteError(ex);

                            Api.DeletePersonFace(person, faceId);
                        }
                    }
                    finally
                    {
                        System.Web.HttpContext.Current.Session.Remove(PanelSessionKey);
                    }

                    PXLongOperation.StartOperation(this, () =>
                    {
                        Api.Train(person.GroupName);
                    });
                }
            }

            return(adapter.Get());
        }
            private protected override void ProcessWhenNoExceptionThrown()
            {
                var cache  = Base.Caches <TDocument>();
                var entity = cache.Current;

                if (entity == null && cache.GetValue <TExceptionField>(entity) == null)
                {
                    return;
                }

                var value = cache.GetValue <TExceptionField>(entity) as string;

                if (!value.IsNullOrEmpty())
                {
                    try
                    {
                        var doc = new HtmlDocument();
                        doc.LoadHtml(value);
                        var nodes = doc.DocumentNode
                                    .Descendants(ExceptionHtmlConsts.Tag)
                                    .Where(el => el.Attributes[ExceptionHtmlConsts.PXExceptionDataTag]?.Value == ExceptionHtmlConsts.Base64FormatExceptionDataTagValue)
                                    .ToList();
                        foreach (var node in nodes)
                        {
                            // remove empty lines
                            if (node.PreviousSibling?.Name == "br")
                            {
                                doc.DocumentNode.RemoveChild(node.PreviousSibling);
                                if (node.PreviousSibling?.PreviousSibling?.Name == "br")
                                {
                                    doc.DocumentNode.RemoveChild(node.PreviousSibling.PreviousSibling);
                                }
                            }
                            if (node.NextSibling?.Name == "br")
                            {
                                doc.DocumentNode.RemoveChild(node.NextSibling);
                            }
                            doc.DocumentNode.RemoveChild(node);
                        }
                        cache.SetValue <TExceptionField>(entity, doc.DocumentNode.OuterHtml);
                    }
                    catch (Exception ex)
                    {
                        PXTrace.WriteError(ex);
                    }
                }
            }
Exemplo n.º 19
0
            private bool CreateMessage()
            {
                if (_message != null)
                {
                    _activityMessage = PXSelect <CRSMEmail,
                                                 Where <CRSMEmail.noteID, Equal <Required <SMEmail.refNoteID> > > > .Select(_graph, _message.RefNoteID);

                    return(true);
                }

                try
                {
                    if (_email.Message.From == null || _email.Message.From.Count() == 0)
                    {
                        return(false);
                    }

                    using (PXTransactionScope ts = new PXTransactionScope())
                    {
                        // Only two functions in scope so as not to create activity without email,
                        // but also to prevent repetition of processing messages with bad attachments
                        CreateActivity();
                        CreateEmail();

                        ts.Complete();
                    }

                    if (_message == null)
                    {
                        return(false);
                    }

                    _activityMessage = PXSelect <CRSMEmail,
                                                 Where <CRSMEmail.noteID, Equal <Required <SMEmail.refNoteID> > > > .Select(_graph, _message.RefNoteID);

                    AppendAttachments();
                    PersistAM();
                    return(true);
                }
                catch (Exception ex)
                {
                    PXTrace.WriteError(ex);
                    PersistException(ex);
                    return(false);
                }
            }
Exemplo n.º 20
0
        protected static void LogMessages(BaseResult result)
        {
            foreach (AvaMessage msg in result.Messages)
            {
                switch (result.ResultCode)
                {
                case SeverityLevel.Exception:
                case SeverityLevel.Error:
                    PXTrace.WriteError(msg.Summary + ": " + msg.Details);
                    break;

                case SeverityLevel.Warning:
                    PXTrace.WriteWarning(msg.Summary + ": " + msg.Details);
                    break;
                }
            }
        }
 public void SendAndForget(NotificationResultWrapper result, CancellationToken cancellationToken, Action <string> onSendingFailed, Action continuation)
 {
     try
     {
         this.Send(result, cancellationToken);
     }
     catch (Exception e)
     {
         string queueName = _msmq?.QueueName ?? Address;
         PXTrace.WriteError($"Sending to MSMQ {queueName} failed: {e.Message}");
         onSendingFailed($"Send to target {this.Name} failed: ({e.Message})");
     }
     finally
     {
         continuation();
     }
 }
        private void AddReversedTaxTransactionsToReversedTaxAdjustment(TaxAdjustment originalTaxAdj, TaxAdjustment reversedTaxAdj)
        {
            if (reversedTaxAdj == null)
            {
                PXTrace.WriteError("The creation reversed Tax Adjustment for the Tax Adjustment with the ID {0} failed", originalTaxAdj.RefNbr);
                throw new PXException("The creation reversed Tax Adjustment for the Tax Adjustment with the ID {0} failed", originalTaxAdj.RefNbr);
            }

            var originalTransactions =
                PXSelect <TaxTran,
                          Where <TaxTran.tranType, Equal <Required <TaxAdjustment.docType> >,
                                 And <TaxTran.refNbr, Equal <Required <TaxAdjustment.refNbr> > > > >
                .Select(this, originalTaxAdj.DocType, originalTaxAdj.RefNbr);

            foreach (TaxTran originalTaxTran in originalTransactions)
            {
                TaxTran reversingTran = PXCache <TaxTran> .CreateCopy(originalTaxTran);

                reversingTran.TranType = originalTaxTran.TranType;
                reversingTran.RefNbr   = reversedTaxAdj.RefNbr;
                reversingTran.RecordID = null;

                reversingTran.Released   = null;
                reversingTran.CuryInfoID = null;

                reversingTran.ExpenseAmt     = -originalTaxTran.ExpenseAmt;
                reversingTran.CuryExpenseAmt = -originalTaxTran.CuryExpenseAmt;

                reversingTran.OrigTaxableAmt     = -originalTaxTran.OrigTaxableAmt;
                reversingTran.CuryOrigTaxableAmt = -originalTaxTran.CuryOrigTaxableAmt;

                reversingTran.TaxAmt     = -originalTaxTran.TaxAmt;
                reversingTran.CuryTaxAmt = -originalTaxTran.CuryTaxAmt;

                reversingTran.TaxableAmt     = -originalTaxTran.TaxableAmt;
                reversingTran.CuryTaxableAmt = -originalTaxTran.CuryTaxableAmt;

                reversingTran.ReportTaxAmt     = -originalTaxTran.ReportTaxAmt;
                reversingTran.ReportTaxableAmt = -originalTaxTran.ReportTaxableAmt;

                Transactions.Insert(reversingTran);
            }

            Transactions.View.RequestRefresh();
        }
Exemplo n.º 23
0
    protected void Page_InitComplete(object sender, EventArgs e)
    {
        this.InitializeModules();
        if (!this.Page.IsCallback)
        {
            this.FillBrachesList();
        }
        this.InitAuditMenu();

        if (!this.Page.IsCallback || ControlHelper.IsReloadPage(tlbPath))
        {
            var           favBtn      = (PXToolBarButton)tlbPath.Items["favorites"];
            PXSiteMapNode currentNode = System.Web.SiteMap.CurrentNode as PXSiteMapNode;
            try
            {
                if (currentNode == null || String.IsNullOrEmpty(currentNode.ScreenID))
                {
                    favBtn.Visible = false;
                }
                else
                {
                    tlbPath.CallbackUpdatable = favBtn.DynamicText = true;
                    var entryScreenId = GetEntryNodeId(PXSiteMap.CurrentNode.ScreenID);
                    if (!entryScreenId.HasValue)
                    {
                        favBtn.Visible = false;
                    }
                    else
                    {
                        favBtn.Pushed  = this.IsInFavorites(entryScreenId.Value);
                        favBtn.Tooltip = favBtn.Pushed ? InfoMessages.RemoveFromFavorites : InfoMessages.AddToFavorites;
                    }
                }
            }
            catch (Exception ex)
            {
                PXTrace.WriteError(ex);
            }
        }

        // Force the customization controls creation !!!
        this.EnsureChildControls();
    }
        public void Commit()
        {
            if (_inconsistencyHandlingMode == InconsistencyHandlingMode.None || !_errors.Any())
            {
                return;
            }

            foreach (InconsistencyError error in _errors)
            {
                foreach (RecordContextInfo contextInfo in error.ContextData)
                {
                    PXTrace.WriteInformation(contextInfo.Cache.GetFullDescription(contextInfo.Record));
                }

                PXTrace.WriteInformation($"{error.ErrorCode} {error.IntegrityException.Message}");
            }

            if (_inconsistencyHandlingMode == InconsistencyHandlingMode.Prevent)
            {
                DataIntegrityException firstError = _errors.First().IntegrityException;

                throw new DataIntegrityException(
                          firstError.InconsistencyCode,
                          Messages.DataIntegrityErrorDuringProcessingFormat,
                          firstError.Message);
            }

            if (_inconsistencyHandlingMode == InconsistencyHandlingMode.Log)
            {
                DateTime now = DateTime.UtcNow;

                foreach (InconsistencyError error in _errors)
                {
                    string context = error.ContextData.Any()
                                                ? string.Join("\r\n",
                                                              error.ContextData.Select(contextInfo => contextInfo.Cache.ToXml(contextInfo.Record)))
                                                : string.Empty;
                    var errorMsg = $"Error message: {error.IntegrityException.Message}; Date: {DateTime.Now}; Screen: {_graph.Accessinfo.ScreenID}; Context: {context}; InconsistencyCode: {error.IntegrityException.InconsistencyCode}";
                    PXTrace.WriteError(errorMsg);
                }
            }
        }
        public virtual IEnumerable ReverseAdjustment(PXAdapter adapter)
        {
            TaxAdjustment taxAdjToReverse = Document.Current;

            if (taxAdjToReverse?.Released != true || !AskUserApprovalIfReversingDocumentAlreadyExists(taxAdjToReverse))
            {
                return(adapter.Get());
            }

            Save.Press();

            try
            {
                IsReversingInProgress = true;
                Clear(PXClearOption.PreserveTimeStamp);

                var           reverseAdjustmentWithCuryInfo = CreateReversingTaxAdjustmentWithCuryInfo(taxAdjToReverse);
                TaxAdjustment reverseAdjustment             = Document.Insert(reverseAdjustmentWithCuryInfo.Item1);

                UpdateCurrencyInfoForReversedTaxAdjustment(reverseAdjustmentWithCuryInfo.Item2);
                AddReversedTaxTransactionsToReversedTaxAdjustment(taxAdjToReverse, reverseAdjustment);

                Document.Cache.RaiseExceptionHandling <TaxAdjustment.finPeriodID>(Document.Current, Document.Current.FinPeriodID, null);
                PXTrace.WriteVerbose("Reverse Tax Adjustment for Tax Adjustment \"{0}\" was created", taxAdjToReverse.RefNbr);
                return(new List <TaxAdjustment> {
                    Document.Current
                });
            }
            catch (PXException e)
            {
                PXTrace.WriteError(e);
                Clear(PXClearOption.PreserveTimeStamp);
                Document.Current = taxAdjToReverse;
                throw;
            }
            finally
            {
                IsReversingInProgress = false;
            }
        }
        private Tuple <TaxAdjustment, CurrencyInfo> CreateReversingTaxAdjustmentWithCuryInfo(TaxAdjustment taxAdjToReverse)
        {
            CurrencyInfo originalCuryInfo =
                PXSelect <CurrencyInfo,
                          Where <CurrencyInfo.curyInfoID, Equal <Required <CurrencyInfo.curyInfoID> > > >
                .SelectSingleBound(this, currents : null, pars : taxAdjToReverse.CuryInfoID);

            if (originalCuryInfo == null)
            {
                PXTrace.WriteError("The {0} object with the ID {1} is not found", nameof(CurrencyInfo), taxAdjToReverse.CuryInfoID);
                throw new PXException("The {0} object with the ID {1} is not found. The reverse tax adjustment can't be created.",
                                      nameof(CurrencyInfo), taxAdjToReverse.CuryInfoID);
            }

            CurrencyInfo reversedAdjCuryInfo = PXCache <CurrencyInfo> .CreateCopy(originalCuryInfo);

            reversedAdjCuryInfo.CuryInfoID = null;
            reversedAdjCuryInfo.IsReadOnly = false;
            reversedAdjCuryInfo            = currencyinfo.Insert(reversedAdjCuryInfo);

            TaxAdjustment reverseAdjustment = PXCache <TaxAdjustment> .CreateCopy(taxAdjToReverse);

            reverseAdjustment.CuryInfoID = reversedAdjCuryInfo.CuryInfoID;

            reverseAdjustment.RefNbr     = null;
            reverseAdjustment.OrigRefNbr = taxAdjToReverse.RefNbr;
            reverseAdjustment.Released   = false;
            reverseAdjustment.Hold       = true;

            reverseAdjustment.BatchNbr = null;
            reverseAdjustment.NoteID   = null;

            reverseAdjustment.OrigDocAmt     = -reverseAdjustment.OrigDocAmt;
            reverseAdjustment.CuryOrigDocAmt = -reverseAdjustment.CuryOrigDocAmt;

            //Adjustment doc balance is calculated via PXFormula attribute on TaxTan, therefore it's cleared here
            reverseAdjustment.CuryDocBal = null;
            reverseAdjustment.DocBal     = null;
            return(Tuple.Create(reverseAdjustment, reversedAdjCuryInfo));
        }
Exemplo n.º 27
0
        public void Emit(LogEvent logEvent)
        {
            switch (logEvent.Level)
            {
            case LogEventLevel.Information:
            case LogEventLevel.Debug:
                PXTrace.WriteInformation(logEvent.ToTraceMessage(_formatProvider));
                break;

            case LogEventLevel.Error:
            case LogEventLevel.Fatal:
                PXTrace.WriteError(logEvent.ToTraceMessage(_formatProvider));
                break;

            case LogEventLevel.Warning:
                PXTrace.WriteWarning(logEvent.ToTraceMessage(_formatProvider));
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Exemplo n.º 28
0
        public static async Task SendPushNotificationAsync(VXUserPushNotification pushNotification, PushMessage pushMessage)
        {
            var          subject    = @"mailto:[email protected]";
            const string publicKey  = @"BAHU3QNr2PvPSufR9hKYgV7daemnktvh6AYqBqta9brwWK6S064nzJQCadUT4LD3fyJMs5FiKh9uW_v_t4aU4eI";
            const string privateKey = @"hoIs3IDTJvGbPUgK2qhwFuREX5deqKhBVNAN0a70_dg";

            var subscription = new PushSubscription(pushNotification.Endpoint, pushNotification.ReceiverKey, pushNotification.AuthKey);
            var vapidDetails = new VapidDetails(subject, publicKey, privateKey);

            var webPushClient = new WebPushClient();

            try
            {
                await webPushClient.SendNotificationAsync(subscription, JsonConvert.SerializeObject(pushMessage), vapidDetails);
            }
            catch (AggregateException ae)
            {
                ae.Handle((ex) =>
                {
                    if (ex is WebPushException)
                    {
                        var xpe = (WebPushException)ex;
                        switch (xpe.StatusCode)
                        {
                        case System.Net.HttpStatusCode.Gone:
                            //TODO: Delete endpoint from VXUserPushNotification
                            return(true);

                        default:
                            PXTrace.WriteError(ex);
                            return(false);
                        }
                    }

                    PXTrace.WriteError(ex);
                    return(false);
                });
            }
        }
Exemplo n.º 29
0
 public bool PrepareImportRow(string viewName, IDictionary keys, IDictionary values)
 {
     if (string.Compare(viewName, PIDetail.View.Name, true) == 0)
     {
         PXCache       barCodeCache = AddByBarCode.Cache;
         INBarCodeItem item         = (INBarCodeItem)(AddByBarCode.Current ?? barCodeCache.CreateInstance());
         try
         {
             barCodeCache.SetValueExt <INBarCodeItem.inventoryID>(item, GetImportedValue <INPIDetail.inventoryID>(values, true));
             if (PXAccess.FeatureInstalled <FeaturesSet.subItem>())
             {
                 barCodeCache.SetValueExt <INBarCodeItem.subItemID>(item, GetImportedValue <INPIDetail.subItemID>(values, true));
             }
             if (PXAccess.FeatureInstalled <FeaturesSet.warehouseLocation>())
             {
                 barCodeCache.SetValueExt <INBarCodeItem.locationID>(item, GetImportedValue <INPIDetail.locationID>(values, true));
             }
             if (PXAccess.FeatureInstalled <FeaturesSet.lotSerialTracking>())
             {
                 barCodeCache.SetValueExt <INBarCodeItem.lotSerialNbr>(item, GetImportedValue <INPIDetail.lotSerialNbr>(values, false));
             }
             barCodeCache.SetValueExt <INBarCodeItem.qty>(item, GetImportedValue <INPIDetail.physicalQty>(values, true));
             barCodeCache.SetValueExt <INBarCodeItem.autoAddLine>(item, false);
             barCodeCache.Update(item);
             UpdatePhysicalQty();
         }
         catch (Exception e)
         {
             PXTrace.WriteError(IN.Messages.RowError, excelRowNumber, e.Message);
             importHasError = true;
         }
         finally
         {
             excelRowNumber++;
         }
     }
     return(false);
 }
Exemplo n.º 30
0
        public virtual void SetFlagsFromStatus(PMTask task, string status)
        {
            if (string.IsNullOrEmpty(status))
            {
                throw new ArgumentNullException();
            }

            switch (status)
            {
            case ProjectTaskStatus.Planned:
                task.IsActive    = false;
                task.IsCompleted = false;
                task.IsCancelled = false;
                break;

            case ProjectTaskStatus.Active:
                task.IsActive    = true;
                task.IsCompleted = false;
                task.IsCancelled = false;
                break;

            case ProjectTaskStatus.Canceled:
                task.IsActive    = false;
                task.IsCompleted = false;
                task.IsCancelled = true;
                break;

            case ProjectTaskStatus.Completed:
                task.IsActive    = true;
                task.IsCompleted = true;
                task.IsCancelled = false;
                break;

            default:
                PXTrace.WriteError("Unknown status: " + status);
                break;
            }
        }