I use the fallowing method to update a contact in Exchange over EWS:
private void UpdateContact(Microsoft.Exchange.WebServices.Data.Contact exContact, ContactInfo contact) {
var pathList = new List<string>();
try {
log.DebugFormat("Process ExchangeContact '{0}' with Contact '{1}'", (exContact.IsNew ? "<new>" : exContact.DisplayName), contact.Id);
exContact.GivenName = contact.AdditionalName;
exContact.Surname = contact.Name;
exContact.FileAsMapping = FileAsMapping.SurnameCommaGivenName;
exContact.CompanyName = "";
if (contact is PersonInfo) {
var person = (PersonInfo) contact;
if (person.PersonCompany != null && person.PersonCompany.Company != null) {
exContact.CompanyName = person.PersonCompany.Company.DisplayName;
}
exContact.ImAddresses[ImAddressKey.ImAddress1] = person.MessengerName;
exContact.ImAddresses[ImAddressKey.ImAddress2] = person.SkypeName;
}
// Specify the business, home, and car phone numbers.
var comm = contact.GetCommunication(Constants.CommunicationType.PhoneBusiness);
exContact.PhoneNumbers[PhoneNumberKey.BusinessPhone] = (comm != null ? comm.Value : null);
comm = contact.GetCommunication(Constants.CommunicationType.PhonePrivate);
exContact.PhoneNumbers[PhoneNumberKey.HomePhone] = (comm != null ? comm.Value : null);
comm = contact.GetCommunication(Constants.CommunicationType.PhoneMobile);
exContact.PhoneNumbers[PhoneNumberKey.MobilePhone] = (comm != null ? comm.Value : null);
comm = contact.GetCommunication(Constants.CommunicationType.MailBusiness);
exContact.EmailAddresses[EmailAddressKey.EmailAddress1] = (comm != null ? new EmailAddress(comm.Value) : null);
comm = contact.GetCommunication(Constants.CommunicationType.MailPrivate);
exContact.EmailAddresses[EmailAddressKey.EmailAddress2] = (comm != null ? new EmailAddress(comm.Value) : null);
// Specify two IM addresses.
// Specify the home address.
var address = contact.AddressList.FirstOrDefault(x => x.AddressType != null && x.AddressType.Id == Constants.AddressType.Private);
if (address != null) {
var paEntry = new PhysicalAddressEntry
{
Street = address.Street,
City = address.City,
State = address.Region,
PostalCode = address.PostalCode,
CountryOrRegion = address.CountryName
};
exContact.PhysicalAddresses[PhysicalAddressKey.Home] = paEntry;
if (contact.PostalAddress == address) {
exContact.PostalAddressIndex = PhysicalAddressIndex.Home;
}
} else {
exContact.PhysicalAddresses[PhysicalAddressKey.Home] = null;
}
address = contact.AddressList.FirstOrDefault(x => x.AddressType != null && x.AddressType.Id == Constants.AddressType.Business);
if (address != null) {
var paEntry = new PhysicalAddressEntry
{
Street = address.Street,
City = address.City,
State = address.Region,
PostalCode = address.PostalCode,
CountryOrRegion = address.CountryName
};
exContact.PhysicalAddresses[PhysicalAddressKey.Business] = paEntry;
if(contact.PostalAddress == address) {
exContact.PostalAddressIndex = PhysicalAddressIndex.Business;
}
} else {
exContact.PhysicalAddresses[PhysicalAddressKey.Business] = null;
}
// Save the contact.
if (exContact.IsNew) {
exContact.Save();
} else {
exContact.Update(ConflictResolutionMode.AlwaysOverwrite);
}
pathList.AddRange(this.AddFileAttachments(this.Access.IndependService.GetContact(exContact.Id.UniqueId), contact.GetDocuments()));
} catch(Exception e) {
log.Error("Error updating/inserting Contact in Exchange.", e);
} finally {
foreach (var path in pathList) {
this.Access.Context.Container.Resolve<IDocumentService>().UndoCheckOut(path);
}
}
}
When I do this for update, I get an Exception with Errorcode ErrorIncorrectUpdatePropertyCount on the line exContact.Update(ConflictResolutionMode.AlwaysOverwrite);
Can someone help me, what is the problem? - Thanks.
The solution is that I have to check, if the string-values are empty strings and in this case to set null. On this way, all is working.
Related
Can anyone help me find where in the code Acumatica writes to the CRRelation table when createing a Sales Order from an Opportunity? I've done a search for all instances of "CRRelation" but none of them seem to be doing the actual writing to the table.
It is done in the DoCreateSalesOrder(CreateSalesOrderFilter param) method which is called in the CreateSalesOrder action:
public PXAction<CROpportunity> createSalesOrder;
[PXUIField(DisplayName = Messages.CreateSalesOrder, MapEnableRights = PXCacheRights.Update, MapViewRights = PXCacheRights.Select)]
[PXButton(ImageKey = PX.Web.UI.Sprite.Main.DataEntry)]
public virtual IEnumerable CreateSalesOrder(PXAdapter adapter)
{
foreach (CROpportunity opportunity in adapter.Get())
{
Customer customer = (Customer)PXSelect<Customer, Where<Customer.bAccountID, Equal<Current<CROpportunity.bAccountID>>>>
.SelectSingleBound(this, new object[] { opportunity });
if (customer == null)
{
throw new PXException(Messages.ProspectNotCustomer);
}
var products = Products.View.SelectMultiBound(new object[] { opportunity }).RowCast<CROpportunityProducts>();
if (products.Any(_ => _.InventoryID == null) && !products.Any(_ => _.InventoryID != null))
{
throw new PXException(Messages.SalesOrderHasOnlyNonInventoryLines);
}
if (CreateOrderParams.AskExtFullyValid((graph, viewName) => { }, DialogAnswerType.Positive))
{
Save.Press();
PXLongOperation.StartOperation(this, delegate()
{
var grapph = PXGraph.CreateInstance<OpportunityMaint>();
grapph.Opportunity.Current = opportunity;
grapph.CreateOrderParams.Current = CreateOrderParams.Current;
grapph.DoCreateSalesOrder(CreateOrderParams.Current);
});
}
yield return opportunity;
}
}
if we look in that method we can find the following lines which are creating the relation:
var campaignRelation = docgraph.RelationsLink.Insert();
campaignRelation.RefNoteID = doc.NoteID;
campaignRelation.Role = CRRoleTypeList.Source;
campaignRelation.TargetType = CRTargetEntityType.CROpportunity;
campaignRelation.TargetNoteID = opportunity.NoteID;
campaignRelation.DocNoteID = opportunity.NoteID;
campaignRelation.EntityID = opportunity.BAccountID;
campaignRelation.ContactID = opportunity.ContactID;
docgraph.RelationsLink.Update(campaignRelation);
You can find the full code of that method below:
protected virtual void DoCreateSalesOrder(CreateSalesOrderFilter param)
{
bool recalcAny = param.RecalculatePrices == true ||
param.RecalculateDiscounts == true ||
param.OverrideManualDiscounts == true ||
param.OverrideManualDocGroupDiscounts == true ||
param.OverrideManualPrices == true;
var opportunity = this.Opportunity.Current;
Customer customer = (Customer)PXSelect<Customer, Where<Customer.bAccountID, Equal<Current<CROpportunity.bAccountID>>>>.Select(this);
SOOrderEntry docgraph = PXGraph.CreateInstance<SOOrderEntry>();
CurrencyInfo info = PXSelect<CurrencyInfo, Where<CurrencyInfo.curyInfoID, Equal<Current<CROpportunity.curyInfoID>>>>.Select(this);
info.CuryInfoID = null;
info = CurrencyInfo.GetEX(docgraph.currencyinfo.Insert(info.GetCM()));
SOOrder doc = new SOOrder();
doc.OrderType = CreateOrderParams.Current.OrderType ?? SOOrderTypeConstants.SalesOrder;
doc = docgraph.Document.Insert(doc);
doc = PXCache<SOOrder>.CreateCopy(docgraph.Document.Search<SOOrder.orderNbr>(doc.OrderNbr));
doc.CuryInfoID = info.CuryInfoID;
doc = PXCache<SOOrder>.CreateCopy(docgraph.Document.Update(doc));
doc.CuryID = info.CuryID;
doc.OrderDate = Accessinfo.BusinessDate;
doc.OrderDesc = opportunity.Subject;
doc.TermsID = customer.TermsID;
doc.CustomerID = opportunity.BAccountID;
doc.CustomerLocationID = opportunity.LocationID ?? customer.DefLocationID;
if (opportunity.TaxZoneID != null)
{
doc.TaxZoneID = opportunity.TaxZoneID;
if (!recalcAny)
{
SOTaxAttribute.SetTaxCalc<SOLine.taxCategoryID>(docgraph.Transactions.Cache, null, TaxCalc.ManualCalc);
SOTaxAttribute.SetTaxCalc<SOOrder.freightTaxCategoryID>(docgraph.Document.Cache, null,
TaxCalc.ManualCalc);
}
}
doc.ProjectID = opportunity.ProjectID;
doc.BranchID = opportunity.BranchID;
doc = docgraph.Document.Update(doc);
var campaignRelation = docgraph.RelationsLink.Insert();
campaignRelation.RefNoteID = doc.NoteID;
campaignRelation.Role = CRRoleTypeList.Source;
campaignRelation.TargetType = CRTargetEntityType.CROpportunity;
campaignRelation.TargetNoteID = opportunity.NoteID;
campaignRelation.DocNoteID = opportunity.NoteID;
campaignRelation.EntityID = opportunity.BAccountID;
campaignRelation.ContactID = opportunity.ContactID;
docgraph.RelationsLink.Update(campaignRelation);
bool failed = false;
foreach (CROpportunityProducts product in SelectProducts(opportunity.QuoteNoteID))
{
if (product.SiteID == null)
{
InventoryItem item = (InventoryItem)PXSelectorAttribute.Select<CROpportunityProducts.inventoryID>(Products.Cache, product);
if (item != null && item.NonStockShip == true)
{
Products.Cache.RaiseExceptionHandling<CROpportunityProducts.siteID>(product, null,
new PXSetPropertyException(ErrorMessages.FieldIsEmpty, typeof(CROpportunityProducts.siteID).Name));
failed = true;
}
}
SOLine tran = new SOLine();
tran = docgraph.Transactions.Insert(tran);
if (tran != null)
{
tran.InventoryID = product.InventoryID;
tran.SubItemID = product.SubItemID;
tran.TranDesc = product.Descr;
tran.OrderQty = product.Quantity;
tran.UOM = product.UOM;
tran.CuryUnitPrice = product.CuryUnitPrice;
tran.TaxCategoryID = product.TaxCategoryID;
tran.SiteID = product.SiteID;
tran.IsFree = product.IsFree;
tran.ProjectID = product.ProjectID;
tran.TaskID = product.TaskID;
tran.CostCodeID = product.CostCodeID;
tran.ManualPrice = true;
tran.ManualDisc = true;
tran.CuryDiscAmt = product.CuryDiscAmt;
tran.DiscAmt = product.DiscAmt;
tran.DiscPct = product.DiscPct;
tran.POCreate = product.POCreate;
tran.VendorID = product.VendorID;
if (param.RecalculatePrices != true)
{
tran.ManualPrice = true;
}
else
{
if (param.OverrideManualPrices != true)
tran.ManualPrice = product.ManualPrice;
else
tran.ManualPrice = false;
}
if (param.RecalculateDiscounts != true)
{
tran.ManualDisc = true;
}
else
{
if (param.OverrideManualDiscounts != true)
tran.ManualDisc = product.ManualDisc;
else
tran.ManualDisc = false;
}
tran.CuryDiscAmt = product.CuryDiscAmt;
tran.DiscAmt = product.DiscAmt;
tran.DiscPct = product.DiscPct;
}
tran = docgraph.Transactions.Update(tran);
PXNoteAttribute.CopyNoteAndFiles(Products.Cache, product, docgraph.Transactions.Cache, tran,
Setup.Current);
}
PXNoteAttribute.CopyNoteAndFiles(Opportunity.Cache, opportunity, docgraph.Document.Cache, doc, Setup.Current);
if (failed)
throw new PXException(Messages.SiteNotDefined);
//Skip all customer dicounts
if (param.RecalculateDiscounts != true && param.OverrideManualDiscounts != true)
{
var discounts = new Dictionary<string, SOOrderDiscountDetail>();
foreach (SOOrderDiscountDetail discountDetail in docgraph.DiscountDetails.Select())
{
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.skipDiscount>(discountDetail, true);
string key = discountDetail.Type + ':' + discountDetail.DiscountID + ':' + discountDetail.DiscountSequenceID;
discounts.Add(key, discountDetail);
}
Discount ext = this.GetExtension<Discount>();
foreach (CROpportunityDiscountDetail discountDetail in ext.DiscountDetails.Select())
{
SOOrderDiscountDetail detail;
string key = discountDetail.Type + ':' + discountDetail.DiscountID + ':' + discountDetail.DiscountSequenceID;
if (discounts.TryGetValue(key, out detail))
{
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.skipDiscount>(detail, false);
if (discountDetail.IsManual == true && discountDetail.Type == DiscountType.Document)
{
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.extDiscCode>(detail, discountDetail.ExtDiscCode);
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.description>(detail, discountDetail.Description);
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.isManual>(detail, discountDetail.IsManual);
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.curyDiscountAmt>(detail, discountDetail.CuryDiscountAmt);
}
}
else
{
detail = (SOOrderDiscountDetail)docgraph.DiscountDetails.Cache.CreateInstance();
detail.Type = discountDetail.Type;
detail.DiscountID = discountDetail.DiscountID;
detail.DiscountSequenceID = discountDetail.DiscountSequenceID;
detail.ExtDiscCode = discountDetail.ExtDiscCode;
detail.Description = discountDetail.Description;
detail = (SOOrderDiscountDetail)docgraph.DiscountDetails.Cache.Insert(detail);
if (discountDetail.IsManual == true && (discountDetail.Type == DiscountType.Document || discountDetail.Type == DiscountType.ExternalDocument))
{
detail.CuryDiscountAmt = discountDetail.CuryDiscountAmt;
detail.IsManual = discountDetail.IsManual;
docgraph.DiscountDetails.Cache.Update(detail);
}
}
}
SOOrder old_row = PXCache<SOOrder>.CreateCopy(docgraph.Document.Current);
docgraph.Document.Cache.SetValueExt<SOOrder.curyDiscTot>(docgraph.Document.Current, DiscountEngineProvider.GetEngineFor<SOLine, SOOrderDiscountDetail>().GetTotalGroupAndDocumentDiscount(docgraph.DiscountDetails));
docgraph.Document.Cache.RaiseRowUpdated(docgraph.Document.Current, old_row);
}
doc = docgraph.Document.Update(doc);
if (opportunity.TaxZoneID != null && !recalcAny)
{
foreach (CRTaxTran tax in PXSelect<CRTaxTran, Where<CRTaxTran.quoteID, Equal<Current<CROpportunity.quoteNoteID>>>>.Select(this))
{
SOTaxTran newtax = new SOTaxTran();
newtax.LineNbr = int.MaxValue;
newtax.TaxID = tax.TaxID;
newtax = docgraph.Taxes.Insert(newtax);
if (newtax != null)
{
newtax = PXCache<SOTaxTran>.CreateCopy(newtax);
newtax.TaxRate = tax.TaxRate;
newtax.CuryTaxableAmt = tax.CuryTaxableAmt;
newtax.CuryTaxAmt = tax.CuryTaxAmt;
newtax.CuryUnshippedTaxableAmt = tax.CuryTaxableAmt;
newtax.CuryUnshippedTaxAmt = tax.CuryTaxAmt;
newtax.CuryUnbilledTaxableAmt = tax.CuryTaxableAmt;
newtax.CuryUnbilledTaxAmt = tax.CuryTaxAmt;
newtax = docgraph.Taxes.Update(newtax);
}
}
}
if (opportunity.AllowOverrideContactAddress == true)
{
CRContact _CRContact = Opportunity_Contact.SelectSingle();
CRAddress _CRAddress = Opportunity_Address.SelectSingle();
// Insert
if (_CRContact != null)
{
SOBillingContact _billingContact = docgraph.Billing_Contact.Select();
if (_billingContact != null)
{
_billingContact.FullName = _CRContact.FullName;
_billingContact.Salutation = _CRContact.Salutation;
_billingContact.Phone1 = _CRContact.Phone1;
_billingContact.Email = _CRContact.Email;
_billingContact = docgraph.Billing_Contact.Update(_billingContact);
_billingContact.IsDefaultContact = false;
_billingContact = docgraph.Billing_Contact.Update(_billingContact);
}
}
if (_CRAddress != null)
{
SOBillingAddress _billingAddress = docgraph.Billing_Address.Select();
if (_billingAddress != null)
{
_billingAddress.AddressLine1 = _CRAddress.AddressLine1;
_billingAddress.AddressLine2 = _CRAddress.AddressLine2;
_billingAddress.City = _CRAddress.City;
_billingAddress.CountryID = _CRAddress.CountryID;
_billingAddress.State = _CRAddress.State;
_billingAddress.PostalCode = _CRAddress.PostalCode;
_billingAddress = docgraph.Billing_Address.Update(_billingAddress);
_billingAddress.IsDefaultAddress = false;
_billingAddress = docgraph.Billing_Address.Update(_billingAddress);
}
}
}
if (recalcAny)
{
docgraph.recalcdiscountsfilter.Current.OverrideManualPrices = param.OverrideManualPrices == true;
docgraph.recalcdiscountsfilter.Current.RecalcDiscounts = param.RecalculateDiscounts == true;
docgraph.recalcdiscountsfilter.Current.RecalcUnitPrices = param.RecalculatePrices == true;
docgraph.recalcdiscountsfilter.Current.OverrideManualDiscounts = param.OverrideManualDiscounts == true;
docgraph.recalcdiscountsfilter.Current.OverrideManualDocGroupDiscounts = param.OverrideManualDocGroupDiscounts == true;
docgraph.Actions[nameof(Discount.RecalculateDiscountsAction)].Press();
}
if (!this.IsContractBasedAPI)
throw new PXRedirectRequiredException(docgraph, "");
docgraph.Save.Press();
}
NOTE: you can find most part of the sources by the following path in the Acumatica's server folder App_Data\CodeRepository\PX.Objects,App_Data\CodeRepository\PX.Data,App_Data\CodeRepository\PX.Objects.FS
I need to be able to send an email to the original requester when a PO is created from a Requisition in Acumatica 6.1.
Per Acumatica, the Notification screen cannot handle this functionality, so I have this code to extend the POOrder Entry graph, which sends an email to the Customer's contact email from the Requisition when a PO is created (along with the RQRequisitionEntryExt trigger):
public class POOrderEntryExt : PXGraphExtension<POOrderEntry>
{
private bool sendEmailNotification = false;
public bool SendEmailNotification
{
get
{
return sendEmailNotification;
}
set
{
sendEmailNotification = value;
}
}
[PXOverride]
public void Persist(Action del)
{
using (var ts = new PXTransactionScope())
{
if (del != null)
{
del();
}
if (SendEmailNotification)
{
bool sent = false;
string sError = "Failed to send E-mail.";
try
{
Notification rowNotification = PXSelect<Notification,
Where<Notification.name, Equal<Required<Notification.name>>>>
.Select(Base, "PurchaseOrderNotification");
if (rowNotification == null)
throw new PXException("Notification Template was not found.");
var order = Base.Document.Current;
var requisition = (RQRequisition)PXSelect<RQRequisition,
Where<RQRequisition.reqNbr, Equal<Current<POOrder.rQReqNbr>>>>
.SelectSingleBound(Base, new object[] { order });
if (requisition.CustomerID != null)
{
var customer = (BAccountR)PXSelectorAttribute.Select<RQRequisition.customerID>(
Base.Caches[typeof(RQRequisition)], requisition);
if (customer != null)
{
var defCustContact = (Contact)PXSelectorAttribute.Select<BAccountR.defContactID>(
Base.Caches[typeof(BAccountR)], customer);
if (String.IsNullOrEmpty(defCustContact.EMail))
throw new PXException("E-mail is not specified for Customer Contact.");
var sender = TemplateNotificationGenerator.Create(order,
rowNotification.NotificationID.Value);
sender.RefNoteID = order.NoteID;
sender.MailAccountId = rowNotification.NFrom.HasValue ?
rowNotification.NFrom.Value :
PX.Data.EP.MailAccountManager.DefaultMailAccountID;
sender.To = defCustContact.EMail;
sent |= sender.Send().Any();
}
}
}
catch (Exception Err)
{
sent = false;
sError = Err.Message;
}
if (!sent)
throw new PXException(sError);
}
ts.Complete();
}
}
}
And this to modify RQRequisitionEntry:
public class RQRequisitionEntryExt : PXGraphExtension<RQRequisitionEntry>
{
public PXAction<RQRequisition> createPOOrder;
[PXButton(ImageKey = PX.Web.UI.Sprite.Main.DataEntry)]
[PXUIField(DisplayName = Messages.CreateOrders)]
public IEnumerable CreatePOOrder(PXAdapter adapter)
{
PXGraph.InstanceCreated.AddHandler<POOrderEntry>((graph) =>
{
graph.GetExtension<POOrderEntryExt>().SendEmailNotification = true;
});
return Base.createPOOrder.Press(adapter);
}
}
In order to send an email to the Requester's (Employee) contact email from the Request, I modified the POOrderEntryExt to pull the information from the Request object and the Employee's Contact email (I left the RQRequisitionEntryExt the same and in place):
public class POOrderEntryExt : PXGraphExtension<POOrderEntry>
{
private bool sendEmailNotification = false;
public bool SendEmailNotification
{
get
{
return sendEmailNotification;
}
set
{
sendEmailNotification = value;
}
}
[PXOverride]
public void Persist(Action del)
{
using (var ts = new PXTransactionScope())
{
if (del != null)
{
del();
}
if (SendEmailNotification)
{
bool sent = false;
string sError = "Failed to send E-mail.";
try
{
Notification rowNotification = PXSelect<Notification,
Where<Notification.name, Equal<Required<Notification.name>>>>
.Select(Base, "PurchaseOrderNotification");
if (rowNotification == null)
throw new PXException("Notification Template was not found.");
var order = Base.Document.Current;
var requisition = (RQRequisition)PXSelect<RQRequisition,
Where<RQRequisition.reqNbr, Equal<Current<POOrder.rQReqNbr>>>>
.SelectSingleBound(Base, new object[] { order });
var request = (RQRequest)PXSelectJoin<RQRequest,
InnerJoin<RQRequisitionContent,
On<RQRequisitionContent.orderNbr, Equal<RQRequest.orderNbr>>>,
Where<RQRequisitionContent.reqNbr, Equal<POOrder.rQReqNbr>>>
.SelectSingleBound(Base, new object[] { order });
if (request.EmployeeID != null)
{
var employee = (BAccountR)PXSelectorAttribute.Select<RQRequest.employeeID>(
Base.Caches[typeof(RQRequest)], request);
if (employee != null)
{
var defEmpContact = (Contact)PXSelectorAttribute.Select<BAccountR.defContactID>(
Base.Caches[typeof(BAccountR)], employee);
if (String.IsNullOrEmpty(defEmpContact.EMail))
throw new PXException("E-mail is not specified for Employee Contact.");
var sender = TemplateNotificationGenerator.Create(order,
rowNotification.NotificationID.Value);
sender.RefNoteID = order.NoteID;
sender.MailAccountId = rowNotification.NFrom.HasValue ?
rowNotification.NFrom.Value :
PX.Data.EP.MailAccountManager.DefaultMailAccountID;
sender.To = defEmpContact.EMail;
sent |= sender.Send().Any();
}
else
throw new PXException("Customer not found.");
}
else
throw new PXException("Request not found.");
}
catch (Exception Err)
{
sent = false;
sError = Err.Message;
}
if (!sent)
throw new PXException(sError);
}
ts.Complete();
}
}
}
I can get the original code to send an email in my development environment, but my modified code only returns the outer "Failed to send E-mail" error.
Can anyone help point me in the right direction to get my modifications to work?
Because in Acumatica there is one-to-many relationship between RQRequisition and RQRequest, I believe the better approach is to loop through all requests linked to the current requisition and compose a list of requester's emails. After that we can go ahead and send emails to all requesters as part of the Create Orders operation:
public class POOrderEntryExt : PXGraphExtension<POOrderEntry>
{
private bool sendEmailNotification = false;
public bool SendEmailNotification
{
get
{
return sendEmailNotification;
}
set
{
sendEmailNotification = value;
}
}
[PXOverride]
public void Persist(Action del)
{
using (var ts = new PXTransactionScope())
{
if (del != null)
{
del();
}
if (SendEmailNotification)
{
bool sent = false;
string sError = "Failed to send E-mail.";
try
{
Notification rowNotification = PXSelect<Notification,
Where<Notification.name, Equal<Required<Notification.name>>>>
.Select(Base, "PONotification");
if (rowNotification == null)
throw new PXException("Notification Template was not found.");
var order = Base.Document.Current;
var emails = new List<string>();
var requests = PXSelectJoinGroupBy<RQRequest,
InnerJoin<RQRequisitionContent,
On<RQRequest.orderNbr,
Equal<RQRequisitionContent.orderNbr>>>,
Where<RQRequisitionContent.reqNbr,
Equal<Required<RQRequisition.reqNbr>>>,
Aggregate<GroupBy<RQRequest.orderNbr>>>
.Select(Base, order.RQReqNbr);
foreach (RQRequest request in requests)
{
if (request.EmployeeID != null)
{
var requestCache = Base.Caches[typeof(RQRequest)];
requestCache.Current = request;
var emplOrCust = (BAccountR)PXSelectorAttribute
.Select<RQRequest.employeeID>(requestCache, request);
if (emplOrCust != null)
{
var defEmpContact = (Contact)PXSelectorAttribute
.Select<BAccountR.defContactID>(
Base.Caches[typeof(BAccountR)], emplOrCust);
if (!String.IsNullOrEmpty(defEmpContact.EMail) &&
!emails.Contains(defEmpContact.EMail))
{
emails.Add(defEmpContact.EMail);
}
}
}
}
foreach (string email in emails)
{
var sender = TemplateNotificationGenerator.Create(order,
rowNotification.NotificationID.Value);
sender.RefNoteID = order.NoteID;
sender.MailAccountId = rowNotification.NFrom.HasValue ?
rowNotification.NFrom.Value :
PX.Data.EP.MailAccountManager.DefaultMailAccountID;
sender.To = email;
sent |= sender.Send().Any();
}
}
catch (Exception Err)
{
sent = false;
sError = Err.Message;
}
if (!sent)
throw new PXException(sError);
}
ts.Complete();
}
}
}
i have done code to fill up grid view with data set.
just look at :
public void FillGrid(string StartAlpha, string CommandName, string ColumnName, string SearchText)
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
int userid = db.Users.Where(u => u.EmailAddress.Equals((String)Session["EmailID"])).Select(u => u.Id).SingleOrDefault();
var sms = Enumerable.Repeat(new
{
Id = default(int),
Title = string.Empty,
Body = string.Empty,
FromUser = string.Empty,
ToUser = string.Empty,
SentDateTime = default(DateTime?),
IsMedia = default(bool),
CreatedDate = default(DateTime),
}, 1).ToList();
DataSet myDataSet = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Id", typeof(string)));
dt.Columns.Add(new DataColumn("Title", typeof(string)));
dt.Columns.Add(new DataColumn("Body", typeof(string)));
dt.Columns.Add(new DataColumn("FromUser", typeof(string)));
dt.Columns.Add(new DataColumn("ToUser", typeof(string)));
dt.Columns.Add(new DataColumn("SentDateTime", typeof(DateTime)));
dt.Columns.Add(new DataColumn("IsMedia", typeof(bool)));
dt.Columns.Add(new DataColumn("CreatedDate", typeof(DateTime)));
if (StartAlpha.Equals("All"))
{
switch (CommandName)
{
case "Inbox":
break;
case "Outbox":
lbl_countall.Text = db.SMS.Where(s => s.SentDateTime != null).Count().ToString();
lbut_showinbox.Font.Bold = false;
lbut_showoutbox.Font.Bold = true;
lbut_showdraffs.Font.Bold = false;
sms = db.SMS.OrderByDescending(s => s.SentDateTime).Where(s => (s.SentDateTime != null || s.IsDraft.Equals(false)) & s.user_id.Equals(userid)).Select(s => new
{
Id = s.Id,
Title = s.Title,
Body = s.Body,
FromUser = db.SMSAccounts.Where(a=>a.user_id.Equals(userid)).Select(a=>a.FromMobileNo).FirstOrDefault(),
ToUser = s.To_MobileNo,
SentDateTime = s.SentDateTime,
IsMedia = false,
CreatedDate = s.CreatedDate
}).FilterForColumn(ColumnName, SearchText).ToList();
foreach (var item in sms)
{
if (item != null)
{
DataRow dr = dt.NewRow();
dr["Id"] = item.Id.ToString();
dr["Title"] = item.Title.ToString();
dr["Body"] = Regex.Replace(item.Body.ToString().Trim(), #"<(.|\n)*?>", string.Empty);
dr["FromUser"] = item.FromUser.ToString();
if (item.ToUser != null)
{
dr["ToUser"] = item.ToUser.ToString();
}
else
{
dr["ToUser"] = "NoN";
}
if (item.SentDateTime != null)
{
dr["SentDatetTime"] = item.SentDateTime;
}
else
{
dr["SentDatetTime"] = DBNull.Value;
}
dr["IsMedia"] = item.IsMedia;
dr["CreatedDate"] = item.CreatedDate;
dt.Rows.Add(dr);
}
}
break;
case "Drafts":
lbl_countall.Text = db.SMS.Where(s => s.SentDateTime != null || s.IsDraft.Equals(true)).Count().ToString();
lbut_showinbox.Font.Bold = false;
lbut_showoutbox.Font.Bold = false;
lbut_showdraffs.Font.Bold = true;
sms = db.SMS.OrderByDescending(s => s.SentDateTime).Where(s => (s.SentDateTime == null || s.IsDraft.Equals(true)) & s.user_id.Equals(userid)).Select(s => new
{
Id = s.Id,
Title = s.Title,
Body = s.Body,
FromUser = db.SMSAccounts.Where(a => a.user_id.Equals(userid)).Select(a => a.FromMobileNo).FirstOrDefault(),
ToUser = s.To_MobileNo,
SentDateTime = s.SentDateTime,
IsMedia = false,
CreatedDate = s.CreatedDate
}).FilterForColumn(ColumnName, SearchText).ToList();
foreach (var item in sms)
{
if (item != null)
{
DataRow dr = dt.NewRow();
dr["Id"] = item.Id.ToString();
dr["Title"] = item.Title.ToString();
dr["Body"] = Regex.Replace(item.Body.ToString().Trim(), #"<(.|\n)*?>", string.Empty);
dr["FromUser"] = item.FromUser.ToString();
if (item.ToUser != null)
{
dr["ToUser"] = item.ToUser.ToString();
}
else
{
dr["ToUser"] = "NoN";
}
if (item.SentDateTime != null)
{
dr["SentDatetTime"] = item.SentDateTime;
}
else
{
dr["SentDatetTime"] = DBNull.Value;
}
dr["IsMedia"] = item.IsMedia;
dr["CreatedDate"] = item.CreatedDate;
dt.Rows.Add(dr);
}
}
break;
}
}
else
{
switch (CommandName)
{
//case "Inbox":
.............
// break;
case "Outbox":
lbl_countall.Text = db.SMS.Where(s => s.SentDateTime != null).Count().ToString();
lbut_showinbox.Font.Bold = false;
lbut_showoutbox.Font.Bold = true;
lbut_showdraffs.Font.Bold = false;
sms = db.SMS.OrderByDescending(s => s.SentDateTime).Where(s => (s.SentDateTime != null || s.IsDraft.Equals(false)) & s.user_id.Equals(userid)).Select(s => new
{
Id = s.Id,
Title = s.Title,
Body = s.Body,
FromUser = db.SMSAccounts.Where(a => a.user_id.Equals(userid)).Select(a => a.FromMobileNo).FirstOrDefault(),
ToUser = s.To_MobileNo,
SentDateTime = s.SentDateTime,
IsMedia = false,
CreatedDate = s.CreatedDate
}).FilterForColumn(ColumnName, SearchText).ToList().Where(x => x.Title.StartsWith(StartAlpha, StringComparison.CurrentCultureIgnoreCase)).ToList();
foreach (var item in sms)
{
if (item != null)
{
DataRow dr = dt.NewRow();
dr["Id"] = item.Id.ToString();
dr["Title"] = item.Title.ToString();
dr["Body"] = Regex.Replace(item.Body.ToString().Trim(), #"<(.|\n)*?>", string.Empty);
dr["FromUser"] = item.FromUser.ToString();
if (item.ToUser != null)
{
dr["ToUser"] = item.ToUser.ToString();
}
else
{
dr["ToUser"] = "NoN";
}
if (item.SentDateTime != null)
{
dr["SentDatetTime"] = item.SentDateTime;
}
else
{
dr["SentDatetTime"] = DBNull.Value;
}
dr["IsMedia"] = item.IsMedia;
dr["CreatedDate"] = item.CreatedDate;
dt.Rows.Add(dr);
}
}
break;
case "Drafts":
lbl_countall.Text = db.SMS.Where(s => s.SentDateTime != null).Count().ToString();
lbut_showinbox.Font.Bold = false;
lbut_showoutbox.Font.Bold = false;
lbut_showdraffs.Font.Bold = true;
sms = db.SMS.OrderByDescending(s => s.SentDateTime).Where(s => (s.SentDateTime == null || s.IsDraft.Equals(true)) & s.user_id.Equals(userid)).Select(s => new
{
Id = s.Id,
Title = s.Title,
Body = s.Body,
FromUser = db.SMSAccounts.Where(a => a.user_id.Equals(userid)).Select(a => a.FromMobileNo).FirstOrDefault(),
ToUser = s.To_MobileNo,
SentDateTime = s.SentDateTime,
IsMedia = false,
CreatedDate = s.CreatedDate
}).FilterForColumn(ColumnName, SearchText).ToList().Where(x => x.Title.StartsWith(StartAlpha, StringComparison.CurrentCultureIgnoreCase)).ToList();
foreach (var item in sms)
{
if (item != null)
{
DataRow dr = dt.NewRow();
dr["Id"] = item.Id.ToString();
dr["Title"] = item.Title.ToString();
dr["Body"] = Regex.Replace(item.Body.ToString().Trim(), #"<(.|\n)*?>", string.Empty);
dr["FromUser"] = item.FromUser.ToString();
if (item.ToUser != null)
{
dr["ToUser"] = item.ToUser.ToString();
}
else
{
dr["ToUser"] = "NoN";
}
if (item.SentDateTime != null)
{
dr["SentDatetTime"] = item.SentDateTime;
}
else
{
dr["SentDatetTime"] = DBNull.Value;
}
dr["IsMedia"] = item.IsMedia;
dr["CreatedDate"] = item.CreatedDate;
dt.Rows.Add(dr);
}
}
break;
}
}
myDataSet.Tables.Add(dt);
if (myDataSet.Tables[0].Rows.Count > 0)
{
DataView myDataView = new DataView();
myDataView = myDataSet.Tables[0].DefaultView;
if (this.ViewState["SortExp"] != null)
{
myDataView.Sort = this.ViewState["SortExp"].ToString()
+ " " + this.ViewState["SortOrder"].ToString();
}
GV_ViewSMS.DataSource = myDataView;
}
if (GV_ViewSMS.Rows.Count != 0)
{
SetPageNumbers();
}
GV_ViewSMS.DataBind();
}
}
and this error occurs :
Server Error in '/' Application.
Column 'SentDatetTime' does not belong to table .
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Column 'SentDatetTime' does not belong to table .
Source Error:
Line 439: else
Line 440: {
Line 441: dr["SentDatetTime"] = DBNull.Value;
Line 442: }
Line 443: dr["IsMedia"] = item.IsMedia;
Source File: e:\EASYMAIL_off\EASYMAIL\BulkSMS.aspx.cs Line: 441
Stack Trace:
[ArgumentException: Column 'SentDatetTime' does not belong to table .]
System.Data.DataRow.GetDataColumn(String columnName) +5731291
System.Data.DataRow.set_Item(String columnName, Object value) +13
BulkSMS.FillGrid(String StartAlpha, String CommandName, String ColumnName, String SearchText) in e:\EASYMAIL_off\EASYMAIL\BulkSMS.aspx.cs:441
BulkSMS.Page_Load(Object sender, EventArgs e) in e:\EASYMAIL_off\EASYMAIL\BulkSMS.aspx.cs:40
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
System.Web.UI.Control.OnLoad(EventArgs e) +95
System.Web.UI.Control.LoadRecursive() +59
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +678
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1055.0
What wrong with my Code?????
please help me to throughout this problem.....
Looks like you have a spelling error SentDatetTime -> SentDateTime:
if (item.SentDateTime != null)
{
dr["SentDateTime"] = item.SentDateTime;
}
else
{
dr["SentDateTime"] = DBNull.Value;
}
I use sqldependency AND signalR AND thread but it goes on infinite loop
combine BackgroundWorker in global.aspx and sqldependency and signalR
I dont know about problem please help me.
void Application_Start(object sender, EventArgs e)
{
//var session = HttpContext.Current.Session;
//if (session != null && HttpContext.Current != null)
//{
try
{
CSASPNETBackgroundWorker.BackgroundWorker worker = new CSASPNETBackgroundWorker.BackgroundWorker();
worker.DoWork += new CSASPNETBackgroundWorker.BackgroundWorker.DoWorkEventHandler(worker_DoWork);
worker.RunWorker(null);
// This Background Worker is Applicatoin Level,
// so it will keep working and it is shared by all users.
Application["worker"] = worker;
// Code that runs on application startup
}
catch { }
// }
System.Data.SqlClient.SqlDependency.Start(connectionstring);
}
string user_id;
void worker_DoWork(ref int progress,
ref object _result, params object[] arguments)
{
// Do the operation every 1 second wihout the end.
while (true)
{
Random rand = new Random();
int randnum = rand.Next(5000, 20000);
Thread.Sleep(randnum);
// This statement will run every 1 second.
// string user_id = "";
// if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
// user_id = "22";// HttpContext.Current.Session["userId"].ToString();
user_id = ConfigurationManager.AppSettings["session_user_id"].ToString();
updatealarm(user_id);
}
// Other logic which you want it to keep running.
// You can do some scheduled tasks here by checking DateTime.Now.
}
}
AND
public class AlarmInfoRepository {
string connectionstr = ConfigurationManager.ConnectionStrings["officeConnectionString"].ConnectionString;
public IEnumerable GetData(string user_id)
{
using (SqlConnection connection = new SqlConnection(connectionstr))
{
//PersianCalendar jc = new PersianCalendar();
//string todayStr = jc.GetYear(DateTime.Now).ToString("0000") + "/" + jc.GetMonth(DateTime.Now).ToString("00") + "/" +
// jc.GetDayOfMonth(DateTime.Now).ToString("00");
//string timeStr = String.Format("{0:00}:{1:00}:{2:00}", jc.GetHour(DateTime.Now.AddSeconds(10)), jc.GetMinute(DateTime.Now.AddSeconds(10)), jc.GetSecond(DateTime.Now.AddSeconds(10)));
if (connection.State == ConnectionState.Closed)
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT dbo.[web_alarmkartable].[id],dbo.[web_alarmkartable].peygir_id,dbo.[web_alarmkartable].user_id,
dbo.[web_alarmkartable].[content],dbo.[web_alarmkartable].[latestcreate_date],dbo.[web_alarmkartable].[latestcreate_time],
dbo.[web_alarmkartable].[firstcreate_date],dbo.[web_alarmkartable].[firstcreate_time],dbo.[web_alarmkartable].[duration],
dbo.[web_alarmkartable].[periodtype_id],dbo.[web_alarmkartable].[period],ISNULL(dbo.[web_alarmkartable].[color],'') AS color,dbo.[web_alarmkartable].id_tel FROM dbo.[web_alarmkartable] where dbo.[web_alarmkartable].content !='' AND dbo.[web_alarmkartable].content IS NOT NULL
AND (dbo.[web_alarmkartable].seen IS NULL OR dbo.[web_alarmkartable].seen =0) AND (dbo.[web_alarmkartable].expier IS NULL OR dbo.[web_alarmkartable].expier =0 )
AND (dbo.[web_alarmkartable].del=0 OR dbo.[web_alarmkartable].del IS NULL) AND dbo.[web_alarmkartable].user_id=" + user_id, connection))
{
// Make sure the command object does not already have
// a notification object associated with it.
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new AlarmInfo()
{
id = x.GetInt32(0),
peygir_id = x.GetInt32(1),
user_id = x.GetInt32(2),
content = x.GetString(3),
latestcreate_date = x.GetString(4),
latestcreate_time = x.GetString(5),
firstcreate_date = x.GetString(6),
firstcreate_time = x.GetString(7),
duration = x.GetDecimal(8),
periodtype_id = x.GetInt32(9),
period = x.GetDecimal(10),
color = x.GetString(11),
id_tel = x.GetInt32(12)
}).ToList();
}
//if (connection.State == ConnectionState.Open)
// connection.Close();
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if ((e.Info.ToString() == "Insert" || e.Info.ToString() == "Update") && e.Type == SqlNotificationType.Change)
AlermHub.Show(e.Info.ToString());
}
}
AND
We have the opportunity to init jaxb context from external oxm file
Map<String, Object> props = new HashMap<String, Object>(1);
props.put(JAXBContextProperties.OXM_METADATA_SOURCE, "oxm.xml");
JAXBContext jc = JAXBContextFactory.createContext(new Class[0], props, <ClassLoader>);
Can we safe current jaxb context xml bindings to xml? From context inited from jaxb annotated classes (I have jaxb.properties)
JAXBContext jc = JAXBContext.newInstance(new Class[]{...});
Like I save generated schema to file
jc.generateSchema(new SchemaOutputResolver(){...});
I need to write oxm file of my schema with only difference in date/time representation.
I create function to create oxm from package. It is not complete, but do everything that I needed, and good as starting point...
public static void createOXM(Package pack, String filename)
throws Exception
{
/*
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="eclipselink_oxm_2_4.xsd"
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm" package-name="<name>"
xml-mapping-metadata-complete="true" xml-accessor-type="NONE" xml-accessor-order="UNDEFINED">
*/
org.eclipse.persistence.jaxb.xmlmodel.XmlBindings bindings =
new org.eclipse.persistence.jaxb.xmlmodel.XmlBindings();
bindings.setPackageName(pack.getName());
bindings.setXmlMappingMetadataComplete(true);
bindings.setXmlAccessorType(org.eclipse.persistence.jaxb.xmlmodel.XmlAccessType.NONE);
bindings.setXmlAccessorOrder(org.eclipse.persistence.jaxb.xmlmodel.XmlAccessOrder.UNDEFINED);
List<Class<?>> classes = getClassesForPackage(pack);
for (Class<?> cls: classes)
{
int clsMod = cls.getModifiers();
String clsName = cls.getName().replaceAll("[^\\.]+\\.", "");
if (cls.isAnonymousClass() || !Modifier.isPublic(clsMod)) // Class$1 etc...
continue;
if (cls.getAnnotation(XmlTransient.class) != null)
continue;
org.eclipse.persistence.jaxb.xmlmodel.XmlBindings.JavaTypes javaTypes = bindings.getJavaTypes();
if (javaTypes == null)
{
javaTypes = new org.eclipse.persistence.jaxb.xmlmodel.XmlBindings.JavaTypes();
bindings.setJavaTypes(javaTypes);
}
org.eclipse.persistence.jaxb.xmlmodel.JavaType javaType = new org.eclipse.persistence.jaxb.xmlmodel.JavaType();
javaTypes.getJavaType().add(javaType);
javaType.setName(clsName);
XmlRootElement xmlRoot = cls.getAnnotation(XmlRootElement.class);
if (xmlRoot != null)
{
org.eclipse.persistence.jaxb.xmlmodel.XmlRootElement root =
new org.eclipse.persistence.jaxb.xmlmodel.XmlRootElement();
javaType.setXmlRootElement(root);
if (!"##default".equals(xmlRoot.name()))
root.setName(xmlRoot.name());
if (!"##default".equals(xmlRoot.namespace()))
root.setNamespace(xmlRoot.namespace());
}
XmlType xmlType = cls.getAnnotation(XmlType.class);
if (xmlType != null)
{
org.eclipse.persistence.jaxb.xmlmodel.XmlType type = new org.eclipse.persistence.jaxb.xmlmodel.XmlType();
javaType.setXmlType(type);
if (!"##default".equals(xmlType.name()))
type.setName(xmlType.name());
if (!"##default".equals(xmlType.namespace()))
type.setNamespace(xmlType.namespace());
String[] props = xmlType.propOrder();
if (props != null && props.length > 0)
{
for (String prop: props)
if (!prop.trim().isEmpty())
type.getPropOrder().add(prop.trim());
}
}
XmlAccessorType xmlAccType = cls.getAnnotation(XmlAccessorType.class);
if (xmlAccType != null)
{
String accType = xmlAccType.value().name();
javaType.setXmlAccessorType(org.eclipse.persistence.jaxb.xmlmodel.XmlAccessType.valueOf(accType));
}
if (cls.isEnum())
{
org.eclipse.persistence.jaxb.xmlmodel.XmlBindings.XmlEnums enums = bindings.getXmlEnums();
if (enums == null)
{
enums = new org.eclipse.persistence.jaxb.xmlmodel.XmlBindings.XmlEnums();
bindings.setXmlEnums(enums);
}
org.eclipse.persistence.jaxb.xmlmodel.XmlEnum en = new org.eclipse.persistence.jaxb.xmlmodel.XmlEnum();
en.setJavaEnum(clsName);
enums.getXmlEnum().add(en);
XmlEnum xmlEnum = cls.getAnnotation(XmlEnum.class);
if (xmlEnum != null)
{
Class<?> xmlClass = xmlEnum.value();
if (xmlClass != String.class)
en.setValue(xmlClass.getName());
}
for (Field field: cls.getDeclaredFields())
if (field.isEnumConstant())
{
org.eclipse.persistence.jaxb.xmlmodel.XmlEnumValue value =
new org.eclipse.persistence.jaxb.xmlmodel.XmlEnumValue();
en.getXmlEnumValue().add(value);
value.setJavaEnumValue(field.getName());
value.setValue(field.getName());
XmlEnumValue enumValue = field.getAnnotation(XmlEnumValue.class);
if (enumValue != null)
value.setValue(enumValue.value());
}
continue;
}
Class clsSuper = cls.getSuperclass();
if (clsSuper.getPackage() == pack)
javaType.setSuperType(clsSuper.getName());
for (Field field: cls.getDeclaredFields())
{
org.eclipse.persistence.jaxb.xmlmodel.JavaType.JavaAttributes javaAttrs = javaType.getJavaAttributes();
if (javaAttrs == null)
{
javaAttrs = new org.eclipse.persistence.jaxb.xmlmodel.JavaType.JavaAttributes();
javaType.setJavaAttributes(javaAttrs);
}
XmlTransient xmlTrans = field.getAnnotation(XmlTransient.class);
if (xmlTrans != null)
{
org.eclipse.persistence.jaxb.xmlmodel.XmlTransient attr =
new org.eclipse.persistence.jaxb.xmlmodel.XmlTransient();
attr.setJavaAttribute(field.getName());
javaAttrs.getJavaAttribute().add(new JAXBElement(new QName("", "xml-transient"), attr.getClass(), attr));
continue;
}
XmlValue xmlValue = field.getAnnotation(XmlValue.class);
if (xmlValue != null)
{
org.eclipse.persistence.jaxb.xmlmodel.XmlValue attr = new org.eclipse.persistence.jaxb.xmlmodel.XmlValue();
attr.setJavaAttribute(field.getName());
javaAttrs.getJavaAttribute().add(new JAXBElement(new QName("", "xml-value"), attr.getClass(), attr));
continue;
}
XmlAttribute xmlAttr = field.getAnnotation(XmlAttribute.class);
if (xmlAttr != null)
{
org.eclipse.persistence.jaxb.xmlmodel.XmlAttribute attr =
new org.eclipse.persistence.jaxb.xmlmodel.XmlAttribute();
attr.setJavaAttribute(field.getName());
if (!"##default".equals(xmlAttr.name()) && !field.getName().equals(xmlAttr.name()))
attr.setName(xmlAttr.name());
if (!"##default".equals(xmlAttr.namespace()))
attr.setNamespace(xmlAttr.namespace());
if (xmlAttr.required())
attr.setRequired(true);
XmlSchemaType xmlSchemaType = field.getAnnotation(XmlSchemaType.class);
if (xmlSchemaType != null)
{
org.eclipse.persistence.jaxb.xmlmodel.XmlSchemaType schemaType =
new org.eclipse.persistence.jaxb.xmlmodel.XmlSchemaType();
attr.setXmlSchemaType(schemaType);
schemaType.setName(xmlSchemaType.name());
if (!"http://www.w3.org/2001/XMLSchema".equals(xmlSchemaType.namespace()))
schemaType.setName(xmlSchemaType.namespace());
if (xmlSchemaType.type() != XmlSchemaType.DEFAULT.class)
schemaType.setType(xmlSchemaType.type().getName());
}
XmlJavaTypeAdapter xmlJavaTypeAdapter = field.getAnnotation(XmlJavaTypeAdapter.class);
if (xmlJavaTypeAdapter != null)
{
org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter javaTypeAdapter =
new org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter();
attr.setXmlJavaTypeAdapter(javaTypeAdapter);
if (xmlJavaTypeAdapter.value() != null)
javaTypeAdapter.setValue(xmlJavaTypeAdapter.value().getName());
if (xmlJavaTypeAdapter.type() != XmlJavaTypeAdapter.DEFAULT.class)
javaTypeAdapter.setValue(xmlJavaTypeAdapter.type().getName());
}
javaAttrs.getJavaAttribute().add(new JAXBElement(new QName("", "xml-attribute"), attr.getClass(), attr));
continue;
}
XmlElement xmlElem = field.getAnnotation(XmlElement.class);
if (xmlElem != null && xmlAttr != null)
throw new RuntimeException("XmlAttribute and XmlElement can be both");
org.eclipse.persistence.jaxb.xmlmodel.XmlElement attr = new org.eclipse.persistence.jaxb.xmlmodel.XmlElement();
attr.setJavaAttribute(field.getName());
if (xmlElem != null)
{
if (!"##default".equals(xmlElem.name()) && !field.getName().equals(xmlElem.name()))
attr.setName(xmlElem.name());
if (!"##default".equals(xmlElem.namespace()))
attr.setNamespace(xmlElem.namespace());
if (!"\u0000".equals(xmlElem.defaultValue()))
attr.setDefaultValue(xmlElem.defaultValue());
if (xmlElem.required())
attr.setRequired(true);
if (xmlElem.nillable())
attr.setNillable(true);
}
XmlElementWrapper xmlWrapper = field.getAnnotation(XmlElementWrapper.class);
if (xmlWrapper != null)
{
org.eclipse.persistence.jaxb.xmlmodel.XmlElementWrapper elemWrapper =
new org.eclipse.persistence.jaxb.xmlmodel.XmlElementWrapper();
attr.setXmlElementWrapper(elemWrapper);
if (!"##default".equals(xmlWrapper.name()))
elemWrapper.setName(xmlWrapper.name());
if (!"##default".equals(xmlWrapper.namespace()))
elemWrapper.setNamespace(xmlWrapper.namespace());
if (xmlWrapper.required())
elemWrapper.setRequired(true);
if (xmlWrapper.nillable())
elemWrapper.setNillable(true);
}
XmlSchemaType xmlSchemaType = field.getAnnotation(XmlSchemaType.class);
if (xmlSchemaType != null)
{
org.eclipse.persistence.jaxb.xmlmodel.XmlSchemaType schemaType =
new org.eclipse.persistence.jaxb.xmlmodel.XmlSchemaType();
attr.setXmlSchemaType(schemaType);
schemaType.setName(xmlSchemaType.name());
if (!"http://www.w3.org/2001/XMLSchema".equals(xmlSchemaType.namespace()))
schemaType.setName(xmlSchemaType.namespace());
if (xmlSchemaType.type() != XmlSchemaType.DEFAULT.class)
schemaType.setType(xmlSchemaType.type().getName());
}
XmlJavaTypeAdapter xmlJavaTypeAdapter = field.getAnnotation(XmlJavaTypeAdapter.class);
if (xmlJavaTypeAdapter != null)
{
org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter javaTypeAdapter =
new org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter();
attr.setXmlJavaTypeAdapter(javaTypeAdapter);
if (xmlJavaTypeAdapter.value() != null)
javaTypeAdapter.setValue(xmlJavaTypeAdapter.value().getName());
if (xmlJavaTypeAdapter.type() != XmlJavaTypeAdapter.DEFAULT.class)
javaTypeAdapter.setValue(xmlJavaTypeAdapter.type().getName());
}
javaAttrs.getJavaAttribute().add(new JAXBElement(new QName("", "xml-element"), attr.getClass(), attr));
}
}
JAXBContext jc = JAXBContext.newInstance(bindings.getClass());
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
m.setProperty(Marshaller.JAXB_FRAGMENT, false);
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(bindings, new File(filename));
}
Have fun!