How to save changes on Opportunity from other screen? - c#

I have a field in CROpportunity named UsrOrderTotalValue.
Sales Order(SO301000) and Opportunitis(CR304000) are linked with added to SOOrder tab custome field UsrOpportunityID.
When Save Button pusshed on Sales Order, it's needed to save to a UsrOrderTotalValue some Value.
Some code snipet is given below.
Besides below I tried different approaches of using Persist, but nothing works.
My Acumatica version:
Acumatica 2018 R1 (18.110.0017)
OpportunityMaint opportunityGraph = PXGraph.CreateInstance<OpportunityMaint>();
SOOrderExt sOOrderExt = row.GetExtension<SOOrderExt>();
CROpportunity cROpportunity = Opportunity.Select(sOOrderExt.UsrOpportunityID);
opportunityGraph.Opportunity.Update(cROpportunity);
opportunityGraph.Save.Press();

Try like below, I have hardcoded value, please replace with your fields.
[PXOverride]
public void Persist(Action del)
{
if ((Base.Document.Cache.GetStatus(Base.Document.Current) == PXEntryStatus.Inserted || Base.Document.Cache.GetStatus(Base.Document.Current) == PXEntryStatus.Updated))
{
OpportunityMaint opportunityGraph = PXGraph.CreateInstance<OpportunityMaint>();
CROpportunity cROpportunity = new CROpportunity();
cROpportunity.OpportunityID = "000001";
cROpportunity = opportunityGraph.Opportunity.Current = opportunityGraph.Opportunity.Select(cROpportunity);
if (cROpportunity != null)
cROpportunity.OpportunityName = "test";
opportunityGraph.Opportunity.Update(cROpportunity);
opportunityGraph.Save.Press();
}
del();
}

Related

How to set Publish Date in Word Document using OpenXML

I have a situation where a user can upload a word document which contains placeholders for certain properties (i.e. in MS Word the user has gone to Insert > Quick Parts > Document Properties and chosen a property). The specific properties I want to support are Title, Author, Company and Publish Date.
Title and Author are set as Package Properties, and Company is set as an Extended File Property. These are set with the below code, which works correctly:
private static void SetDocumentProperties(ReportTemplateModel model, WordprocessingDocument wordDocument)
{
//these properties always exist
wordDocument.PackageProperties.Title = model.Title;
wordDocument.PackageProperties.Creator = model.Author;
wordDocument.PackageProperties.Created = DateTime.Now;
wordDocument.PackageProperties.Modified = DateTime.Now;
//these properties can be null
if (wordDocument.ExtendedFilePropertiesPart == null)
{
wordDocument.AddNewPart<ExtendedFilePropertiesPart>();
}
if (wordDocument.ExtendedFilePropertiesPart.Properties == null)
{
wordDocument.ExtendedFilePropertiesPart.Properties = new Properties(new Company(model.SiteName));
}
else
{
wordDocument.ExtendedFilePropertiesPart.Properties.Company = new Company(model.SiteName);
}
}
My problem is that I can't work out how the set the Publish Date property. I have tried adding it as a Custom File Property using the below code (which is adapted from https://www.snip2code.com/Snippet/292005/WDSetCustomProperty), but this does not work. I've read a few things about setting custom properties, but I'm confused how they're meant to work. I'm also unsure if the Publish Date should actually be set as a custom property, or some other type of property.
var customProps = wordDocument.CustomFilePropertiesPart;
if (customProps == null)
{
customProps = wordDocument.AddCustomFilePropertiesPart();
customProps.Properties = new DocumentFormat.OpenXml.CustomProperties.Properties();
}
var properties1 = new DocumentFormat.OpenXml.CustomProperties.Properties();
//I have tried both of these lines, neither worked.
//properties1.AddNamespaceDeclaration("op", "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties");
properties1.AddNamespaceDeclaration("vt", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes");
var customDocumentProperty1 = new DocumentFormat.OpenXml.CustomProperties.CustomDocumentProperty()
{
FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}",
PropertyId = 2,
Name = "Publish Date"
};
customDocumentProperty1.Append(new DocumentFormat.OpenXml.VariantTypes.VTLPWSTR { Text = DateTime.Today.ToShortDateString() });
properties1.Append(customDocumentProperty1);
part.Properties = properties1;
What type of property should the Publish Date be set as, and what is the right syntax for setting this?
Update: I have found that Publish Date is a CoverPageProperty which can be created using the below snippet, but I still haven't found how to set it correctly within the document.
var coverPageProps = new DocumentFormat.OpenXml.Office.CoverPageProps.CoverPageProperties
{
PublishDate = new PublishDate(DateTime.Today.ToShortDateString())
};
Adding the below code to my SetDocumentProperties method seems to work. I must admit I don't fully understand the below code, so any explanation would still be welcome. Additionally, if anyone has a solution which doesn't include writing XML as a string inside C# I would much prefer to avoid that.
const string publishDatePartId = "publishDatePart";
var publishDateXmlPart = wordDocument.MainDocumentPart.AddNewPart<CustomXmlPart>("application/xml", publishDatePartId);
var writer = new XmlTextWriter(publishDateXmlPart.GetStream(FileMode.Create), System.Text.Encoding.UTF8);
writer.WriteRaw($"<CoverPageProperties xmlns=\"http://schemas.microsoft.com/office/2006/coverPageProps\">" +
$"<PublishDate>{DateTime.Today.ToShortDateString()}</PublishDate>" +
$"</CoverPageProperties>");
writer.Flush();
writer.Close();
var customXmlPropertiesPart = publishDateXmlPart.AddNewPart<CustomXmlPropertiesPart>(publishDatePartId);
customXmlPropertiesPart.DataStoreItem = new DocumentFormat.OpenXml.CustomXmlDataProperties.DataStoreItem()
{
//I don't know what this ID is, but it seems to somehow relate to the Publish Date
ItemId = "{55AF091B-3C7A-41E3-B477-F2FDAA23CFDA}"
};

