Hi All
We had our V9 update last night and every since one of my plugin's is not working correctly. The plugin creates xml on clicking create order to send to a portal. It was working fine last week in CRM V8.2 but since the upgrade it will only do one product so the order could have 10 products but it will only send the last one. I have put my code below any help would be great
Kind Regards
Dan
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;
using System;
using System.Text.RegularExpressions;
using System.Text;
using System.Net;
using System.IO;
using Fullscope.Plugin;
namespace Zero2Ten.Plugin
{
public class LVWebServiceConnector : IPlugin
{
internal IOrganizationService organizationService = null;
public LVWebServiceConnector()
{
}
public void Execute(IServiceProvider serviceProvider)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
IPluginExecutionContext service = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
ITracingService extension = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
if (service.InputParameters.Contains("Target") && service.InputParameters["Target"] is Entity)
{
try
{
IOrganizationServiceFactory organizationServiceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
organizationService = organizationServiceFactory.CreateOrganizationService(new Guid?(service.UserId));
Entity order = service.InputParameters.Contains("Target") ? (Entity)service.InputParameters["Target"] : null;
// using (WebClient client = new WebClient())
// {
// byte[] responseBytes = client.DownloadData("trobaugh.org/default.html");
// string response = Encoding.UTF8.GetString(responseBytes);
// // For demonstration purposes, throw an exception so that the response
// // is shown in the trace dialog of the Microsoft Dynamics CRM user interface.
// throw new InvalidPluginExecutionException("WebClientPlugin completed successfully.");
// }
//APIConnector testconnector = new APIConnector();
//HttpWebResponse response = testconnector.GetAPI("tpweb.stanton-bonna.co.uk/.../TestConnection");
//throw new InvalidPluginExecutionException(response.StatusCode + "::" + response.StatusDescription);
if (service.PostEntityImages.Contains("postimage"))
{
order = service.PostEntityImages["postimage"];
}
//check if the order has already been processed
if (!order.Contains("sb_lvordernumber") || string.IsNullOrEmpty(order["sb_lvordernumber"].ToString()))
{
//transform the order to an LV Order Array
string xml = TransformOrder(order);
APIConnector connector = new APIConnector();
//write the response to a note on Order xml details
Entity note = new Entity("annotation");
note.Attributes.Add("subject", "LV Web Response");
note.Attributes.Add("notetext", xml);
note.Attributes.Add("objectid", new EntityReference("salesorder", order.Id));
organizationService.Create(note);
//call the web service
string webresponse = connector.postXMLData("removedonpurpose", xml);
// Entity note = new Entity("annotation");
// note.Attributes.Add("subject", "LV Web Response");
// note.Attributes.Add("notetext", webresponse);
// note.Attributes.Add("objectid", new EntityReference("salesorder", order.Id));
// organizationService.Create(note);
//find the LV Order number in the response
int location = webresponse.LastIndexOf("LV order '");
if (location > 0)
{
string orderNumber = webresponse.Substring(location + 10, 6);
Entity updatedOrder = new Entity("salesorder");
updatedOrder.Id = order.Id;
updatedOrder["sb_lvordernumber"] = orderNumber;
organizationService.Update(updatedOrder);
}
}
}
// catch (Exception ex)
//{
// Exception exception = ex;
// throw new InvalidPluginExecutionException("An error occurred in the LVWebServiceConnector.Execute plug-in: " + exception.Message, exception);
// }
catch (InvalidPluginExecutionException ex)
{
extension.Trace("InvalidPluginExecutionException: " + ex.ToString(), new object[0]);
throw;
}
catch (Exception ex)
{
extension.Trace("Unhandled exception: " + ex.ToString(), new object[0]);
throw new InvalidPluginExecutionException(ex.ToString());
}
// catch (System.Security.SecurityException secEx)
// {
// throw new InvalidPluginExecutionException(String.Format("An error occurred in the plug-in: {0} \n {1}.", secEx.Message, secEx.StackTrace));
// }
// catch (Exception ex)
// {
// if (ex.InnerException != null);
// throw new InvalidPluginExecutionException(String.Format("An error occurred in the plug-in: {0}", ex.Message));
// }
}
}
private static string TransformCustomer(Entity order)
{
WebCustomer[] customers = new WebCustomer[1] { new WebCustomer() };
if (order.Contains("billto_line1")) customers[0].address_line_1 = order["billto_line1"].ToString();
if (order.Contains("billto_line2")) customers[0].address_line_1 = order["billto_line2"].ToString();
if (order.Contains("billto_line3")) customers[0].address_line_1 = order["billto_line3"].ToString();
if (order.Contains("billto_name")) customers[0].company_name = order["billto_name"].ToString();
if (order.Contains("sb_billtoemail")) customers[0].contact_email = order["sb_billtoemail"].ToString();
if (order.Contains("billto_contactname")) customers[0].contact_name = order["billto_contactname"].ToString();
if (order.Contains("billto_telephone")) customers[0].contact_phone = order["billto_telephone"].ToString();
if (order.Contains("sb_lvacccode")) customers[0].customer_code = order["sb_lvacccode"].ToString();
if (order.Contains("billto_postalcode")) customers[0].postcode = order["billto_postalcode"].ToString();
using (StringWriter textWriter = new StringWriter())
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(customers.GetType());
serializer.Serialize(textWriter, customers);
return textWriter.ToString();
}
}
private string TransformOrder(Entity order)
{
//sales order
WebSalesOrder websalesorder = new WebSalesOrder();
if (order.Contains("sb_customerreference")) websalesorder.web_id = order["sb_customerreference"].ToString();
// if (order.Contains("ordernumber")) websalesorder.web_id = order["ordernumber"].ToString();
websalesorder.order_date = String.Format("{0:s}", DateTime.Now);
websalesorder.currency_code = "GBP";
websalesorder.lv_ordertype = "Order";
if (order.Contains("totalamount")) websalesorder.total = Math.Round(((Money)order["totalamount"]).Value, 2).ToString();
//if (order.Contains("name")) websalesorder.customer_reference = order["name"].ToString();
if (order.Contains("ordernumber")) websalesorder.customer_reference = order["ordernumber"].ToString();
if (order.Contains("sb_delinsc")) websalesorder.delivery_instructions = order["sb_delinsc"].ToString();
// if (order.Contains("name")) websalesorder.customer_reference = order["name"].ToString();
if (order.Contains("sb_reqdeldate")) websalesorder.delivery_date = String.Format("{0:s}", (DateTime)order["sb_reqdeldate"]);
// References
WebSalesOrderreferences[] websalesorderreferences = new WebSalesOrderreferences[6];
websalesorderreferences[0] = new WebSalesOrderreferences();
// websalesorder.references = websalesorderreferences;
websalesorderreferences[0].reference_index ="7";
if (order.Contains("sb_wateraut"))websalesorderreferences[0].reference_value = order["sb_wateraut"].ToString();
websalesorderreferences[1] = new WebSalesOrderreferences();
websalesorderreferences[1].reference_index = "8";
if (order.Contains("sb_countycode")) websalesorderreferences[1].reference_value = order["sb_countycode"].ToString();
websalesorderreferences[2] = new WebSalesOrderreferences();
websalesorderreferences[2].reference_index = "11";
if (order.Contains("sb_intsales")) websalesorderreferences[2].reference_value = order["sb_intsales"].ToString();
websalesorderreferences[3] = new WebSalesOrderreferences();
websalesorderreferences[3].reference_index = "16";
if (order.Contains("sb_contaccname")) websalesorderreferences[3].reference_value = order["sb_contaccname"].ToString();
websalesorderreferences[4] = new WebSalesOrderreferences();
websalesorderreferences[4].reference_index = "17";
if (order.Contains("sb_conaccno")) websalesorderreferences[4].reference_value = order["sb_conaccno"].ToString();
websalesorderreferences[5] = new WebSalesOrderreferences();
websalesorderreferences[5].reference_index = "3";
if (order.Contains("sb_quoteno")) websalesorderreferences[5].reference_value = order["sb_quoteno"].ToString();
websalesorder.references = websalesorderreferences;
// Flags
WebSalesOrderFlags[] websalesorderflags = new WebSalesOrderFlags[1];
websalesorderflags[0] = new WebSalesOrderFlags();
// websalesorder.references = websalesorderreferences;
websalesorderflags[0].flagstring_index = "5";
if (order.Contains("sb_isfpa")) websalesorderflags[0].flagstring_value = order["sb_isfpa"].ToString();
websalesorder.flags = websalesorderflags;
// WebSalesOrderreferencesWebReference[] webreferences = new WebSalesOrderreferencesWebReference[1];
// webreferences[0].reference_index = "7";
// webreferences[0].reference_value = "ST";
// websalesorderreferences[0].webreferences = webreferences;
// websalesorder.references = websalesorderreferences;
// text References
WebSalesOrdertexts[] websalesordertexts = new WebSalesOrdertexts[4];
websalesordertexts[0] = new WebSalesOrdertexts();
websalesordertexts[0].text_index = "1";
if (order.Contains("sb_delinsc")) websalesordertexts[0].text_value = order["sb_delinsc"].ToString();
websalesordertexts[1] = new WebSalesOrdertexts();
websalesordertexts[1].text_index = "3";
if (order.Contains("shipto_contactname")) websalesordertexts[1].text_value = order["shipto_contactname"].ToString();
websalesordertexts[2] = new WebSalesOrdertexts();
websalesordertexts[2].text_index = "2";
if (order.Contains("sb_orderinstructions")) websalesordertexts[2].text_value = order["sb_orderinstructions"].ToString();
websalesordertexts[3] = new WebSalesOrdertexts();
websalesordertexts[3].text_index = "4";
if (order.Contains("sb_orcontre")) websalesordertexts[3].text_value = order["sb_orcontre"].ToString();
websalesorder.texts = websalesordertexts;
//customer
WebSalesOrderCustomer[] websalesordercustomer = new WebSalesOrderCustomer[1];
websalesordercustomer[0] = new WebSalesOrderCustomer();
if (order.Contains("billto_line1")) websalesordercustomer[0].address_line_1 = order["billto_line1"].ToString();
if (order.Contains("billto_line2")) websalesordercustomer[0].address_line_2 = order["billto_line2"].ToString();
if (order.Contains("billto_line3")) websalesordercustomer[0].address_line_3 = order["billto_line3"].ToString();
if (order.Contains("billto_name")) websalesordercustomer[0].company_name = order["billto_name"].ToString();
if (order.Contains("sb_billtoemail")) websalesordercustomer[0].contact_email = order["sb_billtoemail"].ToString();
if (order.Contains("billto_contactname")) websalesordercustomer[0].contact_name = order["billto_contactname"].ToString();
if (order.Contains("billto_telephone")) websalesordercustomer[0].contact_phone = order["billto_telephone"].ToString();
if (order.Contains("sb_lvacccode")) websalesordercustomer[0].customer_code = order["sb_lvacccode"].ToString();
if (order.Contains("billto_postalcode")) websalesordercustomer[0].postcode = order["billto_postalcode"].ToString();
websalesorder.customer = websalesordercustomer;
//delivery
WebSalesOrderDelivery[] websalesorderdelivery = new WebSalesOrderDelivery[1];
websalesorderdelivery[0] = new WebSalesOrderDelivery();
if (order.Contains("sb_del1")) websalesorderdelivery[0].address_line_1 = order["sb_del1"].ToString();
if (order.Contains("sb_del2")) websalesorderdelivery[0].address_line_2 = order["sb_del2"].ToString();
if (order.Contains("sb_del3")) websalesorderdelivery[0].address_line_3 = order["sb_del3"].ToString();
if (order.Contains("sb_delcity")) websalesorderdelivery[0].address_line_4 = order["sb_delcity"].ToString();
if (order.Contains("sb_delsta")) websalesorderdelivery[0].address_line_5 = order["sb_delsta"].ToString();
if (order.Contains("shipto_name")) websalesorderdelivery[0].company_name = order["shipto_name"].ToString();
if (order.Contains("shipto_contactname")) websalesorderdelivery[0].contact_name = order["shipto_contactname"].ToString();
if (order.Contains("shipto_telephone")) websalesorderdelivery[0].contact_phone = order["shipto_telephone"].ToString();
if (order.Contains("ordernumber") && order["ordernumber"].ToString().Length > 6) websalesorderdelivery[0].delivery_code = order["ordernumber"].ToString().Substring(order["ordernumber"].ToString().Length - 6);
if (order.Contains("sb_delpost")) websalesorderdelivery[0].postcode = order["sb_delpost"].ToString();
websalesorder.delivery = websalesorderdelivery;
//order items
EntityCollection orderitems = GetOrderItems(order.Id);
WebSalesOrderItemsWebSalesOrderItem[] weborderitems = new WebSalesOrderItemsWebSalesOrderItem[orderitems.Entities.Count];
int i = 0;
foreach (Entity salesorderitem in orderitems.Entities)
{
weborderitems[i] = new WebSalesOrderItemsWebSalesOrderItem();
if (salesorderitem.Contains("lineitemnumber")) weborderitems[i].lv_itemnumber = Convert.ToInt32(((decimal)salesorderitem["lineitemnumber"])).ToString();
if (salesorderitem.Contains("sb_productnumber")) weborderitems[i].product_code = salesorderitem["sb_productnumber"].ToString();
if (salesorderitem.Contains("quantity")) weborderitems[i].quantity = Convert.ToInt32(((decimal)salesorderitem["quantity"])).ToString();
// if (salesorderitem.Contains("discountpercentage")) weborderitems[i].discount_percentage = Convert.ToInt32(((decimal)salesorderitem["discountpercentage"])).ToString();
if (salesorderitem.Contains("extendedamount")) weborderitems[i].total = ((Money)salesorderitem["extendedamount"]).Value.ToString();
if (salesorderitem.Contains("extendedamount")) weborderitems[i].goods = ((Money)salesorderitem["extendedamount"]).Value.ToString();
//units
WebSalesOrderItemsWebSalesOrderItemUnit[] units = new WebSalesOrderItemsWebSalesOrderItemUnit[1];
units[0] = new WebSalesOrderItemsWebSalesOrderItemUnit();
weborderitems[i].unit = units;
i++;
}
websalesorder.items = weborderitems;
WebSalesOrder[] websalesorders = new WebSalesOrder[1] { websalesorder };
using (StringWriter textWriter = new StringWriter())
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(websalesorders.GetType());
serializer.Serialize(textWriter, websalesorders);
return textWriter.ToString();
}
}
private EntityCollection GetOrderItems(Guid orderid)
{
string fetchXML = "<fetch version='1.0' output-format='xml - platform' mapping='logical' distinct='false'><entity name='salesorderdetail'><filter type='and'><condition attribute='salesorderid' operator='eq' value='{0}' /></filter></entity></fetch>";
fetchXML = string.Format(fetchXML, orderid.ToString());
return organizationService.RetrieveMultiple(new Microsoft.Xrm.Sdk.Query.FetchExpression(fetchXML));
}
}
}