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(); } } }
public virtual void VerifyApiAccessPermission() { KCSiteMaster row = SiteMaster.Current; if (row == null) { return; } if (row.ApplicationId != "" && row.SharedSecret != "") { PXLongOperation.StartOperation(this, delegate() { KCInternalReponse response = new KCSiteMasterHelper().VerifyApiAccess(row); if (response != null) { if (!response.IsSuccess && !string.IsNullOrEmpty(response.Message)) { throw new PXException(response.Message); } else if (!string.IsNullOrEmpty(response.Message)) { PXTrace.WriteInformation(response.Message); } } else { string exceptionmsg = string.Format(KCConstants.DualParameters, KCConstants.VerifyApiAccess, KCMessages.NullException); throw new PXException(exceptionmsg); } }); } }
public virtual IEnumerable AuthorizeCCPayment(PXAdapter adapter) { var methodName = GetClassMethodName(); AccessInfo info = this.Base.Accessinfo; PXTrace.WriteInformation($"{methodName} started."); List <TPrimary> list = new List <TPrimary>(); foreach (TPrimary doc in adapter.Get <TPrimary>()) { CheckDocumentUpdatedInDb(doc); PXCache cache = this.Base.Caches[typeof(TPrimary)]; bool prevAllowUpdateState = cache.AllowUpdate; cache.AllowUpdate = true; ICCPayment pDoc = GetPaymentDoc(doc); PXTrace.WriteInformation($"{methodName}. RefNbr:{pDoc.RefNbr}; UserName:{info.UserName}"); list.Add(doc); BeforeAuthorizePayment(doc); var afterAuthorizeActions = GetAfterAuthorizeActions(); CCPaymentEntry paymentEntry = GetCCPaymentEntry(); foreach (var item in afterAuthorizeActions) { paymentEntry.AddAfterProcessCallback(item); } if (ReleaseAfterAuthorize) { paymentEntry.AddAfterProcessCallback(ReleaseARDocument); } paymentEntry.AuthorizeCCpayment(pDoc, new GenericExternalTransactionAdapter <ExternalTransactionDetail>(ExternalTransaction)); cache.AllowUpdate = prevAllowUpdateState; } return(list); }
public virtual IEnumerable <ApproveInfo> Assign(Table item, EPAssignmentMap map, bool isApprove) { path.Clear(); processMapType = GraphHelper.GetType(map.EntityType); Type itemType = item.GetType(); PXSelectBase <EPAssignmentRoute> rs = new PXSelectReadonly <EPAssignmentRoute, Where <EPAssignmentRoute.assignmentMapID, Equal <Required <EPAssignmentMap.assignmentMapID> >, And <EPAssignmentRoute.parent, IsNull> >, OrderBy <Asc <EPAssignmentRoute.sequence> > >(this); PXResultset <EPAssignmentRoute> routes = rs.Select(map.AssignmentMapID, null); Type mapgraphtype = GraphHelper.GetType(map.GraphType); //impossible, but written to support purpose of legacy db states if (mapgraphtype == null) { mapgraphtype = EntityHelper.GetPrimaryGraphType(this, processMapType); } if (_Graph != null && mapgraphtype.IsAssignableFrom(_Graph.GetType())) { processGraph = _Graph; } else { processGraph = CreateInstance(GraphHelper.GetType(map.GraphType) ?? mapgraphtype); } if (processGraph != null && processMapType != null) { if (processMapType.IsAssignableFrom(itemType)) { this.processGraph.Caches[itemType].Current = item; } else if (itemType.IsAssignableFrom(processMapType)) { object placed = this.processGraph.Caches[processMapType].CreateInstance(); PXCache cache = (PXCache)Activator.CreateInstance(typeof(PXCache <>).MakeGenericType(itemType), this); cache.RestoreCopy(placed, item); this.processGraph.Caches[processMapType].Current = placed; } else { return(null); } } var result = ProcessLevel(item, map.AssignmentMapID, routes).ToList(); if (result.Any()) { return(result); } PXTrace.WriteWarning(Messages.DocumentPreApproved); throw new RequestApproveException(); }
public void Debug(string message) { if (_debugEnabled) { PXTrace.WriteInformation($"{TaxProviderName} - {message}"); } }
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(); }
public async Task <string> PostPrediction(string querystring) { string add = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/717af479-1d8c-40f9-afb3-fd800eda8bca"; Uri address = new Uri(add); using (var client = new HttpClient(new HttpClientHandler())) { client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "2b9324da598d4b52b6b78eccb45a7a05"); try { var result = await client.PostAsJsonAsync(address, querystring); if (result.IsSuccessStatusCode) { return(await result.Content.ReadAsStringAsync()); } else { PXTrace.WriteInformation(address.ToString()); PXTrace.WriteInformation(result.ToString()); return(result.ToString()); } } catch (Exception ex) { throw new PX.Data.PXException(ex.Message); } } }
#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)); } } }
/// <summary> /// Ask user for approval for creation of another reversal if reversing <see cref="TaxAdjustment"/> already exists. /// </summary> /// <param name="taxAdjToReverse">The tax adjustment to reverse.</param> /// <returns/> private bool AskUserApprovalIfReversingDocumentAlreadyExists(TaxAdjustment taxAdjToReverse) { TaxAdjustment reversingTaxAdj = PXSelect <TaxAdjustment, Where <TaxAdjustment.docType, Equal <Required <TaxAdjustment.docType> >, And <TaxAdjustment.origRefNbr, Equal <Required <TaxAdjustment.origRefNbr> > > >, OrderBy < Desc <TaxAdjustment.createdDateTime> > > .SelectSingleBound(this, currents : null, pars : new[] { taxAdjToReverse.DocType, taxAdjToReverse.RefNbr }); if (reversingTaxAdj == null) { return(true); } string docTypeDescr; TaxAdjustmentType.ListAttribute labelsListAttribute = new TaxAdjustmentType.ListAttribute(); if (!labelsListAttribute.ValueLabelDic.TryGetValue(reversingTaxAdj.DocType, out docTypeDescr)) { docTypeDescr = taxAdjToReverse.DocType; PXTrace.WriteWarning("Failed to retrieve tax adjustment type {0} description from {1} attribute.", reversingTaxAdj.DocType, nameof(TaxAdjustmentType.ListAttribute)); } string localizedMsg = PXMessages.LocalizeFormatNoPrefix(AR.Messages.ReversingDocumentExists, docTypeDescr, reversingTaxAdj.RefNbr); return(Document.Ask(Messages.Reverse, localizedMsg, MessageButtons.YesNo).IsPositive()); }
protected virtual void RecalculatePackagesForOrder(Document doc) { if (doc == null) { throw new ArgumentNullException(nameof(doc)); } if (string.IsNullOrEmpty(doc.ShipVia)) { throw new PXException(Messages.ShipViaMustBeSet); } ClearPackages(doc); IList <SOPackageEngine.PackSet> packsets = CalculatePackages(doc, doc.ShipVia); foreach (SOPackageEngine.PackSet ps in packsets) { if (ps.Packages.Count > 1000) { PXTrace.WriteWarning("During autopackaging more than 1000 packages were generated. Please check your configuration."); } InsertPackages(ps.Packages); } if (packsets.Count > 0) { Documents.Cache.SetValue <Document.isPackageValid>(doc, true); } }
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); } }
protected void PersistMessages(IEnumerable <CRSMEmail> messages) { using (PXTransactionScope ts = new PXTransactionScope()) { foreach (CRSMEmail item in messages) { try { var activityCache = Graph.Caches[item.GetType()]; PXDBDefaultAttribute.SetSourceType <CRSMEmail.refNoteID>(activityCache, item, null); activityCache.PersistInserted(item); } catch (Exception e) { if (!MassProcessMode) { throw; } PXTrace.WriteInformation(e); } } Graph.Caches <CRActivityStatistics>().Persist(PXDBOperation.Insert); Graph.Caches <CRActivityStatistics>().Persist(PXDBOperation.Update); ts.Complete(); } }
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 + ", "; } }
public async Task <string> GetPrediction(string querystring) { string add = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/717af479-1d8c-40f9-afb3-fd800eda8bca?verbose=true&timezoneOffset=0&subscription-key=2b9324da598d4b52b6b78eccb45a7a05"; string querystring2 = System.Web.HttpUtility.UrlEncode(querystring); add = add + "q=" + querystring2; Uri address = new Uri(add); using (var client = new HttpClient()) { try { var result = await client.GetAsync(address); if (result.IsSuccessStatusCode) { return(await result.Content.ReadAsStringAsync()); } else { PXTrace.WriteInformation(address.ToString()); PXTrace.WriteInformation(result.ToString()); return(result.ToString()); } } catch (Exception ex) { throw new PX.Data.PXException(ex.Message); } } }
public static void TraceAndThrowException(string message, params object[] args) { var exception = new PXException(message, args); PXTrace.WriteError(exception); throw exception; }
private static Message GetListOfMessagesContent(SubmitFeedParamaters objSubmitFeedParams) { Message objMessage = new Message(); objMessage.MessageID = objSubmitFeedParams.shipmentNbr; OrderFulfillment objOrderFulfillment = new OrderFulfillment(); FulfillmentData objFulfillmentData = new FulfillmentData(); objOrderFulfillment.AmazonOrderID = objSubmitFeedParams.amazonOrderID; objOrderFulfillment.FulfillmentDate = new DateTimeOffset(Convert.ToDateTime(objSubmitFeedParams.shipmentDate), PXTimeZoneInfo.FindSystemTimeZoneById("GMTM0800A").UtcOffset).ToString("yyyy-MM-ddTHH:mm:sszzz"); PXTrace.WriteInformation(String.Format("Shipment# {0} FulfillmentDate {1}", objMessage.MessageID, objOrderFulfillment.FulfillmentDate)); objFulfillmentData.CarrierName = objSubmitFeedParams.carrierCode; objFulfillmentData.ShippingMethod = objSubmitFeedParams.shipVia; objFulfillmentData.ShipperTrackingNumber = objSubmitFeedParams.trackingNbr; objOrderFulfillment.FulfillmentData = objFulfillmentData; if (objSubmitFeedParams.liShipItem != null && objSubmitFeedParams.liShipItem.Count > 0) { objOrderFulfillment.Item = objSubmitFeedParams.liShipItem; } objMessage.OrderFulfillment = objOrderFulfillment; return(objMessage); }
public const int FileNameMaxLength = 208; //2^7 + 2^6 + 2^4 public FileDto(Guid entityId, string name, byte[] content, Guid?fileId = null, string contentId = null) { EntityNoteId = entityId; Content = content ?? throw new ArgumentNullException(nameof(content)); Name = name ?? throw new ArgumentNullException(nameof(name)); try { var extension = System.IO.Path.GetExtension(Name); if (Name.Length > FileNameMaxLength) { if (extension.IsNullOrEmpty()) { var newName = Name.Substring(0, FileNameMaxLength); PXTrace.WriteWarning("Trying to save file with too long name. The name was cut off. Original value: {0}, new value: {1}", name, newName); Name = newName; } else { var newName = Name.Substring(0, FileNameMaxLength + extension.Length); PXTrace.WriteWarning("Trying to save file with too long name. The name was cut off. Original value: {0}, new value: {1}", name, newName); Name = newName + extension; } } } catch { PXTrace.WriteWarning("Trying to save file with invalid file name. The name will be replaced with default: \'file\'."); Name = "file"; } FileId = fileId ?? Guid.NewGuid(); ContentId = contentId; }
/// <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); } }
public void ShipPackages(SOShipment shiporder, Action <SOShipment> baseMethod) { if (shiporder.Operation == SOOperation.Issue) { if (String.IsNullOrEmpty(shiporder.ShipVia) || shiporder.ShipVia == "FREESHIP" || shiporder.ShipVia == "GROUND" || shiporder.ShipVia == "OVERNIGHT" || shiporder.ShipVia == "2DAY") { Base.Clear(); Base.Document.Current = Base.Document.Search <SOShipment.shipmentNbr>(shiporder.ShipmentNbr); shiporder = Base.Document.Current; SOPackageDetail p = Base.Packages.SelectSingle(); if (p == null) { throw new PXException(PX.Objects.SO.Messages.PackageIsRequired); } SelectLeastExpensiveShipVia(); } else { PXTrace.WriteInformation("Skipping rate shopping because a Ship Via is already selected."); } } var sw = new Stopwatch(); sw.Start(); baseMethod(shiporder); sw.Stop(); PXTrace.WriteInformation($"ShipPackages took {sw.ElapsedMilliseconds}ms."); }
private void TraceTransactionsInformation() { foreach (var line in subcontractLines) { PXTrace.WriteInformation(line.Dump()); } }
public virtual List <BoxInfo> PackByWeight(List <INItemBoxEx> boxes, decimal baseWeight, decimal baseQty, int inventoryID) { boxes.Sort((INItemBoxEx x, INItemBoxEx y) => decimal.Compare(x.MaxWeight.GetValueOrDefault(), y.MaxWeight.GetValueOrDefault())); List <BoxInfo> list = new List <BoxInfo>(); if (baseQty == 0) { PXTrace.WriteWarning("Packing Engine failed to execute. BaseQty supplied is zero."); return(list); } decimal unitWeight = baseWeight / baseQty; if (baseWeight > 0 && boxes.Count > 0) { INItemBoxEx box = GetBoxThatCanFitWeight(boxes, baseWeight); if (box != null) { BoxInfo p = new BoxInfo(); p.Box = box; p.Value = baseWeight; list.Add(p); } else { //Distribute qty among Biggest boxes available: INItemBoxEx biggestBox = boxes[boxes.Count - 1]; if (biggestBox.MaxNetWeight > 0) { if (biggestBox.MaxNetWeight < unitWeight) { throw new PXException(Messages.PackagesRecalcErrorNoBoxesThatFitItem, InventoryItem.PK.Find(graph, (int?)inventoryID)?.InventoryCD); } int numberOfMaxBoxes = (int)Math.Floor(baseWeight / biggestBox.MaxNetWeight); int itemsPerBox = (int)Math.Floor(biggestBox.MaxNetWeight / unitWeight); for (int i = 0; i < numberOfMaxBoxes; i++) { BoxInfo p = new BoxInfo(); p.Box = biggestBox; p.Value = itemsPerBox * unitWeight; list.Add(p); baseWeight -= itemsPerBox * unitWeight; baseQty -= itemsPerBox; } //remainder list.AddRange(PackByWeight(boxes, baseWeight, baseQty, inventoryID)); } } } return(list); }
public static void SendData(IEnumerable <SOOrder> data, string name = "orders.csv") { //Create needed graphs var graph = PXGraph.CreateInstance <AFSetupMaint>(); AFSetup setup = graph.AFSetupView.Current ?? graph.AFSetupView.Select(); //----------------------------------------------------------------------------- //Change for Setup daya string bucketName = setup.AFBucketName; //"acumatica-forecast"; string s3DirectoryName = setup.AFDirectoryName; //"dynamics/facturas"; string accessKey = setup.AFAccessKey; string secretKey = setup.AFSecretKey; //----------------------------------------------------------------------------- PXTrace.WriteInformation($"AFAccessKey: {accessKey} AFSecretKey: {secretKey} AFBucketName: {bucketName} AFDirectoryName: {s3DirectoryName}"); //if (data?.Count == 0) return; using (var stream = new MemoryStream()) { using (StreamWriter sw = new StreamWriter(stream)) { try { // Convert to csv and upload foreach (var i in data) { try { //var row = data[i]; //Check current item //PXProcessing.SetCurrentItem(row); //sw.WriteLine(i); } catch (Exception e) { PXProcessing <SOOrder> .SetError(e.Message); } } var line = $"TEST,2020-01-25T00:10:10,1.00"; sw.WriteLine(line); //Si existe el CFDI permite la subida del XML y PDF //Se crea la instancia a S3 AFAmazonTools myUploader = new AFAmazonTools(); var result = myUploader.UploadToS3(accessKey, secretKey, stream.ToArray(), bucketName, s3DirectoryName, name); } catch (Exception e) { PXProcessing <SOOrder> .SetError(e.Message); } } } }
public virtual IEnumerable IndexCustomArticles(PXAdapter adapter) { PXLongOperation.StartOperation(this, delegate() { foreach (var result in WikiArticles.Select()) { string plaintext = null; var _wp = (WikiPage)result[typeof(WikiPage)]; var _wr = (WikiRevision)result[typeof(WikiRevision)]; var _wl = (WikiPageLanguage)result[typeof(WikiPageLanguage)]; if (_wp.IsHtml != true) { WikiReader reader = PXGraph.CreateInstance <WikiReader>(); PXWikiSettings settings = new PXWikiSettings(new PXPage(), reader); PXTxtRenderer renderer = new PXTxtRenderer(settings.Absolute); var ctx = new PXDBContext(settings.Absolute); ctx.Renderer = renderer; plaintext = (_wl.Title ?? "") + Environment.NewLine + PXWikiParser.Parse(_wr.Content, ctx); } else { plaintext = (_wl.Title ?? "") + Environment.NewLine + SearchService.Html2PlainText(_wr.Content); } //Try updating the article in current Company if (!PXDatabase.Update <WikiRevision>( new PXDataFieldAssign("PlainText", PXDbType.NVarChar, plaintext), new PXDataFieldRestrict("PageID", PXDbType.UniqueIdentifier, _wr.PageID), new PXDataFieldRestrict("PageRevisionID", PXDbType.Int, _wr.PageRevisionID), new PXDataFieldRestrict("Language", PXDbType.VarChar, _wr.Language) )) { //Article may be shared. Try updating the article through graph (thus handling the shared record update stratagy) //if article is not updatable an exception may be thrown - ignore. try { ArticleUpdater updater = PXGraph.CreateInstance <ArticleUpdater>(); WikiRevision rev = updater.Revision.Select(_wr.PageID, _wr.PageRevisionID, _wr.Language); rev.PlainText = plaintext; updater.Revision.Update(rev); updater.Persist(); } catch (Exception ex) { PXTrace.WriteInformation("Plain text field could not be updated for article = {0}. Error Message: {1}", _wr.PageID, ex.Message); } } } }); return(adapter.Get()); }
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); }
/// <summary> /// MAKE API CALLS ----> GET,POST,PUT,PATCH /// </summary> /// <param name="apiurl"></param> /// <param name="apirequest"></param> /// <param name="apimethod"></param> /// <param name="header"></param> /// <returns></returns> public static KCAPIWebReponse CallWebAPI(string apiurl, string apirequest, string apimethod, WebHeaderCollection header, string contenttype = "application/json") { KCAPIWebReponse response = new KCAPIWebReponse(); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3; HttpWebRequest web_request = (HttpWebRequest)WebRequest.Create(apiurl); web_request.Headers = header; web_request.Method = apimethod; web_request.ContentType = contenttype;// ; if (!string.IsNullOrEmpty(apirequest)) { byte[] byteArray = Encoding.ASCII.GetBytes(apirequest); web_request.ContentLength = byteArray.Length; Stream req_datastream = web_request.GetRequestStream(); req_datastream.Write(byteArray, 0, byteArray.Length); req_datastream.Close(); } try { HttpWebResponse web_response = (HttpWebResponse)web_request.GetResponse(); Stream res_datastream = web_response.GetResponseStream(); using (StreamReader reader = new StreamReader(res_datastream)) { string responseFromServer = reader.ReadToEnd(); response.httpWebRes = web_response; response.response = responseFromServer; response.Message = "Success"; response.IsSuccess = true; reader.Close(); //res_datastream.Close(); web_response.Close(); } } catch (WebException exception) { string sResponse = new StreamReader(exception.Response.GetResponseStream()).ReadToEnd(); PXTrace.WriteInformation(sResponse); response.Message = exception.Message + Environment.NewLine; response.IsSuccess = false; } catch (Exception exception) { response.Message = exception.Message; response.IsSuccess = false; } return(response); }
public virtual decimal GetPerUnitTaxAmountForTaxableAdjustmentCalculation(Tax taxForTaxableAdustment, TaxDetail taxDetail, PXCache taxDetailCache, object row, PXCache rowCache, string curyTaxAmtFieldName, Func <List <object> > perUnitTaxSelector) { taxForTaxableAdustment.ThrowOnNull(nameof(taxForTaxableAdustment)); taxDetail.ThrowOnNull(nameof(taxDetail)); taxDetailCache.ThrowOnNull(nameof(taxDetailCache)); row.ThrowOnNull(nameof(row)); rowCache.ThrowOnNull(nameof(rowCache)); curyTaxAmtFieldName.ThrowOnNullOrWhiteSpace(nameof(curyTaxAmtFieldName)); perUnitTaxSelector.ThrowOnNull(nameof(perUnitTaxSelector)); if (taxForTaxableAdustment.TaxType == CSTaxType.PerUnit) { return(0m); } Type taxAmountField = taxDetailCache.GetBqlField(curyTaxAmtFieldName); List <object> allPerUnitTaxes = perUnitTaxSelector?.Invoke(); if (allPerUnitTaxes == null || allPerUnitTaxes.Count == 0) { return(0m); } var(perUnitInclusiveTaxes, perUnitLevel1Taxes) = GetNonExcludedPerUnitTaxesByCalculationLevel(allPerUnitTaxes); if (perUnitInclusiveTaxes.Count == 0 && perUnitLevel1Taxes.Count == 0) { return(0m); } switch (taxForTaxableAdustment.TaxCalcLevel) { case CSTaxCalcLevel.Inclusive when perUnitLevel1Taxes.Count > 0: PXTrace.WriteInformation(Messages.CombinationOfExclusivePerUnitTaxAndInclusveTaxIsForbiddenErrorMsg); throw new PXSetPropertyException(Messages.CombinationOfExclusivePerUnitTaxAndInclusveTaxIsForbiddenErrorMsg, PXErrorLevel.Error); case CSTaxCalcLevel.Inclusive: //The adjustment to taxable is amount of all per unit taxes. The level 1 per unit taxes are prohibited. return(SumTaxAmountsWithReverseAdjustment(taxDetailCache.Graph, perUnitInclusiveTaxes, taxAmountField)); case CSTaxCalcLevel.CalcOnItemAmt: var allNonExcludedPerUnitTaxes = perUnitInclusiveTaxes.Concat(perUnitLevel1Taxes); return(SumTaxAmountsWithReverseAdjustment(taxDetailCache.Graph, allNonExcludedPerUnitTaxes, taxAmountField)); case CSTaxCalcLevel.CalcOnItemAmtPlusTaxAmt: // For level 2 taxes: // Taxable = LineAmt - InclusiveTaxAmt (including per unit inclusive taxes) + Level 1 Taxes amount (including per unit level 1 taxes) // Therefore, we need to add only the previously subtracted amount of inclusive per unit taxes return(SumTaxAmountsWithReverseAdjustment(taxDetailCache.Graph, perUnitInclusiveTaxes, taxAmountField)); default: return(0m); } }
public virtual void CheckPartiallyReceiptedPOServices(PXCache sender, PXFieldUpdatedEventArgs e, string poOrderType) { POSetup row = (POSetup)e.Row; if (row != null) { PXResultset <POLine> partiallyReceiptedPOServices = PXSelectReadonly2 <POLine, InnerJoin <IN.InventoryItem, On <POLine.FK.InventoryItem> >, Where <POLine.orderType, Equal <Required <POLine.orderType> >, And <POLine.lineType, Equal <POLineType.service>, And <POLine.completed, NotEqual <True>, And <POLine.receivedQty, NotEqual <decimal0> > > > > > .SelectWindowed(this, 0, 1000, poOrderType); if (partiallyReceiptedPOServices.Count > 0) { if (poOrderType == POOrderType.RegularOrder) { if (row.AddServicesFromNormalPOtoPR == true) { PXUIFieldAttribute.SetWarning <POSetup.addServicesFromNormalPOtoPR>(sender, row, Messages.PossibleOverbillingAPNormalPO); } else { PXUIFieldAttribute.SetWarning <POSetup.addServicesFromNormalPOtoPR>(sender, row, Messages.PossibleOverbillingPRNormalPO); } } else { if (row.AddServicesFromDSPOtoPR == true) { PXUIFieldAttribute.SetWarning <POSetup.addServicesFromDSPOtoPR>(sender, row, Messages.PossibleOverbillingAPDSPO); } else { PXUIFieldAttribute.SetWarning <POSetup.addServicesFromDSPOtoPR>(sender, row, Messages.PossibleOverbillingPRDSPO); } } string overbillingMessage = Messages.PossibleOverbillingTraceList + " \n"; int i = 0; foreach (PXResult <POLine, IN.InventoryItem> line in partiallyReceiptedPOServices) { POLine poline = (POLine)line; IN.InventoryItem item = (IN.InventoryItem)line; overbillingMessage += string.Format(Messages.PossibleOverbillingTraceMessage, (poOrderType == POOrderType.RegularOrder ? Messages.RegularOrder : Messages.DropShip), poline.OrderNbr, poline.LineNbr, item.InventoryCD) + "\n"; i++; if (i >= 1000) { break; } } PXTrace.WriteWarning(overbillingMessage); } } }
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()); }
public virtual IEnumerable trainFaceRecongnition(PXAdapter adapter) { Save.Press(); PXLongOperation.StartOperation(this, delegate() { IFaceClient client = Trainer.Authenticate(MasterView.Current.FaceApiEndpoint, MasterView.Current.FaceApiSubscriptionKey); var trainer = new Trainer(client, MasterView.Current.FaceApiGroupID); bool uploaded = false; foreach (EPEmployee emp in PXSelect <EPEmployee> .Select(this)) { bool deleted = false; Person person = null; Guid[] files = PXNoteAttribute.GetFileNotes(this.Caches[typeof(EPEmployee)], emp); foreach (Guid fileID in files) { var fm = new PX.SM.UploadFileMaintenance(); PX.SM.FileInfo fi = fm.GetFile(fileID); string ext = System.IO.Path.GetExtension(fi.Name).ToLower(); PXTrace.WriteWarning(emp.AcctCD.TrimEnd() + " " + ext); if (ext.IsIn(".png", ".jpg", ".bmp")) { if (!deleted) { var utilities = new Utilities(client, MasterView.Current.FaceApiGroupID); utilities.DeleteEmployee(emp.AcctCD.TrimEnd()); deleted = true; } if (person == null) { person = trainer.GetEmployee_CreateIfNonExistent(emp.AcctCD.TrimEnd()); } using (var stream = new System.IO.MemoryStream(fi.BinData)) { PXTrace.WriteWarning(emp.AcctCD.TrimEnd() + " " + fi.Name + " " + stream.Length); trainer.UploadTrainingImageStream(person, stream); Thread.Sleep(1000); uploaded = true; } } } } if (uploaded) { trainer.InvokeTraining(); } }); return(adapter.Get()); }
private ListOrdersResponse InvokeListOrders(PXGraph graph, ServiceCallParameters objParams) { ListOrdersResponse response = new ListOrdersResponse(); try { ListOrdersRequest request = new ListOrdersRequest(); request.SellerId = objParams.objSOAmazonSetup.SellerId; request.MWSAuthToken = objParams.objSOAmazonSetup.AuthToken; List <string> marketplaceId = new List <string>(); marketplaceId.Add(objParams.objSOAmazonSetup.MarketplaceId); request.MarketplaceId = marketplaceId; request.CreatedAfter = Convert.ToDateTime(objParams.fromDate); if (objParams.toDate.Value.Date < DateTime.Now.Date) { request.CreatedBefore = objParams.toDate.Value.AddDays(1).AddTicks(-1); } PXTrace.WriteInformation("objParams.fromDate.Value.Date:" + objParams.fromDate.Value.Date.ToString()); PXTrace.WriteInformation("objParams.toDate.Value.Date:" + objParams.toDate.Value.Date.ToString()); PXTrace.WriteInformation("request.CreatedAfter:" + request.CreatedAfter.ToString()); PXTrace.WriteInformation("request.CreatedBefore:" + request.CreatedBefore.ToString()); List <string> liFulfillmentChannel = null; List <string> liOrderStatus = null; SOHelper.GetFilterValues(objParams.objSOAmazonSetup.IntegrationType.Trim(), out liFulfillmentChannel, out liOrderStatus); request.FulfillmentChannel = liFulfillmentChannel; request.OrderStatus = liOrderStatus; response = this.clientOrder.ListOrders(request); } catch (Exception ex) { if (ex is MarketplaceWebServiceOrdersException) { MarketplaceWebServiceOrdersException exception = ex as MarketplaceWebServiceOrdersException; if (!string.IsNullOrEmpty(exception.ErrorCode) && exception.ErrorCode.ToLower().Trim() == SOMessages.requestThrottled) { Thread.Sleep(SOHelper.DelayProcess(graph, SOConstants.apiListOrders)); response = InvokeListOrders(graph, objParams); } else { throw new PXException(!string.IsNullOrEmpty(ex.Message) ? ex.Message : ex.InnerException != null && ex.InnerException.InnerException != null ? ex.InnerException.InnerException.Message : SOConstants.exceptionIsEmpty); } } else { throw new PXException(!string.IsNullOrEmpty(ex.Message) ? ex.Message : ex.InnerException != null && ex.InnerException.InnerException != null ? ex.InnerException.InnerException.Message : SOConstants.exceptionIsEmpty); } } return(response); }