Copy Records to another Screen in acumatica

I have 2 screen, inquiry and data entry.
and i want to copy Record from Screen1 to screen2, see picture below.
scree1 and Screen2
I use the following code:
public PXAction<FuncLocFilter> CreateFuncLoc;
[PXButton]
[PXUIField(DisplayName = "Create Functional Location")]
protected virtual void createFuncLoc()
{
FuncLocFilter row = Filter.Current;
BSMTFuncLoc FnLc = new BSMTFuncLoc();
FunLocEntry graph = PXGraph.CreateInstance<FunLocEntry>();
graph.FunLocations.Current.FuncLocCD = row.FuncLocCD;
graph.FunLocations.Current.StructureID = row.StructureID;
graph.FunLocations.Current.HierLevels = row.HierLevels;
graph.FunLocations.Current.EditMask = row.EditMask;
if (graph.FunLocations.Current != null)
{
throw new PXRedirectRequiredException(graph, true, "Functional Location");
}
}
but i encountered an error like the following:
Error
can someone please help solve this seemingly stupid question?
im sorry my english is bad.. :)
Thanks!
Below is a common pattern to create data records via code/programming in Acumatica
public PXAction<FuncLocFilter> CreateFuncLoc;
[PXButton]
[PXUIField(DisplayName = "Create Functional Location")]
protected virtual void createFuncLoc()
{
FuncLocFilter row = Filter.Current;
// 1. Create an instance of the BLC (graph)
FunLocEntry graph = PXGraph.CreateInstance<FunLocEntry>();
// 2. Create an instance of the BSMTFuncLoc DAC, set key field values (besides the ones whose values are generated by the system),
// and insert the record into the cache
BSMTFuncLoc FnLc = new BSMTFuncLoc();
FnLc.FuncLocCD = row.FuncLocCD;
FnLc = graph.FunLocations.Insert(FnLc);
// 3. Set non-key field values and update the record in the cache
FnLc.StructureID = row.StructureID;
FnLc.HierLevels = row.HierLevels;
FnLc.EditMask = row.EditMask;
FnLc = graph.FunLocations.Update(FnLc);
// 4. Redirect
if (graph.FunLocations.Current != null)
{
throw new PXRedirectRequiredException(graph, true, "Functional Location");
}

Parse.com - if key exists, update

Currently, I'm sending some data to Parse.com. All works well, however, I would like to add a row if it's a new user or update the current table if it's an old user.
So what I need to do is check if the current Facebook ID (the key I'm using) shows up anywhere in the fbid column, then update it if case may be.
How can I check if the key exists in the column?
Also, I'm using C#/Unity.
static void sendToParse()
{
ParseObject currentUser = new ParseObject("Game");
currentUser["name"] = fbname;
currentUser["email"] = fbemail;
currentUser["fbid"] = FB.UserId;
Task saveTask = currentUser.SaveAsync();
Debug.LogError("Sent to Parse");
}
Okay, I figured it out.
First, I check which if there is any Facebook ID in the table that matches the current ID, then get the number of matches.
public static void getObjectID()
{
var query = ParseObject.GetQuery("IdealStunts")
.WhereEqualTo("fbid", FB.UserId);
query.FirstAsync().ContinueWith(t =>
{
ParseObject obj = t.Result;
objectID = obj.ObjectId;
Debug.LogError(objectID);
});
}
If there is any key matching the current Facebook ID, don't do anything. If there aren't, just add a new user.
public static void sendToParse()
{
if (count != 0)
{
Debug.LogError("Already exists");
}
else
{
ParseObject currentUser = new ParseObject("IdealStunts");
currentUser["name"] = fbname;
currentUser["email"] = fbemail;
currentUser["fbid"] = FB.UserId;
Task saveTask = currentUser.SaveAsync();
Debug.LogError("New User");
}
}
You will have to do a StartCoroutine for sendToParse, so getObjectID has time to look through the table.
It may be a crappy implementation, but it works.
What you need to do is create a query for the fbid. If the query returns an object, you update it. If not, you create a new.
I'm not proficient with C#, but here is an example in Objective-C:
PFQuery *query = [PFQuery queryWithClassName:#"Yourclass]; // Name of your class in Parse
query.cachePolicy = kPFCachePolicyNetworkOnly;
[query whereKey:#"fbid" equalTo:theFBid]; // Variable containing the fb id
NSArray *users = [query findObjects];
self.currentFacebookUser = [users lastObject]; // Array should contain only 1 object
if (self.currentFacebookUser) { // Might have to test for NULL, but probably not
// Update the object and save it
} else {
// Create a new object
}

Out of Memory at line XXXX

can anyone help me how to resolve the out of memory error on my asp page? im using linq to sql.. after adding data several data.. like more than 10 rows. in the grid. an out of memory error occurs.. attached herewith is my add function..
public ServiceDetail checkservicedetailid()
{
string ServiceName = ViewState["Tab"].ToString();
ServiceDetail checkservicedetailid = ServiceDetails_worker.get(a => a.ServiceName == ServiceName && a.MarginAnalysisID == checkmarginanalysisid().MarginAnalysisID).SingleOrDefault();
return checkservicedetailid;
}
public IEnumerable<ServiceDetail> get(Expression<Func<ServiceDetail, Boolean>> express)
{
return ServiceDetailsDB.ServiceDetails.Where(express);
}
protected void btnSaveEmptyOC_Click(object sender, EventArgs e)
{
try
{
if (checkservicedetailid() != null)
{
CashExpense tblCashExpenses = new CashExpense();
Guid CashExpensesID = Guid.NewGuid();
tblCashExpenses.CashExpensesID = CashExpensesID;
tblCashExpenses.ServiceDetailsID = checkservicedetailid().ServiceDetailsID;
tblCashExpenses.Description = txtDescriptionEmptyOC.Text;
tblCashExpenses.Quantity = Decimal.Parse(txtQTYEmptyOC.Text);
tblCashExpenses.UnitCost = Decimal.Parse(txtUnitCostEmptyOC.Text);
tblCashExpenses.CreatedBy = User.Identity.Name;
tblCashExpenses.DateCreated = DateTime.Now;
tblCashExpenses.CashExpensesTypeID = "OTHER";
CashExpenses_worker.insert(tblCashExpenses);
CashExpenses_worker.submit();
//Clear items after saving
txtDescriptionEmptyOC.Text = "";
txtQTYEmptyOC.Text = "";
txtUnitCostEmptyOC.Text = "";
ValidationMessage.ShowValidationMessage(MessageCenter.CashExpenseMaintenace.InsertOC2, "SaveEmptyOC", this.Page);
MyAuditProvider.Insert(this.GetType().ToString(), ViewState["MarginAnalysisID"].ToString(), MessageCenter.Mode.ADD, MessageCenter.CashExpenseMaintenace.InsertOC2, Page.Request, User);
divOtherCost.Visible = false;
grd_othercost.Visible = true;
btnaddothercost.Visible = true;
}
else
{
//Displays a Message on the Validation Summary (Service Id does not exist)
ValidationMessage.ShowValidationMessage(MessageCenter.CashExpenseMaintenace.SaveServiceDetailOC, "SaveEmptyOC", this.Page);
}
}
catch
{
//Displays a Message on the Validation Summary (Error on Saving)
ValidationMessage.ShowValidationMessage(MessageCenter.CashExpenseMaintenace.InsertOCError, "SaveEmptyOC", this.Page);
}
finally
{
//Rebinds the Grid
populategrd_othercost();
}
}
I'm guessing from your code here:
ServiceDetail checkservicedetailid = ServiceDetails_worker.get(
a => a.ServiceName == ServiceName &&
a.MarginAnalysisID == checkmarginanalysisid().MarginAnalysisID
).SingleOrDefault();
that .get() is taking a Func<SomeType, bool>, and you are doing something like:
var row = dbCtx.SomeTable.Where(predicate);
(please correct me here if I'm incorrect)
This, however, is using LINQ-to-Objects, meaning: it is loading every row from the table to the client and testing locally. That'll hurt memory, especially if a different db-context is created for each row. Additionally, the checkmarginanalysisid() call is being executed per row, when presumably it doesn't change between rows.
You should be testing this with an Expression<Func<SomeType, bool>> which would be translated to TSQL and executed at the server. You may also need to remove untranslatable methods, i.e.
var marginAnalysisId = checkmarginanalysisid().MarginAnalysisID;
ServiceDetail checkservicedetailid = ServiceDetails_worker.get(
a => a.ServiceName == ServiceName &&
a.MarginAnalysisID == marginAnalysisId
).SingleOrDefault();
where that is get(Expression<Func<SomeType, bool>>).
I tried all of the solution given to me both by my peers as well as the solution provided here, from GC.Collect, to disposing linq datacontext after use etc. however the error keeps on occurring, i then tried to remove the update panel, Ive read a site that showed how ridiculous update panel when it comes to handling data esp when a function is done repeatedly. And poof! the memory problem is gone!

Monotouch EKEvent Notes not being saved

What am I doing wrong here? currentEvent.Title prints correctly. currentEvent.Notes is always blank..
public void CalendarEvents()
{
EKEventStore store = new EKEventStore();
EKCalendar calendar = store.DefaultCalendarForNewEvents;
// Query the event
if (calendar != null)
{
// Add a new event
EKEvent newEvent = EKEvent.FromStore(store);
newEvent.Title = "Lunch at McDonalds";
newEvent.Calendar = calendar;
newEvent.StartDate = DateTime.Now.Date;
newEvent.EndDate = DateTime.Now.Date.AddDays(4);
newEvent.Availability = EKEventAvailability.Free;
newEvent.Notes = "hello";
store.SaveEvent(newEvent, EKSpan.ThisEvent, new IntPtr());
// Searches for every event in the next year
NSPredicate predicate = store.PredicateForEvents(NSDate.Now,DateTime.Now.AddDays(360),new EKCalendar[] {calendar});
store.EnumerateEvents(predicate, delegate(EKEvent currentEvent, ref bool stop)
{
// Perform your check for an event type
Console.WriteLine(currentEvent.Title);
Console.WriteLine(currentEvent.Notes);
});
}
}
The API likely has changed because the above won't compile 'as-is'. So I updated your:
store.SaveEvent(newEvent, EKSpan.ThisEvent, new IntPtr());
to
NSError error;
store.SaveEvent(newEvent, EKSpan.ThisEvent, out error);
Otherwise, using the latest MonoTouch, I get both strings displayed in the "Application Output" (app running on device).
Lunch at McDonalds
hello
Maybe that was fixed when the API was modified ?

Categories

Resources